def __init__(self, p_HelloMessage): self.f_Id = Config.C_ClientId self.f_QoS = Config.C_BrokerQoS try: l_Broker = Config.C_BrokerIP.split(':') self.f_MQTTClient = mqtt.MQTTClient( b"esp_{}".format(self.f_Id), l_Broker[0], port=l_Broker[0] if (len(l_Broker) > 1) else 0, user=Config.C_BrokerUser, password=Config.C_BrokerPassword, keepalive=Config.C_WatchdogTO) self.f_MQTTClient.set_last_will(topic=Config.C_BrokerPubPat.format( ClientId=self.f_Id, Name='Bye'), msg=b"\0\0\0\0Crash", qos=self.f_QoS) self.f_MQTTClient.connect() self.f_MQTTClient.set_callback(self.callback, g_Watchdog.touch) self.f_MQTTClient.subscribe( Config.C_BrokerSubPat.format(ClientId=self.f_Id), qos=self.f_QoS) Config.C_BrokerSubPat = None mqtt.MQTTClient.__init__ = None # will not instantiate again self.publish("Hello", p_HelloMessage) except OSError: reboot()
def __init__(self): log = logger.get_logger() log.log_msg(logger.INFO, "Initiating communication to Thingspeak") client = mqtt.MQTTClient(config.conf["thingspeak"]["channel_id"], config.conf["thingspeak"]["host"], config.conf["thingspeak"]["port"]) client.connect() log.log_msg(logger.INFO, "Connection successful") client.disconnect()
def run(self): self._mqttc = mqtt.MQTTClient() self._mqttc.connect(on_success=lambda: self._connect_mqtt_event.set()) threading.Thread(target=self._state_dispatcher.listen).start() self._mqttc.loop_start() super().run() self._mqttc.loop_stop() self._mqttc.disconnect() self._state_dispatcher.stop()
def __init__(self, config, display): self.__debug = config.get('debug') self.__display = display self.__server = config.get('mqtt_server') self.__topic = "emf_hub/ptt" self._id = str(ubinascii.hexlify(pyb.unique_id()), 'ascii') self.__next_ping = pyb.millis() + 60000 self.__c = mqtt.MQTTClient(self._id, self.__server) # Connect to server self.__connect()
def __init__(self, slave_address): self.address = slave_address # ATTRIBUTE SLAVES self.sensors = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] self.define_sensors() # ATTRIBUTE SENSOR TOPICS self.sensor_topics = ["", "", "", "", "", "", "", "", "", ""] self.define_sensor_topics() # CREATE MQTT CLIENT self.client = mqtt.MQTTClient() # INIT DEVICE self.init()
def send_data(self, dict_of_fields): log = logger.get_logger() log.log_msg(logger.INFO, "Sending data to thingspeak") try: client = mqtt.MQTTClient(config.conf["thingspeak"]["channel_id"], config.conf["thingspeak"]["host"], config.conf["thingspeak"]["port"]) client.connect() credentials = "channels/{:s}/publish/{:s}".format( config.conf["thingspeak"]["channel_id"], config.conf["thingspeak"]["write_api_key"]) payload = "&".join([ "{}={}".format(key, value) for key, value in dict_of_fields.items() ]) + "\n" client.publish(credentials, payload) client.disconnect() log.log_msg(logger.INFO, "Data was sent") except Exception as e: log.log_msg(logger.ERROR, "Could not send data: {}".format(e))
def main(): # Connect to wifi w = wifi.Wifi(config.ssid, config.password, config.ifconfig) if not w.connect(): print("Could not connect to wifi") machine.reset() time.sleep_ms(300) print("Connecting to MQTT") c = mqtt.MQTTClient('umqtt_client', config.mqttserver, port=config.mqttport) c.DEBUG = True c.set_callback(_make_mqtt_callback(c)) _mqtt_connect(c) while True: c.wait_msg(timeout=1.0 / 25.0)
def on_message(client, userdata, msg): print("on_message function") print(msg.topic) print(msg.payload) if (int(msg.payload) == 2): print("Equal to 2") else: print("Not equal to 2") def on_connect(client, userdata, flags, rc): print("on_connect function") # INIT MQTT client = mqtt.MQTTClient() # DEFINE CALLBACK FUNCTIONS client.define_on_message(on_message) client.define_on_connect(on_connect) # MQTT FUNCTIONS client.connect() client.subscribe('ECAM/jordan', 0) client.listen() ###### MAIN BEHAVIOUR ###### TEMPERATURE_THRESHOLD = 85 BRIGHTNESS_THRESHOLD = 1200
## Setup WIFI Networking as a client if 'wifi-station' in settings: nic = network.WLAN(network.STA_IF) nic.active(True) check_wifi(nic) print("WIFI : Connected ") ## Clean out allocated memory so far gc.collect() gc.threshold(gc.mem_free() // 4 + gc.mem_alloc()) ## Create MQTT Connection c = mqtt.MQTTClient(client_id=settings['device']['name'], server=settings['mqtt']['server'], user=settings['mqtt']['user'], password=settings['mqtt']['key'], ssl=False) print("MQTT Client : Created") c.connect() print("MQTT Client : Connected") # Publish temperatures to Adafruit IO using MQTT # # Format of feed name: # "ADAFRUIT_USERNAME/groups/ADAFRUIT_IO_GROUPNAME" mqtt_feedname = bytes( '{:s}/groups/{:s}/csv'.format(settings['mqtt']['user'], settings['mqtt']['feed']), 'utf-8')
import gpiozero as gpio import model import mqtt import time coffee_indicator = gpio.LED(4) mqtt_client = mqtt.MQTTClient("10.2.75.239", 1883) def indicate_coffee_done(message): """ Handles flashing the LED to indicate that the coffee is ready """ for i in range(0, 5): coffee_indicator.on() time.sleep(0.5) coffee_indicator.off() time.sleep(0.5) if __name__ == '__main__': mqtt_client.subscribe('coffee/status', indicate_coffee_done) mqtt_client.loop_forever()
def __init__(self): super().__init__() self.config = configparser.ConfigParser() self.config.read("conf.ini") self.initiated = True self.ip = subprocess.check_output(['hostname', '-I']).decode('utf-8').split(' ')[0] self.title('MoonFiber Spinner Controller @' + self.ip) self.toolbar = Frame(self) self.wifi_status = StringVar() self.usb_status = StringVar() self.machine_status = StringVar() for i, var in enumerate( (self.machine_status, self.usb_status, self.wifi_status)): var.set("No Connection") Label(self.toolbar, textvariable=var).grid(row=i + 1, column=0) self.start_button = Button(self.toolbar, text='Start', command=self.start) self.start_button.grid(row=0, column=3) self.start_button['state'] = 'disabled' self.stop_button = Button(self.toolbar, text='Stop', command=self.stop) self.stop_button.grid(row=0, column=4) self.stop_button['state'] = 'disabled' self.droptest_button = Button(self.toolbar, text='Drop Test', command=self.droptest) self.droptest_button.grid(row=0, column=5) self.droptest_res = StringVar() Label(self.toolbar, textvariable=self.droptest_res) self.config_button = Button( self.toolbar, text='Configure', command=lambda: controller.show_frame("ConfigFrame")) self.config_button.grid(row=0, column=0) self._mqtt_status = False self.mqtt_client = mqtt.MQTTClient(client_id=('Ampex GUI @' + self.ip), status_var=self.wifi_status, status_prop=self.mqtt_status, ready=self.ready) self._serial_status = False self.serializer = usb_serial.Serializer( self.config["DEFAULTS"]["CONFIG_SERIAL_PORT"], var=self.usb_status, prop=self.serial_status, after=lambda delay, callback: self.after(delay, callback), ready=self.ready) self.toolbar.grid(row=0, column=0, sticky='nsew') self.container = Frame(self) self.container.grid(row=1, column=0) self.frames = {} for F in (PlotsFrame, ConfigFrame): page_name = F.__name__ frame = F(master=self.container, controller=self) self.frames[page_name] = frame frame.grid(row=0, column=0, sticky="nsew") self.sensor_vars = {} for i, name in enumerate(self.frames["PlotsFrame"].sensors.keys()): self.sensor_vars[name] = StringVar() self.sensor_vars[name].set(name) Label(self, textvariable=self.sensor_vars[name]).grid(row=2 + i, column=99) self.show_frame("PlotsFrame") common.set_sensor_vars(self.sensor_vars) common.status_var = self.machine_status
## Setup WIFI Networking as a client if 'wifi-station' in settings: nic = network.WLAN(network.STA_IF) nic.active(True) check_wifi(nic) ## Setup WIFI Networking as an access point if 'wifi-ap' in settings: ap = network.WLAN(network.AP_IF) ap.active(True) ap.config(essid=settings['wifi-ap']['name']) wait_ap(ap) if 'mqtt' in settings: import mqtt c = mqtt.MQTTClient(settings['device']['name'], settings['mqtt']['ip'], 1883) c.connect() #last_ip = "" slow_check_timestamp = timer.timestamp # main loop def loop(sched=None): global slow_check_timestamp timer.update() ### read and update temperatures if temp_io.ready():
mqtt.connect() except: machine.reset() print("MQTT connection established") def publish_plant(sensor): m.publish("sensors/plant/{}/{}".format(UID, sensor.name), str(sensor.result)) print("PLANT {} VALUE {}".format(sensor.name, sensor.result)) def add_plant(): for s in sensor: s.set_timer() tmr.add(10 * 1000, add_plant) print("Boot complete") m = mqtt.MQTTClient("Pflanze_{}".format(UID), "mqtt.space.aachen.ccc.de") tmr = timer.Timer(50) sensor = [ moisture.Moisture("alpha", 36, 1000, 5, publish_plant, tmr), moisture.Moisture("beta", 39, 1000, 5, publish_plant, tmr), moisture.Moisture("gamma", 34, 1000, 5, publish_plant, tmr), moisture.Moisture("delta", 35, 1000, 5, publish_plant, tmr) ] init_wifi() init_mqtt(m) add_plant()
id = str(ubinascii.hexlify(pyb.unique_id()), 'ascii') #Get MSISDN mynumber = None myNumber() # Setup Sequence ID if db.get('msgseq') == None: db.set('msgseq', 0) db.flush() else: pass #Setup and Connect MQTT c = mqtt.MQTTClient('badge'+id, server) c.connect() c.set_callback(callback) c.subscribe('/badge/'+id, qos=0) lastseq = db.get('msgseq') c.publish('resend/'+id, str(lastseq)) #Main Screen and Watch for Input/Messages display() while True: if buttons.is_triggered('BTN_A'): viewmsg() if buttons.is_triggered('BTN_B'): display() check()
def __init__(self) : # CREATE MQTT CLIENT self.client = mqtt.MQTTClient()