api.py 15 KB

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