def start_process(): mac = ubinascii.hexlify(network.WLAN().config('mac'), ':').decode() try: set_wifi() client = MQTTClient("umqtt_client", "10.0.0.233") connect_server(client) print("-------press ctrl-c to stop the polling") # create and publish control message control_message = {"mac": mac} client.publish(MQTT_CONTROL_CHANNEL, json.dumps(control_message)) print("Publish control message : " + str(control_message)) print() time.sleep(5) client.check_msg() # process configuration sensors = process_configuration() while True: for sensor in sensors: publish_data_message(client, sensor) # catches the ctrl-c command, which breaks the loop above except KeyboardInterrupt: print("Continuous polling stopped") finally: client.disconnect()
def restart(): time.sleep(10) machine.reset() connectWIFI() myIot = DFRobot_Iot(ALIYUN_SERVER, DeviceName, ClientId, ProductKey, DeviceSecret) client = MQTTClient(myIot.client_id, myIot.mqttserver, port=ALIYUN_PORT, user=myIot.username, password=myIot.password, keepalive=120) client.set_callback(sub_cb) client.connect() print('Connection mqtt successful') timeLimit = 10 #10s lastTime = 0 while True: try: client.check_msg() if (time.time() - lastTime) > timeLimit: print("publish Hello World !") client.publish(pubTopic, "Hello World !", qos=1) lastTime = time.time() except OSError as e: restart()
class Device: sta_if = network.WLAN(network.STA_IF) pusher = Pin(config.GPIO_PUSHER, Pin.IN, Pin.PULL_UP) led = Pin(config.GPIO_LED, Pin.OUT) user_topic = b'/user/%s' % config.USER_ID focused = 0 def __init__(self): # Instantiate MQTT client self.mqtt_client = MQTTClient( client_id=config.DEVICE_ID, server=config.MQTT_ENDPOINT, port=config.MQTT_PORT, user=config.MQTT_USERNAME, password=config.MQTT_PASSWORD, keepalive=10000, ) # MQTT messages handler self.mqtt_client.set_callback(self.on_mqtt_message) # Button press handler self.pusher.irq(trigger=Pin.IRQ_RISING, handler=self.on_button_press) def wait_for_network(self): while (self.sta_if.isconnected() != True): utime.sleep(0.025) def mqtt_check_message(self): while (True): utime.sleep(0.025) self.mqtt_client.check_msg() def connect_mqtt(self): try: self.mqtt_client.connect() self.mqtt_client.subscribe(self.user_topic) except Exception as e: print(sys.print_exception(e)) else: print("Connected to %s" % config.MQTT_ENDPOINT) def compile_mqtt_payload(self, user_id, status): return '{"userId":"%s","focused":%i}' % (user_id, status) def mqtt_publish_status(self, status): payload = self.compile_mqtt_payload(config.USER_ID, status) self.mqtt_client.publish('/status', payload) def set_status(self, status): self.focused = status self.led.value(status) def on_button_press(self, value): try: new_status = 0 if self.focused else 1 self.set_status(new_status) self.mqtt_publish_status(new_status) except Exception as e: print(sys.print_exception(e)) def on_mqtt_message(self, topic, message): try: if topic == self.user_topic: new_status = ujson.loads(message)['focused'] self.set_status(new_status) except Exception as e: print(sys.print_exception(e)) def run(self): try: # Wait for WiFi connectivity self.wait_for_network() # Connect to the MQTT server self.connect_mqtt() except Exception as e: print(sys.print_exception(e)) else: self.mqtt_check_message()
class iotNetwork: netCfg = None wdogTime = 5000 # ms tim = machine.Timer(-1) netConnected = False wdogTriggered = False def __init__(self, w=5000): self.wdogTime = w cfgFile = open('iotdb.db', 'r+b') self.netCfg = btree.open(cfgFile) def wdog(self, b): print("Wdog fired.") self.wdogTriggered = True machine.reset() def connect(self): print("Connect") self.tim.init(period=self.wdogTime, mode=machine.Timer.ONE_SHOT, callback=self.wdog) self.sta_if = network.WLAN(network.STA_IF) if self.sta_if.isconnected(): print("Already connected, disconecting ...") self.sta_if.disconnect() print("... done.") print('connecting to network...') self.sta_if.active(True) essid = (self.netCfg[b"ESSID"]).decode() password = (self.netCfg[b"PASSWD"]).decode() self.sta_if.connect(essid, password) while not self.sta_if.isconnected(): pass print("... Connected") self.tim.init(period=-1, mode=machine.Timer.ONE_SHOT) def disconnect(self): print("Disconnect") self.sta_if.disconnect() print("Disconnect") count = 0 while self.sta_if.isconnected(): count += 1 print(count) print("Disconnected") def connectMQTT(self): print("MQTT...") self.tim.init(period=self.wdogTime, mode=machine.Timer.ONE_SHOT, callback=self.wdog) mqttHost = (self.netCfg[b"MQTT_HOST"]).decode() mqttPort = int((self.netCfg[b"PORT"]).decode()) self.base = (self.netCfg[b"MQTT_BASE"]).decode() clientId = ubinascii.hexlify(machine.unique_id()) try: self.client = MQTTClient(clientId, mqttHost) self.client.connect() except: sleep(10) self.tim.init(period=-1, mode=machine.Timer.ONE_SHOT) print("...Done") def checkMQTT(self): self.client.check_msg() def disconnectMQTT(self): print("MQTT Disconnect") self.client.disconnect() print("MQTT Disconnected") def publishMQTT(self, topic, message): print("Publish: " + topic + "->" + message) print(self.base + topic, message) self.client.publish(self.base + topic, message) def subscribeMQTT(self, topic, cb): self.client.set_callback(cb) self.client.subscribe(self.base + topic) print("Subscribing to " + self.base + topic) def ifconfig(self): print(self.sta_if.ifconfig()) def getIP(self): n = self.sta_if.ifconfig() return (n[0])
class mqttClass: # Initial setup def __init__(self, host_IP='192.168.5.4', username=None, key=None, subscriptions=None, interval=100, timer_n=1): self.mqtt_server = host_IP # self.clientname=hexlify(unique_id()+str(randint(1000,9999))) self.clientname = str(randint(1000, 9999)) port = 1883 # user=b'username' # password=b'password' #mqtt=MQTTClient(clientname,mqtt_server,port,user,password) self.mqtt = MQTTClient(self.clientname, self.mqtt_server, port, username, key) self.update_timer = Timer(timer_n) self.timer_rate = interval #Array of topics currently subscribed to. self.topic_list = set() self.failcount = 0 self.mqtt.set_callback(self.callback_handler) topic_defaults = { # insert topic(s) as key, and function location as value 'test': self.test_function, 'default': self.default_function } # Dictionary to associate subscription topics to their function() if type(subscriptions) is dict: print("registered subscription dictionary") self.topic_outsourcing = subscriptions else: self.topic_outsourcing = topic_defaults #Connect and maintain MQTT connection. def reconnect(self): print(self.mqtt_server + " dropped mqtt connection. Reconnecting") sleep(2) if (self.failcount < 10): self.connect() else: print('Too many reconnect attempts. Restart program.') self.failcount += 1 def connect(self): try: self.mqtt.connect() print("Connected to " + self.mqtt_server) except OSError as e: self.reconnect() self.failcount = 0 self.auto_subscribe() self.update_timer.init(mode=Timer.PERIODIC, period=self.timer_rate, callback=self.update_callback) return 1 # Look for new messages on subscribed topics. def update_callback(self, event=None): try: self.mqtt.check_msg() except: print('ERROR: ' + self.mqtt_server + ' failed callback.') print("Quitting timer callback. Restart subscriptions.") self.update_timer.deinit() self.connect() def update(self): self.mqtt.check_msg() def __str__(self): return str(self.mqtt_server) ##################################################################### ####################### SUBSCRIPTION HANDLING ####################### ##################################################################### # Setup subscription to a topic. def sub(self, topic): self.topic_list.add(topic) self.mqtt.subscribe(topic) def auto_subscribe(self): # print(self.topic_outsourcing) for k in self.topic_outsourcing: self.sub(k) print('subscribed to ' + str(k)) # For topic 'test', print out the topic and message def test_function(self, top, msg): print() print("test topic rx" + str(top)) print(msg) print() # Redirect from MQTT callback function. # Error checking. def default_function(self, top, whatever): print("Discarding data: " + str(whatever) + ".") print("No filter for topic " + str(top) + " discovered.") #When a message is received, this function is called. def callback_handler(self, bytes_topic, bytes_msg): # Format the data into variables that are python friendly. topic = bytes_topic.decode() message = bytes_msg.decode() # Locate the function for the incoming topic. If not found, use the default_function. topicFunction = self.topic_outsourcing.get(topic, self.default_function) topicFunction(topic, message) #return self.update() ############################################################ ####################### PUBLISHING ########################## ############################################################ # Publish to a topic. def pub(self, topic, message): # print("topic: "+topic) # print("message: "+str(message)) sent = 0 while (sent < 100): try: self.mqtt.publish(topic, str(message)) # print("checks in the mail") sent = 9000 except OSError as e: self.mqtt.connect() print("mqtt dropped " + str(sent) + "times") sent += 1 sleep(0.1)
class FortiThing(object): def __init__(self): freq(160000000) self._i2c = I2C(scl=Pin(22), sda=Pin(21), freq=100000) self._bme = bme280_float.BME280(i2c=self._i2c) self._adc = ADC(Pin(37)) self._lis3dh = LIS3DH_I2C(self._i2c, address=0x19, int1=Pin(15)) self._lis3dh.set_tap(tap=1, threshold=10, time_limit=10, time_latency=20, time_window=255) self._touchPad = TouchPad(Pin(32)) self._blueled = Pin(4, Pin.OUT) self._blueled.off() self._mqttClient = None self._nb_leds = 4 self._clock_pin = 14 self._data_pin = 13 self._empty_pin = 12 self._spi = SPI(1, baudrate=10000000, sck=Pin(self._clock_pin), mosi=Pin(self._data_pin), miso=Pin(self._empty_pin)) self._leds = DotStar(self._spi, self._nb_leds) for i in range(0, self._nb_leds): self._leds[i] = (0, 0, 0) try: self._oled = ssd1306.SSD1306_I2C(128, 64, self._i2c, 0x3c) except Exception as e: self._oled = None print("Exception occurred when initializing OLED.") print("Exception: " + str(e)) #################################### # Basic hardware operations #################################### def screen(self, *argv): print(argv) try: self._oled.fill(0) self._oled.text(argv[0], 0, 0) index = 0 for arg in argv[1:]: self._oled.text(arg, 0, index * 12 + 20) index += 1 self._oled.show() except Exception as e: pass def set_led_array(self, number, color, value): if color == 'red': self._leds[number] = (value, self._leds[number][1], self._leds[number][2]) if color == 'green': self._leds[number] = (self._leds[number][0], value, self._leds[number][2]) if color == 'blue': self._leds[number] = (self._leds[number][0], self._leds[number][1], value) def set_blue_led(self, led_on): self._blueled.on() if led_on == 1 or led_on else self._blueled.off() def get_switch_status(self): return not Pin(18, Pin.IN, Pin.PULL_UP).value() def get_tph(self): return self._bme.read_compensated_data() def get_adc(self): return self._adc.read() def get_touchpad(self): return (self._touchPad.read()) def get_acceleration(self): return self._lis3dh.acceleration def get_tapped(self): return self._lis3dh.tapped def get_shaked(self): return self._lis3dh.shake(shake_threshold=10, avg_count=10, total_delay=0.1) #################################### # Wifi connectivity #################################### def wifi_connect(self, wifi_essid, wifi_password): try: self.screen("Status", "Connecting WiFi") sta_if = network.WLAN(network.STA_IF) ap_if = network.WLAN(network.AP_IF) ap_if.active(False) # Deactivate Access Point sta_if.active(True) # Activate Station interface sta_if.connect(wifi_essid, wifi_password) count = 0 while not sta_if.isconnected() and count < 60: sleep(0.5) count += 1 if count >= 60: self.screen("Error", "WiFi connection failed", "More than 60 attemps") raise Exception self.screen("Status", "WiFi Connected") except Exception as e: print("Exception occurred when connecting.") print("Exception: " + str(e)) self.screen("Error", "Exception occurred", "when connecting") #################################### # IoT / MQTT services #################################### def mqtt_connect(self, client_id, server, port, ssl, user, password, sub_cb): self.screen("Status", "MQTT Connecting") self._mqttClient = MQTTClient(client_id=client_id, server=server, port=port, ssl=ssl, user=user, password=password) self._mqttClient.set_callback(sub_cb) self._mqttClient.connect() self.screen("Status", "MQTT Connected") def mqtt_subscribe(self, path): self.screen("Status", "Subscribing topic") self._mqttClient.subscribe(path) self.screen("Status", "Topic Subscribed") def mqtt_publish(self, path, value): self._mqttClient.publish(path, value) def mqtt_check_msg(self): self._mqttClient.check_msg()