Jelajahi Sumber

1,增加扫码枪功能

刘锦天 6 bulan lalu
induk
melakukan
2aea4812f2

+ 2 - 0
TeamAAS-VM/Core/FilePath.cs

@@ -61,5 +61,7 @@ namespace TeamAAS_VP.Core
         /// 后台脚本存放文件夹
         /// </summary>
         public static string BackgroundScriptPath = "..//Background Script";
+
+        public static string ScanRS232ConfigPath = "..//Config//ScanRS232Config.cfg";
     }
 }

+ 291 - 193
TeamAAS-VM/Core/Management.cs

@@ -58,6 +58,7 @@ using TeamAAS_VP.Services;
 using TeamAAS_VP.ViewModels;
 using TeamAAS_VP.ViewModels.Home;
 using TouchSocket.Core;
+using TouchSocket.SerialPorts;
 using TouchSocket.Sockets;
 using static MaterialDesignThemes.Wpf.Theme.ToolBar;
 using static Org.BouncyCastle.Math.EC.ECCurve;
@@ -104,8 +105,20 @@ namespace TeamAAS_VP.Core
         private ObservableCollection<ShowRender> _Renders;
         private double _CTtime;
         public int ResultDataCount;
+        // 扫码结果
+        private string ScanValue = "";
+        // 扫码完成事件
+        private readonly ManualResetEventSlim _scanDoneEvent = new ManualResetEventSlim(false);
 
 
+        private SerialPortClient _Scan_Client;
+
+        public SerialPortClient Scan_Client
+        {
+            get { return _Scan_Client; }
+            set { _Scan_Client = value; }
+        }
+
         private bool _ShowMes_Query;
         /// <summary>
         /// 显示查询结果
@@ -699,6 +712,67 @@ namespace TeamAAS_VP.Core
                 LogHelper.WriteLogError("连接电批时出错!", ex);
             }
         }
+
+        public async Task InitScan()
+        {
+            if (!File.Exists(FilePath.ScanRS232ConfigPath))
+            {
+                var scan = new ScanRs232ConfigModel();
+                FileHelper.WriteJsonFile(scan, FilePath.ScanRS232ConfigPath);
+            }
+
+            try
+            {
+                var res = FileHelper.ReadJsonFile<ScanRs232ConfigModel>(FilePath.ScanRS232ConfigPath);
+                if (res != null)
+                {
+                    Scan_Client = new SerialPortClient();
+                    Scan_Client.Connecting = (client1, e) => { return EasyTask.CompletedTask; };//即将连接到端口
+                    Scan_Client.Connected = (client1, e) => { return EasyTask.CompletedTask; };//成功连接到端口
+                    Scan_Client.Closing = (client1, e) => { return EasyTask.CompletedTask; };//即将从端口断开连接。此处仅主动断开才有效。
+                    Scan_Client.Closed = (client1, e) => { return EasyTask.CompletedTask; };//从端口断开连接,当连接不成功时不会触发。
+                    Scan_Client.Received = async (c, e) =>
+                    {
+                        //await Console.Out.WriteLineAsync(Encoding.UTF8.GetString(e.ByteBlock.Buffer));
+                        await Console.Out.WriteLineAsync(e.ByteBlock.Span.ToString(Encoding.ASCII));
+                    };
+                    Scan_Client.Received = Scan_DataReceived;
+
+                    await Scan_Client.SetupAsync(new TouchSocketConfig()
+                         .SetSerialPortOption(new SerialPortOption()
+                         {
+                             BaudRate = res.BaudRate,//波特率
+                             DataBits = res.DataBits,//数据位
+                             Parity = res.Parity,//校验位
+                             PortName = res.PortName,//COM
+                             StopBits = res.StopBits//停止位
+                         })
+                         .SetSerialDataHandlingAdapter(() => new PeriodPackageAdapter() { CacheTimeout = TimeSpan.FromMilliseconds(100) })
+                         );
+
+                    await Scan_Client.ConnectAsync();
+
+                    if (Scan_Client.Online)
+                    {
+                        SendTaskMessage(Lang.扫码机已连接, MessageLevel.Debug);
+                    }
+                    else
+                    {
+                        SendTaskMessage(Lang.扫码机未连接, MessageLevel.Debug);
+                    }
+                }
+                else
+                {
+                    SendTaskMessage(Lang.请设置扫码机串口, MessageLevel.Error);
+                }
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("初始化扫码枪时出错!", ex);
+                SendTaskMessage(Lang.初始化扫码枪时出错 + ex.Message, MessageLevel.Error);
+            }
+
+        }
         #endregion
 
         #region 机器人指令执行
