def __on_message(self, client, userdata, message):
     try:
         message = json.loads(message.payload.decode())
         if message['msg'] == 'ENVIRONMENTAL-CURRENT-SENSOR-DATA':
             for reading in self.device.parseEnvironmentSensors(message):
                 Client.event(
                     self.device,
                     reading[0],
                     json.dumps({
                         'value': reading[1],
                         'unit': reading[2],
                         'time': reading[3]
                     }),
                     block=False
                 )
                 time.sleep(0.1)
         elif message['msg'] == 'CURRENT-STATE':
             self.device.state = message.get('product-state')
             if not self.init_state.is_set():
                 self.init_state.set()
         elif message['msg'] == 'STATE-CHANGE':
             self.device.updateState(message.get('product-state'))
         else:
             logger.warning("unknown message: '{}'".format(message))
     except Exception as ex:
         logger.error("malformed message: '{}'".format(ex))
def getReading(source):
    payload = dict()
    while True:
        readings = source.read()
        if readings:
            payload['value'] = float(readings['1.8.0'][0])
            payload['unit'] = readings['1.8.0'][1]
            payload['time'] = '{}Z'.format(
                datetime.datetime.utcnow().isoformat())
            Client.event(device=SM_ID,
                         service=SEPL_SERVICE,
                         data=json.dumps(payload))
def pushReadings():
    while True:
        for controller in SerialManager.getControllers():
            try:
                Client.event(
                    controller._extended_id,
                    'detection',
                    json.dumps({
                        'value': float(controller._kwh),
                        'unit': 'kWh',
                        'time': '{}Z'.format(datetime.datetime.utcnow().isoformat())
                    }),
                    block=False
                )
                time.sleep(0.1)
            except Exception as ex:
                logger.error(ex)
        time.sleep(20)
Beispiel #4
0
    def run(self):
        # Get data via CoAP Observe request
        # self.check_observations()

        # Get data via frequently GET requests (maybe as fallback if observe is not supported)
        while True:
            time.sleep(30)
            localhost_client = HelperClient(("127.0.0.1", 5683))

            # Observe all sensor resources # todo id und status von endpoint bei join mitnehmen
            services_of_connected_devices = localhost_client.get(
                "lookup/res?status=1&if=core.s")
            for device in services_of_connected_devices:
                id = device.get("id")
                url = request_helper.parse_url(device.get("path"))
                logger.info(
                    "OBSERVER: Perform GET to: {host}:{port} with id: {id}".
                    format(host=url.hostname, port=url.port, id=id))
                device_client = HelperClient((url.hostname, url.port))
                response = None

                try:
                    response = device_client.get(url.path)
                    device = DB.DB.get(id)
                except Exception as e:
                    logger.error("OBSERVER: GET was not successful")

                if response:
                    try:
                        # Data Type of platoform contain data and metadata
                        # structure of data has to be defined in the service output parameter
                        Client.event(device,
                                     service=url.path,
                                     data=json.dumps(response.payload))
                    except Exception as e:
                        logger.error(
                            "OBSERVER: Send data to platform was not successful"
                        )
Beispiel #5
0
def pushReadings():
    while True:
        for device in DevicePool.devices().values():
            try:
                response = http.get('http://{}/api/air/kick'.format(device.ip))
                if response.status == 204:
                    time.sleep(5)
                response = http.get('http://{}/api/air/state'.format(device.ip))
                if response.status == 200:
                    air_state = json.loads(response.body)
                    for sensor in air_state['air']['sensors']:
                        Client.event(
                            device.id,
                            'reading_{}'.format(sensor['type']),
                            json.dumps({
                                'value': sensor['value'],
                                'unit': 'µg/m³',
                                'time': '{}Z'.format(datetime.datetime.utcnow().isoformat())
                            }),
                            block=False
                        )
            except Exception as ex:
                logger.error(ex)
        time.sleep(20)
    def run(self):
        logger.info("Start observing of values")
        while True:
            time.sleep(int(config["CONNECTOR"]["ping_interval"]))
            logger.debug("get values from devices and push to platform")
            connected_devices = device_pool.DevicePool.devices()

            for device in connected_devices:
                device_json = self.openhab_api_manager.get_thing(device)

                channels = device_json.get("channels")
                for channel in channels:
                    items = channel.get("linkedItems")
                    if items:
                        if len(items) != 0:
                            try:
                                service_response = self.openhab_api_manager.getItemState(
                                    items[0])
                                # convert depending on data type
                                if channel.get("itemType") == "Number":
                                    service_response = float(service_response)
                                payload = {
                                    "value": service_response,
                                    "time":
                                    datetime.datetime.utcnow().isoformat()
                                }
                                # channel type uid == service id
                                logger.debug(
                                    "try to publish data from service: " +
                                    channel.get("channelTypeUID"))
                                logger.debug("publish data: " +
                                             json.dumps(payload))
                                response = Client.event(
                                    device, channel.get("channelTypeUID"),
                                    json.dumps(payload))
                                logger.debug(response.status)
                            except Exception as ex:
                                logger.error("'{}': {}".format(items[0], ex))
        logger.info('------ delete existing device ------')
        Client.delete(id_3)

    if 7 in tests:
        time.sleep(0.5)
        logger.info('------ add new device ------')
        new_device = Device(id_4, 'iot#1740e97f-1ae1-4547-a757-a62018083d3f',
                            'Dummy Device 4')
        Client.add(new_device)

    if 8 in tests:
        time.sleep(0.5)
        logger.info('------ push 5 events ------')
        for event in range(5):
            data = json.dumps({'str_field': 'dummy event', 'int_field': event})
            response = Client.event(id_4, 'dummy-event', data,
                                    'dummy metadata {}'.format(event))
            logger.info("event response '{}'".format(response.payload))

    if 9 in tests:
        time.sleep(0.5)
        logger.info('------ receive command and respond ------')
        msg_obj = Client.receive()
        device_id = msg_obj.payload.get('device_url')
        service = msg_obj.payload.get('service_url')
        command = msg_obj.payload.get('protocol_parts')
        logger.info("received command for device '{}' on service '{}':".format(
            device_id, service))
        logger.info(command)
        Client.response(msg_obj, '200', 'status')
        logger.info('sent response')
Beispiel #8
0
 def handle_observe_response(self, response, id=None):
     if id and response:
         device = DB.DB.get(id)
         service = ""
         payload = response
         Client.event(device, service, payload)