Example #1
0
class MqttBridge(BaseBridge):
    def __init__(self):
        super(MqttBridge, self).__init__()
        self.client = MqttClient()
        self.client.on_message = self.onMqttMessage
        self.client.on_connect = self.onConnect

    def publishApiMessage(self, heat_pump_id, base_topic, topic, value):
        self.client.publish(base_topic + topic, value)

    # noinspection PyUnusedLocal
    def onConnect(self, client, userdata, flags, rc):
        # type: (MqttBridge, MqttClient, object, dict, object) -> None
        topics = []
        for topic in self.binding.topics:
            topics.append((topic, 0))
        if len(topics) == 0:
            return
        print "mqtt subscribing to topics: ", topics
        client.subscribe(topics)

    # noinspection PyUnusedLocal
    def onMqttMessage(self, client, userdata, msg):
        # type: (MqttBridge, MqttClient, object, MQTTMessage) -> None
        topic = str(msg.topic)
        self.binding.onApiMessage(topic, msg.payload)

    def start(self):
        print "mqtt connect to:", config.MQTT['host']
        self.client.connect(config.MQTT['host'])
        self.client.loop_start()

    def stop(self):
        self.client.disconnect()
        self.client.loop_stop()
Example #2
0
def main():

    client = Client(protocol=MQTTv311)
    client.username_pw_set(USERNAME, password=PASSWORD)

    host1 = "98:07:2D:40:95:83"
    host2 = "98:07:2D:35:7B:00"

    print("Connecting to SensorTags")
    tag1 = SensorTag(host1)
    #tag2 = SensorTag(host2)

    sensor_enabler(tag1)
    #sensor_enabler(tag2)

    sleep(1.0)

    try:
        while True:
            data1 = read_sensor_data(tag1)
            #data2 = read_sensor_data(tag2)
            sleep(1.0)
            pprint({"SensorTag1": data1})
            #pprint({"SensorTag2": data2})
            client.connect(HOST, port=PORT, keepalive=60)
            client.publish(TOPIC1, payload=dumps(data1))
            #client.publish(TOPIC2, payload=dumps(data2))
            client.disconnect()
            sleep(30)
    except KeyboardInterrupt:
        print("Disconnected to SensorTags")
        tag1.disconnect()
Example #3
0
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.")
Example #4
0
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()
Example #5
0
class MQTTValuePub(object):
    '''
    Use MQTT to send values on network
    pip install paho-mqtt
    '''
    def __init__(self, name, broker="iot.eclipse.org"):
        from paho.mqtt.client import Client

        self.name = name
        self.message = None
        self.client = Client()
        print("connecting to broker", broker)
        self.client.connect(broker)
        self.client.loop_start()
        print("connected.")

    def run(self, values):
        packet = {"name": self.name, "val": values}
        p = pickle.dumps(packet)
        z = zlib.compress(p)
        self.client.publish(self.name, z)

    def shutdown(self):
        self.client.disconnect()
        self.client.loop_stop()