@@ -1511,44 +1585,202 @@ namespace TeamAAS_VP.Core
                             var procIds = new List<Guid>();
                             try
                             {
-                                if (targetPoint.CameraProcedureId1 != Guid.Empty) procIds.Add(targetPoint.CameraProcedureId1);
+                                if (targetPoint.CameraProcedureId1 != Guid.Empty && !procIds.Contains(targetPoint.CameraProcedureId1)) procIds.Add(targetPoint.CameraProcedureId1);
                             }
                             catch { }
                             try
                             {
-                                if (targetPoint.CameraProcedureId2 != Guid.Empty) procIds.Add(targetPoint.CameraProcedureId2);
+                                if (targetPoint.CameraProcedureId2 != Guid.Empty && !procIds.Contains(targetPoint.CameraProcedureId2)) procIds.Add(targetPoint.CameraProcedureId2);
                             }
                             catch { }
                             try
                             {
-                                if (targetPoint.CameraProcedureId3 != Guid.Empty) procIds.Add(targetPoint.CameraProcedureId3);
+                                if (targetPoint.CameraProcedureId3 != Guid.Empty && !procIds.Contains(targetPoint.CameraProcedureId3)) procIds.Add(targetPoint.CameraProcedureId3);
                             }
                             catch { }
                             try
                             {
-                                if (targetPoint.CameraProcedureId4 != Guid.Empty) procIds.Add(targetPoint.CameraProcedureId4);
+                                if (targetPoint.CameraProcedureId4 != Guid.Empty && !procIds.Contains(targetPoint.CameraProcedureId4)) procIds.Add(targetPoint.CameraProcedureId4);
                             }
                             catch { }
                             try
                             {
-                                if (targetPoint.CameraProcedureId5 != Guid.Empty) procIds.Add(targetPoint.CameraProcedureId5);
+                                if (targetPoint.CameraProcedureId5 != Guid.Empty && !procIds.Contains(targetPoint.CameraProcedureId5)) procIds.Add(targetPoint.CameraProcedureId5);
                             }
                             catch { }
                             try
                             {
-                                if (targetPoint.CameraProcedureId6 != Guid.Empty) procIds.Add(targetPoint.CameraProcedureId6);
+                                if (targetPoint.CameraProcedureId6 != Guid.Empty && !procIds.Contains(targetPoint.CameraProcedureId6)) procIds.Add(targetPoint.CameraProcedureId6);
                             }
                             catch { }
                             try
                             {
-                                if (targetPoint.CameraProcedureId7 != Guid.Empty) procIds.Add(targetPoint.CameraProcedureId7);
+                                if (targetPoint.CameraProcedureId7 != Guid.Empty && !procIds.Contains(targetPoint.CameraProcedureId7)) procIds.Add(targetPoint.CameraProcedureId7);
                             }
                             catch { }
                             try
                             {
-                                if (targetPoint.CameraProcedureId8 != Guid.Empty) procIds.Add(targetPoint.CameraProcedureId8);
+                                if (targetPoint.CameraProcedureId8 != Guid.Empty && !procIds.Contains(targetPoint.CameraProcedureId8)) procIds.Add(targetPoint.CameraProcedureId8);
                             }
                             catch { }
