ExportIO.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import json
  2. import message_pb2 as message
  3. import google.protobuf.text_format as tf
  4. import queue
  5. import time
  6. import asyncio
  7. import async_communication as ASC
  8. import threading
  9. '''
  10. 单片机状态,2表示门已经关闭
  11. '''
  12. class ExportIO(threading.Thread):
  13. def __init__(self,parameter,rabbitmq_parameter):
  14. threading.Thread.__init__(self)
  15. self._unit,self._id,self._ip,self._port=parameter
  16. self._close=False
  17. self._latest_iomsg=None
  18. self._last_user_table = None
  19. self._send_queue=queue.Queue()
  20. self._last_statucall_time=time.time()
  21. self._user_leave_callback=None
  22. self._last_table=None
  23. self._open_door_flag = False
  24. self._rabbit_mq=ASC.RabbitAsyncCommunicator(rabbitmq_parameter["ip"],rabbitmq_parameter["port"],
  25. rabbitmq_parameter['user'],rabbitmq_parameter['password'])
  26. #消费关门消息
  27. self._rabbit_mq.Init(None, None)
  28. self._rabbit_mq.start()
  29. #数据库重试的次数, 超过3次就重启数据库梁
  30. self._retry_count = 0
  31. def SetUserLeaveCallback(self,callback):
  32. self._user_leave_callback=callback
  33. def close(self):
  34. self._close=True
  35. self._rabbit_mq.close()
  36. self.join()
  37. def export_idle(self):
  38. if self._latest_iomsg==None:
  39. return False
  40. else:
  41. return self._latest_iomsg.outside_safety==1
  42. #open_door 函数,负责修改开门任务标记,只要数据库查到了,就把_open_door_flag修改为true
  43. #open_door 函数被node_py的主函数调用,不要做太多的事,剩余的开门控制和数据库清理,交给open_door_loop
  44. def open_door(self,table):
  45. self._open_door_flag = True
  46. return
  47. async def open_door_loop(self):
  48. while self._close==False:
  49. try:
  50. if (self._latest_iomsg is not None) and self._open_door_flag == True:
  51. #门不是开状态,那么就发送开门,无论里面是否有车
  52. if self._latest_iomsg.door_statu != 2:
  53. print(" 出口编号:%d , 执行开门 " % (self._id))
  54. opencmd = "{\"TerminalID\": %d, \"DispatchDirection\": 2, \"OutPutDo\": {\"Do0\": 0, \"Do1\": 0, \"Do2\": 0,\"Do3\": 0,\"Do4\": 0, \"Do5\": 0, \"Do6\": 0, \"Do7\": 0}, \"ProcessControl\": 4}" % (
  55. self._id - 1)
  56. print(opencmd)
  57. self._send_queue.put(opencmd)
  58. print(" opendoor queue size:%d"%self._send_queue.qsize())
  59. await asyncio.sleep(3)
  60. #如果门开到位,则检查汽车是否离开,如果没车就删库,清除flag, 注意了, 在汽车离开3秒后,由单片机底层自动关门,我们不用管
  61. elif self._latest_iomsg.outside_safety == 1:
  62. if not self._user_leave_callback == None:
  63. self._user_leave_callback(self._id)
  64. self._open_door_flag = False
  65. self._retry_count = self._retry_count + 1
  66. print(" _retry_count = %d"%self._retry_count)
  67. else:#else 无限等待,什么也不做, 等待汽车离开
  68. self._retry_count = 0
  69. except:
  70. pass
  71. await asyncio.sleep(0)
  72. async def connect(self):
  73. print("Trying to connect {}:{}".format(self._ip, self._port))
  74. while self._close == False:
  75. try:
  76. reader, writer = await asyncio.open_connection(
  77. self._ip, self._port
  78. )
  79. break
  80. except Exception as e:
  81. print("Failed to connect {} {}: {}".format(self._ip, self._port, e))
  82. await asyncio.sleep(3)
  83. print("Connected to {}:{}".format(self._ip, self._port))
  84. return reader, writer
  85. async def recv_loop(self):
  86. # if (self._id == 5):
  87. # print(" test 1 ")
  88. while self._close==False:
  89. # if (self._id == 5):
  90. # print(" test 2 ")
  91. try:
  92. recieve=await self._reader.readuntil(b'$')
  93. # if (self._id == 5):
  94. # print(" 00 recieve = " + str(recieve))
  95. except Exception as e:
  96. print("self._reader.readuntil(b'$') error")
  97. print(" e: {}".format(e))
  98. self._reader,self._writer=await self.connect()
  99. await asyncio.sleep(0.001)
  100. continue
  101. #socket.ConnectionResetError:
  102. # print(recieve)
  103. start_index = recieve.find(b'@')
  104. end_index = recieve.find(b'$')
  105. if start_index >= 0 and end_index >= 0 and end_index >=start_index:
  106. bytes = recieve[start_index + 4:end_index]
  107. self._latest_iomsg =self.recieve2message(bytes)
  108. if (not self._rabbit_mq == None) and (not self._latest_iomsg == None):
  109. if self._latest_iomsg.outside_safety == 0 or self._latest_iomsg.door_statu == 0:
  110. print("self._latest_iomsg error")
  111. continue
  112. else:
  113. # if (self._id == 5):
  114. # print(" 11 recieve = " + str(recieve))
  115. ex_name = "statu_ex"
  116. key = "out_mcpu_%d_statu_port" % self._id
  117. self._rabbit_mq.publish(ex_name, key, tf.MessageToString(self._latest_iomsg, as_utf8=True))
  118. else:
  119. print("self._rabbit_mq")
  120. print(self._rabbit_mq)
  121. print("self._latest_iomsg")
  122. print(self._latest_iomsg)
  123. else:
  124. print(" start_index = %s"%start_index)
  125. print("end_index = %s"%end_index)
  126. print("WARNING : mcpu recieve format error , time = %s"%time.time())
  127. print(" 22 recieve = " + str(recieve))
  128. await asyncio.sleep(0)
  129. continue
  130. await asyncio.sleep(0)
  131. async def send_loop(self):
  132. while self._close == False:
  133. try:
  134. if self._send_queue.qsize() > 0:
  135. print("给单片机发送指令 size:%d" % self._send_queue.qsize())
  136. msg = self._send_queue.get(False)
  137. if not msg == None:
  138. self._writer.write(msg.encode())
  139. await self._writer.drain()
  140. except Exception as e:
  141. print(" send error :{}".format(e))
  142. self._reader, self._writer = await self.connect()
  143. await asyncio.sleep(0)
  144. time.sleep(0.001)
  145. async def main(self):
  146. self._reader,self._writer=await self.connect()
  147. await asyncio.gather(self.recv_loop(),self.send_loop(),self.open_door_loop())
  148. def run(self):
  149. asyncio.run(self.main())
  150. def recieve2message(self,bytes):
  151. try:
  152. data=json.loads(bytes)
  153. except:
  154. print("tf json load error ")
  155. return None
  156. statu_msg=message.out_mcpu_statu()
  157. if 'InsideExistenceFlag' in data.keys():
  158. statu_msg.outside_safety = data['InsideExistenceFlag'] + 1
  159. else:
  160. print("statu_msg.outside_safety not live")
  161. print(bytes)
  162. statu_msg.outside_safety = 0
  163. if 'OutsideDoorStatus' in data.keys():
  164. statu_msg.door_statu = data["OutsideDoorStatus"] + 1 # 1 k 2g 3 running
  165. else:
  166. print("statu_msg.door_statu not live ")
  167. print(bytes)
  168. statu_msg.door_statu = 0
  169. return statu_msg