class Iot(object): client_id = ubinascii.hexlify(machine.unique_id()) client = None def __init__(self, *args, **kwargs): super(Iot, self).__init__(*args, **kwargs) try: print('mqtt running') self.client = MQTTClient(self.client_id, "mqtt.eclipse.org", keepalive=0) self.client.connect() self.client.set_callback(self.on_message) self.client.subscribe(b"sooko/lampu") while True: self.client.wait_msg() except: print('mqtt stoped') Wifi().disconnect() machine.reset() def on_message(self, topic, msg): print(topic, msg) if msg == b"on": self.grenn_on() self.client.publish(b"loger", b"saya hidup") elif msg == b"off": self.grenn_off() self.client.publish(b"loger", b"saya mati") def grenn_on(self): Pin(2, Pin.OUT).value(0) def grenn_off(self): Pin(2, Pin.OUT).value(1)
class Board: def __init__(self): self.id = ubinascii.hexlify(machine.unique_id()).decode("utf-8") print("machine id: {}".format(self.id)) self.mqtt = MQTTClient(self.id, MQTT_HOST, MQTT_PORT, MQTT_USER, MQTT_PASSWORD) self.led = Led() self.lightsensor = Lightsensor() self.dispatcher = {} self.dispatcher["{}/led/rgb".format( self.id)] = lambda rgb: self.led.set_rgb(rgb["red"], rgb["green"], rgb["blue"]) self.dispatcher["{}/led/ping".format( self.id)] = lambda msg: self.led.ping() def process_message(self, topic, msg): topic_str = topic.decode("utf-8") msg_str = msg.decode("utf-8") if topic_str in self.dispatcher: self.dispatcher[topic_str](ujson.loads(msg_str)) def publish_lightlevel(self, alarm): self.mqtt.publish(topic="lightdata", msg=ujson.dumps({ "lightlevel": self.lightsensor.get_lightlevel(), "board_id": self.id })) def run(self): self.mqtt.set_callback(self.process_message) self.mqtt.connect() self.mqtt.subscribe("{}/led/rgb".format(self.id)) self.mqtt.subscribe("{}/led/ping".format(self.id)) self.mqtt.publish(topic="board_discovery", msg=ujson.dumps({"id": self.id})) alarms = [] alarms.append( Timer.Alarm(handler=self.publish_lightlevel, s=5, periodic=True)) try: while True: self.mqtt.wait_msg() machine.idle() finally: for alarm in alarms: alarm.cancel() self.mqtt.disconnect()
def data(msg, PASSWD): import setting import ujson from mqtt import MQTTClient global answer answer = 'OK' IOTHUB = setting.get('iothub') DEVICE = setting.get('iotdevicename') KEY = setting.get('iotdevicesecret') USER = IOTHUB + '/' + DEVICE + '/api-version=2016-11-14' print('--------------MQTT----------') print('DEVICE: ', DEVICE) print('IOTHUB: ', IOTHUB) print('USER: '******'PASSWD: ', PASSWD) c = MQTTClient( DEVICE, IOTHUB, 8883, USER, PASSWD, 0, True ) # client_id, server, port=0, user=None, password=None, keepalive=0, ssl=False, ssl_params={}) c.set_callback(sub_cb) try: c.connect() print('--------------PUBLISH----------') print('DEVICE: ', 'devices/' + DEVICE + '/messages/events/') print('MSG: ', msg) c.publish('devices/' + DEVICE + '/messages/events/', msg, False, 1) # topic, msg, retain=False, qos=0 c.subscribe('$iothub/twin/res/#', 1) # topic, qos=0 c.publish('$iothub/twin/GET/?$rid=2', '', False, 1) c.wait_msg() dictr = {} dictr["RSSI"] = setting.get('RSSI') dictr["health"] = setting.get('health') dictr["hwid"] = setting.get('hwid') dictr["VBat"] = setting.get('VBat') dictr["FWversion"] = setting.get('FWversion') dictr["FWnumber"] = setting.get('FWnumber') try: dict = ujson.loads(answer) print('RX TWIN MSG: ', dict) dict_rep = dict["reported"] keyp = dict_rep["keypresses"] + 1 dictr["keypresses"] = keyp except: dictr["keypresses"] = 1 print('TX TWIN MSG: ', dictr) reported = ujson.dumps(dictr) c.publish('$iothub/twin/PATCH/properties/reported/?$rid=1', reported, False, 1) c.disconnect() except (): answer = 'ERROR' return answer
def main(server="test.mosquitto.org"): c = MQTTClient("umqtt_clientc", server) c.set_callback(sub_cb) c.connect() c.subscribe(b"mhermans/lights/#") 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()
def mqtt_listen(server=MQTT_BROKER): global mqttc mqttc = MQTTClient("umqtt_client", server) mqttc.set_callback(sub_cb) mqttc.connect() mqttc.subscribe(b"sensor/#") while True: if True: # Blocking wait for message mqttc.wait_msg() else: # Non-blocking wait for message mqttc.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) mqttc.disconnect()
class Board: def __init__(self, components): self.led = components["pycom_led"]() self.validate_components() self.mqtt = MQTTClient("b1", "<host>", user="******", password="******", port=1883) def validate_components(self): set_intensity = getattr(self.led, "set_intensity", None) if set_intensity is None or not callable(set_intensity): raise Exception("led missing method set_intensity") set_status = getattr(self.led, "set_status", None) if set_status is None or not callable(set_status): raise Exception("led missing method set_status") def process_message(self, topic, msg): topic_str = topic.decode("utf-8") msg_str = msg.decode("utf-8") if topic_str == "b1/led/intensity": self.led.set_intensity(float(msg_str)) if topic_str == "b1/led/status": self.led.set_status(msg_str) def run(self): self.mqtt.set_callback(self.process_message) self.mqtt.connect() self.mqtt.subscribe("b1/led/intensity") self.mqtt.subscribe("b1/led/status") alarms = [] try: while True: self.mqtt.wait_msg() machine.idle() finally: for alarm in alarms: alarm.cancel() self.mqtt.disconnect()
def main(server=SERVER): c = MQTTClient(CLIENT_ID, server, user="******", password="******", port=1883) # Subscribed messages will be delivered to this callback c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC) print("Connected to %s, subscribed to %s topic" % (server, TOPIC)) try: while 1: c.wait_msg() oled.fill(0) oled.text('Waiting msg.', 10, 10) oled.text('string', 10, 32) oled.show() finally: c.disconnect()
wifi_ssid = "raspiWLAN" wifi_passwd = '' broker_addr = "test.mosquitto.org" def settimeout(duration): pass def on_message(topic, msg): print("topic is: " + str(topic)) print("msg is: " + str(msg)) ### if __name__ == "__main__": ufun.connect_to_wifi(wifi_ssid, wifi_passwd) client = MQTTClient("dev_id", broker_addr, 1883) client.set_callback(on_message) if not client.connect(): print("Connected to broker: " + broker_addr) client.subscribe('lopy/lights') print('Waiting messages...') while 1: client.wait_msg()
class MQTT(): def __init__(self) -> None: from mqtt import MQTTClient self.config = readconfig("config.json") self.client = MQTTClient("umqtt_client", self.config["server"]["mqtt"], 1883, "USER", "PWD") self.topic_send = "ListenerSend" self.topic_recv = "pdibid/server" self.oled = OLED() self.oled.clear() self.display_title() def display_title(self): self.oled.text("IP:", 0, 0) #24,0 self.oled.text("CPU:", 0, 8) self.oled.text("RAM:", 0, 18) self.oled.text("DISK:", 0, 28) self.oled.text("NET:", 0, 38) self.oled.text("TIME:", 0, 48) self.oled.display() def call_back(self, topic, msg): get_data = json.loads(msg) print(get_data) display_data = { "IP": get_data["ip"], "CPU": get_data["cpu"]["lavg_5"][2:] + "% " + get_data["cpu"]["nr"], "RAM": str(get_data["memory"]["percent"]) + "% " + str(get_data["memory"]["MemTotal"]), "DISK": str(get_data["disk"]["percent"]) + "% " + str(get_data["disk"]["available"]), "NET": "i-" + str(get_data["net"]["eth0"]["receive"])[:2] + " o-" + str(get_data["net"]["eth0"]["transmit"])[:2], "TIME": get_data["time"][11:-7] } self.oled.clear_part(24, 0, 104, 8) #ip self.oled.text(display_data["IP"], 24, 0) self.oled.clear_part(32, 8, 128 - 32, 8) #cpu self.oled.text(display_data["CPU"], 32, 8) self.oled.clear_part(32, 18, 128 - 32, 10) # ram self.oled.text(display_data["RAM"], 32, 18) self.oled.clear_part(40, 28, 128 - 40, 10) #disk self.oled.text(display_data["DISK"], 40, 28) self.oled.clear_part(32, 38, 128 - 32, 10) #net self.oled.text(display_data["NET"], 32, 38) self.oled.clear_part(40, 48, 128 - 40, 10) #time self.oled.text(display_data["TIME"], 40, 48) self.oled.display() self.client.publish(self.topic_send, '{"code":"0","msg":"recviver and run"}', retain=True) def run(self): self.client.set_callback(self.call_back) self.client.connect() self.client.subscribe(self.topic_recv) self.client.publish(self.topic_send, '{"code":"0","msg":"Listener online"}', retain=True) while True: self.client.wait_msg()
# subscribe 消息 def on_subscribe(): mqttClient.set_callback(on_message_come) mqttClient.subscribe(Topic, qos=1) def sub_cb(topic, msg): print((topic, msg)) codey.wifi.start('Maker-guest', 'makeblock') codey.led.show(0, 0, 0) while True: if codey.wifi.is_connected(): on_mqtt_connect() on_subscribe() codey.led.show(0, 0, 255) while True: if True: # Blocking wait for message on_publish("/sensors/temperature/home", str(38), qos=1) mqttClient.wait_msg() else: # Non-blocking wait for message mqttClient.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) else: codey.led.show(0, 0, 0)