+                            var sysConfig = _configService.GetSystemConfiguration();
+                            if (sysConfig.ScannerUse == true && cameraIndex == 1 && sysConfig.CodeUse2 == true)
+                            {
+                                ScanValue = "";
+                                _scanDoneEvent.Reset(); // 重要:先关门
+
+                                await Scan_Client.SendAsync("T\r\n");
+
+                                // 等待扫码结果,最多 3 秒
+                                bool scanOk = await Task.Run(() => _scanDoneEvent.Wait(3000));
+
+                                if (!scanOk || ScanValue.IsNullOrWhiteSpace())
+                                {
+                                    SendTaskMessage("二维码拍照失败或超时", MessageLevel.Alarm);
+                                    await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (short)3);
+                                    return;
+                                }
+
+                                code = ScanValue;
+                                SendTaskMessage($"扫码成功,SN:{code}", MessageLevel.Info);
+                                //这里缺少从MES获取产品配方的内容,需要补充
+                                _LastMesCheckTime[0] = (await _mesService.GetServerTimeAsync(code, 2)).Now;
+                                //_LastMesCheckTime[1] = DateTime.Now;
+                                LogHelper.WriteLogMes($"【mes开始QUERY】");
+                                SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
+                                (bool isSuccess, string response) = await _mesService.StationGetAsync(code, "", 2);//询问mes
+
+                                if (isSuccess)
+                                {
+                                    //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
+
+                                    LogHelper.WriteLogMes($"询问mes成功");
+                                    SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
+                                    if (response != "MES功能未启用!")
+                                    {
+                                        string[] items = response.Split('\n');
+                                        if (items[3].Contains("sn="))
+                                        {
+                                            ProductMainSN = items[3].Replace("sn=", "");
+                                            _productService.CurrentProductCode = ProductMainSN;
+                                        }
+                                        SendTaskMessage($"产品主sn:{ProductMainSN}", MessageLevel.Info);
+                                        if (items[5].Contains("wo="))
+                                        {
+                                            wo = items[5].Replace("wo=", "");
+                                        }
+                                        SendTaskMessage($"产品wo:{wo}", MessageLevel.Info);
+                                    }
+                                    LogHelper.WriteLogMes($"【mes结束QUERY】");
+                                    SendTaskMessage($"mes结束QUERY", MessageLevel.Info);
+                                    await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
+                                    return;
+                                }
+                                else
+                                {
+                                    //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
+
+                                    await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
+
+                                    LogHelper.WriteLogMes($"询问mes失败");
+                                    SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
+                                    return;
+                                }
+                            }
+
+                            if (sysConfig.ScannerUse == true && cameraIndex == 1 && sysConfig.CodeUse == true)
+                            {
+                                ScanValue = "";
+                                _scanDoneEvent.Reset(); // 重要:先关门
+
+                                await Scan_Client.SendAsync("T\r\n");
+
+                                // 等待扫码结果,最多 3 秒
+                                bool scanOk = await Task.Run(() => _scanDoneEvent.Wait(3000));
+
+                                if (!scanOk || ScanValue.IsNullOrWhiteSpace())
+                                {
+                                    SendTaskMessage("二维码拍照失败或超时", MessageLevel.Alarm);
+                                    await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (short)3);
+                                    return;
+                                }
+
+                                code = ScanValue;
+                                SendTaskMessage($"扫码成功,SN:{code}", MessageLevel.Info);
+                                //这里缺少从MES获取产品配方的内容,需要补充
+                                _LastMesCheckTime[0] = (await _mesService.GetServerTimeAsync(code, 2)).Now;
+                                LogHelper.WriteLogMes($"【mes开始QUERY】");
+                                SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
+                                //(bool isSuccess, string response) = await _mesService.StationGetAsync(code, "", 2);//询问mes
+                                (bool isSuccess, string response) = await _mesService.StationGetExAsync(code, "", 2);//基于电池的SN获取产品SN,询问mes
+                                if (isSuccess)
+                                {
+                                    //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
+
+
+                                    string ProductMainSN_Temp = "";
+                                    LogHelper.WriteLogMes($"询问mes成功");
+                                    SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
+
+                                    if (response != "MES功能未启用!")
+                                    {
+                                        string[] item = response.Split('\n');
+                                        if (item[2].Contains("sn="))
+                                        {
+                                            ProductMainSN_Temp = item[2].Replace("sn=", "");
+                                            SendTaskMessage($"sn:{ProductMainSN_Temp}", MessageLevel.Info);
+                                        }
+                                    }
+                                    LogHelper.WriteLogMes($"询问mes成功");
+                                    SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
+
+                                    //20260214,特别版(电池组装)
+                                    (bool isSuccess2, string response2) = await _mesService.StationGetAsync(ProductMainSN_Temp, "", 2);//询问mes
+                                    if (isSuccess2)
+                                    {
+                                        LogHelper.WriteLogMes($"询问mes成功");
+                                        SendTaskMessage($"询问mes成功:{response2}", MessageLevel.Debug);
+
+                                        if (response2 != "MES功能未启用!")
+                                        {
+                                            string[] item = response2.Split('\n');
+                                            if (item[3].Contains("sn="))
+                                            {
+                                                ProductMainSN = item[3].Replace("sn=", "");
+                                                _productService.CurrentProductCode = ProductMainSN;
+                                                SendTaskMessage($"产品主sn:{ProductMainSN}", MessageLevel.Info);
+                                            }
+                                            if (item[5].Contains("wo="))
+                                            {
+                                                wo = item[5].Replace("wo=", "");
+                                                SendTaskMessage($"产品主wo:{wo}", MessageLevel.Info);
+                                            }
+                                        }
+                                        LogHelper.WriteLogMes($"第二次询问mes成功");
+                                        SendTaskMessage($"第二次询问mes成功:{response2}", MessageLevel.Debug);
+
+                                        await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
+                                    }
+                                    else
+                                    {
+                                        LogHelper.WriteLogMes($"第二次询问mes失败");
+                                        SendTaskMessage($"第二次询问mes失败:{response2}", MessageLevel.Error);
+
+                                        await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
+                                    }
+                                }
+                                else
+                                {
+                                    //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
+
+                                    await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
+
+                                    LogHelper.WriteLogMes($"询问mes失败");
+                                    SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
+                                }
+                                return;
+                            }
+
 
                             if (procIds.Count == 0)
                             {
@@ -1579,7 +1811,7 @@ namespace TeamAAS_VP.Core
                                 });
                             }
 
