using HandyControl.Controls; using HslCommunication.Core.IMessage; using LogForceTestApp.Modules.MainModule.Models; using LogoForceTestApp.Core; using LogoForceTestApp.Modules.MainModule.Enums; using LogoForceTestApp.Modules.MainModule.Models; using LogoForceTestApp.Modules.MainModule.Services; using LogoForceTestApp.Services; using LogoForceTestApp.Services.Interfaces; using Microsoft.Extensions.Options; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OxyPlot; using OxyPlot.Axes; using OxyPlot.Series; using Prism.Commands; using Prism.Events; using Prism.Mvvm; using Prism.Services.Dialogs; using PropertyChanged; using Repository; using Repository.Entiies; using Serilog; using StatementMachineService.Core; using StatementMachineService.Events; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.Metrics; using System.IO; using System.Linq; using System.Management.Instrumentation; using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Timers; using System.Windows; using System.Windows.Data; using System.Windows.Forms; using System.Windows.Input; using System.Windows.Media.Media3D; using System.Xml.Linq; using Team.Utility; using TouchSocket.Core; using TouchSocket.Sockets; using static AutoMapper.Internal.ExpressionFactory; using Application = System.Windows.Application; namespace LogoForceTestApp.Modules.MainModule.ViewModels { public class MainPageViewModel : BindableBase { int _upLoadSlowTime; private bool _start; private List _points = new(); private readonly ConcurrentQueue _upLoadTraceModels = new(); private readonly IHttpClientFactory _httpClientFactory; private readonly IScanService _scanService; private readonly IModbusTcpSlaverService _modbusTcpSlaverService; private readonly IStateService _stateService; private readonly IRepository _repository; private readonly IWritableOptions _appSttings; private readonly IEventAggregator _eventAggregator; private readonly InovanceTcp inovanceTcp; private readonly ILogger _logger; private readonly IWarningUpdateService _warningUpdateService; private readonly IDialogService _dialogService; private readonly Dictionary SignalMapper; private readonly TcpClient tcpClient; private bool _firstStart = true; private ResettableTimer _resettableTimer; public List InforNew { get; set; } public PlotModel PlotModel { get; private set; } public bool ScanConnected { get; set; } public Param Param { get; set; } public string NewBarcode { get; set; } public string ErrorCode { get; set; } [DoNotNotify] public string CSVPath { get; set; } [DoNotNotify] public string ImagePath { get; set; } public int OkDuration { get; set; } = 6000; public OeeConfig OeeConfig { get; set; } public bool Connected { get; set; } public DelegateCommand NotarizeCommand { get; set; } #region 物料码 public string Wu1 { get; set; } public string Wu2 { get; set; } public string Wu3 { get; set; } public string Wu4 { get; set; } public string Wu5 { get; set; } public string Wu6 { get; set; } public string Wu7 { get; set; } public string Wu8 { get; set; } public string Wu9 { get; set; } public string Wu10 { get; set; } public string Wu11 { get; set; } public string Wu12 { get; set; } #endregion public DelegateCommand UpCommand { get; set; } public string Person { get; set; } public string NowID { get; set; } public DelegateCommand WuCommand { get; set; } public MainPageViewModel(IHttpClientFactory httpClientFactory, IScanService scanService, IModbusTcpSlaverService modbusTcpSlaverService, IStateService stateService, IRepository repository, IWritableOptions appSttings, IEventAggregator eventAggregator, InovanceTcp inovanceTcp, ILogger logger, IWarningUpdateService warningUpdateService, TcpClient tcpClient) { _httpClientFactory = httpClientFactory; _scanService = scanService; _modbusTcpSlaverService = modbusTcpSlaverService; _stateService = stateService; _repository = repository; _appSttings = appSttings; CSVPath = _appSttings.Value.CSVPath; ImagePath = _appSttings.Value.ImageSavePath; _eventAggregator = eventAggregator; this.inovanceTcp = inovanceTcp; _eventAggregator.GetEvent().Subscribe(WaringUpdateLogChanged); _logger = logger; _warningUpdateService = warningUpdateService; NotarizeCommand = new DelegateCommand(UploadMaterial); UpCommand = new DelegateCommand(UpName); WuCommand = new DelegateCommand(UploadWu); #region tcp this.tcpClient = tcpClient; // tcpClient.Connecting = (client, e) => { return EasyTask.CompletedTask; };//即将连接到服务器,此时已经创建socket,但是还未建立tcp tcpClient.Connected = (client, e) => { WriteLog("成功连接到服务器"); return EasyTask.CompletedTask; };//成功连接到服务器 tcpClient.Disconnecting = (client, e) => { return EasyTask.CompletedTask; };//即将从服务器断开连接。此处仅主动断开才有效。 tcpClient.Disconnected = (client, e) => { WriteLog("连接断开", LogType.Error); while (true) { try { tcpClient.Connect(3000, CancellationToken.None); } catch (Exception) { Thread.Sleep(1000); continue; } WriteLog("重连成功"); return EasyTask.CompletedTask; } };//从服务器断开连接,当连接不成功时不会触发。 tcpClient.Received = (client, e) => { //从服务器收到信息。但是一般byteBlock和requestInfo会根据适配器呈现不同的值。 var mes = Encoding.UTF8.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len); if (mes.Split(':')[0] == "WU") { WriteLog("物料上传成功"); ClearWu(); } if (mes.Split(':')[0] == "Type") { System.Windows.Forms.DialogResult digres = System.Windows.Forms.MessageBox.Show("切换SOP:" + mes.Split(':')[1], "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation); if (digres == System.Windows.Forms.DialogResult.OK) { Read(mes.Split(':')[1], mes.Split(':')[2]); tcpClient.Send("切换完成"); WriteLog($"切换SOP:{mes.Split(':')[1]}成功"); } } if (mes.Split(':')[0] == "LoginSuc") { NowID = Person; WriteLog("用户上传成功"); Person = ""; } return EasyTask.CompletedTask; }; #endregion //SetupModel(); FileInfos = new ObservableCollection(); FileInfos2 = new ObservableCollection(); FileInfos3 = new ObservableCollection(); } private void UploadWu() { try { if (Wu1 == null) { Wu1 = ""; } string wustr = Wu1; tcpClient.Send("WU:" + wustr); } catch (Exception ex) { WriteLog("上传异常:" + ex.Message); } } private void UpName() { try { tcpClient.Send($"Login:{Person}"); } catch (Exception ex) { WriteLog(ex.Message, LogType.Error); } } public void ClearWu() { Wu1 = ""; Wu2 = ""; Wu3 = ""; Wu4 = ""; Wu5 = ""; Wu6 = ""; Wu7 = ""; Wu8 = ""; Wu9 = ""; Wu10 = ""; } private void UploadMaterial() { try { if (Wu1 == null) { Wu1 = ""; } if (Wu2 == null) { Wu2 = ""; } if (Wu3 == null) { Wu3 = ""; } if (Wu4 == null) { Wu4 = ""; } if (Wu5 == null) { Wu5 = ""; } if (Wu6 == null) { Wu6 = ""; } if (Wu7 == null) { Wu7 = ""; } if (Wu8 == null) { Wu8 = ""; } if (Wu9 == null) { Wu9 = ""; } if (Wu10 == null) { Wu10 = ""; } string wustr = Wu1 + "," + Wu2 + "," + Wu3 + "," + Wu4 + "," + Wu5 + "," + Wu6 + "," + Wu7 + "," + Wu8 + "," + Wu9 + "," + Wu10; tcpClient.Send("WU:" + wustr); } catch (Exception ex) { WriteLog("上传异常:" + ex.Message); } } #region sop切换 public ObservableCollection FileInfos { get; set; } public ObservableCollection FileInfos2 { get; set; } public ObservableCollection FileInfos3 { get; set; } private void Read(string name, string id) { string sPath = "//192.168.10.200/作业指导书/"; var path = sPath + name + "/"; //var path = sPath + $"{name}.json"; //FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read); //using var streamReader = new StreamReader(fileStream); //var json = streamReader.ReadToEnd(); //var r = JsonConvert.DeserializeObject(json);//反序列化 Application.Current.Dispatcher.Invoke(() => { LoadPicture(path + id); }); } //-----图片------ private ObservableCollection imageList = new ObservableCollection(); public ObservableCollection ImageList { get { return imageList; } set { imageList = value; } } object lockobj = new object(); /// /// 加载缺陷图片 /// /// 图片文件夹路径 public void LoadPicture(string strPath) { ImageList.Clear(); BindingOperations.EnableCollectionSynchronization(ImageList, lockobj); string folderFullName = strPath;//图片文件夹路径 Task.Run(() => { DirectoryInfo TheFolder = new DirectoryInfo(folderFullName); var res = TheFolder.GetFiles(); for (int i = 0; i < res.Length; i++) { PictureInfo pictureInfo = new PictureInfo(); pictureInfo.PicturePath = res[i].DirectoryName + @"\" + res[i].Name; Uri uri = new Uri(pictureInfo.PicturePath, UriKind.Absolute); //BitmapImage myimg =ImageProcess.GetBitImage(uri); pictureInfo.Info = res[i].Name; ImageList.Add(pictureInfo); } }); } //复制文件 public static void CopyFolder(string sourceFolder, string destFolder) { // 检查目标文件夹是否存在,如果不存在则创建 if (!Directory.Exists(sourceFolder)) { Directory.CreateDirectory(sourceFolder); } // 获取源文件夹中的所有文件的完整路径 string[] files = Directory.GetFiles(sourceFolder); // 遍历所有文件 foreach (string file in files) { // 获取文件信息 FileInfo fileInfo = new FileInfo(file); // 构造目标文件的路径 string newPath = Path.Combine(destFolder, fileInfo.Name); // 将文件复制到目标文件夹,如果目标文件已存在则覆盖 File.Copy(file, newPath, true); } // 获取源文件夹中的所有子文件夹 string[] dirs = Directory.GetDirectories(sourceFolder); // 递归复制所有子文件夹 foreach (string dir in dirs) { // 获取子文件夹的名称 string dirName = Path.GetFileName(dir); // 构造目标子文件夹的路径 string newDirPath = Path.Combine(destFolder, dirName); // 递归调用自身来复制子文件夹 CopyFolder(dir, newDirPath); } } #endregion private void WriteLog(string message, LogType logType = LogType.Info, Exception exception = null) { if (exception != null) { _logger.Error("{@Message}", exception.ToString()); } else { _logger.Information("{@Message}", message); } string singleLine = message.Trim(); string item = $"【{DateTime.Now:F}】 {singleLine}"; _eventAggregator.GetEvent().Publish(new Tuple(logType, item)); } #region old private void StopCheck(object sender, StateEventArgs e) { var modbus = _modbusTcpSlaverService.GetModbusSlaveByIp(); //var points = modbus.DataStore.HoldingRegisters.ReadPoints(200, 1); Application.Current.Dispatcher.Invoke(new Action(() => { var (errorCode, error) = _warningUpdateService.GetErrorCode(1); //Dialog.Show(new OeeDialogPage(), ""); // var DialogResult = await Dialog.Show() //.Initialize(vm => vm.Message = "DialogResult") //.GetResultAsync(); var param = new DialogParameters { { "OP_Id", Param.OPID }, {"ExceptionCode", errorCode} }; modbus.DataStore.CoilInputs.WritePoints(12, new bool[] { true }); _dialogService.ShowDialog("OeeDialogPage", param, async r => { //dialog.Parameters.Add("OP_Id", OP_Id); //dialog.Parameters.Add("ExceptionCode", ExceptionCode); //dialog.Parameters.Add("ExceptionContent", ExceptionContent); //dialog.Parameters.Add("Duration", Duration); //dialog.Parameters.Add("ExceptionTime", ExceptionTime.ToString("yyyy-mm-dd HH:mm:ss")); //dialog.Parameters.Add("Mode", "手动调试模式"); //dialog.Parameters.Add("Reason", ExceptionReason); var param = r.Parameters; var opid = param.GetValue("OP_Id"); var exceptionCodeMessage = param.GetValue("ExceptionCode"); var exceptionCode = exceptionCodeMessage.Split('-')[0]; var exceptionContent = param.GetValue("ExceptionContent"); var duration = param.GetValue("Duration"); var exceptionTime = param.GetValue("ExceptionTime"); var mode = param.GetValue("Mode"); var reason = param.GetValue("Reason"); var oeeLogger = new OeeLogger { site = OeeConfig.Site, floor = OeeConfig.Floor, product = OeeConfig.Product, line = OeeConfig.Line, vendor = "Team", process = OeeConfig.Process, terminalId = OeeConfig.TerminalId, machineId = OeeConfig.MachineId, status = mode, op_id = opid, startTime = exceptionTime, ipaddr = OeeConfig.Ipaddr, macaddr = OeeConfig.Macaddr, warningCodeList = new Warningcodelist[2] }; oeeLogger.warningCodeList[0] = new Warningcodelist { warningCode = "400002", remark = exceptionContent }; oeeLogger.warningCodeList[1] = new Warningcodelist { warningCode = exceptionCode, remark = reason }; await UploadOeeAsync(oeeLogger); modbus.DataStore.CoilInputs.WritePoints(12, new bool[] { false }); }); })); } private async void ResettableTimer_Elapsed(object sender, ElapsedEventArgs e) { OeeLogger oeeLogger = new() { site = OeeConfig.Site, floor = OeeConfig.Floor, product = OeeConfig.Product, line = OeeConfig.Line, vendor = "Team", process = OeeConfig.Process, terminalId = OeeConfig.TerminalId, machineId = OeeConfig.MachineId, status = "Waiting for parts", op_id = Param.OPID, startTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ipaddr = OeeConfig.Ipaddr, macaddr = OeeConfig.Macaddr, warningCodeList = new Warningcodelist[1] }; oeeLogger.warningCodeList[0] = new Warningcodelist { warningCode = "100002", remark = "待料" }; await UploadOeeAsync(oeeLogger); } private void WaringUpdateLogChanged(Tuple tuple) { Debug.WriteLine(tuple.Item2); HandyControl.Controls.MessageBox.Show("test"); } private void OeeConfigChanged(OeeConfig config) { OeeConfig ??= new OeeConfig(); OeeConfig.Ip = config.Ip; OeeConfig.Port = config.Port; OeeConfig.WaitPartDuration = config.WaitPartDuration; OeeConfig.StopDuration = config.StopDuration; OeeConfig.Site = config.Site; OeeConfig.Floor = config.Floor; OeeConfig.Product = config.Product; OeeConfig.Line = config.Line; OeeConfig.Process = config.Process; OeeConfig.Vendor = config.Vendor; OeeConfig.TerminalId = config.TerminalId; OeeConfig.MachineId = config.MachineId; OeeConfig.Op_id = config.Op_id; OeeConfig.Ipaddr = config.Ipaddr; OeeConfig.Macaddr = config.Macaddr; OeeConfig.OeePath = config.OeePath; OeeConfig.UnUse = config.UnUse; } private async Task UploadOeeAsync(OeeLogger oeeLogger) { if (OeeConfig == null) { WriteLog("oee配置文件不存在请重新配置", LogType.Error); return; } using var client = _httpClientFactory.CreateClient(); //var url = _appSttings.Value.OeeUrl; var loggingURI = $"http://{OeeConfig.Ip}:{OeeConfig.Port}/device/upload/logging/v1"; try { var json = JsonConvert.SerializeObject(oeeLogger, Formatting.Indented); WriteToLocal(json); if (!OeeConfig.UnUse) { client.BaseAddress = new Uri(loggingURI); var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await client.PostAsync(loggingURI, content); WriteLog("oee上传成功"); var s = await response.Content.ReadAsStringAsync(); WriteLog($"状态码:{response.StatusCode}:" + s, LogType.Info); } else { WriteLog("oee上传屏蔽,未上传"); } } catch (Exception e) { WriteLog($"oee上传失败,{e.Message}", LogType.Error); } } private void WriteToLocal(string json) { var name = DateTime.Now.ToString("yyyy-mm-dd-HH-mm-ss") + "_oee" + ".json"; var path = Path.Combine(OeeConfig.OeePath, name); if (!Directory.Exists(OeeConfig.OeePath)) { WriteLog("oee路径不存在", LogType.Error); return; } using var stream = new StreamWriter(path); stream.Write(json); } private void ClearQueue(object sender, StateEventArgs e) { var length = _upLoadTraceModels.Count; for (int i = 0; i < length; i++) { _upLoadTraceModels.TryDequeue(out _); } } private void InitTraceData() { var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "param.json"); if (File.Exists(filePath)) { using var stream = new StreamReader(filePath); var json = stream.ReadToEnd(); Param = JsonConvert.DeserializeObject(json); } else { Param = new Param { station_id = "LkYC_BO7_2F_01_002_TRACE", line_id = "B07-2F-01", station_vendor = "Team", test = "Logo 30N Non-Destructive Test", OPID = "C10088888", DownLimit = "30", UpperLimit = "60" }; } } private void ScanMethodComplete(object sender, StateEventArgs e) { //var modbus = _modbusTcpSlaverService.GetModbusSlaveByIp(); //modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { false }); //WriteLog("复位扫码OK信号"); } private void SaveDataCompleted(object sender, StateEventArgs e) { var modbus = _modbusTcpSlaverService.GetModbusSlaveByIp(); modbus.DataStore.CoilInputs.WritePoints(10, new bool[] { false }); modbus.DataStore.CoilInputs.WritePoints(11, new bool[] { false }); } private void SaveImage(string barcode, string result) { var filePath = string.Empty; var fileName = barcode + "-" + Guid.NewGuid().ToString("N") + $"-{result}" + ".png"; string directory = ImagePath; Application.Current.Dispatcher.Invoke(new Action(() => { try { var finalPath = Path.Combine(directory, result); if (!Directory.Exists(finalPath)) { Directory.CreateDirectory(finalPath); } filePath = Path.Combine(finalPath, fileName); (PlotModel.PlotView as OxyPlot.Wpf.PlotView)?.SaveBitmap(filePath); } catch (Exception e) { WriteLog($"保存图片出现异常:{e.Message}"); } })); } public float ReadFloat(ushort startId) { var modbus = _modbusTcpSlaverService.GetModbusSlaveByIp(); var data = modbus.DataStore .HoldingRegisters.ReadPoints((ushort)(32 + startId), 2); var bytes1 = BitConverter.GetBytes(data[0]); var bytes2 = BitConverter.GetBytes(data[1]); var bytes = new List(); bytes.AddRange(bytes1); bytes.AddRange(bytes2); var value = BitConverter.ToSingle(bytes.ToArray(), 0); return value; } private async void ScanMethod(object sender, StateEventArgs e) { ErrorCode = string.Empty; var modbus = _modbusTcpSlaverService.GetModbusSlaveByIp(); if (!ScanConnected) { WriteLog($"扫码枪未连接,无法执行扫码动作"); ErrorCode = "扫码枪未连接,无法执行扫码动作"; modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { false }); return; } for (int i = 0; i < 3; i++) { try { WriteLog($"开始第{i + 1}次扫码"); NewBarcode = await _scanService.ReadAsync("start"); WriteLog($"第{i + 1}次扫码结果:{NewBarcode}"); if (NewBarcode != string.Empty && (NewBarcode.ToUpper()) != "NOREAD") { break; } } catch (Exception ex) { modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { false }); WriteLog($"扫码出现异常:{ex.Message}", LogType.Error, ex); ErrorCode = "扫码出现异常"; } } if (NewBarcode != string.Empty && NewBarcode.ToUpper() != "NOREAD") { // modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { true }); WriteLog($"扫码成功,SN:{NewBarcode}"); if (!_appSttings.Value.TraceDisable) { var result = await GetTraceAsync(NewBarcode); if (result) { modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { true }); WriteLog($"获取trace成功,SN:{NewBarcode}"); if (OkDuration <= 1000) { OkDuration = 4000; } await Task.Delay(OkDuration); modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { false }); } else { modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { false }); WriteLog($"trace卡关无法继续 "); ErrorCode = "trace卡关校验失败"; } } else { modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { true }); WriteLog($"卡关屏蔽中,直接放行:SN:{NewBarcode}"); } } else { ErrorCode = $"扫码没有读取正确的二维码"; modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { false }); WriteLog($"扫码失败:{NewBarcode}", LogType.Error); } } private async Task GetTraceAsync(string barcode) { using var client = _httpClientFactory.CreateClient(); try { var content = await client.GetStringAsync($"http://localhost:8765/v2/process_control?serial={barcode}&serial_type=part_id"); var data = JsonConvert.DeserializeObject(content); try { if (string.IsNullOrWhiteSpace(barcode)) { barcode = Guid.NewGuid().ToString("N"); } var fileName = "request_" + barcode + ".json"; var path = Path.Combine("logs", fileName); using var stream = new StreamWriter(path); await stream.WriteLineAsync(content); _logger.Information(content); } catch (Exception) { } if (!data.pass) { foreach (var item in data.processes) { if (!item.pass) { WriteLog($"{item.id}:{item.name}卡关fail!", LogType.Error); } } } return data.pass; } catch (HttpRequestException e) { WriteLog($"请求超时失败:{e.Message}", LogType.Error, e); return false; } } private async void SaveData(object sender, StateEventArgs e) { var modbus = _modbusTcpSlaverService.GetModbusSlaveByIp(); _upLoadTraceModels.TryDequeue(out var _updateModel); if (_updateModel == null) { WriteLog("_updateModel not init"); modbus.DataStore.CoilInputs.WritePoints(10, new bool[] { false }); modbus.DataStore.CoilInputs.WritePoints(11, new bool[] { true }); return; } var productTestForce = ReadFloat(74);//test WriteLog($"读取当前压检值:{productTestForce}"); modbus.DataStore.CoilInputs.WritePoints(10, new bool[] { false }); modbus.DataStore.CoilInputs.WritePoints(11, new bool[] { false }); var plcResult = modbus.DataStore.HoldingRegisters.ReadPoints(32, 1); var juge = plcResult[0] == 1 ? "pass" : "fail"; _updateModel.data.insight.test_attributes.uut_stop = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); _updateModel.data.insight.test_attributes.test_result = juge; _updateModel.data.insight.results[0].value = productTestForce.ToString("F2"); _updateModel.data.insight.results[0].result = juge; var runResult = plcResult[0] == 1 ? RunResultState.OK : RunResultState.NG; _eventAggregator.GetEvent().Publish(runResult); WriteLog("开始保存图片"); SaveImage(_updateModel.serials.part_id, juge); WriteLog("保存图片完成"); await _repository.AddAsync(new TestResult { Id = Guid.NewGuid(), Barcode = _updateModel.serials.part_id, Datetime = DateTime.Now, Result = productTestForce }); WriteLog("开始保存csv"); try { var dateName = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss"); var fileName = dateName + "-" + _updateModel.serials.part_id + ".csv"; var filePath = Path.Combine(CSVPath, fileName); var exsit = File.Exists(filePath); using var streamWriter = new StreamWriter(filePath, false, Encoding.UTF8); if (!exsit) { var header = "SERIAL_NUMBER,MEASURE_DATE,MEASURE_TIME,STATION,OP_NAME,AIM_VENDOR,AIM_NAME,AIM_UNIQUE," + "INSPECTION_PROGRAM_NAME,PROJECT,PART,PROCESS,BUILDS,SHIFT_D_N,CAVITY,RESULT,BIN_MP,COLOR,TEMPERATURE," + "HUMIDITY,PRODUCT_TEMP,COLOR_BANKING,KB_LAYOUT,DATA_BIN," + "DATA1,DATA2,DATA3,DATA4,DATA5,DATA6,DATA7,DATA8,DATA9,DATA10,DATA11,DATA12,DATA13," + "DATA14,DATA15,DATA16,DATA17,DATA18,DATA19,DATA20,DATA21,DATA22,DATA23,DATA24,DATA25,DATA26," + "DATA27,DATA28,DATA29,DATA30,DATA31,DATA32,DATA33,DATA34,DATA35,DATA36,DATA37,DATA38,DATA39," + "DATA40,DATA41,DATA42,DATA43,DATA44,DATA45,DATA46,DATA47,DATA48,DATA49,DATA50,DATA51,DATA52," + "DATA53,DATA54,DATA55,DATA56,DATA57,DATA58,DATA59,DATA60,DATA61,DATA62,DATA63,DATA64,DATA65," + "DATA66,DATA67,DATA68,DATA69,DATA70,DATA71,DATA72,DATA73,DATA74,DATA75," + "DATA76,DATA77,DATA78,DATA79,DATA80,DATA81,DATA82,DATA83,DATA84,DATA85,DATA86,DATA87,DATA88," + "DATA89,DATA90,DATA91,DATA92,DATA93,DATA94,DATA95,DATA96,DATA97,DATA98,DATA99,DATA100"; await streamWriter.WriteLineAsync(header); await streamWriter.FlushAsync(); } var value = $"SPC_G1/{_updateModel.data.insight.results[0].value}/H{Param.UpperLimit}/L{Param.DownLimit}"; var data = $"{_updateModel.serials.part_id},{DateTime.Now:yyyy/MM/dd}" + $",{DateTime.Now:HH:mm:ss}" + $",logo-test,{Param.OPID},{_updateModel.data.insight.uut_attributes.station_vendor}," + $"{_appSttings.Value.AimName},{_appSttings.Value.AIM_UNIQUE},{_appSttings.Value.INSPECTION_PROGRAM_NAME}," + $"{_appSttings.Value.Project},{_appSttings.Value.Part},{_appSttings.Value.Process},{_appSttings.Value.Builds},,," + $"{_updateModel.data.insight.test_attributes.test_result},,color,,,,,,,{value}"; var list = new List(); for (int i = 0; i < 99; i++) { data += ","; } await streamWriter.WriteLineAsync(data); await streamWriter.FlushAsync(); streamWriter.Close(); WriteLog("保存csv完成"); } catch (Exception ex) { WriteLog($"保存csv失败:{ex}"); } WriteLog("开始上传数据"); if (!_appSttings.Value.UnUseUpload) { var json = JsonConvert.SerializeObject(_updateModel, Formatting.Indented); try { var barcode = _updateModel.serials.part_id; if (string.IsNullOrWhiteSpace(barcode)) { barcode = Guid.NewGuid().ToString("N"); } var fileName = "upload_" + barcode + ".json"; var path = Path.Combine("logs", fileName); using var stream = new StreamWriter(path); await stream.WriteLineAsync(json); } catch (Exception) { } _logger.Information("正在上传数据:" + json); var stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); var ret = await UploadAsync(json); if (stopWatch.ElapsedMilliseconds > 2000) { _upLoadSlowTime++; WriteLog($"连续{_upLoadSlowTime}上传trace数据大于2s", LogType.Warning); if (_upLoadSlowTime >= 5) { ErrorCode = "连续5次上传数据缓慢,请检查网络连接"; } } else { _upLoadSlowTime = 0; } if (ret) { modbus.DataStore.CoilInputs.WritePoints(10, new bool[] { true }); modbus.DataStore.CoilInputs.WritePoints(11, new bool[] { false }); } else { modbus.DataStore.CoilInputs.WritePoints(10, new bool[] { false }); modbus.DataStore.CoilInputs.WritePoints(11, new bool[] { true }); } } else { modbus.DataStore.CoilInputs.WritePoints(10, new bool[] { true }); modbus.DataStore.CoilInputs.WritePoints(11, new bool[] { false }); } OeeLogger oeeLogger = new() { site = OeeConfig.Site, floor = OeeConfig.Floor, product = OeeConfig.Product, line = OeeConfig.Line, vendor = "Team", process = OeeConfig.Process, terminalId = OeeConfig.TerminalId, machineId = OeeConfig.MachineId, status = "running", op_id = Param.OPID, startTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ipaddr = OeeConfig.Ipaddr, macaddr = OeeConfig.Macaddr, warningCodeList = new Warningcodelist[1] }; oeeLogger.warningCodeList[0] = new Warningcodelist { warningCode = "100001", remark = "压力检测完成" }; await UploadOeeAsync(oeeLogger); WriteLog("上传数据完成"); } //UpLoadTraceModel _updateModel; private async Task UploadAsync(string data) { using var client = _httpClientFactory.CreateClient(); var stringContent = new StringContent(data); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); var statisticsLog = new StatisticsLog { Id = Guid.NewGuid(), Timestamp = DateTime.Now, RequstType = RequstType.Post }; try { var responseMessage = await client.PostAsync("http://localhost:8765/v2/logs", stringContent); if (responseMessage.StatusCode == System.Net.HttpStatusCode.OK) { WriteLog($"上传数据成功"); statisticsLog.TraceState = TraceState.PostOK; var s = await responseMessage.Content.ReadAsStringAsync(); WriteLog($"response:{s}"); statisticsLog.RequestCode = (int)responseMessage.StatusCode; return true; } else { statisticsLog.TraceState = TraceState.PostNG; WriteLog($"上传失败:状态码{responseMessage.StatusCode}," + $"请求uri:{responseMessage.RequestMessage.RequestUri}"); statisticsLog.RequestCode = (int)responseMessage.StatusCode; var s = await responseMessage.Content.ReadAsStringAsync(); WriteLog($"response:{s}"); return false; } } catch (HttpRequestException e) { statisticsLog.TraceState = TraceState.PostNG; statisticsLog.RequestCode = 600; WriteLog($"上传失败:{e.Message}"); return false; } finally { await _repository.AddAsync(statisticsLog); } } private void StopReadForceMethod(object sender, StateEventArgs e) { WriteLog("停止读取压力传感器数值"); _start = false; } private void ModbusTcpSlaverService_CoilDiscretesHandler(object sender, LogoForceTestApp.Services.Interfaces.Events.StorageEventArgs e) { } private void SetupModel() { PlotModel = new PlotModel(); PlotModel.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Minimum = 0, Maximum = 80 }); PlotModel.Series.Add(new LineSeries { LineStyle = LineStyle.Solid }); RaisePropertyChanged(nameof(PlotModel)); } private void Clear() { var s = (LineSeries)PlotModel.Series[0]; s.Points.Clear(); } private void Update(DataPoint dataPoint) { var s = (LineSeries)PlotModel.Series[0]; s.Points.Add(dataPoint); } #endregion } }