ProgramItem.py 24 KB

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