api.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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 = params.goods_art_no
  105. token = "Bearer " + params.token
  106. session = SqlQuery()
  107. pr = CRUD(PhotoRecord)
  108. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  109. if not images:
  110. raise UnicornException("没有可用货号数据")
  111. image_dir = "{}/data/".format(os.getcwd())
  112. for itemImg in images:
  113. if not os.path.exists(image_dir + "/" + os.path.basename(itemImg.image_path)):
  114. shutil.copy(itemImg.image_path, image_dir)
  115. check_path(image_dir)
  116. dealImage = DealImage(image_dir)
  117. resFlag, path = dealImage.dealMoveImage(
  118. image_dir=image_dir, callback_func=None, goods_art_no=goods_art_no
  119. )
  120. if not resFlag:
  121. raise UnicornException(path)
  122. temp_class = {}
  123. temp_name_list = []
  124. for tempItem in params.temp_list:
  125. temp_class[tempItem.template_id] = tempItem.template_local_classes
  126. temp_name_list.append(tempItem.template_id)
  127. config_data = {
  128. "image_dir": path,
  129. "image_order": params.template_image_order,
  130. "goods_art_no": goods_art_no,
  131. "is_check_number": False,
  132. "resize_image_view": "后跟",
  133. "cutout_mode": "0",
  134. "logo_path": params.logo_path,
  135. "special_goods_art_no_folder_line": "",
  136. "is_use_excel": False if params.excel_path == "" else True, # 是否使用excel
  137. "excel_path": params.excel_path, # excel路径
  138. "is_check_color_is_all": False,
  139. "cutout_is_pass": True,
  140. "assigned_page_dict": {},
  141. "detail_is_pass": True,
  142. "upload_is_pass": False,
  143. "upload_is_enable": False,
  144. "is_filter": False,
  145. "temp_class": temp_class,
  146. "temp_name": params.temp_name,
  147. "temp_name_list": temp_name_list,
  148. "target_error_folder": f"{path}/软件-生成详情错误",
  149. }
  150. # 动态导入类
  151. temp_class_dict = {}
  152. for key, class_path in config_data["temp_class"].items():
  153. module_path, class_name = class_path.rsplit(".", 1)
  154. module = importlib.import_module(module_path)
  155. cls = getattr(module, class_name)
  156. temp_class_dict[key] = cls
  157. config_data["temp_class"] = temp_class_dict
  158. obj = None
  159. run_main = RunMain(obj,token)
  160. return_data = run_main.check_before_cutout(config_data)
  161. cutout_res = run_main.check_for_cutout_image_first_call_back(return_data)
  162. check_for_detail_first_res = None
  163. if cutout_res == True:
  164. return_data_check_before_detail = run_main.check_before_detail(config_data)
  165. print("return_data_check_before_detail", return_data_check_before_detail)
  166. check_for_detail_first_res = run_main.check_for_detail_first_call_back(
  167. return_data_check_before_detail
  168. )
  169. if isinstance(check_for_detail_first_res, partial):
  170. result = check_for_detail_first_res()
  171. try:
  172. config_data = result["config_data"]
  173. except:
  174. config_data = result
  175. print("config_data", config_data)
  176. if config_data["sign_text"] == "已结束详情处理":
  177. # at_pic = AutoDealPics()
  178. print("config_data", config_data)
  179. if config_data["upload_is_enable"]:
  180. to_deal_dir = "{}/软件-详情图生成".format(config_data["image_dir"])
  181. check_path(to_deal_dir)
  182. print("to_deal_dir", to_deal_dir)
  183. if os.path.exists(to_deal_dir):
  184. upload_pic = UploadPic(
  185. windows=None,
  186. to_deal_dir=to_deal_dir,
  187. config_data=config_data,
  188. token=token,
  189. )
  190. upload_pic.run()
  191. out_put_dir = config_data["out_put_dir"]
  192. return {
  193. "code": 0,
  194. "msg": "详情处理完成",
  195. "data": {"out_put_dir": out_put_dir.replace("\\", "/")},
  196. }
  197. else:
  198. return {
  199. "code": 1,
  200. "msg": "处理失败,请联系管理员",
  201. "data": None}
  202. @app.post("/get_device_configs", description="获取可执行程序命令列表")
  203. def get_device_configs(params: ModelGetDeviceConfig):
  204. mode_type = params.mode_type
  205. session = SqlQuery()
  206. configModel = CRUD(DeviceConfig)
  207. configList = configModel.read_all(
  208. session,
  209. conditions={"mode_type": mode_type},
  210. order_by="action_index",
  211. ascending=True,
  212. )
  213. return {
  214. "code": 0,
  215. "msg": "",
  216. "data": {"list": configList},
  217. }
  218. @app.post("/device_config_detail", description="获取可执行程序详情")
  219. def get_device_configs(params: ModelGetDeviceConfigDetail):
  220. action_id = params.id
  221. session = SqlQuery()
  222. configModel = CRUD(DeviceConfig)
  223. model = configModel.read(session, conditions={"id": action_id})
  224. if model == None:
  225. return {"code": 1, "msg": "数据不存在", "data": None}
  226. return {"code": 0, "msg": "", "data": model}
  227. @app.post("/remove_config", description="删除一条可执行命令")
  228. def get_device_configs(params: ModelGetDeviceConfigDetail):
  229. action_id = params.id
  230. session = SqlQuery()
  231. configModel = CRUD(DeviceConfig)
  232. model = configModel.read(session, conditions={"id": action_id})
  233. if model == None:
  234. return {"code": 1, "msg": "数据不存在", "data": None}
  235. configModel.delete(session, obj_id=action_id)
  236. return {"code": 0, "msg": "删除成功", "data": None}
  237. @app.post("/save_device_config", description="创建或修改一条可执行命令")
  238. def save_device_config(params: SaveDeviceConfig):
  239. action_id = params.id
  240. session = SqlQuery()
  241. deviceConfig = CRUD(DeviceConfig)
  242. if action_id == None or action_id == 0:
  243. # 走新增逻辑
  244. params.id = None
  245. save_device_config = deviceConfig.create(session, obj_in=params)
  246. else:
  247. model = deviceConfig.read(session, conditions={"id": action_id})
  248. if model == None:
  249. return {"code": 1, "msg": "数据不存在", "data": None}
  250. # 走编辑逻辑
  251. kwargs = params.__dict__
  252. save_device_config = deviceConfig.update(session, obj_id=action_id, **kwargs)
  253. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  254. @app.post("/reset_config", description="创建或修改一条可执行命令")
  255. def reset_config(params: ModelGetDeviceConfig):
  256. mode_type = params.mode_type
  257. if mode_type == None or mode_type == "":
  258. return {"code": 1, "msg": "参数错误", "data": None}
  259. session = SqlQuery()
  260. deviceConfig = CRUD(DeviceConfig)
  261. res = deviceConfig.deleteConditions(session, conditions={"mode_type": mode_type})
  262. if res is False:
  263. return {"code": 1, "msg": "操作失败", "data": None}
  264. actions = json.load(open("action.json", encoding="utf-8"))
  265. act = []
  266. for item in actions:
  267. if item.get("mode_type") == mode_type:
  268. act.append(item)
  269. batch_insert_device_configs(session, act)
  270. return {"code": 0, "msg": "操作成功", "data": None}
  271. @app.get("/get_photo_records", description="获取拍照记录")
  272. def get_photo_records(page: int = 1, size: int = 5):
  273. session = SqlQuery()
  274. photos = CRUD(PhotoRecord)
  275. statement = (
  276. select(PhotoRecord)
  277. .offset((page - 1) * size)
  278. .limit(size)
  279. .order_by(desc("id"))
  280. .group_by("goods_art_no")
  281. )
  282. list = []
  283. result = session.exec(statement).all()
  284. for item in result:
  285. list_item = photos.read_all(
  286. session, conditions={"goods_art_no": item.goods_art_no}
  287. )
  288. list.append(
  289. {
  290. "goods_art_no": item.goods_art_no,
  291. "action_time": item.create_time,
  292. "items": list_item,
  293. }
  294. )
  295. session.close()
  296. return {
  297. "code": 0,
  298. "msg": "",
  299. "data": {"list": list, "page": page, "size": size},
  300. }
  301. @app.get("/get_photo_record_detail", description="通过货号获取拍照记录详情")
  302. def get_photo_records(goods_art_no: str = None):
  303. if goods_art_no == None:
  304. return {"code": 1, "msg": "参数错误", "data": None}
  305. session = SqlQuery()
  306. photos = CRUD(PhotoRecord)
  307. items = photos.read_all(session, conditions={"goods_art_no": goods_art_no})
  308. session.close()
  309. return {
  310. "code": 0,
  311. "msg": "",
  312. "data": {"list": items},
  313. }
  314. @app.post("/delect_goods_arts", description="通过货号删除记录")
  315. def delect_goods_arts(params: PhotoRecordDelete):
  316. session = SqlQuery()
  317. photos = CRUD(PhotoRecord)
  318. for item in params.goods_art_nos:
  319. photos.deleteConditions(session, conditions={"goods_art_no": item})
  320. session.close()
  321. return {
  322. "code": 0,
  323. "msg": "操作成功",
  324. "data": None,
  325. }
  326. @app.get("/get_sys_config", description="查询系统配置")
  327. def get_sys_config(key: str = None):
  328. if key == None:
  329. return {"code": 1, "msg": "参数错误", "data": None}
  330. session = SqlQuery()
  331. photos = CRUD(SysConfigs)
  332. item = photos.read(session, conditions={"key": key})
  333. session.close()
  334. return {
  335. "code": 0,
  336. "msg": "",
  337. "data": json.loads(item.value),
  338. }
  339. @app.post("/update_sys_configs", description="创建或修改系统配置")
  340. def save_sys_configs(params: SysConfigParams):
  341. session = SqlQuery()
  342. sysConfig = CRUD(SysConfigs)
  343. model = sysConfig.read(session, conditions={"key": params.key})
  344. if model == None:
  345. return {"code": 1, "msg": "配置不存在", "data": None}
  346. # 走编辑逻辑
  347. kwargs = params.__dict__
  348. save_device_config = sysConfig.updateConditions(
  349. session, conditions={"key": params.key}, **kwargs
  350. )
  351. return {"code": 0, "msg": "操作成功", "data": save_device_config}