Commit a73a41b0 刘韬

1

1 个父辈 ee2815f3
......@@ -56,10 +56,6 @@
<Reference Include="ExcelNumberFormat, Version=1.1.0.0, Culture=neutral, PublicKeyToken=23c6f5d73be07eca, processorArchitecture=MSIL">
<HintPath>..\packages\ExcelNumberFormat.1.1.0\lib\net20\ExcelNumberFormat.dll</HintPath>
</Reference>
<Reference Include="IDHIKCamera, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\IDHK\IDHIKCamera\IDHIKCamera\bin\Debug\IDHIKCamera.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=2.0.12.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.2.0.12\lib\net45\log4net.dll</HintPath>
</Reference>
......@@ -147,6 +143,10 @@
<Project>{e28de77a-fc70-4be4-96ec-d0c1a7215a15}</Project>
<Name>DAL</Name>
</ProjectReference>
<ProjectReference Include="..\IDHIKCamera\IDHIKCamera.csproj">
<Project>{2fa7c3a5-e237-4c79-8f4a-4b71c218be89}</Project>
<Name>IDHIKCamera</Name>
</ProjectReference>
<ProjectReference Include="..\Model\Model.csproj">
<Project>{20e61a3d-bf87-4a99-9756-7fe13d2daa6e}</Project>
<Name>Model</Name>
......
......@@ -171,13 +171,19 @@ namespace BLL
}
public static void Close()
{
if (useIDCamera)
try
{
IDHIK.Instance.CloseAll();
}
else
if (useIDCamera)
{
IDHIK.Instance.CloseAll();
}
else
{
cameraVision?.Close();
}
}catch (Exception ex)
{
cameraVision?.Close();
LogNet.log.Error($"关闭相机失败 {ex}");
}
}
public static string[] GetBarCodeText(List<BarcodeInfo> barcodeInfos)
......@@ -224,7 +230,10 @@ namespace BLL
catch (Exception e)
{
LogNet.log.Error($"{cameraName}取图失败:", e);
}
}
finally {
Close();
}
return barcodeInfos;
}
}
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace IDHIKCamera
{
/// <summary>
/// 条码信息
/// </summary>
[Serializable]
public class CodeInfo
{
public string CodeStr = "";
public int X = 0;
public int Y = 0;
public string CodeType;
public double Orientation = 0;
public CodeInfo()
{
}
public CodeInfo(string codeStr, int x, int y)
{
this.CodeStr = codeStr;
this.X = x;
this.Y = y;
}
public CodeInfo(string codeStr, int x, int y, string type)
{
this.CodeType = type;
this.CodeStr = codeStr;
this.X = x;
this.Y = y;
}
public string GetCodeStr()
{
return Gb2312Correct(CodeStr);
}
/// <summary>
/// 判断字符串中是否包含中文
/// </summary>
/// <param name="str">需要判断的字符串</param>
/// <returns>判断结果</returns>
public static bool HasChinese(string str)
{
return Regex.IsMatch(str, @"[\u4e00-\u9fa5]");
}
/// <summary>
/// utf8文字用gb2312格式显示时候乱码,需要转换为gb2312
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string Gb2312Correct(string text)
{
//string ascii= Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(text));
//return ascii;
if (!HasChinese(text))
{
return text;
}
//声明字符集
System.Text.Encoding utf8, gb2312;
//utf8
utf8 = System.Text.Encoding.GetEncoding("utf-8");
//gb2312
gb2312 = System.Text.Encoding.GetEncoding("gb2312");
byte[] gb;
gb = utf8.GetBytes(text);
//utf8.GetString(System.Text.Encoding.Convert(utf8, gb2312, gb));
gb = System.Text.Encoding.Convert(utf8, gb2312, gb);
//返回转换后的字符
string s = utf8.GetString(gb);
int sp = 0;
while (true)
{
sp = s.IndexOf("?", sp + 1);
if (sp < 0)
break;
if (s.Substring(sp, 2) != "?;")
{
s = s.Insert(sp + 1, ";");
}
}
return s;
}
}
}
namespace IDHIKCamera
{
partial class FrmTest
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnIDHIKInit = new System.Windows.Forms.Button();
this.cbDeviceList = new System.Windows.Forms.ComboBox();
this.btnIDHIKTest = new System.Windows.Forms.Button();
this.btnExit = new System.Windows.Forms.Button();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.lblCodeInfo = new System.Windows.Forms.Label();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.btnStop = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// btnIDHIKInit
//
this.btnIDHIKInit.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnIDHIKInit.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.btnIDHIKInit.Location = new System.Drawing.Point(156, 79);
this.btnIDHIKInit.Name = "btnIDHIKInit";
this.btnIDHIKInit.Size = new System.Drawing.Size(137, 35);
this.btnIDHIKInit.TabIndex = 46;
this.btnIDHIKInit.Text = "IDHIK 加载相机";
this.btnIDHIKInit.UseVisualStyleBackColor = true;
this.btnIDHIKInit.Visible = false;
this.btnIDHIKInit.Click += new System.EventHandler(this.btnIDHIKInit_Click);
//
// cbDeviceList
//
this.cbDeviceList.Font = new System.Drawing.Font("微软雅黑", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.cbDeviceList.FormattingEnabled = true;
this.cbDeviceList.Location = new System.Drawing.Point(12, 6);
this.cbDeviceList.Name = "cbDeviceList";
this.cbDeviceList.Size = new System.Drawing.Size(929, 28);
this.cbDeviceList.TabIndex = 45;
//
// btnIDHIKTest
//
this.btnIDHIKTest.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnIDHIKTest.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.btnIDHIKTest.Location = new System.Drawing.Point(13, 40);
this.btnIDHIKTest.Name = "btnIDHIKTest";
this.btnIDHIKTest.Size = new System.Drawing.Size(137, 35);
this.btnIDHIKTest.TabIndex = 44;
this.btnIDHIKTest.Text = "IDHIK扫码测试";
this.btnIDHIKTest.UseVisualStyleBackColor = true;
this.btnIDHIKTest.Click += new System.EventHandler(this.btnIDHIKTest_Click);
//
// btnExit
//
this.btnExit.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnExit.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.btnExit.Location = new System.Drawing.Point(965, 9);
this.btnExit.Name = "btnExit";
this.btnExit.Size = new System.Drawing.Size(127, 35);
this.btnExit.TabIndex = 47;
this.btnExit.Text = "关闭";
this.btnExit.UseVisualStyleBackColor = true;
this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
//
// pictureBox1
//
this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pictureBox1.Location = new System.Drawing.Point(13, 120);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(1079, 616);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.pictureBox1.TabIndex = 48;
this.pictureBox1.TabStop = false;
//
// lblCodeInfo
//
this.lblCodeInfo.AutoSize = true;
this.lblCodeInfo.Location = new System.Drawing.Point(353, 40);
this.lblCodeInfo.Name = "lblCodeInfo";
this.lblCodeInfo.Size = new System.Drawing.Size(77, 12);
this.lblCodeInfo.TabIndex = 50;
this.lblCodeInfo.Text = "扫到条码信息";
//
// checkBox1
//
this.checkBox1.AutoSize = true;
this.checkBox1.Font = new System.Drawing.Font("宋体", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.checkBox1.Location = new System.Drawing.Point(156, 49);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(82, 18);
this.checkBox1.TabIndex = 51;
this.checkBox1.Text = "循环测试";
this.checkBox1.UseVisualStyleBackColor = true;
//
// btnStop
//
this.btnStop.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnStop.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.btnStop.Location = new System.Drawing.Point(13, 81);
this.btnStop.Name = "btnStop";
this.btnStop.Size = new System.Drawing.Size(137, 35);
this.btnStop.TabIndex = 52;
this.btnStop.Text = "停止测试";
this.btnStop.UseVisualStyleBackColor = true;
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// FrmTest
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1095, 748);
this.Controls.Add(this.btnStop);
this.Controls.Add(this.checkBox1);
this.Controls.Add(this.lblCodeInfo);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.btnExit);
this.Controls.Add(this.btnIDHIKInit);
this.Controls.Add(this.cbDeviceList);
this.Controls.Add(this.btnIDHIKTest);
this.Name = "FrmTest";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "IDHIK Scan Test";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.Load += new System.EventHandler(this.FrmTest_Load);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnIDHIKInit;
private System.Windows.Forms.ComboBox cbDeviceList;
private System.Windows.Forms.Button btnIDHIKTest;
private System.Windows.Forms.Button btnExit;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Label lblCodeInfo;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.Button btnStop;
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace IDHIKCamera
{
public partial class FrmTest : Form
{
public FrmTest()
{
InitializeComponent();
pictureBox1.Show();
}
/// <summary>
/// 初始化摄像机名称和二维码类型
/// </summary>
public static void LoadConfig()
{
try
{
IDHIK.Instance.Load();
List<string> names = IDHIK.Instance.cameraName;
if (names != null)
{
// hikNameList.AddRange(names);
foreach (string name in names)
{
LibLogUtil.Info("加载到IDHIK相机:" + name);
}
}
//IDHIK.Instance.OpenAll();
}
catch (Exception ex)
{
LibLogUtil.Error("解析IDHIK出错:" + ex.StackTrace);
}
}
private void btnIDHIKInit_Click(object sender, EventArgs e)
{
LoadConfig();
foreach (string name in IDHIK.Instance.cameraName)
{
cbDeviceList.Items.Add(name);
}
if (cbDeviceList.Items.Count > 0)
{
cbDeviceList.SelectedIndex = 0;
btnIDHIKInit.Visible = false;
}
}
private Task scanTask = null;
private int count = 0;
private void btnIDHIKTest_Click(object sender, EventArgs e)
{
StopTest = true;
string cName = cbDeviceList.Text;
if (cName == "")
{
return;
}
ScanTest(cName);
count = 1;
if (checkBox1.Checked)
{
StopTest = false;
scanTask = Task.Factory.StartNew(() =>
{
while (checkBox1.Checked)
{
if (StopTest)
{
break;
}
count++;
ScanTest(cName);
Thread.Sleep(100);
}
});
}
}
private void ScanTest(string cName)
{
try
{
List<CodeInfo> codes = CameraScan(new string[] { cName });
lblCodeInfo.Text = "";
string str = $"扫码{count}:\r\n";
foreach (CodeInfo code in codes)
{
str += $"[{code.CodeType}][{code.X},{code.Y}]{code.CodeStr}\r\n";
}
lblCodeInfo.Text = str;
}
catch (Exception ex)
{
LibLogUtil.Error("出错:" + ex.ToString());
}
}
[HandleProcessCorruptedStateExceptions]
public List<CodeInfo> CameraScan(string[] cameraNameList)
{
HashSet<string> codestr = new HashSet<string>();
List<CodeInfo> codeList = new List<CodeInfo>();
if (cameraNameList == null || cameraNameList.Length <= 0)
{
throw new Exception("CameraScan方法没有传入相机名称.");
}
try
{
foreach (string cameraName in cameraNameList)
{
string r = "";
LibLogUtil.Info($"【" + cameraName + "】开始取图片");
if (cameraName.Trim().Equals(""))
{
continue;
}
DateTime startTime = DateTime.Now;
Image bmp = null;
try
{
bmp = IDHIK.Instance.GrabOne(cameraName, out List<CodeInfo> cc);
//HalconDotNet.HOperatorSet.RotateImage()
if (bmp == null)
{
LibLogUtil.Error(" 【" + cameraName + "】取图片失败[" + IDHIK.Instance._errInfo + "],关闭相机");
IDHIK.Instance.Close(cameraName);
continue;
}
LibLogUtil.Info(" 【" + cameraName + "】取图片扫码完成,数量【" + cc.Count + "】");
cc.ForEach((c) =>
{
if (!codestr.Contains(c.CodeStr))
{
codeList.Add(c);
codestr.Add(c.CodeStr);
r += "##" + c.CodeStr;
}
});
LibLogUtil.Info(" 【" + cameraName + "】" + " 扫码完成【" + (DateTime.Now - startTime).TotalSeconds.ToString() + "】 " + count + ":" + r);
pictureBox1.Image = (Image)bmp;
pictureBox1.Refresh();
}
catch (AccessViolationException e)
{
LibLogUtil.Error(" 扫码出现AccessViolationException异常,关闭相机【" + cameraName + "】:" + e.ToString());
// GC.Collect();
}
catch (Exception ex)
{
LibLogUtil.Error(" 扫码出错:" + ex.ToString());
}
finally
{
if (bmp != null)
bmp.Dispose();
}
}
}
catch (AccessViolationException e)
{
LibLogUtil.Error(" 扫码出现AccessViolationException异常:" + e.ToString());
}
catch (Exception ex)
{
LibLogUtil.Error(" 扫码出错:" + ex.ToString());
}
return codeList;
}
private bool StopTest = false;
private void btnExit_Click(object sender, EventArgs e)
{
StopTest = true;
checkBox1.Checked = false;
this.Close();
}
private void FrmTest_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
LoadConfig();
foreach (string name in IDHIK.Instance.cameraName)
{
cbDeviceList.Items.Add(name);
}
if (cbDeviceList.Items.Count > 0)
{
cbDeviceList.SelectedIndex = 0;
}
else
{
btnIDHIKInit.Visible = true;
}
}
private void btnStop_Click(object sender, EventArgs e)
{
checkBox1.Checked = false;
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
\ No newline at end of file
using System;
namespace IDHIKCamera
{
public class LibLogUtil
{
public delegate void LogEventHandler(LibLogEventArg libLogEventArg);
public static event LogEventHandler LogEvent;
public static string prefix_log = "IDHIKCamera-";
public static void Info(string msg)
{
LogEvent?.Invoke(new LibLogEventArg()
{
Msg = $"{prefix_log}{msg}",
Level = LibLogLevel.Info
});
}
public static void Warn(string msg)
{
LogEvent?.Invoke(new LibLogEventArg()
{
Msg = $"{prefix_log}{msg}",
Level = LibLogLevel.Warning,
});
}
public static void Error(string msg, Exception ex = null)
{
LogEvent?.Invoke(new LibLogEventArg()
{
Msg = $"{prefix_log}{msg}",
Level = LibLogLevel.Error,
Exception = ex
});
}
}
public class LibLogEventArg : EventArgs
{
public string Msg { get; set; }
public LibLogLevel Level { get; set; }
public Exception Exception { get; set; }
}
public enum LibLogLevel
{
Debug,
Info,
Warning,
Error
}
}
using MvCodeReaderSDKNet;
using MVIDCodeReaderNet;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
namespace IDHIKCamera
{
public class IDHIK
{
private IDHIK() { }
private static IDHIK instance = null;
public static IDHIK Instance
{
get
{
if (instance == null)
{
instance = new IDHIK();
}
return instance;
}
}
protected string[] _name;
public string _errInfo;
protected int _count;
protected bool[] _isOpen;
public List<string> cameraName = new List<string>();
public bool DrawLine = true;
/// <summary>
/// 当前相机
/// </summary>
private MvCodeReader[] cameraCurr;
/// <summary>
/// 所有相机列表
/// </summary>
private MvCodeReader.MV_CODEREADER_DEVICE_INFO_LIST cameraAll;
private bool LoadOk = false;
public bool Load()
{
if (LoadOk)
{
return true;
}
try
{
LoadOk = true;
cameraAll = new MvCodeReader.MV_CODEREADER_DEVICE_INFO_LIST();
cameraAll.nDeviceNum = 0;
int nRet = MvCodeReader.MV_CODEREADER_EnumDevices_NET(ref cameraAll, MvCodeReader.MV_CODEREADER_GIGE_DEVICE);
if (0 != nRet)
{
SetErrorMsg("Load failed", nRet);
LibLogUtil.Error("IDHIK Load camera error : " + _errInfo);
return false;
}
cameraName = new List<string>();
string strUserDefinedName = "";
for (int i = 0; i < cameraAll.nDeviceNum; i++)
{
MvCodeReader.MV_CODEREADER_DEVICE_INFO stDevInfo = (MvCodeReader.MV_CODEREADER_DEVICE_INFO)Marshal.PtrToStructure(cameraAll.pDeviceInfo[i], typeof(MvCodeReader.MV_CODEREADER_DEVICE_INFO));
if (stDevInfo.nTLayerType == MvCodeReader.MV_CODEREADER_GIGE_DEVICE)
{
IntPtr buffer = Marshal.UnsafeAddrOfPinnedArrayElement(stDevInfo.SpecialInfo.stGigEInfo, 0);
MvCodeReader.MV_CODEREADER_GIGE_DEVICE_INFO stGigEDeviceInfo = (MvCodeReader.MV_CODEREADER_GIGE_DEVICE_INFO)Marshal.PtrToStructure(buffer, typeof(MvCodeReader.MV_CODEREADER_GIGE_DEVICE_INFO));
string name = "";
if (stGigEDeviceInfo.chUserDefinedName != "")
{
byte[] byteUserDefinedName = Encoding.GetEncoding("GB2312").GetBytes(stGigEDeviceInfo.chUserDefinedName);
bool bIsValidUTF8 = IsTextUTF8(byteUserDefinedName);
if (bIsValidUTF8)
{
strUserDefinedName = Encoding.UTF8.GetString(byteUserDefinedName);
}
else
{
strUserDefinedName = Encoding.GetEncoding("GB2312").GetString(byteUserDefinedName);
}
name = "GEV: " + strUserDefinedName + " (" + stGigEDeviceInfo.chSerialNumber + ")";
}
else
{
name = stGigEDeviceInfo.chModelName + " (" + stGigEDeviceInfo.chSerialNumber + ")";
}
if (name.Contains("ID"))
{
LibLogUtil.Info("IDHIK 加载到相机:" + name);
}
else
{
LibLogUtil.Info("IDHIK 加载到相机:" + name + ",非ID相机");
}
cameraName.Add(name);
}
}
_name = cameraName.ToArray();
_count = cameraName.Count;
_isOpen = new bool[_count];
cameraCurr = new MvCodeReader[_count];
SetErrorMsg("Load OK");
LibLogUtil.Info("IDHIK 加载完成,共" + _count + "个相机:");
return true;
}
catch (Exception ex)
{
SetErrorMsg(ex.Message);
return false;
}
}
public bool OpenAll()
{
lock (cameraCurr)
{
bool rtn = true;
for (int i = 0; i < cameraName.Count; i++)
{
rtn = Open(i);
if (!rtn) break;
}
return rtn;
}
}
public bool Open(string name)
{
int n = cameraName.FindIndex(s => s == name);
if (n == -1)
{
SetErrorMsg(name + " Not find", n);
return false;
}
else
return Open(n);
}
public bool Open(int index)
{
lock (cameraCurr)
{
// _index = index;
if (index < 0 || index >= _count)
{
SetErrorMsg("Not find index :" + index);
LibLogUtil.Error("open camera " + index + " error : " + _errInfo);
return false;
}
if (cameraCurr[index] != null) Close(index);
try
{
MvCodeReader.MV_CODEREADER_DEVICE_INFO stDevInfo = (MvCodeReader.MV_CODEREADER_DEVICE_INFO)Marshal.PtrToStructure(cameraAll.pDeviceInfo[index], typeof(MvCodeReader.MV_CODEREADER_DEVICE_INFO));
cameraCurr[index] = new MvCodeReader();
int nRet = cameraCurr[index].MV_CODEREADER_CreateHandle_NET(ref stDevInfo);
if (nRet != MvCodeReader.MV_CODEREADER_OK)
{
SetErrorMsg("open camera " + index + " error MV_CODEREADER_CreateHandle_NET fail : ", nRet);
return false;
}
nRet = cameraCurr[index].MV_CODEREADER_OpenDevice_NET();
if (MvCodeReader.MV_CODEREADER_OK != nRet)
{
cameraCurr[index].MV_CODEREADER_DestroyHandle_NET();
SetErrorMsg("open camera " + index + " error MV_CODEREADER_OpenDevice_NET fail : ", nRet);
return false;
}
// ch:设置采集连续模式 | en:Set Continues Aquisition Mode
cameraCurr[index].MV_CODEREADER_SetEnumValue_NET("TriggerMode", (uint)MvCodeReader.MV_CODEREADER_TRIGGER_MODE.MV_CODEREADER_TRIGGER_MODE_OFF);
_isOpen[index] = true;
SetErrorMsg("OK");
LibLogUtil.Info("open camera " + index + " " + _errInfo);
return true;
}
catch (Exception ex)
{
LibLogUtil.Error("打开相机出错:" + ex.ToString());
SetErrorMsg(ex.Message);
return false;
}
}
}
public bool Open_AddParameter(int index)
{
lock (cameraCurr)
{
// _index = index;
if (index < 0 || index >= _count)
{
SetErrorMsg("Not find index :" + index);
LibLogUtil.Error("open camera " + index + " error : " + _errInfo);
return false;
}
if (cameraCurr[index] != null) Close(index);
try
{
MvCodeReader.MV_CODEREADER_DEVICE_INFO stDevInfo = (MvCodeReader.MV_CODEREADER_DEVICE_INFO)Marshal.PtrToStructure(cameraAll.pDeviceInfo[index], typeof(MvCodeReader.MV_CODEREADER_DEVICE_INFO));
cameraCurr[index] = new MvCodeReader();
int nRet = cameraCurr[index].MV_CODEREADER_CreateHandle_NET(ref stDevInfo);
if (nRet != MvCodeReader.MV_CODEREADER_OK)
{
SetErrorMsg("open camera " + index + " error MV_CODEREADER_CreateHandle_NET fail : ", nRet);
return false;
}
nRet = cameraCurr[index].MV_CODEREADER_OpenDevice_NET();
if (MvCodeReader.MV_CODEREADER_OK != nRet)
{
cameraCurr[index].MV_CODEREADER_DestroyHandle_NET();
SetErrorMsg("open camera " + index + " error MV_CODEREADER_OpenDevice_NET fail : ", nRet);
return false;
}
//1.相机修改为相机修改normal模式
var RunningMode = cameraCurr[index].MV_CODEREADER_SetEnumValue_NET("RunningMode", 0);
LibLogUtil.Info($"设置为normal模式为:{RunningMode}");
//2.设置为触发模式
var tggerMode = cameraCurr[index].MV_CODEREADER_SetEnumValue_NET("tggerMode", 0);
LibLogUtil.Info($"设置为触发模式为:{tggerMode}");
//3.设置为软触发
var TriggerMode = cameraCurr[index].MV_CODEREADER_SetEnumValue_NET("TriggerMode", 1);
LibLogUtil.Info($"设置为软触发模式为:{TriggerMode}");
//4.设置软触发源
var TriggerSource = cameraCurr[index].MV_CODEREADER_SetEnumValue_NET("TriggerSource", 7);
LibLogUtil.Info($"设置为软触发源:{TriggerSource}");
//5.设置拍照张数
var AcquisitionBurstFrameCount = cameraCurr[index].MV_CODEREADER_SetIntValue_NET("AcquisitionBurstFrameCount", 5);
LibLogUtil.Info($"设置拍照张数:{AcquisitionBurstFrameCount}");
//6.设置图片压缩比例
var JpgQuality = cameraCurr[index].MV_CODEREADER_SetIntValue_NET("JpgQuality", 50);
LibLogUtil.Info($"设置图片压缩比例:{JpgQuality}");
//ch:设置采集连续模式 | en:Set Continues Aquisition Mode
//cameraCurr[index].MV_CODEREADER_SetEnumValue_NET("TriggerMode", (uint)MvCodeReader.MV_CODEREADER_TRIGGER_MODE.MV_CODEREADER_TRIGGER_MODE_OFF);
_isOpen[index] = true;
SetErrorMsg("OK");
LibLogUtil.Info("open camera " + index + " " + _errInfo);
return true;
}
catch (Exception ex)
{
LibLogUtil.Error("打开相机出错:" + ex.ToString());
SetErrorMsg(ex.Message);
return false;
}
}
}
public Image GrabOne_AddParameter(int index, out List<CodeInfo> codeInfos)
{
codeInfos = new List<CodeInfo>();
if (cameraCurr[index] == null || ((!_isOpen[index])))
{
bool result = Open(index);
if (!result)
{
return null;
}
}
if (cameraCurr[index] == null)
{
SetErrorMsg("Camera null");
return null;
}
try
{
return ImageCapture(index, out codeInfos);
}
catch (Exception ex)
{
SetErrorMsg(ex.Message);
return null;
}
finally
{
if (cameraCurr[index] != null)
{
cameraCurr[index].MV_CODEREADER_StopGrabbing_NET();
var LineSelector=cameraCurr[index].MV_CODEREADER_SetEnumValue_NET("LineSelector",5);
LibLogUtil.Info($"前置条件:{LineSelector}");
var LineInverter=cameraCurr[index].MV_CODEREADER_SetBoolValue_NET("LineInverter", false);
LibLogUtil.Info($"关闭光源:{LineInverter}");
}
//Task.Run(() => { IDHIK.Instance.Close(index); Thread.Sleep(500); IDHIK.Instance.Open(index); });
}
}
public void Close(int index)
{
lock (cameraCurr)
{
if (cameraCurr[index] != null)
{
LibLogUtil.Info($" close camer [{index}] ");
_isOpen[index] = false;
cameraCurr[index].MV_CODEREADER_CloseDevice_NET();
cameraCurr[index].MV_CODEREADER_DestroyHandle_NET();
cameraCurr[index] = null;
}
}
}
public void Close(string name)
{
lock (cameraCurr)
{
int index = cameraName.FindIndex(s => s == name);
if (index == -1)
{
SetErrorMsg($"name {name} Not find");
return;
}
if (cameraCurr[index] != null)
{
LibLogUtil.Info($" close camera [{name}] [{index}] ");
_isOpen[index] = false;
cameraCurr[index].MV_CODEREADER_CloseDevice_NET();
cameraCurr[index].MV_CODEREADER_DestroyHandle_NET();
cameraCurr[index] = null;
}
}
}
public void CloseAll()
{
if (cameraCurr == null)
return;
lock (cameraCurr)
{
LibLogUtil.Info(" cameraCurr.Length : " + cameraCurr.Length.ToString());
for (int i = 0; i < cameraCurr.Length; i++)
{
if (cameraCurr[i] != null)
{
LibLogUtil.Info($" close cameraCurr[{i}] ");
_isOpen[i] = false;
cameraCurr[i].MV_CODEREADER_CloseDevice_NET();
cameraCurr[i].MV_CODEREADER_DestroyHandle_NET();
cameraCurr[i] = null;
}
}
}
}
public Image GrabOne(int index, out List<CodeInfo> codeInfos)
{
codeInfos = new List<CodeInfo>();
if (cameraCurr[index] == null || ((!_isOpen[index])))
{
bool result = Open(index);
if (!result)
{
return null;
}
}
if (cameraCurr[index] == null)
{
SetErrorMsg("Camera null");
return null;
}
try
{
return ImageCapture(index, out codeInfos);
}
catch (Exception ex)
{
SetErrorMsg(ex.Message);
return null;
}
finally
{
if (cameraCurr[index] != null)
{
cameraCurr[index].MV_CODEREADER_StopGrabbing_NET();
}
Task.Run(() => { IDHIK.Instance.Close(index); Thread.Sleep(500); IDHIK.Instance.Open(index); });
}
}
public Image GrabOne(string name, out List<CodeInfo> codeInfos)
{
codeInfos = new List<CodeInfo>();
int idx = Array.FindIndex(_name, s => s == name);
if (idx == -1)
return null;
else
return GrabOne(idx, out codeInfos);
}
// ch:用于从驱动获取图像的缓存 | en:Buffer for getting image from driver
private byte[] m_BufForDriver = new byte[1024 * 1024 * 20];
private Bitmap bmp = null;
private Image ImageCapture(int index, out List<CodeInfo> codeList)
{
IntPtr pstFrameInfoEx2= IntPtr.Zero, pData= IntPtr.Zero;
codeList = new List<CodeInfo>();
if (!StartGrabbing(index))
{
return null;
}
try
{
int nRet = MvCodeReader.MV_CODEREADER_OK;
pData = IntPtr.Zero;
MvCodeReader.MV_CODEREADER_IMAGE_OUT_INFO_EX2 stFrameInfoEx2 = new MvCodeReader.MV_CODEREADER_IMAGE_OUT_INFO_EX2();
pstFrameInfoEx2 = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MvCodeReader.MV_CODEREADER_IMAGE_OUT_INFO_EX2)));
Marshal.StructureToPtr(stFrameInfoEx2, pstFrameInfoEx2, false);
//Thread.Sleep(500);
nRet = cameraCurr[index].MV_CODEREADER_GetOneFrameTimeoutEx2_NET(ref pData, pstFrameInfoEx2, 3000);
LibLogUtil.Info($"获取结果{nRet}");
if (nRet == MvCodeReader.MV_CODEREADER_OK)
{
stFrameInfoEx2 = (MvCodeReader.MV_CODEREADER_IMAGE_OUT_INFO_EX2)Marshal.PtrToStructure(pstFrameInfoEx2, typeof(MvCodeReader.MV_CODEREADER_IMAGE_OUT_INFO_EX2));
}
else
{
LibLogUtil.Error($"结果不等于0,出错{nRet}");
}
List<Point[]> pts=new List<Point[]>();
if (nRet == MvCodeReader.MV_CODEREADER_OK)
{
if (0 >= stFrameInfoEx2.nFrameLen)
{
SetErrorMsg("Can not grab one : ", nRet);
return null;
}
MvCodeReader.MV_CODEREADER_RESULT_BCR_EX2 stBcrResultEx2 = (MvCodeReader.MV_CODEREADER_RESULT_BCR_EX2)Marshal.PtrToStructure(stFrameInfoEx2.UnparsedBcrList.pstCodeListEx2, typeof(MvCodeReader.MV_CODEREADER_RESULT_BCR_EX2));
for (int i = 0; i < stBcrResultEx2.nCodeNum; ++i)
{
// 条码位置的4个点坐标
Point[] stPointList = new Point[4];
CodeInfo code = new CodeInfo();
int suX = 0;
int suY = 0;
for (int j = 0; j < 4; ++j)
{
stPointList[j].X = (int)(stBcrResultEx2.stBcrInfoEx2[i].pt[j].x);
stPointList[j].Y = (int)(stBcrResultEx2.stBcrInfoEx2[i].pt[j].y);
suX += (int)(stBcrResultEx2.stBcrInfoEx2[i].pt[j].x);
suY += (int)(stBcrResultEx2.stBcrInfoEx2[i].pt[j].y);
}
pts.Add(stPointList);
code.CodeType = GetBarType((MvCodeReader.MV_CODEREADER_CODE_TYPE)stBcrResultEx2.stBcrInfoEx2[i].nBarType);
String strCode = System.Text.Encoding.Default.GetString(stBcrResultEx2.stBcrInfoEx2[i].chCode);
//code.CodeStr = ReplaceCode( String.IsNullOrEmpty(strCode) ? "" : strCode);
code.CodeStr = RemoveNUL(String.IsNullOrEmpty(strCode) ? "" : strCode);
code.Orientation = stBcrResultEx2.stBcrInfoEx2[i].nAngle;
code.X = suX / 4;
code.Y = suY / 4;
codeList.Add(code);
}
// 绘制图像
Marshal.Copy(pData, m_BufForDriver, 0, (int)stFrameInfoEx2.nFrameLen);
if (stFrameInfoEx2.enPixelType == MvCodeReader.MvCodeReaderGvspPixelType.PixelType_CodeReader_Gvsp_Mono8)
{
IntPtr pImage = Marshal.UnsafeAddrOfPinnedArrayElement(m_BufForDriver, 0);
bmp = new Bitmap(stFrameInfoEx2.nWidth, stFrameInfoEx2.nHeight, stFrameInfoEx2.nWidth, PixelFormat.Format8bppIndexed, pImage);
ColorPalette cp = bmp.Palette;
for (int i = 0; i < 256; i++)
{
cp.Entries[i] = Color.FromArgb(i, i, i);
}
bmp.Palette = cp;
if (DrawLine)
{
Graphics g = Graphics.FromImage(bmp);
Pen pen = new Pen(Color.Blue, 3); // 画笔颜色
foreach (Point[] points in pts)
{
g.DrawPolygon(pen, points);
}
g.Save();
g.Dispose();
}
return bmp;
}
else if (stFrameInfoEx2.enPixelType == MvCodeReader.MvCodeReaderGvspPixelType.PixelType_CodeReader_Gvsp_Jpeg)
{
MemoryStream ms = new MemoryStream();
ms.Write(m_BufForDriver, 0, (int)stFrameInfoEx2.nFrameLen);
Image img = Bitmap.FromStream(ms);
if (DrawLine)
{
Graphics g = Graphics.FromImage(img);
Pen pen = new Pen(Color.Blue, 3); // 画笔颜色
foreach (Point[] points in pts)
{
g.DrawPolygon(pen, points);
}
g.Save();
g.Dispose();
}
return img;
}
}
}
catch (Exception ex)
{
SetErrorMsg(ex.ToString());
}
finally
{
StopGrabbing(index);
Marshal.FreeHGlobal(pstFrameInfoEx2);
//Marshal.FreeHGlobal(pData);
}
return null;
}
private bool StartGrabbing(int index)
{
// ch:开始采集 | en:Start Grabbing
int rtn = cameraCurr[index].MV_CODEREADER_StartGrabbing_NET();
LibLogUtil.Info($"相机索引:{rtn}");
if (rtn != MvCodeReader.MV_CODEREADER_OK)
{
SetErrorMsg("Can not grab one : ", rtn);
return false;
}
return true;
}
private bool StopGrabbing(int index)
{
// ch:停止采集 | en:Stop Grabbing
int nRet = cameraCurr[index].MV_CODEREADER_StopGrabbing_NET();
LibLogUtil.Info($"关闭结果{nRet};索引{index}");
if (nRet != MvCodeReader.MV_CODEREADER_OK)
{
SetErrorMsg("Stop Grabbing Fail!", nRet);
return false;
}
return true;
}
public static T DeepClone<T>(T _object)
{
try
{
T dstobject;
using (MemoryStream mStream = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(mStream, _object);
mStream.Seek(0, SeekOrigin.Begin);//指定当前流的位置为流的开头。
dstobject = (T)bf.Deserialize(mStream);
mStream.Close();
}
return dstobject;
}
catch (Exception e)
{
LibLogUtil.Error("DeepClone" + e.ToString());
return default;
}
}
private static void __OnFreeCallBack(IntPtr pImg)
{
Marshal.FreeHGlobal(pImg);
}
// ch:显示错误信息 | en:Show error message
private string SetErrorMsg(string csMessage, int nErrorNum = 0)
{
string errorMsg;
if (nErrorNum == 0)
{
errorMsg = csMessage;
}
else
{
errorMsg = csMessage + ": Error =" + String.Format("{0:X}", nErrorNum);
}
switch (nErrorNum)
{
case MvCodeReader.MV_CODEREADER_E_HANDLE: errorMsg += " Error or invalid handle "; break;
case MvCodeReader.MV_CODEREADER_E_SUPPORT: errorMsg += " Not supported function "; break;
case MvCodeReader.MV_CODEREADER_E_BUFOVER: errorMsg += " Cache is full "; break;
case MvCodeReader.MV_CODEREADER_E_CALLORDER: errorMsg += " Function calling order error "; break;
case MvCodeReader.MV_CODEREADER_E_PARAMETER: errorMsg += " Incorrect parameter "; break;
case MvCodeReader.MV_CODEREADER_E_RESOURCE: errorMsg += " Applying resource failed "; break;
case MvCodeReader.MV_CODEREADER_E_NODATA: errorMsg += " No data "; break;
case MvCodeReader.MV_CODEREADER_E_PRECONDITION: errorMsg += " Precondition error, or running environment changed "; break;
case MvCodeReader.MV_CODEREADER_E_VERSION: errorMsg += " Version mismatches "; break;
case MvCodeReader.MV_CODEREADER_E_NOENOUGH_BUF: errorMsg += " Insufficient memory "; break;
case MvCodeReader.MV_CODEREADER_E_UNKNOW: errorMsg += " Unknown error "; break;
case MvCodeReader.MV_CODEREADER_E_GC_GENERIC: errorMsg += " General error "; break;
case MvCodeReader.MV_CODEREADER_E_GC_ACCESS: errorMsg += " Node accessing condition error "; break;
case MvCodeReader.MV_CODEREADER_E_ACCESS_DENIED: errorMsg += " No permission "; break;
case MvCodeReader.MV_CODEREADER_E_BUSY: errorMsg += " Device is busy, or network disconnected "; break;
case MvCodeReader.MV_CODEREADER_E_NETER: errorMsg += " Network error "; break;
}
_errInfo = errorMsg;
// if(nErrorNum > 0)
{
LibLogUtil.Error(errorMsg);
}
return errorMsg;
}
private static String GetBarType(MvCodeReader.MV_CODEREADER_CODE_TYPE nBarType)
{
switch (nBarType)
{
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_TDCR_DM:
return "Data Matrix";
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_TDCR_QR:
return "QR Code";
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_EAN8:
return "EAN-8";
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_UPCE:
return "UPC-E";
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_UPCA:
return "UPC-A";
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_EAN13:
return "EAN-13";
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_ISBN13:
return "ISBN-13";
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_CODABAR:
return "Codabar";
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_ITF25:
return "ITF-25";
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_CODE39:
return "Code 39";
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_CODE93:
return "Code 93";
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_CODE128:
return "Code 128";
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_TDCR_PDF417:
return "PDF417";
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_MATRIX25:
return "MATRIX25";
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_MSI:
return "MSI";
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_CODE11:
return "Code 11";
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_INDUSTRIAL25:
return "Industral-25";
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_CHINAPOST:
return "CHINAPOST";
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_ITF14:
return "ITF-14";
case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_TDCR_ECC140:
return "ECC140";
default:
return "/";
}
}
// 判断字符编码
public static bool IsTextUTF8(byte[] inputStream)
{
int encodingBytesCount = 0;
bool allTextsAreASCIIChars = true;
for (int i = 0; i < inputStream.Length; i++)
{
byte current = inputStream[i];
if ((current & 0x80) == 0x80)
{
allTextsAreASCIIChars = false;
}
// First byte
if (encodingBytesCount == 0)
{
if ((current & 0x80) == 0)
{
// ASCII chars, from 0x00-0x7F
continue;
}
if ((current & 0xC0) == 0xC0)
{
encodingBytesCount = 1;
current <<= 2;
// More than two bytes used to encoding a unicode char.
// Calculate the real length.
while ((current & 0x80) == 0x80)
{
current <<= 1;
encodingBytesCount++;
}
}
else
{
// Invalid bits structure for UTF8 encoding rule.
return false;
}
}
else
{
// Following bytes, must start with 10.
if ((current & 0xC0) == 0x80)
{
encodingBytesCount--;
}
else
{
// Invalid bits structure for UTF8 encoding rule.
return false;
}
}
}
if (encodingBytesCount != 0)
{
// Invalid bits structure for UTF8 encoding rule.
// Wrong following bytes count.
return false;
}
// Although UTF8 supports encoding for ASCII chars, we regard as a input stream, whose contents are all ASCII as default encoding.
return !allTextsAreASCIIChars;
}
public static string RemoveNUL(string input)
{
// 将 [NUL] 隐藏字符,替换为空字符串
string result = input.Replace("\x00", "");
return result;
}
/// <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();
if (!HasChinese(message))
{
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(00))
{
continue;
}
if (!value.Equals(24))
{
newBytes.Add(by);
}
}
message = asciiEncoding.GetString(newBytes.ToArray());
}
return message;
}
public static bool HasChinese(string str)
{
return Regex.IsMatch(str, @"[\u4e00-\u9fa5]");
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{2FA7C3A5-E237-4C79-8F4A-4B71C218BE89}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>IDHIKCamera</RootNamespace>
<AssemblyName>IDHIKCamera</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="MvCodeReaderSDK.Net">
<HintPath>..\SharedDLL\MvCodeReaderSDK.Net.dll</HintPath>
</Reference>
<Reference Include="MVIDCodeReader.Net, Version=1.1.9.0, Culture=neutral, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>bin\Debug\MVIDCodeReader.Net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CodeInfo.cs" />
<Compile Include="FrmTest.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmTest.Designer.cs">
<DependentUpon>FrmTest.cs</DependentUpon>
</Compile>
<Compile Include="HDLogUtil.cs" />
<Compile Include="IDHIK.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="FrmTest.resx">
<DependentUpon>FrmTest.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Content Include="MvCodeReaderSDK.Net.dll" />
<Content Include="MvCodeReaderSDK.Net.XML" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
\ No newline at end of file
此文件的差异太大,无法显示。
此文件类型无法预览
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("IDHIKCamera")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IDHIKCamera")]
[assembly: AssemblyCopyright("Copyright © 2023")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("2fa7c3a5-e237-4c79-8f4a-4b71c218be89")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
......@@ -17,6 +17,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "paddleOCR", "paddleOCR\padd
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataHandling", "DataHandling\DataHandling.csproj", "{0F23B7DB-9953-46ED-9166-115646467647}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IDHIKCamera", "IDHIKCamera\IDHIKCamera.csproj", "{2FA7C3A5-E237-4C79-8F4A-4B71C218BE89}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
......@@ -111,6 +113,18 @@ Global
{0F23B7DB-9953-46ED-9166-115646467647}.Release|x64.Build.0 = Release|Any CPU
{0F23B7DB-9953-46ED-9166-115646467647}.Release|x86.ActiveCfg = Release|Any CPU
{0F23B7DB-9953-46ED-9166-115646467647}.Release|x86.Build.0 = Release|Any CPU
{2FA7C3A5-E237-4C79-8F4A-4B71C218BE89}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2FA7C3A5-E237-4C79-8F4A-4B71C218BE89}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2FA7C3A5-E237-4C79-8F4A-4B71C218BE89}.Debug|x64.ActiveCfg = Debug|Any CPU
{2FA7C3A5-E237-4C79-8F4A-4B71C218BE89}.Debug|x64.Build.0 = Debug|Any CPU
{2FA7C3A5-E237-4C79-8F4A-4B71C218BE89}.Debug|x86.ActiveCfg = Debug|Any CPU
{2FA7C3A5-E237-4C79-8F4A-4B71C218BE89}.Debug|x86.Build.0 = Debug|Any CPU
{2FA7C3A5-E237-4C79-8F4A-4B71C218BE89}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2FA7C3A5-E237-4C79-8F4A-4B71C218BE89}.Release|Any CPU.Build.0 = Release|Any CPU
{2FA7C3A5-E237-4C79-8F4A-4B71C218BE89}.Release|x64.ActiveCfg = Release|Any CPU
{2FA7C3A5-E237-4C79-8F4A-4B71C218BE89}.Release|x64.Build.0 = Release|Any CPU
{2FA7C3A5-E237-4C79-8F4A-4B71C218BE89}.Release|x86.ActiveCfg = Release|Any CPU
{2FA7C3A5-E237-4C79-8F4A-4B71C218BE89}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
......
......@@ -216,7 +216,8 @@ namespace SmartScan
BLLCommon.labelEdit.PrintLast(BLLCommon.config.DefaultPrintLabel, BLLCommon.config.PrinterName, BLLCommon.config.PrintLandscape, content, out string[] barcode);
LogNet.log.Info(string.Format("打印标签 Label[{0}] Printer[{1}]", BLLCommon.config.DefaultPrintLabel, BLLCommon.config.PrinterName));
var bmp = BLLCommon.labelEdit.PrintImage(BLLCommon.config.DefaultPrintLabel, content, out _);
_=UnifiedDataHandler.PostSmfImageAsync(bmp, new Dictionary<string, string> { { "cid", BLLCommon.config.CID+"_2" } }, bmp.Width, bmp.Height);
if (bmp != null)
_ =UnifiedDataHandler.PostSmfImageAsync(bmp, new Dictionary<string, string> { { "cid", BLLCommon.config.CID+"_2" } }, bmp.Width, bmp.Height);
bmp.Dispose();
//SaveRetrospect(labelBmp, barcode);
UnifiedDataHandler.RecordPrintNg(false, true, out string[] strarrys);
......
......@@ -237,6 +237,7 @@ namespace SmartScan
if (image.Count > 0)
{
BLLCommon.mateEdit.CurrntBitmap = image[0];
if (BLLCommon.mateEdit.CurrntBitmap!=null)
_ = UnifiedDataHandler.PostSmfImageAsync(BLLCommon.mateEdit.CurrntBitmap, new Dictionary<string, string> { { "cid", BLLCommon.config.CID + "_1" } }, BLLCommon.mateEdit.CurrntBitmap.Width, BLLCommon.mateEdit.CurrntBitmap.Height);
}
......
此文件类型无法预览
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!