def test_snips_component_mqtt_pubsub(mqtt_server): """Test whether a :class:`MQTTSnipsComponent` object executes the right callback after a topic it's subscribed to gets published on the MQTT bus and publishes the right payload. """ def publish_audio(): publish.single('hermes/audioServer/default/playBytes/1234', 'foobar') def publish_hotword(): publish.single('hermes/hotword/hey_snips/detected', '{"siteId": "default"}') # Test handle_hotword method: JSON payload threading.Thread(target=DecoratedMQTTComponentPubSub, daemon=True).start() threading.Timer(DELAY, publish_hotword).start() message = subscribe.simple('hermes-test/tts/say') assert json.loads(message.payload.decode('utf-8')) == { 'siteId': 'default', 'text': 'I detected the hotword hey_snips on site ID default.' } # Test handle_audio method: 'Binary' payload (just a string here) threading.Timer(DELAY, publish_audio).start() message = subscribe.simple('hermes-test/tts/say') assert json.loads(message.payload.decode('utf-8')) == { 'siteId': 'default', 'text': 'I detected audio with request ID 1234 and payload foobar on site ID default.' }
def easy_subscribe(self, topics, qos=0, msg_count=1, retained=False, hostname="localhost", port=1883, keepalive=60, will=None, auth=None, tls=None): """ Subscribe to a set of topics and return the messages received. This is a blocking function. arguments: topics the only required argument is the topic string to which the client will subscribe. This can either be a string or a list of strings if multiple topics should be subscribed to. qos the qos to use when subscribing, defaults to 0. msg_count the number of messages to retrieve from the broker. Defaults to 1. If 1, a single MQTTMessage object will be returned. If >1, a list of MQTTMessages will be returned. retained set to True to consider retained messages, set to False to ignore messages with the retained flag set. hostname a string containing the address of the broker to connect to. Defaults to localhost. port the port to connect to the broker on. Defaults to 1883. keepalive the keepalive timeout value for the client. Defaults to 60 seconds. will a dict containing will parameters for the client: will = {'topic': "<topic>", 'payload':"<payload">, 'qos':<qos>, 'retain':<retain>}. Topic is required, all other parameters are optional and will default to None, 0 and False respectively. Defaults to None, which indicates no will should be used. auth a dict containing authentication parameters for the client: auth = {'username':"******", 'password':"******"} Username is required, password is optional and will default to None if not provided. Defaults to None, which indicates no authentication is to be used. tls a dict containing TLS configuration parameters for the client: dict = {'ca_certs':"<ca_certs>", 'certfile':"<certfile>", 'keyfile':"<keyfile>", 'tls_version':"<tls_version>", 'ciphers':"<ciphers">} ca_certs is required, all other parameters are optional and will default to None if not provided, which results in the client using the default behaviour - see the paho.mqtt.client documentation. Defaults to None, which indicates that TLS should not be used. """ import paho.mqtt.subscribe as subscribe subscribe.simple(topics, qos, msg_count, retained, hostname, port, self.client_id, keepalive, will, auth, tls, self.protocol)
def round_go(): #msg = subscribe.simple(button_listen, hostname=server_ip, msg_count=12) #wait for coordinator to tell me button pressed print("button pressed, prompting webcam to take a picture") #TAKE A PICTURE WITH WEBCAM msg = subscribe.simple(button_listen, hostname=server_ip, msg_count=1) location = distance_calculator() time.sleep(1) publish.single(location_listen, str(location), hostname=server_ip) #Tell Coordinator the location msg = subscribe.simple(recog_synch, hostname=server_ip, msg_count=2) time.sleep(0.5) publish.single(cast_synch, "", hostname=server_ip) msg = subscribe.simple(recog_synch, hostname=server_ip, msg_count=2) time.sleep(0.5) publish.single(cast_synch, "", hostname=server_ip) msg = subscribe.simple(recog_synch, hostname=server_ip, msg_count=2) time.sleep(0.5) publish.single(cast_synch, "", hostname=server_ip) msg = subscribe.simple(recog_synch, hostname=server_ip, msg_count=2) time.sleep(0.5) publish.single(cast_synch, "", hostname=server_ip) print("goodbye")
def testCase6(): print("\nRunning test case 6...") ret = client.publish( "/cc3200/MoveMotors", "{\"type\": \"PICK\", \"motor0\": 180, \"motor1\": 10, \"motor2\": 100, \"motor3\": 90}" ) msg = subscribe.simple("/server/DoneMoving", msg_count=2) ret = client.publish( "/cc3200/MoveMotors", "{\"type\": \"PICK\", \"motor0\": 37, \"motor1\": 30, \"motor2\": 150, \"motor3\": 90}" ) msg = subscribe.simple("/server/DoneMoving", msg_count=2) ret = client.publish( "/cc3200/MoveMotors", "{\"type\": \"DROP\", \"motor0\": 37, \"motor1\": 160, \"motor2\": 100, \"motor3\": 40}" ) msg = subscribe.simple("/server/DoneMoving", msg_count=2) ret = client.publish( "/cc3200/MoveMotors", "{\"type\": \"DROP\", \"motor0\": 180, \"motor1\": 170, \"motor2\": 90, \"motor3\": 40}" ) msg = subscribe.simple("/server/DoneMoving", msg_count=2) ret = client.publish( "/cc3200/MoveMotors", "{\"type\": \"PICK\", \"motor0\": 90, \"motor1\": 100, \"motor2\": 90, \"motor3\": 90}" ) msg = subscribe.simple("/server/DoneMoving", msg_count=2) print("Recieved done.\n")
def wait_for_touchpad(): global flag logger = logging.getLogger('touchpad') logger.info('subscribe topic') subscribe.simple('hass/rpi/touchpad', hostname=data['mqtt_broker'], port=data['mqtt_port'], auth=MQTT_AUTH) logger.info('touchpad pressed') flag = False
def __init__(self, master, *args, **kw): tk.Frame.__init__(self, master) # self.textLabel = tk.Label(text="Aguarde o motorista no local infomado") # self.textLabel.pack() master.msgVariable.set('Aguarde o motorista no local infomado') master.update() subscribe.simple('motorista') master.msgVariable.set('A Van já está no local informado.')
def welcomeMessage(message): msg = subscribe.simple(config.topicTempInside, hostname=config.iotserver) print(msg.payload.decode("utf-8")) text = u'\U0001F321' + 'Температура в офисе: ' text = text + msg.payload.decode("utf-8") + 'C' bot.send_message(message.chat.id, text) msg = subscribe.simple(config.topicTempOutside, hostname=config.iotserver) print(msg.payload.decode("utf-8")) text = u'\U0001F321' + 'Температура на улице: ' text = text + msg.payload.decode("utf-8") + 'C' bot.send_message(message.chat.id, text) print (text)
def run_job(): while True: msg = subscribe.simple('@msg/fallevent/#', hostname='mqtt.netpie.io', port=1883, client_id=CLIENT_ID, auth={ 'username': NETPIE_TOKEN, 'password': None }, keepalive=10) if msg.topic == '@msg/fallevent/John': data_str = msg.payload.decode('ascii').replace('\x00', '') data = FallEvent(John=data_str) db.session.add(data) db.session.commit() elif msg.topic == '@msg/fallevent/Mandy': data_str = msg.payload.decode('ascii').replace('\x00', '') data = FallEvent(Mandy=data_str) db.session.add(data) db.session.commit() else: data_str = msg.payload.decode('ascii').replace('\x00', '') data = FallEvent(Chris=data_str) db.session.add(data) db.session.commit()
def listener(a,b): while True: messageFrom = subscribe.simple(person_to + "/" + person_from, hostname="broker.shiftr.io",auth={'password':'******','username':'******'}) #print messageFrom.payload stdout.write("\r" + messageFrom.payload + " "*len(person_from) + "\n") stdout.write(person_from + " : ") stdout.flush()
def _subscribe(get_query): add_slash = "" if get_query[-1] != "/": add_slash = "/" topic = f"root/topics{get_query}{add_slash}{DEVICE_ID}" logging.debug(f"Subscribe topic: {topic}") return subscribe.simple(topics=topic, hostname=URL, qos=1).payload
def sendStandard_mqtt(self, text, target, function, address, job, dataType, expectAnswer=True): # Mqtt/DT/d/1/d/BR/T publish.single("Mqtt/%s/%s/%s/%s/%s/%s/" % (self.source, function, address, job, target, dataType), payload=str(text), hostname=self.dataMap["mqtt"]["serverIP"], auth=self.auth) if expectAnswer: msg = subscribe.simple("Answer/%s/#" % target, qos=0, msg_count=1, hostname=self.dataMap["mqtt"]["serverIP"], port=1883, keepalive=60, auth=self.auth) # print("%s %s" % (msg.topic, msg.payload)) if msg.topic.split('/')[-1] != 'true': ret = False else: ret = True return msg.payload.decode('utf-8'), ret
def start(self): if self.interact: print('Interact mode: make sure you have more than one bidder ') print('(if you do not want to compete against yourself)... ') print('maybe it does not even work :)') self.client.loop_start() (usr, pwd) = self.auth available = subscribe.simple('Available-items', hostname=self.broker, auth={ 'username': usr, 'password': pwd }) objs = available.payload.decode("utf-8") print('This are the available objects: ', objs) self.lst = objs.split() in_obj = input('Wich object do you want to bid for? ') while not self.parse_list(in_obj): in_obj = input('Wich object do you want to bid for? ') self.interest_objects = str(in_obj) self.bet_process_interact() else: Process(target=self.get_items, args=()).start()
def rfidData(): members = UserProfile.objects.all() bandera = True for member in members: listaRFID = member.rfid.all() ipBroker = member.ipBroker for sensor in listaRFID: topic = sensor.topic m = subscribe.simple(topic, hostname=ipBroker, retained=False) men = str(m.payload) men = men.replace("'", "") men = men.replace("b", "") men = men.replace("UID Tag", "") men = men.split(" ") mens = str(men[1] + " " + men[2] + " " + men[3] + " " + men[4]) if mens == str(member.uid): sensor.uid = mens sensor.save() member.rfid.add(sensor) return
def choosePic(): flexAngle = mqtt.simple("keleido/flex", qos=2, hostname="192.168.0.10") flexJson = json.loads(str(flexAngle.payload, 'utf-8')) print(flexJson) Angle = flexJson['angle'] number_of_frame = int(Angle / 10) + 20 return number_of_frame
def getCurrentSettings(flowerTopic): topicsList = [ flowerTopic + "/mode", flowerTopic + "/humidity", flowerTopic + "/humidityThreshold", flowerTopic + "/dayWatering", flowerTopic + "/waterDelay", flowerTopic + "/waterDuration", flowerTopic + "/lastWater" ] data = subscribe.simple(topicsList, auth={ "username": MQTT_LOGIN, "password": MQTT_PASSWORD }, hostname=MQTT_HOST, port=MQTT_PORT, msg_count=7, keepalive=10) decodeData = [] for i in data: decodeData.append(i.payload.decode("utf-8")) strToReturn = "Режим:" + decodeData[0] + "\n" strToReturn += "Влажность:" + decodeData[1] + "%\n" strToReturn += "Порог влажности:" + decodeData[2] + "%\n" strToReturn += "День недели следующего полива:" + decodeData[ 3] + " (" + weekadays[int(decodeData[3])] + ")\n" strToReturn += "Перерыв между поливами:" + decodeData[4] + " дней\n" strToReturn += "Продолжительность полива:" + decodeData[5] + " секунд\n" strToReturn += "Последний полив:" + decodeData[6] + "\n" # print(strToReturn) return strToReturn
def single_subscribe(cls, topic, hostname, timeout = None): ''' A substitute for paho.mqtt.subscribe.simple. Adds a timeout to messages. if timeout is not provided, regular subscribe.simple command will be used ''' if timeout == None: return mqtt_subscribe.simple(topic, hostname= hostname).payload def on_message(client, data, _msg): if _msg.topic == topic: MqttConnection._single_msg = _msg.payload temp_client = mqtt_client.Client() temp_client.on_message = on_message temp_client.connect(host=hostname) temp_client.loop_start() temp_client.subscribe(topic) # block as long as the message is None and time hasn't run out start_time = time.perf_counter() while MqttConnection._single_msg == None and time.perf_counter() - start_time < timeout: pass # clean up temp_client.loop_stop() temp_client.disconnect() copy_msg = copy.deepcopy(MqttConnection._single_msg) MqttConnection._single_msg = None return copy_msg
def callBroker(self): self.dict = { 'ca_certs': self.my_ca_cert, 'certfile': self.my_pri_cert, 'keyfile': self.my_key_cert } brokerResponse = subscribe.simple(topics=self.topic, msg_count=10, hostname=self.connect_url, port=8883, transport="tcp", tls=self.dict) flight_list = [] for a in brokerResponse: print(a.topic) str_decode = str(a.payload.decode("utf-8", "ignore")) str_decode_json = json.loads(str_decode) print(str_decode_json["Update"]["Message"]) if (str_decode_json["Update"]["Message"] == "New Estimated Departure" or str_decode_json["Update"]["Message"] == "New Estimated Arrival" or str_decode_json["Update"]["Message"] == "New Gate Information"): print(str_decode_json) flight_list.append(str_decode_json["Update"]["FlightNumber"]) return flight_list
def node(node, token): try: msg = subscribe.simple(node, hostname="192.168.0.6") if (len(msg.payload) > 5): t1 = time.time() cipher = bytes(msg.payload.decode('utf-8'), 'utf-8') print(cipher) key = b'\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61' iv = b'\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61' tem = base64.b64decode(cipher) realcipher = tem[0:16] aes = AES.new(key, AES.MODE_CBC, iv) decode = aes.decrypt(realcipher).decode('utf-8') print(time.time() - t1) print(decode) l = decode.split(',') res = [int(sub.split('=')[1]) for sub in l] id = res[0] temperature = res[1] humidity = res[2] print(id) print(temperature) print(humidity) sensor_data['ID'] = res[0] sensor_data['temperature'] = res[1] sensor_data['humidity'] = res[2] client = mqtt.Client() client.username_pw_set(token) client.connect(THINGSBOARD_HOST, 1883, 120) client.publish('v1/devices/me/telemetry', json.dumps(sensor_data)) time.sleep(2) except (TimeoutError, OSError): print("ERROR CONNECTION")
def background_thread(): """Example of how to send server generated events to clients.""" count = 0 MQTT_BROKER_URL = app.config.get('MQTT_BROKER_URL') MQTT_BROKER_PORT = int(app.config.get('MQTT_BROKER_PORT')) CLIENT_ID = app.config.get('MQTT_CLIENT_ID') NETPIE_TOKEN = app.config.get('MQTT_TOKEN') board = [-99, -99, -99] while True: count += 1 msg = subscribe.simple('@msg/taist2020/board/#', hostname=MQTT_BROKER_URL, port=MQTT_BROKER_PORT, client_id=CLIENT_ID, auth={ 'username': NETPIE_TOKEN, 'password': None }, keepalive=600) board_no, rssi = extract(msg) board[board_no - 1] = rssi predicted = predict(board) socketio.emit('my response', { 'data': predicted, 'board_1': board[0], 'board_2': board[1], 'board_3': board[2] }, namespace='/test')
def worker_thread(): """Creates mqtt client which check connection between pi and mqtt broker""" global bConnected client = mqtt.Client(client_id='smartdispenserws') client.on_message = on_message client.on_connect = on_connect time.sleep(1) while not bConnected: try: print("Trying to connect broker") host = "test.mosquitto.org" porta = 1883 client.connect(host=host, port=porta, keepalive=60) client.loop_start() client.on_message = on_message time.sleep(1) if client.is_connected(): bConnected = True print("Cliente Broker está conectado") except: print("Cliente está desconectado") bConnected = False msg = subscribe.simple("smartdispenser_tx", hostname=host, port=porta) print("%s %s" % (msg.topic, msg.payload)) client.loop_stop()
def update_sensor_status(): global sensor_payloads for sensor in SENSORS: message = subscribe.simple('zigbee2mqtt/%s' % sensor.replace('_', '/'), hostname='192.168.0.253') sensor_payloads[sensor] = json.loads(message.payload)
def recv(): while (True): msg = sub.simple("pir_channel", hostname="localhost") #textb.clear() inMess = msg.payload.decode() textb.set(inMess) print(inMess)
def get_state(self): self.NFC.setup() data_NFC = self.NFC.get_data() # In case that there are any NFC value, relay will turn on. if (data_NFC != None): logger.info('Relay on') while True: self.Flow_meter.setup() #data_FLOW = self.Flow_meter.get_data() data_FLOW = subscribe.simple(topics = "/sensor/FlowSensor", hostname = "192.168.43.110" ) # If there is a flow, assign the quantity of beer to its NFC card. if (data_FLOW != 0): self.beer[data_NFC] = self.beer.get(data_NFC, 0) + data_FLOW # If it's not the first value, calculate the difference between last value and the current one. if (self.lastdata_FLOW != 0): difference = data_FLOW - self.lastdata_FLOW logger.debug('Difference: {}'.format(difference)) self.lastdata_FLOW = data_FLOW # Reset the value to start the next iteration. self.Flow_meter.value = 0.0 break logger.info('Relay off')
def loop(): while (True): conn = est_conn(address) if conn: print("Listening for data.....") msg = subscribe.simple( "iot", hostname="0.0.0.0") # replace "0.0.0.0" with your local IP data = [] msg.payload = msg.payload.decode("utf-8") print("payload=", msg.payload) count = 0 for letter in msg.payload: if letter == " ": break else: count += 1 temperature = float(msg.payload[:count]) humidity = float(msg.payload[count + 1:]) #print(temperature+ "and"+ humidity) data.append(temperature) data.append(humidity) print("trying to insert ", data) row_id = insert_data(conn, data) print("Inserted ", data, " into row=", row_id) else: print("connection failed") break
def worker(cid): global cur_iteration, result mqtt_server = "192.168.2.110" mqtt_port = 1883 mqtt_qos = 1 mqtt_retain = False mqtt_keepAlive = 60 mqtt_cleanSession = True carduid = "7B8CF40B" # admin's carduid start_time = time.time() publish.single(topic="{}/state/carduid".format(cid), payload=carduid, qos=mqtt_qos, hostname=mqtt_server, port=mqtt_port, client_id="{}".format(cid)) msg = subscribe.simple(topics="{}/command/action".format(cid), qos=mqtt_qos, hostname=mqtt_server, port=mqtt_port) duration = time.time() - start_time result[cur_iteration][cid] = duration
def update_config(self): # Auth is created on each publish auth_config = self.create_auth() config = subscribe.simple("/devices/{}/config".format(iot_device_id), qos=1, hostname="mqtt.googleapis.com", port=8883, client_id=iot_client_id, auth=auth_config, tls={ 'ca_certs': './roots.pem', 'tls_version': ssl.PROTOCOL_TLSv1_2 }) data = json.loads(config.payload) # pylint: disable=E1101 # Create empty DICT deviceUUID = {} # Expected point list is: # {"uuid": ("1.2.3.4", "analogValue", 1, "presentValue")} # Parse JSON for Protocol -> Bacnet -> Points for v in data['protocol']['bacnet'].values(): for p in v['points']: # Insert into DICT deviceUUID[p['uuid']] = (v['address'], p['type'], p['instance'], p['property']) # Write DICT to self for reference self.bacnet_points = deviceUUID
def get_single_msg(self, topic): msg = subscribe.simple(topic, hostname=hostname, port=port, client_id="", keepalive=60) return msg
def carpark_thread(): MQTT_BROKER_URL = app.config.get("MQTT_BROKER_URL") MQTT_BROKER_PORT = int(app.config.get("MQTT_BROKER_PORT")) CLIENT_ID = app.config.get("MQTT_CLIENT_ID") NETPIE_TOKEN = app.config.get("MQTT_TOKEN") while True: msg = subscribe.simple( "@msg/taist2020/board/#", hostname=MQTT_BROKER_URL, port=MQTT_BROKER_PORT, client_id=CLIENT_ID, auth={ "username": NETPIE_TOKEN, "password": None }, keepalive=600, ) floor, avail = _extract(msg) data = Carpark(floor_slot=floor, available=avail == "available") db.session.add(data) db.session.commit() socketio.emit( "carpark response", { "floor": floor, "avail": avail, "last_update": str(data.timestamp) }, namespace="/test", )
def transition_five(self, instance): #spell choices --> selected spell msg = subscribe.simple(selection_listen, hostname=server_ip, msg_count=1) #receive selected spell selected_spell = ObjectProperty(None) spell_id = str(msg.payload.strip()) spell_id = spell_id[2:] for child in self.display_area.children[:]: if child.id == "hello": for spells in child.spell_grid.children[:]: if spells.id == spell_id[0]: selected_spell = spells child.spell_grid.remove_widget(selected_spell) self.display_area.remove_widget(child) next_display = spellChoice(id="hello") next_display.spell_area.add_widget(selected_spell) self.display_area.add_widget(next_display)
def getsoil_humidity(): msg = subscribe.simple("soil_humidity", hostname="localhost", port=1883, keepalive=60) soil_humidity = float(msg.payload) return soil_humidity / 10
# The Eclipse Distribution License is available at # http://www.eclipse.org/org/documents/edl-v10.php. # # Contributors: # Roger Light - initial implementation # This shows an example of using the subscribe.simple helper function. import sys try: import paho.mqtt.subscribe as subscribe except ImportError: # This part is only required to run the example from within the examples # directory when the module itself is not installed. # # If you have the module installed, just use "import paho.mqtt.subscribe" import os import inspect cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"../src"))) if cmd_subfolder not in sys.path: sys.path.insert(0, cmd_subfolder) import paho.mqtt.subscribe as subscribe import paho.mqtt.client topics = ['#'] m = subscribe.simple(topics, hostname="iot.eclipse.org", retained=False, msg_count=2) for a in m: print(a.topic) print(a.payload)
#! /usr/bin/python3 import paho.mqtt.subscribe as subscribe msg = subscribe.simple("esp32/temperature", hostname="localhost") print("%s, %s" % (msg.topic, msg.payload))
if iteration == total: sys.stdout.write('\n') sys.stdout.flush() file = "mq.lua" host = "mqtt.lan" dest = "/dim/mac/u/" destr = "/dim/mac/ur/" import paho.mqtt.publish as publish import paho.mqtt.subscribe as subscribe import json publish.single(dest, '{"payload": { "command":"open", "file":"%s"}}' % file, hostname=host) print "Waiting for ESP at", dest msg = subscribe.simple(destr, hostname=host) print("%s %s" % (msg.topic, msg.payload)) i = 0 len = 0 with open(file, 'r') as f: for len, l in enumerate(f): pass with open(file, 'r') as f: for line in f: printProgress(i,len,prefix = 'Progress', suffix = 'Complete', barLength=50) data = {} data["payload"] = {} data["payload"]["command"] = "l" data["payload"]["line"] = line publish.single(dest, json.dumps(data), hostname=host)