Example #6
0
class MQTTClient(object):
    """Manages Paho MQTT client lifecycle and callbacks"""

    def __init__(self, config: dict, message_processor=None):
        self.config = config

        self.client = Client(
            client_id=config.mqtt_client,
            clean_session=config.mqtt_clean_session,
            userdata={"client": config.mqtt_client},
        )

        self.client.username_pw_set(config.mqtt_username, config.mqtt_password)

        if self.config.mqtt_debug:
            self.client.on_log = self._on_log

        self.client.on_connect = self._on_connect
        self.client.on_subscribe = self._on_subscribe
        self.client.on_message = self._on_message
        self.client.on_publish = self._on_publish
        self.client.on_disconnect = self._on_disconnect

        self.client.connect(config.mqtt_host, config.mqtt_port, 60)

        if message_processor:
            self.message_processor = message_processor

    def _on_log(self, client, userdata, level, buf):
        click.echo(f"{buf}, origin: {userdata['client']}")

    def _on_connect(self, client, userdata, flags, rc):
        click.echo(f"Connected {userdata['client']}, result code: {str(rc)} {str(flags)}")
        click.echo(f"Subscribing to all topics...")
        self.client.subscribe(self.config.mqtt_topics)

    def _on_subscribe(self, client, userdata, mid, granted_qos):
        click.echo(f"Subscribed {userdata['client']}, mid: {mid}, granted qos: {granted_qos}")
        click.echo(f"Listening for {userdata['client']} messages...")

    def _on_disconnect(self, client, userdata, rc):
        click.echo(f"Disconnected {userdata['client']}, result code: {str(rc)}")

    def _on_message(self, client, userdata, msg):
        if hasattr(self, "message_processor"):
            self.message_processor(client, userdata, msg)
        else:
            click.echo(f"Topic: {msg.topic}, Mid: {msg.mid}, Payload: {msg.payload.decode('utf-8')}")

    def _on_publish(self, client, userdata, mid):
        click.echo(f"Published by {userdata['client']}, mid: {mid}")

    def listen(self):
        try:
            self.client.loop_forever()
        except KeyboardInterrupt:
            click.echo(f"Received KeyboardInterrupt, disconnecting {self.config.mqtt_client}")
            self.client.disconnect()
Example #7
0
def on_connect(client: mqtt_client.Client, userdata, flags, rc):
    if rc == 0:
        client.subscribe("+/devices/+/up", qos=2)
    elif rc == 3:
        # Server isn't available, retry later
        print("Server isn't available")
    else:
        # Error in config
        print("Error in config")
        client.disconnect()
Example #8
0
def test_traffic_mqtt():
    client = Client(client_id="test")
    client.on_connect = on_connect
    client.username_pw_set(username="******", password="******")
    client.connect(host="52.164.202.250", port=1883)
    client.loop_start()
    t.sleep(5)

    t.sleep(2)
    client.disconnect()
    t.sleep(2)
Example #9
0
def send_to_mqtt(packet, db = "testcargo"):
    packet['database'] = db
    client = Client(client_id="test")
    client.on_connect = on_connect
    client.username_pw_set(username="******", password="******")
    client.connect(host="52.164.202.250", port=1883)
    client.loop_start()
    t.sleep(5)
    transmit(client)
    t.sleep(2)
    client.disconnect()
    t.sleep(2)
Example #10
0
 def on_connect(self, client: Client, userdata, flags, rc, properties=None):
     """ mqtt连接回调函数 """
     status = ['连接成功', '协议版本错误', '客户端标识符无效', '服务器不可用', '用户名或密码错误', '未授权']
     if rc != 0:
         self.publishStateChangedSignal.emit(status[rc])
         return
     # 发布信息并发送消息给主界面
     self.publishStateChangedSignal.emit('🙉 代理服务器连接成功!')
     client.publish(self.topic, self.message, 1)
     self.publishStateChangedSignal.emit('🙊 假数据包发送成功!')
     client.disconnect()
     self.publishStateChangedSignal.emit(f'🙊 已与代理服务器 {self.broker} 断开连接')
Example #11
0
class Mqtt(object):
    def __init__(self, host):
        self.host = host
        self.client = Client()

    def send(self, topic, payload):
        try:
            self.client.connect(self.host)
            self.client.publish(topic, payload)
            self.client.disconnect()
        except:
            print("MQTT connection error with {}".format(self.host))
Example #12
0
 def _test_mqtt_connection(self):
     print("testing mqtt connection", flush=True)
     mqtt = Client()
     while True:
         try:
             mqtt.connect(mqtthost)
             break
         except:
             print("Waiting for mqtt...", flush=True)
             time.sleep(5)
     print("mqtt connected", flush=True)
     mqtt.disconnect()
