class MQTTDevice: def __init__(self, topic_online, true_message="true", false_message="false"): self.true_message = true_message self.false_message = false_message self.client = MQTTClient(MQTT_CLIENT_ID_RANDOM, MQTT_BROKER_ADDRESS, port=MQTT_PORT, keepalive=KEEP_ALIVE_TIME_SEC) self.next_scheduled_ping_time = 0 self._client_setup(topic_online) def _client_setup(self, topic_online): self.client.set_last_will(topic_online, self.false_message) self.client.connect() self.client.publish(topic_online, self.true_message) self.setup_subscriptions() # override this method in subclass # set callback and subscriptions def setup_subscriptions(self): pass def _ping(self): if (self.next_scheduled_ping_time < utime.time()): self.client.ping() self.next_scheduled_ping_time = utime.time() + PING_EVERY_SEC #run method has to be called every execution cycle def run(self): self._ping() self.client.check_msg()
def run(self): # Now we setup our MQTT client client = MQTTClient(self.io_id, "io.adafruit.com", user=self.io_user, password=self.io_key, port=self.port) client.set_callback(self.message_callback) client.connect() client.subscribe(topic="{0}/feeds/sensors".format(self.io_user)) while True: if self.sensor_on: data = self.read_data() print(" >", data) client.publish(topic="{0}/feeds/temperature".format( self.io_user), msg=str(data[0])) client.publish(topic="{0}/feeds/humidity".format(self.io_user), msg=str(data[1])) client.publish(topic="{0}/feeds/pressure".format(self.io_user), msg=str(data[2])) utime.sleep(self.update_frequency) client.check_msg() utime.sleep(1) # Check messages only once per second
def MQTTClientInit(): global mqttmsg # wifi configuration WIFI_SSID = 'LAPTOP-BHHF3UMN 4817' WIFI_PASS = '******' def sub_cb(topic, msg): print(msg) wlan = WLAN(mode=WLAN.STA) wlan.connect(WIFI_SSID, auth=(WLAN.WPA2, WIFI_PASS), timeout=5000) while not wlan.isconnected(): machine.idle() print("Connected to WiFi\n") client = MQTTClient("lights11", "io.adafruit.com",user="******", password="******", port=1883) client.set_callback(sub_cb) client.connect() client.subscribe(topic="Yunwei/feeds/lights") while True: print("Sending "+mqttmsg) client.publish(topic="Yunwei/feeds/lights", msg=mqttmsg) time.sleep(5) #print("Sending 222") #client.publish(topic="Yunwei/feeds/lights", msg=mqttmsg) client.check_msg() time.sleep(5)
class Pycom1: def __init__(self): self.x = '0' def sub_cb(self, topic, msg): self.x = str(msg) def wifi_enable(self): wlan = WLAN(mode=WLAN.STA) wlan.connect("thingQbator", auth=(WLAN.WPA2, "C1sco12345"), timeout=5000) while not wlan.isconnected(): machine.idle() print("\nConnected to Wifi\n") def mqtt_enable(self): self.client = MQTTClient("pycom1", "173.39.91.118", port=1883) self.client.set_callback(self.sub_cb) self.client.connect() self.client.subscribe(topic="qbator/call_temp") def run(self): while True: self.client.check_msg() if self.x.strip("b'") == '1': print(self.x) self.client.publish(topic="qbator/temp", msg=str(int(t_sensor.temperature()))) self.client.publish(topic="qbator/hum", msg=str(int(t_sensor.humidity()))) else: continue
def sub_mqtt_Connect(): client = MQTTClient("lopy", "192.168.2.1", port=1883) client.set_callback(sub_mqtt) client.connect() client.subscribe(topic="distancia") print("Suscrito...") while True: client.check_msg()
def main(server=SERVER): client = MQTTClient(CLIENT_ID, server, port=1883) client.set_callback(sub_cb) client.connect() client.subscribe('messages_esp') adc = ADC(0) while True: client.check_msg() adcValue = adc.read() messageAdc = {"adcValue": str(adcValue)} client.publish('message_esp', ujson.dumps(messageAdc)) time.sleep(2) client.disconnect()
def main(): print("starting") time.sleep(1.0) # Since open-drain on() means relays OFF and off() means Relays ON RELAY1.on() RELAY2.on() client = MQTTClient("relays1", "192.168.1.145", port=1883) client.settimeout = settimeout client.connect() client.set_callback(switch) client.subscribe("switching/#") while True: client.check_msg() print("waiting") time.sleep(1.0)
def main(server="test.mosquitto.org"): c = MQTTClient("umqtt_clientc", server) c.set_callback(sub_cb) c.connect() c.subscribe(b"mhermans/lights/#") while True: if True: # Blocking wait for message c.wait_msg() else: # Non-blocking wait for message c.check_msg() # Then need to sleep to avoid 100% CPU usage (in a real # app other useful actions would be performed instead) time.sleep(1) c.disconnect()
def mqtt_listen(server=MQTT_BROKER): global mqttc mqttc = MQTTClient("umqtt_client", server) mqttc.set_callback(sub_cb) mqttc.connect() mqttc.subscribe(b"sensor/#") while True: if True: # Blocking wait for message mqttc.wait_msg() else: # Non-blocking wait for message mqttc.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) mqttc.disconnect()
def run(self): # Setup MQTT client client = MQTTClient(client_id=self.io_id, server="io.adafruit.com", user=self.io_user, password=self.io_key, port=self.port) client.set_callback(self.message_callback) client.connect() client.subscribe(topic="{0}/feeds/sensors".format(self.io_user)) while True: if self.sensor_on: # transitory time for i in range(0, 9): self.read_data() utime.sleep(2) data = self.read_data() client.publish(topic="{0}/feeds/temperature".format( self.io_user), msg=str("{0:0.1f}".format(data[0]))) client.publish(topic="{0}/feeds/humidity".format(self.io_user), msg=str("{0:0.1f}".format(data[1]))) client.publish(topic="{0}/feeds/pressure".format(self.io_user), msg=str("{0:0.1f}".format(data[2] / 100))) if self.battery: client.publish(topic="{0}/feeds/battery".format( self.io_user), msg=str("{0:0.1f}".format(data[3]))) print(" >{0} - battery: {1}".format(data[0:3], data[3])) else: print(" >{0}".format(data[0:3])) utime.sleep(self.update_frequency) client.check_msg() utime.sleep(1)
def run_gate(): global on_for_update c = MQTTClient("gate_client", secrets.MQTT_BROKER) c.set_callback(device_control) try: c.connect(clean_session=False) c.publish(topic.GATE_STATUS, msg_payload()) c.subscribe(topic.GATE_UPDATE, qos=1) c.check_msg() c.disconnect() flash_led(LED1) except OSError as e: print("mqtt error", e) if not on_for_update: switch_off() webrepl.start()
def run(self, wlan): # Setup MQTT client client = MQTTClient(client_id=self.io_id, server="io.adafruit.com", user=self.io_user, password=self.io_key, port=self.port) client.set_callback(self.message_callback) client.connect() client.subscribe(topic="{0}/feeds/sensors".format(self.io_user)) while True: if self.sensor_on and wlan.isconnected(): data = self.read_data() print(" >", data) client.publish(topic="{0}/feeds/tank-1".format(self.io_user), msg=str(data)) utime.sleep(self.update_frequency) elif not wlan.isconnected(): machine.reset() client.check_msg() utime.sleep(1)
def send_server(): global sd from network import WLAN from mqtt import MQTTClient import machine import time def sub_cb(topic, msg): print(msg) wlan = WLAN(mode=WLAN.STA) wlan.connect("Android", auth=(WLAN.WPA2, "123456789a"), timeout=5000) while not wlan.isconnected(): machine.idle() print("Connected to Wifi\n") client = MQTTClient("FiPy", "129.241.91.125", user="******", password="******", port=1883) client.set_callback(sub_cb) client.connect() client.subscribe(topic="Fuelfighter") last = None packetTemp = None copy_counter = 0 while True: stime = (ut() + 500) // 1000 if "server.txt" in ls('/sd') and stime != last: last = stime file = open('/sd/server.txt', 'r') packet = file.read() file.close() if packet != packetTemp: client.publish(topic="Fuelfighter", msg=packet) client.check_msg()
from mqtt import MQTTClient import machine import time import ubinascii from machine import Timer CLIENT_ID = ubinascii.hexlify(machine.unique_id()) SERVER = "test.mosquitto.org" #SERVER = "broker.hivemq.org" PORT = 1883 def push_heartbeat(): c_mqtt.connect() c_mqtt.publish(b"mhermans/heartbeat", b'1') c_mqtt.disconnect() global c_mqtt c_mqtt = MQTTClient(client_id=CLIENT_ID, server=SERVER, port=PORT) while True: c_mqtt.check_msg() # main loop # pub: heartbeat every 5sec. # sub: print every msg immediatly
print("FAILED") finally: last_random_sent_ticks = time.ticks_ms() # Use the MQTT protocol to connect to Adafruit IO client = MQTTClient(AIO_CLIENT_ID, AIO_SERVER, AIO_PORT, AIO_USER, AIO_KEY) # Subscribed messages will be delivered to this callback client.set_callback(sub_cb) client.connect() client.subscribe(AIO_CONTROL_FEED) print("Connected to %s, subscribed to %s topic" % (AIO_SERVER, AIO_CONTROL_FEED)) pycom.rgbled(0x00ff00) # Status green: online to Adafruit IO try: # Code between try: and finally: may cause an error # so ensure the client disconnects the server if # that happens. while 1: # Repeat this loop forever client.check_msg( ) # Action a message if one is received. Non-blocking. send_random() # Send a random number to Adafruit IO if it's time. finally: # If an exception is thrown ... client.disconnect() # ... disconnect the client and clean up. client = None wlan.disconnect() wlan = None pycom.rgbled(0x000022) # Status blue: stopped print("Disconnected from Adafruit IO.")
# subscribe 消息 def on_subscribe(): mqttClient.set_callback(on_message_come) mqttClient.subscribe(Topic, qos=1) def sub_cb(topic, msg): print((topic, msg)) codey.wifi.start('Maker-guest', 'makeblock') codey.led.show(0, 0, 0) while True: if codey.wifi.is_connected(): on_mqtt_connect() on_subscribe() codey.led.show(0, 0, 255) while True: if True: # Blocking wait for message on_publish("/sensors/temperature/home", str(38), qos=1) mqttClient.wait_msg() else: # Non-blocking wait for message mqttClient.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) else: codey.led.show(0, 0, 0)
def main(): global colour global connected_wifi c = MQTTClient(CLIENT_ID, SERVER, user=USERNAME, password=PASSWORD, port=PORT) c.set_callback(sub_cb) c.connect() np[0] = (100,100,100) np.write() c.subscribe(COLOUR_TOPIC) c.subscribe(TEST_TOPIC) c.publish(PUB_TOPIC, "I have connected to "+connected_wifi+" and waiting for a colour code!") while True: c.check_msg() if state ==1: if button.value() == 0: time.sleep_ms(20) while button.value() == 0: for x in range(0, 125): if button.value() == 0: colour = (125,x,0) np[0] = colour np.write() time.sleep_ms(10) for x in range(125, -1, -1): if button.value() == 0: colour = (x,125,0) np[0] = colour np.write() time.sleep_ms for x in range(0, 125): if button.value() == 0: colour = (0,125,x) np[0] = colour np.write() time.sleep_ms(10) for x in range(125, -1, -1): if button.value() == 0: colour = (0,x,125) np[0] = colour np.write() time.sleep_ms(10) for x in range(0, 125): if button.value() == 0: colour = (x,0,125) np[0] = colour np.write() time.sleep_ms(10) for x in range(125, -1, -1): if button.value() == 0: colour = (125,0,x) np[0] = colour np.write() time.sleep_ms(10) message = "{\"red\":" +str(colour[0]) + ", \"green\": " + str(colour[1]) + ",\"blue\": " + str(colour[2])+"}" c.publish(COLOUR_TOPIC, message) time.sleep_ms(50) if state ==2: rainbow() c.disconnect() np[0] = (0,0,0) np.write()
print("network configuration:", wlan.ifconfig()) # WolkAbout setup MQTT_CLIENT = MQTTClient(CLIENT_ID, wolk.HOST, wolk.PORT, wolk.DEVICE_KEY, wolk.DEVICE_PASSWORD) WOLK_DEVICE = wolk.WolkConnect(MQTT_CLIENT, handle_actuation, get_actuator_status) SLEEP_INTERVAL_MS = 20 try: WOLK_DEVICE.connect() WOLK_DEVICE.publish_actuator_status("SW") LOOP_COUNTER = 0 while True: LOOP_COUNTER += 1 try: MQTT_CLIENT.check_msg() except OSError as os_e: # sometimes an 'empty socket read' error happens # and that needlessly kills the script pass if LOOP_COUNTER % 3000 == 0: # every 60 seconds WOLK_DEVICE.publish_actuator_status("SW") LOOP_COUNTER = 0 sleep_ms(SLEEP_INTERVAL_MS) except Exception as e: WOLK_DEVICE.disconnect() print_exception(e)
chr1 = srv1.characteristic(uuid=b'ab34567890123456', value=2) #chr2 = srv1.characteristic(uuid=b'ab34567890123465', value=2) def char1_cb(chr, xx): print("Write request with value = {}".format(chr.value())) topic = '' sub_cb(topic, chr.value()) char1_cb = chr1.callback(trigger=Bluetooth.CHAR_WRITE_EVENT, handler=char1_cb, arg=chr1) i = 0 # Main Program while True: if p_in_Button() == 0: # MQTT_C.publish(MQTT_Topic6,str(0)) # time.sleep_ms(200) MQTT_C.publish(MQTT_Topic1, str(mp.temperature())) time.sleep_ms(200) MQTT_C.publish(MQTT_Topic4, str(si.humid_ambient(t_ambient))) time.sleep_ms(200) # MQTT_C.publish(MQTT_Topic5,"Altitude: " + str(mp.altitude())) # time.sleep_ms(200) # MQTT_C.publish(MQTT_Topic6,str(i)) # time.sleep_ms(200) i = 0 MQTT_C.check_msg()
print("mqtt connected") while True: try: while not wlan.isconnected(): # if connection lost wifi_connect() # reconnect to wifi # re connect to mqtt server client.connect() client.subscribe(topic="saleh_shalabi/feeds/App") client.subscribe(topic="saleh_shalabi/feeds/reset_Plac") client.subscribe(topic="saleh_shalabi/feeds/reset_Cars") print("Conncetion lost, but istablished agane") else: client.check_msg() # check msg on mqtt if s.recv( 64 ) == b'Car_IN': # if a msg by lora from a device and its "Car_IN" print(s.recv(64)) if Places == 0: # check the values print("where Are u going to park") else: # new values if there is places Cars_TOT = Cars_TOT + 1 Places = Places - 1 if s.recv( 64 ) == b'Car_OUT': # if a msg by lora from a device and its "Car_OUT" print(s.recv(64))
def inviaDati(durataIntervallo,valoreMisurato): def sub_cb(topic, msg): print(msg) #seriale della Wipy/codice univoco assegnato dai progettisti serialWipy = "000001" print("INIZIO INVIO DATI") wlan = WLAN(mode=WLAN.STA) wlan.connect("VLLC", auth=(WLAN.WPA2, "vallavlciol"), timeout=5000) while not wlan.isconnected(): machine.idle() print("Connected to WiFi\n") #CODICE GET DATA GIUSTA ITA rtc = machine.RTC() rtc.ntp_sync("it.pool.ntp.org") utime.sleep_ms(750) #print('\nRTC Set from NTP to UTC:', rtc.now()) oraItalia = rtc.now() mese = oraItalia[1] if(mese >= 11 or mese <= 3): oraDaModificare = oraItalia[3]+1 oraItalia = [oraItalia[0],oraItalia[1],oraItalia[2],oraDaModificare,oraItalia[4],oraItalia[5],oraItalia[6],oraItalia[7]] print("Ora esatta ", oraItalia) #FINE CODICE DATA ITA #pycom.rgbled(0x00ff00) client = MQTTClient("wipy", "io.adafruit.com",user="******", password="******", port=1883) client.set_callback(sub_cb) client.connect() client.subscribe(topic="bldg/feeds/bldgdata") print("Sending value") #imp diff tra (tuple) e [list] -> posso accedere a tuple con tupla[2] ma non a lista (lista si append) #CI CALCOLIAMO DATA INIZIO A PARTIRE DA durataIntervallo IN SECONDI e dataFine #ESEMPIO IF 4680 sec -> 78min -> è intero-> calcolo le ore perchè >60 -> 78/60 = 1,3 = 1 ora -> calcolo i minuti 78-60*1 = 18 minuti -> calcolo i secondi 4680-18*60-3600*1 = 0 secondi come previsto #ESEMPIO ELSE 3125 sec -> 3125/60 = 52,0833333333 = 52 minuti -> minore di 60, calcolo i secondi -> 3125-60*52 ? 5 secondi numeroOre = 0 numeroSecondi = 0 numeroMinuti = durataIntervallo/60 interoNumeroMinuti = int(numeroMinuti) if(interoNumeroMinuti>=60): numeroOre = int(interoNumeroMinuti/60) numeroMinuti = interoNumeroMinuti-(60*numeroOre) numeroSecondi = durataIntervallo-60*numeroMinuti-3600*numeroOre else: if (interoNumeroMinuti==0): numeroMinuti = 0 numeroOre = 0 #hai minuti minori di 60 numeroSecondi = durataIntervallo else: numeroOre = 0 numeroMinuti = interoNumeroMinuti numeroSecondi = durataIntervallo-(60*interoNumeroMinuti) dataFine=oraItalia #ho QUESTO, HO DURATA DA ALTRO SCRIPT E CALCOLO DATA INIZIO sottraendo A DATA FINE la DURATA secondiInizio = dataFine[5]-numeroSecondi minutiInizio = dataFine[4]-numeroMinuti oreInizio = dataFine[3]-numeroOre #controlli per evitare anomalie (es swcondi negativi) -> se trovo nidificati dei negativi, scalo tutte e tre le variabili if (secondiInizio<0): secondiInizio = 60+secondiInizio #sottrazione minutiInizio = minutiInizio-1 if (minutiInizio<0): oreInizio = oreInizio-1 minutiInizio = 60+minutiInizio #if (oreInizio < 0): #evito per il momento questa condizione dataInizio=[(dataFine[0]-0),(dataFine[1]-0),(dataFine[2]-0),oreInizio,minutiInizio,secondiInizio,0,None] msg=serialWipy+"-"+str(dataInizio)+"-"+str(dataFine)+"-"+str(durataIntervallo)+"-"+str(valoreMisurato)+"\n\n" #per ogni messaggio aggiungiamo: seriale, data inizio intervallo, data fine intervallo, dimensione intervallo (in s) valore misurazione in intervallo print(msg) client.publish(topic="bldg/feeds/bldgdata", msg=msg) time.sleep(1) #print("Sending OFF") #client.publish(topic="bldg/feeds/bldgdata", msg="OFF") client.check_msg() print("FINE INVIO DATI")
def on_start(): ssid = '' #nome della rete password = '' #password #Connessione alla rete print('Connessione al Wi-Fi %s...' % ssid) halo.wifi.start(ssid=ssid, password=password, mode=halo.wifi.WLAN_MODE_STA) while not halo.wifi.is_connected(): pass print('Connessione Wi-Fi %s effettuata' % ssid) halo.led.show_ring( 'orange yellow green cyan blue purple blue cyan green yellow orange red' ) #Segnale di riuscita time.sleep(3) halo.led.off_all() #Dichiarazioni delle credenziali per il protocollo MQTT client_id = 'Client Halocode' broker = 'test.mosquitto.org' port = 8883 topicSensor = 'Olimpiadi di Robotica NDS Sensori' topicMotor = 'Olimpiadi di Robotica NDS Motori' #Quando riceve un messaggio l'halocode, a seconda di cosa riceve, farà determinati colori coi led. #E' incentrato sui comandi dei motori inviati dall'app def mqtt_callback(topic, msg): msgDecoded = msg.decode('utf-8') print('Messaggio ricevuto: %s' % msg.decode('utf-8')) if msgDecoded == 'forward': halo.led.show_ring( 'blue orange black black black black black black black orange blue orange' ) halo.led.off_all() elif msgDecoded == 'back': halo.led.show_ring( 'black black black orange blue orange blue orange black black black black' ) halo.led.off_all() elif msgDecoded == 'left': halo.led.show_ring( 'black black black black black black orange blue orange blue orange black' ) halo.led.off_all() elif msgDecoded == 'right': halo.led.show_ring( 'orange blue orange blue orange black black black black black black black' ) halo.led.off_all() elif msgDecoded == 'counterclockwise': halo.led.show_single(12, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(1, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(2, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(3, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(4, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(5, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(6, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(7, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(8, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(9, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(10, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(11, 255, 255, 255) time.sleep(0.0001) halo.led.off_all() elif msgDecoded == 'clockwise': halo.led.show_single(12, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(11, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(10, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(9, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(8, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(7, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(6, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(5, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(4, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(3, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(2, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(1, 255, 255, 255) time.sleep(0.0001) halo.led.off_all() #Inizializzazione della variabile per MQTT cli = MQTTClient(client_id, broker, user=None, password=None, port=port, ssl=True, keepalive=60000) cli.set_callback(mqtt_callback) #Connessione al broker con interfaccia di riuscita o fallimento print('Connessione al broker %s...' % broker) done = False while not done: try: cli.connect() print('Connessione al broker %s effettuata' % broker) done = True halo.led.show_ring( 'orange yellow green cyan blue purple blue cyan green yellow orange red' ) time.sleep(3) halo.led.off_all() except: print( "Qualcosa e' andato storto durante la connessione, riprovo la connessione..." ) cli.disconnect() halo.led.show_ring( 'red red red red red red red red red red red red') time.sleep(2) halo.led.off_all() #Iscrizione al topic cli.subscribe(topicMotor) print('In ascolto sul topic "%s"...' % topicMotor) #Ciclo infinito dove halocode manderà in continuazione i valori dei sensori firstTime = True done = False while not done: cli.check_msg() halo.pin0.write_digital(0) time.sleep(0.00028) Vo = halo.pin3.read_analog() time.sleep(0.00004) halo.pin0.write_digital(1) VCalc = Vo * (5.0 / 1024.0) receivedPM = 0.17 * VCalc - 0.1 windTension = halo.pin2.read_analog() * 1.5 / 1024 windSpeed = windTension * 32.4 / 1.5 msg = '{"PM2.5": %s, "VelVento": %s, "Flag": True}' % (receivedPM, windSpeed) print('Invio del messaggio %s ...' % msg) cli.publish(topicSensor, msg, qos=1) print('Messaggio inviato')
class Device(object): def __init__(self, device_token): self.__device_token = bytes(device_token, 'utf-8') self.__variables = None self.__diag_variables = None self.__mqtt = None self.__bindings = dict() def __publish(self, topic, payload=None): if payload is None: return False msg = json.dumps({'payload': payload}) self.__mqtt.publish(C4R_TOPIC_FORMAT % (self.__device_token, topic), msg, qos=1) print(topic, "<--", msg) def __on_message(self, topic, msg): print(topic.decode().rsplit('/')[-1], "-->", msg.decode()) data = json.loads(msg) for var_name, callback in self.__bindings.items(): if var_name in data.keys(): ret = callback(data[var_name]) self.__publish('data', {var_name: ret}) def connect(self): self.__mqtt = MQTTClient(client_id=self.__device_token, server=C4R_BROKER_HOST, port=C4R_BROKER_PORT) self.__mqtt.set_callback(self.__on_message) try: self.__mqtt.connect() self.__mqtt.subscribe(C4R_TOPIC_FORMAT % (self.__device_token, 'commands'), qos=1) except Exception as e: print("[Exception] %s: %s" % (type(e).__name__, e)) return False return True def declare(self, variables): self.__variables = variables def declare_diag(self, diag_variables): self.__diag_variables = diag_variables def publish_config(self): cfg = [] for var_name, var_config in self.__variables.items(): cfg.append({'name': var_name, 'type': var_config['type']}) self.__bindings[var_name] = var_config['bind'] self.__publish('config', cfg) def publish_diag(self): self.__publish('diagnostics', self.__diag_variables) def publish_data(self): for var_name, callback in self.__bindings.items(): self.__variables[var_name]['value'] = \ callback(self.__variables[var_name]['value']) cfg = {var_name: var_config['value'] for var_name, var_config in self.__variables.items()} self.__publish('data', cfg) def check_commands(self): self.__mqtt.check_msg()
machine.reset() PING = time.time() + 30 # If we have a slave talk to it every second if (time.time() >= HEARTBEAT): HEARTBEAT = time.time() + 1 rgbled(0x0F, 0x00, 0x0F) debug("mem_free: %d" % gc.mem_free(), 1) if (ourSlave['twcid'] != None): send_master_heartbeat("limit", ourSlave['charge_rate']) # send_master_heartbeat("limit", 15) # check for any new messages try: mqtt_client.check_msg() except Exception as e: # any errors here indicate a network disconnection # easiest way to deal for now is simply reset if e.args[0] not in (errno.ENOENT,): raise debug("mqtt check_msg failed", 0) time.sleep(1) machine.reset() else: debug("no mqtt messages waiting", 2) if (ERRORS > 10): rgbled(0xFF, 0x00, 0x00) try: mqtt_client.publish(topic=TOPIC_MASTER, msg="soft_reset")
from mqtt import MQTTClient import machine import time import ubinascii from machine import Timer CLIENT_ID = ubinascii.hexlify(machine.unique_id()) SERVER = "test.mosquitto.org" #SERVER = "broker.hivemq.org" PORT = 1883 def push_heartbeat(): c_mqtt.connect() c_mqtt.publish(b"mhermans/heartbeat", b'1') c_mqtt.disconnect() global c_mqtt c_mqtt = MQTTClient(client_id = CLIENT_ID, server = SERVER, port = PORT) while True: c_mqtt.check_msg() # main loop # pub: heartbeat every 5sec. # sub: print every msg immediatly
nets = wlan.scan() for net in nets: print(net) if net.ssid == '@305': # ชื่อ wifi print('[wifi] found.... %s' % net.ssid) wlan.connect(net.ssid, auth=(net.sec, 'xxxxxxxx'), timeout=10000) # password while not wlan.isconnected(): machine.idle() print('[wifi] connected..!!') break # # subscribe and publish to MQTT def sub_cb(topic, msg): # callback เพื่อบอกว่าเวลาได้ค่ามา ให้ทำอะไรต่อ print(msg) client = MQTTClient("59070174", "broker.mqttdashboard.com") client.set_callback(sub_cb) client.connect() client.subscribe(topic="kmitl/one") while True: # print(p_input() / 4095) p_output.write(p_input() / 4095) # analog output client.publish(topic="kmitl", msg="%f" % (p_input() / 4095)) client.check_msg() # ตรวจสอบว่ามี messages เข้ามาหรือเปล่า time.sleep(1)
class MyMqtt: DELAY = 2 DEBUG = True def __init__(self): with open("secret.json", "r") as f: secrets = ujson.load(f) self.broker = "io.adafruit.com" # self.broker = "10.0.0.137" self.secrets = secrets self.user = self.secrets["MQTT_USER"] self.password = self.secrets["MQTT_PASSWORD"] self.group = self.secrets["MQTT_GROUP"] print("User: {}, Password: {}, Group: {}".format( self.user, self.password, self.group)) self.client = MQTTClient("device_id", "io.adafruit.com", user=self.user, password=self.password, port=1883, keepalive=1) self.client.set_callback(sub_cb) self.client.connect() # This can fail #self.client.subscribe(topic="{}/feeds/{}.{}".format( # self.user, self.group, "led")) def log(self, in_reconnect, e): if self.DEBUG: if in_reconnect: print("mqtt reconnect: %r" % e) else: print("mqtt: %r" % e) def reconnect(self): try: self.client.disconnect() # This can fail except OSError as e: self.log(True, "MQ.disconnect {}".format(e)) try: self.client = MQTTClient("device_id", "io.adafruit.com", user=self.user, password=self.password, port=1883, keepalive=1) except OSError as e: self.log(True, "MQ.__INIT {}".format(e)) try: self.client.connect() # This can fail except OSError as e: self.log(True, "MQ.connect {}".format(e)) def send_value(self, value, feed): topic = "{}/feeds/{}.{}".format(self.user, self.group, feed) print(" SV topic = |{}|".format(topic)) msg = '{}'.format(value) print(" SV msg = |{}|".format(msg)) s = self.client.publish(topic=topic, msg=msg) return s def poll(self): self.client.check_msg()
import time, network from mqtt import MQTTClient SSID = '' # Network SSID KEY = '' # Network key # Init wlan module and connect to network print("Trying to connect... (may take a while)...") wlan = network.WINC() wlan.connect(SSID, key=KEY, security=wlan.WPA_PSK) # We should have a valid IP now via DHCP print(wlan.ifconfig()) client = MQTTClient("openmv", "test.mosquitto.org", port=1883) client.connect() def callback(topic, msg): print(topic, msg) # must set callback first client.set_callback(callback) client.subscribe("openmv/test") while (True): client.check_msg() # poll for messages. time.sleep(1000)
def switchToParallelMQTT(): # BEGIN SETTINGS AIO_CLIENT_ID = "Charles" AIO_SERVER = "203.101.227.137" AIO_PORT = 1883 AIO_USER = "******" AIO_KEY = "qut" AIO_CONTROL_FEED = "fipy/test" AIO_RANDOMS_FEED = "fipy/randoms" # Setup thingsboard connection THINGSBOARD_HOST = '203.101.225.130' QUT01_ACCESS_TOKEN = 'test12345' # FUNCTIONS # Function to respond to messages from Adafruit IO def sub_cb(topic, msg): # sub_cb means "callback subroutine" print((topic, msg)) # Outputs the message that was received. Debugging use. if msg == b"ON": # If message says "ON" ... pycom.rgbled(0xffffff) # ... then LED on elif msg == b"OFF": # If message says "OFF" ... pycom.rgbled(0x000000) # ... then LED off else: # If any other message is received ... print("Unknown message" ) # ... do nothing but output that it happened. def send_readings(): try: latlon, velocity, gpsQ, height, GMT, PDOP, HDOP, VDOP, uniqsatNum = parsedReadings.__next__( ) except: latlon = velocity = gpsQ = height = GMT = PDOP = HDOP = VDOP = uniqsatNum = 'Error occurred, please restart FiPy...' gnssReadings = "Laitude and Longitude: {0}, Velocity: {1}, Orthometric height: {2}, Time in GMT: {3}, GPS Quality indicator: {4}, Number of active satellites: {5}, PDOP:{6} HDOP:{7} VDOP:{8}"\ .format(latlon, velocity, gpsQ, height, GMT, uniqsatNum, PDOP, HDOP, VDOP) if 'Error' in latlon: location = {'lat': latlon, 'lon': latlon} elif 'N/A' in latlon: location = {'lat': latlon, 'lon': latlon} else: temp1 = latlon.split(";") Lat = float(temp1[0].replace("S", "-").replace("N", "")) Lon = float(temp1[1].replace("E", "").replace("W", "-")) location = {'lat': float(Lat), 'lon': float(Lon)} try: print("Publishing: {0} to {1} ... ".format(gnssReadings, AIO_RANDOMS_FEED), end='') client.publish(topic=AIO_RANDOMS_FEED, msg=str(gnssReadings)) print("DONE") time.sleep(0.5) client2.publish(topic='v1/devices/me/attributes', msg=json.dumps(location)) print("coordinate sent: {0}".format(latlon)) except Exception: print("FAILED") finally: print( "------------------------------------------------------------------------------" ) client2 = MQTTClient(client_id="test", server=THINGSBOARD_HOST, port=1883, user=QUT01_ACCESS_TOKEN, password=QUT01_ACCESS_TOKEN, keepalive=60) #Connect to Thingsboard using default MQTT port and 60 seconds keepalive intervals client2.connect() print(">>>connected to things platform<<<") pycom.rgbled(0x00ff00) #green # Use the MQTT protocol to connect to Adafruit IO client = MQTTClient(AIO_CLIENT_ID, AIO_SERVER, AIO_PORT, AIO_USER, AIO_KEY) # Subscribed messages will be delivered to this callback client.set_callback(sub_cb) client.connect() client.subscribe(AIO_CONTROL_FEED) print("Connected to %s, subscribed to %s topic" % (AIO_SERVER, AIO_CONTROL_FEED)) pycom.rgbled(0x00ff00) # Status green: online to Adafruit IO try: while True: # Repeat this loop forever client.check_msg( ) # Action a message if one is received. Non-blocking. send_readings() # Send current GNSS readings time.sleep(3) # publish every 3 seconds except KeyboardInterrupt: # catches the ctrl-c command, which breaks the loop above print("Continuous polling stopped") finally: # If an exception is thrown ... client.disconnect() # ... disconnect the client and clean up. client2.disconnect() client2 = None client = None global wlan # add globale so that wlan can be modified wlan.disconnect() wlan = None pycom.rgbled(0x000022) # Status blue: stopped print("MQTT stopped")
######################################## # set up mqtt client ##### ######################################## client = MQTTClient("Pycom", "io.adafruit.com",user="******", password="******", port=1883) client.connect() location = "kitchen" ######################################## # Initialise button on expansion board # ######################################## Pin.exp_board.G17 p_in = Pin(Pin.exp_board.G17, mode=Pin.IN, pull = Pin.PULL_UP) Pin.exp_board.G17.id() ######################################## # Check if the button is pressed # # Trigger email if button pressed # ######################################## while True: if p_in() == 0: print("Button pressed", p_in()) client.publish(topic="EmmaNiBhriain/feeds/indoor_location", msg=location) client.check_msg() print("location published :", location ) time.sleep(3) else: pass
# Init wlan module and connect to network print("Trying to connect... (may take a while)...") wlan = network.WINC() wlan.connect(SSID, key=KEY, security=wlan.WPA_PSK) # We should have a valid IP now via DHCP print(wlan.ifconfig()) #设置MQTT回调函数,有信息时候执行 def MQTT_callback(topic, msg): print('topic: {}'.format(topic)) print('msg: {}'.format(msg)) SERVER = 'mqtt.p2hp.com' PORT = 1883 CLIENT_ID = '01Studio-OpenMV' # 客户端ID TOPIC = '/public/01Studio/1' # TOPIC名称 client = MQTTClient(CLIENT_ID, SERVER, PORT) client.set_callback(MQTT_callback) #配置回调函数 client.connect() client.subscribe(TOPIC) #订阅主题 while (True): client.check_msg() #检测是否收到信息,收到则执行打印。 time.sleep(300) #设置接收间隔