ProgramItem.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. import asyncio
  2. import json
  3. import os
  4. from .BaseClass import BaseClass
  5. import settings
  6. import time
  7. from .capture.module_digicam import DigiCam
  8. from .capture.module_watch_dog import FileEventHandler
  9. import logging
  10. logger = logging.getLogger(__name__)
  11. class ProgramItem(BaseClass):
  12. # program_sign = Signal(dict)
  13. # program_refresh_photo_list_sign = Signal()
  14. def __init__(
  15. self,
  16. websocket_manager,
  17. action_data: any,
  18. mcu,
  19. goods_art_no: str = None,
  20. image_index: int = -1,
  21. record_id: int = -1,
  22. smart_shooter=None,
  23. is_get_mcu_state=True,
  24. ):
  25. super().__init__(BaseClass)
  26. # 1 表示等待中,2表示没有等待
  27. self.wait_state = 2
  28. self.msg_type = "mcu"
  29. print("action_data====>", action_data)
  30. self.data = action_data
  31. print("ProgramItem smart_shooter", smart_shooter)
  32. self.smart_shooter = smart_shooter
  33. if smart_shooter == None:
  34. self.capture_one = DigiCam()
  35. captrure_folder_path = self.capture_one.getCaptureFolderPath()
  36. self.watch_dog = FileEventHandler()
  37. self.watch_dog.goods_art_no = goods_art_no
  38. self.watch_dog.image_index = image_index
  39. self.watch_dog.mcu = mcu
  40. self.watch_dog.start_observer(captrure_folder_path)
  41. else:
  42. print("使用smart_shooter")
  43. print("21 =========ProgramItem=======action_data=====")
  44. print(action_data)
  45. self.action_id = self.get_value(action_data, "id")
  46. self.mode_type = self.get_value(action_data, "mode_type")
  47. # self.action_type = self.get_value(action_data, "execution_type", "程序1")
  48. self.action_name = self.get_value(action_data, "action_name", "")
  49. self.is_wait = self.get_value(action_data, "is_wait", False)
  50. self.is_need_confirm = self.get_value(action_data, "is_need_confirm", False)
  51. self.image_index = self.get_value(action_data, "picture_index", 99)
  52. self.camera_height = self.get_value(action_data, "camera_height", 0)
  53. self.last_camera_height = 0
  54. self.camera_angle = float(self.get_value(action_data, "camera_angle", 0.0))
  55. self.af_times = self.get_value(action_data, "number_focus", 0)
  56. self.shoe_overturn = self.get_value(action_data, "shoe_upturn", False)
  57. self.is_photograph = self.get_value(action_data, "take_picture", True)
  58. self.turntable_position = float(
  59. self.get_value(action_data, "turntable_position", 0.0)
  60. )
  61. self.is_get_mcu_state = is_get_mcu_state
  62. self.turntable_angle = float(
  63. self.get_value(action_data, "turntable_angle", 0.0)
  64. )
  65. self.delay_time = self.get_value(action_data, "pre_delay", 0.0)
  66. self.after_delay_time = self.get_value(action_data, "after_delay", 0.0)
  67. self.is_led = self.get_value(action_data, "led_switch", False)
  68. self.last_photograph_time = None # 最近一次拍照时间
  69. self.goods_art_no = goods_art_no # 货号
  70. self.record_id = record_id # 货号
  71. self.set_other()
  72. self.error_info_text = "" # 错误提示信息
  73. self.last_move_time = None
  74. # self.setParent(parent)
  75. self.mcu = mcu
  76. # if is_show:
  77. # self.parent = parent
  78. # self.setupUi(self)
  79. # self.init()
  80. # self.show()
  81. def set_other(self):
  82. if self.mode_type == "其他配置":
  83. self.turntable_position = None
  84. self.turntable_angle = None
  85. self.delay_time = 0
  86. self.after_delay_time = 0
  87. self.is_led = False
  88. def get_value(self, data, key, default=None):
  89. if key not in data:
  90. data[key] = default
  91. print("取值模式==>获取到key:{}的值为:{}".format(key, data[key]))
  92. return default
  93. print("默认值模式==>获取到key:{}的值为:{}".format(key, data[key]))
  94. return data[key]
  95. def reset(self):
  96. self.set_state(state_value=0)
  97. self.error_info_text = "" # 错误提示信息
  98. def init(self):
  99. self.icon_dict = {
  100. 0: "resources/other_icon/0weikaishi.png",
  101. 1: "resources/other_icon/1jinxingzhong.png",
  102. 2: "resources/other_icon/2yijieshu.png",
  103. 99: "resources/other_icon/11yichang.png",
  104. }
  105. if self.is_wait:
  106. msg = "{}--等待".format(self.action_name)
  107. self.sendSocketMessage(msg=msg, device_status=0)
  108. else:
  109. msg = "{}".format(self.action_name)
  110. self.sendSocketMessage(msg=msg, device_status=2)
  111. tips_text = "程序:{},对焦:{}".format(1, 1)
  112. self.sendSocketMessage(msg=tips_text, device_status=2)
  113. self.set_state(state_value=0)
  114. # def next_step_clicked(self, *args, **kwargs):
  115. # self.windows.event.set()
  116. def set_state(self, state_value):
  117. self.state = state_value
  118. # icon = QPixmap(self.icon_dict[self.state])
  119. # icon = icon.scaled(
  120. # self.ui_icon.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation
  121. # )
  122. # self.ui_icon.setPixmap(icon)
  123. # if self.state == 0:
  124. # self.ui_retry.setText("")
  125. # self.ui_retry.setEnabled(False)
  126. # if self.state == 1:
  127. # self.ui_retry.setText("")
  128. # self.ui_retry.setEnabled(False)
  129. # if self.state == 2:
  130. # self.ui_retry.setText("单步")
  131. # self.ui_retry.setEnabled(True)
  132. # if self.state == 99:
  133. # self.ui_retry.setText("重试")
  134. # self.ui_retry.setEnabled(True)
  135. # self.ui_action_name.setToolTip(self.error_info_text)
  136. async def check_mcu_move_is_stop(self, re_check=False):
  137. self.error_info_text = ""
  138. # 发送基础数据信息
  139. # self.mcu.to_get_mcu_base_info()
  140. _s = time.time()
  141. last_num_1 = self.mcu.last_mcu_info_data["num"]
  142. await self.mcu.cleanAllReceiveData()
  143. while 1:
  144. print("\033[1;31m执行检查动作\033[0m", self.mcu.mcu_move_state)
  145. print("\033[1;31m执行检查动作\033[0m", self.mcu.action_state)
  146. if self.mcu.action_state != 1:
  147. # 外部终止,停止运行
  148. print("\033[1;31m执行结束\033[0m", "外部终止,停止运行")
  149. return False
  150. cr_time = time.time()
  151. print(cr_time - _s, cr_time, _s)
  152. if cr_time - _s > 8:
  153. self.error_info_text = "MCU检测运动未停止,自动退出"
  154. self.set_state(state_value=99) # 标记异常
  155. print("MCU检测运动未停止,自动退出")
  156. self.sendSocketMessage(msg=self.error_info_text, device_status=-1)
  157. print("\033[1;31m执行结束\033[0m", "MCU检测运动未停止,自动退出")
  158. return False
  159. # return True
  160. # 存在时间间隙,导致误认为所有设备已完成运动
  161. if self.mcu.mcu_move_state == 2:
  162. print("\033[1;31m执行结束\033[0m", "导致误认为所有设备已完成运动")
  163. return True
  164. else:
  165. self.mcu.to_get_mcu_base_info()
  166. asyncio.create_task(self.mcu.send_all_cmd())
  167. # self.mcu.send_all_cmd()
  168. await asyncio.sleep(0.5)
  169. self.mcu.get_basic_info_mcu()
  170. # return True
  171. print("\033[1;31m执行结束\033[0m", self.mcu.action_state)
  172. # await asyncio.sleep(0.1)
  173. # self.mcu.to_get_mcu_base_info()
  174. async def camera_check_mcu_move_is_stop(self, re_check=False):
  175. self.error_info_text = ""
  176. # 发送基础数据信息
  177. # self.mcu.to_get_mcu_base_info()
  178. _s = time.time()
  179. check_times = 0
  180. await self.mcu.cleanAllReceiveData()
  181. while 1:
  182. if self.mcu.action_state != 1:
  183. return False
  184. # 发送获取设备状态消息
  185. self.mcu.send_get_all_info_to_mcu()
  186. await asyncio.sleep(0.5)
  187. if all(
  188. value == 2
  189. for value in [
  190. self.mcu.state_camera_motor,
  191. self.mcu.state_camera_steering,
  192. self.mcu.state_turntable_steering,
  193. self.mcu.state_overturn_steering,
  194. ]
  195. ):
  196. logger.info("拍照前运动检测状态[成功]")
  197. # await asyncio.sleep(0.5)
  198. return True
  199. else:
  200. check_times += 1
  201. if check_times > 5:
  202. logger.info("拍照前运动检测状态[失败]")
  203. return False
  204. # return True
  205. print("\033[1;31m执行结束\033[0m", self.mcu.action_state)
  206. async def run(self, total_len=5, *args):
  207. if total_len == 1:
  208. self.mode_type = "其他配置"
  209. self.set_other()
  210. print("1{} - is run".format(self.action_name))
  211. self.set_state(state_value=1)
  212. if settings.IS_TEST:
  213. await self.do_run()
  214. else:
  215. try:
  216. await self.do_run()
  217. except BaseException as e:
  218. self.sendSocketMessage(
  219. msg="p_item 错误:{}".format(e), device_status=-1
  220. )
  221. self.set_state(state_value=99)
  222. self.set_state(state_value=2)
  223. return True
  224. def run_only_mcu(self, *args):
  225. # ============连接MCU 处理步进电机与舵机等
  226. if settings.IS_MCU:
  227. if self.shoe_overturn:
  228. self.mcu.to_deal_device(device_name="overturn_steering")
  229. time.sleep(0.1)
  230. if self.camera_height is not None:
  231. self.mcu.to_device_move(
  232. device_name="camera_high_motor", value=self.camera_height
  233. )
  234. time.sleep(0.1)
  235. if self.camera_angle is not None:
  236. self.mcu.to_device_move(
  237. device_name="camera_steering", value=self.camera_angle
  238. )
  239. time.sleep(0.1)
  240. if self.turntable_position is not None:
  241. self.mcu.to_device_move(
  242. device_name="turntable_position_motor",
  243. value=self.turntable_position,
  244. )
  245. time.sleep(0.1)
  246. if self.turntable_angle is not None:
  247. self.mcu.to_device_move(
  248. device_name="turntable_steering", value=self.turntable_angle
  249. )
  250. time.sleep(0.1)
  251. loop = asyncio.get_event_loop()
  252. # self.mcu.send_all_cmd()
  253. loop.create_task(self.mcu.send_all_cmd())
  254. async def do_run(self, *args):
  255. await asyncio.sleep(0.001)
  256. # if not self.goods_art_no: # and self.action_name != "初始化位置"
  257. # return False
  258. start_time = time.time()
  259. current_time = time.time()
  260. self.mcu.is_get_mcu_state = self.is_get_mcu_state
  261. # ============连接MCU 处理步进电机与舵机等
  262. if settings.IS_MCU:
  263. if self.mode_type != "其他配置" and await self.check_mcu_move_is_stop() is False:
  264. # MCU运动是否有停止检查,设定超时时间
  265. return
  266. print(
  267. "{} 检查停止时间1:{}".format(
  268. self.action_name, time.time() - start_time
  269. )
  270. )
  271. if self.is_led:
  272. self.mcu.to_deal_device(device_name="laser_position", value=1)
  273. else:
  274. self.mcu.to_deal_device(device_name="laser_position", value=0)
  275. if self.shoe_overturn:
  276. self.mcu.to_deal_device(device_name="overturn_steering")
  277. await asyncio.sleep(0.01)
  278. if self.camera_height is not None:
  279. if (current_time - self.last_move_time)>110:
  280. if self.camera_height == 0:
  281. self.mcu.to_device_move(
  282. device_name="camera_high_motor", value=1
  283. )
  284. elif self.camera_height == 400:
  285. self.mcu.to_device_move(
  286. device_name="camera_high_motor", value=399
  287. )
  288. else:
  289. self.mcu.to_device_move(
  290. device_name="camera_high_motor", value=self.camera_height-1
  291. )
  292. await asyncio.sleep(0.01)
  293. logger.info("设备延迟执行===>,%s",time.time())
  294. self.mcu.to_device_move(
  295. device_name="camera_high_motor", value=self.camera_height
  296. )
  297. self.last_camera_height = self.camera_height
  298. await asyncio.sleep(0.01)
  299. if self.camera_angle is not None:
  300. self.mcu.to_device_move(
  301. device_name="camera_steering", value=self.camera_angle
  302. )
  303. await asyncio.sleep(0.01)
  304. if self.turntable_position is not None:
  305. self.mcu.to_device_move(
  306. device_name="turntable_position_motor",
  307. value=self.turntable_position,
  308. )
  309. await asyncio.sleep(0.01)
  310. if self.turntable_angle is not None:
  311. self.mcu.to_device_move(
  312. device_name="turntable_steering", value=self.turntable_angle
  313. )
  314. await asyncio.sleep(0.01)
  315. # MCU运动是否有停止检查,设定超时时间
  316. # self.mcu.send_all_cmd()
  317. asyncio.create_task(self.mcu.send_all_cmd())
  318. if self.mode_type != "其他配置":
  319. await asyncio.sleep(1.2)
  320. print("二次检查")
  321. if await self.check_mcu_move_is_stop(re_check=True) is False:
  322. print("MCU检测运动未停止,自动退出, 提前退出")
  323. return
  324. # logger.info("设备最后一次执行时间===>,%s",current_time)
  325. self.mcu.is_get_mcu_state = True
  326. if self.delay_time:
  327. await asyncio.sleep(self.delay_time)
  328. if self.is_photograph:
  329. # print("photograph==================")
  330. self.mcu.to_deal_device(device_name="buzzer", times=1)
  331. # 用于临时拍照计数
  332. if not await self.camera_check_mcu_move_is_stop(re_check=True):
  333. logger.info("拍照前运动检测失败===>")
  334. return
  335. await asyncio.sleep(0.5)
  336. is_af = True if self.af_times > 0 else False
  337. if self.smart_shooter != None:
  338. # 拍照
  339. print("smart shooter 拍照")
  340. record_id = self.record_id
  341. goods_art_no = self.goods_art_no
  342. if record_id == -1:
  343. goods_art_no = ""
  344. print("smart shooter CameraShooter", record_id, goods_art_no)
  345. await self.smart_shooter.CameraShooter(
  346. msg_type="run_mcu",
  347. goods_art_no=goods_art_no,
  348. id=record_id,
  349. is_af=is_af,
  350. )
  351. print("smart shooter CameraShooter end")
  352. else:
  353. # 指定自动对焦
  354. self.capture_one.photograph(is_af=is_af)
  355. self.last_photograph_time = time.time() # 记录最近一次拍照时间
  356. # print("{} 拍照时间:{}".format(self.action_name, time.time() - start_time))
  357. print("{}-{}已完成".format(self.mode_type, self.action_name))
  358. if self.after_delay_time:
  359. print("拍照后延时:{}".format(self.after_delay_time))
  360. await asyncio.sleep(self.after_delay_time)
  361. return True
  362. async def RunSmartShooter(self, goods_art_no,record_id):
  363. await asyncio.gather(
  364. self.smart_shooter.CameraShooter(
  365. msg_type="run_mcu",
  366. goods_art_no=goods_art_no,
  367. id=record_id,
  368. ),
  369. )
  370. def digicam_take_picture(self):
  371. self.mcu.to_deal_device(device_name="buzzer", times=1)
  372. # 用于临时拍照计数
  373. is_af = True
  374. self.capture_one.photograph(is_af=is_af)
  375. self.last_photograph_time = time.time() # 记录最近一次拍照时间
  376. print("仅拍照执行完成")
  377. def rephotograph_one_pic(self, *args):
  378. """
  379. 1、获取最近一张照片
  380. 2、判断拍照时间距离当前节点的最近拍照时间是否小于3秒
  381. 3、删除该照片
  382. 4、重新触发进行拍照,并更新最近拍照时间
  383. """
  384. if (
  385. settings.getSysConfigs("other_configs", "running_mode", "普通模式")
  386. == "普通模式"
  387. ):
  388. return
  389. print("-----100-2--self", self)
  390. # 需要删除最近一张照片
  391. # if self.last_photograph_time is not None:
  392. # record = self.windows.image_process_data.photo_todo_list
  393. # if record:
  394. # last_record = record[-1]
  395. # if self.goods_art_no == last_record["goods_art_no"]:
  396. # if last_record["is_photo"]:
  397. # photo_create_time_formate = last_record[
  398. # "photo_create_time_formate"
  399. # ]
  400. # image_path = last_record["image_path"]
  401. # print(
  402. # "photo_create_time_formate,self.last_photograph_time",
  403. # photo_create_time_formate,
  404. # self.last_photograph_time,
  405. # )
  406. # # 如果照片的时间大于触发时间,且小于3秒,则认定是当前触发
  407. # if (
  408. # self.last_photograph_time
  409. # < photo_create_time_formate
  410. # < self.last_photograph_time
  411. # + settings.PHOTO_TRANSFER_TIME_INTERVAL
  412. # ):
  413. # if os.path.exists(image_path):
  414. # os.remove(image_path)
  415. # self.windows.add_goods_images_count(
  416. # self.goods_art_no, flag=False
  417. # )
  418. # if (
  419. # self.windows.image_process_data.goods_art_no_times_record
  420. # ):
  421. # goods_art_no = self.windows.image_process_data.goods_art_no_times_record[
  422. # 0
  423. # ][
  424. # "goods_art_no"
  425. # ]
  426. # if goods_art_no == self.goods_art_no:
  427. # self.windows.image_process_data.goods_art_no_times_record[
  428. # 0
  429. # ][
  430. # "number"
  431. # ] -= 1
  432. # self.program_refresh_photo_list_sign.emit()
  433. # if self.is_photograph:
  434. # # 重新拍照
  435. # self.last_photograph_time = time.time() # 记录最近一次拍照时间
  436. # print("last_photograph_time:", self.last_photograph_time)
  437. # print("photograph==================")
  438. # self.mcu.to_deal_device(device_name="buzzer", times=1)
  439. # # 用于临时拍照计数
  440. # self.windows.add_goods_images_count(self.goods_art_no)
  441. # if self.af_times > 0:
  442. # self.windows.capture_one.photograph(is_af=True)
  443. # else:
  444. # self.windows.capture_one.photograph(is_af=False)
  445. def do_retry(self, *args, **kwargs):
  446. """
  447. 重试操作,注意事项:
  448. 1、需要根据当前系统的角度位置,重新进行返回并拍摄
  449. :param args:
  450. :param kwargs:
  451. :return:
  452. """
  453. # self.program_sign.emit({})
  454. # print("do_retry")
  455. self.reset()
  456. self.mcu.action_state = 1
  457. self.run()
  458. self.mcu.action_state = 2
  459. def get_photo_node_name_and_sound(self, photo_take_time):
  460. data = {
  461. "action_name": self.action_name,
  462. "flag": False,
  463. "is_sound_play": False,
  464. }
  465. if self.state == 0:
  466. return data
  467. if self.last_photograph_time is None:
  468. return data
  469. # if (
  470. # self.last_photograph_time
  471. # < photo_take_time
  472. # < self.last_photograph_time + settings.PHOTO_TRANSFER_TIME_INTERVAL
  473. # ):
  474. # # 认定为当节点拍摄
  475. # # 如果为待用户确认则播放声音
  476. # data["flag"] = True
  477. # if settings.RUNNING_MODE == "待用户确认模式":
  478. # _f = False
  479. # if settings.RUNNING_MODE_DETAIL == "所有节点待确认":
  480. # _f = True
  481. # else:
  482. # print("self.is_need_confirm", self.is_need_confirm)
  483. # if self.is_need_confirm:
  484. # _f = True
  485. # else:
  486. # _f = False
  487. # if _f:
  488. # data["is_sound_play"] = True
  489. # print("========is_sound_play===========")
  490. # self.windows.playsound.tips_type = "photo_confirm"
  491. # self.windows.playsound.start()
  492. # return data
  493. return data