def __scan_ble(self):
     log.debug("Scanning for devices...")
     try:
         self.__scanner.scan(self.__config.get('scanTimeSeconds', 5),
                             passive=self.__config.get(
                                 'passiveScanMode', False))
     except BTLEManagementError as e:
         log.error('BLE working only with root user.')
         log.error(
             'Or you can try this command:\nsudo setcap '
             '\'cap_net_raw,cap_net_admin+eip\' %s'
             '\n====== Attention! ====== '
             '\nCommand above - provided access to ble devices to any user.'
             '\n========================',
             str(bluepy_path[0] + '/bluepy-helper'))
         self._connected = False
         raise e
     except Exception as e:
         log.exception(e)
         time.sleep(10)
    def server_side_rpc_handler(self, content):
        try:
            for method in self.__available_object_resources['methods'][content["device"]]:
                rpc_method = content["data"].get("method")
                if rpc_method is not None and method.get(rpc_method) is not None:
                    arguments = content["data"].get("params")
                    if type(arguments) is list:
                        result = method["node"].call_method(method[rpc_method], *arguments)
                    elif arguments is not None:
                        result = method["node"].call_method(method[rpc_method], arguments)
                    else:
                        result = method["node"].call_method(method[rpc_method])

                    self.__gateway.send_rpc_reply(content["device"],
                                                  content["data"]["id"],
                                                  {content["data"]["method"]: result})

                    log.debug("method %s result is: %s", method[rpc_method], result)
        except Exception as e:
            log.exception(e)
 def __search_attribute_update_variables(self, device_info):
     try:
         if device_info["configuration"].get("attributes_updates", []):
             node = device_info["deviceNode"]
             device_name = device_info["deviceName"]
             if self.__available_object_resources.get(device_name) is None:
                 self.__available_object_resources[device_name] = {}
             if self.__available_object_resources[device_name].get("variables") is None:
                 self.__available_object_resources[device_name]["variables"] = []
             for attribute_update in device_info["configuration"]["attributes_updates"]:
                 attribute_path = self._check_path(attribute_update["attributeOnDevice"], node)
                 attribute_nodes = []
                 self.__search_node(node, attribute_path, result=attribute_nodes)
                 for attribute_node in attribute_nodes:
                     if attribute_node is not None:
                         self.__available_object_resources[device_name]["variables"].append({attribute_update["attributeOnThingsBoard"]: attribute_node})
                     else:
                         log.error("Attribute update node with path \"%s\" - NOT FOUND!", attribute_path)
     except Exception as e:
         log.exception(e)
Example #4
0
 def do_read_property(self,
                      device,
                      mapping_type=None,
                      config=None,
                      callback=None):
     try:
         iocb = device if isinstance(device, IOCB) else self.form_iocb(
             device, config, "readProperty")
         deferred(self.request_io, iocb)
         self.requests_in_progress.update({
             iocb: {
                 "callback": callback,
                 "device": device,
                 "mapping_type": mapping_type,
                 "config": config
             }
         })
         iocb.add_callback(self.__general_cb)
     except Exception as e:
         log.exception(e)
 def __iam_cb(self, iocb: IOCB, vendor_id=None):
     if iocb.ioResponse:
         apdu = iocb.ioResponse
         log.debug("Received IAm Response: %s", str(apdu))
         if self.discovered_devices.get(apdu.pduSource) is None:
             self.discovered_devices[apdu.pduSource] = {}
         value = self.__connector.default_converters["uplink_converter"](
             "{}").convert(None, apdu)
         log.debug("Property: %s is %s", apdu.propertyIdentifier, value)
         self.discovered_devices[apdu.pduSource].update(
             {apdu.propertyIdentifier: value})
         data_to_connector = {
             "address": apdu.pduSource,
             "objectId": apdu.objectIdentifier,
             "name": value,
             "vendor": vendor_id if vendor_id is not None else 0
         }
         self.__connector.add_device(data_to_connector)
     elif iocb.ioError:
         log.exception(iocb.ioError)
