CodeManager.cs 18.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
using CodeLibrary;
using HalconDotNet;
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.Runtime.InteropServices;
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);
        public static List<string> CameraScan(string deviceName, params string[] cameraList) {
            return CameraScan(deviceName, out _, true, cameraList);
        }
        [HandleProcessCorruptedStateExceptions]
        public static List<string> CameraScan(string deviceName, out List<CodeInfo> ccall, bool nosave,params string[] cameraList)
        {
            List<string> codeList = new List<string>();
            List<CodeInfo> cc;
            ccall = new List<CodeInfo>();
            if (cameraList == null || cameraList.Length <= 0)
            {
                return codeList;
            }
            Bitmap bmp=null;
            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 bmp);
                        if (ho_Image == null)
                        {
                            LogUtil.error(deviceName + "  【" + cameraName + "】取图片失败[" + Camera._cam.ErrInfo + "],关闭相机");
                            CloseCamera(cameraName);
                            ho_Image = Camera._cam.CaptureOnImage(cameraName, out bmp);
                            if (ho_Image == null)
                            {
                                LogUtil.error(deviceName + "  【" + cameraName + "】第2次取图片失败[" + Camera._cam.ErrInfo + "],关闭相机");
                                continue;
                            }
                        }
                        LogUtil.debug(deviceName + "  【" + cameraName + "】取图片完成,开始扫码");
                        string r = "";
                        
                        List<CodeInfo> tlci = EyemDecode.Decoder(ref bmp);
                        
                        foreach (CodeInfo code in tlci) {
                            LogUtil.info(deviceName + "  【" + cameraName + "】[eyemDecode]" + code.CodeType + "(X: " + code.X + ",Y: " + code.Y + ") " + code.CodeStr);
                            string str = CodeManager.ReplaceCode(code.CodeStr);
                            if (!codeList.Contains(str))
                            {
                                codeList.Add(str);
                                r = r + "##eyemDecode|" + code.CodeType + "|" + str;
                                if (!findRightCode)
                                {
                                    findRightCode = HasRightCode(str);
                                }
                                if (HasRightCode(str) && ccall.FindAll(x=>  x.CodeStr == str).Count()==0)
                                    ccall.Add(code);
                            }
                        }
                        
                        if (!findRightCode)
                        {
                            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, 2500);
                                }

                                foreach (CodeInfo c in cc)
                                {
                                    string str = CodeManager.ReplaceCode(c.CodeStr);
                                    if (!codeList.Contains(str))
                                    {
                                        codeList.Add(str);
                                        r = r + "##Halcon|" + codeType + "|" + str;

                                        if (!findRightCode)
                                        {
                                            findRightCode = HasRightCode(str);
                                            ccall.Add(c);
                                            nosave = false;
                                        }
                                        //if (HasRightCode(str) && ccall.FindAll(x => x.CodeStr == str).Count() == 0)
                                    }
                                }
                            }
                        }
                        //bmp.Save(@"D:\image\" + DateTime.Now.Ticks.ToString() + "test.bmp");
                        if (!findRightCode || !nosave)
                        {
                            //SaveImageToFile(deviceName, cameraName, ho_Image);
                            SaveImageToFile(deviceName+(!nosave?"eyem":""), cameraName, bmp);

                        }
                        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
                    {
                        //LogUtil.info("回收");
                        if (ho_Image != null)
                        {
                            HalconDotNet.HOperatorSet.ClearObj(ho_Image);
                            //LogUtil.info("回收ho_Image");
                        }
                        if (bmp != null)
                        {
                            bmp.Dispose();
                            //LogUtil.info("回收bmp");
                        }

                    }
                }
            }
            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 string 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());
            }
            return dire + iamgeName;
        }
        public static void SaveImageToFile(string deviceName, string cameraName, Bitmap 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
            {
                //Bitmap bit = (Bitmap)bitmap.Clone();
                if (!Directory.Exists(dire))
                {
                    Directory.CreateDirectory(dire);
                }
                bitmap.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, out string msg)
        {
            string code = "";
            msg = "";
            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[0].StartsWith("L") &&
                        codearray[1].StartsWith("E") &&
                        codearray[2].StartsWith("B") &&
                        codearray[2].Length >= 13)

                    //  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 + "】失败:未找到有效条码");
                msg = "无有效条码NG";
            }
            else
            {
                LogUtil.info("解析条码【" + code + "】失败:有多个(" + targetCode.Count + ")有效条码");
                msg = "有(" + targetCode.Count + ")有效条码NG";
            }
            return "";
        }


        [DllImport("Kernel32.dll")]
        private static extern void CopyMemory(IntPtr dest, IntPtr source, int size);
        public static void HObject2Bpp8(HObject image, out Bitmap res)
        {
            HTuple hpoint, type, width, height;

            const int Alpha = 255;
            int[] ptr = new int[2];
            HOperatorSet.GetImagePointer1(image, out hpoint, out type, out width, out height);

            res = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
            ColorPalette pal = res.Palette;
            for (int i = 0; i <= 255; i++)
            {
                pal.Entries[i] = Color.FromArgb(Alpha, i, i, i);
            }
            res.Palette = pal;
            Rectangle rect = new Rectangle(0, 0, width, height);
            BitmapData bitmapData = res.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
            int PixelSize = Bitmap.GetPixelFormatSize(bitmapData.PixelFormat) / 8;
            ptr[0] = bitmapData.Scan0.ToInt32();
            ptr[1] = hpoint.I;
            if (width % 4 == 0)
                CopyMemory((IntPtr)ptr[0], (IntPtr)ptr[1], width * height * PixelSize);
            else
            {
                for (int i = 0; i < height - 1; i++)
                {
                    ptr[1] += width;
                    CopyMemory((IntPtr)ptr[0], (IntPtr)ptr[1], width * PixelSize);
                    ptr[0] += bitmapData.Stride;
                }
            }
            res.UnlockBits(bitmapData);

        }
    }
}