client.subscribe("Meshcat") def on_message(client, userdata, msg): print_log(datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S') + " | message received!") try: message = json.loads(msg.payload) except ValueError: print_log("Invalid message format!") return station_secret = message["id_secret"] sensor = message["sensor"] value = message["value"] format_date = message["datetime"].split("+")[0] timestamp = datetime.strptime(format_date, '%Y-%m-%dT%H:%M:%S') sid = db.get_id_from_secret(station_secret) if (sid and sensor != "ACC" and sensor != "STR"): db.insert_data(sid, sensor, value, timestamp) if (not sid): sid = "-" #sid = db.new_station(station_secret) #print_log("Add new sensor with ID " + str(sid)) print_log("receive: sid: {} | sensor: {} | value: {} | timestamp: {}".format(sid,sensor,value,timestamp)) mqtt = mqtt.Client() mqtt.on_connect = on_connect mqtt.on_message = on_message mqtt.connect("localhost", 1883) mqtt.loop_forever()
time.sleep(2) client.publish("user/bob/location", "home", retain=True, qos=1) client.publish("user/bob/location", "work", retain=True, qos=1) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("user/bob/location") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) time.sleep(2) def on_log(*args): print args client = client.Client() client.on_connect = on_connect client.on_message = on_message client.on_log = on_log client.username_pw_set("bob", password=None) client.connect("localhost", 8000, 60) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever()
def handle(self): headers = self.request.recv(1024).strip().split('\r\n') valid = 'Connection: Upgrade' in headers and 'Upgrade: websocket' in headers if not valid: return self.request.sendall(HTTP_400) request_key = str(' ').join([ header.split(' ').pop() for header in headers if 'Sec-WebSocket-Key' in header ]) response_key = base64.standard_b64encode( hashlib.sha1(request_key + WEBSOCKET_HASH).digest()) self.request.sendall(HTTP_101 % response_key) # def connect_mqtt_to_websocket( self ) : handler, connected = self, True def subscribe(client, userdata, flags, code): client.subscribe('raspberry/status') def receive(client, userdata, message): try: handler.send_frame(message.payload) except: connected = False # TODO? client = paho.mqtt.client.Client() client.on_connect = subscribe client.on_message = receive client.connect('192.168.0.10', 1883) while connected: client.loop_forever()
def main(): client = paho.mqtt.client.Client("Emiliano", False) client.qos = 0 client.connect(host='127.0.0.1') meanEntrada = 10 stdEntrada = 2 tempMax = 12 horaBase = datetime.datetime.now().replace(minute=0, second=0) personasPorHora = np.random.normal(meanEntrada, stdEntrada) horaBase = horaBase + datetime.timedelta(hours=1) while True: hora = horaBase + datetime.timedelta(seconds=1) horaBase = horaBase + datetime.timedelta(seconds=1) temp = int(np.random.uniform(0, 151)) payload = {"fecha": str(hora), "Temperatura": str(temp)} client.publish('casa/cocina/nevera', json.dumps(payload), qos=0) print(payload) if temp >= 100: payload = { "fecha": str(hora), "Temperatura": str(temp), "Agua": "El agua ya ha hervido" } print(payload) client.publish('casa/cocina/nevera', json.dumps(payload), qos=0) time.sleep(0.5)
def main(): client = paho.mqtt.client.Client("fridge", False) client.qos = 0 client.connect(host = "localhost") minTemp = 8 maxTemp = 12 minIce = 0 maxIce = 10 Actualtime = datetime.datetime.now().replace(minute = 0, second = 0, microsecond = 0) sendIceData = True while(True): temperature = round(random.uniform(minTemp, maxTemp), 2) data = { "date": str(Actualtime), "temperature": str(temperature) } client.publish("house/kitchen/fridge", json.dumps(data), qos = 0) print(data) if(sendIceData): iceCapacity = round(random.uniform(minIce, maxIce), 2) data = { "date": str(Actualtime), "ice_capacity": str(iceCapacity) } client.publish("house/kitchen/fridge", json.dumps(data), qos = 0) print(data) Actualtime += datetime.timedelta(minutes = 5) sendIceData = not sendIceData time.sleep(5)
def main(): ollaEnUso = True mensajeExitoso = "El agua está hirviendo" mensajeFallido = "El agua no está hirviendo" cont = 0 client = paho.mqtt.client.Client("Olla", False) client.qos = 2 client.on_connect = on_connect client.connect('localhost') hora = datetime.datetime.now() while cont < 100 and ollaEnUso: minTemp = 50 maxTemp = 150 temp = np.random.uniform(minTemp, maxTemp) payload = {"Temperatura_Olla": str(round(temp, 2)), "Fecha": str(hora)} if ollaEnUso: if temp > 100: payload["mensaje"] = mensajeExitoso else: payload["mensaje"] = mensajeFallido client.publish('Casa/Cocina/temperatura_olla', json.dumps(payload), qos=0) cont += 1 print(payload) time.sleep(1) hora = hora + datetime.timedelta(seconds=1)
def main(): client = paho.mqtt.client.Client("Emiliano", False) client.qos = 0 client.connect(host='127.0.0.1') meanEntrada = 10 stdEntrada = 2 tempMax = 12 horaBase = datetime.datetime.now().replace(minute=0, second=0) personasPorHora = np.random.normal(meanEntrada, stdEntrada) horaBase = horaBase + datetime.timedelta(hours=1) while True: hora = horaBase + datetime.timedelta(minutes=5) horaBase = horaBase + datetime.timedelta(minutes=5) temp = int(np.random.normal(8, tempMax + 1)) payload = {"fecha": str(hora), "Temperatura": str(temp)} hielo = { "fecha": str(hora), "Capacidad": str(int(np.random.uniform(0, 11))) } client.publish('casa/cocina/nevera', json.dumps(payload), qos=0) print(payload) if int(hora.minute) % 10 == 0: print(hielo) client.publish('casa/cocina/nevera', json.dumps(hielo), qos=0) time.sleep(0.5)
def connect_server(): try: ws = create_connection("ws://" + address + ":" + port + "/rpi") print("connect to " + address + ":" + port) ws.send(json_send) except Exception as e: print(e) ws.close() exit() while True: result = ws.recv() bno, rno = result.split(',') mqtt = mqtt.Client("mypub") mqtt.connect("localhost", 1883) if bno == 1 and rno == 1: mqtt.publish('motor', 1) elif bno == 1 and rno == 2: mqtt.publish('motor', 2) elif bno == 2 and rno == 1: mqtt.publish('motor', 3) elif bno == 2 and rno == 2: mqtt.publish('motor', 4) print("The message is published.") print("open bno:" + bno + " rno:" + rno) ws.close()
def _init_mqtt_client( # *, SyntaxError on python3.5 host: str, port: int, username: typing.Optional[str], password: typing.Optional[str], disable_tls: bool, ) -> paho.mqtt.client.Client: # https://pypi.org/project/paho-mqtt/ client = paho.mqtt.client.Client() client.on_connect = _mqtt_on_connect if not disable_tls: client.tls_set( ca_certs=None) # enable tls trusting default system certs _LOGGER.info( "connecting to MQTT broker %s:%d (TLS %s)", host, port, "disabled" if disable_tls else "enabled", ) if username: client.username_pw_set(username=username, password=password) elif password: raise ValueError("Missing MQTT username") client.connect(host=host, port=port) return client
def main(): mensajeAlerta = "¡No deben haber más de 5 personas en la Sala! por favor retirense" cont = 0 client = paho.mqtt.client.Client("contadorPersonas", False) client.qos = 0 client.on_connect = on_connect client.connect(host='localhost', port=1883) hora = datetime.datetime.now() while cont < 100: minPer = 0 maxPer = 10 personas = np.random.uniform(minPer, maxPer) payload = { "Cantidad Personas": str(round(personas)), "Fecha": str(hora) } if personas > 5: payload["mensaje"] = mensajeAlerta client.publish(topic='Casa/Sala/contador_personas', payload=json.dumps(payload), qos=0) cont += 1 print(payload) time.sleep(1) hora = hora + datetime.timedelta(seconds=60)
def __init__(self, *args, **kwargs): QtWidgets.QMainWindow.__init__(self, *args, **kwargs) self.setupUi(self) client = paho.mqtt.client.Client(client_id='andres', clean_session=False) client.on_connect = on_connect client.on_message = on_message client.connect(host='localhost', port=1883) client.loop_start() self.luz.setText(b) self.temperatura_2.setText(b) self.salen.setText(b) self.entran.setText(b) self.adentro.setText(b) self.encendidoaire.clicked.connect(self.aireon) self.arribaaire.clicked.connect(self.airearriba) self.abajoaire.clicked.connect(self.aireabajo) self.encendidotv.clicked.connect(self.tvon) self.canalmas.clicked.connect(self.tvmas) self.canalmenos.clicked.connect(self.tvmenos) self.volumenmas.clicked.connect(self.tvvolmas) self.volumenmenos.clicked.connect(self.tvvolmenos) self.salen.setText(b) self.entran.setText(b) self.adentro.setText(b) self.labsdos.clicked.connect(self.luz2) self.labsuno.clicked.connect(self.luz1)
def main(): client = paho.mqtt.client.Client(client_id='client3', clean_session=False) client.on_connect = on_connect client.on_message = on_message client.username_pw_set('caio', 'senha') client.connect(host='192.168.20.105', port=1883) client.loop_forever()
def main(): client = paho.mqtt.client.Client("Emiliano", False) client.qos = 0 client.connect(host='127.0.0.1') meanEntrada = 10 stdEntrada = 2 tempMax = 12 horaBase = datetime.datetime.now().replace(minute=0, second=0) personasPorHora = np.random.normal(meanEntrada, stdEntrada) horaBase = horaBase + datetime.timedelta(hours=1) while True: hora = horaBase + datetime.timedelta(minutes=1) horaBase = horaBase + datetime.timedelta(minutes=1) cantPersonas = int(np.random.uniform(0, 11)) payload = { "fecha": str(hora), "cantidad de personas": str(cantPersonas) } client.publish('casa/cocina/sala', json.dumps(payload), qos=0) print(payload) if cantPersonas > 5: payload = { "fecha": str(hora), "cantidad de personas": str(cantPersonas), "Alerta": "Demasiadas personas dentro de la habitación" } print(payload) client.publish('casa/cocina/sala', json.dumps(payload), qos=0) time.sleep(0.5)
def mqrecv(): client = paho.mqtt.client.Client(client_id='192.168.0.110', clean_session=False) client.username_pw_set('DGB1', '12345678') client.on_connect = on_connect client.on_message = on_message client.connect(host='192.168.0.158', port="1883") client.loop_forever()
def MQTT_Proyector(estado): global test falcon_logger.info("Solicitando cambio estado proyector a %s" % estado) if (config.MQTT.POWER_CHECK): cur_stat=Estado_Proyector() if (estado == cur_stat): falcon_logger.info("El protector ya esta en %s. No hago nada" % estado) return estado else: falcon_logger.info("Power Control desactivado") falcon_logger.info("Enviando mensaje MQTT %sbroadlink/replay proyectoron" % test ) try: falcon_logger.info("Estableciendo conexion con %s:%s" % (config.MQTT.HOST,config.MQTT.PORT)) client.connect(host=config.MQTT.HOST, port=config.MQTT.PORT) client.publish("%sbroadlink/record" % test,"proyectoron" ) if (estado=="OFF"): time.sleep(1) client.publish("%sbroadlink/record" % test,"proyectoron" ) falcon_logger.error("Enviando mensaje MQTT %sbroadlink/replay proyectoron" % test ) client.disconnect() except Exception as e: falcon_logger.error("Error al conectar a MQTT. Mensaje no enviado %s" % str(e)) return 9,"Error de conexion" return 0,"ok"
def run(self): client = paho.mqtt.client.Client("broker-monitor") client.connect("localhost", port=port) client.message_callback_add("$SYS/broker/store/messages/count", self.store_count) client.message_callback_add("$SYS/broker/store/messages/bytes", self.store_bytes) client.message_callback_add("$SYS/broker/publish/messages/dropped", self.publish_dropped) client.subscribe("$SYS/broker/store/messages/#") client.subscribe("$SYS/broker/publish/messages/dropped") while True: expect_drops = cq.get() self.cq.task_done() if expect_drops == "quit": break first = time.time() while self.stored < 0 or self.stored_bytes < 0 or ( expect_drops and self.dropped < 0): client.loop(timeout=0.5) if time.time() - 10 > first: print("ABORT TIMEOUT") break if expect_drops: self.rq.put((self.stored, self.stored_bytes, self.dropped)) else: self.rq.put((self.stored, self.stored_bytes, 0)) self.stored = -1 self.stored_bytes = -1 self.dropped = -1 client.disconnect()
def main(): client = paho.mqtt.client.Client(client_id='escaner WI-FI', clean_session=False) client.on_connect = on_connect client.on_message = on_message client.connect(host='127.0.0.1', port=1883) client.loop_forever()
def run(self): client = paho.mqtt.client.Client("broker-monitor") client.connect("localhost", port=port) client.message_callback_add("$SYS/broker/store/messages/count", self.store_count) client.message_callback_add("$SYS/broker/store/messages/bytes", self.store_bytes) client.message_callback_add("$SYS/broker/publish/messages/dropped", self.publish_dropped) client.subscribe("$SYS/broker/store/messages/#") client.subscribe("$SYS/broker/publish/messages/dropped") while True: expect_drops = cq.get() self.cq.task_done() if expect_drops == "quit": break first = time.time() while self.stored < 0 or self.stored_bytes < 0 or (expect_drops and self.dropped < 0): client.loop(timeout=0.5) if time.time() - 10 > first: print("ABORT TIMEOUT") break if expect_drops: self.rq.put((self.stored, self.stored_bytes, self.dropped)) else: self.rq.put((self.stored, self.stored_bytes, 0)) self.stored = -1 self.stored_bytes = -1 self.dropped = -1 client.disconnect()
def main(): client = paho.mqtt.client.Client(client_id="albert-subs", clean_session=False) client.on_connect = on_connect client.on_message = on_message client.connect(host=SETTINGS.BROKER_HOST, port=1883) client.loop_forever()
def start_sensor(config): sensor = DFRobotAS3935(I2C_ADDRESS, bus=config('sensor', 'bus'), capacitance=config('sensor', 'capacitance'), location=Location[config('sensor', 'location').upper()], disturber_detection=config('sensor', 'disturber_detection')) mqtt = create_client(config) try: logging.info('Starting MQTT notifier.') mqtt.connect(config('mqtt', 'broker'), config('mqtt', 'port')) if sensor.reset(): logging.info('Sensor initialized.') GPIO.add_event_detect(IRQ_PIN, GPIO.RISING, callback=mk_callback_handler(sensor, mqtt, config)) logging.info('Starting lightning detection...') mqtt.publish(f'{config("mqtt", "topic")}/status', payload='online', qos=0, retain=True) start_ping(config, mqtt) mqtt.loop_forever() else: logging.fatal('Sensor initialization failed.') except Exception as e: logging.error(e) logging.exception('Unable to connect to MQTT broker!')
def main(): client = paho.mqtt.client.Client("cookingPot", False) client.qos = 0 client.connect(host = "localhost") minTemp = 0 maxTemp = 150 Actualtime = datetime.datetime.now().replace(minute = 0, second = 0, microsecond = 0) while(True): temperature = round(random.uniform(minTemp, maxTemp), 2) data = { "date": str(Actualtime), "temperature": str(temperature) } client.publish("house/kitchen/cooking_pot", json.dumps(data), qos = 0) print(data) if(temperature >= 100): for i in range(60): data = { "date": str(Actualtime), "message": "The water boild" } client.publish("house/kitchen/cooking_pot", json.dumps(data), qos = 0) print(data) Actualtime += datetime.timedelta(seconds = 1) else: Actualtime += datetime.timedelta(minutes = 1) time.sleep(1)
def registerOfflineSubscriber(): """Just a durable client to trigger queuing""" client = paho.mqtt.client.Client("sub-qos1-offline", clean_session=False) client.connect("localhost", port=port) client.subscribe("test/publish/queueing/#", 1) client.loop() client.disconnect()
def main(): client = paho.mqtt.client.Client("alexaEco", False) client.qos = 0 client.connect(host="localhost") Actualtime = datetime.datetime.now().replace(minute=0, second=0, microsecond=0) minTemp = 0 maxTemp = 1 url = "https://api.openweathermap.org/data/2.5/weather?" api_key = "127782c6cbdc7abdbed266714daeeade" city = "Caracas,VE" querystring = url + "appid=" + api_key + "&q=" + city response = requests.get(querystring) jsonRes = response.json() temperature = round(jsonRes["main"]["temp"] - 273.15, 2) while (True): operation = bool(random.getrandbits(1)) if (operation): temperature += round(random.uniform(minTemp, maxTemp), 2) else: temperature -= round(random.uniform(minTemp, maxTemp), 2) temperature = round(temperature, 2) data = {"date": str(Actualtime), "temperature": str(temperature)} client.publish("house/living_room/alexa_eco", json.dumps(data), qos=0) print(data) Actualtime += datetime.timedelta(minutes=3) time.sleep(3)
def main(): cont = 0 client = paho.mqtt.client.Client("Nevera", False) client.qos = 2 client.on_connect = on_connect client.connect('localhost') hora = datetime.datetime.now() while cont < 100: meanTemp = 10 stndTemp = 2 minHielo = 0 maxHielo = 10 temp = np.random.normal(meanTemp, stndTemp) hielo = np.random.uniform(minHielo, maxHielo) payload = { "Temperatura_nevera": str(round(temp, 2)), "Cantidad_de_Hielo": str(round(hielo)), "Fecha": str(hora) } client.publish('Casa/Cocina/temperatura_nevera', json.dumps(payload), qos=0) cont += 1 print(payload) time.sleep(1) hora = hora + datetime.timedelta(seconds=300)
def main(): client = paho.mqtt.client.Client("Emiliano", False) client.qos = 0 client.connect(host='127.0.0.1') meanEntrada = 10 stdEntrada = 2 tempMax = 12 horaBase = datetime.datetime.now().replace(minute=0, second=0) personasPorHora = np.random.normal(meanEntrada, stdEntrada) horaBase = horaBase + datetime.timedelta(hours=1) while True: hora = horaBase + datetime.timedelta(minutes=30) horaBase = horaBase + datetime.timedelta(minutes=30) url = "http://api.openweathermap.org/data/2.5/weather?q=Caracas&appid=6cf9ae43293928ec740fd51b2c9c524a" data = requests.get(url).json() temp = int(data['main']['temp']) - 273 payload = { "fecha": str(hora), "Temperatura de Caracas ": str(temp) } client.publish('casa/cocina/sala', json.dumps(payload), qos=0) print(payload) time.sleep(0.5)
def main(): client = paho.mqtt.client.Client("personCounter", False) client.qos = 0 client.connect(host="localhost") minPer = 0 maxPer = 10 Actualtime = datetime.datetime.now().replace(minute=0, second=0, microsecond=0) while (True): persons = round(random.uniform(minPer, maxPer), 0) data = {"date": str(Actualtime), "persons": str(persons)} client.publish("house/living_room/person_counter", json.dumps(data), qos=0) print(data) if (persons > 5): data = { "date": str(Actualtime), "message": "Maximum number of people exceeded" } client.publish("house/living_room/person_counter", json.dumps(data), qos=0) print(data) Actualtime += datetime.timedelta(minutes=1) time.sleep(1)
def main(): client = paho.mqtt.client.Client(client_id='Sala-subs', clean_session=False) client.on_connect = on_connect client.on_message = on_message client.connect('localhost', port=1883) client.loop_forever()
def main(): cont = 0 resp = requests.get( 'http://api.openweathermap.org/data/2.5/weather?q=Caracas&appid=746872ff706ff4ebf8cd394c72541b42' ) print(resp.json()["main"]["temp"]) # Conversión de Kelvin a Celsius temp = int(resp.json()["main"]["temp"]) - 273.15 print(temp) client = paho.mqtt.client.Client("Alexa", False) client.qos = 2 client.on_connect = on_connect client.connect('localhost') hora = datetime.datetime.now() while cont < 100: tempDelta = np.random.normal(1, 0.5) payload = { "Temperatura Caracas": str(round(temp + tempDelta, 2)), "Fecha": str(hora) } client.publish('Casa/Sala/alexa_echo', json.dumps(payload), qos=0) cont += 1 print(payload) time.sleep(1) hora = hora + datetime.timedelta(seconds=300)
def main(): client = paho.mqtt.client.Client(client_id=MQTT_CLIENT_ID, clean_session=False) client.on_connect = on_connect client.on_message = on_message client.connect(host=MQTT_HOST) client.loop_forever()
def main(): client = paho.mqtt.client.Client(client_id='123', clean_session=False) #client.username_pw_set('[username]', '[password]') client.on_connect = on_connect client.on_message = on_message #client.tls_set('/etc/ssl/certs/DST_Root_CA_X3.pem', tls_version=ssl.PROTOCOL_TLSv1_2) client.connect(host='45.35.48.219') client.loop_forever()
def main(): ledRGB.loadInit() client = paho.mqtt.client.Client(client_id='pythonIGM', clean_session=False) client.on_connect = on_connect client.on_message = on_message client.connect(host='192.168.1.198', port=1883) client.loop_forever()
def connect(self, topic: str): self.__topic = topic client = paho.mqtt.client.Client() client.username_pw_set(mqtt_user, mqtt_password) client.on_connect = self.on_connect client.on_message = self.on_message client.connect(self.__host, 1883, 60) client.loop_start()
def main(): client = paho.mqtt.client.Client(client_id='Actividad Sambil',clean_session=False) client.on_connect = on_connect client.message_callback_add('Sambil/Camaras/#', on_message_C) client.message_callback_add('Sambil/Estacionamiento/#', on_message_A) client.message_callback_add('Sambil/Mesa/#', on_message_M) client.message_callback_add('Sambil/Tienda/#', on_message_T) client.connect(host='localhost') client.loop_forever()
def _write_topic(self, topic, value): client = paho.mqtt.client.Client() notifications = [] client.on_connect = lambda c,d,f,r: c.subscribe('N/#', 0) client.connect(TestHost) client.loop_start() client.on_message = lambda c,d,msg: notifications.append(msg) client.publish(topic, json.dumps({'value': value})) time.sleep(1) client.loop_stop(True) self.assertTrue(len(notifications) > 0) topic = 'N' + topic[1:] v = None for n in notifications: if n.topic == topic: v = int(json.loads(n.payload)['value']) self.assertEqual(v, value)
def test_notifications(self): client = paho.mqtt.client.Client() notifications = [] client.on_connect = lambda c,d,f,r: c.subscribe('N/#', 0) client.connect(TestHost) client.loop_start() time.sleep(2) # wait for retained messages client.on_message = lambda c,d,msg: notifications.append(msg) time.sleep(2) client.loop_stop(True) self.assertTrue(len(notifications) > 0) for n in notifications: action, system_id, service_type, device_instance, path = n.topic.split('/', 4) self.assertEqual(action, 'N') self.assertEqual(system_id, TestPortalId) # If the statements below raise an exception, the test will fail di = int(device_instance) v = json.loads(n.payload)['value']
def test_request(self): client = paho.mqtt.client.Client() notifications = [] client.on_connect = lambda c,d,f,r: c.subscribe('N/#', 0) client.connect(TestHost) client.loop_start() time.sleep(2) # wait for retained messages client.on_message = lambda c,d,msg: notifications.append(msg) topic = 'R/{}/settings/0/Settings/Vrmlogger/LogInterval'.format(TestPortalId) client.publish(topic, '') time.sleep(1) client.loop_stop(True) self.assertTrue(len(notifications) > 0) topic = 'N' + topic[1:] for n in notifications: if n.topic == topic: v = int(json.loads(n.payload)['value']) break else: raise Exception('Topic not found')
phone app sends to mosquitto broker we subscribe on that broker and send http to update.py """ import json, restkit, logging import paho.mqtt.client logging.basicConfig(level=logging.INFO, format="%(asctime)-15s %(message)s") log = logging.getLogger() config = json.load(open('priv.json')) updateServer = restkit.Resource("http://bang:9033/update") client = paho.mqtt.client.Client("map-receiver") client.connect("localhost") log.info('connected to %s', client._host) # need more auth here, to be able to read client.subscribe("/mqttitude/#", 0) def on_message(mosq, obj, msg): payload = json.loads(msg.payload) log.info("got message %r %r", msg.topic, payload) try: userFromTopic = config['mqttTopic'][msg.topic] except KeyError: log.warn("ignoring unknown topic") return if 'lon' not in payload: log.info("ignoring") return record = {
Thread.__init__(self) self.topic = topic self.payload = payload self.daemon = True def run(self): session = models.get_session() store_entry = Store() store_entry.payload = self.payload.decode("utf-8") store_entry.topic = self.topic session.add(store_entry) session.commit() # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): thread = WriteMessage(msg.topic, msg.payload) thread.start() client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever()
def new(host, port, keep_alive): client = paho.mqtt.client() client.subscribe("devnet/2") client.connect(host, port, keep_alive) client.on_message = on_message
pin = int(path[2]) pin_storage[pin] = str(msg.payload) conn.sendall(hw("vw", pin, str(msg.payload))) for old, pin in translate_topic: old_topic = u"%s/%s" % (TOPIC, old) if old_topic == msg.topic: pin_storage[pin] = str(msg.payload) log(u"Write topic %s to vw/%s, val %s" % (old_topic, pin, str(msg.payload))) conn.sendall(hw("vw", pin, str(msg.payload))) # Main code log('Connecting to MQTT broker %s:%d' % (MQTT_SERVER, MQTT_PORT)) try: mqtt = mqtt.Client(MQTT_CLIENT) mqtt.connect(MQTT_SERVER, MQTT_PORT, 60) mqtt.on_message = on_mqtt_message except: log("Can't connect") sys.exit(1) mqtt.subscribe("%s/#" % TOPIC) log('Connecting to %s:%d' % (SERVER, PORT)) try: conn = socket.create_connection((SERVER, PORT), 3) except: log("Can't connect") sys.exit(1) if NODELAY != 0:
def mqtt_client(host, port, keep_alive): client = paho.mqtt.client.Client() client.subscribe("devnet/2") client.on_message = on_message client.connect(host, port, keep_alive) return client
[tlv.T_PROP_VALUE, value.encode("utf8")], ] tlv.dumptlv(tlvdata) hsc_sock.sendto(tlv.hmactlv(tlv.gettlv(tlvdata), hsckey), ("255.255.255.255",UDP_PORT)) hsc_sock.sendto(tlv.hmactlv(tlv.gettlv(tlvdata), hsckey), (MCAST_GROUP,UDP_PORT)) if '$ip' in device['attrs']: hsc_sock.sendto(tlv.hmactlv(tlv.gettlv(tlvdata), hsckey), (device['attrs']['$ip'],UDP_PORT)) client = paho.mqtt.client.Client() client.on_connect = on_connect client.on_message = on_message if config.has_option('mqtt', 'username'): client.username_pw_set(config.get('mqtt', 'username'), config.get('mqtt', 'password')) client.connect(config.get('mqtt', 'host'), config.getint('mqtt', 'port', fallback=1883), config.getint('mqtt', 'keepalive', fallback=60)) client.loop_start() class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) self.winfo_toplevel().title("HAm MQTT Viewer/Commander") self.pack() self.devices_order = [] if config.has_option('preferences', 'devices_order'): for deviceId in config.get('preferences', 'devices_order').split(','): if deviceId.startswith('-'): deviceId = deviceId[1:] devices[deviceId]={'$deviceId': deviceId, 'attrs':{}, 'properties':{}, '__collapsed': True} self.devices_order.append(deviceId)
# Set trigger to False (Low) GPIO.output(GPIO_TRIGGER, False) GPIO.setup(ACTUATOR,GPIO.OUT) GPIO.output(ACTUATOR, False) #broker configurations IP = '192.168.0.103' PORT = 1884 TOPIC_ACT = "impress/demo" TOPIC_SUB = "impress/action" CLIENT_NAME = 'RASPBERRY' # Connect to MQTT broker. client = client.Mosquitto(CLIENT_NAME) client.connect(IP,PORT,60) class Th(Thread): def __init__ (self, num): Thread.__init__(self) self.num = num def on_connect(client, data, rc): client.subscribe(TOPIC_SUB) print("Connection returned result: " + str(rc)) def on_message(client, userdata, msg): message = str(msg.payload) arrMessage = message.split(";") print(arrMessage[0]);
# MQTT topic TOPIC = 'sensor' if __name__ == '__main__': f = open('./agent.yaml', 'r') conf = yaml.load(f) cpe = conf['cpe'] location = conf['location'] mqtt = conf['mqtt'] topic = mqtt['topic'] client = client.Client() client.connect(host=mqtt['host'], port=mqtt['port'], keepalive=60) # FTDI driver ftdi_list = os.listdir('/dev/serial/by-id') dev_list = [] for ftdi in ftdi_list: path = '/dev/serial/by-id/{}'.format(ftdi) tty = os.path.realpath(path) # symbolic link ser = serial.Serial(tty) usb = tty.split('/')[2] dev_list.append((ftdi, usb, ser)) while True: for dev in dev_list: usb = dev[1]