app.py 137 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600
  1. from flask import Flask, jsonify, request, abort
  2. from flask_cors import CORS
  3. from flask_socketio import SocketIO, emit
  4. import threading
  5. import time
  6. import json
  7. import os
  8. import logging
  9. import uuid
  10. # 配置文件路径
  11. SERIAL_CONFIG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'serial_config.json')
  12. # 导入配置
  13. from config import (
  14. MAX_BUFFER_SIZE,
  15. FLASK_SECRET_KEY,
  16. FLASK_DEBUG,
  17. FLASK_HOST,
  18. FLASK_PORT,
  19. LOG_LEVEL,
  20. LOG_FORMAT,
  21. LOG_FILE,
  22. SOCKETIO_ASYNC_MODE,
  23. SOCKETIO_ALLOWED_ORIGINS,
  24. DEFAULT_FORWARD_SERIAL_TO_MQTT,
  25. DEFAULT_FORWARD_MQTT_TO_SERIAL,
  26. DEFAULT_MQTT_PUBLISH_TOPIC,
  27. SOCKETIO_NAMESPACE_DATA,
  28. SOCKETIO_NAMESPACE_STATUS,
  29. SOCKETIO_NAMESPACE_CONTROL,
  30. ERROR_CODES,
  31. ERROR_MESSAGES,
  32. DEFAULT_CUSTOMER_ID,
  33. DEFAULT_DTU_ID,
  34. DTU_HEARTBEAT_INTERVAL,
  35. DTU_OFFLINE_TIMEOUT,
  36. DEFAULT_MQTT_TOPIC_PREFIX,
  37. DTU_REGISTRATION_TOPIC,
  38. DTU_STATUS_TOPIC,
  39. DTU_CONTROL_TOPIC,
  40. DTU_RESPONSE_TOPIC,
  41. DTU_EVENT_TOPIC,
  42. DTU_ALARM_TOPIC,
  43. DTU_BROADCAST_TOPIC,
  44. MAX_PANELS,
  45. MAX_PORTS_PER_PANEL,
  46. DHT11_ENABLED,
  47. DHT11_GPIO_PIN,
  48. DHT11_GPIO_CHIP,
  49. DHT11_POLL_INTERVAL,
  50. DHT11_SIMULATE
  51. )
  52. # 配置日志
  53. logging_config = {
  54. 'level': getattr(logging, LOG_LEVEL),
  55. 'format': LOG_FORMAT
  56. }
  57. if LOG_FILE:
  58. logging_config['filename'] = LOG_FILE
  59. logging.basicConfig(**logging_config)
  60. logger = logging.getLogger('serial_mqtt_gateway')
  61. from modules.serial_port import SerialPort
  62. from modules.mqtt_client import MQTTClient
  63. from modules.network_config import network_manager
  64. from modules.modbus_rtu import ModbusRTUClient, ANTENNA_ADDRESSES, AddressConfigProtocol, build_broadcast_query, build_confirm_address, build_assign_address
  65. from modules.dht11_sensor import DHT11Sensor
  66. app = Flask(__name__)
  67. app.config['SECRET_KEY'] = FLASK_SECRET_KEY
  68. # 配置CORS以允许nginx代理的前端访问
  69. CORS(app, resources={r"/api/*": {"origins": "*"}, r"/socket.io/*": {"origins": "*"}})
  70. # 初始化SocketIO
  71. socketio = SocketIO(
  72. app,
  73. cors_allowed_origins=SOCKETIO_ALLOWED_ORIGINS,
  74. async_mode=SOCKETIO_ASYNC_MODE,
  75. manage_session=False, # 禁用会话管理以提高性能
  76. ping_timeout=30, # 心跳超时时间
  77. ping_interval=25, # 心跳间隔
  78. logger=FLASK_DEBUG, # 根据Flask调试模式决定是否记录SocketIO日志
  79. engineio_logger=FLASK_DEBUG
  80. )
  81. # 初始化串口和MQTT客户端
  82. serial_client = SerialPort()
  83. mqtt_client = MQTTClient()
  84. modbus_client = ModbusRTUClient(serial_client)
  85. address_config = AddressConfigProtocol(serial_client)
  86. # 初始化 DHT11 传感器(后续在 __main__ 中设置回调并启动)
  87. dht11_sensor = None
  88. if DHT11_ENABLED and (DHT11_GPIO_PIN is not None or DHT11_SIMULATE):
  89. dht11_sensor = DHT11Sensor(
  90. gpio_pin=DHT11_GPIO_PIN,
  91. gpio_chip=DHT11_GPIO_CHIP,
  92. poll_interval=DHT11_POLL_INTERVAL,
  93. simulate=DHT11_SIMULATE
  94. )
  95. elif DHT11_ENABLED and DHT11_GPIO_PIN is None and not DHT11_SIMULATE:
  96. logger.warning("DHT11 已启用但未配置 GPIO pin (DHT11_GPIO_PIN),跳过本地传感器启动")
  97. # 转发标志
  98. forward_serial_to_mqtt = DEFAULT_FORWARD_SERIAL_TO_MQTT
  99. forward_mqtt_to_serial = DEFAULT_FORWARD_MQTT_TO_SERIAL
  100. mqtt_publish_topic = DEFAULT_MQTT_PUBLISH_TOPIC
  101. # DTU MQTT协议配置(运行时可修改)
  102. dtu_config = {
  103. 'topic_prefix': DEFAULT_MQTT_TOPIC_PREFIX,
  104. 'customer_id': DEFAULT_CUSTOMER_ID,
  105. 'dtu_id': DEFAULT_DTU_ID,
  106. 'firmware_version': 'v1.0.0',
  107. 'hardware_version': 'v1.0',
  108. 'heartbeat_interval': DTU_HEARTBEAT_INTERVAL,
  109. 'enabled': True
  110. }
  111. DTU_CONFIG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'dtu_config.json')
  112. def load_dtu_config():
  113. global dtu_config
  114. try:
  115. if os.path.exists(DTU_CONFIG_FILE):
  116. with open(DTU_CONFIG_FILE, 'r') as f:
  117. saved = json.load(f)
  118. dtu_config.update(saved)
  119. except Exception as e:
  120. logger.warning(f"加载DTU配置失败: {e}")
  121. def save_dtu_config():
  122. try:
  123. with open(DTU_CONFIG_FILE, 'w') as f:
  124. json.dump(dtu_config, f, indent=2)
  125. except Exception as e:
  126. logger.warning(f"保存DTU配置失败: {e}")
  127. # 端口状态追踪(用于事件检测)
  128. port_state = {} # {panel_id: {port_id: {'last_uid': str, 'expected_uid': str, 'alarm_count': int}}}
  129. # 面板配置(从地址配置模块加载)
  130. panel_config = {} # {panel_id: {'address': int, 'position': int, 'panel_uid': str}}
  131. # 数据存储缓冲区
  132. serial_data_buffer = []
  133. mqtt_data_buffer = []
  134. # 状态标志
  135. serial_status = False
  136. mqtt_status = False
  137. # 串口配置保存和加载函数
  138. def save_serial_config(port, baudrate=9600, timeout=1.0, bytesize=8, parity='N', stopbits=1):
  139. """保存串口配置"""
  140. config = {
  141. 'port': port,
  142. 'baudrate': baudrate,
  143. 'timeout': timeout,
  144. 'bytesize': bytesize,
  145. 'parity': parity,
  146. 'stopbits': stopbits
  147. }
  148. try:
  149. with open(SERIAL_CONFIG_FILE, 'w') as f:
  150. json.dump(config, f)
  151. logger.info(f"串口配置已保存: {port} @ {baudrate}")
  152. except Exception as e:
  153. logger.error(f"保存串口配置失败: {e}")
  154. def load_serial_config():
  155. """加载串口配置"""
  156. if os.path.exists(SERIAL_CONFIG_FILE):
  157. try:
  158. with open(SERIAL_CONFIG_FILE, 'r') as f:
  159. config = json.load(f)
  160. logger.info(f"已加载串口配置: {config.get('port')} @ {config.get('baudrate')}")
  161. return config
  162. except Exception as e:
  163. logger.error(f"加载串口配置失败: {e}")
  164. return None
  165. def auto_connect_serial():
  166. """自动连接上次使用的串口"""
  167. config = load_serial_config()
  168. if config and config.get('port'):
  169. port = config.get('port')
  170. baudrate = config.get('baudrate', 9600)
  171. timeout = config.get('timeout', 1.0)
  172. bytesize = config.get('bytesize', 8)
  173. parity = config.get('parity', 'N')
  174. stopbits = config.get('stopbits', 1)
  175. logger.info(f"尝试自动连接串口: {port} @ {baudrate}")
  176. success, message = serial_client.connect(port, baudrate=baudrate, timeout=timeout, bytesize=bytesize, parity=parity, stopbits=stopbits)
  177. if success:
  178. logger.info(f"自动连接串口成功: {port}")
  179. return True
  180. else:
  181. logger.warning(f"自动连接串口失败: {message}")
  182. return False
  183. # 客户端连接管理
  184. connected_clients = {
  185. 'data': set(),
  186. 'status': set(),
  187. 'control': set()
  188. }
  189. # 设置回调函数
  190. def serial_data_handler(data):
  191. """处理串口接收的数据"""
  192. try:
  193. timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
  194. serial_data_buffer.append({
  195. 'timestamp': timestamp,
  196. 'data': data,
  197. 'direction': 'in'
  198. })
  199. if len(serial_data_buffer) > MAX_BUFFER_SIZE:
  200. serial_data_buffer.pop(0)
  201. socketio.emit('serial_data', {
  202. 'timestamp': timestamp,
  203. 'data': data,
  204. 'direction': 'in'
  205. }, namespace=SOCKETIO_NAMESPACE_DATA)
  206. if forward_serial_to_mqtt and mqtt_client.get_status():
  207. success, msg = mqtt_client.publish(mqtt_publish_topic, data)
  208. if not success:
  209. logger.warning(f"串口数据转发到MQTT失败: {msg}")
  210. except Exception as e:
  211. logger.error(f"处理串口数据时出错: {str(e)}")
  212. def serial_send_handler(data):
  213. """处理串口发送的数据"""
  214. try:
  215. timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
  216. serial_data_buffer.append({
  217. 'timestamp': timestamp,
  218. 'data': data,
  219. 'direction': 'out'
  220. })
  221. if len(serial_data_buffer) > MAX_BUFFER_SIZE:
  222. serial_data_buffer.pop(0)
  223. socketio.emit('serial_data', {
  224. 'timestamp': timestamp,
  225. 'data': data,
  226. 'direction': 'out'
  227. }, namespace=SOCKETIO_NAMESPACE_DATA)
  228. except Exception as e:
  229. logger.error(f"处理串口发送数据时出错: {str(e)}")
  230. def serial_status_handler(status):
  231. """处理串口状态变化"""
  232. try:
  233. global serial_status
  234. serial_status = status
  235. # 通过WebSocket广播状态变化
  236. socketio.emit('serial_status', {
  237. 'connected': status
  238. }, namespace=SOCKETIO_NAMESPACE_STATUS)
  239. logger.info(f"串口状态更新: {'已连接' if status else '已断开'}")
  240. except Exception as e:
  241. logger.error(f"处理串口状态时出错: {str(e)}")
  242. def mqtt_data_handler(data):
  243. """处理MQTT接收的数据"""
  244. try:
  245. # 添加到缓冲区
  246. timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
  247. mqtt_data_buffer.append({
  248. 'timestamp': timestamp,
  249. 'topic': data['topic'],
  250. 'payload': data['payload']
  251. })
  252. # 保持缓冲区大小
  253. if len(mqtt_data_buffer) > MAX_BUFFER_SIZE:
  254. mqtt_data_buffer.pop(0)
  255. # 通过WebSocket广播数据
  256. socketio.emit('mqtt_data', {
  257. 'timestamp': timestamp,
  258. 'topic': data['topic'],
  259. 'payload': data['payload']
  260. }, namespace=SOCKETIO_NAMESPACE_DATA)
  261. # 如果启用了转发且串口已连接,转发数据到串口
  262. if forward_mqtt_to_serial and serial_client.get_status():
  263. success, msg = serial_client.send_data(data['payload'])
  264. if not success:
  265. logger.warning(f"MQTT数据转发到串口失败: {msg}")
  266. except Exception as e:
  267. logger.error(f"处理MQTT数据时出错: {str(e)}")
  268. def mqtt_status_handler(status):
  269. """处理MQTT状态变化"""
  270. try:
  271. global mqtt_status
  272. mqtt_status = status
  273. # 通过WebSocket广播状态变化
  274. socketio.emit('mqtt_status', {
  275. 'connected': status
  276. }, namespace=SOCKETIO_NAMESPACE_STATUS)
  277. logger.info(f"MQTT状态更新: {'已连接' if status else '已断开'}")
  278. # 如果MQTT连接成功且启用了DTU协议,发送注册消息和订阅控制主题
  279. if status and dtu_config.get('enabled'):
  280. socketio.sleep(1) # 等待连接稳定
  281. # 发送DTU注册消息
  282. dtu_register()
  283. # 订阅控制主题
  284. control_topic = build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'control')
  285. mqtt_client.subscribe(control_topic, qos=1)
  286. logger.info(f"已订阅控制主题: {control_topic}")
  287. # 订阅广播主题 (DTU发现 7.14 和批量配置 7.15)
  288. discover_topic = build_dtu_topic('broadcast', 'dtu', 'discover')
  289. config_topic = build_dtu_topic('broadcast', 'dtu', 'config')
  290. mqtt_client.subscribe(discover_topic, qos=1)
  291. mqtt_client.subscribe(config_topic, qos=1)
  292. logger.info(f"已订阅广播主题: {discover_topic}, {config_topic}")
  293. except Exception as e:
  294. logger.error(f"处理MQTT状态时出错: {str(e)}")
  295. # ========== DTU MQTT协议处理函数 ==========
  296. def build_dtu_topic(*parts):
  297. """构建DTU MQTT主题"""
  298. prefix = dtu_config.get('topic_prefix', '线架系统')
  299. return '/'.join([prefix] + list(parts))
  300. def dtu_register(discovery_request_id=None):
  301. """发送DTU注册消息"""
  302. if not mqtt_client.get_status():
  303. logger.warning("MQTT未连接,无法发送注册消息")
  304. return False
  305. try:
  306. # 加载面板配置
  307. devices = address_config.get_stored_devices()
  308. # 优先使用 dtu_config 中预设的 panel_id 映射 (uid_hex -> panel_id)
  309. panel_id_map = dtu_config.get('panel_id_mapping', {}) or {}
  310. panels = []
  311. panel_id = 1
  312. for uid_hex, addr in devices.items():
  313. custom_id = panel_id_map.get(uid_hex) or panel_id_map.get(addr)
  314. if custom_id:
  315. pid = str(custom_id)
  316. else:
  317. pid = f"PANEL_{dtu_config['dtu_id']}_{addr}"
  318. panels.append({
  319. 'panel_id': pid,
  320. 'address': addr,
  321. 'position': panel_id
  322. })
  323. panel_id += 1
  324. # 检测网络类型
  325. network_type = 'ethernet'
  326. signal_strength = None
  327. try:
  328. interfaces = network_manager.get_status().get('interfaces', {})
  329. for name, info in interfaces.items():
  330. if name in ('lo', 'docker0') or name.startswith(('br-', 'veth')):
  331. continue
  332. if info.get('status') != 'UP':
  333. continue
  334. if name.startswith(('wlan', 'wlp')):
  335. network_type = 'wifi'
  336. # 读取信号强度 (dBm, 越接近 0 越强)
  337. try:
  338. import re
  339. with open('/proc/net/wireless') as f:
  340. for line in f.readlines()[2:]:
  341. m = re.match(r'\s*(\S+):.*\s(\d+)\.\s+(-?\d+)\.', line)
  342. if m:
  343. signal_strength = int(m.group(3))
  344. break
  345. except Exception:
  346. pass
  347. elif name.startswith(('wwan', 'ppp', 'usb', 'eth')):
  348. # 移动网卡
  349. if name.startswith(('wwan', 'ppp', 'usb')):
  350. network_type = 'cellular'
  351. break
  352. except Exception:
  353. pass
  354. payload = {
  355. 'msg_id': f"reg_{int(time.time() * 1000)}_{uuid.uuid4().hex[:6]}",
  356. 'timestamp': int(time.time() * 1000),
  357. 'dtu_id': dtu_config['dtu_id'],
  358. 'type': 'REGISTER',
  359. 'payload': {
  360. 'firmware_version': dtu_config.get('firmware_version', 'v1.0.0'),
  361. 'hardware_version': dtu_config.get('hardware_version', 'v1.0'),
  362. 'panel_count': len(panels),
  363. 'network_type': network_type,
  364. 'signal_strength': signal_strength,
  365. 'uptime': int(time.time() * 1000),
  366. 'panels': panels,
  367. 'discovery_request_id': discovery_request_id
  368. }
  369. }
  370. if discovery_request_id:
  371. payload['payload']['discovery_request_id'] = discovery_request_id
  372. topic = build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'register')
  373. success, msg = mqtt_client.publish(topic, json.dumps(payload), qos=1)
  374. if success:
  375. logger.info(f"DTU注册消息已发送: {topic}")
  376. else:
  377. logger.error(f"DTU注册消息发送失败: {msg}")
  378. return success
  379. except Exception as e:
  380. logger.error(f"发送DTU注册消息失败: {str(e)}")
  381. return False
  382. _discover_dedup = {}
  383. def handle_broadcast_discover(payload):
  384. """处理广播发现消息 (7.14)"""
  385. try:
  386. if not isinstance(payload, dict) or payload.get('type') != 'DISCOVER':
  387. return
  388. p = payload.get('payload', {})
  389. cust_id = p.get('customer_id', '')
  390. if cust_id and cust_id != dtu_config.get('customer_id'):
  391. return
  392. request_id = p.get('request_id', '')
  393. now = time.time()
  394. if request_id and request_id in _discover_dedup:
  395. if now - _discover_dedup[request_id] < 60:
  396. return
  397. _discover_dedup[request_id] = now
  398. # 清理超过 60s 的旧条目,防止内存泄漏
  399. if len(_discover_dedup) > 256:
  400. for k in list(_discover_dedup.keys()):
  401. if now - _discover_dedup[k] > 60:
  402. _discover_dedup.pop(k, None)
  403. logger.info(f"收到DISCOVER广播,响应注册消息 (request_id={request_id})")
  404. import random
  405. delay = random.uniform(0, 3.0)
  406. time.sleep(delay)
  407. dtu_register(discovery_request_id=request_id)
  408. dtu_publish_status()
  409. except Exception as e:
  410. logger.error(f"处理广播发现消息失败: {str(e)}")
  411. def handle_broadcast_config(payload):
  412. """处理广播批量配置消息 (7.15)"""
  413. try:
  414. if isinstance(payload, dict) and payload.get('type') == 'CONFIG':
  415. cfg = payload.get('payload', {})
  416. cust_id = cfg.get('customer_id', '')
  417. if cust_id and cust_id != dtu_config.get('customer_id'):
  418. return
  419. config_version = cfg.get('config_version', '')
  420. force_apply = cfg.get('force_apply', False)
  421. items = cfg.get('items', {})
  422. local_version = dtu_config.get('config_version', '')
  423. incoming_msg_id = payload.get('msg_id', '')
  424. if local_version == config_version and not force_apply:
  425. logger.info(f"配置版本 {config_version} 已存在,跳过")
  426. _send_config_response(config_version, [], True, 1011, incoming_msg_id)
  427. return
  428. valid_ranges = {
  429. 'heartbeat_interval': (10, 3600),
  430. 'poll_interval_ms': (100, 10000),
  431. 'modbus_timeout_ms': (200, 5000),
  432. 'mqtt_keepalive': (10, 300),
  433. 'event_debounce_ms': (0, 5000),
  434. }
  435. applied = []
  436. for key, val in items.items():
  437. if key in valid_ranges:
  438. lo, hi = valid_ranges[key]
  439. if not (lo <= val <= hi):
  440. _send_config_response(config_version, applied, False, 1012, incoming_msg_id)
  441. return
  442. if key == 'heartbeat_interval':
  443. dtu_config['heartbeat_interval'] = val
  444. elif key == 'mqtt_keepalive':
  445. dtu_config['mqtt_keepalive'] = val
  446. elif key == 'event_debounce_ms':
  447. dtu_config['event_debounce_ms'] = val
  448. elif key == 'poll_interval_ms':
  449. dtu_config['poll_interval_ms'] = val
  450. elif key == 'modbus_timeout_ms':
  451. dtu_config['modbus_timeout_ms'] = val
  452. applied.append(key)
  453. elif key in ('alarm_enabled',):
  454. dtu_config['alarm_enabled'] = bool(val)
  455. applied.append(key)
  456. else:
  457. _send_config_response(config_version, applied, False, 1013, incoming_msg_id)
  458. return
  459. if applied:
  460. dtu_config['config_version'] = config_version
  461. try:
  462. save_dtu_config()
  463. except Exception as e:
  464. logger.error(f"配置写入持久化失败: {e}")
  465. _send_config_response(config_version, applied, False, 1014, incoming_msg_id)
  466. return
  467. _send_config_response(config_version, applied, True, 0, incoming_msg_id)
  468. except Exception as e:
  469. logger.error(f"处理广播配置消息失败: {str(e)}")
  470. def _send_config_response(config_version, applied_items, success, error_code, original_msg_id=''):
  471. """发送批量配置响应 (随机 0-2000ms 延迟避免广播风暴)"""
  472. import time as _t, json as _j, random as _r
  473. delay = _r.uniform(0, 2.0)
  474. def _delayed_publish():
  475. _t.sleep(delay)
  476. topic = build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'response')
  477. payload = {
  478. 'msg_id': f"rsp_cfg_{int(_t.time() * 1000)}",
  479. 'timestamp': int(_t.time() * 1000),
  480. 'dtu_id': dtu_config['dtu_id'],
  481. 'type': 'RESPONSE',
  482. 'payload': {
  483. 'original_msg_id': original_msg_id or f"cfg_{config_version}",
  484. 'command': 'BROADCAST_CONFIG',
  485. 'success': success,
  486. 'result': {
  487. 'applied_version': config_version,
  488. 'applied_items': applied_items,
  489. 'restart_required': False
  490. } if success else None,
  491. 'error_code': error_code,
  492. 'error_message': get_ota_error_message(error_code) if error_code and error_code >= 1000 else None
  493. }
  494. }
  495. mqtt_client.publish(topic, _j.dumps(payload), qos=1)
  496. # 异步执行避免阻塞 MQTT 主循环
  497. threading.Thread(target=_delayed_publish, daemon=True).start()
  498. def dtu_publish_status(force=False):
  499. """发送DTU状态/心跳消息
  500. Args:
  501. force: 保留参数。事件/告警/查询触发时传入 True,用于立即上报(区别于定时心跳)
  502. """
  503. if not mqtt_client.get_status() or not dtu_config.get('enabled'):
  504. return False
  505. # 调试日志: 区分定时 vs 触发上报
  506. if force:
  507. logger.debug("dtu_publish_status(force=True) - 事件触发立即上报")
  508. try:
  509. # panel_online 计数: 在最近 60s 内所有 24 个端口都被成功轮询过
  510. # 严格语义: 全部 24 端口在最近一轮 poll 周期内被 poll 成功 → online
  511. now_ms = int(time.time() * 1000)
  512. threshold_ms = 60_000 # 60 秒未轮询视为 offline
  513. poll_ok = 0
  514. for pid, cfg in panel_config.items():
  515. ps = port_state.get(pid, {})
  516. expected_ports = cfg.get('port_count', 24)
  517. polled_recently = sum(
  518. 1 for p in ps.values()
  519. if p.get('last_polled_at') and (now_ms - p.get('last_polled_at', 0)) < threshold_ms
  520. )
  521. if polled_recently >= expected_ports:
  522. poll_ok += 1
  523. panel_online = poll_ok
  524. panel_offline = max(0, len(panel_config) - panel_online)
  525. # 检查串口状态
  526. serial_st = serial_client.get_status()
  527. rs485_status = 'normal' if (isinstance(serial_st, dict) and serial_st.get('connected', False)) else 'error'
  528. # 网络状态: 检查实际接口 UP 状态
  529. # 规则: 有线 (eth*/wlan*) UP → online; 仅 wifi 信号弱 (无 link/低质量) → weak; 否则 offline
  530. network_status = 'offline'
  531. try:
  532. interfaces = network_manager.get_status().get('interfaces', {})
  533. real_ifs = {i: s for i, s in interfaces.items()
  534. if s.get('status') == 'UP'
  535. and i not in ('lo', 'docker0')
  536. and not i.startswith(('br-', 'veth'))}
  537. if real_ifs:
  538. # 优先有线连接
  539. if any(i.startswith(('eth', 'en')) for i in real_ifs):
  540. network_status = 'online'
  541. else:
  542. # 仅无线: 检查信号强度 (Linux: /proc/net/wireless)
  543. try:
  544. import re
  545. with open('/proc/net/wireless') as f:
  546. lines = f.readlines()
  547. quality = None
  548. for line in lines[2:]: # 跳过表头
  549. m = re.match(r'\s*(\S+):.*\s(\d+)\.\s+(\d+)\.\s+(\d+)', line)
  550. if m:
  551. # link quality (字段 2, 0-70); signal level (字段 3, dBm, 越低越差)
  552. link = int(m.group(2))
  553. sig = int(m.group(3))
  554. # 估算: link < 30 或 sig < -75 dBm 视为弱
  555. if quality is None or link < quality:
  556. quality = link
  557. network_status = 'weak' if (quality is not None and quality < 30) else 'online'
  558. except Exception:
  559. network_status = 'online'
  560. except Exception:
  561. network_status = 'offline'
  562. # 屏幕连接: 检查 /dev/ttyUSB* 或专用 screen 串口是否打开
  563. # 约定: 如果存在 screen 串口路径配置且对应端口处于已连接 → true
  564. screen_connected = False
  565. try:
  566. screen_port = dtu_config.get('screen_serial_port')
  567. if screen_port and isinstance(serial_st, dict):
  568. active = serial_st.get('port') == screen_port and serial_st.get('connected', False)
  569. screen_connected = active
  570. except Exception:
  571. pass
  572. # CPU/内存使用率 (Linux 才有意义)
  573. cpu_usage = None
  574. memory_usage = None
  575. dtu_temperature = None
  576. try:
  577. import psutil
  578. cpu_usage = psutil.cpu_percent(interval=None)
  579. memory_usage = psutil.virtual_memory().percent
  580. # 主板温度: 优先 psutil.sensors_temperatures
  581. try:
  582. temps = psutil.sensors_temperatures(fahrenheit=False) or {}
  583. for chip_name, entries in temps.items():
  584. for entry in entries:
  585. if entry.current and entry.current > 0:
  586. dtu_temperature = round(entry.current, 1)
  587. break
  588. if dtu_temperature is not None:
  589. break
  590. except Exception:
  591. pass
  592. # 回退: 直接读 /sys/class/thermal/thermal_zone*/temp
  593. if dtu_temperature is None:
  594. import glob as _glob
  595. for tz in sorted(_glob.glob('/sys/class/thermal/thermal_zone*/temp')):
  596. try:
  597. with open(tz) as f:
  598. v = int(f.read().strip())
  599. if v > 0:
  600. dtu_temperature = round(v / 1000.0, 1)
  601. break
  602. except Exception:
  603. continue
  604. except Exception:
  605. pass
  606. # 优先使用外部上报的 dtu_temperature (来自 MQTT/RS485 传感器)
  607. dtu_temperature = env_sensor_data.get('dtu_temperature') or dtu_temperature
  608. payload = {
  609. 'msg_id': f"hbt_{int(time.time() * 1000)}_{uuid.uuid4().hex[:6]}",
  610. 'timestamp': int(time.time() * 1000),
  611. 'dtu_id': dtu_config['dtu_id'],
  612. 'type': 'STATUS',
  613. 'payload': {
  614. 'cpu_usage': cpu_usage,
  615. 'memory_usage': memory_usage,
  616. 'temperature': dtu_temperature,
  617. 'network_status': network_status,
  618. 'panel_online': panel_online,
  619. 'panel_offline': panel_offline,
  620. 'screen_connected': screen_connected,
  621. 'mqtt_connected': mqtt_client.get_status().get('connected', False) if isinstance(mqtt_client.get_status(), dict) else bool(mqtt_client.get_status()),
  622. 'rs485_status': rs485_status
  623. }
  624. }
  625. topic = build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'status')
  626. success, _ = mqtt_client.publish(topic, json.dumps(payload), qos=1)
  627. return success
  628. except Exception as e:
  629. logger.error(f"发送DTU状态消息失败: {str(e)}")
  630. return False
  631. def dtu_publish_event(panel_id, port_id, event_type, jumper_uid, previous_jumper_uid=None):
  632. """发送端口事件消息"""
  633. if not mqtt_client.get_status() or not dtu_config.get('enabled'):
  634. return False
  635. try:
  636. payload = {
  637. 'msg_id': f"evt_{int(time.time() * 1000)}",
  638. 'timestamp': int(time.time() * 1000),
  639. 'dtu_id': dtu_config['dtu_id'],
  640. 'type': 'EVENT',
  641. 'payload': {
  642. 'panel_id': panel_id,
  643. 'port_id': port_id,
  644. 'event_type': event_type,
  645. 'event_id': f"evt_{uuid.uuid4().hex[:8]}",
  646. 'jumper_uid': jumper_uid,
  647. 'previous_jumper_uid': previous_jumper_uid
  648. }
  649. }
  650. topic = build_dtu_topic(dtu_config['customer_id'], 'patchpanel', dtu_config['dtu_id'], panel_id, 'event')
  651. success, _ = mqtt_client.publish(topic, json.dumps(payload), qos=1)
  652. if success:
  653. logger.info(f"端口事件已发送: {panel_id}:{port_id} - {event_type}")
  654. # 记录到事件历史
  655. port_event_history.append({
  656. 'timestamp': int(time.time() * 1000),
  657. 'panel_id': panel_id,
  658. 'port_id': port_id,
  659. 'event_type': event_type,
  660. 'jumper_uid': jumper_uid,
  661. 'previous_jumper_uid': previous_jumper_uid
  662. })
  663. # 限制历史记录数量
  664. if len(port_event_history) > 1000:
  665. port_event_history[:] = port_event_history[-1000:]
  666. # 事件驱动: 立即上报一次 status (符合 7.4 "状态变化时立即上报")
  667. try:
  668. dtu_publish_status(force=True)
  669. except Exception:
  670. pass
  671. return success
  672. except Exception as e:
  673. logger.error(f"发送端口事件失败: {str(e)}")
  674. return False
  675. def dtu_publish_alarm(panel_id, port_id, alarm_type, expected_jumper_uid, actual_jumper_uid, severity='WARNING'):
  676. """发送非法告警消息"""
  677. if not mqtt_client.get_status() or not dtu_config.get('enabled'):
  678. return False
  679. try:
  680. description = f"端口{port_id}期望跳线{expected_jumper_uid},实际{'未读到' if not actual_jumper_uid else actual_jumper_uid}"
  681. payload = {
  682. 'msg_id': f"alm_{int(time.time() * 1000)}",
  683. 'timestamp': int(time.time() * 1000),
  684. 'dtu_id': dtu_config['dtu_id'],
  685. 'type': 'ALARM',
  686. 'payload': {
  687. 'panel_id': panel_id,
  688. 'port_id': port_id,
  689. 'alarm_type': alarm_type,
  690. 'severity': severity,
  691. 'expected_jumper_uid': expected_jumper_uid,
  692. 'actual_jumper_uid': actual_jumper_uid,
  693. 'description': description
  694. }
  695. }
  696. topic = build_dtu_topic(dtu_config['customer_id'], 'patchpanel', dtu_config['dtu_id'], panel_id, 'alarm')
  697. success, _ = mqtt_client.publish(topic, json.dumps(payload), qos=1)
  698. if success:
  699. logger.warning(f"非法告警已发送: {panel_id}:{port_id} - {alarm_type}")
  700. # 记录到事件历史
  701. port_event_history.append({
  702. 'timestamp': int(time.time() * 1000),
  703. 'panel_id': panel_id,
  704. 'port_id': port_id,
  705. 'event_type': 'ALARM',
  706. 'alarm_type': alarm_type,
  707. 'expected_jumper_uid': expected_jumper_uid,
  708. 'actual_jumper_uid': actual_jumper_uid
  709. })
  710. # 限制历史记录数量
  711. if len(port_event_history) > 1000:
  712. port_event_history[:] = port_event_history[-1000:]
  713. # 事件驱动: 告警后立即上报一次 status
  714. try:
  715. dtu_publish_status(force=True)
  716. except Exception:
  717. pass
  718. return success
  719. except Exception as e:
  720. logger.error(f"发送非法告警失败: {str(e)}")
  721. return False
  722. def dtu_publish_panel_status(panel_id, address, ports_data):
  723. """发送配线架状态消息 (7.7)"""
  724. if not mqtt_client.get_status() or not dtu_config.get('enabled'):
  725. return False
  726. try:
  727. topic = build_dtu_topic(dtu_config['customer_id'], 'patchpanel', dtu_config['dtu_id'], panel_id, 'status')
  728. payload = {
  729. 'msg_id': f"pst_{int(time.time() * 1000)}",
  730. 'timestamp': int(time.time() * 1000),
  731. 'dtu_id': dtu_config['dtu_id'],
  732. 'type': 'STATUS',
  733. 'payload': {
  734. 'panel_id': panel_id,
  735. 'position': panel_config.get(panel_id, {}).get('position', 0),
  736. 'address': address,
  737. 'online': True,
  738. 'last_poll_time': int(time.time() * 1000),
  739. 'ports': ports_data
  740. }
  741. }
  742. mqtt_client.publish(topic, json.dumps(payload), qos=0)
  743. return True
  744. except Exception as e:
  745. logger.error(f"发送面板状态失败: {str(e)}")
  746. return False
  747. def dtu_publish_jumper_status():
  748. """发送跳线状态汇总 (7.8) - STATUS envelope with panels[] array"""
  749. if not mqtt_client.get_status() or not dtu_config.get('enabled'):
  750. return False
  751. try:
  752. panels_arr = []
  753. for panel_id, cfg in panel_config.items():
  754. ports_arr = []
  755. ps = port_state.get(panel_id, {})
  756. for port_id in range(1, 25):
  757. p = ps.get(port_id, {})
  758. last_uid = p.get('last_uid')
  759. expected_uid = p.get('expected_uid')
  760. last_polled = p.get('last_polled_at')
  761. if not last_polled:
  762. status = 'UNKNOWN'
  763. elif last_uid is None:
  764. status = 'DISCONNECTED'
  765. if expected_uid:
  766. status = 'ILLEGAL'
  767. elif expected_uid and last_uid != expected_uid:
  768. status = 'ILLEGAL'
  769. else:
  770. status = 'CONNECTED'
  771. ports_arr.append({
  772. 'port_id': port_id,
  773. 'status': status,
  774. 'jumper_uid': last_uid
  775. })
  776. panels_arr.append({
  777. 'panel_id': panel_id,
  778. 'position': cfg.get('position', 0),
  779. 'ports': ports_arr
  780. })
  781. topic = build_dtu_topic(dtu_config['customer_id'], 'jumper', dtu_config['dtu_id'], 'status')
  782. payload = {
  783. 'msg_id': f"jmp_{int(time.time() * 1000)}",
  784. 'timestamp': int(time.time() * 1000),
  785. 'dtu_id': dtu_config['dtu_id'],
  786. 'type': 'STATUS',
  787. 'payload': {'panels': panels_arr}
  788. }
  789. mqtt_client.publish(topic, json.dumps(payload), qos=0)
  790. return True
  791. except Exception as e:
  792. logger.error(f"发送跳线状态汇总失败: {str(e)}")
  793. return False
  794. _env_sensor_data = {
  795. 'temperature': None,
  796. 'humidity': None,
  797. 'sensor_update_time': None
  798. }
  799. def update_env_sensor_data(temperature, humidity, dtu_temperature=None, sensor_update_time=None):
  800. """更新环境传感器数据 - 委托给完整实现(带历史和告警)"""
  801. update_env_sensor_data_full(temperature, humidity, dtu_temperature, sensor_update_time)
  802. def dtu_publish_env_sensor():
  803. """发送环境传感器数据 (7.9) - STATUS envelope"""
  804. if not mqtt_client.get_status() or not dtu_config.get('enabled'):
  805. return False
  806. try:
  807. topic = build_dtu_topic(dtu_config['customer_id'], 'env', dtu_config['dtu_id'], 'sensor')
  808. payload = {
  809. 'msg_id': f"sen_{int(time.time() * 1000)}",
  810. 'timestamp': int(time.time() * 1000),
  811. 'dtu_id': dtu_config['dtu_id'],
  812. 'type': 'STATUS',
  813. 'payload': {
  814. 'temperature': _env_sensor_data.get('temperature'),
  815. 'humidity': _env_sensor_data.get('humidity'),
  816. 'sensor_update_time': _env_sensor_data.get('sensor_update_time')
  817. }
  818. }
  819. mqtt_client.publish(topic, json.dumps(payload), qos=0)
  820. return True
  821. except Exception as e:
  822. logger.error(f"发送环境传感器数据失败: {str(e)}")
  823. return False
  824. def dtu_handle_control(topic, payload):
  825. """处理下行控制指令"""
  826. try:
  827. if not dtu_config.get('enabled'):
  828. return
  829. command = payload.get('payload', {}).get('command')
  830. target = payload.get('payload', {}).get('target')
  831. params = payload.get('payload', {}).get('params', {})
  832. logger.info(f"收到控制指令: command={command}, target={target}")
  833. response_payload = {
  834. 'msg_id': f"rsp_{int(time.time() * 1000)}_{uuid.uuid4().hex[:6]}",
  835. 'timestamp': int(time.time() * 1000),
  836. 'dtu_id': dtu_config['dtu_id'],
  837. 'type': 'RESPONSE',
  838. 'payload': {
  839. 'original_msg_id': payload.get('msg_id'),
  840. 'command': command,
  841. 'success': True,
  842. 'result': {},
  843. 'error_code': 0,
  844. 'error_message': None
  845. }
  846. }
  847. topic_response_dtu = build_dtu_topic(
  848. dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'response')
  849. # 处理各命令
  850. if command == 'SET_PORT_LED':
  851. # 设置端口LED
  852. port_id = params.get('port_id')
  853. led_mode = params.get('led_mode', 'OFF')
  854. # 参数校验
  855. if port_id is None or not (1 <= int(port_id) <= 24):
  856. response_payload['payload']['success'] = False
  857. response_payload['payload']['error_code'] = 1003
  858. response_payload['payload']['error_message'] = f"端口号非法: {port_id}"
  859. mqtt_client.publish(topic_response_dtu, json.dumps(response_payload), qos=1)
  860. return
  861. if led_mode not in ('OFF', 'BLINK_RED', 'BLINK_GREEN', 'BLINK_BLUE'):
  862. response_payload['payload']['success'] = False
  863. response_payload['payload']['error_code'] = 1004
  864. response_payload['payload']['error_message'] = f"LED模式非法: {led_mode}"
  865. mqtt_client.publish(topic_response_dtu, json.dumps(response_payload), qos=1)
  866. return
  867. # LED模式映射
  868. led_mode_map = {'OFF': 0, 'BLINK_RED': 1, 'BLINK_GREEN': 2, 'BLINK_BLUE': 3}
  869. color = led_mode_map.get(led_mode, 0)
  870. # 查找设备地址
  871. device_address = 1 # 默认
  872. for panel_id, cfg in panel_config.items():
  873. if panel_id == target:
  874. device_address = cfg.get('address', 1)
  875. break
  876. result = modbus_client.set_rgb_led(device_address, port_id, color)
  877. response_payload['payload']['success'] = 'error' not in result
  878. response_payload['payload']['result'] = result
  879. if 'error' in result:
  880. response_payload['payload']['error_code'] = 1005
  881. response_payload['payload']['error_message'] = result['error']
  882. elif command == 'QUERY_DTU_STATUS':
  883. # 查询DTU状态
  884. dtu_publish_status(force=True)
  885. elif command == 'SYNC_PORT_MAPPING':
  886. # 同步单端口期望映射
  887. port_id = params.get('port_id')
  888. jumper_uid = params.get('jumper_uid')
  889. if port_id is None or target is None or target not in panel_config:
  890. response_payload['payload']['success'] = False
  891. response_payload['payload']['error_code'] = 1006 if port_id is None else 1002
  892. response_payload['payload']['error_message'] = "参数缺失" if port_id is None else f"目标面板不存在: {target}"
  893. mqtt_client.publish(topic_response_dtu, json.dumps(response_payload), qos=1)
  894. return
  895. if target not in port_state:
  896. port_state[target] = {}
  897. if port_id not in port_state[target]:
  898. port_state[target][port_id] = {'last_uid': None, 'expected_uid': None, 'alarm_count': 0}
  899. port_state[target][port_id]['expected_uid'] = jumper_uid
  900. save_dtu_config()
  901. elif command == 'SYNC_ALL_MAPPING':
  902. # 批量同步期望映射
  903. mappings = params.get('mappings', [])
  904. if not isinstance(mappings, list):
  905. response_payload['payload']['success'] = False
  906. response_payload['payload']['error_code'] = 1006
  907. response_payload['payload']['error_message'] = "mappings 字段格式错误"
  908. mqtt_client.publish(topic_response_dtu, json.dumps(response_payload), qos=1)
  909. return
  910. try:
  911. for mapping in mappings:
  912. panel_id = mapping.get('panel_id')
  913. port_id = mapping.get('port_id')
  914. jumper_uid = mapping.get('jumper_uid')
  915. if panel_id not in panel_config:
  916. raise ValueError(f"目标面板不存在: {panel_id}")
  917. if panel_id not in port_state:
  918. port_state[panel_id] = {}
  919. if port_id not in port_state[panel_id]:
  920. port_state[panel_id][port_id] = {'last_uid': None, 'expected_uid': None, 'alarm_count': 0}
  921. port_state[panel_id][port_id]['expected_uid'] = jumper_uid
  922. save_dtu_config()
  923. except Exception as e:
  924. response_payload['payload']['success'] = False
  925. response_payload['payload']['error_code'] = 1007
  926. response_payload['payload']['error_message'] = f"同步映射失败: {e}"
  927. mqtt_client.publish(topic_response_dtu, json.dumps(response_payload), qos=1)
  928. return
  929. elif command == 'REBOOT':
  930. # 重启DTU: 1s 延迟后执行 reboot
  931. import subprocess
  932. logger.warning(f"MQTT REBOOT 命令收到,1 秒后执行系统重启")
  933. threading.Thread(target=lambda: (
  934. time.sleep(1),
  935. subprocess.run(['reboot'], capture_output=True)
  936. ), daemon=True).start()
  937. response_payload['payload']['result'] = {'message': 'Reboot scheduled in 1s'}
  938. elif command == 'READ_PANEL_STATUS':
  939. # 读取面板状态
  940. # 读取面板的多个寄存器获取状态信息
  941. # 寄存器地址定义: 0x0000=运行状态, 0x0001=LED控制, 0x0002-0x0009=天线卡状态
  942. device_address = 1
  943. for panel_id, cfg in panel_config.items():
  944. if panel_id == target:
  945. device_address = cfg.get('address', 1)
  946. break
  947. # 读取面板状态寄存器 (地址0x0000开始,读取10个寄存器)
  948. status_result = modbus_client.read_holding_registers(device_address, 0x0000, 10)
  949. # 解析状态
  950. registers = status_result.get('registers', [])
  951. panel_status = {
  952. 'device_address': device_address,
  953. 'run_status': registers[0] if len(registers) > 0 else None,
  954. 'led_control': registers[1] if len(registers) > 1 else None,
  955. 'antenna_status': registers[2:10] if len(registers) >= 10 else [],
  956. 'raw_registers': registers
  957. }
  958. response_payload['payload']['success'] = 'error' not in status_result
  959. response_payload['payload']['result'] = panel_status
  960. elif command == 'QUERY_JUMPER_STATUS':
  961. # 查询跳线器状态汇总 (7.8) - 触发 STATUS 上行至 jumper/{dtu_id}/status
  962. dtu_publish_jumper_status()
  963. return # dtu_publish_jumper_status 已发送响应
  964. elif command == 'QUERY_ENV_SENSOR':
  965. # 查询环境传感器 (7.9) - 触发 STATUS 上行至 env/{dtu_id}/sensor
  966. dtu_publish_env_sensor()
  967. return # dtu_publish_env_sensor 已发送响应
  968. elif command == 'OTA_UPGRADE':
  969. params = payload.get('payload', {}).get('params', {})
  970. target_version = params.get('firmware_version')
  971. force_upgrade = params.get('force_upgrade', False)
  972. current_version = dtu_config.get('firmware_version', 'v1.0.0')
  973. incoming_msg_id = payload.get('msg_id', '')
  974. if target_version == current_version and not force_upgrade:
  975. response_payload['payload']['success'] = False
  976. response_payload['payload']['error_code'] = 1021
  977. response_payload['payload']['error_message'] = f"已是目标版本: {target_version}"
  978. mqtt_client.publish(topic_response_dtu, json.dumps(response_payload), qos=1)
  979. return
  980. if params.get('firmware_url'):
  981. import threading
  982. threading.Thread(target=lambda: _run_ota({**params, '_incoming_msg_id': incoming_msg_id}), daemon=True).start()
  983. response_payload['payload']['success'] = True
  984. response_payload['payload']['result'] = {
  985. 'firmware_version': target_version,
  986. 'ota_status': 'DOWNLOADING',
  987. 'restart_required': False
  988. }
  989. elif command == 'OTA_CANCEL':
  990. # 取消OTA升级
  991. # 向OTA控制寄存器写入取消命令 (0x0000=取消)
  992. device_address = 1
  993. for panel_id, cfg in panel_config.items():
  994. if panel_id == target:
  995. device_address = cfg.get('address', 1)
  996. break
  997. # OTA控制寄存器地址: 0x0300
  998. # 值: 0x0000=取消升级
  999. cancel_result = modbus_client.write_single_register(device_address, 0x0300, 0x0000)
  1000. response_payload['payload']['success'] = 'error' not in cancel_result
  1001. response_payload['payload']['result'] = {
  1002. 'message': 'OTA upgrade cancelled' if 'error' not in cancel_result else 'Failed to cancel OTA',
  1003. 'raw_result': cancel_result
  1004. }
  1005. else:
  1006. # 未知命令
  1007. response_payload['payload']['success'] = False
  1008. response_payload['payload']['error_code'] = 1001
  1009. response_payload['payload']['error_message'] = f"未知命令: {command}"
  1010. mqtt_client.publish(topic_response_dtu, json.dumps(response_payload), qos=1)
  1011. return
  1012. # 发送响应(QUERY_DTU_STATUS 已由 dtu_publish_status 发送;QUERY_JUMPER_STATUS/QUERY_ENV_SENSOR 已在分支中发布)
  1013. if command == 'QUERY_DTU_STATUS':
  1014. pass
  1015. else:
  1016. cmd = command
  1017. if cmd == 'READ_PANEL_STATUS':
  1018. if target and target != 'all' and target in panel_config:
  1019. # 单个面板: 使用 panel_id 作为 topic segment
  1020. topic = build_dtu_topic(dtu_config['customer_id'], 'patchpanel',
  1021. dtu_config['dtu_id'], target, 'status')
  1022. mqtt_client.publish(topic, json.dumps(response_payload), qos=0)
  1023. else:
  1024. # target=all: 遍历所有面板发布到各自的 topic
  1025. for pid in panel_config.keys():
  1026. topic = build_dtu_topic(dtu_config['customer_id'], 'patchpanel',
  1027. dtu_config['dtu_id'], pid, 'status')
  1028. mqtt_client.publish(topic, json.dumps(response_payload), qos=0)
  1029. else:
  1030. topic = build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'response')
  1031. p = response_payload['payload']
  1032. if not p.get('success', True) and p.get('error_code', 0) == 0:
  1033. p['error_code'] = 9999
  1034. p['error_message'] = p.get('error_message') or '未知错误'
  1035. mqtt_client.publish(topic, json.dumps(response_payload), qos=1)
  1036. except Exception as e:
  1037. logger.error(f"处理控制指令失败: {str(e)}")
  1038. # 启动DTU心跳定时器
  1039. def start_dtu_heartbeat():
  1040. """启动DTU心跳定时任务"""
  1041. def heartbeat_task():
  1042. env_tick = 0
  1043. while True:
  1044. socketio.sleep(dtu_config.get('heartbeat_interval', DTU_HEARTBEAT_INTERVAL))
  1045. if mqtt_client.get_status() and dtu_config.get('enabled'):
  1046. dtu_publish_status()
  1047. # 每 2 个心跳周期 (120s) 主动推送一次环境传感器数据 (7.9)
  1048. env_tick += 1
  1049. if env_tick >= 2:
  1050. env_tick = 0
  1051. dtu_publish_env_sensor()
  1052. socketio.start_background_task(target=heartbeat_task)
  1053. # 修改mqtt_data_handler以处理控制指令
  1054. def mqtt_data_handler_extended(data):
  1055. """处理MQTT接收的数据(扩展版,含DTU协议)"""
  1056. try:
  1057. topic = data.get('topic', '')
  1058. payload_str = data.get('payload', '')
  1059. # 尝试解析JSON
  1060. try:
  1061. payload = json.loads(payload_str) if isinstance(payload_str, str) else payload_str
  1062. except:
  1063. payload = payload_str
  1064. # 添加到缓冲区
  1065. timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
  1066. mqtt_data_buffer.append({
  1067. 'timestamp': timestamp,
  1068. 'topic': topic,
  1069. 'payload': payload_str
  1070. })
  1071. if len(mqtt_data_buffer) > MAX_BUFFER_SIZE:
  1072. mqtt_data_buffer.pop(0)
  1073. # 通过WebSocket广播
  1074. socketio.emit('mqtt_data', {
  1075. 'timestamp': timestamp,
  1076. 'topic': topic,
  1077. 'payload': payload_str
  1078. }, namespace=SOCKETIO_NAMESPACE_DATA)
  1079. # 检查是否是控制指令主题
  1080. expected_control_topic = build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'control')
  1081. if topic == expected_control_topic:
  1082. dtu_handle_control(topic, payload)
  1083. # 检查是否是状态主题,用于处理OTA状态上报
  1084. expected_status_topic = build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'status')
  1085. if topic == expected_status_topic and isinstance(payload, dict):
  1086. if 'ota_status' in payload or 'firmware_version' in payload:
  1087. handle_ota_status(dtu_config['dtu_id'], payload)
  1088. # 检查是否是环境传感器数据主题 (兼容旧 sensor/.../data 路径,spec 7.9 为 env/.../sensor)
  1089. sensor_topic = build_dtu_topic(dtu_config['customer_id'], 'sensor', dtu_config['dtu_id'], 'data')
  1090. env_topic = build_dtu_topic(dtu_config['customer_id'], 'env', dtu_config['dtu_id'], 'sensor')
  1091. if topic in (sensor_topic, env_topic) and isinstance(payload, dict):
  1092. if 'temperature' in payload or 'humidity' in payload:
  1093. update_env_sensor_data(
  1094. payload.get('temperature'),
  1095. payload.get('humidity'),
  1096. payload.get('dtu_temperature'),
  1097. payload.get('sensor_update_time')
  1098. )
  1099. # 检查是否是广播主题 - DTU发现 (7.14)
  1100. discover_topic = build_dtu_topic('broadcast', 'dtu', 'discover')
  1101. if topic == discover_topic:
  1102. handle_broadcast_discover(payload)
  1103. # 检查是否是广播主题 - 批量配置 (7.15)
  1104. config_topic = build_dtu_topic('broadcast', 'dtu', 'config')
  1105. if topic == config_topic:
  1106. handle_broadcast_config(payload)
  1107. # 转发到串口(如果启用)
  1108. if forward_mqtt_to_serial and serial_client.get_status():
  1109. success, msg = serial_client.send_data(payload_str)
  1110. if not success:
  1111. logger.warning(f"MQTT数据转发到串口失败: {msg}")
  1112. except Exception as e:
  1113. logger.error(f"处理MQTT数据时出错: {str(e)}")
  1114. # WebSocket事件处理
  1115. @socketio.on('connect', namespace=SOCKETIO_NAMESPACE_DATA)
  1116. def handle_data_connect():
  1117. """处理数据命名空间的连接"""
  1118. try:
  1119. client_id = str(uuid.uuid4())
  1120. connected_clients['data'].add(client_id)
  1121. logger.info(f'客户端已连接到数据命名空间,当前连接数: {len(connected_clients["data"])}')
  1122. # 发送当前的缓冲区数据,限制发送的历史记录数量
  1123. max_history = 100 # 限制发送的历史记录数量以提高性能
  1124. emit('serial_data_history', {'data': serial_data_buffer[-max_history:]})
  1125. emit('mqtt_data_history', {'data': mqtt_data_buffer[-max_history:]})
  1126. # 存储客户端ID以便断开连接时使用
  1127. socketio.start_background_task(target=lambda: None) # 确保上下文可用
  1128. except Exception as e:
  1129. logger.error(f"处理数据命名空间连接时出错: {str(e)}")
  1130. @socketio.on('connect', namespace=SOCKETIO_NAMESPACE_STATUS)
  1131. def handle_status_connect():
  1132. """处理状态命名空间的连接"""
  1133. try:
  1134. client_id = str(uuid.uuid4())
  1135. connected_clients['status'].add(client_id)
  1136. logger.info(f'客户端已连接到状态命名空间,当前连接数: {len(connected_clients["status"])}')
  1137. # 发送当前状态
  1138. emit('serial_status', {'connected': serial_status})
  1139. emit('mqtt_status', {'connected': mqtt_status})
  1140. emit('forward_status', {
  1141. 'serial_to_mqtt': forward_serial_to_mqtt,
  1142. 'mqtt_to_serial': forward_mqtt_to_serial,
  1143. 'publish_topic': mqtt_publish_topic
  1144. })
  1145. except Exception as e:
  1146. logger.error(f"处理状态命名空间连接时出错: {str(e)}")
  1147. @socketio.on('connect', namespace=SOCKETIO_NAMESPACE_CONTROL)
  1148. def handle_control_connect():
  1149. """处理控制命名空间的连接"""
  1150. try:
  1151. client_id = str(uuid.uuid4())
  1152. connected_clients['control'].add(client_id)
  1153. logger.info(f'客户端已连接到控制命名空间,当前连接数: {len(connected_clients["control"])}')
  1154. except Exception as e:
  1155. logger.error(f"处理控制命名空间连接时出错: {str(e)}")
  1156. @socketio.on('disconnect', namespace=SOCKETIO_NAMESPACE_DATA)
  1157. def handle_data_disconnect():
  1158. """处理数据命名空间的断开连接"""
  1159. try:
  1160. # 清理客户端连接记录
  1161. # 在实际应用中,可能需要更复杂的逻辑来追踪具体哪个客户端断开了连接
  1162. if len(connected_clients['data']) > 0:
  1163. # 这里简化处理,实际应该维护session到client_id的映射
  1164. connected_clients['data'].pop() # 注意:这是一个简化的实现
  1165. logger.info(f'客户端已断开数据命名空间的连接,当前连接数: {len(connected_clients["data"])}')
  1166. except Exception as e:
  1167. logger.error(f"处理数据命名空间断开连接时出错: {str(e)}")
  1168. @socketio.on('disconnect', namespace=SOCKETIO_NAMESPACE_STATUS)
  1169. def handle_status_disconnect():
  1170. """处理状态命名空间的断开连接"""
  1171. try:
  1172. # 清理客户端连接记录
  1173. if len(connected_clients['status']) > 0:
  1174. connected_clients['status'].pop()
  1175. logger.info(f'客户端已断开状态命名空间的连接,当前连接数: {len(connected_clients["status"])}')
  1176. except Exception as e:
  1177. logger.error(f"处理状态命名空间断开连接时出错: {str(e)}")
  1178. @socketio.on('disconnect', namespace=SOCKETIO_NAMESPACE_CONTROL)
  1179. def handle_control_disconnect():
  1180. """处理控制命名空间的断开连接"""
  1181. try:
  1182. # 清理客户端连接记录
  1183. if len(connected_clients['control']) > 0:
  1184. connected_clients['control'].pop()
  1185. logger.info(f'客户端已断开控制命名空间的连接,当前连接数: {len(connected_clients["control"])}')
  1186. except Exception as e:
  1187. logger.error(f"处理控制命名空间断开连接时出错: {str(e)}")
  1188. @socketio.on('serial_send', namespace=SOCKETIO_NAMESPACE_CONTROL)
  1189. def handle_serial_send(data):
  1190. """通过WebSocket处理串口发送数据请求"""
  1191. try:
  1192. message = data.get('message', '')
  1193. if not message:
  1194. emit('serial_send_response', {
  1195. 'success': False,
  1196. 'message': '消息内容不能为空',
  1197. 'error_code': ERROR_CODES['CONFIG_ERROR']
  1198. })
  1199. return
  1200. if not (isinstance(serial_client.get_status(), dict) and serial_client.get_status().get("connected", False)):
  1201. emit('serial_send_response', {
  1202. 'success': False,
  1203. 'message': '串口未连接',
  1204. 'error_code': ERROR_CODES['SERIAL_CONNECTION_ERROR']
  1205. })
  1206. return
  1207. success, msg = serial_client.send_data(message)
  1208. emit('serial_send_response', {
  1209. 'success': success,
  1210. 'message': msg,
  1211. 'error_code': ERROR_CODES['SUCCESS'] if success else ERROR_CODES['SERIAL_SEND_ERROR']
  1212. })
  1213. if success:
  1214. logger.info(f"通过WebSocket发送串口数据成功: {message[:50]}..." if len(message) > 50 else message)
  1215. except Exception as e:
  1216. error_msg = f"处理串口发送请求时出错: {str(e)}"
  1217. logger.error(error_msg)
  1218. emit('serial_send_response', {
  1219. 'success': False,
  1220. 'message': error_msg,
  1221. 'error_code': ERROR_CODES['UNKNOWN_ERROR']
  1222. })
  1223. @socketio.on('mqtt_publish', namespace=SOCKETIO_NAMESPACE_CONTROL)
  1224. def handle_mqtt_publish(data):
  1225. """通过WebSocket处理MQTT发布数据请求"""
  1226. try:
  1227. topic = data.get('topic', '')
  1228. message = data.get('message', '')
  1229. if not topic or not message:
  1230. emit('mqtt_publish_response', {
  1231. 'success': False,
  1232. 'message': '主题或消息内容不能为空',
  1233. 'error_code': ERROR_CODES['CONFIG_ERROR']
  1234. })
  1235. return
  1236. if not mqtt_client.get_status():
  1237. emit('mqtt_publish_response', {
  1238. 'success': False,
  1239. 'message': 'MQTT未连接',
  1240. 'error_code': ERROR_CODES['MQTT_CONNECTION_ERROR']
  1241. })
  1242. return
  1243. success, msg = mqtt_client.publish(topic, message)
  1244. emit('mqtt_publish_response', {
  1245. 'success': success,
  1246. 'message': msg,
  1247. 'error_code': ERROR_CODES['SUCCESS'] if success else ERROR_CODES['MQTT_PUBLISH_ERROR']
  1248. })
  1249. if success:
  1250. logger.info(f"通过WebSocket发布MQTT消息成功: 主题={topic}, 消息={message[:50]}..." if len(message) > 50 else message)
  1251. except Exception as e:
  1252. error_msg = f"处理MQTT发布请求时出错: {str(e)}"
  1253. logger.error(error_msg)
  1254. emit('mqtt_publish_response', {
  1255. 'success': False,
  1256. 'message': error_msg,
  1257. 'error_code': ERROR_CODES['UNKNOWN_ERROR']
  1258. })
  1259. @socketio.on('update_forward_config', namespace=SOCKETIO_NAMESPACE_CONTROL)
  1260. def handle_update_forward_config(data):
  1261. """通过WebSocket更新转发配置"""
  1262. global forward_serial_to_mqtt, forward_mqtt_to_serial, mqtt_publish_topic
  1263. try:
  1264. # 更新转发标志
  1265. if 'serial_to_mqtt' in data:
  1266. forward_serial_to_mqtt = bool(data['serial_to_mqtt'])
  1267. if 'mqtt_to_serial' in data:
  1268. forward_mqtt_to_serial = bool(data['mqtt_to_serial'])
  1269. if 'publish_topic' in data:
  1270. new_topic = str(data['publish_topic'])
  1271. if not new_topic.strip():
  1272. raise ValueError("发布主题不能为空")
  1273. mqtt_publish_topic = new_topic
  1274. # 广播配置更新
  1275. socketio.emit('forward_status', {
  1276. 'serial_to_mqtt': forward_serial_to_mqtt,
  1277. 'mqtt_to_serial': forward_mqtt_to_serial,
  1278. 'publish_topic': mqtt_publish_topic
  1279. }, namespace=SOCKETIO_NAMESPACE_STATUS)
  1280. emit('update_forward_config_response', {
  1281. 'success': True,
  1282. 'message': '转发配置已更新',
  1283. 'error_code': ERROR_CODES['SUCCESS']
  1284. })
  1285. logger.info(f"转发配置已更新 - 串口到MQTT: {forward_serial_to_mqtt}, MQTT到串口: {forward_mqtt_to_serial}, 发布主题: {mqtt_publish_topic}")
  1286. except ValueError as e:
  1287. error_msg = str(e)
  1288. logger.warning(f"转发配置更新失败: {error_msg}")
  1289. emit('update_forward_config_response', {
  1290. 'success': False,
  1291. 'message': error_msg,
  1292. 'error_code': ERROR_CODES['CONFIG_ERROR']
  1293. })
  1294. except Exception as e:
  1295. error_msg = f'更新转发配置失败: {str(e)}'
  1296. logger.error(error_msg)
  1297. emit('update_forward_config_response', {
  1298. 'success': False,
  1299. 'message': error_msg,
  1300. 'error_code': ERROR_CODES['UNKNOWN_ERROR']
  1301. })
  1302. @socketio.on('clear_data_buffer', namespace=SOCKETIO_NAMESPACE_CONTROL)
  1303. def handle_clear_data_buffer(data):
  1304. """通过WebSocket清空数据缓冲区"""
  1305. try:
  1306. buffer_type = data.get('type', '')
  1307. if buffer_type == 'serial':
  1308. serial_data_buffer.clear()
  1309. emit('clear_data_buffer_response', {
  1310. 'success': True,
  1311. 'message': '串口数据缓冲区已清空',
  1312. 'error_code': ERROR_CODES['SUCCESS']
  1313. })
  1314. logger.info("串口数据缓冲区已清空")
  1315. elif buffer_type == 'mqtt':
  1316. mqtt_data_buffer.clear()
  1317. emit('clear_data_buffer_response', {
  1318. 'success': True,
  1319. 'message': 'MQTT数据缓冲区已清空',
  1320. 'error_code': ERROR_CODES['SUCCESS']
  1321. })
  1322. logger.info("MQTT数据缓冲区已清空")
  1323. elif buffer_type == 'all':
  1324. serial_data_buffer.clear()
  1325. mqtt_data_buffer.clear()
  1326. emit('clear_data_buffer_response', {
  1327. 'success': True,
  1328. 'message': '所有数据缓冲区已清空',
  1329. 'error_code': ERROR_CODES['SUCCESS']
  1330. })
  1331. logger.info("所有数据缓冲区已清空")
  1332. else:
  1333. emit('clear_data_buffer_response', {
  1334. 'success': False,
  1335. 'message': '无效的缓冲区类型',
  1336. 'error_code': ERROR_CODES['CONFIG_ERROR']
  1337. })
  1338. logger.warning(f"清空缓冲区失败: 无效的缓冲区类型 '{buffer_type}'")
  1339. except Exception as e:
  1340. error_msg = f'清空缓冲区失败: {str(e)}'
  1341. logger.error(error_msg)
  1342. emit('clear_data_buffer_response', {
  1343. 'success': False,
  1344. 'message': error_msg,
  1345. 'error_code': ERROR_CODES['UNKNOWN_ERROR']
  1346. })
  1347. # 设置回调
  1348. serial_client.set_data_callback(serial_data_handler)
  1349. serial_client.set_send_callback(serial_send_handler)
  1350. serial_client.set_status_callback(serial_status_handler)
  1351. mqtt_client.set_data_callback(mqtt_data_handler_extended)
  1352. mqtt_client.set_status_callback(mqtt_status_handler)
  1353. # 设备配置文件路径
  1354. DEVICE_CONFIG_FILE = '/root/dzxj_dtu/devices.json'
  1355. confirm_loop_running = False
  1356. def save_device_config():
  1357. """保存设备配置到文件"""
  1358. try:
  1359. filepath = DEVICE_CONFIG_FILE
  1360. success = address_config.save_config(filepath)
  1361. if success:
  1362. logger.info(f"设备配置已保存到: {filepath}")
  1363. except Exception as e:
  1364. logger.error(f"保存设备配置失败: {str(e)}")
  1365. def load_device_config():
  1366. """加载设备配置"""
  1367. try:
  1368. filepath = DEVICE_CONFIG_FILE
  1369. if os.path.exists(filepath):
  1370. success = address_config.load_config(filepath)
  1371. if success:
  1372. devices = address_config.get_stored_devices()
  1373. logger.info(f"已加载 {len(devices)} 个设备配置")
  1374. return devices
  1375. except Exception as e:
  1376. logger.error(f"加载设备配置失败: {str(e)}")
  1377. return {}
  1378. def confirm_loop():
  1379. """后台确认线程:每10秒对所有已存储设备发送 confirm_address"""
  1380. global confirm_loop_running
  1381. confirm_loop_running = True
  1382. logger.info("启动设备确认线程 (间隔10秒)")
  1383. while confirm_loop_running:
  1384. try:
  1385. devices = address_config.get_stored_devices()
  1386. if not devices:
  1387. time.sleep(10)
  1388. continue
  1389. if not serial_client.get_status():
  1390. time.sleep(10)
  1391. continue
  1392. _st = serial_client.get_status()
  1393. if not (isinstance(_st, dict) and _st.get('connected', False)):
  1394. time.sleep(10)
  1395. continue
  1396. for uid_hex, addr in devices.items():
  1397. try:
  1398. uid_bytes = bytes.fromhex(uid_hex)
  1399. cmd = build_confirm_address(addr, uid_bytes)
  1400. success, msg = serial_client.send_raw(cmd)
  1401. if success:
  1402. logger.debug(f"确认设备: 地址={addr}, UID={uid_hex[:16]}...")
  1403. else:
  1404. logger.warning(f"确认失败 地址={addr}: {msg}")
  1405. except Exception as e:
  1406. logger.error(f"确认异常 地址={addr}: {str(e)}")
  1407. time.sleep(0.1)
  1408. except Exception as e:
  1409. logger.error(f"确认线程异常: {str(e)}")
  1410. time.sleep(10)
  1411. # API路由
  1412. # 移除静态文件服务,前端由nginx提供服务
  1413. # 根路径路由
  1414. @app.route('/')
  1415. def index():
  1416. return send_from_directory(STATIC_FOLDER, 'index.html')
  1417. # 404错误处理器 - 解决SPA路由刷新问题
  1418. @app.errorhandler(404)
  1419. def page_not_found(e):
  1420. """处理所有404错误,对于非API路径返回index.html"""
  1421. path = request.path
  1422. # 检查是否是API请求
  1423. if path.startswith('/api/'):
  1424. # 对于API请求,返回404错误
  1425. return jsonify({
  1426. 'success': False,
  1427. 'message': 'API endpoint not found'
  1428. }), 404
  1429. # 对于所有非API路径,返回index.html让前端路由处理
  1430. return send_from_directory(STATIC_FOLDER, 'index.html'), 200
  1431. @app.route('/api/serial/ports', methods=['GET'])
  1432. def get_serial_ports():
  1433. """获取可用串口列表"""
  1434. ports = serial_client.list_ports()
  1435. return jsonify({
  1436. 'success': True,
  1437. 'ports': ports
  1438. })
  1439. @app.route('/api/serial/connect', methods=['POST'])
  1440. def serial_connect():
  1441. """连接串口"""
  1442. try:
  1443. data = request.json
  1444. port = data.get('port')
  1445. baudrate = data.get('baudrate', 9600)
  1446. bytesize = data.get('bytesize', 8)
  1447. parity = data.get('parity', 'N')
  1448. stopbits = data.get('stopbits', 1)
  1449. timeout = data.get('timeout', 0.1)
  1450. if not port:
  1451. logger.warning("连接串口请求缺少串口名称")
  1452. return jsonify({
  1453. 'success': False,
  1454. 'message': '串口名称不能为空',
  1455. 'error_code': ERROR_CODES['CONFIG_ERROR']
  1456. }), 400
  1457. # 先断开之前的连接
  1458. _status = serial_client.get_status()
  1459. if isinstance(_status, dict) and _status.get('connected', False):
  1460. _port = serial_client.current_config.port if serial_client.current_config else 'unknown'
  1461. logger.info(f"断开现有串口连接: {_port}")
  1462. serial_client.disconnect()
  1463. # 连接新的串口
  1464. logger.info(f"尝试连接串口: {port}, 波特率: {baudrate}")
  1465. success, message = serial_client.connect(port, baudrate=baudrate, timeout=timeout, bytesize=bytesize, parity=parity, stopbits=stopbits)
  1466. status_code = 200 if success else 400
  1467. error_code = ERROR_CODES['SUCCESS'] if success else ERROR_CODES['SERIAL_CONNECTION_ERROR']
  1468. response = {
  1469. 'success': success,
  1470. 'message': message,
  1471. 'error_code': error_code
  1472. }
  1473. if success:
  1474. logger.info(f"串口连接成功: {port}")
  1475. # 保存串口配置
  1476. save_serial_config(port, baudrate, timeout, bytesize, parity, stopbits)
  1477. else:
  1478. logger.error(f"串口连接失败: {message}")
  1479. return jsonify(response), status_code
  1480. except Exception as e:
  1481. error_msg = f'连接串口时出错: {str(e)}'
  1482. logger.exception(error_msg) # 使用exception记录完整堆栈
  1483. return jsonify({
  1484. 'success': False,
  1485. 'message': error_msg,
  1486. 'error_code': ERROR_CODES['UNKNOWN_ERROR']
  1487. }), 500
  1488. @app.route('/api/serial/disconnect', methods=['POST'])
  1489. def serial_disconnect():
  1490. """断开串口连接"""
  1491. success, message = serial_client.disconnect()
  1492. return jsonify({
  1493. 'success': success,
  1494. 'message': message
  1495. })
  1496. @app.route('/api/serial/status', methods=['GET'])
  1497. def serial_get_status():
  1498. """获取串口状态"""
  1499. _st = serial_client.get_status()
  1500. saved_config = {}
  1501. try:
  1502. with open(SERIAL_CONFIG_FILE, 'r') as f:
  1503. saved_config = json.load(f)
  1504. except (FileNotFoundError, json.JSONDecodeError):
  1505. pass
  1506. result = {'saved_config': saved_config}
  1507. if isinstance(_st, dict):
  1508. result['connected'] = _st.get('connected', False)
  1509. if result['connected']:
  1510. cfg = _st.get('config')
  1511. result['port'] = cfg.port if cfg else None
  1512. else:
  1513. result['port'] = None
  1514. else:
  1515. result['connected'] = bool(_st)
  1516. result['port'] = None
  1517. return jsonify(result)
  1518. @app.route('/api/serial/send', methods=['POST'])
  1519. def serial_send():
  1520. """发送数据到串口"""
  1521. data = request.json
  1522. message = data.get('message')
  1523. if not message:
  1524. return jsonify({
  1525. 'success': False,
  1526. 'message': '消息内容不能为空'
  1527. })
  1528. success, message = serial_client.send_data(message)
  1529. return jsonify({
  1530. 'success': success,
  1531. 'message': message
  1532. })
  1533. @app.route('/api/mqtt/connect', methods=['POST'])
  1534. def mqtt_connect():
  1535. """连接MQTT服务器"""
  1536. try:
  1537. data = request.json
  1538. host = data.get('broker') or data.get('host', 'localhost')
  1539. port = data.get('port', 1883)
  1540. client_id = data.get('client_id', f'serial_gateway_{int(time.time())}')
  1541. username = data.get('username')
  1542. password = data.get('password')
  1543. keepalive = data.get('keepalive', 60)
  1544. # 先断开之前的连接
  1545. if mqtt_client.get_status():
  1546. logger.info(f"断开现有MQTT连接: {mqtt_client.host}:{mqtt_client.port}")
  1547. mqtt_client.disconnect()
  1548. # 连接新的MQTT服务器
  1549. logger.info(f"尝试连接MQTT服务器: {host}:{port}, 客户端ID: {client_id}")
  1550. will_topic = build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'status')
  1551. will_payload = json.dumps({
  1552. 'dtu_id': dtu_config['dtu_id'], 'type': 'STATUS',
  1553. 'payload': {'online': False, 'reason': 'CONNECTION_LOST'}
  1554. })
  1555. success, message = mqtt_client.connect(
  1556. host=host, port=port, client_id=client_id,
  1557. username=username, password=password,
  1558. keepalive=keepalive,
  1559. will_topic=will_topic, will_payload=will_payload, will_qos=1, will_retain=False
  1560. )
  1561. # 如果连接成功,订阅主题
  1562. if success and 'topics' in data:
  1563. mqtt_client.subscribe(data['topics'])
  1564. status_code = 200 if success else 400
  1565. error_code = ERROR_CODES['SUCCESS'] if success else ERROR_CODES['MQTT_CONNECTION_ERROR']
  1566. response = {
  1567. 'success': success,
  1568. 'message': message,
  1569. 'error_code': error_code
  1570. }
  1571. if success:
  1572. logger.info(f"MQTT服务器连接成功: {host}:{port}")
  1573. else:
  1574. logger.error(f"MQTT服务器连接失败: {message}")
  1575. return jsonify(response), status_code
  1576. except Exception as e:
  1577. error_msg = f'连接MQTT服务器时出错: {str(e)}'
  1578. logger.exception(error_msg)
  1579. return jsonify({
  1580. 'success': False,
  1581. 'message': error_msg,
  1582. 'error_code': ERROR_CODES['UNKNOWN_ERROR']
  1583. }), 500
  1584. @app.route('/api/mqtt/disconnect', methods=['POST'])
  1585. def mqtt_disconnect():
  1586. """断开MQTT连接"""
  1587. success, message = mqtt_client.disconnect()
  1588. return jsonify({
  1589. 'success': success,
  1590. 'message': message
  1591. })
  1592. @app.route('/api/mqtt/status', methods=['GET'])
  1593. def mqtt_get_status():
  1594. """获取MQTT状态"""
  1595. _st = mqtt_client.get_status()
  1596. return jsonify({
  1597. 'connected': _st.get('connected', False) if isinstance(_st, dict) else bool(_st)
  1598. })
  1599. @app.route('/api/mqtt/publish', methods=['POST'])
  1600. def mqtt_publish():
  1601. """发布MQTT消息"""
  1602. data = request.json
  1603. topic = data.get('topic')
  1604. message = data.get('message')
  1605. if not topic or not message:
  1606. return jsonify({
  1607. 'success': False,
  1608. 'message': '主题和消息内容不能为空'
  1609. })
  1610. success, message = mqtt_client.publish(topic, message)
  1611. return jsonify({
  1612. 'success': success,
  1613. 'message': message
  1614. })
  1615. @app.route('/api/mqtt/subscribe', methods=['POST'])
  1616. def mqtt_subscribe():
  1617. """订阅MQTT主题"""
  1618. data = request.json
  1619. topics = data.get('topics', [])
  1620. if not topics:
  1621. return jsonify({
  1622. 'success': False,
  1623. 'message': '请至少订阅一个主题'
  1624. })
  1625. success, message = mqtt_client.subscribe(topics)
  1626. return jsonify({
  1627. 'success': success,
  1628. 'message': message
  1629. })
  1630. @app.route('/api/mqtt/broadcast_discover', methods=['POST'])
  1631. def mqtt_broadcast_discover():
  1632. """发送DTU发现广播 (7.14)
  1633. 服务器通过广播主题发送DISCOVER消息,
  1634. 触发所有在线DTU进行注册响应
  1635. """
  1636. data = request.json or {}
  1637. customer_id = data.get('customer_id', dtu_config.get('customer_id', 'default'))
  1638. discover_topic = build_dtu_topic('broadcast', 'dtu', 'discover')
  1639. request_id = f"dsc_{int(time.time() * 1000)}"
  1640. payload = {
  1641. 'msg_id': request_id,
  1642. 'timestamp': int(time.time() * 1000),
  1643. 'dtu_id': 'PLATFORM',
  1644. 'type': 'DISCOVER',
  1645. 'payload': {
  1646. 'request_id': request_id,
  1647. 'customer_id': customer_id
  1648. }
  1649. }
  1650. success, message = mqtt_client.publish(discover_topic, json.dumps(payload), qos=1)
  1651. logger.info(f"发送DTU发现广播: topic={discover_topic}, payload={payload}")
  1652. return jsonify({
  1653. 'success': success,
  1654. 'message': 'DTU发现广播已发送' if success else message,
  1655. 'topic': discover_topic
  1656. })
  1657. @app.route('/api/mqtt/broadcast_config', methods=['POST'])
  1658. def mqtt_broadcast_config():
  1659. """发送DTU批量配置广播 (7.15)
  1660. 服务器通过广播主题发送CONFIG消息,
  1661. 用于批量配置所有在线DTU
  1662. """
  1663. data = request.json or {}
  1664. customer_id = data.get('customer_id', dtu_config.get('customer_id', 'default'))
  1665. config_items = data.get('items', {})
  1666. config_version = data.get('config_version', f"cfg_{int(time.time())}")
  1667. force_apply = data.get('force_apply', False)
  1668. config_topic = build_dtu_topic('broadcast', 'dtu', 'config')
  1669. payload = {
  1670. 'msg_id': f"cfg_{int(time.time() * 1000)}",
  1671. 'timestamp': int(time.time() * 1000),
  1672. 'dtu_id': 'PLATFORM',
  1673. 'type': 'CONFIG',
  1674. 'payload': {
  1675. 'customer_id': customer_id,
  1676. 'config_version': config_version,
  1677. 'force_apply': force_apply,
  1678. 'items': config_items
  1679. }
  1680. }
  1681. success, message = mqtt_client.publish(config_topic, json.dumps(payload), qos=1)
  1682. logger.info(f"发送DTU批量配置广播: topic={config_topic}, payload={payload}")
  1683. return jsonify({
  1684. 'success': success,
  1685. 'message': 'DTU批量配置广播已发送' if success else message,
  1686. 'topic': config_topic,
  1687. 'config': {
  1688. 'config_version': config_version,
  1689. 'items': config_items,
  1690. 'force_apply': force_apply
  1691. }
  1692. })
  1693. @app.route('/api/data/serial', methods=['GET'])
  1694. def get_serial_data():
  1695. """获取串口数据"""
  1696. return jsonify({
  1697. 'data': serial_data_buffer
  1698. })
  1699. @app.route('/api/data/mqtt', methods=['GET'])
  1700. def get_mqtt_data():
  1701. """获取MQTT数据"""
  1702. return jsonify({
  1703. 'data': mqtt_data_buffer
  1704. })
  1705. @app.route('/api/forward/config', methods=['POST'])
  1706. def set_forward_config():
  1707. """设置转发配置"""
  1708. global forward_serial_to_mqtt, forward_mqtt_to_serial, mqtt_publish_topic
  1709. data = request.json
  1710. forward_serial_to_mqtt = data.get('serial_to_mqtt', False)
  1711. forward_mqtt_to_serial = data.get('mqtt_to_serial', False)
  1712. if 'publish_topic' in data:
  1713. mqtt_publish_topic = data['publish_topic']
  1714. return jsonify({
  1715. 'success': True,
  1716. 'message': '转发配置已更新',
  1717. 'config': {
  1718. 'serial_to_mqtt': forward_serial_to_mqtt,
  1719. 'mqtt_to_serial': forward_mqtt_to_serial,
  1720. 'publish_topic': mqtt_publish_topic
  1721. }
  1722. })
  1723. @app.route('/api/forward/status', methods=['GET'])
  1724. def get_forward_status():
  1725. """获取转发状态"""
  1726. return jsonify({
  1727. 'serial_to_mqtt': forward_serial_to_mqtt,
  1728. 'mqtt_to_serial': forward_mqtt_to_serial,
  1729. 'publish_topic': mqtt_publish_topic
  1730. })
  1731. # 健康检查端点
  1732. @app.route('/api/health', methods=['GET'])
  1733. def health_check():
  1734. """健康检查端点"""
  1735. try:
  1736. # 获取客户端连接数量
  1737. client_counts = {
  1738. 'data': len(connected_clients['data']),
  1739. 'status': len(connected_clients['status']),
  1740. 'control': len(connected_clients['control'])
  1741. }
  1742. # 获取缓冲区大小
  1743. buffer_sizes = {
  1744. 'serial': len(serial_data_buffer),
  1745. 'mqtt': len(mqtt_data_buffer)
  1746. }
  1747. # 执行系统负载检查
  1748. # 注意:这只是一个简化的负载检查,实际应用中可能需要更复杂的监控
  1749. is_healthy = True
  1750. load_warnings = []
  1751. # 检查缓冲区是否过大
  1752. if buffer_sizes['serial'] > MAX_BUFFER_SIZE * 0.8:
  1753. is_healthy = False
  1754. load_warnings.append(f"串口缓冲区接近最大容量: {buffer_sizes['serial']}/{MAX_BUFFER_SIZE}")
  1755. if buffer_sizes['mqtt'] > MAX_BUFFER_SIZE * 0.8:
  1756. is_healthy = False
  1757. load_warnings.append(f"MQTT缓冲区接近最大容量: {buffer_sizes['mqtt']}/{MAX_BUFFER_SIZE}")
  1758. # 检查WebSocket连接数是否过多
  1759. total_clients = sum(client_counts.values())
  1760. if total_clients > 100: # 设置合理的阈值
  1761. is_healthy = False
  1762. load_warnings.append(f"WebSocket连接数过多: {total_clients}")
  1763. # 尝试获取网络状态信息(使用try-except包装,防止网络模块出错导致健康检查失败)
  1764. network_info = None
  1765. try:
  1766. network_info = network_manager.get_network_status()
  1767. except Exception as e:
  1768. logger.warning(f"获取网络状态时出错: {str(e)}")
  1769. # 不影响整体健康检查,只添加警告
  1770. load_warnings.append(f"网络状态获取失败: {str(e)}")
  1771. response = {
  1772. 'status': 'healthy' if is_healthy else 'warning',
  1773. 'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),
  1774. 'services': {
  1775. 'serial': serial_status,
  1776. 'mqtt': mqtt_status,
  1777. 'websocket': True
  1778. },
  1779. 'client_counts': client_counts,
  1780. 'buffer_sizes': buffer_sizes,
  1781. 'warnings': load_warnings
  1782. }
  1783. # 仅当获取到网络信息时添加
  1784. if network_info:
  1785. response['network'] = network_info
  1786. return jsonify(response), 200
  1787. except Exception as e:
  1788. # 捕获所有异常,确保健康检查不会返回500错误
  1789. logger.error(f"健康检查端点出错: {str(e)}")
  1790. # 返回一个基础的健康状态,至少显示服务在运行
  1791. return jsonify({
  1792. 'status': 'error',
  1793. 'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),
  1794. 'error': str(e),
  1795. 'services': {
  1796. 'api': True, # API服务本身是运行的
  1797. 'serial': None,
  1798. 'mqtt': None,
  1799. 'websocket': None
  1800. }
  1801. }), 200 # 仍然返回200,避免健康检查导致的连锁反应
  1802. # 网络配置相关API
  1803. @app.route('/api/network/config', methods=['GET'])
  1804. def get_network_config():
  1805. """获取当前网络配置"""
  1806. try:
  1807. config = network_manager.get_network_config()
  1808. return jsonify(config)
  1809. except Exception as e:
  1810. logger.error(f'获取网络配置失败: {str(e)}')
  1811. return jsonify({'success': False, 'message': f'获取网络配置失败: {str(e)}'}), 500
  1812. @app.route('/api/network/config', methods=['POST'])
  1813. def update_network_config():
  1814. """更新网络配置"""
  1815. try:
  1816. config_data = request.json
  1817. result = network_manager.update_network_config(config_data)
  1818. if result['success']:
  1819. return jsonify(result)
  1820. else:
  1821. return jsonify(result), 400
  1822. except Exception as e:
  1823. logger.error(f'更新网络配置失败: {str(e)}')
  1824. return jsonify({'success': False, 'message': f'更新网络配置失败: {str(e)}'}), 500
  1825. @app.route('/api/network/status', methods=['GET'])
  1826. def get_network_status():
  1827. """获取网络状态信息"""
  1828. try:
  1829. status = network_manager.get_network_status()
  1830. return jsonify(status)
  1831. except Exception as e:
  1832. logger.error(f'获取网络状态失败: {str(e)}')
  1833. return jsonify({'success': False, 'message': f'获取网络状态失败: {str(e)}'}), 500
  1834. @app.route('/api/network/restart', methods=['POST'])
  1835. def restart_network_service():
  1836. """重启网络服务以应用新配置"""
  1837. try:
  1838. result = network_manager.restart_network_service()
  1839. if result['success']:
  1840. return jsonify(result)
  1841. else:
  1842. return jsonify(result), 500
  1843. except Exception as e:
  1844. logger.error(f'重启网络服务失败: {str(e)}')
  1845. return jsonify({'success': False, 'message': f'重启网络服务失败: {str(e)}'}), 500
  1846. # Modbus RTU API
  1847. @app.route('/api/modbus/antenna_addresses', methods=['GET'])
  1848. def get_antenna_addresses():
  1849. """获取天线地址映射表"""
  1850. return jsonify({
  1851. 'success': True,
  1852. 'antennas': {str(k): f"0x{v:04x}" for k, v in ANTENNA_ADDRESSES.items()}
  1853. })
  1854. @app.route('/api/modbus/read_antenna', methods=['POST'])
  1855. def modbus_read_antenna():
  1856. """读取指定天线的卡号
  1857. 请求参数:
  1858. {
  1859. "device_address": 1, // 设备地址 (1-247)
  1860. "antenna": 1, // 天线编号 (1-24)
  1861. "timeout": 1.0 // 可选,超时时间(秒)
  1862. }
  1863. """
  1864. try:
  1865. data = request.json
  1866. device_address = data.get('device_address', 1)
  1867. antenna = data.get('antenna', 1)
  1868. timeout = data.get('timeout')
  1869. if antenna < 1 or antenna > 24:
  1870. return jsonify({
  1871. 'success': False,
  1872. 'message': f'无效的天线编号: {antenna}, 必须是1-24'
  1873. }), 400
  1874. if not (isinstance(serial_client.get_status(), dict) and serial_client.get_status().get("connected", False)):
  1875. return jsonify({
  1876. 'success': False,
  1877. 'message': '串口未连接'
  1878. }), 400
  1879. result = modbus_client.read_antenna_card(
  1880. device_address=device_address,
  1881. antenna_num=antenna,
  1882. timeout=timeout
  1883. )
  1884. if 'error' in result:
  1885. return jsonify({
  1886. 'success': False,
  1887. 'message': result['error'],
  1888. 'raw_data': result.get('raw_data', '')
  1889. }), 400
  1890. return jsonify({
  1891. 'success': True,
  1892. 'data': result
  1893. })
  1894. except Exception as e:
  1895. logger.error(f'读取天线数据失败: {str(e)}')
  1896. return jsonify({
  1897. 'success': False,
  1898. 'message': str(e)
  1899. }), 500
  1900. @app.route('/api/modbus/read_registers', methods=['POST'])
  1901. def modbus_read_registers():
  1902. """读取保持寄存器
  1903. 请求参数:
  1904. {
  1905. "device_address": 1,
  1906. "start_address": 2, // 起始地址 (十六进制如0x0002或十进制如2)
  1907. "quantity": 4, // 寄存器数量
  1908. "timeout": 1.0
  1909. }
  1910. """
  1911. try:
  1912. data = request.json
  1913. device_address = data.get('device_address', 1)
  1914. start_address = data.get('start_address', 0)
  1915. quantity = data.get('quantity', 1)
  1916. timeout = data.get('timeout')
  1917. # 支持十六进制字符串
  1918. if isinstance(start_address, str):
  1919. start_address = int(start_address, 16)
  1920. if isinstance(device_address, str):
  1921. device_address = int(device_address, 16)
  1922. if not (isinstance(serial_client.get_status(), dict) and serial_client.get_status().get("connected", False)):
  1923. return jsonify({
  1924. 'success': False,
  1925. 'message': '串口未连接'
  1926. }), 400
  1927. result = modbus_client.read_holding_registers(
  1928. device_address=device_address,
  1929. start_address=start_address,
  1930. quantity=quantity,
  1931. timeout=timeout
  1932. )
  1933. if 'error' in result:
  1934. return jsonify({
  1935. 'success': False,
  1936. 'message': result['error'],
  1937. 'raw_data': result.get('raw_data', '')
  1938. }), 400
  1939. return jsonify({
  1940. 'success': True,
  1941. 'data': result
  1942. })
  1943. except Exception as e:
  1944. logger.error(f'读取寄存器失败: {str(e)}')
  1945. return jsonify({
  1946. 'success': False,
  1947. 'message': str(e)
  1948. }), 500
  1949. @app.route('/api/modbus/write_register', methods=['POST'])
  1950. def modbus_write_register():
  1951. """写单个寄存器
  1952. 请求参数:
  1953. {
  1954. "device_address": 1,
  1955. "register_address": 1, // 寄存器地址
  1956. "value": 256, // 写入的值
  1957. "timeout": 1.0
  1958. }
  1959. """
  1960. try:
  1961. data = request.json
  1962. device_address = data.get('device_address', 1)
  1963. register_address = data.get('register_address', 1)
  1964. value = data.get('value', 0)
  1965. timeout = data.get('timeout')
  1966. if not (isinstance(serial_client.get_status(), dict) and serial_client.get_status().get("connected", False)):
  1967. return jsonify({
  1968. 'success': False,
  1969. 'message':'串口未连接'
  1970. }), 400
  1971. result = modbus_client.write_single_register(
  1972. device_address=device_address,
  1973. register_address=register_address,
  1974. value=value,
  1975. timeout=timeout
  1976. )
  1977. if 'error' in result:
  1978. return jsonify({
  1979. 'success': False,
  1980. 'message': result['error'],
  1981. 'raw_data': result.get('raw_data', '')
  1982. }), 400
  1983. return jsonify({
  1984. 'success': True,
  1985. 'data': result
  1986. })
  1987. except Exception as e:
  1988. logger.error(f'写寄存器失败: {str(e)}')
  1989. return jsonify({
  1990. 'success': False,
  1991. 'message': str(e)
  1992. }), 500
  1993. @app.route('/api/modbus/set_rgb_led', methods=['POST'])
  1994. def modbus_set_rgb_led():
  1995. """设置RGB灯状态
  1996. 请求参数:
  1997. {
  1998. "device_address": 1,
  1999. "led_number": 1, // 灯编号 (1-24)
  2000. "color": 1, // 颜色: 0=灭, 1=红灯, 2=绿灯, 3=蓝灯
  2001. "timeout": 1.0
  2002. }
  2003. """
  2004. try:
  2005. data = request.json
  2006. device_address = data.get('device_address', 1)
  2007. led_number = data.get('led_number', 1)
  2008. color = data.get('color', 0)
  2009. timeout = data.get('timeout')
  2010. if not (isinstance(serial_client.get_status(), dict) and serial_client.get_status().get("connected", False)):
  2011. return jsonify({
  2012. 'success': False,
  2013. 'message': '串口未连接'
  2014. }), 400
  2015. result = modbus_client.set_rgb_led(
  2016. device_address=device_address,
  2017. led_number=led_number,
  2018. color=color,
  2019. timeout=timeout
  2020. )
  2021. if 'error' in result:
  2022. return jsonify({
  2023. 'success': False,
  2024. 'message': result['error'],
  2025. 'raw_data': result.get('raw_data', '')
  2026. }), 400
  2027. # 更新 LED 状态追踪
  2028. led_states[led_number] = color
  2029. return jsonify({
  2030. 'success': True,
  2031. 'data': result
  2032. })
  2033. except Exception as e:
  2034. logger.error(f'设置RGB灯失败: {str(e)}')
  2035. return jsonify({
  2036. 'success': False,
  2037. 'message': str(e)
  2038. }), 500
  2039. @app.route('/api/modbus/scan', methods=['POST'])
  2040. def modbus_scan_devices():
  2041. """扫描在线设备
  2042. 请求参数:
  2043. {
  2044. "max_address": 247, // 最大设备地址
  2045. "timeout": 0.2 // 单个设备超时时间
  2046. }
  2047. """
  2048. try:
  2049. data = request.json or {}
  2050. max_address = data.get('max_address', 247)
  2051. timeout = data.get('timeout', 0.2)
  2052. if not (isinstance(serial_client.get_status(), dict) and serial_client.get_status().get("connected", False)):
  2053. return jsonify({
  2054. 'success': False,
  2055. 'message': '串口未连接'
  2056. }), 400
  2057. # 异步扫描可能更好,但这里先同步实现
  2058. result = modbus_client.scan_devices(max_address)
  2059. return jsonify({
  2060. 'success': True,
  2061. 'devices': result
  2062. })
  2063. except Exception as e:
  2064. logger.error(f'扫描设备失败: {str(e)}')
  2065. return jsonify({
  2066. 'success': False,
  2067. 'message': str(e)
  2068. }), 500
  2069. # ========== 地址配置协议 API ==========
  2070. @app.route('/api/modbus/broadcast_query', methods=['POST'])
  2071. def modbus_broadcast_query():
  2072. """发送广播查询指令"""
  2073. try:
  2074. data = request.json or {}
  2075. timeout = data.get('timeout')
  2076. if not (isinstance(serial_client.get_status(), dict) and serial_client.get_status().get("connected", False)):
  2077. return jsonify({'success': False, 'message': '串口未连接'}), 400
  2078. responses = address_config.broadcast_query(timeout)
  2079. assign_results = []
  2080. if responses:
  2081. assign_results = address_config.process_responses(responses)
  2082. for r in assign_results:
  2083. uid_bytes = r.get('uid', r.get('request', ''))
  2084. save_device_config()
  2085. return jsonify({
  2086. 'success': True,
  2087. 'responses': responses,
  2088. 'assign_results': assign_results,
  2089. 'count': len(responses)
  2090. })
  2091. except Exception as e:
  2092. logger.error(f'广播查询失败: {str(e)}')
  2093. return jsonify({'success': False, 'message': str(e)}), 500
  2094. @app.route('/api/modbus/auto_configure', methods=['POST'])
  2095. def modbus_auto_configure():
  2096. """自动配置设备地址"""
  2097. try:
  2098. data = request.json or {}
  2099. timeout = data.get('timeout')
  2100. if not (isinstance(serial_client.get_status(), dict) and serial_client.get_status().get("connected", False)):
  2101. return jsonify({'success': False, 'message': '串口未连接'}), 400
  2102. result = address_config.auto_configure(timeout)
  2103. if result.get('success') and (result.get('discovered', 0) > 0 or result.get('confirmed', 0) > 0 or result.get('assigned', 0) > 0):
  2104. save_device_config()
  2105. return jsonify(result)
  2106. except Exception as e:
  2107. logger.error(f'自动配置失败: {str(e)}')
  2108. return jsonify({'success': False, 'message': str(e)}), 500
  2109. @app.route('/api/modbus/stored_devices', methods=['GET'])
  2110. def get_stored_devices():
  2111. """获取已存储的设备列表"""
  2112. return jsonify({'success': True, 'devices': address_config.get_stored_devices()})
  2113. @app.route('/api/modbus/stored_devices', methods=['POST'])
  2114. def add_stored_device():
  2115. """添加已存储的设备"""
  2116. try:
  2117. data = request.json
  2118. uid = data.get('uid', '').lower()
  2119. address = data.get('address', 1)
  2120. if len(uid) != 24:
  2121. return jsonify({'success': False, 'message': 'UID长度必须是24个十六进制字符'}), 400
  2122. address_config.add_stored_device(uid, address)
  2123. save_device_config()
  2124. return jsonify({'success': True, 'message': f'已添加设备: UID={uid}, 地址={address}'})
  2125. except Exception as e:
  2126. return jsonify({'success': False, 'message': str(e)}), 500
  2127. @app.route('/api/modbus/load_config', methods=['POST'])
  2128. def modbus_load_config():
  2129. """从文件加载设备配置"""
  2130. try:
  2131. data = request.json
  2132. filepath = data.get('filepath', '/tmp/modbus_devices.json')
  2133. success = address_config.load_config(filepath)
  2134. return jsonify({'success': success, 'devices': address_config.get_stored_devices()})
  2135. except Exception as e:
  2136. return jsonify({'success': False, 'message': str(e)}), 500
  2137. @app.route('/api/modbus/save_config', methods=['POST'])
  2138. def modbus_save_config():
  2139. """保存设备配置到文件"""
  2140. try:
  2141. data = request.json
  2142. filepath = data.get('filepath', '/tmp/modbus_devices.json')
  2143. success = address_config.save_config(filepath)
  2144. return jsonify({'success': success, 'message': f'配置已保存到: {filepath}' if success else '保存失败'})
  2145. except Exception as e:
  2146. return jsonify({'success': False, 'message': str(e)}), 500
  2147. @app.route('/api/modbus/confirm_devices', methods=['POST'])
  2148. def confirm_devices():
  2149. """手动触发对所有已存储设备的确认"""
  2150. try:
  2151. devices = address_config.get_stored_devices()
  2152. if not devices:
  2153. return jsonify({'success': False, 'message': '没有已存储的设备'}), 400
  2154. if not (isinstance(serial_client.get_status(), dict) and serial_client.get_status().get("connected", False)):
  2155. return jsonify({'success': False, 'message': '串口未连接'}), 400
  2156. results = []
  2157. for uid_hex, addr in devices.items():
  2158. try:
  2159. uid_bytes = bytes.fromhex(uid_hex)
  2160. cmd = build_confirm_address(addr, uid_bytes)
  2161. success, msg = serial_client.send_raw(cmd)
  2162. logger.info(f"确认设备 地址={addr}: {'成功' if success else '失败 ' + msg}")
  2163. results.append({'address': addr, 'uid': uid_hex, 'success': success, 'message': msg})
  2164. except Exception as e:
  2165. results.append({'address': addr, 'uid': uid_hex, 'success': False, 'message': str(e)})
  2166. time.sleep(0.1)
  2167. return jsonify({'success': True, 'results': results, 'count': len(results)})
  2168. except Exception as e:
  2169. return jsonify({'success': False, 'message': str(e)}), 500
  2170. # 端口状态追踪 - 用于存储每个端口的事件状态
  2171. port_event_history = [] # 存储最近的端口事件
  2172. @app.route('/api/port/status', methods=['GET'])
  2173. def get_port_status():
  2174. """获取所有端口状态"""
  2175. return jsonify({'success': True, 'port_state': port_state})
  2176. @app.route('/api/port/events', methods=['GET'])
  2177. def get_port_events():
  2178. """获取端口事件历史"""
  2179. limit = request.args.get('limit', 100, type=int)
  2180. return jsonify({
  2181. 'success': True,
  2182. 'events': port_event_history[-limit:]
  2183. })
  2184. @app.route('/api/port/clear_events', methods=['POST'])
  2185. def clear_port_events():
  2186. """清除端口事件历史"""
  2187. global port_event_history
  2188. port_event_history = []
  2189. return jsonify({'success': True, 'message': '事件历史已清除'})
  2190. # 设备最后响应时间跟踪
  2191. device_last_seen = {}
  2192. @app.route('/api/panel/status', methods=['GET'])
  2193. def get_panel_status():
  2194. """获取所有面板状态"""
  2195. now = time.time()
  2196. PANEL_OFFLINE_TIMEOUT = 60
  2197. panel_status = {}
  2198. for panel_id, ports in port_state.items():
  2199. port_count = len(ports)
  2200. alarm_count = sum(1 for p in ports.values() if p.get('alarm_count', 0) > 0)
  2201. connected_count = sum(1 for p in ports.values() if p.get('last_uid'))
  2202. panel_status[panel_id] = {
  2203. 'panel_id': panel_id,
  2204. 'port_count': port_count,
  2205. 'connected_count': connected_count,
  2206. 'alarm_count': alarm_count,
  2207. 'status': 'online' if connected_count > 0 else 'offline'
  2208. }
  2209. for panel_id, cfg in panel_config.items():
  2210. last_seen = device_last_seen.get(panel_id, 0)
  2211. is_online = (now - last_seen) < PANEL_OFFLINE_TIMEOUT
  2212. if panel_id in panel_status:
  2213. panel_status[panel_id].update({
  2214. 'address': cfg.get('address'),
  2215. 'position': cfg.get('position'),
  2216. 'panel_uid': cfg.get('panel_uid'),
  2217. 'status': 'online' if is_online else 'offline'
  2218. })
  2219. else:
  2220. panel_status[panel_id] = {
  2221. 'panel_id': panel_id,
  2222. 'address': cfg.get('address'),
  2223. 'position': cfg.get('position'),
  2224. 'panel_uid': cfg.get('panel_uid'),
  2225. 'port_count': 0,
  2226. 'connected_count': 0,
  2227. 'alarm_count': 0,
  2228. 'status': 'online' if is_online else 'offline'
  2229. }
  2230. return jsonify({'success': True, 'panels': panel_status})
  2231. # LED 状态追踪 (内存中跟踪每个灯的最后设置状态)
  2232. led_states = {i: 0 for i in range(1, 25)} # 0=off, 1=red, 2=green, 3=blue
  2233. @app.route('/api/modbus/led_status', methods=['GET'])
  2234. def get_led_status():
  2235. """获取所有 LED 状态"""
  2236. return jsonify({'success': True, 'leds': led_states})
  2237. @app.route('/api/modbus/set_all_leds', methods=['POST'])
  2238. def set_all_leds():
  2239. """批量设置 LED
  2240. 请求: {"device_address": 1, "color": 1}
  2241. 设置所有 24 个 LED 到指定颜色
  2242. """
  2243. try:
  2244. data = request.json
  2245. device_address = data.get('device_address', 1)
  2246. color = data.get('color', 0)
  2247. timeout = data.get('timeout')
  2248. if not (isinstance(serial_client.get_status(), dict) and serial_client.get_status().get("connected", False)):
  2249. return jsonify({'success': False, 'message': '串口未连接'}), 400
  2250. results = []
  2251. for led_num in range(1, 25):
  2252. result = modbus_client.set_rgb_led(
  2253. device_address=device_address,
  2254. led_number=led_num,
  2255. color=color,
  2256. timeout=timeout
  2257. )
  2258. if 'error' in result:
  2259. results.append({'led': led_num, 'success': False, 'error': result['error']})
  2260. else:
  2261. results.append({'led': led_num, 'success': True})
  2262. led_states[led_num] = color
  2263. return jsonify({'success': True, 'results': results})
  2264. except Exception as e:
  2265. logger.error(f'批量设置LED失败: {str(e)}')
  2266. return jsonify({'success': False, 'message': str(e)}), 500
  2267. # 在 set_rgb_led 中更新 LED 状态追踪
  2268. # 不再需要静态文件目录,前端由nginx提供服务
  2269. # ========== DTU MQTT协议配置API ==========
  2270. @app.route('/api/dtu/config', methods=['GET'])
  2271. def get_dtu_config():
  2272. """获取DTU配置"""
  2273. return jsonify({
  2274. 'success': True,
  2275. 'data': dtu_config
  2276. })
  2277. @app.route('/api/dtu/config', methods=['POST'])
  2278. def update_dtu_config():
  2279. """更新DTU配置"""
  2280. try:
  2281. data = request.json
  2282. old_config = dtu_config.copy()
  2283. # 更新配置项
  2284. if 'topic_prefix' in data:
  2285. dtu_config['topic_prefix'] = data['topic_prefix']
  2286. if 'customer_id' in data:
  2287. dtu_config['customer_id'] = data['customer_id']
  2288. if 'dtu_id' in data:
  2289. dtu_config['dtu_id'] = data['dtu_id']
  2290. if 'firmware_version' in data:
  2291. dtu_config['firmware_version'] = data['firmware_version']
  2292. if 'hardware_version' in data:
  2293. dtu_config['hardware_version'] = data['hardware_version']
  2294. if 'heartbeat_interval' in data:
  2295. dtu_config['heartbeat_interval'] = data['heartbeat_interval']
  2296. if 'enabled' in data:
  2297. dtu_config['enabled'] = data['enabled']
  2298. # 如果MQTT已连接且主题配置发生变化,重新订阅
  2299. if mqtt_status and dtu_config.get('enabled'):
  2300. old_control_topic = build_dtu_topic(
  2301. old_config.get('customer_id', DEFAULT_CUSTOMER_ID),
  2302. 'dtu',
  2303. old_config.get('dtu_id', DEFAULT_DTU_ID),
  2304. 'control'
  2305. )
  2306. new_control_topic = build_dtu_topic(
  2307. dtu_config['customer_id'],
  2308. 'dtu',
  2309. dtu_config['dtu_id'],
  2310. 'control'
  2311. )
  2312. if old_control_topic != new_control_topic:
  2313. # 取消旧订阅,订阅新主题
  2314. mqtt_client.unsubscribe(old_control_topic)
  2315. mqtt_client.subscribe(new_control_topic)
  2316. logger.info(f"控制主题已更新: {old_control_topic} -> {new_control_topic}")
  2317. # 重新发送注册消息
  2318. dtu_register()
  2319. return jsonify({
  2320. 'success': True,
  2321. 'message': 'DTU配置已更新',
  2322. 'data': dtu_config
  2323. })
  2324. except Exception as e:
  2325. logger.error(f"更新DTU配置失败: {str(e)}")
  2326. return jsonify({'success': False, 'message': str(e)}), 500
  2327. @app.route('/api/dtu/register', methods=['POST'])
  2328. def manual_dtu_register():
  2329. """手动触发DTU注册"""
  2330. try:
  2331. if not mqtt_status:
  2332. return jsonify({'success': False, 'message': 'MQTT未连接'}), 400
  2333. success = dtu_register()
  2334. if success:
  2335. return jsonify({'success': True, 'message': '注册消息已发送'})
  2336. else:
  2337. return jsonify({'success': False, 'message': '注册消息发送失败'}), 500
  2338. except Exception as e:
  2339. logger.error(f"手动触发DTU注册失败: {str(e)}")
  2340. return jsonify({'success': False, 'message': str(e)}), 500
  2341. def _get_cpu_usage():
  2342. try:
  2343. import psutil
  2344. return psutil.cpu_percent(interval=None)
  2345. except Exception:
  2346. return None
  2347. def _get_memory_usage():
  2348. try:
  2349. import psutil
  2350. return psutil.virtual_memory().percent
  2351. except Exception:
  2352. return None
  2353. @app.route('/api/dtu/status', methods=['GET'])
  2354. def get_dtu_status():
  2355. """获取DTU状态"""
  2356. try:
  2357. # 获取串口状态
  2358. serial_st = serial_client.get_status()
  2359. # 获取面板状态
  2360. devices = address_config.get_stored_devices()
  2361. # 主板温度: 优先外部上报,否则本地读取
  2362. dtu_temperature = env_sensor_data.get('dtu_temperature')
  2363. if dtu_temperature is None:
  2364. try:
  2365. import psutil
  2366. temps = psutil.sensors_temperatures(fahrenheit=False) or {}
  2367. for chip_name, entries in temps.items():
  2368. for entry in entries:
  2369. if entry.current and entry.current > 0:
  2370. dtu_temperature = round(entry.current, 1)
  2371. break
  2372. if dtu_temperature is not None:
  2373. break
  2374. except Exception:
  2375. pass
  2376. if dtu_temperature is None:
  2377. import glob as _glob
  2378. for tz in sorted(_glob.glob('/sys/class/thermal/thermal_zone*/temp')):
  2379. try:
  2380. with open(tz) as f:
  2381. v = int(f.read().strip())
  2382. if v > 0:
  2383. dtu_temperature = round(v / 1000.0, 1)
  2384. break
  2385. except Exception:
  2386. continue
  2387. status = {
  2388. 'dtu_id': dtu_config.get('dtu_id'),
  2389. 'mqtt_connected': mqtt_status,
  2390. 'serial_connected': isinstance(serial_st, dict) and serial_st.get('connected', False),
  2391. 'dtu_enabled': dtu_config.get('enabled', True),
  2392. 'topic_prefix': dtu_config.get('topic_prefix'),
  2393. 'customer_id': dtu_config.get('customer_id'),
  2394. 'panel_count': len(devices),
  2395. 'cpu_usage': _get_cpu_usage(),
  2396. 'memory_usage': _get_memory_usage(),
  2397. 'temperature': dtu_temperature,
  2398. 'dtu_temperature': dtu_temperature,
  2399. 'firmware_version': dtu_config.get('firmware_version', 'v1.0.0'),
  2400. 'topics': {
  2401. 'register': build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'register'),
  2402. 'status': build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'status'),
  2403. 'control': build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'control'),
  2404. 'response': build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'response'),
  2405. 'event': build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'event'),
  2406. 'alarm': build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'alarm')
  2407. }
  2408. }
  2409. return jsonify({'success': True, 'data': status})
  2410. except Exception as e:
  2411. logger.error(f"获取DTU状态失败: {str(e)}")
  2412. return jsonify({'success': False, 'message': str(e)}), 500
  2413. @app.route('/api/dtu/control', methods=['POST'])
  2414. def dtu_control():
  2415. """发送DTU控制命令(HTTP 入口,复用 dtu_handle_control 逻辑)"""
  2416. try:
  2417. data = request.json or {}
  2418. # 兼容两种入参格式:
  2419. # 1) {"command": "...", "target": "...", "params": {...}} 简洁格式
  2420. # 2) {"payload": {"command": "...", "target": "...", "params": {...}}} MQTT envelope 格式
  2421. inner = data.get('payload') if isinstance(data.get('payload'), dict) else data
  2422. command = inner.get('command')
  2423. # REBOOT 走快速通道立即执行
  2424. if command == 'REBOOT':
  2425. import subprocess
  2426. logger.warning("执行系统重启命令")
  2427. threading.Thread(target=lambda: (
  2428. time.sleep(1),
  2429. subprocess.run(['reboot'], capture_output=True)
  2430. ), daemon=True).start()
  2431. return jsonify({'success': True, 'message': '系统正在重启...'})
  2432. # 其他命令委托给 MQTT 处理器(构造 MQTT envelope 后调用)
  2433. mqtt_envelope = {
  2434. 'msg_id': data.get('msg_id', f"http_{int(time.time() * 1000)}_{uuid.uuid4().hex[:6]}"),
  2435. 'timestamp': data.get('timestamp', int(time.time() * 1000)),
  2436. 'dtu_id': data.get('dtu_id', dtu_config.get('dtu_id')),
  2437. 'type': 'CONTROL',
  2438. 'payload': {
  2439. 'command': command,
  2440. 'target': inner.get('target'),
  2441. 'params': inner.get('params', {})
  2442. }
  2443. }
  2444. # 调用 MQTT 处理器(其内部会发送响应到 dtu/.../response 主题)
  2445. dtu_handle_control('http/control', mqtt_envelope)
  2446. # 如果命令是 QUERY_JUMPER_STATUS / QUERY_ENV_SENSOR / QUERY_DTU_STATUS,
  2447. # 实际响应已发布到对应主题,HTTP 端点仅返回成功标记
  2448. if command in ('QUERY_JUMPER_STATUS', 'QUERY_ENV_SENSOR', 'QUERY_DTU_STATUS'):
  2449. return jsonify({
  2450. 'success': True,
  2451. 'message': f'{command} 已发布到 MQTT 主题'
  2452. })
  2453. # 其他命令: 从 MQTT 主题同步拉取最新响应(简化处理:直接返回已发布标记)
  2454. return jsonify({
  2455. 'success': True,
  2456. 'message': f'{command} 命令已下发,等待 MQTT 响应'
  2457. })
  2458. except Exception as e:
  2459. logger.error(f"DTU控制命令失败: {str(e)}")
  2460. return jsonify({'success': False, 'message': str(e)}), 500
  2461. # OTA状态存储
  2462. ota_status = {
  2463. 'status': 'IDLE', # IDLE, DOWNLOADING, VERIFYING, FLASHING, SUCCESS, FAILED
  2464. 'progress': 0,
  2465. 'firmware_version': None,
  2466. 'target_version': None,
  2467. 'error_code': None,
  2468. 'error_message': None,
  2469. 'last_update': None
  2470. }
  2471. @app.route('/api/dtu/ota_detect', methods=['POST'])
  2472. def ota_detect():
  2473. """检测固件包信息(自动下载并解析 manifest)"""
  2474. try:
  2475. url = request.json.get('url', '')
  2476. if not url:
  2477. return jsonify({'success': False, 'message': '请提供固件 URL'}), 400
  2478. import urllib.request, tempfile, tarfile, json, hashlib
  2479. tmp = tempfile.mktemp(suffix='.tar.gz')
  2480. try:
  2481. urllib.request.urlretrieve(url, tmp)
  2482. except Exception as e:
  2483. return jsonify({'success': False, 'message': f'下载失败: {str(e)}'}), 400
  2484. file_size = os.path.getsize(tmp)
  2485. h = hashlib.md5()
  2486. with open(tmp, 'rb') as f:
  2487. for chunk in iter(lambda: f.read(65536), b''):
  2488. h.update(chunk)
  2489. md5sum = h.hexdigest()
  2490. version = ''
  2491. try:
  2492. with tarfile.open(tmp, 'r:gz') as tar:
  2493. m = tar.extractfile('firmware/firmware.json')
  2494. if m:
  2495. manifest = json.loads(m.read())
  2496. version = manifest.get('version', '')
  2497. except Exception as e:
  2498. logger.warning(f"解析 firmware.json 失败: {e}")
  2499. os.remove(tmp)
  2500. return jsonify({
  2501. 'success': True,
  2502. 'data': {
  2503. 'file_size': file_size,
  2504. 'checksum': md5sum,
  2505. 'checksum_type': 'MD5',
  2506. 'firmware_version': version
  2507. }
  2508. })
  2509. except Exception as e:
  2510. logger.error(f"检测固件失败: {str(e)}")
  2511. return jsonify({'success': False, 'message': str(e)}), 500
  2512. @app.route('/api/dtu/ota_status', methods=['GET'])
  2513. def get_ota_status():
  2514. """获取OTA升级状态"""
  2515. try:
  2516. return jsonify({
  2517. 'success': True,
  2518. 'data': {
  2519. 'current_firmware': dtu_config.get('firmware_version', 'v1.0.0'),
  2520. 'ota_status': ota_status.get('status', 'IDLE'),
  2521. 'ota_progress': ota_status.get('progress', 0),
  2522. 'target_version': ota_status.get('target_version'),
  2523. 'error_code': ota_status.get('error_code'),
  2524. 'error_message': ota_status.get('error_message'),
  2525. 'last_update': ota_status.get('last_update')
  2526. }
  2527. })
  2528. except Exception as e:
  2529. logger.error(f"获取OTA状态失败: {str(e)}")
  2530. return jsonify({'success': False, 'message': str(e)}), 500
  2531. def handle_ota_status(dtu_id, payload):
  2532. """处理MQTT上报的OTA状态"""
  2533. ota_status['status'] = payload.get('ota_status', 'IDLE')
  2534. ota_status['progress'] = payload.get('ota_progress', 0)
  2535. ota_status['firmware_version'] = payload.get('firmware_version')
  2536. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2537. error_code = payload.get('error_code')
  2538. if error_code and error_code != 0:
  2539. ota_status['error_code'] = error_code
  2540. ota_status['error_message'] = payload.get('error_message', get_ota_error_message(error_code))
  2541. ota_status['status'] = 'FAILED'
  2542. elif ota_status['status'] == 'SUCCESS':
  2543. ota_status['error_code'] = None
  2544. ota_status['error_message'] = None
  2545. if ota_status.get('firmware_version'):
  2546. dtu_config['firmware_version'] = ota_status['firmware_version']
  2547. save_dtu_config()
  2548. logger.info(f"MQTT OTA状态更新: {ota_status['status']}, 进度: {ota_status['progress']}%")
  2549. def get_ota_error_message(error_code):
  2550. error_messages = {1021: '已是目标版本', 1022: '校验失败', 1023: '下载失败', 1024: '写入失败', 1025: '存储空间不足'}
  2551. return error_messages.get(error_code, f'未知错误码: {error_code}')
  2552. def _publish_ota_progress():
  2553. """通过MQTT发布OTA进度"""
  2554. try:
  2555. if not mqtt_client.get_status():
  2556. return
  2557. topic = build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'status')
  2558. payload = {
  2559. 'msg_id': f"ota_status_{int(time.time() * 1000)}",
  2560. 'timestamp': int(time.time() * 1000),
  2561. 'dtu_id': dtu_config['dtu_id'],
  2562. 'type': 'STATUS',
  2563. 'payload': {
  2564. 'ota_status': ota_status.get('status', 'IDLE'),
  2565. 'ota_progress': ota_status.get('progress', 0),
  2566. 'firmware_version': ota_status.get('target_version', ''),
  2567. 'error_code': ota_status.get('error_code', 0),
  2568. 'error_message': ota_status.get('error_message')
  2569. }
  2570. }
  2571. mqtt_client.publish(topic, json.dumps(payload), qos=1)
  2572. except Exception:
  2573. pass
  2574. def _send_ota_error_response(error_code, original_msg_id=''):
  2575. """通过MQTT发送OTA错误响应(1021-1025)"""
  2576. try:
  2577. if not mqtt_client.get_status():
  2578. return
  2579. topic = build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'response')
  2580. payload = {
  2581. 'msg_id': f"rsp_ota_{int(time.time() * 1000)}_{uuid.uuid4().hex[:6]}",
  2582. 'timestamp': int(time.time() * 1000),
  2583. 'dtu_id': dtu_config['dtu_id'],
  2584. 'type': 'RESPONSE',
  2585. 'payload': {
  2586. 'original_msg_id': original_msg_id,
  2587. 'command': 'OTA_UPGRADE',
  2588. 'success': False,
  2589. 'result': None,
  2590. 'error_code': error_code,
  2591. 'error_message': get_ota_error_message(error_code)
  2592. }
  2593. }
  2594. mqtt_client.publish(topic, json.dumps(payload), qos=1)
  2595. except Exception:
  2596. pass
  2597. def _run_ota(params):
  2598. """执行OTA升级(后台线程,供HTTP和MQTT共用)"""
  2599. import subprocess, os, hashlib, shutil, tarfile, tempfile, urllib.request
  2600. url = params['firmware_url']
  2601. version = params['firmware_version']
  2602. file_size = params['file_size']
  2603. checksum = params['checksum']
  2604. checksum_type = params.get('checksum_type', 'MD5').upper()
  2605. force = params.get('force_upgrade', False)
  2606. ota_status['status'] = 'DOWNLOADING'
  2607. ota_status['progress'] = 0
  2608. ota_status['target_version'] = version
  2609. ota_status['error_code'] = None
  2610. ota_status['error_message'] = None
  2611. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2612. _publish_ota_progress()
  2613. try:
  2614. tmp_dir = tempfile.mkdtemp(prefix='ota_')
  2615. fw_path = os.path.join(tmp_dir, 'firmware.tar.gz')
  2616. ota_status['progress'] = 5
  2617. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2618. logger.info(f"OTA: 开始下载固件 {url}")
  2619. req = urllib.request.Request(url, headers={'User-Agent': 'OTA-Updater'})
  2620. # 进度上报节流: 每 10% 或每 5 秒
  2621. last_published_pct = 0
  2622. last_publish_time = time.time()
  2623. with urllib.request.urlopen(req, timeout=120) as resp:
  2624. with open(fw_path, 'wb') as f:
  2625. total = int(resp.headers.get('Content-Length', 0))
  2626. downloaded = 0
  2627. while True:
  2628. chunk = resp.read(65536)
  2629. if not chunk: break
  2630. f.write(chunk)
  2631. downloaded += len(chunk)
  2632. if total:
  2633. pct = 5 + int(downloaded / total * 30)
  2634. ota_status['progress'] = min(pct, 35)
  2635. now = time.time()
  2636. if pct - last_published_pct >= 10 or (now - last_publish_time) >= 5:
  2637. last_published_pct = pct
  2638. last_publish_time = now
  2639. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2640. _publish_ota_progress()
  2641. dl_size = os.path.getsize(fw_path)
  2642. ota_status['progress'] = 40
  2643. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2644. _publish_ota_progress()
  2645. if abs(dl_size - file_size) > 1024:
  2646. raise Exception(f"文件大小不匹配: 预期{file_size}, 实际{dl_size}")
  2647. ota_status['status'] = 'VERIFYING'
  2648. ota_status['progress'] = 50
  2649. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2650. _publish_ota_progress()
  2651. h = hashlib.new(checksum_type)
  2652. with open(fw_path, 'rb') as f:
  2653. for chunk in iter(lambda: f.read(65536), b''): h.update(chunk)
  2654. actual_checksum = h.hexdigest().lower()
  2655. if actual_checksum != checksum.lower():
  2656. raise Exception(f"校验和不匹配: 预期{checksum}, 实际{actual_checksum}")
  2657. ota_status['progress'] = 60
  2658. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2659. _publish_ota_progress()
  2660. extract_dir = os.path.join(tmp_dir, 'firmware')
  2661. os.makedirs(extract_dir, exist_ok=True)
  2662. with tarfile.open(fw_path, 'r:gz') as tar: tar.extractall(extract_dir)
  2663. manifest_path = os.path.join(extract_dir, 'firmware', 'firmware.json')
  2664. if not os.path.exists(manifest_path):
  2665. raise Exception("固件包缺少 firmware.json")
  2666. with open(manifest_path, 'r') as f: manifest = json.load(f)
  2667. fw_version = manifest.get('version', version)
  2668. if not force:
  2669. current_ver = dtu_config.get('firmware_version', 'v0.0.0')
  2670. if fw_version == current_ver:
  2671. raise Exception(f'已是目标版本 {current_ver}')
  2672. ota_status['status'] = 'FLASHING'
  2673. ota_status['progress'] = 70
  2674. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2675. _publish_ota_progress()
  2676. fw_root = os.path.join(extract_dir, 'firmware')
  2677. project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  2678. excludes = {'__pycache__', '.git', 'log', 'venv'}
  2679. for root, dirs, files in os.walk(fw_root):
  2680. rel = os.path.relpath(root, fw_root)
  2681. if rel == '.': rel = ''
  2682. parts = rel.split(os.sep) if rel else []
  2683. if parts and parts[0] in excludes: continue
  2684. for fname in files:
  2685. if fname == 'firmware.json': continue
  2686. src = os.path.join(root, fname)
  2687. dst = os.path.join(project_dir, rel, fname)
  2688. os.makedirs(os.path.dirname(dst), exist_ok=True)
  2689. shutil.copy2(src, dst)
  2690. ota_status['progress'] = 90
  2691. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2692. dtu_config['firmware_version'] = fw_version
  2693. save_dtu_config()
  2694. ota_status['status'] = 'SUCCESS'
  2695. ota_status['progress'] = 100
  2696. ota_status['firmware_version'] = fw_version
  2697. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2698. _publish_ota_progress()
  2699. shutil.rmtree(tmp_dir, ignore_errors=True)
  2700. for i in range(10, 0, -1):
  2701. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2702. time.sleep(1)
  2703. logger.info("OTA: 重启服务...")
  2704. subprocess.Popen(
  2705. [subprocess.sys.executable, '-m', 'flask', 'run', '--host=0.0.0.0', '--port=5001'],
  2706. cwd=os.path.dirname(os.path.abspath(__file__)),
  2707. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
  2708. )
  2709. os._exit(0)
  2710. except Exception as e:
  2711. ota_status['status'] = 'FAILED'
  2712. ota_status['error_message'] = str(e)
  2713. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2714. # 映射错误到标准错误码 (1021-1025)
  2715. msg = str(e)
  2716. if '校验和' in msg or 'firmware.json' in msg:
  2717. ota_status['error_code'] = 1022
  2718. elif '已是目标版本' in msg:
  2719. ota_status['error_code'] = 1021
  2720. elif '下载' in msg or 'urlopen' in msg or 'Connection' in msg or 'timeout' in msg:
  2721. ota_status['error_code'] = 1023
  2722. elif '磁盘' in msg or '空间' in msg or 'No space' in msg:
  2723. ota_status['error_code'] = 1025
  2724. elif '写入' in msg or 'flash' in msg.lower() or 'shutil' in msg:
  2725. ota_status['error_code'] = 1024
  2726. else:
  2727. ota_status['error_code'] = 9999
  2728. _publish_ota_progress()
  2729. # 通过MQTT发送错误响应(同时适配HTTP和MQTT触发)
  2730. _send_ota_error_response(ota_status['error_code'], params.get('_incoming_msg_id', ''))
  2731. logger.error(f"OTA: 升级失败 - {str(e)}")
  2732. if 'tmp_dir' in dir() and tmp_dir and os.path.exists(tmp_dir):
  2733. shutil.rmtree(tmp_dir, ignore_errors=True)
  2734. @app.route('/api/dtu/ota_upgrade', methods=['POST'])
  2735. def trigger_ota_upgrade():
  2736. """触发OTA升级"""
  2737. try:
  2738. data = request.json
  2739. if not data:
  2740. return jsonify({'success': False, 'message': '请求体不能为空'}), 400
  2741. required_fields = ['firmware_url', 'firmware_version', 'file_size', 'checksum', 'checksum_type']
  2742. missing = [f for f in required_fields if not data.get(f)]
  2743. if missing:
  2744. return jsonify({'success': False, 'message': f'缺少必填字段: {", ".join(missing)}'}), 400
  2745. # 已是目标版本且未强制: 1021 (同时通过 MQTT 上报响应)
  2746. force_upgrade = data.get('force_upgrade', False)
  2747. current_version = dtu_config.get('firmware_version', 'v1.0.0')
  2748. if data['firmware_version'] == current_version and not force_upgrade:
  2749. # 通过 MQTT 上报 1021 响应 (与其他错误码一致)
  2750. try:
  2751. _send_ota_error_response(1021, data.get('msg_id', ''))
  2752. except Exception:
  2753. pass
  2754. return jsonify({
  2755. 'success': False,
  2756. 'error_code': 1021,
  2757. 'message': f'已是目标版本: {current_version}'
  2758. }), 400
  2759. # 注入 _incoming_msg_id 使 MQTT 错误响应可回填
  2760. ota_params = {**data, '_incoming_msg_id': data.get('msg_id', '')}
  2761. t = threading.Thread(target=_run_ota, args=(ota_params,), daemon=True)
  2762. t.start()
  2763. return jsonify({
  2764. 'success': True,
  2765. 'message': 'OTA升级已启动',
  2766. 'data': {
  2767. 'target_version': data['firmware_version'],
  2768. 'ota_status': 'DOWNLOADING'
  2769. }
  2770. })
  2771. except Exception as e:
  2772. logger.error(f"触发OTA升级失败: {str(e)}")
  2773. return jsonify({'success': False, 'message': str(e)}), 500
  2774. # ==================== 环境传感器 API ====================
  2775. # 环境传感器数据存储
  2776. env_sensor_data = {
  2777. 'temperature': None, # 环境温度 (℃)
  2778. 'humidity': None, # 环境湿度 (%)
  2779. 'dtu_temperature': None, # DTU主板温度 (℃)
  2780. 'update_time': None, # 数据更新时间
  2781. 'sensor_update_time': None, # 传感器更新时间
  2782. 'connected': False # 传感器连接状态
  2783. }
  2784. # 环境传感器告警阈值
  2785. env_sensor_threshold = {
  2786. 'temp_high': 45.0, # 环境温度上限 (℃)
  2787. 'temp_low': -10.0, # 环境温度下限 (℃)
  2788. 'humidity_high': 80.0, # 环境湿度上限 (%)
  2789. 'humidity_low': 20.0, # 环境湿度下限 (%)
  2790. 'dtu_temp_high': 70.0 # DTU主板温度上限 (℃)
  2791. }
  2792. # 环境传感器历史数据 (保留最近1000条)
  2793. env_sensor_history = []
  2794. @app.route('/api/sensor/env', methods=['GET'])
  2795. def get_env_sensor_data():
  2796. """获取环境传感器当前数据"""
  2797. data = dict(env_sensor_data)
  2798. # DTU 主板温度回退: 若外部未上报,从 sysfs 本地读取
  2799. if data.get('dtu_temperature') is None:
  2800. try:
  2801. import psutil
  2802. temps = psutil.sensors_temperatures(fahrenheit=False) or {}
  2803. for chip_name, entries in temps.items():
  2804. for entry in entries:
  2805. if entry.current and entry.current > 0:
  2806. data['dtu_temperature'] = round(entry.current, 1)
  2807. break
  2808. if data['dtu_temperature'] is not None:
  2809. break
  2810. except Exception:
  2811. pass
  2812. if data.get('dtu_temperature') is None:
  2813. import glob as _glob
  2814. for tz in sorted(_glob.glob('/sys/class/thermal/thermal_zone*/temp')):
  2815. try:
  2816. with open(tz) as f:
  2817. v = int(f.read().strip())
  2818. if v > 0:
  2819. data['dtu_temperature'] = round(v / 1000.0, 1)
  2820. data['update_time'] = data.get('update_time') or __import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  2821. break
  2822. except Exception:
  2823. continue
  2824. # 附加 CPU/内存使用率(始终本地读取)
  2825. data['cpu_usage'] = _get_cpu_usage()
  2826. data['memory_usage'] = _get_memory_usage()
  2827. return jsonify({
  2828. 'success': True,
  2829. 'data': data
  2830. })
  2831. @app.route('/api/sensor/threshold', methods=['GET', 'POST'])
  2832. def handle_env_sensor_threshold():
  2833. """获取或设置环境传感器告警阈值"""
  2834. if request.method == 'GET':
  2835. return jsonify({
  2836. 'success': True,
  2837. 'data': env_sensor_threshold
  2838. })
  2839. else:
  2840. try:
  2841. data = request.get_json()
  2842. for key in env_sensor_threshold.keys():
  2843. if key in data:
  2844. env_sensor_threshold[key] = float(data[key])
  2845. logger.info(f"更新环境传感器告警阈值: {env_sensor_threshold}")
  2846. return jsonify({
  2847. 'success': True,
  2848. 'message': '阈值设置成功',
  2849. 'data': env_sensor_threshold
  2850. })
  2851. except Exception as e:
  2852. logger.error(f"设置告警阈值失败: {str(e)}")
  2853. return jsonify({'success': False, 'message': str(e)}), 400
  2854. @app.route('/api/sensor/history', methods=['GET'])
  2855. def get_env_sensor_history():
  2856. """获取环境传感器历史数据"""
  2857. try:
  2858. import datetime
  2859. # 获取查询参数
  2860. range_param = request.args.get('range', '24h')
  2861. start_time = request.args.get('start_time')
  2862. end_time = request.args.get('end_time')
  2863. limit = request.args.get('limit', 100, type=int)
  2864. filtered_history = env_sensor_history
  2865. # 解析range参数
  2866. if not start_time and not end_time:
  2867. now = datetime.datetime.now()
  2868. if range_param == '1h':
  2869. start_time = (now - datetime.timedelta(hours=1)).strftime('%Y-%m-%d %H:%M:%S')
  2870. elif range_param == '6h':
  2871. start_time = (now - datetime.timedelta(hours=6)).strftime('%Y-%m-%d %H:%M:%S')
  2872. elif range_param == '24h':
  2873. start_time = (now - datetime.timedelta(hours=24)).strftime('%Y-%m-%d %H:%M:%S')
  2874. elif range_param == '7d':
  2875. start_time = (now - datetime.timedelta(days=7)).strftime('%Y-%m-%d %H:%M:%S')
  2876. elif range_param == '30d':
  2877. start_time = (now - datetime.timedelta(days=30)).strftime('%Y-%m-%d %H:%M:%S')
  2878. # 按时间过滤
  2879. if start_time:
  2880. filtered_history = [h for h in filtered_history if h.get('update_time') >= start_time]
  2881. if end_time:
  2882. filtered_history = [h for h in filtered_history if h.get('update_time') <= end_time]
  2883. # 按时间排序 (新到旧)
  2884. filtered_history = sorted(filtered_history, key=lambda x: x.get('update_time', ''), reverse=True)
  2885. # 限制返回数量
  2886. filtered_history = filtered_history[:limit]
  2887. return jsonify({
  2888. 'success': True,
  2889. 'data': filtered_history,
  2890. 'total': len(filtered_history)
  2891. })
  2892. except Exception as e:
  2893. logger.error(f"获取历史数据失败: {str(e)}")
  2894. return jsonify({'success': False, 'message': str(e)}), 500
  2895. def update_env_sensor_data_full(temperature, humidity, dtu_temperature, sensor_update_time):
  2896. """更新环境传感器数据 (由MQTT消息触发) - 完整版,含历史和告警"""
  2897. import datetime
  2898. now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  2899. env_sensor_data['temperature'] = temperature
  2900. env_sensor_data['humidity'] = humidity
  2901. env_sensor_data['dtu_temperature'] = dtu_temperature
  2902. env_sensor_data['sensor_update_time'] = sensor_update_time
  2903. env_sensor_data['update_time'] = now
  2904. env_sensor_data['connected'] = True
  2905. # 同步到 MQTT 上行所用的 _env_sensor_data
  2906. _env_sensor_data['temperature'] = temperature
  2907. _env_sensor_data['humidity'] = humidity
  2908. _env_sensor_data['sensor_update_time'] = sensor_update_time
  2909. # 添加到历史记录
  2910. history_record = {
  2911. 'temperature': temperature,
  2912. 'humidity': humidity,
  2913. 'dtu_temperature': dtu_temperature,
  2914. 'sensor_update_time': sensor_update_time,
  2915. 'update_time': now
  2916. }
  2917. env_sensor_history.append(history_record)
  2918. # 保留最近1000条
  2919. if len(env_sensor_history) > 1000:
  2920. env_sensor_history[:] = env_sensor_history[-1000:]
  2921. # 检查告警
  2922. check_env_sensor_alarms(temperature, humidity, dtu_temperature)
  2923. logger.info(f"环境传感器数据更新: 温度={temperature}℃, 湿度={humidity}%, DTU温度={dtu_temperature}℃")
  2924. def dht11_data_callback(temperature, humidity):
  2925. """DHT11 本地 GPIO 传感器数据回调。
  2926. 将读取到的温湿度更新到环境传感器数据区,并通过 MQTT 上报。
  2927. 保留已有的 dtu_temperature(主板温度),仅更新环境温湿度字段。
  2928. """
  2929. try:
  2930. sensor_update_time = int(time.time() * 1000)
  2931. dtu_temperature = env_sensor_data.get('dtu_temperature')
  2932. update_env_sensor_data_full(temperature, humidity, dtu_temperature, sensor_update_time)
  2933. # 立即通过 MQTT 上报环境传感器数据
  2934. try:
  2935. dtu_publish_env_sensor()
  2936. except Exception as pub_err:
  2937. logger.warning(f"DHT11 数据 MQTT 上报失败: {pub_err}")
  2938. logger.info(f"DHT11 本地传感器数据已处理: 温度={temperature}°C, 湿度={humidity}%")
  2939. except Exception as e:
  2940. logger.error(f"处理 DHT11 本地传感器数据失败: {e}")
  2941. def check_env_sensor_alarms(temperature, humidity, dtu_temperature):
  2942. """检查环境传感器告警"""
  2943. alarms = []
  2944. if temperature is not None:
  2945. if temperature > env_sensor_threshold['temp_high']:
  2946. alarms.append({
  2947. 'type': 'temperature_high',
  2948. 'message': f'环境温度过高: {temperature}℃ (阈值: {env_sensor_threshold["temp_high"]}℃)',
  2949. 'level': 'warning'
  2950. })
  2951. elif temperature < env_sensor_threshold['temp_low']:
  2952. alarms.append({
  2953. 'type': 'temperature_low',
  2954. 'message': f'环境温度过低: {temperature}℃ (阈值: {env_sensor_threshold["temp_low"]}℃)',
  2955. 'level': 'warning'
  2956. })
  2957. if humidity is not None:
  2958. if humidity > env_sensor_threshold['humidity_high']:
  2959. alarms.append({
  2960. 'type': 'humidity_high',
  2961. 'message': f'环境湿度过高: {humidity}% (阈值: {env_sensor_threshold["humidity_high"]}%)',
  2962. 'level': 'warning'
  2963. })
  2964. elif humidity < env_sensor_threshold['humidity_low']:
  2965. alarms.append({
  2966. 'type': 'humidity_low',
  2967. 'message': f'环境湿度过低: {humidity}% (阈值: {env_sensor_threshold["humidity_low"]}%)',
  2968. 'level': 'warning'
  2969. })
  2970. if dtu_temperature is not None:
  2971. if dtu_temperature > env_sensor_threshold['dtu_temp_high']:
  2972. alarms.append({
  2973. 'type': 'dtu_temp_high',
  2974. 'message': f'DTU主板温度过高: {dtu_temperature}℃ (阈值: {env_sensor_threshold["dtu_temp_high"]}℃)',
  2975. 'level': 'critical'
  2976. })
  2977. # 发送告警通知
  2978. for alarm in alarms:
  2979. logger.warning(f"环境传感器告警: {alarm['message']}")
  2980. # 可以通过WebSocket发送告警
  2981. socketio.emit('env_sensor_alarm', alarm)
  2982. if __name__ == '__main__':
  2983. try:
  2984. # 启动前的初始化工作
  2985. logger.info('启动串口-MQTT网关服务...')
  2986. logger.info(f"配置信息: 主机={FLASK_HOST}, 端口={FLASK_PORT}, 调试模式={FLASK_DEBUG}")
  2987. # 加载DTU配置
  2988. load_dtu_config()
  2989. # 加载设备配置
  2990. loaded = load_device_config()
  2991. logger.info(f"已加载 {len(loaded)} 个设备配置")
  2992. panel_config.clear()
  2993. for uid_hex, addr in loaded.items():
  2994. panel_id = f"PANEL_{dtu_config.get('dtu_id', 'DTU001')}_{addr}"
  2995. panel_config[panel_id] = {'address': addr, 'position': addr, 'panel_uid': uid_hex}
  2996. logger.info(f"已加载 {len(panel_config)} 个面板配置")
  2997. # 启动自动发现循环
  2998. def auto_discover_loop():
  2999. while True:
  3000. time.sleep(30)
  3001. try:
  3002. _st = serial_client.get_status()
  3003. if not (isinstance(_st, dict) and _st.get('connected', False)):
  3004. continue
  3005. if not dtu_config.get('enabled'):
  3006. continue
  3007. result = address_config.auto_configure(timeout=2.0)
  3008. if result.get('discovered', 0) > 0:
  3009. logger.info(f"自动发现: {result.get('discovered')} 个设备")
  3010. save_device_config()
  3011. now = time.time()
  3012. for uid in address_config.get_stored_devices():
  3013. device_last_seen[uid] = now
  3014. for pid in panel_config:
  3015. device_last_seen[pid] = now
  3016. except Exception as e:
  3017. logger.error(f"自动发现异常: {str(e)}")
  3018. import threading
  3019. t = threading.Thread(target=auto_discover_loop, daemon=True)
  3020. t.start()
  3021. logger.info("启动自动发现线程 (间隔30秒)")
  3022. # 启动DTU心跳定时器
  3023. if dtu_config.get('enabled'):
  3024. start_dtu_heartbeat()
  3025. logger.info("启动DTU心跳定时器")
  3026. # 启动端口轮询循环
  3027. def port_poll_loop():
  3028. while True:
  3029. interval = dtu_config.get('poll_interval_ms', 5000) / 1000.0
  3030. time.sleep(max(1, interval))
  3031. try:
  3032. _st = serial_client.get_status()
  3033. if not (isinstance(_st, dict) and _st.get('connected', False)):
  3034. continue
  3035. if not dtu_config.get('enabled'):
  3036. continue
  3037. if not panel_config:
  3038. continue
  3039. online = 0
  3040. offline = 0
  3041. for panel_id, cfg in panel_config.items():
  3042. addr = cfg.get('address', 1)
  3043. panel_ok = False
  3044. panel_ports = []
  3045. for port_id in range(1, 25):
  3046. try:
  3047. result = modbus_client.read_antenna_card(addr, port_id, timeout=1.0)
  3048. except Exception:
  3049. result = {'error': 'exception'}
  3050. if 'error' in result:
  3051. panel_ports.append({'port_id': port_id, 'status': 'UNKNOWN', 'jumper_uid': None})
  3052. continue
  3053. panel_ok = True
  3054. card_str = result.get('card_number_str', '')
  3055. uid = card_str.upper() if card_str and card_str != '0000000000000000' else ''
  3056. if panel_id not in port_state:
  3057. port_state[panel_id] = {}
  3058. if port_id not in port_state[panel_id]:
  3059. port_state[panel_id][port_id] = {'last_uid': None, 'expected_uid': None, 'alarm_count': 0, 'last_polled_at': int(time.time() * 1000)}
  3060. ps = port_state[panel_id][port_id]
  3061. ps['last_polled_at'] = int(time.time() * 1000)
  3062. last_uid = ps.get('last_uid')
  3063. if uid and uid != last_uid:
  3064. dtu_publish_event(panel_id, port_id, 'CONNECT' if not last_uid else 'MOVE', uid, last_uid)
  3065. ps['last_uid'] = uid
  3066. elif not uid and last_uid:
  3067. dtu_publish_event(panel_id, port_id, 'DISCONNECT', None, last_uid)
  3068. ps['last_uid'] = None
  3069. ps_exp = ps.get('expected_uid')
  3070. if dtu_config.get('alarm_enabled', True):
  3071. if ps_exp and uid and uid != ps_exp:
  3072. ps['alarm_count'] = ps.get('alarm_count', 0) + 1
  3073. sev = 'CRITICAL' if ps['alarm_count'] >= 3 else 'WARNING'
  3074. dtu_publish_alarm(panel_id, port_id, 'ILLEGAL_CONNECT', ps_exp, uid, sev)
  3075. elif ps_exp and not uid:
  3076. ps['alarm_count'] = ps.get('alarm_count', 0) + 1
  3077. sev = 'CRITICAL' if ps['alarm_count'] >= 3 else 'WARNING'
  3078. dtu_publish_alarm(panel_id, port_id, 'ILLEGAL_DISCONNECT', ps_exp, None, sev)
  3079. elif ps_exp and uid == ps_exp:
  3080. ps['alarm_count'] = 0
  3081. if uid:
  3082. port_status = 'ILLEGAL' if (ps_exp and uid != ps_exp) else 'CONNECTED'
  3083. else:
  3084. port_status = 'DISCONNECTED'
  3085. panel_ports.append({'port_id': port_id, 'status': port_status, 'jumper_uid': uid or None})
  3086. if panel_ok:
  3087. online += 1
  3088. device_last_seen[panel_id] = time.time()
  3089. device_last_seen[cfg.get('panel_uid', '')] = time.time()
  3090. dtu_publish_panel_status(panel_id, addr, panel_ports)
  3091. else:
  3092. offline += 1
  3093. dtu_publish_status(force=True)
  3094. except Exception as e:
  3095. logger.error(f"端口轮询异常: {str(e)}")
  3096. t2 = threading.Thread(target=port_poll_loop, daemon=True)
  3097. t2.start()
  3098. logger.info("启动端口轮询线程 (间隔5秒)")
  3099. # 启动 DHT11 本地传感器读取线程
  3100. if dht11_sensor is not None:
  3101. dht11_sensor.on_data = dht11_data_callback
  3102. dht11_sensor.start()
  3103. # 自动连接上次使用的串口
  3104. logger.info("尝试自动连接串口...")
  3105. auto_connect_serial()
  3106. # 启动服务
  3107. socketio.run(
  3108. app,
  3109. host=FLASK_HOST,
  3110. port=FLASK_PORT,
  3111. debug=FLASK_DEBUG,
  3112. use_reloader=False, # 禁用重载器以避免重复初始化问题
  3113. log_output=False, # 禁用Flask的日志输出,使用我们自己的日志配置
  3114. allow_unsafe_werkzeug=True
  3115. )
  3116. except KeyboardInterrupt:
  3117. # 优雅退出
  3118. logger.info('正在关闭应用...')
  3119. try:
  3120. if isinstance(serial_client.get_status(), dict) and serial_client.get_status().get("connected", False):
  3121. serial_client.disconnect()
  3122. logger.info('串口连接已断开')
  3123. if mqtt_client.get_status():
  3124. mqtt_client.disconnect()
  3125. logger.info('MQTT连接已断开')
  3126. if dht11_sensor is not None:
  3127. dht11_sensor.stop()
  3128. logger.info('DHT11 传感器线程已停止')
  3129. except Exception as e:
  3130. logger.error(f'关闭连接时出错: {str(e)}')
  3131. # 清理WebSocket连接
  3132. for client_type in connected_clients:
  3133. connected_clients[client_type].clear()
  3134. logger.info('应用已安全关闭')
  3135. except Exception as e:
  3136. logger.exception(f'应用启动失败') # 使用exception记录完整堆栈
  3137. # 确保资源被释放
  3138. try:
  3139. serial_client.disconnect()
  3140. mqtt_client.disconnect()
  3141. except:
  3142. pass