连接器加载流程:

    1. 遍历tb_gateway.yaml配置文件【connectors】配置的连接器,每次遍历做如下操作:
      1. 如果连接器的类型不是grpc,获取连接器对应的实现类添加到TBGatewayService里名称为_implemented_connectors的字典中,字典的键值为连接器的type
      2. 连接器的持久化键的获取
      3. 加载连接器的配置文件解析到临时变量connector_conf中
      4. 添加连接器的配置信息到TBGatewayService里名称为connectors_configs的字典中
    2. 保存连接器的持久化键,连接器类型为grpc才会有持久化键

    最终的connectors_configs配置数据格式如下:

    1. {
    2. "mqtt":[
    3. {
    4. "name":"MQTT Broker Connector",
    5. "config":{
    6. "mqtt-test.json":{
    7. "name":"MQTT Broker Connector",
    8. //mqtt-test.json配置文件里的相关的配置信息
    9. "broker":{},
    10. "mapping":{},
    11. "connectRequests":{},
    12. "disconnectRequests":{},
    13. "attributeUpdates":{},
    14. "serverSideRpc":{}
    15. }
    16. },
    17. "config_updated":{
    18. },
    19. "config_file_path":"mqtt-test.json",
    20. "grpc_key":None
    21. }
    22. ]
    23. }

    代码:tb_gateway_service.py:

    1. def _load_connectors(self):
    2. self.connectors_configs = {}
    3. # 加载连接器持久化键{"GRPC Connector 1":"AD5722c73E"}字典
    4. connectors_persistent_keys = self.__load_persistent_connector_keys()
    5. # 从配置文件读取连接器配置对象数组
    6. if self.__config.get("connectors"):
    7. # 遍历连接器
    8. for connector in self.__config['connectors']:
    9. try:
    10. # 连接器持久化键
    11. connector_persistent_key = None
    12. # 如果当前连接器的类型是grpc但是grpc的管理器为None报错并且continue继续遍历下一个连接器,__grpc_manager在TBGatewayService构造器里构造
    13. # self.__grpc_manager = TBGRPCServerManager(self, self.__grpc_config)
    14. if connector['type'] == "grpc" and self.__grpc_manager is None:
    15. log.error("Cannot load connector with name: %s and type grpc. GRPC server is disabled!", connector['name'])
    16. continue
    17. # 如果连接器的类型不是grpc
    18. if connector['type'] != "grpc":
    19. # 获取该类型的连接器的实现类
    20. connector_class = TBModuleLoader.import_module(connector['type'],
    21. self._default_connectors.get(connector['type'],
    22. connector.get('class')))
    23. # 添加连接器实现类到集合中,如{"mqtt":mqtt_connector_class}
    24. self._implemented_connectors[connector['type']] = connector_class
    25. # 如果连接器的类型是grpc,grpc连接器的属性实例,包含name、key、type、configuration:
    26. # {name: GRPC Connector 1,key: auto,type: grpc,configuration: grpc_connector_1.json}
    27. elif connector['type'] == "grpc":
    28. # 如果连接器的key是auto
    29. if connector.get('key') == "auto":
    30. # 如果从配置文件获取到了该连接器的持久化键,就赋值
    31. if connectors_persistent_keys and connectors_persistent_keys.get(connector['name']) is not None:
    32. connector_persistent_key = connectors_persistent_keys[connector['name']]
    33. # 没有获取到该连接器的持久化键,那么生成一个连接器持久化键,并且添加到连接器持久化键字典中,键名是连接器的名字
    34. else:
    35. connector_persistent_key = "".join(choice(hexdigits) for _ in range(10))
    36. connectors_persistent_keys[connector['name']] = connector_persistent_key
    37. # 连接器的类型不是auto那么久把连接器的key值作为该连接器的持久化键
    38. else:
    39. connector_persistent_key = connector['key']
    40. log.info("Connector key for GRPC connector with name [%s] is: [%s]", connector['name'], connector_persistent_key)
    41. # 得到连接器的配置文件路径
    42. config_file_path = self._config_dir + connector['configuration']
    43. connector_conf_file_data = ''
    44. # 打开连接器的配置文件解析配置文件信息到json对象,解析失败报异常
    45. with open(config_file_path, 'r', encoding="UTF-8") as conf_file:
    46. connector_conf_file_data = conf_file.read()
    47. connector_conf = connector_conf_file_data
    48. try:
    49. connector_conf = loads(connector_conf_file_data)
    50. except JSONDecodeError as e:
    51. log.debug(e)
    52. log.warning("Cannot parse connector configuration as a JSON, it will be passed as a string.")
    53. if not self.connectors_configs.get(connector['type']):
    54. self.connectors_configs[connector['type']] = []
    55. log.info("connectors_configs is %s", self.connectors_configs)
    56. # connectors_configs is {'mqtt': []}"
    57. # 如果连接器的类型不是grpc并且连机器的配置文件是字典类型的那么把连接器的配置数据字典添加name键,因为连接器的配置文件没有name键
    58. if connector['type'] != 'grpc' and isinstance(connector_conf, dict):
    59. connector_conf["name"] = connector['name']
    60. # 添加连接器的配置信息到连接器配置字典中 {'mqtt': [{'name': 'MQTT Broker Connector', 'config': {'mqtt-test.json': {...
    61. self.connectors_configs[connector['type']].append({"name": connector['name'],
    62. "config": {connector['configuration']: connector_conf} if connector[
    63. 'type'] != 'grpc' else connector_conf,
    64. "config_updated": stat(config_file_path),
    65. "config_file_path": config_file_path,
    66. "grpc_key": connector_persistent_key})
    67. log.info("connectors_configs is %s", self.connectors_configs)
    68. except Exception as e:
    69. log.exception("Error on loading connector: %r", e)
    70. # 保存连接器的持久化键,连接器类型为grpc才会有持久化键
    71. if connectors_persistent_keys:
    72. self.__save_persistent_keys(connectors_persistent_keys)
    73. else:
    74. log.error("Connectors - not found! Check your configuration!")
    75. self.__init_remote_configuration(force=True)
    76. log.info("Remote configuration is enabled forcibly!")