Exemplo n.º 1
0
async def test_add_profile():
    """add a wlan profile
    """
    broker = await start_broker()

    profile = ns.msg.Profile(uid='baba', pwd='there_is_no_secret_for_me')
    msg = ns.marshall(profile)

    cli = mqtt.MQTTClient()
    await cli.connect(tc.broker)

    await cli.publish('{}/{}'.format(tc.network, tc.board), msg, qos=QOS_0)

    await cli.subscribe([('hb/{}/{}'.format(tc.network, tc.board), QOS_0)])

    try:
        # wait for the ack
        message = await cli.deliver_message(timeout=3)
        packet = message.publish_packet
        payload = packet.payload.data
        print("%s => %s" %
              (packet.variable_header.topic_name, str(payload)))

        ack = ns.unmarshall(payload)
        print(ack)
    except asyncio.TimeoutError:
        assert 0
    finally:
        await cli.disconnect()
        await broker.shutdown()
        tc.cancel_tasks()
Exemplo n.º 2
0
def beginMQTTClient():
    client = hbmqttclient.MQTTClient()
    yield from client.connect(MQTT_BROKER_URI)
    yield from client.subscribe([(CHANNEL_ID, hbmqtt.mqtt.constants.QOS_0)])
    while True:
        weGotMail = False
        try:
            msg = yield from client.deliver_message(timeout=.1)
            weGotMail = True
        except asyncio.TimeoutError:
            pass

        # Handle local user trying to send a message
        try:
            inputLine = inputQueue.get_nowait()
            # print("Oh hey! A message from the user:"******" " + inputLine
            yield from client.publish(CHANNEL_ID, bytearray(response, "utf-8"))

        except queue.Empty:
            pass # No new user input

        if weGotMail:
            # Help from internal python docs on bytearray
            rawStrMsg = msg.data.decode("utf-8")
            clientId = rawStrMsg[0:CLIENT_ID_LENGTH]
            textMessage = rawStrMsg[CLIENT_ID_LENGTH+1:]

            # Ignore messages sent by us
            if clientId == CLIENT_ID:
                continue

            print("Client " + clientId + ": " + textMessage)
Exemplo n.º 3
0
async def test_switch_led():
    """switch on and off the red led
    """
    broker = await start_broker()

    msg_on = ns.marshall(cmd.Leds(red='on'))
    msg_off = ns.marshall(cmd.Leds(red='off'))

    cli = mqtt.MQTTClient()
    await cli.connect(tc.broker)

    await cli.subscribe([('hb/{}/{}'.format(tc.network, tc.board), QOS_0)])

    await cli.publish('{}/{}'.format(tc.network, tc.board), msg_on, qos=QOS_0)
    await asyncio.sleep(1)
    await cli.publish('{}/{}'.format(tc.network, tc.board), msg_off, qos=QOS_0)

    try:
        for _ in range(2):
            # wait for the ack
            message = await cli.deliver_message(timeout=3)
            packet = message.publish_packet
            LOG.debug("%s => %s", packet.variable_header.topic_name,
                      str(packet.payload.data))
    except asyncio.TimeoutError:
        assert 0
    finally:
        # wait before shutting down the broker, otherwise the pub packets get lost
        await asyncio.sleep(1)
        await cli.disconnect()
        await broker.shutdown()
        tc.cancel_tasks()
Exemplo n.º 4
0
 def __init__(self, sensor_id: str, address: str, sensor_type: str, icon: str):
     self.id = sensor_id
     self.address = address
     self.type = sensor_type
     self.icon = icon
     self.broker = mqtt_client.MQTTClient(config={'auto_reconnect': False})
     self.is_running = False
     self.timer = None
     self.topic = app.new_topic('sensor/' + sensor_id)
Exemplo n.º 5
0
 def __init__(self, database):
     self.database = database
     self.broker = mqtt_client.MQTTClient(config={'auto_reconnect': False})
     self.connected = False
     # sensor_id: {...}
     self.readings = {}
     self.sensors = {}
     # subscription futures
     self.sensors_subs = {}
     self._init()
     # connect to broker
     asyncio.ensure_future(self._connect())
Exemplo n.º 6
0
    def __init__(self, device_id, device_type, protocol, address, name):
        if device_type not in self.SUPPORTED_TYPES:
            raise NotSupportedError('Device type not supported.')

        self.id = device_id
        self.type = device_type
        self.protocol = protocol
        self.address = address.split(':', 1)
        self.name = name
        self.is_running = False
        self.broker = mqtt_client.MQTTClient(config={'auto_reconnect': False})
        self.topic = app.new_topic('device/' + device_id)