Example #13
0
class MqttClientConnector():

    _host = None
    _port = None
    _brokerAddr = None
    _mqttClient = None

    #Allow user to use this constructor to pass custom callBack methods
    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:

            print("Connecting to broker:" + self._brokerAddr + ".....")
            self._mqttClient.connect(self._host, self._port, 60)
            self._mqttClient.loop_start()

        except Exception as e:

            print("Cloud not connect to broker " + self._brokerAddr + " " +
                  str(e))

    def disconnect(self):

        self._mqttClient.disconnect()
        self._mqttClient.loop_stop()

    def publishMessage(self, topic, message, qos):

        print("Publishing message:" + message + " to broker: " +
              self._brokerAddr + " Topic:" + topic)
        self._mqttClient.publish(topic, message, qos)

    def subscribeTopic(self, topic, qos):

        print("Subscribing to topic:" + topic + ".....")
        self._mqttClient.subscribe(topic, qos)
Example #14
0
def main():
    parser = argparse.ArgumentParser(
        description='Command line utility for quick MQTT publishes')
    parser.add_argument('--broker-port', type=int, default=1883)
    parser.add_argument('broker_address')
    parser.add_argument('topic')
    parser.add_argument('message', default='')
    args = parser.parse_args()

    client = Client()
    client.on_publish = print_publish_info
    client.connect(args.broker_address, args.broker_port)
    client.publish(args.topic, args.message)
    client.disconnect()
Example #15
0
class MoodyBLEWrapper(Thread):
    def __init__(self, mac, host, ca_cert):
        Thread.__init__(self)
        self._mac = mac
        self._host = host
        self._ca_cert = ca_cert
        self._running = False

        self._mutex = Lock()
        self._client = Client(f"Moody{randint(100, 999)}")
        self._client.tls_set(ca_certs=ca_cert)

        # When receiving data with a delegate, you also receive a characteristic handle
        # This is a mapping of those characteristic for later usage
        self._handle_mappings = {}

    def run(self):
        self._running = True
        self._connect(host=self._host)
        with Peripheral(self._mac) as peripheral:
            for service in list(peripheral.getServices())[2:]:
                print(service, service.uuid.getCommonName())
                char_uuids = [str(c.uuid) for c in service.getCharacteristics()]
                name_char = service.getCharacteristics(char_uuids[0])[0]
                value_char = service.getCharacteristics(char_uuids[1])[0]

                service_name = name_char.read().decode()
                self._handle_mappings[value_char.valHandle] = service_name
                mqtt_delegate = _MQTTDelegate(client=self._client, client_mutex=self._mutex,
                                              handle_map=self._handle_mappings)

                peripheral.withDelegate(mqtt_delegate)
                peripheral.writeCharacteristic(value_char.valHandle + 1, b"\x01\x00")

            while self._running:
                peripheral.waitForNotifications(1)

            peripheral.disconnect()

    def _connect(self, host, port=None):
        if not port:
            port = 8883
        self._client.connect(host=host, port=port)
        self._client.loop_start()

    def stop(self):
        self._running = False
        self._client.loop_stop()
        self._client.disconnect()
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()
Example #18
0
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)
Example #19
0
def mqtt_handler():
    global mqtt_client
    Client.connected_flag = False
    mqtt_client = Client()
    mqtt_client.on_connect = on_connect
    mqtt_client.on_message = on_message
    mqtt_client.loop_start()
    mqtt_client.connect(host=MQTT_ADDR, port=MQTT_PRT)
    while not mqtt_client.connected_flag:  # wait in loop
        print("In wait loop")
        time.sleep(1)

    # subscribe all rooms, using MQTT single layer wildcard
    mqtt_client.subscribe(topic='%s/+' % ORDER_STATUS)
    mqtt_client.loop_forever()
    mqtt_client.disconnect()
Example #20
0
    def on_connect(_client: mqtt.Client, _userdata: dict, _flags: dict,
                   rc: int) -> None:
        """
        Callback function when a MQTT client connects to the server

        Check if the connection is succeeded.
        Stop the loop regardless of whether the connection is succeeded or not.
        The rc argument is a connection result.
        """
        _client.disconnect()
        _client.loop_stop()
        if rc != mqtt.MQTT_ERR_SUCCESS:
            demisto.info(mqtt.connack_string(rc))
            raise paho.mqtt.MQTTException(mqtt.connack_string(rc))
        else:
            demisto.info("connection was succeeded for test")
