ProgramItem.py 24 KB

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