CodeManager.cs 11.4 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()
        {
            //BaslerCamera.Instance.Close();
            //HIKCamera.Instance.Close();
            Camera._cam.CloseAll();
        }

        //public static Bitmap GetCamerImage(string cameraName)
        //{
        //    Bitmap bitm = null;
        //    try
        //    { 
        //        bitm= Camera._cam.GrabOneImage(cameraName);
        //        //Camera._cam.Close(cameraName);
        //    }
        //    catch (Exception ex)
        //    {
        //        LogUtil.error(" 【" + cameraName + "】获取图片出错:", ex);
        //    }
        //    return bitm;
        //}
        private static int codeCount = ConfigAppSettings.GetIntValue(Setting_Init.CodeCount);
        [HandleProcessCorruptedStateExceptions]
        public static List<string> CameraScan(List<string> cameraList, string deviceName, bool isSaveImg = false)
        {
            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;
                    }
                    DateTime startTime = DateTime.Now;
                    LogUtil.info(deviceName + " 【" + cameraName + "】开始取图片");
                    //using (Bitmap bitmap = GetCamerImage(cameraName))
                    //{    
                    HalconDotNet.HObject ho_Image = null;
                    try
                    {
                          ho_Image = Camera._cam.CaptureOnImage(cameraName); 
                        if (ho_Image == null)
                        {
                            LogUtil.error(deviceName + "  【" + cameraName + "】取图片失败[" + Camera._cam.ErrInfo + "],关闭相机");
                            CloseCamera(cameraName);
                            continue;
                        }
                        //LogUtil.info(deviceName + "  【" + cameraName + "】取图片完成,开始转换并扫码");
                        //bit = new Bitmap(bitmap);
                        //LogUtil.info(deviceName + "  【" + cameraName + "】new Bitmap(bitmap);完成");
                        //ho_Image = HDCodeHelper.Bitmap2HObjectBpp24(bit);
                        LogUtil.info(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, codeCount, GetCodeParamFilePath(codeType), codeType);
                            }
                            foreach (CodeInfo c in cc)
                            {
                                string str = CodeManager.ReplaceCode(c.CodeStr);
                                if (!codeList.Contains(str))
                                {
                                    codeList.Add(str);
                                    r = r + "##" + str;
                                }
                            } 
                        }
                        if (String.IsNullOrEmpty(r))
                        {
                            //  SaveImageToFile(deviceName, cameraName, bit);
                        }
                        LogUtil.info(deviceName + " 【" + cameraName + "】扫码完成【" + FormUtil.GetSpanStr(DateTime.Now - startTime) + "】:" + 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 (bitmap != null)
                        //{
                        //    bitmap.Dispose();
                        //}
                        //if (bit != null)
                        //{
                        //    bit.Dispose();
                        //}
                        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, 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.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);
        }
    }
}