Exemplo n.º 1
0
def subscribe(client: mqttClient):
    def on_message(client, userdata, msg):
        """
        Code that gets performed when a new message is received in the Topic
        :param client:
        :param userdata:
        :param msg:
        :return:
        """
        # print('entered on_message()')
        # print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
        # print(msg.payload.decode())
        mqtt_dict = ast.literal_eval(msg.payload.decode())
        pprint(mqtt_dict)

        # ******** SPECIFIC CODE ********************************
        display_topic = get_env_app.get_display_topic()
        generate_weather_display_text.process_in_msg(client, display_topic,
                                                     mqtt_dict)
        # *******************************************************

    cumulus_topic = get_env_app.get_cumulus_topic()
    # print('cumulus_topic=' + cumulus_topic.__str__())
    client.subscribe(cumulus_topic)
    client.on_message = on_message
Exemplo n.º 2
0
 def subscribe(self, mqttClient: MQTTClient):
     for intent in self._supportedIntents:
         try:
             mqttClient.subscribe(str(intent))
         except:
             self._logger.error('Failed subscribing to intent "{}"'.format(
                 str(intent)))
Exemplo n.º 3
0
def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
        data = json.loads(msg.payload)

        if msg.topic == "commands/purifier":
            db.clean_air.update_one({"_id": 1},
                                    {"$set": {
                                        "active": data["active"]
                                    }},
                                    upsert=True)
            print("Device Updated")

        elif msg.topic == "commands/mobile_sensors":
            purifier = db.clean_air.find_one({"mobile_sensors.id": data["id"]})
            updated = purifier["mobile_sensors"]
            for e in updated:
                if e["id"] == data["id"]:
                    e["active"] = data["active"]

            purifier["mobile_sensors"] = updated

            mobile_sensor_data = db.clean_air.update_one(
                {"mobile_sensors.id": data["id"]}, {"$set": purifier})
            print("Device Updated")

    client.subscribe(topic)
    client.on_message = on_message
Exemplo n.º 4
0
def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        string = json.loads(msg.payload.decode())
        print(f"Received {string['current']} from {msg.topic} topic")

    client.subscribe(topic)
    client.on_message = on_message
Exemplo n.º 5
0
    def subscribe(self, client: mqtt_client):
        def on_message(client, userdata, msg):
            print(
                f"Received `{msg.payload.decode()}` from `{msg.topic}` topic -- {time.asctime(time.localtime(time.time()))}"
            )
            logging.info(
                f"Received `{msg.payload.decode()}` from `{msg.topic}` topic -- {time.asctime(time.localtime(time.time()))}"
            )
            try:
                if msg.topic == "/channel/BLANKET-sensor":
                    with open(self.dataset, 'a+') as f:
                        f.write("" +
                                datetime.now().timestamp().__int__().__str__())
                    with open('./health.csv', 'a+') as f:
                        f.write("," + msg.payload.decode())
                    with open(self.dataset, 'a+') as f:
                        f.write("\n")
            except Exception as excM:
                logging.info(
                    f"Exeption: {excM} -- {time.asctime(time.localtime(time.time()))}"
                )
                pidP = os.getpid()
                os.kill(pidP, 2)

        client.subscribe(self.topicBLANKET)
        client.on_message = on_message
Exemplo n.º 6
0
def subscribe(client: mqtt):
    def on_message(client, userdata, msg):
        #util_flusso.processing_message(msg.payload.decode())
        processing.processing_message(msg.payload.decode())

    client.subscribe(topic)
    client.on_message = on_message
Exemplo n.º 7
0
def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")

    client.subscribe(topic_3)
    client.subscribe(topic_4)
    client.on_message = on_message
Exemplo n.º 8
0
    def subscribe_file(self, client: mqtt_client, filename):
        def on_message(client, userdata, msg):
            # Added this because subscriber kept overwriting files with "self.msg" parameters
            audio_rec = re.search('audio', msg.topic)
            text_rec = re.search('text', msg.topic)
            sender = msg.topic.split('/')[-1]
            self.audio_file = './RecAudio/' + sender + '_' + filename + '.wav'
            self.text_file = './RecTxt/' +sender + '_' + filename + '.txt'
            if audio_rec:
                if not path.exists(self.audio_file):
                    print("received audio msg")
                    f = open(self.audio_file, 'wb')
                    f.write(msg.payload)
                    f.close()
            elif text_rec:
                if not path.exists('./RecTxt/' + sender + '*'):
                    print("Write")
                    f = open(self.text_file, 'wb')
                    print(msg.payload)
                    f.write(msg.payload)
                    f.close()
            else:
                self.message = msg.payload.decode()
                print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")

        client.subscribe(self.topic_list)
        client.on_message = on_message
