def __reconnect(self): """ Tries to connect to the MQTT server """ # Cancel the timer, if any self.__stop_timer() try: # Try to reconnect the server result_code = self.__mqtt.reconnect() if result_code: # Something wrong happened message = "Error connecting the MQTT server: {0} ({1})" \ .format(result_code, paho.error_string(result_code)) _logger.error(message) raise ValueError(message) except Exception as ex: # Something went wrong: log it _logger.error("Exception connecting server: %s", ex) finally: # Prepare a reconnection timer. It will be cancelled by the # on_connect callback self.__start_timer(10)
def send(self, val): ts = val['ts']; comp = val['name']; data = str(val['val']); topic = "server/metric/%s/%s" % (self._accountID, self._deviceID); packet = { 'accountId': self._accountID, 'did': self._deviceID, 'on': ts, 'count': 1, 'data': [{'on': ts, 'value': data, 'cid': comp}] }; pr.Dbg("EnableIoT - MQTT: Sending packet to topic '%s': %s" % (str(topic), json.dumps(packet))); (succ, mid) = self._mqtt.publish(topic, json.dumps(packet), qos=self._qos); pr.Dbg("EnableIoT - MQTT: Published Message %d (Err: '%s')" % (mid, mqtt.error_string(succ))); start = time.time(); while (time.time() < (start + self._messageTimeout)): self._gotMessagesLock.acquire(); if (mid in self._gotMessages): self._gotMessages.remove(mid); self._gotMessagesLock.release(); pr.Dbg("EnableIoT - MQTT: Success!"); return True; self._gotMessagesLock.release(); time.sleep(0.5); pr.Dbg("EnableIoT - MQTT: Fail...."); return False;
def run(self): self.client = mqtt.Client() self.client.on_connect = self.on_connect self.client.on_disconnect = self.on_disconnect self.client.on_subscribe = self.on_subscribe self.client.on_message = self.on_message self.client.on_log = self.on_log while not self.app.is_exit_signaled(): while not self.connected: try: self.client.connect(self.app.mqtt_broker, self.app.mqtt_port, 60) self.connected = True except: self.app.log.error("Failed to connect to MQTT broker: %s:%s (rc=%d, %s)", self.app.mqtt_broker, self.app.mqtt_port, rc, mqtt.error_string(rc)) time.sleep(3) rc = self.client.loop() if rc != mqtt.MQTT_ERR_SUCCESS: self.app.log.warning("MQTT loop returned code %d (%s)", rc, mqtt.error_string(rc)) if self.connected: self.client.disconnect() self.app.log.debug("MQTT thread stopped")
def _raise_on_error(result_code: int) -> None: """Raise error if error result.""" if result_code != 0: import paho.mqtt.client as mqtt raise HomeAssistantError( 'Error talking to MQTT: {}'.format(mqtt.error_string(result_code)))
def loop(self): """Run network activities. This function needs to be called frequently to keep the network traffic alive, if not using threaded networking. It will block until a message is received, or until the self.timeout value. If not connected to the broker, it will try to connect once. Do not use this function when running threaded networking. """ if self._use_threaded_networking: self.logger.warning("You must should not use the loop() method when running a threaded networking interface.") return try: errorcode = self.mqttclient.loop(self.timeout) except AttributeError: raise ValueError("You must call start() before loop().") if not errorcode: return if errorcode == mqtt.MQTT_ERR_UNKNOWN: self.logger.warning("Probably keyboard interrupt, quitting (MQTT error message: '{}')".format( mqtt.error_string(errorcode))) self.stop() sys.exit() if errorcode == mqtt.MQTT_ERR_CONN_LOST: self.logger.info("MQTT connection error, trying to reconnect. Error message: '{}'".format( mqtt.error_string(errorcode))) elif errorcode in [mqtt.MQTT_ERR_NO_CONN, mqtt.MQTT_ERR_CONN_REFUSED]: self.logger.warning("MQTT connection error, trying to reconnect. Error message: '{}'".format( mqtt.error_string(errorcode))) else: self.logger.warning("MQTT error. Error message: '{}'".format(mqtt.error_string(errorcode))) return try: self.mqttclient.reconnect() except Exception: self.logger.warning("Failed to connect to the MQTT broker. Host: {}, Port: {}".format(self.host, self.port)) self._set_broker_connectionstatus(False) time.sleep(1)
def store_raw(self, message): # TODO: Wrap in JSON packet # Publish with QoS=2 # http://www.hivemq.com/blog/mqtt-essentials-part-6-mqtt-quality-of-service-levels (result, mid) = self.mqtt_client.publish(topic=self.PUBLISH_TOPIC, payload=message, qos=self.QOS_LEVEL) print "store(): %s" % error_string(result)
def publish(self, topic, payload, qos, retain): try: (rc, mid) = self._iot_mqtt_client_handler.publish(topic, payload, qos, retain) except BaseException as e: send_output(self.wrapper_debug, self.wrapper_Tx, "P F " + e.message) return send_output(self.wrapper_debug, self.wrapper_Tx, "P " + str(rc) + " " + mqtt.error_string(rc)) return rc
def on_connect(self, client, userdata, flags, rc): print('on_connect: %s' % error_string(rc)) if rc != 0: raise ByteportConnectException("Error while connecting to MQTT Broker: " + error_string(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. self.mqtt_client.subscribe(self.self_topic_name, qos=self.QOS_LEVEL) # For testing pub/subscribe via. RabbitMQ -> Exchange -> Queue self.mqtt_client.subscribe(self.PUBLISH_TOPIC, qos=self.QOS_LEVEL)
def subscribe(self, topic, qos, ino_id): try: (rc, mid) = self._iot_mqtt_client_handler.subscribe(topic, qos) if ino_id == None: raise ValueError("None ino_id") self.idMap_lock.acquire() self.idMap.setdefault(topic, ino_id) self.idMap_lock.release() except BaseException as e: send_output(self.wrapper_debug, self.wrapper_Tx, "S F " + e.message) return send_output(self.wrapper_debug, self.wrapper_Tx, "S " + str(rc) + " " + mqtt.error_string(rc)) return rc
def async_connect(self): """Connect to the host. Does not process messages yet. This method must be run in the event loop and returns a coroutine. """ result = yield from self.hass.loop.run_in_executor( None, self._mqttc.connect, self.broker, self.port, self.keepalive) if result != 0: import paho.mqtt.client as mqtt _LOGGER.error('Failed to connect: %s', mqtt.error_string(result)) return not result
def __on_connect(self, client, userdata, flags, rc): if rc == mqtt.CONNACK_ACCEPTED: # connection successful self.connected = True for topic in self.subscriptions.keys(): (res, mid) = self.client.subscribe(topic) self.log.debug("subscribing to '%s' => mid: '%s' == '%s'" % (topic, mid, res)) self.subscriptions[topic]['mid'] = mid self.subscriptions[topic]['subscription_result'] = res else: msg = mqtt.error_string(rc) self.log.error("MQTT connection error: %s" % msg) self.__sender_id = None
def emit_record(topic, rec): global client if client== None: client = get_connected_client() p = 11 tries = 0 while p > 10: p = 0 plock.acquire() p = len(pending) plock.release() if p > 10: tries += 1 if tries > 10: LOG.info("restarting mqtt connection") try: if (client.connect(MQHOST, MQPORT, 60) != mqtt.MQTT_ERR_SUCCESS): LOG.error("Failed to connect to MQTT server.") return None except ConnectionRefusedError: LOG.error("MQTT server connection refused at {}:{} check the server.".format(MQHOST, MQPORT)) tries = 0 else: LOG.info("wait for pending messages before queuing more [{}]".format(p)) time.sleep(1) # make it serializable d = rec['Datetime'] rec['Datetime'] = rec['Datetime'].isoformat() result, mid = client.publish(topic,json.dumps(rec), qos=2) if result != mqtt.MQTT_ERR_SUCCESS: LOG.warn("MQTT publish failed with {}, restarting connection.".format(mqtt.error_string(result))) try: shutdown_client() except: pass else: LOG.info("emit [{}] to {}: {}".format(mid, topic, rec)) plock.acquire() pending[mid] = datetime.datetime.now() plock.release() rec['Datetime'] = d
def subscribe(self, topic, qos, ino_id, is_delta): try: (rc, mid) = self._iot_mqtt_client_handler.subscribe(topic, qos) if ino_id == None: raise ValueError("None ino_id") self.idMap_lock.acquire() new_key = idMap_key(topic, None) # no clientToken since it is a normal sub new_entry = idMap_info(ino_id, False, is_delta!=0) # This is not a ThingShadow-related topic self.idMap[new_key] = new_entry self.idMap_lock.release() except BaseException as e: send_output(self.wrapper_debug, self.wrapper_Tx, "S F " + e.message) return send_output(self.wrapper_debug, self.wrapper_Tx, "S " + str(rc) + " " + mqtt.error_string(rc)) return rc
def async_connect(self): """Connect to the host. Does process messages yet. This method is a coroutine. """ result = yield from self.hass.async_add_job( self._mqttc.connect, self.broker, self.port, self.keepalive) if result != 0: import paho.mqtt.client as mqtt _LOGGER.error('Failed to connect: %s', mqtt.error_string(result)) else: self._mqttc.loop_start() return not result
def publish_file(file_name, file_path): global mqtt_client log.debug('publish_file({})'.format(file_path)) try: with open(file_path) as fh: file_contents = fh.read() ret_obj = mqtt_client.publish(topic=file_name, payload=file_contents, qos=0) if ret_obj.rc == mqtt.MQTT_ERR_SUCCESS: log.debug('MQTT published file: {}'.format(file_path)) else: log.warning('MQTT failed to publish file: {}'.format(file_path)) log.warning('MQTT failed to publish file. error: {}'.format(mqtt.error_string(ret_obj.rc))) except Exception as ex: log.error('Exception in publish_file(). ex: {}'.format(ex))
async def async_connect(self) -> bool: """Connect to the host. Does process messages yet. This method is a coroutine. """ result = None # type: int try: result = await self.hass.async_add_job( self._mqttc.connect, self.broker, self.port, self.keepalive) except OSError as err: _LOGGER.error("Failed to connect due to exception: %s", err) return False if result != 0: import paho.mqtt.client as mqtt _LOGGER.error("Failed to connect: %s", mqtt.error_string(result)) return False self._mqttc.loop_start() return True
def __on_connect(self, client, userdata, flags, rc): if rc == mqtt.CONNACK_ACCEPTED: # connection successful self.log.info("%s: MQTT successfully connected" % self.get_identifier()) self._set_connected(True) self.__retried = 0 for topic in self.subscriptions.keys(): (res, mid) = self.client.subscribe(topic) self.log.debug("%s: subscribing to '%s' => mid: '%s' == '%s'" % (self.get_identifier(), topic, mid, res)) self.subscriptions[topic]['mid'] = mid self.subscriptions[topic]['subscription_result'] = res else: self._set_connected(False) self.__connection_error_counter += 1 if self.__connection_error_counter >= self.__switch_threshold: self.switch_to_host(blacklist_current=True) return msg = mqtt.error_string(rc) self.log.error("%s: MQTT connection error: %s" % (self.get_identifier(), msg)) self.__reconnect()
def __init__(self, namespace, device_uid, username, password, broker_host=DEFAULT_BROKER_HOST, loop_forever=False, explicit_vhost=None): self.namespace = str(namespace) self.device_uid = device_uid self.guid = '%s.%s' % (namespace, device_uid) self.self_topic_name = self.guid if explicit_vhost: vhost = explicit_vhost else: vhost = namespace if vhost: username = '******' % (vhost, username) self.mqtt_client = mqtt.Client(client_id=self.guid, clean_session=False, protocol=MQTTv311) self.mqtt_client.username_pw_set(username, password) self.mqtt_client.on_connect = self.on_connect self.mqtt_client.on_message = self.on_message print "Connecting to %s" % broker_host rc = self.mqtt_client.connect(broker_host, 1883, 60) print('connect(): %s' % error_string(rc)) # 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. if loop_forever: self.mqtt_client.loop_forever()
def error_str(rc): """Convert a Paho error to a human readable string.""" return '{}: {}'.format(rc, mqtt.error_string(rc))
def _on_disconnect(self, client, userdata, return_code): error = mqtt.error_string(return_code) print('disconnected from mqtt broker: {}'.format(error)) # Reconnects using the client information provided previously. self._client.reconnect()
def mqtt_disconnect(self, client, userdata, rc): log.debug("MQTT disconnect: %s", mqtt.error_string(rc))
def on_disconnect(self, client, obj, rc): self.app.log.info("Disconnected from MQTT broker (rc=%d, %s)", rc, mqtt.error_string(rc)) self.connected = False
def on_disconnect(self, client, userdata, rc): # We could implement a reconnect call. self.is_connected = False self.logger.info("[Exiting] Disconnected: %s" % mqtt.error_string(rc)) self.client.loop_stop() self.connect()
def on_connect(self, client, userdata, flags, rc): print('on_connect: %s' % error_string(rc)) if rc != 0: raise ByteportConnectException("Error while connecting to MQTT Broker: " + error_string(rc))
import paho.mqtt.client as mqtt client = mqtt.Client() client.connect("test.mosquitto.org", port=1883) client.publish("IC.embedded/WhyPhy/test", "It's okay") mqtt.error_string((client.publish("IC.embedded/WhyPhy/test", "It's okay")).rc)
def _on_disconnect(self, client, userdata, rc): logger.info(mqtt.error_string(rc))
def on_disconnect(client: mqtt.Client, ref_self: IotManager, return_code: int) -> None: """Callback for when a device disconnects from mqtt broker.""" error = "{}: {}".format(return_code, mqtt.error_string(return_code)) ref_self.is_connected = False
def mqtt_publish(path, mqtt_message): msg_info = client.publish(path, mqtt_message) publish_out = mqtt.error_string(msg_info.rc) print("publish status: " + publish_out + "\n")
def on_connect(self, client, userdata, flags, rc): print("Succesful with result code " + str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. self.client.subscribe("IC.Embedded/IOS/#") print(mqtt.error_string(MSG_INFO.rc))
def _on_connect(self, client, userdata, flags, rc): if rc != mqtt_client.MQTT_ERR_SUCCESS: log.error("unable to connect to broker '%s:%d': " % (self._addons['mqtt_server'],self._addons['mqtt_port']) + mqtt_client.error_string(rc)) return log.info("connected to broker :)") self._connected = True # subscribe to topics list try: for topic in self._mqtt_topics: log.debug("subscribing to " + str(topic)) self._connection.subscribe( topic ) # QoS=0 default except Exception as ex: log.warn("exception while subscribing to topic '%s' :" % str(topic) + str(ex))
def _mqtt_loop(self): rc = self.mqtt_client.loop(timeout=0) if rc != 0: logger.error('Error in MQTT loop (%d): %s', rc, paho.error_string(rc)) self._loop.call_later(1.0, self._mqtt_loop)
#Generate a message containing random color to simulate message sending from device for purpose of debugging Application(Js) import paho.mqtt.client as mqtt client = mqtt.Client(transport="websockets") client.tls_set(certfile="keys/client.crt", keyfile="keys/client.key") client.connect("test.mosquitto.org", port=8081) import random num = random.random() print(num) if (num < 0.2): print("Blue") MSG_INFO = client.publish("IC.Embedded/IOS/test", "Blue") elif (num < 0.4): print("Red") MSG_INFO = client.publish("IC.Embedded/IOS/test", "Red") elif (num < 0.6): print("Orange") MSG_INFO = client.publish("IC.Embedded/IOS/test", "Orange") elif (num < 0.8): print("White") MSG_INFO = client.publish("IC.Embedded/IOS/test", "White") else: print("Pink") MSG_INFO = client.publish("IC.Embedded/IOS/test", "Pink") print(mqtt.error_string(MSG_INFO.rc))
def on_disconnect(client, userdata, rc): print("Device disconnected with result code: " + str(rc)) print(mqtt.error_string(rc))
client = mqtt.Client() client.tls_set(ca_certs="/home/pi/embedded/mosquitto.org.crt", certfile="/home/pi/embedded/client.crt", keyfile="/home/pi/embedded/client.key") connected=False while (not connected): try: client.connect("test.mosquitto.org", port=8884) connected=True except: print("connection failed trying again") #Cheching if connection is succesfull again if client.connect("test.mosquitto.org", port=8884) == 0: print("Connection successful") else: print("Error connection unsuccessful") print(mqtt.error_string(RETURN_CODE)) sys.exit(1) #We initialize the door to be Locked on start up MSG_INFO = client.publish("IC.embedded/patriots/tmp", "Door Locked") mqtt.error_string(MSG_INFO.rc) # MSG_INFO is result of publish() #Reading the incoming message to see if the alarm system should be Active or Not def on_message(client, userdata, message): message_string = str(message.payload) message_string = message_string[2:len(message_string)-1] if message_string == "Active": global warning_sent warning_sent = False elif message_string == "Not Active": global warning_sent
def on_connect(client, data, flags, rc): logger.info("Connection status: %s", mqtt.error_string(rc)) client.subscribe(MQTT_SETTINGS.topic_req, qos=1)
def error_str(rc): return '{}: {}'.format(rc, mqtt.error_string(rc))
def _on_disconnect(self, client, userdata, rc): _log.debug('on_disconnect event, status: {}'.format( mqttc.error_string(rc))) self.create_connection(False)
def on_connect(self, client, obj, flags, rc): self.app.log.info("Connected to MQTT broker %s:%s (rc=%d, %s)", self.app.mqtt_broker, self.app.mqtt_port, rc, mqtt.error_string(rc)) self.app.log.info("Subscribing to: %s", self.app.topic) self.client.subscribe(self.app.topic)
sampleSec = maxSampleSecs #20 mins is max sampling window else: sampleSec += 1 #increment cpm window time if less than 20 mins runSec += 1 #increment total time sendArray = [{ "time": datetime.now().strftime('%H:%M:%S'), "currentCPM": currentCpm }] #array of CPM and timestamp payload = json.dumps( {"CPMData": sendArray}) #create JSON array with counts and timestamp publish = client.publish("IC.embedded/Embedded/user1", payload, qos=0) #publish payload to broker if publish.rc != 0: print(mqtt.error_string( publish.rc)) #notify if error in publishing sampleMins = sampleSec / 60.0 #calculate minutes elapsed #print(sampleMins) if sampleMins != 0: currentCpm = counts / sampleMins #calculate current CPM else: currentCpm = 0 #avoid division by zero #print("Current CPM: {}".format(counts)) lcd_line_1 = datetime.now().strftime( '%b %d %H:%M:%S\n') #display current date and time lcd_line_2 = "Counts/min: " + str( currentCpm) #display current count average lcd.message = lcd_line_1 + lcd_line_2 #write date, time and counts to LCD
def _on_disconnect(self, client, userdata, return_code): logger.info('disconnected from mqtt broker: {}'.format( mqtt.error_string(return_code))) self._client.reconnect()
def error_str(rc): return "Some error occurred. {}: {}".format(rc, mqtt.error_string(rc))
raw=z, max=max_array[3], min=min_array[3], med_bool=1) if update_med: med_array[3] = (max_array[3] + min_array[3]) / 2 current_z, print_z = spi.update_sensor_out(curr=current_z, val=z, max_val=max_array[3], med_val=med_array[3], min_val=min_array[3], weight=spi.z_weight, threshold=15) # Can probably format data (output from the function below) as a dict data = spi.to_send(print_ir, print_x, print_y, print_z) if data != "nan": currentTime = datetime.datetime.now() print("Message sent at:", currentTime) j_data = extract_data(data) print("Publishing to " + spi.publish_topic1 + "...") print( mqtt.error_string( client.publish(topic=spi.publish_topic1, payload=json.dumps(j_data), qos=1).rc)) sleep(0.1) else: print("Pas de connexion") spi.flash_led(spi.FAIL_LED, 2) client.loop_stop() break
print("--on_publish callback --mid: " + str(mid) ) client = mqtt.Client() client.on_subscribe = on_subscribe client.on_message = on_message client.on_publish = on_publish client.on_connect = on_connect try: client.username_pw_set(username="******", password="******") client.connect("127.0.0.1", 1883) except: print("Connection Failed") try: client.subscribe("isima/G12/#", qos=0) client.loop_start() while True: (rc, mid) = client.publish(topic="isima/G12", payload="TEST_G12 le message", qos=0) (rc, mid) = client.publish(topic="isima/G13", payload="TEST_G13 test de base", qos=0) print("Error return from publish of mid = " + str(mid) +" : " + mqtt.error_string(rc)) time.sleep(5) except KeyboardInterrupt: client.loop_stop() client.unsubscribe("isima/G12/#") client.disconnect() print("Done.")
def on_disconnect(client, userdata, rc): print 'Disconnection result:', error_string(rc)
def on_disconnect(client, userdata, rc): logging.info("Disconnected with result: " + mqtt.error_string(rc)) led_set(False)
def _on_disconnect(self, client, userdata, return_code): logger.info('disconnected from mqtt broker: {}'.format(mqtt.error_string(return_code))) self._client.reconnect()
def unsubscribe(self, topic): self.idMap_lock.acquire() try: (rc, mid) = self._iot_mqtt_client_handler.unsubscribe(topic) new_key = idMap_key(topic, None) ino_id = self.idMap[new_key].get_ino_id() del self.idMap[new_key] except BaseException as e: send_output(self.wrapper_debug, self.wrapper_Tx, "U F " + str(e.message)) return finally: self.idMap_lock.release() send_output(self.wrapper_debug, self.wrapper_Tx, "U " + str(rc) + " " + str(ino_id) + " " + mqtt.error_string(rc)) # send back the return value along with the ino_id for C side reference to free the subgroup slot (important) return rc
#!/usr/bin/env python3 import time import paho.mqtt.client as paho broker = 'localhost' queue = 'house/bulb1' username = "******" password = "******" client = paho.Client('client-002') client.username_pw_set(username=username, password=password) print('connecting to broker {}'.format(broker)) res = client.connect(broker) if res != paho.MQTT_ERR_SUCCESS: print('connect failed: {}'.format(paho.error_string(res))) exit(1) print('publishing to {}'.format(queue)) res = client.publish(queue, 'hello world') if res[0] != paho.MQTT_ERR_SUCCESS: print('publish failed: {}'.format(paho.error_string(res))) exit(1) res = client.disconnect() if res != paho.MQTT_ERR_SUCCESS: print('disconnect failed: {}'.format(paho.error_string(res))) exit(1) print('done')
def error_str(rc): """Convert a Paho error to a human readable string.""" return "Some error occurred. {}: {}".format(rc, mqtt.error_string(rc))
def on_connect(client, data, flags, rc): print_d("Connect: {msg}", msg=mqtt.error_string(rc)) client.subscribe(MQTT_SETTINGS.topic_req, qos=1)
def print_error_msg(rc): if rc != mqtt.MQTT_ERR_SUCCESS: mqtt.error_string(rc)
def run(self, death, translator_func, submit_func): def on_message(client, userdata, msg): if not msg.topic or not msg.payload: return try: payload = msg.payload if isinstance(payload, six.binary_type): payload = payload.decode("utf8") details = {'event': json.loads(payload)} except (UnicodeError, ValueError): LOG.exception("Received corrupted/invalid payload: %s", msg.payload) else: message = translator_func(details) if message is not None: try: submit_func(message) except RuntimeError: pass config = self.config real_client = utils.make_mqtt_client(config) real_client.on_message = on_message rc = mqtt.MQTT_ERR_SUCCESS running = True while not death.is_set() and running: max_duration = self.MAX_READ_LOOP_DURATION reconnect_wait = self.RECONNECT_WAIT with timeutils.StopWatch(duration=max_duration) as watch: try: while (rc == mqtt.MQTT_ERR_SUCCESS and not watch.expired()): rc = real_client.loop(timeout=watch.leftover()) if death.is_set(): break except IOError: LOG.exception("Failed consumption") rc = mqtt.MQTT_ERR_UNKNOWN if rc in [ mqtt.MQTT_ERR_NO_CONN, mqtt.MQTT_ERR_CONN_REFUSED, mqtt.MQTT_ERR_CONN_LOST, mqtt.MQTT_ERR_NOT_FOUND, mqtt.MQTT_ERR_UNKNOWN ]: LOG.warn("Reconnecting, reason=%s", mqtt.error_string(rc)) try: real_client.reconnect() except IOError: LOG.exception("Failed reconnecting") LOG.info("Waiting %s seconds before retrying", reconnect_wait) death.wait(reconnect_wait) else: rc = mqtt.MQTT_ERR_SUCCESS elif rc == mqtt.MQTT_ERR_NOMEM: # The client seems to leak memory... # # What a PITA... LOG.critical("Regenerating client, client" " reported out of memory") try: real_client = utils.make_mqtt_client(config) except IOError: LOG.critical( "Fatal client failure (unable" " to recreate client), reason=%s", mqtt.error_string(rc)) running = False else: real_client.on_message = on_message rc = mqtt.MQTT_ERR_SUCCESS elif rc != mqtt.MQTT_ERR_SUCCESS: LOG.critical("Fatal client failure, reason=%s", mqtt.error_string(rc)) running = False
def on_mqtt_disconnect(self, client, userdata, rc): logger.warning("Disconnected with result code %d", rc) if rc == 1: self.refresh_remote_token(force=True) else: logger.warning(mqtt.error_string(rc))
def disconnect(self): try: self._iot_mqtt_client_handler.disconnect() self._iot_mqtt_client_handler.loop_stop() except BaseException as e: send_output(self.wrapper_debug, self.wrapper_Tx, "D F " + e.message) return cnt_sec = 0 while cnt_sec < MAX_CONN_TIME and self.disconn_res == -1: # waiting for on_disconnect cnt_sec += 1 time.sleep(1) if self.disconn_res != -1: send_output(self.wrapper_debug, self.wrapper_Tx, "D " + str(self.disconn_res) + " " + mqtt.error_string(self.disconn_res)) else: send_output(self.wrapper_debug, self.wrapper_Tx, "D F Disconnection time out") return self.disconn_res
def _on_disconnect(client, userdata, flags, rc): msg = mqtt.error_string(rc) logging.warning("Disconnected from client: " + msg)
def publish(self, topic, payload, *args, **kwargs): """publish message using paho library """ logger.debug("Publishing on '%s'", topic) msg = self._client.publish(topic, payload, *args, **kwargs) if not msg.is_published: raise exceptions.MQTTError("err {:s}: {:s}".format(_err_vals.get(msg.rc, "unknown"), paho.error_string(msg.rc))) return msg
elif k == "D": mqttc.disconnect() connected = False mqttc.loop_stop() elif k == "P": pub_topic = input("Publish to topic (<Enter> for '{}'): ".format(pub_topic)).strip() or pub_topic pub_msg_template = input("Publish message template ({{}} replaced with next input) (<Enter> for '{}'): ".format(pub_msg_template)).strip() or pub_msg_template payld = pub_msg_template if '{}' in pub_msg_template: pub_msg_subst = str(1 + int(pub_msg_subst)) if pub_msg_subst.isdigit() else pub_msg_subst pub_msg_subst = input("{{}} substitution (<Enter> for {}): ".format(pub_msg_subst)).strip() or pub_msg_subst payld = pub_msg_template.format(pub_msg_subst) print("...publishing message '{}' to topic '{}' (qos=0, retain=False)".format(payld, pub_topic)) (result, msg_id) = mqttc.publish(pub_topic, payload=payld, qos=0, retain=False) print("...msg_id={!r}, result={} ({})".format(msg_id, result, mqtt.error_string(result))) elif k == "S": sub_topic = input("Subscribe to topic (<Enter> for '{}'): ".format(sub_topic)).strip() or sub_topic print("...subscribing to topic: {} (qos=0)".format(sub_topic)) mqttc.subscribe(sub_topic, qos=0) elif k == "U": sub_topic = input("Unsubscribe from topic (<Enter> for '{}'): ".format(sub_topic)).strip() or sub_topic print("...unsubscribing from topic: " + sub_topic) mqttc.unsubscribe(sub_topic) elif k == "L": log_enabled = not log_enabled elif k == "Q":
def main(): # pylint: disable=too-many-locals """ The main entry point. """ parser = init_parser() options = parser.parse_args() host = options.host port = options.port keepalive = options.keepalive client_id = options.client_id topic = options.topic qos = options.qos filename = options.file interval = options.interval min_interval = options.min_interval max_interval = options.max_interval prompt_to_send = options.prompt_to_send client = mqtt.Client(client_id) client.on_connect = on_connect client.on_disconnect = on_disconnect client.on_publish = on_publish client.on_log = on_log client.connect(host, port, keepalive) client.loop_start() publish_time = 0 with open(filename) as file_object: message = file_object.readline().rstrip() while message: interval = random.randint(min_interval, max_interval) current_time = int(time.time() + 0.5) used_time = current_time - publish_time if used_time < interval: time.sleep(interval - used_time) publish_time = int(time.time() + 0.5) message = message.replace("{DATETIME}", str(publish_time)) if prompt_to_send: print("press enter to send next message.") if PY2: raw_input() # (only a python 3 error) pylint: disable=undefined-variable else: input() mqtt_message_info = client.publish(topic, message, qos=qos) print("Publish: %s has return code %i, %s" % (mqtt_message_info.mid, mqtt_message_info.rc, mqtt.error_string(mqtt_message_info.rc))) if mqtt_message_info.rc != mqtt.MQTT_ERR_SUCCESS: raise ValueError(mqtt.error_string(mqtt_message_info.rc)) if not mqtt_message_info.is_published(): print("Waiting for publish.") mqtt_message_info.wait_for_publish() message = file_object.readline().rstrip() client.disconnect() print("Done")
client.on_message = on_message client.on_connect = on_connect client.on_publish = on_publish try: # client.username_pw_set(username="******", password="******") client.connect("172.16.32.8", 1883) except: print("Connection Failed") client.subscribe(topic_public_key, qos=0) client.subscribe(topic_messages, qos=0) client.loop_start() # print(A_public_key) while True: # Si on a pas la clef publique de Bob, on publie la notre dans l'espoir que Bob reponde avec la sienne if (Bob_public_key == b"0"): # On publie notre clef publique (rc, mid) = client.publish(topic=topic_public_key, payload=A_public_key, qos=0) print("Error return from publish of mid = " + str(mid) + " : " + mqtt.error_string(rc)) # (rc, mid) = client.publish(topic="/ISIMA/TP_7/GROUPE_12/Bob_messages", payload="ON", qos=0) # print("Error return from publish of mid = " + str(mid) +" : " + mqtt.error_string(rc)) time.sleep(5)