api.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. from natsort.natsort import order_by_index
  2. from sqlalchemy import func
  3. from models import *
  4. import requests
  5. import json
  6. from logger import logger
  7. from serial.tools import list_ports
  8. from model import PhotoRecord
  9. import settings
  10. from utils.hlm_http_request import forward_request
  11. from utils.utils_func import check_path
  12. from sockets.socket_client import socket_manager
  13. from mcu.DeviceControl import DeviceControl
  14. import time, shutil
  15. from sqlalchemy import and_, asc, desc
  16. from functools import partial
  17. from service.deal_image import DealImage
  18. from databases import DeviceConfig, SqlQuery, CRUD, select
  19. from service.run_main import RunMain
  20. import importlib
  21. from service.auto_deal_pics.upload_pic import UploadPic
  22. # from service.AutoDealPics import AutoDealPics
  23. # for plugin in settings.plugins:
  24. # module_path, class_name = plugin.rsplit(".", 1)
  25. # print("module_path", module_path, class_name)
  26. # module = importlib.import_module(module_path)
  27. # getattr(module, class_name)
  28. @app.get("/")
  29. async def index():
  30. # await socket_manager.send_message(msg="测试")
  31. return {"message": "Hello World"}
  32. @app.get("/send_test")
  33. async def index():
  34. data = {"data1": 1, "data2": 2, "data3": 3, "data4": 4}
  35. await socket_manager.send_message(msg="测试", data=data)
  36. return {"message": "Hello World"}
  37. @app.get("/scan_serials", description="扫描可用的设备端口")
  38. async def scanSerials():
  39. """扫描串口"""
  40. ports = list_ports.comports()
  41. print("Scanning", ports)
  42. return {"message": "Hello World"}
  43. @app.get("/test_conndevice")
  44. def test_conndevice():
  45. device_control = DeviceControl()
  46. p_list = []
  47. temp_ports_dict = {}
  48. # while 1:
  49. time.sleep(1)
  50. ports_dict = device_control.scan_serial_port()
  51. temp_ports_dict = ports_dict
  52. if not ports_dict:
  53. # 全部清空 移除所有串口
  54. if p_list:
  55. _p = p_list.pop()
  56. device_control.remove_port(_p)
  57. # continue
  58. if ports_dict:
  59. # print(plist)
  60. for index, _i in enumerate(p_list):
  61. if _i not in ports_dict:
  62. _p = p_list.pop(index)
  63. device_control.remove_port(_p)
  64. for _port_name, _port_value in ports_dict.items():
  65. if _port_name not in p_list:
  66. try:
  67. p_list.append(_port_name)
  68. device_control.add_port_by_linkage(_port_name)
  69. except BaseException as e:
  70. print(
  71. e.__traceback__.tb_frame.f_globals["__file__"]
  72. ) # 发生异常所在的文件
  73. print(e.__traceback__.tb_lineno) # 发生异常所在的行数
  74. print("串口不存在{} {}".format(_port_name, e))
  75. # threading.Thread(target=self.add_port, args=(_port_name, _port_value)).start()
  76. # self.add_port(_p)
  77. @app.api_route(
  78. "/forward_request", methods=["GET", "POST"], description="代理转发hlm项目得请求"
  79. )
  80. async def forwardRequest(request: HlmForwardRequest):
  81. """
  82. 转发HTTP请求到目标URL
  83. :param request: FastAPI Request对象
  84. :return: 目标接口的响应
  85. """
  86. try:
  87. if request.method == "GET":
  88. params = request.query_params
  89. elif request.method == "POST":
  90. params = json.dump(request.query_params)
  91. else:
  92. raise UnicornException("仅支持GET和POST方法")
  93. target_url = request.target_url
  94. method = request.method.upper()
  95. headers = request.headers
  96. if not target_url:
  97. raise UnicornException("目标url地址不能为空")
  98. # 调用 hlm_http_request 中的 forward_request 函数
  99. response = forward_request(
  100. target_url, params=params, method=method, headers=headers
  101. )
  102. return response
  103. except requests.RequestException as e:
  104. raise UnicornException(e)
  105. except Exception as e:
  106. raise UnicornException(e)
  107. @app.post("/handle_detail")
  108. async def handle_detail(request: Request, params: HandlerDetail):
  109. goods_art_no_array = params.goods_art_no
  110. handler_result = []
  111. handler_result_folder = ""
  112. for goods_art_no in goods_art_no_array:
  113. try:
  114. if not goods_art_no:
  115. raise UnicornException("货号不能为空")
  116. token = "Bearer " + params.token
  117. session = SqlQuery()
  118. pr = CRUD(PhotoRecord)
  119. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  120. if not images:
  121. raise UnicornException("没有可用货号数据")
  122. image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  123. check_path(image_dir)
  124. for itemImg in images:
  125. if not os.path.exists(
  126. image_dir + "/" + os.path.basename(itemImg.image_path)
  127. ):
  128. shutil.copy(itemImg.image_path, image_dir)
  129. dealImage = DealImage(image_dir)
  130. resFlag, path = dealImage.dealMoveImage(
  131. image_dir=image_dir, callback_func=None, goods_art_no=goods_art_no
  132. )
  133. if not resFlag:
  134. raise UnicornException(path)
  135. temp_class = {}
  136. temp_name_list = []
  137. for tempItem in params.temp_list:
  138. temp_class[tempItem.template_id] = tempItem.template_local_classes
  139. temp_name_list.append(tempItem.template_id)
  140. config_data = {
  141. "image_dir": path,
  142. "image_order": params.template_image_order,
  143. "goods_art_no": goods_art_no,
  144. "is_check_number": False,
  145. "resize_image_view": "后跟",
  146. "cutout_mode": "0",
  147. "logo_path": params.logo_path,
  148. "special_goods_art_no_folder_line": "",
  149. "is_use_excel": False if params.excel_path == "" else True, # 是否使用excel
  150. "excel_path": params.excel_path, # excel路径
  151. "is_check_color_is_all": False,
  152. "cutout_is_pass": True,
  153. "assigned_page_dict": {},
  154. "detail_is_pass": True,
  155. "upload_is_pass": False,
  156. "upload_is_enable": False,
  157. "is_filter": False,
  158. "temp_class": temp_class,
  159. "temp_name": params.temp_name,
  160. "temp_name_list": temp_name_list,
  161. "target_error_folder": f"{path}/软件-生成详情错误",
  162. }
  163. # 动态导入类
  164. temp_class_dict = {}
  165. for key, class_path in config_data["temp_class"].items():
  166. module_path, class_name = class_path.rsplit(".", 1)
  167. module = importlib.import_module(module_path)
  168. cls = getattr(module, class_name)
  169. temp_class_dict[key] = cls
  170. config_data["temp_class"] = temp_class_dict
  171. obj = None
  172. run_main = RunMain(obj,token)
  173. return_data = run_main.check_before_cutout(config_data)
  174. cutout_res = run_main.check_for_cutout_image_first_call_back(return_data)
  175. check_for_detail_first_res = None
  176. if cutout_res == True:
  177. return_data_check_before_detail = run_main.check_before_detail(config_data)
  178. check_for_detail_first_res = run_main.check_for_detail_first_call_back(
  179. return_data_check_before_detail
  180. )
  181. if isinstance(check_for_detail_first_res, partial):
  182. result = check_for_detail_first_res()
  183. try:
  184. config_data = result["config_data"]
  185. except:
  186. config_data = result
  187. if config_data["sign_text"] == "已结束详情处理":
  188. # at_pic = AutoDealPics()
  189. print("config_data", config_data)
  190. if config_data["upload_is_enable"]:
  191. to_deal_dir = "{}/软件-详情图生成".format(config_data["image_dir"])
  192. check_path(to_deal_dir)
  193. print("to_deal_dir", to_deal_dir)
  194. if os.path.exists(to_deal_dir):
  195. upload_pic = UploadPic(
  196. windows=None,
  197. to_deal_dir=to_deal_dir,
  198. config_data=config_data,
  199. token=token,
  200. )
  201. upload_pic.run()
  202. out_put_dir = config_data["out_put_dir"]
  203. out_put_dir_path = "{}/{}".format(os.getcwd(), out_put_dir).replace("\\", "/")
  204. handler_result_folder = os.path.dirname(out_put_dir_path)
  205. handler_result.append(
  206. {"goods_art_no": goods_art_no, "success": True, "info": "处理成功"}
  207. )
  208. else:
  209. handler_result.append(
  210. {"goods_art_no": goods_art_no, "success": False, "info": "处理失败"}
  211. )
  212. except Exception as e:
  213. handler_result.append(
  214. {"goods_art_no": goods_art_no, "success": False, "info": str(e)}
  215. )
  216. return {
  217. "code": 0,
  218. "msg": "",
  219. "data": {"output_folder": handler_result_folder, "list": handler_result},
  220. }
  221. @app.post("/get_device_configs", description="获取可执行程序命令列表")
  222. def get_device_configs(params: ModelGetDeviceConfig):
  223. mode_type = params.mode_type
  224. session = SqlQuery()
  225. configModel = CRUD(DeviceConfig)
  226. configList = configModel.read_all(
  227. session,
  228. conditions={"mode_type": mode_type},
  229. order_by="action_index",
  230. ascending=True,
  231. )
  232. return {
  233. "code": 0,
  234. "msg": "",
  235. "data": {"list": configList},
  236. }
  237. @app.post("/device_config_detail", description="获取可执行程序详情")
  238. def get_device_configs(params: ModelGetDeviceConfigDetail):
  239. action_id = params.id
  240. session = SqlQuery()
  241. configModel = CRUD(DeviceConfig)
  242. model = configModel.read(session, conditions={"id": action_id})
  243. if model == None:
  244. return {"code": 1, "msg": "数据不存在", "data": None}
  245. return {"code": 0, "msg": "", "data": model}
  246. @app.post("/remove_config", description="删除一条可执行命令")
  247. def get_device_configs(params: ModelGetDeviceConfigDetail):
  248. action_id = params.id
  249. session = SqlQuery()
  250. configModel = CRUD(DeviceConfig)
  251. model = configModel.read(session, conditions={"id": action_id})
  252. if model == None:
  253. return {"code": 1, "msg": "数据不存在", "data": None}
  254. configModel.delete(session, obj_id=action_id)
  255. return {"code": 0, "msg": "删除成功", "data": None}
  256. @app.post("/save_device_config", description="创建或修改一条可执行命令")
  257. def save_device_config(params: SaveDeviceConfig):
  258. action_id = params.id
  259. session = SqlQuery()
  260. deviceConfig = CRUD(DeviceConfig)
  261. if action_id == None or action_id == 0:
  262. # 走新增逻辑
  263. params.id = None
  264. save_device_config = deviceConfig.create(session, obj_in=params)
  265. else:
  266. model = deviceConfig.read(session, conditions={"id": action_id})
  267. if model == None:
  268. return {"code": 1, "msg": "数据不存在", "data": None}
  269. # 走编辑逻辑
  270. kwargs = params.__dict__
  271. save_device_config = deviceConfig.update(session, obj_id=action_id, **kwargs)
  272. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  273. @app.post("/reset_config", description="创建或修改一条可执行命令")
  274. def reset_config(params: ModelGetDeviceConfig):
  275. mode_type = params.mode_type
  276. if mode_type == None or mode_type == "":
  277. return {"code": 1, "msg": "参数错误", "data": None}
  278. session = SqlQuery()
  279. deviceConfig = CRUD(DeviceConfig)
  280. res = deviceConfig.deleteConditions(session, conditions={"mode_type": mode_type})
  281. if res is False:
  282. return {"code": 1, "msg": "操作失败", "data": None}
  283. actions = json.load(open("action.json", encoding="utf-8"))
  284. act = []
  285. for item in actions:
  286. if item.get("mode_type") == mode_type:
  287. act.append(item)
  288. batch_insert_device_configs(session, act)
  289. return {"code": 0, "msg": "操作成功", "data": None}
  290. @app.get("/get_photo_records", description="获取拍照记录")
  291. def get_photo_records(page: int = 1, size: int = 5):
  292. session = SqlQuery()
  293. photos = CRUD(PhotoRecord)
  294. statement = (
  295. select(PhotoRecord)
  296. .offset((page - 1) * size)
  297. .limit(size)
  298. .order_by(desc("id"))
  299. .group_by("goods_art_no")
  300. )
  301. list = []
  302. result = session.exec(statement).all()
  303. for item in result:
  304. list_item = photos.read_all(
  305. session, conditions={"goods_art_no": item.goods_art_no}
  306. )
  307. list.append(
  308. {
  309. "goods_art_no": item.goods_art_no,
  310. "action_time": item.create_time,
  311. "items": list_item,
  312. }
  313. )
  314. session.close()
  315. return {
  316. "code": 0,
  317. "msg": "",
  318. "data": {"list": list, "page": page, "size": size},
  319. }
  320. @app.get("/get_photo_record_detail", description="通过货号获取拍照记录详情")
  321. def get_photo_records(goods_art_no: str = None):
  322. if goods_art_no == None:
  323. return {"code": 1, "msg": "参数错误", "data": None}
  324. session = SqlQuery()
  325. photos = CRUD(PhotoRecord)
  326. items = photos.read_all(session, conditions={"goods_art_no": goods_art_no})
  327. session.close()
  328. return {
  329. "code": 0,
  330. "msg": "",
  331. "data": {"list": items},
  332. }
  333. @app.post("/delect_goods_arts", description="通过货号删除记录")
  334. def delect_goods_arts(params: PhotoRecordDelete):
  335. session = SqlQuery()
  336. photos = CRUD(PhotoRecord)
  337. for item in params.goods_art_nos:
  338. photos.deleteConditions(session, conditions={"goods_art_no": item})
  339. session.close()
  340. return {
  341. "code": 0,
  342. "msg": "操作成功",
  343. "data": None,
  344. }
  345. @app.get("/get_sys_config", description="查询系统配置")
  346. def get_sys_config(key: str = None):
  347. if key == None:
  348. return {"code": 1, "msg": "参数错误", "data": None}
  349. session = SqlQuery()
  350. photos = CRUD(SysConfigs)
  351. item = photos.read(session, conditions={"key": key})
  352. session.close()
  353. return {
  354. "code": 0,
  355. "msg": "",
  356. "data": json.loads(item.value),
  357. }
  358. @app.post("/update_sys_configs", description="创建或修改系统配置")
  359. def save_sys_configs(params: SysConfigParams):
  360. session = SqlQuery()
  361. sysConfig = CRUD(SysConfigs)
  362. model = sysConfig.read(session, conditions={"key": params.key})
  363. if model == None:
  364. return {"code": 1, "msg": "配置不存在", "data": None}
  365. # 走编辑逻辑
  366. kwargs = params.__dict__
  367. save_device_config = sysConfig.updateConditions(
  368. session, conditions={"key": params.key}, **kwargs
  369. )
  370. return {"code": 0, "msg": "操作成功", "data": save_device_config}