def beginMQTTClient():
    client = hbmqttclient.MQTTClient()
    yield from client.connect(MQTT_BROKER_URI)
    yield from client.subscribe([(CHANNEL_ID, hbmqtt.mqtt.constants.QOS_0)])
    while True:
        weGotMail = False
        try:
            msg = yield from client.deliver_message(timeout=.1)
            weGotMail = True
        except asyncio.TimeoutError:
            pass

        # Handle local user trying to send a message
        try:
            inputLine = inputQueue.get_nowait()
            # print("Oh hey! A message from the user:"******" " + inputLine
            yield from client.publish(CHANNEL_ID, bytearray(response, "utf-8"))

        except queue.Empty:
            pass  # No new user input

        if weGotMail:
            # Help from internal python docs on bytearray
            rawStrMsg = msg.data.decode("utf-8")
            clientId = rawStrMsg[0:CLIENT_ID_LENGTH]
            textMessage = rawStrMsg[CLIENT_ID_LENGTH + 1:]

            # Ignore messages sent by us
            if clientId == CLIENT_ID:
                continue

            x = "Client " + clientId + ": " + textMessage
            textMessage = textMessage.replace("\'", "\"")
            print(textMessage[6:])
            x1 = json.loads(textMessage[6:])
            #print("2")
            #return x1
            #print(type(x1))
            #print(x1["CO"])
            #val = str(textMessage)
            mycursor.execute(
                sql, (sys.argv[1], ttimetoinsert, x1["body_temp"], x1["Pulse"],
                      x1["ambient_temp"], x1["humidity"], x1["CO"],
                      x1["Smoke"], x1["LPG"], x1["loc_lat"], x1["loc_lng"]))
            mydb.commit()
            #print(mycursor.rowcount, "record inserted.")
            break
Exemplo n.º 8
0
 def __init__(self, sensors: SensorManager, devices: DeviceManager,
              schedule: dict):
     self.sensors = sensors
     self.devices = devices
     self.schedule = schedule
     # ensure lock between start and stop behavior methods
     self.behavior_lock = asyncio.Lock()
     # the currently running behavior (BaseBehavior instance)
     self.behavior = None
     # definition of the currently running behavior (dict)
     self.behavior_def = None
     # the currently operating behavior subscription task
     self.behavior_sub = None
     self.behavior_topic = app.new_topic('behavior/active')
     self.broker = mqtt_client.MQTTClient(config={'auto_reconnect': False})
     self.is_running = False
Exemplo n.º 9
0
    def __init__(self, myapp):
        self.app = myapp
        self.sensors = sensorman.SensorManager(self.app.database)
        self.devices = deviceman.DeviceManager(self.app.database)
        self.broker = mqtt_client.MQTTClient(config={'auto_reconnect': False})
        # the operating (active) schedule
        self.schedule = None
        self.schedule_lock = asyncio.Lock()
        self.timer = None

        # start the timer node
        self.timer = TimerNode('timer',
                               int(self.app.config['BACKEND_INTERVAL']))

        # connect to broker
        asyncio.ensure_future(self._connect())
Exemplo n.º 10
0
def beginMQTTClient(
):  ############################ DEFINING COROUTINE###################
    client = hbmqttclient.MQTTClient()
    yield from client.connect(MQTT_BROKER_URI)
    yield from client.subscribe([(CHANNEL_ID, hbmqtt.mqtt.constants.QOS_0)])
    while True:
        weGotMail = False
        try:
            msg = yield from client.deliver_message(timeout=.1)
            weGotMail = True
        except asyncio.TimeoutError:
            pass
        except asyncio.IncompleteReadError:
            print("GGWP")
        # Handle local user trying to send a message
        try:
            inputLine = inputQueue.get_nowait()
            response = CLIENT_ID + " " + inputLine
            yield from client.publish(CHANNEL_ID, bytearray(response, "utf-8"))

        except queue.Empty:
            pass  # No new user input

        if weGotMail:
            # DECODING BYTEARRAY INTO utf-8
            rawStrMsg = msg.data.decode("utf-8")
            clientId = rawStrMsg[0:CLIENT_ID_LENGTH]
            textMessage = rawStrMsg[CLIENT_ID_LENGTH + 1:]
            #textMessage = str(sensors())
            #continue

            # IGNORE OWN MESSAGES
            if clientId == CLIENT_ID:
                continue

            print("Client " + clientId + ": " + textMessage)
            if (textMessage == "GET_DATA"):
                try:
                    pre_response = str(sensors())
                    response = "Client" + clientId + ":" + pre_response
                    #print(response)
                    yield from client.publish(
                        CHANNEL_ID, bytearray(response, "utf-8")
                    )  #######################REPLY TO SENDER WITH INFO(SENSOR STUFF)#############
                except asyncio.IncompleteReadError:
                    print("Try again")
Exemplo n.º 11
0
    def __init__(self, node_id, seconds):
        self.seconds = seconds
        self.topic = app.new_topic(node_id + '/_internal')

        self.broker = mqtt_client.MQTTClient(config={'auto_reconnect': False})
        asyncio.ensure_future(self._connect())