Example #21
0
class MqttPlugin(plugins.SimplePlugin):
    """
    Plugin that listens to MQTT topics and publishes the payload
    'unmodified' to a channel on the CherryPy bus. The cherrypy channel name
    is the same as the MQTT topic

    Requires PAHO
    """

    def __init__(
        self, bus: wspbus, broker: str, port: int, topic_list: Union[str, List[str]]
    ) -> None:
        """
        Setup the plugin

        :param bus: Cherrypy internal Bus
        :param broker: Mqtt broker
        :param port: Port of the Mqtt broker
        :param topic_list: topic to subscribe
        """

        # Cherrypy plugins.SimplePlugin doesn't accept the super().__init__()
        # Inside cherrypy's docs it's like this
        # https://docs.cherrypy.org/en/latest/extend.html#create-a-plugin
        plugins.SimplePlugin.__init__(self, bus)

        self.broker = broker
        self.port = port
        self.topic_list = topic_list
        self.client = Client(client_id=f"Catalog{randrange(1, 100000)}")
        self.client.on_message = Bus(bus).my_on_message

    def start(self):
        self.bus.log("Setup mqttcherrypy")
        self.client.connect(self.broker, self.port)
        self.bus.log(f"Connected to broker: {self.broker} port: {self.port})")
        self.client.loop_start()
        self.client.subscribe(self.topic_list)
        self.bus.log(f"Subscribed to {self.topic_list}")

    def stop(self):
        self.bus.log("Shut down mqttcherrypy")
        self.client.unsubscribe(self.topic_list)
        self.bus.log(f"Unsubscribed from {self.topic_list}")
        self.client.loop_stop(force=True)
        self.client.disconnect()
        self.bus.log(f"Disconnected from: {self.broker} port: {self.port}")
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)
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 __init__(self, client: mqtt.Client, password: str):
        self.client = client
        self.client.username_pw_set("management/devicebootstrap", password)
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.loop_start()

        self.client.tls_set()
        self.client.connect("ubirch.cumulocity.com", 8883)

        self.connected = False
        while not self.connected:
            time.sleep(10)

        self.authorized = False
        while not self.authorized:
            self.client.publish("s/ucr")
            time.sleep(10)

        client.disconnect()
        client.loop_stop()
Example #25
0
class MqttClient:
    def __init__(self, name):

        self.client = None
        self.name = name
        self.connected = False
        self.client = Client(client_id=self.name)
        self.client.on_connect = self.on_connect
        self.client.connect(host='localhost', port=1883, keepalive=60)

        print("New MQTT client: " + str(self.name))
        self.client.loop_start()

    def on_connect(self, client, userdata, flags, rc):
        self.connected = True
        print("MQTT Client(" + str(self.name) + ") Connected")

    def stop(self):
        self.client.loop_stop()
        self.client.disconnect()
        print("MQTT Client Stoped")
Example #26
0
def mqtt_handler():
    global mqtt_client
    Client.connected_flag = False
    mqtt_client = Client()

    # set mosquitto broker password and username
    mqtt_client.username_pw_set(username=USERNAME, password=PASSWORD)
    # set TLS cert for the client
    mqtt_client.tls_set(ca_certs=TLS_CERT)
    mqtt_client.tls_insecure_set(True)

    mqtt_client.on_connect = on_connect
    mqtt_client.on_message = on_message
    mqtt_client.loop_start()
    mqtt_client.connect(host=MQTT_ADDR, port=MQTT_PRT)
    while not mqtt_client.connected_flag:  # wait in loop
        print("In wait loop")
        time.sleep(1)
    mqtt_client.subscribe(topic='%s/+' % ORDER_STATUS)
    mqtt_client.loop_forever()
    mqtt_client.disconnect()