Example #6
0
    def on_attributes_update(self, content):
        try:
            device = tuple(filter(lambda slave: slave.name == content[DEVICE_SECTION_PARAMETER], self.__slaves))[0]

            for attribute_updates_command_config in device.config['attributeUpdates']:
                for attribute_updated in content[DATA_PARAMETER]:
                    if attribute_updates_command_config[TAG_PARAMETER] == attribute_updated:
                        to_process = {
                            DEVICE_SECTION_PARAMETER: content[DEVICE_SECTION_PARAMETER],
                            DATA_PARAMETER: {
                                RPC_METHOD_PARAMETER: attribute_updated,
                                RPC_PARAMS_PARAMETER: content[DATA_PARAMETER][attribute_updated]
                            }
                        }
                        attribute_updates_command_config['byteOrder'] = device.byte_order or 'LITTLE'
                        attribute_updates_command_config['wordOrder'] = device.word_order or 'LITTLE'
                        self.__process_request(to_process, attribute_updates_command_config,
                                               request_type='attributeUpdates')
        except Exception as e:
            log.exception(e)
 def process_data(self, request):
     if not request.json:
         abort(415)
     endpoint_config = self.__endpoint['config']
     if request.method.upper() not in [
             method.upper() for method in endpoint_config['HTTPMethods']
     ]:
         abort(405)
     try:
         log.info("CONVERTER CONFIG: %r", endpoint_config['converter'])
         converter = self.__endpoint['converter'](
             endpoint_config['converter'])
         converted_data = converter.convert(
             config=endpoint_config['converter'], data=request.get_json())
         self.send_to_storage(self.__name, converted_data)
         log.info("CONVERTED_DATA: %r", converted_data)
         return "OK", 200
     except Exception as e:
         log.exception("Error while post to basic handler: %s", e)
         return "", 500
Example #8
0
 def run(self):
     while not self.__connected:
         try:
             self.__connected = self.client.connect()
             try:
                 self.client.load_type_definitions()
             except Exception as e:
                 log.debug(e)
                 log.debug("Error on loading type definitions.")
             log.debug(self.client.get_namespace_array()[-1])
             log.debug(self.client.get_namespace_index(self.client.get_namespace_array()[-1]))
         except ConnectionRefusedError:
             log.error("Connection refused on connection to OPC-UA server with url %s", self.__server_conf.get("url"))
             time.sleep(10)
         except Exception as e:
             log.debug("error on connection to OPC-UA server.")
             log.error(e)
             time.sleep(10)
         else:
             self.__connected = True
             log.info("OPC-UA connector %s connected to server %s", self.get_name(), self.__server_conf.get("url"))
     self.__opcua_nodes["root"] = self.client.get_root_node()
     self.__opcua_nodes["objects"] = self.client.get_objects_node()
     self.__sub = self.client.create_subscription(self.__server_conf.get("scanPeriodInMillis", 500), self.__sub_handler)
     self.__scan_nodes_from_config()
     log.debug('Subscriptions: %s', self.subscribed)
     log.debug("Available methods: %s", self.__available_object_resources)
     while True:
         try:
             time.sleep(1)
             if self.data_to_send:
                 self.__gateway.send_to_storage(self.get_name(), self.data_to_send.pop())
             if self.__stopped:
                 self.close()
                 break
         except (KeyboardInterrupt, SystemExit):
             self.close()
             raise
         except Exception as e:
             self.close()
             log.exception(e)
Example #9
0
    def server_side_rpc_handler(self, content):
        try:
            for rpc_request in self.__rpc_requests:
                if fullmatch(rpc_request["deviceNameFilter"], content["device"]) and \
                        fullmatch(rpc_request["methodFilter"], content["data"]["method"]):
                    converted_data = rpc_request["downlink_converter"].convert(
                        rpc_request, content)
                    response_queue = Queue(1)
                    request_dict = {
                        "config": {
                            **rpc_request,
                            **converted_data
                        },
                        "request": regular_request
                    }
                    request_dict["converter"] = request_dict["config"].get(
                        "uplink_converter")
                    with self._app.test_request_context():
                        rpc_request_thread = Thread(
                            target=self.__send_request,
                            args=(request_dict, response_queue, log),
                            daemon=True,
                            name="RPC request to %s" % (converted_data["url"]))
                        rpc_request_thread.start()
                        rpc_request_thread.join()
                    if not response_queue.empty():
                        response = response_queue.get_nowait()
                        log.debug(response)
                        self.__gateway.send_rpc_reply(
                            device=content["device"],
                            req_id=content["data"]["id"],
                            content=response[2])
                    else:
                        self.__gateway.send_rpc_reply(
                            device=content["device"],
                            req_id=content["data"]["id"],
                            success_sent=True)

                    del response_queue
        except Exception as e:
            log.exception(e)
