class MoistureMonitor(): def __init__(self, led=None): self.led = led self.t = machine.Timer(0) self.a = machine.ADC(0) gc.collect() loops = 0 self.m = MQTTClient(config.mqtt.id, config.mqtt.host, **config.mqtt["auth"]) while True: try: self.m.connect() except (IndexError, OSError) as err: print("Retrying connect because of a {}...".format(str(err))) if loops > 10: print("Resetting the board") machine.reset() except MemoryError: print("Got a memory error. Resetting the board in 2 seconds") time.sleep(2) machine.reset() except: raise else: break loops += 1 time.sleep(1) def start(self): self.m.publish(b'nodes', 'hi there') self.t.init(period=5000, mode=machine.Timer.PERIODIC, callback=lambda t: self.update()) def stop(self): self.t.deinit() def update(self): now = time.localtime() tstamp = "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(*now[0:6]) val = { "m": self.a.read() / 1024, "t": tstamp } print("Updating moisture, new value is {}".format(val)) self.m.publish(b"moisture", json.dumps(val).encode('utf-8'), retain=True) if self.led is not None: self.led(0) time.sleep(0.1) self.led(1)
# publish free heap statistics to Adafruit IO using MQTT # subscribe to the same feed # # format of feed name: # "ADAFRUIT_USERNAME/feeds/ADAFRUIT_IO_FEEDNAME" mqtt_feedname = bytes('{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, ADAFRUIT_IO_FEEDNAME), 'utf-8') client.set_callback(cb) client.subscribe(mqtt_feedname) 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: free_heap_in_bytes = gc.mem_free() print('Publish: freeHeap = {}'.format(free_heap_in_bytes)) client.publish(mqtt_feedname, bytes(str(free_heap_in_bytes), 'utf-8'), qos=0) 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()
from umqtt.robust import MQTTClient
class MQTTHandler: def __init__(self, name, server): self.mqtt = MQTTClient(hexlify(machine.unique_id()), server) self.name = name self.actions = {} self.publishers = {} self.connect() self.mqtt.set_callback(self.handle_mqtt_msgs) self.publish_all_after_msg = True def connect(self): print('.connect() Check if MQTT is already connected') if self.isconnected(): self.mqtt.disconnect() try: print('.connect() Not connected, so lets connect') self.mqtt.connect() except OSError: print(".connect() MQTT could not connect") return False time.sleep(3) if self.isconnected(): self.resubscribe_all() return True else: # Some delay to avoid system getting blocked in a endless loop in case of # connection problems, unstable wifi etc. time.sleep(5) return False def isconnected(self): try: self.mqtt.ping() except OSError: print(".isconnected() MQTT not connected - Ping not successfull") return False except AttributeError: print(".isconnected() MQTT not connected - Ping not available") return False return True def publish_generic(self, name, value): print(".publish_generic() Publish: {0} = {1}".format(name, value)) self.mqtt.publish(name, str(value)) def handle_mqtt_msgs(self, topic, msg): print(".handle_mqtt_msgs() Received MQTT message: {0}:{1}".format( topic, msg)) if topic in self.actions: print(".handle_mqtt_msgs() Found registered function {0}".format( self.actions[topic])) self.actions[topic](msg) if self.publish_all_after_msg: self.publish_all() def register_action(self, topicname, cbfunction): topic = self.name + b'/' + bytes(topicname, 'ascii') print(".register_action() Get topic {0} for {1}".format( topic, cbfunction)) if self.isconnected(): print('.register_action() MQTT connected, try to register') self.mqtt.subscribe(topic) self.actions[topic] = cbfunction def register_publisher(self, topicname, function): topic = self.name + b'/' + bytes(topicname, 'ascii') print(".register_publisher() Get topic {0} for {1}".format( topic, function)) self.publishers[topic] = function def publish_all(self): for topic in self.publishers: self.publish_generic(topic, self.publishers[topic]()) def resubscribe_all(self): for topic in self.actions: self.mqtt.subscribe(topic)
class SonOff(): led = Pin(13, Pin.OUT, value=1) relay = Pin(12, Pin.OUT, value = 0) button = Pin(0, Pin.IN, Pin.PULL_UP) device_status = "OFF" def __init__(self): if config.POWER_ON_STATE: self.relay_control(1) self.led_control(0) self.device_status = "ON" self.mqtt_client = MQTTClient(client_id=config.DEVICE_NAME, server=config.MQTT_SERVER, port=config.MQTT_PORT, user=config.MQTT_USER, passwd=config.MQTT_PASSWD, keepalive=60) self.mqtt_client.set_callback(self.sub_callback) self.mqtt_client.set_last_will(config.AVAILABILITY_TOPIC, "offline") self.ping_mqtt = 0 self.ping_fail = 0 self.button_interrupt = 0 def relay_control(self, value): self.relay.value(value) return self.relay.value() def led_control(self, value): self.led.value(value) return self.led.value() def mqtt_connect(self): try: self.mqtt_client.connect() for topic in [config.SET_TOPIC, config.POS_SET_TOPIC, config.MQTT_CHECK]: self.mqtt_client.subscribe(topic) self.publish_device_status() self.publish_pos_status("ON" if config.POWER_ON_STATE else "OFF") self.mqtt_client.publish(config.AVAILABILITY_TOPIC, "online") except: self.ping_fail += 1 def sub_callback(self, topic, msg): topic = topic.decode('utf-8') msg = msg.decode('utf-8') if topic == config.SET_TOPIC: if msg == "ON": self.relay_control(1) self.led_control(0) self.device_status = "ON" else: self.relay_control(0) self.led_control(1) self.device_status = "OFF" self.publish_device_status() elif topic == config.POS_SET_TOPIC: if msg == "ON": self.change_config({"POWER_ON_STATE": 1}) else: self.change_config({"POWER_ON_STATE": 0}) self.publish_pos_status(msg) elif topic == config.MQTT_CHECK: if int(msg) == self.ping_mqtt: self.ping_fail = 0 def publish_device_status(self): if self.ping_fail == 0: self.mqtt_client.publish(config.STATE_TOPIC, self.device_status) def publish_pos_status(self, value): if self.ping_fail == 0: self.mqtt_client.publish(config.POS_STATE_TOPIC, value) def button_action(self, pin): self.button_interrupt = 1 def change_config(self, config_data): with open('config.py', 'r') as rf: config_list = rf.readlines() for config_name, config_value in config_data.items(): if config_name in config_map: if isinstance(config_value, int): config_list[config_map[config_name]] = "{} = {}\n".format(config_name, config_value) elif config_value.isdigit(): config_list[config_map[config_name]] = "{} = {}\n".format(config_name, int(config_value)) else: config_list[config_map[config_name]] = '{} = "{}"\n'.format(config_name, config_value) with open('config.py', 'w') as wf: for conf in config_list: wf.write(conf) async def check_message(self): while True: await asyncio.sleep(0.2) try: self.mqtt_client.check_msg() except: self.mqtt_connect() async def check_mqtt(self): while True: await asyncio.sleep(10) self.ping_mqtt = time.time() self.mqtt_client.publish(config.MQTT_CHECK, str(self.ping_mqtt)) self.ping_fail += 1 if self.ping_fail > 10: pass if self.ping_fail > 3: self.mqtt_client.disconnect() self.mqtt_connect() async def check_button(self): while True: await asyncio.sleep(0.4) if self.button_interrupt > 0: self.button_interrupt = 0 if self.device_status == "ON": self.relay_control(0) self.led_control(1) self.device_status = "OFF" else: self.relay_control(1) self.led_control(0) self.device_status = "ON" self.publish_device_status() def run(self): self.button.irq(trigger=Pin.IRQ_FALLING, handler=self.button_action) self.mqtt_connect() loop = asyncio.get_event_loop() loop.create_task(self.check_message()) loop.create_task(self.check_mqtt()) loop.create_task(self.check_button()) try: loop.run_forever() except: pass
server=ADAFRUIT_IO_URL, user=ADAFRUIT_USERNAME, password=ADAFRUIT_IO_KEY, ssl=False) try: client.connect() except Exception as e: print('could not connect to MQTT server {}{}'.format(type(e).__name__, e)) sys.exit() mqtt_feedname = bytes( '{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, ADAFRUIT_IO_FEEDNAME), 'utf-8') client.set_callback(cb) client.subscribe(mqtt_feedname) # following two lines is an Adafruit-specific implementation of the Publish "retain" feature # which allows a Subscription to immediately receive the last Published value for a feed, # even if that value was Published two hours ago. # Described in the Adafruit IO blog, April 22, 2018: https://io.adafruit.com/blog/ mqtt_feedname_get = bytes('{:s}/get'.format(mqtt_feedname), 'utf-8') client.publish(mqtt_feedname_get, '\0') # wait until data has been Published to the Adafruit IO feed while True: try: client.wait_msg() except KeyboardInterrupt: print('Ctrl-C pressed...exiting') client.disconnect() sys.exit()
def broker_connect(t_pub, tc_water): # create a random MQTT clientID random_num = int.from_bytes(os.urandom(3), 'little') mqtt_client_id = bytes('client_' + str(random_num), 'utf-8') # connect to Adafruit IO MQTT broker using unsecure TCP (port 1883) # # To use a secure connection (encrypted) with TLS: # set MQTTClient initializer parameter to "ssl=True" # Caveat: a secure connection uses about 9k bytes of the heap # (about 1/4 of the micropython heap on the ESP8266 platform) ADAFRUIT_IO_URL = b'io.adafruit.com' ADAFRUIT_USERNAME = b'stormin' ADAFRUIT_IO_KEY = b'4a8287af16f346d6be64bb6be020d3e3' ADAIO_PubFD_1 = b'GC_FreeMemory' ADAIO_PubFD_2 = b'Water Temp Deg C' ADAIO_PubFD_3 = b'Outdoor Temp Deg C' ADAIO_PubFD_4 = b'Outdoor Relative Humidity' ADAIO_SubFD_1 = b'blue-led-control' client = MQTTClient(client_id=mqtt_client_id, server=ADAFRUIT_IO_URL, user=ADAFRUIT_USERNAME, password=ADAFRUIT_IO_KEY, ssl=False) try: client.connect() except Exception as e: print('Could not connect to MQTT server {}{}'.format( type(e).__name__, e)) print('Going to Deep Sleep mode') prph.deepsleep(60) sys.exit() # publish free heap statistics to Adafruit IO using MQTT # subscribe to the same feed # # format of feed name: # "ADAFRUIT_USERNAME/feeds/ADAFRUIT_IO_FEEDNAME" mqtt_PubFD1 = bytes( '{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, ADAIO_PubFD_1), 'utf-8') mqtt_PubFD2 = bytes( '{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, ADAIO_PubFD_2), 'utf-8') mqtt_PubFD3 = bytes( '{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, ADAIO_PubFD_3), 'utf-8') mqtt_PubFD4 = bytes( '{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, ADAIO_PubFD_4), 'utf-8') mqtt_SubFD1 = bytes( '{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, ADAIO_SubFD_1), 'utf-8') client.set_callback(cb) client.subscribe(mqtt_SubFD1) PUBLISH_PERIOD_IN_SEC = t_pub SUBSCRIBE_CHECK_PERIOD_IN_SEC = 0.5 accum_time = 0 while True: try: # Publish if accum_time >= PUBLISH_PERIOD_IN_SEC: # Publish free heap memory from GC (Garbage Collection) free_heap_in_bytes = gc.mem_free() / 1000 print('Publish: GC FreeMem = {} k'.format(free_heap_in_bytes)) client.publish(mqtt_PubFD1, bytes(str(free_heap_in_bytes), 'utf-8'), qos=0) # Publish water temperature in C or F # tc, tf = prph.tmp36() print('Publish: Water Temp = {} c'.format(tc_water)) client.publish(mqtt_PubFD2, bytes(str(tc_water), 'utf-8'), qos=0) # Publish outdoor temperature in C t2320, h2320 = prph.am2320(4) print('Publish: Outdoor Temp = {} c'.format(t2320)) client.publish(mqtt_PubFD3, bytes(str(t2320), 'utf-8'), qos=0) # Publish outdoor humidity in % print('Publish: Outdoor Humidity = {} %'.format(h2320)) client.publish(mqtt_PubFD4, bytes(str(h2320), 'utf-8'), qos=0) 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 # print('Accumulated Time = {}'.format(accum_time)) except KeyboardInterrupt: print('Ctrl-C pressed...exiting') client.disconnect() sys.exit()
msg = rakp2p.recv() utime.sleep_ms(80) # message not OK if msg == "NOK": continue # delete message prefix (msg=) msg = msg[4:] if DEBUG: print(msg) # convert json string to object js = ujson.loads(msg) # example message : # {"id":"000","DHT11_humidity":"46.8","DHT11_temperature":"23.0","bat":"5.661562","datasetId":"254"} # one of the 6 nodes contains new data if js["datasetId"] != prev[js["id"]]: mqtt_cl.publish(js["id"] + "/temp", js["DHT11_temperature"]) utime.sleep_ms(50) mqtt_cl.publish(js["id"] + "/hum", js["DHT11_humidity"]) utime.sleep_ms(50) # save datasetId in dictionary prev[js["id"]] = js["datasetId"] if DEBUG: print(prev) except Exception as E: print("Problem with message - %s" % E) if DEBUG: print(msg) finally: rakp2p.stop()
from umqtt.robust import MQTTClient import time import network from sht30 import SHT30 client_id = "wemos" server = "pi.lan" port = 1883 user = "******" password = "******" topic = "{}/{}".format(client_id, "sensor") sensor = SHT30() # Connect to ADC pin (A0) adc = ADC(0) # Wait for network up before proceeding wlan = network.WLAN(network.STA_IF) while not wlan.isconnected(): time.sleep_ms(10) client = MQTTClient(client_id, server, port=port, user=user, password=password) client.connect(clean_session=False) temp, humidity = sensor.measure() client.publish("{}/{}".format(topic, "temperature"), str(temp), qos=1) client.publish("{}/{}".format(topic, "humidity"), str(humidity), qos=1) client.publish("{}/{}".format(topic, "moisture"), str(adc.read()), qos=0) # Uncomment this if wrapped by timeout.py #deepsleep()
np.fill((0, 0, 0)) np[i] = (led_colour) np.write() # Bei der vorletzten LED lassen wir die Temperatur 'vorbereiten' if i == 23: # Konvertiere die Temperatur! ds.convert_temp() else: # ansonsten warte 50 Milisekunden, wegen der Animation time.sleep_ms(20) # hier schauen wir nach, ob es eine neue LED Farbe für uns gibt c.check_msg() # für alle Temperatursensoren, sende Daten zum MQTT Broker print("Count:", j, end=' ') j = j + 1 for rom in roms: TEMP = str(ds.read_temp(rom)) print("Temperature: ", TEMP, "°C ") c.publish(ARBEITSPLATZ + "/temperatur", TEMP) #Snippet10#### # Programmende ############## c.disconnect() print("Disconnected!") sys.exit() ################################### # END # ###################################
# Main Function do_connect() ca = CryptAes() client = MQTTClient(client_id=client_id, server=mqtt_server, port=port, user=username, password=password) client.set_callback(sub_cb) client.connect() client.subscribe(b'Sensor_Data') print("Connected to MQTT Broker") #hard_timer1.init(period=1000, mode=machine.Timer.PERIODIC, callback=hard_handleInterrupt1) client.publish(b'SessionID', ca.sessionID) print("published message") ticks_1 = utime.ticks_ms() while True: new_message = client.check_msg() time.sleep_us(1000) if mail_flag == 1: mail_flag = 0 result = ca.verify_hmac(json_message) ticks_2 = utime.ticks_ms() print(utime.ticks_diff(ticks_2, ticks_1)) if result: client.publish(b'Acknowledge', b'Successful Decryption') print("Authentication Passed. Decrypting")
def Emit(self): emi = MQTTClient('emiter', "192.168.110.51") emi.connect() emi.publish("test/msg", "from nodeMCU !") emi.disconnect()
from umqtt.robust import MQTTClient import time import network #conexion a la red wifi sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect("SSID", "PASS") time.sleep(2) ubidotsToken = "TOKEN" clientID = "CLIENTID" topic = b"/v1.6/devices/{devicelabel}" #el topic define a que device en especifico es que se va a subir datos #b"/v1.6/devices/{NOMBRE_DISPOSITIVO}" en el que NOMBRE_DISPOSITIVO es quien #define entre los devices creados al cual se quiere subir el dato client = MQTTClient(clientID, "industrial.api.ubidots.com", 1883, user=ubidotsToken, password=ubidotsToken) #creacion de objeto client.connect() #conexion a ubidots while True: time.sleep(2) msg = '20|30|200' R, G, B = msg.split('|') msg = b'{"R":%s, "G":%s, "B":%s}' % (int(R), int(G), int(B)) print(msg) client.publish(topic, msg)
def send_state(): client = MQTTClient('state', SERVER) client.connect() client.set_callback(on_message) client.publish(state, '2')
class MQTT: def __init__(self, ssid, pswd): self.WIFI_SSID = ssid self.WIFI_PSWD = pswd self.subLoopRunning = False # create a random MQTT clientID random_num = int.from_bytes(os.urandom(3), 'little') self.mqtt_client_id = bytes('client_' + str(random_num), 'utf-8') #email = [email protected] password db4password self.ADAFRUIT_IO_URL = b'io.adafruit.com' self.ADAFRUIT_USERNAME = b'db4g5' self.ADAFRUIT_IO_KEY = Key() self.connect() def __del__(self): self.subLoopRunning = False def connect(self): # turn off the WiFi Access Point ap_if = network.WLAN(network.AP_IF) ap_if.active(False) # connect the device to the WiFi network wifi = network.WLAN(network.STA_IF) wifi.active(True) wifi.connect(self.WIFI_SSID, self.WIFI_PSWD) attempt_count = 0 while not wifi.isconnected() and attempt_count < 20: attempt_count += 1 time.sleep(1) if attempt_count == 20: print('could not connect to the WiFi network') sys.exit() self.client = MQTTClient(client_id=self.mqtt_client_id, server=self.ADAFRUIT_IO_URL, user=self.ADAFRUIT_USERNAME, password=self.ADAFRUIT_IO_KEY, ssl=False) try: self.client.connect() except Exception as e: print('could not connect to MQTT server {}{}'.format( type(e).__name__, e)) sys.exit() # used to publish new data to a certain topic def publish(self, topic, value): mqtt_feedname = bytes( '{:s}/feeds/{:s}'.format(self.ADAFRUIT_USERNAME, topic), 'utf-8') try: self.client.publish(mqtt_feedname, bytes(str(value), 'utf-8'), qos=0) except Exception: self.connect() # used to poll client subscriptions def __sub_loop(self): while self.subLoopRunning: try: self.client.check_msg() time.sleep(2) except Exception: self.connect() # run only once with custom function func(topic, msg) def setCallback(self, cb): self.client.set_callback(cb) # add a subscription def subscribe(self, topic): mqtt_feedname = bytes( '{:s}/feeds/{:s}'.format(self.ADAFRUIT_USERNAME, topic), 'utf-8') self.client.subscribe(mqtt_feedname) if self.subLoopRunning == False: self.subLoopRunning = True _thread.start_new_thread(self.__sub_loop, ())
leds[0].value(1) leds[1].value(0) leds[2].value(0) if t > TEMP_ALARM: m = 'Temp alarm' leds[0].value(0) leds[1].value(0) leds[2].value(1) elif t > TEMP_WARNING: m = 'Temp warning' leds[0].value(0) leds[1].value(1) leds[2].value(0) # waarden tonen in console print("Temperature {0:2}C - Humidity {1:2}% - {2} ".format(t,h,m)) # waarden publishen naar mqtt server mqtt_cl.publish(TOPIC_TEMP, str(t)) mqtt_cl.publish(TOPIC_HUM, str(h)) mqtt_cl.publish(TOPIC_TEMP_MESSAGE, m) # 5 seconden wachten time.sleep(5) except Exception as e: print('Problemen met MQTT - %s'%e) finally: if mqtt_cl != None: mqtt_cl.disconnect() myWifi.close()
temperature, pressure, humidity = bme.values temperature = temperature.replace("C", "") pressure = pressure.replace("hPa", "") humidity = humidity.replace("%", "") print("Temperature, pressure, humidity:", temperature, pressure, humidity) except Exception as e: print("BME280 reading failed with: {}".format(e)) try: illuminance = str(round(max44009.illuminance_lux, 2)) print("Illuminance:", illuminance) except Exception as e: print("MAX44009 reading failed with: {}".format(e)) try: mqtt_client.publish(config.TOPIC_TEMPERATURE, temperature) mqtt_client.publish(config.TOPIC_PRESSURE, pressure) mqtt_client.publish(config.TOPIC_HUMIDITY, humidity) mqtt_client.publish(config.TOPIC_ILLUMINANCE, illuminance) except Exception as e: print("Transferring data failed with: {}".format(e)) mqtt_client.disconnect() # Temperature displayed in orange. Set here before erasing the measurements area screen.set_color(ili934.color565(255, 165, 0), ili934.color565(255, 255, 255)) # Fill a rectangle only on the measurements area. This is equivalent to # screen.erase(), but we only erase the measurements area of the screen. screen.fill_rectangle(90, 0, config.SCREEN_H - 90, config.SCREEN_W)
#client.subscribe(mqtt_feedname_02) client.subscribe(mqtt_feedname_03) PUBLISH_PERIOD_IN_SEC = 3 SUBSCRIBE_CHECK_PERIOD_IN_SEC = 0.5 accum_time = 0 while True: try: # Publish if accum_time >= PUBLISH_PERIOD_IN_SEC: free_heap_in_bytes = gc.mem_free() print('Publish: rawPot = {}'.format(adc.read())) client.publish(mqtt_feedname_02, bytes(str(adc.read()), 'utf-8'), qos=0) #client.publish(mqtt_feedname_03, f(y)) # bytes(str(free_heap_in_bytes), 'utf-8'), # qos=0) 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')
from umqtt.robust import MQTTClient import time t = 30 h = 40 myMqttClient = bytes("client_" + str(10), 'utf-8') THINGSPEAK_URL = b"mqtt.thingspeak.com" THINGSPEAK_USER_ID = b'user id ' THINGSPEAK_MQTT_API_KEY = b'mqtt apk' client = MQTTClient(client_id=myMqttClient, server=THINGSPEAK_URL, user=THINGSPEAK_USER_ID, password=THINGSPEAK_MQTT_API_KEY, ssl=False) client.connect() THINGSPEAK_CHANNEL_ID = 'channel id' THINGSPEAK_CHANNEL_WRITE_API_KEY = 'write api key' while True: topic = bytes(("channels/" + THINGSPEAK_CHANNEL_ID + "/publish/" + THINGSPEAK_CHANNEL_WRITE_API_KEY), 'utf-8') payload = bytes("field1=" + str(t) + "&field2=" + str(h), 'utf-8') client.publish(topic, payload) print(topic, payload) time.sleep(10)
class domoticz_mqtt_protocol: processcnt = 1 def __init__(self): self._log = core._log self._log.debug("Protocol: domoticz mqtt contruction") self._lock = Event() # release lock, ready for next loop self._lock.clear() def init(self, protocol): self._log.debug("Protocol " + name + ": Init") self._client_id = protocol['client_id'] self._server = protocol['hostname'] self._port = protocol['port'] self._user = protocol['user'] self._password = protocol['password'] self._queue_out = protocol['publish'] self._queue_in = protocol['subscribe'] self._mq = MQTTClient(self._client_id, self._server, self._port, self._user, self._password) # Print diagnostic messages when retries/reconnects happens #self._mq.DEBUG = True self._queue = queues.Queue(maxsize=100) return self._queue def connect(self): self._log.debug("Protocol " + name + ": connect") return self._mq.reconnect() def disconnect(self): self._log.debug("Protocol " + name + ": disconnect") self._mq.disconnect() def check(self): self._log.debug("Protocol " + name + ": check") self._mq.check_msg() def status(self): self._log.debug("Protocol " + name + ": status") self._mq.ping() def recieve(self): self._log.debug("Protocol " + name + ": recieve") self._mq.subscribe(self.queue_in) def send(self, devicedata): self._log.debug("Protocol " + name + ": send " + devicedata["stype"]) # connect or reconnect to mqtt server self.connect() mqttdata = None # case while True: mqttdata = None # case SENSOR_TYPE_SINGLE if devicedata["stype"] == core.SENSOR_TYPE_SINGLE: self._log.debug("Protocol " + name + ": SENSOR_TYPE_SINGLE") # Get plugin values try: devicedata['valueV1'] = self._queue.get_nowait() devicedata['valueN1'] = self._queue.get_nowait() except Exception as e: self._log.debug("Protocol " + name + " SENSOR_TYPE_SINGLE exception: " + repr(e)) break # Assemble mqtt message mqttdata = {} mqttdata["idx"] = devicedata["serverid"] mqttdata["nvalue"] = 0 mqttdata["svalue"] = str(devicedata["valueV1"]) message = ujson.dumps(mqttdata) break # case SENSOR_TYPE_LONG if devicedata["stype"] == core.SENSOR_TYPE_LONG: self._log.debug("Protocol " + name + ": SENSOR_TYPE_LONG") break # case SENSOR_TYPE_DUAL if devicedata["stype"] == core.SENSOR_TYPE_DUAL: self._log.debug("Protocol " + name + ": SENSOR_TYPE_DUAL") break # case SENSOR_TYPE_TEMP_HUM if devicedata["stype"] == core.SENSOR_TYPE_TEMP_HUM: self._log.debug("Protocol " + name + ": SENSOR_TYPE_TEMP_HUM") # Get plugin values try: devicedata['valueV1'] = self._queue.get_nowait() devicedata['valueN1'] = self._queue.get_nowait() devicedata['valueV2'] = self._queue.get_nowait() devicedata['valueN2'] = self._queue.get_nowait() except Exception as e: self._log.debug("Protocol " + self._name + " SENSOR_TYPE_TEMP_HUM Exception: " + repr(e)) break # Assemble mqtt message mqttdata = {} mqttdata["idx"] = devicedata["serverid"] mqttdata["nvalue"] = 0 mqttdata["svalue"] = str(devicedata["valueV1"]) + ";" + str( devicedata["valueV2"]) + ";0" message = ujson.dumps(mqttdata) break # case SENSOR_TYPE_TEMP_BARO if devicedata["stype"] == core.SENSOR_TYPE_TEMP_BARO: self._log.debug("Protocol " + name + ": SENSOR_TYPE_TEMP_BARO") break # case SENSOR_TYPE_TEMP_HUM_BARO if devicedata["stype"] == core.SENSOR_TYPE_TEMP_HUM_BARO: self._log.debug("Protocol " + name + ": SENSOR_TYPE_TEMP_HUM_BARO") # Get plugin values try: devicedata['valueV1'] = self._queue.get_nowait() devicedata['valueN1'] = self._queue.get_nowait() devicedata['valueV2'] = self._queue.get_nowait() devicedata['valueN2'] = self._queue.get_nowait() devicedata['valueV3'] = self._queue.get_nowait() devicedata['valueN3'] = self._queue.get_nowait() except Exception as e: self._log.debug("Protocol " + self._name + " SENSOR_TYPE_TEMP_HUM_BARO Exception: " + repr(e)) break # Assemble mqtt message mqttdata = {} mqttdata["idx"] = devicedata["serverid"] mqttdata["nvalue"] = 0 mqttdata["svalue"] = str(devicedata["valueV1"]) + ";" + str( devicedata["valueV2"]) + ";0;" + str( devicedata["valueV3"]) + ";0" message = ujson.dumps(mqttdata) break # case SENSOR_TYPE_SWITCH if devicedata["stype"] == core.SENSOR_TYPE_SWITCH: self._log.debug("Protocol " + name + ": SENSOR_TYPE_SWITCH") # Get plugin values try: devicedata['valueV1'] = self._queue.get_nowait() devicedata['valueN1'] = self._queue.get_nowait() except Exception as e: self._log.debug("Protocol " + self._name + " SENSOR_TYPE_SWITCH Exception: " + repr(e)) break # Switches can have many values, domoticz only two: on or off switch_on = ['closed', 'press', 'double', 'long'] switch_off = ['open', 'release'] if devicedata["valueV1"] in switch_on: devicedata["valueV1"] = 'On' elif devicedata["valueV1"] in switch_off: devicedata["valueV1"] = 'Off' else: break # Assemble mqtt message mqttdata = {} mqttdata["command"] = "switchlight" mqttdata["idx"] = devicedata["serverid"] mqttdata["switchcmd"] = devicedata["valueV1"] message = ujson.dumps(mqttdata) break # case SENSOR_TYPE_DIMMER if devicedata["stype"] == core.SENSOR_TYPE_DIMMER: self._log.debug("Protocol " + name + ": SENSOR_TYPE_DIMMER") break # case SENSOR_TYPE_WIND if devicedata["stype"] == core.SENSOR_TYPE_WIND: self._log.debug("Protocol " + name + ": SENSOR_TYPE_WIND") break # else UNKNOWN self._log.debug("Protocol " + name + ": Unknown sensor type!") break if mqttdata != None: self._log.debug("Protocol " + name + ": Message: " + message) self._mq.publish(self._queue_out, message) def process(self): # processing todo for protocol self._log.debug("Protocol " + name + " Processing...") devicedata = {} try: while True: message = self._queue.get_nowait() if message == core.QUEUE_MESSAGE_START: break devicedata['stype'] = self._queue.get_nowait() devicedata['serverid'] = self._queue.get_nowait() devicedata['unitname'] = self._queue.get_nowait() devicedata['devicename'] = self._queue.get_nowait() self.send(devicedata) except Exception as e: self._log.debug("Protocol " + name + " process Exception: " + repr(e)) # release lock, ready for next processing self._lock.clear()
user=CHT_USERNAME, # 帳戶名稱 password=CHT_IO_KEY) # 金鑰 client.connect() # 連線至mqtt伺服器 sensor = dht.DHT11(Pin(5)) data = 0 while True: for i in range(5): try: sleep(5) sensor.measure() temp = sensor.temperature() data = data + temp print('.', end='') except OSError as e: print('Failed to read sensor.') data = data / 5 print(data) payload = [{"id": "DHT11", "value": [str(data)]}] # 傳送資料到IoT平台 client.publish( b'/iot/v1/device/25641843256/rawdata', str(payload).encode() # 傳送的資料改為bytes物件 ) print("上傳完畢") data = 0 time.sleep(5) # 暫停60秒
import network from umqtt.robust import MQTTClient import secrets wifi = network.WLAN(network.STA_IF) wifi.active(True) wifi.connect(secrets.wifi_network, secrets.wifi_password) while not wifi.isconnected(): pass # Define some identifying information for our sensor node DEVICE_ID = 'sensor1' # Connect to the MQTT broker print("Connecting to Mqtt...") mqtt_client = MQTTClient(client_id=DEVICE_ID, server=secrets.mqtt_server, user=secrets.mqtt_user, password=secrets.mqtt_password, ssl=False) mqtt_client.connect() mqtt_client.publish('sensors/hello', 'Hello MQTT!')
# Define a namespace for all messages MQTT_Topic_Status = 'JorgePe/Status' MQTT_Topic_Motor = 'JorgePe/Motor' # callback message to process any new message appearing at the subscribed # topics def getmessages(topic, msg): if topic == MQTT_Topic_Status.encode(): brick.display.text(str(msg.decode())) elif topic == MQTT_Topic_Motor.encode(): brick.display.text(str(msg.decode())) motor.run_target(180, int(msg.decode())) motor.reset_angle(0) client = MQTTClient(MQTT_ClientID, MQTT_Broker) client.connect() client.publish(MQTT_Topic_Status, MQTT_ClientID + ' Started') client.set_callback(getmessages) client.subscribe(MQTT_Topic_Status) client.subscribe(MQTT_Topic_Motor) client.publish(MQTT_Topic_Status, MQTT_ClientID + ' Listening') while True: client.check_msg() time.sleep(0.1)
class CatFeeder(object): def __init__(self): """""" self._client = None self._button = Pin(5, mode=Pin.IN, pull=Pin.PULL_UP) self._done_payload = 'Done feeding!' self._servo_buzz = Feeder( pin_servo=0, trigger=14, echo=2, ) self._servo_tuxedo = Feeder( pin_servo=4, trigger=12, echo=13, ) print('Instancing button and servos.') self._button.irq(handler=self.button_pressed, trigger=Pin.IRQ_RISING) print('Setting IRQ.') def mqtt_connect(self): """""" print("Connecting to MQTT server...") self._client = MQTTClient( CLIENT_ID, MQTT_SERVER, user=MQTT_USERNAME, password=MQTT_PASSWORD, ) self._client.set_callback(self.on_message) print("Connecting MQTT") self._client.set_last_will(STATUS_TOPIC, "Offline", retain=True) self._client.connect() self._client.subscribe(TOPIC) print("Connected to %s, subscribed to %s topic" % (MQTT_SERVER, TOPIC)) self._client.publish(STATUS_TOPIC, "Connected", retain=True) while True: self._client.wait_msg() def button_pressed(self, pin): if pin.value(): time.sleep_ms(300) print('#' * 80) self._client.publish(MANUAL_FEEDING, "") def on_message(self, topic, message): """""" print(topic, message) msg = message.strip().decode('utf-8') self._client.publish(LAST_FED_TOPIC, "Feeding...") self.feed() def feed(self): """""" time.sleep(0.2) self._servo_buzz.feed() print('fed buzz') time.sleep(1) print('pause 1 sec') self._servo_tuxedo.feed() print('fed tuxedo') self.done_feeding() def done_feeding(self): """""" time.sleep(0.2) self._client.publish(DONE_TOPIC, self._done_payload) time.sleep(0.2) self._client.publish(QTY_BUZZ_TOPIC, self._servo_buzz.remaining_quantity) time.sleep(0.2) self._client.publish(QTY_TUXEDO_TOPIC, self._servo_tuxedo.remaining_quantity) print("Done feeding!\n\n") print('/' * 80) print('Waiting for message...') while True: self._client.wait_msg() def run(self): self.mqtt_connect() def open_close_test(self, open_=48, pause=1): """""" self._servo_buzz.open_position = open_ self._servo_tuxedo.open_position = open_ self._servo_buzz.pause_open = pause self._servo_tuxedo.pause_open = pause self._servo_buzz.feed() print('fed buzz') time.sleep(1) print('pause 1 sec') self._servo_tuxedo.feed() while True: self._client.wait_msg()
temp = sensor3.temperature press = sensor3.pressure altitude = sensor3.altitude # toon waarden print("Temperature: {0:.1f} C".format(temp)) print("Pressure: {0:.0f} mbar".format(press/100)) print("Altitude: {0:.0f} m".format(altitude)) # MQTT client initialiseren mqtt_server = '192.168.1.22' # mqtt_server = '172.24.0.118' mqtt_client = MQTTClient('52dc166c-2de7-43c1-88ff-f80211c7a8f6', mqtt_server) mqtt_client.connect() while True: # bmp180 uitlezen t = sensor3.temperature # 閹虹煰 p = sensor3.pressure # Pa a = sensor3.altitude # m # waarden tonen in console print("Temperature {0:.1f} C - Pressure {1:.0f} mbar - Altitude {2:.0f} m".format(t,p/100,a)) # waarden publishen naar mqtt server mqtt_client.publish('house/sensor3/temperature', str(t)) mqtt_client.publish('house/sensor3/pressure', str(p)) mqtt_client.publish('house/sensor3/altitude', str(a)) # 5 seconden wachten time.sleep(5)
class Web: def __init__(self, wifiName, wifiPassword, ADAFRUIT_IO_URL, ADAFRUIT_USERNAME, ADAFRUIT_IO_KEY): self.wifiName = wifiName self.wifiPassword = wifiPassword self.ADAFRUIT_IO_URL = ADAFRUIT_IO_URL self.ADAFRUIT_USERNAME = ADAFRUIT_USERNAME self.ADAFRUIT_IO_KEY = ADAFRUIT_IO_KEY self.Connected = "F" # create a random MQTT clientID random_num = int.from_bytes(os.urandom(3), 'little') self.mqtt_client_id = bytes('client_' + str(random_num), 'utf-8') # connect to Adafruit IO MQTT broker using unsecure TCP (port 1883) # # To use a secure connection (encrypted) with TLS: # set MQTTClient initializer parameter to "ssl=True" # Caveat: a secure connection uses about 9k bytes of the heap # (about 1/4 of the micropython heap on the ESP8266 platform) self.client = MQTTClient(client_id=self.mqtt_client_id, server=ADAFRUIT_IO_URL, user=ADAFRUIT_USERNAME, password=ADAFRUIT_IO_KEY, ssl=False) self.values = {} def getConnected(self): return self.Connected def connectToWifi(self): # WiFi connection information WIFI_SSID = self.wifiName WIFI_PASSWORD = self.wifiPassword # turn off the WiFi Access Point ap_if = network.WLAN(network.AP_IF) ap_if.active(False) # connect the device to the WiFi network wifi = network.WLAN(network.STA_IF) wifi.active(True) wifi.connect(WIFI_SSID, WIFI_PASSWORD) # wait until the device is connected to the WiFi network MAX_ATTEMPTS = 20 attempt_count = 0 while not wifi.isconnected() and attempt_count < MAX_ATTEMPTS: attempt_count += 1 time.sleep(1) if attempt_count == MAX_ATTEMPTS: print('could not connect to the WiFi network') self.Connected = "F" wifi.active(False) return Offline.Offline("Offline_Data.txt") self.Connected = "T" return self def connectToMQTT(self): try: self.client.connect() return 0 except Exception: return -1 def cb(self, topic, msg): tp = str(topic, 'utf-8') tp = (tp.split('/'))[-1] ms = float(str(msg, 'utf-8')) self.values[tp] = ms def _subscribe(self, feedname): mqtt_feedname = bytes( '{:s}/feeds/{:s}'.format(self.ADAFRUIT_USERNAME, feedname), 'utf-8') self.client.set_callback(self.cb) self.client.subscribe(mqtt_feedname) mqtt_feedname_get = bytes( '{:s}/feeds/{:s}/get'.format(self.ADAFRUIT_USERNAME, feedname), 'utf-8') self.client.publish(mqtt_feedname_get, '\0') self.client.wait_msg() def publish(self, feedname, stringToPublish): mqtt_feedname = bytes( '{:s}/feeds/{:s}'.format(self.ADAFRUIT_USERNAME, feedname), 'utf-8') self.client.publish(mqtt_feedname, bytes(stringToPublish, 'utf-8'), qos=0) def subscribe_to_keys(self, listOfKeys): for s in listOfKeys: bs = str(s, 'utf-8') self.values[s] = -9999 self._subscribe(bs) def get_latest_value(self, key): return self.values[key] def update_values(self): self.client.check_msg()
c = MQTTClient(client_id=CLIENT_ID, server=config['mqtt']['server'], user=config['mqtt']['user'], password=config['mqtt']['password'], port=config['mqtt']['port'], ssl=config['mqtt']['ssl']) led = machine.Pin(5, machine.Pin.OUT) button = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_UP) def beep(dur=60): led.value(1) time.sleep_ms(dur) led.value(0) while True: if not button.value(): c.connect(clean_session=False) c.publish("hackeriet/labradoor", "open") c.disconnect() d = 500 while d >= 0: beep() time.sleep_ms(d) d = d - 20 beep(2000)