def main(server=SERVER): c = MQTTClient(CLIENT_ID, server) c.connect() print("Connected to %s, waiting for button presses" % server) while True: while True: if button.value() == 0: break time.sleep_ms(20) print("Button pressed") c.publish(TOPIC, b"toggle") time.sleep_ms(200) c.disconnect()
def main(server="localhost"): c = MQTTClient("umqtt_client", server) c.set_callback(sub_cb) c.connect() c.subscribe(b"foo_topic") while True: if True: # Blocking wait for message c.wait_msg() else: # Non-blocking wait for message c.check_msg() # Then need to sleep to avoid 100% CPU usage (in a real # app other useful actions would be performed instead) time.sleep(1) c.disconnect()
class Mqtt(ConfigOp, Consumer): def __init__(self, opc): ConfigOp.__init__(self, 'mqtt', CONFIG_NAME) Consumer.__init__(self) self.add_command(self.__get_info, GET) self.__client = None self.__pub_queue = queue.Queue(10) self.__connected = False self.__last_ping_tm = 0 self.__valid_config = False self.__with_auth = False self.__opc = opc self.__topic = set() self.__sub_cb = None self.add_command(self.__reconnect, SET, 'reconnect') async def consume(self, data): if ENCRYPTED_OUTPUT: st = Sec() self.publish(st.enc_paylaod(data)) else: self.publish(data) sleep(0) async def __get_info(self, _): v = self.get_info() await sleep(0) return result(200, None, v) def config_item(self, name, def_val = None): if self.__config is None or name not in self.__config: return def_val return self.__config[name] def get_info(self): return { ENABLED: self.config_item(ENABLED, False), 'connected': self.is_connected(), 'config_valid': self.__valid_config, 'with_auth': self.__with_auth, 'client-id': DEVICE_NAME, HOST: self.config_item(HOST), PORT: self.config_item(PORT, 1883), USER: self.config_item(USER), PASSWORD: self.config_item(PASSWORD), 'sensor-topic': self.config_item(TOPIC), 'command-topic': CMD_TOPIC } async def __reload_config(self): # NOSONAR delayed_task(5000, self.connect, (True, True)) return result(200, None, RECONNECT_MSG) async def __reconnect(self, _): delayed_task(5000, self.connect, (True)) return result(200, None, RECONNECT_MSG) def __check_config(self): if self.config_item(HOST) is None or self.config_item(TOPIC) is None: self.__valid_config = False self.__with_auth = False else: self.__valid_config = True self.__with_auth = (self.config_item(USER) is not None and self.config_item(PASSWORD) is not None) def is_connected(self): return self.__client is not None and self.__connected def connect(self, force = False, reload = False): try: return self.__connect(force, reload) except BaseException as e: log.warning("Mqtt connection exception: %r", e) return False def __connect(self, force = False, reload = False): if self.is_connected() and not force and not reload: return True self.disconnect() self.load(reload) self.__check_config() if self.__valid_config: if self.config_item(ENABLED, False): if self.__with_auth: self.__client = MQTTClient( DEVICE_NAME, self.config_item(HOST), self.config_item(PORT), self.config_item(USER), self.config_item(PASSWORD), 0, SSL) else: self.__client = MQTTClient( DEVICE_NAME, self.config_item(HOST), self.config_item(PORT), None, None, 0, SSL) else: log.info("MQTT disabled") return False else: log.error("Invalid mqtt config") return False self.__client.connect() self.__client.DEBUG = DEBUG self.__client.set_callback(self.__sub_callback) self.__client.subscribe(bytes(CMD_TOPIC, 'utf-8')) self.__connected = True log.debug("Mqtt broker connected") return True def disconnect(self): log.debug("Disconnect mqtt") self.__connected = False if self.__client is None: return try: self.__client.disconnect() except: #pylint: disable=bare-except pass self.__client = None def publish_op_log(self, p, c, ret): x = {'p': p, 'c': c, 'r': ret, 'tm': time_stamp()} if ENCRYPTED_OUTPUT: st = Sec() x = st.enc_paylaod(x) return self.publish(x, topic = OP_LOG_TOPIC) def __sub_callback(self, topic, pay): s = pay.decode("utf-8") log.info('Received %s: %s' , topic.decode("utf-8"), s) try: json = loads(s) if ENCRYPTED_INPUT: # 处理加密 st = Sec() json = st.dec_payload(json) create_task(self.__opc.op_request(json)) except BaseException as e: m = "Process message failed: %r" % e log.error(m) self.publish_op_log(None, None, result(500, m)) def publish(self, ret, retain = False, qos = 0, topic = None): t = None try: ret['i'] = DEVICE_NAME if topic is None: t = self.config_item(TOPIC) else: t = topic if t is None: log.debug("None topic, ignored") return log.debug("Add msg to pub queue: topic: %s, %r ", t, ret) l = {'t': bytes(t, 'utf-8'), 'm': bytes(dumps(ret), 'utf-8'), 'r': retain, 'q': qos} self.__pub_queue.put_nowait(l) except BaseException as e: log.error("Publish to topic %s failed: %r", t, e) def __next(self, o): if o is not None: return o try: try: return self.__pub_queue.get_nowait() except: #pylint: disable=bare-except return None except: #pylint: disable=bare-except return None async def __int_pub(self, o): '''从旧消息或队列里读取,如果qos大于0,且失败,返回未发送得消息''' while True: m = self.__next(o) if m is None: return None qos = 0 try: qos = m['q'] if self.is_connected(): log.debug("Publish msg %r", m) self.__client.publish(m['t'], m['m'], m['r']) self.__last_ping_tm = time() return None except BaseException as e: log.debug("Publish error: %r", e) self.__connected = False if qos > 0: return m return None def __keep_alive(self): if time() > self.__last_ping_tm + KEEP_ALIVE: try: if self.is_connected(): log.debug("Mqtt ping") self.__client.ping() self.__last_ping_tm = time() except: #pylint: disable=bare-except self.__connected = False def __int_sub(self): try: if self.is_connected(): log.debug("mqtt sub-check") self.__client.check_msg() self.__last_ping_tm = time() except: #pylint: disable=bare-except self.__connected = False async def __loop(self): old_msg = None log.debug("Start mqtt loop") while True: try: if self.is_connected(): old_msg = await self.__int_pub(old_msg) self.__int_sub() self.__keep_alive() else: while not self.is_connected(): self.connect() await sleep(RECONNECT_INTERVAL) except: #pylint: disable=bare-except self.__connected = False # 指示连接错误 await sleep(SLEEP_INTERVAL) def setup(self): self.connect() create_task(self.__loop())
# # connect ESP8266 to Thingspeak using MQTT # myMqttClient = "my-mqtt-client" # can be anything unique thingspeakIoUrl = "mqtt.thingspeak.com" c = MQTTClient(myMqttClient, thingspeakIoUrl, 1883) # uses unsecure TCP connection c.connect() # # publish temperature and free heap to Thingspeak using MQTT # i2cDeviceAddress = 24 i2cRegisterAddress = 5 i2cNumBytesToRead = 2 thingspeakChannelId = "YOUR-CHANNEL-ID" # <--- replace with your Thingspeak Channel ID thingspeakChannelWriteapi = "YOUR-CHANNEL-WRITEAPIKEY" # <--- replace with your Thingspeak Write API Key publishPeriodInSec = 30 while True: dataFromMCP9808 = i2c.readfrom_mem(i2cDeviceAddress, i2cRegisterAddress, i2cNumBytesToRead) # read temperature from sensor using i2c tempInDegC = convertMCP9808ToDegC(dataFromMCP9808) # note: string concatenations below follow best practices as described in micropython reference doc credentials = "channels/{:s}/publish/{:s}".format(thingspeakChannelId, thingspeakChannelWriteapi) payload = "field1={:.1f}&field2={:d}\n".format(tempInDegC, gc.mem_free()) c.publish(credentials, payload) time.sleep(publishPeriodInSec) c.disconnect()
from umqtt.simple import MQTTClient
sys.print_exception(e) strip.blink(2, colors['RED']) def connect(): while True: try: mqtt_client.connect(clean_session=True) mqtt_client.subscribe(settings.MQTT_TOPIC) break except Exception as e: sys.print_exception(e) time.sleep(1) mqtt_client = MQTTClient(ubinascii.hexlify(machine.unique_id()), settings.MQTT_HOST) mqtt_client.DEBUG = True mqtt_client.set_callback(on_message) connect() while True: try: mqtt_client.wait_msg() except Exception as e: sys.print_exception(e) connect() mqtt_client.disconnect()
# Toggle the onboard LED. You should probably disable this if # messages are being sent at a high rate led.value(not led.value()) # Blink the LED every 100ms to indicate we made it into the main.py file for _ in range(10): time.sleep_ms(100) led.value(not led.value()) # Toggle the LED time.sleep_ms(100) # Make sure the LED is off led.high() # define a time, because we only want to send every 1s but received as fast as possible # last_time = time.time() mqtt = MQTTClient(CLIENT_ID, HOST, port=PORT) # Subscribed messages will be delivered to this callback mqtt.set_callback(subscriction_callback) mqtt.connect() mqtt.subscribe(TOPIC) print('Connected to {}, subscribed to {} topic.'.format(HOST, TOPIC)) try: while 1: #micropython.mem_info() mqtt.wait_msg() finally: mqtt.disconnect()
def publish(s): c = MQTTClient('umqtt_client', SERVER) c.connect() c.publish(b'result', s.encode('UTF8')) c.disconnect()
def send(data): c = MQTTClient(SENSOR_ID, SERVER, 1883) c.connect() c.publish(PUB_TOPIC, json.dumps(data)) c.disconnect()
def xmt(server="localhost", topic="MQTT", note="empty message"): c = MQTTClient("umqtt_client", server) c.connect() c.publish(bytes(topic, 'UTF-8'), bytes(note, 'UTF-8')) c.disconnect()
class MQTTService(object): def __init__(self, sub_cb=None): self.__client = None self.__sub_cb = sub_cb self.__heartbeat_timer = Timer(0) self.__heartbeat_counter = 0 self.__client = MQTTClient( Settings.MQTT_CLIENT_ID, Settings.MQTT_HOST, Settings.MQTT_PORT, Settings.MQTT_USERNAME, Settings.MQTT_PASSWORD, Settings.MQTT_KEEPALIVE, ) def __heartbeat_cb(self, timer): self.__heartbeat_counter += 1 if self.__heartbeat_counter >= Settings.MQTT_KEEPALIVE: try: self.__client.publish( b'{}/ping'.format(Settings.MQTT_USERNAME), b'ping') self.__heartbeat_counter = 0 except OSError as ose: err_msg = str(ose) print("err time:", time()) print(err_msg) if err_msg in ("[Errno 104] ECONNRESET", "-1"): try: self.__client.disconnect() except OSError: pass finally: self.__client.connect() elif err_msg == "[Errno 113] EHOSTUNREACH": Utilities.hard_reset() gc.collect() def deinit(self): self.__client.disconnect() self.__heartbeat_timer.deinit() self.__client = None self.__heartbeat_timer = None def connect(self, clean_session=True): # mqtt_client.set_last_will(b'walkline/last_will', b'offline') self.__client.set_callback(self.__sub_cb) self.__client.connect(clean_session=clean_session) self.__heartbeat_timer.init(mode=Timer.PERIODIC, period=1000, callback=self.__heartbeat_cb) print("mqtt forever loop") print("now:", time()) username = Settings.MQTT_BIGIOT_USERNAME if bool( Settings.MQTT_IS_BIGIOT) else Settings.MQTT_CLIENT_ID self.__client.subscribe(b'{}/{}'.format(username, Settings.MQTT_CLIENT_ID)) def disconnect(self): self.__client.disconnect() def set_callback(self, f): self.__sub_cb = f self.__client.set_callback(self.__sub_cb) def set_last_will(self, topic, msg, retain=False, qos=0): self.__client.set_last_will(topic, msg, retain=retain, qos=qos) def ping(self): self.__client.ping() def publish(self, topic, msg, retain=False, qos=0): self.__client.publish(topic, msg, retain=retain, qos=qos) def subscribe(self, topic, qos=0): self.__client.subscribe(topic, qos=qos) def wait_msg(self): self.__client.wait_msg() def check_msg(self): self.__client.check_msg()
mqtt = 1 except Exception as e: print('MQTT connection failed', e) w.get_params() # enable the web interface if the wifi doesn't connect reset() c.subscribe(command_topic) # subscribe to command topic state = "OFF" # socket status relay.off() # set relay off red_led.on() # set red led off blue_led.off() # set blue led on send_status() # update home assistant with light on / off, rgb and brightness while True: c.check_msg() # non-blocking wait for message if button_flag: # if the button has been pressed button_flag = False # clear the button press f = open(w.cFile, 'w') # clear the password to force reconfig w.c["pwd"] = "" f.write(ujson.dumps(w.c)) f.close() reset() # hard reset sleep(.5) print('#',end='') c.disconnect() # if we come out of the loop for any reason then disconnect reset()
# messages are being sent at a high rate led.value(not led.value()) # Blink the LED every 100ms to indicate we made it into the main.py file for _ in range(10): time.sleep_ms(100) led.value(not led.value()) # Toggle the LED time.sleep_ms(100) # Make sure the LED is off led.high() # define a time, because we only want to send every 1s but received as fast as possible # last_time = time.time() mqtt = MQTTClient(CLIENT_ID, HOST, port=PORT) # Subscribed messages will be delivered to this callback mqtt.set_callback(subscriction_callback) mqtt.connect() mqtt.subscribe(TOPIC) print('Connected to {}, subscribed to {} topic.'.format(HOST, TOPIC)) try: while 1: #micropython.mem_info() mqtt.wait_msg() finally: mqtt.disconnect()
from umqtt.simple import MQTTClient import ubinascii, machine, time, dht from machine import Pin _dht22 = dht.DHT22(Pin(12)) _broker = '192.168.0.100' _port = 1883 _topic = b'mqtt/report' _msg = b'I am ESP8266' _alias = ubinascii.hexlify(machine.unique_id()) _client = MQTTClient(client_id=_alias, server=_broker, port=_port) _client.connect() try: for i in range(10): _dht22.measure() _t = _dht22.temperature() _h = _dht22.humidity() _msg = 'sta:{},temp:{:.2f},humd:{:.2f}'.format(_alias, _t, _h) _client.publish(_topic, _msg) time.sleep_ms(2000) finally: _client.disconnect()
class Controller(controller.ControllerProto): CONTROLLER_ID = 2 CONTROLLER_NAME = "Domoticz MQTT" def __init__(self, controllerindex): controller.ControllerProto.__init__(self, controllerindex) self.usesID = True self.onmsgcallbacksupported = True self.controllerport = 1883 self.inchannel = "domoticz/in" self.outchannel = "domoticz/out" # webformload? self._mqttclient = None self.lastreconnect = 0 self.usesAccount = True self.usesPassword = True self.usesMQTT = True self.authmode = 0 self.certfile = "" self.laststatus = -1 self.keepalive = 60 self._connected = False def controller_init(self, enablecontroller=None): if enablecontroller != None: self.enabled = enablecontroller self.connectinprogress = 0 try: ls = self.laststatus except: self.laststatus = -1 if self.controllerpassword == "*****": self.controllerpassword = "" self.initialized = True if self.enabled: try: if self._connected: pass except: self._connected = False try: if self._connected == False: misc.addLog(pglobals.LOG_LEVEL_DEBUG, "MQTT: Try to connect") self.connect() except: self._connected = False else: self.disconnect() return True def connect(self): if self.enabled and self.initialized: if self._connected: misc.addLog(pglobals.LOG_LEVEL_DEBUG, "Already connected force disconnect!") self.disconnect() self.connectinprogress = 1 self.lastreconnect = utime.time() try: am = self.authmode except: am = 0 cname = settings.Settings["Name"] + str(utime.time()) mna = self.controlleruser if mna.strip() == "": mna = None mpw = self.controllerpassword if mpw.strip() == "": mpw = None try: self._mqttclient = MQTTClient(cname, self.controllerip, port=int(self.controllerport), user=mna, password=mpw, keepalive=self.keepalive, ssl=(am != 0)) self._mqttclient.set_callback(self.on_message) self._mqttclient.connect() self._connected = self.isconnected() self._mqttclient.subscribe(self.outchannel.encode()) except Exception as e: misc.addLog( pglobals.LOG_LEVEL_ERROR, "MQTT controller: " + self.controllerip + ":" + str(self.controllerport) + " connection failed " + str(e)) self._connected = False self.laststatus = 0 else: self._connected = False self.laststatus = 0 return self._connected def disconnect(self): try: self._mqttclient.disconnect() except: pass self._connected = False self.laststatus = 0 try: commands.rulesProcessing("DomoMQTT#Disconnected", pglobals.RULE_SYSTEM) except: pass def isconnected(self, ForceCheck=True): res = -1 if self.enabled and self.initialized: if ForceCheck == False: return self._connected if self._mqttclient is not None: try: self._mqttclient.ping() res = 1 except: res = 0 if res != self.laststatus: if res == 0: commands.rulesProcessing("DomoMQTT#Disconnected", pglobals.RULE_SYSTEM) else: commands.rulesProcessing("DomoMQTT#Connected", pglobals.RULE_SYSTEM) self.laststatus = res if res == 1 and self.connectinprogress == 1: self.connectinprogress = 0 return res def webform_load(self): # create html page for settings ws.addFormTextBox("Controller Publish", "inchannel", self.inchannel, 255) ws.addFormTextBox("Controller Subscribe", "outchannel", self.outchannel, 255) try: kp = self.keepalive except: kp = 60 ws.addFormNumericBox("Keepalive time", "keepalive", kp, 2, 600) ws.addUnit("s") try: am = self.authmode fname = self.certfile except: am = 0 fname = "" options = ["MQTT", "MQTTS"] optionvalues = [0, 1] ws.addFormSelector("Mode", "c002_mode", len(optionvalues), options, optionvalues, None, int(am)) return True def webform_save(self, params): # process settings post reply pchange = False pval = self.inchannel self.inchannel = ws.arg("inchannel", params) if pval != self.inchannel: pchange = True pval = self.outchannel self.outchannel = ws.arg("outchannel", params) if pval != self.outchannel: pchange = True try: p1 = self.authmode self.authmode = int(ws.arg("c002_mode", params)) if p1 != self.authmode: pchange = True except: self.authmode = 0 pval = self.keepalive try: self.keepalive = int(ws.arg("keepalive", params)) except: self.keepalive = 60 if pval != self.keepalive: pchange = True if pchange and self.enabled: self.disconnect() utime.sleep(0.1) self.connect() return True def on_message(self, topic, msg): if self.enabled: msg2 = msg.decode('utf-8') mlist = [] if ('{' in msg2): try: mlist = ujson.loads(msg2) except Exception as e: misc.addLog(pglobals.LOG_LEVEL_ERROR, "JSON decode error:" + str(e) + str(msg2)) mlist = [] if (mlist) and (len(mlist) > 0): try: if mlist['Type'] == "Scene": # not interested in scenes.. return False except: pass devidx = -1 nvalue = "0" svalue = "" decodeerr = False tval = [-1, -1, -1, -1] try: devidx = str(mlist['idx']).strip() except: devidx = -1 decodeerr = True try: nvalue = str(mlist['nvalue']).strip() except: nvalue = "0" decodeerr = True try: svalue = str(mlist['svalue']).strip() except: svalue = "" if (';' in svalue): tval = svalue.split(';') tval2 = [] for x in range(1, 4): sval = "" try: sval = str(mlist['svalue' + str(x)]).strip() except: sval = "" if sval != "": tval2.append(sval) if len(tval2) == 1 and svalue == "": svalue = tval2[0] else: for y in range(len(tval2)): matches = misc.findall('[0-9]', tval2[y]) if len(matches) > 0: tval[y] = tval2[y] forcesval1 = False try: if ("Selector" in mlist['switchType']) or ( "Dimmer" in mlist['switchType']): forcesval1 = True except: forcesval1 = False if (tval[0] == -1) or (tval[0] == ""): if (float(nvalue) == 0 and svalue.lower() != "off" and svalue != "") or (forcesval1): tval[0] = str(svalue) else: tval[0] = str(nvalue) if decodeerr: misc.addLog(pglobals.LOG_LEVEL_ERROR, "JSON decode error: " + msg2) else: self._onmsgcallbackfunc(self.controllerindex, devidx, tval) def senddata(self, idx, taskobj, changedvalue=-1): if self.enabled: mStates = ["Off", "On"] # domomsg = '{{ "idx": {0}, "nvalue": {1:0.2f}, "svalue": "{2}" }}' domomsgw = '{{ "idx": {0}, "nvalue": {1:0.2f}, "svalue": "{2}", "RSSI": {3} }}' domomsgwb = '{{ "idx": {0}, "nvalue": {1:0.2f}, "svalue": "{2}", "RSSI": {3}, "Battery": {4} }}' domosmsgw = '{{"command": "switchlight", "idx": {0}, "switchcmd": "Set Level", "level":"{1}", "RSSI": {2} }}' domosmsgwb = '{{"command": "switchlight", "idx": {0}, "switchcmd": "Set Level", "level":"{1}", "RSSI": {2}, "Battery": {3} }}' if self._connected: try: usebattery = float(str(taskobj.battery).strip()) except Exception as e: usebattery = -1 if int(idx) > 0: if usebattery != -1 and usebattery != 255: bval = int(usebattery) else: bval = int(misc.get_battery_value()) msg = "" if (int(taskobj.vtype) == pglobals.SENSOR_TYPE_SWITCH): try: stateid = round(float(taskobj.uservar[0])) except: stateid = 0 if stateid < 0: stateid = 0 if stateid > 1: stateid = 1 msg = domomsgwb.format(str(idx), int(stateid), mStates[stateid], mapRSSItoDomoticz(taskobj.rssi), str(bval)) elif (int(taskobj.vtype) == pglobals.SENSOR_TYPE_DIMMER): msg = domosmsgwb.format( str(idx), str(taskobj.uservar[0]), mapRSSItoDomoticz(taskobj.rssi), str(bval)) else: msg = domomsgwb.format( str(idx), 0, formatDomoticzSensorType(taskobj.vtype, taskobj.uservar), mapRSSItoDomoticz(taskobj.rssi), str(bval)) try: self._mqttclient.publish(self.inchannel.encode(), msg.encode()) except: self._connected = False else: misc.addLog(pglobals.LOG_LEVEL_ERROR, "MQTT idx error, sending failed.") else: misc.addLog(pglobals.LOG_LEVEL_ERROR, "MQTT not connected, sending failed.") if ((utime.time() - self.lastreconnect) > 30): # if ((time.time()-self.lastreconnect)>30) and (self.connectinprogress==0): self.connect() def periodic_check(self): if self.enabled: try: if self._connected: self._mqttclient.check_msg() except: pass return self.onmsgcallbacksupported
payload_t["t"] = sum(payload_t["raw_t"]) / len(payload_t["raw_t"]) payload_h["h"] = sum(payload_h["raw_h"]) / len(payload_h["raw_h"]) except: pass c = MQTTClient(client, broker, port=broker_port) for _ in range(5): try: print("MQTT: CONNECTING ...") c.connect() print("MQTT: CONNECTION SUCCEEDED") break except: print("MQTT: CONNECTION FAILED") time.sleep(2) try: c.ping() c.publish(topic, json.dumps(payload_t)) c.publish(topic, json.dumps(payload_h)) print("MQTT: MESSAGE SENT") c.disconnect() except: print("MQTT: MESSAGE FAILED") print("SLEEP") rtc = machine.RTC() rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) rtc.alarm(rtc.ALARM0, sleepfor * 1000) machine.deepsleep()
class MQTTClientWrapper: def __init__(self, config): self.server = config.MQTT_SERVER self.port = config.MQTT_PORT self.mqtt_client = MQTTClient( client_id=config.MQTT_CLIENT_ID, server=self.server, port=self.port, user=config.MQTT_USER, password=config.MQTT_PASSWORD, keepalive=config.MQTT_KEEPALIVE, ssl=config.MQTT_SSL, ssl_params=config.MQTT_SSL_PARAMS, ) self.mqtt_client.set_callback(self._process_incoming_msgs) self.callbacks = {} self.connected = False self.max_retries = MQTT_MAX_RETRIES def connect(self): attempt = 1 while attempt <= self.max_retries: print('connecting to mosquitto server "{}:{}" (attempt {})...' .format(self.server, self.port, attempt), end='') try: res = self.mqtt_client.connect() if res == 0: print('done') break else: print('error {}'.format(res)) attempt += 1 except OSError: print('error') attempt += 1 else: self.connected = False raise MQTTConnectionError() self.connected = True def disconnect(self): self.mqtt_client.disconnect() def publish(self, topic, msg, qos=0, retain=False): print('publishing topic {}: {}...'.format(topic, msg), end='') self.mqtt_client.publish(topic, msg, qos, retain) print('done') def subscribe(self, topic, callback): self.callbacks[topic] = callback self.mqtt_client.subscribe(topic) def _process_incoming_msgs(self, topic, msg): topic = topic.decode() msg = msg.decode() callback = self.callbacks.get(topic) if callback is not None: callback(topic, msg) def wait_msg(self): return self.mqtt_client.wait_msg() def check_msg(self): return self.mqtt_client.check_msg() def ping(self): return self.mqtt_client.ping()
class Net: def __init__(self): self.SSID = SSID self.KEY = KEY self.dev_name = b'badge-' + hexlify(machine.unique_id()) self.sta = network.WLAN(network.STA_IF) self.client = MQTTClient(self.dev_name, 'mqtt.balda.ch', user='******', password='******') self.client.set_callback(self.mqtt_cb) self.CALLBACKS = {} def online(self): """ Put badge online """ self.sta.active(True) self.sta.connect(self.SSID, self.KEY) i = 0 while not self.sta.isconnected(): time.sleep(1) i = i + 1 if i == 5: return False try: self.client.connect() except OSError: return False return True def offline(self): """ Disconnect badge from network """ try: self.client.disconnect() except OSError: pass self.sta.active(False) def add_callback(self, topic, cb): """ Add MQTT callback topic is a topic name (bytes) cb is a function pointer. It need to have one parameter: the message """ #TODO Add cb type checking self.CALLBACKS.update({topic: cb}) self.client.subscribe(topic) def del_callback(self, topic): """ Remove a MQTT callback """ try: self.CALLBACKS.pop(topic) except KeyError: pass def mqtt_cb(self, topic, msg): """ Base MQTt callback. Use add_callback() to add a new one """ if topic in self.CALLBACKS.keys(): self.CALLBACKS[topic](msg)
MQTT_SERVER = "192.168.1.210" # Mettre a None si pas utile MQTT_USER = '******' MQTT_PSWD = '21052017' print("Creation MQTTClient") q = MQTTClient(client_id=CLIENT_ID, server=MQTT_SERVER, user=MQTT_USER, password=MQTT_PSWD) if q.connect() != 0: print("erreur connexion") sys.exit() print("Connecté") # annonce connexion objet sMac = hexlify(WLAN().config('mac')).decode() q.publish("connect/%s" % CLIENT_ID, sMac) # publication d'un compteur for i in range(10): print("pub %s" % i) q.publish("demo/compteur", str(i)) time.sleep(1) q.disconnect() print("Fin de traitement")
import easywifi import time import machine import gc import time from umqtt.simple import MQTTClient state="CLOSED" oldstate=state oldtest=-1 pin=machine.Pin(33,machine.Pin.IN,machine.Pin.PULL_UP) def test(): return pin.value() X=MQTTClient("openlabs42","clamans.mobach.de") while True: thetest = test() if oldtest != thetest: easywifi.enable() X.connect() oldtest = thetest state = "CLOSED" if thetest == 1 else "OPEN" X.publish("openlabs/state/state",state,1) ugfx.clear(ugfx.WHITE if state=="OPEN" else ugfx.BLACK) ugfx.string_box(0,45,296,38, state, "PermanentMarker36", ugfx.BLACK if state=="OPEN" else ugfx.WHITE, ugfx.justifyCenter) ugfx.flush(ugfx.LUT_FULL) X.disconnect() easywifi.disable() time.sleep(1)
class MQTT_Manager(MQTTClient): def __init__(self): from ubinascii import hexlify from machine import unique_id from ujson import loads from os import uname chip_name = uname().sysname chip_uid = hexlify(unique_id()).decode('utf-8') with open('mqtt_manager.json', 'r') as f: self.CONFIG = loads(f.read()) del (f) self.CONFIG['client_id'] = '{}_{}'.format(chip_name, chip_uid) username = self.CONFIG['client_id'] self.broker = MQTTClient( client_id=self.CONFIG['client_id'], server=self.CONFIG['broker'], port=self.CONFIG['port'], ssl=self.CONFIG['ssl'], user=self.CONFIG.get('username', None), password=self.CONFIG.get('password', None), ) def setup(self): with open("mqtt_manager.json", "w") as f: f.write("""\ { "broker": "broker.hivemq.com", "port": 1883, "ssl": false, "username": "******", "password": "******", "delay": 60, "chatty": 1, "client_id": "?", "topic_debug" : "debug", "topic_status" : "devices/{device_id}/status", "topic_control" : "devices/{device_id}/control" } """) return True def get_topic(self, topic): if not topic: key = 'debug' else: key = 'topic_' + topic if key in self.CONFIG: return self.CONFIG[key].format(device_id=self.CONFIG['client_id']) else: return topic def check(self): try: self.broker.connect() except: print('Error MQTT check') return False return True def send(self, topic, msg): try: self.broker.publish(self.get_topic(topic), bytes(msg, 'utf-8')) except: print('Error MQTT send') return False return True def check_msg(self): try: self.broker.check_msg() except: print('Error MQTT check_msg') return False return True def close(self): try: self.broker.disconnect() except: print('Error MQTT close') return False return True
def publish(t, h): c = MQTTClient('my_sensor', 'iot.eclipse.org') #change my_sensor!! c.connect() c.publish('RIFF/phil/temperature', str(t)) # change the topic tree! c.publish('RIFF/phil/humidity', str(h)) # change the topic tree! c.disconnect()
class MQTT(): def __init__(self, name, secrets, uid=None, led=None): self.name = name self.secrets = secrets self.uid = uid self.led = led self.state = {} self.obj = [] self.cfg = [] self.cb = {} self.do_pub_cfg = True self.reconnect = True self.mqtt = None self.topic = None self.mac = wifi.mac() self.err = 0 def log(self, e): print('mqtt', self.err, ':') print_exception(e) # n = 'mqtt' + '.' + 'log' # with open(n, 'w') as f: # f.write("\n\n[%d]\n" % self.err) # print_exception(e, f) def connect(self): self.discon() self.mqtt = MQTTClient( self.mac, self.secrets.MQTT_SERVER, keepalive=60, user=self.secrets.MQTT_USER.encode(UTF8), password=self.secrets.MQTT_PASSWORD.encode(UTF8)) def rx(tpc, msg): if self.led: self.led.on() print(' >', 'rx', tpc) print(' >', 'rx', msg) try: msg = msg.decode(UTF8) gc_collect() for t, cb in self.cb.items(): if t == tpc: print(' >', 'rx', 'cb') cb(msg) break except Exception as e: self.log(e) else: self.err = 0 if self.led: self.led.off() self.mqtt.set_callback(rx) self.mqtt.connect() sleep(0.5) if self.do_pub_cfg: self.do_pub_cfg = not (self.pub_cfg()) sleep(0.5) if self.topic != None: print('subscribe', self.topic) self.mqtt.subscribe(self.topic) sleep(0.5) gc_collect() def discon(self): if self.mqtt != None: try: self.mqtt.disconnect() except: pass self.mqtt = None gc_collect() def add(self, name, cls, prim=False, key=None, **cfg): obj = cls( prefix=self.secrets.MQTT_PREFIX, uid=self.uid, dev_name=self.name, name=name, prim=prim, key=key, state=self.state, ) self.obj.append(obj) self.cfg.append(cfg) return obj def pub_cfg(self): if self.led: self.led.fast_blink() ok = True for i, obj in enumerate(self.obj): print(obj.__class__.__name__) gc_collect() if not self.pub_json( obj.cfg_tpc(), obj.cfg(**self.cfg[i]), retain=True): ok = False print('pub_cfg', 'err') if self.led: self.led.off() return ok def try_pub_cfg(self): ok = False if wifi.is_connected(): try: if not self.mqtt: self.do_pub_cfg = True self.connect() ok = True else: ok = self.pub_cfg() except Exception as e: self.log(e) self.discon() self.do_pub_cfg = False return ok def set_attr(self, key, val): self.obj[0].set_attr(key, val) def set_wifi_attr(self): self.set_attr("ip", wifi.ip()) self.set_attr("mac", self.mac) self.set_attr("rssi", wifi.rssi()) def publish(self, tpc, msg, **kwarg): print(' <', 'tx', tpc) print(' <', 'tx', msg) if wifi.is_connected() and self.mqtt: if type(tpc) != type(b''): tpc = tpc.encode(UTF8) if type(msg) != type(b''): msg = msg.encode(UTF8) self.mqtt.publish(tpc, msg, **kwarg) sleep(0.5) print(' <', 'tx', 'ok') return True return False def pub_json(self, tpc, obj, **kwarg): gc_collect() with BytesIO() as json: json_dump(obj, json) gc_collect() ok = self.publish(tpc, json.getvalue(), **kwarg) gc_collect() return ok def pub_state(self): gc_collect() if len(self.obj) != 0: return self.pub_json(self.obj[0].base_tpc(), self.state) gc_collect() def sub(self, tpc, cb): print('sub', tpc) gc_collect() self.cb[tpc.encode(UTF8)] = cb first = next(iter(self.cb)) if len(self.cb) == 1: self.topic = first else: self.topic = b'' for i, char in enumerate(first): for t in self.cb.keys(): if t[i] != char: char = None break if char == None: break else: self.topic += chr(char) self.topic += b'#' gc_collect() def sub_dev_cmd(self, tpc): def uid(msg): with open('uid' + '.py', 'w') as f: f.write('UID = "%s"' % msg) self.sub(tpc + '/' + 'uid', uid) def reset(msg): sleep(randint(3)) machine.reset() self.sub(tpc + '/' + 'reset', reset) def secrets(msg): with open('secrets' + '.' + 'json', 'w') as f: f.write(msg) self.sub(tpc + '/' + 'secrets', secrets) def wait(self): while self.reconnect: try: self.connect() while True: gc_collect() self.mqtt.wait_msg() except Exception as e: self.err += 1 self.log(e) self.discon() if self.err > 1000: machine.reset() if self.err > 60: if self.led: led.slow_blink() # add a bit of randomness in case every device on the network are all retrying at the same time: sleep(60 + randint(3)) if self.led: self.led.off() else: sleep(self.err)
if value & 0x1000: temp -= 256.0 temp = int( round(((temp * 9) / 5) + 32) ) #converts the temp to F and makes it a nice round int for the display. return temp #### Main Program #### # Publish Temp. def pub_temp(): while True: led0.low() #Turns LED on sleep(.5) sensor_data = i2c.readfrom_mem(i2cDeviceAddress, i2cRegisterAddress, i2cNumBytesToRead) #read sensor sensor_temp = convert_temp(sensor_data) #creates a new variable made c.publish(topic, str(sensor_temp)) #publish data MQTT broker print(sensor_temp) #To monitor from the serial repl. led0.high() #Turns LED off sleep(1) #Sleep interval sleep(5) #connect to MQTT c = MQTTClient(client, server) c.connect() pub_temp() #Calls the main program c.disconnect() #Disconnects from server
class mqtt_client(): def __init__(self, topics, client_id, mqtt_server_ip, port=1883, callback=basic_callback, debug=False): self.server_ip = mqtt_server_ip self.port = port self.id = client_id self.__mqtt_client = MQTTClient(self.id, self.server_ip) self.__callback = callback self.topics = list(topics) self.connected = False if debug: from logger import logger self.logger = logger() else: from logger import dummy_logger self.logger = dummy_logger() self.__last_reset = time() self.__reset_time = 1800 # 30 minutes self.__connect() def __str__(self): results = 'mqtt client\n id {}\n server {}\n connected {}\n callback {}\n topics {}\n' return results.format(self.id, self.server_ip, self.connected, self.__callback, self.topics) def __connect(self): try: self.logger.log('connecting to mqtt', 'id:', self.id, 'ip:', self.server_ip) self.__mqtt_client = MQTTClient(self.id, self.server_ip, self.port) self.__mqtt_client.connect() if self.__callback != None: self.__mqtt_client.set_callback(self.__callback) for tpc in self.topics: self.logger.log(self.id, 'subscribing to topic ', tpc) self.__mqtt_client.subscribe(tpc) self.logger.log( self.id, 'connected to mqtt server at {}'.format(self.server_ip)) self.__last_reset = time() self.connected = True except OSError as err: print(self.id, 'unable to connect to mqtt server \n', err) self.connected = False def subscribe(self, topic): if topic not in self.topics: self.topics.append(topic) if self.connected: self.__mqtt_client.subscribe(topic) def unsubscribe(self, topic): if topic in self.topics: self.topics.pop(topic) # umqtt.simple does not implement an unsubscribe method def wait_msg(self): self.check_msg(blocking=True) def check_msg(self, blocking=False): try: self.is_alive() # reset connection every xx minutes if time() - self.__last_reset > self.__reset_time: self.reconnect() self.logger.log(self.id, 'checking for new messages') if blocking: self.__mqtt_client.wait_msg() else: self.__mqtt_client.check_msg() self.connected = True except OSError as err: self.connected = False self.logger.log(self.id, 'no connection to mqtt server \n', err) def publish(self, topic, message): tpc = topic.encode('utf-8') msg = message.encode('utf-8') try: self.is_alive() self.__mqtt_client.publish(tpc, msg, 0, True) self.logger.log( self.id, 'published topic {}, message {}'.format(topic, message)) self.connected = True except OSError as err: self.logger.log( self.id, 'error publishing topic {}, message {}. \n not connected to mqtt server\n' .format(topic, message), err) self.connected = False def reconnect(self): self.logger.log(self.id, 'reconnecting now') self.__mqtt_client.disconnect() sleep_ms(1000) self.__connect() def disconnect(self): self.logger.log(self.id, 'disconnecting now') try: self.__mqtt_client.disconnect() except OSError as err: self.connected = False self.logger.log(self.id, 'no connection to mqtt server \n', err) def is_alive(self): # check if connected is true and reconnect if it is not. if succesful, the # function will return true, otherwise, false if not self.connected: self.logger.log('disconnected, attempting reconnect') self.__connect() return self.connected
def main(): global my_new_msg global TOPIC_BASE mq_fail_count = 0 tm_pub_th = time.ticks_ms() led_onoff(1) #- check ap config file AP_SSID = 'upy' AP_PWD = 'pypypypy' ap_config = None ap_config_fn = 'ap.txt' if ap_config_fn in os.listdir(): print('ap config here!') f = open(ap_config_fn) ap_config = f.read() f.close() if ap_config: print( ('ap_config:', ap_config)) ap_config = ap_config.split('\n') AP_SSID = ap_config[0].strip() AP_PWD = ap_config[1].strip() print('line to: ', (AP_SSID, AP_PWD)) # Default MQTT server to connect to server = "iot.eclipse.org" CLIENT_ID = ubinascii.hexlify(machine.unique_id()).decode('utf-8') topic_light = TOPIC_BASE+"/light" topic_t = TOPIC_BASE+'/T' topic_h = TOPIC_BASE+'/H' topic_msg = TOPIC_BASE+'/msg' wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(AP_SSID, AP_PWD) print('connecting to AP') while(not wlan.isconnected()): print(wlan.ifconfig()) time.sleep(0.1) led_onoff(-1) print('connected! --> ', wlan.ifconfig()) c = MQTTClient(CLIENT_ID, server) # Subscribed messages will be delivered to this callback c.set_callback(sub_cb) c.connect() c.subscribe(topic_light) print("Connected to %s, subscribed to %s topic" % (server, topic_light)) # wifi ready, blink led for i in range(3): led_onoff(1) time.sleep(1) led_onoff(0) time.sleep(1) print('I am ready!, ID='+str(CLIENT_ID)) c.publish(topic_msg, 'I am ready!, ID='+str(CLIENT_ID)) try: while 1: if(not wlan.isconnected()): # not do any mq operation time.sleep(0.1) led_onoff(-1) continue try: #c.wait_msg() c.check_msg() if my_new_msg: c.publish(topic_msg, my_new_msg) my_new_msg = None if(time.ticks_ms()-tm_pub_th > 5000): # public some information T, H = dht_get() c.publish(topic_t, str(T)) c.publish(topic_h, str(H)) tm_pub_th = time.ticks_ms() except Exception as e: print('wlan:', wlan.isconnected()) print('ex: ', str(e)) mq_fail_count+=1 time.sleep(1) try: if mq_fail_count>5: mq_fail_count=0 c = MQTTClient(CLIENT_ID, server) # Subscribed messages will be delivered to this callback c.set_callback(sub_cb) c.connect() c.subscribe(topic_light) print("Connected to %s, subscribed to %s topic" % (server, topic_light)) except Exception as e: print('wlan:', wlan.isconnected()) print('ex: ', str(e)) time.sleep(0.001) finally: c.disconnect()
class Sensor: def __init__(self, name, server, port, keyfile, certfile, root_topic): self.topic = root_topic + '/' + name self.repl = None self.on_repl_disabled = None with open(keyfile, 'rb') as f: key = f.read() with open(certfile, 'rb') as f: cert = f.read() self.client = MQTTClient(name, server=server, port=port, ssl=True, ssl_params={ 'key': key, 'cert': cert }, keepalive=60) def connect(self): self.client.set_callback(self._subscribe_callback) self.client.set_last_will(self.topic + '/status', b'offline', retain=True, qos=1) self.client.connect() self.publish_status(b'online') self.client.subscribe(self.topic + '/repl') self.client.wait_msg() def disconnect(self): self.publish_status(b'offline') self.client.disconnect() def publish(self, topic, data): t = self.topic + '/' + topic self.client.publish(t, data) print('Published {} = {}'.format(topic, data)) def update(self): self.client.ping() self.client.wait_msg() def publish_measurment(self, measurment): data = measurment.to_line_protocol() self.publish('measurement', data) def publish_status(self, status): self.client.publish(self.topic + '/status', status, retain=True, qos=1) def _subscribe_callback(self, topic, msg): print('Received: ', topic, msg) if topic.decode() == self.topic + '/repl': prev = self.repl self.repl = (msg == b'1') if self.on_repl_disabled: if prev and not self.repl: self.on_repl_disabled()
def main(server="localhost"): c = MQTTClient("umqtt_client", server) c.connect() c.publish(b"foo_topic", b"hello") print('done') c.disconnect()
def transmit(switch_cntrl, light1, light2, sw, topic, name="outlet_default", server="192.168.1.90", err_slp=100, err_rst=150): print("Starting MQTT transmitter...") #save the start time (syear, smonth, smday, shour, sminute, ssecond, sweekday, syearday) = utime.localtime() #configure switch pins outlet_switch = machine.Pin(sw, machine.Pin.OUT) outlet_light1 = machine.Pin(light1, machine.Pin.OUT) outlet_light2 = machine.Pin(light2, machine.Pin.OUT) outlet_cntrl = machine.Pin(switch_cntrl, machine.Pin.IN, machine.Pin.PULL_UP) #set the outlet to the default state outlet_switch.off() outlet_light1.off() #flash the blue light so user has indication that outlet is working outlet_light2.on() time.sleep(.25) blink1() blink1() outlet_light1.on() #define the channels btopic = bytes(topic, 'utf-8') state_channel = btopic command_channel = btopic + b'/set' availability_channel = btopic + b'/available' debug_channel = 'debug' #set up udp socket c = MQTTClient(name, server) c.set_last_will(topic=availability_channel, msg=b'offline', retain=False, qos=0) c.connect() print("Started!") #notify that you're available c.publish(availability_channel, b'online') def dbg_msg(name, msg): #debug messages payload = {} payload["outlet_name"] = name payload["message"] = msg a = ujson.dumps(payload) c.publish(debug_channel, a) dbg_msg(name, 'switch boot up') #status def status(): (year, month, mday, hour, minute, second, weekday, yearday) = utime.localtime() print("") print("") print("Outlet v.0.5.0") print("{}/{}/{} {}:{}:{} | boot: {}/{}/{} {}:{}:{}".format( month, mday, year, hour, minute, second, smonth, smday, syear, shour, sminute, ssecond)) print("Error Count: {}".format(str(error_cnt))) print("") print("Outlet status: " + str(outlet_switch.value())) print("Outlet name: " + name) print("Outlet topic: " + topic) dbg_msg(name, "Outlet status: " + str(outlet_switch.value())) #mqtt callback def monitor_cmds(topic, msg): if msg == b"ON": outlet_switch.on() try: c.publish(state_channel, b'ON') dbg_msg(name, 'switch commanded on') except: print("Error - Publish On!") rst_comm() error_cnt += 1 outlet_light1.off() outlet_light2.on() elif msg == b"OFF": outlet_switch.off() try: c.publish(state_channel, b'OFF') dbg_msg(name, 'switch commanded off') except: print("Error - Publish Off!") rst_comm() error_cnt += 1 outlet_light1.on() outlet_light2.on() #elif msg == b"schedule update": #elif msg == b"request schedule": #elif msg == b"schedule message": #elif msg == b"control selection": #elif msg == b"reboot": #phyisical button def btn_cntrl(p): time.sleep(1) if outlet_cntrl.value() == 0: if outlet_switch.value() == 0: monitor_cmds('', b'ON') else: monitor_cmds('', b'OFF') #debug messages dbg_msg(name, 'physical button pressed') def rst_comm(): c.disconnect() c.connect() c.subscribe(command_channel) dbg_msg(name, 'device reset') #set interrupts c.set_callback(monitor_cmds) outlet_cntrl.irq(handler=btn_cntrl, trigger=outlet_cntrl.IRQ_FALLING) #subscribe to the command channel c.subscribe(command_channel) #wait error_cnt = 0 while True: try: #check the command channel c.check_msg() except: print("Error - Check Message!") #reboot the connection rst_comm() error_cnt += 1 #print status to the repl try: status() except: print("Error - Status") error_cnt += 1 #watch error count, reset if limit exceeded if error_cnt == err_slp: time.sleep(15) elif error_cnt > err_rst: machine.reset() #Wait for a second time.sleep(1) c.disconnect() print('exiting...')
def main(server): global run global lapnr global nr global c global mqttConnected """ Defines which client to connect to. Using adafruit.io broker requires authentification so we also set username and password """ c = MQTTClient("Sensor boards", server, user=user, password=passwd) c.set_callback(sub_cb) #sets flag for mqtt connected if c.connect() == False: mqttConnected = True print('MQTT Connected') #subscribe to the topic where controls are received c.subscribe("kk2314/feeds/control") while True: if True: c.wait_msg() #blocking check for message #start timing laps if run == True: #reset the run flag run = False #do countdown countdown() c.publish(mqtt_debug, "Started countdown") #start timer start = time.ticks_ms() c.publish(mqtt_debug, "Timer started") print("go") #wait for user to go away from sensor time.sleep(5) #resets statistical variables every beginning of run lap_index = 0 best_lap = 0 avr_lap = 0 total_time = 0 worst_lap = 0 #main while loop which continues until lapnr goes to 0 while lapnr > 0: blink_LED(blue) data = adc.read(0) convert(data) #if sensor detects object within threshold it times a lap if distance < 0.80: lap_time_raw = time.ticks_diff(time.ticks_ms(), start) #reset time measure start = time.ticks_ms() c.publish(mqtt_debug, "Lap end detected") lap_index = lap_index + 1 total_time = total_time + lap_time_raw #check if the lap is the slowest if lap_time_raw > worst_lap: worst_lap = lap_time_raw worst_index = lap_index #update average lap_time avr_lap = total_time / lap_index #check if lap is the fastest if lap_index == 1: best_lap = lap_time_raw best_index = 1 elif lap_time_raw < best_lap: best_lap = lap_time_raw best_index = lap_index #format all the statistical values in mins, secs mins_av, secs_av = format(avr_lap) mins_bs, secs_bs = format(best_lap) mins_ws, secs_ws = format(worst_lap) mins_to, secs_to = format(total_time) mins, secs = format(lap_time_raw) #read current temp get_temp() #send alert if temperature is outside ideal range if temp > 21 and temp < 29: c.publish( mqtt_tempalert, "Temperature is ideal for a splash, Happy Swimming!" ) elif temp < 21: c.publish( mqtt_tempalert, "Careful! We have detected temperature is outside ideal range (Too low)" ) elif temp > 29: c.publish( mqtt_tempalert, "Careful! We have detected temperature is outside ideal range (Too high)" ) #encode all data to JSON - manually to save memory payload_temp = "{}".format(temp) payload = " Lap number {} was: {} m {} s. ".format( lap_index, mins, secs) payload_raw = "{}".format(lap_time_raw / 1000) payload_stat_av = "Average lap time is : {} m {} s ".format( mins_av, secs_av) payload_stat_bs = "Best lap was lap number {} : {} m {} s ".format( best_index, mins_bs, secs_bs) payload_stat_ws = "Worst lap was lap number {} : {} m {} s ".format( worst_index, mins_ws, secs_ws) payload_stat_to = "Total time is : {} m {} s ".format( mins_to, secs_to) #publish converted and raw data to mqtt broker c.publish(mqtt_time, payload) c.publish(mqtt_rawdata, payload_raw) c.publish(mqtt_temp, payload_temp) c.publish(mqtt_stat, payload_stat_av) c.publish(mqtt_stat, payload_stat_bs) c.publish(mqtt_stat, payload_stat_ws) c.publish(mqtt_stat, payload_stat_to) c.publish(mqtt_debug, "Data published successfully") lapnr = lapnr - 1 #wait for 10 sec for object to get out of range of sensor if lapnr != 0: time.sleep(10) c.publish(mqtt_debug, "Done with current run") #debug messages else: c.check_msg() #non-blocking check for message #start timing laps if run == True: #reset the run flag run = False #do countdown countdown() c.publish(mqtt_debug, "Started countdown") #start timer start = time.ticks_ms() c.publish(mqtt_debug, "Timer started") print("go") #wait for user to go away from sensor time.sleep(5) #resets statistical variables every beginning of run lap_index = 0 best_lap = 0 avr_lap = 0 total_time = 0 worst_lap = 0 #main while loop which continues until lapnr goes to 0 while lapnr > 0: blink_LED(blue) data = adc.read(0) convert(data) #if sensor detects object within threshold it times a lap if distance < 0.80: lap_time_raw = time.ticks_diff(time.ticks_ms(), start) #reset time measure start = time.ticks_ms() c.publish(mqtt_debug, "Lap end detected") lap_index = lap_index + 1 total_time = total_time + lap_time_raw #check if the lap is the slowest if lap_time_raw > worst_lap: worst_lap = lap_time_raw worst_index = lap_index #update average lap_time avr_lap = total_time / lap_index #check if lap is the fastest if lap_index == 1: best_lap = lap_time_raw best_index = 1 elif lap_time_raw < best_lap: best_lap = lap_time_raw best_index = lap_index #format all the statistical values in mins, secs mins_av, secs_av = format(avr_lap) mins_bs, secs_bs = format(best_lap) mins_ws, secs_ws = format(worst_lap) mins_to, secs_to = format(total_time) mins, secs = format(lap_time_raw) #read current temp get_temp() #send alert if temperature is outside ideal range if temp > 21 and temp < 29: c.publish( mqtt_tempalert, "Temperature is ideal for a splash, Happy Swimming!" ) elif temp < 21: c.publish( mqtt_tempalert, "Careful! We have detected temperature is outside ideal range (Too low)" ) elif temp > 29: c.publish( mqtt_tempalert, "Careful! We have detected temperature is outside ideal range (Too high)" ) #encode all data to JSON - manually to save memory payload_temp = "{}".format(temp) payload = " Lap number {} was: {} m {} s. ".format( lap_index, mins, secs) payload_raw = "{}".format(lap_time_raw / 1000) payload_stat_av = "Average lap time is : {} m {} s ".format( mins_av, secs_av) payload_stat_bs = "Best lap was lap number {} : {} m {} s ".format( best_index, mins_bs, secs_bs) payload_stat_ws = "Worst lap was lap number {} : {} m {} s ".format( worst_index, mins_ws, secs_ws) payload_stat_to = "Total time is : {} m {} s ".format( mins_to, secs_to) #publish converted and raw data to mqtt broker c.publish(mqtt_time, payload) c.publish(mqtt_rawdata, payload_raw) c.publish(mqtt_temp, payload_temp) c.publish(mqtt_stat, payload_stat_av) c.publish(mqtt_stat, payload_stat_bs) c.publish(mqtt_stat, payload_stat_ws) c.publish(mqtt_stat, payload_stat_to) c.publish(mqtt_debug, "Data published successfully") lapnr = lapnr - 1 #wait for 10 sec for object to get out of range of sensor if lapnr != 0: time.sleep(10) c.publish(mqtt_debug, "Done with current run") #debug messages c.disconnect()
class MQTT_Manager(MQTTClient): def __init__(self): from ubinascii import hexlify from machine import unique_id from ujson import loads from os import uname chip_name = uname().sysname chip_uid = hexlify(unique_id()).decode('utf-8') with open('mqtt_manager.json', 'r') as f: self.CONFIG = loads(f.read()) del (f) self.CONFIG['client_id'] = '{}_{}'.format(chip_name, chip_uid) username = self.CONFIG['client_id'] self.broker = MQTTClient( client_id=self.CONFIG['client_id'], server=self.CONFIG['broker'], user=self.CONFIG.get('username', None), password=self.CONFIG.get('password', None), ) def get_topic(self, topic): # get topics from json file if not topic: key = 'debug' else: key = 'topic_' + topic if key in self.CONFIG: return self.CONFIG[key].format(device_id=self.CONFIG['client_id']) else: return topic def check(self): try: self.broker.connect() except: print('Error MQTT check') return False return True def send(self, topic, msg): try: self.broker.publish(self.get_topic(topic), bytes(msg, 'utf-8')) except: print('Error MQTT send') return False return True def check_msg(self): try: self.broker.check_msg() except: print('Error MQTT check_msg') return False return True def close(self): try: self.broker.disconnect() except: print('Error MQTT close') return False return True
client.set_callback(cb)# To get the messages from broker client.subscribe(RESPONSE_FEED)# Subscribe to the waterplant topic PUBLISH_PERIOD_IN_SEC = 10 SUBSCRIBE_CHECK_PERIOD_IN_SEC = 0.5 accum_time = 0 while True: try: # Publish if accum_time >= PUBLISH_PERIOD_IN_SEC: sensor=adc.read() p=int((sensor*100)/1024) p=100-p dataToSend = p print('Publish: Soil Moisture = {}'.format(dataToSend)) msg=(b'{0},{1}'.format("sagar16812",p)) client.publish(SOIL_FEED,msg) accum_time = 0 # Subscribe. Non-blocking check for a new message. client.check_msg() time.sleep(SUBSCRIBE_CHECK_PERIOD_IN_SEC) accum_time += SUBSCRIBE_CHECK_PERIOD_IN_SEC except KeyboardInterrupt: print('Ctrl-C pressed...exiting') client.disconnect() sys.exit()
def main(): button = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_UP) orgid = "replace with your 6 character org id" token = "replace with your token" user = "******" # Make sure this matches up with the device type you configured through the IoT platform deviceType = "ESP8266" # Change to match your device Id deviceId = "pet2" server = '{}.messaging.internetofthings.ibmcloud.com'.format(orgid) clientId = 'd:{}:{}:{}'.format(orgid, deviceType, deviceId) try: client = MQTTClient(clientId, server, port=8883, ssl=True, user=user, password=token) except: print('MQTT client setup error') try: client.set_callback(updatePet) except: print('MQTT callback error') pendingNotification = False reminded = False counter = 0 while True: counter = counter + 1 # every so many runs through the loop, connect to the MQTT broker to publish and check for messages # prevents repeated button press spam if counter >= 800: counter = 0 if (reminded == False): remind('good') reminded = True client.connect() # non-blocking check for messages client.subscribe(b"iot-2/cmd/update-tracker/fmt/json") client.check_msg() client.disconnect() time.sleep(0.01) # send notification if button was pressed since last time if pendingNotification == True: print('connecting to MQTT broker...') client.connect() client.publish(b"iot-2/evt/habit/fmt/json", b"{\"responded\":\"true\"}") pendingNotification = False print('disconnecting from MQTT broker') client.disconnect() # detect button presses firstButtonReading = button.value() time.sleep(0.01) secondButtonReading = button.value() if firstButtonReading and not secondButtonReading: # notification will be sent pendingNotification = True beHappy()
def main(server="localhost"): c = MQTTClient("umqtt_client", server) c.connect() c.publish(b"foo_topic", b"hello") c.disconnect()
#Hardware Platform: FireBeetle-ESP32 #Result: input MQTTlibrary and remote controls LED by mqtt communication. from umqtt.simple import MQTTClient from machine import Pin import network import time SSID = "yourSSID" PASSWORD = "******" led = Pin(2, Pin.OUT, value=0) SERVER = "182.254.130.180" CLIENT_ID = "yourClientID" TOPIC = b"yourTOPIC" username = '******' password = '******' state = 0 c = None def sub_cb(topic, msg): global state print((topic, msg)) if msg == b"on": led.value(1) state = 0 print("1") elif msg == b"off": led.value(0) state = 1 print("0") elif msg == b"toggle": # LED is inversed, so setting it to current state