Example #10
0
 def __scan_nodes_from_config(self):
     try:
         if self.__interest_nodes:
             for device_object in self.__interest_nodes:
                 for current_device in device_object:
                     try:
                         device_configuration = device_object[current_device]
                         device_info = self.__search_general_info(device_configuration)
                         if device_info is not None and device_info.get("deviceNode") is not None:
                             self.__search_nodes_and_subscribe(device_configuration, device_info)
                             self.__save_methods(device_info, device_configuration)
                             self.__search_attribute_update_variables(device_configuration, device_info)
                         else:
                             log.error("Device node is None, please check your configuration.")
                             log.debug("Current device node is: %s", str(device_configuration.get("deviceNodePattern")))
                             break
                     except Exception as e:
                         log.exception(e)
             log.debug(self.__interest_nodes)
     except Exception as e:
         log.exception(e)
 def __save_methods(self, device_info):
     try:
         if self.__available_object_resources.get(device_info["deviceName"]) is None:
             self.__available_object_resources[device_info["deviceName"]] = {}
         if self.__available_object_resources[device_info["deviceName"]].get("methods") is None:
             self.__available_object_resources[device_info["deviceName"]]["methods"] = []
         if device_info["configuration"].get("rpc_methods", []):
             node = device_info["deviceNode"]
             for method_object in device_info["configuration"]["rpc_methods"]:
                 method_node_path = self._check_path(method_object["method"], node)
                 methods = []
                 self.__search_node(node, method_node_path, True, result=methods)
                 for method in methods:
                     if method is not None:
                         node_method_name = method.get_display_name().Text
                         self.__available_object_resources[device_info["deviceName"]]["methods"].append(
                             {node_method_name: method, "node": node, "arguments": method_object.get("arguments")})
                     else:
                         log.error("Node for method with path %s - NOT FOUND!", method_node_path)
     except Exception as e:
         log.exception(e)
 def __fill_requests(self):
     log.debug(self.__config["mapping"])
     for endpoint in self.__config["mapping"]:
         try:
             log.debug(endpoint)
             converter = None
             if endpoint["converter"]["type"] == "custom":
                 module = TBUtility.check_and_import(self.__connector_type, endpoint["converter"]["extension"])
                 if module is not None:
                     log.debug('Custom converter for url %s - found!', endpoint["url"])
                     converter = module(endpoint)
                 else:
                     log.error("\n\nCannot find extension module for %s url.\nPlease check your configuration.\n", endpoint["url"])
             else:
                 converter = JsonRequestUplinkConverter(endpoint)
             self.__requests_in_progress.append({"config": endpoint,
                                                 "converter": converter,
                                                 "next_time": time(),
                                                 "request": requests.request})
         except Exception as e:
             log.exception(e)
 def on_attributes_update(self, content):
     try:
         for attribute_request in self.__attribute_updates:
             if fullmatch(attribute_request["deviceNameFilter"], content["device"]) and fullmatch(attribute_request["attributeFilter"], list(content["data"].keys())[0]):
                 converted_data = attribute_request["converter"].convert(attribute_request, content)
                 response_queue = Queue(1)
                 request_dict = {"config": {**attribute_request,
                                            **converted_data},
                                 "request": requests.request}
                 attribute_update_request_thread = Thread(target=self.__send_request,
                                                          args=(request_dict, response_queue, log),
                                                          daemon=True,
                                                          name="Attribute request to %s" % (converted_data["url"]))
                 attribute_update_request_thread.start()
                 attribute_update_request_thread.join()
                 if not response_queue.empty():
                     response = response_queue.get_nowait()
                     log.debug(response)
                 del response_queue
     except Exception as e:
         log.exception(e)
 def __function_to_device(self, config, unit_id):
     function_code = config.get('functionCode')
     result = None
     if function_code in (1, 2, 3, 4):
         result = self.__available_functions[function_code](
             config["address"],
             config.get(
                 "objectsCount",
                 config.get("registersCount",
                            config.get("registerCount", 1))),
             unit=unit_id)
     elif function_code in (5, 6, 15, 16):
         result = self.__available_functions[function_code](
             config["address"], config["payload"], unit=unit_id)
     else:
         log.error("Unknown Modbus function with code: %i", function_code)
     log.debug("With result %s", str(result))
     if "Exception" in str(result):
         log.exception(result)
         result = str(result)
     return result
