def main(): machine.freq(160000000) c = MQTTClient("HSBNE-small-sign", "10.0.1.253", user="", password="") c.set_callback(sub_cb) c.set_last_will("devices/small-sign/state", "offline", retain=True) c.connect() c.subscribe("devices/small-sign/#") c.publish("devices/small-sign/state", "online", retain=True) c.publish("devices/main-sign/ip", network.WLAN(network.STA_IF).ifconfig()[0], retain=True) sign = SignMatrix() try: while True: while c.check_msg(): pass if enable != 0: sign.set_delay(delay) sign.scroller(text) else: c.wait_msg() except KeyboardInterrupt: c.publish("devices/small-sign/state", "offline", retain=True, qos=1) c.disconnect()
def initialise(settings=configuration.mqtt.settings): global client, keepalive, topic_path client_id = get_unique_id() keepalive = settings["keepalive"] topic_path = settings["topic_path"] if topic_path == "$me": topic_path = get_topic_path(namespace) client = MQTTClient(client_id, settings["host"], settings["port"], keepalive=keepalive) client.set_callback(on_message) client.set_last_will(topic_path + "/state", "nil") client.connect() # TODO: Catch exception event.add_timer_handler(mqtt_ping_handler, keepalive * 1000) if settings["mqtt_insecure_exec"]: add_message_handler(on_exec_message, "$me/exec") for topic in settings["topic_subscribe"]: if topic.startswith("$all/"): topic = "+/+/+" + topic[4:] if topic.startswith("$me/"): topic = topic_path + topic[3:] client.subscribe(topic) print(" ###### MQTT: Connected to %s: %s" % (settings["host"], topic_path))
def mqtt_client(server): # setup the BUTton and LED global led import machine, ubinascii, utime machine_id = b'ESP8266-%s' % ubinascii.hexlify( machine.unique_id() ) led = machine.Pin(2) led.init(machine.Pin.OUT) button = machine.Pin(0) button.init(machine.Pin.IN, machine.Pin.PULL_UP) # setup Mosquitto from umqtt.robust import MQTTClient mqttc = MQTTClient(machine_id, server) mqttc.connect() mqttc.set_last_will(b'test/bradley_edu', b'%s signoff 1' % ( machine_id ) ) mqttc.set_callback(callback_function) mqttc.subscribe(b'test/#') # run Mosquitto butstate = button.value() while True: if button.value()!=butstate: butstate = button.value() mqttc.publish(b'test/bradley_edu', b'%s B0 %s' % ( machine_id , str(butstate) ) ) mqttc.check_msg() # this will check for messages and call the callback function if needed utime.sleep_ms(20) # time to allow the callback function to do its job to avoid calling multiple instances # we actually never quit but this is how shutdown should look like mqttc.disconnect()
def mqttSendQueue(inMqttBroker, ioMqttCounter, inMqttSendLimit=CONFIG['mqttSendLimit']): uping.ping(inMqttBroker, 1) topic = CONFIG["mqttMeasureTopic"] msgCount = 0 mqttClient = MQTTClient( GLOBAL_MESSAGE_QUEUE.uniqueID(), inMqttBroker, ssl=CONFIG["mqttSSL"], user=CONFIG["mqttUser"], password=CONFIG["mqttPassword"], ) mqttLastWill = ("-1, -1, -1, -1, -1, -1, -1, -1, -1, " + GLOBAL_MESSAGE_QUEUE.uniqueID() + ", " + MESSAGE_TYPES["mqttErrorMessage"] + ", " + "UngracefulDisconnect, " + "Ungraceful disruption of MQTT commit, ") printDebug("queue mqttLastWill", mqttLastWill) mqttClient.set_last_will(topic, mqttLastWill) try: mqttClient.connect() print("## Connected with MQTT Broker", inMqttBroker) printDataDebug("ioMqttData", ioMqttData) while (GLOBAL_MESSAGE_QUEUE.lenQ()[0] > 0 and msgCount < inMqttSendLimit): msg = GLOBAL_MESSAGE_QUEUE.getMsg() mqttClient.publish(topic, json.dumps(msg)) msgCount += 1 ioMqttCounter += 1 except Exception as e: sys.print_exception(e) errorMessage = mqttErrorMessage( GLOBAL_MESSAGE_QUEUE.uniqueID(), "Exception", "MQTTClientConnectError", str(e), ) GLOBAL_MESSAGE_QUEUE.addMsg(errorMessage, "high") try: mqttClient.disconnect() except Exception as e: sys.print_exception(e) errorMessage = mqttErrorMessage( GLOBAL_MESSAGE_QUEUE.uniqueID(), "Exception", "MQTTClientDisconnectError", str(e), ) GLOBAL_MESSAGE_QUEUE.addMsg(errorMessage, "high") return ioMqttCounter
class Telemetry(): """Telemetry via the MQTT protocoll.""" def __init__(self, ID, broker=""): self._isReady = False self._broker = broker self._clientID = ID self._client = None self._rootTopic = self._clientID def connect(self): """ Try to connect to MQTT broker """ print("Initializing telemetry via MQTT ...") self.sta_if = network.WLAN(network.STA_IF) if not self.sta_if.isconnected(): print("Error: Not connected to network") else: from NETWORK import my_mqtt_usr, my_mqtt_pwd, my_mqtt_srv if len(self._broker) == 0: self._broker = my_mqtt_srv self._client = MQTTClient(self._clientID, self._broker) self._client.set_last_will(self._rootTopic, b'link/down') try: if self._client.connect() == 0: print("[{0:>12}] {1}".format("topic", self._rootTopic)) self._client.publish(self._rootTopic, b'link/up') self._isReady = True except: print("Error: MQTT brocker {} not responding".format(self._broker)) print("... done." if self._isReady else "... FAILED") def publishDict(self, d): """ Publish a dictionary as a message under the standard topic """ if self._isReady: self._client.publish(self._rootTopic, ujson.dumps(d)) def publish(self, t, m): """ Publish a message under <standard topic>/<t> """ if self._isReady: try: self._client.publish(self._rootTopic +t, m) except OSError as error: if error.args[0] != errno.ECONNRESET: print("Error: publish caused {0}".format(error.args[0])) def disconnect(self): """ Disconnect from MQTT broker """ if self._isReady: self._client.disconnect() self._isReady = False
def mqttCollectMessages( inMqttBroker=CONFIG["mqttBroker"], inMqttClientUniqueId=CONFIG["mqttClientUniqueId"], inMqttTopic=CONFIG["mqttConfigTopic"], ): global MQTTRECEIVED MQTTRECEIVED = [] outMqttData = [] countMsg = 0 mqttClient = MQTTClient( inMqttClientUniqueId, inMqttBroker, ssl=CONFIG["mqttSSL"], user=CONFIG["mqttUser"], password=CONFIG["mqttPassword"], ) mqttLastWill = ("-1, -1, -1, -1, -1, -1, -1, -1, -1, " + inMqttClientUniqueId + ", " + MESSAGE_TYPES["mqttErrorMessage"] + ", " + "UngracefulDisconnect, " + "Ungraceful disruption of MQTT collect, ") mqttClient.set_last_will(inMqttTopic, mqttLastWill) mqttClient.set_callback(mqttCallback) print("Trying to collect the MQTT Messages.", inMqttTopic) print("MQTTSTATS", MQTTSTATS) try: mqttClient.connect() print("Subscribe to", inMqttTopic) mqttClient.subscribe(topic=inMqttTopic) while CONFIG["mqttReceivedMax"] > countMsg: print("Checking for MQTT message") mqttClient.check_msg() countMsg += 1 time.sleep_ms(200) MQTTSTATS["receivedMsgs"] += len(MQTTRECEIVED) print("MQTTRECEIVED", MQTTRECEIVED) mqttProcess() print("Message(s) of MQTT were processed.") print("MQTTSTATS", MQTTSTATS) time.sleep(1) mqttClient.disconnect() except Exception as e: print("MQTT collections failed.") sys.print_exception(e) errorMessage = mqttErrorMessage( inMqttClientUniqueId, "Exception", "MQTTClientConnectError", str(e), ) outMqttData.append(errorMessage) return outMqttData
def connect(): from umqtt.robust import MQTTClient c = MQTTClient(ID, mqttHost, ssl=mqttSSL, user=mqttUser, password=mqttPass) c.DEBUG = True if not c.connect(): print('connected, will publish to {}/{}/#'.format(mqttTopicRoot, ID)) c.set_last_will('{}/{}/status'.format(mqttTopicRoot, ID), 'offline', retain=True) c.publish('{}/{}/status'.format(mqttTopicRoot, ID), 'connected', retain=True) return c return None
def initialise(settings): global client, keepalive client_id = get_unique_id() keepalive = settings["keepalive"] topic_path = settings["topic_path"] client = MQTTClient(client_id, settings["host"], settings["port"], keepalive=keepalive) client.set_callback(on_message) client.set_last_will(topic_path + "/state", "nil") client.connect() for topic in settings["topic_subscribe"]: client.subscribe(topic) print("Connected to MQTT: %s: %s" % (settings["host"], topic_path))
def mqttCommit(ioMqttCounter, inMqttBroker, inMqttTopic, inMqttClientUniqueId, ioMqttData): uping.ping(inMqttBroker, 1) mqttClient = MQTTClient( inMqttClientUniqueId, inMqttBroker, ssl=CONFIG["mqttSSL"], user=CONFIG["mqttUser"], password=CONFIG["mqttPassword"], ) mqttLastWill = ("-1, -1, -1, -1, -1, -1, -1, -1, -1, " + inMqttClientUniqueId + ", " + MESSAGE_TYPES["mqttErrorMessage"] + ", " + "UngracefulDisconnect, " + "Ungraceful disruption of MQTT commit, ") printDebug("mqttLastWill", mqttLastWill) mqttClient.set_last_will(inMqttTopic, mqttLastWill) try: mqttClient.connect() print("## Connected with MQTT Broker", inMqttBroker) printDataDebug("ioMqttData", ioMqttData) ioMqttCounter = mqttPublish(ioMqttCounter, mqttClient, inMqttTopic, ioMqttData) except Exception as e: sys.print_exception(e) errorMessage = mqttErrorMessage( inMqttClientUniqueId, "Exception", "MQTTClientConnectError", str(e), ) ioMqttData.append(errorMessage) try: mqttClient.disconnect() except Exception as e: sys.print_exception(e) errorMessage = mqttErrorMessage( inMqttClientUniqueId, "Exception", "MQTTClientDisconnectError", str(e), ) ioMqttData.append(errorMessage) return ioMqttCounter
class Telemetry(): """Telemetry via the MQTT protocoll.""" def __init__(self, ID, broker=""): self._isReady = False self._broker = broker self._clientID = ID self._client = None self._rootTopic = self._clientID + "/" self._doEncrypt = False try: from NETWORK import my_mqtt_encrypt_key, my_mqtt_encrypt_CBC if my_mqtt_encrypt_key is not None: from ucryptolib import aes self.AES = aes(my_mqtt_encrypt_key, 2, my_mqtt_encrypt_CBC) self._doEncrypt = True except ImportError: pass def connect(self): """ Try to connect to MQTT broker """ print("Initializing telemetry via MQTT ...") self.sta_if = network.WLAN(network.STA_IF) if not self.sta_if.isconnected(): print("Error: Not connected to network") else: from NETWORK import my_mqtt_usr, my_mqtt_pwd, my_mqtt_srv, my_mqtt_port if len(self._broker) == 0: self._broker = my_mqtt_srv _sll = my_mqtt_port == 8883 self._client = MQTTClient(self._clientID, self._broker, ssl=_sll) self._client.set_last_will(self._rootTopic, b'link/down') try: if self._client.connect() == 0: print("[{0:>12}] {1}".format("topic", self._rootTopic)) self._client.publish(self._rootTopic, b'link/up') self._isReady = True except: print("Error: MQTT brocker {} not responding".format( self._broker)) print("... done." if self._isReady else "... FAILED") return self._isReady def subscribe(self, topic, callBack): """ Subscribe to topic and define call back function """ self._client.set_callback(callBack) t = self._rootTopic + topic self._client.subscribe(t) print("Subscribed to `{0}`".format(t)) def spin(self): """ Needs to be called frequently to check for new messages """ self._client.check_msg() def publishDict(self, t, d): """ Publish a dictionary as a message under <standard topic>/<t> """ if self._isReady: if not self._doEncrypt: self._client.publish(self._rootTopic + t, ujson.dumps(d)) else: s = ujson.dumps(d) b = self.AES.encrypt(bytearray(s + " " * (16 - len(s) % 16))) self._client.publish(self._rootTopic + t, b) def publish(self, t, m): """ Publish a message under <standard topic>/<t> TODO: implement encryption here as well """ if self._isReady: try: self._client.publish(self._rootTopic + t, m) except OSError as error: if error.args[0] != errno.ECONNRESET: print("Error: publish caused {0}".format(error.args[0])) def disconnect(self): """ Disconnect from MQTT broker """ if self._isReady: self._client.disconnect() self._isReady = False @property def connected(self): return self._isReady
class CatFeeder(object): def __init__(self): """""" self._client = None self._button = Pin(5, mode=Pin.IN, pull=Pin.PULL_UP) self._done_payload = 'Done feeding!' self._servo_buzz = Feeder( pin_servo=0, trigger=14, echo=2, ) self._servo_tuxedo = Feeder( pin_servo=4, trigger=12, echo=13, ) print('Instancing button and servos.') self._button.irq(handler=self.button_pressed, trigger=Pin.IRQ_RISING) print('Setting IRQ.') def mqtt_connect(self): """""" print("Connecting to MQTT server...") self._client = MQTTClient( CLIENT_ID, MQTT_SERVER, user=MQTT_USERNAME, password=MQTT_PASSWORD, ) self._client.set_callback(self.on_message) print("Connecting MQTT") self._client.set_last_will(STATUS_TOPIC, "Offline", retain=True) self._client.connect() self._client.subscribe(TOPIC) print("Connected to %s, subscribed to %s topic" % (MQTT_SERVER, TOPIC)) self._client.publish(STATUS_TOPIC, "Connected", retain=True) while True: self._client.wait_msg() def button_pressed(self, pin): if pin.value(): time.sleep_ms(300) print('#' * 80) self._client.publish(MANUAL_FEEDING, "") def on_message(self, topic, message): """""" print(topic, message) msg = message.strip().decode('utf-8') self._client.publish(LAST_FED_TOPIC, "Feeding...") self.feed() def feed(self): """""" time.sleep(0.2) self._servo_buzz.feed() print('fed buzz') time.sleep(1) print('pause 1 sec') self._servo_tuxedo.feed() print('fed tuxedo') self.done_feeding() def done_feeding(self): """""" time.sleep(0.2) self._client.publish(DONE_TOPIC, self._done_payload) time.sleep(0.2) self._client.publish(QTY_BUZZ_TOPIC, self._servo_buzz.remaining_quantity) time.sleep(0.2) self._client.publish(QTY_TUXEDO_TOPIC, self._servo_tuxedo.remaining_quantity) print("Done feeding!\n\n") print('/' * 80) print('Waiting for message...') while True: self._client.wait_msg() def run(self): self.mqtt_connect() def open_close_test(self, open_=48, pause=1): """""" self._servo_buzz.open_position = open_ self._servo_tuxedo.open_position = open_ self._servo_buzz.pause_open = pause self._servo_tuxedo.pause_open = pause self._servo_buzz.feed() print('fed buzz') time.sleep(1) print('pause 1 sec') self._servo_tuxedo.feed() while True: self._client.wait_msg()
class SonOff(): led = Pin(13, Pin.OUT, value=1) relay = Pin(12, Pin.OUT, value = 0) button = Pin(0, Pin.IN, Pin.PULL_UP) device_status = "OFF" def __init__(self): if config.POWER_ON_STATE: self.relay_control(1) self.led_control(0) self.device_status = "ON" self.mqtt_client = MQTTClient(client_id=config.DEVICE_NAME, server=config.MQTT_SERVER, port=config.MQTT_PORT, user=config.MQTT_USER, passwd=config.MQTT_PASSWD, keepalive=60) self.mqtt_client.set_callback(self.sub_callback) self.mqtt_client.set_last_will(config.AVAILABILITY_TOPIC, "offline") self.ping_mqtt = 0 self.ping_fail = 0 self.button_interrupt = 0 def relay_control(self, value): self.relay.value(value) return self.relay.value() def led_control(self, value): self.led.value(value) return self.led.value() def mqtt_connect(self): try: self.mqtt_client.connect() for topic in [config.SET_TOPIC, config.POS_SET_TOPIC, config.MQTT_CHECK]: self.mqtt_client.subscribe(topic) self.publish_device_status() self.publish_pos_status("ON" if config.POWER_ON_STATE else "OFF") self.mqtt_client.publish(config.AVAILABILITY_TOPIC, "online") except: self.ping_fail += 1 def sub_callback(self, topic, msg): topic = topic.decode('utf-8') msg = msg.decode('utf-8') if topic == config.SET_TOPIC: if msg == "ON": self.relay_control(1) self.led_control(0) self.device_status = "ON" else: self.relay_control(0) self.led_control(1) self.device_status = "OFF" self.publish_device_status() elif topic == config.POS_SET_TOPIC: if msg == "ON": self.change_config({"POWER_ON_STATE": 1}) else: self.change_config({"POWER_ON_STATE": 0}) self.publish_pos_status(msg) elif topic == config.MQTT_CHECK: if int(msg) == self.ping_mqtt: self.ping_fail = 0 def publish_device_status(self): if self.ping_fail == 0: self.mqtt_client.publish(config.STATE_TOPIC, self.device_status) def publish_pos_status(self, value): if self.ping_fail == 0: self.mqtt_client.publish(config.POS_STATE_TOPIC, value) def button_action(self, pin): self.button_interrupt = 1 def change_config(self, config_data): with open('config.py', 'r') as rf: config_list = rf.readlines() for config_name, config_value in config_data.items(): if config_name in config_map: if isinstance(config_value, int): config_list[config_map[config_name]] = "{} = {}\n".format(config_name, config_value) elif config_value.isdigit(): config_list[config_map[config_name]] = "{} = {}\n".format(config_name, int(config_value)) else: config_list[config_map[config_name]] = '{} = "{}"\n'.format(config_name, config_value) with open('config.py', 'w') as wf: for conf in config_list: wf.write(conf) async def check_message(self): while True: await asyncio.sleep(0.2) try: self.mqtt_client.check_msg() except: self.mqtt_connect() async def check_mqtt(self): while True: await asyncio.sleep(10) self.ping_mqtt = time.time() self.mqtt_client.publish(config.MQTT_CHECK, str(self.ping_mqtt)) self.ping_fail += 1 if self.ping_fail > 10: pass if self.ping_fail > 3: self.mqtt_client.disconnect() self.mqtt_connect() async def check_button(self): while True: await asyncio.sleep(0.4) if self.button_interrupt > 0: self.button_interrupt = 0 if self.device_status == "ON": self.relay_control(0) self.led_control(1) self.device_status = "OFF" else: self.relay_control(1) self.led_control(0) self.device_status = "ON" self.publish_device_status() def run(self): self.button.irq(trigger=Pin.IRQ_FALLING, handler=self.button_action) self.mqtt_connect() loop = asyncio.get_event_loop() loop.create_task(self.check_message()) loop.create_task(self.check_mqtt()) loop.create_task(self.check_button()) try: loop.run_forever() except: pass