-                            var sysConfig = _configService.GetSystemConfiguration();
+                            
                             if (sysConfig.CodeUse==true && cameraIndex == 1)
                             {
                                 var cts = new CancellationTokenSource();
@@ -1616,113 +1848,11 @@ namespace TeamAAS_VP.Core
                                 {
                                     await _remoteCommandService.SetLightBeforePhoto(selectedProcedure);
                                 }
-                                if(sysConfig.ScannerUse==false)
-                                {
-                                    var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint2(selectedProcedure, null, null, cts.Token);
-
-                                    if (visionResult.IsSucceed)
-                                    {
-                                        code = visionResult.X.ToUpper();
-
-                                        SendTaskMessage($"扫码成功,SN:{code}", MessageLevel.Info);
-                                        //这里缺少从MES获取产品配方的内容,需要补充
-                                        _LastMesCheckTime[0] = (await _mesService.GetServerTimeAsync(code, 2)).Now;
-                                        LogHelper.WriteLogMes($"【mes开始QUERY】");
-                                        SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
-                                        //(bool isSuccess, string response) = await _mesService.StationGetAsync(code, "", 2);//询问mes
-                                        (bool isSuccess, string response) = await _mesService.StationGetExAsync(code, "", 2);//基于电池的SN获取产品SN,询问mes
-                                        if (isSuccess)
-                                        {
-                                            //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
-
-
-                                            string ProductMainSN_Temp = "";
-                                            LogHelper.WriteLogMes($"询问mes成功");
-                                            SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
-
-                                            if (response != "MES功能未启用!")
-                                            {
-                                                string[] item = response.Split('\n');
-                                                if (item[2].Contains("sn="))
-                                                {
-                                                    ProductMainSN_Temp = item[2].Replace("sn=", "");
-                                                    SendTaskMessage($"sn:{ProductMainSN_Temp}", MessageLevel.Info);
-                                                }
-                                            }
-                                            LogHelper.WriteLogMes($"询问mes成功");
-                                            SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
+                                var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint2(selectedProcedure, null, null, cts.Token);
 
-                                            //20260214,特别版(电池组装)
-                                            (bool isSuccess2, string response2) = await _mesService.StationGetAsync(ProductMainSN_Temp, "", 2);//询问mes
-                                            if (isSuccess2)
-                                            {
-                                                LogHelper.WriteLogMes($"询问mes成功");
-                                                SendTaskMessage($"询问mes成功:{response2}", MessageLevel.Debug);
-
-                                                if (response2 != "MES功能未启用!")
-                                                {
-                                                    string[] item = response2.Split('\n');
-                                                    if (item[3].Contains("sn="))
-                                                    {
-                                                        ProductMainSN = item[3].Replace("sn=", "");
-                                                        _productService.CurrentProductCode = ProductMainSN;
-                                                        SendTaskMessage($"产品主sn:{ProductMainSN}", MessageLevel.Info);
-                                                    }
-                                                    if (item[5].Contains("wo="))
-                                                    {
-                                                        wo = item[5].Replace("wo=", "");
-                                                        SendTaskMessage($"产品主wo:{wo}", MessageLevel.Info);
-                                                    }
-                                                }
-                                                LogHelper.WriteLogMes($"第二次询问mes成功");
-                                                SendTaskMessage($"第二次询问mes成功:{response2}", MessageLevel.Debug);
-
-                                                await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
-                                            }
-                                            else
-                                            {
-                                                LogHelper.WriteLogMes($"第二次询问mes失败");
-                                                SendTaskMessage($"第二次询问mes失败:{response2}", MessageLevel.Error);
-
-                                                await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
-                                            }
-                                        }
-                                        else
-                                        {
-                                            //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
-
-                                            await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
-
-                                            LogHelper.WriteLogMes($"询问mes失败");
-                                            SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
-                                        }
-                                    }
-                                    else
-                                    {
-                                        SendTaskMessage($"扫码失败", MessageLevel.Alarm);
-                                        await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
-                                    }
-                                }
-                                else
+                                if (visionResult.IsSucceed)
                                 {
-
-                                    // 发T1并等待回包:回包是 SN 或 NG
-                                    var reply = await ScanT1Async(timeoutMs: 3000);
-                                    if (string.IsNullOrWhiteSpace(reply))
-                                    {
-                                        SendTaskMessage("扫码枪回包超时/空数据", MessageLevel.Alarm);
-                                        await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (short)3);
-                                        return;
-                                    }
-
-                                    if (string.Equals(reply, "NG", StringComparison.OrdinalIgnoreCase))
-                                    {
-                                        SendTaskMessage("扫码枪返回NG", MessageLevel.Alarm);
-                                        await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (short)3);
-                                        return;
-                                    }
-
-                                    code = reply.ToUpperInvariant();
+                                    code = visionResult.X.ToUpper();
 
                                     SendTaskMessage($"扫码成功,SN:{code}", MessageLevel.Info);
                                     //这里缺少从MES获取产品配方的内容,需要补充
@@ -1797,9 +1927,12 @@ namespace TeamAAS_VP.Core
                                         SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
                                     }
                                 }
-
-
-                                    return;
+                                else
+                                {
+                                    SendTaskMessage($"扫码失败", MessageLevel.Alarm);
+                                    await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
+                                }
+                                return;
                             }
 
                             if (sysConfig.CodeUse2 == true && cameraIndex == 1)
@@ -1839,82 +1972,11 @@ namespace TeamAAS_VP.Core
                                 {
                                     await _remoteCommandService.SetLightBeforePhoto(selectedProcedure);
                                 }