Example #15
0
 def on_attributes_update(self, content):
     try:
         for attribute_updates_command_config in \
                 self.__devices[content[DEVICE_SECTION_PARAMETER]][CONFIG_SECTION_PARAMETER]["attributeUpdates"]:
             for attribute_updated in content[DATA_PARAMETER]:
                 if attribute_updates_command_config[
                         TAG_PARAMETER] == attribute_updated:
                     to_process = {
                         DEVICE_SECTION_PARAMETER:
                         content[DEVICE_SECTION_PARAMETER],
                         DATA_PARAMETER: {
                             RPC_METHOD_PARAMETER:
                             attribute_updated,
                             RPC_PARAMS_PARAMETER:
                             content[DATA_PARAMETER][attribute_updated]
                         }
                     }
                     self.__process_rpc_request(
                         to_process, attribute_updates_command_config)
     except Exception as e:
         log.exception(e)
 def run(self):    # Main loop of thread
     try:
         while True:
             for device in self.__devices:
                 device_serial_port = self.__devices[device]["serial"]
                 received_character = b''
                 data_from_device = b''
                 while received_character != b'\n':  # We will read until receive LF symbol
                     try:
                         received_character = device_serial_port.read(1)    # Read one symbol per time
                     except AttributeError as e:
                         if device_serial_port is None:
                             self.__connect_to_devices()    # if port not found - try to connect to it
                             raise e
                     except Exception as e:
                         log.exception(e)
                         break
                     else:
                         data_from_device = data_from_device + received_character
                 try:
                     converted_data = self.__devices[device]['converter'].convert(self.__devices[device]['device_config'], data_from_device)
                     self.__gateway.send_to_storage(self.get_name(), converted_data)
                     time.sleep(.1)
                 except Exception as e:
                     log.exception(e)
                     self.close()
                     raise e
             if not self.__connected:
                 break
     except Exception as e:
         log.exception(e)
    def server_side_rpc_handler(self, content):
        try:
            for rpc_request in self.__rpc_requests:
                if fullmatch(rpc_request['deviceNameFilter'],
                             content['device']) and fullmatch(
                                 rpc_request['methodFilter'],
                                 content['data']['method']):
                    with self.__ftp() as ftp:
                        if not self._connected:
                            self.__connect(ftp)

                        converted_data = None
                        success_sent = None
                        if content['data']['method'] == 'write':
                            try:
                                arr = re.sub(
                                    "'", '',
                                    content['data']['params']).split(';')
                                io_stream = io.BytesIO(str.encode(arr[1]))
                                ftp.storbinary('STOR ' + arr[0], io_stream)
                                io_stream.close()
                                success_sent = True
                            except Exception as e:
                                log.error(e)
                                converted_data = '{"error": "' + str(e) + '"}'
                        else:
                            handle_stream = io.BytesIO()
                            ftp.retrbinary('RETR ' + content['data']['params'],
                                           handle_stream.write)
                            converted_data = str(handle_stream.getvalue(),
                                                 'UTF-8')
                            handle_stream.close()

                        self.__gateway.send_rpc_reply(
                            device=content["device"],
                            req_id=content["data"]["id"],
                            success_sent=success_sent,
                            content=converted_data)
        except Exception as e:
            log.exception(e)
 def __general_cb(self, iocb, callback_params=None, value=None):
     try:
         if callback_params is None:
             callback_params = self.requests_in_progress[iocb]
         if iocb.ioResponse:
             apdu = iocb.ioResponse
             if isinstance(apdu, SimpleAckPDU):
                 log.debug("Write to %s - successfully.",
                           str(apdu.pduSource))
             else:
                 log.debug("Received response: %r", apdu)
         elif iocb.ioError:
             log.exception(iocb.ioError)
         else:
             log.error("There are no data in response and no errors.")
         if isinstance(callback_params,
                       dict) and callback_params.get("callback"):
             try:
                 callback_params["callback"](iocb, callback_params)
             except TypeError:
                 callback_params["callback"](iocb)
     except Exception as e:
         log.exception(
             "During processing callback, exception has been raised:")
         log.exception(e)
     if self.requests_in_progress.get(iocb) is not None:
         del self.requests_in_progress[iocb]