Exemplo n.º 9
0
def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        weatherObject = json.loads(msg.payload.decode())
        temp = []
        # convert to celsius
        converted_temp = weatherObject['temp'] - 273.15
        temp.append(converted_temp)
        dataset.append(temp)
        print(temp)

        # datetime object containing current date and time
        actual_time = datetime.now()
        json_body = [{
            "measurement":
            "temperature",
            "tags": {
                "type": "measured"
            },
            "time":
            datetime.now(
                timezone('Europe/Rome')).strftime('%Y-%m-%dT%H:%M:%SZ'),
            "fields": {
                "temperature": float(converted_temp),
                "city": city
            }
        }]
        print("Write points: {0}".format(json_body))
        client_influx.write_points(json_body)

    client.subscribe(topic)
    client.on_message = on_message
Exemplo n.º 10
0
def subscribe(client: mqtt_client, devEui, collection):
    def on_message(client, userdata, msg):
        print(f"From topic `{msg.topic}` received `{msg.payload.decode()}`")
        publish(client, "lora/uplink/" + devEui + "/res", {"result": "ok"})
        payload = json.loads(msg.payload.decode())
        #controllare dove sta il payload
        #bytes_object = bytes.fromhex(payload['payload'])
        #ascii_string = bytes_object.decode("ASCII")
        #payload['payload'] = ascii_string

        base64_bytes = payload['payload'].encode('ascii')
        message_bytes = base64.b64decode(base64_bytes).hex()
        #message = message_bytes.decode('ascii')
        #message = hex2number(message_bytes)
        payload['parsed_payload'] = message_bytes
        print(payload)

        if isinstance(payload, list):
            collection.insert_many(payload)
        else:
            collection.insert_one(payload)
        """
        if payload["counter_up"] % 2 == 0:
            cursor = collection.find({})
            for document in cursor:
                print(document)
        """

    client.subscribe("lora/uplink/" + devEui + "/req")
    client.on_message = on_message
Exemplo n.º 11
0
    def subscribe_msg(self, client: mqtt_client):
        def on_message(client, userdata, msg):
            self.message = msg.payload.decode()
            print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")

        client.subscribe(self.topic_list)
        client.on_message = on_message
Exemplo n.º 12
0
def subscribe(client: paho):
    def on_message(client, userdata, msg):
        print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
        test(msg.payload.decode())

    client.subscribe(topic)
    client.on_message = on_message