-                                if(sysConfig.ScannerUse==false)
-                                {
-                                    var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint2(selectedProcedure, null, null, ctsAll.Token);
-                                    if (visionResult.IsSucceed)
-                                    {
-                                        code = visionResult.X;
-                                        ProductMainSN = visionResult.X;
-                                        SendTaskMessage($"扫码成功,SN:{code}", MessageLevel.Info);
-                                        //这里缺少从MES获取产品配方的内容,需要补充
-                                        _LastMesCheckTime[0] = (await _mesService.GetServerTimeAsync(code, 2)).Now;
-                                        //_LastMesCheckTime[1] = DateTime.Now;
-                                        LogHelper.WriteLogMes($"【mes开始QUERY】");
-                                        SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
-                                        (bool isSuccess, string response) = await _mesService.StationGetAsync(code, "", 2);//询问mes
-
-                                        if (isSuccess)
-                                        {
-                                            //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
-
-                                            LogHelper.WriteLogMes($"询问mes成功");
-                                            SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
-                                            if (response != "MES功能未启用!")
-                                            {
-                                                string[] items = response.Split('\n');
-                                                if (items[3].Contains("sn="))
-                                                {
-                                                    ProductMainSN = items[3].Replace("sn=", "");
-                                                    _productService.CurrentProductCode = ProductMainSN;
-                                                }
-                                                SendTaskMessage($"产品主sn:{ProductMainSN}", MessageLevel.Info);
-                                                if (items[5].Contains("wo="))
-                                                {
-                                                    wo = items[5].Replace("wo=", "");
-                                                }
-                                                SendTaskMessage($"产品wo:{wo}", MessageLevel.Info);
-                                            }
-                                            LogHelper.WriteLogMes($"【mes结束QUERY】");
-                                            SendTaskMessage($"mes结束QUERY", MessageLevel.Info);
-                                            await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
-                                            return;
-                                        }
-                                        else
-                                        {
-                                            //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
-
-                                            await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
-
-                                            LogHelper.WriteLogMes($"询问mes失败");
-                                            SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
-                                        }
-                                    }
-                                    else
-                                    {
-                                        SendTaskMessage($"扫码失败", MessageLevel.Alarm);
-                                        await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
-                                    }
-                                }
-                                else
+                                var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint2(selectedProcedure, null, null, ctsAll.Token);
+                                if (visionResult.IsSucceed)
                                 {
-                                    // 发T1并等待回包:回包是 SN 或 NG
-                                    var reply = await ScanT1Async(timeoutMs: 3000);
-                                    if (string.IsNullOrWhiteSpace(reply))
-                                    {
-                                        SendTaskMessage("扫码枪回包超时/空数据", MessageLevel.Alarm);
-                                        await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (short)3);
-                                        return;
-                                    }
-
-                                    if (string.Equals(reply, "NG", StringComparison.OrdinalIgnoreCase))
-                                    {
-                                        SendTaskMessage("扫码枪返回NG", MessageLevel.Alarm);
-                                        await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (short)3);
-                                        return;
-                                    }
-
-                                    code = reply.ToUpperInvariant();
+                                    code = visionResult.X;
+                                    ProductMainSN = visionResult.X;
                                     SendTaskMessage($"扫码成功,SN:{code}", MessageLevel.Info);
                                     //这里缺少从MES获取产品配方的内容,需要补充
                                     _LastMesCheckTime[0] = (await _mesService.GetServerTimeAsync(code, 2)).Now;
@@ -1959,6 +2021,11 @@ namespace TeamAAS_VP.Core
                                         SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
                                     }
                                 }
+                                else
+                                {
+                                    SendTaskMessage($"扫码失败", MessageLevel.Alarm);
+                                    await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
+                                }
                                 return;
                             }
                             foreach (var prcId in procIds)
@@ -2077,7 +2144,11 @@ namespace TeamAAS_VP.Core
                                 {
                                     //这里缺少从MES获取产品配方的内容,需要补充
                                     _LastMesCheckTime[i] = (await _mesService.GetServerTimeAsync(code, 2)).Now;
-
+                                    if (homeview.IsNoCode == false)
+                                    {
+                                        var device = _configService.GetDeviceInfo();
+                                        code = device.XnSN;
+                                    }
                                     LogHelper.WriteLogMes($"【mes开始QUERY】");
                                     SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
                                     ShowMes_Query = false;
@@ -3024,5 +3095,32 @@ namespace TeamAAS_VP.Core
             _defaultScannerId = scannerInfo == null ? Guid.Empty : scannerInfo.Id;
             return _defaultScannerId;
         }
+
+        private async Task Scan_DataReceived(ISerialPortClient client, ReceivedDataEventArgs e)
+        {
+            try
+            {
+                // 串口名
+                string portName = client.MainSerialPort.PortName;
+                // 注意:DataReceived 可能一次收到多段/包含回车换行
+                string data = e.ByteBlock.Span.ToString(Encoding.ASCII);
+                await Console.Out.WriteLineAsync(data);
+                // 取第一段(到 \r 之前),并去掉首尾空白
+                string response = data.Split('\r')[0].Trim();
+                // 过滤:空数据不要当成一次有效扫码
+                if (string.IsNullOrWhiteSpace(response))
+                    return;
+                SendTaskMessage($"扫码机:{portName} Receive:{response}", MessageLevel.Info);
+                // 写入结果
+                ScanValue = response;
+                // 通知等待方继续执行(PLC 逻辑里 Wait 的地方)
+                _scanDoneEvent.Set();
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("扫码枪接收信息时出错!", ex);
+                SendTaskMessage(Lang.扫码枪接收信息时出错 + ex.Message, MessageLevel.Error);
+            }
+        }
     }
 }

+ 9 - 0
TeamAAS-VM/Models/DeviceInfo.cs

@@ -72,6 +72,13 @@ namespace TeamAAS_VP.Models
         /// </summary>
         public string comp { get => _comp; set => SetProperty(ref _comp, value); }
 