Example #19
0
    def add_device(self, data):
        if self.__devices_address_name.get(data["address"]) is None:
            for device in self.__config_devices:
                if device["address"] == data["address"]:
                    try:
                        config_address = Address(device["address"])
                        device_name_tag = TBUtility.get_value(
                            device["deviceName"], get_tag=True)
                        device_name = device["deviceName"].replace(
                            "${" + device_name_tag + "}", data.pop("name"))
                        device_information = {
                            **data,
                            **self.__get_requests_configs(device),
                            "type":
                            device["deviceType"],
                            "config":
                            device,
                            "attributes":
                            device.get("attributes", []),
                            "telemetry":
                            device.get("timeseries", []),
                            "poll_period":
                            device.get("pollPeriod", 5000),
                            "deviceName":
                            device_name,
                        }
                        if config_address == data["address"] or \
                                (config_address, GlobalBroadcast) or \
                                (isinstance(config_address, LocalBroadcast) and isinstance(device["address"],
                                                                                           LocalStation)) or \
                                (isinstance(config_address, (LocalStation, RemoteStation)) and isinstance(
                                    data["address"], (
                                            LocalStation, RemoteStation))):
                            self.__devices_address_name[data[
                                "address"]] = device_information["deviceName"]
                            self.__devices.append(device_information)

                        log.debug(data["address"].addrType)
                    except Exception as e:
                        log.exception(e)
Example #20
0
    def real_time_sim_of_batch(self, config, data):
        try:
            #print("new values###################################")
            time_to_sleep = self.get_time(data)
            #print(time_to_sleep)

            data_to_check = data["telemetry"]
            length_of_arr = 0
            for sensor in data_to_check:
                for j in sensor:
                    length_of_arr = len(sensor[j])

            dict_result = {
                "deviceName": data["deviceName"],
                "deviceType": "default",
                "attributes": [],
                "telemetry": []
            }

            i = 0
            for length_of_arr in range(length_of_arr):
                for sensor in data_to_check:
                    for j in sensor:
                        dict_result["telemetry"].append(
                            {j: sensor[j][i]["value"]})
                i += 1
                self.__gateway.send_to_storage(self.get_name(), dict_result)
                self.statistics[
                    "MessagesSent"] = self.statistics["MessagesSent"] + 1
                dict_result = {
                    "deviceName": data["deviceName"],
                    "deviceType": "default",
                    "attributes": [],
                    "telemetry": []
                }

                sleep(time_to_sleep)
            #log.debug(data_to_send)
        except Exception as e:
            log.exception(e)
 def run(self):    # Main loop of thread
     try:
         while True:
             for device in self.devices:
                 serial = self.devices[device]["serial"]
                 ch = b''
                 data_from_device = b''
                 while ch != b'\n':
                     try:
                         try:
                             ch = serial.read(1)    # Reading data from serial
                         except AttributeError as e:
                             if serial is None:
                                 self.__connect_to_devices()    # if port not found - try to connect to it
                                 raise e
                         data_from_device = data_from_device + ch
                     except Exception as e:
                         log.exception(e)
                         continue
                 try:
                     converted_data = self.devices[device]['converter'].convert(self.devices[device]['device_config'], data_from_device)
                     self.__gateway.send_to_storage(self.get_name(), converted_data)
                     time.sleep(.1)
                 except Exception as e:
                     log.exception(e)
                     self.close()
                     raise e
             if not self.connected:
                 break
     except Exception as e:
         log.exception(e)
