data_sender.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. import paho.mqtt.client as mqtt
  2. import json, time, requests
  3. class Sender:
  4. def __init__(self, logger):
  5. self.logger = logger
  6. self.topic = {
  7. 'billet_add': 'trace/performance/billet/add',
  8. 'heat_add': 'trace/performance/converter/add',
  9. 'billet_union': 'trace/billet/billetAssemblyNumber/add',
  10. 'host_send': 'syn/billetHotsendBase/save',
  11. 'car_add': 'syn/storageBill/add',
  12. 'car_save': 'syn/billetHotsendBase/shipp/save',
  13. 'car_go': 'syn/billetHotsendBase/shipp/depart',
  14. 'stack_add': 'syn/billet/addStacking'
  15. }
  16. self.url = {
  17. 'billet_add': 'http://192.168.0.119:8181/jeecg-boot/actualControl/billetActual/reportRealTimeBilletBasicInfo',
  18. 'heat_add': 'http://192.168.0.119:8181/jeecg-boot/actualControl/heatsActuals/reportRealTimeHeatsActuals',
  19. 'host_send': 'http://192.168.0.119:8181/billetHotsendBase/billetHotsendBase/add',
  20. 'car_add': 'http://192.168.0.119:8181/storageBill/add',
  21. 'car_save': 'http://192.168.0.119:8181/billetHotsendBase/billetHotsendBase/add',
  22. 'car_go': 'http://192.168.0.119:8181/billetHotsendBase/billetHotsendBase/rodLineDepart',
  23. 'stack_add': 'http://192.168.0.119:8181/billet/stackingAndLoadingVehicles/addStacking'
  24. }
  25. self.heat_tangible_temp = {
  26. 'optype' : 0,
  27. 'casterCode' : '',
  28. 'emptyLadleWeight' : 0.0,
  29. 'fullLadleWeight' : 0.0,
  30. 'grade' : '',
  31. 'spec' : '',
  32. 'heatsCode' : '',
  33. 'firstCutTime' : '',
  34. 'lastCutTime' : '',
  35. 'ladleCode' : '',
  36. 'moltenSteelWeight' : 0.0,
  37. 'startPourTime' : '',
  38. 'stopPourTime' : '',
  39. 'blankOutput' : 0.0,
  40. 'billetSum' : 0
  41. }
  42. self.billet_tangible_temp = {
  43. 'optype' : 0,
  44. 'heatNo' : '',
  45. 'billetNo' : '',
  46. 'grade' : '',
  47. 'ladleNo' : '',
  48. 'ccmNo' : '',
  49. 'strandNo' : '',
  50. 'heatnoIndex' : 0,
  51. 'length' : 0,
  52. 'strandnoIndex' : 0,
  53. 'castingSpeed' : 0.0,
  54. 'actualLength' : 0,
  55. 'spec' : '',
  56. 'width' : 170,
  57. 'thickness' : 170,
  58. 'weight' : 0.0,
  59. 'cutStartTime' : '',
  60. 'cutStopTime' : '',
  61. 'assemblyNumber' : ''
  62. }
  63. self.billet_union_temp = {
  64. "ccmNo": 0, # 铸机号 int数值类型
  65. "heatNo": "", # 炉号 字符串类型
  66. "billetsNo": "", # 坯号集合 字符串类型 逗号隔开
  67. "assemblyNumber": "", # 组坯号 字符串类型
  68. "assemblyTime": "", # 组坯时间 Date日期类型
  69. "length": 0, # 定尺 int数值类型
  70. "billetsNum": 0, # 钢坯数量 int数值类型
  71. "billetWeight": 0 # 钢坯坯重 double高精度数值类型
  72. }
  73. self.host_send_temp = {
  74. "ccmNo": "",
  75. "billetNos": "",
  76. "billetHotsendTypeConfigId": "",
  77. "vehicleNumber": "",
  78. "liftingTime": "",
  79. "location": "",
  80. "destination":"",
  81. "positionNum":"",
  82. "plateOrStack":"",
  83. "layer":"",
  84. "address":""
  85. }
  86. self.car_add_temp = {
  87. "ccmNo": "",
  88. "licensePlate": "",
  89. "billetHotsendTypeConfigId": "",
  90. "positionNum": ""
  91. }
  92. self.car_save_temp = {
  93. "ccmNo": "",
  94. "billetNos": "",
  95. "billetHotsendTypeConfigId": "",
  96. "licensePlate": "",
  97. "vehicleNumber": "",
  98. "liftingTime": "",
  99. "location": "",
  100. "destination":"",
  101. "positionNum":"",
  102. "plateOrStack":"",
  103. "layer":"",
  104. "address":""
  105. }
  106. self.car_go_temp = {
  107. "ccmNo": "",
  108. "licensePlate": ""
  109. }
  110. self.stack_add_temp = {
  111. "ccmNo": "",
  112. "billetHotsendTypeConfigId": "",
  113. "billetNoList": []
  114. }
  115. self.stack_dict = {
  116. "601堆垛": '6',
  117. "602堆垛": '7',
  118. "604堆垛": '8',
  119. "步进冷床": '9',
  120. "501堆垛": '10',
  121. }
  122. self.mqtt_cli = None
  123. self.http_flag = True
  124. self._cache = {}
  125. self._billet = {}
  126. def set_mqtt_client(self, cli):
  127. self.mqtt_cli = cli
  128. def send(self, purpose, payload, qos=2):
  129. if not isinstance(payload, dict):
  130. self.logger.error('[SENDER]发送数据非dict类型')
  131. raise TypeError(f"Need a dict type but {type(payload)} given.")
  132. return None
  133. self.logger.info(f"[SENDER]使用 {'MQTT'if self.mqtt_cli else ''} {'HTTP'if self.http_flag else ''} 发送数据")
  134. self.logger.debug(f"[SENDER]{purpose}:{payload}")
  135. if self.mqtt_cli and purpose in self.topic:
  136. if not self.mqtt_cli.is_connected:
  137. self.logger.error('[SENDER]MQTT:发送失败,MQTT未连接')
  138. if self.mqtt_cli.publish(self.topic[purpose], json.dumps(payload), qos)[0]:
  139. self.logger.error('[SENDER]MQTT:数据包发送失败')
  140. else:
  141. self.logger.info('[SENDER]MQTT:数据包发送成功')
  142. if self.http_flag and purpose in self.url:
  143. try:
  144. self.logger.debug('[SENDER]HTTP:'+requests.post(self.url[purpose], json=payload, timeout=2).text)
  145. except:
  146. self.logger.error('[SENDER]HTTP:请求超时')
  147. def begin_pour(self, heat_data, bigbagweight):
  148. tmp = self.heat_tangible_temp.copy()
  149. tmp['optype'] = 1
  150. tmp['casterCode'] = heat_data.get('ccmNo', '')
  151. tmp['emptyLadleWeight'] = bigbagweight - heat_data.get('netWeight', 0)
  152. tmp['fullLadleWeight'] = bigbagweight
  153. tmp['grade'] = heat_data.get('grade', '')
  154. tmp['spec'] = heat_data.get('spec', '')
  155. tmp['heatsCode'] = heat_data.get('heatNo', '')
  156. tmp['ladleCode'] = heat_data.get('ladleNo', '')
  157. tmp['moltenSteelWeight'] = heat_data.get('netWeight', 0)
  158. tmp['startPourTime'] = heat_data.get('sendTime', '')
  159. #此处应存储进数据库,暂时使用缓存处理
  160. self._cache[heat_data.get('heatNo', 'error')] = tmp
  161. self.send('heat_add', tmp)
  162. def end_pour(self, heat_data):
  163. if heat_data['heatNo'] in self._cache:
  164. tmp = self._cache[heat_data['heatNo']]
  165. tmp['optype'] = 2
  166. tmp['grade'] = heat_data.get('grade', '')
  167. tmp['spec'] = heat_data.get('spec', '')
  168. tmp['stopPourTime'] = heat_data.get('sendTime', '')
  169. #此处应存储进数据库,暂时使用缓存处理
  170. self._cache[heat_data.get('heatNo', 'error')] = tmp
  171. self.send('heat_add', tmp)
  172. else:
  173. self.logger.error(f"[SENDER]停浇:找不到对应的开浇数据,炉号:{heat_data['heatNo']}")
  174. def heat_first(self, heat_data, cuttime = None):
  175. if not cuttime:
  176. cuttime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
  177. tmp = self._cache[heat_data['heatNo']]
  178. tmp['optype'] = 2
  179. tmp['firstCutTime'] = cuttime
  180. #此处应存储进数据库,暂时使用缓存处理
  181. self._cache[heat_data.get('heatNo', 'error')] = tmp
  182. self.send('heat_add', tmp)
  183. def heat_last(self, heat_data, cuttime = None):
  184. if not cuttime:
  185. cuttime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
  186. tmp = self._cache[heat_data['heatNo']]
  187. tmp['optype'] = 2
  188. tmp['lastCutTime'] = cuttime
  189. #此处应存储进数据库,暂时使用缓存处理
  190. self._cache[heat_data.get('heatNo', 'error')] = tmp
  191. self.send('heat_add', tmp)
  192. def begin_cut(self, heat_data, billetNo, heatnoIndex, sizing, speed):
  193. cuttime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
  194. tmp = self.billet_tangible_temp.copy()
  195. tmp['optype'] = 1
  196. tmp['heatNo'] = heat_data.get('heatNo', '')
  197. tmp['billetNo'] = billetNo
  198. tmp['grade'] = heat_data.get('grade', '')
  199. tmp['spec'] = heat_data.get('spec', '')
  200. tmp['ladleNo'] = heat_data.get('ladleNo', '')
  201. tmp['ccmNo'] = heat_data.get('ccmNo', '')
  202. tmp['strandNo'] = billetNo[-3]
  203. tmp['heatnoIndex'] = heatnoIndex
  204. tmp['length'] = sizing
  205. tmp['strandnoIndex'] = int(billetNo[-2:])
  206. tmp['castingSpeed'] = speed
  207. tmp['weight'] = sizing / 1000 * 0.2265
  208. tmp['cutStartTime'] = cuttime
  209. #此处应存储进数据库,暂时使用缓存处理
  210. self._billet[heat_data.get('heatNo', '')+str(heatnoIndex)] = tmp
  211. self.send('billet_add', tmp)
  212. def end_cut(self, heat_data, heatnoIndex):
  213. cuttime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
  214. trycount = 4
  215. tmp = self._billet.get(heat_data['heatNo']+str(heatnoIndex), {})
  216. while not tmp:
  217. trycount -= 1
  218. time.sleep(0.5)
  219. tmp = self._billet.get(heat_data['heatNo']+str(heatnoIndex), {})
  220. if not tmp:
  221. self.logger.error(f"[SENDER]停切:找不到对应的开切数据,炉号:{heat_data['heatNo']},序号:{heatnoIndex}")
  222. return None
  223. tmp['optype'] = 2
  224. tmp['cutStopTime'] = cuttime
  225. #此处应存储进数据库,暂时使用缓存处理
  226. self._billet[heat_data.get('heatNo', '')+str(heatnoIndex)] = tmp
  227. self.send('billet_add', tmp)
  228. def billet_upload(self, heat_data, billetNo, heatnoIndex, sizing, speed, starttime, stoptime, unionNo):
  229. tmp = self.billet_tangible_temp.copy()
  230. tmp['optype'] = 1
  231. tmp['heatNo'] = heat_data.get('heatNo', '')
  232. tmp['billetNo'] = billetNo
  233. tmp['grade'] = heat_data.get('grade', '')
  234. tmp['spec'] = heat_data.get('spec', '')
  235. tmp['ladleNo'] = heat_data.get('ladleNo', '')
  236. tmp['ccmNo'] = heat_data.get('ccmNo', '')
  237. tmp['strandNo'] = billetNo[-3]
  238. tmp['heatnoIndex'] = heatnoIndex
  239. tmp['length'] = sizing
  240. tmp['strandnoIndex'] = int(billetNo[-2:])
  241. tmp['castingSpeed'] = speed
  242. tmp['weight'] = sizing / 1000 * 0.2265
  243. tmp['cutStartTime'] = starttime
  244. tmp['cutStopTime'] = stoptime
  245. tmp['assemblyNumber'] = unionNo
  246. #此处应存储进数据库
  247. self.send('billet_add', tmp)
  248. def billet_union(self, heat_data, unionNo, billetNos, sizing):
  249. tmp = self.billet_union_temp.copy()
  250. tmp['ccmNo'] = heat_data.get('ccmNo', '')
  251. tmp['heatNo'] = heat_data.get('heatNo', '')
  252. tmp['billetsNo'] = ','.join(billetNos)
  253. tmp['assemblyNumber'] = unionNo
  254. tmp['assemblyTime'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
  255. tmp['length'] = sizing
  256. tmp['billetsNum'] = len(billetNos)
  257. tmp['billetWeight'] = sizing / 1000 * 0.2265 * tmp['billetsNum']
  258. #此处应存储进数据库
  259. self.send('billet_union', tmp)
  260. def host_send(self, ccmNo, billetNos, dst_str, craneNo = "", fromaddr = ""):
  261. tmp = self.host_send_temp.copy()
  262. tmp['ccmNo'] = ccmNo
  263. tmp['billetNos'] = ','.join(billetNos) if isinstance(billetNos, list) else billetNos
  264. tmp['billetHotsendTypeConfigId'] = "1" if dst_str == "棒一" else "15"
  265. tmp['liftingTime'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
  266. tmp['vehicleNumber'] = craneNo
  267. tmp['location'] = fromaddr
  268. tmp['destination'] = dst_str
  269. #此处应存储进数据库
  270. self.send('host_send', tmp)
  271. def car_add(self, ccmNo, carNo, plate: str):
  272. tmp = self.car_add_temp.copy()
  273. tmp['ccmNo'] = ccmNo
  274. tmp['billetHotsendTypeConfigId'] = "16" if plate.startswith("陕E") else ""
  275. tmp['licensePlate'] = plate
  276. tmp['positionNum'] = carNo
  277. #此处应存储进数据库
  278. self.send('car_add', tmp)
  279. def car_save(self, ccmNo, billetNos, plate, craneNo, Ltime, fromaddr, toaddr, layer=0, address=0):
  280. tmp = self.car_save_temp.copy()
  281. tmp['ccmNo'] = ccmNo
  282. tmp['billetNos'] = ','.join(billetNos) if isinstance(billetNos, list) else billetNos
  283. tmp['billetHotsendTypeConfigId'] = "16" if plate.startswith("陕E") else ""
  284. tmp['licensePlate'] = plate
  285. tmp['vehicleNumber'] = craneNo
  286. tmp['liftingTime'] = Ltime
  287. tmp['location'] = fromaddr
  288. tmp['destination'] = toaddr
  289. tmp['positionNum'] = toaddr[-1] if len(toaddr) else ""
  290. tmp['plateOrStack'] = plate
  291. tmp['layer'] = str(layer)
  292. tmp['address'] = str(address)
  293. #此处应存储进数据库
  294. self.send('car_save', tmp)
  295. def car_go(self, ccmNo, carNo, plate = ''):
  296. tmp = self.car_go_temp.copy()
  297. tmp['ccmNo'] = ccmNo
  298. tmp['positionNum'] = carNo
  299. tmp['licensePlate'] = plate
  300. #此处应存储进数据库
  301. self.send('car_go', tmp)
  302. def stack_add(self, ccmNo, billetNos, craneNo, Ltime, fromaddr, toaddr, layer=0, address=0):
  303. tmp = self.stack_add_temp.copy()
  304. tmp['ccmNo'] = ccmNo
  305. tmp['billetHotsendTypeConfigId'] = self.stack_dict.get(toaddr, '')
  306. tmp['billetNoList'] = []
  307. tmp['billetNoList'].append({
  308. 'billetNos' : ','.join(billetNos) if isinstance(billetNos, list) else billetNos,
  309. 'vehicleNumber' : craneNo,
  310. 'liftingTime' : Ltime,
  311. 'location' : fromaddr,
  312. 'destination' : toaddr,
  313. 'positionNum' : "",
  314. 'plateOrStack' : toaddr,
  315. 'layer' : str(layer),
  316. 'address' : str(address)
  317. })
  318. #此处应存储进数据库
  319. self.send('stack_add', tmp)
  320. if __name__ == '__main__':
  321. import logging
  322. logger = logging.getLogger(__name__)
  323. logger.setLevel(level = logging.DEBUG)
  324. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  325. console = logging.StreamHandler()
  326. console.setLevel(logging.DEBUG)
  327. logger.addHandler(console)
  328. mqttcli = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, 'python-mqtt-992-sender_test')
  329. mqttcli.username_pw_set('admin', '123456')
  330. mqttcli.connect('192.168.0.119', 1883)
  331. mqttcli.loop_start()
  332. test = Sender(logger)
  333. test.set_mqtt_client(mqttcli)
  334. test.http_flag = False
  335. testheat = {"netWeight":140.06,"ladleNo":"13","heatNo":"25501045","grade":"微氮铌钢","castState":1,"spec":"上若泰基","ccmNo":"5","sendTime":"2025-01-20 09:44:17"}
  336. #test.host_send("5", "255010455107", "棒一")
  337. #test.host_send("6", ["256009976601","256009976701","256009976801","256009976602"], "高线", "A2")
  338. test.car_add("6", "4", "陕E00901")
  339. test.car_save("6", "256012036107,256012036207,256012036407,256012036108,", "陕E00901", "A3", "2025-01-23 16:22:17", "6#小冷床(右)", "车位4")
  340. #test.car_go("6", "陕E00901")