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 connect_and_subscribe(): global client client = MQTTClient(machine_id, broker) client.set_callback(callback) client.connect() print("Connected to {}".format(broker)) for topic in (b'config', b'control'): t = topic_name(topic) client.subscribe(t) print("Subscribed to {}".format(t))
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=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()
# Read voltage voltage = vcc.read() # still to be done using RTC buckets # need to figure out previous voltage value to eliminate rogue values # if (voltage > 1.5 * voltage_old): # print("Bereinigt! voltage was =", voltage, "set to =", end='') # voltage = voltage_old # print(voltage) # Read temperature for rom in roms: DS.convert_temp() time.sleep_ms(750) temp = str(DS.read_temp(rom)) # Send values through MQTT print("Connecting to MQTT") c.status = c.connect() c.subscribe("temp") c.subscribe("voltage") c.subscribe("stop", qos=2) print("Publishing temperature", temp, " and voltage", voltage) c.publish("temp", temp) c.publish("voltage", str(voltage)) c.check_msg() print("nach MQTT Nachrichten geguckt!") if RUN == False: sys.exit() c.disconnect() print("Disconnected from MQTT")
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()
class MqttClient: # User App of Hub SDK, subscribe and publish MQTT messages # http://www.hivemq.com/demos/websocket-client/ MQTT_HOST = "broker.mqttdashboard.com" MQTT_PORT = 1883 UNIQUE_ID = 'MC30AEA4CC1A40' DEFAULT_KEEPALIVE = const(60) KEEP_ALIVE_THRESHOLD = const(5) def __init__(self, callback=None): self.subscribeCallback = callback self.sn = self.UNIQUE_ID self.client = None self.topicSubOperation = "%s/operation" % ( self.sn) # same as: MC30AEA4CC1A40/operation self.topicPubUpdate = "%s/update" % ( self.sn) # same as: MC30AEA4CC1A40/update self.mqttLive = False log.info('MQTT init') def _clientInit(self): self.client = MQTTClient(client_id=self.sn, server=self.MQTT_HOST, port=self.MQTT_PORT, keepalive=DEFAULT_KEEPALIVE) def _clientConnect(self): log.debug('MQTT connecting...') try: self.client.connect() log.info('MQTT live!') self.mqttLive = True return True except Exception as e: log.exception(e, 'could not establish MQTT connection') return False def _subscribeTopic(self): try: self.client.set_callback(self._msgReceivedCallback ) # set a handler for incoming messages self.client.subscribe(topic=self.topicSubOperation, qos=0) log.info('subscribe [%s]', self.topicSubOperation) except Exception as e: log.exception(e, 'subscribe fail') def _resetPingTimer(self): self.pingCountdown = DEFAULT_KEEPALIVE def _ping(self): ''' do a MQTT ping before keepalive period expires ''' self.pingCountdown -= 1 if self.pingCountdown < KEEP_ALIVE_THRESHOLD: log.debug('mqtt ping...') self.client.ping() self._resetPingTimer() def _connectAttempt(self): if self._clientConnect(): self._subscribeTopic() self._resetPingTimer() return True else: return False def _msgReceivedCallback(self, topic, msg): if self.subscribeCallback is not None: self.subscribeCallback(topic, msg) def mqttIsLive(self): return self.mqttLive def publishMsg(self, msg): try: topic = self.topicPubUpdate log.info("publish: topic[%s] msg[%s]", topic, msg) self.client.publish(topic=topic, msg=msg, qos=0) except Exception as e: log.exception(e, 'publish fail') async def taskMqttWorker(self): reconnectAttemptBackoff = 1 # don't try too hard, use backoff self._connectAttempt() while True: try: self.client.check_msg( ) # if there is a message, _msgReceivedCallback will be called self._ping() reconnectAttemptBackoff = 1 await asyncio.sleep(1) except Exception as e: log.exception(e, 'MQTT check message problem') self.mqttLive = False if not self._connectAttempt(): reconnectAttemptBackoff *= 2 # don't retry too fast, this will abuse the server if reconnectAttemptBackoff > 64: reconnectAttemptBackoff = 64 log.debug('reconnect attempt backoff: %ds', reconnectAttemptBackoff) await asyncio.sleep(reconnectAttemptBackoff) def start(self): self._clientInit() asyncio.create_task(self.taskMqttWorker())
SSID_PASSWD = CREDENTIALS["SSID_PASSWORD"] def do_connect(): station = network.WLAN(network.STA_IF) station.active(True) if not station.isconnected(): print('connecting to network...') station.connect(SSID, SSID_PASSWD) while not station.isconnected(): pass print('network config:', station.ifconfig()) do_connect() webrepl.start() client = MQTTClient(CLIENT_ID, SERVER) client.connect() # Connect to MQTT broker sensor = DHT22(Pin(9, Pin.IN, Pin.PULL_UP)) # DHT-22 on GPIO 15 (input with internal pull-up resistor) measuring_freq = 100 # The number represents how many times I want to get readings in 24 hours sleeping_time = int(86400/measuring_freq * 1000) # Calculating sleeping time in millisecs try: sensor.measure() # Poll sensor t = sensor.temperature() h = sensor.humidity() if isinstance(t, float) and isinstance(h, float): # Confirm sensor results are numeric msg = (b'{:3.1f},{:3.1f}'.format(t, h)) client.publish(TOPIC, msg) # Publish sensor data to MQTT topic print('Temperature: %3.1f°C' %t) print('Humidity: %3.1f%%' %h) sleep(0.1)
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
print('TOKEN [' + tkn_id + '] CONNECTED TO: ' + str(wifi_ntw.ifconfig()[0])) print('STATUS PUBLISHED.') except Exception as e: print('FAILED TO PUBLISH STATUS.') pass def msg_bat(): lvl = bat.read() * 2 * 100 / 4700 try: time.sleep(0.4) aio_client.publish(topic=aio_sts, msg='BATTERY LEVEL: {:.2f} %'.format(lvl)) time.sleep(0.4) aio_client.publish(topic=aio_bat, msg=str(bat.read() * 2)) print('BATTERY LEVEL: {:.2f} %'.format(lvl)) print('BATTERY LEVEL PUBLISHED.') except Exeption as e: print('FAILED TO PUBLISH BATTERY LEVEL.') pass ## EXECUTION wifi_connect() aio_client.connect() sec_on() msg_sts() msg_bat()
def mqtt(): mainOctopus() print("Hello, this will help you initialize MQTT client") print("ver: " + ver + " (c)octopusLAB") print("id: " + esp_id) print("Press Ctrl+C to abort") # TODO improve this # prepare directory if 'config' not in uos.listdir(): uos.makedirs('config') run = True while run: sele = setupMenu() if sele == "x": print("Setup - exit >") time.sleep_ms(2000) print("all OK, press CTRL+D to soft reboot") run = False if sele == "si": #system_info() from utils.sys_info import sys_info sys_info() if sele == "cv": print("------- Set 0/1/str for settings ------") wc = {} wc['name'] = input("device (host)name/describe: ") wc['time'] = int(input("get time from server? [1/0]: ")) wc['mysql'] = int(input("send data to mysql db [1/0]: ")) if wc['mysql']: wc['mysqlURL'] = input("mysql Write URL: ") wc['mqtt'] = int(input("mqtt client [1/0]: ")) wc['influx'] = int(input("send data to influx db [1/0]: ")) if wc['influx']: wc['influxWriteURL'] = input("influx Write URL: ") wc['timer'] = int(input("timer: ")) print("Writing to file config/mqtt_io.json") with open('config/mqtt_io.json', 'w') as f: ujson.dump(wc, f) if sele == "ms": print("Set mqtt >") print() mq = {} mq['mqtt_broker_ip'] = input("BROKER IP: ") mq['mqtt_ssl'] = int(input("> SSL (0/1): ")) mq['mqtt_port'] = int(input("> PORT (1883/8883/?): ")) mq['mqtt_clientid_prefix'] = input("CLIENT PREFIX: ") mq_user = input("Username: "******"" else mq_user mq_pass = input("Password: "******"" else mq_pass mq['mqtt_root_topic'] = input("ROOT TOPIC: ") print("Writing to file config/mqtt.json") with open('config/mqtt.json', 'w') as f: ujson.dump(mq, f) def mqtt_sub(topic, msg): print("MQTT Topic {0}: {1}".format(topic, msg)) if sele == "mt": print("mqtt simple test:") print("wifi_config >") wifi = WiFiConnect(250) wifi.events_add_connecting(connecting_callback) wifi.events_add_connected(connected_callback) print("wifi.connect") wifi_status = wifi.connect() # url config: TODO > extern. print("mqtt_config >") mqtt_clientid_prefix = read_mqtt_config()["mqtt_clientid_prefix"] mqtt_host = read_mqtt_config()["mqtt_broker_ip"] mqtt_root_topic = read_mqtt_config()["mqtt_root_topic"] mqtt_ssl = read_mqtt_config()["mqtt_ssl"] mqtt_user = read_mqtt_config()["mqtt_user"] mqtt_pass = read_mqtt_config()["mqtt_pass"] mqtt_clientid = mqtt_clientid_prefix + esp_id c = MQTTClient(mqtt_clientid, mqtt_host, ssl=mqtt_ssl, user=mqtt_user, password=mqtt_pass) c.set_callback(mqtt_sub) print("mqtt.connect to " + mqtt_host) c.connect() """ # c.subscribe("/octopus/device/{0}/#".format(esp_id)) subStr = mqtt_root_topic+"/"+esp_id+"/#" print("subscribe (root topic + esp id):" + subStr) c.subscribe(subStr) """ mqtt_log_topic = mqtt_root_topic + "/log" print("mqtt log > " + mqtt_log_topic) print(mqtt_log_topic) # mqtt_root_topic_temp = "octopus/device" c.publish(mqtt_log_topic, esp_id) # topic, message (value) to publish
def connect_and_sub(): cliente = MQTTClient(client_id, mqtt_server, puerto) cliente.set_callback(call_back) # func call back cliente.connect() # conection cliente.subscribe(topic_sub) # subscription return cliente
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
# hum=mydht.humidity() # data=[tem,hum] data = [0.1, 1.2] print(data) return data if __name__ == '__main__': try: # mydht=dht.DHT11(machine.Pin(4)) connectWifi(SSID, PASSWORD) client = MQTTClient(CLIENT_ID, SERVER, 0, username, password, 60) #create a mqtt client print(client) client.set_callback(sub_cb) #set callback client.connect() #connect mqtt client.subscribe(subscribe_TOPIC) #client subscribes to a topic mytimer = Timer(0) mytimer.init(mode=Timer.PERIODIC, period=5000, callback=apptimerevent) while True: client.wait_msg() #wait message except Exception as ex_results: print('exception1', ex_results) finally: if (client is not None): client.disconnect() wlan.disconnect() wlan.active(False)
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)
print (w.c) state_topic = topic_base + b'/'+ w.c['name'].encode() + b'/status' command_topic = topic_base + b'/'+ w.c['name'].encode() + b'/set' print (state_topic, command_topic) mqtt = 0 while not mqtt: # connect to mqtt print('mqtt name: {} mqtt address {}'.format(w.c['name'], w.c['mqtt'])) c = MQTTClient(w.c['name'], w.c['mqtt']) c.set_callback(sub_cb) # set the callback function try: c.connect() # get connected 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
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()
########### global variables ############################## unique_ID = hexlify(network.WLAN().config('mac')) pins = { 'sensor': 0, # which pin the temp/humidity sensor is on } mq = MQTTClient(config["mqtt_client"], config["mqtt_broker"]) dht = DHT22(Pin(pins["sensor"])) ######## MQTT Client: starting, connecting, and subscribing ########## # (client_id, client_ip_address), client_id must be unique mq.connect() ######### Publishing an MQTT message ######################## # Code involving publishing must come after the client is declared while True: dht.measure() temp = str(dht.temperature()) humidity = str(dht.humidity()) print("temp: " + temp) print("humidity: " + humidity) mq.publish(topic="env_sensor/temp", msg=temp) mq.publish(topic="env_sensor/humidity", msg=humidity)
# 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()
updateString = updateString + ":" update_min = machine.rng() % 60 #Minute to check for updates each day updateString = updateString + str(update_min) updateString = updateString + ", Site: " update_siteHr = machine.rng() % 6 #Hour to pull siteFile each day updateString = updateString + str(update_siteHr) updateString = updateString + ":" update_siteMin = machine.rng() % 60 #Minute to pull siteFile each day updateString = updateString + str(update_siteMin) topic_ToSend.append(msg_Topic) msg_ToSend.append(updateString) obs_publishReady = obs_publishReady + 1 printLocalTime() read_Version() status = client.connect() while True: wdt.feed() read_teensy() wdt.feed() time.sleep(2) xbeeConn = xbee.atcmd('AI') XBee_RSSI = xbee.atcmd('DB') if XBee_RSSI != None and xbeeConn == 0: if (obs_publishReady > 0): if status == 0: status = publish_Obs() if status == -1: gc.collect() if reboot == True:
# connect ESP to Adafruit IO using MQTT # myMqttClient1 = "mb1" myMqttClient2 = "mb2" myMqttClient3 = "mb3" # replace with your own client name adafruitUsername = "******" # can be found at "My Account" at adafruit.com adafruitAioKey = "3d053bf413d54b4b99b66b2d53b50e6d" # can be found by clicking on "VIEW AIO KEYS" when viewing an Adafruit IO Feed adafruitFeed1 = adafruitUsername + "/feeds/light" # replace "test" with your feed name adafruitFeed2 = adafruitUsername + "/feeds/altitude" adafruitFeed3 = adafruitUsername + "/feeds/azimuth" adafruitIoUrl = "io.adafruit.com" #set up light sensor feed c = MQTTClient(myMqttClient1, adafruitIoUrl, 0, adafruitUsername, adafruitAioKey) c.set_callback(sub_cb) c.connect() c.subscribe(bytes(adafruitFeed1,'utf-8')) #set up altitude feed al = MQTTClient(myMqttClient2, adafruitIoUrl, 0, adafruitUsername, adafruitAioKey) al.set_callback(altitude_cb) al.connect() al.subscribe(bytes(adafruitFeed2,'utf-8')) #set up azimuth feed az = MQTTClient(myMqttClient3, adafruitIoUrl, 0, adafruitUsername, adafruitAioKey) az.set_callback(azimuth_cb) az.connect() az.subscribe(bytes(adafruitFeed3,'utf-8')) while True:
async def mqtt_connect(): global mqtt_client mqtt_client = MQTTClient(MQTT_CLIENT_ID, MQTT_SERVER, MQTT_PORT, MQTT_USER_NAME, MQTTT_PASSWORD, 60) mqtt_client.set_callback(mqtt_callback) mqtt_client.connect()
import time from umqtt.simple import MQTTClient c = MQTTClient("ESP8266", "cubie.kcobos.es") if not c.connect(): print("Conectando") i = 0 while True: c.publish("prueba", "contando " + str(i)) time.sleep(1) i += 1 c.disconnect()
# This file is executed on every boot (including wake-boot from deepsleep) #import esp # esp.osdebug(None) #import uos, machine # uos.dupterm(None, 1) # disable REPL on UART(0) import gc import network import time from testpin import loop from time import sleep from umqtt.simple import MQTTClient from config import SSID, PASSWORD, MQTT_HOST, MQTT_USER, MQTT_PASSWORD gc.collect() sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect(SSID, PASSWORD) while not sta_if.isconnected(): time.sleep(1) print('network config:', sta_if.ifconfig()) mqtt = MQTTClient("umqtt_alarm", MQTT_HOST, port=1883, user=MQTT_USER, password=MQTT_PASSWORD) mqtt.connect() while loop(mqtt): sleep(1)
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)
c = MQTTClient(mqtt_clientid, mqtt_host, ssl=mqtt_ssl) c.set_callback(mqtt_sub) def get_adc_value(): aval = 0 for i in range(0, ADC_SAMPLES): aval += adc.read() return aval // ADC_SAMPLES try: if c.connect() == 0: subStr = mqtt_root_topic + esp_id + "/#" c.subscribe(subStr) print("mqtt log") c.publish(mqtt_root_topic, esp_id) # topic, message (value) to publish simple_blink() except Exception as e: print("Error connecting to MQTT") aoldval = 0 print("> loop:") while True:
class Keleido: def __init__(self, wifiName, wifiPasswd, topic, BrokerIP): self.meaningfulData = 0 self.BrokerIP = BrokerIP self.topic = topic (self.apIf, self.staIf) = self.connectToWifi(wifiName, wifiPasswd) # flex sensor init, writeto_mem has to be in __init__, mem alloc failure otherwise self.i2c_flex = I2C(scl=Pin(5), sda=Pin(4), freq=100000) i2cportNo = self.i2c_flex.scan() self.ADSAddr = i2cportNo[0] # write to config register 0x01 # CONTINUOUS_READ=0000 010 0 100 0 0 0 11 CONTINUOUS_READ = bytearray(0b0010010010000011) self.i2c_flex.writeto_mem(self.ADSAddr, 1, CONTINUOUS_READ) while (self.staIf.isconnected() != True): pass self.printWifiStatus() # mqtt client init self.mqttClient = MQTTClient(machine.unique_id(), self.BrokerIP) self.mqttClient.connect() self.enableWebREPL() def prepareData(self): """ convert int reading to byte JSON string format """ data = {} data["angle"] = self.convertData() dataJsonString = ujson.dumps(data) dataByte = bytes(dataJsonString, 'utf-8') return dataByte def readFlexData(self): # read 2 bytes from conversion register return self.i2c_flex.readfrom_mem(self.ADSAddr, 0, 2) def convertData(self): """ read raw data and convert into somthing meaningful """ data = self.readFlexData() intData = int.from_bytes(data, 'big') if intData >= 32768: angleOfFlex = 0 elif intData > 7200: angleOfFlex = 180 elif intData > 3000: angleOfFlex = int((intData - 2000) / 28) #7200 # elif intData > 2700 : # angleOfFlex = int (intData/22) else: angleOfFlex = 0 #print(i2cportNo) #print(data) #print(intData) #print(angleOfFlex) return angleOfFlex def connectToWifi(self, wifiName, password): 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(wifiName, password) # print wifi info print("WiFi connecting... ") return (ap_if, sta_if) def printWifiStatus(self): print("wiFi is connected? ", self.staIf.isconnected()) print("WiFi status: ", self.staIf.status(), "WiFi config: ", self.staIf.ifconfig()) def enableWebREPL(self): webrepl.start() def broadcastData(self, data=bytes("random data heyheyhey", 'utf-8')): """ publish data in bytes """ self.mqttClient.publish(self.topic, data) def broadcastString(self, inString="No input string\n"): """ publish data in string """ data = bytes(inString, 'utf-8') self.broadcastData(data)
led.value(0) # allumer # --- Programme Pincipal --- from umqtt.simple import MQTTClient try: if os.uname().nodename != 'esp32': raise Exception("ESP32 only project (3.3V Analog required)") q = MQTTClient(client_id=CLIENT_ID, server=MQTT_SERVER, user=MQTT_USER, password=MQTT_PSWD) sMac = hexlify(WLAN().config('mac')).decode() q.set_last_will(topic="disconnect/%s" % CLIENT_ID, msg=sMac) if q.connect() != 0: led_error(step=1) except Exception as e: print(e) # check MQTT_SERVER, MQTT_USER, MQTT_PSWD led_error(step=2) # chargement des bibliotheques try: from ccs811 import CCS811 from machine import Pin except Exception as e: print(e) led_error(step=3)
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()
import network from network import WLAN wlan = WLAN() nic = network.WLAN(network.STA_IF) nic.active(True) nic.connect('BRUNO', 'samsung1') SERVER = '192.168.0.42' CLIENT_ID = 'ESP32_DHT22_Sensor' TOPIC = b'temp_humidity' client = MQTTClient(CLIENT_ID, SERVER) client.connect() while not wlan.isconnected(): machine.idle() print("DESCONECTADO") print("Connected to Wifin") seg = 0 min = 0 hor = 0 while (hor < 24): #time.sleep(1) print(hor, ":", min, ":", seg) seg += 1
# import dht import network import time import machine import gc import time from umqtt.simple import MQTTClient myMqttClient = "moises_stevend" # can be anything unique adafruitIoUrl = "io.adafruit.com" adafruitUsername = "******" # can be found at "My Account" at adafruit.com adafruitAioKey = "dd652bfbb7c94422b873d59f136b11de" # can be found by clicking on "VIEW AIO KEYS" when viewing an Adafruit IO Feed c = MQTTClient(myMqttClient, adafruitIoUrl, 0, adafruitUsername, adafruitAioKey) c.connect() d = dht.DHT11(machine.Pin(4)) while True: try: d.measure() temperatura = d.temperature() print(temperatura) c.publish("moisesStevend/f/DemoFeed", str(temperatura)) # publish temperature to adafruit IO feed #c.publish("MikeTeachman/feeds/feed-micropythonFreeHeap", str(gc.mem_free())) #publish num free bytes on the Heap time.sleep(1) # number of seconds between each Publish d.measure() humedad = d.humidity()
def publish(message): frangable_publish("/bbq/" + client_id, message) s = network.WLAN(network.STA_IF) while not s.isconnected(): publish("Network not connected - sleeping") time.sleep(1) print(s.ifconfig()) connected = False while not connected: try: client.connect() except: print(".") time.sleep(1) else: connected = True publish("alive " + motd + ' ' + s.ifconfig()[0]) while True: v = adc.read() v_i = int(v) # this 6.2 isn't a constant # some calibration shows it is accurate around 165 freedom degrees # which is our target for cooking a turkey
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 send(data): c = MQTTClient(SENSOR_ID, SERVER, 1883) c.connect() c.publish(PUB_TOPIC, json.dumps(data)) c.disconnect()
class test_MessagingWithBroker(unittest.TestCase): DIR = "./" ID = '123' RETRIES = 3 BROKER = '192.168.0.103' PORT = 1883 MqttClient = None MsgEx = None Time = SystemTime.InstanceGet() RecvTopic = None RecvMsg = None RecvMsgCount = 0 UrlFields = { MessageSpecification.URL_FIELD_DEVICE_ID: ID, MessageSpecification.URL_FIELD_PRODUCT_NAME: "smartsensor" } Time.SvcRun() def setUp(self): MessageSpecification.Config(self.UrlFields) self.RecvMsgCount = 0 self.RecvTopic = None self.RecvMsg = None self.MqttClient = MQTTClient(self.ID, self.BROKER, self.PORT) self.MsgEx = MessageExchange(self.DIR, self.MqttClient, self.ID, self.RETRIES) def tearDown(self): self.MsgEx.Reset() @staticmethod def MqttMsgRecvCallback(topic, msg): test_MessagingWithBroker.RecvTopic = topic test_MessagingWithBroker.RecvMsg = msg test_MessagingWithBroker.RecvMsgCount = test_MessagingWithBroker.RecvMsgCount + 1 def test_MqttClient(self): self.MqttClient.set_callback( test_MessagingWithBroker.MqttMsgRecvCallback) connected = False while connected is False: try: print(self.MqttClient.connect()) connected = True print("[MQTT] Connected.") except OSError: utime.sleep(2) continue self.assertTrue(connected) def test_PutGetMessageRoundTrip(self): ep = Endpoint() msg_type = 3 msg_subtype = 3 msg_url = "<pn>/<id>/temp" msg = {"test": "msg"} msg_dir = MessageSpecification.MSG_DIRECTION_BOTH msg_spec = MessageSpecification(msg_type, msg_subtype, msg, msg_url, msg_dir) self.MsgEx.RegisterMessageType(msg_spec) # Initialize the Service on the first run self.MsgEx.SvcInit() ep.MessagePut(msg, msg_type, msg_subtype) # Run the Service again to publish the message. self.MsgEx.SvcRun() utime.sleep(1) # Run the Service again to receive the message. self.MsgEx.SvcRun() recv_msg = ep.MessageGet(msg_type, msg_subtype) print(recv_msg) self.assertEqual(recv_msg[Message.MSG_SECTION_DATA], msg)
global MQTT_TOPIC_ID print('topic: {}'.format(topic)) print('msg: {}'.format(msg)) if topic == MQTT_TOPIC_ID: command_process(msg.decode()) # 这里改成本机(PC)的IP地址 SERVER = '192.168.2.220' CLIENT_ID = 'PYESPCAR_A0' MQTT_TOPIC_ID = b'PYESPCAR_CTL_MSG' client = MQTTClient(CLIENT_ID, SERVER) client.set_callback(mqtt_callback) print('[INFO] Connect to the MQTT Broker') result = client.connect() print('result code : {}'.format(result)) if result == 0: print('[INFO] Sucess!! Connect to the MQTT Broker') else: print('[INFO] Fail to connect to mqtt broker') exit(-1) print('[INFO] Subscribe Topic: {}'.format(MQTT_TOPIC_ID)) client.subscribe(MQTT_TOPIC_ID) while True: try: # 查看是否有数据传入 # 有的话就执行 mqtt_callback client.check_msg()
def main(server="localhost"): c = MQTTClient("umqtt_client", server) c.connect() c.publish(b"foo_topic", b"hello") c.disconnect()
payload_t["timestamp"] = payload_h["timestamp"] = "{:0>4d}-{:0>2d}-{:0>2d}T{:0>2d}:{:0>2d}:{:0>2d}Z".format( *time.localtime() ) # average readings try: 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")