Example #22
0
 def on_attributes_update(self, content):
     if self.__attribute_updates:
         for attribute_update in self.__attribute_updates:
             if match(attribute_update["deviceNameFilter"],
                      content["device"]):
                 for attribute_key in content["data"]:
                     if match(attribute_update["attributeFilter"],
                              attribute_key):
                         try:
                             topic = attribute_update["topicExpression"]\
                                     .replace("${deviceName}", str(content["device"]))\
                                     .replace("${attributeKey}", str(attribute_key))\
                                     .replace("${attributeValue}", str(content["data"][attribute_key]))
                         except KeyError as e:
                             log.exception(
                                 "Cannot form topic, key %s - not found", e)
                             raise e
                         try:
                             data = attribute_update["valueExpression"]\
                                     .replace("${attributeKey}", str(attribute_key))\
                                     .replace("${attributeValue}", str(content["data"][attribute_key]))
                         except KeyError as e:
                             log.exception(
                                 "Cannot form topic, key %s - not found", e)
                             raise e
                         self._client.publish(topic,
                                              data).wait_for_publish()
                         self.__log.debug(
                             "Attribute Update data: %s for device %s to topic: %s",
                             data, content["device"], topic)
                     else:
                         self.__log.error(
                             "Cannot find attributeName by filter in message with data: %s",
                             content)
             else:
                 self.__log.error(
                     "Cannot find deviceName by filter in message with data: %s",
                     content)
     else:
         self.__log.error("Attribute updates config not found.")
 def __load_converters(self):
     try:
         for device in self.__config[CONFIG_DEVICES_SECTION_PARAMETER]:
             if self.__config.get(UPLINK_PREFIX +
                                  CONVERTER_PARAMETER) is not None:
                 converter = TBModuleLoader.import_module(
                     self._connector_type,
                     self.__config[UPLINK_PREFIX +
                                   CONVERTER_PARAMETER])(device)
             else:
                 converter = BytesModbusUplinkConverter(device)
             if self.__config.get(DOWNLINK_PREFIX +
                                  CONVERTER_PARAMETER) is not None:
                 downlink_converter = TBModuleLoader.import_module(
                     self._connector_type,
                     self.__config[DOWNLINK_PREFIX +
                                   CONVERTER_PARAMETER])(device)
             else:
                 downlink_converter = BytesModbusDownlinkConverter(device)
             if device.get(DEVICE_NAME_PARAMETER
                           ) not in self.__gateway.get_devices():
                 self.__gateway.add_device(
                     device.get(DEVICE_NAME_PARAMETER),
                     {CONNECTOR_PARAMETER: self},
                     device_type=device.get(DEVICE_TYPE_PARAMETER))
             self.__devices[device[DEVICE_NAME_PARAMETER]] = {
                 CONFIG_SECTION_PARAMETER: device,
                 UPLINK_PREFIX + CONVERTER_PARAMETER: converter,
                 DOWNLINK_PREFIX + CONVERTER_PARAMETER: downlink_converter,
                 NEXT_PREFIX + ATTRIBUTES_PARAMETER + CHECK_POSTFIX: 0,
                 NEXT_PREFIX + TIMESERIES_PARAMETER + CHECK_POSTFIX: 0,
                 TELEMETRY_PARAMETER: {},
                 ATTRIBUTES_PARAMETER: {},
                 LAST_PREFIX + TELEMETRY_PARAMETER: {},
                 LAST_PREFIX + ATTRIBUTES_PARAMETER: {},
                 CONNECTION_ATTEMPT_PARAMETER: 0
             }
     except Exception as e:
         log.exception(e)
