def main(server="localhost"): global cnt c = MQTTClient(Client_ID, server, 6002, USER, PASSWD) c.set_callback(sub_cb) c.connect() c.subscribe(b"home_info_mqtt") while True: if False: # Blocking wait for message c.wait_msg() else: # Non-blocking wait for message c.check_msg() # Test cnt = cnt + 0.5 send_data = b'\x01\x00\x00{\"datastreams\":[{\"id\":\"Temperature\",\"datapoints\":[{\"value\":' + str( cnt) + '}]}]}' send_d = bytearray(send_data) send_d[1] = (len(send_data) - 3) >> 8 send_d[2] = (len(send_data) - 3) send_data = bytes(send_d) #print(send_data) c.publish(Data_ID, send_data) # 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 test_mqtt(): global client client = MQTTClient(client_id=CLIENT_ID, server=SERVER, port=PORT, user=USER, password=PASSWORD) client.connect() client.set_callback(sub_cb) client.subscribe(b"micropython/led")
class OneNetMQTT: global ip global port def __init__(self, dev_id, product_id, api_key, sub_cba): self.client = MQTTClient(dev_id, ip, port, product_id, api_key, 0) self.client.set_callback(sub_cba) if (self.client.connect() == 1): print("Connect Server Success!") self.connect_flag = True self.client.subscribe(b"home_info_mqtt") else: print("Connect Server Fail!") def __deinit(self): if (self.connect_flag): self.client.disconnect() self.tim.deinit() print("Disconnect Server!") else: print("Nothing Done!") # Received messages from subscriptions will be delivered to this callback def timeouta(self, t): #print(t) state = machine.disable_irq() self.client.check_msg() machine.enable_irq(state) self.tim.init(period=self.timeout, mode=Timer.ONE_SHOT, callback=self.timeouta) def start_heartbeat(self, timeout): self.timeout = timeout self.tim = Timer(-1) self.tim.init(period=timeout, mode=Timer.ONE_SHOT, callback=self.timeouta) def publish3(self, msg): topic_name = '$dp' stra = json.dumps(msg) #stra=str(msg) #print(str) newb = b'\x03\x00\x00' newba = bytearray(newb) newba[1] = (len(stra)) >> 8 newba[2] = len(stra) newb = bytes(newba) + bytes(bytearray(stra)) #print(newb) self.client.publish(topic_name, newb)
def kmain(server=SERVER): global sub_flag, i_pum, i_snd, i_data f_snd = 0 c = MQTTClient(CLIENT_ID, server) try: hello_i = ESP_init(DATA_TP) c.connect() c.publish(TOPIC, hello_i, retain=True, qos=1) sleep_ms(10) c.disconnect() sleep_ms(50) c.connect() c.set_last_will(DATA_TP, b"<Connect_lost>", retain=True, qos=1) sleep_ms(10) c.publish(DATA_TP, b"<Data_begin>", retain=True, qos=1) sleep_ms(10) gc.collect() while sub_flag != 404: foobar = Foo() f_snd = 0 while button.value() != 0 and sub_flag == 100: try: if f_snd == 0 or i_pum - i_snd > 60: str_data = uheapq.heappop(i_data) try: c.publish(DATA_TP, str_data, retain=True, qos=1) sleep_ms(10) f_snd = 0 i_snd += 1 except: f_snd += 1 gc.collect() if f_snd > 30: sub_flag = 104 else: try: c.connect() sleep_ms(200) except: try: import boot except: pass sleep_ms(200) pass pass except: i_snd = i_pum sleep_ms(10) pass if sub_flag == 104: sub_flag = 404 raise sleep_ms(50) if button.value() == 0 and sub_flag == 101: sleep_ms(2000) if button.value() == 0: sub_flag = 100 sleep_ms(2000) if button.value() == 0 and sub_flag == 100: sleep_ms(2000) if button.value() == 0: sub_flag = 101 sleep_ms(2000) except: pass finally: try: del foobar except: pass c.publish(DATA_TP, b"<Data_end>", retain=True, qos=1) sleep_ms(50) c.disconnect() raise
def make(topic): client = MQTTClient(topic, config.CONFIG['broker']) client.connect() logger.debug("Established connection to {}".format(topic)) return client
class ThingAccessor: """ this module provides functions to do: - open and close and MQTT connection - publish a MQTT GET to aws-iot to obtain a shadow. - publish a MQTT UPDATE to aws-iot to update a shadow. - need to call connect before the get or update """ def __init__(self): self._thing = None self._thing_id = None self._aws_iot_cfg = None self._aws_private_key = None self._aws_certificate = None self.msg_rcvd = None self.topic_rcvd = None self._client = None self._base_topic = None self._keepalive = 4000 def _callback(self, topic, msg): logger.debug("In callback:\n\tTopic: %s\n\t%s", topic, msg) self.topic_rcvd = topic self.msg_rcvd = msg def connect(self, thing): """ Opens a MQTT connection Returns an exception message if getting the connection fails, otherwise returns None """ self._thing = thing self._thing_id = thing.id self._aws_iot_cfg = thing.get_aws_iot_cfg() if not self._aws_iot_cfg: return "Error: unable to obtain AWS IOT access parameters" self._aws_private_key = thing.get_private_key() if not self._aws_private_key: return "Error: unable to obtain AWS private key for device" self._aws_certificate = thing.get_certificate() if not self._aws_certificate: return "Error: unable to obtain AWS certificate for device" self._aws_server = self._aws_iot_cfg['endpt_prefix'] + ".iot." + self._aws_iot_cfg['region'] + ".amazonaws.com" ssl_parms = {"key": self._aws_private_key, "cert": self._aws_certificate, "server_side": False} # logger.debug("ssl_parms: %s\n", str(ssl_parms)) self._client = MQTTClient(client_id=self._thing_id, server=self._aws_server, port=8883, keepalive=self._keepalive, ssl=True, \ ssl_params=ssl_parms) self._client.set_callback(self._callback) logger.debug("MQTT connecting to: %s", self._aws_server) try: client_status = self._client.connect() except MQTTException as e: exception_msg = "Exception on MQTT connect: {}".format(e) return exception_msg self._base_topic = "$aws/things/" + self._thing_id self.subscribe("/shadow/get/accepted") self.subscribe("/shadow/update/accepted") return None def subscribe(self, thing_topic): logger.debug("subscribe to: %s", self._base_topic + thing_topic) self._client.subscribe(self._base_topic + thing_topic) def publish(self, thing_topic, msg=""): logger.debug("publish topic: %s -- msg: '%s'", self._base_topic + thing_topic, msg) self._client.publish(self._base_topic + thing_topic, msg) def get(self): """ :return: a tuple consisting of an exception string and the JSON shadow - if an exception happens, the exception string will be valid and the shadow will be None - on no exception, the exception string will be None and the shadow will be JSON """ exception_msg = None shadow_state_json = None self.publish("/shadow/get") for i in range(18): sleep_ms(333) self._client.check_msg() # TODO: check topic is get/accepted if self.msg_rcvd != None: logger.debug("shadow state received on get: %s", self.msg_rcvd) try: shadow_state_json = ujson.loads(self.msg_rcvd) except Exception as e: exception_msg = "Shadow received was not json format: {}".format(e) break if self.msg_rcvd == None: logger.warning("Did not get response to publish of shadow/get on check_msg attempt: %d", (i + 1)) exception_msg = "Did not get response to publish of shadow/get on check_msg attempt: {}".format(i + 1) return (exception_msg, shadow_state_json) def update(self, state): """ :return: an exception string, which will be None if no error/exception occurs """ exception_msg = None if state == None: return "Call to update error: state is None" self.publish("/shadow/update", msg=state) for i in range(18): sleep_ms(333) # if i == 0: # sleep_ms(1000) self._client.check_msg() if self.topic_rcvd != None: break if self.msg_rcvd == None: logger.warning("Did not get response to publish of shadow/update on check_msg attempt: %d", (i + 1)) exception_msg = "Did not get response to publish of shadow/get on check_msg attempt: {}".format(i + 1) return exception_msg def disconnect(self): self._client.disconnect()
def connect_and_subscribe(topic, data): c = MQTTClient(client_id, mqtt_server, user=user, password=password) c.connect() c.publish(topic, data) c.disconnect()
e0.getActivePower(), e0.getPowerFactor(), e1.getLineVoltage(), e1.getLineCurrent(), e1.getActivePower(), e1.getPowerFactor() ] csv_str = ",".join(map(str, values)) c.publish(b'em/1', csv_str) ########################################################## # setup() ########################################################## init_network() blink(5) energyL0, energyL1 = init_energyReader() c = MQTTClient('mqtt_client', 'raspberrypi.home', 1883) c.connect() c.publish(b'em/1', 'm,start') # ######################################################### # loop() # ...argh...lacking way to break out !!! ########################################################## while True: publishEnergyReading(c, energyL0, energyL1) blink(1) time.sleep(20) c.disconnect()