Exemplo n.º 13
0
    def subscribe(self, client: mqtt_client):
        def on_message(client, userdata, msg):
            print(
                f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
            self.Mensaje = msg.payload.decode()

        client.subscribe(topic)
        client.on_message = on_message
Exemplo n.º 14
0
    def _cb_on_connect(self, client: mqtt, userdata: Any,
                       flags: Dict[str, Any], rc: int) -> None:
        """Receive a CONNACK message from the server."""
        client.subscribe([
            (self.HILDEBRAND_MQTT_TOPIC.format(hardwareId=self.hardwareId), 0)
        ])

        self.broker_active = True
Exemplo n.º 15
0
def subscribe(client: mqtt_client):
    # The default message callback.
    # (you can create separate callbacks per subscribed topic)
    def on_message(client, userdata, msg):
        print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")

    client.subscribe(topic)
    client.on_message = on_message
Exemplo n.º 16
0
def subscribe(client: mqtt_client, topic):
    def on_message(client, userdata, msg):
        global user_id
        print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
        user_id = str(msg.payload.decode())

    client.subscribe(topic)
    client.on_message = on_message
Exemplo n.º 17
0
    def _subscribe(self, client: mqtt_client):
        def on_message(client, userdata, msg):
            print(
                f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
            self.signal.emit(msg.topic, msg.payload.decode())

        client.subscribe(topic)
        client.on_message = on_message
Exemplo n.º 18
0
def subscribe_mqtt(client: mqtt_client):
    def on_message(client, userdata, msg):
        global ble_keys
        ble_keys = json.loads(msg.payload)
        #print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")

    client.subscribe(mqtt_topic)
    client.on_message = on_message
Exemplo n.º 19
0
def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        msg_str = msg.payload.decode("utf-8","ignore")
        msg_obj = json.loads(msg_str)
        print("Object type: ", type(msg_obj))
        print(f"Received `{msg_str}` from `{msg.topic}` topic")

    client.subscribe(topic)
    client.on_message = on_message
Exemplo n.º 20
0
def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        print("MQTT Data Received...")
        print("MQTT Topic: " + msg.topic)
        print("Data: " + str(msg.payload))
        sensor_Data_Handler(msg.topic, msg.payload)

    client.subscribe(topic)
    client.on_message = on_message
Exemplo n.º 21
0
def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        message = json.loads(msg.payload.decode())
        topic = msg.topic
        print(f"Message received in topic: {topic}")
        print(message)

    test_topic = "test"
    client.subscribe(test_topic)
    client.on_message = on_message
Exemplo n.º 22
0
def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        print(f"Received '{msg.payload.decode()}' from {msg.topic}")
        time.sleep(2)
        publish_pong(client, msg.payload)
        # time.sleep(2)

    client.subscribe(topic_ping)
    client.subscribe(topic_outgoing)
    client.on_message = on_message
Exemplo n.º 23
0
def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")

        handle = open("output.txt", "w")
        handle.write(f"`{msg.payload.decode()}`")
        handle.close()

    client.subscribe(topic)
    client.on_message = on_message
def subscribe(client: mqtt):
    def onMessage(client, userdata, msg):
        if (topic1 == msg.topic):
            latestSensorData1.append(int(msg.payload.decode()))
        elif (topic2 == msg.topic):
            latestSensorData2.append(int(msg.payload.decode()))
        print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")

    client.subscribe(topic1)
    client.subscribe(topic2)
    client.on_message = onMessage
Exemplo n.º 25
0
def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        print(f"Recebido `{msg.payload.decode()}` de `{msg.topic}` topic")
        msg_flag = msg.payload.decode()
        print(msg_flag)

    global msg_flag
    client.subscribe(topic)
    client.on_message = on_message
    if msg_flag == '-1':
        client.disconect()
Exemplo n.º 26
0
def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
        data = json.loads(msg.payload)
        data["datetime"] = datetime.datetime.now()
        db.clean_air.update_one({"_id": 1}, {"$set": data}, upsert=True)
        print("Payload saved in the database")
        send_notification(data)

    client.subscribe(topic)
    client.on_message = on_message
Exemplo n.º 27
0
def subscribeApp(client: mqtt_client):
    def on_message(client, userdata, msg):
        print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
        if msg.topic == subscribeTopicApp:
            print(f"Received subscribetopic")
            comand = msg.payload.decode().split(",")
            floors = [0] * 5
            counter = 0
            if comand[0] == "disponibles_pisos":
                for floor in estructura:
                    print(f"{floor}")
                    for key in floor:
                        print(f"{key} {floor[key]}")
                        if floor[key] == 0:
                            floors[counter] += 1
                    counter += 1
                publishPisos(client, floors)
            elif comand[0] == "disponible_piso":
                if comand[1].isnumeric():
                    piso = int(comand[1]) - 1
                    msg = str(comand[1]) + "|"
                    msgcounter = 0
                    msgcubil = ""
                    for key in estructura[piso]:
                        if estructura[piso][key] == 0:
                            msgcubil += key + "|"
                            msgcounter += 1
                    msg += str(msgcounter) + "|"
                    msg += msgcubil
                    msg = msg[:-1]
                    publishPiso(client, msg)
            elif comand[0] == "ocupar":
                nd = {comand[3]: [comand[1], comand[2]]}
                estructura2.update(nd)
                print(estructura2)
            elif comand[0] == "buscar":
                keys = estructura2.keys()
                if comand[1] in keys:
                    publishBuscarParqueo(client, estructura2.get(comand[1]))
                else:
                    publishBuscarParqueo(client, 0)
        elif msg.topic == "2587/parqueo/cubil":
            (piso, cubil, ocupado) = str(msg.payload.decode()).split(",")
            estructura[int(piso) - 1][str(cubil)] = int(ocupado)
            # print(estructura[int(piso)-1][str(cubil)])
        elif msg.topic == "2587/parqueo/cubil/estado/info":
            allParkingSpaces = str(msg.payload.decode()).split("|")
            if len(allParkingSpaces) > 1:
                for i in allParkingSpaces:
                    if str(i) != "":
                        (piso, cubil, ocupado) = str(i).split(",")
                        estructura[int(piso) - 1][str(cubil)] = int(ocupado)
            # print(estructura)

    client.subscribe(subscribeTopicApp)
    client.subscribe(subscribeTopicEstadoCubil)
    client.subscribe(subscribeCubil)
    client.subscribe(subscribeCubilEstadoInfo)
    client.on_message = on_message
Exemplo n.º 28
0
def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        Mensaje=str(msg.payload.decode("utf-8"))
        print(Mensaje)
        if Mensaje!="":
            run_ai(Mensaje)
            Mensaje=""
            client.disconnect()
    client.subscribe(topic)
    client.on_message = on_message
    client.loop_forever()
Exemplo n.º 29
0
def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
        musicjsonsub = json.loads(msg.payload.decode())
        musicfilesub = open("musicInput.txt", "w")
        musicfilesub.write(musicjsonsub['songName'])
        musicfilesub.write('\n')
        musicfilesub.write(musicjsonsub['artistName'])
        musicfilesub.close()

    client.subscribe(topic)
    client.on_message = on_message
Exemplo n.º 30
0
def on_connect(client: mqttc, userdata: Any, flags: Any, rc: int) -> None:
    """
    Коллбэк подключения к брокеру
    :param client:
    :param userdata:
    :param flags:
    :param rc:
    """
    if rc == 0:
        print("Connected OK")
        client.subscribe(userdata["mqtt_topic"])
    else:
        print("Bad connection, RC = ", rc)