JGRManager.cs 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644
  1. using AmrControl.ADS;
  2. using AmrControl.Common;
  3. using AmrControl.Common.HttpClients;
  4. using AmrControl.DB;
  5. using AmrControl.DB.Models;
  6. using AmrControl.Dto;
  7. using AmrControl.exceptions;
  8. using AmrControl.mq;
  9. using AmrControl.services;
  10. using AmrControl.Vo;
  11. using Microsoft.AspNetCore.SignalR;
  12. using Microsoft.EntityFrameworkCore.Metadata.Internal;
  13. using Newtonsoft.Json;
  14. using NPOI.HSSF.Record;
  15. using NPOI.SS.Formula.Functions;
  16. using NPOI.SS.UserModel;
  17. using NPOI.Util;
  18. using NPOI.XSSF.UserModel;
  19. using NPOI.XWPF.UserModel;
  20. using Org.BouncyCastle.Crypto.Paddings;
  21. using Org.BouncyCastle.Ocsp;
  22. using Org.BouncyCastle.Utilities;
  23. using System.Collections.Concurrent;
  24. using System.Diagnostics.Metrics;
  25. using System.Drawing;
  26. using System.IO;
  27. using System.Net.NetworkInformation;
  28. using System.Reflection;
  29. using System.Runtime.InteropServices;
  30. using System.Text;
  31. using System.Threading;
  32. using System.Threading.Tasks;
  33. using TwinCAT.Ads.TypeSystem;
  34. using TwinCAT.PlcOpen;
  35. using static NPOI.HSSF.Util.HSSFColor;
  36. namespace AmrControl.JGR
  37. {
  38. /// <summary>
  39. /// 车辆控制器,用来控制车辆,通过ADS-EtherCAT系统
  40. /// </summary>
  41. public class JGRManager : IJGR, IDisposable
  42. {
  43. protected static JGRManager Instance = null;
  44. private readonly static object balanceLock = new object();
  45. private IHubContext<ChatHub> hubContext;
  46. private MyDbHandler dbHandler;
  47. private int endpointX = 0, endpointY = 0;
  48. /// <summary>
  49. /// 仓储入库位
  50. /// </summary>
  51. public readonly int[] inPos = new int[2] { 1, 4 };
  52. /// <summary>
  53. /// 仓储出库位
  54. /// </summary>
  55. public readonly int[] outPos = new int[2] { 1, 4 };
  56. /// <summary>
  57. /// 轨道车入库位
  58. /// </summary>
  59. public readonly int[] inAmrPos = new int[2] { 30, 3 };
  60. /// <summary>
  61. /// 轨道车出库位
  62. /// </summary>
  63. public readonly int[] outAmrPos = new int[2] { 30, 3 };
  64. /// <summary>
  65. /// 拣选工位坐标
  66. /// </summary>
  67. public readonly int[] selectStationPos = new int[2] {29, 7 };
  68. /// <summary>
  69. /// 服务地址
  70. /// </summary>
  71. private string serviceAddr;
  72. private readonly IConfiguration _configuration;
  73. private readonly ITaskExecManager _taskExecManager;
  74. private readonly IRegistryService _registryService;
  75. /// <summary>
  76. /// 车辆任务占用处理
  77. /// </summary>
  78. private volatile ConcurrentDictionary<string, string> jgrTaskMap = new();
  79. /// <summary>
  80. /// 取消任务
  81. /// </summary>
  82. private volatile List<string> cancelTaskIds = new();
  83. /// <summary>
  84. /// 启动
  85. /// </summary>
  86. private volatile bool started;
  87. ///// <summary>
  88. ///// 车的状态更新时间
  89. ///// </summary>
  90. //private readonly double querySeconds = 5;
  91. //包含的车和车的信息,会实时更新
  92. ConcurrentDictionary<string, JGR_Tc_Model> jgrs = new ConcurrentDictionary<string, JGR_Tc_Model>();
  93. Dictionary<string, ChargingStationDataModel> chargers = new Dictionary<string, ChargingStationDataModel>();
  94. Dictionary<string, StationDataModel> stations = new Dictionary<string, StationDataModel>();
  95. int maxDisplayX = 0, maxDisplayY = 0;
  96. /// <summary>
  97. /// 轨道的格子定义
  98. /// </summary>
  99. Dictionary<long, GridCell> railGridCells = new Dictionary<long, GridCell>();
  100. /// <summary>
  101. /// 仓储的格子定义
  102. /// </summary>
  103. Dictionary<long, GridCell> storageGridCells = new Dictionary<long, GridCell>();
  104. private string[] disableStorageCells = new string[]
  105. {
  106. "1,3","1,4","1,5","1,6","2,3","2,4","2,5"
  107. };
  108. /// <summary>
  109. /// 锁对象
  110. /// </summary>
  111. Mutex mutex = new Mutex();
  112. /// <summary>
  113. /// 这种signalr注入的方式和实际使用chathub并不是同一个,实际上并不齐作用
  114. /// 这种方式是新建了一个ChatHub
  115. /// 此处留在这里做个记忆,调了半天。
  116. /// </summary>
  117. /// <param name="context"></param>
  118. public JGRManager(IHubContext<ChatHub> context,
  119. MyDbHandler dbHandler,
  120. IConfiguration configuration,
  121. ITaskExecManager taskExecManager,
  122. IRegistryService registryService)
  123. {
  124. Instance = this;
  125. hubContext = context;
  126. this.dbHandler = dbHandler;
  127. this._configuration = configuration;
  128. this._taskExecManager = taskExecManager;
  129. this._registryService = registryService;
  130. }
  131. public static JGRManager GetInstance()
  132. {
  133. //lock (balanceLock)
  134. //{
  135. // if (Instance == null)
  136. // Instance = new JGRManager();
  137. //}
  138. return Instance;
  139. }
  140. public void Dispose()
  141. {
  142. //关闭前记录最终位置信息
  143. dbHandler.saveJGRs(GetJgrs());
  144. //关闭定时器
  145. cts.Cancel();
  146. ctsTask.Cancel();
  147. started = false;
  148. _registryService.Stop();
  149. //关闭任务
  150. _taskExecManager.stop();
  151. }
  152. public bool Init(IServiceProvider services)
  153. {
  154. started = true;
  155. //从数据库加载信息做初始化动作
  156. InitDB();
  157. ////初始化车辆坐标
  158. //foreach(var car in jgrs.Values)
  159. //{
  160. // SetNewXY(car.jgrSN, car.currLocation_X, car.currLocation_Y);
  161. //}
  162. //加载地图数据
  163. LoadGridConfig();
  164. //异步,执行定期查询车辆状态的事情
  165. queryJgrSatus();
  166. //异步,执行车的调度
  167. movingJGRS();
  168. //监控工站状态
  169. watchStationState();
  170. //注册心跳服务启动,此服务包含心跳,
  171. //同步储位信息,
  172. //后期同步库存也是从该方法
  173. _registryService.Start();
  174. //启动任务
  175. _taskExecManager.start();
  176. return started;
  177. }
  178. async Task watchStationState()
  179. {
  180. while (true)
  181. {
  182. try
  183. {
  184. byte[] datas = TcClient.GetInstance().ReadBytes("GVL_STATION.station", 110);
  185. List<StationStateVO> stationList = new();
  186. int stationPos = 1;
  187. for (var i=0; i<datas.Length; i+=10)
  188. {
  189. stationList.Add(new()
  190. {
  191. stationPosNo = (stationPos++),
  192. //此处按规则新增工站编号信息(位置从仓储开始计算工位)
  193. power = Convert.ToBoolean(datas[i] | (datas[i + 1] << 8) | (datas[i + 2] << 16) | (datas[i + 3] << 32)),
  194. triColorLight = Convert.ToInt16(datas[i + 4] | (datas[i + 5] << 8) | (datas[i + 6] << 16) | (datas[i + 7] << 32)),
  195. wsristStrapMonitorCh1 = Convert.ToInt16(datas[i + 8] | (datas[i + 9] << 8) | (datas[i + 10] << 16) | (datas[i + 11] << 32)),
  196. wsristStrapMonitorCh2 = Convert.ToInt16(datas[i + 12] | (datas[i + 13] << 8) | (datas[i + 14] << 16) | (datas[i + 15] << 32)),
  197. smokePurifier = Convert.ToBoolean(datas[i + 16] | (datas[i + 17] << 8) | (datas[i + 18] << 16) | (datas[i + 19] << 32)),
  198. bigArm_encoding = Convert.ToInt16(datas[i + 20] | (datas[i + 21] << 8) | (datas[i + 22] << 16) | (datas[i + 23] << 32)),
  199. bigArm_angle = Convert.ToSingle(datas[i + 24] | (datas[i + 25] << 8) | (datas[i + 26] << 16) | (datas[i + 27] << 32)),
  200. smallArm_encoding = Convert.ToInt16(datas[i + 28] | (datas[i + 29] << 8) | (datas[i + 30] << 16) | (datas[i + 31] << 32)),
  201. smallArm_angle = Convert.ToSingle(datas[i + 32] | (datas[i + 29] << 33) | (datas[i + 34] << 16) | (datas[i + 35] << 32)),
  202. }) ;
  203. }
  204. hubContext.Clients.All.SendAsync("stationStatus", stationList);
  205. }
  206. catch (Exception ex)
  207. {
  208. Console.WriteLine(ex.ToString());
  209. }
  210. await Task.Delay(TimeSpan.FromMilliseconds(1000)); // 间隔1000毫秒
  211. }
  212. }
  213. /// <summary>
  214. /// 设置sianalr集线器
  215. /// </summary>
  216. /// <param name="hub"></param>
  217. public void SetHub(IHubContext<ChatHub> hub)
  218. {
  219. bool ok = hubContext == hub;
  220. hubContext = hub;
  221. // Console.WriteLine(ok.ToString());
  222. }
  223. public bool ResetADS()
  224. {
  225. return TcClient.GetInstance().InitAds();
  226. }
  227. /// <summary>
  228. /// 给界面上返回单元格的定义
  229. /// </summary>
  230. /// <returns></returns>
  231. public GridCellsDto getCells()
  232. {
  233. GridCellsDto dto = new GridCellsDto();
  234. dto.maxRow = maxDisplayY;
  235. dto.maxCol = maxDisplayX;
  236. dto.railCells = new List<GridCell>(this.railGridCells.Values.ToList());
  237. dto.storageCells = new List<GridCell>(this.storageGridCells.Values.ToList());
  238. return dto;
  239. }
  240. /// <summary>
  241. /// 获得车的清单,目前充电桩和车是一个结构
  242. /// </summary>
  243. /// <returns></returns>
  244. public List<JGR_Tc_Model> GetJgrs()
  245. {
  246. return jgrs.Values.ToList();
  247. }
  248. public List<StationDataModel> getStations()
  249. {
  250. return this.stations.Values.ToList();
  251. }
  252. public StationDataModel? getStation(string stanCode)
  253. {
  254. return this.stations.Values.ToList().Where(item=>item.stationID == stanCode).FirstOrDefault();
  255. }
  256. public List<ChargingStationDataModel> getCharges()
  257. {
  258. return this.chargers.Values.ToList();
  259. }
  260. /// <summary>
  261. /// 定时查询jgr的状态,并推送到前端
  262. ///
  263. /// </summary>
  264. ///
  265. CancellationTokenSource cts = new CancellationTokenSource();
  266. async Task queryJgrSatus()
  267. {
  268. //uint jgrCycleTime = 2;
  269. //uint chargerCycleTime = 3;
  270. //uint stationCycleTime = 4;
  271. //uint tick = 0;
  272. while (started)
  273. {
  274. List<JGR_Tc_Model> lsJgrs = Get_Tc_Models();
  275. string strJgr = JsonConvert.SerializeObject(lsJgrs);
  276. hubContext.Clients.All.SendAsync("JgrStatus", strJgr);
  277. await Task.Delay(TimeSpan.FromMilliseconds(500));
  278. }
  279. ////间隔时间1秒
  280. //using (var timer = new PeriodicTimer(TimeSpan.FromSeconds(1)))
  281. //{
  282. // int x = 1, y = 1;
  283. // //在到达指定周期后执行方法
  284. // while (await timer.WaitForNextTickAsync(cts.Token))
  285. // {
  286. // //遍历每辆车和充电桩,在线的就发,状态变更的也发
  287. // tick = (tick + 1) % uint.MaxValue;
  288. // if (tick % jgrCycleTime == 0)
  289. // {
  290. // List<JGR_Tc_Model> lsJgrs = Get_Tc_Models();
  291. // string strJgr = JsonConvert.SerializeObject(lsJgrs);
  292. // hubContext.Clients.All.SendAsync("JgrStatus", strJgr);
  293. // //dbHandler.saveJGRs(lsJgrs);
  294. // }
  295. ////发送工位信息
  296. //if (tick % stationCycleTime == 0)
  297. //{
  298. //}
  299. ////发送充电桩信息
  300. //if (tick % chargerCycleTime == 0)
  301. //{
  302. // List<ChargingStationDataModel> lsJgrs = getChargers();
  303. // string strCharger = JsonConvert.SerializeObject(lsJgrs);
  304. // hubContext.Clients.All.SendAsync("ChargingStatus", strCharger);
  305. //}
  306. //发送车的信息
  307. //x = (x + 1) % 6;
  308. //if(x ==0)
  309. //{
  310. // x = 1;
  311. //}
  312. //List<JGR_Tc_Model> jgrs = this.GetJgrs();
  313. //JGR_Tc_Model xx = jgrs[0];
  314. //xx.currLocation_X = (short)x;
  315. ////转成displayX
  316. //long key = 0;
  317. //key = (jgrs[0].currLocation_X & 0xffff);
  318. //key = key + ((jgrs[0].currLocation_Y & 0xffff) << 16);
  319. //if(this.storageGridCells.ContainsKey(key))
  320. //{
  321. // xx.displayX = this.storageGridCells[key].displayX;
  322. //}
  323. //xx = jgrs[1];
  324. //xx.currLocation_X = (short)x;
  325. ////转成displayX
  326. //key = 0;
  327. //key = (jgrs[1].currLocation_X & 0xffff);
  328. //key = key + ((jgrs[1].currLocation_Y & 0xffff) << 16);
  329. //if (this.railGridCells.ContainsKey(key))
  330. //{
  331. // xx.displayX = this.railGridCells[key].displayX;
  332. //}
  333. //string str = JsonConvert.SerializeObject(jgrs);
  334. //hubContext.Clients.All.SendAsync("JgrStatus", str);
  335. //List<StationDataModel> stations = this.getStations();
  336. //str = JsonConvert.SerializeObject(stations);
  337. //hubContext.Clients.All.SendAsync("StationStatus", str);
  338. //var item = this.getCharges();
  339. //str = JsonConvert.SerializeObject(item);
  340. //hubContext.Clients.All.SendAsync("ChargingStatus", str);
  341. //}
  342. //}
  343. }
  344. /// <summary>
  345. /// 初始化数据库信息
  346. /// </summary>
  347. void InitDB()
  348. {
  349. if (dbHandler == null)
  350. return;
  351. //sqlite数据库初始化
  352. dbHandler.InitSqlite();
  353. //加载车的信息
  354. var dbjgrs = dbHandler.getJGRs();
  355. this.jgrs.Clear();
  356. foreach (var item in dbjgrs)
  357. {
  358. this.jgrs[item.jgrSN] = item;
  359. }
  360. //加载充电桩的信息
  361. var charges = dbHandler.getChargers();
  362. this.chargers.Clear();
  363. foreach (var charge in charges)
  364. {
  365. this.chargers.Add(charge.csSN, charge);
  366. }
  367. //加载工位信息
  368. var station = dbHandler.getSatations();
  369. this.stations.Clear();
  370. foreach (var st in station)
  371. {
  372. this.stations.Add(st.stationID, st);
  373. }
  374. }
  375. /// <summary>
  376. /// 加载地图数据
  377. /// </summary>
  378. void LoadGridConfig()
  379. {
  380. string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "files", "grid.xlsx");
  381. if (File.Exists(filePath))
  382. {
  383. try
  384. {
  385. railGridCells.Clear();
  386. storageGridCells.Clear();
  387. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  388. IWorkbook workbook = new XSSFWorkbook(fs);
  389. ISheet sheet = workbook.GetSheet("位置定义");
  390. if (sheet != null)
  391. {
  392. //先判断行列范围,
  393. int rowLen = 0, colLen = 0;
  394. for (int i = 0; i < 100; i++)
  395. {
  396. IRow row = sheet.GetRow(i);
  397. if (row == null)
  398. break;
  399. NPOI.SS.UserModel.ICell cell = row.Cells[0];
  400. string cellValue = "";
  401. if (cell.CellType == CellType.String)
  402. {
  403. cellValue = cell.StringCellValue;
  404. }
  405. else if (cell.CellType == CellType.Numeric)
  406. {
  407. cellValue = cell.NumericCellValue.ToString();
  408. }
  409. else
  410. {
  411. cellValue = "";
  412. }
  413. if (string.IsNullOrEmpty(cellValue) == false)
  414. {
  415. rowLen = i;
  416. }
  417. }
  418. List<NPOI.SS.UserModel.ICell> cells = sheet.GetRow(0).Cells;
  419. for (int i = 1; i < cells.Count; i++)
  420. {
  421. NPOI.SS.UserModel.ICell cell = cells[i];
  422. string cellValue = "";
  423. if (cell.CellType == CellType.String)
  424. {
  425. cellValue = cell.StringCellValue;
  426. }
  427. else if (cell.CellType == CellType.Numeric)
  428. {
  429. cellValue = cell.NumericCellValue.ToString();
  430. }
  431. else
  432. {
  433. cellValue = "";
  434. }
  435. if (string.IsNullOrEmpty(cellValue) == false)
  436. {
  437. colLen = i;
  438. }
  439. }
  440. maxDisplayX = colLen + 1;
  441. maxDisplayY = rowLen + 1;
  442. //显示的X\Y坐标位置的内容
  443. int displayX = 0, displayY = 0;
  444. for (int i = 1; i <= rowLen; i++)
  445. {
  446. displayY = i;
  447. for (int j = 1; j <= colLen; j++)
  448. {
  449. displayX = j;
  450. string cellValue = "";
  451. NPOI.SS.UserModel.ICell cell = sheet.GetRow(i).GetCell(j, MissingCellPolicy.RETURN_NULL_AND_BLANK);
  452. if (cell == null)
  453. {
  454. continue;
  455. }
  456. else if (cell.CellType == CellType.String)
  457. {
  458. cellValue = cell.StringCellValue;
  459. }
  460. else if (cell.CellType == CellType.Numeric)
  461. {
  462. cellValue = cell.NumericCellValue.ToString();
  463. }
  464. else
  465. {
  466. continue;
  467. }
  468. List<string> strValues = new List<string>();
  469. //解析内容
  470. if (cellValue.Contains('#') == false)
  471. {
  472. strValues.Add(cellValue);
  473. }
  474. else
  475. {
  476. //有多个重叠定义
  477. string[] strs = cellValue.Split('#');
  478. foreach (var item in strs)
  479. {
  480. strValues.Add(item.Trim());
  481. }
  482. }
  483. foreach (string item in strValues)
  484. {
  485. //单元格只有一种定义
  486. GridCell gcell = new GridCell();
  487. gcell.displayX = displayX;
  488. gcell.displayY = displayY;
  489. int indexX = 0, indexY = 0, indexS = 0;
  490. indexX = item.IndexOf('X') + 1;
  491. indexY = item.IndexOf('Y');
  492. indexS = item.IndexOf('/');
  493. string strX = item.Substring(indexX, indexY - indexX);
  494. string strY = item.Substring(indexY + 1, indexS - indexY - 1);
  495. if (strX != null && strY != null)
  496. {
  497. gcell.positionX = Convert.ToInt32(strX);
  498. gcell.positionY = Convert.ToInt32(strY);
  499. }
  500. if (item.Contains("R-"))
  501. {
  502. if (railGridCells.Keys.Contains(gcell.GetKey()))
  503. {
  504. Console.WriteLine($"轨道数据中有重复定义的格子:x:{gcell.positionX} y:{gcell.positionY} ");
  505. continue;
  506. }
  507. railGridCells.Add(gcell.GetKey(), gcell);
  508. }
  509. else if (item.Contains("S-"))
  510. {
  511. if (storageGridCells.Keys.Contains(gcell.GetKey()))
  512. {
  513. Console.WriteLine($"仓储数据中有重复定义的格子:x:{gcell.positionX} y:{gcell.positionY} ");
  514. continue;
  515. }
  516. string pos = gcell.positionX.ToString() + "," + gcell.positionY.ToString();
  517. if(disableStorageCells.Contains(pos))
  518. {
  519. gcell.enableUse = false;
  520. } else
  521. {
  522. gcell.enableUse = true;
  523. }
  524. storageGridCells.Add(gcell.GetKey(), gcell);
  525. }
  526. if (item.Contains("/1"))
  527. {
  528. gcell.isEnable = true;
  529. }
  530. else
  531. {
  532. gcell.isEnable = false;
  533. gcell.enableUse = false;
  534. }
  535. }
  536. }
  537. }
  538. }
  539. //关闭文件
  540. fs.Close();
  541. }
  542. catch (Exception e)
  543. {
  544. Console.WriteLine("轨道位置定义文件没能正常解析:" + e.Message);
  545. }
  546. }
  547. }
  548. /// <summary>
  549. /// 从TC中读取小车的信息
  550. /// </summary>
  551. /// <returns></returns>
  552. public List<JGR_Tc_Model> Get_Tc_Models()
  553. {
  554. List<JGR_Tc_Model> list = new List<JGR_Tc_Model>();
  555. try
  556. {
  557. //List<JGR_Tc_Model> railCars = GetJgrs().Where(item=> item.jgrType == 1).ToList();
  558. //if(railCars !=null && railCars.Count > 0)
  559. //{
  560. // foreach (JGR_Tc_Model car in railCars)
  561. // {
  562. // byte[] readRFIDCmd = new byte[5];
  563. // readRFIDCmd[0] = 0x05;
  564. // readRFIDCmd[1] = 0x0F;
  565. // WriteCmd(car.jgrSN, readRFIDCmd);
  566. // Thread.Sleep(50);
  567. // }
  568. //}
  569. //先获取小车的数量
  570. //在读取信息,并分段为小车的数据结构
  571. int jgrCounts = TcClient.GetInstance().ReadValue<Byte>("GVL_EXPORT.jgrAvailableTotal");
  572. int size = Marshal.SizeOf<JGR_Ads_Struct>();
  573. byte[] datas = TcClient.GetInstance().ReadBytes("GVL_EXPORT.jgrStatusArr", jgrCounts * size);
  574. if (datas == null || datas.Length < jgrCounts * size)
  575. {
  576. return list;
  577. }
  578. byte[] buf = new byte[size];
  579. for (int i = 0; i < jgrCounts; i++)
  580. {
  581. Array.Clear(buf);
  582. Array.Copy(datas, i * size, buf, 0, size);
  583. JGR_Ads_Struct model = AppHelper.BytesToStruct<JGR_Ads_Struct>(buf);
  584. //出厂编号,30个长度带'\0',有效最多29个字节
  585. string jgrSN = getString(model.jgrSN);
  586. if (this.jgrs.ContainsKey(jgrSN) == false)
  587. {
  588. Console.WriteLine("发现的车没有在数据库中配置,车的编号:"+jgrSN);
  589. continue;
  590. }
  591. //JGR_Tc_Model jgr = new JGR_Tc_Model();
  592. //jgr.jgrSN = jgrSN;
  593. //车的数量以数据库配置为准
  594. JGR_Tc_Model jgr = this.jgrs[jgrSN];
  595. // 0:仓储车 , 1:运输车, 2:仓储位充电器,3:轨道位充电器
  596. //jgr.jgrType = model.jgrType;
  597. //车ID,取值范围0~63,不同类型的车/充电器的jgrID可以重复
  598. //jgr.jgrID = model.jgrID;
  599. //无线模块的地址,长度2字节
  600. //jgr.rcAddr = model.rcAddr;
  601. //无线模块的频率码,取值0~155,对应频率为 900+RC_FreqCode*0.2,单位MHz,默认频率码为0x32(50)
  602. //jgr.rcFreqCode = model.rcFreqCode;
  603. //在线/离线状态 是否在线(通讯是否正常)
  604. jgr.isOnline = model.isOnline;
  605. //健康状态 =0:正常; >=1:异常,异常编码看接口给
  606. jgr.isHealthy = model.isHealthy;
  607. //充电标志,1:充电中,0:未在充电
  608. jgr.isCharging = model.isCharging;
  609. //充电电压,单位:V
  610. jgr.chargeVoltage = model.chargeVoltage;
  611. //充电电流,单位:mA
  612. jgr.chargeCurrent = model.chargeCurrent;
  613. //电池剩余电量,取值 0~100 , 100表示满电量
  614. jgr.electricity = model.electricity;
  615. //驱动器通电/断电状态
  616. jgr.isDriverPowerOn = model.isDriverPowerOn;
  617. //(*工作模式
  618. //1: 正常工作模式,即自动控制模式,只需给出运动的目标坐标,动作序列小车自己控制,正常工作时使用;
  619. //2:调试模式,即手动控制模式,用于调试,每一个动作都需要发送指令*)
  620. jgr.workMode = model.workMode;
  621. //行进/停止状态
  622. //(* 车体运动状态
  623. //0:静止状态
  624. //1:X负向移动
  625. //2:X正向移动
  626. //3:Y负向移动
  627. //4:Y正向移动*)
  628. jgr.moveStatus = model.moveStatus;
  629. //移动速度,单位:m/s
  630. jgr.moveSpeed = model.moveSpeed;
  631. //当前位置X
  632. jgr.currLocation_X = model.currLocation_X;
  633. //当前位置Y
  634. jgr.currLocation_Y = model.currLocation_Y;
  635. //目标位置X
  636. jgr.destLocation_X = model.destLocation_X;
  637. //目标位置Y
  638. jgr.destLocation_Y = model.destLocation_Y;
  639. /// <summary>
  640. /// 显示位置X,Y坐标,需要根据实际物理坐标转为显示坐标
  641. /// </summary>
  642. long key = 0;
  643. key = (model.currLocation_X & 0xffff);
  644. key = key + ((model.currLocation_Y & 0xffff) << 16);
  645. if (model.jgrType == (byte)JgrType.RailCar)
  646. {
  647. if (railGridCells.ContainsKey(key))
  648. {
  649. jgr.displayX = railGridCells[key].displayX;
  650. jgr.displayY = railGridCells[key].displayY;
  651. }
  652. }
  653. else if (model.jgrType == (byte)JgrType.StorageCar)
  654. {
  655. if (storageGridCells.ContainsKey(key))
  656. {
  657. jgr.displayX = storageGridCells[key].displayX;
  658. jgr.displayY = storageGridCells[key].displayY;
  659. }
  660. }
  661. //车轮是否在位置切换中
  662. jgr.isWheelAltering = model.isWheelAltering;
  663. //车轮位置
  664. jgr.wheelPosition = model.wheelPosition;
  665. //4个碰撞传感器,true:碰撞,false:未碰撞
  666. jgr.collideSensor = new byte[4];
  667. Array.Copy(model.collideSensor, jgr.collideSensor, 4);
  668. //X加速度,单位 m/s2
  669. jgr.acceleration_X = model.acceleration_X;
  670. //Y加速度,单位 m/s2
  671. jgr.acceleration_Y = model.acceleration_Y;
  672. //Z加速度,单位 m/s2
  673. jgr.acceleration_Z = model.acceleration_Z;
  674. //XZ角度,单位:°
  675. jgr.angleXZ = model.angleXZ;
  676. //YZ角度,单位:°
  677. jgr.angleYZ = model.angleYZ;
  678. //吊篮限位标志,吊篮处于的位置 1:最高点; 2:最低点
  679. jgr.basketPosition = model.basketPosition;
  680. //吊篮抓夹状态 1:闭合状态; 2:张开状态
  681. jgr.basketGripperStatus = model.basketGripperStatus;
  682. //吊篮是否在移动,吊篮运动状态 吊篮运动状态 0:静止; 1:正在上提; 2:正在下放
  683. jgr.basketMoveStatus = model.basketMoveStatus;
  684. //RFID
  685. string rfId = getString(model.rfid);
  686. jgr.rfid = rfId.StartsWith("RFID") ? rfId : "";
  687. list.Add(jgr);
  688. }
  689. return list;
  690. }
  691. catch(Exception e)
  692. {
  693. Console.WriteLine("从TC读取小车消息异常:" + e.Message);
  694. return list;
  695. }
  696. }
  697. List<ChargingStationDataModel> getChargers()
  698. {
  699. List<ChargingStationDataModel> list = new List<ChargingStationDataModel>();
  700. //先获取小车的数量
  701. //在读取信息,并分段为小车的数据结构
  702. int counts = TcClient.GetInstance().ReadValue<Byte>("GVL_EXPORT.chargerAvailableTotal");
  703. int size = Marshal.SizeOf<Charge_Ads_Struct>();
  704. try
  705. {
  706. byte[] datas = TcClient.GetInstance().ReadBytes("GVL_EXPORT.chargerStatusArr", counts * size);
  707. if (datas == null || datas.Length < counts * size)
  708. {
  709. return list;
  710. }
  711. byte[] buf = new byte[size];
  712. for (int i = 0; i < counts; i++)
  713. {
  714. Array.Clear(buf);
  715. Array.Copy(datas, i * size, buf, 0, size);
  716. Charge_Ads_Struct model = AppHelper.BytesToStruct<Charge_Ads_Struct>(buf);
  717. ChargingStationDataModel item = new ChargingStationDataModel();
  718. // 0:仓储车 , 1:运输车, 2:仓储位充电器,3:轨道位充电器
  719. item.csType = model.chargeType;
  720. //出厂编号,30个长度带'\0',有效最多29个字节
  721. item.csSN = getString(model.chargeSN);
  722. //车ID,取值范围0~63,不同类型的车/充电器的jgrID可以重复
  723. item.csID = model.chargeID;
  724. //无线模块的地址,长度2字节
  725. item.rcAddr = model.rcAddr;
  726. //无线模块的频率码,取值0~155,对应频率为 900+RC_FreqCode*0.2,单位MHz,默认频率码为0x32(50)
  727. item.rcFreqCode = model.rcFreqCode;
  728. //在线/离线状态 是否在线(通讯是否正常)
  729. item.isOnline = model.isOnline;
  730. //健康状态 =0:正常; >=1:异常,异常编码看接口给
  731. item.isHealthy = model.isHealthy;
  732. //充电标志,1:充电中,0:未在充电
  733. item.isCharging = model.isCharging;
  734. item.chargerStatus = model.chargerStatus;
  735. //充电电压,单位:V
  736. item.chargeVoltage = model.chargeVoltage;
  737. //充电电流,单位:mA
  738. item.chargeCurrent = model.chargeCurrent;
  739. if(this.chargers.ContainsKey(item.csSN))
  740. {
  741. item.positionX = chargers[item.csSN].positionX;
  742. item.positionY = chargers[item.csSN].positionY;
  743. item.displayX = chargers[item.csSN].displayX;
  744. item.displayY = chargers[item.csSN].displayY;
  745. }
  746. list.Add(item);
  747. }
  748. return list;
  749. }
  750. catch (Exception e)
  751. {
  752. Console.WriteLine("从TC读取充电桩的消息异常:" + e.Message);
  753. return list;
  754. }
  755. }
  756. string getString(byte[] data)
  757. {
  758. //判断非0的长度,0是字符串结尾
  759. int index = 0;
  760. for (int i = 0; i < data.Length; i++)
  761. {
  762. if (data[index] == 0)
  763. {
  764. break;
  765. }
  766. index++;
  767. }
  768. return Encoding.ASCII.GetString(data, 0, index).Trim();
  769. }
  770. /// <summary>
  771. /// 设置新车或者充电桩的新位置
  772. /// </summary>
  773. /// <param name="jgrSN"></param>
  774. /// <param name="x"></param>
  775. /// <param name="y"></param>
  776. /// <returns></returns>
  777. public string SetNewXY(string jgrSN, int x , int y)
  778. {
  779. string ret = "0";
  780. if(this.jgrs.ContainsKey(jgrSN) || this.chargers.ContainsKey(jgrSN))
  781. {
  782. short sx = Convert.ToInt16(x.ToString());
  783. short sy = Convert.ToInt16(y.ToString());
  784. byte[] data = new byte[9];
  785. data[1] = 0x11;
  786. //有正负
  787. data[3] = (byte)((sx >> 8) & 0xff);
  788. data[4] = (byte)(sx & 0xff);
  789. data[5] = (byte)((sy >> 8) & 0xff);
  790. data[6] = (byte)(sy & 0xff);
  791. ret = WriteCmd(jgrSN, data);
  792. }
  793. return ret;
  794. }
  795. /// <summary>
  796. /// 执行命令
  797. /// </summary>
  798. /// <param name="debugDto"></param>
  799. /// <returns>="0",正常;="xx"异常信息</returns>
  800. public string SetCmd(JgrDebugDto debugDto)
  801. {
  802. string ret = "0";
  803. byte[] data = null;
  804. //如果没有这辆车,或者车不是正常模式,则不让发车
  805. if (this.jgrs.ContainsKey(debugDto.SN) == false)
  806. return "未找到车,车的编号:" + debugDto.SN;
  807. if (this.jgrs[debugDto.SN].isOnline == 0)
  808. return "小车没有在线";
  809. if (this.jgrs[debugDto.SN].isHealthy > 0)
  810. return "车处于异常状态,需要人工复位";
  811. var currJGR = this.jgrs[debugDto.SN];
  812. //如果车处于刹车状态,则解除刹车
  813. //处理各自动作,最理想的做法是把动作指令统一映射成ADS通信协议,写入ADS
  814. switch (debugDto.CmdCode)
  815. {
  816. /// <summary>
  817. /// 小车系统重启
  818. /// </summary>
  819. case JgrCmdCode.Restart:
  820. if(currJGR.workMode != 2 )
  821. {
  822. return "小车没有处于调试模式";
  823. }
  824. break;
  825. /// <summary>
  826. /// 设置电源
  827. /// </summary>
  828. case JgrCmdCode.SetPower:
  829. //if (debugDto.Parameters.ContainsKey("switch") == false)
  830. //{
  831. // ret = "缺少参数\"switch\"";
  832. // break;
  833. //}
  834. //else
  835. //{
  836. // data = new byte[8];
  837. // data[1] = 5;
  838. // data[3] = (byte)((debugDto.Parameters["switch"] == "on" || debugDto.Parameters["switch"] == "1") ? 1 : 2);
  839. // ret = WriteCmd(debugDto.SN, data);
  840. //}
  841. break;
  842. /// <summary>
  843. /// 设置终点
  844. /// </summary>
  845. case JgrCmdCode.SetEndPoint:
  846. if (debugDto.Parameters.ContainsKey("X") == false || debugDto.Parameters.ContainsKey("Y") == false)
  847. {
  848. ret = "缺少参数\"X、Y\"";
  849. break;
  850. }
  851. else
  852. {
  853. if (int.TryParse(debugDto.Parameters["X"], out endpointX) == false)
  854. {
  855. endpointX = 0;
  856. }
  857. if (int.TryParse(debugDto.Parameters["Y"], out endpointY) == false)
  858. {
  859. endpointY = 0;
  860. }
  861. if (endpointX == 0 || endpointY == 0)
  862. {
  863. endpointX = endpointY = 0;
  864. ret = "X-Y坐标参数格式有问题!";
  865. }
  866. else
  867. {
  868. MovingPath path = new MovingPath();
  869. path.jgrSN = debugDto.SN;
  870. path.startLocationX = this.jgrs[debugDto.SN].currLocation_X;
  871. path.startLocationY = this.jgrs[debugDto.SN].currLocation_Y;
  872. path.destLocationX = endpointX;
  873. path.destLocationY = endpointY;
  874. ret = TryAddPath(debugDto.SN, path);
  875. }
  876. }
  877. break;
  878. /// <summary>
  879. /// 移动到设置的终点
  880. /// </summary>
  881. case JgrCmdCode.StartMove:
  882. //在设置终点中就完成动作了,不需要独立的触发命令
  883. break;
  884. /// <summary>
  885. /// 正常中止,停在前进方向最近的一格上
  886. /// </summary>
  887. case JgrCmdCode.StopNormal:
  888. data = new byte[8];
  889. data[1] = 0x12;
  890. data[3] = 2;
  891. ret = WriteCmd(debugDto.SN, data);
  892. break;
  893. /// <summary>
  894. /// 急停,最短距离停下
  895. /// </summary>
  896. case JgrCmdCode.StopEmergency:
  897. data = new byte[8];
  898. data[1] = 0x12;
  899. data[3] = 1;
  900. ret = WriteCmd(debugDto.SN, data);
  901. break;
  902. /// <summary>
  903. /// 前进方向移动到下一格,X增加
  904. /// </summary>
  905. case JgrCmdCode.MoveForward:
  906. if (this.jgrs[debugDto.SN].GetPathCounts() == 0)
  907. {
  908. int newX = this.jgrs[debugDto.SN].currLocation_X + 1;
  909. int newY = this.jgrs[debugDto.SN].currLocation_Y;
  910. //检测这一个格子是否可以前进,如果可以前进,则加入到路径中
  911. MovingPath path = new MovingPath();
  912. path.jgrSN = debugDto.SN;
  913. path.startLocationX = this.jgrs[debugDto.SN].currLocation_X;
  914. path.startLocationY = this.jgrs[debugDto.SN].currLocation_Y;
  915. path.destLocationX = newX;
  916. path.destLocationY = newY;
  917. ret = TryAddPath(debugDto.SN, path);
  918. }
  919. break;
  920. /// <summary>
  921. /// 后退一格,X减少
  922. /// </summary>
  923. case JgrCmdCode.MoveBack:
  924. if (this.jgrs[debugDto.SN].GetPathCounts() == 0)
  925. {
  926. int newX = this.jgrs[debugDto.SN].currLocation_X - 1;
  927. int newY = this.jgrs[debugDto.SN].currLocation_Y;
  928. //检测这一个格子是否可以前进,如果可以前进,则加入到路径中
  929. MovingPath path = new MovingPath();
  930. path.jgrSN = debugDto.SN;
  931. path.startLocationX = this.jgrs[debugDto.SN].currLocation_X;
  932. path.startLocationY = this.jgrs[debugDto.SN].currLocation_Y;
  933. path.destLocationX = newX;
  934. path.destLocationY = newY;
  935. ret = TryAddPath(debugDto.SN, path);
  936. }
  937. break;
  938. /// <summary>
  939. /// 前进方向左侧移动一格,Y减少
  940. /// </summary>
  941. case JgrCmdCode.MoveLeft:
  942. if (this.jgrs[debugDto.SN].GetPathCounts() == 0)
  943. {
  944. int newX = this.jgrs[debugDto.SN].currLocation_X;
  945. int newY = this.jgrs[debugDto.SN].currLocation_Y - 1;
  946. //检测这一个格子是否可以前进,如果可以前进,则加入到路径中
  947. MovingPath path = new MovingPath();
  948. path.jgrSN = debugDto.SN;
  949. path.startLocationX = this.jgrs[debugDto.SN].currLocation_X;
  950. path.startLocationY = this.jgrs[debugDto.SN].currLocation_Y;
  951. path.destLocationX = newX;
  952. path.destLocationY = newY;
  953. ret = TryAddPath(debugDto.SN, path);
  954. }
  955. break;
  956. /// <summary>
  957. /// 前进方向右侧移动一格,Y增加
  958. /// </summary>
  959. case JgrCmdCode.MoveRight:
  960. if (this.jgrs[debugDto.SN].GetPathCounts() == 0)
  961. {
  962. int newX = this.jgrs[debugDto.SN].currLocation_X;
  963. int newY = this.jgrs[debugDto.SN].currLocation_Y + 1;
  964. //检测这一个格子是否可以前进,如果可以前进,则加入到路径中
  965. MovingPath path = new MovingPath();
  966. path.jgrSN = debugDto.SN;
  967. path.startLocationX = this.jgrs[debugDto.SN].currLocation_X;
  968. path.startLocationY = this.jgrs[debugDto.SN].currLocation_Y;
  969. path.destLocationX = newX;
  970. path.destLocationY = newY;
  971. ret = TryAddPath(debugDto.SN, path);
  972. }
  973. break;
  974. /// <summary>
  975. /// 车轮置顶
  976. /// </summary>
  977. case JgrCmdCode.SetWheelTop:
  978. data = new byte[8];
  979. data[1] = 6;
  980. data[3] = 1;
  981. ret = WriteCmd(debugDto.SN, data);
  982. break;
  983. /// <summary>
  984. /// 车轮置底
  985. /// </summary>
  986. case JgrCmdCode.SetWheelBottom:
  987. data = new byte[8];
  988. data[1] = 6;
  989. data[3] = 3;
  990. ret = WriteCmd(debugDto.SN, data);
  991. break;
  992. /// <summary>
  993. /// 车轮置在中间,四轮着地
  994. /// </summary>
  995. case JgrCmdCode.SetWheelMiddle:
  996. data = new byte[8];
  997. data[1] = 6;
  998. data[3] = 2;
  999. ret = WriteCmd(debugDto.SN, data);
  1000. break;
  1001. /// <summary>
  1002. /// 吊篮抓取
  1003. /// </summary>
  1004. case JgrCmdCode.BasketUp:
  1005. data = new byte[8];
  1006. data[1] = 7;
  1007. data[3] = 5;
  1008. data[4] = Convert.ToByte(debugDto.Parameters["Z"]);
  1009. ret = WriteCmd(debugDto.SN, data);
  1010. break;
  1011. /// <summary>
  1012. /// 吊篮释放
  1013. /// </summary>
  1014. case JgrCmdCode.BasketDown:
  1015. data = new byte[8];
  1016. data[1] = 7;
  1017. data[3] = 6;
  1018. data[4] = Convert.ToByte(debugDto.Parameters["Z"]);
  1019. ret = WriteCmd(debugDto.SN, data);
  1020. break;
  1021. /// <summary>
  1022. /// 吊篮停止运动
  1023. /// </summary>
  1024. case JgrCmdCode.BasketStopMoving:
  1025. data = new byte[8];
  1026. data[1] = 7;
  1027. data[3] = 0;
  1028. ret = WriteCmd(debugDto.SN, data);
  1029. break;
  1030. /// <summary>
  1031. /// 吊篮夹子张开
  1032. /// </summary>
  1033. case JgrCmdCode.GripperOpen:
  1034. data = new byte[8];
  1035. data[1] = 7;
  1036. data[3] = 3;
  1037. ret = WriteCmd(debugDto.SN, data);
  1038. break;
  1039. /// <summary>
  1040. /// 吊篮夹子闭合
  1041. /// </summary>
  1042. case JgrCmdCode.GripperClose:
  1043. data = new byte[8];
  1044. data[1] = 7;
  1045. data[3] = 4;
  1046. ret = WriteCmd(debugDto.SN, data);
  1047. break;
  1048. /// <summary>
  1049. /// 开始充电
  1050. /// </summary>
  1051. case JgrCmdCode.StartCharging:
  1052. //先检查车的位置与充电桩的位置重叠
  1053. //然后给指定充电桩发送指令
  1054. foreach (var item in this.chargers)
  1055. {
  1056. if (item.Value.positionX == this.jgrs[debugDto.SN].currLocation_X && item.Value.positionY == this.jgrs[debugDto.SN].currLocation_Y)
  1057. {
  1058. //给充电桩发送伸出指令
  1059. data = new byte[8];
  1060. data[1] = 8;
  1061. data[3] = 1;
  1062. data[4] = 1;
  1063. ret = WriteCmd(item.Value.csSN, data);
  1064. if (ret != "0")
  1065. return ret;
  1066. //给充电桩发送充电指令
  1067. data[1] = 8;
  1068. data[3] = 0;
  1069. data[4] = 1;
  1070. ret = WriteCmd(item.Value.csSN, data);
  1071. if (ret != "0")
  1072. return ret;
  1073. //给车发送充电指令
  1074. data[1] = 8;
  1075. data[3] = 0;
  1076. data[4] = 1;
  1077. ret = WriteCmd(debugDto.SN, data);
  1078. if (ret != "0")
  1079. return ret;
  1080. break;
  1081. }
  1082. }
  1083. break;
  1084. /// <summary>
  1085. /// 停止充电
  1086. /// </summary>
  1087. case JgrCmdCode.StopCharging:
  1088. //先检查车的位置与充电桩的位置重叠
  1089. //然后给指定充电桩发送指令
  1090. foreach (var item in this.chargers)
  1091. {
  1092. if (item.Value.positionX == this.jgrs[debugDto.SN].currLocation_X && item.Value.positionY == this.jgrs[debugDto.SN].currLocation_Y)
  1093. {
  1094. //给充电桩发送停止充电指令
  1095. data = new byte[8];
  1096. data[1] = 8;
  1097. data[3] = 0;
  1098. data[4] = 0;
  1099. ret = WriteCmd(item.Value.csSN, data);
  1100. if (ret != "0")
  1101. return ret;
  1102. //给车发送停止充电指令
  1103. data[1] = 8;
  1104. data[3] = 0;
  1105. data[4] = 0;
  1106. ret = WriteCmd(debugDto.SN, data);
  1107. if (ret != "0")
  1108. return ret;
  1109. //给充电桩发送缩回指令
  1110. data[1] = 8;
  1111. data[3] = 1;
  1112. data[4] = 0;
  1113. ret = WriteCmd(item.Value.csSN, data);
  1114. if (ret != "0")
  1115. return ret;
  1116. break;
  1117. }
  1118. }
  1119. break;
  1120. //调试模式
  1121. case JgrCmdCode.DebugModel:
  1122. data = new byte[8];
  1123. data[1] = 9;
  1124. data[3] = 2;
  1125. ret = WriteCmd(debugDto.SN, data);
  1126. break;
  1127. //正常模式
  1128. case JgrCmdCode.NormalModel:
  1129. data = new byte[8];
  1130. data[1] = 9;
  1131. data[3] = 1;
  1132. ret = WriteCmd(debugDto.SN, data);
  1133. break;
  1134. //车的驱动器通电
  1135. case JgrCmdCode.MonitorPowerOn:
  1136. data = new byte[8];
  1137. data[1] = 5;
  1138. data[3] = 1;
  1139. ret = WriteCmd(debugDto.SN, data);
  1140. break;
  1141. //车的驱动器断电
  1142. case JgrCmdCode.MonitorPowerOff:
  1143. data = new byte[8];
  1144. data[1] = 5;
  1145. data[3] = 2;
  1146. ret = WriteCmd(debugDto.SN, data);
  1147. break;
  1148. default:
  1149. //不带参数
  1150. break;
  1151. }
  1152. return ret;
  1153. }
  1154. /// <summary>
  1155. /// 返回"0"是正常
  1156. /// </summary>
  1157. /// <param name="sn"></param>
  1158. /// <param name="data"></param>
  1159. /// <returns></returns>
  1160. public string WriteCmd(string sn , byte[] data)
  1161. {
  1162. string? ret = null;
  1163. try
  1164. {
  1165. mutex.WaitOne();
  1166. ret = "0";
  1167. //1.先写车或充电桩的序列号
  1168. //2.再写命令字节数据
  1169. //3.再写触发标志位
  1170. //4.再回读状态位
  1171. TcClient.GetInstance().WriteValue<String>("insert_random_frame.SN", sn);
  1172. TcClient.GetInstance().WriteValue<byte[]>("insert_random_frame.FrameContentToSendVar", data);
  1173. TcClient.GetInstance().WriteValue<byte>("insert_random_frame.insert", 1);
  1174. //数据读走,状态位置为0
  1175. int timeout = 20;
  1176. while(timeout-- > 0)
  1177. {
  1178. Thread.Sleep(30);
  1179. byte val = TcClient.GetInstance().ReadValue<Byte>("insert_random_frame.insert");
  1180. ret = val.ToString();
  1181. if (val == 0)
  1182. {
  1183. break;
  1184. }
  1185. }
  1186. }
  1187. catch(Exception e)
  1188. {
  1189. ret = "发送命令失败:"+e.Message;
  1190. } finally
  1191. {
  1192. mutex.ReleaseMutex();
  1193. }
  1194. return ret;
  1195. }
  1196. /// <summary>
  1197. /// 尝试为车添加路径,路径需要拆解,并判断是否可行
  1198. /// //目前假设路径上没有禁用的格子
  1199. /// </summary>
  1200. /// <param name="jgrSN"></param>
  1201. /// <param name="path"></param>
  1202. /// <returns></returns>
  1203. string TryAddPath(string jgrSN, MovingPath path)
  1204. {
  1205. string ret = "0";
  1206. if (path.startLocationX == path.destLocationX && path.startLocationY == path.destLocationY)
  1207. {
  1208. //目标一样
  1209. return "起点与终点一致,不用移动";
  1210. }
  1211. List<MovingPath> paths = new List<MovingPath>();
  1212. //检查路径是否合理,如果不算直线,则需要拆解为多条路径
  1213. if(path.startLocationX == path.destLocationX || path.startLocationY == path.destLocationY)
  1214. {
  1215. //检查路径是否可行
  1216. if(CheckPathAvaible(jgrSN,path))
  1217. {
  1218. paths.Add(path);
  1219. this.jgrs[jgrSN].AddPath(paths);
  1220. return ret;
  1221. }
  1222. else
  1223. {
  1224. return "移动路径没有被接受";
  1225. }
  1226. }
  1227. else
  1228. {
  1229. //拆成多段路径
  1230. //如果X轴能走到位置,则走X轴
  1231. MovingPath path1 = new MovingPath();
  1232. MovingPath path2 = new MovingPath();
  1233. MovingPath path3 = new MovingPath();
  1234. if (path.startLocationY > path.destLocationY)
  1235. {
  1236. path1.startLocationX = path.startLocationX;
  1237. path1.startLocationY = path.startLocationY;
  1238. path1.destLocationX = path.startLocationX;
  1239. path1.destLocationY = path.destLocationY;
  1240. path2.startLocationX = path1.destLocationX;
  1241. path2.startLocationY = path1.destLocationY;
  1242. path2.destLocationX = path.destLocationX;
  1243. path2.destLocationY = path.destLocationY;
  1244. if(CheckPathAvaible(jgrSN,path1) && CheckPathAvaible(jgrSN, path2))
  1245. {
  1246. paths.Add(path1);
  1247. paths.Add(path2);
  1248. this.jgrs[jgrSN].AddPath(paths);
  1249. return ret;
  1250. }
  1251. }
  1252. else
  1253. {
  1254. path1.startLocationX = path.startLocationX;
  1255. path1.startLocationY = path.startLocationY;
  1256. path1.destLocationX = path.destLocationX;
  1257. path1.destLocationY = path.startLocationY;
  1258. path2.startLocationX = path1.destLocationX;
  1259. path2.startLocationY = path1.destLocationY;
  1260. path2.destLocationX = path.destLocationX;
  1261. path2.destLocationY = path.destLocationY;
  1262. if (CheckPathAvaible(jgrSN, path1) && CheckPathAvaible(jgrSN, path2))
  1263. {
  1264. paths.Add(path1);
  1265. paths.Add(path2);
  1266. this.jgrs[jgrSN].AddPath(paths);
  1267. return ret;
  1268. }
  1269. }
  1270. //从当前位置的上边,下边位置尝试移动
  1271. for (int i = path.startLocationY -1; i >= 1; i--)
  1272. {
  1273. path1 = new MovingPath();
  1274. path2 = new MovingPath();
  1275. path3 = new MovingPath();
  1276. path1.startLocationX = path.startLocationX;
  1277. path1.startLocationY = path.startLocationY;
  1278. path1.destLocationX = path.startLocationX;
  1279. path1.destLocationY = i;
  1280. path2.startLocationX = path1.destLocationX;
  1281. path2.startLocationY = path1.destLocationY;
  1282. path2.destLocationX = path.destLocationX;
  1283. path2.destLocationY = path1.destLocationY;
  1284. path3.startLocationX = path2.destLocationX;
  1285. path3.startLocationY = path2.destLocationY;
  1286. path3.destLocationX = path.destLocationX;
  1287. path3.destLocationY = path.destLocationY;
  1288. if (CheckPathAvaible(jgrSN, path1) && CheckPathAvaible(jgrSN, path2) && CheckPathAvaible(jgrSN, path3))
  1289. {
  1290. paths.Add(path1);
  1291. paths.Add(path2);
  1292. paths.Add(path3);
  1293. this.jgrs[jgrSN].AddPath(paths);
  1294. return ret;
  1295. }
  1296. }
  1297. for (int i = path.startLocationY + 1; i <= 8 ; i++)
  1298. {
  1299. path1 = new MovingPath();
  1300. path2 = new MovingPath();
  1301. path3 = new MovingPath();
  1302. path1.startLocationX = path.startLocationX;
  1303. path1.startLocationY = path.startLocationY;
  1304. path1.destLocationX = path.startLocationX;
  1305. path1.destLocationY = i;
  1306. path2.startLocationX = path1.destLocationX;
  1307. path2.startLocationY = path1.destLocationY;
  1308. path2.destLocationX = path.destLocationX;
  1309. path2.destLocationY = path1.destLocationY;
  1310. path3.startLocationX = path2.destLocationX;
  1311. path3.startLocationY = path2.destLocationY;
  1312. path3.destLocationX = path.destLocationX;
  1313. path3.destLocationY = path.destLocationY;
  1314. if (CheckPathAvaible(jgrSN, path1) && CheckPathAvaible(jgrSN, path2) && CheckPathAvaible(jgrSN, path3))
  1315. {
  1316. paths.Add(path1);
  1317. paths.Add(path2);
  1318. paths.Add(path3);
  1319. this.jgrs[jgrSN].AddPath(paths);
  1320. return ret;
  1321. }
  1322. }
  1323. }
  1324. return "移动路径没有被接受";
  1325. }
  1326. bool CheckPathAvaible(string jgrSN,MovingPath path)
  1327. {
  1328. Dictionary<long, GridCell> cells = null;
  1329. bool ok = true;
  1330. if (jgrs[jgrSN].jgrType == (byte)JgrType.StorageCar)
  1331. {
  1332. cells = storageGridCells;
  1333. }
  1334. else if (jgrs[jgrSN].jgrType == (byte)JgrType.RailCar)
  1335. {
  1336. cells = railGridCells;
  1337. }
  1338. else
  1339. {
  1340. return false;
  1341. }
  1342. if (path.startLocationX == path.destLocationX)
  1343. {
  1344. //Y轴移动
  1345. int startY = path.startLocationY < path.destLocationY ? path.startLocationY : path.destLocationY;
  1346. int stopY = path.startLocationY > path.destLocationY ? path.startLocationY : path.destLocationY;
  1347. //检查路径是否可行
  1348. for (int i = startY; i <= stopY; i++)
  1349. {
  1350. long key = 0;
  1351. key = (path.startLocationX & 0xffff);
  1352. key = key + ((i & 0xffff) << 16);
  1353. if(cells.ContainsKey(key)==false || cells[key].isEnable == false)
  1354. {
  1355. return false;
  1356. }
  1357. }
  1358. return true;
  1359. }
  1360. else if (path.startLocationY == path.destLocationY)
  1361. {
  1362. //X轴移动
  1363. int startX = path.startLocationX < path.destLocationX ? path.startLocationX : path.destLocationX;
  1364. int stopX = path.startLocationX > path.destLocationX ? path.startLocationX : path.destLocationX;
  1365. //检查路径是否可行
  1366. for (int i = startX; i <= stopX; i++)
  1367. {
  1368. long key = 0;
  1369. key = (i & 0xffff);
  1370. key = key + ((path.startLocationY & 0xffff) << 16);
  1371. if (cells.ContainsKey(key)==false || cells[key].isEnable == false)
  1372. {
  1373. return false;
  1374. }
  1375. }
  1376. return true;
  1377. }
  1378. else
  1379. {
  1380. return false;
  1381. }
  1382. }
  1383. /// <summary>
  1384. /// 定时执行车辆移动的指令
  1385. /// </summary>
  1386. CancellationTokenSource ctsTask = new CancellationTokenSource();
  1387. async Task movingJGRS()
  1388. {
  1389. ///选择没有冲突的路径,执行路径
  1390. ///锁定执行的路径和周边的单元格
  1391. ///读取车的实时位置,解锁已经经过的单元格
  1392. ///没有冲突的路径可以同时执行
  1393. //间隔时间1秒
  1394. /*************************/
  1395. //因为目前每个区域只有一辆车,所以不存在过多的调度问题,有路径可以直接运行
  1396. //以下操作只是针对区域中只有一辆车的情况
  1397. //以下操作只是针对区域中只有一辆车的情况
  1398. //以下操作只是针对区域中只有一辆车的情况
  1399. //以下操作只是针对区域中只有一辆车的情况
  1400. /*************************/
  1401. using (var timer = new PeriodicTimer(TimeSpan.FromSeconds(1)))
  1402. {
  1403. while (await timer.WaitForNextTickAsync(ctsTask.Token))
  1404. {
  1405. var lsJgrs = jgrs.Values.ToList();
  1406. for(int i = 0; i< lsJgrs.Count;i++)
  1407. {
  1408. var item = Get_Tc_Models().Where(m=>m.jgrSN == lsJgrs[i].jgrSN).First();
  1409. //如果车正在运动,则不处理
  1410. //if(item.isOnline == 0 || item.isHealthy > 0 || item.isCharging == 1 || item.isDriverPowerOn == 0 || item.moveStatus != 0 )
  1411. //{
  1412. // continue;
  1413. //}
  1414. if (item.isOnline == 0 || item.isHealthy > 0 || item.isCharging == 1 || item.moveStatus != 0)
  1415. {
  1416. continue;
  1417. }
  1418. MovingPath path = item.GetFirstPath();
  1419. if (path != null)
  1420. {
  1421. if (path.IsRuning == false)
  1422. {
  1423. //没开始则开始,如果已经到位置,则移除
  1424. if (path.startLocationX == (int)(item.currLocation_X) && path.startLocationY == (int)(item.currLocation_Y))
  1425. {
  1426. //如果车的起始位置与路径起始位置一致,则发起移动
  1427. //下指令移动
  1428. path.IsRuning = true;
  1429. path.StartTime = DateTime.Now;
  1430. byte[] data = new byte[8];
  1431. data[1] = 0x0a;
  1432. if(path.destLocationX == path.startLocationX)
  1433. {
  1434. //移动Y
  1435. short len = Convert.ToInt16((path.destLocationY - path.startLocationY).ToString());
  1436. //有正负
  1437. data[5] = (byte)((len >> 8) & 0xff);
  1438. data[6] = (byte)(len & 0xff);
  1439. WriteCmd(item.jgrSN, data);
  1440. }
  1441. else if(path.destLocationY == path.startLocationY)
  1442. {
  1443. //移动X
  1444. short len = Convert.ToInt16((path.destLocationX - path.startLocationX).ToString());
  1445. //有正负
  1446. data[3] = (byte)((len >> 8) & 0xff);
  1447. data[4] = (byte)(len & 0xff);
  1448. WriteCmd(item.jgrSN, data);
  1449. }
  1450. else
  1451. {
  1452. //异常,正常是不会出现的
  1453. item.RemoveFirstPath();
  1454. i--;
  1455. }
  1456. }
  1457. else
  1458. {
  1459. //如果车的起始位置与路径起始位置不一致,则是有异常发生,移除路径
  1460. item.RemoveFirstPath();
  1461. i--;
  1462. Console.WriteLine("规划的路径起点与当前位置不一致,规划的路径被抛弃");
  1463. }
  1464. }
  1465. else
  1466. {
  1467. //如果已经移动到位
  1468. if (path.destLocationX == (int)(item.currLocation_X) && path.destLocationY == (int)(item.currLocation_Y))
  1469. {
  1470. item.RemoveFirstPath();
  1471. //下以次还是检查这辆车,好发起新的路径移动
  1472. i--;
  1473. }
  1474. else
  1475. {
  1476. //如果移动过程中超时
  1477. if (DateTime.Now - path.StartTime > TimeSpan.FromSeconds(120))
  1478. {
  1479. Console.WriteLine("小车移动超时,小车编号:" + item.jgrSN);
  1480. //把超时的移动路径移走
  1481. item.RemoveFirstPath();
  1482. i--;
  1483. }
  1484. }
  1485. }
  1486. } //end if (path != null)
  1487. }//end for
  1488. }//end while
  1489. }
  1490. }
  1491. public string moveJGCar(string jgrSN, int startLocationX, int startLocationY, int destLocationX, int destLocationY)
  1492. {
  1493. JGR_Tc_Model curCarState = GetJgrs().Where(item => item.jgrSN == jgrSN).First();
  1494. //没开始则开始,如果已经到位置,则移除
  1495. if (startLocationX == (int)(curCarState.currLocation_X) && startLocationY == (int)(curCarState.currLocation_Y))
  1496. {
  1497. byte[] data = new byte[8];
  1498. data[1] = 0x0a;
  1499. if (destLocationX == startLocationX)
  1500. {
  1501. //移动Y
  1502. short len = Convert.ToInt16((destLocationY - startLocationY).ToString());
  1503. //有正负
  1504. data[5] = (byte)((len >> 8) & 0xff);
  1505. data[6] = (byte)(len & 0xff);
  1506. //移动仓储车到出库位
  1507. Console.WriteLine(jgrSN + "移动到位置: " + destLocationX + "," + destLocationY);
  1508. try
  1509. {
  1510. return WriteCmd(jgrSN, data);
  1511. } finally
  1512. {
  1513. Console.WriteLine(jgrSN + "移动到位置: " + destLocationX + "," + destLocationY+",指令发送完成");
  1514. }
  1515. }
  1516. else if (destLocationY == startLocationY)
  1517. {
  1518. //移动X
  1519. short len = Convert.ToInt16((destLocationX - startLocationX).ToString());
  1520. //有正负
  1521. data[3] = (byte)((len >> 8) & 0xff);
  1522. data[4] = (byte)(len & 0xff);
  1523. try
  1524. {
  1525. //移动仓储车到出库位
  1526. Console.WriteLine(jgrSN + "移动到位置: " + destLocationX + "," + destLocationY);
  1527. return WriteCmd(jgrSN, data);
  1528. } finally
  1529. {
  1530. Console.WriteLine(jgrSN + "移动到位置: " + destLocationX + "," + destLocationY + ",指令发送完成");
  1531. }
  1532. }
  1533. }
  1534. return "没有进行路径规划";
  1535. }
  1536. public StationDataModel? getStationByNo(string stanCode)
  1537. {
  1538. return dbHandler.getStationByNo(stanCode);
  1539. }
  1540. /// <summary>
  1541. /// 移动指定车辆到指定位置
  1542. /// </summary>
  1543. /// <param name="free_car"></param>
  1544. /// <param name="positionX"></param>
  1545. /// <param name="positionY"></param>
  1546. public async void moveCarToDestAsync(JGR_Tc_Model free_car, int positionX, int positionY)
  1547. {
  1548. try
  1549. {
  1550. if (ThreadLocalManager.Get() == null ||
  1551. string.IsNullOrEmpty(ThreadLocalManager.Get().taskId)
  1552. || string.IsNullOrWhiteSpace(ThreadLocalManager.Get().taskId))
  1553. {
  1554. Console.WriteLine("没有任务id,不能执行当前业务");
  1555. return;
  1556. }
  1557. await waitAndMoveCar(free_car, positionX, positionY);
  1558. //等待到达终点
  1559. await waitArrived(free_car.jgrSN, (short)positionX, (short)positionY);
  1560. //通知完成
  1561. notifyTaskCompleted(new string[] { free_car.jgrSN });
  1562. } catch (CancelTaskException ex)
  1563. {
  1564. Console.WriteLine($"异常信息:{ex.Message}");
  1565. if (free_car != null)
  1566. {
  1567. //发送取消任务成功通知
  1568. sendCancelTaskSuccess(new string[] { free_car.jgrSN });
  1569. }
  1570. }
  1571. }
  1572. /// <summary>
  1573. /// 发送任务取消成功的消息
  1574. /// </summary>
  1575. private void sendCancelTaskSuccess(string[] jgrSNs)
  1576. {
  1577. RabbitmqService.getInstance().SendMsg(new MqMessage<CancelTaskNotify>()
  1578. {
  1579. msgId = _taskExecManager.genTaskId(),
  1580. msgType = 5,
  1581. msgData = new CancelTaskNotify()
  1582. {
  1583. taskId = ThreadLocalManager.Get().taskId,
  1584. cancelTime = DateTime.Now
  1585. }
  1586. });
  1587. removeCancelTask(ThreadLocalManager.Get().taskId);
  1588. if(jgrSNs !=null && jgrSNs.Length>0)
  1589. {
  1590. //移除车辆占用
  1591. foreach (var sn in jgrSNs)
  1592. {
  1593. jgrTaskMap.Remove(sn, out _);
  1594. }
  1595. }
  1596. }
  1597. /// <summary>
  1598. /// 移动车
  1599. /// </summary>
  1600. /// <param name="free_car"></param>
  1601. /// <param name="positionX"></param>
  1602. /// <param name="positionY"></param>
  1603. /// <returns></returns>
  1604. async Task waitAndMoveCar(JGR_Tc_Model free_car, int positionX, int positionY)
  1605. {
  1606. //判断车状态是否被其他任务占用
  1607. await waitCarToFree(free_car);
  1608. //规划路径并执行
  1609. await planPathAndRun(free_car.jgrSN, positionX, positionY);
  1610. }
  1611. /// <summary>
  1612. /// 等待车辆为空闲状态
  1613. /// </summary>
  1614. /// <param name="free_car"></param>
  1615. /// <returns></returns>
  1616. async Task waitCarToFree(JGR_Tc_Model free_car)
  1617. {
  1618. int times = 0;
  1619. bool rs;
  1620. do
  1621. {
  1622. if (cancelTaskIds.Contains(ThreadLocalManager.Get().taskId))
  1623. {
  1624. throw new CancelTaskException("取消任务处理");
  1625. }
  1626. if ((++times) % 500 == 0)
  1627. {
  1628. //发送超时消息
  1629. sendExceptNotify("等待指定车辆超时");
  1630. }
  1631. await Task.Delay(TimeSpan.FromMilliseconds(200));
  1632. rs = checkIsFree(free_car, false);
  1633. } while (!rs);
  1634. //占用车辆
  1635. jgrTaskMap[free_car.jgrSN] = ThreadLocalManager.Get().taskId;
  1636. }
  1637. /// <summary>
  1638. /// 发送异常通知消息
  1639. /// </summary>
  1640. /// <param name="reason"></param>
  1641. private void sendExceptNotify(string reason)
  1642. {
  1643. RabbitmqService.getInstance().SendMsg(new MqMessage<TaskExceptNotify>() {
  1644. msgId = _taskExecManager.genTaskId(),
  1645. msgType = 4,
  1646. msgData = new TaskExceptNotify()
  1647. {
  1648. taskId = ThreadLocalManager.Get().taskId,
  1649. exceptReason = reason
  1650. }
  1651. });
  1652. }
  1653. /// <summary>
  1654. /// 移动车到目标位置
  1655. /// </summary>
  1656. /// <param name="free_car"></param>
  1657. /// <param name="positionX"></param>
  1658. /// <param name="positionY"></param>
  1659. public async void moveCarToDestAsync(JgrType jgrType, int positionX, int positionY)
  1660. {
  1661. JGR_Tc_Model? free_car = null;
  1662. try
  1663. {
  1664. if (ThreadLocalManager.Get() == null ||
  1665. string.IsNullOrEmpty(ThreadLocalManager.Get().taskId)
  1666. || string.IsNullOrWhiteSpace(ThreadLocalManager.Get().taskId))
  1667. {
  1668. Console.WriteLine("没有任务id,不能执行当前业务");
  1669. return;
  1670. }
  1671. free_car = await waitFreeCar(jgrType);
  1672. notifyCarInfo(free_car);
  1673. //规划路径并执行
  1674. await planPathAndRun(free_car.jgrSN, positionX, positionY);
  1675. await waitArrived(free_car.jgrSN, (short)positionX, (short)positionY);
  1676. //int current_x = free_car.currLocation_X;
  1677. //int current_y = free_car.currLocation_Y;
  1678. //if (free_car.currLocation_Y > 3)
  1679. //{
  1680. // if (positionY > 3)
  1681. // {
  1682. // current_y -= 1;
  1683. // }
  1684. // else
  1685. // {
  1686. // current_y = (short)positionY;
  1687. // }
  1688. //}
  1689. //else
  1690. //{
  1691. // current_x = (short)positionX;
  1692. //}
  1693. ////首次运动
  1694. //JGR_Tc_Model curCarState = Get_Tc_Models().Where(item => item.jgrSN == free_car.jgrSN).First();
  1695. //if (curCarState.currLocation_X != (short)current_x || curCarState.currLocation_Y != (short)current_y)
  1696. //{
  1697. // await retryMoveCar(free_car.jgrSN, current_x, current_y);
  1698. // await waitArrived(free_car.jgrSN, (short)current_x, (short)current_y);
  1699. //}
  1700. //if (free_car.currLocation_X != (short)positionX)
  1701. //{
  1702. // current_x = (short)positionX;
  1703. // curCarState = Get_Tc_Models().Where(item => item.jgrSN == free_car.jgrSN).First();
  1704. // await retryMoveCar(free_car.jgrSN, current_x, current_y);
  1705. // await waitArrived(free_car.jgrSN, (short)current_x, (short)current_y);
  1706. //}
  1707. ////再次运动到达目的地
  1708. //curCarState = Get_Tc_Models().Where(item => item.jgrSN == free_car.jgrSN).First();
  1709. //await retryMoveCar(free_car.jgrSN, positionX, positionY);
  1710. notifyTaskCompleted(new string[] { free_car.jgrSN });
  1711. }
  1712. catch (CancelTaskException ex)
  1713. {
  1714. Console.WriteLine($"异常信息:{ex.Message}");
  1715. if(free_car != null)
  1716. {
  1717. //发送取消任务成功通知
  1718. sendCancelTaskSuccess(new string[] { free_car.jgrSN });
  1719. }
  1720. }
  1721. }
  1722. /// <summary>
  1723. /// 通知获取车辆信息给业务端
  1724. /// </summary>
  1725. private void notifyCarInfo(JGR_Tc_Model carInfo, string rfId="")
  1726. {
  1727. //发送消息给业务端
  1728. RabbitmqService.getInstance().SendMsg(new MqMessage<GetCarNotify>()
  1729. {
  1730. msgId = _taskExecManager.genTaskId(),
  1731. msgType = 1,
  1732. msgData = new GetCarNotify()
  1733. {
  1734. taskId = ThreadLocalManager.Get().taskId,
  1735. carId = carInfo.jgrSN,
  1736. carType = carInfo.jgrType,
  1737. rfId = rfId
  1738. }
  1739. }) ;
  1740. }
  1741. /// <summary>
  1742. /// 通知任务完成处理
  1743. /// </summary>
  1744. /// <param name="jgrSNs"></param>
  1745. private void notifyTaskCompleted(string[] jgrSNs)
  1746. {
  1747. //移除车辆占用
  1748. foreach(var sn in jgrSNs)
  1749. {
  1750. jgrTaskMap.Remove(sn, out _);
  1751. }
  1752. //通知任务完成
  1753. RabbitmqService.getInstance().SendMsg(new MqMessage<TaskCompletedNotify>() {
  1754. msgId = _taskExecManager.genTaskId(),
  1755. msgType = 2,
  1756. msgData = new TaskCompletedNotify()
  1757. {
  1758. taskId = ThreadLocalManager.Get().taskId
  1759. }
  1760. });
  1761. _taskExecManager.notifyTaskCompleted(ThreadLocalManager.Get().taskId);
  1762. }
  1763. /// <summary>
  1764. /// 等待空闲车辆
  1765. /// </summary>
  1766. /// <param name="jgrType"></param>
  1767. /// <returns></returns>
  1768. async Task<JGR_Tc_Model> waitFreeCar(JgrType jgrType)
  1769. {
  1770. int times = 0;
  1771. JGR_Tc_Model? curCarState = null;
  1772. do {
  1773. if (cancelTaskIds.Contains(ThreadLocalManager.Get().taskId))
  1774. {
  1775. throw new CancelTaskException("取消任务处理");
  1776. }
  1777. if ((++times)%500 == 0)
  1778. {
  1779. sendExceptNotify("等待空闲车超时");
  1780. }
  1781. await Task.Delay(TimeSpan.FromMilliseconds(200));
  1782. curCarState = findFreeCar(jgrType);
  1783. } while (curCarState == null);
  1784. if (cancelTaskIds.Contains(ThreadLocalManager.Get().taskId))
  1785. {
  1786. throw new CancelTaskException("取消任务处理");
  1787. }
  1788. return curCarState;
  1789. }
  1790. /// <summary>
  1791. /// 仓储车入库操作
  1792. /// </summary>
  1793. /// <param name="dto">入库参数</param>
  1794. public async void storageCarToInAsync(JGR_Tc_Model railCar, InStorageDTO dto)
  1795. {
  1796. JGR_Tc_Model? storageCarInfo = null;
  1797. try
  1798. {
  1799. if (ThreadLocalManager.Get() == null ||
  1800. string.IsNullOrEmpty(ThreadLocalManager.Get().taskId)
  1801. || string.IsNullOrWhiteSpace(ThreadLocalManager.Get().taskId))
  1802. {
  1803. Console.WriteLine("没有任务id,不能执行当前业务");
  1804. return;
  1805. }
  1806. //等待仓盒信息
  1807. string rfId = await awaitStorage(railCar);
  1808. //移动车辆
  1809. waitAndMoveCar(railCar, inAmrPos[0], inAmrPos[1]);
  1810. //等待直到获取仓储车
  1811. storageCarInfo = await waitFreeCar(JgrType.StorageCar);
  1812. notifyCarInfo(storageCarInfo, rfId);
  1813. //int current_x = storageCarInfo.currLocation_X;
  1814. //int current_y = storageCarInfo.currLocation_Y;
  1815. //规划路径并执行
  1816. await planPathAndRun(storageCarInfo.jgrSN, inPos[0], inPos[1] - 1);
  1817. //到位判断等待
  1818. await waitArrived(storageCarInfo.jgrSN, (short)inPos[0], (short)(inPos[1] - 1));
  1819. ////根据仓储车朝向原则上y轴减去1为车的位置
  1820. //if (current_x != inPos[0] || current_y != inPos[1] - 1)
  1821. //{
  1822. // //移动车到入库位置
  1823. // await retryMoveCar(storageCarInfo.jgrSN, inPos[0], inPos[1] - 1);
  1824. // //到位判断等待
  1825. // await waitArrived(storageCarInfo.jgrSN, (short)inPos[0], (short)(inPos[1] - 1));
  1826. //}
  1827. //读取轨道车是否到达入库位置
  1828. await waitArrived(railCar.jgrSN, (short)inAmrPos[0], (short)inAmrPos[1]);
  1829. //发送抓取指令
  1830. byte[] data = new byte[8];
  1831. data[1] = 7;
  1832. data[3] = 5;
  1833. data[4] = 0x80;
  1834. await retrySendCmd(storageCarInfo.jgrSN, data);
  1835. //读取吊篮状态是否已恢复到0的位置
  1836. await waitBasketPositionReset(storageCarInfo.jgrSN, 1);
  1837. //移动仓储车到入料位
  1838. int dest_x = int.Parse(dto.storagePos.Split(",")[0]);
  1839. //仓储车相对位置减1
  1840. int dest_y = int.Parse(dto.storagePos.Split(",")[1]) - 1;
  1841. //目标层数
  1842. int dest_z = int.Parse(dto.storagePos.Split(",")[2]);
  1843. //移动车到入库位置
  1844. await planPathAndRun(storageCarInfo.jgrSN, dest_x, dest_y);
  1845. // await retryMoveCar(storageCarInfo.jgrSN, dest_x, dest_y);
  1846. await waitArrived(storageCarInfo.jgrSN, (short)dest_x, (short)dest_y);
  1847. //执行下放抓斗命令
  1848. data = new byte[8];
  1849. data[1] = 7;
  1850. data[3] = 6;
  1851. data[4] = Convert.ToByte(dest_z);
  1852. await retrySendCmd(storageCarInfo.jgrSN, data);
  1853. //读取吊篮状态
  1854. await waitBasketPositionReset(storageCarInfo.jgrSN, 2);
  1855. //将任务完成状态放到集合中等待查询读取
  1856. notifyTaskCompleted(new string[] { dto.carId, storageCarInfo.jgrSN });
  1857. } catch (CancelTaskException ex)
  1858. {
  1859. Console.WriteLine($"异常信息:{ex.Message}");
  1860. string[] cars = new string[1];
  1861. cars[0] = dto.carId;
  1862. if (storageCarInfo != null)
  1863. {
  1864. cars = new string[2];
  1865. cars[0] = dto.carId;
  1866. cars[1] = storageCarInfo.jgrSN;
  1867. }
  1868. //发送取消任务成功通知
  1869. sendCancelTaskSuccess(cars);
  1870. }
  1871. }
  1872. async Task<string> awaitStorage(JGR_Tc_Model railCar)
  1873. {
  1874. int times = 0;
  1875. string rfId = "";
  1876. do
  1877. {
  1878. if (cancelTaskIds.Contains(ThreadLocalManager.Get().taskId))
  1879. {
  1880. throw new CancelTaskException("取消任务处理");
  1881. }
  1882. if ((++times) % 1000 == 0)
  1883. {
  1884. //发送超时消息
  1885. sendExceptNotify("等待放置仓盒超时");
  1886. }
  1887. await Task.Delay(TimeSpan.FromSeconds(1));
  1888. rfId = GetJgrs().Where(car => railCar.jgrSN.Equals(car.jgrSN)).First().rfid;
  1889. } while(string.IsNullOrEmpty(rfId) || string.IsNullOrWhiteSpace(rfId));
  1890. return rfId;
  1891. }
  1892. /// <summary>
  1893. /// 等待仓储车吊篮状态复位到0的位置
  1894. /// </summary>
  1895. /// <param name="jgrSN">仓储车id</param>
  1896. /// <param name="checkGripperState">验证gripper状态</param>
  1897. /// <returns></returns>
  1898. async Task waitBasketPositionReset(string jgrSN, int checkGripperState)
  1899. {
  1900. int times = 0;
  1901. JGR_Tc_Model? carState = null;
  1902. bool isReady = false;
  1903. do
  1904. {
  1905. if (cancelTaskIds.Contains(ThreadLocalManager.Get().taskId))
  1906. {
  1907. throw new CancelTaskException("取消任务处理");
  1908. }
  1909. if ((++times) % 1000 == 0)
  1910. {
  1911. //发送超时消息
  1912. sendExceptNotify("等待仓储车吊篮状态复位超时");
  1913. }
  1914. await Task.Delay(TimeSpan.FromMilliseconds(100));
  1915. carState = Get_Tc_Models().Where(item => item.jgrSN == jgrSN).First();
  1916. isReady = carState.basketPosition == 0 && carState.basketGripperStatus == checkGripperState;
  1917. } while (!isReady);
  1918. }
  1919. /// <summary>
  1920. /// 重试指令
  1921. /// </summary>
  1922. /// <param name="jgrSN"></param>
  1923. /// <param name="data"></param>
  1924. /// <returns></returns>
  1925. async Task retrySendCmd(string jgrSN, byte[] data)
  1926. {
  1927. int times = 0;
  1928. string ret;
  1929. do
  1930. {
  1931. if (cancelTaskIds.Contains(ThreadLocalManager.Get().taskId))
  1932. {
  1933. throw new CancelTaskException("取消任务处理");
  1934. }
  1935. if ((++times) % 1000 == 0)
  1936. {
  1937. //发送超时消息
  1938. sendExceptNotify("发送车辆操作指令超时");
  1939. }
  1940. await Task.Delay(TimeSpan.FromMilliseconds(100));
  1941. //车辆到达入料位置,发起下放抓取指令
  1942. ret = WriteCmd(jgrSN, data);
  1943. } while (ret != "0");
  1944. }
  1945. /// <summary>
  1946. /// 可重试移动车位置,暂不考虑退出
  1947. /// </summary>
  1948. /// <param name="jgrSN"></param>
  1949. /// <param name="dx"></param>
  1950. /// <param name="dy"></param>
  1951. /// <returns></returns>
  1952. async Task retryMoveCar(string jgrSN, int dx, int dy)
  1953. {
  1954. int times = 0;
  1955. string str;
  1956. JGR_Tc_Model carState = Get_Tc_Models().Where(item => item.jgrSN == jgrSN).First();
  1957. int current_x = carState.currLocation_X;
  1958. int current_y = carState.currLocation_Y;
  1959. do
  1960. {
  1961. if (cancelTaskIds.Contains(ThreadLocalManager.Get().taskId))
  1962. {
  1963. throw new CancelTaskException("取消任务处理");
  1964. }
  1965. if ((++times) % 1000 == 0)
  1966. {
  1967. //发送超时消息
  1968. sendExceptNotify("移动车辆指令重试超时");
  1969. }
  1970. await Task.Delay(TimeSpan.FromMilliseconds(100));
  1971. str = moveJGCar(carState.jgrSN, current_x, current_y, dx, dy);
  1972. } while (!"0".Equals(str));
  1973. }
  1974. /// <summary>
  1975. /// 判断是否达到指定坐标位置,此处暂不考虑长时间未到达的情况,后期可于此做退出机制
  1976. /// </summary>
  1977. /// <param name="jgrSN"></param>
  1978. /// <param name="dx"></param>
  1979. /// <param name="dy"></param>
  1980. /// <returns></returns>
  1981. public async Task waitArrived(string jgrSN, short dx, short dy)
  1982. {
  1983. int times = 0;
  1984. JGR_Tc_Model curCarState = Get_Tc_Models().Where(item => item.jgrSN == jgrSN).First();
  1985. while (curCarState.currLocation_X != dx || curCarState.currLocation_Y != dy)
  1986. {
  1987. if (cancelTaskIds.Contains(ThreadLocalManager.Get().taskId))
  1988. {
  1989. throw new CancelTaskException("取消指令操作");
  1990. }
  1991. if ((++times) % 500 == 0)
  1992. {
  1993. //发送超时消息
  1994. sendExceptNotify("等待车辆到达超时");
  1995. }
  1996. await Task.Delay(TimeSpan.FromMilliseconds(200));
  1997. curCarState = Get_Tc_Models().Where(item => item.jgrSN == jgrSN).First();
  1998. }
  1999. }
  2000. /// <summary>
  2001. /// 出库操作逻辑
  2002. /// </summary>
  2003. /// <param name="storagePos">存储位置</param>
  2004. /// <param name="amrDx">amr运动目标坐标位置x</param>
  2005. /// <param name="amrDy">amr运动目标坐标位置y</param>
  2006. /// <exception cref="NotImplementedException"></exception>
  2007. public async void storageCarToOutAsync(string storagePos, int amrDx, int amrDy)
  2008. {
  2009. JGR_Tc_Model? railCar = null;
  2010. JGR_Tc_Model? storageCarInfo = null;
  2011. try
  2012. {
  2013. if (ThreadLocalManager.Get() == null ||
  2014. string.IsNullOrEmpty(ThreadLocalManager.Get().taskId)
  2015. || string.IsNullOrWhiteSpace(ThreadLocalManager.Get().taskId))
  2016. {
  2017. Console.WriteLine("没有任务id,不能执行当前业务");
  2018. return;
  2019. }
  2020. //呼叫轨道车到出库位
  2021. railCar = await waitFreeCar(JgrType.RailCar);
  2022. notifyCarInfo(railCar);
  2023. //移动车辆到出库位
  2024. planPathAndRun(railCar.jgrSN, outAmrPos[0], outAmrPos[1]);
  2025. //获取仓储车
  2026. storageCarInfo = await waitFreeCar(JgrType.StorageCar);
  2027. //移动仓储车到储位拿取
  2028. //int current_x = storageCarInfo.currLocation_X;
  2029. //int current_y = storageCarInfo.currLocation_Y;
  2030. int dx = int.Parse(storagePos.Split(',')[0]);
  2031. int dy = int.Parse(storagePos.Split(',')[1]) - 1;
  2032. int dz = int.Parse(storagePos.Split(',')[2]);
  2033. await planPathAndRun(storageCarInfo.jgrSN, dx, dy);
  2034. //到位判断等待
  2035. await waitArrived(storageCarInfo.jgrSN, (short)dx, (short)dy);
  2036. Console.WriteLine(storageCarInfo.jgrSN + "已经到达位置: " + dx + "," + dy);
  2037. ////根据仓储车朝向原则上y轴减去1为车的位置
  2038. //if (current_x != dx || current_y != dy)
  2039. //{
  2040. // //移动车到抓取位置
  2041. // await retryMoveCar(storageCarInfo.jgrSN, dx, dy);
  2042. // //到位判断等待
  2043. // await waitArrived(storageCarInfo.jgrSN, (short)dx, (short)dy);
  2044. //}
  2045. //移动到位发送抓取指令
  2046. byte[] data = new byte[8];
  2047. data[1] = 7;
  2048. data[3] = 5;
  2049. data[4] = Convert.ToByte(dz);
  2050. await retrySendCmd(storageCarInfo.jgrSN, data);
  2051. Console.WriteLine(storageCarInfo.jgrSN + "发送抓取指令,指令内容:", string.Join(',', data));
  2052. //读取吊篮状态
  2053. await waitBasketPositionReset(storageCarInfo.jgrSN, 1);
  2054. Console.WriteLine(storageCarInfo.jgrSN + "等待吊篮上升到最高层,状态为抓取状态:");
  2055. await planPathAndRun(storageCarInfo.jgrSN, outPos[0], outPos[1] - 1);
  2056. ////移动仓储车到出库位
  2057. //await retryMoveCar(storageCarInfo.jgrSN, outPos[0], outPos[1] - 1);
  2058. //到位判断等待
  2059. await waitArrived(storageCarInfo.jgrSN, (short)outPos[0], (short)(outPos[1] - 1));
  2060. Console.WriteLine(storageCarInfo.jgrSN + "已经到达位置: " + outPos[0].ToString() + "," + (outPos[1] - 1).ToString());
  2061. //等待轨道车是否到达出库位
  2062. await waitArrived(railCar.jgrSN, (short)outAmrPos[0], (short)outAmrPos[1]);
  2063. Console.WriteLine(railCar.jgrSN + "已经到达位置: " + outAmrPos[0].ToString() + "," + outAmrPos[1].ToString());
  2064. //发送下放指令
  2065. data = new byte[8];
  2066. data[1] = 7;
  2067. data[3] = 6;
  2068. data[4] = 0x80;
  2069. await retrySendCmd(storageCarInfo.jgrSN, data);
  2070. Console.WriteLine(storageCarInfo.jgrSN + "发送下放指令,指令内容:", string.Join(",", data));
  2071. //读取吊篮状态
  2072. await waitBasketPositionReset(storageCarInfo.jgrSN, 2);
  2073. Console.WriteLine(storageCarInfo.jgrSN + "吊篮复位,状态为闭合状态。");
  2074. //先移动一格等待
  2075. //await planPathAndRun(jgrSN, outAmrPos[0]-1, outAmrPos[1]);
  2076. //await waitArrived(jgrSN, (short)(outAmrPos[0] - 1), (short)outAmrPos[1]);
  2077. //移动到指定位置
  2078. await planPathAndRun(railCar.jgrSN, amrDx, amrDy);
  2079. //发送指令让车移动到拣料工位
  2080. //发送指令让车移动到拣料工位
  2081. //await retryMoveCar(jgrSN, selectStationPos[0], selectStationPos[1]);
  2082. await waitArrived(railCar.jgrSN, (short)amrDx, (short)amrDy);
  2083. Console.WriteLine(railCar.jgrSN + "移动车辆到指定工位,工位坐标:" + amrDx.ToString() + "," + amrDy.ToString());
  2084. //将任务完成状态放到集合中等待查询读取
  2085. notifyTaskCompleted(new string[] { storageCarInfo.jgrSN, railCar.jgrSN });
  2086. Console.WriteLine("完成出库任务");
  2087. }
  2088. catch (CancelTaskException ex)
  2089. {
  2090. Console.WriteLine($"异常信息:{ex.Message}");
  2091. string[] cars;
  2092. if (railCar == null && storageCarInfo == null)
  2093. {
  2094. cars = Array.Empty<string>();
  2095. }
  2096. else if (railCar == null && storageCarInfo != null)
  2097. {
  2098. cars = new string[1]
  2099. {
  2100. storageCarInfo.jgrSN
  2101. };
  2102. }
  2103. else if (railCar != null && storageCarInfo == null)
  2104. {
  2105. cars = new string[1]
  2106. {
  2107. railCar.jgrSN
  2108. };
  2109. }
  2110. else
  2111. {
  2112. cars = new string[2]
  2113. {
  2114. railCar.jgrSN,
  2115. storageCarInfo.jgrSN
  2116. };
  2117. }
  2118. //发送取消任务成功通知
  2119. sendCancelTaskSuccess(cars);
  2120. }
  2121. }
  2122. /// <summary>
  2123. /// 移库操作
  2124. /// </summary>
  2125. /// <param name="storageCarInfo"></param>
  2126. /// <param name="dto"></param>
  2127. public async void moveStorageAsync(MoveStorageDTO dto)
  2128. {
  2129. JGR_Tc_Model? storageCarInfo = null;
  2130. try
  2131. {
  2132. if (ThreadLocalManager.Get() == null ||
  2133. string.IsNullOrEmpty(ThreadLocalManager.Get().taskId)
  2134. || string.IsNullOrWhiteSpace(ThreadLocalManager.Get().taskId))
  2135. {
  2136. Console.WriteLine("没有任务id,不能执行当前业务");
  2137. return;
  2138. }
  2139. storageCarInfo = await waitFreeCar(JgrType.StorageCar);
  2140. notifyCarInfo(storageCarInfo);
  2141. int dx = int.Parse(dto.sourcePos.Split(',')[0]);
  2142. int dy = int.Parse(dto.sourcePos.Split(',')[1]) - 1;
  2143. int dz = int.Parse(dto.sourcePos.Split(',')[2]);
  2144. await planPathAndRun(storageCarInfo.jgrSN, dx, dy);
  2145. //到位判断等待
  2146. await waitArrived(storageCarInfo.jgrSN, (short)dx, (short)dy);
  2147. ////获取仓储车当前位置
  2148. //int current_x = storageCarInfo.currLocation_X;
  2149. //int current_y = storageCarInfo.currLocation_Y;
  2150. ////移动仓储车到源仓位位置
  2151. //int dx = int.Parse(dto.sourcePos.Split(',')[0]);
  2152. //int dy = int.Parse(dto.sourcePos.Split(',')[1]) - 1;
  2153. //int dz = int.Parse(dto.sourcePos.Split(',')[2]);
  2154. ////根据仓储车朝向原则上y轴减去1为车的位置
  2155. //if (current_x != dx || current_y != dy)
  2156. //{
  2157. // //移动车到抓取位置
  2158. // await retryMoveCar(storageCarInfo.jgrSN, dx, dy);
  2159. // //到位判断等待
  2160. // await waitArrived(storageCarInfo.jgrSN, (short)dx, (short)dy);
  2161. //}
  2162. //移动到位发送抓取指令
  2163. byte[] data = new byte[8];
  2164. data[1] = 7;
  2165. data[3] = 5;
  2166. data[4] = Convert.ToByte(dz);
  2167. await retrySendCmd(storageCarInfo.jgrSN, data);
  2168. //读取吊篮状态
  2169. await waitBasketPositionReset(storageCarInfo.jgrSN, 1);
  2170. //更新目标位置
  2171. dx = int.Parse(dto.destPos.Split(',')[0]);
  2172. dy = int.Parse(dto.destPos.Split(',')[1]) - 1;
  2173. dz = int.Parse(dto.destPos.Split(',')[2]);
  2174. await planPathAndRun(storageCarInfo.jgrSN, dx, dy);
  2175. //移动车到抓取位置
  2176. //await retryMoveCar(storageCarInfo.jgrSN, dx, dy);
  2177. //到位判断等待
  2178. await waitArrived(storageCarInfo.jgrSN, (short)dx, (short)dy);
  2179. //移动到位发送抓取指令
  2180. data = new byte[8];
  2181. data[1] = 7;
  2182. data[3] = 6;
  2183. data[4] = Convert.ToByte(dz);
  2184. await retrySendCmd(storageCarInfo.jgrSN, data);
  2185. //读取吊篮状态
  2186. await waitBasketPositionReset(storageCarInfo.jgrSN, 2);
  2187. //将任务完成状态放到集合中等待查询读取
  2188. notifyTaskCompleted(new string[] { storageCarInfo.jgrSN });
  2189. } catch(CancelTaskException ex)
  2190. {
  2191. Console.WriteLine($"异常信息:{ex.Message}");
  2192. string[] cars = Array.Empty<string>();
  2193. if(storageCarInfo != null)
  2194. {
  2195. cars = new string[1] { storageCarInfo.jgrSN };
  2196. }
  2197. //发送取消任务成功通知
  2198. sendCancelTaskSuccess(cars);
  2199. }
  2200. }
  2201. /// <summary>
  2202. /// 规划路线并下发路线
  2203. /// </summary>
  2204. /// <param name="jgrSN"></param>
  2205. /// <param name="destX"></param>
  2206. /// <param name="destY"></param>
  2207. /// <returns></returns>
  2208. public async Task planPathAndRun(string jgrSN, int destX, int destY)
  2209. {
  2210. if (cancelTaskIds.Contains(ThreadLocalManager.Get().taskId))
  2211. {
  2212. throw new CancelTaskException("取消任务处理");
  2213. }
  2214. List<MovingPath> paths = tryPlanPath(jgrSN, new()
  2215. {
  2216. jgrSN = jgrSN,
  2217. startLocationX = this.jgrs[jgrSN].currLocation_X,
  2218. startLocationY = this.jgrs[jgrSN].currLocation_Y,
  2219. destLocationX = destX,
  2220. destLocationY = destY
  2221. });
  2222. if (paths != null && paths.Count > 0)
  2223. {
  2224. for(int i=0; i<paths.Count; i++)
  2225. {
  2226. if (cancelTaskIds.Contains(ThreadLocalManager.Get().taskId))
  2227. {
  2228. throw new CancelTaskException("取消任务处理");
  2229. }
  2230. var path = paths[i];
  2231. await retryMoveCar(jgrSN, path.destLocationX, path.destLocationY);
  2232. if(i < paths.Count - 1)
  2233. {
  2234. //到位判断等待
  2235. await waitArrived(jgrSN, (short)path.destLocationX, (short)path.destLocationY);
  2236. Console.WriteLine(jgrSN + "已经到达位置: " + path.destLocationX + "," + path.destLocationY);
  2237. }
  2238. }
  2239. //jgrs[jgrSN].AddPath(paths);
  2240. }
  2241. }
  2242. /// <summary>
  2243. /// 规划路线
  2244. /// </summary>
  2245. /// <param name="jgrSN"></param>
  2246. /// <param name="path"></param>
  2247. /// <returns></returns>
  2248. public List<MovingPath> tryPlanPath(string jgrSN, MovingPath path)
  2249. {
  2250. try
  2251. {
  2252. if (cancelTaskIds.Contains(ThreadLocalManager.Get().taskId))
  2253. {
  2254. throw new CancelTaskException("取消任务处理");
  2255. }
  2256. return planPath(jgrSN, path);
  2257. }
  2258. catch
  2259. {
  2260. Task.Delay(TimeSpan.FromSeconds(2)).Wait();
  2261. return tryPlanPath(jgrSN, path);
  2262. }
  2263. }
  2264. List<MovingPath> planPath(string jgrSN, MovingPath path)
  2265. {
  2266. if (path.startLocationX == path.destLocationX && path.startLocationY == path.destLocationY)
  2267. {
  2268. //目标一样
  2269. return new();
  2270. }
  2271. List<MovingPath> paths = new List<MovingPath>();
  2272. //检查路径是否合理,如果不算直线,则需要拆解为多条路径
  2273. if (path.startLocationX == path.destLocationX || (path.startLocationY == path.destLocationY && path.startLocationY<4))
  2274. {
  2275. //检查路径是否可行
  2276. if (CheckPathAvaible(jgrSN, path))
  2277. {
  2278. paths.Add(path);
  2279. return paths;
  2280. }
  2281. }
  2282. //拆成多段路径
  2283. //如果X轴能走到位置,则走X轴
  2284. MovingPath path1 = new MovingPath();
  2285. MovingPath path2 = new MovingPath();
  2286. if (path.startLocationY > path.destLocationY)
  2287. {
  2288. path1.startLocationX = path.startLocationX;
  2289. path1.startLocationY = path.startLocationY;
  2290. path1.destLocationX = path.startLocationX;
  2291. path1.destLocationY = path.destLocationY;
  2292. path2.startLocationX = path1.destLocationX;
  2293. path2.startLocationY = path1.destLocationY;
  2294. path2.destLocationX = path.destLocationX;
  2295. path2.destLocationY = path.destLocationY;
  2296. if (CheckPathAvaible(jgrSN, path1) && CheckPathAvaible(jgrSN, path2))
  2297. {
  2298. paths.Add(path1);
  2299. paths.Add(path2);
  2300. return paths;
  2301. }
  2302. }
  2303. else
  2304. {
  2305. path1.startLocationX = path.startLocationX;
  2306. path1.startLocationY = path.startLocationY;
  2307. path1.destLocationX = path.destLocationX;
  2308. path1.destLocationY = path.startLocationY;
  2309. path2.startLocationX = path1.destLocationX;
  2310. path2.startLocationY = path1.destLocationY;
  2311. path2.destLocationX = path.destLocationX;
  2312. path2.destLocationY = path.destLocationY;
  2313. if (CheckPathAvaible(jgrSN, path1) && CheckPathAvaible(jgrSN, path2))
  2314. {
  2315. paths.Add(path1);
  2316. paths.Add(path2);
  2317. return paths;
  2318. }
  2319. }
  2320. //从当前位置的上边,下边位置尝试移动
  2321. for (int i = path.startLocationY - 1; i >= 1; i--)
  2322. {
  2323. path1 = new MovingPath();
  2324. path2 = new MovingPath();
  2325. MovingPath path3 = new MovingPath();
  2326. path1.startLocationX = path.startLocationX;
  2327. path1.startLocationY = path.startLocationY;
  2328. path1.destLocationX = path.startLocationX;
  2329. path1.destLocationY = i;
  2330. path2.startLocationX = path1.destLocationX;
  2331. path2.startLocationY = path1.destLocationY;
  2332. path2.destLocationX = path.destLocationX;
  2333. path2.destLocationY = path1.destLocationY;
  2334. path3.startLocationX = path2.destLocationX;
  2335. path3.startLocationY = path2.destLocationY;
  2336. path3.destLocationX = path.destLocationX;
  2337. path3.destLocationY = path.destLocationY;
  2338. if (CheckPathAvaible(jgrSN, path1) && CheckPathAvaible(jgrSN, path2) && CheckPathAvaible(jgrSN, path3))
  2339. {
  2340. paths.Add(path1);
  2341. paths.Add(path2);
  2342. paths.Add(path3);
  2343. return paths;
  2344. }
  2345. }
  2346. for (int i = path.startLocationY + 1; i <= 8; i++)
  2347. {
  2348. path1 = new MovingPath();
  2349. path2 = new MovingPath();
  2350. MovingPath path3 = new MovingPath();
  2351. path1.startLocationX = path.startLocationX;
  2352. path1.startLocationY = path.startLocationY;
  2353. path1.destLocationX = path.startLocationX;
  2354. path1.destLocationY = i;
  2355. path2.startLocationX = path1.destLocationX;
  2356. path2.startLocationY = path1.destLocationY;
  2357. path2.destLocationX = path.destLocationX;
  2358. path2.destLocationY = path1.destLocationY;
  2359. path3.startLocationX = path2.destLocationX;
  2360. path3.startLocationY = path2.destLocationY;
  2361. path3.destLocationX = path.destLocationX;
  2362. path3.destLocationY = path.destLocationY;
  2363. if (CheckPathAvaible(jgrSN, path1) && CheckPathAvaible(jgrSN, path2) && CheckPathAvaible(jgrSN, path3))
  2364. {
  2365. paths.Add(path1);
  2366. paths.Add(path2);
  2367. paths.Add(path3);
  2368. return paths;
  2369. }
  2370. }
  2371. throw new Exception("路线拥挤,请等待");
  2372. }
  2373. /// <summary>
  2374. /// 查找空车
  2375. /// </summary>
  2376. /// <param name="jgrType"></param>
  2377. /// <returns></returns>
  2378. public JGR_Tc_Model? findFreeCar(JgrType jgrType)
  2379. {
  2380. if (ThreadLocalManager.Get() == null ||
  2381. string.IsNullOrEmpty(ThreadLocalManager.Get().taskId)
  2382. || string.IsNullOrWhiteSpace(ThreadLocalManager.Get().taskId))
  2383. {
  2384. Console.WriteLine("没有任务id,不能执行当前业务");
  2385. return null;
  2386. }
  2387. JGR_Tc_Model? free_car = null;
  2388. //查找空车
  2389. List<JGR_Tc_Model> carStatus = GetJgrs();
  2390. if (carStatus != null && carStatus.Count > 0)
  2391. {
  2392. foreach (var car in carStatus)
  2393. {
  2394. if (car.jgrType == (byte)jgrType && checkIsFree(car, true))
  2395. {
  2396. free_car = car;
  2397. if (!jgrTaskMap.ContainsKey(car.jgrSN))
  2398. {
  2399. jgrTaskMap[car.jgrSN] = ThreadLocalManager.Get().taskId;
  2400. }
  2401. break;
  2402. }
  2403. }
  2404. }
  2405. return free_car;
  2406. }
  2407. /// <summary>
  2408. /// 车辆是否空闲
  2409. /// </summary>
  2410. /// <param name="car"></param>
  2411. /// <returns></returns>
  2412. private bool checkIsFree(JGR_Tc_Model car, bool isCheckRfId)
  2413. {
  2414. if(car.jgrType == (byte)JgrType.RailCar)
  2415. {
  2416. return car.moveStatus == 0
  2417. && (!isCheckRfId || (string.IsNullOrEmpty(car.rfid)
  2418. || string.IsNullOrWhiteSpace(car.rfid)))
  2419. && (!jgrTaskMap.ContainsKey(car.jgrSN)
  2420. || jgrTaskMap[car.jgrSN] == ThreadLocalManager.Get().taskId);
  2421. } else if(car.jgrType == (byte)JgrType.StorageCar)
  2422. {
  2423. return car.moveStatus == 0 && car.basketPosition == 0 && car.basketGripperStatus == 2
  2424. && (!jgrTaskMap.ContainsKey(car.jgrSN)
  2425. || jgrTaskMap[car.jgrSN] == ThreadLocalManager.Get().taskId);
  2426. }
  2427. return false;
  2428. }
  2429. /// <summary>
  2430. /// 获取仓储结构
  2431. /// </summary>
  2432. /// <returns></returns>
  2433. public Dictionary<long, GridCell> getStorageGridCells()
  2434. {
  2435. return storageGridCells;
  2436. }
  2437. public bool checkStoragePos(int x, int y)
  2438. {
  2439. var storageGridCells = getStorageGridCells();
  2440. if (storageGridCells != null && storageGridCells.Count > 0)
  2441. {
  2442. //判断储位是否为不能出入库的储位
  2443. foreach (var cell in storageGridCells)
  2444. {
  2445. if (cell.Value.positionX == x && cell.Value.positionY == y)
  2446. {
  2447. if (!cell.Value.enableUse)
  2448. {
  2449. return false;
  2450. }
  2451. return true;
  2452. }
  2453. }
  2454. }
  2455. return false;
  2456. }
  2457. public void notifyCancelTask(string taskId)
  2458. {
  2459. try
  2460. {
  2461. mutex.WaitOne();
  2462. cancelTaskIds.Add(taskId);
  2463. }
  2464. finally
  2465. {
  2466. mutex.ReleaseMutex();
  2467. }
  2468. }
  2469. public void removeCancelTask(string taskId)
  2470. {
  2471. try
  2472. {
  2473. mutex.WaitOne();
  2474. cancelTaskIds.Remove(taskId);
  2475. }
  2476. finally
  2477. {
  2478. mutex.ReleaseMutex();
  2479. }
  2480. }
  2481. }
  2482. public interface IJGR
  2483. {
  2484. bool Init(IServiceProvider services);
  2485. bool ResetADS();
  2486. void SetHub(IHubContext<ChatHub> hub);
  2487. /// <summary>
  2488. /// 获得车的清单,目前充电桩和车是一个结构
  2489. /// </summary>
  2490. /// <returns></returns>
  2491. List<JGR_Tc_Model> GetJgrs();
  2492. }
  2493. }