Example #27
0
class MQTTValueSub(object):
    '''
    Use MQTT to recv values on network
    pip install paho-mqtt
    '''
    def __init__(self, name, broker="iot.eclipse.org", def_value=None):
        from paho.mqtt.client import Client

        self.name = name
        self.data = None
        self.client = Client(clean_session=True)
        self.client.on_message = self.on_message
        print("(clean_session) connecting to broker", broker)
        self.client.connect(broker)
        self.client.loop_start()
        self.client.subscribe(self.name)
        self.def_value = def_value
        print("connected.")

    def on_message(self, client, userdata, message):
        self.data = message.payload

    def run(self):
        if self.data is None:
            return self.def_value

        p = zlib.decompress(self.data)
        obj = pickle.loads(p)

        if self.name == obj['name']:
            self.last = obj['val']
            #print("steering, throttle", obj['val'])
            return obj['val']

        return self.def_value

    def shutdown(self):
        self.client.disconnect()
        self.client.loop_stop()
Example #28
0
class MosQuiTTo(IotProvider):
    """
    Child class containing implementations of IotProvider specific to MosQuiTTo.
    """
    def __init__(self, iot_provider_cfg):
        # 1. Set tls_version to correspond to mosquitto broker.
        # 2. Call parent class' __init__
        self.tls_version = eval(
            f"ssl.PROTOCOL_TLSv1_{iot_provider_cfg['tls_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 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.mosquitto_comm = Client()
        self.mosquitto_comm.on_connect = self.on_connect
        self.mosquitto_comm.on_message = self.onmsg
        self.mosquitto_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.mosquitto_comm.connect(self.iot_broker, self.iot_port)
        self.mosquitto_comm.loop_start()

    def disconnect(self):
        self.mosquitto_comm.disconnect()

    def publish(self, publish_topic, msg_str, qos):
        self.mosquitto_comm.publish(publish_topic, msg_str, qos=qos)
class Publisher:
    def __init__(self, server_address, location):
        self.client = Client()
        self.location = location
        self.address = server_address

    def publish(self, humidity, temperature):
        payload_humidity = self.__build_payload("humidity", humidity)
        payload_temperature = self.__build_payload("temperature", temperature)

        try:
            logging.debug("Connectint to MQTT...")
            self.client.connect(self.address)
            self.client.publish(TOPIC, payload_temperature)
            self.client.publish(TOPIC, payload_humidity)
            logging.info("Published values on " + TOPIC)
            self.client.disconnect()
        except Exception as ex:
            logging.error(ex)

    def __build_payload(self, prop, value):
        return '{{"timestamp":"{}", "place": "{}", "property":"{}", "value":{:.4f}}}'.format(
            datetime.now(), self.location, prop, value)
Example #30
0
class MQTTClient:
    def __init__(self):
        h = Hosts()
        t = NetTools()
        self.client = Client(t.get_ip())
        self.client.on_connect = self._on_connect
        self.client.on_message = self._on_message
        self.client.connect(host=h.get_ip_from_host(HOME_SERVER_HOSTNAME),
                            port=1883,
                            keepalive=60)
        self.connected = True
        self.subscribe = self.client.subscribe
        self.publish = self.client.publish

    @staticmethod
    def _on_connect(client: Client, userdata: Any, flags: Any, rc: int):
        """Set up a callback function to ensure the connection to Server was successful"""
        logger.info(f'Connected with result code {rc}.')

        # Subscribing in on_connect means that if we lose connection and reconnect
        # then subscriptions will be renewed
        client.subscribe('$SYS/#')

    @staticmethod
    def _on_message(client: Client, userdata: Any, msg: MQTTMessage):
        """Callback for when PUBLISH message is received from the server"""
        logger.debug(f'{msg.topic} {msg.payload}')

    def disconnect(self):
        """Disconnect from the broker"""
        self.client.disconnect()
        self.connected = False

    def __del__(self):
        """In case class is cleaned up before disconnecting"""
        if self.connected:
            self.disconnect()
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
Example #32
0
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()