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 _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(): 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 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 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 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 mqtt_start(): client = paho.mqtt.client.Client(transport='tcp') client.username_pw_set("hjpc", "htxzdj") client.on_connect = on_connect client.on_message = on_message client._client_id = clitntID client.connect(aliHOST, aliPORT, 60) #client.publish('hjOneLineGet',payload='',qos = 0) print("pyOneLineServer 初始化结束, 等待请阅请求", flush=True) client.loop_forever()
def connect(config): client = paho.mqtt.client.Client() user = config.get("username", None) password = config.get("password", None) if user and password: client.username_pw_set(user, password) client.connect(config['host'], config['port']) return client
def main(): print("Ctrl+c para salir") print("Inicializando..") client = paho.mqtt.client.Client(client_id='Serial-monitor', clean_session=False) client.on_connect = on_connect client.on_message = on_message client.username_pw_set("usuario", "contrasenya") client.connect(host=broker_address, port=broker_port) client.loop_forever()
def main(): client = paho.mqtt.client.Client(client_id='[clientid]', clean_session=False) client.username_pw_set('[username]', '[password]') client.on_connect = on_connect client.on_message = on_message client.tls_set('/home/credd/ca-certificates.crt', tls_version=ssl.PROTOCOL_TLSv1_2) client.tls_insecure_set(True) client.connect('reddtech.us', 8883, 60) #client.loop_forever() client.loop_forever()
def main(): # Load MQTT configuration from MQTT_Config.yaml with open(r'MQTT_Config.yaml') as configuration: config = yaml.load(configuration, Loader=yaml.FullLoader) print(config) # Start MQTT subscription listening for data from the tracker. client = paho.mqtt.client.Client(client_id=str(uuid.getnode()), clean_session=False) client.username_pw_set(config['MQTT_USER'], config['MQTT_PASS']) client.on_connect = on_connect client.on_message = on_message client.connect(host=config['MQTT_BROKER'], port=config['MQTT_PORT']) client.subscribe(topic="biketracker/payload") client.loop_forever()
def start_connect(ip="47.93.30.53",port=1883,username="******",pwd="123456"): # client_id = "好咖啡" + time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) client_id = "好咖啡"+ time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) global client # ClientId不能重复,所以使用当前时间。连接方式参数为tcp也可以不写 client = mqtt.Client(client_id, transport='tcp') # 初始化订阅用户和密码 必须设置,否则会返回「Connected with result code 4」 client.username_pw_set(username, pwd) client.on_connect = on_connect # 打印连接状态 client.connect(ip, port, 60) # 开始连接 global xc1 xc1 = Thread(target=client.loop_forever) # 开启客户端阻塞线程 xc1.setDaemon(True) xc1.start() # 线程启动
def start_connect(client_id="达神", ip="47.93.30.53", port=1883, username="******", pwd="123456", sl="tcp"): global client client = mqtt.Client(client_id, transport=sl) client.username_pw_set(username, pwd) client.on_connect = on_connect # 打印连接状态 try: client.connect(ip, port, 60) # 开始连接 global xc1 xc1 = Thread(target=client.loop_forever) # 开启客户端阻塞线程 xc1.setDaemon(True) xc1.start() # 线程启动 except ConnectionRefusedError: showinfo("提示", "连接失败!\n请检查该服务器ip是否正常\n目标ip:%s" % ip)
def start_connect(ip="47.93.30.53", port=1883, username="******", pwd="123456", qos=0, topic="/data/#"): client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) global client client = mqtt.Client( client_id, transport='tcp') # ClientId不能重复,所以使用当前时间。连接方式参数为tcp也可以不写 client.username_pw_set( username, pwd) # 初始化订阅用户和密码 必须设置,否则会返回「Connected with result code 4」 client.on_connect = on_connect # 打印连接状态 client.connect(ip, port, 60) # 开始连接 on_subscribe(topic, qos) # 初始化订阅内容 global xc1 xc1 = Thread(target=client.loop_forever) #开启客户端阻塞线程 xc1.setDaemon(True) xc1.start() #线程启动
def construct_mqtt_password(self, node): client = paho.mqtt.client.Client(client_id='esphomeyaml', clean_session=False) client.username_pw_set(os.environ['MQTT_USERNAME'], os.environ['MQTT_PASSWORD']) client.connect(host='mqtt', port=1883) hal_mqtt_username = self.get_device_name() if CORE.command in ["compile", "run"]: vault_client = hvac.Client(url='http://vault:8200', token=os.environ['VAULT_TOKEN']) vault_client.token = os.environ['VAULT_TOKEN'] hal_mqtt_password = vault_client.write( "sys/tools/random/16")['data']['random_bytes'] client.publish("mqtt/add/user/%s" % hal_mqtt_username, hal_mqtt_password, 2) else: hal_mqtt_password = "******" return hal_mqtt_password
def main(): #print('Attaching Debugger') # Allow other computers to attach to ptvsd at this IP address and port, using the secret #ptvsd.enable_attach("my_secret", address = ('0.0.0.0', 3000)) # Pause the program until a remote debugger is attached #ptvsd.wait_for_attach() print('Starting MQTT client') client = paho.mqtt.client.Client(client_id='platformio', clean_session=False) #with open('/run/secrets/mqtt_username') as username, open('/run/secrets/mqtt_password') as password: # client.username_pw_set(username.read().strip(), password.read().strip()) client.username_pw_set(os.environ['MQTT_USERNAME'],os.environ['MQTT_PASSWORD'] ) print('On_connect') client.on_connect = on_connect client.on_message = on_message print('TLS + Connect') with open('ca', 'w+') as ca: ca.write(os.environ['CA']) client.tls_set('ca', tls_version=ssl.PROTOCOL_TLSv1_2) client.connect(host='mqtt', port=8883) print('Finished setup, starting loop.') sys.stdout.flush() client.loop_forever()
def run(self) -> None: """ start the listener """ logger.info("Starting {name}".format(name=self.conf.sys_name)) logger.info("Initializing LED strip...") driver = get_driver(self.conf.Strip.driver) self.strip = driver( num_leds=self.conf.Strip.num_leds, max_clock_speed_hz=self.conf.Strip.max_clock_speed_hz) self.strip.set_global_brightness(self.conf.Strip.initial_brightness) self.strip.sync_up() logger.info("Connecting to the MQTT Broker") client = paho.mqtt.client.Client() client.on_connect = self.on_connect client.on_message = self.on_message if self.conf.MQTT.username is not None: client.username_pw_set(self.conf.MQTT.username, self.conf.MQTT.password) client.connect(self.conf.MQTT.Broker.host, self.conf.MQTT.Broker.port, self.conf.MQTT.Broker.keepalive) logger.info("{name} is ready".format(name=self.conf.sys_name)) self.notify_brightness(self.conf.Strip.initial_brightness) # start a show show to listen for brightness changes and refresh the strip regularly self.start_show("clear", {}) self.notify_user("off") try: signal.signal( signal.SIGTERM, self.stop_controller) # attach stop_controller() to SIGTERM client.loop_forever() except KeyboardInterrupt: self.stop_controller() finally: logger.critical("MQTTControl.py has exited")
def main(): mqtt.on_connect = on_connect mqtt.on_message = on_message mqtt.username_pw_set(MQTT_USER, MQTT_PASS) mqtt.connect(MQTT_ADDR, int(MQTT_PORT)) mqtt.loop_forever()
client.subscribe("cmnd/tasmota/light_D8DF25/power1") client.subscribe("#") # The callback for when a PUBLISH message is received from the server. 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") # Create an MQTT client and attach our routine to it. mqtt = mqtt.Client(userdata="tom") 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) # Process network traffic and dispatch callbacks. This will also handle # reconnecting. Check the documentation at # https://github.com/eclipse/paho.mqtt.python # for information on how to use other loop*() functions # mqtt.loop_start() mqtt.loop_forever()
# settings logging.basicConfig(level=logging.INFO) # start of program # Load environment variables logging.info("starting program") load_dotenv("example.env") mqtt_host = get_env("MQTT_HOST") mqtt_port = int(get_env("MQTT_PORT")) mqtt_username = get_env("MQTT_USERNAME") mqtt_password = get_env("MQTT_PASSWORD") # Create new MQTT client client = paho.mqtt.client.Client() client.username_pw_set(mqtt_username, mqtt_password) client.on_publish = on_publish_callback # Establish connection to broker client.connect(mqtt_host, mqtt_port) logging.info("connected to ags broker") # Publish to broker client.publish("mqtt/hello-world", "hello world - 1", 1) client.publish("mqtt/hello-world", "hello world - 2", 1) # Wait for 3 seconds (to allow callback to run) before exiting client.loop_start() time.sleep(3) client.loop_stop()
parser.add_argument( 'topic', type=str, help= 'Topic mask to unpublish retained messages from. For example: "/devices/my-device/#"' ) args = parser.parse_args() client = paho.mqtt.client.Client(client_id=None, clean_session=True, protocol=paho.mqtt.client.MQTTv31) if args.username: client.username_pw_set(args.username, args.password) client.connect(args.host, args.port) client.on_message = on_mqtt_message client.subscribe(args.topic) influx_client = InfluxDBClient('localhost', 8086, database='mqtt_data') db_writer = DBWriterThread(influx_client, daemon=True) db_writer.start() while 1: rc = client.loop() if rc != 0: break
@app.route('/video/62/play', methods=['POST']) def videoplay62(): if request.method == 'POST': topic = '{}/feeds/onoff'.format(USERNAME) client.publish(topic, payload="62v") print(topic) return {'hello': 'world'} @app.route('/audio/6/play', methods=['POST']) def audioplay6(): if request.method == 'POST': topic = '{}/feeds/onoff'.format(USERNAME) client.publish(topic, payload="6a") print(topic) return {'hello': 'world'} if __name__ == '__main__': if USERNAME == '' or PASSWORD == '': logger.error("No MQTT username or password set.") sys.exit(-1) client.username_pw_set(USERNAME, PASSWORD) client.connect(host=HOST, port=PORT) client.loop_start() app.run()
# Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. #client.subscribe("user/bob/location", qos=2) # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print msg print(msg.topic + " " + str(msg.payload)) time.sleep(2) def on_log(*args): print args client = client.Client(client_id="bobolab", clean_session=False) 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) #client.publish("SYS1", "uioiu") # 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()
for topic in mqtt_protocol: client.subscribe(topic) def callback_disconnect(client, userdata, rc): print("User disconnected with response code : ", str(rc)) # set name if it keeps connecting and disconnecting mqtt_client = mqtt_client.Client() mqtt_client.on_connect = callback_connect mqtt_client.on_disconnect = callback_disconnect mqtt_client.on_message = callback_msg print("Connecting to broker ", broker) mqtt_client.username_pw_set("Iot-of-doom-admin", password="******") mqtt_client.connect(broker) mqtt_client.loop_start() # ==============HTTP SETUP=============== class Pairing(Resource): def post(self): parser = reqparse.RequestParser() parser.add_argument("deviceId") args = parser.parse_args() return confirm_pairing(args["deviceId"])
[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)) 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}
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
import paho.mqtt.client as mqtt mqtt = mqtt.Client("sss") mqtt.username_pw_set("username", "password") mqtt.connect("xxx.xxx.xxx.xxx", 1883) mqtt.publish("mainTopic/subTopic", "Payload메시지") print("Published!") mqtt.loop() print("Exit")
#!/usr/bin/env python import time import os import paho.mqtt.client as mqtt mqtt_host = os.environ.get('MQTT_HOST', 'localhost') mqtt_user = os.environ.get('MQTT_USER', None) mqtt_pass = os.environ.get('MQTT_PASS', None) mqtt_port = os.environ.get('MQTT_PORT', 1883) if mqtt_user is not None: mqtt.username_pw_set(mqtt_user, mqtt_pass) def on_connect(client, userdata, flags, rc): client.subscribe("psa/alarm") client.subscribe("sensor/door/frame") client.subscribe("sensor/door/bell") print("Connected to mqtt with result code " + str(rc)) def on_message(client, userdata, msg): topic = msg.topic payload = msg.payload.decode() soundfile = None if topic == "psa/alarm": soundfile = "space/ALARM" client.publish('psa/sound', soundfile) elif topic == "sensor/door/frame" and payload == "open": soundfile = "door-louder"