Esempio n. 1
0
    def __init__(self, module_id, battery_reader=None, status_led=None):
        """
        Initialises the wireless module.
        :param module_id: An integer representing the wireless module number.
        :param battery_reader: A `BatteryReader` class to read the battery voltage from
        """
        self.sensors = []

        self.pub_data_topic = b"/v3/wireless_module/{}/data".format(module_id)
        self.battery_topic = b"/v3/wireless_module/{}/battery".format(
            module_id)

        self.sub_start_topic = b"/v3/wireless_module/{}/start".format(
            module_id)
        self.sub_stop_topic = b"/v3/wireless_module/{}/stop".format(module_id)

        self.status_topic = b"/v3/wireless_module/{}/status".format(module_id)

        self.start_publish = False
        last_will_payload = {"online": False}

        # Generate a unique client_id used to set up MQTT Client
        client_id = ubinascii.hexlify(machine.unique_id())
        self.mqtt = Client(client_id, config.MQTT_BROKER)
        self.mqtt.set_last_will(self.status_topic,
                                ujson.dumps(last_will_payload))

        self.battery = battery_reader
        self.status_led = status_led

        asyncio.get_event_loop().set_exception_handler(self.error_handler)
from mqtt_client import device_interface as Client
import flask
import json

host = "52.184.15.163"
port = 1883
app = flask.Flask(__name__)
client = Client("server")
client.run("out", host, port)
client.subscribe("out", 2)

msg_queen = {}


def add_to_queen(msg, client):
    topic = str(msg.topic, encoding="utf-8")
    payload = str(msg.payload, encoding="utf-8")
    if topic in msg_queen.keys():
        msg_queen[topic].append(payload)
    else:
        msg_queen[topic] = [payload]
    print("**************************")
    print("get topic  :" + topic)
    print("get payload:" + payload)
    print("**************************")


client.default_func = add_to_queen


@app.route("/lock", methods=["GET", "POST"])
Esempio n. 3
0
from mqtt_client import device_interface as Client

