# Path: thingsboard_gateway/connectors/connector.py
# class Connector(ABC):
#     def open(self):
#     def close(self):
#     def get_name(self):
#     def is_connected(self):
#     def on_attributes_update(self, content):
#     def server_side_rpc_handler(self, content):
# 
# Path: thingsboard_gateway/tb_utility/tb_loader.py
# class TBModuleLoader:
#     PATHS = []
#     LOADED_CONNECTORS = {}
# 
#     @staticmethod
#     def find_paths():
#         root_path = path.abspath(path.dirname(path.dirname(__file__)))
#         log.debug("Root path is: " + root_path)
#         if path.exists(DEB_INSTALLATION_EXTENSION_PATH):
#             log.debug("Debian installation extensions folder exists.")
#             TBModuleLoader.PATHS.append(DEB_INSTALLATION_EXTENSION_PATH)
#         TBModuleLoader.PATHS.append(root_path + EXTENSIONS_FOLDER)
#         TBModuleLoader.PATHS.append(root_path + CONNECTORS_FOLDER)
# 
#     @staticmethod
#     def import_module(extension_type, module_name):
#         if len(TBModuleLoader.PATHS) == 0:
#             TBModuleLoader.find_paths()
#         buffered_module_name = extension_type + module_name
#         if TBModuleLoader.LOADED_CONNECTORS.get(buffered_module_name) is not None:
#             return TBModuleLoader.LOADED_CONNECTORS[buffered_module_name]
#         try:
#             for current_path in TBModuleLoader.PATHS:
#                 current_extension_path = current_path + path.sep + extension_type
#                 if path.exists(current_extension_path):
#                     for file in listdir(current_extension_path):
#                         if not file.startswith('__') and file.endswith('.py'):
#                             try:
#                                 module_spec = spec_from_file_location(module_name, current_extension_path + path.sep + file)
#                                 log.debug(module_spec)
# 
#                                 if module_spec is None:
#                                     continue
# 
#                                 module = module_from_spec(module_spec)
#                                 module_spec.loader.exec_module(module)
#                                 for extension_class in getmembers(module, isclass):
#                                     if module_name in extension_class:
#                                         log.info("Import %s from %s.", module_name, current_extension_path)
#                                         TBModuleLoader.LOADED_CONNECTORS[buffered_module_name] = extension_class[1]
#                                         return extension_class[1]
#                             except ImportError:
#                                 continue
#         except Exception as e:
#             log.exception(e)


import time
import serial
from random import choice
from string import ascii_lowercase
from threading import Thread
from thingsboard_gateway.connectors.connector import Connector, log  # Import base class for connector and logger
from thingsboard_gateway.tb_utility.tb_loader import TBModuleLoader
                                                                         inter_byte_timeout=self.__config.get('inter_byte_timeout', None),
                                                                         exclusive=self.__config.get('exclusive', None))
                        time.sleep(.1)
                        if time.time() - connection_start > 10:  # Break connection try if it setting up for 10 seconds
                            log.error("Connection refused per timeout for device %s", self.__devices[device]["device_config"].get("name"))
                            break
            except serial.serialutil.SerialException:
                log.error("Port %s for device %s - not found", self.__config.get('port', '/dev/ttyUSB0'), device)
            except Exception as e:
                log.exception(e)
            else:  # if no exception handled - add device and change connection state
                self.__gateway.add_device(self.__devices[device]["device_config"]["name"], {"connector": self}, self.__devices[device]["device_config"]["type"])
                self.__connected = True

    def open(self):  # Function called by gateway on start
        self.stopped = False
        self.start()

    def get_name(self):  # Function used for logging, sending data and statistic
        return self.name

    def is_connected(self):  # Function for checking connection state
        return self.__connected

    def __load_converters(self, connector_type):  # Function for search a converter and save it.
        devices_config = self.__config.get('devices')
        try:
            if devices_config is not None:
                for device_config in devices_config:
                    if device_config.get('converter') is not None:

