def connect_and_subscribe(): global CLIENT_ID, BROKER_ADDRESS, ROOT_TOPIC, client, SWITCH_PIN try: SWITCH_PIN.value(0) client = MQTTClient(CLIENT_ID, BROKER_ADDRESS) client.set_callback(received) client.connect() time.sleep(2) print("connecting") client.subscribe(ROOT_TOPIC + b'#') print('Connected to %s MQTT broker, subscribed to %s topic' % (BROKER_ADDRESS, ROOT_TOPIC)) SWITCH_PIN.value(1) client.publish(ROOT_TOPIC + b'version', 'Version 2021.091') return client except: SWITCH_PIN.value(1) time.sleep(1) SWITCH_PIN.value(0) time.sleep(1) SWITCH_PIN.value(1) time.sleep(1) SWITCH_PIN.value(0) time.sleep(1) SWITCH_PIN.value(1) time.sleep(1) SWITCH_PIN.value(0) return None
class MQTT(object): def __init__(self,config="mqtt.txt"): self.user = None self.password = None self.root = b"" self.config = config self.enable = True self.load_config() self.mqtt = MQTTClient("pylinky",self.server,user=self.user,password=self.password,keepalive=60) def connect(self): if self.enable: self.mqtt.connect() def load_config(self): try: with open(self.config,"r") as f: conf = f.readlines() if len(conf) > 0: self.server = conf[0].strip() if len(conf) > 1: self.user = conf[1].strip() if len(conf) > 2: self.password = conf[2].strip() if len(conf) > 3: self.root = conf[3].strip().encode() except OSError: self.enable = False def publish(self,tag,value): if self.enable: self.mqtt.publish(self.root+b"/"+tag,value)
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 connect_and_subscribe(): client = MQTTClient(client_id, MQTT_SERVER) client.set_callback(sub_cb) client.connect() client.subscribe('servo') print('Connected to MQTT') client.publish('esp32', 'connected!') return client
def connect_to_mqtt(self, publish_discovery): client = MQTTClient(self.MQTT_CLIENT_ID, self.MQTT_SERVER) client.connect() client.set_callback(self.on_mqtt_msg) client.subscribe(self.MQTT_TOPIC_CMD) if publish_discovery: discovery = { "name": "standingdesk", "state_topic": self.MQTT_TOPIC_STATE, "unit_of_measurement": "cm" } client.publish(self.MQTT_TOPIC_DISCOVERY, json.dumps(discovery)) return client
def main(server=SERVER): c = MQTTClient(CLIENT_ID, server, user='******', password='******', keepalive=alive_time) c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC1) c.subscribe(TOPIC2) c.subscribe(TOPIC3) c.subscribe(TOPIC4) # retain the last published value by MQTT broker c.publish(b"icreate/feeds/wecreate.relay1/get", b"hello") c.publish(b"icreate/feeds/wecreate.relay2/get", b"hello") c.publish(b"icreate/feeds/wecreate.relay3/get", b"hello") c.publish(b"icreate/feeds/wecreate.relay4/get", b"hello") print("Connected to %s, subscribed to %s, %s, %s and %s topics" % (server, TOPIC1, TOPIC2, TOPIC3, TOPIC4)) # function to continuously ping the MQTT broker in order to keep the connection alive def ping_wait(): while True: for i in range(alive_time): time.sleep(1) c.ping() print("Pinging...") #for i in range(4): #pingLed.value(not pingLed.value()) #time.sleep(0.1) # start a thread to ping the broker th.start_new_thread(ping_wait, ()) try: while True: c.wait_msg() except OSError as e: print("Reconnecting...") machine.reset() finally: c.disconnect()
def connect_mqtt(): global client_id, mqtt_server client = MQTTClient(client_id, mqtt_broker, port, None, None, 60) # set keepalive = 60 client.connected_flag=False #create flags client.bad_connection_flag=False # client.retry_count=0 # client.on_connect=on_connect #attach function to callback client.on_disconnect=on_disconnect print("publising on ",connection_status_topic ) print("Setting will message") client.set_last_will(connection_status_topic,connection_status_topic+' '+"False",0,True) #set will message print("connecting ",mqtt_broker) client.connect() client.publish(connection_status_topic,connection_status_topic+' '+"True",0,True)#use retain flag return client
def connect_mqtt(): global client_id, mqtt_server client = MQTTClient(client_id, secrets["mqtt_broker"], port, None, None, 60) # set keepalive = 60 client.connected_flag=False #create flags client.bad_connection_flag=False # client.retry_count=0 # client.on_connect=on_connect #attach function to callback client.on_disconnect=on_disconnect print("publising on ",connection_status_topic ) print("Setting will message") client.set_last_will(connection_status_topic,"False",0,True) #set will message print("connecting ",secrets["mqtt_broker"]) client.connect() #client = MQTTClient(client_id, mqtt_server, user=your_username, password=your_password) #client.connect() #print('Connected to %s MQTT broker' % (mqtt_server)) client.publish(connection_status_topic,"True",0,True)#use retain flag return client
def connect(): global device_id, mqtt_server, connected, client client = MQTTClient(client_id, mqtt_server, 1883, device_id, b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzb21lIjoicGF5bG9hZCJ9.UJxr678lFNPfhg9vBVw2AUstoxtzfPmcygBHPLu65Z8') client.set_callback(listenToSystemCommands) try: client.connect() except OSError as e: print("cannot connect to IOTINE.\nRebooting in 15s.") time.sleep(15) restart_and_reconnect() client.subscribe(device_id+'/$SYS/COMMANDS/NON') client.subscribe(device_id+'/$SYS/COMMANDS/IO_STATE/NON') client.subscribe(device_id+'/$SYS/COMMANDS/UPDATE/NON') client.subscribe(device_id+'/$SYS/COMMANDS/NEWFILE/NON') client.publish(device_id+'/$__VERSION/'+user_id, str(__VERSION)) client.publish(device_id+'/FSYS/'+user_id, str(os.listdir())) print('Connected to IOTINE') return client
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()
def main(): esp.osdebug(None) import gc gc.collect() i2c = I2C(scl=machine.Pin(5), sda=machine.Pin(4)) sensor = dht.DHT11(Pin(12)) bmp180 = BMP180(i2c) bmp180.oversample_sett = 2 bmp180.baseline = 101325 mqtt_server = '192.168.10.124' net = do_connect('HoltAtHome4','anthony050192') client_id = ubinascii.hexlify(machine.unique_id()) client = MQTTClient(client_id, mqtt_server) client.connect() count = 255 base = '/home/office/' print("Free : ", gc.mem_free()) while True: lightLevel = bh1750fvi.sample(i2c) print("Light Level : ",lightLevel) print("Count : ",count) client.publish(base + 'light', str(lightLevel)) count = count+1 if count > 2: sensor.measure() humidity = sensor.humidity() temp1 = sensor.temperature() temp = bmp180.temperature p = bmp180.pressure mbar = p/100 freeMem = gc.mem_free() dewPoint = calcRH(temp,humidity) print("Temperature :", temp) print("Temperature1:", temp1) print("Pressure :", mbar) print("Humidity :", humidity) print("Dew Point :", dewPoint) print("Free : ", freeMem) client.publish(base + 'temperature', str(temp)) client.publish(base + 'pressure', str(mbar)) client.publish(base + 'humidity', str(humidity)) client.publish(base + 'dewpoint', str(dewPoint)) client.publish(base + 'envNode/freemem' , str(freeMem)) count = 0 gc.collect() time.sleep(15)
class Wifi(object): # rtc=Rtc() c = None ssid = "" password = "" server = "" led = Pin(2, Pin.OUT, value=1) button = Pin(0, Pin.IN) clients = ubinascii.hexlify(machine.unique_id()) client = clients.decode() topic = b"kembang" state = "" timer = Timer(0) timer2 = Timer(1) status = 0 nyala_pada_1 = "" nyala_pada_2 = "" nyala_pada_3 = "" nyala_pada_4 = "" mati_pada_1 = "" mati_pada_2 = "" mati_pada_3 = "" mati_pada_4 = "" waktu = "" # menit=0 def __init__(self, *args, **kwargs): super(Wifi, self).__init__(*args, **kwargs) self.button.irq(trigger=Pin.IRQ_RISING, handler=self.func) self.start_ap() self.start_mqtt() def tim2(self, dt): pass def func(self, dt): self.ap() def start_ap(self): print("menunggu....") time.sleep(5) if station.isconnected() == True: print("sudah konek") return self.ap() def ap(self): self.timer.deinit() station.disconnect() while (wlan.ifconfig()[0] == '0.0.0.0'): time.sleep(1) print(wlan.ifconfig()) try: print("tcp sedang menuggu") ip = wlan.ifconfig()[0] s = socket.socket() s.bind(("192.168.4.1", 800)) s.listen(1) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) station.disconnect() while True: if self.status == 1: break print("acepting....") conn, addr = s.accept() print(addr, "connected") while True: data = conn.recv(1024) if (len(data) == 0): print("close socket") conn.close() break print(data) str_data = data.decode() print(str_data) if "connect" in str_data: print("conceting AP") paket = str_data.split("-") print(paket) t = ("ssid=\"{}\"".format(paket[1]), "pwd=\"{}\"".format(paket[2]), "server=\"{}\"".format(paket[3])) print(t) f = open("net.py", "w") f.write("\n".join(t)) f.close() self.server = paket[3] print(self.server) station.connect(paket[1], paket[2]) conn.send("data diterima") if str_data == "scan": lis = [] nets = station.scan() for nt in nets: name = str(nt[0], 'utf8') lis.append(name) print(lis) conn.send(str(lis)) if str_data == "exit": self.status = 1 break if str_data == "tanya": print(station.isconnected()) if station.isconnected() == True: conn.send("terhubung") return self.start_mqtt() self.status = 1 break else: conn.send("belum terhubung") except: print("gagal c*k") if (s): s.close() wlan.active(False) def start_mqtt(self): try: self.c = MQTTClient(self.clients, net.server) self.c.connect() except: self.c = MQTTClient(self.clients, self.server) self.c.connect() try: print("mulai mqtt") self.c.set_callback(self.sub_cb) self.c.subscribe(self.topic) self.c.subscribe(b"waktu") self.c.subscribe(b"nyala_pada_1") self.c.subscribe(b"nyala_pada_2") self.c.subscribe(b"nyala_pada_3") self.c.subscribe(b"nyala_pada_4") self.c.subscribe(b"mati_pada_1") self.c.subscribe(b"mati_pada_2") self.c.subscribe(b"mati_pada_3") self.c.subscribe(b"mati_pada_4") print("Connected to %s, subscribed to %s topic" % (self.server, self.topic)) while 1: self.timer.deinit() self.state = "terhubung" self.c.wait_msg() except: print("pedot") self.state = "terputus" self.timer.init(period=1000, callback=self.tim) def sub_cb(self, topic, msg): strtopic = topic.decode() message = msg.decode() if "waktu" in strtopic: self.waktu = message elif self.client + "add" in strtopic: self.c.publish(self.clients + b"lampu", b"[lampu,on,off]") elif self.client + "nyala_pada_1" in strtopic: self.nyala_pada_1 = message elif self.client + "nyala_pada_2" in strtopic: self.nyala_pada_2 = message elif self.client + "nyala_pada_3" in strtopic: self.nyala_pada_3 = message elif self.client + "nyala_pada_4" in strtopic: self.nyala_pada_4 = message elif self.client + "mati_pada_1" in strtopic: self.mati_pada_1 = message elif self.client + "mati_pada_2" in strtopic: self.mati_pada_2 = message elif self.client + "mati_pada_3" in strtopic: self.mati_pada_3 = message elif self.client + "mati_pada_4" in strtopic: self.mati_pada_4 = message elif self.waktu == self.nyala_pada_1: self.led.value(0) elif self.waktu == self.nyala_pada_2: self.led.value(0) elif self.waktu == self.nyala_pada_3: self.led.value(0) elif self.waktu == self.nyala_pada_4: self.led.value(0) elif self.waktu == self.mati_pada_1: self.led.value(1) elif self.waktu == self.mati_pada_2: self.led.value(1) elif self.waktu == self.mati_pada_3: self.led.value(1) elif self.waktu == self.mati_pada_4: self.led.value(1) elif msg == b"on": self.led.value(0) # self.c.publish(self.client,b"saya client") elif msg == b"off": self.led.value(1) print(self.waktu) print(self.client) print(self.nyala_pada_1) def tim(self, dt): print(station.isconnected()) if self.state == "terputus": self.start_mqtt() else: self.timer.deinit()
class MQTT(object): CLIENT_ID = ubinascii.hexlify(machine.unique_id()) def __init__(self, callback, pub_topic, server='0.0.0.0', sub_topic='default'): self.__connection = False self.__server = server self.__sub_topic = sub_topic self.__callback = None self.__topic = None self.__msg = None if pub_topic[-1] != '/': pub_topic += '/' self.__pub_topic = pub_topic def connect(self): try: self.client = MQTTClient(self.CLIENT_ID, self.__server) self.client.set_callback(self.__sub_cb) self.client.connect() self.client.subscribe(self.__sub_topic) self.__connection = True return self.client except Exception: return None def publish(self, pub_topic, msg): self.client.publish(pub_topic, msg) def __sub_cb(self, topic, msg): self.__topic = topic.decode('utf-8') self.__msg = msg.decode('utf-8') @property def connection(self): return self.__connection @property def server(self): return self.__server @property def sub_topic(self): return self.__sub_topic @property def pub_topic(self): return self.__pub_topic @property def callback(self): return self.__topic, self.__msg @callback.setter def callback(self, msg): self.__topic = topic = msg self.__msg = msg = msg
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()
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)
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() SwitchStatus = True while True: try: client.check_msg() if button.value() == 1: if SwitchStatus is True: SwitchStatus = False msg = '{"id":'+ClientId+',"params":{"ButtonStatus":'+str(1)+'},"method":"thing.event.property.post"}' client.publish(pubTopic,msg,qos=1) print("Publish ON") else: SwitchStatus = True msg = '{"id":'+ClientId+',"params":{"ButtonStatus":'+str(0)+'},"method":"thing.event.property.post"}' client.publish(pubTopic,msg,qos=1) print("Publish OFF") time.sleep(1) except OSError as e: restart()
# Credenciales para publicar en Thinkspeak # THINGSPEAK_CHANNEL_ID = b'1022434' THINGSPEAK_CHANNEL_WRITE_API_KEY = b'ANZ6JAHJLQ7C40SU' PUBLISH_PERIOD_IN_SEC = 1 while True: current_time = time.time() #Enviar datos cada 15 segundos # if current_time - last_measurement_time > 15: # Envio de los datos a Thinkgspeak # Valorlluvia = not Lluvia.value() credentials = bytes("channels/{:s}/publish/{:s}".format(THINGSPEAK_CHANNEL_ID, THINGSPEAK_CHANNEL_WRITE_API_KEY), 'utf-8') last_measurement_time = current_time payload = bytes("field1={:.1f}\n".format(Valorlluvia), 'utf-8') client.connect() print('Envio de datos a Thinkspeak') client.publish(credentials, payload) client.disconnect() time.sleep(PUBLISH_PERIOD_IN_SEC) # Interacción con la página Web # conn, addr = s.accept() print('Conexion desde %s' % str(addr)) request = conn.recv(4097) request = str(request) typecont = str(request) print('Contenido = %s' % request) led_on = request.find('/?cerrar=yes') led_off = request.find('/?cerrar=no') detection = typecont.find ('/?cerrar=yes') #print( 'Esto es deteccion', detection) # Manejo del actuador # if led_on == 6 or detection == 138:
def sub_cb(topic, msg): print((topic, msg)) def restart(): time.sleep(10) machine.reset() connectWIFI() myIot = DFRobot_Iot(ONENET_SERVER, ProductID, DeviceId, ApiKey) client = MQTTClient(myIot.client_id, myIot.mqttserver, port=ONENET_PORT, user=myIot.username, password=myIot.password) client.set_callback(sub_cb) client.connect() timeLimit = 10 #10s lastTime = 0 while True: try: client.check_msg() if (time.time() - lastTime) > timeLimit: print("publish hello") client.publish(pubTopic, 'hello') lastTime = time.time() except OSError as e: restart()
client_id = "esp8266_home" topic = "home" ds_pin = machine.Pin(4) ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin)) client = MQTTClient(client_id, broker) client.connect print("Connected to {}".format(broker)) roms = ds_sensor.scan() post_data = {} while True: ds_sensor.convert_temp() time.sleep_ms(750) for rom in roms: #print(rom) data = ds_sensor.read_temp(rom) print(data) post_data['Temperature'] = ds_sensor.read_temp(rom) #client.publish('{}/{}'.format(topic,client_id),bytes(str(data), 'utf-8')) client.publish('home-assistant/home/esp8266_home', '24') print('Sensor state: {}'.format(data)) kpn.post_data(post_data) time.sleep(5) # Main timer1 = Timer(-1) timer1.init(period=(10 * 1000), mode=Timer.PERIODIC, callback=lambda t: measure())
print("using DHCP...") ### Setup ADC to measure VCC if not adcmode.set_adc_mode(adcmode.ADC_MODE_VCC): print("ADC mdode changed in flash - restart needed") machine.reset() vcc = machine.ADC(1).read()/1024.0 while not sta_if.isconnected(): time.sleep(0.5) print("wifi connected: ", sta_if.ifconfig()) ### connect to MQTT CLIENT_ID = ubinascii.hexlify(machine.unique_id()) client = MQTTClient(CLIENT_ID, secrets.MQTT_SVR, user=secrets.MQTT_USER, password=secrets.MQTT_PWD ) client.connect() print("mqtt: connected") payload = secrets.MQTT_PAYLOAD.format(vcc) client.publish(secrets.MQTT_TOPIC, payload) print("mqtt: published %s: %s"%(secrets.MQTT_TOPIC, payload)) client.disconnect() print("mqtt: disconnected") except Exception as e: print( "FATAL: ", type(e) ) print( " ", repr(e) ) time.sleep(0.1) # without this, deepsleep doesn't work well esp.deepsleep(0)
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])
def restart(): time.sleep(10) machine.reset() connectWIFI() myIot = DFRobot_Iot(ONENET_SERVER, ProductID, DeviceId, ApiKey) client = MQTTClient(myIot.client_id, myIot.mqttserver, port=ONENET_PORT, user=myIot.username, password=myIot.password) client.set_callback(sub_cb) client.connect() SwitchStatus = True while True: try: client.check_msg() if button.value() == 1: if SwitchStatus is True: SwitchStatus = False client.publish(pubTopic, "ON") else: SwitchStatus = True client.publish(pubTopic, "OFF") time.sleep(1) except OSError as e: restart()
# para crear el cliente mqtt es necesario definir unos parámetros server = '192.168.0.15' port=1880 user='' passwd='' CLIENT_ID = ubinascii.hexlify(machine.unique_id()) mqtt = MQTTClient(CLIENT_ID,server,port,user,passwd) pin1.value(0) # Se define un bucle infinito con el fin de que siempre se esté atento a cuando el uart reciba un dato while True==True: pin1.value(1) val = uart.read() # Se crea la variable val con los datos que llegan por el uart. Esto es posible por la funcion .read() if val != None: print(val) mqtt.connect() # mediante connect y disconect garantizamos que solo cuando se tenga un dato que entregar se envíen los datos con mqtt mqtt.publish('Datos',val) # publicamos en el tópico Datos el dato val con lo recibido del uart mqtt.disconect() else: utime.sleep(1) pin1.value(0)