t = Client("ccc")
t.load_from_config()
t.save_to_config("./test_config.json")
print(t.action)
Esempio n. 4
0
class WirelessModule:
    """
    A class structure to read and collate data from different sensors into a dictionary and send through MQTT.
    """
    def __init__(self, module_id, battery_reader=None, status_led=None):
        """
        Initialises the wireless module.
        :param module_id: An integer representing the wireless module number.
        :param battery_reader: A `BatteryReader` class to read the battery voltage from
        """
        self.sensors = []

        self.pub_data_topic = b"/v3/wireless_module/{}/data".format(module_id)
        self.battery_topic = b"/v3/wireless_module/{}/battery".format(
            module_id)

        self.sub_start_topic = b"/v3/wireless_module/{}/start".format(
            module_id)
        self.sub_stop_topic = b"/v3/wireless_module/{}/stop".format(module_id)

        self.status_topic = b"/v3/wireless_module/{}/status".format(module_id)

        self.start_publish = False
        last_will_payload = {"online": False}

        # Generate a unique client_id used to set up MQTT Client
        client_id = ubinascii.hexlify(machine.unique_id())
        self.mqtt = Client(client_id, config.MQTT_BROKER)
        self.mqtt.set_last_will(self.status_topic,
                                ujson.dumps(last_will_payload))

        self.battery = battery_reader
        self.status_led = status_led

        asyncio.get_event_loop().set_exception_handler(self.error_handler)

    def error_handler(self, _loop, context):
        self.status_led.set_state(WmState.Error)
        print("An error occured in a uasyncio task!")
        print(context["message"])
        sys.print_exception(context["exception"])

        # FIXME: A nicer solution would be to restart all running tasks rather than reset

        print("Resetting in 5 seconds...")

        time.sleep(5)
        machine.reset()

    def add_sensors(self, sensor_arr):
        """
        Store instances of sensor class.
        :param sensor_arr: An array of sensor class instances.
        """
        self.sensors = sensor_arr

    def _read_sensors(self):
        """
        Read sensor data from each sensor object stored within this class instance.
        :return: A dictionary of all the sensor types and their corresponding sensor reading/s.
        :pre-requisite: The read() method for each sensor must return a dictionary.
        """
        readings = {"sensors": []}

        for sensor in self.sensors:
            sensor_data = sensor.read()
            for data in sensor_data:
                readings["sensors"].append(data)

        return readings

    def sub_cb(self, topic, msg):
        """
        Method to process any message received from one of the subscribed topics.
        :param topic: The topic on which the message is received.
        :param msg: The message received.
        """
        print("Successfully received message: ", msg, "on:", topic)
        if topic == self.sub_start_topic:
            self.start_publish = True
        elif topic == self.sub_stop_topic:
            self.start_publish = False

    async def start_battery_loop(self, interval):
        """
        Start publishing the battery voltage and if required show the battery warning
        on the status LED.
        :param interval: Integer representing number of seconds to wait before sending battery voltage data
        """
        if self.battery is None:
            return

        while True:
            battery_voltage = self.battery.read()
            if self.mqtt.connected:
                self.mqtt.publish(self.battery_topic,
                                  ujson.dumps(battery_voltage),
                                  retain=True)
            self.status_led.set_warning_state(
                WmState.LowBattery if
                battery_voltage["voltage"] <= LOW_BATTERY_THRESHOLD else None)
            await asyncio.sleep(interval)

    async def wait_for_start(self):
        """
        Asynchronously blocks until publishing is started.
        If at the time of calling the function the module is not publishing,
        each sensor will be told to start when publishing begins.
        """
        if not self.start_publish:
            print("Waiting for start message...")

            while not self.start_publish:
                self.status_led.set_state(WmState.Idle)
                self.mqtt.check_for_message()
                await asyncio.sleep_ms(100)

            self.status_led.set_state(WmState.Publishing)

            # Start message received, tell sensors to start
            for sensor in self.sensors:
                sensor.on_start()

    async def start_data_loop(self, interval):
        """
        Start the wireless module data publishing process: Wait for start message,
        publish sensor data when start message received and continuously check for a
        stop message - after which the process is repeated.
        :param interval: Integer representing number of seconds to wait before sending data.
        """
        secs_to_ms = 1000
        interval *= secs_to_ms

        status = {"online": True}
        self.mqtt.publish(self.status_topic, ujson.dumps(status), retain=True)

        # get millisecond counter and initialise to some previous time to start data publication immediately
        prev_data_sent = time.ticks_ms() - interval

        while True:
            await self.wait_for_start()

            # Compute the time difference since the last sensor data was read
            time_taken = time.ticks_diff(time.ticks_ms(), prev_data_sent)
            await asyncio.sleep_ms(interval - time_taken)
            prev_data_sent = time.ticks_ms()

            # Get and publish sensor data
            sensor_data = self._read_sensors()

            self.mqtt.publish(self.pub_data_topic, ujson.dumps(sensor_data))
            print("MQTT data sent: {} on {}".format(sensor_data,
                                                    self.pub_data_topic))

            self.mqtt.check_for_message()

    async def run(self, data_interval=1, battery_data_interval=300):
        """
        Start running the wireless module. Connects to MQTT and starts the data and battery loops.
        :param data_interval: Integer representing number of seconds to wait before sending data.
        :param battery_interval: Integer representing number of seconds to wait before sending battery voltage data
        """
        # Start publishing battery data straight away
        asyncio.create_task(self.start_battery_loop(battery_data_interval))

        # Attempt to connect to MQTT (will block until successful)
        self.status_led.set_state(WmState.ConnectingToMqtt)
        sub_topics = [self.sub_start_topic, self.sub_stop_topic]
        await self.mqtt.connect_and_subscribe(sub_topics, self.sub_cb)

        # Start the main publishing loop
        asyncio.create_task(self.start_data_loop(data_interval))
Esempio n. 5
0
def main():
    logger.add("log.log", rotation="1Mb")

    bridge = DrHueBridge()
    bridge_parser = Parser(data_holding_class=ParsedBridgeData)

    def config_message_callback(client, user_data, message):
        logger.debug(f"MESSAGE RECIEVED: {message}")

        config = json.loads(message.payload)
        hue_config = config.get('hue', {}).get('state', None)
        if hue_config is not None:
            hue_api_calls = bridge_parser.parse_config(hue_config)
            bridge.multi_put(hue_api_calls)

    client = Client(
        device_id='rpi',
        registry_id='home',
        project_id='theo-home',
    )

    client.add_message_callback(client.config_topic, config_message_callback)

    prev_telemetry_data = None
    prev_state_data = None
    while True:
        bridge_parser.raw_data = bridge.get_raw_data()
        client.loop()
        if bridge_parser.has_telemetry_changed(prev_telemetry_data):
            logger.info('Telemetry changed!')
            client.send_telemetry_event(bridge_parser.data_holding_class.name,
                                        bridge_parser.telemetry)
            prev_telemetry_data = bridge_parser.telemetry
        if bridge_parser.has_state_changed(prev_state_data):
            logger.info('State changed!')
            client.send_state(bridge_parser.data_holding_class.name,
                              bridge_parser.state)
            prev_state_data = bridge_parser.state
        client.loop()