+        private string _XnSN;
+        /// <summary>
+        /// 虚拟SN
+        /// 
+        /// </summary>
+        public string XnSN { get => _XnSN; set => SetProperty(ref _XnSN, value); }
+
         private bool _saveCsv;
         /// <summary>
         /// 是否保存CSV文件,默认不保存
@@ -107,6 +114,7 @@ namespace TeamAAS_VP.Models
             comp = string.Empty;
             MesUrl = string.Empty;
             EnableMES = false;
+            XnSN = string.Empty;
         }
 
         public DeviceInfo Copy()
@@ -123,6 +131,7 @@ namespace TeamAAS_VP.Models
                 comp = this.comp,
                 MesUrl = this.MesUrl,
                 EnableMES = this.EnableMES,
+                XnSN=this.XnSN,
                 SaveCsv = this.SaveCsv,
                 SaveCsvPath = this.SaveCsvPath,
                 EnableDoubleMes = this.EnableDoubleMes,

+ 44 - 0
TeamAAS-VM/Models/ScanRs232ConfigModel.cs

@@ -0,0 +1,44 @@
+using Prism.Mvvm;
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TeamAAS_VP.Models
+{
+    public class ScanRs232ConfigModel : BindableBase
+    {
+        private string _PortName = "COM9";
+        public string PortName
+        {
+            get { return _PortName; }
+            set { SetProperty(ref _PortName, value); }
+        }
+        private int _BaudRate = 9600;
+        public int BaudRate
+        {
+            get { return _BaudRate; }
+            set { SetProperty(ref _BaudRate, value); }
+        }
+        private Parity _Parity = Parity.None;
+        public Parity Parity
+        {
+            get { return _Parity; }
+            set { SetProperty(ref _Parity, value); }
+        }
+        private StopBits _StopBits = StopBits.One;
+        public StopBits StopBits
+        {
+            get { return _StopBits; }
+            set { SetProperty(ref _StopBits, value); }
+        }
+        private int _DataBits = 8;
+        public int DataBits
+        {
+            get { return _DataBits; }
+            set { SetProperty(ref _DataBits, value); }
+        }
+    }
+}

+ 45 - 0
TeamAAS-VM/Resources/Languages/Lang.Designer.cs

@@ -1563,6 +1563,15 @@ namespace TeamAAS_VP.Resources.Languages {
             }
         }
         
+        /// <summary>
+        ///   查找类似 初始化扫码枪时出错 的本地化字符串。
+        /// </summary>
+        public static string 初始化扫码枪时出错 {
+            get {
+                return ResourceManager.GetString("初始化扫码枪时出错", resourceCulture);
+            }
+        }
+        
         /// <summary>
         ///   查找类似 初始化数据库 的本地化字符串。
         /// </summary>
@@ -2904,6 +2913,24 @@ namespace TeamAAS_VP.Resources.Languages {
             }
         }
         
+        /// <summary>
+        ///   查找类似 扫码机已连接 的本地化字符串。
+        /// </summary>
+        public static string 扫码机已连接 {
+            get {
+                return ResourceManager.GetString("扫码机已连接", resourceCulture);
+            }
+        }
+        
+        /// <summary>
+        ///   查找类似 扫码机未连接 的本地化字符串。
+        /// </summary>
+        public static string 扫码机未连接 {
+            get {
+                return ResourceManager.GetString("扫码机未连接", resourceCulture);
+            }
+        }
+        
         /// <summary>
         ///   查找类似 扫码枪 的本地化字符串。
         /// </summary>
@@ -2922,6 +2949,15 @@ namespace TeamAAS_VP.Resources.Languages {
             }
         }
         
+        /// <summary>
+        ///   查找类似 扫码枪接收信息时出错 的本地化字符串。
+        /// </summary>
+        public static string 扫码枪接收信息时出错 {
+            get {
+                return ResourceManager.GetString("扫码枪接收信息时出错", resourceCulture);
+            }
+        }
+        
         /// <summary>
         ///   查找类似 抛料数 的本地化字符串。
         /// </summary>
@@ -5289,6 +5325,15 @@ namespace TeamAAS_VP.Resources.Languages {
             }
         }
         
+        /// <summary>
+        ///   查找类似 请设置扫码机串口 的本地化字符串。
+        /// </summary>
+        public static string 请设置扫码机串口 {
+            get {
+                return ResourceManager.GetString("请设置扫码机串口", resourceCulture);
+            }
+        }
+        
         /// <summary>
         ///   查找类似 请输入产品名称 的本地化字符串。
         /// </summary>

+ 15 - 0
TeamAAS-VM/Resources/Languages/Lang.en.resx

@@ -2053,4 +2053,19 @@
   <data name="扫码枪列表" type="System.Resources.ResXNullRef, System.Windows.Forms">
     <value />
   </data>
+  <data name="扫码机已连接" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码机未连接" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="请设置扫码机串口" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="初始化扫码枪时出错" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码枪接收信息时出错" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
 </root>

+ 15 - 0
TeamAAS-VM/Resources/Languages/Lang.ja-JP.resx

@@ -2053,4 +2053,19 @@
   <data name="扫码枪列表" type="System.Resources.ResXNullRef, System.Windows.Forms">
     <value />
   </data>
