ProgramItem.py 26 KB

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