Example #24
0
 def __process_rpc_request(self, content, rpc_command_config):
     if rpc_command_config is not None:
         rpc_command_config["unitId"] = self.__devices[content["device"]]["config"]["unitId"]
         self.__connect_to_current_master(content["device"])
         # if rpc_command_config.get('bit') is not None:
         #     rpc_command_config["functionCode"] = 6
         if rpc_command_config.get("functionCode") in (5, 6, 15, 16):
             rpc_command_config["payload"] = self.__devices[content["device"]]["downlink_converter"].convert(
                 rpc_command_config, content)
         response = None
         try:
             response = self.__function_to_device(rpc_command_config, rpc_command_config["unitId"])
         except Exception as e:
             log.exception(e)
             response = e
         if isinstance(response, (ReadRegistersResponseBase, ReadBitsResponseBase)):
             to_converter = {"rpc": {content["data"]["method"]: {"data_sent": rpc_command_config,
                                                                 "input_data": response}}}
             response = self.__devices[content["device"]]["converter"].convert(config={**self.__devices[content["device"]]["config"],
                                                                                                  "byteOrder": self.__devices[content["device"]]["config"].get("byteOrder", self.__byte_order),
                                                                                                  "wordOrder": self.__devices[content["device"]]["config"].get("wordOrder", self.__word_order)}, data=to_converter)
             log.debug("Received RPC method: %s, result: %r", content["data"]["method"], response)
             # response = {"success": response}
         elif isinstance(response, (WriteMultipleRegistersResponse,
                                    WriteMultipleCoilsResponse,
                                    WriteSingleCoilResponse,
                                    WriteSingleRegisterResponse)):
             log.debug("Write %r", str(response))
             response = {"success": True}
         if content.get("id") or (content.get("data") is not None and content["data"].get("id")):
             if isinstance(response, Exception):
                 self.__gateway.send_rpc_reply(content["device"],
                                               content["data"]["id"],
                                               {content["data"]["method"]: str(response)})
             else:
                 self.__gateway.send_rpc_reply(content["device"],
                                               content["data"]["id"],
                                               response)
         log.debug("%r", response)
Example #25
0
 async def __call__(self, request: web.Request):
     json_data = await request.json()
     if not json_data and not len(request.query):
         return web.Response(status=415)
     endpoint_config = self.__endpoint['config']
     if request.method.upper() not in [
             method.upper() for method in endpoint_config['HTTPMethods']
     ]:
         return web.Response(status=405)
     try:
         log.info("CONVERTER CONFIG: %r", endpoint_config['converter'])
         converter = self.__endpoint['converter'](
             endpoint_config['converter'])
         data = json_data if json_data else dict(request.query)
         converted_data = converter.convert(
             config=endpoint_config['converter'], data=data)
         self.send_to_storage(self.__name, converted_data)
         log.info("CONVERTED_DATA: %r", converted_data)
         return web.Response(status=200)
     except Exception as e:
         log.exception("Error while post to anonymous handler: %s", e)
         return web.Response(status=500)
Example #26
0
 def scan_nodes_from_config(self):
     try:
         if self.__interest_nodes:
             for device_object in self.__interest_nodes:
                 for current_device in device_object:
                     try:
                         device_configuration = device_object[
                             current_device]
                         devices_info_array = self.__search_general_info(
                             device_configuration)
                         for device_info in devices_info_array:
                             if device_info is not None and device_info.get(
                                     "deviceNode") is not None:
                                 self.__search_nodes_and_subscribe(
                                     device_info)
                                 self.__save_methods(device_info)
                                 self.__search_attribute_update_variables(
                                     device_info)
                             else:
                                 log.error(
                                     "Device node is None, please check your configuration."
                                 )
                                 log.debug(
                                     "Current device node is: %s",
                                     str(
                                         device_configuration.get(
                                             "deviceNodePattern")))
                                 break
                     except BrokenPipeError:
                         log.debug("Broken Pipe. Connection lost.")
                     except OSError:
                         log.debug("Stop on scanning.")
                     except FuturesTimeoutError:
                         self.__check_connection()
                     except Exception as e:
                         log.exception(e)
             log.debug(self.__interest_nodes)
     except Exception as e:
         log.exception(e)
