11import asyncio
22import json
33import logging
4+ import ssl
45import time
56from collections .abc import Callable
67from dataclasses import dataclass
@@ -36,7 +37,7 @@ def __new__(cls, *args: Any, **kwargs: Any) -> "BillingClient":
3637 def __init__ (
3738 self ,
3839 broker_host : str ,
39- broker_port : int = 1883 ,
40+ broker_port : int = 8883 , # TLS 默认端口
4041 username : str | None = None ,
4142 password : str | None = None ,
4243 logger : logging .Logger | None = None ,
@@ -49,6 +50,7 @@ def __init__(
4950 self .broker_port = broker_port
5051 self .username = username
5152 self .password = password
53+
5254 self ._client : AsyncMQTTClient | None = None
5355 self ._is_connected = False
5456 # 用于缓存有效的 API keys,从 MQTT 推送中动态更新
@@ -65,6 +67,16 @@ def __init__(
6567 # 自动连接 MQTT
6668 self ._auto_connect ()
6769
70+ def _create_tls_context (self ) -> ssl .SSLContext :
71+ """创建默认的 TLS SSL 上下文"""
72+ # 创建 SSL 上下文,默认忽略证书验证
73+ context = ssl .SSLContext (ssl .PROTOCOL_TLS_CLIENT )
74+ context .minimum_version = ssl .TLSVersion .TLSv1_2
75+ context .check_hostname = False # MQTT 通常不使用主机名验证
76+ context .verify_mode = ssl .CERT_NONE # 忽略证书校验
77+
78+ return context
79+
6880 @classmethod
6981 def get_instance (cls ) -> "BillingClient" :
7082 """获取单例实例"""
@@ -92,24 +104,34 @@ def is_connected(self) -> bool:
92104 return self ._is_connected
93105
94106 async def connect (self ) -> None :
95- """连接到 MQTT 代理"""
107+ """连接到 MQTT 代理(默认使用 TLS) """
96108 async with self ._lock :
97109 if self ._is_connected :
98110 self ._logger .info ("BillingClient 已经连接,跳过重复连接" )
99111 return
100112
101113 try :
102- self ._client = AsyncMQTTClient (
103- hostname = self .broker_host ,
104- port = self .broker_port ,
105- username = self .username ,
106- password = self .password ,
114+ # 创建 TLS 上下文
115+ tls_context = self ._create_tls_context ()
116+
117+ # 配置 MQTT 客户端参数,默认使用 TLS
118+ client_kwargs = {
119+ "hostname" : self .broker_host ,
120+ "port" : self .broker_port ,
121+ "username" : self .username ,
122+ "password" : self .password ,
123+ "tls_context" : tls_context ,
124+ }
125+
126+ self ._logger .info (
127+ f"使用 TLS 连接到 MQTT 代理 { self .broker_host } :{ self .broker_port } "
107128 )
129+
130+ self ._client = AsyncMQTTClient (** client_kwargs )
108131 await self ._client .connect ()
109132 self ._is_connected = True
110- self ._logger .info (
111- f"已连接到 MQTT 代理 { self .broker_host } :{ self .broker_port } "
112- )
133+
134+ self ._logger .info ("已通过 TLS 连接到 MQTT 代理" )
113135
114136 # 订阅 Key 状态更新
115137 await self ._client .subscribe ("key-status-updates" )
0 commit comments