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 mqttStart(): ''' Start MQTT ''' global client global clientOk # MQTT Start client = mqtt.Client() log().info("Starting MQTT " + MQTT_HOST) print(Color.B_LightYellow + "Starting MQTT " + MQTT_HOST + Color.B_Default) if DEVELOPERS_MODE: log().debug("mqttStart MQTT_USERNAME: "******"mqttStart MQTT_PASSWORD: "******"Can't start MQTT") print(Color.F_Red + "Can't start MQTT" + Color.F_Default) # e.errno = 51 - 'Network is unreachable' mostraErro(e, 20, "MQTT Start") else: clientOk = False mostraErro(e, 30, "MQTT Start") if clientOk: client.loop_start() # start the loop
def start(deliver_callback): log.info("Start MQTT CAN receiver") global callback callback = deliver_callback rc = client.connect("pi3.lan") log.info("client.connect %d", rc) client.loop_start()
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 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()
def jsonmqttclient(server, subname, function, object): def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) client.subscribe(subname) def on_message(client, userdata, msg): print(msg.topic + " " + str(msg.payload)) function(json.loads(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect(server, 1883, 60) client.loop_start()
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 _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_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 __init__(self, url, echo=None, target=AppendToFile(sys.stdout), **kwargs): parsed = urllib.parse.urlsplit(url) if parsed.scheme in ('ws', 'websockets'): kwargs["transport"] = 'websockets' self.kwargs = kwargs import paho.mqtt.client client = paho.mqtt.client.Client(**kwargs) client.connect(parsed.hostname, parsed.port if parsed.port else 1883) client.on_message = partial(MqttTopic.read, self) client.loop_start() self.client = client self.topic = urllib.parse.unquote(parsed.path[1:]) self.echo = echo self.target = target logger.debug("Connected to {url} {kwargs}".format(**locals()))
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 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')
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) self.create_widgets() self.update_clock()
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)
"temp": temp }) # mqtt Publish client.publish(MQTT_TOPIC_PUB, json_msg) time.sleep(0.01) # Main Procedure if __name__ == '__main__': # Mqtt Client Initialize client = paho.mqtt.client.Client() client.on_connect = mqtt_connect client.on_message = mqtt_message client.tls_set(MQTT_ROOTCA, certfile=MQTT_CERT, keyfile=MQTT_PRIKEY, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None) # Connect To Mqtt Broker(aws) client.connect(AWSIoT_ENDPOINT, port=MQTT_PORT, keepalive=60) # Start Mqtt Subscribe client.loop_start() # Start Publish Loop loop = asyncio.get_event_loop() loop.run_until_complete(pub_loop())
def mqttStart(): ''' Start MQTT ''' global client global clientOk # MQTT Start # client = mqtt.Client(transport="tcp") # "websockets" client = mqtt.Client(client_id='', clean_session=True, userdata=None, protocol=MQTTversion, transport="tcp") # mqtt.MQTTv31 log().info("Starting MQTT " + MQTT_HOST) printC(Color.B_Blue, "Starting MQTT Client " + MQTT_HOST) if DEVELOPERS_MODE: printC(Color.F_Blue, "SSL: " + ssl.OPENSSL_VERSION) log().debug("mqttStart External: " + str(External_MQTT_Server) + ' ' + str(type(External_MQTT_Server))) log().debug("mqttStart TLS: " + str(External_MQTT_TLS) + ' ' + str(type(External_MQTT_TLS))) log().debug("mqttStart MQTT_USERNAME: "******"mqttStart MQTT_PASSWORD: "******"mqttStart MQTT_PORT: " + str(MQTT_PORT) + ' ' + str(type(MQTT_PORT))) client.username_pw_set(username=MQTT_USERNAME, password=MQTT_PASSWORD) client.on_connect = on_connect # client.on_message = on_message client.on_disconnect = on_disconnect client.on_publish = on_publish if DEVELOPERS_MODE: client.on_log = on_log #v.0.22 TLS if (External_MQTT_TLS): log().debug("Trying TLS: " + str(MQTT_PORT)) printC(Color.F_Green, "Trying TLS: " + str(MQTT_PORT) + " " + str(type(MQTT_PORT))) # ssl._create_default_https_context = ssl._create_unverified_context if DEVELOPERS_MODE: printC(Color.F_Magenta, "TLS_protocol_version: " + str(TLS_protocol_version)) context = ssl.SSLContext( protocol=TLS_protocol_version ) # ssl.PROTOCOL_TLSv1 , ssl.PROTOCOL_TLS_CLIENT #context.check_hostname = False client.tls_set_context(context) #ssl._create_default_https_context = ssl._create_unverified_context #ssl.create_default_context() #client.tls_set() #client.tls_set_context(ssl._create_unverified_context) #client.tls_insecure_set(True) #import certifi #client.tls_set(certifi.where()) try: clientOk = True #rc = client.connect(MQTT_HOST, MQTT_PORT, 60) # 1883 rc = client.connect(host=MQTT_HOST, port=int(MQTT_PORT), keepalive=60) # 1883 except Exception as e: # OSError if e.__class__.__name__ == 'OSError': clientOk = False log().warning("Can't start MQTT") print(Color.F_Red + "Can't start MQTT" + Color.F_Default) # e.errno = 51 - 'Network is unreachable' mostraErro(e, 20, "MQTT Start") else: clientOk = False mostraErro(e, 30, "MQTT Start") if clientOk: client.loop_start() # start the loop
def mqtt_publish(mqtt_client, topic, msg): msg_count = 0 #msg = f"messages: {msg_count}" result = mqtt_client.publish(topic, msg) # result: [0, 1] status = result[0] if status == 0: print("Send " + msg + " to topic " + topic) else: print("Failed to send message to topic {topic}") msg_count += 1 mqtt_client = connect_mqtt() mqtt_client.loop_start() for item in sys.argv: # print item results_items.append(item) try: while looping: response = ser.readline() localtime = time.asctime(time.localtime(time.time())) count = count + 1 # print count # If one of the arguments is not found, we must exit after a while if count >= 100: print " At least 1 or more argument missing after " + str( count
# def on_message(client, userdata, msg): # print(msg.topic + " " + str(msg.payload)) # print(type(msg.payload)) # # 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)
def subscribe_for_commands(on_message): client = paho.mqtt.client.Client("commandsSub") client.on_message = on_message client.connect(HOSTNAME) client.loop_start() client.subscribe("commands")
def mqtt(): mqtt_client.publish("zorelu", "ledoff", 2) # 发布一个主题为'chat',内容为‘hello ’的信息 mqtt_client.loop_start() #mqtt_client.loop_stop(force=False) return "mqtt ok "