Example #27
0
    def __load_converters(self, connector, gateway):
        try:
            if self.config.get(UPLINK_PREFIX + CONVERTER_PARAMETER) is not None:
                converter = TBModuleLoader.import_module(connector.connector_type,
                                                         self.config[UPLINK_PREFIX + CONVERTER_PARAMETER])(self)
            else:
                converter = BytesModbusUplinkConverter({**self.config, 'deviceName': self.name})

            if self.config.get(DOWNLINK_PREFIX + CONVERTER_PARAMETER) is not None:
                downlink_converter = TBModuleLoader.import_module(connector.connector_type, self.config[
                    DOWNLINK_PREFIX + CONVERTER_PARAMETER])(self)
            else:
                downlink_converter = BytesModbusDownlinkConverter(self.config)

            if self.name not in gateway.get_devices():
                gateway.add_device(self.name, {CONNECTOR_PARAMETER: connector},
                                   device_type=self.config.get(DEVICE_TYPE_PARAMETER))

            self.config[UPLINK_PREFIX + CONVERTER_PARAMETER] = converter
            self.config[DOWNLINK_PREFIX + CONVERTER_PARAMETER] = downlink_converter
        except Exception as e:
            log.exception(e)
Example #28
0
    def poll_period_to_device(self,
                              config,
                              unit_id,
                              poll_type,
                              callback=None,
                              errback=None):
        current_time = time.time()
        device = config['config']
        try:
            if device.get(type) is not None:
                if config["next_" + poll_type + "_check"] < current_time:
                    #  Reading data from device
                    for interested_data in range(len(device[poll_type])):
                        current_data = device[poll_type][interested_data]
                        current_data["deviceName"] = device.get('deviceName')

                        def __internalCallback(response):
                            device_responses = {
                                "timeseries": {},
                                "attributes": {},
                            }
                            if not isinstance(response,
                                              ReadRegistersResponseBase
                                              ) and response.isError():
                                log.exception(response)
                            device_responses[poll_type][device["tag"]] = {
                                "data_sent": current_data,
                                "input_data": response
                            }
                            if callback is not None:
                                callback(device_responses)

                        _ = self._function_to_device(
                            current_data,
                            unit_id,
                            callback=__internalCallback,
                            errback=errback)
        except Exception as e:
            log.exception(e)
Example #29
0
 def scan_network(self):
     self._application.do_whois()
     log.debug("WhoIsRequest has been sent.")
     for device in self.__config_devices:
         try:
             if self._application.check_or_add(device):
                 for mapping_type in ["attributes", "timeseries"]:
                     for config in device[mapping_type]:
                         data_to_application = {
                             "device":
                             device,
                             "mapping_type":
                             mapping_type,
                             "config":
                             config,
                             "callback":
                             self.__bacnet_device_mapping_response_cb
                         }
                         self._application.do_read_property(
                             **data_to_application)
         except Exception as e:
             log.exception(e)
Example #30
0
    def server_side_rpc_handler(self, content):
        log.debug(
            "Modbus connector received rpc request for %s with content: %s",
            self.get_name(), content)
        rpc_command_config = self.__devices[
            content["device"]]["config"]["rpc"].get(
                content["data"].get("method"))
        if rpc_command_config.get('bit') is not None:
            rpc_command_config["functionCode"] = 6
            rpc_command_config["unitId"] = self.__devices[
                content["device"]]["config"]["unitId"]

        if rpc_command_config is not None:
            rpc_command_config["payload"] = self.__devices[
                content["device"]]["downlink_converter"].convert(
                    rpc_command_config, content)
            response = None
            try:
                response = self.__function_to_device(
                    rpc_command_config, rpc_command_config["unitId"])
            except Exception as e:
                log.exception(e)
            if response is not None:
                log.debug(response)
                if type(response) in (WriteMultipleRegistersResponse,
                                      WriteMultipleCoilsResponse,
                                      WriteSingleCoilResponse,
                                      WriteSingleRegisterResponse):
                    response = True
                else:
                    response = False
                log.debug(response)
                self.__gateway.send_rpc_reply(
                    content["device"], content["data"]["id"],
                    {content["data"]["method"]: response})
        else:
            log.error(
                "Received rpc request, but method %s not found in config for %s.",
                content["data"].get("method"), self.get_name())