Commit 1bc028d6 authored by João Santos's avatar João Santos

Update py_mqtt.py

parent c531f079
......@@ -3,11 +3,14 @@ import json
import logging
import random
import time
from Control_Interface.controlInterface import controlInterface
BROKER = 'broker.hivemq.com'
PORT = 1883
TOPIC = "python-mqtt/tcp"
TOPIC_SUB = "python-mqtt-sub"
TOPIC_PUB = "python-mqtt-pub"
CLIENT_ID = f'python-mqtt-{random.randint(0, 1000)}'
......@@ -18,11 +21,21 @@ MAX_RECONNECT_DELAY = 60
FLAG_EXIT = False
interface = controlInterface()
print(interface.getListIp())
interface.newNhr("9410")
interface.newNhr("9430")
NHRs = {
"9410" : interface.getNhr9410()[0],
"9430" : interface.getNhr9430()[0],
}
def on_connect(client, userdata, flags, rc):
if rc == 0 and client.is_connected():
print("Connected to MQTT Broker!")
client.subscribe(TOPIC)
client.subscribe(TOPIC_SUB)
else:
print(f'Failed to connect, return code {rc}')
......@@ -49,9 +62,20 @@ def on_disconnect(client, userdata, rc):
FLAG_EXIT = True
def on_message(client, userdata, msg):
print(f'Received `{msg.payload.decode()}` from `{msg.topic}` topic')
def on_message(client, userdata, message):
print(f'Received `{message.payload.decode()}` from `{message.topic}` topic')
message = json.loads(message.payload.decode())
selector = message['selector']
fn = message['fn']
args = message.get('args', [])
print(message['selector'])
nhr = NHRs[selector]
result = getattr(nhr, fn)(*args)
client.publish(TOPIC_PUB, json.dumps(result))
def connect_mqtt():
client = mqtt_client.Client(CLIENT_ID)
......@@ -73,13 +97,13 @@ def publish(client):
logging.error("publish: MQTT client is not connected!")
time.sleep(1)
continue
result = client.publish(TOPIC, msg)
result = client.publish(TOPIC_PUB, msg)
# result: [0, 1]
status = result[0]
if status == 0:
print(f'Send `{msg}` to topic `{TOPIC}`')
print(f'Send `{msg}` to topic `{TOPIC_SUB}`')
else:
print(f'Failed to send message to topic {TOPIC}')
print(f'Failed to send message to topic {TOPIC_SUB}')
msg_count += 1
time.sleep(1)
......@@ -97,4 +121,4 @@ def run():
if __name__ == '__main__':
run()
\ No newline at end of file
run()
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment