test_tcp_0.9.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. from multiprocessing import Process
  2. #from event_storage import EventStorage
  3. from memory_storage import MemoryStorage
  4. from sonar_socket2 import Receiver
  5. from sonar_udp import sender
  6. from sonar_command_tcp_once import Client
  7. import socket
  8. import struct
  9. import time
  10. import construct as c
  11. import redis
  12. servo_angle = 'servo1_angle'
  13. MIN_ANGLE = 5
  14. MAX_ANGLE = 355
  15. servo_data = c.Struct(
  16. header=c.Int16ul, # 固定不便,可能用于区分不同设备
  17. none_1=c.Int8ub, # 固定不便,可能用于区分不同设备
  18. servo1_flag=c.Int8ub,
  19. none_2=c.Int8ub, # 固定不便,可能用于区分不同设备
  20. servo2_flag=c.Int8ub,
  21. depth=c.Bytes(4),
  22. temp=c.Bytes(4),
  23. yaw=c.Bytes(4), # 航向
  24. roll=c.Bytes(4), # 横滚
  25. pitch=c.Bytes(4), # 俯仰
  26. servo1_angle=c.Bytes(4),
  27. servo2_angle=c.Bytes(4),
  28. )
  29. class MyProcess(Process): #继承Process类
  30. def __init__(self,name,config):
  31. super(MyProcess,self).__init__()
  32. self.name = name
  33. self.__sock = None
  34. self.__ip = config['ip']
  35. self.__port = config['port']
  36. self.__save_run_time = 0
  37. #self.__converter = converter
  38. #self.__storager = MemoryStorage({'ip':'127.0.0.1','port':4001})
  39. # self.__save_frequency = config['save_frequency']
  40. self.__save_frequency = 300 #最小值60
  41. self.redis_db = None
  42. self.__connected = False
  43. self.run_count = 0
  44. self.servo_status = None
  45. def run(self):
  46. self.__connect()
  47. self.__connected = True
  48. self.redis_db = MemoryStorage()
  49. while True:
  50. speed = 30
  51. acceleration = 2000
  52. status = self.get_sonar_status() #发查询指令,当作心跳包。
  53. print('duoji_runing')
  54. now_time = time.time()
  55. if now_time - self.__save_run_time >= self.__save_frequency - 10: #提前开启声纳
  56. dict = {'sonar_open': 'open','range':'small'}
  57. self.redis_db.set_value(dict)
  58. self.rotate_zero(speed,acceleration)
  59. if now_time - self.__save_run_time >= self.__save_frequency:
  60. self.__save_run_time = time.time()
  61. self.rotate_once_small(speed, acceleration,self.redis_db,MAX_ANGLE,self.__save_run_time)
  62. self.redis_db.set_value({'range': 'big'})
  63. time.sleep(3)
  64. self.rotate_once_big(speed, acceleration, self.redis_db, MIN_ANGLE,self.__save_run_time)
  65. self.run_count = self.run_count + 1
  66. print('run_count',self.run_count)
  67. # 关闭声纳
  68. dict = {'sonar_open': 'close'}
  69. self.redis_db.set_value(dict)
  70. time.sleep(1)
  71. # data_dict = get_sonar_status(self.__sock)
  72. # self.__conn.set_value(data_dict)
  73. # find_data = b'\xF0\x0F\xFF\xFF\xFF\xFF\x03'
  74. # self.__sock.send(find_data)
  75. #
  76. # # 接收服务器返回的数据
  77. # response = self.__sock.recv(1024)
  78. # print(response)
  79. # #res = servo_data.parse(response)
  80. # while True:
  81. # if isinstance(self.__command, list):
  82. # for i in self.__command:
  83. # command_list = json.loads(i['command'])
  84. # self.command_polling(command_list=command_list)
  85. # time.sleep(1)
  86. # else:
  87. # self.command_polling()
  88. # time.sleep(1)
  89. #
  90. # if self.__stopped:
  91. # break
  92. # 建立socket连接
  93. def __connect(self):
  94. if self.__sock:
  95. self.__sock.close()
  96. self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  97. self.__sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 允许重用本地地址和端口
  98. self.__sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # 在客户端开启心跳维护
  99. self.__sock.settimeout(10) # 设置超时时间3mins
  100. try:
  101. self.__sock.connect((self.__ip, self.__port))
  102. #logger.info(f'Connect to [{self.name}]:[{self.__ip}]:[{self.__port}] success !')
  103. self.__connected = True
  104. except Exception as e:
  105. #logger.info(f'Connect to [{self.name}]:[{self.__ip}]:[{self.__port}] failed:{e} !!!')
  106. self.__connected = False
  107. self.__reconnect()
  108. def __reconnect(self):
  109. while True:
  110. try:
  111. if self.__sock:
  112. self.__sock.close()
  113. self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  114. self.__sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  115. self.__sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # 在客户端开启心跳维护
  116. self.__sock.settimeout(10) # 设置超时时间,单位:秒
  117. self.__sock.connect((self.__ip, self.__port))
  118. self.__connected = True
  119. #logger.info(f'Reconnect to [{self.name}]:[{self.__ip}]:[{self.__port}] success !')
  120. break
  121. except Exception as e:
  122. #logger.info(f'Reconnect to [{self.name}]:[{self.__ip}]:[{self.__port}] failed:{e} !!! Continue reconnect in 5s..')
  123. self.__connected = False
  124. time.sleep(5)
  125. def __send_command(self, command):
  126. if self.__connected:
  127. try:
  128. #send_data = bytes.fromhex(command)
  129. self.__sock.send(command)
  130. response = self.__sock.recv(1024)
  131. return response
  132. except Exception as e:
  133. time.sleep(5)
  134. self.__reconnect()
  135. print('send',e)
  136. return None
  137. # logger.info(f'Send command to [{self.name}]:[{self.__ip}]:[{self.__port}] error:{e}')
  138. else:
  139. self.__reconnect()
  140. return None
  141. def calculate_checksum(self,data):
  142. checksum = 0
  143. for byte in data:
  144. checksum += byte
  145. checksum = (~checksum) & 0xFF
  146. byte_data = bytes([checksum])
  147. hex_string = byte_data.hex()
  148. return hex_string
  149. def data_converter(self,hex_data):
  150. servo_data = c.Struct(
  151. header=c.Int16ul, # 固定不便,可能用于区分不同设备
  152. none_1=c.Int8ub, # 固定不便,可能用于区分不同设备
  153. servo1_flag=c.Int8ub,
  154. none_2=c.Int8ub, # 固定不便,可能用于区分不同设备
  155. servo2_flag=c.Int8ub,
  156. depth=c.Bytes(4),
  157. temp=c.Bytes(4),
  158. yaw=c.Bytes(4), # 航向
  159. roll=c.Bytes(4), # 横滚
  160. pitch=c.Bytes(4), # 俯仰
  161. servo1_angle=c.Bytes(4),
  162. servo2_angle=c.Bytes(4),
  163. )
  164. res = servo_data.parse(hex_data)
  165. return res
  166. def get_sonar_status(self):
  167. find_data = b'\xF0\x0F\xFF\xFF\xFF\xFF\x03'
  168. response = self.__send_command(find_data)
  169. result = {'depth':None,'temp':None,'yaw':None,'roll':None,'pitch':None,'servo1_angle':None,'servo2_angle':None}
  170. if response != None:
  171. if len(response) == 35:
  172. res = servo_data.parse(response)
  173. result['depth'] = struct.unpack('>f', res.depth)[0]
  174. result['temp'] = struct.unpack('>f', res.temp)[0]
  175. result['yaw'] = struct.unpack('>f', res.yaw)[0]
  176. result['roll'] = struct.unpack('>f', res.roll)[0]
  177. result['pitch'] = struct.unpack('>f', res.pitch)[0]
  178. result['servo1_angle'] = struct.unpack('>f', res.servo1_angle)[0]
  179. result['servo2_angle'] = struct.unpack('>f', res.servo2_angle)[0]
  180. return result
  181. def send_command(self,location,speed,acceleration):
  182. header = 'f00f'
  183. servo1_location = struct.pack('>f', location).hex()
  184. servo2_location = struct.pack('>f',location).hex()
  185. servo1_speed = struct.pack('>f', speed).hex()
  186. servo2_speed = struct.pack('>f', speed).hex()
  187. servo1_acceleration = struct.pack('>f', acceleration).hex()
  188. servo2_acceleration = struct.pack('>f', acceleration).hex()
  189. data = servo1_location + servo2_location + servo1_speed +servo2_speed + servo1_acceleration + servo2_acceleration
  190. data_hex = bytes.fromhex(data)
  191. checksum = self.calculate_checksum(data_hex)
  192. send_data = header + data + checksum
  193. send_data = bytes.fromhex(send_data)
  194. #print(send_data) # 输出校验和的十六进制表示
  195. response = self.__send_command(send_data)
  196. def rotate_zero(self,speed, acceleration):
  197. while True:
  198. status = self.get_sonar_status()
  199. if status[servo_angle] != None:
  200. if status[servo_angle] > MIN_ANGLE + 0.5:
  201. print(status[servo_angle])
  202. self.send_command(location=MIN_ANGLE, speed=speed, acceleration=acceleration)
  203. else:
  204. break
  205. def rotate_once_small(self, speed, acceleration, save_data, location, time_start):
  206. count = 0
  207. num = 0 # 图像编号
  208. angel = None
  209. save_flag = 0
  210. while True:
  211. status = self.get_sonar_status()
  212. if status[servo_angle] != None:
  213. if status[servo_angle] < MIN_ANGLE + 0.5:
  214. # time_start = time.time() # 记录开始时间
  215. save_flag = 1
  216. self.send_command(location=location, speed=speed, acceleration=acceleration)
  217. if save_flag == 1:
  218. info_dict = {'flag': '1', 'timestamp': time_start, 'num': num, 'depth': status['depth'],
  219. 'temp': status['temp'], 'yaw': status['yaw'], 'roll': status['roll'],
  220. 'pitch': status['pitch'],'img_type':'s',
  221. 'servo_angle': status[servo_angle]}
  222. save_data.set_value(info_dict)
  223. num += 1
  224. if angel != status[servo_angle]:
  225. angel = status[servo_angle]
  226. count = 0
  227. else:
  228. count = count + 1
  229. if status[servo_angle] >= MAX_ANGLE - 1 or count > 3:
  230. save_data.set_value({'flag': '0'})
  231. break
  232. def rotate_once_big(self, speed, acceleration, save_data, location, time_start):
  233. count = 0
  234. num = 0 # 图像编号
  235. angel = None
  236. save_flag = 0
  237. while True:
  238. status = self.get_sonar_status()
  239. if status[servo_angle] != None:
  240. if status[servo_angle] >= MAX_ANGLE - 1:
  241. # time_start = time.time() # 记录开始时间
  242. save_flag = 1
  243. self.send_command(location=location, speed=speed, acceleration=acceleration)
  244. if save_flag == 1:
  245. info_dict = {'flag': '1', 'timestamp': time_start, 'num': num, 'depth': status['depth'],
  246. 'temp': status['temp'], 'yaw': status['yaw'], 'roll': status['roll'],
  247. 'pitch': status['pitch'],'img_type':'b',
  248. 'servo_angle': status[servo_angle]}
  249. save_data.set_value(info_dict)
  250. num += 1
  251. if angel != status[servo_angle]:
  252. angel = status[servo_angle]
  253. count = 0
  254. else:
  255. count = count + 1
  256. if status[servo_angle] <= MIN_ANGLE + 0.5 or count > 3:
  257. save_data.set_value({'flag': '0'})
  258. break
  259. def rotate_once(self,speed, acceleration,save_data):
  260. status = self.get_sonar_status()
  261. if status[servo_angle] != None:
  262. if status[servo_angle] > 0.5:
  263. self.send_command(location=0, speed=speed, acceleration=acceleration)
  264. else:
  265. count = 0
  266. num = 0 # 图像编号
  267. angel = None
  268. save_image_flag = 0
  269. while count < 5:
  270. status = self.get_sonar_status()
  271. if status[servo_angle] != None and save_image_flag == 0:
  272. if status[servo_angle] < 0.5:
  273. time_start = time.time() # 记录开始时间
  274. save_image_flag = 1
  275. self.send_command(location=359, speed=speed, acceleration=acceleration)
  276. #print(angel,status[servo_angle])
  277. if angel != status[servo_angle]:
  278. angel = status[servo_angle]
  279. count = 0
  280. else:
  281. count = count + 1
  282. if save_image_flag == 2:
  283. count = count + 2
  284. if status[servo_angle] != None:
  285. if count > 2 or status[servo_angle] >= 358:
  286. save_image_flag = 0
  287. save_data.set_value({'range':'big'})
  288. if status[servo_angle] != None:
  289. if count > 2 or status[servo_angle] >= 358:
  290. save_image_flag = 2
  291. time.sleep(5)
  292. self.send_command(location=0, speed=speed, acceleration=acceleration)
  293. time_now = time.time()
  294. if save_image_flag == 1:
  295. info_dict = {'flag': '1', 'timestamp': time_start, 'num': num, 'depth': status['depth'],
  296. 'temp': status['temp'], 'yaw': status['yaw'], 'roll': status['roll'],
  297. 'pitch': status['pitch'],
  298. 'servo_angle': status[servo_angle]}
  299. save_data.set_value(info_dict)
  300. num += 1
  301. print('asdasd',111111111111111111111)
  302. elif save_image_flag == 2:
  303. info_dict = {'flag': '1', 'timestamp': time_start, 'num': num, 'depth': status['depth'],
  304. 'temp': status['temp'], 'yaw': status['yaw'], 'roll': status['roll'],
  305. 'pitch': status['pitch'],
  306. 'servo_angle': status[servo_angle]}
  307. save_data.set_value(info_dict)
  308. num += 1
  309. print('asdasd', 22222222222222222222222222222222)
  310. else:
  311. info_dict = {'flag': '0', 'timestamp': time_start, 'num': num, 'depth': status['depth'],
  312. 'temp': status['temp'], 'yaw': status['yaw'], 'roll': status['roll'],
  313. 'pitch': status['pitch'],
  314. 'servo_angle': status[servo_angle]}
  315. save_data.set_value(info_dict)
  316. # time_sum = time_end - time_start # 计算的时间差为程序的执行时间,单位为秒/s
  317. # print(time_sum)
  318. def rotate_multiple(self,client_socket,angel,speed,acceleration):
  319. #模式二,指定间隔,达到,停顿,继续,完成,停止
  320. status = self.get_sonar_status()
  321. if status[servo_angle] != None:
  322. if status[servo_angle] > 0.5:
  323. self.send_command(location=0, speed=speed, acceleration=acceleration)
  324. else:
  325. i = int(360/angel)
  326. t = 0
  327. time_start = time.time() # 记录开始时间
  328. while t < i+1:
  329. count = 0
  330. speed = 300
  331. acceleration = 2000
  332. last_angel = None
  333. while count < 4:
  334. status = self.get_sonar_status()
  335. location_angel = min(angel * t, 359)
  336. self.send_command(location=location_angel, speed=speed, acceleration=acceleration)
  337. if last_angel != status[servo_angle]:
  338. last_angel=status[servo_angle]
  339. count = 0
  340. else:
  341. print(t,last_angel)
  342. count = count + 1
  343. if count > 3:
  344. t = t + 1
  345. self.send_command(location=0, speed=speed, acceleration=acceleration)
  346. if __name__ == '__main__':
  347. servo_config = {'ip': '192.168.7.61', 'port': 4001, 'save_frequency': 0}
  348. awaken_gls10 = Process(target=sender, name='awaken_gls10', daemon=True)
  349. command_p = Client()
  350. save_image = Process(target=Receiver,name='save_image',daemon=True)
  351. p = MyProcess(name='servo',config=servo_config) # 实例化进程对象
  352. awaken_gls10.start()
  353. command_p.daemon = True
  354. command_p.start()
  355. save_image.start()
  356. p.daemon = True
  357. p.start()
  358. while True:
  359. time.sleep(1)
  360. print('main..............................',time.time())