CodeManager.cs 12.5 KB
using CodeLibrary; 
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Text;
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>();
        public static List<int> Code_Block_Size_List = new List<int>();
        private static char spiltChar = '#';
        /// <summary>
        /// 初始化摄像机名称和二维码类型
        /// </summary> 
        public static void LoadConfig()
        {
            HDLogUtil.LogName = "RollingLogFileAppender";

            string code_block_size_list = ConfigAppSettings.GetValue(Setting_Init.code_block_size_list);
            var cl = code_block_size_list.Split(',');
            foreach (string s in cl)
            {
                int i;
                if (int.TryParse(s, out i))
                {
                    Code_Block_Size_List.Add(i);
                }
            }
            if (Code_Block_Size_List.Count == 0)
                Code_Block_Size_List.Add(19);

            LogUtil.info("加载到配置二维码块尺寸:"+ string.Join(",",Code_Block_Size_List));

            string codeStr = ConfigAppSettings.GetValue(Setting_Init.CodeType);
            codeTypeList = new List<string>();          

            try
            {
                string[] codeArray = codeStr.Split(spiltChar);
                foreach (string str in codeArray)
                {
                    if (str.Trim().Equals(""))
                    {
                        continue;
                    }
                    string file = GetCodeParamFilePath(str.Trim());
                    LogUtil.info("加载到配置二维码类型:" + str.Trim()+",配置文件:"+file);
                    codeTypeList.Add(str.Trim());
                }




                LoadCamera(false);
                CodeLibrary.HDCodeLearnHelper.LoadConfig("", codeStr);
            }
            catch (Exception ex)
            {
                LogUtil.error("解析摄像机配置出错:"+ex.ToString());
            }
        }
        private static void LoadCamera(bool isReLoad)
        {
            if (isReLoad || Camera._cam == null)
            {
                try
                {
                    if (Camera._cam != null)
                    {
                        Camera._cam.CloseAll();
                    }
                    Camera.Type = CameraType.HIK;
                    Camera._cam.Load();
                }
                catch (Exception ex)
                {
                    LogUtil.error("加载HIK相机出错:"+ex.ToString());
                }
            }
            string[] names = Camera._cam.Name;


            if (names != null)
            {
                foreach (string n in names)
                {
                    if (!hikNameList.Contains(n))
                    {
                        hikNameList.Add(n);
                    }
                }
                // hikNameList.AddRange(names);
                foreach (string name in hikNameList)
                {
                    LogUtil.info("加载到HIK相机:" + name);
                }
            }
        }

        public static void CloseCamera(string cameraName)
        {
            Camera._cam.Close(cameraName);
        }
        public static void CloseAllCamera()
        { 
            Camera._cam.CloseAll();
        }
      
        private static int codeCount = ConfigAppSettings.GetIntValue(Setting_Init.CodeCount);
        [HandleProcessCorruptedStateExceptions]
        public static List<string> CameraScan(List<string> cameraList, string deviceName, int timeOut = 1500)
        {
            if (codeCount < 1)
            {
                codeCount = 1;
            }
            LogUtil.info($"Task=>cameraList={cameraList.Count()}");
            List<string> codeList = new List<string>();
            if (cameraList == null || cameraList.Count <= 0)
            {
                return codeList;
            }
            try
            {
                Task[] cameraTask = new Task[cameraList.Count()];

                for (int i = 0; i < cameraList.Count(); i++)
                {
                    var cameraName = cameraList[i];
                    if (cameraName.Trim().Equals(""))
                    {
                        continue;
                    }
                    DateTime startTime = DateTime.Now;
                    LogUtil.info(" 【" + cameraName + "】开始取图片");
                    HalconDotNet.HObject ho_Image = null;
                    LogUtil.info(" 【" + cameraName + "】开始取图片2");
                    Bitmap bmp = null;
                    try
                    {
                        bool nohalcon = false;
                        LogUtil.info(" 【" + cameraName + "】开始取图片3");
                        ho_Image = Camera._cam.CaptureOnImage(cameraName, out bmp, nohalcon);
                        if (ho_Image == null && !nohalcon)
                        {
                            LogUtil.error("  【" + cameraName + "】取图片失败[" + Camera._cam.ErrInfo + "],关闭相机");
                            CloseCamera(cameraName);
                            continue;
                        }
                        LogUtil.info("  【" + cameraName + "】取图片完成,开始扫码");
                        string r = "";

                        foreach (int codesize in Code_Block_Size_List)
                        {
                            List<CodeInfo> tlci = EyemDecode.Decoder(ref bmp, null, codesize);

                            foreach (CodeInfo code in tlci)
                            {
                                LogUtil.info("  【" + cameraName + $"】[eyemDecode blocksize:{codesize}]" + code.CodeType + "(X: " + code.X + ",Y: " + code.Y + ") " + code.CodeStr);
                                string str = CodeManager.ReplaceCode(code.CodeStr);
                                lock (codeList)
                                {
                                    if (!codeList.Contains(str))
                                    {
                                        codeList.Add(str);
                                        r = r + "##" + str;
                                    }
                                }
                            }
                        }
                        
                        List<CodeInfo> cc = new List<CodeInfo>();
                        foreach (string codeType in codeTypeList)
                        {
                            //判断是否是一维码
                            if (codeType.ToLower().Equals("barcode"))
                            {
                                cc = HDCodeHelper.DecodeBarCode(ho_Image);
                            }
                            else
                            {
                                cc = HDCodeHelper.DecodeCode(ho_Image, codeType, GetCodeParamFilePath(codeType), codeCount, 2000);
                            }
                            foreach (CodeInfo c in cc)
                            {
                                string str = CodeManager.ReplaceCode(c.CodeStr);
                                lock (codeList)
                                {
                                    if (!codeList.Contains(str))
                                    {
                                        codeList.Add(str);
                                        r = r + "##" + str;
                                    }
                                }
                            }
                        }
                        
                        if (codeList.Count() == 0)
                        {
                            SaveImageToFile("mimo", cameraName, bmp);
                        }
                        LogUtil.info(" 【" + cameraName + "】" + " 扫码完成【" + FormUtil.GetSpanStr(DateTime.Now - startTime) + "】 :" + r);
                    }
                    catch (AccessViolationException e)
                    {
                        LogUtil.error(" 扫码出现AccessViolationException异常,关闭相机【" + cameraName + "】:" + e.ToString());
                        Camera._cam.Close(cameraName);
                        //  GC.Collect();
                    }
                    catch (Exception ex)
                    {
                        LogUtil.error(" 扫码出错:" + ex.ToString());
                    }
                    finally
                    {
                        if (ho_Image != null)
                        {
                            ho_Image.Dispose();
                        }
                        if (bmp != null)
                            bmp.Dispose();
                    }

                }
            }
            catch (AccessViolationException e)
            {
                LogUtil.error(" 扫码出现AccessViolationException异常:" + e.ToString());
                //    GC.Collect();
            }
            catch (Exception ex)
            {
                LogUtil.error(" 扫码出错:" + ex.ToString());
            }
            return codeList;
        }
        private static void SaveImageToFile(string deviceName, string cameraName, Bitmap bitmap)
        {
            string date = DateTime.Now.ToString("HH-mm-ss-") + DateTime.Now.Millisecond;
            string dire = @"D:\image\" + deviceName.Trim().Replace('_', '-') + @"\" + cameraName.Trim().Replace('_', '-').Replace(':', '-') + @"\";
            string iamgeName = date + ".bmp";
            try
            {
                Bitmap bit = (Bitmap)bitmap.Clone();
                if (Directory.Exists(dire).Equals(false))
                {
                    Directory.CreateDirectory(dire);
                }
                bit.Save(dire + iamgeName, ImageFormat.Bmp);
                LogUtil.info(deviceName + "  【" + cameraName + "】扫码失败,保存图片到【" + dire + iamgeName + "】成功");
            }
            catch (Exception ex)
            {
                LogUtil.error("保存" + deviceName + "  【" + cameraName + "】的图片到【" + dire + iamgeName + "】出错"+ex.ToString());
            }
        }

        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>
        public 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.Replace("\u0026", "");
            message = message.Replace("\\000026", "");
            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)
            {
                int value = (int)by;
                if (value.Equals(24) || value.Equals(30) || value.Equals(29) || value.Equals(4) || value.Equals(26))
                {
                    continue;
                }
                if (!value.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);
        }
    }
}