CodeManager.cs 14.3 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;
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);
            }
        }
        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);
                }
            }
            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 ScanCount = 0;
        private static int codeCount = ConfigAppSettings.GetIntValue(Setting_Init.CodeCount);
        [HandleProcessCorruptedStateExceptions]
        public static List<string> CameraScan(string deviceName, params string[] cameraList)
        {
            List<string> codeList = new List<string>();
            if (cameraList == null || cameraList.Length <= 0)
            {
                return codeList;
            }
            try
            {
                foreach (string cameraName in cameraList)
                {
                    if (cameraName.Trim().Equals(""))
                    {
                        continue;
                    }
                    ScanCount++;
                    DateTime startTime = DateTime.Now;
                    if (deviceName != "")
                    {
                        LogUtil.debug(deviceName + " 【" + cameraName + "】开始取图片");
                    }
                    HalconDotNet.HObject ho_Image = null;
                    bool findRightCode = false;
                    try
                    {
                        ho_Image = Camera._cam.CaptureOnImage(cameraName);
                        if (ho_Image == null)
                        {
                            LogUtil.error(deviceName + "  【" + cameraName + "】取图片失败[" + Camera._cam.ErrInfo + "],关闭相机");
                            CloseCamera(cameraName);
                            continue;
                        }

                        LogUtil.debug(deviceName + "  【" + cameraName + "】取图片完成,开始扫码");
                        List<CodeInfo> cc = new List<CodeInfo>();
                        string r = "";
                        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, 1500);
                            }
                            foreach (CodeInfo c in cc)
                            {
                                string str = CodeManager.ReplaceCode(c.CodeStr);
                                if (!codeList.Contains(str))
                                {
                                    codeList.Add(str);
                                    r = r + "##" + str;
                                    if (!findRightCode)
                                    {
                                        findRightCode = HasRightCode(str);
                                    }
                                }
                            }
                        }
                        if (!findRightCode)
                        {
                            SaveImageToFile(deviceName, cameraName, ho_Image);
                        }
                        if (deviceName != "" || r != "")
                        {
                            LogUtil.info(deviceName + " 【" + cameraName + "】扫码完成【" + FormUtil.GetSpanStr(DateTime.Now - startTime) + "】[" + findRightCode + "]" + ScanCount + " :" + r);
                        }
                    }
                    catch (AccessViolationException e)
                    {
                        LogUtil.error(deviceName + " 扫码出现AccessViolationException异常,关闭相机【" + cameraName + "】:" + e.ToString());
                        Camera._cam.Close(cameraName);
                        //  GC.Collect();
                    }
                    catch (Exception ex)
                    {
                        LogUtil.error(deviceName + " 扫码出错:" + ex.ToString());
                    }
                    finally
                    {
                        if (ho_Image != null)
                        {
                            HalconDotNet.HOperatorSet.ClearObj(ho_Image); 
                        } 
                    }
                }
            }
            catch (AccessViolationException e)
            {
                LogUtil.error(deviceName + " 扫码出现AccessViolationException异常,关闭所有相机:" + e.ToString());
                Camera._cam.CloseAll();
                //GC.Collect();
            }
            catch (Exception ex)
            {
                LogUtil.error(deviceName + " 扫码出错:" + ex.ToString());
            }
            return codeList;
        }
        private static void SaveImageToFile(string deviceName, string cameraName, HalconDotNet.HObject bitmap)
        {
            string date = deviceName.Trim().Replace('_', '-') + "-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + "-" + DateTime.Now.Millisecond.ToString().PadLeft(4, '0');
            string dire = @"D:\image\" + deviceName.Trim().Replace('_', '-') + @"\" + cameraName.Trim().Replace('_', '-').Replace(':', '-') + @"\";
            string iamgeName = date + ".bmp";
            try
            {
                if (!Directory.Exists(dire))
                {
                    Directory.CreateDirectory(dire);
                }

                bitmap.WriteObject(dire + iamgeName);
                LogUtil.info(deviceName + "  【" + cameraName + "】扫码失败,保存图片到【" + dire + iamgeName + "】成功");
            }
            catch (Exception ex)
            {
                LogUtil.error("保存" + deviceName + "  【" + cameraName + "】的图片到【" + dire + iamgeName + "】出错" + ex.ToString());
            }
        }
        private static void SaveImageToFile(string deviceName, string cameraName, Bitmap bitmap)
        {
            string date = deviceName.Trim().Replace('_', '-') + "-" + 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 bool HasRightCode(params string[] codes)
        {
            //分号分割后长度=4,L,E,B,R 
            try
            {
                foreach (string code in codes)
                {
                    string[] strarray = code.Split(';');
                    if (strarray.Length == 4)
                    {
                        if (strarray[0].StartsWith("L") &&
                            strarray[1].StartsWith("E") &&
                            strarray[2].StartsWith("B"))
                        {
                            return true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return false;
        }
        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.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))
                {
                    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);
        }
        public static string GetValidCode(List<string> codeList)
        {
            string code = "";
            List<string> targetCode = new List<string>();
            foreach (string cc in codeList)
            {
                if (string.IsNullOrEmpty(cc))
                {
                    continue;
                }
                code += cc + "##";
            }
            code = ReplaceCode(code);

            if (String.IsNullOrEmpty(code))
            {
                return "";
            }

            foreach (string cc in codeList)
            {
                if (string.IsNullOrEmpty(cc))
                {
                    continue;
                }
                //L0000000000360K003732; E20200311 0365; B6D.49925.551014212020031105000; R014212020031103159##B29
                string[] codearray = ReplaceCode(cc).Split(';');
                if (codearray.Length >= 4)
                {
                    if (codearray[2].StartsWith("B") && codearray[2].Length >= 13 && codearray[3].StartsWith("R"))
                    {
                        string tc = codearray[2].Substring(1, 12) + ";" + codearray[3];
                        if (!targetCode.Contains(tc))
                        {
                            targetCode.Add(tc);
                        }
                    }

                }
            }
            if (targetCode.Count == 1)
            {
                LogUtil.info("解析条码【" + code + "】结果【" + targetCode[0] + "】");
                return targetCode[0];
            }
            else if (targetCode.Count <= 0)
            {
                LogUtil.info("解析条码【" + code + "】失败:未找到有效条码");
            }
            else
            {
                LogUtil.info("解析条码【" + code + "】失败:有多个(" + targetCode.Count + ")有效条码");
            }
            return "";
        }
    }
}