+  <data name="扫码机已连接" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码机未连接" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="请设置扫码机串口" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="初始化扫码枪时出错" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码枪接收信息时出错" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
 </root>

+ 20 - 0
TeamAAS-VM/Resources/Languages/Lang.resx

@@ -2203,4 +2203,24 @@
     <value>扫码枪列表</value>
     <comment>扫码枪列表</comment>
   </data>
+  <data name="扫码机已连接" xml:space="preserve">
+    <value>扫码机已连接</value>
+    <comment>扫码机已连接</comment>
+  </data>
+  <data name="扫码机未连接" xml:space="preserve">
+    <value>扫码机未连接</value>
+    <comment>扫码机未连接</comment>
+  </data>
+  <data name="请设置扫码机串口" xml:space="preserve">
+    <value>请设置扫码机串口</value>
+    <comment>请设置扫码机串口</comment>
+  </data>
+  <data name="初始化扫码枪时出错" xml:space="preserve">
+    <value>初始化扫码枪时出错</value>
+    <comment>初始化扫码枪时出错</comment>
+  </data>
+  <data name="扫码枪接收信息时出错" xml:space="preserve">
+    <value>扫码枪接收信息时出错</value>
+    <comment>扫码枪接收信息时出错</comment>
+  </data>
 </root>

+ 15 - 0
TeamAAS-VM/Resources/Languages/Lang.zh-TW.resx

@@ -2053,4 +2053,19 @@
   <data name="扫码枪列表" type="System.Resources.ResXNullRef, System.Windows.Forms">
     <value />
   </data>
+  <data name="扫码机已连接" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码机未连接" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="请设置扫码机串口" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="初始化扫码枪时出错" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码枪接收信息时出错" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
 </root>

+ 1 - 0
TeamAAS-VM/TeamAAS-VP.csproj

@@ -576,6 +576,7 @@
     <Compile Include="Models\PLC\PlcRobotParameter.cs" />
     <Compile Include="Models\ProductionRecord.cs" />
     <Compile Include="Models\Scanner\ScannerInfo.cs" />
+    <Compile Include="Models\ScanRs232ConfigModel.cs" />
     <Compile Include="Models\ScrewFeederBatchRecord.cs" />
     <Compile Include="Resources\Languages\Lang.Designer.cs">
       <AutoGen>True</AutoGen>

+ 2 - 0
TeamAAS-VM/ViewModels/MainWindowViewModel.cs

@@ -391,6 +391,8 @@ namespace TeamAAS_VP.ViewModels
             }));
             management.InitBackgroundcript();
 
+            await management.InitScan();
+
             //当前日期
             CurrentTime = Guid.NewGuid();
             Status.Add(new StatusInfo(CurrentTime, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), new SolidColorBrush(Colors.White)));

+ 25 - 2
TeamAAS-VM/ViewModels/SettingViewModel.cs

@@ -14,6 +14,7 @@ using System.Collections.ObjectModel;
 using System.ComponentModel;
 using System.Drawing.Drawing2D;
 using System.Globalization;
+using System.IO;
 using System.Linq;
 using System.Text;
 using System.Windows;
@@ -56,6 +57,15 @@ namespace TeamAAS_VP.ViewModels
 
         #region 属性
 
+
+        private ScanRs232ConfigModel _ScanConfig;
+
+        public ScanRs232ConfigModel ScanConfig
+        {
+            get { return _ScanConfig; }
+            set { SetProperty(ref _ScanConfig, value); }
+        }
+
         private bool _IsSaveScrewCurve;
         /// <summary>
         /// 是否保存锁付曲线图
@@ -464,6 +474,8 @@ namespace TeamAAS_VP.ViewModels
         private DelegateCommand _SaveCardReaderConfigCommand;
         public DelegateCommand SaveCardReaderConfigCommand =>
             _SaveCardReaderConfigCommand ?? (_SaveCardReaderConfigCommand = new DelegateCommand(ExecuteSaveCardReaderConfigCommand));
+
+        
         #endregion
 
         #region 事件
@@ -1184,7 +1196,12 @@ namespace TeamAAS_VP.ViewModels
 
         private void OnLoad()
         {
-
+            if (!File.Exists(FilePath.ScanRS232ConfigPath))
+            {
+                var scan = new ScanRs232ConfigModel();
+                FileHelper.WriteJsonFile(scan, FilePath.ScanRS232ConfigPath);
+            }
+            this.ScanConfig = FileHelper.ReadJsonFile<ScanRs232ConfigModel>(FilePath.ScanRS232ConfigPath);
         }
 
         private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
@@ -1335,7 +1352,11 @@ namespace TeamAAS_VP.ViewModels
             {
                 DeviceInfo = _configService.GetDeviceInfo();
             }
-
+            if (CardReaderConfig == null)
+            {
+                // load card reader config
+                CardReaderConfig = _configService.GetCardReaderConfig();
+            }
             CurrentLanguage = _configService.GetSystemConfiguration().CurrentLanguage;
 
             // load system parameters into UI
