def on_message(client: mqtt.Client, userdata, msg: mqtt.MQTTMessage): print("Printing shopping list", flush=True) try: shopping_list = get_shopping_list(userdata) except selenium.common.exceptions.WebDriverException as e: print(e) return data = json.dumps({ "subject": "Shopping List", "message": shopping_list }) client.publish("printer/print", data)
def on_message(self, client: mqtt.Client, userdata, message: mqtt.MQTTMessage): # Check if this is a message that sets the lock if message.topic == self.set_topic or message.topic == self.scheduler_topic: # Read the target state lock: str = message.payload.decode("utf-8") print("Setting the lock to %s" % lock) self.last_state = lock # Echo it back response = lock client.publish(self.state_topic, response, qos=1, retain=True) else: # Pass the message down SIISThing.on_message(self, client, userdata, message)
def testpubsub(self): client = Client() HOST = "localhost" client.connect(HOST, 1883, 60) topic = "TOPIC_PASSIVE_LISTEN" while True: str = raw_input() if str: client.publish( topic, json.dumps({ "transcribed": "HEYXIAORUI", "threshold": None }))
def on_connect(client: Client, userdata, flags, rc, properties=None): """ mqtt连接回调函数 """ global isOk status = ['连接成功', '协议版本错误', '客户端标识符无效', '服务器不可用', '用户名或密码错误', '未授权'] if rc != 0: sys.exit(status[rc]) else: with open('captured_packet.json', encoding='utf-8') as f: packet_info = json.load(f) # 发布信息 print('🙉 代理服务器连接成功!') client.publish(packet_info['topic'], packet_info['msg'], 1) print('🙊 假数据包发送成功!') isOk = True client.disconnect()
def main(): client = Client(client_id="SHELL/UTILITY") client.connect(host=SERVICE_BROKER_PORT["ip"], port=SERVICE_BROKER_PORT["port"]) client.loop_start() chat_id = int( input_dialog( title='Chat ID', text='Please activate the bot on your phone:' ' https://t.me/SmartHome_IoTbot and type here your' ' telegram chat id .. to obtain it go to ' 'https://telegram.me/get_id_bot:').run() ) client.publish(topic=SERVICE_TOPIC, payload=json.dumps({"chat_id": chat_id})) client.loop_stop() client.disconnect()
class AzureIoT(IotProvider): def __init__(self, iot_provider_cfg): # 1. Set device_name. # 2. Set tls_version. # 3. Set MQTT Protocol version # 4. Call parent class' __init__ self.device_name = iot_provider_cfg["device_name"] self.tls_version = eval( f"ssl.PROTOCOL_TLSv1_{iot_provider_cfg['tls_version']}") self.mqtt_version = eval( f"mqtt.MQTTv{iot_provider_cfg['mqtt_version']}") super().__init__(iot_provider_cfg) def on_connect(self, client, userdata, flags, rc): # Event handler for connection event. Subscribe to topic(s) here. client.subscribe(self.subscribe_topic, qos=0) def on_disconnect(client, userdata, rc): print(f"Disconnected with code {rc}") def onmsg(self, client, userdata, msg): # Wraps core event handler for incoming messages msg_payload = msg.payload super().onmsg(msg_payload) def connect(self): # A connection to iot is established at the beginning and if publish fails self.azure_iot_comm = Client(client_id=self.device_name, protocol=self.mqtt_version) self.azure_iot_comm.on_connect = self.on_connect self.azure_iot_comm.on_disconnect = self.on_disconnect self.azure_iot_comm.on_message = self.onmsg self.azure_iot_comm.username_pw_set( username=f"{self.iot_broker}/{self.device_name}") self.azure_iot_comm.tls_set(self.iot_ca_cert_path, self.iot_client_cert_path, self.iot_client_key_path, tls_version=self.tls_version, cert_reqs=ssl.CERT_REQUIRED) self.azure_iot_comm.connect(self.iot_broker, self.iot_port) self.azure_iot_comm.loop_start() def disconnect(self): self.azure_iot_comm.disconnect() def publish(self, publish_topic, msg_str, qos): # Overriding qos to 0 because Azure doesn't seem to like any other qos self.azure_iot_comm.publish(publish_topic, msg_str, qos=0)
def on_message(self, client: mqtt.Client, userdata, msg): self.logger.debug("Received {}:{}".format(msg.topic, msg.payload)) if msg.topic == MQTT_SET_TOPIC: if msg.payload.decode() == MQTT_ON_MESSAGE: self.logger.info("Enabling Noisy") self.noisy_run_flag.set() self.noisy_thread = threading.Thread( target=self.noisy.crawl, args=(self.noisy_run_flag, )) self.noisy_thread.start() client.publish(MQTT_STATE_TOPIC, MQTT_ON_MESSAGE) elif msg.payload.decode() == MQTT_OFF_MESSAGE: self.logger.info("Disabling Noisy") self.noisy_run_flag.clear() self.noisy_thread.join() client.publish(MQTT_STATE_TOPIC, MQTT_OFF_MESSAGE)
class MqttController: def __init__(self): self.client = Client() self.client.on_connect = self.__on_connect self.client.on_message = self.__on_message self.evtCallback: Optional[EventCallback] = None def connect(self, connectCallback, host, port=1883, keepalive=60): log.info("Trying to connect MQTT client.") self.connectCallback = connectCallback self.client.connect(host, port, keepalive) self.client.loop_start() def disconnect(self): self.client.loop_stop() self.client.disconnect() def setCallback(self, callback: EventCallback): self.evtCallback = callback def delCallback(self): self.evtCallback = None def __on_connect(self, client, userdata, flags, rc): log.info("MQTT client connected, registering subscriptions.") self.client.subscribe("/baresip/event") self.connectCallback() def __on_message(self, client, userdata, msg: MQTTMessage): log.info("MQTT message received for path=%s.", msg.topic) log.debug("payload=%s", msg.payload) # parse message try: msgObj = json.loads(msg.payload) evtType = EventType[msgObj["type"]] # notify respective callback cb = self.evtCallback if cb is not None: log.debug("Calling event callback in a thread.") t = threading.Thread(target=lambda: cb(evtType, msgObj)) t.start() else: log.debug("No callback registered.") except JSONDecodeError: log.error("Received invalid JSON message.") except KeyError: log.warn("Received unhandled type code or type code is missing.") def send_command(self, msg): log.debug("Trying to send message %s to phone.", msg) info = self.client.publish("/baresip/command/", msg) log.debug("Waiting for publish") log.debug(info.rc) info.wait_for_publish() if info.rc != MQTT_ERR_SUCCESS: log.error("Failed to publish message") else: log.debug("Message sent successfully.")
class MQTT: client = None def __init__(self, client_id: str = 'raspberry005', clean_session: bool = True, auto_connect: bool = True, **kwargs): self.client = Client(client_id=client_id, clean_session=clean_session, **kwargs) self.client.on_message = self._on_message if auto_connect: self.connect(host='iot.eclipse.org') def connect(self, host: str, port: int = 1883, keepalive: int = 60, **kwargs): is_connected = self.client.connect(host=host, port=port, keepalive=keepalive, **kwargs) if is_connected in range(3): log.info('Successful connect') return True raise ConnectionError(f'MQTT connection error id {is_connected}') def _on_message(self, client, userdata, msg): log.info(f'{msg.topic} {msg.payload!s}') def pulish(self, topic: str, payload: str = None, retain: bool = False, **kwargs): message_info = self.client.publish(topic=topic, payload=payload, retain=retain, **kwargs) message_info.wait_for_publish() if message_info.is_published(): log.info(f'Successful published message "{payload}" to topic {topic}') return True log.info(f'Publishing error for message "{payload}" to topic {topic}') return False def __del__(self): self.client.disconnect()
def publish_soil_status_mqtt( analog_signal, soil_wet, ): mqttBroker = "localhost" client = Client("Temperature_Inside") client.username_pw_set(username=uname, password=passwd) client.connect(mqttBroker) moisture_sensor_number = analog_signal + 1 moisture_sensor_name = "MOISTURE" + str(moisture_sensor_number) if soil_wet == 1: payload = "WET SOIL" elif soil_wet == 0: payload = "DRY SOIL" client.publish(moisture_sensor_name, payload) print("Published MQTT " + moisture_sensor_name + ": " + payload)
def on_message(client: mqtt.Client, userdata, msg: mqtt.MQTTMessage): try: data = msg.payload.decode("utf-8") if msg.topic == "farm/farm1/instants": try: commands = json.loads(data) for command in commands: run.run_command(command) except Exception: print(data) traceback.print_exc() elif msg.topic == "farm/farm1/ping" and data == "ping": client.publish("farm/farm1/ping", "pong") else: print(data) except Exception: traceback.print_exc()
class MqttClientConnector(): _host = None _port = None _brokerAddr = None _mqttClient = None def __init__(self, host, port, on_connect, on_message, on_publish, on_subscribe): self._brokerAddr = host + ":" + str(port) self._host = host self._port = port self._mqttClient = Client() self._mqttClient.on_connect = on_connect self._mqttClient.on_message = on_message self._mqttClient.on_publish = on_publish self._mqttClient.on_subscribe = on_subscribe def connect(self): try: # make a connection with broker print("Connect to broker:" + self._brokerAddr + ".....") self._mqttClient.connect(self._host, self._port, 60) self._mqttClient.loop_start() except Exception as e: print("Broker error, Connected failed" + str(e)) def disconnect(self): # disconnect with broker self._mqttClient.disconnect() self._mqttClient.loop_stop() def publishMessage(self, topic, message, qos): # publish msg to remote boroker print("Start publishing message : " + message) self._mqttClient.publish(topic, message, qos) def subscribeTopic(self, topic, qos): # subscribe msg to remote boroker print("Start subscribing to topic: " + topic) self._mqttClient.subscribe(topic, qos)
def main(): p = argparse.ArgumentParser() p.add_argument('-a', '--account-path', help='Path to JSON file containing Google account details') args = p.parse_args() google_session = get_google_session(args.account_path) brokers = {} clients = [] reporter = Reporter(google_session) for device_id, device, desc in generate_devices_from_config(): if not device.url.startswith('mqtt://'): continue device_name, host, port, username, password = parse_mqtt_url( device.url) broker = (host, port, username, password) brokers.setdefault(broker, {}).setdefault(device_name, []).append(device) for (host, port, username, password), devices in brokers.items(): client = Client(clean_session=True, userdata=devices) client.on_message = reporter.on_msg if username is not None: client.username_pw_set(username, password) client.connect(host, port) for device_name in devices: # log(f'{device_name} --> STATE') client.subscribe(f'stat/{device_name}/RESULT') client.publish(f'cmnd/{device_name}/state') client.loop_start() clients.append(client) try: while 1: time.sleep(5) except KeyboardInterrupt: print('Ctrl-C') for client in clients: client.loop_stop()
def run(client: mqtt.Client): client.publish( f"homeassistant/switch/{CONFIG.get_device_name()}/screen/config", f'{{"unique_id": "screen-{CONFIG.get_device_name()}", "name": "{CONFIG.get_device_name()} Screen", "device": {{"identifiers": ["{CONFIG.get_device_name()}"], "name": "{CONFIG.get_device_name()}"}}, "~": "homeassistant/switch/{CONFIG.get_device_name()}/screen", "availability_topic": "~/state", "command_topic": "~/set", "retain": true}}', retain=True) client.publish( f"homeassistant/switch/{CONFIG.get_device_name()}/screen/state", "online", retain=True) logging.info("Set mqtt toptic state to online") client.subscribe( f"homeassistant/switch/{CONFIG.get_device_name()}/screen/set") client.on_message = on_message client.loop_forever()
class MQTTSnipsComponent(SnipsComponent): """A Snips component using the MQTT protocol directly. Attributes: snips (:class:`.SnipsConfig`): The Snips configuration. mqtt (`paho.mqtt.client.Client`_): The MQTT client object. .. _`paho.mqtt.client.Client`: https://www.eclipse.org/paho/clients/python/docs/#client """ def _connect(self): """Connect with the MQTT broker referenced in the Snips configuration file. """ self.mqtt = Client() self.mqtt.on_connect = self._subscribe_topics connect(self.mqtt, self.snips.mqtt) def _start(self): """Start the event loop to the MQTT broker so the component starts listening to MQTT topics and the callback methods are called. """ self.mqtt.loop_forever() def _subscribe_topics(self, client, userdata, flags, connection_result): """Subscribe to the MQTT topics we're interested in. Each method with an attribute set by a :func:`snipskit.decorators.mqtt.topic` decorator is registered as a callback for the corresponding topic. """ for name in dir(self): callable_name = getattr(self, name) if hasattr(callable_name, 'topic'): self.mqtt.subscribe(getattr(callable_name, 'topic')) self.mqtt.message_callback_add(getattr(callable_name, 'topic'), callable_name) def publish(self, topic, payload, json_encode=True): """Publish a payload on an MQTT topic on the MQTT broker of this object. Args: topic (str): The MQTT topic to publish the payload on. payload (str): The payload to publish. json_encode (bool, optional): Whether or not the payload is a dict that will be encoded as a JSON string. The default value is True. Set this to False if you want to publish a binary payload as-is. Returns: :class:`paho.mqtt.MQTTMessageInfo`: Information about the publication of the message. .. versionadded:: 0.5.0 """ if json_encode: payload = json.dumps(payload) return self.mqtt.publish(topic, payload)
def publish_to_channel(paho_client: Client, message: str, topic: str, qos: int = 0) -> None: rc = paho_client.publish(payload=message, topic=topic, qos=qos) if rc == MQTT_ERR_NO_CONN: raise ConnectionRefusedError( f"Unable to publish message '{message}'. Client not connected: rc = {rc}" )
def test_run(self, threshold_value_config: ThresholdValueEstimatorConfig, mqtt_config: Client): centroid_value = threshold_value_config.run() assert centroid_value == 120 wait_all_mqtt_messages_consumed( f'mqtt-subscription-{threshold_value_config._mqtt_client_id}' f'qos{threshold_value_config.qos}') mqtt_config.publish( topic='test/car/config/threshold_value_estimator/centroid_value', payload="220", qos=1).wait_for_publish() wait_all_mqtt_messages_consumed( f'mqtt-subscription-{threshold_value_config._mqtt_client_id}' f'qos{threshold_value_config.qos}') centroid_value = threshold_value_config.run() assert centroid_value == 220
def my_on_message(self, client: Client, userdata: Any, msg: MQTTMessage, email_service: Client = None): """ Check if alarm is true. If so, send emails. :param client: MQTT client :param userdata: They could be any type :param msg: MQTT message :param email_service: Service Client """ data = json.loads(msg.payload.decode()) if data["alarm"]: message_body = f"{data['device']} is out of range of good functioning" else: return with self.user_lock: for user_id in self._user_list: for email in self._user_list[user_id]: msg = MIMEMultipart() msg["From"] = f"Smart Home - IoT distributed platform <{self.from_email}>" msg["To"] = email msg["Subject"] = self.subject msg.attach(MIMEText(message_body + self.signature, 'plain')) server = smtplib.SMTP("smtp.gmail.com", 587) server.starttls() server.login(self.from_email, self.password) text = msg.as_string() server.sendmail(self.from_email, email, text) server.quit() print(f"[{time.ctime()}] EMAIL SENT TO {email}") email_service.publish(self.alarm_user_topic, payload=json.dumps({ "userID": [user_id for user_id in self._user_list] })) print( f"[{time.ctime()}] EMAILS SENT TO USERS: {[user_id for user_id in self._user_list]}" )
class MQTT_PUBLISHER: def __init__(self): self.client = Client() def schedule(self, event_name, event_value, topic, host, port, value_name, value): if event_name == 'INIT': # connects to the broker self.client.connect(host, port) return [event_value, None] elif event_name == 'RUN': message_dict = {value_name: str(value)} message = json.dumps(message_dict) self.client.publish(topic, message) return [None, event_value] def __del__(self): self.client.disconnect()
def on_message(client: mqtt.Client, userdata, msg: mqtt.MQTTMessage): node_name, sensor_name = path.split(msg.topic) if sensor_name == "key" and not args.watch: they_pk = msg.payload.decode() client.publish("server/key", payload=public_key, qos=1, retain=False) sk = dh.gen_shared_key(int(they_pk)) print(f"key exchange completed with {node_name} node, shared key {sk}") hbname = node_name + "/heartbeat" if hbname in monitors: hbm: monitor.heartbeat.HeartbeatMonitor = monitors[hbname] hbm.init(sk) else: hbm = monitor.heartbeat.HeartbeatMonitor(sk) monitors[hbname] = hbm processor.threats.append(hbm.threats) processor.update() authenticated[node_name] = True if node_name == "box" and alarm and not args.watch: # box node was turned off and is coming back online, hit the alarm! client.publish("server/alarm", 1, qos=1) return if msg.topic in monitors: if node_name in authenticated.keys() or args.watch: value = float(msg.payload.decode()) monitors[msg.topic].input(value) if sensor_name == "heartbeat": db.write_heartbeat(node_name) else: db.write_cache(node_name, sensor_name, value) else: print( f"rejected value {msg.payload} from {msg.topic} because {node_name} not in {authenticated.keys()}" )
def sample(entries: list, delta_t: float, client: mqtt.Client = client, initial_call: int = 0) -> None: """Run one sampling iteration, and creates/runs a timer for the next one""" global next_call next_call += cfg.sample_period print("Taking a sample at time %0.1fs" % (time.time() - start_time)) client.publish("/nodes", cfg.client_name) samples: list = [time.time()] # Add all the values to the samples list for entry in entries: try: with open(entry.path, "r") as file: # Take care of the differential variables if entry.differential == 1: raw = float(file.readline().split()[0]) if initial_call: val_buf: float = 0 else: val_buf = raw - entry.previous_raw entry.previous_raw = raw else: val_buf = float(file.readline().split()[0]) message = json.dumps({ "value": val_buf, "unit": entry.unit, "ts": samples[0], "std": entry.std, "average": entry.average }) client.publish(cfg.client_name + entry.topic, message) samples += [val_buf] except FileNotFoundError: pass # Write the samples to the CSV file # with open(cfg.csv_path, "a") as csv_file: # csv_writer = csv.writer(csv_file) # csv_writer.writerow(samples) threading.Timer(next_call - time.time(), sample, args=[entries, cfg.sample_period, client]).start()
def run_client(settings): def on_connect(*args, **kwargs): print("connected") def on_message(*args, **kwargs): print("message received", args, kwargs) client = MQTTClient() client.on_connect = on_connect client.on_message = on_message client.connect(server, settings["mqtt_settings"]["port"], 60) t0 = time.time() while True: time.sleep(1) client.loop() td = time.time() - t0 f = lambda x: np.log(x / 10) * 10 + 50 data = '{"meat_temp": %.1f, "oven_temp": %.1f}' % (f(td), f(td + 100)) print("publishing data") client.publish("test_topic", data)
class MqttPublisher(BasePublisher): def __init__(self, *args, **kwargs): self.client = None self.message = None def connect(self, host="localhost", port=5000): self.client = Client() self.client.connect(host=host) print("Connected") def send_message(self, message, topic="test"): msg_size = len(message["message"]) message["sentAt"] = time.time() message["size_in_BYTES"] = msg_size self.client.publish(topic=topic, payload=json.dumps(message)) print("Published") def close(self): pass
def on_message(client: mqtt.Client, userdata, message: mqtt.MQTTMessage): if message.topic == cfg.mqtt_command_topic: try: msg = message.payload.decode('utf-8') print(msg) data = json.loads(msg) if 'brightness' in data: light.set_brightness(data['brightness']) if 'color' in data: light.set_color(data['color']['r'], data['color']['g'], data['color']['b']) if 'state' in data: light.set_state(data['state'] == 'ON') json_state = light.create_state_json() client.publish(cfg.mqtt_state_topic, json_state) print(json_state) except: pass
class MQTTPublisher(yaml.YAMLObject, Publisher, metaclass=PublisherMeta): """ MQTT Publisher Publishing service that sends data to an MQTT broker. """ yaml_tag = u'!MQTTPublisher' # Constructor is not actually required for pyyaml object creation def __init__(self, host, username, password): self.host = host self.username = username self.password = password def activate(self): self.mqtt_client = MQTTClient() self.mqtt_client.username_pw_set(self.username, self.password) self.mqtt_client.connect(self.host) def publish(self, data: list): for d in data: self.mqtt_client.publish(d.name, payload=f'{d.value}')
class MqttClient(object): """Mqtt通讯封装""" def __init__(self, address): logging.info( "MqttClient.__init__() address=({address[0]}, {address[1]})". format(address=address)) self.client = Mqtt() self.address = address assert isinstance(address, tuple), "the address is invalid." def handleConnected(self): logging.info("MqttClient.handleConnected()") def publish(self, topic, payload=None, qos=0, retain=False): logging.info("MqttClient.publish() topic={}".format(topic)) self.client.publish(topic, payload, qos, retain) def subscribe(self, topic, qos=0): logging.info("MqttClient.subscribe() topic={}".format(topic)) self.client.subscribe(topic, qos) def handleMessage(self, topic, payload): logging.info("MqttClient.handleMessage() topic={}".format(topic)) def sendMessage(self, topic, payload=None, qos=0, retain=False): logging.info("MqttClient.sendMessage() topic={}".format(topic)) self.client.publish(topic, payload, qos, retain) def run(self): logging.info("MqttClient.run()") def on_connect(client, userdata, flags, rc): self.handleConnected() def on_message(client, userdata, msg): self.handleMessage(msg.topic, msg.payload) self.client.on_connect = on_connect self.client.on_message = on_message self.client.connect(self.address[0], self.address[1]) self.client.loop_forever()
class MqttClient(object): """Mqtt通讯封装""" def __init__(self, address): if not isinstance(address, tuple) or len(address) != 2: raise ValueError("Invalid address.") def on_connect(client, userdata, flags, rc): self.handleConnected() def on_message(client, userdata, msg): self.handleMessage(msg.topic, msg.payload) self.client = Mqtt() self.address = address self.client.on_connect = on_connect self.client.on_message = on_message def handleConnected(self): pass def handleMessage(self, topic, payload): pass def publish(self, topic, payload=None, qos=0, retain=False): self.client.publish(topic, payload, qos, retain) def subscribe(self, topic, qos=0): self.client.subscribe(topic, qos) def start(self): self.client.connect_async(self.address[0], self.address[1]) self.client.loop_start() def stop(self): self.client.loop_stop() def username_pw_set(self, username, password=None): self.client.username_pw_set(username, password) def will_set(self, topic, payload=None, qos=0, retain=False): self.client.will_set(topic, payload, qos, retain)
def register(self, mqtt_client: mclient.Client, name: str, measurement_unit: str, ava_topic=None, value_template=None, json_attributes=False, device=None, unique_id=None, icon=None, asDict=False): config = self.get_config_payload(name=name, measurement_unit=measurement_unit, ava_topic=ava_topic, value_template=value_template, json_attributes=json_attributes, device=device, unique_id=unique_id, icon=icon, asDict=asDict) mqtt_client.publish(self.config, config, 0, True)
def callback_servidor(mqttc, userdata, msg): ''' maneja la conexión inicial con el servidor hasta que recibe permiso, y las desconexiones inesperadas del servidor desconectando a todos los jugadores ''' if msg.payload == b"SERVER_FAIL": print("SERVER_FAIL: se ha caido el servidor. Por favor, introduzca 0.") mqttc.disconnect() conectado.value = 0 elif msg.payload == b"SERVER_READY": sleep(random() * 10) mqttc.publish(choques + "/servidor/" + userdata[0], payload="CONNECT_REQUEST") elif msg.payload == b"CONNECT_ACCEPT": print("SERVIDOR ACTIVO") mqttc.unsubscribe(choques + "/servidor/exception") mqttc.unsubscribe(choques + "/servidor/" + userdata[0]) mqttc.publish(choques + "/solicitudes", payload=userdata[0]) elif msg.payload == b"USER_EXC": print("Usuario no válido") print("Prueba otro usuario que no este en uso") mqttc.disconnect() nombre_usuario = input("¿nombre usuario? ") sleep(1) mqttc = Client(userdata=[nombre_usuario, 0, 0]) #,clean_session=True) mqttc.message_callback_add(choques + "/servidor/#", callback_servidor) mqttc.message_callback_add(choques + "/partidas/#", callback_partidas) mqttc.message_callback_add(choques + "/jugadores/" + nombre_usuario, callback_jugadores) mqttc.will_set(choques + "/jugadores/" + nombre_usuario, payload="DISCONNECT") mqttc.connect(broker) mqttc.subscribe(choques + "/jugadores/" + nombre_usuario) mqttc.subscribe(choques + "/servidor") mqttc.subscribe(choques + "/servidor/" + nombre_usuario) mqttc.subscribe(choques + "/servidor/exception") mqttc.publish(choques + "/servidor/" + nombre_usuario, payload="CONNECT_REQUEST") mqttc.loop_start()
def faker(ctx, mqtt=False, mqttsn=False, timer=0.3, shot=False): import time from src.faker.fake_data import data_generator if mqtt: from paho.mqtt.client import Client c = Client() c.connect('localhost', 1883, 60) gen = data_generator(lambda x: c.publish( 'ek', ";".join(map(lambda a: str(float(a)), x)))) elif mqttsn: from mqttsn.client import Client c = Client(host='localhost', port=1885) c.connect() gen = data_generator(lambda x: c.publish( 'ek', ";".join(map(lambda a: str(float(a)), x)))) while True: next(gen) time.sleep(timer) if shot: break
class JMSClient(object): """Class JMSClient """ _mh = None _client = None _host = None _port = None _user = None _passw = None _verbose = None _is_connected = None _messages = [] def __init__(self, verbose=False): """Class constructor Called when the object is initialized Args: verbose (bool): verbose mode """ try: self._mh = MasterHead.get_head() self._client = Client() self._client.on_message = self._on_message self._verbose = verbose if (self._verbose): self._client.on_log = self._on_log except MQTTException as ex: self._mh.demsg('htk_on_error', ex, self._mh.fromhere()) @property def client(self): """ MQTT client property getter """ return self._client @property def host(self): """ server host property getter """ return self._host @property def port(self): """ server port property getter """ return self._port @property def user(self): """ username property getter """ return self._user @property def passw(self): """ user password property getter """ return self._passw @property def verbose(self): """ verbose property getter """ return self._verbose @property def is_connected(self): """ is_connected property getter """ return self._is_connected def _on_log(self, client, obj, level, string): """ Callback for on_log event """ print(string) def _on_message(self, client, obj, msg): """ Callback for on_message event """ self._messages.append(msg.payload.decode()) def connect(self, host, port=1883, user=None, passw=None, timeout=10): """Method connects to server Args: host (str): hostname port (str): port user (str): username passw (str): password timeout (int): timeout Returns: bool: result Raises: event: jms_before_connect event: jms_after_connected """ try: msg = 'host:{0}, port:{1}, user:{2}, passw:{3}, timeout:{4}'.format( host, port, user, passw, timeout) self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_jms_connecting', msg), self._mh.fromhere()) ev = event.Event( 'jms_before_connect', host, port, user, passw, timeout) if (self._mh.fire_event(ev) > 0): host = ev.argv(0) port = ev.argv(1) user = ev.argv(2) passw = ev.argv(3) timeout = ev.argv(4) self._host = host self._port = port self._user = user self._passw = passw if (ev.will_run_default()): if (self._user != None): self._client.username_pw_set(self._user, self._passw) setdefaulttimeout(timeout) self._client.connect(self._host, self._port) self._is_connected = True self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_jms_connected'), self._mh.fromhere()) ev = event.Event('jms_after_connect') self._mh.fire_event(ev) return True except (MQTTException, error, ValueError) as ex: self._mh.demsg('htk_on_error', ex, self._mh.fromhere()) return False def disconnect(self): """Method disconnects from server Args: none Returns: bool: result """ try: self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_jms_disconnecting'), self._mh.fromhere()) if (not self._is_connected): self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_jms_not_connected'), self._mh.fromhere()) return False else: self._client.disconnect() self._is_connected = False self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_jms_disconnected'), self._mh.fromhere()) return True except (MQTTException, error, ValueError) as ex: self._mh.demsg('htk_on_error', ex, self._mh.fromhere()) return False def send(self, destination_name, message): """Method sends message Args: destination_name (str): topic name message (str): message Returns: bool: result Raises: event: jms_before_send event: jms_after_send """ try: msg = 'destination_name:{0}, message:{1}'.format( destination_name, message) self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_jms_sending_msg', msg), self._mh.fromhere()) if (not self._is_connected): self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_jms_not_connected'), self._mh.fromhere()) return False ev = event.Event('jms_before_send', destination_name, message) if (self._mh.fire_event(ev) > 0): destination_name = ev.argv(0) message = ev.argv(1) if (ev.will_run_default()): res, id = self._client.publish(destination_name, message) if (res != 0): self._mh.demsg('htk_on_error', self._mh._trn.msg( 'htk_jms_sending_error'), self._mh.fromhere()) self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_jms_msg_sent'), self._mh.fromhere()) ev = event.Event('jms_after_send') self._mh.fire_event(ev) return True except (MQTTException, error, ValueError) as ex: self._mh.demsg('htk_on_error', ex, self._mh.fromhere()) return False def receive(self, destination_name, cnt=1, timeout=10): """Method receives messages Args: destination_name (str): queue name cnt (int): count of messages timeout (int): timeout to receive message Returns: list: messages Raises: event: jms_before_receive event: jms_after_receive """ try: msg = 'destination_name:{0}, count:{1}'.format( destination_name, cnt) self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_jms_receiving_msg', msg), self._mh.fromhere()) if (not self._is_connected): self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_jms_not_connected'), self._mh.fromhere()) return None ev = event.Event('jms_before_receive', destination_name, cnt) if (self._mh.fire_event(ev) > 0): destination_name = ev.argv(0) cnt = ev.argv(1) if (ev.will_run_default()): res, id = self._client.subscribe(destination_name) if (res != 0): self._mh.demsg('htk_on_error', self._mh._trn.msg( 'htk_jms_sending_error'), self._mh.fromhere()) return None res = 0 cnt_before = 0 start = time() while (res == 0): res = self._client.loop() cnt_after = len(self._messages) if (cnt_after > cnt_before and cnt_after < cnt): cnt_before = cnt_after elif (cnt_after == cnt or time() > start + timeout): res = -1 messages = self._messages self._client.unsubscribe(destination_name) self._messages = [] self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_jms_msg_received', len(messages)), self._mh.fromhere()) ev = event.Event('jms_after_receive') self._mh.fire_event(ev) return messages except (MQTTException, error, ValueError) as ex: self._mh.demsg('htk_on_error', ex, self._mh.fromhere()) return None
class Messenger(object): """ MQTT client for Herald transport. """ def __init__(self, peer): """ Initialize client :param peer: The peer behind the MQTT client. :return: """ self.__peer = peer self.__mqtt = MqttClient() self.__mqtt.on_connect = self._on_connect self.__mqtt.on_disconnect = self._on_disconnect self.__mqtt.on_message = self._on_message self.__callback_handler = None self.__WILL_TOPIC = "/".join( (TOPIC_PREFIX, peer.app_id, RIP_TOPIC)) def __make_uid_topic(self, subtopic): """ Constructs a complete UID topic. :param subtopic: The UID :return: Fully qualified topic :rtype : str """ return "/".join( (TOPIC_PREFIX, self.__peer.app_id, UID_TOPIC, subtopic)) def __make_group_topic(self, subtopic): """ Constructs a complete group topic. :param subtopic: The group name :return: Fully qualified topic :rtype : str """ return "/".join( (TOPIC_PREFIX, self.__peer.app_id, GROUP_TOPIC, subtopic)) def __handle_will(self, message): if self.__callback_handler and self.__callback_handler.on_peer_down: self.__callback_handler.on_peer_down( message.payload.decode('utf-8')) else: _log.debug("Missing callback for on_peer_down.") def _on_connect(self, *args, **kwargs): """ Handles a connection-established event. :param args: unnamed arguments :param kwargs: named arguments :return: """ _log.info("Connection established.") _log.debug("Subscribing for topic %s.", self.__make_uid_topic(self.__peer.uid)) self.__mqtt.subscribe(self.__make_uid_topic(self.__peer.uid)) self.__mqtt.subscribe(self.__make_group_topic("all")) self.__mqtt.subscribe(self.__WILL_TOPIC) for group in self.__peer.groups: _log.debug("Subscribing for topic %s.", self.__make_group_topic(group)) self.__mqtt.subscribe(self.__make_group_topic(group)) if self.__callback_handler and self.__callback_handler.on_connected: self.__callback_handler.on_connected() else: _log.warning("Missing callback for on_connect.") def _on_disconnect(self, *args, **kwargs): """ Handles a connection-lost event. :param args: unnamed arguments :param kwargs: named arguments :return: """ _log.info("Connection lost.") if self.__callback_handler and self.__callback_handler.on_disconnected: self.__callback_handler.on_disconnected() def _on_message(self, client, data, message): """ Handles an incoming message. :param client: the client instance for this callback :param data: the private user data :param message: an instance of MQTTMessage :type message: paho.mqtt.client.MQTTMessage :return: """ _log.info("Message received.") if message.topic == self.__WILL_TOPIC: self.__handle_will(message) return if self.__callback_handler and self.__callback_handler.on_message: self.__callback_handler.on_message(message.payload.decode('utf-8')) else: _log.warning("Missing callback for on_message.") def fire(self, peer_uid, message): """ Sends a message to another peer. :param peer_uid: Peer UID :param message: Message content :return: """ self.__mqtt.publish( self.__make_uid_topic(peer_uid), message, 1 ) def fire_group(self, group, message): """ Sends a message to a group of peers. :param group: Group's name :param message: Message content :return: """ self.__mqtt.publish( self.__make_group_topic(group), message, 1 ) def set_callback_listener(self, listener): """ Sets callback listener. :param listener: the listener :return: """ self.__callback_handler = listener def login(self, username, password): """ Set credentials for an MQTT broker. :param username: Username :param password: Password :return: """ self.__mqtt.username_pw_set(username, password) def connect(self, host, port): """ Connects to an MQTT broker. :param host: broker's host name :param port: broker's port number :return: """ _log.info("Connecting to MQTT broker at %s:%s ...", host, port) self.__mqtt.will_set(self.__WILL_TOPIC, self.__peer.uid, 1) self.__mqtt.connect(host, port) self.__mqtt.loop_start() def disconnect(self): """ Diconnects from an MQTT broker. :return: """ _log.info("Disconnecting from MQTT broker...") self.__mqtt.publish(self.__WILL_TOPIC, self.__peer.uid, 1) self.__mqtt.loop_stop() self.__mqtt.disconnect()
class MQTTEventSink(EventSink): def __init__(self, broker, topic="iot-1/d/%012x/evt/%s/json", hostname=None, hostport=1883, username=None, password=None, keepalive=60): EventSink.__init__(self, broker) self._client = Paho() self._client.on_connect = \ lambda mosq, obj, rc: self._on_connect(mosq, obj, rc) self._client.on_disconnect = \ lambda mosq, obj, rc: self._on_disconnect(mosq, obj, rc) self._client.on_publish = \ lambda mosq, obj, mid: self._on_publish(mosq, obj, mid) self._topic_format = topic self._topic = self._topic_format % (0, "%s") self._hostname = hostname self._hostport = hostport self._username = username self._password = password self._keepalive = keepalive self._loopflag = False self._neta = None def _on_connect(self, mosq, obj, rc): self._topic = self._topic_format % (get_mac(), "%s") log.debug("MQTT publisher connected: " + str(rc)) def _on_disconnect(self, mosq, obj, rc): log.debug("MQTT publisher disconnected: " + str(rc)) def _on_publish(self, mosq, obj, mid): #log.debug("MQTT publisher published: " + str(mid)) pass def _try_connect(self): if self._username is not None and self._password is not None: self._client.username_pw_set(self._username, self._password) try: self._client.connect(self._hostname, self._hostport, self._keepalive) except socket.gaierror: return False self._client.loop_start() self._loopflag = True return True def on_start(self): return self._try_connect() def send(self, encoded_event): # Fill in the blank "%s" left in self._topic import json # extract the actual topic string event = json.loads(encoded_event) topic_event_type = event["d"]["event"] topic = self._topic % topic_event_type # Check to see if event is from neighbors # and need to be published to Mqtt server if "published" in event["d"]: if event["d"]["published"] == 1: return True else: del event["d"]["published"] # Publish message res, mid = self._client.publish(topic, encoded_event) if res == paho.mqtt.client.MQTT_ERR_SUCCESS: log.info("MQTT message published to " + topic) elif res == paho.mqtt.client.MQTT_ERR_NO_CONN: log.error("MQTT publisher failure: No connection") return False else: log.error("MQTT publisher failure: Unknown error") return False return True def check_available(self, event): if self._neta is not None and not self._neta: return False if not self._loopflag: if not self._try_connect(): log.error("MQTT publisher failure: Cannot connect") return False return True def on_event(self, event, topic): et = event.get_type() ed = event.get_raw_data() if et == "internet_access": self._neta = ed def encode_event(self, event): # return event.to_json() return json.dumps({"d": event.to_map()})
class MqttApplication(Application): """ An abstract base Application for running some type of MQTT client-based Application. """ def __init__(self, broker, hostname=None, hostport=1883, username=None, password=None, keepalive=60, **kwargs): super(MqttApplication, self).__init__(broker=broker, **kwargs) self._client = MqttClient() self._client.on_connect = \ lambda mqtt_client, obj, rc: self._on_connect(mqtt_client, obj, rc) self._client.on_disconnect = \ lambda mqtt_client, obj, rc: self._on_disconnect(mqtt_client, obj, rc) self._client.on_publish = \ lambda mqtt_client, obj, mid: self._on_publish(mqtt_client, obj, mid) self._client.on_subscribe = \ lambda mqtt_client, userdata, mid, qos: self._on_subscribe(mqtt_client, mid, qos) self._client.on_message = \ lambda mqtt_client, userdata, msg: self._on_message(mqtt_client, msg.payload, msg.topic, msg.qos, msg.retain) self._hostname = hostname self._hostport = hostport self._username = username self._password = password self._keepalive = keepalive self._is_connected = False @property def is_connected(self): return self._is_connected # Your API for pub-sub via MQTT: def mqtt_publish(self, raw_data, topic, **kwargs): """ Publishes the given data to the specified topic. :param raw_data: :type raw_data: str :param topic: :param kwargs: e.g. qos, retain; passed to self._client.publish :return: err_code, msg_id """ return self._client.publish(topic, raw_data, **kwargs) def mqtt_subscribe(self, topic, **kwargs): """ Subscribes to the specified topic. :param topic: :param kwargs: e.g. qos; passed to self._client.publish :return: err_code, msg_id """ return self._client.subscribe(topic, **kwargs) # To make use of either publish or subscribe, make sure to implement these! def _on_publish(self, mqtt_client, obj, mid): log.debug("MQTT app %s published msg %d: %s" % (self.name, mid, obj)) def _on_subscribe(self, mqtt_client, mid, qos): log.debug("MQTT app %s subscribe response msg %d: qos=%s" % (self.name, mid, qos)) def _on_message(self, mqtt_client, payload, topic, qos, retain): """Called when a message arrives on a topic we subscribed to.""" log.debug("MQTT app %s received message on topic %s: %s" % (self.name, topic, payload)) # You may want to override these functions in your concrete Application, but make sure to call super()! def _on_connect(self, mqtt_client, obj, rc): log.debug("MQTT app %s connected: %s" % (self.name, str(rc))) # need to start AFTER connecting, which is async! self._is_connected = True def _on_disconnect(self, mqtt_client, obj, rc): # sink will try reconnecting once EventReporter queries if it's available. self._is_connected = False log.debug("MQTT app %s disconnected: %s" % (self.name, str(rc))) def _try_connect(self): if self._username is not None and self._password is not None: self._client.username_pw_set(self._username, self._password) try: # NOTE: this is an async connection! self._client.connect(self._hostname, self._hostport, self._keepalive) self._client.loop_start() except socket.gaierror: return False return True def on_start(self): super(MqttApplication, self).on_start() return self._try_connect()
class PipaMQTTClient(object): def __init__(self, client_id, host, port=1883, **kwargs): self._logger = logging.getLogger("gsensors.PipaMQTTClient") self._host = host self._port = port self._mqtt_client = Client(client_id=client_id, clean_session=False) self._mqtt_client.on_connect = self.on_connect self._mqtt_client.on_disconnect = self.on_disconnect self._mqtt_client.on_message = self.on_message self.worker = None self.worker_runner = None self.topics_sources = {} self.running = False self.connected = False def publish(self, topic, payload=None, qos=0, retain=False): # check connected if not self.connected: raise RuntimeError("MQTT client not connected ! ") if not self.running: raise RuntimeError("MQTT client not running ! ") self._mqtt_client.publish(topic, payload=payload, qos=qos, retain=retain) def PublishAction(self, topic, payload=None, retain=False): if payload is None: def _action(source, value): data = "%s" % value self._logger.debug("publish %s: %s" % (topic, data)) self.publish(topic, payload=data, retain=retain) else: def _action(*args, **kwargs): self._logger.debug("publish %s: %s" % (topic, payload)) self.publish(topic, payload=payload, retain=retain) return _action def on_disconnect(self, client, userdata, rc): self._logger.error("Disconnected with result code: "+str(rc)) self.connected = False self.connect() def on_connect(self, client, userdata, flags, rc): if rc == 0: self._logger.info("Connected to MQTT broker") self.connected = True # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. #client.subscribe("$SYS/#") #client.subscribe("#") for topic in self.topics_sources.keys(): client.subscribe(topic) else: self._logger.error("Connection fail with error: %s" % rc) def on_message(self, client, userdata, msg): self._logger.debug("get a msg %s: %s" % (msg.topic, msg.payload)) if msg.topic in self.topics_sources: source = self.topics_sources[msg.topic] source.update(msg) def register_source(self, source, topic): # check that topic has no wildcard assert "#" not in topic if topic in self.topics_sources: raise ValueError("topic already monitored") self.topics_sources[topic] = source self._mqtt_client.subscribe(topic) return source def connect(self): self.worker_runner = gevent.spawn(self._connect) def _connect(self): while not self.connected: try: #self._mqtt_client.reinitialise() self._mqtt_client.connect(host=self._host, port=self._port, keepalive=60) except socket.error as err: self._logger.error("Imposible to connect to MQTT: %s" % err) self._logger.info("Will retry in 2 seconds") gevent.sleep(2) def wait_connected(self): while not self.connected: gevent.sleep(1) def start(self): if self.running: return self.running = True self.worker = gevent.spawn(self._mqtt_loop) self.connect() def _mqtt_loop(self): while self.running: self._mqtt_client.loop(timeout=0.02) gevent.sleep(0.01)