def property_menu_delete(self): device,prop,propname = self.cur_menu_property topic = mqttprefix+'/'+device['$deviceId']+'/'+propname client.publish(topic, None, retain=True) client.publish(topic+'/$settable', None, retain=True) client.publish(topic+'/$datatype', None, retain=True) client.publish(topic+'/$format', None, retain=True) client.publish(topic+'/$name', None, retain=True)
def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) 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")
def readUltrasonicSensors(): while(1): distance = measure() if distance < 30: client.publish(TOPIC_ACT, "1;1;1") else: client.publish(TOPIC_ACT, "1;1;0") time.sleep(1)
def mqtt_send(device, prop_name, value): print("Publishing ",mqttprefix+'/'+device['$deviceId']+'/'+prop_name+'/set', value) client.publish(mqttprefix+'/'+device['$deviceId']+'/'+prop_name+'/set', value) tlvdata = [ [tlv.T_DISCO_SET,b""], [tlv.T_PROP_NAME, ('/'+device['$deviceId']+'/'+prop_name).encode("utf8")], [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))
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_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')
def handle_hw(data, mqtt): params = data.split("\0") cmd = params.pop(0) if cmd == 'info': pass ### VIRTUAL pin operations if cmd == 'vw': # This should call user handler pin = int(params.pop(0)) val = params.pop(0) log("Virtual write pin %d, value %s" % (pin, val)) mqtt.publish(u"%s/vw/%d" % (TOPIC, pin), val) elif cmd == 'vr': # This should call user handler pin = int(params.pop(0)) log("Virtual read pin %d" % pin) mqtt.publish(u"%s/vr/%d" % (TOPIC, pin)) try: conn.sendall(hw("vw", pin, pin_storage[pin])) except: pass else: log("Unknown HW cmd: %s" % cmd)
def _on_connect(self, client, userdata, dict, rc): print("Connected with result code " + str(rc)) client.publish(self.lwt_topic, 'true', retain=True) client.subscribe(self.realm+"#") for dev in self.devices: client.publish(self.realm+dev.mac_addr_str+'/on/$settable', 'true', retain=True) #client.publish(self.realm+dev.mac_addr_str+'/on/$name', dev['display_name'], retain=True) client.publish(self.realm+dev.mac_addr_str+'/on/$datatype', 'boolean', retain=True) self.publish_state_change(dev)
def parse_line(line): global got_data global vcc global temperature global humidity global pressure global gas global brightness match = re.match("BME680 temperature: ([^ ]+)", line) if match: temperature = float(match.group(1)) match = re.match("BME680 humidity: ([^ ]+)", line) if match: humidity = float(match.group(1)) match = re.match("BME680 pressure: ([^ ]+)", line) if match: pressure = float(match.group(1)) match = re.match("BME680 gas resistance: ([^ ]+)", line) if match: gas = match.group(1) match = re.match("VCC: ([^ ]+)", line) if match: vcc = int(match.group(1)) match = re.match("MAX44009: ([^ ]+)", line) if match: got_data = True brightness = float(match.group(1)) requests.post( "http://influxdb.derf0.net:8086/write?db=sensors", f"bme680,area=hm17,location={location} temperature_celsius={temperature},humidity_relpercent={humidity},pressure_hpa={pressure},air_quality_ohm={gas}", ) requests.post( "http://influxdb.derf0.net:8086/write?db=sensors", f"max44009,area=hm17,location={location} illuminance_lux={brightness}", ) mqtt.publish(f"sensor/hm17/{location}/brightness_lux", brightness) mqtt.publish( f"sensor/hm17/{location}/bme680", json.dumps({ "temperature_celsius": round(temperature, 1), "humidity_percent": round(humidity, 1), "pressure_hpa": pressure, "iaq_ohm": gas, }), ) temperature = None humidity = None pressure = None gas = None vcc = None brightness = None
def mqtt(): mqtt_client.publish("zorelu", "ledoff", 2) # 发布一个主题为'chat',内容为‘hello ’的信息 mqtt_client.loop_start() #mqtt_client.loop_stop(force=False) return "mqtt ok "
time.sleep(1) print('init %d' % get_mac()) last_data_time = int(time.time() * 1000) #send_pin_status() while True: #print('loop') try: #if last_data_time + 100 < int(time.time() * 1000): #ser = serial.Serial('/dev/ttyACM0') #ser.timeout = 1 ser.write('a') # read_analog data = ser.readline().strip() if data: pinvalues = {} for i, v in enumerate(data.split(',')): pinvalues[str(i)] = v payload = {'data': pinvalues, 'type': 'sensorvalue'} mqtt.publish('/hydroots/client/%d' % get_mac(), bytearray(json.dumps(payload))) #last_data_time = int(time.time() * 1000) print('analog read success') except Exception as e: data = {'type': 'ack'} mqtt.publish('/hydroots/client/%d' % get_mac(), bytearray(json.dumps(data))) print('exception during read') mqtt.loop(timeout=1) time.sleep(1)
#Process the message #If msg=turnon, turnon the water pump #If msg=turnoff, turnoff the water pump def on_message(client, userdata, msg): if(msg.payload=='ON'): print(msg.topic+" "+str(msg.payload)) subprocess.call(['gpio','export',RELAY_PIN,'out']) elif(msg.payload=='OFF') print(msg.topic+" "str(msg.payload)) subprocess.call(['gpio','export',RELAY_PIN,'in']) # Notify the broker that a new pi wants to connect # First time communicate through the common topic 'register' def register(macaddress) mqtt.publish("register/",macaddress) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("test.mosquitto.org", 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 main(): #configuración de la comuncación con protocolo mqtt client = paho.mqtt.client.Client("Unimet", False) client.qos = 0 client.connect(host='localhost') #Peso max y min de cada envio en kgs meanTonelada = 5 precioOroKg = 42900 stdTonelada = 2 repetir = 2500 #Para conectarnos con la base de datos en postgres conn = psycopg2.connect(host='localhost', user='******', password='******', dbname='cerveceria') #conn = psycopg2.connect(host = 'ec2-107-20-167-11.compute-1.amazonaws.com', user= '******', password ='******', dbname= 'd7dcs98v6bp756') cursor = conn.cursor() conn.autocommit = True #Para saber la cantidad de proveedores primer query cantidadproveedores = 'SELECT COUNT(id) FROM proveedor' cursor.execute(cantidadproveedores) conn.commit() #Guardar el resultado en una variable "devuelve un array o tupla" fa = cursor.fetchall() cantidadpesos = 'SELECT COUNT(id_peso) FROM peso_automatico' cursor.execute(cantidadpesos) conn.commit() peso = cursor.fetchall() fi = int(np.random.uniform(fa, fa)) hoy = date.today() estado = 'materiaprima' while (repetir > 0): repetir = repetir - 1 hoy = hoy + timedelta(days=7) time.sleep(10) for i in range(1, fi + 1): #Simula el peso que debe generar el peso cantidadTonelada = int(np.random.normal(meanTonelada, stdTonelada)) query = "SELECT fk_mp FROM proveedor WHERE id=%s" cursor.execute(query, (i, )) conn.commit() fe = (cursor.fetchall()) #Para saber el proveedor fk_MP = int(np.random.uniform(fe, fe)) #Id del peso que ejecuto el envio peso_aut = int(np.random.uniform(1, peso)) precioTotal = cantidadTonelada * precioOroKg payload = { "fecha": str(hoy + timedelta(days=np.random.uniform(0, 6))), "cantidad": str(cantidadTonelada), "proveedor": str(i), "mp": str(fk_MP), "peso": str(peso_aut), "est": str(estado), "costototal": str(precioTotal) } client.publish('unimet/admin/bd', json.dumps(payload), qos=0) print(payload) time.sleep(2) cantidadTonelada = int(np.random.normal(meanTonelada, stdTonelada)) peso_aut = int(np.random.uniform(1, peso)) precioTotal = cantidadTonelada * precioOroKg payload1 = { "fecha": str(hoy + timedelta(days=np.random.uniform(0, 6))), "cantidad": str(cantidadTonelada), "proveedor": str(i), "mp": str(fk_MP), "peso": str(peso_aut), "est": str(estado), "costototal": str(precioTotal) } client.publish('unimet/admin/bd', json.dumps(payload1), qos=0) print(payload1) time.sleep(2)
def on_message(client, userdata, msg): objson = json.loads(str(msg.payload, 'utf-8')) txt = objson["text"] author = objson["anthor"] if len(author) > 0: print(txt + " -- " + author) else: print(txt) print(" ", flush=True) def mqtt_start(): client.username_pw_set("hjpc", "htxzdj") client.on_connect = on_connect client.on_message = on_message client._client_id = clitntID + str(hex(random.randint( 0, 0xffffffff))) #产生随机clientID client.connect(aliHOST, aliPORT, 60) print("pyOneLineServer 初始化结束, 等待请阅请求", flush=True) client.loop_start() if __name__ == "__main__": client = paho.mqtt.client.Client(transport='tcp') mqtt_start() while True: client.publish(topic='hjOneLineGet', payload="text") time.sleep(2) #不要小于0.1,否则会发生很多丢包情况 quit()
def main(): client = paho.mqtt.client.Client("Unimet", False) client.qos = 0 client.connect(host='localhost') canttiendas = cursor.execute('select count(*) from tienda') canttiendas = cursor.fetchone()[0] cursor.execute('select count(*) from telf_inteligente') cantphones = cursor.fetchone()[0] segundos = 50 while(True): tienetelf = random.choice([True, False]) iddetienda = random.randint(1,canttiendas) cursor.execute("select count(*) from estadisticas_tienda where ingreso = true AND id_camara ='%s' " % iddetienda) personaentraron = cursor.fetchone()[0] cursor.execute("select count(*) from estadisticas_tienda where ingreso = false AND id_camara ='%s' " % iddetienda) personasalieron = cursor.fetchone()[0] personasentienda = personaentraron - personasalieron idtelf=0 if tienetelf == True: cursor.execute("SELECT id_telf FROM estadisticas_tienda where id_camara ='%s' ORDER BY fecha_hora DESC LIMIT 1 "% iddetienda ) prueba=cursor.rowcount print(prueba) #hola=cursor.fetchone()[0] #print(hola) if prueba ==1: hola=cursor.fetchone()[0] if hola is not None: idtelf = hola print(idtelf) cursor.execute("SELECT ingreso FROM estadisticas_tienda where id_camara ='%s' AND id_telf='%s' ORDER BY fecha_hora DESC LIMIT 1 " ,(iddetienda,idtelf) ) variablebool = cursor.fetchone()[0] if variablebool == False: cont = 0 while(True): idtelf = random.randint(1,cantphones) cursor.execute("SELECT ingreso FROM estadisticas_tienda where id_camara ='%s' AND id_telf ='%s' ORDER BY fecha_hora DESC LIMIT 1 ",(iddetienda,idtelf)) chao=cursor.rowcount print('aaa') #print(chao) cont = cont + 1 if chao==1: chao2 = cursor.fetchone()[0] if chao2 is not None: estaentienda = chao if estaentienda == True: break elif cont >50: idtelf=0 break else: idtelf=0 if personasentienda>0: sumaventa = 250 segundos = segundos + sumaventa minutventa= datetime.timedelta(seconds=segundos) horaventa = datetime.datetime.now() + minutventa nombre = names.get_full_name() cedula = random.randint(1,30000000) total = random.randint(1000,100000) payload = { "monto":str(total), "fecha_horaventa": str(horaventa), "id_tienda": str(iddetienda), "id_telf":str(idtelf), "cedula":str(cedula), "nombre":str(nombre), "query":str('venta') } client.publish('unimet/admin/bd',json.dumps(payload),qos=0) print(payload) time.sleep(0.5)
def stop_all(client, reason): for node in array_node_id: print('stop: ' + node) client.publish(TOPIC_PREFIX + '/stop/' + node, reason) client.publish(TOPIC_PREFIX + '/stop/' + RANDNAME, reason) log_print('send stop: ' + reason)
import serial import paho.mqtt.client as broker from time import sleep # connect to broker host = '192.17.189.184' port = '1885' nodeName = '3d_printers' topic = "heatMap/{}".format(nodeName) ser = serial.Serial('/dev/tty.usbserial', 9600) broker.connect(host, port) broker.loop_start() while True: payload = ser.readline() broker.publish(topic, payload) sleep(0.5)
def on_connect(client, userdata, flags, rc): print('Conexion a MQTT server establecida (%s)' % client._client_id) client.subscribe(topic='broadlink/#', qos=2) client.publish("broadlink/record", nombre)
sensor = sensoren[name] messdaten = aktuelleTemperatur(sensor) zeitstempel = datetime.datetime.now().timestamp() if messdaten != None: protokoll = str(zeitstempel) + ": " + name + ": " + str(messdaten) print(protokoll) with open("messdaten.log", "a") as file: file.write(protokoll + "\n") client.publish("haus/har/temperatur/"+name, messdaten) else: print(name + ': Messfehler') print("finished") def pegel(url): my_pegel_request = requests.get(url) my_pegel_text = my_pegel_request.text my_pegel_json = json.loads(my_pegel_text) my_pegel = float(my_pegel_json["timeseries"][0]["currentMeasurement"]["value"]) return my_pegel mqtt = mqttVerbindungsaufbau() while True: messen(mqtt) mqtt.publish("haus/pegel/oberwinter", pegel(oberwinter)) time.sleep(900) mqtt.loop_stop() mqtt.disconnect()
def handle_publish(json_str): data = json.loads(json_str) mqtt.publish(data['topic'], data['message'])
def main(): client.qos = 0 client.connect(host='localhost') meanEntrada = 10 stdEntrada = 2 day = 1 while (day != 30): print('----------------------------------------------Dia ', day, '---------------------------------------------------------') personasPorDia = np.random.normal(meanEntrada, stdEntrada) while (personasPorDia > 1): mes = np.random.randint(1, 13) if mes == 2: dia = np.random.randint(1, 28) else: dia = np.random.randint(1, 31) print( '---------------------Persona Nueva-------------------------') horaBase = datetime.datetime.now().replace(hour=0, minute=0, second=0, day=dia, month=mes) hora = horaBase + datetime.timedelta( hours=np.random.uniform(10, 20)) + datetime.timedelta( minutes=np.random.uniform(0, 60)) datosSensor = Sensor() sensor = np.random.randint(datosSensor[0], datosSensor[1] + 1) ma_r = np.random.normal(1, 11) if ma_r >= 1 and ma_r <= 7: sexo = Gender() mc = personasMA() if mc[0] == True: mcAdress = generateMC() cedula = np.random.uniform(1000000, 15000000) while (cedula < 0): cedula = np.random.uniform(1000000, 15000000) cedula = round(cedula) personasCMA(mcAdress, sexo, sensor, hora, mc, cedula) time.sleep(0.5) recorrido(hora, mcAdress, cedula) else: duracionNMC(sensor, hora, sexo, mc[1]) else: sexo = Gender() mc = personasMA() ma_dev = devolver_ma() if ma_dev == []: mc = personasMA() if mc[0] == True: mcAdress = generateMC() cedula = np.random.uniform(1000000, 15000000) while (cedula < 0): cedula = np.random.uniform(1000000, 15000000) cedula = round(cedula) personasCMA(mcAdress, sexo, sensor, hora, mc, cedula) time.sleep(0.5) recorrido(hora, mcAdress, cedula) else: duracionNMC(sensor, hora, sexo, mc[1]) else: ma_escogido = escoger_ma(ma_dev)[0] ultimoA = ultimoAcceso(ma_escogido) separar = ultimoA.split('-', 3) mes = int(separar[1]) dia = int(separar[2].split(' ')[0]) if dia == hora.day and mes == hora.month: mc = personasMA() if mc[0] == True: mcAdress = generateMC() cedula = np.random.uniform(1000000, 15000000) while (cedula < 0): cedula = np.random.uniform(1000000, 15000000) cedula = round(cedula) personasCMA(mcAdress, sexo, sensor, hora, mc, cedula) time.sleep(0.5) recorrido(hora, mcAdress, cedula) else: duracionNMC(sensor, hora, sexo, mc[1]) else: print('---------Persona Antes Registrada---------') payload = { "idsensor": int(sensor), "fecha_hora": str(hora), "mcadress": str(ma_escogido), "nombre": '', "edad": '' } client.publish('sambil/sensores/entrada', json.dumps(payload), qos=0) print(payload) time.sleep(0.5) cedula = int(CedulaMA(ma_escogido)) recorrido(hora, ma_escogido, cedula) personasPorDia -= 1 day = day + 1
def recorridoNMC(hora, sexo, edad): visitas = cantTiendas(hora) cedula = np.random.uniform(1000000, 15000000) while (cedula < 0): cedula = np.random.uniform(1000000, 15000000) cedula = round(cedula) cond = (visitas[0] + visitas[1] + visitas[2]) while (cond != 0): if visitas[1] == 0 and visitas[0] != 0 or visitas[ 2] == 0 and visitas[0] != 0: #Tiendas Normales datosTiendas = tiendas() normal = np.random.randint(datosTiendas[0], datosTiendas[1] + 1) datosNormal = sensor_tiendas(normal) sensorN = np.random.randint(datosNormal[0], datosNormal[1] + 1) hora = hora + datetime.timedelta(minutes=np.random.randint(2, 8)) payload = { "idsensor": int(sensorN), "fecha_hora": str(hora), "mcadress": '', "nombre": '', "apellido": '', "telefono": '', "sexo": str(sexo), "edad": int(edad) } client.publish('sambil/sensores/tiendas-mesas', json.dumps(payload), qos=0) print('---------Entrando a tienda-----------') print(payload) time.sleep(0.5) comprar = np.random.randint(1, 3) print('comprar:', comprar) if comprar == 1: comprarTienda(normal, '', cedula, hora) sensorN = np.random.randint(datosNormal[0], datosNormal[1] + 1) salida = np.random.randint(10, 31) hora = hora + datetime.timedelta(minutes=salida) payload = { "idsensor": int(sensorN), "fecha_hora": str(hora), "mcadress": '', "nombre": '', "apellido": '', "telefono": '', "sexo": str(sexo), "edad": int(edad) } client.publish('sambil/sensores/tiendas-mesas', json.dumps(payload), qos=0) print('---------Saliendo de tienda-----------') print(payload) visitas[0] = visitas[0] - 1 time.sleep(0.5) elif visitas[0] == 0 and visitas[1] != 0 or visitas[ 2] == 0 and visitas[1] != 0: #Tiendas de comida donde SI compra datosTC = tiendasComida() comidaC = np.random.randint(datosTC[0], datosTC[1] + 1) datosSensorT = sensor_tiendas(comidaC) sensorC = np.random.randint(datosSensorT[0], datosSensorT[1] + 1) hora = hora + datetime.timedelta(minutes=np.random.randint(2, 8)) payload = { "idsensor": int(sensorC), "fecha_hora": str(hora), "mcadress": '', "nombre": '', "apellido": '', "telefono": '', "sexo": str(sexo), "edad": int(edad) } client.publish('sambil/sensores/tiendas-mesas', json.dumps(payload), qos=0) print('---------Entrando a tienda-----------') print(payload) compraComida(comidaC, '', hora, sexo, edad, cedula) visitas[1] = visitas[1] - 1 elif visitas[0] == 0 and visitas[2] != 0 or visitas[ 1] == 0 and visitas[2] != 0: #Tiendas de comida donde NO compra datosTNC = tiendasComida() comidaNC = np.random.randint(datosTNC[0], datosTNC[1] + 1) datosSTNC = sensor_tiendas(comidaNC) sensorNC = np.random.randint(datosSTNC[0], datosSTNC[1] + 1) hora = hora + datetime.timedelta(minutes=np.random.randint(2, 8)) payload = { "idsensor": int(sensorNC), "fecha_hora": str(hora), "mcadress": '', "nombre": '', "apellido": '', "telefono": '', "sexo": str(sexo), "edad": int(edad) } client.publish('sambil/sensores/tiendas-mesas', json.dumps(payload), qos=0) print('---------Entrando a tienda-----------') print(payload) time.sleep(0.5) sensorNC = np.random.randint(datosSTNC[0], datosSTNC[1] + 1) salida = np.random.randint(5, 10) hora = hora + datetime.timedelta(minutes=salida) payload = { "idsensor": int(sensorNC), "fecha_hora": str(hora), "mcadress": '', "nombre": '', "apellido": '', "telefono": '', "sexo": str(sexo), "edad": int(edad) } client.publish('sambil/sensores/tiendas-mesas', json.dumps(payload), qos=0) print('---------Saliendo de tienda-----------') print(payload) visitas[2] = visitas[2] - 1 time.sleep(0.5) cond = cond - 1 hora = hora + datetime.timedelta(minutes=np.random.randint(2, 8)) datosSensor = Sensor() sensor = np.random.randint(datosSensor[0], datosSensor[1] + 1) payload = { "idsensor": int(sensor), "fecha_hora": str(hora), "mcadress": '', "nombre": '', "apellido": '', "telefono": '', "sexo": str(sexo), "edad": int(edad) } client.publish('sambil/sensores/entrada', json.dumps(payload), qos=0) print('---------Saliendo de CC-----------') print(payload)
def _set_subscribe_topics(self, client, userdata, flags, respons_code): client.subscribe('+/{0}/#'.format(self.name)) if self.rwt_use: client.publish('stat/{0}/LWT'.format(self.name), 'Online', retain=self.rwt_retain)
def on_message(client, userdata, msg): print(f"{msg.topic} {msg.payload}") save_message(msg.payload.decode()); client.publish(topic="ret",payload="Viraj",qos=1,retain=False)
def on_message(client, userdata, msg): # logger.debug("----receiv----") logger.debug("%s:%s" % (msg.topic, msg.payload)) if msg.topic == "dev": try: # device_id = struct.unpack("32s", msg.payload) # device_id_hex = ## modified from last change, hex string to int dev_str = msg.payload.decode('ascii').split('.') # device_id = int(msg.payload, 16) # add = 1 # device_id, add = struct.unpack("QI", msg.payload) # device_id = int(msg.payload[0]) logger.info("dev_s:%s" % dev_str) except: # device_id = 1 logger.error('unpack error') return try: device_id = dev_str[0] #int(dev_str[0], 16) #parse hex to int device_pin = int(dev_str[1]) pin_id = "%s%d" % (device_id, device_pin) except: logger.error('wrong device id format') return if not device_id == 0: # add = int(msg.payload[2]) shopid = deltaChange.put_dev(device_id, 1) logger.info('put shop %s' % shopid) deltaChange.put_shop(shopid, 1) deltaChange.update(device_id) body = generate_chart_data(device_id) # TODO try: client.publish("shop%s" % shopid, body, qos=2) logger.info('sent updated shop %s' % shopid) except: logger.error('update error') # start show case elif msg.topic == 'remote': logger.info('receive %s : %s' %(msg.topic, msg.payload)) remote_register = str(msg.payload.decode('ascii')).split('.') if len(remote_register) == 4 and remote_register[0] == 'hb': #TODO: push the device's online duration #device_id = int(remote_register[1], 16) #time = int(remote_register[2]) # right now worked try: logger.debug('remote/hb/device:%s' % int(remote_register[1], 16)) except: logger.error('hb parse error:%s' % remote_register) device_id = remote_register[1] #int(remote_register[1], 16) time = int(remote_register[2]) # in munite live_status = parseSigStatus(remote_register[3]) # TODO: need filter elif len(remote_register) == 3 and remote_register[0] == 'wb': #new_device_id = int(remote_register[0], 16) websession = remote_register[2] # need shopid from the msg shopid = int(remote_register[1]) body = generate_chart_data(shopid) logger.info('web %s join in' % shopid) client.publish("shop%s" % shopid, body, qos=2) else: return else: logger.info('receive %s : %s' %(msg.topic, msg.payload))
def on_message(client, userdata, msg): print("收到订阅 hjOneLineGet 内容: " + str(msg.payload), flush=True) text = radomLine() client.publish(topic='hjOneLinePut', payload=text)
def on_message(mosq, obj, msg): contents = str(msg.payload) print(contents) # Read MQTT Feed # Split Based on Spaces data = contents.split() # Get Conditions Code from ClientRaw conditions = (data[48]) # Get Temperature Code from ClientRaw temp = str(data[4]) # Get Temperature Trend and Convert Code from ClientRaw temptrend = int(data[143]) if temptrend == 1: temptrend = "& Rising" if temptrend == -1: temptrend = "& Falling" # Get Pressure Code from ClientRaw press = str(data[6]) # Get Pressure Trend and Convert Code from ClientRaw presstrend = float(data[50]) if presstrend > +0.1: presstrend = "& Rising" elif presstrend < -0.1: presstrend = "& Falling" else: presstrend = "& Steady" # Get Rain Code from ClientRaw rainday = str(data[7]) # Get Rain Rate Code from ClientRaw - to Trigger Show Rain on MQTT Feed rainrate = float(data[10]) # Get Wind Gust (Av Last 10 Min) Code from ClientRaw wind = str(data[158]) # Get Wind Direction and Convert Code to Readable Direction from ClientRaw windir = int(data[3]) if windir >= 11.25 and windir < 33.75: windir = "North North East" elif windir >= 33.75 and windir < 56.25: windir = "North East" elif windir >= 56.25 and windir < 78.75: windir = "East North East" elif windir >= 78.75 and windir < 101.25: windir = East elif windir >= 101.25 and windir < 123.75: windir = "East South East" elif windir >= 123.75 and windir < 146.25: windir = "South East" elif windir >= 146.25 and windir < 168.75: windr = "South South East" elif windir >= 168.75 and windir < 191.25: windir = "Southerly" elif windir >= 191.25 and windir < 213.75: windir = "South South West" elif windir >= 213.75 and windir < 236.25: windir = "South West" elif windir >= 236.25 and windir < 258.75: windir = "West South West" elif windir >= 258.75 and windir < 281.25: windir = "Westerly" elif windir >= 281.25 and windir < 303.75: windir = "West North West" elif windir >= 303.75 and windir < 326.25: windir = "North West" elif windir >= 326.25 and windir < 348.75: windir = "North North West" else: windir = "Northerly" # Remap Conditions Code to Text # Sunny if conditions == '0': conditions = 'Sunny' # Mainly cloudy if conditions == '18': conditions = 'Dry, Mainly Cloudy' # Partly cloudy if conditions == '19': conditions = 'Partly Cloudy' if conditions == '2': conditions = 'Partly Cloudy' if conditions == '3': conditions = 'Partly Cloudy' # Sunny Spells if conditions == '5': conditions = 'Sunny Spells' # Light Rain if conditions == '21': conditions = 'Light Rain' if conditions == '22': conditions = 'Light Rain' if conditions == '23': conditions = 'Light Rain' # Night Light Rain if conditions == '15': conditions = 'Light Rain' # Rain if conditions == '20': conditions = 'Rain' # Night Rain if conditions == '14': conditions = 'Night Time: Rain' # Stopped raining - Day or Night if conditions == '34': conditions = 'Stopped Raining' # Night Clear if conditions == '1': conditions = 'Night Time, Clear' # Night Fog if conditions == '11': conditions = 'Night Time, Mist/Fog' # Sleet if conditions == '16': conditions = 'Sleet' # Print and Publish Output output_string = "The Weather is " + conditions + ", " + temp + " Degrees Centigrade " + temptrend + "," + " " + "Pressure: " + press + " Mb " + presstrend + ", Wind " + windir + " " + wind + " Mph" output_string_rain = "The Weather is " + conditions + ", " + rainday + " mm" + ", " + temp + " Degrees Centigrade " + temptrend + "," + " " + "Pressure: " + press + " Mb " + presstrend + ", Wind " + windir + " " + wind + " Mph" #Get Time currentDT = datetime.datetime.now() #Print Time print("Publishing at: ", currentDT.strftime("%I:%M:%S %p")) #Print Output print(output_string) # Send to MQTT print("Publishing message to topic") #Publish to MQTT - Include Rain if Rain Rate Hour is > 0mm if rainrate > 0: paho.publish("eink/home", output_string_rain ) # topic to publish the conditions to ie eink/messages else: paho.publish("eink/home", output_string ) # topic to publish the conditions to ie eink/messages
def tell(whom, what, client=None): if not client: client = _MQTTC client.publish("tell/" + whom, what)
def on_connect(client, userdata, flags, rc): print('Connected') mqtt.subscribe('hermes/#') mqtt.publish("hermes/hotword/default/detected")
# Connect to broker with client client.connect(mqtt_host, mqtt_port) logging.info("Connected to ags broker") # Loop and send every 30 second # Create JSON body client.loop_start() while True: seed(time.time()) current = str(int(time.time())) data = { "token": token, "data": { "timestamp": current, "temperature": randint(20, 30), "humidity": randint(30, 40), "light": randint(300, 400), "soil_moisture": randint(300, 400), "water_level": 511 }, } body = json.dumps(data) logging.info(body) # Publish data to broker info = client.publish("mqtt/influx", body, 1, False) info2 = client.publish("mqtt/rethink", body, 1, False) time.sleep(30)
def audioplay6(): if request.method == 'POST': topic = '{}/feeds/onoff'.format(USERNAME) client.publish(topic, payload="6a") print(topic) return {'hello': 'world'}
print("Bye!") sys.exit() hx = HX711(20, 16) hx.set_reading_format("MSB", "MSB") hx.set_reference_unit(referenceUnit) hx.reset() hx.tare() mqtt = mqtt.Client("Pi1") # MQTT Client Name mqtt.connect("192.168.137.1", 1883) # MQTT Broker Add isSit = "false" mqtt.publish("Pi1", "{\"s1_isSit\":false}") # initialization while True: try: val = hx.get_weight(5) print(val) if val > 20: # load over 20Kg if isSit != "true": mqtt.publish("Pi1", "{\"s1_isSit\":true}") isSit = "true" else: # load under 20Kg if isSit != "false": mqtt.publish("Pi1", "{\"s1_isSit\":false}") isSit = "false"
# if msg.payload == b"Hello": # print("Received message #1, do something") # # if msg.payload == b"World!": # print("Received #2") mqtt = mqtt.Client(userdata="alto") mqtt.username_pw_set("alto","Ihm$2Te0T") # mqtt.on_connect = on_connect # mqtt.on_message = on_message mqtt.connect_async(host="192.168.1.127",port=1883) mqtt.loop_start() print("saas") while True: time.sleep(3) status = "off" topic = "cmnd/tasmota/light_D8DF25/power0" mqtt.publish(topic=topic,payload=status) topic = "cmnd/tasmota/light_D8DF25/power1" mqtt.publish(topic=topic,payload=status) topic = "cmnd/tasmota/light_D8DF25/power2" mqtt.publish(topic=topic,payload=status) time.sleep(3) status = "on" topic = "cmnd/tasmota/light_D8DF25/power0" mqtt.publish(topic=topic,payload=status) topic = "cmnd/tasmota/light_D8DF25/power1" mqtt.publish(topic=topic,payload=status) topic = "cmnd/tasmota/light_D8DF25/power2" mqtt.publish(topic=topic,payload=status)
def _on_connect(self, client, userdata, dict, rc): print("Connected with result code " + str(rc)) client.publish(self.lwt_topic, 'true', retain=True) client.publish(self.realm+'$fw/name', 'pulseaudio-mqtt', retain=True) client.publish(self.realm+'$name', 'Lautstärkeregler', retain=True) client.subscribe(self.realm+"#") for dev_path, dev in self.devices.items(): print(dev_path) client.publish(self.realm+dev['name']+'/volume/$settable', 'true', retain=True) client.publish(self.realm+dev['name']+'/volume/$name', dev['display_name'], retain=True) client.publish(self.realm+dev['name']+'/volume/$datatype', 'float', retain=True) client.publish(self.realm+dev['name']+'/volume/$format', '0:1.5', retain=True) self.publish_volume(dev_path, dev['volume'])
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] ser = dev[2] raw_data = ser.readline()[:-1] data = json.dumps(dict(cpe=cpe, location=location, usb=usb, data=raw_data)) client.publish(topic, data)
def change_device_name(self,device): attrs=', '.join([k+'='+v for k, v in device['attrs'].items()]) old_name = device['attrs'].get('$name','(unnamed)') new_name = simpledialog.askstring("Device name", attrs, initialvalue=old_name) if new_name != None: client.publish(mqttprefix+'/'+device['$deviceId']+'/$name', new_name, retain=True)
import paho.mqtt.client as mqtt mqtt = mqtt.Client() mqtt.connect("Localhost", 1883) mqtt.publish("DriveChannel", "Hello, World!")
def publish_t_h(t, h): mqtt.publish(t, "temperature") mqtt.publish(h, "humidity")
def compraComida(comidaC, mcAdress, hora, sexo, edad, cedula): print('----------Comprando Comida-----------') factura = np.random.randint(1111111, 9999999) monto = np.random.uniform(10, 300) monto = round(monto, 2) mesa = np.random.randint(1, 3) if mcAdress != '': if np.random.randint(1, 3) == 2: cedula = np.random.uniform(1000000, 15000000) while (cedula < 0): cedula = np.random.uniform(1000000, 15000000) cedula = round(cedula) hora = hora + datetime.timedelta(minutes=np.random.randint(7, 10)) payload = { "factura": int(factura), "idtienda": int(comidaC), "monto": float(monto), "mcadress": str(mcAdress), "cedula": int(cedula), "fecha_hora": str(hora) } client.publish('sambil/compra/mcadress', json.dumps(payload), qos=0) print(payload) if mesa == 1 and mcAdress != '': hora = hora + datetime.timedelta(minutes=np.random.randint(2, 5)) datosSM = sensor_mesa(comidaC) mesa = np.random.randint(datosSM[0], datosSM[0] + 1) payload = { "idsensor": int(mesa), "fecha_hora": str(hora), "mcadress": str(mcAdress), } client.publish('sambil/sensores/tiendas-mesas', json.dumps(payload), qos=0) print("-------Usando Mesa-------") print(payload) time.sleep(0.5) hora = hora + datetime.timedelta(minutes=np.random.randint(60, 110)) elif mesa == 1 and mcAdress == '': hora = hora + datetime.timedelta(minutes=np.random.randint(2, 5)) datosSM = sensor_mesa(comidaC) mesa = np.random.randint(datosSM[0], datosSM[0] + 1) payload = { "idsensor": int(mesa), "fecha_hora": str(hora), "mcadress": '', "nombre": '', "apellido": '', "telefono": '', "sexo": str(sexo), "edad": int(edad) } client.publish('sambil/sensores/tiendas-mesas', json.dumps(payload), qos=0) print("-------Usando Mesa-------") print(payload) time.sleep(0.5) hora = hora + datetime.timedelta(minutes=np.random.randint(60, 110)) if mcAdress != '': salirTiendasComidamc(comidaC, hora, mcAdress) else: salirTiendasComidaNMC(comidaC, hora, sexo, edad)
def publish(destinationQueue,action): mqtt.publish('\\'+ destinationQueue,action)
def main(): client = paho.mqtt.client.Client("Unimet", False) client.qos = 0 client.connect(host='localhost') payload = { "personas": [{ "idpersona": "1", "edad": "20", "sexo": "masculino", "macaddress": "3001", "estado": "1", "aux": "1" }, { "idpersona": "2", "edad": "30", "sexo": "femenino", "macaddress": "3002", "estado": "1", "aux": "1" }, { "idpersona": "3", "edad": "40", "sexo": "femenino", "macaddress": "3003", "estado": "1", "aux": "1" }, { "idpersona": "4", "edad": "50", "sexo": "femenino", "macaddress": "3004", "estado": "1", "aux": "0" }, { "idpersona": "5", "edad": "60", "sexo": "masculino", "macaddress": "3005", "estado": "1", "aux": "0" }, { "idpersona": "6", "edad": "15", "sexo": "masculino", "macaddress": "3006", "estado": "1", "aux": "1" }, { "idpersona": "7", "edad": "35", "sexo": "femenino", "macaddress": "3007", "estado": "1", "aux": "1" }, { "idpersona": "8", "edad": "40", "sexo": "femenino", "macaddress": "3008", "estado": "1", "aux": "1" }, { "idpersona": "9", "edad": "52", "sexo": "femenino", "macaddress": "3009", "estado": "1", "aux": "0" }] } client.publish('unimet/admin/bd', json.dumps(payload), qos=0)
def main(): client = paho.mqtt.client.Client("Unimet", False) client.qos = 0 client.connect(host='localhost') cantsensores = cursor.execute('select count(*) from camara_acc') cantsensores = cursor.fetchone()[0] cantpersonas = cursor.execute('select count(*) from persona') cantpersonas = cursor.fetchone()[0] horaBase = datetime.datetime.now() horaBase = horaBase segun = 50 segundos = 100 numerotiendas = cursor.execute('select count(*) from tienda') numerotiendas = cursor.fetchone()[0] camarastienda = cursor.execute('select count(*) from camara_tienda') camarastienda = cursor.fetchone()[0] while (True): cursor.execute( 'select count(*) from estadisticas_acceso where ingreso = false') HanSalidocc = cursor.fetchone()[0] cursor.execute( 'select count(*) from estadisticas_acceso where ingreso = true') HanEntradocc = cursor.fetchone()[0] if HanEntradocc > HanSalidocc: #personas que entran y salen de tiendas aun sin telf contelf = random.choice([True, False]) idtienda = random.randint(1, camarastienda) HanEntradotienda = cursor.execute( "select count(*) from estadisticas_tienda where ingreso = true AND id_camara = '%s'" % idtienda) HanEntradotienda = cursor.fetchone()[0] HanSalidotienda = cursor.execute( "select count(*) from estadisticas_tienda where ingreso = false AND id_camara = '%s'" % idtienda) HanSalidotienda = cursor.fetchone()[0] if HanEntradotienda > HanSalidotienda: bootienda = random.choice([True, False]) elif HanEntradotienda == HanSalidotienda: bootienda = True sumatienda = 250 segundos = segundos + sumatienda minutienda = datetime.timedelta(seconds=segundos) horatienda = datetime.datetime.now() + minutienda telf = 0 if bootienda == False and contelf == False: cont = 0 while (True): cantidaddeaccesos3 = cursor.execute( 'select count(*) from estadisticas_acceso') cantidaddeaccesos3 = cursor.fetchone()[0] idtienda = random.randint(1, camarastienda) aleatorio3 = random.randint(1, cantidaddeaccesos3) sql4 = '''select id_persona from estadisticas_acceso where id_estadi_acceso = %s;''' cursor.execute(sql4, ([aleatorio3])) personaaleatoria3 = cursor.fetchone()[0] cursor.execute( "select count(*) from estadisticas_acceso where ingreso = true AND id_persona = '%s' " % personaaleatoria3) DeEsosEntraron3 = cursor.fetchone()[0] cursor.execute( "select count(*) from estadisticas_acceso where ingreso = false AND id_persona = '%s' " % personaaleatoria3) DeEsosSalieron3 = cursor.fetchone()[0] #persona3 = personaaleatoria3 cursor.execute( "select count(*) from estadisticas_tienda where ingreso = true AND id_persona = '%s' AND id_camara = '%s'", (personaaleatoria3, idtienda)) DeEsosentraronAtienda = cursor.fetchone()[0] cursor.execute( "select count(*) from estadisticas_tienda where ingreso = false AND id_persona = '%s' AND id_camara = '%s' ", (personaaleatoria3, idtienda)) DeEsossalierondetienda = cursor.fetchone()[0] cont = cont + 1 #print(cont) personatienda = personaaleatoria3 if (DeEsosEntraron3 > DeEsosSalieron3 and DeEsosentraronAtienda > DeEsossalierondetienda ) or cont == 500: break bootienda = True elif bootienda == True and contelf == False: while (True): cantidaddeaccesos2 = cursor.execute( 'select count(*) from estadisticas_acceso') cantidaddeaccesos2 = cursor.fetchone()[0] aleatorio2 = random.randint(1, cantidaddeaccesos2) sql3 = '''select id_persona from estadisticas_acceso where id_estadi_acceso = %s;''' cursor.execute(sql3, ([aleatorio2])) personaaleatoria2 = cursor.fetchone()[0] cursor.execute( "select count(*) from estadisticas_acceso where ingreso = true AND id_persona = '%s' " % personaaleatoria2) DeEsosEntraron2 = cursor.fetchone()[0] cursor.execute( "select count(*) from estadisticas_acceso where ingreso = false AND id_persona = '%s' " % personaaleatoria2) DeEsosSalieron2 = cursor.fetchone()[0] persona2 = personaaleatoria2 personatienda = persona2 if DeEsosEntraron2 > DeEsosSalieron2: break if bootienda == False and contelf == True: cursor.execute( "select count(*) from estadisticas_acceso where id_telf is not null and ingreso=true" ) si = cursor.fetchone()[0] cursor.execute( "select count(*) from estadisticas_acceso where id_telf is not null and ingreso=false" ) no = cursor.fetchone()[0] if si > no: cont = 0 while (True): #print(cont) cursor.execute( "select id_estadi_acceso from estadisticas_acceso where id_telf is not null" ) rows = cursor.fetchall() result_list = list(itertools.chain(*rows)) #result_list = [row for row in rows] cursor.execute( "select count(*) from estadisticas_acceso where id_telf is not null" ) resultado = cursor.fetchone()[0] numero = random.randint(1, resultado) id = result_list[numero - 1] cursor.execute( "select id_telf from estadisticas_acceso where id_estadi_acceso = '%s'" % id) telf = cursor.fetchone()[0] cursor.execute( "select count(*) from estadisticas_acceso where ingreso = true AND id_telf = '%s'" % telf) telfentraron = cursor.fetchone()[0] cursor.execute( "select count(*) from estadisticas_acceso where ingreso = false AND id_telf = '%s'" % telf) telfsalieron = cursor.fetchone()[0] cont = cont + 1 if telfentraron > telfsalieron or cont > 2000: cursor.execute( "select count(*) from estadisticas_tienda where id_telf = '%s' AND id_camara = '%s' and ingreso = true", (telf, idtienda)) contelfentienda = cursor.fetchone()[0] cursor.execute( "select count(*) from estadisticas_tienda where id_telf = '%s' AND id_camara = '%s' and ingreso = false", (telf, idtienda)) contelfentienda2 = cursor.fetchone()[0] cont = cont + 1 if contelfentienda > contelfentienda2: cursor.execute( "select id_persona from telf_inteligente where id_telf = '%s'" % telf) personatienda = cursor.fetchone()[0] break elif cont > 2002: telf = 0 break elif bootienda == True and contelf == True: cursor.execute( "select count(*) from estadisticas_acceso where id_telf is not null and ingreso=true" ) si = cursor.fetchone()[0] cursor.execute( "select count(*) from estadisticas_acceso where id_telf is not null and ingreso=false" ) no = cursor.fetchone()[0] if si > no: cont = 0 while (True): #print('yeaaaa') cursor.execute( "select id_estadi_acceso from estadisticas_acceso where id_telf is not null" ) rows = cursor.fetchall() result_list = list(itertools.chain(*rows)) #result_list = [row for row in rows] cursor.execute( "select count(*) from estadisticas_acceso where id_telf is not null" ) resultado = cursor.fetchone()[0] numero = random.randint(1, resultado) id = result_list[numero - 1] cursor.execute( "select id_telf from estadisticas_acceso where id_estadi_acceso = '%s'" % id) telf = cursor.fetchone()[0] cursor.execute( "select count(*) from estadisticas_acceso where ingreso = true AND id_telf = '%s'" % telf) telfentraron = cursor.fetchone()[0] cursor.execute( "select count(*) from estadisticas_acceso where ingreso = false AND id_telf = '%s'" % telf) telfsalieron = cursor.fetchone()[0] cont = cont + 1 #print(cont) if telfentraron > telfsalieron or cont > 500: cursor.execute( "select count(*) from estadisticas_tienda where ingreso = true AND id_telf = '%s' AND id_camara = '%s'", (telf, idtienda)) contelfentienda = cursor.fetchone()[0] cursor.execute( "select count(*) from estadisticas_tienda where ingreso = false AND id_telf = '%s' AND id_camara = '%s' ", (telf, idtienda)) contelfentienda2 = cursor.fetchone()[0] cont = cont + 1 if contelfentienda == contelfentienda2: cursor.execute( "select id_persona from telf_inteligente where id_telf = '%s'" % telf) personatienda = cursor.fetchone()[0] break if cont > 502: telf = 0 while (True): cantidaddeaccesos2 = cursor.execute( 'select count(*) from estadisticas_acceso' ) cantidaddeaccesos2 = cursor.fetchone()[0] aleatorio2 = random.randint( 1, cantidaddeaccesos2) sql3 = '''select id_persona from estadisticas_acceso where id_estadi_acceso = %s;''' cursor.execute(sql3, ([aleatorio2])) personaaleatoria2 = cursor.fetchone()[0] cursor.execute( "select count(*) from estadisticas_acceso where ingreso = true AND id_persona = '%s' " % personaaleatoria2) DeEsosEntraron2 = cursor.fetchone()[0] cursor.execute( "select count(*) from estadisticas_acceso where ingreso = false AND id_persona = '%s' " % personaaleatoria2) DeEsosSalieron2 = cursor.fetchone()[0] persona2 = personaaleatoria2 personatienda = persona2 if DeEsosEntraron2 > DeEsosSalieron2: break break # si es true alguien ingreso, si es false alguien salio payload = { "ingresotienda": str(bootienda), "idcamaratienda": str(idtienda), "fecha_hora_tienda": str(horatienda), "idpersona_tienda": str(personatienda), "id_telf": str(telf), "query": str('tienda') } client.publish('unimet/admin/bd', json.dumps(payload), qos=0) print(payload) time.sleep(0.5)
connection = sqlite3.connect("mqtt.db") sql_command = "CREATE TABLE IF NOT EXISTS mqtt(id INTEGER PRIMARY KEY AUTOINCREMENT, time DATETIME DEFAULT CURRENT_TIMESTAMP, msg VARCHAR(10))" cursor = connection.cursor() connection.execute(sql_command) def on_connect(client, userdata, flags, rc): print(f"Connected with result code {rc}") client.subscribe("ass") def save_message(msg): sql = "INSERT INTO mqtt(msg) VALUES('"+msg+"');" cursor.execute(sql); row = cursor.execute('select * from mqtt') for row in cursor: print(row[0], row[1], row[2]) #print(total) def on_message(client, userdata, msg): print(f"{msg.topic} {msg.payload}") save_message(msg.payload.decode()); client.publish(topic="ret",payload="Viraj",qos=1,retain=False) client = client.Client() client.on_connect = on_connect client.on_message = on_message client.connect("broker.emqx.io", 1883, 60) client.publish(topic="ret",payload="Viraj",qos=1,retain=False) client.loop_forever()