@@ -1516,6 +1537,8 @@ namespace TeamAAS_VP.ViewModels
             {
                 try
                 {
+                    ExecuteSaveCardReaderConfigCommand();
+                    FileHelper.WriteJsonFile(this.ScanConfig, FilePath.ScanRS232ConfigPath);
                     var sysConfig = _configService.GetSystemConfiguration();
                     sysConfig.WorkMode = WorkMode;
                     sysConfig.PickPointNum = PickPointNum;

+ 1 - 1
TeamAAS-VM/Views/HomeView.xaml

@@ -480,7 +480,7 @@
                           VerticalAlignment="Bottom"
                           Margin=" 120,3"
                           HorizontalAlignment="Right"
-                          Content="SN"
+                          Content="虚拟SN"
                           IsEnabled="{Binding IsRunning, Converter={StaticResource InvertBooleanConverter}}"
                           IsChecked="{Binding IsNoCode, Mode=TwoWay, Converter={StaticResource InvertBooleanConverter}}" />
                 <CheckBox Grid.Row="2"

+ 89 - 2
TeamAAS-VM/Views/SettingView.xaml

@@ -738,9 +738,20 @@
                              Text="{Binding DeviceInfo.DataInfo.PROCESS_MACHINE_ID, Mode=TwoWay}"
                              Margin="6,2" />
 
+                    <TextBlock Grid.Row="22"
+                       Grid.Column="0"
+                       Text="虚拟SN:"
+                       HorizontalAlignment="Right"
+                       VerticalAlignment="Center" />
+                    <TextBox Grid.Row="22"
+                         Grid.Column="1"
+                         Text="{Binding DeviceInfo.XnSN, Mode=TwoWay}"
+                         Margin="6,2" />
+
+
                     <Button Content="保存"
                             Command="{Binding SaveDeviceInfoCommand}"
-                            Grid.Row="22"
+                            Grid.Row="23"
                             HorizontalAlignment="Center"
                             Margin="0,10"
                             Grid.Column="1" />
@@ -2734,7 +2745,83 @@
                                 </Button>
                             </Grid>
                         </GroupBox>
-
+                        <GroupBox Grid.Row="5"
+          Header="{lex:Loc 扫码机配置}"
+          HorizontalAlignment="Left"
+          MinWidth="200"
+          Margin="0,0,20,0">
+                            <Grid Margin="10">
+                                <Grid.ColumnDefinitions>
+                                    <ColumnDefinition Width="auto" />
+                                    <ColumnDefinition Width="*" />
+                                </Grid.ColumnDefinitions>
+                                <Grid.RowDefinitions>
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                </Grid.RowDefinitions>
+                                <TextBlock Text="PortName:"
+                   Grid.Row="0"
+                   Grid.Column="0"
+                   HorizontalAlignment="Right" />
+                                <TextBox Text="{Binding ScanConfig.PortName,Mode=TwoWay}"
+                 Grid.Row="0"
+                 Grid.Column="1"
+                 Margin="6,0" />
+                                <TextBlock Text="BaudRate:"
+                   Grid.Row="1"
+                   Grid.Column="0"
+                   HorizontalAlignment="Right" />
+                                <TextBox Text="{Binding ScanConfig.BaudRate,Mode=TwoWay}"
+                 Grid.Row="1"
+                 Grid.Column="1"
+                 Margin="6,0" />
+                                <TextBlock Text="Parity:"
+                   Grid.Row="2"
+                   Grid.Column="0"
+                   HorizontalAlignment="Right" />
+                                <ComboBox Grid.Row="2"
+                  Grid.Column="1"
+                  SelectedItem="{Binding ScanConfig.Parity,Mode=TwoWay}"
+                  ItemsSource="{Binding Source={StaticResource Parity}}" />
+                                <TextBlock Text="StopBits:"
+                   Grid.Row="3"
+                   Grid.Column="0"
+                   HorizontalAlignment="Right" />
+                                <ComboBox Grid.Row="3"
+                  Grid.Column="1"
+                  SelectedItem="{Binding ScanConfig.StopBits,Mode=TwoWay}"
+                  ItemsSource="{Binding Source={StaticResource StopBits}}" />
+                                <TextBlock Text="DataBits:"
+                   Grid.Row="4"
+                   Grid.Column="0"
+                   HorizontalAlignment="Right" />
+                                <TextBox Text="{Binding ScanConfig.DataBits,Mode=TwoWay}"
+                 Grid.Row="4"
+                 Grid.Column="1"
+                 Margin="6,0" />
+
+                                <!--<Button Grid.Row="5"
+            Grid.Column="0"
+            Grid.ColumnSpan="2"
+            Margin="0,10,0,0"
+            Style="{StaticResource MaterialDesignRaisedButton}"
+            materialDesign:ButtonAssist.CornerRadius="10"
+            MinWidth="120"
+            Command="{Binding SaveScanConfigConfigCommand}">
+            <StackPanel Orientation="Horizontal"
+                HorizontalAlignment="Center">
+                <materialDesign:PackIcon Kind="ContentSaveCheck"
+                Margin="0,0,6,0" />
+                <TextBlock VerticalAlignment="Center"
+                Text="保存扫码机配置" />
+            </StackPanel>
+        </Button>-->
+                            </Grid>
+                        </GroupBox>
 
                     </StackPanel>
                 </StackPanel>