WebCallWork.cs 15.0 KB
using BLL;
using Model;
using Newtonsoft.Json;
using SmartScan.PlusSettingFrm;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.ServiceModel;
using System.ServiceModel.Activation;

namespace SmartScan
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single, IncludeExceptionDetailInFaults = true)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    internal class WebCallWork : IWeb
    {
        public WebCallWork()
        {
        }                                                                                                                                                                   

        public void CloseApp()
        {
            LogNet.log.Info("WebService CloseApp 接口被调用");
            Common.frmMain.Invoke(new Action(() => { Common.frmMain.Close(); }));
        }
        public WebResultCamera WorkWithCamera()
        {
            LogNet.log.Info("WebService WorkWithCamera 接口被调用");
            WebCodeAll[] msg = null;
            Common.frmMain.Invoke(new Action(() => { msg = Common.frmMain.WebTouchWork(); }));
            return new WebResultCamera() { Data = msg };
        }

        public WebResultCode WorkWithCode(Stream json)
        {
            LogNet.log.Info($"WebService WorkWithCode 接口被调用");

            StreamReader sr = new(json);
            string input = sr.ReadToEnd();
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new();
            object[] obj = (object[])serializer.DeserializeObject(input);
            string[] str = new string[obj.Length];
            for (int i = 0; i < str.Length; i++)
                str[i] = obj[i].ToString();

            WebCodeText[] msg = null;
            Common.frmMain.Invoke(new Action(() => { msg = Common.frmMain.WebTouchWork(str); }));
            return new WebResultCode() { Data = msg };
        }

        public string alive()
        {
            return "1";
        }

        public WebResultCode ProcessBitmap(Stream info, string param)
        {
            BinaryFormatter bf = new BinaryFormatter();
            Bitmap bitmap = (Bitmap)bf.Deserialize(info);
            try
            {
                List<CameraVisionLib.Model.BarcodeInfo> workCodeInfo = new();
                Dictionary<string, string> workCodeKeyword;// = new(StringComparer.OrdinalIgnoreCase);
                bool[] originalCodeIsUsed = null;
                workCodeInfo = Camera.GetBarCode(bitmap);

                if (workCodeInfo.Count == 0)
                    return new WebResultCode() { ErrorCode = -1, Msg = "扫码失败" };
                BLLCommon.mateEdit.CurrntBitmap = DeepClone(bitmap);
                bool rtn = BLLCommon.mateEdit.MatchingTemplate(workCodeInfo, BLLCommon.config.DefaultMaterialName, false, out string mateName, out workCodeKeyword, out AMatch aMatch);

                LogNet.log.Info("模板匹配结果:" + rtn);
                WebResultCode webResultCode = null;
                Dictionary<string, string> keys = new Dictionary<string, string>();
                foreach (var item in workCodeKeyword)
                {
                    // workCodeKeyword[item.Key]= item.Value.Replace("<OCR>", "");
                    keys.Add(item.Key, item.Value.Replace("<OCR>", ""));
                }
                if (!BLLCommon.extension.SetKey(null, keys, rtn, out string errmsg))
                {
                    webResultCode = new WebResultCode() { ErrorCode = -2, Msg = errmsg };
                }

                if (webResultCode != null || !rtn)
                    return webResultCode;
                LogNet.log.Info("模板匹配结束");
                List<KeyValuePair<string, string>> result = new List<KeyValuePair<string, string>>();

                #region 判断是否需要请求http替换数据
                workCodeKeyword = WebserverReplaceData(keys);
                //bool isReplaceData = ConfigHelper.Config.Get<bool>("WebServer_isReplaceData", false);
                //if (isReplaceData)
                //{
                //    LogNet.log.Info("WebServer:开始请求替换数据!");
                //    InvokePlugin invoke = new InvokePlugin();
                //    invoke.LoadDLL("DataHandling", LogNet.log);
                //    if (workCodeKeyword!=null)
                //    {
                //        if (workCodeKeyword.Count!=0)
                //        {
                //            LogNet.log.Info($"{JsonConvert.SerializeObject(workCodeKeyword)}");

                //            if (ConfigHelper.Config.Get("WebServer_Isformal", false))
                //            {
                //                Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
                //                if (workCodeKeyword.ContainsKey("PN"))
                //                {
                //                    keyValuePairs.Add("firmaUrunKodu", workCodeKeyword["PN"]);
                //                }
                //                else
                //                {
                //                    keyValuePairs.Add("firmaUrunKodu", "");
                //                }
                //                keyValuePairs.Add("lot", "");
                //                keyValuePairs.Add("barkodAdet", "1");
                //                keyValuePairs.Add("userName", "bekoservice");
                //                keyValuePairs.Add("pass", "beko1209tyu");
                //                keyValuePairs.Add("printerMacId", "");
                //                keyValuePairs.Add("basanUserName", "");
                //            }                          
                //            workCodeKeyword = invoke.RequestServer(workCodeKeyword, 1);
                //        }
                //    }              
                //}
                #endregion
                foreach (var wc in workCodeKeyword)
                {
                    result.Add(new KeyValuePair<string, string>(wc.Key, wc.Value));
                }
                return new WebResultCode() { workCodeKeyword = result, workCodeInfo = workCodeInfo };
            }
            catch (Exception ex)
            {
                LogNet.log.Error("ProcessBitmap", ex);
                return new WebResultCode() { ErrorCode = -1, Msg = "扫码失败:" + ex };
            }
            finally {
                bitmap?.Dispose();
            }
        }
        public static T DeepClone<T>(T _object)
        {
            try
            {
                T dstobject;
                using (MemoryStream mStream = new MemoryStream())
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    bf.Serialize(mStream, _object);
                    mStream.Seek(0, SeekOrigin.Begin);//指定当前流的位置为流的开头。
                    dstobject = (T)bf.Deserialize(mStream);
                    mStream.Close();
                }
                return dstobject;
            }
            catch (Exception e)
            {
                LogNet.log.Error("DeepClone" , e);
                return default;
            }
        }
        public WebResultCode ProcessBitmaps(BitmapData bitmapData)
        {
            BLLCommon.mateEdit.CurrntBitmap?.Dispose();
            Bitmap bitmap = null;
            MemoryStream stream = null;
            try
            {
                if (bitmapData == null)
                {
                    return new WebResultCode() { ErrorCode = -1, Msg = "未接收到任何数据!" };
                }
                if (bitmapData.ImageData.Length <= 0)
                {
                    return new WebResultCode() { ErrorCode = -1, Msg = "扫码相机未传送图片;" };
                }
                byte[] imageData = Convert.FromBase64String(bitmapData.ImageData);


                stream = new MemoryStream(imageData);                
                bitmap = new Bitmap(stream);
                
                if (bitmap == null)
                {
                    return new WebResultCode() { ErrorCode = -1, Msg = "图片解析完成为空;" };
                }
                List<CameraVisionLib.Model.BarcodeInfo> workCodeInfo = new();

                if (bitmapData.BarCodeList == null && bitmapData.IsIDCamera)
                {
                    return new WebResultCode() { ErrorCode = -1, Msg = "扫码相机未传来条码数据;" };
                }
                if (bitmapData.IsIDCamera)
                {
                    bitmapData.BarCodeList.ForEach(barcode =>
                    {
                        workCodeInfo.Add(new CameraVisionLib.Model.BarcodeInfo
                        {
                            Text = barcode.Text,
                            //Size = barcode.Size,
                            Angle = barcode.Angle,
                            Center = new PointF(barcode.X, barcode.Y),
                            CodeType = barcode.CodeType,
                            Distance = barcode.Distance,
                        });
                    });
                }
                else
                {
                    workCodeInfo = Camera.GetBarCode(bitmap);

                    if (workCodeInfo.Count == 0)
                        return new WebResultCode() { ErrorCode = -1, Msg = "扫码失败" };
                }
                BLLCommon.mateEdit.CurrntBitmap = DeepClone(bitmap);
                Dictionary<string, string> workCodeKeyword;

                bool rtn = BLLCommon.mateEdit.MatchingTemplate(workCodeInfo, BLLCommon.config.DefaultMaterialName, false, out string mateName, out workCodeKeyword, out AMatch aMatch);
                var point = new Point(-1, -1);
                int angle = 0;
                LogNet.log.Info("模板匹配结果:" + rtn);
                if (rtn)
                {
                    string key = ConfigHelper.Config.Get("Label_Key", "");
                    workCodeKeyword.TryGetValue(key, out String Value);
                    LogNet.log.Info("模板匹配结果:" + rtn + $";关键字{key}:{Value};匹配成功条码xy:X={aMatch.Points.X};Y={aMatch.Points.Y},中心点x={bitmapData.X};y={bitmapData.Y},角度={aMatch.Angle},料盘尺寸={bitmapData.PlateW};匹配成功条码:{string.Join(", ", aMatch.IsCodeUsed)}");
                    point = UsrKeywordlabeling.LabelingAngle(Value, aMatch, new Point(bitmapData.X, bitmapData.Y), bitmapData.IsIDCamera, bitmapData.PlateW, out angle);
                    //point =UsrCustomlabeling.LabelingAngle_New(mateName, aMatch, new Point(bitmapData.X, bitmapData.Y), bitmapData.IsIDCamera, bitmapData.PlateW, out  angle);
                }
                Dictionary<string, string> keys = new Dictionary<string, string>();
                foreach (var item in workCodeKeyword)
                {
                    keys.Add(item.Key, item.Value.Replace("<OCR>", ""));
                }
                if (!BLLCommon.extension.SetKey(null, keys, rtn, out string errmsg))
                {
                    return new WebResultCode() { ErrorCode = -2, Msg = errmsg };
                }
                List<KeyValuePair<string, string>> result = new List<KeyValuePair<string, string>>();
                workCodeKeyword = WebserverReplaceData(keys);
                foreach (var wc in workCodeKeyword)
                {
                    result.Add(new KeyValuePair<string, string>(wc.Key, wc.Value));
                }
                NewPositionAngle newPosition = new NewPositionAngle
                {
                    X = point.X,
                    Y = point.Y,
                    Angle = angle,
                    IsCodeUsed = aMatch.IsCodeUsed
                };
                LogNet.log.Info($"返回坐标及角度X={newPosition.X};Y={newPosition.Y};角度={newPosition.Angle}");
                return new WebResultCode() { workCodeKeyword = result, workCodeInfo = workCodeInfo, PositionAngle = newPosition };
            }
            catch (Exception ex)
            {
                LogNet.log.Error("ProcessBitmaps", ex);
                return new WebResultCode() { ErrorCode = -1, Msg = "扫码失败:" + ex };
            }
            finally {
                bitmap?.Dispose();
                stream?.Dispose();
            }
        }

        public Dictionary<string, string> WebserverReplaceData(Dictionary<string, string> workCodeKeyword) 
        {
            #region 判断是否需要请求http替换数据
            bool isReplaceData = ConfigHelper.Config.Get<bool>("WebServer_isReplaceData", false);
            if (isReplaceData)
            {
                LogNet.log.Info("WebServer:开始请求替换数据!");
                InvokePlugin invoke = new InvokePlugin();
                invoke.LoadDLL("DataHandling", LogNet.log);
                if (workCodeKeyword != null)
                {
                    if (workCodeKeyword.Count != 0)
                    {
                        //foreach (var item in workCodeKeyword)
                        //{
                        //       item.Value= item.Value.Replace("<OCR>", "");
                        //}
                        LogNet.log.Info($"识别关键字内容:{JsonConvert.SerializeObject(workCodeKeyword)}");

                        if (ConfigHelper.Config.Get("WebServer_Isformal", true))
                        {
                            Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
                           
                            string firmaUrunKoduValue = "";

                            if (workCodeKeyword.TryGetValue("PN", out string pnValue) && !string.IsNullOrWhiteSpace(pnValue))
                            {
                                firmaUrunKoduValue = pnValue;
                            }
                            else if (workCodeKeyword.TryGetValue("firmaUrunKodu", out string firmaUrunKodu) && !string.IsNullOrWhiteSpace(firmaUrunKodu))
                            {
                                firmaUrunKoduValue = firmaUrunKodu;
                            }

                            keyValuePairs.Add("firmaUrunKodu", firmaUrunKoduValue);
                            keyValuePairs.Add("lot", "");
                            keyValuePairs.Add("barkodAdet", "1");
                            keyValuePairs.Add("userName", "bekoservice");
                            keyValuePairs.Add("pass", "beko1209tyu");
                            keyValuePairs.Add("printerMacId", "");
                            keyValuePairs.Add("basanUserName", "");
                            workCodeKeyword = invoke.RequestServer(keyValuePairs, 1);
                        }
                        else
                        {
                            workCodeKeyword = invoke.RequestServer(workCodeKeyword, 1);
                        }                       
                    }
                }
            }
            return workCodeKeyword;
            #endregion
        }       
    }
}