app.py 135 KB

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