worktree-test/mqtt_comm.py

83 lines
2.1 KiB
Python
Raw Permalink Normal View History

2021-03-03 15:39:43 +00:00
import paho.mqtt.client as mqtt
import time
import configfile
from time import gmtime, strftime
import difflib
class MQTT_Client():
def __init__(self,host_name, client_name, port,connect): #construtor initialises variables and callback functions
conf = configfile.Configuration()
#callback functions definition(here because it doesn't work anywhere else)
def on_connect(client, userdata, flags, rc):
self.connected =1
if(rc==1):
print("Connected with result code "+str(rc))
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
def on_publish(client, userdata, mid):
self.published =1
self.last_message=mid;
def on_disconnect(client, userdata, rc):
self.connected =0
print("MQTT Disconnected")
#initialize variables
self.connect=connect
self.client_id =client_name
self.host_in = host_name
self.port_n = port
self.published = 0
self.connected = 0
self.last_message = 0
self.client = mqtt.Client(client_id=client_name)
self.client.on_connect = on_connect
self.client.on_message = on_message
self.client.on_publish = on_publish
self.client.on_disconnect=on_disconnect
#create connection to MQTT server
def client_connect(self):
try:
print("Connecting to host: ",self.host_in)
self.client.connect(host=self.host_in,port=self.port_n,keepalive=60)
except Exception as error:
print("Exception:",error);
class Host():
def __init__(self, Port, Topic, Name, PublishFlag):
self.port = Port;
self.topic = Topic;
self.name = Name
self.publishFlag = PublishFlag
def getTopic(self):
return self.topic
def getPort(self):
return self.port
def getName(self):
return self.name
def publish(self):
if self.publishFlag:
print("I publish to ", self.topic)