class mqttClient(threading.Thread): def __init__(self, id, ip, topic_sub, robot): threading.Thread.__init__(self) self._client = MQTTClient(id, ip) self._client.set_callback(self.getmessages) self._client.connect() self._client.subscribe(topic_sub, qos=1) self._topic_sub = topic_sub self._id = id self._robot = robot self._delta_time = 1 self._topics = [] def sendMessage(self, topic, msg, qos=0): """ Sets the message to send :param msg : String the message to send """ if (not (topic in self._topics)): self._client.subscribe(topic, qos) self._topics.append(topic) self._client.publish(topic, msg) def getmessages(self, topic, msg): """ Gets the message from a topic :param topic: the topic to listen :param msg: the message to get """ if (topic == bytes(self._topic_sub, 'utf-8')): print("Here") txt = msg.decode('utf-8') self._robot.update_List(txt) print(txt) def run(self): """ The run function for the thread """ while True: self._client.check_msg() time.sleep(self._delta_time)
def main(server="localhost"): conn_wifi() client = MQTTClient("client_2", "18.188.220.135", user="******", password="******", port=1883) client.set_callback(sub_cb) client.connect() client.subscribe(b"hello/lights") while True: if True: # Blocking wait for message client.wait_msg() else: # Non-blocking wait for message client.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) client.disconnect()
class MQTTReader: __slots__ = ('host', 'port', 'topic', 'client') def __init__(self, name, host, port, topic): self.topic = topic self.host = host self.port = port self.client = MQTTClient(name, host, port) self.client.set_callback(sub_cb) self._connect() self.client.subscribe(topic=self.topic) def _connect(self): print("Connecting to %s:%s" % (self.host, self.port)) self.client.connect() print("Connection successful") def on_completed(self): print("mqtt_completed, disconnecting") self.client.disconnect() def on_error(self, e): print("mqtt on_error: %s, disconnecting" % e) self.client.disconnect() def disconnect(self): self.client.disconnect() def wait_msg(self): self.client.wait_msg() def check_msg(self): self.client.check_msg() def last_msg(self): return (str(MESSAGE, 'utf-8'))
# 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()
c.connect() c.publish(b"sevenseg/on", b"now") writestring("777 777") dispmsg = "oooo" def sub_cb(topic, msg): global dispmsg print(topic, msg) dispmsg = msg c.set_callback(sub_cb) c.connect() c.subscribe(topic=b"sevenseg/show") # main loop import time currmsg = dispmsg br = 1 while True: c.check_msg() if dispmsg != currmsg: currmsg = dispmsg writestring(dispmsg) c.publish(b"sevenseg/on", b"now") time.sleep(0.1) swrite(b"\x0A%c" % ((br % 8) + 7)) # pulse the brightness br += 1
return False def sub_cb(topic, msg): t = topic.decode('ASCII') m = msg.decode('ASCII') if t == IN: print("IN: %s" % m) if(m.startswith('T')): if(len(m) > 2): print(m[1] + m[2]) else: print(m[1]) if(m == 'ligar led'): pinA.value(1) if(m == 'desligar led'): pinA.value(0) while True: if wifi.isconnected(): umqtt_client = MQTTClient("P3", MQTT_SERVER) umqtt_client.DEBUG = True umqtt_client.set_callback(sub_cb) umqtt_client.connect(clean_session=False) umqtt_client.subscribe(IN) print("Connected to MQTT broker: %s" % MQTT_SERVER) break while True: umqtt_client.check_msg()
class Application: DEFAULT_EVENT_PERIOD = 300 # seconds def __init__(self, ssid, password, mqtt_host, mqtt_root_topic, pin_soil_power, pin_pump, pin_scl, pin_sda, i2c_addr_bme280, event_periods, debug): """Setup the application""" self._events = [] self.should_bail = False self.debug = debug self.event_periods = event_periods # ensure network is up do_network_connect(ssid, password) # configure mqtt client self.mqtt_root_topic = mqtt_root_topic self.mqtt_client = MQTTClient("umqtt_client", mqtt_host) self.mqtt_client.set_callback(self.mqtt_recieve) self.mqtt_client.connect() # configure output pins self.pin_soil_power = machine.Pin(pin_soil_power, machine.Pin.OUT) self.pin_pump = machine.Pin(pin_pump, machine.Pin.OUT) # set up i2c bus and sensors self.i2c = machine.I2C(scl=machine.Pin(pin_scl), sda=machine.Pin(pin_sda)) self.sensor_bme280 = bme280.BME280(i2c=self.i2c, address=i2c_addr_bme280) self.sensor_si1145 = si1145.SI1145(i2c=self.i2c) self.sensor_adc = ads1x15.ADS1015(self.i2c) # topic to trigger event loop end self.mqtt_client.subscribe(self.mqtt_make_topic("halt")) self.mqtt_client.subscribe(self.mqtt_make_topic("water_plant")) # fire off initial events. These are self submitting so each one # will submit the next job to the event queue. self.event_update_ntp(utime.time()) current_time = utime.time() self.event_temperature(current_time) self.event_light(current_time) self.event_soil_moisture(current_time) self.schedule_pump_on(current_time) def __del__(self): self.mqtt_client.disconnect() def log(self, current_time, message): """Simple logging to stout.""" if self.debug: print(utime.localtime(current_time), message) def mqtt_make_topic(self, *sub_topics): """Build mqtt topic strings.""" return bytes("/".join((self.mqtt_root_topic,) + sub_topics), "utf-8") def mqtt_recieve(self, topic, msg): """Received messages from subscriptions will be delivered to this callback.""" if topic == self.mqtt_make_topic("halt"): self.should_bail = True elif topic == self.mqtt_make_topic("water_plant"): self.event_pump_on(utime.time()) self.log(utime.time(), topic + b': ' + msg) def event_schedule_dtime(self, dtime, event): """ Add a new event to the queue to be triggered at specific date/time. Trigger date/time is specified in epoch seconds. i.e. response from ``utime.time()``. """ self._events.append((dtime, event)) def event_schedule_offset(self, offset_secs, event): """ Add a new event to the queue to be triggered ``offset_secs`` from current time. """ dtime_secs = utime.time() + offset_secs self._events.append((dtime_secs, event)) def event_period(self, value): """Look-up period in event_periods, default if not found.""" return self.event_periods.get(value, self.DEFAULT_EVENT_PERIOD) def run(self): """Main event loop. Will run loop until ``should_bail`` is True.""" self.should_bail = False while not self.should_bail: self.loop() def loop(self): """The inner-event loop.""" # Do house-keeping self.mqtt_client.check_msg() # Get current time current_time = utime.time() # loop over list of pending events triggered = [] for i in range(len(self._events)): # if current time greater than event trigger time then # trigger event if self._events[i][0] <= current_time: # call the event callback. self._events[i][1](current_time) triggered.append(i) # remove handled events for i in triggered[::-1]: del self._events[i] # sleep a bit utime.sleep(1) def event_update_ntp(self, current_time): """Sync RTC time from NTP.""" self.log(current_time, 'Event: ntptime.settime') try: ntptime.settime() except OSError: self.log(current_time, 'NTP timed out.') self.event_schedule_offset(self.event_period('ntp_sync'), self.event_update_ntp) def event_temperature(self, current_time): """Get temperature fields from BME280.""" self.log(current_time, 'Event: temperature') temp, press, humid = self.sensor_bme280.read_compensated_data() self.mqtt_client.publish(self.mqtt_make_topic('temperature'), bytes(str(temp / 100), 'utf-8')) self.mqtt_client.publish(self.mqtt_make_topic('pressure'), bytes(str(press / 256 / 100), 'utf-8')) self.mqtt_client.publish(self.mqtt_make_topic('humidity'), bytes(str(humid / 1024), 'utf-8')) self.event_schedule_offset(self.event_period('temperature'), self.event_temperature) def event_light(self, current_time): """Get light fields from SI1145.""" self.log(current_time, 'Event: light') self.mqtt_client.publish(self.mqtt_make_topic('uv'), bytes(str(self.sensor_si1145.read_uv), 'utf-8')) self.mqtt_client.publish(self.mqtt_make_topic('visible'), bytes(str(self.sensor_si1145.read_visible), 'utf-8')) self.mqtt_client.publish(self.mqtt_make_topic('ir'), bytes(str(self.sensor_si1145.read_ir), 'utf-8')) self.event_schedule_offset(self.event_period('light'), self.event_light) def event_soil_moisture(self, current_time): """Get current soil mositure value from ADC.""" # Need to power up the sensor first. This is left powered off to prolong the # life of the sensor. self.log(current_time, 'Event: soil moisture') self.pin_soil_power.on() utime.sleep_ms(2000) value = self.sensor_adc.read(1) self.pin_soil_power.off() self.mqtt_client.publish(self.mqtt_make_topic('soil_moisture'), bytes(str(value), 'utf-8')) self.event_schedule_offset(self.event_period('soil_moisture'), self.event_soil_moisture) def event_pump_on(self, current_time): """Turn on pump, schedule it off.""" self.log(current_time, 'Event: pump on') self.mqtt_client.publish(self.mqtt_make_topic('pump'), b'on') self.pin_pump.on() self.event_schedule_offset(self.event_period('pump_running'), self.event_pump_off) self.schedule_pump_on(current_time) def schedule_pump_on(self, current_time): next_trigger = next_water_time(current_time) next_str = str(utime.localtime(next_trigger)) self.log(current_time, "Scheduled next pump on at " + next_str) self.mqtt_client.publish(self.mqtt_make_topic('pump_next_on'), bytes(next_str, 'utf-8')) self.event_schedule_dtime(next_trigger, self.event_pump_on) def event_pump_off(self, current_time): """Turn off pump.""" self.log(current_time, 'Event: pump off') self.mqtt_client.publish(self.mqtt_make_topic('pump'), b'off') self.pin_pump.off()
try: if not (myWifi.get_IPdata() == "" or myWifi.get_IPdata()[0]=="0.0.0.0"): mqttCl=MQTTClient("espLoraP2P"+Topics.nodeId,BROKER) mqttCl.set_callback(mqttMsg) mqttCl.connect() mqttCl.publish(Topics.topicSettings,sSettings) mqttCl.subscribe(Topics.topicResponse) delay = 40000 #Indien verbinding met Wifi en settings zijn ingevuld, wacht 40s anders wacht 90s if sSettings == "{}": delay=90000 #maximaal 1.5 minuten wachten op respons node-red, onboard LED brand om duidelijk te maken dat er wijzigingen mogelijk zijn via node-red led_board.value(1) stopTime = utime.ticks_add(utime.ticks_ms(), delay) while utime.ticks_diff(stopTime, utime.ticks_ms()) > 0 and not Topics.response: mqttCl.check_msg() if Topics.response == False and sSettings=="{}": print("No response from node-red and no settings, exit program!") led_board.value(0) sys.exit() Topics.response = False led_board.value(0) except Exception as E: print(E) print("problems with Wifi or MQTT") finally: if mqttCl is not None: del mqttCl if myWifi is not None: myWifi.close()
delay=message['args']['delay']) elif _command == 'loop_random': cmd_loop_random(max_brightness=message['args']['max_brightness'], delay=message['args']['delay']) elif _command == 'loop_strobing': cmd_loop_strobing(palette=message['args']['palette'], delay=message['args']['delay']) elif _command == 'loop_rainbow': cmd_loop_rainbow(delay=message['args']['delay']) except ValueError: print('invalid json') _topic = "" _message = "" _command = "" mqtt_client = MQTTClient(client_id=c.MQTT_CLIENT_ID, server=c.MQTT_HOST, port=c.MQTT_PORT, user=c.MQTT_USER, password=c.MQTT_PASS) mqtt_client.set_callback(cmd_handler) if not mqtt_client.connect(clean_session=True): mqtt_client.subscribe(c.MQTT_TOPIC) while 1 and _command != 'stop': if mqtt_client.check_msg() is None: if _command in commands_on_repeat: cmd_handler(_topic, _message)
class Connectivity: def __init__(self): self.sta = network.WLAN(network.STA_IF) self.ConnectWiFi() self.mqtt() def ConnectWiFi(self): self.sta.active(True) #self.sta.connect('g.tec', '#g.tec#17!') self.sta.connect('GBLan', 'join1234') print("connecting to WiFi at GBLan") while self.sta.isconnected() == False: pass self.serverIP = self.sta.ifconfig()[3] print("Successfully connected to " + self.serverIP) def mqtt(self): print("connecting to mqtt ROBUST at {}".format(self.serverIP)) self.c = MQTTClient("umqtt_client", self.serverIP) self.c.set_callback(self.processMEssage) self.c.connect() self.c.subscribe("master/#") print("connected to mqtt broker") def Emit(self): emi = MQTTClient('emiter', self.serverIP) emi.connect() emi.publish("devices/tester", "from MCU !") emi.disconnect() def Check(self): self.c.check_msg() def deb(self, topic, msg): print((topic, msg)) def processMEssage(self, topic, msg): if topic == b'master': toprint = "from master: " if msg == b'SHOWUP': toprint = " -Replying to a showup message" self.c.publish("devices/tester", "MCU - PRESENT") else: toprint = toprint + msg.decode("utf-8") elif topic == b'master/horizontal': val = int(msg.decode('UTF-8')) self.moveHorizontal(val) toprint = "." elif topic == b'master/vertical': val = int(msg.decode('UTF-8')) self.moveVertical(val) toprint = "." else: toprint = "unexpected " print(toprint) def moveVertical(self, val): print("using Generic") def moveHorizontal(self, val): print("using generic")
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()
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
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()
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, ())
class Service(BaseService): # Setup def __init__(self): super().__init__() self.mqtt = None self._log_stream = None self._asyncio_loop = asyncio.get_event_loop() self._services = {} self._init_mqtt() self._mqtt_connect() self._init_logging() self._get_updates() self._init_services() self.start_all_services() self._asyncio_loop.create_task(self._update_ntp()) def _init_mqtt(self): MQTT_USER = env['MQTT_USER'] if 'MQTT_USER' in env.keys() else None MQTT_PASSWORD = env['MQTT_PASSWORD'] if 'MQTT_PASSWORD' in env.keys( ) else None # Create an mqtt client self.mqtt = MQTTClient(self.hardware_id, env['MQTT_HOST'], user=MQTT_USER, password=MQTT_PASSWORD) self.mqtt.set_callback(self._mqtt_callback) def _init_logging(self): LOG_LOCALLY = env['LOG_LOCALLY'] if 'LOG_LOCALLY' in env.keys( ) else True self._log_stream = MQTTStream(self.mqtt, self.hardware_id, LOG_LOCALLY) self._asyncio_loop.create_task(self._log_stream._process_log_queue()) # Set the log level based on the global environment variable 'LOG_LEVEL' log_level_string = env['LOG_LEVEL'] if 'LOG_LEVEL' in env.keys( ) else 'DEBUG' # Convert the log level `string` to the right enum LOG_LEVEL = logging.DEBUG for x in ['DEBUG', 'INFO', 'WARNING', 'ERROR']: if x == log_level_string: LOG_LEVEL = eval('logging.%s' % x) break # Make this the default log stream logging.basicConfig(level=LOG_LEVEL, stream=self._log_stream) self._asyncio_loop.create_task(self._process_mqtt_messages()) @staticmethod def _mqtt_callback(topic, message): topic_path = topic.decode('utf-8').split('/')[1:] service, channel = topic_path # Command router if channel == 'commands': message = json.loads(message) _command_queue.append((service, message)) async def _process_mqtt_messages(self): while True: try: self.mqtt.check_msg() except: pass await asyncio.sleep(0.1) while len(_command_queue): service, message = _command_queue.pop(0) args = message['args'] if 'args' in message.keys() else '' command = 'service.%s(%s)' % (message['command'], args) # Include `command`, `token`, and `args`, in the response response = { 'command': message['command'], 'token': message['token'], 'args': args } if message['command'] in self._services[service]._methods: try: response['response'] = eval( command, globals(), {'service': self._services[service]}) except Exception as e: response['exception'] = repr(e) self._logger.error( 'Remote command ("%s") caused an exception.' % command) sys.print_exception(e, self._log_stream) else: response[ 'exception'] = 'The specified command is not available.' self._logger.error( 'Remote command ("%s") caused an exception.' % command) self.mqtt.publish( '%s/%s/responses' % (self.hardware_id, service), json.dumps(response)) gc.collect() async def _update_ntp(self): def update(): global _startup_time try: self._logger.info('Get NTP time') lock = _thread.allocate_lock() with lock: _startup_time = ntptime.time() - time.time() self._logger.info('_startup_time=%s' % _startup_time) except Exception as e: self._logger.warning(e) sys.print_exception(e, self._log_stream) # Try every 10 s until we get an update while not _startup_time: update() await asyncio.sleep(10) gc.collect() # Afterwords, sync once per day while True: await asyncio.sleep(60 * 60 * 24) update() gc.collect() @requires_network def _wifi_connect(self): pass @requires_network def _mqtt_connect(self): self.mqtt.connect() self.mqtt.subscribe('%s/#' % self.hardware_id) @requires_network def _get_updates(self): reboot_flag = False # Get a list of all services for service in os.listdir('services'): if service == '__init__.py' or service.startswith('.'): continue self._logger.info('Check for updates to %s' % service) service_env = get_env(service) if 'GITHUB_URL' in service_env.keys(): self._logger.info('GITHUB_URL=%s' % service_env['GITHUB_URL']) remote_module_path = service_env[ 'PYTHON_MODULE_PATH'] if 'PYTHON_MODULE_PATH' in service_env else '' o = OTAUpdater(service_env['GITHUB_URL'], module_path='services/%s' % service, remote_module_path=remote_module_path) try: gc.collect() if o.check_for_update_to_install_during_next_reboot(): gc.collect() o.download_and_install_update_if_available() reboot_flag = True gc.collect() except Exception as e: self._logger.error("Couldn't get update info. %s" % repr(e)) sys.print_exception(e, self._log_stream) else: self._logger.error('No env defined for %s' % self.name) sys.print_exception(e, self._log_stream) if reboot_flag: self._logger.info('Updates installed. Rebooting...') machine.reset() def _init_services(self): self._logger.info('root environment = %s' % (json.dumps(self.get_env()))) # Get a list of all services for service in os.listdir('services'): if service == '__init__.py' or service.startswith('.'): continue try: if service == 'supervisor': self._services[service] = self else: # Create new service exec('import %s' % service, locals()) self._services[service] = locals()[service].Service() self._logger.info('Initialized %s %s' % (self._services[service].name, self._services[service].version)) service_env = self.get_env(service) self._logger.info('%s environment = %s' % (service, json.dumps(service_env))) except Exception as e: self._logger.error('Failed to initialize %s: %s' % (service, repr(e))) sys.print_exception(e, self._log_stream) self._logger.info('Start asyncio background thread.') # Start the asyncio loop in a background thread _thread.start_new_thread(self._asyncio_loop.run_forever, tuple()) @property def status(self): return { name: (service.state, service.version) for name, service in self._services.items() } def reset(self): machine.reset() def stop_all_services(self): for service in self._services.values(): service.stop() def start_all_services(self): for service in self._services.values(): service.start() # This function runs continuously async def loop(self): self._logger.debug('state=%s' % self.state) # Keep wifi and mqtt connections alive try: self.mqtt.ping() except: # _mqtt_connect() requires wifi, so this will also reconnect wifi # if necessary self._mqtt_connect() gc.collect() self._logger.info('gc.mem_free()=%s' % gc.mem_free()) await asyncio.sleep(60)
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['value1'] = 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["value1"]) 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['value1'] = self._queue.get_nowait() devicedata['value2'] = 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["value1"]) + ";" + str( devicedata["value2"]) + ";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['value1'] = self._queue.get_nowait() devicedata['value2'] = self._queue.get_nowait() devicedata['value3'] = 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["value1"]) + ";" + str( devicedata["value2"]) + ";0;" + str( devicedata["value3"]) + ";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['value1'] = 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["value1"] in switch_on: devicedata["value1"] = 'On' elif devicedata["value1"] in switch_off: devicedata["value1"] = 'Off' else: break # Assemble mqtt message mqttdata = {} mqttdata["command"] = "switchlight" mqttdata["idx"] = devicedata["serverid"] mqttdata["switchcmd"] = devicedata["value1"] 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() 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()
wifi.start() server_ip = "192.168.30.105" client_id = "umqtt_client" import time from umqtt.robust import MQTTClient try: c = MQTTClient(client_id, server_ip) c.DEBUG = True def sub_cb(topic, msg): print((topic, msg)) c.publish(topic, msg) c.set_callback(sub_cb) if not c.connect(clean_session=False): c.subscribe(b"foo_topic") while 1: time.sleep(1) if c.check_msg() is not None: c.wait_msg() else: print('other operator') finally: c.disconnect()
class Sonoff: def __init__(self, button_callback=None): self.led = Led() if button_callback is None: self.button = Button(callback=self.button_callback) else: self.button = Button(callback=button_callback) self.relay = Relay() self.wlan = WLAN(WLAN_SSID, WLAN_PASS) self.mqtt = None self.mqtt_topic_in = MQTT_TPIN self.mqtt_topic_out = MQTT_TPOU def reset(self, save_state=True): self.led.blink(1, 1000) if save_state: self.relay.save() machine.reset() def mqtt_publish(self, message): if self.mqtt is not None: try: print('[i] Sonoff.mqtt_publish: {0} - {1}'.format( self.mqtt_topic_out.decode('utf-8'), message)) self.mqtt.publish(self.mqtt_topic_out, str(message).encode()) except KeyboardInterrupt: raise except Exception as e: eprint('[-] Sonoff.mqtt_publish: {0}'.format(e)) self.mqtt.reconnect() def button_callback(self, pin): bstart_ms = utime.ticks_ms() while self.button.state() == 1: utime.sleep_ms(100) if utime.ticks_diff(bstart_ms, utime.ticks_ms()) > 1000: self.reset() else: self.mqtt_publish(self.relay.toggle()) def mqtt_subscribe_callback(self, topic, msg): topic = topic.decode('utf-8') msg = msg.decode('utf-8') print('[i] mqtt_subscribe_callback: {0} - {1}'.format(topic, msg)) if msg == 'reset': self.reset() elif msg == 'blink': self.led.blink() elif msg == 'state': self.mqtt_publish(self.relay.state()) else: self.mqtt_publish(self.relay.switch(msg)) def mqtt_start(self, mqtt_broker, mqtt_client_id, mqtt_port=1883): self.mqtt_topic_in = str(self.wlan.get_hostname() + MQTT_TPIN).encode() self.mqtt_topic_out = str(self.wlan.get_hostname() + MQTT_TPOU).encode() try: self.mqtt = MQTTClient(mqtt_client_id, mqtt_broker, mqtt_port) self.mqtt.set_callback(self.mqtt_subscribe_callback) self.mqtt.connect(clean_session=False) print('[+] Sonoff.mqtt_start: Connected to ({0}'.format( str(mqtt_broker))) except KeyboardInterrupt: raise except Exception as e: eprint('[-] Sonoff.mqtt_setup: {0}'.format(e)) eprint(' Failed to connect to MQTT, resetting..') self.reset() try: self.mqtt.subscribe(self.mqtt_topic_in) print('[+] Sonoff.mqtt_start: Subscribed to {0}'.format( self.mqtt_topic_in.decode('utf-8'))) except KeyboardInterrupt: raise except Exception as e: eprint('[-] Sonoff.mqtt_setup: {0}'.format(e)) eprint(' Failed to subscribe to {1}, resetting..'.format( self.mqtt_topic_in.decode('utf-8'))) self.reset() self.led.blink(3) def mqtt_stop(self): self.mqtt.disconnect() def run(self): i = 0 j = 0 while True: i += 1 try: self.mqtt.check_msg() self.relay.check() if i % 100 == 0: print('[i] Sonoff.run: {0} - {1}'.format( self.mqtt_topic_out.decode('utf-8'), self.relay.state())) self.mqtt_publish(self.relay.check()) if i % 300 == 0: if not self.wlan.isconnected(): self.wlan.connect(delay=WLAN_DLAY) self.led.blink(3) else: self.led.blink(1, 300) if i % 36000 == 0: gc.collect() utime.sleep_ms(100) except KeyboardInterrupt: raise except Exception as e: j += 1 eprint('[-] Sonoff.run: {0}'.format(e)) if j == 10: eprint('[-] Resetting...') self.reset() else: eprint('[-] Running garbage collection...') gc.collect()
class MQTTReaderAWS: __slots__ = ('host', 'port', 'topic', 'client') def __init__(self, client_id, host, port, topic, key_file, cert_file): self.client_id = client_id self.host = host self.port = port self.topic = topic self.key_file = key_file self.cert_file = cert_file self.mqtt_client = None self.connect_mqtt() self.mqtt_client.set_callback(sub_cb) self.mqtt_client.subscribe(topic=self.topic) def connect_mqtt(self): try: with open(self.key_file, "r") as f: key = f.read() print("Got Key") with open(self.cert_file, "r") as f: cert = f.read() print("Got Cert") self.mqtt_client = MQTTClient(client_id=self.client_id, server=self.host, port=self.port, keepalive=5000, ssl=True, ssl_params={ "cert": cert, "key": key, "server_side": False }) self.mqtt_client.connect() print('MQTT Connected') except Exception as e: print('Cannot connect MQTT: ' + str(e)) raise def disconnect(self): self.mqtt_client.disconnect() # Checks whether a pending message from server is available. # If not, returns immediately with None. Otherwise, does # the same processing as wait_msg. def wait_msg(self): self.mqtt_client.wait_msg() # Wait for a single incoming MQTT message and process it. # Subscribed messages are delivered to a callback previously # set by .set_callback() method. Other (internal) MQTT # messages processed internally. def check_msg(self): try: self.mqtt_client.check_msg() except: pass # Behaves like wait_msg, but worse def subscribe(self): self.mqtt_client.subscribe(self.topic, 0) def last_msg(self): return (str(MESSAGE, 'utf-8'))
class UnmanagedDevice: """ An "unmanaged device" for the Watson IoT platform. Can be used with "Quickstart"; see https://quickstart.internetofthings.ibmcloud.com """ decoders = {} encoders = {} commands = {} def __init__(self, org=QUICKSTART_ORG, device_type=None, device_id=None, username='******', token='', port=8883, clean_session=True, domain=DOMAIN, ssl_params=None, log_level='info'): """ Builds proper params for connecting to IoT platform MQTT broker. Registers JSON encoder & decoder. Creates MQTT client object, but does not connect. `quickstart` implies an *insecure* connection! `device_type` and `token` not necessary if `org` is `quickstart`. :param log_level: Logging level :type log_level: str :param org: IoT platform organization :type org: str :param device_type: IoT platform device type :type device_type: str :param device_id: IoT platform client identifier :type device_id: str :param username: IoT platform username :type username: str :param token: IoT platform API token :type token: str :param port: MQTT broker port :type port: int :param clean_session: Whether to use a clean session when connecting :type clean_session: bool :param domain: IoT platform domain name :type domain: str :param ssl_params: Additional SSL parameters for a secure connection :type ssl_params: dict """ if not device_id: raise Exception('"device_id" parameter required') self.org = org if not self.is_quickstart: if not device_type: raise Exception('"device_type" parameter required') if not token: raise Exception('"token" parameter required') self.username = username self.token = token self.device_type = device_type self.address = '%s.messaging.%s' % (org, domain) self.client_id = 'd:%s:%s:%s' % (self.org, self.device_type, device_id) self.port = port self.keep_alive = 60 self.logger = logging.getLogger( '%s.%s' % (self.__module__, self.__class__.__name__)) self.logger.level = LOG_LEVELS[log_level] self.clean_session = clean_session self.ssl_params = ssl_params or {} self.client = MQTTClient(self.client_id, self.address, user=self.username, password=self.token, keepalive=60, ssl=self.is_secure, ssl_params=self.ssl_params) if self.logger.level == logging.DEBUG: self.client.DEBUG = True self.set_decoder('json', bytes_to_json) self.set_encoder('json', json.dumps) self.set_decoder('text', bytes_to_utf8) # noinspection PyTypeChecker self.set_encoder('text', str) @property def is_connected(self): """ Crudely checks connectivity by pinging :return: Whether or not socket is alive :rtype: bool """ try: self.client.ping() return True except OSError: return False def set_encoder(self, name, func): """ "Registers" an encoder :param name: Name of encoder :type name: str :param func: Encoding function :type func: function """ self.encoders[name] = func def unset_encoder(self, name): """ "Un-registers" a encoder :param name: Name of existing encoder :type name: str """ try: del self.encoders[name] except KeyError: pass def set_decoder(self, name, func): """ "Registers" a decoder :param name: Name of decoder :type name: str :param func: Decoding function :type func: function """ self.decoders[name] = func def unset_decoder(self, name): """ "Un-registers" a decoder :param name: Name of existing decoder :type name: str """ try: del self.decoders[name] except KeyError: pass def set_command(self, command_id, handler): """ "Registers" a command handler (if org is not "quickstart") :param command_id: Command ID :type command_id: str :param handler: Command handler :type handler: function """ if self.is_quickstart: raise Exception('"quickstart" org does not support commands') self.commands[command_id] = handler def unset_command(self, command_id): """ "Unregisters" a command :param command_id: Command ID :type command_id: str """ try: del self.commands[command_id] except KeyError: pass @property def is_secure(self): """ Secure connection? `False` if `org` is `quickstart` :return: Whether or not SSL is enabled. :rtype: bool """ return self.port == 8883 and not self.is_quickstart @property def is_quickstart(self): """ Is "quickstart" org? :return: Whether or not `org` is `quickstart` :rtype: bool """ return self.org == QUICKSTART_ORG def connect(self): """ Connects to the MQTT broker. If not a "quickstart" org, then subscribes to commands. """ self.client.connect(self.clean_session) self.logger.debug('client "%s" connected to %s:%s' % (self.client_id, self.address, self.port)) if not self.is_quickstart: def message_callback(topic, message): """ Callback executed when a msg for a subscribed topic is received :param topic: Raw MQTT topic :type topic: bytes :param message: Raw MQTT message :type message: bytes """ topic = bytes_to_utf8(topic) matches = TOPIC_REGEX.match(topic) command_id = matches.group(1) message_format = matches.group(2) if message_format in self.decoders: message = self.decoders[message_format](message) else: self.logger.debug( 'no suitable decoder for message format "%s"' % message_format) self.logger.debug('topic: %s\nmessage: %s' % (topic, message)) if command_id in self.commands: self.logger.info('received command "%s"' % command_id) self.commands[command_id](message) else: self.logger.warning('command "%s" received, \ but no handler registered' % command_id) self.client.set_callback(message_callback) self.client.subscribe(DEVICE_COMMAND_TOPIC) self.logger.debug('subscribed to device command topic: %s', DEVICE_COMMAND_TOPIC) def publishEvent(self, event_id, payload, message_format='json', qos=0): """ Publishes an event :param event_id: Event ID :type event_id: str :param payload: Event payload :type payload: Any :param message_format: Message format :type message_format: str :param qos: Quality of Service :type qos: int """ if not self.is_connected: raise Exception('client is not connected') if qos == 2: raise Exception('QoS level 2 not implemented') event_id = event_id.strip() if message_format in self.encoders: payload = self.encoders[message_format](payload) self.client.publish('iot-2/evt/%s/fmt/%s' % (event_id, message_format), payload, qos) def disconnect(self): """ Disconnects (if connected) """ try: self.client.disconnect() self.logger.warning('Closed connection to the IBM Watson \ IoT Platform') except OSError: self.logger.warning('Attempted to disconnect from a \ disconnected socket') def loop(self): """ Non-blocking check-for-messages. You need to do something else after this, such as `time.sleep(1)`, or other meaningful work, if you are going to do this in a busy-loop. This appears unsupported in some environments (incl. unix) """ self.client.check_msg() def sync_loop(self): """ Blocking check-for-messages. Run this in a busy-loop. """ self.client.wait_msg()
def website(): global Thread_website # WiFi connection information WIFI_SSID = 'iPhone' WIFI_PASSWORD = '******' # the following function is the callback which is # called when subscribed data is received def cb(topic, msg): print("Topic: " + str(topic)) if topic == b'DB4_Group_1/feeds/target_temp': rf(topic, msg) else: ac(topic, msg) def rf(topic, msg): global reference_temp print('Received Data: Topic = {}, Msg = {}'.format(topic, msg)) reference_temp = float(str(msg, 'utf-8')) print('Reference temperature = {} degrees Celsius'.format( reference_temp)) def ac(topic, msg): global concentration print('Received Data: Topic = {}, Msg = {}'.format(topic, msg)) concentration = float(str(msg, 'utf-8')) print('Concentration = {} cells'.format(concentration)) # 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') # sys.exit() # 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'DB4_Group_1' ADAFRUIT_IO_KEY = b'aio_mIHs90rn1ZSaLS9t9amzm6Ug4Ahn' ADAFRUIT_IO_TEMP = b'target_temp' ADAFRUIT_IO_TEMP_CHART = b'temp_measurements' ADAFRUIT_IO_MOTOR_FREQ = b'motor_freq' ADAFRUIT_IO_ALGAE_OD = b'algae_od' ADAFRUIT_IO_ALGAE_FEED_RATE = b'algae_feed_rate' mqtt_motor_freq = bytes( '{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, ADAFRUIT_IO_MOTOR_FREQ), 'utf-8') mqtt_temp_chart = bytes( '{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, ADAFRUIT_IO_TEMP_CHART), 'utf-8') mqtt_ref_temp = bytes( '{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, ADAFRUIT_IO_TEMP), 'utf-8') mqtt_algae_od = bytes( '{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, ADAFRUIT_IO_ALGAE_OD), 'utf-8') mqtt_algae_feed_rate = bytes( '{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, ADAFRUIT_IO_ALGAE_FEED_RATE), 'utf-8') 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)) sys.exit() client.set_callback(cb) client.subscribe(mqtt_ref_temp) mqtt_ref_temp_get = bytes('{:s}/get'.format(mqtt_ref_temp), 'utf-8') client.publish(mqtt_ref_temp_get, '\0') client.subscribe(mqtt_algae_feed_rate) mqtt_algae_feed_rate_get = bytes('{:s}/get'.format(mqtt_algae_feed_rate), 'utf-8') client.publish(mqtt_algae_feed_rate_get, '\0') while True: Thread_website = True lock.acquire() for i in range(10): try: client.check_msg() except KeyboardInterrupt: print('Ctrl-C pressed...exiting') client.disconnect() sys.exit() time.sleep_ms(10) cooling_motor_data = cooling_pump.freq() client.publish(mqtt_motor_freq, bytes(str(cooling_motor_data), 'utf-8'), qos=0) client.publish(mqtt_temp_chart, bytes(str(current_temp), 'utf-8'), qos=0) client.publish(mqtt_algae_od, bytes(str(intensity_av), 'utf-8'), qos=0) lock.release() time.sleep(7)
class Telemetry(): """Telemetry via the MQTT protocoll.""" def __init__(self, ID, broker=""): self._isReady = False self._broker = broker self._clientID = ID self._client = None self._rootTopic = self._clientID + "/" self._doEncrypt = False try: from NETWORK import my_mqtt_encrypt_key, my_mqtt_encrypt_CBC if my_mqtt_encrypt_key is not None: from ucryptolib import aes self.AES = aes(my_mqtt_encrypt_key, 2, my_mqtt_encrypt_CBC) self._doEncrypt = True except ImportError: pass def connect(self): """ Try to connect to MQTT broker """ print("Initializing telemetry via MQTT ...") self.sta_if = network.WLAN(network.STA_IF) if not self.sta_if.isconnected(): print("Error: Not connected to network") else: from NETWORK import my_mqtt_usr, my_mqtt_pwd, my_mqtt_srv, my_mqtt_port if len(self._broker) == 0: self._broker = my_mqtt_srv _sll = my_mqtt_port == 8883 self._client = MQTTClient(self._clientID, self._broker, ssl=_sll) self._client.set_last_will(self._rootTopic, b'link/down') try: if self._client.connect() == 0: print("[{0:>12}] {1}".format("topic", self._rootTopic)) self._client.publish(self._rootTopic, b'link/up') self._isReady = True except: print("Error: MQTT brocker {} not responding".format( self._broker)) print("... done." if self._isReady else "... FAILED") return self._isReady def subscribe(self, topic, callBack): """ Subscribe to topic and define call back function """ self._client.set_callback(callBack) t = self._rootTopic + topic self._client.subscribe(t) print("Subscribed to `{0}`".format(t)) def spin(self): """ Needs to be called frequently to check for new messages """ self._client.check_msg() def publishDict(self, t, d): """ Publish a dictionary as a message under <standard topic>/<t> """ if self._isReady: if not self._doEncrypt: self._client.publish(self._rootTopic + t, ujson.dumps(d)) else: s = ujson.dumps(d) b = self.AES.encrypt(bytearray(s + " " * (16 - len(s) % 16))) self._client.publish(self._rootTopic + t, b) def publish(self, t, m): """ Publish a message under <standard topic>/<t> TODO: implement encryption here as well """ if self._isReady: try: self._client.publish(self._rootTopic + t, m) except OSError as error: if error.args[0] != errno.ECONNRESET: print("Error: publish caused {0}".format(error.args[0])) def disconnect(self): """ Disconnect from MQTT broker """ if self._isReady: self._client.disconnect() self._isReady = False @property def connected(self): return self._isReady
class MqttClient(object): """docstring for MqttClient""" t1 = None t2 = None config = None mqtt = None CLIENT_ID = "" token = None apiurl = None def __init__(self, conf): super(MqttClient, self).__init__() self.config = conf self.CLIENT_ID = conf["deviceid"] self.t1 = time.time() self.apiurl = "http://" + self.config["broker"] + ":" + str( self.config["noapport"] ) + "/api/device/token/" + self.config["deviceid"] def connect(self): self.mqtt = MQTTClient(self.CLIENT_ID, self.config["broker"], port=self.config["brkport"], user=self.config["brkuser"], password=self.config["brkpasswd"]) self.mqtt.set_callback(self.callback) def subscribe(self, channel): if not self.mqtt.connect(clean_session=False): self.mqtt.subscribe(channel) def publish(self, channel, msg): self.mqtt.publish(channel, msg) def getToken(self): tok = requests.get(self.apiurl).json()["token"] if tok: self.token = tok return self.token else: return None def tick(self, t): self.mqtt.check_msg() self.t2 = time.time() timediff = self.t2 - self.t1 if timediff > self.config["durationpub"]: self.t1 = self.t2 self.subscribe(bytes(self.config["topic"], 'utf-8')) self.getToken() def callback(self, topic, msg): try: obj = json.loads(msg) if obj.get("token") not in [self.token, self.config["brkuser"]]: return print((topic, msg, obj["token"])) if obj.get("action") == "loop": xmsg = {aciton: "loop", data: "online"} self.publish("helloworld", json.dumps(xmsg)) except Exception as e: raise e
class MqttClient(): """ Interface to paho.mqtt.client """ def __init__(self, log_queue, in_queue, out_queue, broker, node_name, user_name, user_password): """ Initialize """ self.mqtt = None self.connected = False self.log_queue = log_queue self.broker = broker self.node_name = node_name if self.node_name == "": self.node_name = "client-"+str(randrange(1000)) self.log_queue.add_message("debug", "MQTT Client Name: "+self.node_name) self.user_name = user_name self.user_password = user_password self.mqtt_in_queue = in_queue self.mqtt_out_queue = out_queue def start(self): """ start up the thrread """ # print("start mqtt client") try: self.log_queue.add_message("info", "Start MQTT Client") self.log_queue.add_message("info", self.broker) # esp32 self.mqtt = mqtt.Client(self.node_name) # esp32 self.mqtt.username_pw_set(username=self.user_name, password=self.user_password) if sys.platform.startswith("esp32"): self.mqtt = MQTTClient(self.node_name, self.broker, # cleansession=True, user=self.user_name, password=self.user_password) self.log_queue.add_message("info", 'MQTT connecting ...') self.mqtt.set_callback(self.data_cb_esp32) self.mqtt.connect() self.connected = True else: self.mqtt = mqtt.Client(self.node_name) self.mqtt.username_pw_set(username=self.user_name, password=self.user_password) self.mqtt.on_message = self.data_cb self.mqtt.on_connect = self.connect_cb self.mqtt.on_subscribe = self.subscribe_cb self.mqtt.on_disconnect = self.disconnect_cb self.log_queue.add_message("info", 'MQTT connecting ...') # connect to broker self.mqtt.connect(self.broker) #start the loop self.mqtt.loop_start() time.sleep(4) loop = 0 while not self.connected: #Wait for connection time.sleep(0.1) loop = loop + 1 if loop > 200: raise OSError self.log_queue.add_message("info", "Connected to MQTT Broker") except OSError as exc: self.log_queue.add_message("info", "Error during MQTT init") self.log_queue.add_message("info", 'Exception during mqtt init:') self.log_queue.add_message("info", str(exc)) def connect_cb(self, client, userdata, flags, rcode): """ callback from paho module called after connection """ self.log_queue.add_message("debug", 'connect cb: ' +str(rcode)) if rcode == 0: self.log_queue.add_message("info", " ... MQTT Connected...") #Signal connection self.connected = True else: self.log_queue.add_message("info", "Connection failed:", str(rcode)) raise OSError def disconnect_cb(self, client, userdata, rcode=0): """ callback from paho modile during disconnection """ self.log_queue.add_message("critical", "DisConnected result code "+str(rcode)) self.mqtt.loop_stop() def subscribe_cb(self, client, userdata, mid, granted_qos): """ callback from paho module during subscription """ time.sleep(1) if len(client.topic_ack) == 0: self.log_queue.add_message("debug", "All subs acknowledged") else: self.log_queue.add_message("debug", "on_subscribe error") def data_cb(self, client, userdata, message): """ callback from paho module. A new message has been received """ message_body = str(message.payload.decode("utf-8")) #print("message received ", message_body) #print("message topic=", message.topic) #print("message qos=", message.qos) #print("message retain flag=", message.retain) new_message = {'topic' : message.topic, 'body' : message_body} self.mqtt_in_queue.put(new_message) def data_cb_esp32(self, topic_binary, message_binary): """ data callback in esp32 """ # print("mqtt data cb") topic = topic_binary.decode('utf-8') message = message_binary.decode('utf-8') # print(">>> "+str(topic) + "<<<>>>"+str(message)+"<<<") self.mqtt_in_queue.put({"topic":topic, "body": message}) def restart_and_reconnect(self): """ restart mqtt connection """ print('Failed to connect to MQTT broker. Reconnecting...') time.sleep(10) machine.reset() def shutdown(self): """ sown the thread """ if self.mqtt is not None: self.mqtt.loop_stop() def subscribe(self, topic): """ subrecibe to a new topic """ self.log_queue.add_message("debug", "Subscribing to: "+topic) self.mqtt.subscribe(topic) def unsubscribe(self, topic): """ unsubrecibe to a new topic """ self.log_queue.add_message("debug", "Unsubscribing to: "+topic) self.mqtt.unsubscribe(topic) def is_connected(self): """ return connection status """ return self.connected def send_to_mqtt(self, message): """ publish a new message """ message_topic = message["topic"] message_body = message["body"] # print(">>>"+message_topic) if sys.platform.startswith("esp32"): self.mqtt.publish(message_topic, message_body) else: (rc, _mid) = self.mqtt.publish(message_topic, message_body) if rc != 0: self.log_queue.add_message("error", "Error Sendng MQTT Message: " +str(rc)+' .. '+message_topic) def check_msg(self): """ check message """ if sys.platform.startswith("esp32"): self.mqtt.check_msg() else: pass
while not wifi.isconnected(): time.sleep(0.5) iw.oled.show_text("WiFi connected") iw.oled.show_text("MQTT connecting") mqtt = MQTTClient("XXXXXXXXXX", "broker.mqttdashboard.com") mqtt.connect() iw.oled.show_text("MQTT connected") def sub_cb(topic, msg): if topic == b"krujeen/data/temp": iw.oled.fill(0) iw.oled.text(msg, 0, 0) iw.oled.show() mqtt.set_callback(sub_cb) mqtt.subscribe("krujeen/data/#") while True: temp = pin34.read() temp = ((temp * 3.3 / 1024) - 0.5) * 10 temp_str = str(temp) mqtt.check_msg() #if iw.sw1.value() == 0: mqtt.publish("krujeen/data/say", "TEST") urequests.post( 'http://maker.ifttt.com/trigger/krujeen_log/with/key/XXXXXXXXXX', json={'value1': temp}) time.sleep(60)
class Connectivity: def __init__(self, puzzle): self.puzzle = puzzle self.sta = network.WLAN(network.STA_IF) self.publishingChannel = "puzzles/"+self.puzzle.ID+"/values" self.ConnectWiFi() self.mqtt() self.started = False def ConnectWiFi(self): self.sta.active(True) #self.sta.connect('g.tec', '#g.tec#17!') self.sta.connect('GBLan', 'join1234') print("connecting to WiFi at GBLan") while self.sta.isconnected() == False: pass self.serverIP = self.sta.ifconfig()[3] print("Successfully connected to " + self.serverIP) def mqtt(self): print("connecting to mqtt ROBUST at {}".format(self.serverIP)) self.c = MQTTClient("umqtt_client", self.serverIP) self.c.set_callback(self.processMEssage) self.messager = Message.MessageConstructor(self.puzzle.ID) self.c.connect() self.c.subscribe("master/#") str = self.messager.GeneratePressentMessageStr() self.c.publish("devices/tester", str) print("connected to mqtt broker") def Emit(self): emi = MQTTClient('emiter', self.serverIP) emi.connect() emi.publish("devices/tester", "from MCU !") emi.disconnect() def Check(self): self.c.check_msg() def deb(self, topic, msg): print((topic, msg)) def processMEssage(self, topic, msg): print("received") print(topic) print (msg) if topic == b'master': toprint = "from master to ALL: " if self.messager is not None: obj = self.messager.FromString(msg) if obj.Order == 0: toprint = " -Replying to a showup message" serialMsg = self.messager.GeneratePressentMessageStr() self.c.publish("devices/"+self.puzzle.ID, serialMsg) target = str(self.puzzle.solution) serialMsg = self.messager.GenerateThisIsMySolutionMessage(target) self.c.publish("devices/"+self.puzzle.ID, serialMsg) else: print ("Unexpected message from master to all:") print (topic) print (msg) elif topic == b'master/'+self.puzzle.ID: #try: toprint = "from master to "+self.puzzle.ID+": " if self.messager is not None: obj = self.messager.FromString(msg) # 0 showup, # 1 present, # 2 forceSolve, # 3 Reset, # 4 UpdateRequested, # 5 ImSolved , <-- out message # 6 UpdateYOURSolution if obj.Order == 2: #forceSolve self.puzzle.forceSolve() elif obj.Order == 3: #Reset self.puzzle.ResetGame() elif obj.Order == 4: #UpdateRequested self.publishValue() elif obj.Order == 6: #UpdateYOURSolution self.puzzle.SetCurrentValueAsNewSolution() elif obj.Order == 9: #setThisNewSolution print(obj) self.puzzle.SetThisSolution(obj.Params["newSolution"]) else: toprint = toprint + msg.decode("utf-8") print(toprint) #except: # print("ups") # print(topic) # print (msg) else: print("CUSTOM ***") print(topic) print (msg) print("**********") self.ProcessCustomRAWValue(topic, msg) def Publish(self, msg): self.c.publish("devices/"+self.puzzle.ID, msg) def PublishValue(self, channel, val): self.c.publish(channel, val) def UpdateRequested(self, str): print("default UpdateSolution used") def ProcessCustomRAWValue(self, topic, val): print("using Generic Raw")
class openhab_mqtt_protocol: processcnt = 1 def __init__(self): self._log = core._log self._log.debug("Protocol: openhab 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_out1 = {} self._queue_out2 = {} self._queue_out3 = {} self._queue_out = protocol[ 'publish'] #### was commented out AJ, now back in self._pubstr = protocol['publish'] #### added AJ 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() mqttdata1 = None mqttdata2 = None mqttdata3 = None # case - all sensor types while True: mqttdata1 = None # looks like duplication of above! mqttdata1 = {} mqttdata2 = {} mqttdata3 = {} self._queue_out1 = '' self._queue_out2 = '' self._queue_out3 = '' message1 = '' message2 = '' message3 = '' # Get next plugin datavalues from utils.py, plugin_senddata(self, queuedata) try: devicedata['unitname'] = self._queue.get_nowait() devicedata['devicename'] = self._queue.get_nowait() except Exception as e: self._log.debug("Protocol: " + name + " SENSOR_TYPE_SINGLE exception: " + repr(e)) break # case SENSOR_TYPE_SINGLE if devicedata["stype"] == core.SENSOR_TYPE_SINGLE: # get plugin values devicedata['valueV1'] = self._queue.get_nowait() devicedata['valueN1'] = self._queue.get_nowait() # Assemble mqtt message mqttdata1 = {} mqttdata1['topic'] = devicedata['unitname'] + "/" + devicedata[ 'devicename'] + "/" + devicedata['valueN1'] mqttdata1['msg'] = str(devicedata["valueV1"]) message1 = str(devicedata["valueV1"]) 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 messages mqttdata1 = {} mqttdata1['topic'] = devicedata['unitname'] + "/" + devicedata[ 'devicename'] + "/" + devicedata['valueN1'] mqttdata1['msg'] = str(devicedata["valueV1"]) message1 = str(devicedata["valueV1"]) mqttdata2 = {} mqttdata2['topic'] = devicedata['unitname'] + "/" + devicedata[ 'devicename'] + "/" + devicedata['valueN2'] mqttdata2['msg'] = str(devicedata["valueV2"]) message1 = str(devicedata["valueV2"]) 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 topics for valueV1, V2, V3 mqttdata1 = {} mqttdata1['topic'] = devicedata['unitname'] + "/" + devicedata[ 'devicename'] + "/" + devicedata['valueN1'] mqttdata1['msg'] = str(devicedata["valueV1"]) message1 = str(devicedata["valueV1"]) mqttdata2 = {} mqttdata2['topic'] = devicedata['unitname'] + "/" + devicedata[ 'devicename'] + "/" + devicedata['valueN2'] mqttdata2['msg'] = str(devicedata["valueV2"]) message2 = str(devicedata["valueV2"]) mqttdata3 = {} mqttdata3['topic'] = devicedata['unitname'] + "/" + devicedata[ 'devicename'] + "/" + devicedata['valueN3'] mqttdata3['msg'] = str(devicedata["valueV3"]) message3 = str(devicedata["valueV3"]) 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, OpenHAB (usually) only two: 1 (=on) or 0 (=off) switch_on = ['closed', 'press', 'double', 'long', 'on'] switch_off = ['open', 'release', 'off'] if devicedata["valueV1"] in switch_on: devicedata["valueV1"] = 1 elif devicedata["valueV1"] in switch_off: devicedata["valueV1"] = 0 else: break # Assemble mqtt message mqttdata1 = {} mqttdata1['topic'] = devicedata['unitname'] + "/" + devicedata[ 'devicename'] + "/" + devicedata['valueN1'] mqttdata1['msg'] = str(devicedata["valueV1"]) message1 = str(devicedata["valueV1"]) 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 # Now publish the data to the MQTT broker/server # test for a user entry in webform protocol 'Publish' field; use it if it exists if self._pubstr != '': # entry exists in Publish field self._queue_out1 = self._pubstr self._queue_out2 = self._pubstr self._queue_out3 = self._pubstr else: # use "standard" format (unitname/devicename/valuename)... self._log.debug('Protocol: ' + name + ': "standard" topic format') self._queue_out1 = str(mqttdata1['topic']) if devicedata.get('valueN2') != None: self._queue_out2 = devicedata['unitname'] + "/" + devicedata[ 'devicename'] + "/" + devicedata['valueN2'] if devicedata.get('valueN3') != None: self._queue_out3 = devicedata['unitname'] + "/" + devicedata[ 'devicename'] + "/" + devicedata['valueN3'] # Whichever the sensor type, check if we have mqtt data to send, and if so publish it # publish datavalue1... if message1 != None: self._log.debug("Protocol: " + name + " Publish: Topic: " + self._queue_out1 + ", Message: " + message1) self._mq.publish(self._queue_out1, message1) # publish datavalue2 (if it exists) if devicedata.get('valueN2') != None: if message2 != None: self._log.debug("Protocol: " + name + " Publish: Topic: " + self._queue_out2 + ", Message: " + message2) self._mq.publish(self._queue_out2, message2) # publish datavalue3 (if it exists) if devicedata.get('valueN3') != None: if mqttdata3['msg'] != None: self._log.debug("Protocol: " + name + " Publish: Topic: " + self._queue_out3 + ", Message: " + message3) self._mq.publish(self._queue_out3, message3) # we may eventually need more, for example for Dummy device (4 values)... # End of send # def process(self): # processing todo for protocol (main loop of protocol) self._log.debug("Protocol: " + name + " Processing...") devicedata = {} try: while True: message1 = self._queue.get_nowait( ) # keep reading from the protocol queue if message1 == core.QUEUE_MESSAGE_START: # found "start" message break # ready to read devicedata values devicedata['stype'] = self._queue.get_nowait() # get sensor type devicedata['serverid'] = self._queue.get_nowait() # get server id #print("OHmqtt l 266: devicedata = ", devicedata) self.send( devicedata ) # go and get other datavalues as needed, and publish them to MQTT ... except Exception as e: self._log.debug("Protocol: " + name + " process Exception: " + repr(e)) # release lock, ready for next processing self._lock.clear()
# initialize buttons button_g = Pin(14, Pin.IN, Pin.PULL_UP) button_g.irq(trigger=Pin.IRQ_FALLING, handler=button_press) button_r = Pin(15, Pin.IN, Pin.PULL_UP) button_r.irq(trigger=Pin.IRQ_FALLING, handler=button_press) button_timer = Timer(1) onboard = PWM(Pin(13)) onboard.freq(0) onboard.duty(0) encrypter = CryptAes() while True: new_message = c.check_msg() if button > 1 and send_message == 1: # read from sensors raw_t = i2c.readfrom_mem(0x48, 0x00, 2) raw_x = i2c.readfrom_mem(0x53, 0x32, 2) raw_y = i2c.readfrom_mem(0x53, 0x34, 2) raw_z = i2c.readfrom_mem(0x53, 0x36, 2) #temperature = twos_comp(int.from_bytes(raw_t, 'big'), 16) * .0078 #accel_val_x = ustruct.unpack("<h", raw_x)[0] * .0039 #accel_val_y = ustruct.unpack("<h", raw_y)[0] * .0039 #accel_val_z = ustruct.unpack("<h", raw_z)[0] * .0039 # package sensor data sensor_data = raw_t + raw_x + raw_y + raw_z
class WeicheMqtt: """ MQTT Interface for all the weiche logic """ def __init__(self, config, effectqueue, set_lights): self.config = config self.effectqueue = effectqueue self.set_lights = set_lights self.mqtt = None def connect(self): """ Connect to the configured mqtt server, subscribe to topics and request an update """ server = self.config.config('mqtt', 'server') server, port = server.split(":", 1) print("[*] Connecting to mqtt at %s port %s"%(server, port)) self.mqtt = MQTTClient(self.config.client_id, server) self.mqtt.set_callback(self.mqtt_cb) self.mqtt.connect() default_topic = self.config.config('mqtt', 'default_topic') print("[*] Subscribing to topic (single msg)", default_topic) self.mqtt.subscribe(default_topic) mood_topic = self.config.config('mqtt', 'mood_topic') if mood_topic is None: print("[!] no mood topic set, ignoring") else: print("[*] Subscribing to topic (mood msg)", mood_topic) self.mqtt.subscribe(mood_topic) cue_topic = self.config.config('mqtt', 'queue_topic') print("[*] Subscribing to topic (cue)", cue_topic) self.mqtt.subscribe(cue_topic) # Request an update for the current light state self.mqtt.publish(b"/haspa/power/status", json.dumps([self.config.client_id])) return self.mqtt.sock # Received messages from subscriptions will be delivered to this callback def mqtt_cb(self, topic, msg): """ Branching for the different topics """ try: msg = msg.decode('utf-8') jsondata = json.loads(msg) except: print("[!] Json error: ", msg) if isinstance(topic, bytes): topic = topic.decode() if topic == self.config.config('mqtt', 'default_topic'): self.mqtt_light_callback(jsondata) elif topic == self.config.config('mqtt', 'queue_topic'): self.mqtt_queue_callback(jsondata) elif topic == self.config.config('mqtt', 'mood_topic'): self.mqtt_mood_callback(jsondata) def mqtt_light_callback(self, jsondata): """ Simple set lights targeted for this controller """ if self.config.client_id not in jsondata.keys(): return background_lights = jsondata[self.config.client_id] while len(background_lights) < 8: background_lights.append(0) self.set_lights(background_lights) def mqtt_mood_callback(self, jsondata): """ Simple set lights, does not contain a target id """ background_lights = jsondata if len(background_lights == 4): # double it up background_lights += background_lights while len(background_lights) < 8: background_lights.append(0) self.set_lights(background_lights) def mqtt_queue_callback(self, jsondata): """ Set a lightshow targeted at this controller """ if not isinstance(jsondata, dict): print("[!] cue data has to be {\"ID\":[[time,[led1, led2, ...]], ...]") return if self.config.client_id not in jsondata.keys(): print("[!] Not meant for me") return print("[*] Received queue update. New cue:") self.effectqueue.update(jsondata[self.config.client_id]) self.effectqueue.debug() @property def sock(self): """ Get the mqtt socket for poll() or select() """ return self.mqtt.sock def check_msg(self): """ Proxy """ return self.mqtt.check_msg()
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") (d_iv, d_nodeid, d_data) = ca.decrypt() print("Successful Decryption") accel_val_x = ustruct.unpack("<h", d_data[0:2])[0] accel_val_y = ustruct.unpack("<h", d_data[2:4])[0] accel_val_z = ustruct.unpack("<h", d_data[4:6])[0]