Thursday, July 21, 2016

Python Script to Connect to Mosquitto MQTT and Generate HTML Page




#!/usr/bin/python
#import pyinotify
import mosquitto
import time

#target = open("/var/www/button.html",'w')

#define what happens after connection
def on_connect(rc):
    print "Connected";

#On recipt of a message create a pynotification and show it
def on_message(msg):

if msg.topic == "CiscoBtn" :
    target = open("/var/www/button.html",'w+')
else:
target = open("/var/www/parking.html",'w+')

target.write(time.strftime("%d/%m/%Y"))
    target.write(" ")
    target.write(time.strftime("%I:%M:%S"))
    target.write(" ")
    target.write(msg.payload)
    target.write("\n")
target.close()

#create a broker
mqttc = mosquitto.Mosquitto("python_sub")


#define the callbacks
mqttc.on_message = on_message
mqttc.on_connect = on_connect

#connect
mqttc.connect("127.0.0.1", 1883, 60, True)

#subscribe to topic test
mqttc.subscribe("CiscoBtn", 0)
mqttc.subscribe("CiscoParking",1);


#keep connected to broker
while mqttc.loop() == 0:
    pass
mqttc.on_connect = on_connect

No comments:

Post a Comment

Featured Post

XDP - Getting Started with XDP (Linux)