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;
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 = 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;
                    }
                    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 ScanCount = 0;
        private static int codeCount = Setting_Init.CodeCount;
        private static int codeTimeout = Setting_Init.ScanCodeTimeout;
        [HandleProcessCorruptedStateExceptions]
        public static List<string> CameraScan(List<string> cameraList, string deviceName,   int timeOut = 1500)
        {
            if (codeCount < 1)
            {
                codeCount = 1;
            }
            List<string> codeList = new List<string>();
            if (cameraList == null || cameraList.Count <= 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,out Bitmap bmp);
                        if (bmp == null)
                        {
                            LogUtil.error(deviceName + "  【" + cameraName + "】取图片失败[" + Camera._cam.ErrInfo + "],关闭相机");
                            CloseCamera(cameraName);
                            continue;
                        }
                        LogUtil.debug(deviceName + "  【" + cameraName + "】取图片完成,开始扫码");
                        List<CodeInfo> cc = new List<CodeInfo>();
                        string r = "";
                        RemoteDecodeHelper.RemoteDecodeParam remoteDecodeParam = new RemoteDecodeHelper.RemoteDecodeParam
                        {
                            codeTypeList = codeTypeList.ToArray(),
                            codeCount = codeCount,
                            timeout = codeTimeout
                        };
                        cc = RemoteDecodeHelper.DecodeRequest(bmp, remoteDecodeParam);
                        if (cc != null)
                        {
                            foreach (CodeInfo c in cc)
                            {
                                string str = CodeManager.ReplaceCode(c.CodeStr);
                                if (!codeList.Contains(str))
                                {
                                    codeList.Add(str);
                                    r = r + "##remote|" + c.CodeType + "|" + str;
                                    if (!findRightCode)
                                    {
                                        findRightCode = HasRightCode(str);
                                    }
                                }
                            }
                        }
                        if (deviceName != "" || r != "")
                        {
                            LogUtil.info(deviceName + " 【" + cameraName + "】扫码完成【" + FormUtil.GetSpanStr(DateTime.Now - startTime) + "】[" + findRightCode + "]" + ScanCount + " :" + r);
                        }
                        if (!findRightCode)
                        {
                            SaveImageToFile(deviceName, cameraName, bmp);
                        }
                    }
                    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)
                        {
                            ho_Image.Dispose();
                        }
                    }
                }
            }
            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 + 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);
        }
    }
}