LogikalClient.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Threading;
  8. using System.Windows.Forms;
  9. using Comal.Classes;
  10. using H.Formatters;
  11. using H.Pipes;
  12. using InABox.Clients;
  13. using InABox.Configuration;
  14. using InABox.Core;
  15. using InABox.Integration.Logikal;
  16. using Newtonsoft.Json;
  17. using PRSDesktop.Integrations.Logikal;
  18. using Exception = System.Exception;
  19. using Process = System.Diagnostics.Process;
  20. namespace PRSDesktop;
  21. public class LogikalClient : IDisposable
  22. {
  23. private readonly PipeClient<LogikalMessage> _client;
  24. private ConcurrentDictionary<Guid, ManualResetEventSlim> Events = new();
  25. private ConcurrentDictionary<Guid, LogikalMessage> Responses = new();
  26. private const int DefaultRequestTimeout = 5 * 60 * 1000; // 5 minutes
  27. public LogikalSettings Settings { get; private set; }
  28. public bool Ready { get; private set; } = false;
  29. private LogikalErrorResponse NOTLOGGEDIN = new LogikalErrorResponse()
  30. {
  31. Status = LogikalStatus.NotLoggedIn,
  32. Message = "Not Logged In"
  33. };
  34. public LogikalClient()
  35. {
  36. Settings = new GlobalConfiguration<LogikalSettings>().Load();
  37. var _basedirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) ?? "";
  38. var _logikalapp = System.IO.Path.Combine(_basedirectory, "PRSLogikal", "PRSLogikal.exe");
  39. if (!File.Exists(_logikalapp))
  40. _logikalapp = @"C:\development\prs\prs.logikal\bin\Debug\prslogikal.exe";
  41. if (!File.Exists(_logikalapp))
  42. {
  43. MessageBox.Show("Unable to locate PRS/Logikal interface!");
  44. return;
  45. }
  46. var _info = new ProcessStartInfo(_logikalapp);
  47. _info.WindowStyle = ProcessWindowStyle.Minimized;
  48. Process.Start(_info);
  49. _client = new PipeClient<LogikalMessage>("$logikal", formatter: new NewtonsoftJsonFormatter());
  50. _client.Connected += Client_Connected;
  51. _client.Disconnected += Client_Disconnected;
  52. _client.MessageReceived += Client_MessageReceived;
  53. _client.ExceptionOccurred += Client_ExceptionOccurred;
  54. _client.ConnectAsync();
  55. }
  56. public void Dispose()
  57. {
  58. _client.DisposeAsync().AsTask().Wait();
  59. }
  60. private void Client_Connected(object? sender, H.Pipes.Args.ConnectionEventArgs<LogikalMessage> e)
  61. {
  62. Logger.Send(LogType.Information, "", $"Connected to Pipe: {e.Connection.PipeName}");
  63. //Disconnected = false;
  64. // Here we will register a Licence "Hit" for the Logikal interface
  65. }
  66. private void Client_Disconnected(object? sender, H.Pipes.Args.ConnectionEventArgs<LogikalMessage> e)
  67. {
  68. Logger.Send(LogType.Information, "", $"Disconnected from Pipe: {e.Connection.PipeName}");
  69. foreach (var ev in Events)
  70. {
  71. Responses.TryAdd(ev.Key, LogikalMessage.Error("Disconnected"));
  72. ev.Value.Set();
  73. }
  74. //Disconnected = true;
  75. }
  76. private void Client_ExceptionOccurred(object? sender, H.Pipes.Args.ExceptionEventArgs e)
  77. {
  78. Logger.Send(LogType.Error, "", $"Exception occured: {e.Exception.Message}");
  79. }
  80. private static Dictionary<LogikalMethod, Type> _methods = new Dictionary<LogikalMethod, Type>()
  81. {
  82. { LogikalMethod.Connect, typeof(LogikalConnectResponse) },
  83. { LogikalMethod.Login, typeof(LogikalLoginResponse) },
  84. { LogikalMethod.Logout, typeof(LogikalLogoutResponse) },
  85. { LogikalMethod.Disconnect, typeof(LogikalDisconnectResponse) },
  86. { LogikalMethod.ProjectCentres, typeof(LogikalProjectCentresResponse<LogikalProjectCentre, LogikalProject>) },
  87. { LogikalMethod.Projects, typeof(LogikalProjectsResponse<LogikalProject>) },
  88. { LogikalMethod.Phases, typeof(LogikalPhasesResponse<LogikalPhase>) },
  89. { LogikalMethod.ElevationSummary, typeof(LogikalElevationSummaryResponse<LogikalElevationSummary>) },
  90. { LogikalMethod.ElevationDetail, typeof(LogikalElevationDetailResponse<LogikalElevationDetail,LogikalFinish,LogikalProfile,LogikalGasket,LogikalComponent, LogikalGlass, LogikalLabour>) },
  91. { LogikalMethod.BOM, typeof(LogikalBOMResponse<LogikalBOM,LogikalFinish,LogikalProfile,LogikalGasket,LogikalComponent, LogikalGlass, LogikalLabour>) },
  92. { LogikalMethod.Error, typeof(LogikalErrorResponse) },
  93. };
  94. private LogikalResponse FromMessage(LogikalMessage message)
  95. {
  96. try
  97. {
  98. LogikalResponse _result = null;
  99. if (_methods.TryGetValue(message.Method, out var _type))
  100. {
  101. _result = JsonConvert.DeserializeObject(message.Payload, _type) as LogikalResponse;
  102. if (_result != null)
  103. return _result;
  104. return new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = $"Deserialize Failure: {message.Method}: {message.Payload}" };
  105. }
  106. else
  107. return new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = $"Invalid Message Method: {message.Method}: {message.Payload}" };
  108. }
  109. catch (Exception e)
  110. {
  111. return new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = $"Exception Deserializing Response: {e.Message}\n{e.StackTrace}" };
  112. }
  113. }
  114. public LogikalResponse Send(LogikalRequest request, int timeout = DefaultRequestTimeout)
  115. {
  116. var checkfile = Path.Combine(CoreUtils.GetPath(),"simulator.logikal");
  117. var filename = Path.Combine(CoreUtils.GetPath(), $"{request.Method()}.logikal");
  118. if (File.Exists(checkfile) && File.Exists(filename))
  119. {
  120. var dec = Serialization.Deserialize<LogikalMessage>(File.ReadAllText(filename));
  121. if (dec != null)
  122. return FromMessage(dec);
  123. }
  124. var message = new LogikalMessage()
  125. {
  126. ID = Guid.NewGuid(),
  127. Method = request.Method(),
  128. Payload = Serialization.Serialize(request),
  129. };
  130. var ev = Queue(message.ID);
  131. _client.WriteAsync(message);
  132. var result = GetResult(message.ID, ev, timeout);
  133. if (File.Exists(checkfile))
  134. {
  135. var enc = Serialization.Serialize(result);
  136. File.WriteAllText(filename, enc);
  137. }
  138. return FromMessage(result);
  139. }
  140. public ManualResetEventSlim Queue(Guid id)
  141. {
  142. var ev = new ManualResetEventSlim();
  143. Events[id] = ev;
  144. return ev;
  145. }
  146. public LogikalMessage GetResult(Guid id, ManualResetEventSlim ev, int timeout)
  147. {
  148. if (Responses.TryRemove(id, out var result))
  149. {
  150. Events.TryRemove(id, out ev);
  151. return result;
  152. }
  153. try
  154. {
  155. if (!ev.Wait(timeout))
  156. {
  157. return LogikalMessage.Error("Timeout");
  158. }
  159. }
  160. catch (Exception e)
  161. {
  162. Console.WriteLine(e);
  163. throw;
  164. }
  165. Responses.TryRemove(id, out result);
  166. Events.TryRemove(id, out ev);
  167. return result ?? LogikalMessage.Error("Unknown");
  168. }
  169. private void Client_MessageReceived(object? sender, H.Pipes.Args.ConnectionMessageEventArgs<LogikalMessage?> e)
  170. {
  171. if (Events.TryGetValue(e.Message.ID, out var ev))
  172. {
  173. Responses[e.Message.ID] = e.Message;
  174. ev.Set();
  175. }
  176. }
  177. ~LogikalClient()
  178. {
  179. Dispose();
  180. }
  181. public LogikalResponse Connect()
  182. {
  183. Settings = new GlobalConfiguration<LogikalSettings>().Load();
  184. Client.Save(new LogikalUsage(),"");
  185. if (Ready)
  186. return new LogikalConnectResponse();
  187. var _request = new LogikalConnectRequest()
  188. {
  189. Path = Settings.Path
  190. };
  191. var _result = Send(_request);
  192. return _result;
  193. }
  194. public LogikalResponse Disconnect()
  195. {
  196. Ready = false;
  197. var _request = new LogikalDisconnectRequest();
  198. var _result = Send(_request);
  199. return _result;
  200. }
  201. public LogikalResponse Login()
  202. {
  203. //Settings = new GlobalConfiguration<LogikalSettings>().Load();
  204. if (Ready)
  205. return new LogikalLoginResponse();
  206. var _request = new LogikalLoginRequest();
  207. var _result = Send(_request)
  208. .Success<LogikalLoginResponse>(r =>
  209. {
  210. Ready = true;
  211. });
  212. return _result;
  213. }
  214. public LogikalResponse Logout()
  215. {
  216. Ready = false;
  217. var _request = new LogikalLogoutRequest();
  218. var _result = Send(_request);
  219. return _result;
  220. }
  221. public LogikalResponse GetProjectCentres()
  222. {
  223. if (!Ready)
  224. return NOTLOGGEDIN;
  225. var _request = new LogikalProjectCentresRequest();
  226. var _result = Send(_request);
  227. return _result;
  228. }
  229. public LogikalResponse GetProjects(string jobnumber)
  230. {
  231. if (!Ready)
  232. return NOTLOGGEDIN;
  233. var _request = new LogikalProjectsRequest(jobnumber);
  234. var _result = Send(_request);
  235. return _result;
  236. }
  237. public LogikalResponse GetProject(Guid projectid)
  238. {
  239. if (!Ready)
  240. return NOTLOGGEDIN;
  241. var _request = new LogikalProjectRequest(projectid);
  242. var _result = Send(_request);
  243. return _result;
  244. }
  245. public LogikalResponse GetPhases(Guid projectid)
  246. {
  247. if (!Ready)
  248. return NOTLOGGEDIN;
  249. var _request = new LogikalPhasesRequest(projectid);
  250. var _result = Send(_request);
  251. return _result;
  252. }
  253. public LogikalResponse GetElevationSummaries(Guid projectid, string phase)
  254. {
  255. if (!Ready)
  256. return NOTLOGGEDIN;
  257. var _request = new LogikalElevationSummaryRequest(projectid, phase);
  258. var _result = Send(_request);
  259. return _result;
  260. }
  261. public LogikalResponse GetBillOfMaterials(Guid projectid, Guid[] elevationids, bool excel, bool sqlite)
  262. {
  263. if (!Ready)
  264. return NOTLOGGEDIN;
  265. var _request = new LogikalBOMRequest(
  266. projectid,
  267. elevationids,
  268. Settings.FinishSQL,
  269. Settings.BillOfMaterialsProfileSQL,
  270. Settings.GasketSQL,
  271. Settings.ComponentSQL,
  272. Settings.GlassSQL,
  273. Settings.LabourSQL,
  274. excel,
  275. sqlite);
  276. var _result = Send(_request);
  277. return _result;
  278. }
  279. public LogikalResponse GetElevationDetails(Guid projectid, Guid[] elevationids, bool excel, bool sqlite)
  280. {
  281. if (!Ready)
  282. return NOTLOGGEDIN;
  283. var _request = new LogikalElevationDetailRequest(
  284. projectid,
  285. elevationids,
  286. Settings.FinishSQL,
  287. Settings.DesignProfileSQL,
  288. Settings.GasketSQL,
  289. Settings.ComponentSQL,
  290. Settings.GlassSQL,
  291. Settings.LabourSQL,
  292. excel,
  293. sqlite,
  294. Settings.DrawingFormat == Comal.Classes.LogikalDrawingFormat.DXF
  295. ? InABox.Integration.Logikal.LogikalDrawingFormat.DXF
  296. : InABox.Integration.Logikal.LogikalDrawingFormat.PNG,
  297. Settings.DrawingView == Comal.Classes.LogikalDrawingView.Exterior
  298. ? InABox.Integration.Logikal.LogikalDrawingView.Exterior
  299. : InABox.Integration.Logikal.LogikalDrawingView.Interior,
  300. Settings.DrawingType == Comal.Classes.LogikalDrawingType.Explosion
  301. ? InABox.Integration.Logikal.LogikalDrawingType.Explosion
  302. : Settings.DrawingType == Comal.Classes.LogikalDrawingType.Section
  303. ? InABox.Integration.Logikal.LogikalDrawingType.Section
  304. : Settings.DrawingType == Comal.Classes.LogikalDrawingType.Elevation
  305. ? InABox.Integration.Logikal.LogikalDrawingType.Elevation
  306. : Settings.DrawingType == Comal.Classes.LogikalDrawingType.ElevationWithSectionLines
  307. ? InABox.Integration.Logikal.LogikalDrawingType.ElevationWithSectionLines
  308. : InABox.Integration.Logikal.LogikalDrawingType.SectionLine
  309. );
  310. var _result = Send(_request);
  311. return _result;
  312. }
  313. }