def main(): btn = machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_UP) led = machine.Pin(2, machine.Pin.OUT) #D4 if btn.value(): led.value(1) sta_if = network.WLAN(network.STA_IF) if not sta_if.isconnected(): sta_if.active(True) sta_if.connect('ESL_Lab1', 'wifi@esl') while not sta_if.isconnected(): pass led.value(0) dhtValue = dht.DHT22(machine.Pin(4)) dhtValue.measure() led.value(1) c = MQTTClient(CLIENT_ID, SERVER) c.connect() DHTbuff = "%.2f,%.2f" % (dhtValue.humidity(), dhtValue.temperature()) c.publish(TOPIC, DHTbuff) led.value(0) time.sleep(3) # print ("Data temp : "+str(dhtValue.temperature())+" humidity : "+str(dhtValue.humidity())) rtc = machine.RTC() rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) rtc.alarm(rtc.ALARM0, 2000) machine.deepsleep()
def activateDeepSleep(self, value, millisec): # print (millisec) if value: c = MQTTClient(CLIENT_ID, SERVER) c.connect() dhtValue = dht.DHT22(machine.Pin(4)) dhtValue.measure() c.publish(TOPIC, b""+str(dhtValue.temperature())+","+str(dhtValue.humidity())) time.sleep(3) # print ("Data temp : "+str(dhtValue.temperature())+" humidity : "+str(dhtValue.humidity())) set_deepSleep(millisec)
def main(server="localhost"): c = MQTTClient("umqtt_client", server) c.connect() n = 0 while n < 100: msg = b"hello: %d" % (n) print('published message', msg) c.publish(b"test", msg) n = n + 1 time.sleep(1) c.disconnect()
def main(server=SERVER): c = MQTTClient(CLIENT_ID, server) c.connect() print("Connected to %s, waiting for button presses" % server) while True: adc_value = adc.read() print("adc_value = %d", adc_value) adc_value = "adc_value = " + str(adc_value) c.publish(TOPIC, adc_value.encode("utf-8")) time.sleep_ms(200) c.disconnect()
def do_mqtt(): global data global client host = data["mqtt"]["host"] #port = data["mqtt"]["port"] CLIENT_ID = ubinascii.hexlify(machine.unique_id()) client = MQTTClient(CLIENT_ID, host) client.connect() client.set_callback(sub_cb) client.publish(TOPIC, "ESP8266 uPython ready") client.subscribe(TOPIC)
def run(): message = {'11:00': test1.readtemp(), '11:30': 24.7} payload = json.dumps({'name':'mdeded', 'temprecord':message}) print(payload) #CLIENT_ID = machine.unique_id() client = MQTTClient('50688','192.168.0.10') client.connect() time.sleep(0.5) client.publish('/esys/mdeded/',bytes(payload,'utf-8'))
def main(server="192.168.0.10"): ap_if = network.WLAN(network.AP_IF) ap_if.active(False) sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect('EEERover','exhibition') c = MQTTClient(machine.unique_id(), server) c.connect() c.publish(b"esys/Thom&Doug/test", bytes("hello", 'utf-8')) c.disconnect()
def main(server="192.168.0.10"): # Setup the network ap_if = network.WLAN(network.AP_IF) ap_if.active(False) sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect('EEERover','exhibition') # init the sensors gas = gas_sensor_setup(5, 4, 100000) th = th_sensor_setup(5, 4) pre = pre_sensor_setup(5, 4, 100000) # Wait for i2c setup time.sleep_ms(500) c = MQTTClient(machine.unique_id(), server) c.connect() while True: # Gather readings no2_val, co_val = gas_sensor_read(gas) t_val, h_val = th_sensor_read(th) pre_val = pre_sensor_read(pre) # Create JSON message to be sent # Dummy Long and Lat for Imperial send_msg = { 'id': "1", 'long': 0.1749, 'lat': 51.4988, 'no2': no2_val, 'co': co_val, 'temp': t_val, 'hum': h_val, 'pre': pre_val } # Print out readings for debugging print("Temp ", t_val) print("no2 ", no2_val) print("Pressure ", pre_val) print("hum ", h_val) print("co", co_val) # MQTT publish the readings c.publish(b"esys/Thom&Doug/test", bytes(json.dumps(send_msg), 'utf-8')) time.sleep_ms(5000) c.disconnect()
def main(server=SERVER): c = MQTTClient(CLIENT_ID, server) c.connect() threshold = 256 print("Connected to %s, waiting for ring" % server) while True: while True: if piezo.value() > threshold: break time.sleep_ms(20) print("Ring") c.publish(TOPIC, b"ON") time.sleep_ms(200)
def mqtt(topic, data): config = get_config('config') client = MQTTClient(client_id=config['client_id'], server=config['broker'], port=config['mqtt_port'], user=config['mqtt_user'], password=config['mqtt_pass']) client.connect() try: client.publish('vabox/' + config['client_id'] + '/' + topic, str(data)) client.disconnect() except OSError: pass
class AWSShadow: def __init__(self, client_id=imei, hostname=aws_endpoint, sslp=ssl_params): self.client = MQTTClient(client_id, hostname, ssl=True, ssl_params=sslp) self.connected = False def is_connected(self): return self.connected def connect(self): try: print("trying MQTT") self.client.connect() self.connected = True print("connected to MQTT") except OSError as e: print_exception(e) self.connected = False @staticmethod def _get_on_off(value): if value: return 'on' else: return 'off' def update(self, light, nightlight, lumens): try: print("updating shadow") telemetry = {"lumens": lumens} state = { "state": { "reported": { "light_state": self._get_on_off(light), "night_light_state": self._get_on_off(nightlight) }, "desired": None } } telemetry_path = "smartswitch/{}/lumens/".format(imei) shadow_path = "$aws/things/{}/shadow/".format(imei) print(shadow_path) self.client.publish(telemetry_path, ujson.dumps(telemetry)) print("updated {}".format(telemetry_path)) self.client.publish(shadow_path + "update", ujson.dumps(state)) print("updated {}".format(shadow_path)) return True except OSError: self.connected = False
def publish(client_id=CLIENT_ID, hostname=SERVER, topic="", keepalive=60): global msg_payload global payload_Topic global tempUpdate global temp_Inbound global precipUpdate global precip_Inbound global alertUpdate global alert_Inbound global dailyUpdate global temp_Topic global daily_Topic global precip_Topic global topic_ToSend global msg_ToSend global missed_Obs global topic_File global msg_File # Connect to the MQTT server. #xbee_debug("Publishing", "") client = MQTTClient(client_id, hostname) #xbee_debug("#X","- Connecting to '%s'... " % hostname) brokerConnected = True print(brokerConnected) brokerConnected = client.connect() print(brokerConnected) if (brokerConnected == True and (topic == daily_Topic or topic == precip_Topic)): publishBackup(topic) elif brokerConnected == False: #xbee_debug("#X","Client Connected") client.publish(topic, msg_payload) time.sleep(1) if topic == temp_Topic and tempUpdate == True: tempUpdate = False temp_Inbound = False if topic == daily_Topic and dailyUpdate == True: dailyUpdate = False temp_Inbound = False if topic == precip_Topic and precipUpdate == True: precipUpdate = False precip_Inbound = False if topic == alert_Topic and alertUpdate == True: alertUpdate = False alert_Inbound = False client.disconnect() payload_Topic = "" msg_payload = "" else: pass
def sense(): import machine, onewire, ds18x20 import network import boot import ubinascii from umqtt.simple import MQTTClient import time pin = 21 # connect to the network and set network varialbe (just in case) # boot.connect() # sta_if = network.WLAN(network.STA_IF) #pull from the temperature.py script print("setting up sensor") from temperature import TemperatureSensor t = TemperatureSensor(pin, 'DS18B20-1') num_sens = len(t.ds.scan()) print('Found ' + str(num_sens) + ' Sensors. reading....') for k in range(0, num_sens): print('Temp of sensor ' + str(k) + ': ') temp = t.read_temp( addr_num=k) # use t.read_temp(False) to return Celsius print(temp) # connect to devans laptop IP print("connecting.... ") c = MQTTClient("ESP32_dev", "192.168.121.117", port=1883, keepalive=60) c.connect() print("Done it should be connected") c.publish('sensor-setup', str(num_sens)) try: while True: for k in range(0, num_sens): print("Data To Published, Temperature is " + str(t.read_temp(addr_num=k)) + ' F' + ' From Sensor ' + str(k)) c.publish( 'sensor-data', str(t.name) + '-' + str(k) + ' Temp: ' + str(t.read_temp(addr_num=k)) + ' F') print("Done!") time.sleep(1) except KeyboardInterrupt: print('interrupted!') c.disconnect()
def notify_mail(): c = MQTTClient( 'mailbox', secrets.MQTT_HOST, secrets.MQTT_PORT, ) c.connect() c.publish( secrets.MQTT_TOPIC, '{"mail": 1}', retain=False, qos=1, ) c.disconnect()
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 publish_test(clientId="clientId", hostname=aws_endpoint, sslp=ssl_params): # "clientId" should be unique for each device connected c = MQTTClient(clientId, aws_endpoint, ssl=True, ssl_params=sslp) print("connecting...") c.connect() print("connected") # topic: "sample/xbee" # message: {message: AWS Samples are cool!} print("publishing message...") c.publish("sample/xbee", '{"message": "AWS Sample Message"}') print("published") c.disconnect() print("DONE")
class mqtt_client(): def __init__(self, topics, callback, client_id, mqtt_server_ip): self.server_ip = mqtt_server_ip self.id = client_id self.__mqtt_client = MQTTClient(self.id, self.server_ip) self.topics = topics print(self.topics) self.__callback = callback self.connected = False self.__connect() def __connect(self): try: # print('id', self.id, 'ip' , self.server_ip) myclient = MQTTClient(self.id, self.server_ip) self.__mqtt_client = MQTTClient(self.id, self.server_ip) self.__mqtt_client.set_callback(self.__callback) self.__mqtt_client.connect() for tpc in self.topics: print('subscribing to topic ', tpc) self.__mqtt_client.subscribe(tpc) print('connected to mqtt server at {}'.format(self.server_ip)) self.connected = True except OSError: print('unable to connect to mqtt server') self.connected = False def check_msg(self): try: self.__mqtt_client.check_msg() self.connected = True except OSError: self.connected = False def send_msg(self, topic, message): tpc = topic.encode('utf-8') msg = message.encode('utf-8') try: self.__mqtt_client.publish(tpc, msg, 0, True) print('published topic {}, message {}'.format(topic, message)) self.connected = True except OSError: self.connected = False 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.__connect() return self.connected
def serve(): bme = bme280.BME280(i2c=i2c) # create the onewire object ds = ds18x20.DS18X20(onewire.OneWire(Pin(2))) # the ds18b20 is on GPIO4 # mqtt client client_id = CONFIG['MQTT_CLIENT_ID_PREFIX'] + ubinascii.hexlify( machine.unique_id()).decode('utf-8') password = ubinascii.a2b_base64(CONFIG['MQTT_PASSWORD']) client = MQTTClient(client_id, CONFIG['MQTT_BROKER'], user=CONFIG['MQTT_USER'], password=password, port=CONFIG['MQTT_PORT']) client.connect() print("'%s' is connected to '%s'" % (client_id, CONFIG['MQTT_BROKER'])) while True: temp = bme.temperature hum = bme.humidity pres = bme.pressure temps = ds18b20.read_temperatures(ds) # publish the values client.publish("%s.temp_c" % client_id, temp) client.publish("%s.humidity_rh" % client_id, hum) client.publish("%s.pressure_hpa" % client_id, pres) for serial_nbr, temp in temps.items(): client.publish("%s.%s.temp_c" % (client_id, serial_nbr), '%0.5f' % temp) sleep(300)
def temperature(): while (True): try: d = dht.DHT22(machine.Pin(4)) d.measure() c = MQTTClient('client', '192.168.4.4') c.connect() c.publish('temperature', str(d.temperature()) + ' ' + str(d.humidity())) time.sleep(1800) except: time.sleep(10)
def main(server="192.168.0.10"): ap_if = network.WLAN(network.AP_IF) ap_if.active(False) sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect('EEERover', 'exhibition') send_msg = {'data_to_send': "heloo", 'also_send_this': 56} c = MQTTClient(machine.unique_id(), server) c.connect() c.publish(b"esys/Thom&Doug/test", bytes(json.dumps(send_msg), 'utf-8')) c.disconnect()
def listen(): #Create an instance of MQTTClient client = MQTTClient(CONFIG['CLIENT_ID'], CONFIG['MQTT_BROKER'], user=CONFIG['USER'], password=CONFIG['PASSWORD'], port=CONFIG['PORT']) # Attach call back handler to be called on receiving messages client.set_callback(onMessage) client.connect() client.publish(CONFIG['TOPIC'], "ESP8266 is Connected") client.publish(CONFIG['TOPIC'], "off") client.subscribe(CONFIG['TOPIC']) print("ESP8266 is Connected to %s and subscribed to %s topic" % (CONFIG['MQTT_BROKER'], CONFIG['TOPIC'])) try: while True: #msg = client.wait_msg() msg = (client.check_msg()) if button.value() == 1: print("Button pressed") display.fill(0) display.text('Pi4IoT', 30, 0) if led.value() == 1: client.publish(CONFIG['TOPIC'], b"off") display.text('LED: OFF', 30, 20) else: client.publish(CONFIG['TOPIC'], b"on") display.text('LED: ON', 30, 20) display.show() time.sleep_ms(500) finally: client.disconnect()
def main( mqtt_broker='test.mosquitto.org', mqtt_port=1883, mqtt_user=None, mqtt_password=None, client_id=CLIENT_ID): global mqtt mqtt = MQTTClient( client_id, mqtt_broker, mqtt_port, mqtt_user, mqtt_password, keepalive=60 ) mqtt.set_callback(mqtt_cb) mqtt.set_last_will( AVAILABILITY_TOPIC, b"offline", retain=True) mqtt.connect() mqtt.subscribe(COMMAND_TOPIC) #此处增加对亮度命令的订阅 mqtt.subscribe(BRIGHTNESS_COMMAND_TOPIC) mqtt.publish( CONFIG_TOPIC, CONFIG_DATA.encode(), retain=True) mqtt.publish( AVAILABILITY_TOPIC, b"online", retain=True) mqtt.publish( STATE_TOPIC, light_state.encode(), retain=True ) mqtt.publish( BRIGHTNESS_STATE_TOPIC, str(light_brightness).encode(), retain=True ) print("链接到服务器:{s},端口:{p}".format(s=mqtt_broker,p=mqtt_port)) print("接受开关命令topic:开关({c})".format(c=COMMAND_TOPIC)) print("接受亮度命令topic:开关({c})".format(c=BRIGHTNESS_COMMAND_TOPIC)) while True: mqtt.check_msg()
def main(): print('Device UP!') wdt = machine.WDT() wdt.feed() sensor = ESPSensors(pin=config['dht_pin'], sensor_type=['t', 'h'], sensor_model=config['dht_model']) sensor.set_name(config['device_name']) sensor.set_expire_after_seconds(int(config['sleep_time_sec']) + 10) sensor.register_sensor() wdt.feed() wlan = wlan_connect(config['wifi_ssid'], config['wifi_passwd'], config['net_ip'], config['net_mask'], config['net_gw'], config['net_dns']) print(wlan.ifconfig()) wdt.feed() templates = sensor.get_template() discover_topics = sensor.get_discover_topic() values = sensor.get_value() print(values) json_attributes = { 'name': config['device_name'], 'ip_address': wlan.ifconfig()[0] } mqtt_client = MQTTClient(config['device_name'], server=config['mqtt_server'], port=1883, user=bytearray(config['mqtt_user'], 'utf-8'), password=bytearray(config['mqtt_password'], 'utf-8')) mqtt_client.connect() for s_type in ['temperature', 'humidity']: lwt_topic = templates[s_type]['availability_topic'] mqtt_client.set_last_will(lwt_topic, 'offline', retain=True) wdt.feed() mqtt_client.publish(bytearray(lwt_topic), bytearray('online'), retain=True) wdt.feed() mqtt_client.publish(bytearray(discover_topics[s_type]), bytearray(dumps(templates[s_type])), retain=True, qos=0) wdt.feed() mqtt_client.publish(bytearray(templates[s_type]['state_topic']), bytearray(str(values[s_type])), retain=True, qos=0) wdt.feed() mqtt_client.publish(bytearray( templates[s_type]['json_attributes_topic']), bytearray(dumps(json_attributes)), retain=True, qos=0) wdt.feed() mqtt_client.disconnect()
class UmqttBroker(object): """UmqttBroker""" def __init__(self): config = CONFIG.load_config() try: self.client_id = config["mqtt"]["client_id"] self.broker = config["mqtt"]["broker"] self.user = config["mqtt"]["user"] self.password = config["mqtt"]["password"] self.port = config["mqtt"]["port"] except: print( "Couldn't load mqtt config param (client_id, broker url, user, password, port) in config.json" ) #Create an instance of MQTTClient self.client = MQTTClient(self.client_id, self.broker, user=self.user, password=self.password, port=self.port) @staticmethod def onMessage(topic, msg): # Generic callback. print("Topic: %s, Message: %s" % (topic, msg)) def listen(self, topic): # Attach call back handler to be called on receiving messages self.client.set_callback(self.onMessage) self.client.connect() self.client.subscribe(topic) print("ESP8266 is Connected to %s and subscribed to %s topic" % (self.broker, topic)) try: while True: self.client.wait_msg() finally: self.client.disconnect() def emit(self, data, topic): self.client.connect() self.client.publish('{}'.format(topic), bytes(str(data), 'utf-8')) print('Sensor state: {}'.format(data))
def send_data_MQTT(light_data,temp_data): #sends light and temperature data to online graphing broker sta_if = network.WLAN(network.STA_IF); sta_if.active(True) #connects to phone hotspot sta_if.connect(AP_NAME,AP_PASSWORD) while sta_if.isconnected() == False: #wait for connection to establish time.sleep_ms(10) print("Network Connected") client=MQTTClient(myClient,thingspeakURL) #set up MQTT and connect to online graphing broker client.connect() print("MQTT Connected") credentials="channels/{:s}/publish/{:s}".format(ts_channelId, ts_channelWriteAPI) payload="field1={:d}&field2={:d}\n".format(light_data,temp_data) client.publish(credentials, payload) print("published") client.disconnect() #disconnect from MQTT and phone hotspot sta_if.disconnect()
def main(): client = MQTTClient(client_id, mqtt_server, mqtt_port, mqtt_user, mqtt_password) client.connect() print("Connected to {}".format(mqtt_server)) while True: #d = dht.DHT11(machine.Pin(5)) # NodeMCU D2 d = dht.DHT22(machine.Pin(5)) # NodeMCU D2 d.measure() data = d.temperature() # eg. 23 (°C) client.publish('{}/{}'.format(topic, client_id), bytes(str(data), 'utf-8')) print('sensor temperature: {}'.format(data)) time.sleep(2)
def publish(data): client = MQTTClient(client_id=CLIENT_ID, server=config.MQTT_SERVER) client.connect() for msg_topic in data: msg = msg_topic['msg'] topic = msg_topic['topic'] print('Publishing msg: {}'.format(msg)) print('Publishing topic: {}'.format(topic)) client.publish(topic=topic.encode(), msg=msg.encode()) time.sleep(1) client.disconnect()
def send_data(server=SERVER, topic=b'foo_topic', data=b'Hello!'): """Send data via MQTT. Keyword arguments: server -- IP of the MQTT Broker. topic -- The MQTT topic. data -- The data. Test connection on the broker: mosquitto_sub -t foo_topic """ client = MQTTClient("umqtt_client", server) client.connect() client.publish(topic, data) client.disconnect()
def connect(username, broker, topic, Mqtt_CLIENT_ID, PASSWORD): client = MQTTClient(client_id=Mqtt_CLIENT_ID, server=broker, port=1883, user=username, password=PASSWORD, keepalive=10000) try: client.connect() except OSError: print('Connection failed') sys.exit() data = dict() data["TempData"] = 60 data2=json.dumps(data)#convert it to json print('connection finished') client.publish(topic,data2) print("Done") time.sleep(5)
def publish_thingsboard(token, UNIQUE_ID, data, password=''): from umqtt.simple import MQTTClient import gc import json import machine import utime client = MQTTClient(UNIQUE_ID, "iot.ier.unam.mx", port=1883, user=token, password=password) client.settimeout = settimeout client.connect() print(json.dumps(data)) client.publish('v1/devices/me/telemetry', json.dumps(data)) client.disconnect()
class Mymqtt: def callback_msg(self, topic, msg): print("{}: {}".format(topic.decode(), msg.decode())) def timer_check_msg(self, inst): if self.check_msg: self.client.check_msg() def __init__(self, topic=None, server="broker.hivemq.com", client=None, callback=None, check_msg=False): conectar_wifi() urandom.seed(ADC(0).read()) self.server = server self.id_client = str( urandom.getrandbits(18)) if client is None else client self.topic = topic self.client = MQTTClient(self.id_client, self.server) self.client.set_callback( self.callback_msg if callback is None else callback) self.client.connect() self.check_msg = check_msg self.timer = Timer(-1) self.timer.init(period=1000, mode=Timer.PERIODIC, callback=self.timer_check_msg) def msg_off(self): self.check_msg = False def msg_on(self): self.check_msg = True def send(self, msg, topic=None): topic = self.topic if topic is None else topic if topic is None: # Si no se ha dado un topic nuevo print("NO ENVIADO, no se ha proporcionado ningún topic") return False self.client.publish(topic, msg) return True def subscribe(self, *topics): for top in topics: self.client.subscribe(b'{}'.format(top))
class MyMQTT(object): def __init__(self, config): self.config = config self.connected = False self.client = MQTTClient( self.config['clientname'], self.config['server']) self.connect() def connect(self): try: print(("Connecting to MQTT host: %s" % (self.config['server']))) self.client.connect(clean_session=False) self.connected = True except OSError: self.connected = False print("Unable to connect to MQTT") def sub(self, topic, callback=sub_callback): if not self.connected: self.connect() if self.connected: self.client.set_callback(callback) self.client.subscribe(topic) else: print(("MQTT not connected, not subscribing to %s" % (topic))) def pub(self, topic, data): if not self.connected: self.connect() if self.connected: try: print(("Publishing data to MQTT: %s" % data)) self.client.publish(topic, data, retain=True, qos=1) except Exception as tmpex: self.connected = False print(("Error publishing to MQTT: %s" % tmpex)) self.close() else: print(("MQTT not connected, not publishing %s:%s" % (topic, data))) def close(self): self.client.disconnect() def check(self): self.client.check_msg()
def main(server="localhost"): c = MQTTClient("umqtt_client", server) c.connect() c.publish(b"foo_topic", b"hello") c.disconnect()
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(SUB_TOPIC) print('Connected to {}, subscribed to {} topic.'.format(HOST, SUB_TOPIC)) try: while True: while True: mqtt.check_msg() if button.value() == 0: # the button is active low break # if it's pressed break out of the internal while loop time.sleep_ms(20) print('Button Pressed') mqtt.publish(PUB_TOPIC, b'Button Pressed') time.sleep_ms(200) finally: mqtt.disconnect()
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()
# not block and instead returns the characters that it can read, even # if a newline isn't present. This means that we need to check for a newline # and be smart about processing the bytes/characters that were able # to receive if one was not present. uart_message = uart.readline() if uart_message: # Toggle the LED for every piece of serial data received # This is useful for debugging, but you might want to disable # if the data rate is high led.value(not led.value()) # Now, check the message that was received. if uart_message.endswith('\n'): # If we received a full line, # then publish it directly mqtt.publish(PUB_TOPIC, uart_message) # and empty the mqtt_message # Note: This means we are losing data from some prior serial # commands that didn't complete with a newline. For some/many # applications this is probably okay. If not, you need to be # more careful here. mqtt_message = '' # Note: This also means that if a command is received in two “chunks”, # with series of bytes is received without a newline, then the remainder # with a newline, it will treat the second as the entire command. This # could be remedied by simply checking for command format and/or length. elif uart_message != b'\n': # else if the byte was not a newline character, append it to the