MainPageViewModel.cs 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  1. using HandyControl.Controls;
  2. using HslCommunication.Core.IMessage;
  3. using LogForceTestApp.Modules.MainModule.Models;
  4. using LogoForceTestApp.Core;
  5. using LogoForceTestApp.Modules.MainModule.Enums;
  6. using LogoForceTestApp.Modules.MainModule.Models;
  7. using LogoForceTestApp.Modules.MainModule.Services;
  8. using LogoForceTestApp.Services;
  9. using LogoForceTestApp.Services.Interfaces;
  10. using Microsoft.Extensions.Options;
  11. using Newtonsoft.Json;
  12. using Newtonsoft.Json.Linq;
  13. using OxyPlot;
  14. using OxyPlot.Axes;
  15. using OxyPlot.Series;
  16. using Prism.Commands;
  17. using Prism.Events;
  18. using Prism.Mvvm;
  19. using Prism.Services.Dialogs;
  20. using PropertyChanged;
  21. using Repository;
  22. using Repository.Entiies;
  23. using Serilog;
  24. using StatementMachineService.Core;
  25. using StatementMachineService.Events;
  26. using System;
  27. using System.Collections.Concurrent;
  28. using System.Collections.Generic;
  29. using System.Collections.ObjectModel;
  30. using System.Diagnostics;
  31. using System.Diagnostics.Metrics;
  32. using System.IO;
  33. using System.Linq;
  34. using System.Management.Instrumentation;
  35. using System.Net.Http;
  36. using System.Security.Cryptography;
  37. using System.Text;
  38. using System.Text.RegularExpressions;
  39. using System.Threading;
  40. using System.Threading.Tasks;
  41. using System.Timers;
  42. using System.Windows;
  43. using System.Windows.Data;
  44. using System.Windows.Forms;
  45. using System.Windows.Input;
  46. using System.Windows.Media.Media3D;
  47. using System.Xml.Linq;
  48. using Team.Utility;
  49. using TouchSocket.Core;
  50. using TouchSocket.Sockets;
  51. using static AutoMapper.Internal.ExpressionFactory;
  52. using Application = System.Windows.Application;
  53. namespace LogoForceTestApp.Modules.MainModule.ViewModels
  54. {
  55. public class MainPageViewModel : BindableBase
  56. {
  57. int _upLoadSlowTime;
  58. private bool _start;
  59. private List<DataPoint> _points = new();
  60. private readonly ConcurrentQueue<UpLoadTraceModel> _upLoadTraceModels = new();
  61. private readonly IHttpClientFactory _httpClientFactory;
  62. private readonly IScanService _scanService;
  63. private readonly IModbusTcpSlaverService _modbusTcpSlaverService;
  64. private readonly IStateService _stateService;
  65. private readonly IRepository _repository;
  66. private readonly IWritableOptions<AppSettings> _appSttings;
  67. private readonly IEventAggregator _eventAggregator;
  68. private readonly InovanceTcp inovanceTcp;
  69. private readonly ILogger _logger;
  70. private readonly IWarningUpdateService _warningUpdateService;
  71. private readonly IDialogService _dialogService;
  72. private readonly Dictionary<int, string> SignalMapper;
  73. private readonly TcpClient tcpClient;
  74. private bool _firstStart = true;
  75. private ResettableTimer _resettableTimer;
  76. public List<InformationNew> InforNew { get; set; }
  77. public PlotModel PlotModel { get; private set; }
  78. public bool ScanConnected { get; set; }
  79. public Param Param { get; set; }
  80. public string NewBarcode { get; set; }
  81. public string ErrorCode { get; set; }
  82. [DoNotNotify]
  83. public string CSVPath { get; set; }
  84. [DoNotNotify]
  85. public string ImagePath { get; set; }
  86. public int OkDuration { get; set; } = 6000;
  87. public OeeConfig OeeConfig { get; set; }
  88. public bool Connected { get; set; }
  89. public DelegateCommand NotarizeCommand { get; set; }
  90. #region 物料码
  91. public string Wu1 { get; set; }
  92. public string Wu2 { get; set; }
  93. public string Wu3 { get; set; }
  94. public string Wu4 { get; set; }
  95. public string Wu5 { get; set; }
  96. public string Wu6 { get; set; }
  97. public string Wu7 { get; set; }
  98. public string Wu8 { get; set; }
  99. public string Wu9 { get; set; }
  100. public string Wu10 { get; set; }
  101. public string Wu11 { get; set; }
  102. public string Wu12 { get; set; }
  103. #endregion
  104. public DelegateCommand UpCommand { get; set; }
  105. public string Person { get; set; }
  106. public string NowID { get; set; }
  107. public DelegateCommand WuCommand { get; set; }
  108. public MainPageViewModel(IHttpClientFactory httpClientFactory, IScanService scanService,
  109. IModbusTcpSlaverService modbusTcpSlaverService, IStateService stateService, IRepository repository,
  110. IWritableOptions<AppSettings> appSttings, IEventAggregator eventAggregator, InovanceTcp inovanceTcp,
  111. ILogger logger, IWarningUpdateService warningUpdateService, TcpClient tcpClient)
  112. {
  113. _httpClientFactory = httpClientFactory;
  114. _scanService = scanService;
  115. _modbusTcpSlaverService = modbusTcpSlaverService;
  116. _stateService = stateService;
  117. _repository = repository;
  118. _appSttings = appSttings;
  119. CSVPath = _appSttings.Value.CSVPath;
  120. ImagePath = _appSttings.Value.ImageSavePath;
  121. _eventAggregator = eventAggregator;
  122. this.inovanceTcp = inovanceTcp;
  123. _eventAggregator.GetEvent<WaringUpdateLog>().Subscribe(WaringUpdateLogChanged);
  124. _logger = logger;
  125. _warningUpdateService = warningUpdateService;
  126. NotarizeCommand = new DelegateCommand(UploadMaterial);
  127. UpCommand = new DelegateCommand(UpName);
  128. WuCommand = new DelegateCommand(UploadWu);
  129. #region tcp
  130. this.tcpClient = tcpClient;
  131. //
  132. tcpClient.Connecting = (client, e) => { return EasyTask.CompletedTask; };//即将连接到服务器,此时已经创建socket,但是还未建立tcp
  133. tcpClient.Connected = (client, e) =>
  134. {
  135. WriteLog("成功连接到服务器");
  136. return EasyTask.CompletedTask;
  137. };//成功连接到服务器
  138. tcpClient.Disconnecting = (client, e) => { return EasyTask.CompletedTask; };//即将从服务器断开连接。此处仅主动断开才有效。
  139. tcpClient.Disconnected = (client, e) =>
  140. {
  141. WriteLog("连接断开", LogType.Error);
  142. while (true)
  143. {
  144. try
  145. {
  146. tcpClient.Connect(3000, CancellationToken.None);
  147. }
  148. catch (Exception)
  149. {
  150. Thread.Sleep(1000);
  151. continue;
  152. }
  153. WriteLog("重连成功");
  154. return EasyTask.CompletedTask;
  155. }
  156. };//从服务器断开连接,当连接不成功时不会触发。
  157. tcpClient.Received = (client, e) =>
  158. {
  159. //从服务器收到信息。但是一般byteBlock和requestInfo会根据适配器呈现不同的值。
  160. var mes = Encoding.UTF8.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);
  161. if (mes.Split(':')[0] == "WU")
  162. {
  163. WriteLog("物料上传成功");
  164. ClearWu();
  165. }
  166. if (mes.Split(':')[0] == "Type")
  167. {
  168. System.Windows.Forms.DialogResult digres = System.Windows.Forms.MessageBox.Show("切换SOP:" + mes.Split(':')[1], "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
  169. if (digres == System.Windows.Forms.DialogResult.OK)
  170. {
  171. Read(mes.Split(':')[1], mes.Split(':')[2]);
  172. tcpClient.Send("切换完成");
  173. WriteLog($"切换SOP:{mes.Split(':')[1]}成功");
  174. }
  175. }
  176. if (mes.Split(':')[0] == "LoginSuc")
  177. {
  178. NowID = Person;
  179. WriteLog("用户上传成功");
  180. Person = "";
  181. }
  182. return EasyTask.CompletedTask;
  183. };
  184. #endregion
  185. //SetupModel();
  186. FileInfos = new ObservableCollection<LocalFile>();
  187. FileInfos2 = new ObservableCollection<LocalFile2>();
  188. FileInfos3 = new ObservableCollection<LocalFile3>();
  189. }
  190. private void UploadWu()
  191. {
  192. try
  193. {
  194. if (Wu1 == null)
  195. {
  196. Wu1 = "";
  197. }
  198. string wustr = Wu1;
  199. tcpClient.Send("WU:" + wustr);
  200. }
  201. catch (Exception ex)
  202. {
  203. WriteLog("上传异常:" + ex.Message);
  204. }
  205. }
  206. private void UpName()
  207. {
  208. try
  209. {
  210. tcpClient.Send($"Login:{Person}");
  211. }
  212. catch (Exception ex)
  213. {
  214. WriteLog(ex.Message, LogType.Error);
  215. }
  216. }
  217. public void ClearWu()
  218. {
  219. Wu1 = ""; Wu2 = ""; Wu3 = ""; Wu4 = ""; Wu5 = "";
  220. Wu6 = ""; Wu7 = ""; Wu8 = ""; Wu9 = ""; Wu10 = "";
  221. }
  222. private void UploadMaterial()
  223. {
  224. try
  225. {
  226. if (Wu1 == null)
  227. {
  228. Wu1 = "";
  229. }
  230. if (Wu2 == null)
  231. {
  232. Wu2 = "";
  233. }
  234. if (Wu3 == null)
  235. {
  236. Wu3 = "";
  237. }
  238. if (Wu4 == null)
  239. {
  240. Wu4 = "";
  241. }
  242. if (Wu5 == null)
  243. {
  244. Wu5 = "";
  245. }
  246. if (Wu6 == null)
  247. {
  248. Wu6 = "";
  249. }
  250. if (Wu7 == null)
  251. {
  252. Wu7 = "";
  253. }
  254. if (Wu8 == null)
  255. {
  256. Wu8 = "";
  257. }
  258. if (Wu9 == null)
  259. {
  260. Wu9 = "";
  261. }
  262. if (Wu10 == null)
  263. {
  264. Wu10 = "";
  265. }
  266. string wustr = Wu1 + "," + Wu2 + "," + Wu3 + "," + Wu4 + "," + Wu5
  267. + "," + Wu6 + "," + Wu7 + "," + Wu8 + "," + Wu9 + "," + Wu10;
  268. tcpClient.Send("WU:" + wustr);
  269. }
  270. catch (Exception ex)
  271. {
  272. WriteLog("上传异常:" + ex.Message);
  273. }
  274. }
  275. #region sop切换
  276. public ObservableCollection<LocalFile> FileInfos { get; set; }
  277. public ObservableCollection<LocalFile2> FileInfos2 { get; set; }
  278. public ObservableCollection<LocalFile3> FileInfos3 { get; set; }
  279. private void Read(string name, string id)
  280. {
  281. string sPath = "//192.168.10.200/作业指导书/";
  282. var path = sPath + name + "/";
  283. //var path = sPath + $"{name}.json";
  284. //FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
  285. //using var streamReader = new StreamReader(fileStream);
  286. //var json = streamReader.ReadToEnd();
  287. //var r = JsonConvert.DeserializeObject<GenaralFile>(json);//反序列化
  288. Application.Current.Dispatcher.Invoke(() =>
  289. {
  290. LoadPicture(path + id);
  291. });
  292. }
  293. //-----图片------
  294. private ObservableCollection<PictureInfo> imageList = new ObservableCollection<PictureInfo>();
  295. public ObservableCollection<PictureInfo> ImageList
  296. {
  297. get { return imageList; }
  298. set { imageList = value; }
  299. }
  300. object lockobj = new object();
  301. /// <summary>
  302. /// 加载缺陷图片
  303. /// </summary>
  304. /// <param name="strPath">图片文件夹路径</param>
  305. public void LoadPicture(string strPath)
  306. {
  307. ImageList.Clear();
  308. BindingOperations.EnableCollectionSynchronization(ImageList, lockobj);
  309. string folderFullName = strPath;//图片文件夹路径
  310. Task.Run(() =>
  311. {
  312. DirectoryInfo TheFolder = new DirectoryInfo(folderFullName);
  313. var res = TheFolder.GetFiles();
  314. for (int i = 0; i < res.Length; i++)
  315. {
  316. PictureInfo pictureInfo = new PictureInfo();
  317. pictureInfo.PicturePath = res[i].DirectoryName + @"\" + res[i].Name;
  318. Uri uri = new Uri(pictureInfo.PicturePath, UriKind.Absolute);
  319. //BitmapImage myimg =ImageProcess.GetBitImage(uri);
  320. pictureInfo.Info = res[i].Name;
  321. ImageList.Add(pictureInfo);
  322. }
  323. });
  324. }
  325. //复制文件
  326. public static void CopyFolder(string sourceFolder, string destFolder)
  327. {
  328. // 检查目标文件夹是否存在,如果不存在则创建
  329. if (!Directory.Exists(sourceFolder))
  330. {
  331. Directory.CreateDirectory(sourceFolder);
  332. }
  333. // 获取源文件夹中的所有文件的完整路径
  334. string[] files = Directory.GetFiles(sourceFolder);
  335. // 遍历所有文件
  336. foreach (string file in files)
  337. {
  338. // 获取文件信息
  339. FileInfo fileInfo = new FileInfo(file);
  340. // 构造目标文件的路径
  341. string newPath = Path.Combine(destFolder, fileInfo.Name);
  342. // 将文件复制到目标文件夹,如果目标文件已存在则覆盖
  343. File.Copy(file, newPath, true);
  344. }
  345. // 获取源文件夹中的所有子文件夹
  346. string[] dirs = Directory.GetDirectories(sourceFolder);
  347. // 递归复制所有子文件夹
  348. foreach (string dir in dirs)
  349. {
  350. // 获取子文件夹的名称
  351. string dirName = Path.GetFileName(dir);
  352. // 构造目标子文件夹的路径
  353. string newDirPath = Path.Combine(destFolder, dirName);
  354. // 递归调用自身来复制子文件夹
  355. CopyFolder(dir, newDirPath);
  356. }
  357. }
  358. #endregion
  359. private void WriteLog(string message, LogType logType = LogType.Info, Exception exception = null)
  360. {
  361. if (exception != null)
  362. {
  363. _logger.Error("{@Message}", exception.ToString());
  364. }
  365. else
  366. {
  367. _logger.Information("{@Message}", message);
  368. }
  369. string singleLine = message.Trim();
  370. string item = $"【{DateTime.Now:F}】 {singleLine}";
  371. _eventAggregator.GetEvent<LogEvent>().Publish(new Tuple<LogType, string>(logType, item));
  372. }
  373. #region old
  374. private void StopCheck(object sender, StateEventArgs e)
  375. {
  376. var modbus = _modbusTcpSlaverService.GetModbusSlaveByIp();
  377. //var points = modbus.DataStore.HoldingRegisters.ReadPoints(200, 1);
  378. Application.Current.Dispatcher.Invoke(new Action(() =>
  379. {
  380. var (errorCode, error) = _warningUpdateService.GetErrorCode(1);
  381. //Dialog.Show(new OeeDialogPage(), "");
  382. // var DialogResult = await Dialog.Show<OeeDialogPage>()
  383. //.Initialize<OeeDialogPageViewModel>(vm => vm.Message = "DialogResult")
  384. //.GetResultAsync<string>();
  385. var param = new DialogParameters
  386. {
  387. { "OP_Id", Param.OPID },
  388. {"ExceptionCode", errorCode}
  389. };
  390. modbus.DataStore.CoilInputs.WritePoints(12, new bool[] { true });
  391. _dialogService.ShowDialog("OeeDialogPage", param, async r =>
  392. {
  393. //dialog.Parameters.Add("OP_Id", OP_Id);
  394. //dialog.Parameters.Add("ExceptionCode", ExceptionCode);
  395. //dialog.Parameters.Add("ExceptionContent", ExceptionContent);
  396. //dialog.Parameters.Add("Duration", Duration);
  397. //dialog.Parameters.Add("ExceptionTime", ExceptionTime.ToString("yyyy-mm-dd HH:mm:ss"));
  398. //dialog.Parameters.Add("Mode", "手动调试模式");
  399. //dialog.Parameters.Add("Reason", ExceptionReason);
  400. var param = r.Parameters;
  401. var opid = param.GetValue<string>("OP_Id");
  402. var exceptionCodeMessage = param.GetValue<string>("ExceptionCode");
  403. var exceptionCode = exceptionCodeMessage.Split('-')[0];
  404. var exceptionContent = param.GetValue<string>("ExceptionContent");
  405. var duration = param.GetValue<int>("Duration");
  406. var exceptionTime = param.GetValue<string>("ExceptionTime");
  407. var mode = param.GetValue<string>("Mode");
  408. var reason = param.GetValue<string>("Reason");
  409. var oeeLogger = new OeeLogger
  410. {
  411. site = OeeConfig.Site,
  412. floor = OeeConfig.Floor,
  413. product = OeeConfig.Product,
  414. line = OeeConfig.Line,
  415. vendor = "Team",
  416. process = OeeConfig.Process,
  417. terminalId = OeeConfig.TerminalId,
  418. machineId = OeeConfig.MachineId,
  419. status = mode,
  420. op_id = opid,
  421. startTime = exceptionTime,
  422. ipaddr = OeeConfig.Ipaddr,
  423. macaddr = OeeConfig.Macaddr,
  424. warningCodeList = new Warningcodelist[2]
  425. };
  426. oeeLogger.warningCodeList[0] = new Warningcodelist
  427. {
  428. warningCode = "400002",
  429. remark = exceptionContent
  430. };
  431. oeeLogger.warningCodeList[1] = new Warningcodelist
  432. {
  433. warningCode = exceptionCode,
  434. remark = reason
  435. };
  436. await UploadOeeAsync(oeeLogger);
  437. modbus.DataStore.CoilInputs.WritePoints(12, new bool[] { false });
  438. });
  439. }));
  440. }
  441. private async void ResettableTimer_Elapsed(object sender, ElapsedEventArgs e)
  442. {
  443. OeeLogger oeeLogger = new()
  444. {
  445. site = OeeConfig.Site,
  446. floor = OeeConfig.Floor,
  447. product = OeeConfig.Product,
  448. line = OeeConfig.Line,
  449. vendor = "Team",
  450. process = OeeConfig.Process,
  451. terminalId = OeeConfig.TerminalId,
  452. machineId = OeeConfig.MachineId,
  453. status = "Waiting for parts",
  454. op_id = Param.OPID,
  455. startTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  456. ipaddr = OeeConfig.Ipaddr,
  457. macaddr = OeeConfig.Macaddr,
  458. warningCodeList = new Warningcodelist[1]
  459. };
  460. oeeLogger.warningCodeList[0] = new Warningcodelist
  461. {
  462. warningCode = "100002",
  463. remark = "待料"
  464. };
  465. await UploadOeeAsync(oeeLogger);
  466. }
  467. private void WaringUpdateLogChanged(Tuple<LogType, string> tuple)
  468. {
  469. Debug.WriteLine(tuple.Item2);
  470. HandyControl.Controls.MessageBox.Show("test");
  471. }
  472. private void OeeConfigChanged(OeeConfig config)
  473. {
  474. OeeConfig ??= new OeeConfig();
  475. OeeConfig.Ip = config.Ip;
  476. OeeConfig.Port = config.Port;
  477. OeeConfig.WaitPartDuration = config.WaitPartDuration;
  478. OeeConfig.StopDuration = config.StopDuration;
  479. OeeConfig.Site = config.Site;
  480. OeeConfig.Floor = config.Floor;
  481. OeeConfig.Product = config.Product;
  482. OeeConfig.Line = config.Line;
  483. OeeConfig.Process = config.Process;
  484. OeeConfig.Vendor = config.Vendor;
  485. OeeConfig.TerminalId = config.TerminalId;
  486. OeeConfig.MachineId = config.MachineId;
  487. OeeConfig.Op_id = config.Op_id;
  488. OeeConfig.Ipaddr = config.Ipaddr;
  489. OeeConfig.Macaddr = config.Macaddr;
  490. OeeConfig.OeePath = config.OeePath;
  491. OeeConfig.UnUse = config.UnUse;
  492. }
  493. private async Task UploadOeeAsync(OeeLogger oeeLogger)
  494. {
  495. if (OeeConfig == null)
  496. {
  497. WriteLog("oee配置文件不存在请重新配置", LogType.Error);
  498. return;
  499. }
  500. using var client = _httpClientFactory.CreateClient();
  501. //var url = _appSttings.Value.OeeUrl;
  502. var loggingURI = $"http://{OeeConfig.Ip}:{OeeConfig.Port}/device/upload/logging/v1";
  503. try
  504. {
  505. var json = JsonConvert.SerializeObject(oeeLogger, Formatting.Indented);
  506. WriteToLocal(json);
  507. if (!OeeConfig.UnUse)
  508. {
  509. client.BaseAddress = new Uri(loggingURI);
  510. var content = new StringContent(json, Encoding.UTF8, "application/json");
  511. var response = await client.PostAsync(loggingURI, content);
  512. WriteLog("oee上传成功");
  513. var s = await response.Content.ReadAsStringAsync();
  514. WriteLog($"状态码:{response.StatusCode}:" + s, LogType.Info);
  515. }
  516. else
  517. {
  518. WriteLog("oee上传屏蔽,未上传");
  519. }
  520. }
  521. catch (Exception e)
  522. {
  523. WriteLog($"oee上传失败,{e.Message}", LogType.Error);
  524. }
  525. }
  526. private void WriteToLocal(string json)
  527. {
  528. var name = DateTime.Now.ToString("yyyy-mm-dd-HH-mm-ss") + "_oee" + ".json";
  529. var path = Path.Combine(OeeConfig.OeePath, name);
  530. if (!Directory.Exists(OeeConfig.OeePath))
  531. {
  532. WriteLog("oee路径不存在", LogType.Error);
  533. return;
  534. }
  535. using var stream = new StreamWriter(path);
  536. stream.Write(json);
  537. }
  538. private void ClearQueue(object sender, StateEventArgs e)
  539. {
  540. var length = _upLoadTraceModels.Count;
  541. for (int i = 0; i < length; i++)
  542. {
  543. _upLoadTraceModels.TryDequeue(out _);
  544. }
  545. }
  546. private void InitTraceData()
  547. {
  548. var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "param.json");
  549. if (File.Exists(filePath))
  550. {
  551. using var stream = new StreamReader(filePath);
  552. var json = stream.ReadToEnd();
  553. Param = JsonConvert.DeserializeObject<Param>(json);
  554. }
  555. else
  556. {
  557. Param = new Param
  558. {
  559. station_id = "LkYC_BO7_2F_01_002_TRACE",
  560. line_id = "B07-2F-01",
  561. station_vendor = "Team",
  562. test = "Logo 30N Non-Destructive Test",
  563. OPID = "C10088888",
  564. DownLimit = "30",
  565. UpperLimit = "60"
  566. };
  567. }
  568. }
  569. private void ScanMethodComplete(object sender, StateEventArgs e)
  570. {
  571. //var modbus = _modbusTcpSlaverService.GetModbusSlaveByIp();
  572. //modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { false });
  573. //WriteLog("复位扫码OK信号");
  574. }
  575. private void SaveDataCompleted(object sender, StateEventArgs e)
  576. {
  577. var modbus = _modbusTcpSlaverService.GetModbusSlaveByIp();
  578. modbus.DataStore.CoilInputs.WritePoints(10, new bool[] { false });
  579. modbus.DataStore.CoilInputs.WritePoints(11, new bool[] { false });
  580. }
  581. private void SaveImage(string barcode, string result)
  582. {
  583. var filePath = string.Empty;
  584. var fileName = barcode + "-" + Guid.NewGuid().ToString("N") + $"-{result}" + ".png";
  585. string directory = ImagePath;
  586. Application.Current.Dispatcher.Invoke(new Action(() =>
  587. {
  588. try
  589. {
  590. var finalPath = Path.Combine(directory, result);
  591. if (!Directory.Exists(finalPath))
  592. {
  593. Directory.CreateDirectory(finalPath);
  594. }
  595. filePath = Path.Combine(finalPath, fileName);
  596. (PlotModel.PlotView as OxyPlot.Wpf.PlotView)?.SaveBitmap(filePath);
  597. }
  598. catch (Exception e)
  599. {
  600. WriteLog($"保存图片出现异常:{e.Message}");
  601. }
  602. }));
  603. }
  604. public float ReadFloat(ushort startId)
  605. {
  606. var modbus = _modbusTcpSlaverService.GetModbusSlaveByIp();
  607. var data = modbus.DataStore
  608. .HoldingRegisters.ReadPoints((ushort)(32 + startId), 2);
  609. var bytes1 = BitConverter.GetBytes(data[0]);
  610. var bytes2 = BitConverter.GetBytes(data[1]);
  611. var bytes = new List<byte>();
  612. bytes.AddRange(bytes1);
  613. bytes.AddRange(bytes2);
  614. var value = BitConverter.ToSingle(bytes.ToArray(), 0);
  615. return value;
  616. }
  617. private async void ScanMethod(object sender, StateEventArgs e)
  618. {
  619. ErrorCode = string.Empty;
  620. var modbus = _modbusTcpSlaverService.GetModbusSlaveByIp();
  621. if (!ScanConnected)
  622. {
  623. WriteLog($"扫码枪未连接,无法执行扫码动作");
  624. ErrorCode = "扫码枪未连接,无法执行扫码动作";
  625. modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { false });
  626. return;
  627. }
  628. for (int i = 0; i < 3; i++)
  629. {
  630. try
  631. {
  632. WriteLog($"开始第{i + 1}次扫码");
  633. NewBarcode = await _scanService.ReadAsync("start");
  634. WriteLog($"第{i + 1}次扫码结果:{NewBarcode}");
  635. if (NewBarcode != string.Empty && (NewBarcode.ToUpper()) != "NOREAD")
  636. {
  637. break;
  638. }
  639. }
  640. catch (Exception ex)
  641. {
  642. modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { false });
  643. WriteLog($"扫码出现异常:{ex.Message}", LogType.Error, ex);
  644. ErrorCode = "扫码出现异常";
  645. }
  646. }
  647. if (NewBarcode != string.Empty && NewBarcode.ToUpper() != "NOREAD")
  648. {
  649. // modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { true });
  650. WriteLog($"扫码成功,SN:{NewBarcode}");
  651. if (!_appSttings.Value.TraceDisable)
  652. {
  653. var result = await GetTraceAsync(NewBarcode);
  654. if (result)
  655. {
  656. modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { true });
  657. WriteLog($"获取trace成功,SN:{NewBarcode}");
  658. if (OkDuration <= 1000)
  659. {
  660. OkDuration = 4000;
  661. }
  662. await Task.Delay(OkDuration);
  663. modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { false });
  664. }
  665. else
  666. {
  667. modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { false });
  668. WriteLog($"trace卡关无法继续 ");
  669. ErrorCode = "trace卡关校验失败";
  670. }
  671. }
  672. else
  673. {
  674. modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { true });
  675. WriteLog($"卡关屏蔽中,直接放行:SN:{NewBarcode}");
  676. }
  677. }
  678. else
  679. {
  680. ErrorCode = $"扫码没有读取正确的二维码";
  681. modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { false });
  682. WriteLog($"扫码失败:{NewBarcode}", LogType.Error);
  683. }
  684. }
  685. private async Task<bool> GetTraceAsync(string barcode)
  686. {
  687. using var client = _httpClientFactory.CreateClient();
  688. try
  689. {
  690. var content = await client.GetStringAsync($"http://localhost:8765/v2/process_control?serial={barcode}&serial_type=part_id");
  691. var data = JsonConvert.DeserializeObject<Rootobject>(content);
  692. try
  693. {
  694. if (string.IsNullOrWhiteSpace(barcode))
  695. {
  696. barcode = Guid.NewGuid().ToString("N");
  697. }
  698. var fileName = "request_" + barcode + ".json";
  699. var path = Path.Combine("logs", fileName);
  700. using var stream = new StreamWriter(path);
  701. await stream.WriteLineAsync(content);
  702. _logger.Information(content);
  703. }
  704. catch (Exception)
  705. {
  706. }
  707. if (!data.pass)
  708. {
  709. foreach (var item in data.processes)
  710. {
  711. if (!item.pass)
  712. {
  713. WriteLog($"{item.id}:{item.name}卡关fail!", LogType.Error);
  714. }
  715. }
  716. }
  717. return data.pass;
  718. }
  719. catch (HttpRequestException e)
  720. {
  721. WriteLog($"请求超时失败:{e.Message}", LogType.Error, e);
  722. return false;
  723. }
  724. }
  725. private async void SaveData(object sender, StateEventArgs e)
  726. {
  727. var modbus = _modbusTcpSlaverService.GetModbusSlaveByIp();
  728. _upLoadTraceModels.TryDequeue(out var _updateModel);
  729. if (_updateModel == null)
  730. {
  731. WriteLog("_updateModel not init");
  732. modbus.DataStore.CoilInputs.WritePoints(10, new bool[] { false });
  733. modbus.DataStore.CoilInputs.WritePoints(11, new bool[] { true });
  734. return;
  735. }
  736. var productTestForce = ReadFloat(74);//test
  737. WriteLog($"读取当前压检值:{productTestForce}");
  738. modbus.DataStore.CoilInputs.WritePoints(10, new bool[] { false });
  739. modbus.DataStore.CoilInputs.WritePoints(11, new bool[] { false });
  740. var plcResult = modbus.DataStore.HoldingRegisters.ReadPoints(32, 1);
  741. var juge = plcResult[0] == 1 ? "pass" : "fail";
  742. _updateModel.data.insight.test_attributes.uut_stop = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  743. _updateModel.data.insight.test_attributes.test_result = juge;
  744. _updateModel.data.insight.results[0].value = productTestForce.ToString("F2");
  745. _updateModel.data.insight.results[0].result = juge;
  746. var runResult = plcResult[0] == 1 ? RunResultState.OK : RunResultState.NG;
  747. _eventAggregator.GetEvent<ResultEvent>().Publish(runResult);
  748. WriteLog("开始保存图片");
  749. SaveImage(_updateModel.serials.part_id, juge);
  750. WriteLog("保存图片完成");
  751. await _repository.AddAsync(new TestResult
  752. {
  753. Id = Guid.NewGuid(),
  754. Barcode = _updateModel.serials.part_id,
  755. Datetime = DateTime.Now,
  756. Result = productTestForce
  757. });
  758. WriteLog("开始保存csv");
  759. try
  760. {
  761. var dateName = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");
  762. var fileName = dateName + "-" + _updateModel.serials.part_id + ".csv";
  763. var filePath = Path.Combine(CSVPath, fileName);
  764. var exsit = File.Exists(filePath);
  765. using var streamWriter = new StreamWriter(filePath, false, Encoding.UTF8);
  766. if (!exsit)
  767. {
  768. var header = "SERIAL_NUMBER,MEASURE_DATE,MEASURE_TIME,STATION,OP_NAME,AIM_VENDOR,AIM_NAME,AIM_UNIQUE," +
  769. "INSPECTION_PROGRAM_NAME,PROJECT,PART,PROCESS,BUILDS,SHIFT_D_N,CAVITY,RESULT,BIN_MP,COLOR,TEMPERATURE," +
  770. "HUMIDITY,PRODUCT_TEMP,COLOR_BANKING,KB_LAYOUT,DATA_BIN," +
  771. "DATA1,DATA2,DATA3,DATA4,DATA5,DATA6,DATA7,DATA8,DATA9,DATA10,DATA11,DATA12,DATA13," +
  772. "DATA14,DATA15,DATA16,DATA17,DATA18,DATA19,DATA20,DATA21,DATA22,DATA23,DATA24,DATA25,DATA26," +
  773. "DATA27,DATA28,DATA29,DATA30,DATA31,DATA32,DATA33,DATA34,DATA35,DATA36,DATA37,DATA38,DATA39," +
  774. "DATA40,DATA41,DATA42,DATA43,DATA44,DATA45,DATA46,DATA47,DATA48,DATA49,DATA50,DATA51,DATA52," +
  775. "DATA53,DATA54,DATA55,DATA56,DATA57,DATA58,DATA59,DATA60,DATA61,DATA62,DATA63,DATA64,DATA65," +
  776. "DATA66,DATA67,DATA68,DATA69,DATA70,DATA71,DATA72,DATA73,DATA74,DATA75," +
  777. "DATA76,DATA77,DATA78,DATA79,DATA80,DATA81,DATA82,DATA83,DATA84,DATA85,DATA86,DATA87,DATA88," +
  778. "DATA89,DATA90,DATA91,DATA92,DATA93,DATA94,DATA95,DATA96,DATA97,DATA98,DATA99,DATA100";
  779. await streamWriter.WriteLineAsync(header);
  780. await streamWriter.FlushAsync();
  781. }
  782. var value = $"SPC_G1/{_updateModel.data.insight.results[0].value}/H{Param.UpperLimit}/L{Param.DownLimit}";
  783. var data = $"{_updateModel.serials.part_id},{DateTime.Now:yyyy/MM/dd}" + $",{DateTime.Now:HH:mm:ss}" +
  784. $",logo-test,{Param.OPID},{_updateModel.data.insight.uut_attributes.station_vendor}," +
  785. $"{_appSttings.Value.AimName},{_appSttings.Value.AIM_UNIQUE},{_appSttings.Value.INSPECTION_PROGRAM_NAME}," +
  786. $"{_appSttings.Value.Project},{_appSttings.Value.Part},{_appSttings.Value.Process},{_appSttings.Value.Builds},,," +
  787. $"{_updateModel.data.insight.test_attributes.test_result},,color,,,,,,,{value}";
  788. var list = new List<string>();
  789. for (int i = 0; i < 99; i++)
  790. {
  791. data += ",";
  792. }
  793. await streamWriter.WriteLineAsync(data);
  794. await streamWriter.FlushAsync();
  795. streamWriter.Close();
  796. WriteLog("保存csv完成");
  797. }
  798. catch (Exception ex)
  799. {
  800. WriteLog($"保存csv失败:{ex}");
  801. }
  802. WriteLog("开始上传数据");
  803. if (!_appSttings.Value.UnUseUpload)
  804. {
  805. var json = JsonConvert.SerializeObject(_updateModel, Formatting.Indented);
  806. try
  807. {
  808. var barcode = _updateModel.serials.part_id;
  809. if (string.IsNullOrWhiteSpace(barcode))
  810. {
  811. barcode = Guid.NewGuid().ToString("N");
  812. }
  813. var fileName = "upload_" + barcode + ".json";
  814. var path = Path.Combine("logs", fileName);
  815. using var stream = new StreamWriter(path);
  816. await stream.WriteLineAsync(json);
  817. }
  818. catch (Exception)
  819. {
  820. }
  821. _logger.Information("正在上传数据:" + json);
  822. var stopWatch = new System.Diagnostics.Stopwatch();
  823. stopWatch.Start();
  824. var ret = await UploadAsync(json);
  825. if (stopWatch.ElapsedMilliseconds > 2000)
  826. {
  827. _upLoadSlowTime++;
  828. WriteLog($"连续{_upLoadSlowTime}上传trace数据大于2s", LogType.Warning);
  829. if (_upLoadSlowTime >= 5)
  830. {
  831. ErrorCode = "连续5次上传数据缓慢,请检查网络连接";
  832. }
  833. }
  834. else
  835. {
  836. _upLoadSlowTime = 0;
  837. }
  838. if (ret)
  839. {
  840. modbus.DataStore.CoilInputs.WritePoints(10, new bool[] { true });
  841. modbus.DataStore.CoilInputs.WritePoints(11, new bool[] { false });
  842. }
  843. else
  844. {
  845. modbus.DataStore.CoilInputs.WritePoints(10, new bool[] { false });
  846. modbus.DataStore.CoilInputs.WritePoints(11, new bool[] { true });
  847. }
  848. }
  849. else
  850. {
  851. modbus.DataStore.CoilInputs.WritePoints(10, new bool[] { true });
  852. modbus.DataStore.CoilInputs.WritePoints(11, new bool[] { false });
  853. }
  854. OeeLogger oeeLogger = new()
  855. {
  856. site = OeeConfig.Site,
  857. floor = OeeConfig.Floor,
  858. product = OeeConfig.Product,
  859. line = OeeConfig.Line,
  860. vendor = "Team",
  861. process = OeeConfig.Process,
  862. terminalId = OeeConfig.TerminalId,
  863. machineId = OeeConfig.MachineId,
  864. status = "running",
  865. op_id = Param.OPID,
  866. startTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  867. ipaddr = OeeConfig.Ipaddr,
  868. macaddr = OeeConfig.Macaddr,
  869. warningCodeList = new Warningcodelist[1]
  870. };
  871. oeeLogger.warningCodeList[0] = new Warningcodelist
  872. {
  873. warningCode = "100001",
  874. remark = "压力检测完成"
  875. };
  876. await UploadOeeAsync(oeeLogger);
  877. WriteLog("上传数据完成");
  878. }
  879. //UpLoadTraceModel _updateModel;
  880. private async Task<bool> UploadAsync(string data)
  881. {
  882. using var client = _httpClientFactory.CreateClient();
  883. var stringContent = new StringContent(data);
  884. stringContent.Headers.ContentType = new
  885. System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
  886. var statisticsLog = new StatisticsLog
  887. {
  888. Id = Guid.NewGuid(),
  889. Timestamp = DateTime.Now,
  890. RequstType = RequstType.Post
  891. };
  892. try
  893. {
  894. var responseMessage = await client.PostAsync("http://localhost:8765/v2/logs", stringContent);
  895. if (responseMessage.StatusCode == System.Net.HttpStatusCode.OK)
  896. {
  897. WriteLog($"上传数据成功");
  898. statisticsLog.TraceState = TraceState.PostOK;
  899. var s = await responseMessage.Content.ReadAsStringAsync();
  900. WriteLog($"response:{s}");
  901. statisticsLog.RequestCode = (int)responseMessage.StatusCode;
  902. return true;
  903. }
  904. else
  905. {
  906. statisticsLog.TraceState = TraceState.PostNG;
  907. WriteLog($"上传失败:状态码{responseMessage.StatusCode}," +
  908. $"请求uri:{responseMessage.RequestMessage.RequestUri}");
  909. statisticsLog.RequestCode = (int)responseMessage.StatusCode;
  910. var s = await responseMessage.Content.ReadAsStringAsync();
  911. WriteLog($"response:{s}");
  912. return false;
  913. }
  914. }
  915. catch (HttpRequestException e)
  916. {
  917. statisticsLog.TraceState = TraceState.PostNG;
  918. statisticsLog.RequestCode = 600;
  919. WriteLog($"上传失败:{e.Message}");
  920. return false;
  921. }
  922. finally
  923. {
  924. await _repository.AddAsync(statisticsLog);
  925. }
  926. }
  927. private void StopReadForceMethod(object sender, StateEventArgs e)
  928. {
  929. WriteLog("停止读取压力传感器数值");
  930. _start = false;
  931. }
  932. private void ModbusTcpSlaverService_CoilDiscretesHandler(object sender, LogoForceTestApp.Services.Interfaces.Events.StorageEventArgs<bool> e)
  933. {
  934. }
  935. private void SetupModel()
  936. {
  937. PlotModel = new PlotModel();
  938. PlotModel.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Minimum = 0, Maximum = 80 });
  939. PlotModel.Series.Add(new LineSeries { LineStyle = LineStyle.Solid });
  940. RaisePropertyChanged(nameof(PlotModel));
  941. }
  942. private void Clear()
  943. {
  944. var s = (LineSeries)PlotModel.Series[0];
  945. s.Points.Clear();
  946. }
  947. private void Update(DataPoint dataPoint)
  948. {
  949. var s = (LineSeries)PlotModel.Series[0];
  950. s.Points.Add(dataPoint);
  951. }
  952. #endregion
  953. }
  954. }