def main(): btn = machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_UP) led = machine.Pin(2, machine.Pin.OUT) #D4 if btn.value(): led.value(1) sta_if = network.WLAN(network.STA_IF) if not sta_if.isconnected(): sta_if.active(True) sta_if.connect('ESL_Lab1', 'wifi@esl') while not sta_if.isconnected(): pass led.value(0) dhtValue = dht.DHT22(machine.Pin(4)) dhtValue.measure() led.value(1) c = MQTTClient(CLIENT_ID, SERVER) c.connect() DHTbuff = "%.2f,%.2f" % (dhtValue.humidity(), dhtValue.temperature()) c.publish(TOPIC, DHTbuff) led.value(0) time.sleep(3) # print ("Data temp : "+str(dhtValue.temperature())+" humidity : "+str(dhtValue.humidity())) rtc = machine.RTC() rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) rtc.alarm(rtc.ALARM0, 2000) machine.deepsleep()
def activateDeepSleep(self, value, millisec): # print (millisec) if value: c = MQTTClient(CLIENT_ID, SERVER) c.connect() dhtValue = dht.DHT22(machine.Pin(4)) dhtValue.measure() c.publish(TOPIC, b""+str(dhtValue.temperature())+","+str(dhtValue.humidity())) time.sleep(3) # print ("Data temp : "+str(dhtValue.temperature())+" humidity : "+str(dhtValue.humidity())) set_deepSleep(millisec)
def connect_and_subscribe(): global client client = MQTTClient(machine_id, broker) client.set_callback(callback) client.connect() print("Connected to {}".format(broker)) for topic in (b'config', b'control'): t = topic_name(topic) client.subscribe(t) print("Subscribed to {}".format(t))
def main(server=SERVER): c = MQTTClient(CLIENT_ID, server) c.connect() print("Connected to %s, waiting for button presses" % server) while True: while True: if button.value() == 0: break time.sleep_ms(20) print("Button pressed") c.publish(TOPIC, b"toggle") time.sleep_ms(200) c.disconnect()
def SendToThingspeak(host, api_key, channel_id, result): from umqtt.simple import MQTTClient try: client = MQTTClient('umqtt_client', host) topic = 'channels/%s/publish/%s' % (channel_id, api_key) payload = ( ''.join(['&field%d=%.2f' % (x + 1, result[x]) for x in range(8)]) + '&status=Pressure: %s; Forecast: %s; Accuracy: %s percent' % (result[10], result[9], result[8]))[1:] client.connect() client.publish(topic, payload) client.disconnect() print('Sent data to Thingspeak via MQTT') except: print('Failed to send data to Thingspeak via MQTT')
def main(server=SERVER): c = MQTTClient(CLIENT_ID, server) c.connect() threshold = 256 print("Connected to %s, waiting for ring" % server) while True: while True: if piezo.value() > threshold: break time.sleep_ms(20) print("Ring") c.publish(TOPIC, b"ON") time.sleep_ms(200)
class AWSShadow: def __init__(self, client_id=imei, hostname=aws_endpoint, sslp=ssl_params): self.client = MQTTClient(client_id, hostname, ssl=True, ssl_params=sslp) self.connected = False def is_connected(self): return self.connected def connect(self): try: print("trying MQTT") self.client.connect() self.connected = True print("connected to MQTT") except OSError as e: print_exception(e) self.connected = False @staticmethod def _get_on_off(value): if value: return 'on' else: return 'off' def update(self, light, nightlight, lumens): try: print("updating shadow") telemetry = {"lumens": lumens} state = { "state": { "reported": { "light_state": self._get_on_off(light), "night_light_state": self._get_on_off(nightlight) }, "desired": None } } telemetry_path = "smartswitch/{}/lumens/".format(imei) shadow_path = "$aws/things/{}/shadow/".format(imei) print(shadow_path) self.client.publish(telemetry_path, ujson.dumps(telemetry)) print("updated {}".format(telemetry_path)) self.client.publish(shadow_path + "update", ujson.dumps(state)) print("updated {}".format(shadow_path)) return True except OSError: self.connected = False
def main(server="192.168.0.10"): ap_if = network.WLAN(network.AP_IF) ap_if.active(False) sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect('EEERover', 'exhibition') gas = gas_sensor_setup(5, 4, 100000) th = th_sensor_setup(5, 4) # pre = pre_sensor_setup(5, 4, 100000) time.sleep_ms(500) c = MQTTClient(machine.unique_id(), server) c.connect() while True: no2_val, co_val = gas_sensor_read(gas) t_val, h_val = th_sensor_read(th) # pre_val = pre_sensor_read(pre) send_msg = { 'NO2': no2_val, 'Temperature': t_val, 'Humidity': h_val, 'Pressure': pre_val, 'CO': co_val } print("Temp ", t_val) print("no2 ", no2_val) print("Pressure ", pre_val) print("hum ", h_val) print("co", co_val) c.publish(b"esys/Thom&Doug/test", bytes(json.dumps(send_msg), 'utf-8')) time.sleep_ms(5000) c.disconnect()
def send_message(): client = MQTTClient("test1", "calupietru.duckdns.org", port=1883, user="******", password="******") client.connect() m = get_data() k = kg() mem = gc.mem_free() message = { "espid": "Ascea", "timestamp": None, "memoria_libera": str(mem), "temperatura": round(m[1], 1), "umidita": round(m[0], 1), "peso": round(k, 1), } message["timestamp"] = int(time.time()) client.publish("/maia/1", json.dumps(message)) client.disconnect()
def __init__(self, broker, ssl, username, password, prefix='', client_id=None): if client_id is None: client_id = ubinascii.hexlify(machine.unique_id()).decode() self.client_id = client_id self.full_client_id = '{}{}'.format(prefix, client_id) print('Using MQTT client_id "{}", full_client_id "{}"'.format( self.client_id, self.full_client_id)) self.broker = broker self.client = MQTTClient(self.full_client_id, self.broker, ssl=ssl, user=username, password=password)
async def mqtt_task(mqtt_queue, config): broker = config['broker'] client_id = b'esp32_' + ubinascii.hexlify(machine.unique_id()) client = MQTTClient(client_id, broker) client.connect() try: while True: msg = await mqtt_queue.get() data = msg[1] if msg[0] == 'pm': data['timestamp'] = utime.time() print(ujson.dumps(data)) client.publish('pm', bytearray(ujson.dumps(data))) elif msg[0] == 'hum/tmp': client.publish('hum/tmp', bytearray(data)) else: print('unkown message: ' + msg[0]) except asyncio.CancelledError: return
def main(timer_id=None): led = Pin(5, Pin.OUT) i2c = I2C(scl=Pin(22), sda=Pin(21), freq=10000) bme = BME280(i2c=i2c) mqtt = MQTTClient(CLIENT_ID, SERVER, 1883, USER, PASS) try: mqtt.connect() js = json.dumps({ "temperature": bme.temperature[:-1], "humidity": bme.humidity[:-1], "pressure": bme.pressure[:-3] }) led.off() print(timer_id, js) mqtt.publish(TOPIC, js) led.on() except Exception as ex: print(ex) finally: mqtt.disconnect() gc.collect()
def main(): """Measure and talk to MQTT broker.""" d = DHT11(machine.Pin(0)) SERVER = '192.168.1.8' CLIENT_ID = ubinascii.hexlify(machine.unique_id()) TOPIC_HUMIDITY = b'kgrund/fukt' TOPIC_TEMPERATURE = b'kgrund/temp' c = MQTTClient(CLIENT_ID, SERVER) c.connect() print('Connected to {}'.format(SERVER)) while True: """Measure and then publish values to the broker every 20 seconds.""" try: d.measure() humidity = bytes(str(d.humidity()), 'ascii') temperature = bytes(str(d.temperature()), 'ascii') c.publish(TOPIC_HUMIDITY, humidity) c.publish(TOPIC_TEMPERATURE, temperature) except Exception: print('Cant find DHT, will try again') time.sleep(20)
def publish_test(client_id=CLIENT_ID, hostname=AWS_ENDPOINT, sslp=SSL_PARAMS): """ Connects to AWS, publishes a message and disconnects. :param client_id: Unique identifier for the device connected. :param hostname: AWS hostname to connect to. :param sslp: SSL certificate parameters. """ # Connect to AWS. client = MQTTClient(client_id, hostname, ssl=True, ssl_params=sslp) print("- Connecting to AWS... ", end="") client.connect() print("[OK]") # Publish message. print("- Publishing message... ", end="") client.publish(TOPIC, '{"message": "%s"}' % MESSAGE) print("[OK]") # Disconnect. client.disconnect() print("- Done")
def main(): print("Writing") write_morse("PARIS") print("") print("Reading") message = read_morse() print("Got: " + message) print("Connecting") client = MQTTClient(CONFIG['client_id'], CONFIG['broker']) client.connect() print("Connected to {}".format(CONFIG['broker'])) print("Publishing to {}".format(CONFIG['topic'])) datastr = "ts=" + str(utime.ticks_ms()) + "&val=" + message client.publish('{}/{}'.format(CONFIG['topic'], CONFIG['client_id']), bytes(datastr, 'utf-8')) client.disconnect()
def mqtt_sub(server, topic, callback): global subscribe_thread global subscribe_client c = MQTTClient("cokey_mqtt_client", server) c.set_callback(callback) if (True != c.connect()): return False if (True != c.subscribe(topic)): return False subscribe_client = c if (not subscribe_thread): _thread.start_new_thread(mqtt_sub_loop, ()) subscribe_thread = True return True
def init_client(): global client print( "Trying to connect to mqtt broker." ) wifi.connect() try: client = MQTTClient(config.mqtt_client_id, config.mqtt_broker, user=config.mqtt_user, password=config.mqtt_password) client.connect() print("Connected to {}".format(config.mqtt_broker)) t = config.mqtt_topic + b"/#" client.subscribe(t) print("Subscribed to %s topic" % t) except: print( "Trouble to init mqtt." )
def get_client(): #Create our MQTT client. client = MQTTClient(client_id=DEVICE_ID, server=MQTT_BRIDGE_HOSTNAME, port=MQTT_BRIDGE_PORT) client.set_callback(on_message) try: client.connect() except Exception as err: print(err) raise(err) return client
def temperature(): while (True): try: d = dht.DHT22(machine.Pin(4)) d.measure() c = MQTTClient('client', '192.168.4.4') c.connect() c.publish('temperature', str(d.temperature()) + ' ' + str(d.humidity())) time.sleep(1800) except: time.sleep(10)
def send_data(server=SERVER, topic=b'foo_topic', data=b'Hello!'): """Send data via MQTT. Keyword arguments: server -- IP of the MQTT Broker. topic -- The MQTT topic. data -- The data. Test connection on the broker: mosquitto_sub -t foo_topic """ try: client = MQTTClient("umqtt_client", server) client.connect() client.publish(topic, data) client.disconnect() except e: print('Data logging via MQTT failed:') print(e)
class MQTTManager: """Manages communication to/from the MQTT broker""" def __init__(self): self.topic = "esys/dadada/" if client_id == "": self.client_id = machine.unique_id() else: self.client_id = client_id self.broker = broker self.client = MQTTClient(self.client_id, self.broker) self.timestamp = "" self.client.set_callback(self.update_timestamp()) self.client.connect() self.client.subscribe("esys/time") def publish(self, topic, message): """publish message to the broker with topic""" self.client.publish(topic, message) def update_timestamp(self, topic, message): """callback to update timestamp""" self.timestamp = message
def connect_and_subscribe(): server = CONFIG["MQTT_HOSTNAME"] client = MQTTClient( client_id=CONFIG["MQTT_CLIENT_ID"], server=server, user=CONFIG["MQTT_USERNAME"], password=CONFIG["MQTT_PASSWORD"], ) print("Connecting to", server) client.set_callback(update_state_from_mqtt_message) client.connect(clean_session=True) print("Connected to %s MQTT broker" % server) client.subscribe(TOPIC) print('Subscribed to topic "%s"' % str(TOPIC)) return client
def main(): topic = configuration.get('topic') submit_interval = configuration.get('submit_interval') exception_timeout = configuration.get('exception_reset_timeout') mqtt_server_ip = configuration.get('mqtt_server_ip') client_id = ubinascii.hexlify(machine.unique_id()) try: client = MQTTClient(client_id, mqtt_server_ip) client.connect() print('Connected to {}'.format(mqtt_server_ip)) temperature, humidity = sensor.measure() info = {'temperature': temperature, 'humidity': humidity} client.publish(topic, ujson.dumps(info)) client.disconnect() print('sleeping deeply for {} seconds'.format(submit_interval)) # deep sleep argument in microseconds esp.deepsleep(submit_interval * 1000000) except Exception as e: print(('Caught exception, {}' 'resetting in {} seconds...').format(e, exception_timeout)) time.sleep(exception_timeout) machine.reset()
def main(server="localhost"): c = MQTTClient("NDC MicroPython controller", server) c.connect() def callback(p): print("PUSHED") c.publish(b"foo_topic", b"UP") e_click = Pin(27, Pin.IN, Pin.PULL_UP) e_click.irq(trigger=Pin.IRQ_FALLING, handler=callback) try: while True: pass finally: c.disconnect()
def main(): client = MQTTClient(client_id, mqtt_server, mqtt_port, mqtt_user, mqtt_password) client.connect() print("Connected to {}".format(mqtt_server)) while True: #d = dht.DHT11(machine.Pin(5)) # NodeMCU D2 d = dht.DHT22(machine.Pin(5)) # NodeMCU D2 d.measure() data = d.temperature() # eg. 23 (°C) client.publish('{}/{}'.format(topic, client_id), bytes(str(data), 'utf-8')) print('sensor temperature: {}'.format(data)) time.sleep(2)
def init_all(): #declare so u can modify the glob vars global Wifi_SSID, Wifi_Pass, Devices, Devices_Data, Mqtt_User, Mqtt_Pass, MQTT_Client, Motion_Detectors, Motion #get config file with open("config_web/Configuration.json", 'r') as f: conf = f.read() config = json.loads(conf) #Networks Wifi_SSID = config["Used_Net"]['SSID'] Wifi_Pass = config["Used_Net"]["Password"] #Devices Devices = dict(config["Devices"][0]) #Devices_Data is init here so it ease the job of writing data same structure on the config file Devices_Data = dict(config["Devices"][0]) #in Grab_DATA_Devices_Send we don't need these three Devices Devices_Data.pop("Light") Devices_Data.pop("RGB") Devices_Data.pop("MSense") #Declaring interupts for the motion detecters for i in Devices["MSense"]: pir = Pin(i, Pin.IN) pir.irq(trigger=Pin.IRQ_RISING, handler=handle_interrupt) Motion_Detectors.append(pir) #init motion alarm Motion[0] = False Motion[1] = "INIT" #Declaring as list Devices_Data["DHT"] = [] Devices_Data["GSense"] = [] #Mqtt: Get username because we gonna need it after for publishing topics Mqtt_User = config["Mqtt_User"] #Mqtt: client with :clientid , Server ip/domain, username ,password MQTT_ClientID = config["ClientID"] print(config["Mqtt_Server"] + "----" + config["ClientID"]) MQTT_Client = MQTTClient(config["ClientID"], config["Mqtt_Server"], user=config["Mqtt_User"], password=config["Mqtt_Pass"]) #init phonenumbers for send alarm msg Phonenumbers = config["Phonenumbers"]
def publisher(): from umqtt.simple import MQTTClient import time, network from project import d from machine import Pin SERVER = '149.28.147.236' CLIENT_ID = 'esp8266 - A' # 客户端的ID TOPIC1 = b'temperature' # TOPIC的ID TOPIC2 = b'humidity' # TOPIC的ID led = machine.Pin(2, machine.Pin.OUT) try: client = MQTTClient(CLIENT_ID, SERVER) except: print('network error') client.connect() while True: d.measure() temp = d.temperature() hum = d.humidity() print(temp, hum) led.off() time.sleep(0.5) led.on() client.publish(TOPIC2, str(hum)) client.publish(TOPIC1, str(temp)) print('publised @ ', time.time()) time.sleep(5)
def publish_Obs(client_id=CLIENT_ID, hostname=SERVER, keepalive=60): global topic_ToSend global msg_ToSend global obs_publishReady global publish_Success global wdt global tfile_readComplete global mfile_readComplete global timeStart publish_Success = False cnt = 0 wdt.feed() client = MQTTClient(client_id, hostname) issue = client.connect() if issue == 0: while cnt < obs_publishReady: topic = topic_ToSend[cnt] msg = msg_ToSend[cnt] client.publish(topic, msg) wdt.feed() cnt = cnt + 1 wdt.feed() time.sleep(0.5) client.disconnect() if cnt == obs_publishReady: publish_Success = True timeStart = time.ticks_ms() obs_publishReady = 0 topic_ToSend.clear() msg_ToSend.clear() if files_Exist == True and tfile_readComplete == True and mfile_readComplete == True: wdt.feed() deleteFiles() time.sleep(1) createFiles() else: wdt.feed() else: ##client socket connection contained error to post to message que topic_ToSend.append(msg_Topic) msg_ToSend.append(issue) obs_publishReady = obs_publishReady + 1
def publish_message(message) -> None: # message is in binary format print('Publish message: {0}'.format(message)) try: c = MQTTClient( client_id= "smart_uv_light_umqtt_client", # if username/pwd wrong, this will throw Exception server="192.168.1.194", user=b"mosquitto", password=b"mosquitto", ssl=False) if 0 == c.connect(): # 0 is success. c.publish(b"smart_uv_light_status_topic", message) c.disconnect() else: print('Connect to MQTT server failed. ') except OSError as exception: # When machine is just booted, WiFi hasn't been connected yet. Immediately invoke MQTT will throw error. # Instead of tracking startup grace period, just keep code simple by catching and log the error. print('publish_message encountered error {}'.format(exception))
def mqtt_conect(mqtt_conf, alarm_led, switches): print('Connecting to Mqtt server') mqttclient = MQTTClient(client_id, server=mqtt_conf['server'], port=mqtt_conf['port'], user=mqtt_conf['user'], password=mqtt_conf['password']) mqttclient.set_callback(sub_cb) try: mqttclient.connect() time.sleep_ms(10) alarm_led.off() if mqtt_conf['topics']: for switch in switches: topic = switch + '/feeds/lights/command' print(topic) mqttclient.subscribe(topic=topic) print("Mqqt connected") return mqttclient, False except: alarm_led.on() print("Mqqt isn't connected, retry in 60 seconds ") return False, time.time()
async def mqtt_connect(): global mqtt_client MQTT_SERVER = PRODUCT_ID + ".iotcloud.tencentdevices.com" MQTT_PORT = 1883 MQTT_CLIENT_ID = PRODUCT_ID+DEVICE_NAME MQTT_USER_NAME = "你的用户名" MQTTT_PASSWORD = "******" # 构建对象 mqtt_client = MQTTClient(MQTT_CLIENT_ID, MQTT_SERVER, MQTT_PORT, MQTT_USER_NAME, MQTTT_PASSWORD, 60) # 为收到的订阅消息设置回调 mqtt_client.set_callback(mqtt_callback) # 连接到服务器 mqtt_client.connect()
def connect(username, broker, topic, Mqtt_CLIENT_ID, PASSWORD): client = MQTTClient(client_id=Mqtt_CLIENT_ID, server=broker, port=1883, user=username, password=PASSWORD, keepalive=10000) try: client.connect() except OSError: print('Connection failed') sys.exit() data = dict() data["TempData"] = 60 data2=json.dumps(data)#convert it to json print('connection finished') client.publish(topic,data2) print("Done") time.sleep(5)
def photo_resistor(): client = MQTTClient(CLIENT_ID, SERVER) client.connect() sensor = ADC(0) while True: try: value = sensor.read() if isinstance(value, int): value = str(value) msg = value print("Message:", msg) client.publish(TOPIC, msg) except OSError: print("System Error") # sleep(3600) # one hour sleep(10) # for testing
def publish(): SERVER = '192.168.0.13' # MQTT Server Address (Change to the IP address of you$ CLIENT_ID = 'ESP32_DHT22_Sensor' TOPIC = b'temp_humidity' client = MQTTClient(CLIENT_ID, SERVER) client.connect() # Connect to MQTT broker dht_running = True sensor = DHT22(Pin( 15, Pin.IN, Pin.PULL_UP)) #DHT22 on GPIO 15 (input with internal pull up resistor) while dht_running: try: sensor.measure() # Poll sensor t = sensor.temperature() h = sensor.humidity() tm = time.localtime(time.time()) tmstr = '{:04d}-{:02d}-{:02d} {:02d}:{:02d}'.format( tm[0], tm[1], tm[2], tm[3], tm[4]) print(tm) print(t, h, tm[0]) if isinstance(t, float) and isinstance( h, float ) and tm[0] > 2000: # Confirm sensor results are numeric msg = (b'{0},{1:3.1f},{2:3.1f}'.format(tmstr, t, h)) client.publish( TOPIC, msg, retain=True) # Publish sensor data to MQTT topic print(str(msg)) print('Sent to ' + SERVER + ' as ' + CLIENT_ID + '. Exiting.') client.disconnect() dht_running = False else: print('Invalid sensor readings.') except OSError: print('Failed to read sensor.') time.sleep(5)
import machine import math import network import time import ubinascii import uos from umqtt.simple import MQTTClient motd = "2018-11-24 bbq temperature" broker = 'jarvis' client_id = 'esp8266_'+str(ubinascii.hexlify(machine.unique_id()), 'utf-8') print("client_id = "+client_id) topic = 'strip/' + client_id client = MQTTClient(topic, broker) print("listening to ", broker, " for ", topic) adc = machine.ADC(0) def time_check(): publish("time check") client.check_msg() try: ntptime.settime() except: print(".") def frangable_publish(topic, payload): try:
def main(server="localhost"): c = MQTTClient("umqtt_client", server) c.set_callback(sub_cb) c.connect() c.subscribe(b"foo_topic") 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()
fleet['esp8266_51333700'] = "O O OOO 5 S T " # 5 fleet['esp8266_609a1100'] = " " # 6 fleet['esp8266_7f35d500'] = "H H HHH 0 " # 5x8 fleet['esp8266_c1584a00'] = "8 8 8 8 8 8 8 8" # 3x5 segment = [[0]] * 7 for i in range(0, 7): j = (1, 2, 3, 4, 5, 0, 6)[i] if client_id == "esp8266_5133d500": # publish("I'm special") j = (5, 4, 3, 2, 1, 6, 0)[i] segment[i] = [x for x in range(j * 21, (j+1)*21)] segment_map = [0] * lights display_char = last_display_char = 0 client = MQTTClient(topic, broker) print("listening to ", broker, " for ", topic) pallet = [ (255, 0, 0), # red (0, 255, 0), # green (70, 105, 0), # yellow (170, 255, 0), # orange (0, 0, 255), # blue # (255, 255, 255), # white ] char_segment_map = { '0': 0x3F, '1': 0x06, '2': 0x5B, '3': 0x4F, '4': 0x66, '5': 0x6D, '6': 0x7D, '7': 0x07, '8': 0x7F, '9': 0x6F, 'A': 0x77, 'b': 0x7C, 'C': 0x39, 'd': 0x5E, 'E': 0x79, 'F': 0x71,
# When using on a robot or system, you probably want to remove the # 'From MQTT: ' part of the message. uart.write('From MQTT: {:s}\r\n'.format(msg)) # Blink the LED every 100ms to indicate we made it into the main.py file for _ in range(10): time.sleep_ms(100) led.value(not led.value()) # Toggle the LED # Make sure the LED is off led.high() # Create a MQTTClient instance. mqtt = MQTTClient(CLIENT_ID, HOST, port=PORT) # Subscribed messages will be delivered to this callback mqtt.set_callback(subscriction_callback) # Connect to the MQTT server mqtt.connect() # Define the topic to subscribe to mqtt.subscribe(SUB_TOPIC) print('\nMQTT:\n Connected to: {}:{}\n Subscribed to: {:s}\n Publishing to: {:s}'.format(HOST, PORT, SUB_TOPIC, PUB_TOPIC)) try: while True: # This is the non-blocking method to check if there are MQTT messages mqtt.check_msg()
# messages are being sent at a high rate led.value(not led.value()) # Blink the LED every 100ms to indicate we made it into the main.py file for _ in range(10): time.sleep_ms(100) led.value(not led.value()) # Toggle the LED time.sleep_ms(100) # Make sure the LED is off led.high() # define a time, because we only want to send every 1s but received as fast as possible # last_time = time.time() mqtt = MQTTClient(CLIENT_ID, HOST, port=PORT) # Subscribed messages will be delivered to this callback mqtt.set_callback(subscriction_callback) mqtt.connect() mqtt.subscribe(TOPIC) print('Connected to {}, subscribed to {} topic.'.format(HOST, TOPIC)) try: while 1: #micropython.mem_info() mqtt.wait_msg() finally: mqtt.disconnect()
switch = machine.Pin(5, machine.Pin.IN) amp1r = machine.Pin(14, machine.Pin.OUT) amp1l = machine.Pin(13, machine.Pin.OUT) amp2r = machine.Pin(16, machine.Pin.OUT) amp2l = machine.Pin(12, machine.Pin.OUT) act_amp = 1 new_amp = 1 wlan_connected = 1 ap_if = network.WLAN(network.AP_IF) sta_if = network.WLAN(network.STA_IF) sta_if.active(True) CLIENT_ID = ubinascii.hexlify(machine.unique_id()) mqtt = MQTTClient(CLIENT_ID, MQTT_SERVER) def connect_wifi(): global sta_if,ap_if print('connecting to network...') sta_if.connect(SSID,PW) while not sta_if.isconnected(): pass print('connection success: ', sta_if.ifconfig()) ap_if.active(False) def connect_mqtt(): global mqtt mqtt.connect() mqtt.subscribe(MQTT_TOPIC) print("MQTT connected to %s, subscribed to %s topic" % (MQTT_SERVER, MQTT_TOPIC))
Control led lights based on MQTT messages """ import machine import math import neopixel import network import time import uos from umqtt.simple import MQTTClient pin = 4 topic = 'leds' broker = 'jarvis' client = MQTTClient('leds', broker) lights = 39 np = neopixel.NeoPixel(machine.Pin(pin), lights) def allOff(): """ Turn all the lights off """ print("allOff") for i in range(0, np.n): np[i] = (0, 0, 0) np.write() def startUpAllOn(): """ Turn all the lights on starting from the edges
""" Model House Light Control Control led lights in model house based on MQTT messages """ import machine import neopixel import network import time import uos from umqtt.simple import MQTTClient topic = 'model' broker = '192.168.1.117' #'jarvis' client= MQTTClient('model', broker) np = neopixel.NeoPixel(machine.Pin(4), 6) def cycle(iterations, speed): for i in range(0, iterations): for i in range(0, np.n): np[(i-1) % np.n] = (0, 0, 0) np[i] = (10, 10, 10) np.write() time.sleep_ms(speed) def diagnostic(): n = np.n
state = 1 - state # Blink the LED every 100ms to indicate we made it into the main.py file for _ in range(10): time.sleep_ms(100) led.value(not led.value()) # Toggle the LED time.sleep_ms(100) # Make sure the LED is off led.high() # define a time, because we only want to send every 1s but received as fast as possible # last_time = time.time() mqtt = MQTTClient(CLIENT_ID, HOST, port=PORT) # Subscribed messages will be delivered to this callback mqtt.set_callback(subscriction_callback) mqtt.connect() mqtt.subscribe(SUB_TOPIC) print('Connected to {}, subscribed to {} topic.'.format(HOST, SUB_TOPIC)) try: while True: while True: mqtt.check_msg() if button.value() == 0: # the button is active low break # if it's pressed break out of the internal while loop time.sleep_ms(20) print('Button Pressed') mqtt.publish(PUB_TOPIC, b'Button Pressed')
def main(server="localhost"): c = MQTTClient("umqtt_client", server) c.connect() c.publish(b"foo_topic", b"hello") c.disconnect()
# timestamp print("SETTIME") ntptime.settime() # UTC from pool0.ntp.org payload_t["timestamp"] = payload_h["timestamp"] = "{:0>4d}-{:0>2d}-{:0>2d}T{:0>2d}:{:0>2d}:{:0>2d}Z".format( *time.localtime() ) # average readings try: payload_t["t"] = sum(payload_t["raw_t"]) / len(payload_t["raw_t"]) payload_h["h"] = sum(payload_h["raw_h"]) / len(payload_h["raw_h"]) except: pass c = MQTTClient(client, broker, port=broker_port) for _ in range(5): try: print("MQTT: CONNECTING ...") c.connect() print("MQTT: CONNECTION SUCCEEDED") break except: print("MQTT: CONNECTION FAILED") time.sleep(2) try: c.ping() c.publish(topic, json.dumps(payload_t)) c.publish(topic, json.dumps(payload_h)) print("MQTT: MESSAGE SENT")