Python paho.mqtt.client.Client() Examples
The following are 30
code examples of paho.mqtt.client.Client().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
paho.mqtt.client
, or try the search function
.
Example #1
Source File: mqtt2sql.py From mqtt2sql with GNU General Public License v3.0 | 8 votes |
def on_log(self, client, userdata, level, string): """ Called when the client has log information. @param client: the client instance for this callback @param userdata: the private user data as set in Client() or userdata_set() @param level: gives the severity of the message and will be one of MQTT_LOG_INFO, MQTT_LOG_NOTICE, MQTT_LOG_WARNING, MQTT_LOG_ERR, and MQTT_LOG_DEBUG. The message itself is in string. @param string: The message itself """ debuglog(2, "on_log({},{},{},{})".format(client, userdata, level, string))
Example #2
Source File: social_handler.py From PokemonGo-Bot-Backup with MIT License | 6 votes |
def connect_to_mqtt(self): try: if DEBUG_ON: print 'connect again' self._mqttc = mqtt.Client(None) self._mqttc.on_message = self.mqtt_on_message self._mqttc.on_connect = self.mqtt_on_connect self._mqttc.on_subscribe = self.mqtt_on_subscribe self._mqttc.on_publish = self.mqtt_on_publish self._mqttc.on_disconnect = self.on_disconnect self._mqttc.connect("broker.pikabot.org", 1883, 60) # Enable this line if you are doing the snip code, off stress # self._mqttc.loop_start() except TypeError: print 'Connect to mqtter error' return
Example #3
Source File: iot_python_chapter_09_06.py From Internet-of-Things-with-Python with MIT License | 6 votes |
def on_connect(client, userdata, flags, rc): print("Connected to the {0} topic". format(topic)) subscribe_result = client.subscribe(topic) publish_result_1 = client.publish( topic=topic, payload="Listening to messages in the Paho Python Client") publish_result_2 = publish_command( client, topic, "print_temperature_fahrenheit", "temperature_fahrenheit", 45) publish_result_3 = publish_command( client, topic, "print_information_message", "text", "Python IoT")
Example #4
Source File: iot_mqtt_client.py From kim-voice-assistant with MIT License | 6 votes |
def __init__(self, message_callback = None): """ 初始化mqtt客户端 """ self._logger = logging.getLogger() self.mqtt_path = device.product_key + ".iot-as-mqtt.cn-shanghai.aliyuncs.com" # MQTT地址 self._topic = topic # 获取签名 self.sign_dict = Sign.get_sign({ "deviceName": device.device_name, "productKey": device.product_key }, device.device_secret) self.mqtt_client_id = self.sign_dict['iot_client_id'] + \ "|securemode=3,signmethod=hmacsha1,timestamp=" + \ self.sign_dict['timestamp'] + "|" self._logger.info('use mqtt device id:"%s"', self.mqtt_client_id) # 实例化mqtt客户端 self.mqttc = mqtt.Client(transport="tcp", client_id=self.mqtt_client_id) self._iot_server = IotServer.get_instance()
Example #5
Source File: social_handler.py From PokemonGo-Bot with MIT License | 6 votes |
def initialize(self): try: if DEBUG_ON: print('connect again') self._mqttc = mqtt.Client(None) self._mqttc.on_message = self.mqtt_on_message self._mqttc.on_connect = self.mqtt_on_connect self._mqttc.on_subscribe = self.mqtt_on_subscribe self._mqttc.on_publish = self.mqtt_on_publish self._mqttc.on_disconnect = self.on_disconnect # Enable this line if you are doing the snip code, off stress # self._mqttc.loop_start() except TypeError: print('Connect to mqtter error') return
Example #6
Source File: HermesLedControl.py From HermesLedControl with GNU General Public License v3.0 | 6 votes |
def connectMqtt(self): try: mqttClient = mqtt.Client() if self._mqttUsername and self._mqttPassword: mqttClient.username_pw_set(self._mqttUsername, self._mqttPassword) mqttClient.on_log = self.onLog mqttClient.on_connect = self.onConnect mqttClient.on_message = self.onMessage if self._tlsFile: mqttClient.tls_set(certfile=self._tlsFile) mqttClient.tls_insecure_set(False) mqttClient.connect(self._mqttServer, int(self._mqttPort)) mqttClient.loop_start() return mqttClient except: self._logger.fatal("Couldn't connect to mqtt, aborting") self.onStop() # noinspection PyUnusedLocal
Example #7
Source File: Dmqtt.py From IPDC with MIT License | 6 votes |
def Publish(target,channel,message): client = mqtt.Client() client.max_inflight_messages_set(200000) client.connect(target, 1883) (rc, mid) = client.publish(channel, message, qos=1) #time.sleep(0.01) print("DMQTT RESULT : "+str(rc))
Example #8
Source File: mqtt.py From hermes-audio-server with MIT License | 6 votes |
def __init__(self, config, verbose, logger): """Initialize an MQTT client. Args: config (:class:`.ServerConfig`): The configuration of the MQTT client. verbose (bool): Whether or not the MQTT client runs in verbose mode. logger (:class:`logging.Logger`): The Logger object for logging messages. """ self.config = config self.verbose = verbose self.logger = logger self.mqtt = Client() self.logger.debug('Using %s', pyaudio.get_portaudio_version_text()) self.logger.debug('Creating PyAudio object...') self.audio = pyaudio.PyAudio() self.initialize() self.mqtt.on_connect = self.on_connect self.mqtt.on_disconnect = self.on_disconnect self.connect()
Example #9
Source File: mqtt.py From thingflow-python with Apache License 2.0 | 6 votes |
def __init__(self, host, port=1883, client_id="", client_username="", client_password=None, server_tls=False, server_cert=None, topics=[], mock_class=None): self.host = host self.port = port self.client_id = client_id self.client_username = client_id self.client_password = client_password self.topics = topics self.server_tls = server_tls self.server_cert = server_cert if mock_class: self.client = MockMQTTClient(self.client_id) else: self.client = paho.Client(self.client_id) if self.client_username: self.client.username_pw_set(self.client_username, password=self.client_password) self._connect()
Example #10
Source File: event_loop.py From AMS with Apache License 2.0 | 6 votes |
def connect(self, host, port, ca_path=None, client_path=None, key_path=None): self.__client = mqtt.Client(protocol=mqtt.MQTTv311, userdata=self.__user_data) if ca_path is not None and client_path is not None and key_path is not None: self.ssl_setting(ca_path, client_path, key_path) will = self.__user_will if will is None: event_loop_message = EventLoop.get_message(EVENT_LOOP.STATE.WILL, self.__pid) payload = self.__topicPub.serialize(event_loop_message) will = {"topic": self.__topicPub.get_path(), "payload": payload} self.__client.will_set(will["topic"], payload=will["payload"], qos=2, retain=False) self.__client.on_connect = self.__on_connect self.__client.on_message = self.__on_message self.__client.connect(host=host, port=port, keepalive=EVENT_LOOP.KEEP_ALIVE)
Example #11
Source File: sonoff.py From mqtt-pwn with GNU General Public License v3.0 | 6 votes |
def __init__(self, host=DEFAULT_BROKER_HOST, port=DEFAULT_BROKER_PORT): self._mqtt_client = mqtt.Client() self.host = host self.port = port self.timeout = 10 self.prefix = TOPIC_PREFIX self.listen_timeout = 5 self.cli = None self.should_stop = False self.keyboard_interrupt_occurred = False self.loop_lock = Lock() self._mqtt_client.on_message = self.mqtt_on_message self._mqtt_client.on_connect = self.mqtt_on_connect
Example #12
Source File: active_scanner.py From mqtt-pwn with GNU General Public License v3.0 | 6 votes |
def __init__(self, client_id=None, host=DEFAULT_BROKER_HOST, port=DEFAULT_BROKER_PORT, timeout=60, topics=None, listen_timeout=60, scan_instance=None, cli=None): """Active Scanner object initiation""" self._mqtt_client = mqtt.Client(client_id) self.cli = cli if cli: self.host = cli.mqtt_client.host self.port = cli.mqtt_client.port else: self.host = host self.port = port self.timeout = timeout self.topics = topics self.listen_timeout = int(listen_timeout) self.scan_instance = scan_instance self._base_topic = '$SYS/test123' self._mqtt_client.on_message = self.mqtt_on_message
Example #13
Source File: bridge.py From mqtt_bridge with MIT License | 6 votes |
def _callback_mqtt(self, client, userdata, mqtt_msg): u""" callback from MQTT :param mqtt.Client client: MQTT client used in connection :param userdata: user defined data :param mqtt.MQTTMessage mqtt_msg: MQTT message """ rospy.logdebug("MQTT received from {}".format(mqtt_msg.topic)) now = rospy.get_time() if self._interval is None or now - self._last_published >= self._interval: try: ros_msg = self._create_ros_message(mqtt_msg) self._publisher.publish(ros_msg) self._last_published = now except Exception as e: rospy.logerr(e)
Example #14
Source File: mqtt2sql.py From mqtt2sql with GNU General Public License v3.0 | 6 votes |
def on_subscribe(self, client, userdata, mid, granted_qos): """ Called when the broker responds to a subscribe request. @param client: the client instance for this callback @param userdata: the private user data as set in Client() or userdata_set() @param mid: Matches the mid variable returned from the corresponding subscribe() call. @param granted_qos: a list of integers that give the QoS level the broker has granted for each of the different subscription requests. """ debuglog(2, "on_subscribe({},{},{},{})".format(client, userdata, mid, granted_qos))
Example #15
Source File: mqtt2sql.py From mqtt2sql with GNU General Public License v3.0 | 6 votes |
def on_publish(self, client, userdata, mid): """ Called when a message that was to be sent using the publish() call has completed transmission to the broker. For messages with QoS levels 1 and 2, this means that the appropriate handshakes have completed. For QoS 0, this simply means that the message has left the client. The mid variable matches the mid variable returned from the corresponding publish() call, to allow outgoing messages to be tracked. @param client: the client instance for this callback @param userdata: the private user data as set in Client() or userdata_set() @param mid: matches the mid variable returned from the corresponding publish() call, to allow outgoing messages to be tracked. """ debuglog(2, "on_publish({},{},{})".format(client, userdata, mid))
Example #16
Source File: mqtt2sql.py From mqtt2sql with GNU General Public License v3.0 | 6 votes |
def on_message(self, client, userdata, message): """ Called when a message has been received on a topic that the client subscribes to. This callback will be called for every message received. @param client: the client instance for this callback @param userdata: the private user data as set in Client() or userdata_set() @param message: an instance of MQTTMessage. This is a class with members topic, payload, qos, retain. """ global EXIT_CODE # pylint: disable=global-statement if EXIT_CODE != ExitCode.OK: sys.exit(EXIT_CODE) log(2, '{} {} [QOS {} Retain {}]'.format(message.topic, message.payload, message.qos, message.retain)) debuglog(2, "on_message({},{},{})".format(client, userdata, message)) if EXIT_CODE == ExitCode.OK: self.pool_sqlconnections.acquire() self.write2sql_thread = Thread(target=self.write2sql, args=(message,)) self.write2sql_thread.start()
Example #17
Source File: mqtt2sql.py From mqtt2sql with GNU General Public License v3.0 | 6 votes |
def on_connect(self, client, userdata, message, return_code): """ Called when the broker responds to our connection request. @param client: the client instance for this callback @param userdata: the private user data as set in Client() or userdata_set() @param message: response message sent by the broker @param return_code: the connection result """ debuglog(1, "MQTT on_connect({},{},{},{}): {}".format(client, userdata, message, return_code, mqtt.error_string(return_code))) for topic in self._args.mqtt_topic: debuglog(1, "subscribe to topic {}".format(topic)) client.subscribe(topic, 0)
Example #18
Source File: gcs_example_mqtt_device.py From python-docs-samples with Apache License 2.0 | 5 votes |
def download_blob(bucket_name, config_name, destination_file_name): """Downloads a blob from the bucket.""" storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(config_name) blob.download_to_filename(destination_file_name) print('Config {} downloaded to {}.'.format( config_name, destination_file_name))
Example #19
Source File: roomba.py From Roomba980-Python with MIT License | 5 votes |
def setup_client(self): if self.client is None: if not HAVE_MQTT: print("Please install paho-mqtt 'pip install paho-mqtt' " "to use this library") return False self.client = mqtt.Client( client_id=self.blid, clean_session=self.clean, protocol=mqtt.MQTTv311) # Assign event callbacks self.client.on_message = self.on_message self.client.on_connect = self.on_connect self.client.on_publish = self.on_publish self.client.on_subscribe = self.on_subscribe self.client.on_disconnect = self.on_disconnect # Uncomment to enable debug messages # client.on_log = self.on_log # set TLS, self.cert_name is required by paho-mqtt, even if the # certificate is not used... # but v1.3 changes all this, so have to do the following: self.log.info("Seting TLS") try: self.client.tls_set( self.cert_name, cert_reqs=ssl.CERT_NONE, tls_version=ssl.PROTOCOL_TLSv1) except ValueError: # try V1.3 version self.log.warn("TLS Setting failed - trying 1.3 version") self.client._ssl_context = None context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_NONE context.load_default_certs() self.client.tls_set_context(context) # disables peer verification self.client.tls_insecure_set(True) self.client.username_pw_set(self.blid, self.password) return True return False
Example #20
Source File: __init__.py From dash-button with Apache License 2.0 | 5 votes |
def __init__(self, connector, protocol): if connector == self.Connector.OBSERVER: sys.path.insert(0, 'observer') elif connector == self.Connector.SERVER: sys.path.insert(0, 'openwrt') else: print("Error! Unknown connector") return if protocol == self.Protocol.MQTT: self.client = mqtt.Client() self.prot = protocol self.callbacks = {}
Example #21
Source File: gateway.py From python-docs-samples with Apache License 2.0 | 5 votes |
def get_client( project_id, cloud_region, registry_id, gateway_id, private_key_file, algorithm, ca_certs, mqtt_bridge_hostname, mqtt_bridge_port, jwt_expires_minutes): """Create our MQTT client. The client_id is a unique string that identifies this device. For Google Cloud IoT Core, it must be in the format below.""" client_template = 'projects/{}/locations/{}/registries/{}/devices/{}' client_id = client_template.format( project_id, cloud_region, registry_id, gateway_id) client = mqtt.Client(client_id) # With Google Cloud IoT Core, the username field is ignored, and the # password field is used to transmit a JWT to authorize the device. client.username_pw_set( username='unused', password=create_jwt( project_id, private_key_file, algorithm, jwt_expires_minutes)) # Enable SSL/TLS support. client.tls_set(ca_certs=ca_certs, tls_version=ssl.PROTOCOL_TLSv1_2) # Register message callbacks. # https://eclipse.org/paho/clients/python/docs/ # describes additional callbacks that Paho supports. In this example, # the callbacks just print to standard out. client.on_connect = on_connect client.on_publish = on_publish client.on_disconnect = on_disconnect client.on_message = on_message client.on_subscribe = on_subscribe # Connect to the Google MQTT bridge. client.connect(mqtt_bridge_hostname, mqtt_bridge_port) return client # [END iot_mqtt_config]
Example #22
Source File: archive.py From ny-power with Apache License 2.0 | 5 votes |
def mqtt_client(influxclient): client = mqtt.Client(clean_session=True) client.influx = influxclient client.username_pw_set("pump", get_pass()) client.on_connect = on_connect client.on_message = on_message client.connect(MQTT_HOST) return client
Example #23
Source File: client.py From microgear-python with ISC License | 5 votes |
def connect(block=False): global block_loop block_loop = block global current_subscribe_list global current_id times = 1 while not microgear.accesstoken: get_token() time.sleep(times) times = times+10 microgear.mqtt_client = mqtt.Client(microgear.accesstoken["token"]) current_id = '/&id/'+str(microgear.accesstoken["token"])+'/#' current_subscribe_list.append('/&id/'+str(microgear.accesstoken["token"])+'/#') endpoint = microgear.accesstoken["endpoint"].split("//")[1].split(":") username = microgear.gearkey+"%"+str(int(time.time())) password = hmac(microgear.accesstoken["secret"]+"&"+microgear.gearsecret,microgear.accesstoken["token"]+"%"+username) microgear.mqtt_client.username_pw_set(username,password) if microgear.securemode: microgear.mqtt_client.tls_set(certifi.where()) microgear.mqtt_client.connect(endpoint[0],int(microgear.gbsport), 60) else: microgear.mqtt_client.connect(endpoint[0],int(microgear.gbport), 60) microgear.mqtt_client.on_connect = client_on_connect microgear.mqtt_client.on_message = client_on_message microgear.mqtt_client.on_publish = client_on_publish microgear.mqtt_client.on_subscribe = client_on_subscribe microgear.mqtt_client.on_disconnect = client_on_disconnect if(block): microgear.mqtt_client.loop_forever() else: microgear.mqtt_client.loop_start() while True: time.sleep(2) break
Example #24
Source File: MqttManager.py From ProjectAlice with GNU General Public License v3.0 | 5 votes |
def mqttClient(self) -> mqtt.Client: return self._mqttClient
Example #25
Source File: MqttManager.py From ProjectAlice with GNU General Public License v3.0 | 5 votes |
def __init__(self): super().__init__() self._mqttClient = mqtt.Client() self._thanked = False self._wideAskingSessions = list() self._multiDetectionsHolder = list() self._audioFrameRegex = re.compile(constants.TOPIC_AUDIO_FRAME.replace('{}', '(.*)')) self._wakewordDetectedRegex = re.compile(constants.TOPIC_WAKEWORD_DETECTED.replace('{}', '(.*)')) self._vadUpRegex = re.compile(constants.TOPIC_VAD_UP.replace('{}', '(.*)')) self._vadDownRegex = re.compile(constants.TOPIC_VAD_DOWN.replace('{}', '(.*)')) self._INTENT_RANDOM_ANSWER = Intent('UserRandomAnswer', isProtected=True)
Example #26
Source File: server.py From channels-asgi-mqtt with GNU General Public License v3.0 | 5 votes |
def __init__(self, channel, host, port, username=None, password=None, client_id=None, topics_subscription=None, mqtt_channel_name = None, mqtt_channel_sub=None, mqtt_channel_pub=None): self.channel = channel self.host = host self.port = port self.client_id = client_id self.client = mqtt.Client(client_id=self.client_id, userdata={ "server": self, "channel": self.channel, "host": self.host, "port": self.port, }) self.username = username self.password = password self.client.on_connect = self._on_connect self.client.on_disconnect = self._on_disconnect self.client.on_message = self._on_message self.topics_subscription = topics_subscription or [("#", 2),] assert isinstance(self.topics_subscription, list), "Topic subscription must be a list with (topic, qos)" self.mqtt_channel_name = mqtt_channel_name or "mqtt" self.mqtt_channel_pub = mqtt_channel_pub or "mqtt.pub" self.mqtt_channel_sub = mqtt_channel_sub or "mqtt.sub"
Example #27
Source File: mqtt.py From thingflow-python with Apache License 2.0 | 5 votes |
def __init__(self, host, port=1883, client_id="", client_username="", client_password=None, server_tls=False, server_cert=None, topics=[], mock_class=None): super().__init__() self.stop_requested = False self.host = host self.port = port self.client_id = client_id self.client_username = client_id self.client_password = client_password self.topics = topics self.server_tls = server_tls self.server_cert = server_cert if mock_class: self.client = MockMQTTClient(self.client_id) else: self.client = paho.Client(self.client_id) if self.client_username: self.client.username_pw_set(self.client_username, password=self.client_password) self._connect() def on_message(client, userdata, msg): m = MQTTEvent(msg.timestamp, msg.state, msg.mid, msg.topic, msg.payload, msg.qos, msg.dup, msg.retain) self._dispatch_next(m) self.client.on_message = on_message
Example #28
Source File: mqtt.py From chromecast-mqtt-connector with Mozilla Public License 2.0 | 5 votes |
def __init__(self, ip, port, username, password, connection_callback): self.logger = logging.getLogger("mqtt") self.mqtt = Client() if username is not None: self.mqtt.username_pw_set(username, password) self.mqtt.on_connect = self._on_connect self.mqtt.on_message = self._on_message self.ip = ip self.port = port self.connection_callback = connection_callback self.queue = []
Example #29
Source File: __init__.py From smarthome with GNU General Public License v3.0 | 5 votes |
def _connect_to_broker(self): """ Establish connection to MQTT broker """ clientname = os.uname()[1] + '.MQTT-module' self.logger.info("Connecting to broker '{}:{}'. Starting mqtt client '{}'".format(self.broker_ip, self.broker_port, clientname)) self._client = mqtt.Client(client_id=clientname) # set testament, if configured if (self.last_will_topic != '') and (self.last_will_payload != ''): retain = False if (self.birth_topic != '') and (self.birth_payload != ''): retain = True self._client.will_set(self.last_will_topic, self.last_will_payload, self.qos, retain=retain) self.logger.debug("- Last will set to topic '{}' and payload '{}' with retain set to '{}'".format(self.last_will_topic,self.last_will_payload, retain)) if self.username != '': self._client.username_pw_set(self.username, self.password) self.logger.debug("- Using broker login information user '{}' and password".format(self.username)) self._client.on_connect = self._on_connect self._client.on_disconnect = self._on_disconnect self._client.on_log = self._on_mqtt_log self._client.on_message = self._on_mqtt_message self._network_connected_to_broker = False if not self._network_connect_to_broker(from_init=True): self.logger.warning("MQTT broker can not be reached. No messages are sent/received until the broker can be reached") return
Example #30
Source File: victim.py From mqtt-pwn with GNU General Public License v3.0 | 5 votes |
def __init__(self, client_id=None, host="m2m.eclipse.org", port=1883, timeout=60, username=None, password=None): """The class initializer""" self._mqtt_client = mqtt.Client(client_id) self.host = host self.port = port self.timeout = timeout self.username = username self.password = password self.uuid = Utils.calc_uuid() self.os = Utils.determine_os() self.hostname = Utils.determine_hostname() self._base_topic = '$SYS/test123' self._output_topic = f"{self._base_topic}/output/{self.uuid}" self._register_topic = f"{self._base_topic}/register/{self.uuid}" self._subscription_topics = [ (f'{self._base_topic}/input/{self.uuid}', 0), ] self._mqtt_client.on_connect = self.mqtt_on_connect self._mqtt_client.on_message = self.mqtt_on_message self._mqtt_client.on_subscribe = self.mqtt_on_subscribe