Esempio n. 6
0
from example_for_load import led_off, led_on, config_file
from mqtt_client import device_interface as Client

if __name__ == "__main__":
    host = "52.184.15.163"
    port = 1883
    client = Client("device/1111")
    client.qos = 2
    client.add_action(led_on)
    client.add_action(led_off)
    client.run("123", host, port)
    client.add_subscribe("test")
    client.save_to_config(config_file)
Esempio n. 7
0

def time_test(msg):
    print("time_test:success,call by mqtt client")
    payload = str(msg.payload, encoding="utf-8")
    time1 = float(payload.split()[1])
    time2 = time.perf_counter()
    print("time use is :{}".format((time2 - time1) * 1000))


if __name__ == "__main__":
    topic = "test"
    clinet_id = "test1"
    host = "52.184.15.163"
    port = 1883
    t = Client(clinet_id)
    t.add2device_topic(topic)
    t.add_action(print_msg)
    t.add_action(print_msg2)
    t.add_action(print_msg3)
    t.add_action(time_test)
    # print(t.action.keys())
    # print(type(t.action.keys()))
    # print("print_msg" in t.action.keys())
    t.run("123", host, port)
    t.subscribe("test", 2)
    print("set down")
    t2 = Client("test3")
    t2.run("234", host, port)
    # for i in range(100):
    #     t2.publish("test","time_test "+str(time.perf_counter()),2)
Esempio n. 8
0
from mqtt_client import device_interface as Client
from mqtt_client import _load_python_file

client = Client("12333")



if __name__ == "__main__":
    paths = "C:\\Users\\sl1729\\Documents\\Xilinx_summer_school_project\\face_s_server_project\\test_add_action2.py"
    print(type(client))
    client.__init__("12333")
    print(dir(client))
    module = client.load_python_module(paths)
    client2 = getattr(module, "client")
    print(client2 == client)

    # for func in dir(module):
    #     if func.startswith("_"):
    #         continue
    #     func = getattr(module, func)
    #     if callable(func):
    #         func()
    print(client.action)
Esempio n. 9
0

def time_test(msg):
    print("time_test:success,call by mqtt client")
    payload = str(msg.payload, encoding="utf-8")
    time1 = float(payload.split()[1])
    time2 = time.perf_counter()
    print("time use is :{}".format((time2 - time1) * 1000))


if __name__ == "__main__":
    topic = "test"
    clinet_id = "test1"
    host = "52.184.15.163"
    port = 1883
    t = Client(clinet_id)
    t.add2device_topic(topic)
    t.add_action(print_msg)
    t.add_action(print_msg2)
    t.add_action(print_msg3)
    t.add_action(time_test)
    print(t.action_load)
    # print(t.action.keys())
    # print(type(t.action.keys()))
    # print("print_msg" in t.action.keys())
    # t.run("123",host,port)
    # t.subscribe("test",2)
    # print("set down")
    # t2 = Client("test3")
    # t2.run("234",host,port)
    # # for i in range(100):
Esempio n. 10
0
        "pic_name": "test.jpg",
        "topic": "device_id",
        "time": "202007291709"
    }
    files = {'file': (frame)}
    r = requests.post(url, params=params_data, files=files)
    print("get state code is :", r.status_code)


device_id = "device"
device_topic_sub = "todevice"
app_topic = "toapp"
app_id = "app"
host = "52.184.15.163"
port = 1883
client = Client(device_id)
client.run("123", host, port)
time.sleep(1)
client.add_subscribe(device_topic_sub)
client.add_action(_load_python_file)
client.add_action(_save_input_py_file)
client.add2device_topic("todevice")
client.add2app_device_topic("toapp")


@client.add_action2
def starnger_test():
    print("this is test for find stranger")
    find_stranger("toapp")
    print("finish to send msg 1")
    upload_pic("111")
Esempio n. 11
0
from mqtt_client import device_interface as Client
import time

LOAD_FROM_FILE = True
config_file = "./example_for_load_config.json"

client = Client("device/1111")


def led_on():
    print("1234led_on")


def led_off():
    print("1234len_off")


if __name__ == "__main__":
    host = "52.184.15.163"
    port = 1883
    test_client = Client("device/2222")
    test_client.run("234", host, port)
    if LOAD_FROM_FILE:
        client.load_from_config(config_file)
    else:
        client.add_action(led_on)
        client.add_action(led_off)
        client.run("123", host, port)
        client.add_subscribe("test")
        client.save_to_config()
    while True: