NCodeManager.cs 11.0 KB
using CodeLibrary;
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OnlineStore.DeviceLibrary
{
    public class CodeManager
    { 
        public static List<string> codeTypeList = new List<string>(); 
        public static List<string> balserNameList = new List<string>();
        public static List<string> hikNameList = new List<string>();

        private static char spiltChar = '#';
        /// <summary>
        /// 初始化摄像机名称和二维码类型
        /// </summary> 
        public static void LoadConfig()
        { 
            string codeStr = ConfigAppSettings.GetValue(Setting_Init.CodeType); 
            codeTypeList = new List<string>();
            HDLogUtil.LogName = "RollingLogFileAppender";
            try
            { 
                string[] codeArray = codeStr.Split(spiltChar);
                foreach (string str in codeArray)
                {
                    if (str.Trim().Equals(""))
                    {
                        continue;
                    }
                    LogUtil.info("加载到配置二维码类型:" + str.Trim());
                    codeTypeList.Add(str.Trim());
                }

                LoadCamera(false);
                CodeLibrary.HDCodeLearnHelper.LoadConfig("", codeStr); 
            }
            catch (Exception ex)
            {
                LogUtil.error("解析摄像机配置出错:" + ex.StackTrace);
            }
        }
        private static void LoadCamera(bool isReLoad)
        {
            if (isReLoad)
            {
                try
                {
                    CodeLibrary.HIKCManager.Load();
                }
                catch (Exception ex)
                {
                    LogUtil.error("加载HIK相机出错:" + ex.ToString());
                }
                try
                {
                    CodeLibrary.BaslerCManager.Load();
                }
                catch (Exception ex)
                {
                    LogUtil.error("加载Basler相机出错:" + ex.ToString());
                }
            }
            string[] names = CodeLibrary.HIKCManager.CameraName;


            if (names != null)
            {
                hikNameList.AddRange(names);
                foreach (string name in hikNameList)
                {
                    LogUtil.info("加载到HIK相机:" + name);
                }
            }
            names = CodeLibrary.BaslerCManager.CameraName;
            if (names != null)
            {
                balserNameList.AddRange(names);
                foreach (string name in balserNameList)
                {
                    LogUtil.info("加载到Balser相机:" + name);
                }
            }
        }
        public static void CloseCamera(string name)
        {
            //BaslerCamera.Instance.Close();
            //HIKCamera.Instance.Close();
            if (HIKCManager.CameraName.Contains(name))
            {
                HIKCManager.Close(name);
            }
            else
            {
                BaslerCManager.Close(name);
            }
        }
        public static void CloseAllCamera()
        {
            HIKCManager.CloseAll();
            BaslerCManager.CloseAll();
        }

        public static Bitmap GetCamerImage(string cameraName)
        {
            Bitmap bitm = null;
            try
            {
                if (balserNameList.Contains(cameraName))
                {
                    bool result = true;
                    if (!BaslerCManager.IsOpen(cameraName))
                    {
                        result = BaslerCManager.Open(cameraName);
                    } 
                    //    LogUtil.info("打开相机:" + cameraName + "(" + result + ")"); 
                    if (result)
                    {
                        bitm= BaslerCManager.GrabOne(cameraName); 
                    }
                    else
                    {
                        LogUtil.error("相机【" + cameraName + "】打开失败:" + BaslerCamera.Instance.ErrInfo);
                    }
                }
                else if (hikNameList.Contains(cameraName))
                {
                    bool result = true;
                    if (!HIKCManager.IsOpen(cameraName))
                    {
                        result = HIKCManager.Open(cameraName);
                    }
                  
                    //    LogUtil.info("打开相机:" + cameraName + "(" + result + ")"); 
                    if (result)
                    {
                        bitm = HIKCManager.GrabOne(cameraName); 
                    }
                    else
                    {
                        LogUtil.error("相机【" + cameraName + "】打开失败:" + HIKCamera.Instance.ErrInfo);
                    }
                }
                else
                {
                    LogUtil.info("未找到相机【" + cameraName + "】无法获取图片");
                    //若未加载到相机,需要重新加载相机
                    if (balserNameList.Count <= 0 && hikNameList.Count <= 0)
                    {
                        LogUtil.error("获取图片时发现未加载到相机,重新加载相机");
                        LoadCamera(true);
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("从相机【" + cameraName + "】获取图片出错:" + ex.ToString());
            }
            return bitm;
        }

        [HandleProcessCorruptedStateExceptions]
        public static List<string> CameraScan(List<string> cameraNameList  )
        {
            List<string> codeList = new List<string>();  
            try
            {
                List<Task<List<CodeInfo>>> taskList = new List<Task<List<CodeInfo>>>();
                foreach (string cameraName in cameraNameList)
                {
                    Task.Factory.StartNew(delegate ()
                    {
                        using (Bitmap bitmap = GetCamerImage(cameraName))
                        {
                            if (bitmap == null)
                            {
                                LogUtil.error(" 摄像机【" + cameraName + "】获取图片失败,关闭相机");
                                CloseCamera(cameraName);
                                return;
                            }

                            LogUtil.debug(" 摄像机【" + cameraName + "】获取图片完成");
                            System.Threading.Thread.Sleep(1);
                            HalconDotNet.HObject ho_Image = HDCodeHelper.Bitmap2HObjectBpp24(bitmap);
                            LogUtil.debug(" 摄像机【" + cameraName + "】转换图片完成,开始扫码");
                            List<CodeInfo> cc = new List<CodeInfo>();
                            foreach (string codeType in codeTypeList)
                            {
                                Task<List<CodeInfo>> typeDeCode =  new Task<List<CodeInfo>>(delegate ()
                                {
                                    return DeCode(ho_Image, codeType);
                                });
                                taskList.Add(typeDeCode);
                                typeDeCode.Start();
                            }
                        } 
                    });
                }

                Task.WaitAll(taskList.ToArray());
                foreach (Task<List<CodeInfo>> t in taskList)
                { 
                    List<CodeInfo> cc = t.Result;
                    if (cc.Count > 0)
                    {
                        string r = "";
                        foreach (CodeInfo c in cc)
                        {
                            codeList.Add(c.CodeStr);
                            r = r + "##" + c.CodeStr;
                        }

                    }
                }
            }
            catch (AccessViolationException e)
            {
                LogUtil.error("扫码出现AccessViolationException异常:" + e.ToString());
                GC.Collect();
            }
            catch (Exception ex)
            {
                LogUtil.error("扫码出错:" + ex.ToString());
            }
            return codeList;
        }

        private static  List<CodeInfo> DeCode(HalconDotNet.HObject ho_Image,string codeType)
        {
            List<CodeInfo> cc = new List<CodeInfo>();
            //判断是否是一维码
            if (codeType.ToLower().Equals("barcode"))
            {
                cc = HDCodeHelper.DecodeBarCode(ho_Image);
            }
            else
            {
                cc = HDCodeHelper.DecodeCode(ho_Image, 1, GetCodeParamFilePath(codeType), codeType);
            }
            //if (cc.Count > 0)
            //{
            //    string r = "";
            //    foreach (CodeInfo c in cc)
            //    {
            //        codeList.Add(c.CodeStr);
            //        r = r + "##" + c.CodeStr;
            //    }
            //    LogUtil.debug(" 【" + cameraName + "】【" + codeType + "】扫码完成:" + r);
            //}
            return cc;
        } 

        public static string GetCodeParamFilePath(string codePath)
        {
            string appPath = Application.StartupPath;
            string path = appPath + ConfigAppSettings.GetValue(Setting_Init.CodeParamPath);
            string filePath = path + codePath + ".dcm";
            if (File.Exists(filePath))
            {
                return filePath;
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        /// 处理接收后的二维码
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private static string ReplaceCode(string message)
        {
            message = message.Trim();
            message = message.Replace("\r", "");
            message = message.Replace("\n", "");
            char a = (char)02;
            message = message.Replace(a.ToString(), "");
            message = message.Trim();
            System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
            byte[] bytes = asciiEncoding.GetBytes(message);
            List<byte> newBytes = new List<byte>();
            foreach (byte by in bytes)
            {
                if (!by.Equals(24))
                {
                    newBytes.Add(by);
                }
            }
            message = asciiEncoding.GetString(newBytes.ToArray());
            return message;
        }
        public static string ProcessCode(List<string> codeList)
        {
            string code = "";
            foreach (string cc in codeList)
            {
                if (string.IsNullOrEmpty(cc))
                {
                    continue;
                }
                code += cc + "##";
            }
            return ReplaceCode(code);
        }
    }
}