DBService.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. using IvfTl.Control.Entity.DBEntitys;
  2. using IvfTl.Control.Entity.DTO.ControllerResults;
  3. using IvfTl.Control.Entity.GlobalEntitys;
  4. using IvfTl.Control.Entity.GlobalEnums;
  5. using IvfTl.Control.Entity.InitEntitys;
  6. using ivf_tl_UtilHelper;
  7. using Microsoft.Data.Sqlite;
  8. using Newtonsoft.Json;
  9. using SqlSugar;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Threading.Tasks;
  15. namespace IvfTl.Control.Services
  16. {
  17. public class DBService
  18. {
  19. public event Action<string, LogEnum> ErrorLogEvent;
  20. public event Action<Exception, string, string, LogEnum> ExceptionLogEvent;
  21. public string DbPath = "";
  22. private SqlSugarScope Db;
  23. public DBService()
  24. {
  25. }
  26. public bool StartDbService(string dbPath)
  27. {
  28. try
  29. {
  30. DbPath = dbPath;
  31. string connStr = new SqliteConnectionStringBuilder()
  32. {
  33. DataSource = dbPath,
  34. Mode = SqliteOpenMode.ReadWrite,
  35. }.ToString();
  36. ConnectionConfig connectionConfig = new ConnectionConfig()
  37. {
  38. ConnectionString = connStr,
  39. DbType = DbType.Sqlite,//数据库类型
  40. IsAutoCloseConnection = true //不设成true要手动close
  41. };
  42. Db = new SqlSugarScope(connectionConfig);
  43. // V-051:本地 SQLite CodeFirst 自动建 house_autofocus_calibration 镜像表
  44. // (M2-04 的标定镜像写入此表;本地库原无该表 → 写入失败无数据)。
  45. // InitTables 发 CREATE TABLE IF NOT EXISTS,已建则不动;单独 try 包裹,
  46. // 建表失败不阻断 DB 服务启动(与既有防御式风格一致)。
  47. // D1-09 修复:本地 aivfoTL.db schema 落后于实体(多表缺列,如 tl_setting.localAutofocusEnabled、
  48. // house_well_setting 缺列等)→ control 各 Update/Query 报 "no such column"。
  49. // CodeFirst.InitTables 对已存在表只补缺失列(additive,ADD COLUMN,不删列不丢数据),逐实体自愈本地 schema;
  50. // 每实体独立 try/catch,单表失败(如 SQLite ADD NOT NULL 列限制)不影响其它表与 DB 服务启动。
  51. var localEntities = new[]
  52. {
  53. typeof(HouseAutofocusCalibrationDB), typeof(TLSettingDB), typeof(HouseDB),
  54. typeof(HouseWellSettingDB), typeof(DishDB), typeof(BalanceDB),
  55. typeof(EmbryoDB), typeof(HouseWellPhotoDB), typeof(PictureDB)
  56. };
  57. foreach (var et in localEntities)
  58. {
  59. try { Db.CodeFirst.InitTables(et); }
  60. catch (Exception exTable)
  61. {
  62. ExceptionLogEvent?.Invoke(exTable, "DBServiceImpl.StartDbService.InitTables:" + et.Name, null, LogEnum.DbException);
  63. }
  64. }
  65. return true;
  66. }
  67. catch (Exception ex)
  68. {
  69. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.StartDbService", null, LogEnum.DbException);
  70. return false;
  71. }
  72. }
  73. /// <summary>
  74. /// 生成实体
  75. /// </summary>
  76. public void BuildEntity(string path, string nameSpace)
  77. {
  78. Db.DbFirst.IsCreateAttribute().CreateClassFile(path, nameSpace);
  79. }
  80. /// <summary>
  81. /// 数据库更新
  82. /// </summary>
  83. /// <param name="tLInitControllerResult"></param>
  84. public void DBUpdateTLInfo(TLInitControllerResult tLInitControllerResult)
  85. {
  86. try
  87. {
  88. TLSettingDB tLSettingDB = ConvertHelper.ConvertToTLSettingDB(tLInitControllerResult.TLSetting);
  89. if (tLSettingDB == null)
  90. {
  91. return;
  92. }
  93. var oldSetting = Db.Queryable<TLSettingDB>().First(x => x.tlSn == tLSettingDB.tlSn);
  94. if (oldSetting != null)
  95. {
  96. tLSettingDB.cid = oldSetting.cid;
  97. Db.Updateable(tLSettingDB).ExecuteCommand();
  98. }
  99. else
  100. {
  101. Db.Insertable(tLSettingDB).ExecuteCommand();
  102. }
  103. UpdateHoustInfo(tLInitControllerResult.HouseList, tLSettingDB.tlSn);
  104. UpdateHouseWellSetting(tLInitControllerResult.HouseWellList, tLSettingDB.tlSn);
  105. }
  106. catch (Exception ex)
  107. {
  108. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.DBUpdateTLInfo", null, LogEnum.DbException);
  109. }
  110. }
  111. /// <summary>
  112. /// 数据库更新并获取数据
  113. /// </summary>
  114. /// <param name="tLInitData"></param>
  115. /// <returns></returns>
  116. public (TLSettingDB, List<HouseDB>, List<HouseWellSettingDB>) DBGetTLInfo(TLInitData tLInitData)
  117. {
  118. try
  119. {
  120. Db.Updateable<TLSettingDB>()
  121. .SetColumns(it => it.softwareVersion == tLInitData.softwareVersion)
  122. .SetColumns(x => x.verticalMotorPulseMax == tLInitData.verticalMotorPulseMax)
  123. .Where(it => it.tlSn == tLInitData.tlSn).ExecuteCommand();
  124. var houseSnList = tLInitData.houseLinkDataList.Select(x => x.houseSn).ToList();
  125. UpdateHouseInfo(tLInitData.houseLinkDataList, tLInitData.tlSn);
  126. UpdateHouseWellSetting(tLInitData.houseEEPROInitDTOList, tLInitData.tlSn);
  127. TLSettingDB tLSettingDB = Db.Queryable<TLSettingDB>().First(it => it.tlSn == tLInitData.tlSn);
  128. List<HouseDB> houseDBList = Db.Queryable<HouseDB>().Where(x => x.tlSn == tLInitData.tlSn && houseSnList.Contains(x.houseSn)).ToList();
  129. List<HouseWellSettingDB> HouseWellSettingDBList = Db.Queryable<HouseWellSettingDB>().Where(x => x.tlSn == tLInitData.tlSn && houseSnList.Contains(x.houseSn)).ToList();
  130. return (tLSettingDB, houseDBList, HouseWellSettingDBList);
  131. }
  132. catch (Exception ex)
  133. {
  134. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.UpdateHouseInfo", null, LogEnum.DbException);
  135. return (new TLSettingDB(), new List<HouseDB>(), new List<HouseWellSettingDB>());
  136. }
  137. }
  138. #region DishDB
  139. public List<Dish> GetDBDishs(string tlsn)
  140. {
  141. try
  142. {
  143. var dishList = Db.Queryable<DishDB>().Where(it => it.tlSn == tlsn && it.endTime == null).ToList();
  144. if (!dishList.Any()) return new List<Dish>();
  145. List<Dish> result = new List<Dish>();
  146. foreach (var item in dishList)
  147. {
  148. Dish dish = ConvertHelper.ConvertToDish(item);
  149. result.Add(dish);
  150. var embryoList = Db.Queryable<EmbryoDB>().Where(it => it.dishId == item.id).ToList();
  151. if (!embryoList.Any()) continue;
  152. dish.Embryo = new List<Embryo>();
  153. foreach (var itemEmbryo in embryoList)
  154. {
  155. dish.Embryo.Add(ConvertHelper.ConvertToEmbryo(itemEmbryo));
  156. }
  157. }
  158. return result;
  159. }
  160. catch (Exception ex)
  161. {
  162. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.GetDBDishs", null, LogEnum.DbException);
  163. return new List<Dish>();
  164. }
  165. }
  166. public void AddDishs(List<DishDB> dishDbList, string tlsn)
  167. {
  168. try
  169. {
  170. Db.Deleteable<DishDB>().Where(x => x.tlSn == tlsn).ExecuteCommand();
  171. Db.Insertable(dishDbList).ExecuteCommand();
  172. return;
  173. var alldishList = Db.Queryable<DishDB>().Where(it => it.tlSn == tlsn).ToList();
  174. var oldDishList = alldishList.Where(it => !it.endTime.HasValue).ToList();
  175. List<DishDB> endDishs = new List<DishDB>();
  176. foreach (var item in oldDishList)
  177. {
  178. var aa = dishDbList.FirstOrDefault(x => x.id == item.id);
  179. if (aa == null)
  180. {
  181. item.endTime = DateTime.Now;
  182. endDishs.Add(item);
  183. }
  184. }
  185. if (endDishs.Any())
  186. {
  187. Db.Updateable(endDishs).UpdateColumns(it => new { it.endTime }).ExecuteCommand();
  188. }
  189. List<DishDB> insertDishList = new List<DishDB>();
  190. List<DishDB> updateDishList = new List<DishDB>();
  191. foreach (var item in dishDbList)
  192. {
  193. var aa = alldishList.FirstOrDefault(x => x.id == item.id);
  194. if (aa == null)
  195. {
  196. insertDishList.Add(item);
  197. }
  198. else
  199. {
  200. if (aa.endTime.HasValue)
  201. {
  202. aa.endTime = null;
  203. updateDishList.Add(aa);
  204. }
  205. }
  206. }
  207. if (insertDishList.Any())
  208. {
  209. Db.Insertable(insertDishList).ExecuteCommand();
  210. }
  211. if (updateDishList.Any())
  212. {
  213. Db.Updateable(updateDishList).UpdateColumns(it => new { it.endTime }).ExecuteCommand();
  214. }
  215. }
  216. catch (Exception ex)
  217. {
  218. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.AddDishs", null, LogEnum.DbException);
  219. }
  220. }
  221. public void AddDish(Dish dish, string tlsn)
  222. {
  223. try
  224. {
  225. Db.Deleteable<DishDB>().Where(x => x.id == dish.id && x.tlSn == tlsn).ExecuteCommand();
  226. Db.Deleteable<EmbryoDB>().Where(x => x.dishId == dish.id && x.tlSn == tlsn).ExecuteCommand();
  227. DishDB dishDB = ConvertHelper.ConvertToDishDB(dish);
  228. Db.Insertable(dishDB).ExecuteCommand();
  229. List<EmbryoDB> embryoDbList = new List<EmbryoDB>();
  230. foreach (var item in dish.Embryo)
  231. {
  232. embryoDbList.Add(ConvertHelper.ConvertToEmbryoDB(item));
  233. }
  234. Db.Insertable(embryoDbList).ExecuteCommand();
  235. }
  236. catch (Exception ex)
  237. {
  238. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.AddDish", null, LogEnum.DbException);
  239. }
  240. }
  241. public void EndDish(long id, DateTime endTime, string tlsn)
  242. {
  243. try
  244. {
  245. Db.Updateable<DishDB>().SetColumns(it => it.endTime == endTime).Where(it => it.id == id && it.tlSn == tlsn).ExecuteCommand();
  246. Db.Updateable<EmbryoDB>().SetColumns(it => new EmbryoDB()
  247. {
  248. state = (int)EmbryoState.End,
  249. stateTime = endTime,
  250. }).Where(it => it.dishId == id && it.tlSn == tlsn && it.state == (int)EmbryoState.None).ExecuteCommand();
  251. }
  252. catch (Exception ex)
  253. {
  254. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.EndDish", null, LogEnum.DbException);
  255. }
  256. }
  257. #endregion
  258. #region EmbryoDB
  259. public void AddEmbryos(List<EmbryoDB> embryoDbList, string tlsn)
  260. {
  261. try
  262. {
  263. Db.Deleteable<EmbryoDB>().Where(x => x.tlSn == tlsn).ExecuteCommand();
  264. Db.Insertable(embryoDbList).ExecuteCommand();
  265. return;
  266. var allEmbryoList = Db.Queryable<EmbryoDB>().Where(it => it.tlSn == tlsn).ToList();
  267. var ingEmbryoList = allEmbryoList.Where(x => x.state == (int)EmbryoState.None).ToList();
  268. var updateEmbryoList = new List<EmbryoDB>();
  269. foreach (var item in ingEmbryoList)
  270. {
  271. var a = embryoDbList.FirstOrDefault(x => x.id == item.id);
  272. if (a == null)
  273. {
  274. item.state = (int)EmbryoState.End;
  275. item.stateTime = DateTime.Now;
  276. updateEmbryoList.Add(item);
  277. }
  278. if (a.state != item.state)
  279. {
  280. item.state = a.state;
  281. item.stateTime = a.stateTime;
  282. updateEmbryoList.Add(item);
  283. }
  284. }
  285. if (updateEmbryoList.Any())
  286. {
  287. Db.Updateable(updateEmbryoList).UpdateColumns(it => new { it.state, it.stateTime }).ExecuteCommand();
  288. }
  289. updateEmbryoList.Clear();
  290. var insertEmbryoList = new List<EmbryoDB>();
  291. foreach (var item in embryoDbList)
  292. {
  293. var aa = allEmbryoList.FirstOrDefault(x => x.id == item.id);
  294. if (aa == null)
  295. {
  296. insertEmbryoList.Add(item);
  297. }
  298. else
  299. {
  300. if (aa.state != item.state)
  301. {
  302. aa.state = item.state;
  303. aa.stateTime = item.stateTime;
  304. updateEmbryoList.Add(aa);
  305. }
  306. }
  307. }
  308. if (insertEmbryoList.Any())
  309. {
  310. Db.Insertable(insertEmbryoList).ExecuteCommand();
  311. }
  312. if (updateEmbryoList.Any())
  313. {
  314. Db.Updateable(updateEmbryoList).UpdateColumns(it => new { it.state, it.stateTime }).ExecuteCommand();
  315. }
  316. }
  317. catch (Exception ex)
  318. {
  319. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.AddEmbryos", null, LogEnum.DbException);
  320. }
  321. }
  322. public void ChangeEmbryoState(Embryo embryo)
  323. {
  324. try
  325. {
  326. Db.Updateable<EmbryoDB>().SetColumns(it => new EmbryoDB()
  327. {
  328. state = embryo.state,
  329. stateTime = embryo.stateTime,
  330. }).Where(it => it.id == embryo.id && it.tlSn == embryo.tlSn).ExecuteCommand();
  331. }
  332. catch (Exception ex)
  333. {
  334. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.ChangeEmbryoState", null, LogEnum.DbException);
  335. }
  336. }
  337. #endregion
  338. #region BalanceDB
  339. public List<Balance> DbGetBalances(string tlsn)
  340. {
  341. try
  342. {
  343. var a = Db.Queryable<BalanceDB>().Where(it => it.tlSn == tlsn && it.endTime == null).ToList();
  344. if (!a.Any()) return new List<Balance>();
  345. List<Balance> result = new List<Balance>();
  346. foreach (var item in a)
  347. {
  348. result.Add(ConvertHelper.ConvertToBalance(item));
  349. }
  350. return result;
  351. }
  352. catch (Exception ex)
  353. {
  354. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.DbGetBalances", null, LogEnum.DbException);
  355. return new List<Balance>();
  356. }
  357. }
  358. public void AddBalances(List<BalanceDB> balanceDbList, string tlsn)
  359. {
  360. try
  361. {
  362. Db.Deleteable<BalanceDB>().Where(x => x.tlSn == tlsn).ExecuteCommand();
  363. Db.Insertable(balanceDbList).ExecuteCommand();
  364. return;
  365. var allBalanceList = Db.Queryable<BalanceDB>().Where(it => it.tlSn == tlsn).ToList();
  366. var ingBalacneList = allBalanceList.Where(x => !x.endTime.HasValue).ToList();
  367. var updateList = new List<BalanceDB>();
  368. foreach (var item in ingBalacneList)
  369. {
  370. var a = balanceDbList.FirstOrDefault(x => x.id == item.id);
  371. if (a == null)
  372. {
  373. item.endTime = DateTime.Now;
  374. updateList.Add(item);
  375. }
  376. }
  377. if (updateList.Any())
  378. {
  379. Db.Updateable(updateList).UpdateColumns(it => new { it.endTime }).ExecuteCommand();
  380. }
  381. updateList.Clear();
  382. var insertList = new List<BalanceDB>();
  383. foreach (var item in balanceDbList)
  384. {
  385. var old = allBalanceList.FirstOrDefault(x => x.id == item.id);
  386. if (old == null)
  387. {
  388. insertList.Add(item);
  389. }
  390. else
  391. {
  392. if (old.endTime != item.endTime)
  393. {
  394. old.endTime = item.endTime;
  395. updateList.Add(old);
  396. }
  397. }
  398. }
  399. if (updateList.Any())
  400. {
  401. Db.Updateable(updateList).UpdateColumns(it => new { it.endTime }).ExecuteCommand();
  402. }
  403. if (insertList.Any())
  404. {
  405. Db.Insertable(insertList).ExecuteCommand();
  406. }
  407. }
  408. catch (Exception ex)
  409. {
  410. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.AddBalances", null, LogEnum.DbException);
  411. }
  412. }
  413. public void AddBalance(Balance balance)
  414. {
  415. try
  416. {
  417. var oldBalance = Db.Queryable<BalanceDB>().First(x => x.id == balance.id);
  418. if (oldBalance == null)
  419. {
  420. BalanceDB balanceDB = ConvertHelper.ConvertToBalanceDB(balance);
  421. Db.Insertable(balanceDB).ExecuteCommand();
  422. }
  423. else
  424. {
  425. if (oldBalance.endTime.HasValue)
  426. {
  427. oldBalance.endTime = null;
  428. Db.Updateable(oldBalance).UpdateColumns(it => new { it.endTime }).ExecuteCommand();
  429. }
  430. }
  431. }
  432. catch (Exception ex)
  433. {
  434. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.AddBalance", null, LogEnum.DbException);
  435. }
  436. }
  437. public void EndBalance(long id, DateTime? endTime)
  438. {
  439. try
  440. {
  441. Db.Updateable<BalanceDB>().SetColumns(it => it.endTime == endTime).Where(it => it.id == id).ExecuteCommand();
  442. return;
  443. var oldBalance = Db.Queryable<BalanceDB>().First(x => x.id == id);
  444. if (oldBalance == null) return;
  445. oldBalance.endTime = endTime;
  446. Db.Updateable(oldBalance).UpdateColumns(it => new { it.endTime }).ExecuteCommand();
  447. }
  448. catch (Exception ex)
  449. {
  450. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.EndBalance", null, LogEnum.DbException);
  451. }
  452. }
  453. #endregion
  454. #region houseDB
  455. /// <summary>
  456. /// 更新仓室信息
  457. /// </summary>
  458. /// <param name="houseList"></param>
  459. /// <param name="tlsn"></param>
  460. private void UpdateHoustInfo(List<House> houseList, string tlsn)
  461. {
  462. try
  463. {
  464. List<HouseDB> houseDBList = new List<HouseDB>();
  465. foreach (var item in houseList)
  466. {
  467. houseDBList.Add(ConvertHelper.ConvertToHouseDB(item));
  468. }
  469. if (!houseDBList.Any()) return;
  470. Db.Deleteable<HouseDB>().Where(x => x.tlSn == tlsn).ExecuteCommand();
  471. Db.Insertable(houseDBList).ExecuteCommand();
  472. }
  473. catch (Exception ex)
  474. {
  475. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.UpdateHoustInfo", null, LogEnum.DbException);
  476. }
  477. }
  478. /// <summary>
  479. /// 初始化时更新仓室信息
  480. /// </summary>
  481. /// <param name="houseLinkDataList"></param>
  482. /// <param name="tlsn"></param>
  483. private void UpdateHouseInfo(List<HouseInitData> houseLinkDataList, string tlsn)
  484. {
  485. try
  486. {
  487. if (!houseLinkDataList.Any()) return;
  488. var houseSnList = houseLinkDataList.Select(x => x.houseSn).ToList();
  489. var oldHouseList = Db.Queryable<HouseDB>().Where(x => x.tlSn == tlsn && houseSnList.Contains(x.houseSn)).ToList();
  490. if (!oldHouseList.Any()) return;
  491. foreach (var item in oldHouseList)
  492. {
  493. var newItem = houseLinkDataList.FirstOrDefault(x => x.houseSn == item.houseSn);
  494. if (newItem == null) continue;
  495. item.housePort = newItem.housePort;
  496. item.ccdId = newItem.ccdId;
  497. item.ccdSn = newItem.ccdSn;
  498. item.inletValveOpeningTime = newItem.inletValveOpeningTime;
  499. item.temperatureLowerHeatingPlate = newItem.temperatureLowerHeatingPlate;
  500. item.verticalMotorSpacePulse = newItem.verticalMotorSpacePulse;
  501. }
  502. var updateHouseRsult = Db.Updateable(oldHouseList)
  503. .UpdateColumns(it => new
  504. {
  505. it.housePort,
  506. it.ccdId,
  507. it.ccdSn,
  508. it.inletValveOpeningTime,
  509. it.temperatureLowerHeatingPlate,
  510. it.verticalMotorSpacePulse
  511. }).ExecuteCommand();
  512. }
  513. catch (Exception ex)
  514. {
  515. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.UpdateHouseInfo", null, LogEnum.DbException);
  516. }
  517. }
  518. #endregion
  519. #region HouseWellSettingDB
  520. private void UpdateHouseWellSetting(List<HouseWellSetting> houseWellSettingList, string tlSn)
  521. {
  522. try
  523. {
  524. List<HouseWellSettingDB> houseWellSettingDBList = new List<HouseWellSettingDB>();
  525. foreach (var item in houseWellSettingList)
  526. {
  527. houseWellSettingDBList.Add(ConvertHelper.ConvertToHouseWellSettingDB(item));
  528. }
  529. Db.Deleteable<HouseWellSettingDB>().Where(x => x.tlSn == tlSn).ExecuteCommand();
  530. Db.Insertable(houseWellSettingDBList).ExecuteCommand();
  531. }
  532. catch (Exception ex)
  533. {
  534. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.UpdateHouseWellSetting", null, LogEnum.DbException);
  535. }
  536. }
  537. private void UpdateHouseWellSetting(List<HouseEEPROInfo> houseEEPROInfos, string tlsn)
  538. {
  539. try
  540. {
  541. if (!houseEEPROInfos.Any()) return;
  542. var houseSnList = houseEEPROInfos.Select(x => x.houseSn).ToList();
  543. var oldHouseList = Db.Queryable<HouseWellSettingDB>().Where(x => x.tlSn == tlsn && houseSnList.Contains(x.houseSn)).ToList();
  544. if (!oldHouseList.Any()) return;
  545. foreach (var item in oldHouseList)
  546. {
  547. var newItem = houseEEPROInfos.FirstOrDefault(x => x.houseSn == item.houseSn);
  548. if (newItem == null) continue;
  549. item.eepromClearPosition = newItem.eepromClearPosition;
  550. switch (item.wellSn)
  551. {
  552. case 1:
  553. item.horizontalMotorPosition = newItem.hwell1;
  554. break;
  555. case 2:
  556. item.horizontalMotorPosition = newItem.hwell2;
  557. break;
  558. case 3:
  559. item.horizontalMotorPosition = newItem.hwell3;
  560. break;
  561. case 4:
  562. item.horizontalMotorPosition = newItem.hwell4;
  563. break;
  564. case 5:
  565. item.horizontalMotorPosition = newItem.hwell5;
  566. break;
  567. case 6:
  568. item.horizontalMotorPosition = newItem.hwell6;
  569. break;
  570. case 7:
  571. item.horizontalMotorPosition = newItem.hwell7;
  572. break;
  573. case 8:
  574. item.horizontalMotorPosition = newItem.hwell8;
  575. break;
  576. case 9:
  577. item.horizontalMotorPosition = newItem.hwell9;
  578. break;
  579. case 10:
  580. item.horizontalMotorPosition = newItem.hwell10;
  581. break;
  582. case 11:
  583. item.horizontalMotorPosition = newItem.hwell11;
  584. break;
  585. case 12:
  586. item.horizontalMotorPosition = newItem.hwell12;
  587. break;
  588. case 13:
  589. item.horizontalMotorPosition = newItem.hwell13;
  590. break;
  591. case 14:
  592. item.horizontalMotorPosition = newItem.hwell14;
  593. break;
  594. case 15:
  595. item.horizontalMotorPosition = newItem.hwell15;
  596. break;
  597. case 16:
  598. item.horizontalMotorPosition = newItem.hwell16;
  599. break;
  600. }
  601. }
  602. var updateHouseRsult = Db.Updateable(oldHouseList)
  603. .UpdateColumns(it => new
  604. {
  605. it.horizontalMotorPosition,
  606. it.eepromClearPosition,
  607. }).ExecuteCommand();
  608. }
  609. catch (Exception ex)
  610. {
  611. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.UpdateHouseWellSetting", null, LogEnum.DbException);
  612. }
  613. }
  614. #endregion
  615. #region pictureDB
  616. public void AddPictrue(PictureDB pictureDB)
  617. {
  618. try
  619. {
  620. var oldPic = Db.Queryable<PictureDB>().First(x => x.TlSn == pictureDB.TlSn && x.SourceImageName == pictureDB.SourceImageName);
  621. if (oldPic == null)
  622. {
  623. Db.Insertable(pictureDB).ExecuteCommand();
  624. }
  625. }
  626. catch (Exception ex)
  627. {
  628. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.AddPictrue", null, LogEnum.DbException);
  629. }
  630. }
  631. public void DeletePictrue(string fileName, string tlsn)
  632. {
  633. try
  634. {
  635. Db.Deleteable<PictureDB>().Where(x => x.TlSn == tlsn && x.SourceImageName == fileName).ExecuteCommand();
  636. }
  637. catch (Exception ex)
  638. {
  639. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.DeletePictrue", null, LogEnum.DbException);
  640. }
  641. }
  642. public PictureDB SearchPicture(string fileName, string tlsn)
  643. {
  644. try
  645. {
  646. var pic = Db.Queryable<PictureDB>().First(x => x.TlSn == tlsn && x.SourceImageName == fileName);
  647. return pic;
  648. }
  649. catch (Exception ex)
  650. {
  651. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.SearchPicture", null, LogEnum.DbException);
  652. return null;
  653. }
  654. }
  655. #endregion
  656. #region HouseWellPhotoDB
  657. /// <summary>
  658. /// 更新拍照位置
  659. /// </summary>
  660. /// <param name="houses"></param>
  661. /// <param name="housesn"></param>
  662. /// <param name="tlsn"></param>
  663. /// <param name="positionType">0表示自动对焦</param>
  664. public void UpdatePosition(List<HouseWellPhotoDB> houses, int housesn, string tlsn, int positionType)
  665. {
  666. try
  667. {
  668. var wellList = houses.Select(x => x.wellSn).Distinct().ToList();
  669. //Db.Deleteable<HouseWellPhotoDB>().Where(x => x.tlSn == tlsn && x.houseSn == housesn && wellList.Contains(x.wellSn) && x.positionType == positionType).ExecuteCommand();
  670. if (positionType == 0)
  671. {
  672. Db.Deleteable<HouseWellPhotoDB>().Where(x => x.tlSn == tlsn && x.houseSn == housesn && wellList.Contains(x.wellSn) && x.positionType == 0).ExecuteCommand();
  673. }
  674. else
  675. {
  676. Db.Deleteable<HouseWellPhotoDB>().Where(x => x.tlSn == tlsn && x.houseSn == housesn && wellList.Contains(x.wellSn) && x.positionType != 0).ExecuteCommand();
  677. }
  678. Db.Insertable(houses).ExecuteCommand();
  679. }
  680. catch (Exception ex)
  681. {
  682. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.UpdatePosition", null, LogEnum.DbException);
  683. }
  684. }
  685. /// <summary>
  686. /// 获取电机位置
  687. /// </summary>
  688. /// <param name="wellSn"></param>
  689. /// <param name="housesn"></param>
  690. /// <param name="tlsn"></param>
  691. /// <param name="positionType">0表示自动对焦</param>
  692. /// <returns></returns>
  693. public List<HouseWellPhotoDB> GetPosition(List<int> wellSn, int housesn, string tlsn, int positionType)
  694. {
  695. try
  696. {
  697. //return Db.Queryable<HouseWellPhotoDB>().Where(x => x.tlSn == tlsn && x.houseSn == housesn && wellSn.Contains(x.wellSn) && x.positionType == positionType).ToList();
  698. if (positionType == 0)
  699. {
  700. return Db.Queryable<HouseWellPhotoDB>().Where(x => x.tlSn == tlsn && x.houseSn == housesn && wellSn.Contains(x.wellSn) && x.positionType == 0).ToList();
  701. }
  702. else
  703. {
  704. return Db.Queryable<HouseWellPhotoDB>().Where(x => x.tlSn == tlsn && x.houseSn == housesn && wellSn.Contains(x.wellSn) && x.positionType != 0).ToList();
  705. }
  706. }
  707. catch (Exception ex)
  708. {
  709. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.GetPosition", null, LogEnum.DbException);
  710. return new List<HouseWellPhotoDB>();
  711. }
  712. }
  713. #endregion
  714. #region HouseAutofocusCalibrationDB(M2-04 标定结果库内镜像)
  715. /// <summary>
  716. /// 标定结果镜像入 house_autofocus_calibration(真相源仍为本地 calibration.json,见 12 §2.7)。
  717. /// scene=0 出厂基准:按 (tlSn,houseSn,wellSn,scene=0,deleted==null) upsert(每 well 唯一);
  718. /// scene=1 日常对焦:直接 Insertable append(留历史,清理任务只删 scene=1)。
  719. /// 入参取标定产出的原始值(WellCalib 解包后传入),本方法不依赖 IvfTl.AutoFocus 程序集。
  720. /// 写库异常被本方法吞掉(记日志),绝不向上抛,保证不崩对焦/采集线程。
  721. /// </summary>
  722. /// <param name="tlSn">tl 设备 sn</param>
  723. /// <param name="houseSn">仓室编号</param>
  724. /// <param name="wellSn">well 编号</param>
  725. /// <param name="scene">场景:0=出厂基准 1=日常对焦</param>
  726. /// <param name="focusZ">最清晰层 Z 脉冲(锚点)</param>
  727. /// <param name="exposure">曝光(×100µs)</param>
  728. /// <param name="horizontalPulse">水平电机位置脉冲</param>
  729. /// <param name="peakRatio">清晰度峰比</param>
  730. /// <param name="circleFound">是否检到 well 圆</param>
  731. /// <param name="centerOffsetPct">居中偏移百分比</param>
  732. /// <param name="note">备注</param>
  733. /// <param name="source">结果来源,默认 LOCAL_JSON</param>
  734. public void SaveAutofocusCalibration(string tlSn, int houseSn, int wellSn, int scene,
  735. int focusZ, int exposure, int horizontalPulse, decimal peakRatio, bool circleFound,
  736. decimal centerOffsetPct, string note = "", string source = "LOCAL_JSON")
  737. {
  738. try
  739. {
  740. DateTime now = DateTime.Now;
  741. if (scene == 0)
  742. {
  743. // 出厂基准:每 well 唯一,存在则更新(upsert),不存在则插入;清理任务不删 scene=0。
  744. var old = Db.Queryable<HouseAutofocusCalibrationDB>()
  745. .First(x => x.tlSn == tlSn && x.houseSn == houseSn && x.wellSn == wellSn
  746. && x.scene == 0 && x.deleted == null);
  747. if (old != null)
  748. {
  749. old.focusZ = focusZ;
  750. old.exposure = exposure;
  751. old.horizontalPulse = horizontalPulse;
  752. old.peakRatio = peakRatio;
  753. old.circleFound = circleFound ? 1 : 0;
  754. old.centerOffsetPct = centerOffsetPct;
  755. old.calibTime = now;
  756. old.source = source;
  757. old.note = note;
  758. old.updateTime = now;
  759. Db.Updateable(old).ExecuteCommand();
  760. return;
  761. }
  762. }
  763. // scene=1 日常对焦 append,或 scene=0 首次插入。
  764. var entity = new HouseAutofocusCalibrationDB
  765. {
  766. tlSn = tlSn,
  767. houseSn = houseSn,
  768. wellSn = wellSn,
  769. scene = scene,
  770. focusZ = focusZ,
  771. exposure = exposure,
  772. horizontalPulse = horizontalPulse,
  773. peakRatio = peakRatio,
  774. circleFound = circleFound ? 1 : 0,
  775. centerOffsetPct = centerOffsetPct,
  776. calibTime = now,
  777. source = source,
  778. note = note,
  779. createTime = now,
  780. };
  781. Db.Insertable(entity).ExecuteCommand();
  782. }
  783. catch (Exception ex)
  784. {
  785. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.SaveAutofocusCalibration", null, LogEnum.DbException);
  786. }
  787. }
  788. /// <summary>
  789. /// M2-06 安全门降级用:读 scene=0 出厂基准的最清晰层 Z 脉冲(FocusZ)。
  790. /// 查 house_autofocus_calibration 中 (tlSn,houseSn,wellSn,scene=0,deleted==null) 的基准行,
  791. /// 取最新一条(按 calibTime 倒序)的 focusZ;无基准/异常返回 null。
  792. /// 用于安全门关闭(local_autofocus_enabled=0)时按基准位置拍照(降级),不做实际对焦。
  793. /// 读库异常被本方法吞掉(记日志),绝不向上抛,保证不崩对焦/采集线程。
  794. /// </summary>
  795. public int? GetBaselineFocusZ(string tlSn, int houseSn, int wellSn)
  796. {
  797. try
  798. {
  799. var baseline = Db.Queryable<HouseAutofocusCalibrationDB>()
  800. .Where(x => x.tlSn == tlSn && x.houseSn == houseSn && x.wellSn == wellSn
  801. && x.scene == 0 && x.deleted == null)
  802. .OrderBy(x => x.calibTime, OrderByType.Desc)
  803. .First();
  804. return baseline?.focusZ;
  805. }
  806. catch (Exception ex)
  807. {
  808. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.GetBaselineFocusZ", null, LogEnum.DbException);
  809. return null;
  810. }
  811. }
  812. /// <summary>
  813. /// G4-1 / 需求文档12 §2.7:对焦标定数据清理任务。
  814. /// 物理删除 house_autofocus_calibration 中 scene=1(日常对焦) 且 calibTime 早于 (now - keepDays) 的记录;
  815. /// scene=0(出厂基准) 永不删除——否则日常对焦失去参照基准(12 §2.7 约束①)。
  816. /// keepDays&lt;=0 视为不清理(安全阀:避免 cutoff 异常误删全部)。
  817. /// 全 try 兜底,异常吞掉记日志,绝不向上抛(不崩采集/对焦线程)。返回删除条数。
  818. /// </summary>
  819. /// <param name="keepDays">保留天数(来自 tl_setting.clean_autofocus_data 下发值,默认30)</param>
  820. public int CleanAutofocusData(int keepDays)
  821. {
  822. try
  823. {
  824. if (keepDays <= 0) return 0;
  825. DateTime cutoff = DateTime.Now.AddDays(-keepDays);
  826. // Deleteable 物理删除(本表无逻辑删除全局过滤):retention 需真正缩表,故物理删而非置 deleted。
  827. int n = Db.Deleteable<HouseAutofocusCalibrationDB>()
  828. .Where(x => x.scene == 1 && x.calibTime < cutoff)
  829. .ExecuteCommand();
  830. return n;
  831. }
  832. catch (Exception ex)
  833. {
  834. ExceptionLogEvent?.Invoke(ex, "DBServiceImpl.CleanAutofocusData", null, LogEnum.DbException);
  835. return 0;
  836. }
  837. }
  838. #endregion
  839. }
  840. }