app.py 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551
  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. assign_results = []
  2063. if responses:
  2064. assign_results = address_config.process_responses(responses)
  2065. for r in assign_results:
  2066. uid_bytes = r.get('uid', r.get('request', ''))
  2067. save_device_config()
  2068. return jsonify({
  2069. 'success': True,
  2070. 'responses': responses,
  2071. 'assign_results': assign_results,
  2072. 'count': len(responses)
  2073. })
  2074. except Exception as e:
  2075. logger.error(f'广播查询失败: {str(e)}')
  2076. return jsonify({'success': False, 'message': str(e)}), 500
  2077. @app.route('/api/modbus/auto_configure', methods=['POST'])
  2078. def modbus_auto_configure():
  2079. """自动配置设备地址"""
  2080. try:
  2081. data = request.json or {}
  2082. timeout = data.get('timeout')
  2083. if not (isinstance(serial_client.get_status(), dict) and serial_client.get_status().get("connected", False)):
  2084. return jsonify({'success': False, 'message': '串口未连接'}), 400
  2085. result = address_config.auto_configure(timeout)
  2086. if result.get('success') and (result.get('discovered', 0) > 0 or result.get('confirmed', 0) > 0 or result.get('assigned', 0) > 0):
  2087. save_device_config()
  2088. return jsonify(result)
  2089. except Exception as e:
  2090. logger.error(f'自动配置失败: {str(e)}')
  2091. return jsonify({'success': False, 'message': str(e)}), 500
  2092. @app.route('/api/modbus/stored_devices', methods=['GET'])
  2093. def get_stored_devices():
  2094. """获取已存储的设备列表"""
  2095. return jsonify({'success': True, 'devices': address_config.get_stored_devices()})
  2096. @app.route('/api/modbus/stored_devices', methods=['POST'])
  2097. def add_stored_device():
  2098. """添加已存储的设备"""
  2099. try:
  2100. data = request.json
  2101. uid = data.get('uid', '').lower()
  2102. address = data.get('address', 1)
  2103. if len(uid) != 24:
  2104. return jsonify({'success': False, 'message': 'UID长度必须是24个十六进制字符'}), 400
  2105. address_config.add_stored_device(uid, address)
  2106. save_device_config()
  2107. return jsonify({'success': True, 'message': f'已添加设备: UID={uid}, 地址={address}'})
  2108. except Exception as e:
  2109. return jsonify({'success': False, 'message': str(e)}), 500
  2110. @app.route('/api/modbus/load_config', methods=['POST'])
  2111. def modbus_load_config():
  2112. """从文件加载设备配置"""
  2113. try:
  2114. data = request.json
  2115. filepath = data.get('filepath', '/tmp/modbus_devices.json')
  2116. success = address_config.load_config(filepath)
  2117. return jsonify({'success': success, 'devices': address_config.get_stored_devices()})
  2118. except Exception as e:
  2119. return jsonify({'success': False, 'message': str(e)}), 500
  2120. @app.route('/api/modbus/save_config', methods=['POST'])
  2121. def modbus_save_config():
  2122. """保存设备配置到文件"""
  2123. try:
  2124. data = request.json
  2125. filepath = data.get('filepath', '/tmp/modbus_devices.json')
  2126. success = address_config.save_config(filepath)
  2127. return jsonify({'success': success, 'message': f'配置已保存到: {filepath}' if success else '保存失败'})
  2128. except Exception as e:
  2129. return jsonify({'success': False, 'message': str(e)}), 500
  2130. @app.route('/api/modbus/confirm_devices', methods=['POST'])
  2131. def confirm_devices():
  2132. """手动触发对所有已存储设备的确认"""
  2133. try:
  2134. devices = address_config.get_stored_devices()
  2135. if not devices:
  2136. return jsonify({'success': False, 'message': '没有已存储的设备'}), 400
  2137. if not (isinstance(serial_client.get_status(), dict) and serial_client.get_status().get("connected", False)):
  2138. return jsonify({'success': False, 'message': '串口未连接'}), 400
  2139. results = []
  2140. for uid_hex, addr in devices.items():
  2141. try:
  2142. uid_bytes = bytes.fromhex(uid_hex)
  2143. cmd = build_confirm_address(addr, uid_bytes)
  2144. success, msg = serial_client.send_raw(cmd)
  2145. logger.info(f"确认设备 地址={addr}: {'成功' if success else '失败 ' + msg}")
  2146. results.append({'address': addr, 'uid': uid_hex, 'success': success, 'message': msg})
  2147. except Exception as e:
  2148. results.append({'address': addr, 'uid': uid_hex, 'success': False, 'message': str(e)})
  2149. time.sleep(0.1)
  2150. return jsonify({'success': True, 'results': results, 'count': len(results)})
  2151. except Exception as e:
  2152. return jsonify({'success': False, 'message': str(e)}), 500
  2153. # 端口状态追踪 - 用于存储每个端口的事件状态
  2154. port_event_history = [] # 存储最近的端口事件
  2155. @app.route('/api/port/status', methods=['GET'])
  2156. def get_port_status():
  2157. """获取所有端口状态"""
  2158. return jsonify({'success': True, 'port_state': port_state})
  2159. @app.route('/api/port/events', methods=['GET'])
  2160. def get_port_events():
  2161. """获取端口事件历史"""
  2162. limit = request.args.get('limit', 100, type=int)
  2163. return jsonify({
  2164. 'success': True,
  2165. 'events': port_event_history[-limit:]
  2166. })
  2167. @app.route('/api/port/clear_events', methods=['POST'])
  2168. def clear_port_events():
  2169. """清除端口事件历史"""
  2170. global port_event_history
  2171. port_event_history = []
  2172. return jsonify({'success': True, 'message': '事件历史已清除'})
  2173. # 设备最后响应时间跟踪
  2174. device_last_seen = {}
  2175. @app.route('/api/panel/status', methods=['GET'])
  2176. def get_panel_status():
  2177. """获取所有面板状态"""
  2178. now = time.time()
  2179. PANEL_OFFLINE_TIMEOUT = 60
  2180. panel_status = {}
  2181. for panel_id, ports in port_state.items():
  2182. port_count = len(ports)
  2183. alarm_count = sum(1 for p in ports.values() if p.get('alarm_count', 0) > 0)
  2184. connected_count = sum(1 for p in ports.values() if p.get('last_uid'))
  2185. panel_status[panel_id] = {
  2186. 'panel_id': panel_id,
  2187. 'port_count': port_count,
  2188. 'connected_count': connected_count,
  2189. 'alarm_count': alarm_count,
  2190. 'status': 'online' if connected_count > 0 else 'offline'
  2191. }
  2192. for panel_id, cfg in panel_config.items():
  2193. last_seen = device_last_seen.get(panel_id, 0)
  2194. is_online = (now - last_seen) < PANEL_OFFLINE_TIMEOUT
  2195. if panel_id in panel_status:
  2196. panel_status[panel_id].update({
  2197. 'address': cfg.get('address'),
  2198. 'position': cfg.get('position'),
  2199. 'panel_uid': cfg.get('panel_uid'),
  2200. 'status': 'online' if is_online else 'offline'
  2201. })
  2202. else:
  2203. panel_status[panel_id] = {
  2204. 'panel_id': panel_id,
  2205. 'address': cfg.get('address'),
  2206. 'position': cfg.get('position'),
  2207. 'panel_uid': cfg.get('panel_uid'),
  2208. 'port_count': 0,
  2209. 'connected_count': 0,
  2210. 'alarm_count': 0,
  2211. 'status': 'online' if is_online else 'offline'
  2212. }
  2213. return jsonify({'success': True, 'panels': panel_status})
  2214. # LED 状态追踪 (内存中跟踪每个灯的最后设置状态)
  2215. led_states = {i: 0 for i in range(1, 25)} # 0=off, 1=red, 2=green, 3=blue
  2216. @app.route('/api/modbus/led_status', methods=['GET'])
  2217. def get_led_status():
  2218. """获取所有 LED 状态"""
  2219. return jsonify({'success': True, 'leds': led_states})
  2220. @app.route('/api/modbus/set_all_leds', methods=['POST'])
  2221. def set_all_leds():
  2222. """批量设置 LED
  2223. 请求: {"device_address": 1, "color": 1}
  2224. 设置所有 24 个 LED 到指定颜色
  2225. """
  2226. try:
  2227. data = request.json
  2228. device_address = data.get('device_address', 1)
  2229. color = data.get('color', 0)
  2230. timeout = data.get('timeout')
  2231. if not (isinstance(serial_client.get_status(), dict) and serial_client.get_status().get("connected", False)):
  2232. return jsonify({'success': False, 'message': '串口未连接'}), 400
  2233. results = []
  2234. for led_num in range(1, 25):
  2235. result = modbus_client.set_rgb_led(
  2236. device_address=device_address,
  2237. led_number=led_num,
  2238. color=color,
  2239. timeout=timeout
  2240. )
  2241. if 'error' in result:
  2242. results.append({'led': led_num, 'success': False, 'error': result['error']})
  2243. else:
  2244. results.append({'led': led_num, 'success': True})
  2245. led_states[led_num] = color
  2246. return jsonify({'success': True, 'results': results})
  2247. except Exception as e:
  2248. logger.error(f'批量设置LED失败: {str(e)}')
  2249. return jsonify({'success': False, 'message': str(e)}), 500
  2250. # 在 set_rgb_led 中更新 LED 状态追踪
  2251. # 不再需要静态文件目录,前端由nginx提供服务
  2252. # ========== DTU MQTT协议配置API ==========
  2253. @app.route('/api/dtu/config', methods=['GET'])
  2254. def get_dtu_config():
  2255. """获取DTU配置"""
  2256. return jsonify({
  2257. 'success': True,
  2258. 'data': dtu_config
  2259. })
  2260. @app.route('/api/dtu/config', methods=['POST'])
  2261. def update_dtu_config():
  2262. """更新DTU配置"""
  2263. try:
  2264. data = request.json
  2265. old_config = dtu_config.copy()
  2266. # 更新配置项
  2267. if 'topic_prefix' in data:
  2268. dtu_config['topic_prefix'] = data['topic_prefix']
  2269. if 'customer_id' in data:
  2270. dtu_config['customer_id'] = data['customer_id']
  2271. if 'dtu_id' in data:
  2272. dtu_config['dtu_id'] = data['dtu_id']
  2273. if 'firmware_version' in data:
  2274. dtu_config['firmware_version'] = data['firmware_version']
  2275. if 'hardware_version' in data:
  2276. dtu_config['hardware_version'] = data['hardware_version']
  2277. if 'heartbeat_interval' in data:
  2278. dtu_config['heartbeat_interval'] = data['heartbeat_interval']
  2279. if 'enabled' in data:
  2280. dtu_config['enabled'] = data['enabled']
  2281. # 如果MQTT已连接且主题配置发生变化,重新订阅
  2282. if mqtt_status and dtu_config.get('enabled'):
  2283. old_control_topic = build_dtu_topic(
  2284. old_config.get('customer_id', DEFAULT_CUSTOMER_ID),
  2285. 'dtu',
  2286. old_config.get('dtu_id', DEFAULT_DTU_ID),
  2287. 'control'
  2288. )
  2289. new_control_topic = build_dtu_topic(
  2290. dtu_config['customer_id'],
  2291. 'dtu',
  2292. dtu_config['dtu_id'],
  2293. 'control'
  2294. )
  2295. if old_control_topic != new_control_topic:
  2296. # 取消旧订阅,订阅新主题
  2297. mqtt_client.unsubscribe(old_control_topic)
  2298. mqtt_client.subscribe(new_control_topic)
  2299. logger.info(f"控制主题已更新: {old_control_topic} -> {new_control_topic}")
  2300. # 重新发送注册消息
  2301. dtu_register()
  2302. return jsonify({
  2303. 'success': True,
  2304. 'message': 'DTU配置已更新',
  2305. 'data': dtu_config
  2306. })
  2307. except Exception as e:
  2308. logger.error(f"更新DTU配置失败: {str(e)}")
  2309. return jsonify({'success': False, 'message': str(e)}), 500
  2310. @app.route('/api/dtu/register', methods=['POST'])
  2311. def manual_dtu_register():
  2312. """手动触发DTU注册"""
  2313. try:
  2314. if not mqtt_status:
  2315. return jsonify({'success': False, 'message': 'MQTT未连接'}), 400
  2316. success = dtu_register()
  2317. if success:
  2318. return jsonify({'success': True, 'message': '注册消息已发送'})
  2319. else:
  2320. return jsonify({'success': False, 'message': '注册消息发送失败'}), 500
  2321. except Exception as e:
  2322. logger.error(f"手动触发DTU注册失败: {str(e)}")
  2323. return jsonify({'success': False, 'message': str(e)}), 500
  2324. def _get_cpu_usage():
  2325. try:
  2326. import psutil
  2327. return psutil.cpu_percent(interval=None)
  2328. except Exception:
  2329. return None
  2330. def _get_memory_usage():
  2331. try:
  2332. import psutil
  2333. return psutil.virtual_memory().percent
  2334. except Exception:
  2335. return None
  2336. @app.route('/api/dtu/status', methods=['GET'])
  2337. def get_dtu_status():
  2338. """获取DTU状态"""
  2339. try:
  2340. # 获取串口状态
  2341. serial_st = serial_client.get_status()
  2342. # 获取面板状态
  2343. devices = address_config.get_stored_devices()
  2344. # 主板温度: 优先外部上报,否则本地读取
  2345. dtu_temperature = env_sensor_data.get('dtu_temperature')
  2346. if dtu_temperature is None:
  2347. try:
  2348. import psutil
  2349. temps = psutil.sensors_temperatures(fahrenheit=False) or {}
  2350. for chip_name, entries in temps.items():
  2351. for entry in entries:
  2352. if entry.current and entry.current > 0:
  2353. dtu_temperature = round(entry.current, 1)
  2354. break
  2355. if dtu_temperature is not None:
  2356. break
  2357. except Exception:
  2358. pass
  2359. if dtu_temperature is None:
  2360. import glob as _glob
  2361. for tz in sorted(_glob.glob('/sys/class/thermal/thermal_zone*/temp')):
  2362. try:
  2363. with open(tz) as f:
  2364. v = int(f.read().strip())
  2365. if v > 0:
  2366. dtu_temperature = round(v / 1000.0, 1)
  2367. break
  2368. except Exception:
  2369. continue
  2370. status = {
  2371. 'dtu_id': dtu_config.get('dtu_id'),
  2372. 'mqtt_connected': mqtt_status,
  2373. 'serial_connected': isinstance(serial_st, dict) and serial_st.get('connected', False),
  2374. 'dtu_enabled': dtu_config.get('enabled', True),
  2375. 'topic_prefix': dtu_config.get('topic_prefix'),
  2376. 'customer_id': dtu_config.get('customer_id'),
  2377. 'panel_count': len(devices),
  2378. 'cpu_usage': _get_cpu_usage(),
  2379. 'memory_usage': _get_memory_usage(),
  2380. 'temperature': dtu_temperature,
  2381. 'dtu_temperature': dtu_temperature,
  2382. 'firmware_version': dtu_config.get('firmware_version', 'v1.0.0'),
  2383. 'topics': {
  2384. 'register': build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'register'),
  2385. 'status': build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'status'),
  2386. 'control': build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'control'),
  2387. 'response': build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'response'),
  2388. 'event': build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'event'),
  2389. 'alarm': build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'alarm')
  2390. }
  2391. }
  2392. return jsonify({'success': True, 'data': status})
  2393. except Exception as e:
  2394. logger.error(f"获取DTU状态失败: {str(e)}")
  2395. return jsonify({'success': False, 'message': str(e)}), 500
  2396. @app.route('/api/dtu/control', methods=['POST'])
  2397. def dtu_control():
  2398. """发送DTU控制命令(HTTP 入口,复用 dtu_handle_control 逻辑)"""
  2399. try:
  2400. data = request.json or {}
  2401. # 兼容两种入参格式:
  2402. # 1) {"command": "...", "target": "...", "params": {...}} 简洁格式
  2403. # 2) {"payload": {"command": "...", "target": "...", "params": {...}}} MQTT envelope 格式
  2404. inner = data.get('payload') if isinstance(data.get('payload'), dict) else data
  2405. command = inner.get('command')
  2406. # REBOOT 走快速通道立即执行
  2407. if command == 'REBOOT':
  2408. import subprocess
  2409. logger.warning("执行系统重启命令")
  2410. threading.Thread(target=lambda: (
  2411. time.sleep(1),
  2412. subprocess.run(['reboot'], capture_output=True)
  2413. ), daemon=True).start()
  2414. return jsonify({'success': True, 'message': '系统正在重启...'})
  2415. # 其他命令委托给 MQTT 处理器(构造 MQTT envelope 后调用)
  2416. mqtt_envelope = {
  2417. 'msg_id': data.get('msg_id', f"http_{int(time.time() * 1000)}_{uuid.uuid4().hex[:6]}"),
  2418. 'timestamp': data.get('timestamp', int(time.time() * 1000)),
  2419. 'dtu_id': data.get('dtu_id', dtu_config.get('dtu_id')),
  2420. 'type': 'CONTROL',
  2421. 'payload': {
  2422. 'command': command,
  2423. 'target': inner.get('target'),
  2424. 'params': inner.get('params', {})
  2425. }
  2426. }
  2427. # 调用 MQTT 处理器(其内部会发送响应到 dtu/.../response 主题)
  2428. dtu_handle_control('http/control', mqtt_envelope)
  2429. # 如果命令是 QUERY_JUMPER_STATUS / QUERY_ENV_SENSOR / QUERY_DTU_STATUS,
  2430. # 实际响应已发布到对应主题,HTTP 端点仅返回成功标记
  2431. if command in ('QUERY_JUMPER_STATUS', 'QUERY_ENV_SENSOR', 'QUERY_DTU_STATUS'):
  2432. return jsonify({
  2433. 'success': True,
  2434. 'message': f'{command} 已发布到 MQTT 主题'
  2435. })
  2436. # 其他命令: 从 MQTT 主题同步拉取最新响应(简化处理:直接返回已发布标记)
  2437. return jsonify({
  2438. 'success': True,
  2439. 'message': f'{command} 命令已下发,等待 MQTT 响应'
  2440. })
  2441. except Exception as e:
  2442. logger.error(f"DTU控制命令失败: {str(e)}")
  2443. return jsonify({'success': False, 'message': str(e)}), 500
  2444. # OTA状态存储
  2445. ota_status = {
  2446. 'status': 'IDLE', # IDLE, DOWNLOADING, VERIFYING, FLASHING, SUCCESS, FAILED
  2447. 'progress': 0,
  2448. 'firmware_version': None,
  2449. 'target_version': None,
  2450. 'error_code': None,
  2451. 'error_message': None,
  2452. 'last_update': None
  2453. }
  2454. @app.route('/api/dtu/ota_detect', methods=['POST'])
  2455. def ota_detect():
  2456. """检测固件包信息(自动下载并解析 manifest)"""
  2457. try:
  2458. url = request.json.get('url', '')
  2459. if not url:
  2460. return jsonify({'success': False, 'message': '请提供固件 URL'}), 400
  2461. import urllib.request, tempfile, tarfile, json, hashlib
  2462. tmp = tempfile.mktemp(suffix='.tar.gz')
  2463. try:
  2464. urllib.request.urlretrieve(url, tmp)
  2465. except Exception as e:
  2466. return jsonify({'success': False, 'message': f'下载失败: {str(e)}'}), 400
  2467. file_size = os.path.getsize(tmp)
  2468. h = hashlib.md5()
  2469. with open(tmp, 'rb') as f:
  2470. for chunk in iter(lambda: f.read(65536), b''):
  2471. h.update(chunk)
  2472. md5sum = h.hexdigest()
  2473. version = ''
  2474. try:
  2475. with tarfile.open(tmp, 'r:gz') as tar:
  2476. m = tar.extractfile('firmware/firmware.json')
  2477. if m:
  2478. manifest = json.loads(m.read())
  2479. version = manifest.get('version', '')
  2480. except Exception as e:
  2481. logger.warning(f"解析 firmware.json 失败: {e}")
  2482. os.remove(tmp)
  2483. return jsonify({
  2484. 'success': True,
  2485. 'data': {
  2486. 'file_size': file_size,
  2487. 'checksum': md5sum,
  2488. 'checksum_type': 'MD5',
  2489. 'firmware_version': version
  2490. }
  2491. })
  2492. except Exception as e:
  2493. logger.error(f"检测固件失败: {str(e)}")
  2494. return jsonify({'success': False, 'message': str(e)}), 500
  2495. @app.route('/api/dtu/ota_status', methods=['GET'])
  2496. def get_ota_status():
  2497. """获取OTA升级状态"""
  2498. try:
  2499. return jsonify({
  2500. 'success': True,
  2501. 'data': {
  2502. 'current_firmware': dtu_config.get('firmware_version', 'v1.0.0'),
  2503. 'ota_status': ota_status.get('status', 'IDLE'),
  2504. 'ota_progress': ota_status.get('progress', 0),
  2505. 'target_version': ota_status.get('target_version'),
  2506. 'error_code': ota_status.get('error_code'),
  2507. 'error_message': ota_status.get('error_message'),
  2508. 'last_update': ota_status.get('last_update')
  2509. }
  2510. })
  2511. except Exception as e:
  2512. logger.error(f"获取OTA状态失败: {str(e)}")
  2513. return jsonify({'success': False, 'message': str(e)}), 500
  2514. def handle_ota_status(dtu_id, payload):
  2515. """处理MQTT上报的OTA状态"""
  2516. ota_status['status'] = payload.get('ota_status', 'IDLE')
  2517. ota_status['progress'] = payload.get('ota_progress', 0)
  2518. ota_status['firmware_version'] = payload.get('firmware_version')
  2519. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2520. error_code = payload.get('error_code')
  2521. if error_code and error_code != 0:
  2522. ota_status['error_code'] = error_code
  2523. ota_status['error_message'] = payload.get('error_message', get_ota_error_message(error_code))
  2524. ota_status['status'] = 'FAILED'
  2525. elif ota_status['status'] == 'SUCCESS':
  2526. ota_status['error_code'] = None
  2527. ota_status['error_message'] = None
  2528. if ota_status.get('firmware_version'):
  2529. dtu_config['firmware_version'] = ota_status['firmware_version']
  2530. save_dtu_config()
  2531. logger.info(f"MQTT OTA状态更新: {ota_status['status']}, 进度: {ota_status['progress']}%")
  2532. def get_ota_error_message(error_code):
  2533. error_messages = {1021: '已是目标版本', 1022: '校验失败', 1023: '下载失败', 1024: '写入失败', 1025: '存储空间不足'}
  2534. return error_messages.get(error_code, f'未知错误码: {error_code}')
  2535. def _publish_ota_progress():
  2536. """通过MQTT发布OTA进度"""
  2537. try:
  2538. if not mqtt_client.get_status():
  2539. return
  2540. topic = build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'status')
  2541. payload = {
  2542. 'msg_id': f"ota_status_{int(time.time() * 1000)}",
  2543. 'timestamp': int(time.time() * 1000),
  2544. 'dtu_id': dtu_config['dtu_id'],
  2545. 'type': 'STATUS',
  2546. 'payload': {
  2547. 'ota_status': ota_status.get('status', 'IDLE'),
  2548. 'ota_progress': ota_status.get('progress', 0),
  2549. 'firmware_version': ota_status.get('target_version', ''),
  2550. 'error_code': ota_status.get('error_code', 0),
  2551. 'error_message': ota_status.get('error_message')
  2552. }
  2553. }
  2554. mqtt_client.publish(topic, json.dumps(payload), qos=1)
  2555. except Exception:
  2556. pass
  2557. def _send_ota_error_response(error_code, original_msg_id=''):
  2558. """通过MQTT发送OTA错误响应(1021-1025)"""
  2559. try:
  2560. if not mqtt_client.get_status():
  2561. return
  2562. topic = build_dtu_topic(dtu_config['customer_id'], 'dtu', dtu_config['dtu_id'], 'response')
  2563. payload = {
  2564. 'msg_id': f"rsp_ota_{int(time.time() * 1000)}_{uuid.uuid4().hex[:6]}",
  2565. 'timestamp': int(time.time() * 1000),
  2566. 'dtu_id': dtu_config['dtu_id'],
  2567. 'type': 'RESPONSE',
  2568. 'payload': {
  2569. 'original_msg_id': original_msg_id,
  2570. 'command': 'OTA_UPGRADE',
  2571. 'success': False,
  2572. 'result': None,
  2573. 'error_code': error_code,
  2574. 'error_message': get_ota_error_message(error_code)
  2575. }
  2576. }
  2577. mqtt_client.publish(topic, json.dumps(payload), qos=1)
  2578. except Exception:
  2579. pass
  2580. def _run_ota(params):
  2581. """执行OTA升级(后台线程,供HTTP和MQTT共用)"""
  2582. import subprocess, os, hashlib, shutil, tarfile, tempfile, urllib.request
  2583. url = params['firmware_url']
  2584. version = params['firmware_version']
  2585. file_size = params['file_size']
  2586. checksum = params['checksum']
  2587. checksum_type = params.get('checksum_type', 'MD5').upper()
  2588. force = params.get('force_upgrade', False)
  2589. ota_status['status'] = 'DOWNLOADING'
  2590. ota_status['progress'] = 0
  2591. ota_status['target_version'] = version
  2592. ota_status['error_code'] = None
  2593. ota_status['error_message'] = None
  2594. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2595. _publish_ota_progress()
  2596. try:
  2597. tmp_dir = tempfile.mkdtemp(prefix='ota_')
  2598. fw_path = os.path.join(tmp_dir, 'firmware.tar.gz')
  2599. ota_status['progress'] = 5
  2600. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2601. logger.info(f"OTA: 开始下载固件 {url}")
  2602. req = urllib.request.Request(url, headers={'User-Agent': 'OTA-Updater'})
  2603. # 进度上报节流: 每 10% 或每 5 秒
  2604. last_published_pct = 0
  2605. last_publish_time = time.time()
  2606. with urllib.request.urlopen(req, timeout=120) as resp:
  2607. with open(fw_path, 'wb') as f:
  2608. total = int(resp.headers.get('Content-Length', 0))
  2609. downloaded = 0
  2610. while True:
  2611. chunk = resp.read(65536)
  2612. if not chunk: break
  2613. f.write(chunk)
  2614. downloaded += len(chunk)
  2615. if total:
  2616. pct = 5 + int(downloaded / total * 30)
  2617. ota_status['progress'] = min(pct, 35)
  2618. now = time.time()
  2619. if pct - last_published_pct >= 10 or (now - last_publish_time) >= 5:
  2620. last_published_pct = pct
  2621. last_publish_time = now
  2622. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2623. _publish_ota_progress()
  2624. dl_size = os.path.getsize(fw_path)
  2625. ota_status['progress'] = 40
  2626. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2627. _publish_ota_progress()
  2628. if abs(dl_size - file_size) > 1024:
  2629. raise Exception(f"文件大小不匹配: 预期{file_size}, 实际{dl_size}")
  2630. ota_status['status'] = 'VERIFYING'
  2631. ota_status['progress'] = 50
  2632. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2633. _publish_ota_progress()
  2634. h = hashlib.new(checksum_type)
  2635. with open(fw_path, 'rb') as f:
  2636. for chunk in iter(lambda: f.read(65536), b''): h.update(chunk)
  2637. actual_checksum = h.hexdigest().lower()
  2638. if actual_checksum != checksum.lower():
  2639. raise Exception(f"校验和不匹配: 预期{checksum}, 实际{actual_checksum}")
  2640. ota_status['progress'] = 60
  2641. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2642. _publish_ota_progress()
  2643. extract_dir = os.path.join(tmp_dir, 'firmware')
  2644. os.makedirs(extract_dir, exist_ok=True)
  2645. with tarfile.open(fw_path, 'r:gz') as tar: tar.extractall(extract_dir)
  2646. manifest_path = os.path.join(extract_dir, 'firmware', 'firmware.json')
  2647. if not os.path.exists(manifest_path):
  2648. raise Exception("固件包缺少 firmware.json")
  2649. with open(manifest_path, 'r') as f: manifest = json.load(f)
  2650. fw_version = manifest.get('version', version)
  2651. if not force:
  2652. current_ver = dtu_config.get('firmware_version', 'v0.0.0')
  2653. if fw_version == current_ver:
  2654. raise Exception(f'已是目标版本 {current_ver}')
  2655. ota_status['status'] = 'FLASHING'
  2656. ota_status['progress'] = 70
  2657. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2658. _publish_ota_progress()
  2659. fw_root = os.path.join(extract_dir, 'firmware')
  2660. project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  2661. excludes = {'__pycache__', '.git', 'log', 'venv'}
  2662. for root, dirs, files in os.walk(fw_root):
  2663. rel = os.path.relpath(root, fw_root)
  2664. if rel == '.': rel = ''
  2665. parts = rel.split(os.sep) if rel else []
  2666. if parts and parts[0] in excludes: continue
  2667. for fname in files:
  2668. if fname == 'firmware.json': continue
  2669. src = os.path.join(root, fname)
  2670. dst = os.path.join(project_dir, rel, fname)
  2671. os.makedirs(os.path.dirname(dst), exist_ok=True)
  2672. shutil.copy2(src, dst)
  2673. ota_status['progress'] = 90
  2674. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2675. dtu_config['firmware_version'] = fw_version
  2676. save_dtu_config()
  2677. ota_status['status'] = 'SUCCESS'
  2678. ota_status['progress'] = 100
  2679. ota_status['firmware_version'] = fw_version
  2680. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2681. _publish_ota_progress()
  2682. shutil.rmtree(tmp_dir, ignore_errors=True)
  2683. for i in range(10, 0, -1):
  2684. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2685. time.sleep(1)
  2686. logger.info("OTA: 重启服务...")
  2687. subprocess.Popen(
  2688. [subprocess.sys.executable, '-m', 'flask', 'run', '--host=0.0.0.0', '--port=5001'],
  2689. cwd=os.path.dirname(os.path.abspath(__file__)),
  2690. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
  2691. )
  2692. os._exit(0)
  2693. except Exception as e:
  2694. ota_status['status'] = 'FAILED'
  2695. ota_status['error_message'] = str(e)
  2696. ota_status['last_update'] = time.strftime('%Y-%m-%d %H:%M:%S')
  2697. # 映射错误到标准错误码 (1021-1025)
  2698. msg = str(e)
  2699. if '校验和' in msg or 'firmware.json' in msg:
  2700. ota_status['error_code'] = 1022
  2701. elif '已是目标版本' in msg:
  2702. ota_status['error_code'] = 1021
  2703. elif '下载' in msg or 'urlopen' in msg or 'Connection' in msg or 'timeout' in msg:
  2704. ota_status['error_code'] = 1023
  2705. elif '磁盘' in msg or '空间' in msg or 'No space' in msg:
  2706. ota_status['error_code'] = 1025
  2707. elif '写入' in msg or 'flash' in msg.lower() or 'shutil' in msg:
  2708. ota_status['error_code'] = 1024
  2709. else:
  2710. ota_status['error_code'] = 9999
  2711. _publish_ota_progress()
  2712. # 通过MQTT发送错误响应(同时适配HTTP和MQTT触发)
  2713. _send_ota_error_response(ota_status['error_code'], params.get('_incoming_msg_id', ''))
  2714. logger.error(f"OTA: 升级失败 - {str(e)}")
  2715. if 'tmp_dir' in dir() and tmp_dir and os.path.exists(tmp_dir):
  2716. shutil.rmtree(tmp_dir, ignore_errors=True)
  2717. @app.route('/api/dtu/ota_upgrade', methods=['POST'])
  2718. def trigger_ota_upgrade():
  2719. """触发OTA升级"""
  2720. try:
  2721. data = request.json
  2722. if not data:
  2723. return jsonify({'success': False, 'message': '请求体不能为空'}), 400
  2724. required_fields = ['firmware_url', 'firmware_version', 'file_size', 'checksum', 'checksum_type']
  2725. missing = [f for f in required_fields if not data.get(f)]
  2726. if missing:
  2727. return jsonify({'success': False, 'message': f'缺少必填字段: {", ".join(missing)}'}), 400
  2728. # 已是目标版本且未强制: 1021 (同时通过 MQTT 上报响应)
  2729. force_upgrade = data.get('force_upgrade', False)
  2730. current_version = dtu_config.get('firmware_version', 'v1.0.0')
  2731. if data['firmware_version'] == current_version and not force_upgrade:
  2732. # 通过 MQTT 上报 1021 响应 (与其他错误码一致)
  2733. try:
  2734. _send_ota_error_response(1021, data.get('msg_id', ''))
  2735. except Exception:
  2736. pass
  2737. return jsonify({
  2738. 'success': False,
  2739. 'error_code': 1021,
  2740. 'message': f'已是目标版本: {current_version}'
  2741. }), 400
  2742. # 注入 _incoming_msg_id 使 MQTT 错误响应可回填
  2743. ota_params = {**data, '_incoming_msg_id': data.get('msg_id', '')}
  2744. t = threading.Thread(target=_run_ota, args=(ota_params,), daemon=True)
  2745. t.start()
  2746. return jsonify({
  2747. 'success': True,
  2748. 'message': 'OTA升级已启动',
  2749. 'data': {
  2750. 'target_version': data['firmware_version'],
  2751. 'ota_status': 'DOWNLOADING'
  2752. }
  2753. })
  2754. except Exception as e:
  2755. logger.error(f"触发OTA升级失败: {str(e)}")
  2756. return jsonify({'success': False, 'message': str(e)}), 500
  2757. # ==================== 环境传感器 API ====================
  2758. # 环境传感器数据存储
  2759. env_sensor_data = {
  2760. 'temperature': None, # 环境温度 (℃)
  2761. 'humidity': None, # 环境湿度 (%)
  2762. 'dtu_temperature': None, # DTU主板温度 (℃)
  2763. 'update_time': None, # 数据更新时间
  2764. 'sensor_update_time': None, # 传感器更新时间
  2765. 'connected': False # 传感器连接状态
  2766. }
  2767. # 环境传感器告警阈值
  2768. env_sensor_threshold = {
  2769. 'temp_high': 45.0, # 环境温度上限 (℃)
  2770. 'temp_low': -10.0, # 环境温度下限 (℃)
  2771. 'humidity_high': 80.0, # 环境湿度上限 (%)
  2772. 'humidity_low': 20.0, # 环境湿度下限 (%)
  2773. 'dtu_temp_high': 70.0 # DTU主板温度上限 (℃)
  2774. }
  2775. # 环境传感器历史数据 (保留最近1000条)
  2776. env_sensor_history = []
  2777. @app.route('/api/sensor/env', methods=['GET'])
  2778. def get_env_sensor_data():
  2779. """获取环境传感器当前数据"""
  2780. data = dict(env_sensor_data)
  2781. # DTU 主板温度回退: 若外部未上报,从 sysfs 本地读取
  2782. if data.get('dtu_temperature') is None:
  2783. try:
  2784. import psutil
  2785. temps = psutil.sensors_temperatures(fahrenheit=False) or {}
  2786. for chip_name, entries in temps.items():
  2787. for entry in entries:
  2788. if entry.current and entry.current > 0:
  2789. data['dtu_temperature'] = round(entry.current, 1)
  2790. break
  2791. if data['dtu_temperature'] is not None:
  2792. break
  2793. except Exception:
  2794. pass
  2795. if data.get('dtu_temperature') is None:
  2796. import glob as _glob
  2797. for tz in sorted(_glob.glob('/sys/class/thermal/thermal_zone*/temp')):
  2798. try:
  2799. with open(tz) as f:
  2800. v = int(f.read().strip())
  2801. if v > 0:
  2802. data['dtu_temperature'] = round(v / 1000.0, 1)
  2803. data['update_time'] = data.get('update_time') or __import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  2804. break
  2805. except Exception:
  2806. continue
  2807. # 附加 CPU/内存使用率(始终本地读取)
  2808. data['cpu_usage'] = _get_cpu_usage()
  2809. data['memory_usage'] = _get_memory_usage()
  2810. return jsonify({
  2811. 'success': True,
  2812. 'data': data
  2813. })
  2814. @app.route('/api/sensor/threshold', methods=['GET', 'POST'])
  2815. def handle_env_sensor_threshold():
  2816. """获取或设置环境传感器告警阈值"""
  2817. if request.method == 'GET':
  2818. return jsonify({
  2819. 'success': True,
  2820. 'data': env_sensor_threshold
  2821. })
  2822. else:
  2823. try:
  2824. data = request.get_json()
  2825. for key in env_sensor_threshold.keys():
  2826. if key in data:
  2827. env_sensor_threshold[key] = float(data[key])
  2828. logger.info(f"更新环境传感器告警阈值: {env_sensor_threshold}")
  2829. return jsonify({
  2830. 'success': True,
  2831. 'message': '阈值设置成功',
  2832. 'data': env_sensor_threshold
  2833. })
  2834. except Exception as e:
  2835. logger.error(f"设置告警阈值失败: {str(e)}")
  2836. return jsonify({'success': False, 'message': str(e)}), 400
  2837. @app.route('/api/sensor/history', methods=['GET'])
  2838. def get_env_sensor_history():
  2839. """获取环境传感器历史数据"""
  2840. try:
  2841. import datetime
  2842. # 获取查询参数
  2843. range_param = request.args.get('range', '24h')
  2844. start_time = request.args.get('start_time')
  2845. end_time = request.args.get('end_time')
  2846. limit = request.args.get('limit', 100, type=int)
  2847. filtered_history = env_sensor_history
  2848. # 解析range参数
  2849. if not start_time and not end_time:
  2850. now = datetime.datetime.now()
  2851. if range_param == '1h':
  2852. start_time = (now - datetime.timedelta(hours=1)).strftime('%Y-%m-%d %H:%M:%S')
  2853. elif range_param == '6h':
  2854. start_time = (now - datetime.timedelta(hours=6)).strftime('%Y-%m-%d %H:%M:%S')
  2855. elif range_param == '24h':
  2856. start_time = (now - datetime.timedelta(hours=24)).strftime('%Y-%m-%d %H:%M:%S')
  2857. elif range_param == '7d':
  2858. start_time = (now - datetime.timedelta(days=7)).strftime('%Y-%m-%d %H:%M:%S')
  2859. elif range_param == '30d':
  2860. start_time = (now - datetime.timedelta(days=30)).strftime('%Y-%m-%d %H:%M:%S')
  2861. # 按时间过滤
  2862. if start_time:
  2863. filtered_history = [h for h in filtered_history if h.get('update_time') >= start_time]
  2864. if end_time:
  2865. filtered_history = [h for h in filtered_history if h.get('update_time') <= end_time]
  2866. # 按时间排序 (新到旧)
  2867. filtered_history = sorted(filtered_history, key=lambda x: x.get('update_time', ''), reverse=True)
  2868. # 限制返回数量
  2869. filtered_history = filtered_history[:limit]
  2870. return jsonify({
  2871. 'success': True,
  2872. 'data': filtered_history,
  2873. 'total': len(filtered_history)
  2874. })
  2875. except Exception as e:
  2876. logger.error(f"获取历史数据失败: {str(e)}")
  2877. return jsonify({'success': False, 'message': str(e)}), 500
  2878. def update_env_sensor_data_full(temperature, humidity, dtu_temperature, sensor_update_time):
  2879. """更新环境传感器数据 (由MQTT消息触发) - 完整版,含历史和告警"""
  2880. import datetime
  2881. now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  2882. env_sensor_data['temperature'] = temperature
  2883. env_sensor_data['humidity'] = humidity
  2884. env_sensor_data['dtu_temperature'] = dtu_temperature
  2885. env_sensor_data['sensor_update_time'] = sensor_update_time
  2886. env_sensor_data['update_time'] = now
  2887. env_sensor_data['connected'] = True
  2888. # 同步到 MQTT 上行所用的 _env_sensor_data
  2889. _env_sensor_data['temperature'] = temperature
  2890. _env_sensor_data['humidity'] = humidity
  2891. _env_sensor_data['sensor_update_time'] = sensor_update_time
  2892. # 添加到历史记录
  2893. history_record = {
  2894. 'temperature': temperature,
  2895. 'humidity': humidity,
  2896. 'dtu_temperature': dtu_temperature,
  2897. 'sensor_update_time': sensor_update_time,
  2898. 'update_time': now
  2899. }
  2900. env_sensor_history.append(history_record)
  2901. # 保留最近1000条
  2902. if len(env_sensor_history) > 1000:
  2903. env_sensor_history[:] = env_sensor_history[-1000:]
  2904. # 检查告警
  2905. check_env_sensor_alarms(temperature, humidity, dtu_temperature)
  2906. logger.info(f"环境传感器数据更新: 温度={temperature}℃, 湿度={humidity}%, DTU温度={dtu_temperature}℃")
  2907. def check_env_sensor_alarms(temperature, humidity, dtu_temperature):
  2908. """检查环境传感器告警"""
  2909. alarms = []
  2910. if temperature is not None:
  2911. if temperature > env_sensor_threshold['temp_high']:
  2912. alarms.append({
  2913. 'type': 'temperature_high',
  2914. 'message': f'环境温度过高: {temperature}℃ (阈值: {env_sensor_threshold["temp_high"]}℃)',
  2915. 'level': 'warning'
  2916. })
  2917. elif temperature < env_sensor_threshold['temp_low']:
  2918. alarms.append({
  2919. 'type': 'temperature_low',
  2920. 'message': f'环境温度过低: {temperature}℃ (阈值: {env_sensor_threshold["temp_low"]}℃)',
  2921. 'level': 'warning'
  2922. })
  2923. if humidity is not None:
  2924. if humidity > env_sensor_threshold['humidity_high']:
  2925. alarms.append({
  2926. 'type': 'humidity_high',
  2927. 'message': f'环境湿度过高: {humidity}% (阈值: {env_sensor_threshold["humidity_high"]}%)',
  2928. 'level': 'warning'
  2929. })
  2930. elif humidity < env_sensor_threshold['humidity_low']:
  2931. alarms.append({
  2932. 'type': 'humidity_low',
  2933. 'message': f'环境湿度过低: {humidity}% (阈值: {env_sensor_threshold["humidity_low"]}%)',
  2934. 'level': 'warning'
  2935. })
  2936. if dtu_temperature is not None:
  2937. if dtu_temperature > env_sensor_threshold['dtu_temp_high']:
  2938. alarms.append({
  2939. 'type': 'dtu_temp_high',
  2940. 'message': f'DTU主板温度过高: {dtu_temperature}℃ (阈值: {env_sensor_threshold["dtu_temp_high"]}℃)',
  2941. 'level': 'critical'
  2942. })
  2943. # 发送告警通知
  2944. for alarm in alarms:
  2945. logger.warning(f"环境传感器告警: {alarm['message']}")
  2946. # 可以通过WebSocket发送告警
  2947. socketio.emit('env_sensor_alarm', alarm)
  2948. if __name__ == '__main__':
  2949. try:
  2950. # 启动前的初始化工作
  2951. logger.info('启动串口-MQTT网关服务...')
  2952. logger.info(f"配置信息: 主机={FLASK_HOST}, 端口={FLASK_PORT}, 调试模式={FLASK_DEBUG}")
  2953. # 加载DTU配置
  2954. load_dtu_config()
  2955. # 加载设备配置
  2956. loaded = load_device_config()
  2957. logger.info(f"已加载 {len(loaded)} 个设备配置")
  2958. panel_config.clear()
  2959. for uid_hex, addr in loaded.items():
  2960. panel_id = f"PANEL_{dtu_config.get('dtu_id', 'DTU001')}_{addr}"
  2961. panel_config[panel_id] = {'address': addr, 'position': addr, 'panel_uid': uid_hex}
  2962. logger.info(f"已加载 {len(panel_config)} 个面板配置")
  2963. # 启动自动发现循环
  2964. def auto_discover_loop():
  2965. while True:
  2966. time.sleep(30)
  2967. try:
  2968. _st = serial_client.get_status()
  2969. if not (isinstance(_st, dict) and _st.get('connected', False)):
  2970. continue
  2971. if not dtu_config.get('enabled'):
  2972. continue
  2973. result = address_config.auto_configure(timeout=2.0)
  2974. if result.get('discovered', 0) > 0:
  2975. logger.info(f"自动发现: {result.get('discovered')} 个设备")
  2976. save_device_config()
  2977. now = time.time()
  2978. for uid in address_config.get_stored_devices():
  2979. device_last_seen[uid] = now
  2980. for pid in panel_config:
  2981. device_last_seen[pid] = now
  2982. except Exception as e:
  2983. logger.error(f"自动发现异常: {str(e)}")
  2984. import threading
  2985. t = threading.Thread(target=auto_discover_loop, daemon=True)
  2986. t.start()
  2987. logger.info("启动自动发现线程 (间隔30秒)")
  2988. # 启动DTU心跳定时器
  2989. if dtu_config.get('enabled'):
  2990. start_dtu_heartbeat()
  2991. logger.info("启动DTU心跳定时器")
  2992. # 启动端口轮询循环
  2993. def port_poll_loop():
  2994. while True:
  2995. interval = dtu_config.get('poll_interval_ms', 5000) / 1000.0
  2996. time.sleep(max(1, interval))
  2997. try:
  2998. _st = serial_client.get_status()
  2999. if not (isinstance(_st, dict) and _st.get('connected', False)):
  3000. continue
  3001. if not dtu_config.get('enabled'):
  3002. continue
  3003. if not panel_config:
  3004. continue
  3005. online = 0
  3006. offline = 0
  3007. for panel_id, cfg in panel_config.items():
  3008. addr = cfg.get('address', 1)
  3009. panel_ok = False
  3010. panel_ports = []
  3011. for port_id in range(1, 25):
  3012. try:
  3013. result = modbus_client.read_antenna_card(addr, port_id, timeout=1.0)
  3014. except Exception:
  3015. result = {'error': 'exception'}
  3016. if 'error' in result:
  3017. panel_ports.append({'port_id': port_id, 'status': 'UNKNOWN', 'jumper_uid': None})
  3018. continue
  3019. panel_ok = True
  3020. card_str = result.get('card_number_str', '')
  3021. uid = card_str.upper() if card_str and card_str != '0000000000000000' else ''
  3022. if panel_id not in port_state:
  3023. port_state[panel_id] = {}
  3024. if port_id not in port_state[panel_id]:
  3025. port_state[panel_id][port_id] = {'last_uid': None, 'expected_uid': None, 'alarm_count': 0, 'last_polled_at': int(time.time() * 1000)}
  3026. ps = port_state[panel_id][port_id]
  3027. ps['last_polled_at'] = int(time.time() * 1000)
  3028. last_uid = ps.get('last_uid')
  3029. if uid and uid != last_uid:
  3030. dtu_publish_event(panel_id, port_id, 'CONNECT' if not last_uid else 'MOVE', uid, last_uid)
  3031. ps['last_uid'] = uid
  3032. elif not uid and last_uid:
  3033. dtu_publish_event(panel_id, port_id, 'DISCONNECT', None, last_uid)
  3034. ps['last_uid'] = None
  3035. ps_exp = ps.get('expected_uid')
  3036. if dtu_config.get('alarm_enabled', True):
  3037. if ps_exp and uid and uid != ps_exp:
  3038. ps['alarm_count'] = ps.get('alarm_count', 0) + 1
  3039. sev = 'CRITICAL' if ps['alarm_count'] >= 3 else 'WARNING'
  3040. dtu_publish_alarm(panel_id, port_id, 'ILLEGAL_CONNECT', ps_exp, uid, sev)
  3041. elif ps_exp and not uid:
  3042. ps['alarm_count'] = ps.get('alarm_count', 0) + 1
  3043. sev = 'CRITICAL' if ps['alarm_count'] >= 3 else 'WARNING'
  3044. dtu_publish_alarm(panel_id, port_id, 'ILLEGAL_DISCONNECT', ps_exp, None, sev)
  3045. elif ps_exp and uid == ps_exp:
  3046. ps['alarm_count'] = 0
  3047. if uid:
  3048. port_status = 'ILLEGAL' if (ps_exp and uid != ps_exp) else 'CONNECTED'
  3049. else:
  3050. port_status = 'DISCONNECTED'
  3051. panel_ports.append({'port_id': port_id, 'status': port_status, 'jumper_uid': uid or None})
  3052. if panel_ok:
  3053. online += 1
  3054. device_last_seen[panel_id] = time.time()
  3055. device_last_seen[cfg.get('panel_uid', '')] = time.time()
  3056. dtu_publish_panel_status(panel_id, addr, panel_ports)
  3057. else:
  3058. offline += 1
  3059. dtu_publish_status(force=True)
  3060. except Exception as e:
  3061. logger.error(f"端口轮询异常: {str(e)}")
  3062. t2 = threading.Thread(target=port_poll_loop, daemon=True)
  3063. t2.start()
  3064. logger.info("启动端口轮询线程 (间隔5秒)")
  3065. # 自动连接上次使用的串口
  3066. logger.info("尝试自动连接串口...")
  3067. auto_connect_serial()
  3068. # 启动服务
  3069. socketio.run(
  3070. app,
  3071. host=FLASK_HOST,
  3072. port=FLASK_PORT,
  3073. debug=FLASK_DEBUG,
  3074. use_reloader=False, # 禁用重载器以避免重复初始化问题
  3075. log_output=False, # 禁用Flask的日志输出,使用我们自己的日志配置
  3076. allow_unsafe_werkzeug=True
  3077. )
  3078. except KeyboardInterrupt:
  3079. # 优雅退出
  3080. logger.info('正在关闭应用...')
  3081. try:
  3082. if isinstance(serial_client.get_status(), dict) and serial_client.get_status().get("connected", False):
  3083. serial_client.disconnect()
  3084. logger.info('串口连接已断开')
  3085. if mqtt_client.get_status():
  3086. mqtt_client.disconnect()
  3087. logger.info('MQTT连接已断开')
  3088. except Exception as e:
  3089. logger.error(f'关闭连接时出错: {str(e)}')
  3090. # 清理WebSocket连接
  3091. for client_type in connected_clients:
  3092. connected_clients[client_type].clear()
  3093. logger.info('应用已安全关闭')
  3094. except Exception as e:
  3095. logger.exception(f'应用启动失败') # 使用exception记录完整堆栈
  3096. # 确保资源被释放
  3097. try:
  3098. serial_client.disconnect()
  3099. mqtt_client.disconnect()
  3100. except:
  3101. pass