# Path: thingsboard_gateway/connectors/connector.py
# class Connector(ABC):
#     def open(self):
#     def close(self):
#     def get_name(self):
#     def is_connected(self):
#     def on_attributes_update(self, content):
#     def server_side_rpc_handler(self, content):
# 
# Path: thingsboard_gateway/tb_utility/tb_loader.py
# class TBModuleLoader:
#     PATHS = []
#     LOADED_CONNECTORS = {}
# 
#     @staticmethod
#     def find_paths():
#         root_path = path.abspath(path.dirname(path.dirname(__file__)))
#         log.debug("Root path is: " + root_path)
#         if path.exists(DEB_INSTALLATION_EXTENSION_PATH):
#             log.debug("Debian installation extensions folder exists.")
#             TBModuleLoader.PATHS.append(DEB_INSTALLATION_EXTENSION_PATH)
#         TBModuleLoader.PATHS.append(root_path + EXTENSIONS_FOLDER)
#         TBModuleLoader.PATHS.append(root_path + CONNECTORS_FOLDER)
# 
#     @staticmethod
#     def import_module(extension_type, module_name):
#         if len(TBModuleLoader.PATHS) == 0:
#             TBModuleLoader.find_paths()
#         buffered_module_name = extension_type + module_name
#         if TBModuleLoader.LOADED_CONNECTORS.get(buffered_module_name) is not None:
#             return TBModuleLoader.LOADED_CONNECTORS[buffered_module_name]
#         try:
#             for current_path in TBModuleLoader.PATHS:
#                 current_extension_path = current_path + path.sep + extension_type
#                 if path.exists(current_extension_path):
#                     for file in listdir(current_extension_path):
#                         if not file.startswith('__') and file.endswith('.py'):
#                             try:
#                                 module_spec = spec_from_file_location(module_name, current_extension_path + path.sep + file)
#                                 log.debug(module_spec)
# 
#                                 if module_spec is None:
#                                     continue
# 
#                                 module = module_from_spec(module_spec)
#                                 module_spec.loader.exec_module(module)
#                                 for extension_class in getmembers(module, isclass):
#                                     if module_name in extension_class:
#                                         log.info("Import %s from %s.", module_name, current_extension_path)
#                                         TBModuleLoader.LOADED_CONNECTORS[buffered_module_name] = extension_class[1]
#                                         return extension_class[1]
#                             except ImportError:
#                                 continue
#         except Exception as e:
#             log.exception(e)


# Path: thingsboard_gateway/extensions/serial/custom_serial_connector.py
import time
import serial
from random import choice
from string import ascii_lowercase
from threading import Thread
from thingsboard_gateway.connectors.connector import Connector, log  # Import base class for connector and logger
from thingsboard_gateway.tb_utility.tb_loader import TBModuleLoader

                                                                         inter_byte_timeout=self.__config.get('inter_byte_timeout', None),
                                                                         exclusive=self.__config.get('exclusive', None))
                        time.sleep(.1)
                        if time.time() - connection_start > 10:  # Break connection try if it setting up for 10 seconds
                            log.error("Connection refused per timeout for device %s", self.__devices[device]["device_config"].get("name"))
                            break
            except serial.serialutil.SerialException:
                log.error("Port %s for device %s - not found", self.__config.get('port', '/dev/ttyUSB0'), device)
            except Exception as e:
                log.exception(e)
            else:  # if no exception handled - add device and change connection state
                self.__gateway.add_device(self.__devices[device]["device_config"]["name"], {"connector": self}, self.__devices[device]["device_config"]["type"])
                self.__connected = True

    def open(self):  # Function called by gateway on start
        self.stopped = False
        self.start()

    def get_name(self):  # Function used for logging, sending data and statistic
        return self.name

    def is_connected(self):  # Function for checking connection state
        return self.__connected

    def __load_converters(self, connector_type):  # Function for search a converter and save it.
        devices_config = self.__config.get('devices')
        try:
            if devices_config is not None:
                for device_config in devices_config:
                    if device_config.get('converter') is not None:

                        converter = TBModuleLoader.import_module(connector_type, device_config['converter'])