Commit ca4d7705 刘韬

1

1 个父辈 f46a3c9a
正在显示 59 个修改的文件 包含 3944 行增加83 行删除
......@@ -45,10 +45,6 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>..\dll\Asa.PrintLabel.dll</HintPath>
</Reference>
<Reference Include="CodeLibrary, Version=1.0.8780.28463, Culture=neutral, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\dll\CodeLibrary.dll</HintPath>
</Reference>
<Reference Include="ConfigHelper">
<HintPath>..\dll\ConfigHelper.dll</HintPath>
</Reference>
......@@ -232,6 +228,10 @@
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CodeLibrary\CodeLibrary.csproj">
<Project>{2e0d9598-cb37-46dc-9c9b-d36d4d344451}</Project>
<Name>CodeLibrary</Name>
</ProjectReference>
<ProjectReference Include="..\Common\Common.csproj">
<Project>{43cdd09e-fcf3-4960-a01d-3bbfe9933122}</Project>
<Name>Common</Name>
......
......@@ -56,8 +56,8 @@ namespace AutoScanAndLabel
}
catch (Exception ex)
{
LogUtil.error(ex.Message);
throw new Exception(ex.Message); ;
LogUtil.error(ex.ToString());
throw new Exception(ex.ToString());
}
}
......
using Basler.Pylon;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeLibrary
{
public class BaslerCamera
{
public static BaslerCamera Instance= new BaslerCamera();
/// <summary>
/// 当前相机
/// </summary>
private Camera cameraCur = null;
/// <summary>
/// 所有相机列表
/// </summary>
private List<ICameraInfo> cameraAll;
/// <summary>
/// 所有相机的名称
/// </summary>
private List<string> cameraName;
/// <summary>
/// 获取连续图像
/// </summary>
public delegate void GrabImageEvent();
/// <summary>
/// 获取连续图像事件,需要跨线程操作
/// </summary>
public event GrabImageEvent GrabImage;
private BaslerCamera()
{
Load();
}
/// <summary>
/// 错误信息
/// </summary>
public string ErrInfo { set; get; }
/// <summary>
/// 相机总数
/// </summary>
public int Count
{
get { return cameraAll == null ? 0 : cameraAll.Count; }
}
/// <summary>
/// 相机名称,ModelName,SerialNumber
/// </summary>
public string[] CameraName
{
get {
if (cameraName == null)
{
cameraName = new List<string>();
}
return cameraName.ToArray(); }
}
/// <summary>
/// 当前相机是否打开
/// </summary>
public bool IsOpen
{
get
{
if (cameraCur == null)
return false;
else
return cameraCur.IsOpen;
}
}
/// <summary>
/// 相机图像宽度
/// </summary>
public int Width { set; get; }
/// <summary>
/// 相机图像高度
/// </summary>
public int Height { set; get; }
/// <summary>
/// 相机32位缓存
/// </summary>
public byte[] Buffer { get; private set; }
/// <summary>
/// 相机32位图像
/// </summary>
public Bitmap Image { get; private set; }
/// <summary>
/// 加载相机
/// </summary>
public void Load()
{
try
{
cameraAll = CameraFinder.Enumerate();
cameraName = new List<string>();
foreach (ICameraInfo info in cameraAll)
cameraName.Add(info[CameraInfoKey.ModelName].ToString() + " (" + info[CameraInfoKey.SerialNumber].ToString() + ")");
}
catch (Exception ex)
{
HDLogUtil.error("Basler Load Error:" + ex.StackTrace);
}
}
/// <summary>
/// 打开指定相机
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public bool Open(string name)
{
int n = cameraName.FindIndex(s => s == name);
if (n == -1)
return false;
else
return Open(n);
}
/// <summary>
/// 打开指定相机
/// </summary>
/// <param name="idx">索引</param>
/// <returns></returns>
public bool Open(int idx)
{
if (idx < 0 || idx >= cameraAll.Count) return false;
if (cameraCur != null) Close();
try
{
cameraCur = new Camera(cameraAll[idx]);
//cameraCur.ConnectionLost += OnConnectionLost;
//cameraCur.CameraOpened += OnCameraOpened;
//cameraCur.CameraClosed += OnCameraClosed;
//cameraCur.StreamGrabber.GrabStarted += OnGrabStarted;
cameraCur.StreamGrabber.ImageGrabbed += OnImageGrabbed;
//cameraCur.StreamGrabber.GrabStopped += OnGrabStopped;
cameraCur.Open();
Width = Convert.ToInt32(cameraCur.Parameters[PLCamera.Width].GetValue());
Height = Convert.ToInt32(cameraCur.Parameters[PLCamera.Height].GetValue());
cameraCur.Parameters[PLCamera.UserSetSelector].SetValue(PLCamera.UserSetSelector.UserSet1); //加载用户设置1
bool bln = cameraCur.Parameters[PLCamera.UserSetLoad].TryExecute(); //执行设置
return true;
}
catch (Exception ex)
{
ErrInfo = ex.Message;
return false;
}
}
/// <summary>
/// 关闭当前相机
/// </summary>
public void Close()
{
if (cameraCur != null)
{
cameraCur.Close();
cameraCur.Dispose();
cameraCur = null;
}
}
/// <summary>
/// 停止抓取数据
/// </summary>
public void Stop()
{
if (cameraCur != null)
cameraCur.StreamGrabber.Stop();
}
/// <summary>
/// 抓取一张图像
/// </summary>
public void GrabOne()
{
cameraCur.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.SingleFrame);
//cameraCur.StreamGrabber.Start();
//IGrabResult grabResult = cameraCur.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);
IGrabResult grabResult = cameraCur.StreamGrabber.GrabOne(5000);
if (!grabResult.IsValid) return;
Image = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
BitmapData bmpData = Image.LockBits(new Rectangle(0, 0, grabResult.Width, grabResult.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
IntPtr ptrBmp = bmpData.Scan0;
int picSize = bmpData.Stride * grabResult.Height;
PixelDataConverter conv = new PixelDataConverter();
conv.OutputPixelFormat = PixelType.BGRA8packed;
conv.Convert(ptrBmp, picSize, grabResult);
Buffer = new byte[picSize];
System.Runtime.InteropServices.Marshal.Copy(ptrBmp, Buffer, 0, picSize);
Image.UnlockBits(bmpData);
//cameraCur.StreamGrabber.Stop();
}
/// <summary>
/// 抓取连续图像,触发GrabImage事件
/// </summary>
public void GrabContinuous()
{
cameraCur.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
cameraCur.StreamGrabber.Start(GrabStrategy.OneByOne, GrabLoop.ProvidedByStreamGrabber);
}
private void OnImageGrabbed(object sender, ImageGrabbedEventArgs e)
{
try
{
IGrabResult grabResult = e.GrabResult;
if (!grabResult.IsValid) return;
Image = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
BitmapData bmpData = Image.LockBits(new Rectangle(0, 0, grabResult.Width, grabResult.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
IntPtr ptrBmp = bmpData.Scan0;
int picSize = bmpData.Stride * grabResult.Height;
PixelDataConverter conv = new PixelDataConverter();
conv.OutputPixelFormat = PixelType.BGRA8packed;
conv.Convert(ptrBmp, picSize, grabResult);
Buffer = new byte[picSize];
System.Runtime.InteropServices.Marshal.Copy(ptrBmp, Buffer, 0, picSize);
Image.UnlockBits(bmpData);
GrabImage?.Invoke();
}
catch (Exception ex)
{
ErrInfo = ex.Message;
}
finally
{
e.DisposeGrabResultIfClone();
}
}
}
}
<?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>{2E0D9598-CB37-46DC-9C9B-D36D4D344451}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CodeLibrary</RootNamespace>
<AssemblyName>CodeLibrary</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</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>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Prefer32Bit>false</Prefer32Bit>
<PlatformTarget>x64</PlatformTarget>
</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>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="Basler.Pylon, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e389355f398382ab, processorArchitecture=x86">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\dll\Basler.Pylon.dll</HintPath>
</Reference>
<Reference Include="ConfigHelper">
<HintPath>..\..\..\..\..\类库\ConfigHelper.dll</HintPath>
</Reference>
<Reference Include="halcondotnet">
<HintPath>..\dll\halcondotnet.dll</HintPath>
</Reference>
<Reference Include="IDHIKCamera, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\dll\IDHIKCamera.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\dll\log4net.dll</HintPath>
</Reference>
<Reference Include="MvCameraControl.Net, Version=2.4.1.2, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\类库\MvCameraControl.Net.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\dll\Newtonsoft.Json.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" />
<Reference Include="zxing">
<HintPath>..\dll\zxing.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="camera\Common.cs" />
<Compile Include="camera\HIK.cs" />
<Compile Include="camera\HIKIDMVS.cs" />
<Compile Include="eyemDecode.cs" />
<Compile Include="eyemDecode2.cs" />
<Compile Include="FrmBase.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmBase.Designer.cs">
<DependentUpon>FrmBase.cs</DependentUpon>
</Compile>
<Compile Include="FrmCodeLearn.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmCodeLearn.Designer.cs">
<DependentUpon>FrmCodeLearn.cs</DependentUpon>
</Compile>
<Compile Include="FrmCodeDecode.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmCodeDecode.Designer.cs">
<DependentUpon>FrmCodeDecode.cs</DependentUpon>
</Compile>
<Compile Include="HDCodeHelper.cs" />
<Compile Include="HDCodeLearnHelper.cs" />
<Compile Include="HDLogUtil.cs" />
<Compile Include="ImageHelper.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="CodeResourceControl.cs" />
<Compile Include="RemoteDecodeHelper.cs" />
<Compile Include="ZXingCodeHelper.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="FrmBase.resx">
<DependentUpon>FrmBase.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="FrmCodeLearn.resx">
<DependentUpon>FrmCodeLearn.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="FrmCodeDecode.resx">
<DependentUpon>FrmCodeDecode.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Content Include="resources\resources.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="记录.txt" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
\ No newline at end of file
using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CodeLibrary
{
public class CodeResourceControl
{
public static readonly ILog LOG = LogManager.GetLogger("LngResource");
//public delegate string GetStrDelegate(string id, string defaultStr);
//public static event GetStrDelegate GetStrEvent;
//public delegate string GetStringDelegate(string id, string defaultStr, params object[] param);
//public static event GetStringDelegate GetStringEvent;
public static bool OpenResourceLog = false;
public static string China = "zh-CN";
public static string English = "en-US";
public static string Japanese = "ja-JP";
//private static Dictionary<string, string> chineseMap = new Dictionary<string, string>();
//private static Dictionary<string, string> englishMap = new Dictionary<string, string>();
public static Dictionary<string, Dictionary<string, string>> LangMap = new Dictionary<string, Dictionary<string, string>>();
public delegate string GetLanguageDelegate();
public static event GetLanguageDelegate GetLanguageEvent;
public delegate void RefreshLanguageDelegate();
public static event RefreshLanguageDelegate RefreshLanguageEvent;
public static string GetLanguage()
{
if (GetLanguageEvent == null)
{
return China;
}
string result = GetLanguageEvent?.Invoke();
if (result == null)
{
return "";
}
CurrLanguage = result;
return result;
}
private static string spiltStr = "_";
private static string Text = "Text";
public static string GetTextIdStr(string className, string controlName)
{
return className + spiltStr + controlName + spiltStr + Text;
}
public static string GetTextIdStr(string className)
{
return className + spiltStr + Text;
}
public static string GetString(string id, string defaultStr)
{
string strCurLanguage = defaultStr;
var haslang = getLangRes(CurrLanguage);
if (!haslang)
{
return strCurLanguage;
}
try
{
LangMap[CurrLanguage].TryGetValue(id, out strCurLanguage);
if ((strCurLanguage == null || strCurLanguage.Equals("")) && (!defaultStr.Equals("")))
{
strCurLanguage = defaultStr;
NoIdLog(id, defaultStr);
}
}
catch (Exception)
{
if (defaultStr.Equals(""))
{
}
else
{
strCurLanguage = "No id:[" + id + "], please add.";
strCurLanguage = defaultStr;
NoIdLog(id, defaultStr);
}
}
if (strCurLanguage == null)
{
strCurLanguage = "";
}
return strCurLanguage;
}
public static string GetString(string id, string defaultStr, params object[] param)
{
string strCurLanguage = GetString(id, defaultStr);
return String.Format(strCurLanguage, param);
}
private static void NoIdLog(string id, string defaultStr)
{
if (OpenResourceLog)
{
if (LangMap.ContainsKey(CurrLanguage) && !LangMap[CurrLanguage].ContainsKey(id) && checkInterid(id))
LOG.Info("No Res id:" + id + "#" + defaultStr);
}
}
private static bool checkInterid(string id)
{
return true;
//string[] interstring = new string[] { "_txt", "_lbl" };
//var x = from a in interstring
// where id.IndexOf(a) > -1
// select a;
//return x.Count() == 0;
}
static CodeResourceControl()
{
}
private static bool getLangRes(string lang)
{
if (!LangMap.ContainsKey(lang))
{
string path = Application.StartupPath + @"\resources\" + lang + ".txt";
if (!File.Exists(path))
{
path = Application.StartupPath + @"\resources\" + lang + ".lngres";
if (!File.Exists(path))
{
return false;
}
}
string[] lines = File.ReadAllLines(path);
var map = new Dictionary<string, string>();
foreach (string line in lines)
{
string[] array = line.Split('#');
if (array.Length<2)
array = line.Split('\t');
if (array.Length >= 3)
{
string key = array[0];
string chinese = array[1];
string english = array[2];
if (map.ContainsKey(key))
{
map.Remove(key);
}
map.Add(key, english);
}
}
LangMap.Add(lang, map);
return true;
}
return true;
}
public static string CurrLanguage = "";
public static void LanguageProcess(ContainerControl cc, string className)
{
if (CurrLanguage.Equals(CodeResourceControl.GetLanguage()))
{
//return;
}
//string className = cc.ClassName;
CurrLanguage = CodeResourceControl.GetLanguage();
string name = CodeResourceControl.GetString(CodeResourceControl.GetTextIdStr(className), cc.Text);
if (!name.Equals("")) { cc.Text = name; }
PreControlLanaguage(cc, className);
RefreshLanguageEvent?.Invoke();
}
private static void PreControlLanaguage(Control partentControl, string className)
{
//if (partentControl.Tag.ToString() == "not")
// return;
//string className = this.ClassName;
Con_GetTxt(partentControl, out string title);
string newStr = CodeResourceControl.GetString(CodeResourceControl.GetTextIdStr(className, partentControl.Name), title);
if (!newStr.Equals(""))
{
Con_SetTxt(partentControl, newStr.Replace("\\n", "\n"));
}
foreach (Control con in partentControl.Controls)
{
if (con.Tag != null && con.Tag.ToString() == "not")
continue;
string txt = "";
bool haslang = false;
if (Con_GetTxt(con, out txt))
{
newStr = CodeResourceControl.GetString(CodeResourceControl.GetTextIdStr(className, con.Name), txt);
if (!newStr.Equals(""))
{
Con_SetTxt(con, newStr.Replace("\\n", "\n"));
//haslang = true;
}
}
if (con.Controls.Count > 0 && !haslang)
{
PreControlLanaguage(con, className);
}
}
}
static bool Con_GetTxt(Control con, out string txt)
{
txt = "";
if (con is Label || con is Button || con is RadioButton || con is CheckBox)
{
txt = con.Text;
return true;
}
string methodname = getMethodname(con);
var t = con.GetType();
var p = t.GetProperty(methodname);
if (p != null)
{
txt = p.GetValue(con, null).ToString();
return true;
}
return false;
}
static void Con_SetTxt(Control con, string txt)
{
if (con is Label || con is Button || con is RadioButton || con is CheckBox)
{
con.Text = txt;
return;
}
string methodname = getMethodname(con);
var t = con.GetType();
var p = t.GetProperty(methodname);
if (p == null)
return;
else
p.SetValue(con, txt, null);
}
static string getMethodname(Control con)
{
string methodname = "Text";
//if (con is UCBtnExt) methodname = "BtnText";
//if (con is UCTextBoxEx) methodname = "InputText";
//if (con is UCCheckBox) methodname = "TextValue";
//if (con is UCPanelTitle || con is FrmWithTitle) methodname = "Title";
if (con is Form) methodname = "Title";
return methodname;
}
}
}
using HalconDotNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeLibrary
{
public class DHBarCodeHelper
{ /// <summary>
/// 根据图片解析二维码
/// </summary>
/// <param name="ho_Image">Halcon中的图片对象</param>
/// <param name="codeCount">二维码数量</param>
/// <param name="codeParamPath">二维码参数路径,""表示不使用参数</param>
/// <param name="paramType">二维码类型,不传类型默认Data Matrix ECC 200</param>
/// <returns>解析到的二维码</returns>
public static List<CodeInfo> DecodeCode(HObject ho_Image, int codeCount, string codeParamPath, params string[] paramType)
{
List<string> codeType = new List<string>(paramType.ToList());
if (codeType.Count<string>() <= 0)
{
codeType.Add("CODE_39");
}
List<CodeInfo> codeList = new List<CodeInfo>();
foreach (string t in codeType)
{
List<CodeInfo> array = GetCode(ho_Image, t, codeParamPath, codeCount);
codeList.AddRange(array.ToArray<CodeInfo>());
}
return codeList;
}
private static List<CodeInfo> GetCode(HObject ho_Image, string symbolType, string hv_model_path, int codeCount)
{
List<CodeInfo> codeList = new List<CodeInfo>();
try
{
HTuple hv_Area = null;
HTuple hv_Row1 = null;
HTuple hv_Column = null;
HTuple hv_PointOrder = null;
HObject ho_SymbolXLDs;
HTuple hv_ResultHandles = null;
HTuple hv_DecodedDataStrings = null;
HTuple hv_DataCodeHandle = null;
HOperatorSet.GenEmptyObj(out ho_SymbolXLDs);
HOperatorSet.CreateBarCodeModel(symbolType, "default_parameters", "maximum_recognition", out hv_DataCodeHandle);
//string hv_model_path = GetCodeParamFilePath(symbolType);
if (!hv_model_path.Equals("") && File.Exists(hv_model_path))
{
HOperatorSet.ReadDataCode2dModel(hv_model_path, out hv_DataCodeHandle);
}
ho_SymbolXLDs.Dispose();
if (codeCount <= 0)
{
HOperatorSet.FindDataCode2d(ho_Image, out ho_SymbolXLDs, hv_DataCodeHandle,
new HTuple(), new HTuple(), out hv_ResultHandles, out hv_DecodedDataStrings);
}
else
{
HOperatorSet.FindDataCode2d(ho_Image, out ho_SymbolXLDs, hv_DataCodeHandle,
"stop_after_result_num", codeCount, out hv_ResultHandles, out hv_DecodedDataStrings);
}
HOperatorSet.AreaCenterXld(ho_SymbolXLDs, out hv_Area, out hv_Row1, out hv_Column, out hv_PointOrder);
if (HalconWindow != null)
{
ShowImage(HalconWindow, ho_Image, ho_SymbolXLDs);
}
HOperatorSet.ClearDataCode2dModel(hv_DataCodeHandle);
string[] resultList = hv_DecodedDataStrings.SArr;
if (resultList.Length > 0)
{
for (int i = 0; i < hv_DecodedDataStrings.SArr.Length; i++)
{
try
{
int x = (int)Math.Round(hv_Column.DArr[i]);
int y = (int)Math.Round(hv_Row1.DArr[i]);
string str = hv_DecodedDataStrings.SArr[i];
CodeInfo code = new CodeInfo(str, x, y);
codeList.Add(code);
}
catch (Exception ex)
{
HDLogUtil.error("处理二维码出错:索引=" + i + "," + resultList.ToString());
}
}
}
return codeList;
}
catch (Exception ex)
{
return codeList;
}
}
}
}
namespace CodeLibrary
{
partial class FrmBase
{
/// <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.SuspendLayout();
//
// FrmBase
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Name = "FrmBase";
this.Text = "FrmBase";
this.VisibleChanged += new System.EventHandler(this.FrmBase_VisibleChanged);
this.ResumeLayout(false);
}
#endregion
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CodeLibrary
{
public partial class FrmBase : Form
{
public string CurrLanguage = "";
public string ClassName
{
get
{
return this.GetType().Name;
}
set
{
}
}
public FrmBase()
{
InitializeComponent();
}
public void LanguageProcess()
{
if (CurrLanguage.Equals(CodeResourceControl.GetLanguage()))
{
//return;
}
string className = this.ClassName;
CurrLanguage = CodeResourceControl.GetLanguage();
string name= CodeResourceControl.GetString(CodeResourceControl.GetTextIdStr(className), this.Text);
if (!name.Equals("")) { this.Text=name; }
foreach (Control con in this.Controls)
{
if (con is Label || con is Button || con is RadioButton || con is CheckBox)
{
string newStr = CodeResourceControl.GetString(CodeResourceControl.GetTextIdStr(className, con.Name), con.Text);
if (!newStr.Equals(""))
{
con.Text = newStr;
con.Tag = newStr;
}
if (CurrLanguage.Equals(CodeResourceControl.English))
{
con.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
}
else
{
con.Font = new System.Drawing.Font("微软雅黑", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
}
}
else if (con.Controls.Count > 0)
{
PreControlLanaguage(con);
}
}
}
private void PreControlLanaguage(Control partentControl)
{
string className = this.ClassName;
string newStr = CodeResourceControl.GetString(CodeResourceControl.GetTextIdStr(className, partentControl.Name), partentControl.Text);
if (!newStr.Equals(""))
{
partentControl.Text = newStr;
}
foreach (Control con in partentControl.Controls)
{
if (con is Label || con is Button || con is RadioButton || con is CheckBox)
{
newStr = CodeResourceControl.GetString(CodeResourceControl.GetTextIdStr(className, con.Name), con.Text);
if (!newStr.Equals(""))
{ con.Text = newStr; }
if (CurrLanguage.Equals(CodeResourceControl.English))
{
con.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
}
else
{
con.Font = new System.Drawing.Font("微软雅黑", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
}
}
else if (con.Controls.Count > 0)
{
PreControlLanaguage(con);
}
}
}
private void FrmBase_VisibleChanged(object sender, EventArgs e)
{
if (this.Visible.Equals(true))
{
CodeResourceControl.LanguageProcess(this, this.GetType().Name);
}
}
}
}
<?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 HalconDotNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CodeLibrary;
namespace CodeLibrary
{
public partial class FrmCodeLearn : FrmBase
{
private List<string> baslerNameList = new List<string>();
private List<string> hikNameList = new List<string>();
public FrmCodeLearn()
{
InitializeComponent();
}
private string selCamera =CodeResourceControl.GetString("selCamera", "请先选择相机");
private string selImage = CodeResourceControl.GetString("selImage", "请先选择图片");
private string title = CodeResourceControl.GetString("title", "提示");
private string imageIsNull = CodeResourceControl.GetString("imageIsNull", "获取二维码图片为空");
private string sureDelete = CodeResourceControl.GetString("sureDelete", "确定删除文件:");
private HObject GetCameraImg()
{
HObject ho_image = null;
//Bitmap bitmap = null;
int index = cmbCamera.SelectedIndex;
string camerName = cmbCamera.Text;
if (index < 0)
{
MessageBox.Show(selCamera);
return null;
}
ho_image = Camera._cam.CaptureOnImage(camerName,out List<CodeInfo> cc);
return ho_image;
}
private void btnOpen_Click(object sender, EventArgs e)
{
string filePath = txtParamPath.Text;
string cameraName = "";
string codeType = this.cmbCodeType.Text;
int count = cmbCount.SelectedIndex + 1;
if (chbUseCamera.Checked)
{
if (chbHalcon.Checked)
{
cameraName = cmbHalconCamera.Text;
if (cameraName.Equals(""))
{
MessageBox.Show(selCamera,title, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
else
{
// Bitmap bitmap = GetCameraBitmap();
HObject ho_Image = GetCameraImg();
if (ho_Image != null)
{
HDLogUtil.info("从相机【" + cmbCamera.Text + "】获取到一张图片");
ClearPicImg();
//pictureBox1.Image = (Image)bitmap.Clone();
//HObject hoImage = HDCodeHelper.Bitmap2HObjectBpp24(bitmap);
HDCodeLearnHelper.DefaultImage = ho_Image;
ShowImage(ho_Image);
}
else
{
return;
}
}
}
else
{
if (pictureBox1.Image == null)
{
MessageBox.Show(selImage,title ,MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
Bitmap bitmap = new Bitmap( pictureBox1.Image);
HObject Image;
HDCodeHelper.Bitmap2HObjectBpp24(bitmap,out Image);
HDCodeLearnHelper.DefaultImage = Image;
ShowImage(Image);
}
Task.Factory.StartNew(delegate ()
{
HDCodeLearnHelper.StartLearn(this.hWindowControl1.HalconWindow, cameraName, codeType, filePath, count,5000);
});
FormStatus(true);
}
private void LoadCamera()
{
cmbCamera.Items.Clear();
if (Camera._cam == null || Camera._cam.Name==null)
return;
foreach (string str in Camera._cam.Name)
{
cmbCamera.Items.Add(str);
}
if (cmbCamera.Items.Count > 0)
{
cmbCamera.SelectedIndex = 0;
}
}
private void FormStatus(bool open)
{
btnOpen.Enabled = !open;
btnStop.Enabled = open;
}
private void btnStop_Click(object sender, EventArgs e)
{
HDCodeLearnHelper.StopLearn();
FormStatus(false);
}
private void ClearPicImg()
{
try
{
if (pictureBox1.Image != null)
{
pictureBox1.Image.Dispose();
pictureBox1.Image = null;
}
}
catch (Exception ex)
{
HDLogUtil.error("ClearPicImg error : " + ex.ToString());
}
}
private void FrmCamera_Load(object sender, EventArgs e)
{
cmbCount.SelectedIndex = 0;
chbTest.Checked = HDCodeLearnHelper.IsNeedTest;
CheckForIllegalCrossThreadCalls = false;
HDLogUtil.logBox = this.richTextBox2;
if (HDCodeLearnHelper.codeTypeList.Count <= 0)
{
HDCodeLearnHelper.LoadConfig("", "");
}
LoadCamera();
FormStatus(false);
cmbHalconCamera.DataSource = HDCodeLearnHelper.cameraNameList;
if (HDCodeLearnHelper.cameraNameList.Count > 0)
{
cmbHalconCamera.SelectedIndex = 0;
}
cmbCodeType.DataSource = HDCodeLearnHelper.codeTypeList;
if (HDCodeLearnHelper.codeTypeList.Count > 0)
{
cmbCodeType.SelectedIndex = 0;
}
string filePath =HDCodeHelper.GetCodeParamFilePath(cmbCodeType.Text);
txtParamPath.Text = filePath;
cmbCount.Items.Clear();
for(int i = 1; i <= 300; i++)
{
cmbCount.Items.Add(i);
}
cmbCount.SelectedIndex = 0;
chbUseCamera.Checked = true;
timer1.Start();
}
private void FrmCamera_FormClosed(object sender, FormClosedEventArgs e)
{
if (btnStop.Enabled.Equals(true))
{
btnStop_Click(null, null);
HDLogUtil.logBox = null;
FormStatus(false);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (HDCodeLearnHelper.IsRun)
{
if (btnOpen.Enabled)
{
btnOpen.Enabled = false ;
}
}
else
{
if (btnOpen.Enabled.Equals(false))
{
btnOpen.Enabled = true;
}
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void cmbCodeType_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbCodeType.SelectedIndex >= 0)
{
txtParamPath.Text = HDCodeHelper.GetCodeParamFilePath(cmbCodeType.Text );
}
}
private void btnClearLog_Click(object sender, EventArgs e)
{
HDLogUtil.ClearLog();
}
private void chbTest_CheckedChanged(object sender, EventArgs e)
{
HDCodeLearnHelper.IsNeedTest = chbTest.Checked;
}
private void btnSelImage_Click(object sender, EventArgs e)
{
System.Windows.Forms.OpenFileDialog openDialog = new System.Windows.Forms.OpenFileDialog();
openDialog.Title = selImage;
openDialog.Filter = "(*.jpg;*.png;*.bmp)|*.jpg;*.png;*.bmp";
//openDialog.DefaultExt = "png";
System.Windows.Forms.DialogResult result = openDialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.Cancel)
{
return;
}
txtPath.Text = openDialog.FileName;
string filename = txtPath.Text;
if (string.IsNullOrEmpty(filename))
{
MessageBox.Show(imageIsNull);
}
ClearPicImg();
//读取图片内容
Image img = (Image)Image.FromFile(filename).Clone();
pictureBox1.Image = img;
}
private void chbUseCamera_CheckedChanged(object sender, EventArgs e)
{
if (chbUseCamera.Checked)
{
cmbHalconCamera.Enabled = true ;
btnSelImage.Enabled = false;
}
else
{
cmbHalconCamera.Enabled = false ;
btnSelImage.Enabled = true ;
}
}
private void btnDelOld_Click(object sender, EventArgs e)
{
string path = txtParamPath.Text;
if (path.Equals(""))
{
return;
}
FileInfo file = new FileInfo(path);
DialogResult result = MessageBox.Show(sureDelete +file.Name+ "", title, MessageBoxButtons.YesNo);
if (result.Equals(DialogResult.Yes))
{
File.Delete(path);
}
}
private void chbHalcon_CheckedChanged(object sender, EventArgs e)
{
if (chbHalcon.Checked)
{
cmbHalconCamera.Visible = true;
cmbCamera.Visible = false;
}
else
{
cmbHalconCamera.Visible = false ;
cmbCamera.Visible = true ;
}
}
public void ShowImage(HObject ho_Image)
{
HTuple width, height;
HOperatorSet.GetImageSize(ho_Image, out width, out height);
int dWidth = (int)width.D;
int dHeight = (int)height.D;
this.hWindowControl1.HalconWindow.SetPart(0, 0, dHeight, dWidth);
HOperatorSet.DispObj(ho_Image, hWindowControl1.HalconWindow);
}
}
}
using IDHIKCamera;
using log4net;
using log4net.Config;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace CodeLibrary
{
public class HDLogUtil
{
private static string logName = "";
public static string LogName
{
get { return logName; }
set
{
logName = value;
LOGGER = LogManager.GetLogger(LogName);
}
}
private static ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static Dictionary<int, DateTime> lastErrorLogTime = new Dictionary<int, DateTime>();
public static System.Windows.Forms.RichTextBox logBox = null;
public static int showCount = 50;
public static bool debug_opened = false;
static HDLogUtil()
{
XmlConfigurator.Configure();
//LibLogUtil.LogEvent += LibLogUtil_LogEvent;
}
/*
private static void LibLogUtil_LogEvent(LibLogEventArg libLogEventArg)
{
if (libLogEventArg.Level.Equals(LibLogLevel.Info))
{
HDLogUtil.info(libLogEventArg.Msg + " " + libLogEventArg.Exception?.ToString());
}
else if (libLogEventArg.Level.Equals(LibLogLevel.Warning))
{
HDLogUtil.info(libLogEventArg.Msg + " " + libLogEventArg.Exception?.ToString());
}
else if (libLogEventArg.Level.Equals(LibLogLevel.Debug))
{
HDLogUtil.debug(libLogEventArg.Msg + " " + libLogEventArg.Exception?.ToString());
}
else if (libLogEventArg.Level.Equals(LibLogLevel.Error))
{
HDLogUtil.error(libLogEventArg.Msg + " " + libLogEventArg.Exception?.ToString());
}
}
*/
public static void info(string msg)
{
LOGGER.Info("HDLogUtil" + " - " + msg);
AddToBox(msg);
}
public static void debug(string msg)
{
LOGGER.Debug("HDLogUtil" + " - " + msg);
if (debug_opened)
{
AddToBox(msg);
}
}
public static void error(string errorMsg)
{
LOGGER.Error("HDLogUtil" + " - " + errorMsg);
AddToBox(errorMsg);
}
private static void AddToBox(string msg)
{
try
{
if (logBox == null)
{
return;
}
ShowLogPro(msg);
}
catch (Exception ex)
{
LOGGER.Error("出错:" + ex.StackTrace);
}
}
private static int count = 0;
private static void ShowLogPro(string msg)
{
try
{
if (count > showCount)
{
count = 0;
logBox.Clear();
}
System.DateTime now = System.DateTime.Now;
logBox.AppendText(now.ToLongTimeString() + " " + msg + Environment.NewLine);
count++;
}
catch (Exception ex)
{
LOGGER.Error("出错:" + ex.ToString());
}
}
public static void ClearLog()
{
if (logBox != null)
{
logBox.Text = "";
count = 0;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace CodeLibrary
{
public class ImageHelper
{ /// <summary>
/// 图像灰度化
/// </summary>
/// <param name="bmp"></param>
/// <returns></returns>
public static Bitmap ToGray(Bitmap bmp)
{
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
//获取该点的像素的RGB的颜色
Color color = bmp.GetPixel(i, j);
//利用公式计算灰度值
int gray = (int)(color.R * 0.3 + color.G * 0.59 + color.B * 0.11);
Color newColor = Color.FromArgb(gray, gray, gray);
bmp.SetPixel(i, j, newColor);
}
}
return bmp;
}
/// <summary>
/// 图像灰度反转
/// </summary>
/// <param name="bmp"></param>
/// <returns></returns>
public static Bitmap GrayReverse(Bitmap bmp)
{
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
//获取该点的像素的RGB的颜色
Color color = bmp.GetPixel(i, j);
Color newColor = Color.FromArgb(255 - color.R, 255 - color.G, 255 - color.B);
bmp.SetPixel(i, j, newColor);
}
}
return bmp;
}
/// <summary>
/// 图像二值化1:取图片的平均灰度作为阈值,低于该值的全都为0,高于该值的全都为255
/// </summary>
/// <param name="bmp"></param>
/// <returns></returns>
public static Bitmap ConvertTo1Bpp1(Bitmap bmp)
{
int average = 0;
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
Color color = bmp.GetPixel(i, j);
average += color.B;
}
}
average = (int)average / (bmp.Width * bmp.Height);
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
//获取该点的像素的RGB的颜色
Color color = bmp.GetPixel(i, j);
int value = 255 - color.B;
Color newColor = value > average ? Color.FromArgb(0, 0, 0) : Color.FromArgb(255, 255, 255);
bmp.SetPixel(i, j, newColor);
}
}
return bmp;
}
/// <summary>
/// 图像二值化2
/// </summary>
/// <param name="img"></param>
/// <returns></returns>
public static Bitmap ConvertTo1Bpp2(Bitmap img)
{
int w = img.Width;
int h = img.Height;
Bitmap bmp = new Bitmap(w, h, PixelFormat.Format1bppIndexed);
BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);
for (int y = 0; y < h; y++)
{
byte[] scan = new byte[(w + 7) / 8];
for (int x = 0; x < w; x++)
{
Color c = img.GetPixel(x, y);
if (c.GetBrightness() >= 0.5) scan[x / 8] |= (byte)(0x80 >> (x % 8));
}
Marshal.Copy(scan, 0, (IntPtr)((int)data.Scan0 + data.Stride * y), scan.Length);
}
return bmp;
}
/// <summary>
/// 图像明暗调整
/// </summary>
/// <param name="b">原始图</param>
/// <param name="degree">亮度[-255, 255]</param>
/// <returns></returns>
public static Bitmap KiLighten(Bitmap b, int degree)
{
if (b == null)
{
return null;
}
if (degree < -255) degree = -255;
if (degree > 255) degree = 255;
try
{
int width = b.Width;
int height = b.Height;
int pix = 0;
BitmapData data = b.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
unsafe
{
byte* p = (byte*)data.Scan0;
int offset = data.Stride - width * 3;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
// 处理指定位置像素的亮度
for (int i = 0; i < 3; i++)
{
pix = p[i] + degree;
if (degree < 0) p[i] = (byte)Math.Max(0, pix);
if (degree > 0) p[i] = (byte)Math.Min(255, pix);
} // i
p += 3;
} // x
p += offset;
} // y
}
b.UnlockBits(data);
return b;
}
catch
{
return null;
}
} // end of Lighten
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("CodeLibrary")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CodeLibrary")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("2e0d9598-cb37-46dc-9c9b-d36d4d344451")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyVersion("1.0.0.0")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyFileVersion("1.0.*")]
\ No newline at end of file
using CodeLibrary;
using HalconDotNet;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
public class RemoteDecodeHelper
{
static int webclienttimeout = 30 * 1000;
static Process p = new Process();
static string serverhost = "http://127.0.0.1:58137/";
public static List<CodeInfo> DecodeRequest(HObject hoimg, RemoteDecodeParam remoteDecodeParam)
{
byte[] requestdata;
lock (hoimg)
{
using (MemoryStream mStream = new MemoryStream())
{
hoimg.Serialize(mStream);
requestdata = mStream.ToArray();
mStream.Close();
}
}
return DecodeRequest(requestdata, remoteDecodeParam,true);
}
public static List<CodeInfo> DecodeRequest(Bitmap bitmap, RemoteDecodeParam remoteDecodeParam)
{
if (bitmap == null)
return null;
byte[] requestdata;
lock (bitmap)
{
using (MemoryStream mStream = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(mStream, bitmap);
requestdata = mStream.ToArray();
mStream.Close();
}
}
return DecodeRequest(requestdata, remoteDecodeParam);
}
static List<CodeInfo> DecodeRequest(byte[] requestdata, RemoteDecodeParam remoteDecodeParam,bool isHObject=false)
{
try
{
CheckAndRunServer();
}
catch (Exception ex) {
return new List<CodeInfo> { new CodeInfo("ScanCodeServer start error:"+ ex, 0,0) };
}
string param;
using (MemoryStream mStreamparam = new MemoryStream())
{
XmlSerializer xf = new XmlSerializer(typeof(RemoteDecodeParam));
xf.Serialize(mStreamparam, remoteDecodeParam);
param = base64UrlEncode(mStreamparam.ToArray());
mStreamparam.Close();
}
string url = serverhost+"ProcessBitmap?param=";
if (isHObject)
url = serverhost+"Process?param=";
byte[] resp;
try
{
using (MyWebClient webClient = new MyWebClient(webclienttimeout))
{
resp = webClient.UploadData(url + param, requestdata);
requestdata = null;
}
}
catch(WebException we)
{
TaskKill("ScanCodeServer");
return new List<CodeInfo> { new CodeInfo("ScanCodeServer run error:" + we, 0, 0) };
}
catch
{
return null;
}
List<CodeInfo> codeInfos=null;
var ss = Encoding.UTF8.GetString(resp).Trim().Trim('"');
ss = ss.Replace(@"\/", "/");
try
{
var bb = Convert.FromBase64String(ss);
using (MemoryStream mStreamResult = new MemoryStream(bb))
{
XmlSerializer xff = new XmlSerializer(typeof(List<CodeInfo>));
codeInfos = (List<CodeInfo>)xff.Deserialize(mStreamResult);
}
}
catch {
throw new Exception(ss);
}
return codeInfos;
}
/// <summary>
/// 在url中传递base64字符串需要替换加号等符号
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
static string base64UrlEncode(byte[] input)
{
return Convert.ToBase64String(input).Replace('+', '-').Replace('/', '_');
}
/// <summary>
/// 检查并自动启动服务器
/// </summary>
static void CheckAndRunServer()
{
lock (p)
{
var port = (int)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\ScanCodeServer\\", "port", 58137);
serverhost = "http://127.0.0.1:" + port + "/";
var pss = Process.GetProcessesByName("ScanCodeServer");
if (pss.Length > 0 && !pss[0].HasExited)
return;
var f = Application.StartupPath+ "\\ScanCodeServer\\ScanCodeServer.exe";
if (!File.Exists(f))
{
throw new Exception("找不到扫码服务器文件");
}
p.StartInfo = new ProcessStartInfo(f);
p.Start();
Thread.Sleep(3000);
int checkcount = 15;
while (checkcount > 0)
{
checkcount--;
Thread.Sleep(500);
port = (int)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\ScanCodeServer\\", "port", 58137);
serverhost = "http://127.0.0.1:"+ port + "/";
using (MyWebClient webClient = new MyWebClient(webclienttimeout))
{
var s = webClient.DownloadString(serverhost + "alive");
if (s.Trim() == "\"1\"")
return;
}
}
TaskKill("ScanCodeServer");
throw new Exception("扫码服务器打开失败,退出码:"+ p.ExitCode);
}
}
static void TaskKill(string processname) {
var pss = Process.GetProcessesByName(processname);
foreach (var p in pss)
{
try
{
p.Kill();
}
catch { }
}
}
[Serializable]
public struct RemoteDecodeParam
{
public string[] codeTypeList;
public int codeCount;
public int timeout;
}
public class MyWebClient : WebClient
{
private int _timeout;
public MyWebClient(int timeout)
{
this._timeout = timeout;
}
protected override WebRequest GetWebRequest(Uri address)
{
var result = base.GetWebRequest(address);
result.Timeout = this._timeout;
return result;
}
}
}
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using ZXing;
using ZXing.Common;
using ZXing.Multi.QrCode;
namespace CodeLibrary
{
public class ZXingCodeHelper
{
public static List<string> DeCodes(Bitmap map, string codeType)
{
if (codeType.ToUpper().Equals("QR CODE"))
{
return DecodeQRCodes(map);
}
else if (codeType.ToUpper().Equals("DATA MATRIX ECC 200"))
{
return DecodeCodes(map);
}
else if (codeType.ToUpper().Equals("BARCODE"))
{
return DecodeCodes(map);
}
else
{
return DecodeCodes(map);
}
}
public static List<string> DecodeCodes(Bitmap bmp)
{
MultiFormatReader mreader = new MultiFormatReader();
ZXing.Multi.GenericMultipleBarcodeReader genericMultiple = new ZXing.Multi.GenericMultipleBarcodeReader(mreader);
LuminanceSource source = new BitmapLuminanceSource(bmp);
BinaryBitmap binarybitmap = new BinaryBitmap(new HybridBinarizer(source));
Result[] rr = genericMultiple.decodeMultiple(binarybitmap);
List<string> result = new List<string>();
if (rr != null)
{
foreach (Result res in rr)
{
if (res != null)
{
string text = res.ToString();
if (!IsGBCode(text))
{
text = ConvertISO88591ToEncoding(text, Encoding.Default);
}
result.Add(text);
}
}
}
return result;
}
public static List<string> DecodeBarCodes(Bitmap bmp)
{
List<string> result = new List<string>();
BarcodeReader br = new BarcodeReader();
DecodingOptions decodeOption = new DecodingOptions();
decodeOption.PossibleFormats = new List<BarcodeFormat>() { BarcodeFormat.CODE_39, BarcodeFormat.CODE_128 };
br.Options = decodeOption;
Result res = br.Decode(bmp);
if (res != null)
{
result.Add(res.ToString());
}
return result;
}
public static List<string> DecodeDMCodes(Bitmap bmp)
{
ZXing.Datamatrix.DataMatrixReader qc = new ZXing.Datamatrix.DataMatrixReader();
List<string> result = new List<string>();
LuminanceSource source = new BitmapLuminanceSource(bmp);
BinaryBitmap binarybitmap = new BinaryBitmap(new HybridBinarizer(source));
IDictionary<DecodeHintType, object> hints = new Dictionary<DecodeHintType, object>();
hints.Add(DecodeHintType.CHARACTER_SET, "UTF-8");
hints.Add(DecodeHintType.TRY_HARDER, "3");
Result res = qc.decode(binarybitmap, hints);
if (res != null)
{
result.Add(res.ToString());
}
return result;
}
public static List<string> DecodeQRCodes(Bitmap bmp)
{
QRCodeMultiReader qc = new QRCodeMultiReader();
List<string> result = new List<string>();
LuminanceSource source = new BitmapLuminanceSource(bmp);
BinaryBitmap binarybitmap = new BinaryBitmap(new HybridBinarizer(source));
IDictionary<DecodeHintType, object> hints = new Dictionary<DecodeHintType, object>();
hints.Add(DecodeHintType.CHARACTER_SET, "GB2312");
hints.Add(DecodeHintType.TRY_HARDER, "3");
Result[] r = qc.decodeMultiple(binarybitmap, hints);
if (r != null)
{
foreach (Result res in r)
{
if (res != null)
{
string text = res.ToString();
//if (!IsGBCode(text))
//{
// string chStr = "生产日期(或厂家批次):";
// int index = text.IndexOf(chStr);
// if (index > 0)
// {
// string sub1 = text.Substring(0, index);
// int sub3startIndex =index+ chStr.Length;
// string sub3 = text.Substring(sub3startIndex,text.Length- sub3startIndex);
// string sub1r = ConvertISO88591ToEncoding(sub1, Encoding.Default);
// string sub3r = ConvertISO88591ToEncoding(sub3, Encoding.Default);
// text = sub1r + chStr + sub3r;
// }
// else
// {
// text = ConvertISO88591ToEncoding(text, Encoding.Default);
// }
//}
result.Add(text);
}
}
}
return result;
}
//public static string DecodeQRCode(Bitmap bmp)
//{
// string text = "";
// DecodingOptions option = new DecodingOptions();
// //option.PossibleFormats = new List<BarcodeFormat>() { BarcodeFormat.QR_CODE, BarcodeFormat.All_1D };
// option.PossibleFormats = new List<BarcodeFormat>() { BarcodeFormat.QR_CODE };
// BarcodeReader br = new BarcodeReader();
// br.Options = option;
// Result rs = br.Decode(bmp);
// if (rs == null)
// {
// text = "";
// }
// else
// {
// text = rs.ToString();
// if (!IsGBCode(text))
// {
// text = ConvertISO88591ToEncoding(text, Encoding.Default);
// }
// }
// return text;
//}
//转换
private static string ConvertISO88591ToEncoding(string srcString, Encoding dstEncode)
{
String sResult;
Encoding ISO88591Encoding = Encoding.GetEncoding("ISO-8859-1");
Encoding GB2312Encoding = Encoding.GetEncoding("GB2312"); //这个地方很特殊,必须利用GB2312编码
byte[] srcBytes = ISO88591Encoding.GetBytes(srcString);
//将原本存储ISO-8859-1的字节数组当成GB2312转换成目标编码(关键步骤)
byte[] dstBytes = Encoding.Convert(GB2312Encoding, dstEncode, srcBytes);
char[] dstChars = new char[dstEncode.GetCharCount(dstBytes, 0, dstBytes.Length)];
dstEncode.GetChars(dstBytes, 0, dstBytes.Length, dstChars, 0);//利用char数组存储字符
sResult = new string(dstChars);
return sResult;
}
/// <summary>
/// 判断一个word是否为GB2312编码的汉字
/// </summary>
/// <param name="word"></param>
/// <returns></returns>
private static bool IsGBCode(string word)
{
byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(word);
if (bytes.Length <= 1) // if there is only one byte, it is ASCII code or other code
{
return false;
}
else
{
byte byte1 = bytes[0];
byte byte2 = bytes[1];
if (byte1 >= 176 && byte1 <= 247 && byte2 >= 160 && byte2 <= 254) //判断是否是GB2312
{
return true;
}
else
{
return false;
}
}
}
}
}
using Basler.Pylon;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeLibrary
{
public class BaslerCManager
{
/// <summary>
/// 当前相机
/// </summary>
// private Camera cameraCur = null;
private static Dictionary<string, BaslerCameraBean> cameraMap = new Dictionary<string, BaslerCameraBean>();
/// <summary>
/// 所有相机列表
/// </summary>
private static List<ICameraInfo> cameraAll;
/// <summary>
/// 所有相机的名称
/// </summary>
private static List<string> cameraName;
/// <summary>
/// 获取连续图像
/// </summary>
public delegate void GrabImageEvent();
///// <summary>
///// 获取连续图像事件,需要跨线程操作
///// </summary>
//public event GrabImageEvent GrabImage;
private BaslerCManager()
{
Load();
}
/// <summary>
/// 错误信息
/// </summary>
public static string ErrInfo { set; get; }
/// <summary>
/// 相机总数
/// </summary>
public int Count
{
get { return cameraAll == null ? 0 : cameraAll.Count; }
}
/// <summary>
/// 相机名称,ModelName,SerialNumber
/// </summary>
public static string[] CameraName
{
get
{
if (cameraName == null)
{
cameraName = new List<string>();
}
return cameraName.ToArray();
}
}
public static BaslerCameraBean GetCamera(string cName)
{
if (cameraMap.ContainsKey(cName))
{
return cameraMap[cName];
}
return null;
}
public static void AddCamera(string name, BaslerCameraBean bean)
{
if (cameraMap.ContainsKey(name))
{
cameraMap.Remove(name);
}
cameraMap.Add(name, bean);
}
/// <summary>
/// 当前相机是否打开
/// </summary>
public static bool IsOpen(string name)
{
BaslerCameraBean bean = GetCamera(name);
if (bean == null)
{ return false; }
else
{
return bean.cameraCur.IsOpen;
}
}
/// <summary>
/// 加载相机
/// </summary>
public static void Load()
{
try
{
cameraAll = CameraFinder.Enumerate();
cameraName = new List<string>();
foreach (ICameraInfo info in cameraAll)
cameraName.Add(info[CameraInfoKey.ModelName].ToString() + " (" + info[CameraInfoKey.SerialNumber].ToString() + ")");
}
catch (Exception ex)
{
HDLogUtil.error("Basler Load Error:" + ex.StackTrace);
}
}
/// <summary>
/// 打开指定相机
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static bool Open(string name, GrabImageEvent grab=null)
{
int n = cameraName.FindIndex(s => s == name);
if (n == -1)
return false;
else
{
if (cameraMap.ContainsKey(name))
{
if (cameraMap[name].cameraCur != null)
{
cameraMap[name].cameraCur.Close();
}
cameraMap.Remove(name);
}
Camera cameraCur = null;
if (n < 0 || n >= cameraAll.Count) { return false ; }
try
{
cameraCur = new Camera(cameraAll[n]);
BaslerCameraBean bean = new BaslerCameraBean(cameraCur);
bean.Open( );
AddCamera(name, bean);
}
catch (Exception ex)
{
ErrInfo = ex.Message;
return false ;
}
return true;
}
}
/// <summary>
/// 关闭当前相机
/// </summary>
public static void Close(string name)
{
BaslerCameraBean bean = GetCamera(name);
if (bean != null && bean.cameraCur != null)
{
bean.Close();
}
}
public static void CloseAll()
{
foreach(string key in cameraMap.Keys)
{
Close(key);
}
}
/// <summary>
/// 停止抓取数据
/// </summary>
public static void Stop(string name)
{
BaslerCameraBean bean = GetCamera(name);
if (bean != null)
{
bean.Stop();
}
}
/// <summary>
/// 抓取一张图像
/// </summary>
public static Bitmap GrabOne(string name)
{
BaslerCameraBean bean = GetCamera(name);
if (bean != null && bean.cameraCur != null)
{
return bean.GrabOne();
}
return null;
}
}
}
using Basler.Pylon;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static CodeLibrary.BaslerCamera;
namespace CodeLibrary
{
public class BaslerCameraBean
{
public Camera cameraCur = null;
/// <summary>
/// 相机图像宽度
/// </summary>
public int Width { set; get; }
/// <summary>
/// 相机图像高度
/// </summary>
public int Height { set; get; }
/// <summary>
/// 相机32位缓存
/// </summary>
public byte[] Buffer { get; private set; }
/// <summary>
/// 相机32位图像
/// </summary>
public Bitmap Image { get; private set; }
/// <summary>
/// 获取连续图像事件,需要跨线程操作
/// </summary>
public event GrabImageEvent GrabImage;
/// <summary>
/// 错误信息
/// </summary>
public string ErrInfo { set; get; }
public BaslerCameraBean (Camera c)
{
this.cameraCur = c;
}
public BaslerCameraBean (Camera c ,int width,int height)
{
this.cameraCur = c;
this.Width = width;
this.Height = height;
}
public void Open()
{
cameraCur.StreamGrabber.ImageGrabbed += OnImageGrabbed;
//cameraCur.StreamGrabber.GrabStopped += OnGrabStopped;
cameraCur.Open();
int Width = Convert.ToInt32(cameraCur.Parameters[PLCamera.Width].GetValue());
int Height = Convert.ToInt32(cameraCur.Parameters[PLCamera.Height].GetValue());
cameraCur.Parameters[PLCamera.UserSetSelector].SetValue(PLCamera.UserSetSelector.UserSet1); //加载用户设置1
bool bln = cameraCur.Parameters[PLCamera.UserSetLoad].TryExecute(); //执行设置
}
/// <summary>
/// 关闭当前相机
/// </summary>
public void Close()
{
if (cameraCur != null)
{
cameraCur.Close();
cameraCur.Dispose();
cameraCur = null;
}
}
/// <summary>
/// 停止抓取数据
/// </summary>
public void Stop()
{
if (cameraCur != null)
cameraCur.StreamGrabber.Stop();
}
/// <summary>
/// 抓取一张图像
/// </summary>
public Bitmap GrabOne()
{
cameraCur.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.SingleFrame);
//cameraCur.StreamGrabber.Start();
//IGrabResult grabResult = cameraCur.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);
IGrabResult grabResult = cameraCur.StreamGrabber.GrabOne(5000);
if (!grabResult.IsValid) return null ;
Image = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
BitmapData bmpData = Image.LockBits(new Rectangle(0, 0, grabResult.Width, grabResult.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
IntPtr ptrBmp = bmpData.Scan0;
int picSize = bmpData.Stride * grabResult.Height;
PixelDataConverter conv = new PixelDataConverter();
conv.OutputPixelFormat = PixelType.BGRA8packed;
conv.Convert(ptrBmp, picSize, grabResult);
Buffer = new byte[picSize];
System.Runtime.InteropServices.Marshal.Copy(ptrBmp, Buffer, 0, picSize);
Image.UnlockBits(bmpData);
return Image;
//cameraCur.StreamGrabber.Stop();
}
/// <summary>
/// 抓取连续图像,触发GrabImage事件
/// </summary>
public void GrabContinuous()
{
cameraCur.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
cameraCur.StreamGrabber.Start(GrabStrategy.OneByOne, GrabLoop.ProvidedByStreamGrabber);
}
private void OnImageGrabbed(object sender, ImageGrabbedEventArgs e)
{
try
{
IGrabResult grabResult = e.GrabResult;
if (!grabResult.IsValid) return;
Image = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
BitmapData bmpData = Image.LockBits(new Rectangle(0, 0, grabResult.Width, grabResult.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
IntPtr ptrBmp = bmpData.Scan0;
int picSize = bmpData.Stride * grabResult.Height;
PixelDataConverter conv = new PixelDataConverter();
conv.OutputPixelFormat = PixelType.BGRA8packed;
conv.Convert(ptrBmp, picSize, grabResult);
Buffer = new byte[picSize];
System.Runtime.InteropServices.Marshal.Copy(ptrBmp, Buffer, 0, picSize);
Image.UnlockBits(bmpData);
GrabImage?.Invoke();
}
catch (Exception ex)
{
ErrInfo = ex.Message;
}
finally
{
e.DisposeGrabResultIfClone();
}
}
}
}
using System;
using Basler.Pylon;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections.Generic;
using HalconDotNet;
using System.Runtime.InteropServices;
namespace CodeLibrary
{
partial class Basler : ClsCamera
{
/// <summary>
/// 当前相机
/// </summary>
private global::Basler.Pylon.Camera[] cameraCurr;
/// <summary>
/// 所有相机列表
/// </summary>
private List<ICameraInfo> cameraAll;
///// <summary>
///// 所有相机的名称
///// </summary>
//private List<string> cameraName;
///// <summary>
///// 连续抓图事件
///// </summary>
//public event Continuous Continuous_Event;
public override void Close(string name)
{
int index = Array.FindIndex(_name, s => s == name);
if (index == -1)
return;
if (cameraCurr[index] != null)
{
_isOpen[index] = false;
cameraCurr[index].Close();
cameraCurr[index].Dispose();
cameraCurr[index] = null;
}
}
public override void Close(int index)
{
if (cameraCurr[index] != null)
{
_isOpen[index] = false;
cameraCurr[index].Close();
cameraCurr[index].Dispose();
cameraCurr[index] = null;
}
}
public override void CloseAll()
{
for (int i = 0; i < cameraCurr.Length; i++)
{
if (cameraCurr[i] != null)
{
_isOpen[i] = false;
cameraCurr[i].Close();
cameraCurr[i].Dispose();
cameraCurr[i] = null;
}
}
}
public override Bitmap GrabOne(int index)
{
if (cameraCurr[index] != null)
{
try
{
cameraCurr[index].Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.SingleFrame);
//cameraCur.StreamGrabber.Start();
//IGrabResult grabResult = cameraCur.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);
IGrabResult grabResult = cameraCurr[index].StreamGrabber.GrabOne(5000);
if (!grabResult.IsValid)
{
_errInfo = grabResult.ErrorDescription;
return null;
}
Bitmap _image = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format24bppRgb);
BitmapData bmpData = _image.LockBits(new Rectangle(0, 0, grabResult.Width, grabResult.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
IntPtr ptrBmp = bmpData.Scan0;
int picSize = bmpData.Stride * grabResult.Height;
PixelDataConverter conv = new PixelDataConverter();
conv.OutputPixelFormat = PixelType.BGR8packed;
conv.Convert(ptrBmp, picSize, grabResult);
//_buffer = new byte[picSize];
//System.Runtime.InteropServices.Marshal.Copy(ptrBmp, _buffer, 0, picSize);
_image.UnlockBits(bmpData);
_errInfo = "OK";
return _image;
}
catch (Exception ex)
{
_errInfo = ex.Message;
return null;
}
}
return null;
}
public override Bitmap GrabOne(string name)
{
int idx = Array.FindIndex(_name, s => s == name);
if (idx == -1)
return null;
else
return GrabOne(idx);
}
//public override void GrabStop(int index)
//{
// if (cameraCurr[index] != null)
// cameraCurr[index].StreamGrabber.Stop();
//}
public override bool Load()
{
try
{
cameraAll = CameraFinder.Enumerate();
cameraName = new List<string>();
foreach (ICameraInfo info in cameraAll)
cameraName.Add(info[CameraInfoKey.ModelName].ToString() + " (" + info[CameraInfoKey.SerialNumber].ToString() + ")");
_name = cameraName.ToArray();
_count = cameraName.Count;
_isOpen = new bool[_count];
_width = new int[_count];
_height = new int[_count];
cameraCurr = new global::Basler.Pylon.Camera[_count];
_errInfo = "OK";
return true;
}
catch (Exception ex)
{
_errInfo = ex.Message;
return false;
}
}
public override bool Open(int index)
{
// _index = index;
if (index < 0 || index >= _count)
{
_errInfo = "Not find";
return false;
}
if (cameraCurr[index] != null) Close(index);
try
{
cameraCurr[index] = new global::Basler.Pylon.Camera(cameraAll[index]);
//cameraCur.ConnectionLost += OnConnectionLost;
//cameraCur.CameraOpened += OnCameraOpened;
//cameraCur.CameraClosed += OnCameraClosed;
//cameraCur.StreamGrabber.GrabStarted += OnGrabStarted;
// cameraCurr[index].StreamGrabber.ImageGrabbed += OnImageGrabbed;
//cameraCur.StreamGrabber.GrabStopped += OnGrabStopped;
cameraCurr[index].Open();
_width[index] = Convert.ToInt32(cameraCurr[index].Parameters[PLCamera.Width].GetValue());
_height[index] = Convert.ToInt32(cameraCurr[index].Parameters[PLCamera.Height].GetValue());
cameraCurr[index].Parameters[PLCamera.UserSetSelector].SetValue(PLCamera.UserSetSelector.UserSet1); //加载用户设置1
bool bln = cameraCurr[index].Parameters[PLCamera.UserSetLoad].TryExecute(); //执行设置
_isOpen[index] = true;
_errInfo = "OK";
return true;
}
catch (Exception ex)
{
_errInfo = ex.Message;
return false;
}
}
public override bool Open(string name)
{
int n = cameraName.FindIndex(s => s == name);
if (n == -1)
{
_errInfo = "Not find";
return false;
}
else
return Open(n);
}
public override bool OpenAll()
{
bool rtn = true;
for (int i = 0; i < cameraName.Count; i++)
{
rtn = Open(i);
if (!rtn) break;
}
return rtn;
}
public override Bitmap GrabOneImage(string name)
{
int n = cameraName.FindIndex(s => s == name);
if (n == -1)
{
_errInfo = "Not find";
return null;
}
if (cameraCurr[n] != null)
{
return GrabOne(name);
}
return null;
}
public override HObject CaptureOnImage(string name)
{
return CaptureOnImage(name, out _);
}
public override HObject CaptureOnImage(string name,out Bitmap bmp,bool nohalcon=false)
{
HObject hoImage = null;
bmp = null;
int index = cameraName.FindIndex(s => s == name);
if (index == -1)
{
_errInfo = name + "Not find";
return hoImage;
}
if (cameraCurr[index] != null)
{
}
else
{
Open(index);
}
try
{
if (cameraCurr[index] != null)
{
cameraCurr[index].Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.SingleFrame);
//cameraCur.StreamGrabber.Start();
//IGrabResult grabResult = cameraCur.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);
IGrabResult grabResult = cameraCurr[index].StreamGrabber.GrabOne(5000);
if (!grabResult.IsValid || !grabResult.GrabSucceeded)
{
_errInfo = grabResult.ErrorDescription;
return hoImage;
}
//相机像素数据
byte[] buffer = grabResult.PixelData as byte[];
//锁定像素数据
GCHandle hand = GCHandle.Alloc(buffer, GCHandleType.Pinned);
//获取像素数据的指针
IntPtr pr = hand.AddrOfPinnedObject();
//HalconDotNet.HObject image;
//转成灰度图HOjbect
HalconDotNet.HOperatorSet.GenImage1(out hoImage, new HalconDotNet.HTuple("byte"), grabResult.Width, grabResult.Height, pr);
//释放内存
if (hand.IsAllocated) hand.Free();
_errInfo = "OK";
return hoImage;
}
}
catch (Exception ex)
{
_errInfo = ex.Message;
return hoImage;
}
finally
{
// cameraCurr[index].MV_CC_StopGrabbing_NET();
}
return hoImage;
}
}
}
\ No newline at end of file
using CodeLibrary.camera;
using HalconDotNet;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
namespace CodeLibrary
{
/// <summary>
/// 相机
/// </summary>
public class Camera
{
public static ClsCamera _cam;
private static CameraType _type;
/// <summary>
/// 相机
/// </summary>
private Camera()
{ }
/// <summary>
/// 相机类型
/// </summary>
public static CameraType Type
{
set
{
if (_cam != null)
{
return;
// _cam.CloseAll();
}
_type = value;
switch (_type)
{
case CameraType.HIK:
_cam = new HIK();
// ((HIK)_cam).Continuous_Event += Camera_Continuous_Event;
break;
//case CameraType.Basler:
// _cam = new Basler();
// ((Basler)_cam).Continuous_Event += Camera_Continuous_Event;
//break;
case CameraType.HIKIDMVS:
_cam = new HIKIDMVS();
//((HIKIDMVS)_cam).Continuous_Event += Camera_Continuous_Event;
break;
}
}
get
{
return _type;
}
}
}
/// <summary>
/// 相机类型
/// </summary>
public enum CameraType
{
/// <summary>
/// 海康
/// </summary>
HIK,
/// <summary>
/// 海IDMVS
/// </summary>
HIKIDMVS,
/// <summary>
/// Basle
/// </summary>
Basler
}
public abstract class ClsCamera
{
/// <summary>
/// 所有相机的名称
/// </summary>
protected List<string> cameraName;
protected string _errInfo;
protected bool[] _isOpen;
protected int _count;
protected string[] _name;
protected int[] _width;
protected int[] _height;
//protected byte[] _buffer;
// protected Bitmap _image;
// protected int _index;
public delegate void Continuous();
public virtual string ErrInfo => _errInfo;
public virtual bool[] IsOpen => _isOpen;
public virtual int Count => _count;
public virtual string[] Name => _name;
//public virtual int[] Width => _width;
//public virtual int[] Height => _height;
//public virtual byte[] Buffer => _buffer;
// public virtual Bitmap Image => _image;
public abstract bool Load();
public abstract bool OpenAll();
public abstract bool Open(int index);
public abstract bool Open(string name);
public abstract void CloseAll();
public abstract void Close(int index);
public abstract void Close(string name);
// public abstract bool GrabOne();
public abstract Bitmap GrabOne(int index, PixelType pt = PixelType.Default);
public abstract Bitmap GrabOne(string name, PixelType pt = PixelType.Default);
// public abstract bool GrabContinuous(int index);
// public abstract void GrabStop(int index);
public abstract Bitmap GrabOneImage(string name, PixelType pt= PixelType.Default);
public abstract HObject CaptureOnImage(string name,out List<CodeInfo> cc);
public abstract HObject CaptureOnImage(string name, out Bitmap bmp, out List<CodeInfo> codeInfos, bool nohalcon = false);
public abstract bool ProcessOnImage(string name, out object[] result, params Func<string,Bitmap, object>[] func);
//扫码相机专用
public abstract List<CodeInfo> GetImageAndIdentifyCode(out Bitmap bitmap);
}
public enum PixelType
{
MONO8,
RGB8,
Default = MONO8,
}
}
using HalconDotNet;
using IDHIKCamera;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Reflection;
namespace CodeLibrary.camera
{
public class HIKIDMVS : ClsCamera
{
static new string cameraName = null;
public override bool Load()
{
try
{
HDLogUtil.error("加载扫码相机:" );
IDHIK.Instance.Load();
List<string> names = IDHIK.Instance.cameraName;
_name = names.ToArray();
IDHIK.Instance.DrawLine = false;
HDLogUtil.error($"加载扫码相机:{string.Join(",", names)}");
if (names != null)
{
// hikNameList.AddRange(names);
//foreach (string name in names)
//{
// LogNet.log.Info("加载到IDHIK相机:" + name);
//}
cameraName = names.Find(s => s.Contains("ID"));
HDLogUtil.error("加载到扫码相机:" + cameraName);
}
}
catch (Exception ex)
{
HDLogUtil.error("解析IDHIK出错:" + ex.StackTrace);
return false;
}
return true;
}
public override bool Open(int index)
{
return IDHIK.Instance.Open(index);
}
public override bool Open(string name)
{
return IDHIK.Instance.Open(name);
}
public override bool OpenAll()
{
return IDHIK.Instance.OpenAll();
}
public override void Close(int index)
{
IDHIK.Instance.Close(index);
}
public override void Close(string name)
{
IDHIK.Instance.Close(name);
}
public override void CloseAll()
{
IDHIK.Instance.CloseAll();
}
public override HObject CaptureOnImage(string name, out List<CodeInfo> cc)
{
Bitmap bitmap = null;
cc = GetImageAndIdentifyCode(out bitmap);
return null;
}
public override HObject CaptureOnImage(string name, out Bitmap bmp,out List<CodeInfo> codeInfos, bool nohalcon = false)
{
codeInfos= GetImageAndIdentifyCode(out bmp);
return null;
}
public override Bitmap GrabOne(int index, PixelType pt = PixelType.MONO8)
{
Bitmap bitmap = null;
_ = GetImageAndIdentifyCode(out bitmap);
return bitmap;
}
public override Bitmap GrabOne(string name, PixelType pt = PixelType.MONO8)
{
Bitmap bitmap = null;
_ = GetImageAndIdentifyCode(out bitmap);
return bitmap;
}
public override Bitmap GrabOneImage(string name, PixelType pt = PixelType.MONO8)
{
Bitmap bitmap = null;
_ = GetImageAndIdentifyCode(out bitmap);
return bitmap;
}
public override bool ProcessOnImage(string name, out object[] result, params Func<string, Bitmap, object>[] func)
{
result = null;
return true;
}
static List<BarcodeInfo> grabOne(out Bitmap bitmap)
{
bitmap = null;
List<BarcodeInfo> barcodeInfos = new List<BarcodeInfo>();
if (string.IsNullOrEmpty(cameraName))
{
return barcodeInfos;
}
try
{
bitmap = (Bitmap)IDHIK.Instance.GrabOne(cameraName, out List<CodeInfo> cc);
if (cc != null)
{
cc.ForEach(c =>
{
barcodeInfos.Add(new BarcodeInfo()
{
Center = new PointF(c.X, c.Y),
Angle = (float)c.Orientation,
CodeType = c.CodeType,
Text = c.CodeStr
});
});
}
}
catch (Exception e)
{
HDLogUtil.error($"{cameraName}取图失败:{e}");
}
return barcodeInfos;
}
public override List<CodeInfo> GetImageAndIdentifyCode(out Bitmap bitmap)
{
bitmap = null;
List<CodeInfo> codeisc = new List<CodeInfo>();
HDLogUtil.error("获取图片相机名称:" + cameraName);
if (string.IsNullOrEmpty(cameraName))
{
return null;
}
try
{
List<CodeInfo> cod = new List<CodeInfo>();
bitmap = (Bitmap)IDHIK.Instance.GrabOne(cameraName, out cod);
cod.ForEach(c =>
{
codeisc.Add(new CodeInfo()
{
CodeStr=c.CodeStr,
CodeType=c.CodeType,
X = c.X,
Y = c.Y,
Orientation= c.Orientation,
});
});
}
catch (Exception e)
{
HDLogUtil.error($"{cameraName}取图失败:{e}");
}
return codeisc;
}
}
public class BarcodeInfo
{
//
// 摘要:
// 文本
public string Text { get; set; }
//
// 摘要:
// 条码类型
public string CodeType { get; set; }
//
// 摘要:
// 中心点
public PointF Center { get; set; }
//
// 摘要:
// 角度,3点钟方向0°,逆时针为正,顺时针为负。
public float Angle { get; set; }
//
// 摘要:
// 条码尺寸大小
public SizeF Size { get; set; }
//
// 摘要:
// 原点垂直于经过中心点的直线的距离
public float Distance { get; set; }
//
// 摘要:
// 副本,深拷贝
public BarcodeInfo Clone()
{
BarcodeInfo barcodeInfo = new BarcodeInfo();
PropertyInfo[] properties = barcodeInfo.GetType().GetProperties();
PropertyInfo[] properties2 = GetType().GetProperties();
for (int i = 0; i < properties.Length; i++)
{
properties[i].SetValue(barcodeInfo, properties2[i].GetValue(this));
}
return barcodeInfo;
}
}
}
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace CodeLibrary
{
public unsafe class EyemDecode
{
public static string codeType = "QR_CODE|DATA_MATRIX";
//public static List<CodeInfo> Decoder(ref Bitmap bmap, string file = null) {
// return Decoder(ref bmap, file);
//}
/// <summary>
/// 识别图像二维码
/// </summary>
/// <param name="bmap">需要手动释放这个bitmap</param>
/// <param name="file">如果传文件的话,bmp传null</param>
/// <returns></returns>
public static List<CodeInfo> Decoder(ref Bitmap bmap, string file = null, int iBlockSize=19, int iRangeC=5, int iSymbolMin=128, int iSymbolMax=215)
{
List<CodeInfo> codelist = new List<CodeInfo>();
try
{
//创建图像引用
EyemImage eyemImage;
BitmapData bitmapData = null;
if (file == null)
{
Rectangle rect = new Rectangle(0, 0, bmap.Width, bmap.Height);
bitmapData = bmap.LockBits(rect, ImageLockMode.ReadOnly, bmap.PixelFormat);
eyemImage = new EyemImage();
eyemImage.ucpImage = bitmapData.Scan0;
eyemImage.iWidth = rect.Width;
eyemImage.iHeight = rect.Height;
eyemImage.iChannels = 1;
eyemImage.iDepth = 0;
}
else
{
eyemImageRead(file, -1, out eyemImage);
}
//创建扫描区域
EyemRect eyemRect = new EyemRect();
eyemRect.iXs = 0;
eyemRect.iYs = 0;
eyemRect.iWidth = eyemImage.iWidth;
eyemRect.iHeight = eyemImage.iHeight;
//string codeType = "QR_CODE|DATA_MATRIX"; //QRCode
int ipNum;
EyemBarCode* tpResults;
DataCodeHandle hObject = null;
try
{
int result = eyemDetectAndDecode(eyemImage, eyemRect, "", codeType, out hObject, out tpResults, out ipNum, false, iBlockSize, iRangeC, iSymbolMin, iSymbolMax);
HDLogUtil.info($"eyemDetectAndDecode:{result},ipNum:{ipNum}");
if (result != 0 || ipNum == 0)
return codelist;
for (int i = 0; i < ipNum; i++)
{
CodeInfo ci = new CodeInfo(Marshal.PtrToStringAnsi(tpResults[i].hText), tpResults[i].iCenterX, tpResults[i].iCenterY);
ci.CodeType = Marshal.PtrToStringAnsi(tpResults[i].hType);
codelist.Add(ci);
}
}
catch (Exception ex) {
HDLogUtil.error($""+ ex.ToString());
}
finally
{
if (hObject != null)
hObject.Dispose();
if (bitmapData != null)
bmap.UnlockBits(bitmapData);
if (file != null)
eyemImageFree(ref eyemImage);
//bmap.Dispose();
}
}
catch (Exception ex)
{
HDLogUtil.error(ex.ToString());
}
//eyemImageFree(eyemImage.ucpImage);
return codelist;
}
//释放解码句柄
private class DataCodeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
public DataCodeHandle() : base(true) { }
protected override bool ReleaseHandle()
{
return eyemDetectAndDecodeFree(handle);
}
}
[DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
private static extern int eyemDetectAndDecode(EyemImage tpImage, EyemRect tpRoi, string fileName, string strCodeType, out DataCodeHandle hObject, out EyemBarCode* tpResults, out int ipNum, bool bUseNiBlack, int iBlockSize, int iRangeC, int iSymbolMin, int iSymbolMax, double dScaleUpAndDown = 1, double dToleErr = 0.5, double dMinorStep = 1.0);
/*
* 参数说明
tpImage 输入图像,可使用”eyemImageRead“接口读取图片(需与“eyemImageFree”配合使用),也可直接创建EyemImage对象。
tpRoi 感兴趣区域,尺寸不能小于iSymbolMax。
fileName 文件名,可不填。
strCodeType 所要识别条码类型,“QRCode|DataMatrix|CODE_128”等等。
hObject 结果释放句柄,配合eyemDetectAndDecodeFree使用
tpResults 识别结果
ipNum 结果数量
bUseNiBlack 使用NiBlack二值化,默认值 false。
iBlockSize 定位块大小(奇数),略大于最大定位块(只二维码),佳世达一般设置为11。
iRangeC 搜索范围,范围越大识别越好时间也相应越长,佳世达一般设置为5。
iSymbolMin 最小二维码尺寸,默认128。
iSymbolMax 最大二维码尺寸,佳世达一般设置为215。
dScaleUpAndDown 缩放,<1表示缩小,>1表示放大,=1表示不缩放
dToleErr 最大允许误差默认50%,越小越严格但可能会识别不到。
dMinorStep 步进,默认1.0。
//返回值
-3 图像不存在
-1 内存不足
0 正常
-100 未识别到条码或参数设置不正确
*/
/// <summary>
/// 读取图像
/// </summary>
/// <param name="filename"></param>
/// <param name="iFalgs"></param>
/// <param name="ucpImage"></param>
/// <returns></returns>
[DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
private static extern int eyemImageRead(string filename, int iFalgs, out EyemImage ucpImage);
/// <summary>
/// 释放图像资源
/// </summary>
/// <param name="eyemImage"></param>
[DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
public static extern void eyemImageFree(ref EyemImage eyemImage);
//释放工具
[DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
private static extern bool eyemDetectAndDecodeFree(IntPtr hObject);
[StructLayout(LayoutKind.Sequential)]
public struct EyemImage
{
/// <summary>
/// 地址
/// </summary>
public IntPtr ucpImage;
/// <summary>
/// 图像内存 x 方向大小
/// </summary>
public int iWidth;
/// <summary>
/// 图像内存 y 方向大小
/// </summary>
public int iHeight;
/// <summary>
/// iDepth:
/// uint8_t 取值范围[0, 255], iDepth = 0(常用,解码图像一般为此种格式)
/// int8_t 取值范围[-128, 127], iDepth = 1
/// uint16_t 取值范围[0, 56635], iDepth = 2(常用,点料机图像一般为此种格式)
/// int16_t 取值范围[-32768, 32767], iDepth = 3
/// int32_t 取值范围[-2147483648, 2147483647], iDepth = 4
/// float_t 取值范围[-3.4028235E38, 3.4028235E38], iDepth = 5
/// double_t 取值范围[-1.7E-308, 1.7E+308], iDepth = 6
/// </summary>
public int iDepth;
/// <summary>
/// 彩色图 iChannels=3或4(比RGB多了Alpha通道),一般为3
/// 灰度图 iChannels = 1
/// </summary>
public int iChannels; // 图像通道数
}
[StructLayout(LayoutKind.Sequential)]
public struct EyemRect
{
public int iXs; // 起始点(左上角) x 坐标
public int iYs; // 起始点(左上角) y 坐标
public int iWidth; // x 方向大小(宽度)
public int iHeight; // y 方向大小(高度)
}
[StructLayout(LayoutKind.Sequential)]
public struct EyemBarCode
{
public double dAngle; // 角度
public int iCenterX; // y坐标
public int iCenterY; // y坐标
public IntPtr hType; // 码类型
public IntPtr hText; // 码内容
}
}
}
using MvCamCtrl.NET;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace CodeLibrary
{
public class HIKCManager
{ /// <summary>
/// 当前相机
/// </summary>
// private Camera cameraCur = null;
private static Dictionary<string, HIKCameraBean> cameraMap = new Dictionary<string, HIKCameraBean>();
/// <summary>
/// 当前相机
/// </summary>
// private MyCamera cameraCurr;
/// <summary>
/// 所有相机列表
/// </summary>
private static MyCamera.MV_CC_DEVICE_INFO_LIST cameraAll;
/// <summary>
/// 所有相机的名称
/// </summary>
private static List<string> cameraName = new List<string>();
/// <summary>
/// 海康相机
/// </summary>
public HIKCManager()
{
cameraAll = new MyCamera.MV_CC_DEVICE_INFO_LIST();
Load();
}
public static HIKCameraBean GetCamera(string cName)
{
if (cameraMap.ContainsKey(cName))
{
return cameraMap[cName];
}
return null;
}
public static void AddCamera(string name, HIKCameraBean bean)
{
if (cameraMap.ContainsKey(name))
{
cameraMap.Remove(name);
}
cameraMap.Add(name, bean);
}
/// <summary>
/// 错误信息
/// </summary>
public static string ErrInfo { set; get; }
/// <summary>
/// 相机总数
/// </summary>
public static int Count
{
get { return (int)cameraAll.nDeviceNum; }
}
/// <summary>
/// 相机名称,ModelName,SerialNumber
/// </summary>
public static string[] CameraName
{
get
{
if (cameraName == null)
{
cameraName = new List<string>();
}
return cameraName.ToArray();
}
}
/// <summary>
/// 当前相机是否打开
/// </summary>
public static bool IsOpen(string cName)
{
HIKCameraBean bean = GetCamera(cName);
if (bean == null || bean.cameraCur == null)
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// 加载相机
/// </summary>
public static void Load()
{
try
{
int rtn = MyCamera.MV_CC_EnumDevices_NET(MyCamera.MV_GIGE_DEVICE | MyCamera.MV_USB_DEVICE, ref cameraAll);
if (rtn != MyCamera.MV_OK) return;
cameraName.Clear();
string s = "";
for (int i = 0; i < cameraAll.nDeviceNum; i++)
{
MyCamera.MV_CC_DEVICE_INFO device = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(cameraAll.pDeviceInfo[i], typeof(MyCamera.MV_CC_DEVICE_INFO));
if (device.nTLayerType == MyCamera.MV_GIGE_DEVICE)
{
IntPtr buffer = Marshal.UnsafeAddrOfPinnedArrayElement(device.SpecialInfo.stGigEInfo, 0);
MyCamera.MV_GIGE_DEVICE_INFO gigeInfo = (MyCamera.MV_GIGE_DEVICE_INFO)Marshal.PtrToStructure(buffer, typeof(MyCamera.MV_GIGE_DEVICE_INFO));
s = "GigE:" + gigeInfo.chModelName + " (" + gigeInfo.chSerialNumber + ")";
}
else if (device.nTLayerType == MyCamera.MV_USB_DEVICE)
{
IntPtr buffer = Marshal.UnsafeAddrOfPinnedArrayElement(device.SpecialInfo.stUsb3VInfo, 0);
MyCamera.MV_USB3_DEVICE_INFO usbInfo = (MyCamera.MV_USB3_DEVICE_INFO)Marshal.PtrToStructure(buffer, typeof(MyCamera.MV_USB3_DEVICE_INFO));
s = "USB:" + usbInfo.chModelName + " (" + usbInfo.chSerialNumber + ")";
}
cameraName.Add(s);
}
}
catch (Exception ex)
{
HDLogUtil.error("HIK Load Error:" + ex.StackTrace);
}
}
/// <summary>
/// 打开指定相机
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static bool Open(string name)
{
int n = cameraName.FindIndex(s => s == name);
if (n == -1)
return false;
else
{
if (cameraMap.ContainsKey(name))
{
if (cameraMap[name].cameraCur != null)
{
cameraMap[name].Close();
}
cameraMap.Remove(name);
}
if (n < 0 || n >= cameraAll.pDeviceInfo.Length) { return false; }
try
{
MyCamera.MV_CC_DEVICE_INFO device = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(cameraAll.pDeviceInfo[n], typeof(MyCamera.MV_CC_DEVICE_INFO));
MyCamera cameraCur = new MyCamera();
HIKCameraBean bean = new HIKCameraBean(cameraCur);
bean.Open(device);
AddCamera(name, bean);
}
catch (Exception ex)
{
ErrInfo = ex.Message;
return false;
}
return true;
}
}
/// <summary>
/// 关闭当前相机
/// </summary>
public static void Close(string cName)
{
HIKCameraBean bean = GetCamera(cName);
if (bean != null && bean.cameraCur != null)
{
bean.cameraCur.MV_CC_CloseDevice_NET();
bean.cameraCur.MV_CC_DestroyDevice_NET();
bean.cameraCur = null;
}
}
public static void CloseAll()
{
foreach (string key in cameraMap.Keys)
{
Close(key);
}
}
/// <summary>
/// 停止抓取数据
/// </summary>
public static void Stop(string cName)
{
HIKCameraBean bean = GetCamera(cName);
if (bean == null || bean.cameraCur != null)
{ return; }
if (bean.cameraCur == null) return;
int rtn = bean.cameraCur.MV_CC_StopGrabbing_NET();
if (rtn != MyCamera.MV_OK) return;
}
/// <summary>
/// 抓取一张图像
/// </summary>
public static Bitmap GrabOne(string cName)
{
HIKCameraBean bean = GetCamera(cName);
if (bean == null || bean.cameraCur != null)
{ return null; }
return bean.GrabOne();
}
/// <summary>
/// 抓取连续图像,触发GrabImage事件
/// </summary>
/// <param name="hWnd"></param>
public static void GrabContinuous(string cName, IntPtr hWnd)
{
HIKCameraBean bean = GetCamera(cName);
if (bean == null || bean.cameraCur != null)
{ return ; }
int rtn = bean.cameraCur.MV_CC_StartGrabbing_NET();
if (rtn != MyCamera.MV_OK) return;
rtn = bean.cameraCur.MV_CC_Display_NET(hWnd);
if (rtn != MyCamera.MV_OK) return;
}
}
}
using MvCamCtrl.NET;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace CodeLibrary
{
public class HIKCameraBean
{
/// <summary>
/// 当前相机
/// </summary>
public MyCamera cameraCur;
/// <summary>
/// 海康相机
/// </summary>
internal HIKCameraBean(MyCamera cameraCur)
{
this.cameraCur = cameraCur;
}
/// <summary>
/// 错误信息
/// </summary>
public string ErrInfo { set; get; }
/// <summary>
/// 当前相机是否打开
/// </summary>
public bool IsOpen
{
get
{
if (cameraCur == null)
return false;
else
return true;
}
}
/// <summary>
/// 相机图像宽度
/// </summary>
public int Width { set; get; }
/// <summary>
/// 相机图像高度
/// </summary>
public int Height { set; get; }
/// <summary>
/// 相机32位缓存
/// </summary>
public byte[] Buffer { get; private set; }
/// <summary>
/// 相机32位图像
/// </summary>
public Bitmap Image { get; private set; }
/// <summary>
/// 打开指定相机
/// </summary>
/// <param name="idx">索引</param>
/// <returns></returns>
public bool Open(MyCamera.MV_CC_DEVICE_INFO device)
{
if (cameraCur == null) return false;
int nRet = cameraCur.MV_CC_CreateDevice_NET(ref device);
if (nRet != MyCamera.MV_OK) return false;
nRet = cameraCur.MV_CC_OpenDevice_NET();
if (nRet != MyCamera.MV_OK)
{
cameraCur.MV_CC_DestroyDevice_NET();
return false;
}
if (device.nTLayerType == MyCamera.MV_GIGE_DEVICE)
{
int nPacketSize = cameraCur.MV_CC_GetOptimalPacketSize_NET();
if (nPacketSize > 0) nRet = cameraCur.MV_CC_SetIntValue_NET("GevSCPSPacketSize", (uint)nPacketSize);
}
cameraCur.MV_CC_SetEnumValue_NET("AcquisitionMode", 2); //工作在连续模式
cameraCur.MV_CC_SetEnumValue_NET("TriggerMode", 0); //连续模式
MyCamera.MVCC_INTVALUE pstValue = new MyCamera.MVCC_INTVALUE();
nRet = cameraCur.MV_CC_GetWidth_NET(ref pstValue);
Width = (int)pstValue.nCurValue;
nRet = cameraCur.MV_CC_GetHeight_NET(ref pstValue);
Height = (int)pstValue.nCurValue;
return true;
}
/// <summary>
/// 关闭当前相机
/// </summary>
public void Close()
{
if (cameraCur != null)
{
cameraCur.MV_CC_CloseDevice_NET();
cameraCur.MV_CC_DestroyDevice_NET();
cameraCur = null;
}
}
/// <summary>
/// 停止抓取数据
/// </summary>
public void Stop()
{
if (cameraCur == null) return;
int rtn = cameraCur.MV_CC_StopGrabbing_NET();
if (rtn != MyCamera.MV_OK) return;
}
/// <summary>
/// 抓取一张图像
/// </summary>
public Bitmap GrabOne()
{
int rtn = cameraCur.MV_CC_StartGrabbing_NET();
if (rtn != MyCamera.MV_OK) return null;
MyCamera.MVCC_INTVALUE stParam = new MyCamera.MVCC_INTVALUE();
rtn = cameraCur.MV_CC_GetIntValue_NET("PayloadSize", ref stParam);
if (rtn != MyCamera.MV_OK) return null;
uint dataSize = stParam.nCurValue;
byte[] dataArr = new byte[dataSize];
uint buffSize = dataSize * 3 + 2048;
byte[] buffArr = new byte[buffSize];
IntPtr pData = Marshal.UnsafeAddrOfPinnedArrayElement(dataArr, 0);
MyCamera.MV_FRAME_OUT_INFO_EX stFrameInfo = new MyCamera.MV_FRAME_OUT_INFO_EX();
rtn = cameraCur.MV_CC_GetOneFrameTimeout_NET(pData, dataSize, ref stFrameInfo, 100000);
if (rtn != MyCamera.MV_OK) return null;
MyCamera.MvGvspPixelType enDstPixelType = stFrameInfo.enPixelType;
switch (stFrameInfo.enPixelType)
{
case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono8:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono10:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono10_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono12:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono12_Packed:
enDstPixelType = stFrameInfo.enPixelType; break;
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR8:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG8:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB8:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG8:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR10:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG10:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB10:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG10:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR12:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG12:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB12:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG12:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR10_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG10_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB10_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG10_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR12_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG12_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB12_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG12_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_RGB8_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_YUV422_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_YUV422_YUYV_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_YCBCR411_8_CBYYCRYY:
enDstPixelType = MyCamera.MvGvspPixelType.PixelType_Gvsp_RGB8_Packed; break;
}
IntPtr pImage = Marshal.UnsafeAddrOfPinnedArrayElement(buffArr, 0);
MyCamera.MV_PIXEL_CONVERT_PARAM stConverPixelParam = new MyCamera.MV_PIXEL_CONVERT_PARAM();
stConverPixelParam.nWidth = stFrameInfo.nWidth;
stConverPixelParam.nHeight = stFrameInfo.nHeight;
stConverPixelParam.pSrcData = pData;
stConverPixelParam.nSrcDataLen = stFrameInfo.nFrameLen;
stConverPixelParam.enSrcPixelType = stFrameInfo.enPixelType;
stConverPixelParam.enDstPixelType = enDstPixelType;
stConverPixelParam.pDstBuffer = pImage;
stConverPixelParam.nDstBufferSize = buffSize;
rtn = cameraCur.MV_CC_ConvertPixelType_NET(ref stConverPixelParam);
if (rtn != MyCamera.MV_OK) return null;
if (enDstPixelType == MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono8)
{
Image = new Bitmap(stFrameInfo.nWidth, stFrameInfo.nHeight, stFrameInfo.nWidth * 1, PixelFormat.Format8bppIndexed, pImage);
ColorPalette cp = Image.Palette;
for (int i = 0; i < 256; i++)
cp.Entries[i] = Color.FromArgb(i, i, i);
Image.Palette = cp;
int picSize = Image.Width * Image.Height;
Buffer = new byte[picSize];
Array.Copy(buffArr, Buffer, picSize);
//Rectangle rect = new Rectangle(0, 0, Image.Width, Image.Height);
//BitmapData bmpData = Image.LockBits(rect, ImageLockMode.ReadWrite, Image.PixelFormat);
//IntPtr iPtr = bmpData.Scan0;
//int picSize = Image.Width * Image.Height;
//Buffer = new byte[picSize];
//Marshal.Copy(iPtr, Buffer, 0, picSize);
//Image.UnlockBits(bmpData);
}
else
{
for (int i = 0; i < stFrameInfo.nHeight; i++)
{
for (int j = 0; j < stFrameInfo.nWidth; j++)
{
byte chRed = buffArr[i * stFrameInfo.nWidth * 3 + j * 3];
buffArr[i * stFrameInfo.nWidth * 3 + j * 3] = buffArr[i * stFrameInfo.nWidth * 3 + j * 3 + 2];
buffArr[i * stFrameInfo.nWidth * 3 + j * 3 + 2] = chRed;
}
}
Image = new Bitmap(stFrameInfo.nWidth, stFrameInfo.nHeight, stFrameInfo.nWidth * 3, PixelFormat.Format24bppRgb, pImage);
int picSize = Image.Width * Image.Height * 3;
Buffer = new byte[picSize];
Array.Copy(buffArr, Buffer, picSize);
return Image;
}
rtn = cameraCur.MV_CC_StopGrabbing_NET();
if (rtn != MyCamera.MV_OK)
{
}
return null;
}
/// <summary>
/// 抓取连续图像,触发GrabImage事件
/// </summary>
/// <param name="hWnd"></param>
public void GrabContinuous(IntPtr hWnd)
{
int rtn = cameraCur.MV_CC_StartGrabbing_NET();
if (rtn != MyCamera.MV_OK) return;
rtn = cameraCur.MV_CC_Display_NET(hWnd);
if (rtn != MyCamera.MV_OK) return;
}
}
}
FrmCodeDecode_Text,二维码识别,Qr code recognition
FrmCodeDecode_label4_Text,参数路径,Parameters of the path
FrmCodeDecode_chbUseParam_Text,使用参数,operation parameter
FrmCodeDecode_btnAn_Text,变暗,darken
FrmCodeDecode_btnLight_Text,提亮,brighten
FrmCodeDecode_btnCopyN_Text,复制名称,Copy Name
FrmCodeDecode_label3_Text,条码类型:,Bar code type:
FrmCodeDecode_label2_Text,相机列表:,Camera list:
FrmCodeDecode_btnExit_Text,退出,Exit
FrmCodeDecode_btnCameraImage_Text,相机获取图片,camera image
FrmCodeDecode_lblCount_Text,条码数量:,Barcode number:
FrmCodeDecode_btnClearLog_Text,清理日志,Clear log
FrmCodeDecode_btnDCode_Text,二维码识别,Qr code recognition
FrmCodeDecode_btnLearn_Text,学习,learn
FrmCodeDecode_btnbarCode_Text,一维码识别,One dimensional code recognition
FrmCodeDecode_btnGray_Text,图像转灰,Turning grey
FrmCodeDecode_btnErZhi_Text,二值化,binaryzation 
FrmCodeDecode_btnSelImage_Text,打开本地图片,Open local image
FrmCodeDecode_label1_Text,图片路径,Image path
FrmCodeLearn_Text,条码参数学习,Bar code parameter learning
FrmCodeLearn_chbHalcon_Text,Halcon获取图片,Halcon Get photo
FrmCodeLearn_label4_Text,图片路径,Image path
FrmCodeLearn_btnDelOld_Text,删除旧参数,Delete old parameter
FrmCodeLearn_chbUseCamera_Text,相机获取实时图片,camera image
FrmCodeLearn_btnSelImage_Text,打开本地图片,Open local image
FrmCodeLearn_chbTest_Text,学习结束自动识别测试,Automatic identification test
FrmCodeLearn_btnClearLog_Text,清理日志,Clear log
FrmCodeLearn_lblCount_Text,条码数量:,Barcode number:
FrmCodeLearn_label3_Text,参数路径,Parameters of the path
FrmCodeLearn_label2_Text,类型:,Type:
FrmCodeLearn_label1_Text,相机:,camera:
FrmCodeLearn_btnExit_Text,退出,Exit
FrmCodeLearn_btnStop_Text,结束学习,End of learning
FrmCodeLearn_btnOpen_Text,开始学习,start to learn
selCamera,请先选择相机,Please select camera
selImage,请先选择图片,Please select picture
title,提示,Notice
imageIsNull,获取二维码图片为空,Get the two-dimensional code picture is empty
sureDelete,确定删除文件:,Make sure to delete the file:
FrmCodeDecode_label6_Text,图片识别结果,Image recognition results:
FrmCodeDecode_butt_cameracode_Text,获取相机图片及条码,Obtain camera images and barcodes
FrmCodeDecode_check_issaveimage_Text,是否保存图片,Is Image Save
FrmCodeDecode_button_optionfeil_Text,选择文件夹,Option Folder
\ No newline at end of file
20181123
增加相机本身获取图片的代码,后续扫码都直接从相机中获取图片,然后扫码
20190731
RC29西安三台料仓的二维码使用halcon无法识别,增加zxing的识别方式。
......@@ -152,7 +152,7 @@ namespace OnlineStore.Common
}
catch (Exception e)
{
LogUtil.error("HTTP GET ERROR:" + e.Message, 102);
LogUtil.error("HTTP GET ERROR:" + e, 102);
}
return "";
}
......
......@@ -72,11 +72,11 @@ namespace OnlineStore.Common
}
catch (SocketException se)
{
throw new Exception(se.Message);
throw new Exception(se.ToString());
}
catch (Exception ex)
{
throw new Exception(ex.Message);
throw new Exception(ex.ToString());
}
}
......@@ -93,7 +93,7 @@ namespace OnlineStore.Common
}
catch (Exception ex)
{
throw new Exception(ex.Message);
throw new Exception(ex.ToString());
}
}
......@@ -115,7 +115,7 @@ namespace OnlineStore.Common
}
catch (Exception ex)
{
LogUtil.error( "ReceiveAccept方法,客户端【"+client.AddStr+"】:" + ex.Message);
LogUtil.error( "ReceiveAccept方法,客户端【"+client.AddStr+"】:" + ex);
//throw new Exception(ex.Message);
}
}
......
......@@ -78,7 +78,7 @@ namespace OnlineStore.Common
}
catch (Exception ex)
{
throw new Exception(ex.Message);
throw new Exception(ex.ToString());
}
}
private StringBuilder sb = new StringBuilder(); //这个是用来保存:接收到了的,但是还没有结束的消息
......
......@@ -312,7 +312,7 @@ namespace OnlineStore.Common.util
}
catch (Exception ex)
{
Common.LogUtil.info($"上传smf图片失败,原因:{ex.Message}");
Common.LogUtil.info($"上传smf图片失败,原因:{ex.ToString()}");
}
}
}
......
......@@ -135,7 +135,7 @@ namespace WebApi.Controllers
catch (Exception ex)
{
result.code = 204;
result.status = $"parse error:{ex.Message}";
result.status = $"parse error:{ex}";
LogUtil.error("QueryStatus", ex);
}
......
......@@ -78,7 +78,7 @@ namespace WebApi.Controllers
catch (Exception ex)
{
result.code = 204;
result.status = $"parse error:{ex.Message}";
result.status = $"parse error:{ex}";
LogUtil.error("startRoller", ex);
}
......
......@@ -89,7 +89,7 @@ namespace WebApi.Controllers
catch (Exception ex)
{
result.code = 204;
result.status = $"parse error:{ex.Message}";
result.status = $"parse error:{ex}";
LogUtil.error("stopRoller", ex);
}
......
using CodeLibrary;
using ConfigHelper;
using DeviceLibrary.AutoScanAndLabel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OnlineStore.Common;
using System;
......@@ -837,6 +838,7 @@ namespace DeviceLibrary
{
try
{
LogUtil.info("labelParam:" + JsonConvert.SerializeObject(labelParam));
//标签位置
SolidBrush blue = new SolidBrush(Color.DarkBlue);
//料盘中心点
......@@ -858,7 +860,9 @@ namespace DeviceLibrary
g.FillEllipse(red, new Rectangle(centrality, pointsize));
int idnex = 0;
labelParam.NewXYAngle.TryGetValue("IsCodeUsed", out idnex);
Point CalPoint = new Point(labelParam.codeInfos[idnex].X, labelParam.codeInfos[idnex].Y);
Point CalPoint = new Point(point.X, point.Y);
if (idnex>=0)
CalPoint = new Point(labelParam.codeInfos[idnex].X, labelParam.codeInfos[idnex].Y);
g.FillEllipse(blue, new Rectangle(CalPoint, pointsize));
g.FillEllipse(yeelow, new Rectangle(point, pointsize));
g.Save();
......@@ -891,7 +895,7 @@ namespace DeviceLibrary
}
catch (Exception ex)
{
LogUtil.error($"保存新坐标图片失败{ex.Message}");
LogUtil.error($"保存新坐标图片失败{ex}");
}
}
public static Point Customlabeling(LabelParam labelParam, Point centrality, out int angle)
......
......@@ -296,13 +296,14 @@ namespace DeviceLibrary
//计算贴标角度的脉冲值
int labelAxisPos = Config.Label_R_360 / 350 * labelAngle;
LogUtil.info($"完整贴标脉冲{labelAxisPos}");
LogUtil.info($"贴标角度脉冲{labelAxisPos}");
//计算像素点位与中心点的差
Label_p3 = new Point(p.X - Right_Batch_Point.X, p.Y - Right_Batch_Point.Y);
//计算像素*脉冲像素比得到脉冲值+中心点基准脉冲
int xDiff = (int)(Label_p3.X * Config.Cam_Pixel_X_Ratio);
int yDiff = (int)(Label_p3.Y * Config.Cam_Pixel_Y_Ratio);
LogUtil.info($"贴标XY脉冲差:X:{xDiff}={Label_p3.X}*{Config.Cam_Pixel_X_Ratio}, Y:{yDiff}={Label_p3.Y}*{Config.Cam_Pixel_Y_Ratio},");
if (LabelMoveInfo.MoveParam.PlateW == 7)
{
LabelMoveInfo.log("当前盘为7寸");
......
......@@ -50,14 +50,14 @@ namespace DeviceLibrary
LeftShelfNoTray = false;
LeftMoveInfo.NextMoveStep(MoveStep.L03);
CylinderMove(null, IO_Type.LeftStopDown, IO_Type.LeftStopUP);
LeftBatchAxisToP2(true);
LeftBatchAxisToP2(Config.Left_Batch_P2, Config.Left_Batch_P1_speed, IO_VALUE.HIGH);
LeftMoveInfo.log($"批量轴上升到P2位置,第一次提升,LeftStartMovePosition={LeftStartMovePosition}");
step = 1;
break;
//没有这个步骤
case MoveStep.L02:
LeftMoveInfo.NextMoveStep(MoveStep.L03);
LeftBatchAxisToP2(false);
LeftBatchAxisToP2(Config.Left_Batch_P2, Config.Left_Batch_P2_speed, IO_VALUE.HIGH);
LeftMoveInfo.log($"批量轴上升到P2位置,二次提升,LeftStartMovePosition={LeftStartMovePosition}");
break;
//轴下降一点
......@@ -86,11 +86,12 @@ namespace DeviceLibrary
break;
//中间步骤给盘,下降一点,获取盘信息
case MoveStep.L11_ReelPutted:
if (step == 2)
if (step == 2 || RightMoveInfo.MoveStep== MoveStep.Wait)
{
LeftCount++;
LeftMoveInfo.NextMoveStep(MoveStep.L12);
LeftBatchAxisDown();
LeftBatchAxisToP2(Config.Left_Batch_P1, Config.Left_Batch_P1_speed, IO_VALUE.LOW);
//LeftBatchAxisDown();
LabelMoveInfo.MoveParam = LeftMoveInfo.MoveParam.clone();
LeftMoveInfo.log($"左侧料盘已放入,批量轴下降固定值");
}
......@@ -137,8 +138,9 @@ namespace DeviceLibrary
{
if (step == 2)
{
LeftMoveInfo.NextMoveStep(MoveStep.L04);
LeftBatchAxisDown();
LeftMoveInfo.NextMoveStep(MoveStep.L03);
LeftBatchAxisToP2(Config.Left_Batch_P1, Config.Left_Batch_P1_speed, IO_VALUE.LOW);
LeftMoveInfo.log($"贴标完成,批量轴下降固定值");
}
else
......@@ -276,24 +278,14 @@ namespace DeviceLibrary
}
int LeftStartMovePosition = 0;
void LeftBatchAxisToP2(bool isFirstMove = true)
void LeftBatchAxisToP2(int target, int Speed, IO_VALUE ioValue)
{
int targetP2 = Config.Left_Batch_P2;
int targetSpeed = Config.Left_Batch_P2_speed;
if (!isFirstMove)
{
int currPosition = Left_Batch_Axis.GetAclPosition();
if (currPosition != -1)
{
//targetP2 = currPosition + Config.Left_Batch_ChangeValue * 80;
if (targetP2 > Config.Left_Batch_P2)
{
targetP2 = Config.Left_Batch_P2;
}
LeftMoveInfo.log("BatchAxisToP2 目标P2: " + targetP2 + "(" + currPosition + ")");
}
targetSpeed = (int)(Config.Left_Batch_P2_speed * 0.7);
}
int targetP2 = target;
int targetSpeed = Speed;
int currPosition = Left_Batch_Axis.GetAclPosition();
LeftMoveInfo.log("BatchAxisToP2 目标P2: " + targetP2 + "(" + currPosition + ")");
LeftMoveInfo.TimeOutSeconds = 200;
LeftMoveInfo.CanWhileCount = 0;
// 需要增加定时器,获取验证信号并停止伺服
......@@ -302,7 +294,7 @@ namespace DeviceLibrary
Config.Left_Batch_Axis.TargetPosition = targetP2;
Left_Batch_Axis.AbsMove(null, targetP2, targetSpeed);
//开始检测信号
Left_Batch_Axis.BatchAxisStartCheck(IO_Type.LeftTop_Check, IO_VALUE.HIGH);
Left_Batch_Axis.BatchAxisStartCheck(IO_Type.LeftTop_Check, ioValue);
}
/// <summary>
/// 左批量轴下降到X23对射信号灭
......@@ -333,7 +325,7 @@ namespace DeviceLibrary
{
int currpoint = Left_Batch_Axis.GetAclPosition();
int countPleHight = PlwHight / Config.Right_Batch_ChangeValue * Config.Left_Batch_ChangeValue;
targetP1 = currpoint - countPleHight;
targetP1 = currpoint - countPleHight + 5000;
LeftMoveInfo.log($"出料提升机构,获取到料盘高度脉冲{PlwHight},当前位置{currpoint},计算盘高{countPleHight}");
}
int targetSpeed = Config.Left_Batch_P1_speed;
......
......@@ -9,6 +9,7 @@ using System.Text;
using System.Threading.Tasks;
using System.Threading;
using OnlineStore.Common.util;
using Newtonsoft.Json;
namespace DeviceLibrary
{
......@@ -31,8 +32,9 @@ namespace DeviceLibrary
clampTool.Release();
//复制右侧料盘信息
MiddleMoveInfo.MoveParam = RightMoveInfo.MoveParam.clone();
RightMoveInfo.MoveParam = new LabelParam();
MiddleMoveInfo.log("右侧可以取料,旋转轴/上下轴转到P2点");
MiddleMoveInfo.log($"右侧可以取料,旋转轴/上下轴转到P2点:{JsonConvert.SerializeObject(MiddleMoveInfo.MoveParam)}");
//MiddleMoveInfo.WaitList.Add(WaitResultInfo.WaitIO(IO_Type.RightArm_Check, IO_VALUE.HIGH));
}
else if (MiddleMoveInfo.IsTimeOut(60))
......@@ -138,8 +140,9 @@ namespace DeviceLibrary
MiddleMoveInfo.NextMoveStep(MoveStep.M08);
CurrentPrintInfo = MiddleMoveInfo.MoveParam.clone();
LabelMoveInfo.NextMoveStep(MoveStep.Lbl_PrintLabel);
LabelMoveInfo.MoveParam = MiddleMoveInfo.MoveParam.clone();
Take_Middle_Axis.AbsMove(MiddleMoveInfo, Config.Take_Middle_P3, Config.Take_Middle_P3_speed);
MiddleMoveInfo.log("左侧允许放料,旋转轴P3");
MiddleMoveInfo.log($"左侧允许放料,旋转轴P3");
}
else
{
......
using CodeLibrary;
using Newtonsoft.Json;
using OnlineStore;
using OnlineStore.Common;
using OnlineStore.Common.util;
......@@ -130,7 +131,7 @@ namespace DeviceLibrary
RightMoveInfo.MoveParam.IsNg = true;
}
else
RightMoveInfo.log($"已完成扫码,等待料盘被取走 Count={x.Count}");
RightMoveInfo.log($"已完成扫码,等待料盘被取走 Count={x.Count},{JsonConvert.SerializeObject(RightMoveInfo.MoveParam)}");
}
RightMoveInfo.NextMoveStep(MoveStep.R10_WaitReelLeave);
}
......
......@@ -38,7 +38,7 @@ namespace DeviceLibrary
Config = (Robot_Config)CSVConfigReader.LoadConfig(Config);
CodeManager.LoadConfig();
IDHIKCamera.LibLogUtil.LogEvent += LibLogUtil_LogEvent;
//IDHIKCamera.LibLogUtil.LogEvent += LibLogUtil_LogEvent;
clampTool = new ClampTool();
if (!clampTool.Open())
......@@ -69,21 +69,22 @@ namespace DeviceLibrary
}
catch (Exception ex)
{
LoadFinishEvent?.Invoke(false, ex.Message);
LoadFinishEvent?.Invoke(false, ex.ToString());
}
}
private static void LibLogUtil_LogEvent(IDHIKCamera.LibLogEventArg libLogEventArg)
{
if (libLogEventArg.Level <= IDHIKCamera.LibLogLevel.Warning)
{
LogUtil.info(libLogEventArg.Msg);
}
else
{
LogUtil.error(libLogEventArg.Msg);
}
}
//private static void LibLogUtil_LogEvent(IDHIKCamera.LibLogEventArg libLogEventArg)
//{
// if (libLogEventArg.Level <= IDHIKCamera.LibLogLevel.Warning)
// {
// LogUtil.info(libLogEventArg.Msg);
// }
// else
// {
// {
// LogUtil.error(libLogEventArg.Msg);
// }
//}
public static void LoadDebug()
{
......
......@@ -36,10 +36,6 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>..\dll\Asa.PrintLabel.dll</HintPath>
</Reference>
<Reference Include="CodeLibrary, Version=1.0.8498.33726, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\dll\CodeLibrary.dll</HintPath>
</Reference>
<Reference Include="ConfigHelper">
<HintPath>..\dll\ConfigHelper.dll</HintPath>
</Reference>
......@@ -166,6 +162,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CodeLibrary\CodeLibrary.csproj">
<Project>{2e0d9598-cb37-46dc-9c9b-d36d4d344451}</Project>
<Name>CodeLibrary</Name>
</ProjectReference>
<ProjectReference Include="..\Common\Common.csproj">
<Project>{43cdd09e-fcf3-4960-a01d-3bbfe9933122}</Project>
<Name>Common</Name>
......
......@@ -193,7 +193,7 @@ namespace DeviceLibrary
}
LogUtil.info($"开始请求ns100服务:识别条码为:{string.Join("##", codes.Select(a=>a.CodeStr+$"@@x:{a.X};y:{a.Y};角度{a.Orientation}"))}");
webResult =NeoSacnRequest(bmp, codes, PlateW);
webResult =NeoSacnRequest(BitmapToBase64(bmp), codes, PlateW);
}
else
{
......
......@@ -2,6 +2,7 @@
using DeviceLibrary;
using HalconDotNet;
using IDHIKCamera;
using Microsoft.Win32;
using Newtonsoft.Json;
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
......@@ -27,7 +28,7 @@ public class RemoteDecodeHelper_mod
static bool IsIDCamera = ConfigHelper.Config.Get<bool>("isStartscanningcode");
static int webclienttimeout = 30 * 1000;
static Process p = new Process();
const string serverhost = "http://127.0.0.1:58137/";
static string serverhost = "http://127.0.0.1:58137/";
public static WebResultCode DecodeRequest(Bitmap bitmap, RemoteDecodeParam remoteDecodeParam)
{
CheckAndRunServer();
......@@ -93,7 +94,7 @@ public class RemoteDecodeHelper_mod
}
#region 扫码相机请求ns100方法
public static WebResultCode NeoSacnRequest(Bitmap bitmap, List<CodeLibrary.CodeInfo> codeInfos,int PlateW)
public static WebResultCode NeoSacnRequest(string bitmapBase64, List<CodeLibrary.CodeInfo> codeInfos,int PlateW)
{
WebResultCode resultCode = null;
try
......@@ -111,7 +112,6 @@ public class RemoteDecodeHelper_mod
CheckAndRunServer();
BitmapData bitmapData = new BitmapData();
string iamgestr = BitmapToBase64(bitmap);
List<BarcodeInfos> barcodeInfos = new List<BarcodeInfos>();
codeInfos.ForEach(c =>
{
......@@ -124,7 +124,7 @@ public class RemoteDecodeHelper_mod
X=c.X, Y=c.Y
});
});
bitmapData.ImageData = iamgestr;
bitmapData.ImageData = bitmapBase64;
bitmapData.BarCodeList = barcodeInfos;
bitmapData.X = RobotManage.Config.Right_Batch_X;
bitmapData.Y = RobotManage.Config.Right_Batch_Y;
......@@ -149,7 +149,7 @@ public class RemoteDecodeHelper_mod
}
catch (Exception ex)
{
LogUtil.error($"请求错误:{ex.Message}");
LogUtil.error($"请求错误:{ex.ToString()}");
}
return resultCode;
}
......@@ -175,7 +175,7 @@ public class RemoteDecodeHelper_mod
}
catch (Exception ex)
{
LogUtil.error($"请求错误:{ex.Message}");
LogUtil.error($"请求错误:{ex}");
}
return resultCode;
}
......@@ -246,7 +246,7 @@ public class RemoteDecodeHelper_mod
}
}
static string BitmapToBase64(Bitmap bitmap)
public static string BitmapToBase64(Bitmap bitmap)
{
using (MemoryStream memoryStream = new MemoryStream())
{
......@@ -298,13 +298,20 @@ public class RemoteDecodeHelper_mod
{
lock (p)
{
var port = (int)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\NS100\\", "port", 58137);
serverhost = "http://127.0.0.1:" + port + "/";
Process proes = new Process();
var pss = Process.GetProcessesByName("Neo Scan");
if (pss.Length > 0)
try
{
LogUtil.info("ns100服务已启动;");
return;
}
if (pss.Length > 0 && !pss[0].HasExited)
{
LogUtil.info("ns100服务已启动;");
return;
}
}
catch { }
var f = ConfigHelper.Config.Get("Display_GetDataAppPath");
string path = Path.Combine(Application.StartupPath, f);
LogUtil.info("启动ns100服务:"+path);
......@@ -316,13 +323,15 @@ public class RemoteDecodeHelper_mod
p.StartInfo = new ProcessStartInfo(path);
p.StartInfo.Arguments = "hide";
p.Start();
int checkcount = 5;
int checkcount = 15;
while (checkcount > 0)
{
try
{
checkcount--;
Thread.Sleep(1000);
Thread.Sleep(500);
port = (int)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\NS100\\", "port", 58137);
serverhost = "http://127.0.0.1:" + port + "/";
MyWebClient webClient = new MyWebClient(webclienttimeout);
var s = webClient.DownloadString(serverhost + "alive");
if (s.Trim() == "\"1\"")
......
......@@ -37,19 +37,19 @@ namespace DeviceLibrary
}
catch (ConnectionException e)
{
msg = "Connection Error:" + e.Message;
msg = "Connection Error:" + e;
}
catch (IOException e)
{
msg = "IO Error:" + e.Message;
msg = "IO Error:" + e;
}
catch (ZebraPrinterLanguageUnknownException e)
{
msg = "Connection Error:" + e.Message;
msg = "Connection Error:" + e;
}
catch (Exception e)
{
msg = "Error:" + e.Message;
msg = "Error:" + e;
}
}
else {
......
......@@ -13,6 +13,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DeviceLibrary", "DeviceLibr
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DL.StandardRobots", "DL.StandardRobots\DL.StandardRobots.csproj", "{F85A7412-B5B3-4291-A448-A10564602E1A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeLibrary", "CodeLibrary\CodeLibrary.csproj", "{2E0D9598-CB37-46DC-9C9B-D36D4D344451}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
......@@ -39,6 +41,10 @@ Global
{F85A7412-B5B3-4291-A448-A10564602E1A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F85A7412-B5B3-4291-A448-A10564602E1A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F85A7412-B5B3-4291-A448-A10564602E1A}.Release|Any CPU.Build.0 = Release|Any CPU
{2E0D9598-CB37-46DC-9C9B-D36D4D344451}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2E0D9598-CB37-46DC-9C9B-D36D4D344451}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2E0D9598-CB37-46DC-9C9B-D36D4D344451}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2E0D9598-CB37-46DC-9C9B-D36D4D344451}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
......
此文件类型无法预览
此文件类型无法预览
此文件类型无法预览
此文件类型无法预览
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!