1 Star 0 Fork 48

darky/称重软件系统过磅汽车衡车牌识别停车门禁智慧城市共享地磅公磅收费

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
App.xaml.cs 98.80 KB
一键复制 编辑 原始数据 按行查看 历史
温暖 提交于 2023-04-14 01:50 . LPR
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209
using ADRcpLib;
using ADSioLib;
using log4net;
using ReaderB;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Threading;
using WG3000_COMM.Common;
using WG3000_COMM.Core;
using static LPR.IPCHelper;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace LPR
{
public class ShareMem
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, IntPtr lParam);
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr CreateFileMapping(int hFile, IntPtr lpAttributes, uint flProtect, uint dwMaxSizeHi, uint dwMaxSizeLow, string lpName);
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr OpenFileMapping(int dwDesiredAccess, bool bInheritHandle, string lpName);
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr MapViewOfFile(IntPtr hFileMapping, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, uint dwNumberOfBytesToMap);
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool UnmapViewOfFile(IntPtr pvBaseAddress);
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
[DllImport("kernel32", EntryPoint = "GetLastError")]
public static extern int GetLastError();
const int ERROR_ALREADY_EXISTS = 183;
const int FILE_MAP_COPY = 0x0001;
const int FILE_MAP_WRITE = 0x0002;
const int FILE_MAP_READ = 0x0004;
const int FILE_MAP_ALL_ACCESS = 0x0002 | 0x0004;
const int PAGE_READONLY = 0x02;
const int PAGE_READWRITE = 0x04;
const int PAGE_WRITECOPY = 0x08;
const int PAGE_EXECUTE = 0x10;
const int PAGE_EXECUTE_READ = 0x20;
const int PAGE_EXECUTE_READWRITE = 0x40;
const int SEC_COMMIT = 0x8000000;
const int SEC_IMAGE = 0x1000000;
const int SEC_NOCACHE = 0x10000000;
const int SEC_RESERVE = 0x4000000;
const int INVALID_HANDLE_VALUE = -1;
IntPtr m_hSharedMemoryFile = IntPtr.Zero;
IntPtr m_pwData = IntPtr.Zero;
bool m_bAlreadyExist = false;
bool m_bInit = false;
long m_MemSize = 0;
public struct MAIN_LPR_OVER_WEIGHT_DATA
{
public string mz;
public string overWeightCount;
public string axleNum;
}
//[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public byte[] StructToBytes<T>(T obj)
{
int size = Marshal.SizeOf(typeof(T));
IntPtr bufferPtr = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(obj, bufferPtr, false);
byte[] bytes = new byte[size];
Marshal.Copy(bufferPtr, bytes, 0, size);
return bytes;
}
catch (Exception ex)
{
throw new Exception("Error in StructToBytes ! " + ex.Message);
}
finally
{
Marshal.FreeHGlobal(bufferPtr);
}
}
public object BytesToStuct(byte[] bytes)
{
int size = Marshal.SizeOf(typeof(MAIN_LPR_OVER_WEIGHT_DATA));
if (size > bytes.Length)
{
return null;
}
IntPtr structPtr = Marshal.AllocHGlobal(size);
Marshal.Copy(bytes, 0, structPtr, size);
object obj = Marshal.PtrToStructure(structPtr, typeof(MAIN_LPR_OVER_WEIGHT_DATA));
Marshal.FreeHGlobal(structPtr);
return obj;
}
public ShareMem()
{
}
~ShareMem()
{
Close();
}
public int Init(string strName, long lngSize)
{
if (lngSize <= 0 || lngSize > 104857600) lngSize = 104857600;
//0x00800000
m_MemSize = lngSize;
if (strName.Length > 0)
{
//创建内存共享体(INVALID_HANDLE_VALUE)
m_hSharedMemoryFile = CreateFileMapping(INVALID_HANDLE_VALUE, IntPtr.Zero, (uint)PAGE_READWRITE, 0, (uint)lngSize, strName);
if (m_hSharedMemoryFile == IntPtr.Zero)
{
m_bAlreadyExist = false;
m_bInit = false;
return 2;
//创建共享体失败
}
else
{
if (GetLastError() == ERROR_ALREADY_EXISTS) //已经创建
{
m_bAlreadyExist = true;
}
else //新创建
{
m_bAlreadyExist = false;
}
}
//---------------------------------------
//创建内存映射
m_pwData = MapViewOfFile(m_hSharedMemoryFile, FILE_MAP_WRITE, 0, 0, (uint)lngSize);
if (m_pwData == IntPtr.Zero)
{
m_bInit = false;
CloseHandle(m_hSharedMemoryFile);
return 3;
//创建内存映射失败
}
else
{
m_bInit = true;
if (m_bAlreadyExist == false)
{
//初始化
}
}
//----------------------------------------
}
else
{
return 1;
//参数错误
}
return 0;
//创建成功
}
/// <summary>
/// 关闭共享内存
/// </summary>
public void Close()
{
if (m_bInit)
{
UnmapViewOfFile(m_pwData);
CloseHandle(m_hSharedMemoryFile);
}
}
/// <summary>
/// 读数据
/// </summary>
/// <param name="bytData">数据</param>
/// <param name="lngAddr">起始地址</param>
/// <param name="lngSize">个数</param>
/// <returns></returns>
public int Read(ref byte[] bytData, int lngAddr, int lngSize)
{
if (lngAddr + lngSize > m_MemSize) return 2;
//超出数据区
if (m_bInit)
{
Marshal.Copy(m_pwData, bytData, lngAddr, lngSize);
}
else
{
return 1;
//共享内存未初始化
}
return 0;
//读成功
}
/// <summary>
/// 写数据
/// </summary>
/// <param name="bytData">数据</param>
/// <param name="lngAddr">起始地址</param>
/// <param name="lngSize">个数</param>
/// <returns></returns>
public int Write(byte[] bytData, int lngAddr, int lngSize)
{
if (lngAddr + lngSize > m_MemSize) return 2;
//超出数据区
if (m_bInit)
{
Marshal.Copy(bytData, lngAddr, m_pwData, lngSize);
}
else
{
return 1;
//共享内存未初始化
}
return 0;
//写成功
}
}
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : Application
{
private static readonly ILog log = LogManager.GetLogger("LPR");
private static readonly int CLOSE_APP = 0x0801;
//当识别到车牌并成功发送给主程序后,主程序发送消息正在称重,称重完成后发送消息继续车牌识别
private static readonly int READY_TO_WEIGH = 0x0804;
private static readonly int GET_PLATE = 0x0806;
private static readonly int WEIGHING_COMPLETE = 0x0807;
private static readonly int IS_WEIGHING = 0x0808;
private static readonly int IS_STABLE = 0x080A;
public static readonly int VIOLATE_WHITE_LIST = 0x080B;
public static readonly int OVER_WEIGHT = 0x080C;
//继电器控制命令0x08F0~0x08FF,最后一位的二进制0000表示全关,1111表示全开
private static readonly int RELAY_MIN = 0x08F0;
private static readonly int RELAY_MAX = 0x08FF;
//单独红绿灯控制参数
private static readonly int GREENON = 0x0F0A;
private static readonly int REDON = 0x0F0B;
private VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK m_PlateResultCB1 = null;
private VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK m_PlateResultCB2 = null;
private string m_LprMode; //车牌识别模式 1:远程射频卡 2:车牌识别相机
private string m_PlateNo = string.Empty;
private string m_DevNo = string.Empty;
//车牌识别相机句柄
int handle1 = 0;
int handle2 = 0;
int serial_handle1 = 0;
int serial_handle2 = 0;
int iSignoState = 0;
byte stat1 = 0;
byte stat2 = 0;
public bool InWeighing { get; private set; }
//控制继电器的命令
private byte[] m_DICmd = new byte[8] { 0x01, 0x02, 0x00, 0x00, 0x00, 0x04, 0x79, 0xC9 };
private byte[] m_DOCmd = new byte[10] { 0x01, 0x0F, 0x00, 0x00, 0x00, 0x04, 0x01, 0x00, 0x00, 0x00 };
private byte[] m_OpenRelay = new byte[9] { 0x7C, 0xFF, 0xFF, 0xD7, 0x00, 0x02, 0x01, 0x01, 0xAB };
private byte[] m_CloseRelay = new byte[9] { 0x7C, 0xFF, 0xFF, 0xD7, 0x00, 0x02, 0x01, 0x00, 0xAC };
private string m_DIORet = string.Empty; //继电器接收到命令的返回值
private int m_TimerTickCount = 0; //持续给继电器发送命令的次数,大于10则超时
private SerialPort m_RelayPort = new SerialPort(); //继电器串口
private DispatcherTimer m_DOTimer; //持续给继电器发送命令的定时器
private DispatcherTimer m_DITimer; //持续给继电器发送命令的定时器
private string signoState;
public string SignoState
{
get { return signoState; }
set
{
if (value != signoState)
{
SendMessageToApp("双髻鲨汽车衡称重软件", "Signo," + value);
//log.Info("发送DI状态给双髻鲨汽车衡称重软件:" + value);
}
signoState = value;
}
}
/// <summary>
/// LPR图片保存位置
/// </summary>
private string LPRSavePath
{
get
{
return ConfigurationManager.AppSettings["LPRSavePath"] + "\\";
}
}
//新的网口继电器
byte[] buffer = new byte[64];
private Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private Thread tcpThread;
byte[] checkRelay = new byte[] { 0x6A, 0xA6, 0x03, 0xFE, 0x06, 0x07 };
byte[] checkGPIO = new byte[] { 0x6A, 0xA6, 0x03, 0xFE, 0x07, 0x08 };
byte[] controlRelay = new byte[] { 0x6A, 0xA6, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00 };
private DispatcherTimer delay2timer = new DispatcherTimer(); //定义定时器,进行周期的查询继电器和数字量状态
private bool ioSwitch = true;
//private bool sendCMDToRealy2Flag = false;
private byte realyStatus;
public byte RealyStatus
{
get { return realyStatus; }
set
{
if (value != realyStatus)
{
//ShowRelayStatus(value);
log.Info("DO收到继电器反馈:" + Convert.ToString(Convert.ToInt32(value) / 4, 2).PadLeft(4, '0'));
}
realyStatus = value;
}
}
private byte gpioStatus;
public byte GPIOStatus
{
get { return gpioStatus; }
set
{
if (value != gpioStatus)
{
int i = (Convert.ToInt32(value) - 3) / 4;
SendMessageToApp("双髻鲨汽车衡称重软件", "Signo," + i.ToString());
//log.Info("发送DI状态给双髻鲨汽车衡称重软件:" + i);
}
gpioStatus = value;
}
}
private byte gpio2Status;
public byte GPIO2Status
{
get { return gpio2Status; }
set
{
if (value != gpio2Status)
{
SendMessageToApp("双髻鲨汽车衡称重软件", "Gpio," + value);
}
gpio2Status = value;
}
}
//远程读卡器串口 旧版
private bool m_IsActiveScan;
private string m_RF1PortName;
private string m_RF2PortName;
private int m_RF1OpenRet = -1;
private int m_RF1ComIndex;
private byte m_RF1ComAdr = 0xFF;
private int m_RF2OpenRet = -1;
private int m_RF2ComIndex;
private byte m_RF2ComAdr = 0xFF;
private DispatcherTimer m_RFTimer = new DispatcherTimer();
//远程读卡器串口 新版
private SerialPort m_RF1Port = new SerialPort();
private SerialPort m_RF2Port = new SerialPort();
private string m_EpcStrAppend = string.Empty;
public static SioBase SioBase = new SioNet();
public static RcpBase RcpBase = new RcpBase();
public static SioBase SioBase2 = new SioNet();
public static RcpBase RcpBase2 = new RcpBase();
public bool IsConnectedSio
{
get
{
if (SioBase == null) return false;
if (!SioBase.bConnected) return false;
return true;
}
}
public bool IsConnectedSio2
{
get
{
if (SioBase2 == null) return false;
if (!SioBase2.bConnected) return false;
return true;
}
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
//根据启动时传递的参数,决定初始化远程刷卡器或者车牌识别相机
if (e.Args.Count() != 0) m_LprMode = e.Args[0];
if (m_LprMode == "1")
{
log.Info("车牌识别方式:远程刷卡器");
//旧版
//OpenRFPort(); //打开读卡器串口
////打开定时器轮询
//m_RFTimer.Interval = TimeSpan.FromMilliseconds(500);
//m_RFTimer.Tick += (sender, args) => RFTimer_Tick();
//m_RFTimer.Start();
//第二版
OpenRFPort();
SioBase.onStatus += SioBase_onStatus;
SioBase.onReceived += SioBase_onReceived;
RcpBase.RxRspParsed += RcpBase_RxRspParsed;
if (ConfigurationManager.AppSettings["RF3Enable"] == "1")
{
SioBase.Connect(ConfigurationManager.AppSettings["RF3IP"], 49152);
}
SioBase2.onStatus += SioBase2_onStatus;
SioBase2.onReceived += SioBase2_onReceived;
RcpBase2.RxRspParsed += RcpBase2_RxRspParsed;
if (ConfigurationManager.AppSettings["RF4Enable"] == "1")
{
SioBase2.Connect(ConfigurationManager.AppSettings["RF4IP"], 49152);
}
}
if (m_LprMode == "2")
{
log.Info("车牌识别方式:车牌识别相机");
VzClientSDK.VzLPRClient_Setup();
Login();
var connStatTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(10) };
connStatTimer.Start();
connStatTimer.Tick += (sender, args) =>
{
if (ConfigurationManager.AppSettings["Camera1Enable"] == "1" && handle1 != 0) VzClientSDK.VzLPRClient_IsConnected(handle1, ref stat1);
if (ConfigurationManager.AppSettings["Camera2Enable"] == "1" && handle2 != 0) VzClientSDK.VzLPRClient_IsConnected(handle2, ref stat2);
if (stat1 == 0 && ConfigurationManager.AppSettings["Camera1Enable"] == "1")
{
log.Info("检测到车牌相机1掉线");
Login();
}
if (stat2 == 0 && ConfigurationManager.AppSettings["Camera2Enable"] == "1")
{
log.Info("检测到车牌相机2掉线");
Login();
}
};
OpenRFPort();
SioBase.onStatus += SioBase_onStatus;
SioBase.onReceived += SioBase_onReceived;
RcpBase.RxRspParsed += RcpBase_RxRspParsed;
if (ConfigurationManager.AppSettings["RF3Enable"] == "1")
{
SioBase.Connect(ConfigurationManager.AppSettings["RF3IP"], 49152);
}
SioBase2.onStatus += SioBase2_onStatus;
SioBase2.onReceived += SioBase2_onReceived;
RcpBase2.RxRspParsed += RcpBase2_RxRspParsed;
if (ConfigurationManager.AppSettings["RF4Enable"] == "1")
{
SioBase2.Connect(ConfigurationManager.AppSettings["RF4IP"], 49152);
}
}
//若有接入继电器,打开继电器串口,初始化继电器定时器
if (ConfigurationManager.AppSettings["RelayEnable"] == "1")
{
m_RelayPort.PortName = ConfigurationManager.AppSettings["RelayUart"];
m_RelayPort.BaudRate = 9600;
try
{
m_RelayPort.Open();
if (m_RelayPort.IsOpen)
{
Thread recvRelayPortDataThread = new Thread(new ThreadStart(RecvRelayPortData)) { IsBackground = true };
recvRelayPortDataThread.Start();
SendMsgToApp("ZXLPR", 0x08F0);
log.Info("打开继电器串口,并初始化继电器:" + m_RelayPort.PortName);
}
}
catch (Exception ex)
{
log.Error(ex.Message);
}
m_DOTimer = new DispatcherTimer();
m_DOTimer.Interval = TimeSpan.FromMilliseconds(100);
m_DOTimer.Tick += (sender, args) => RelayTimer_Tick(m_DOCmd);
m_DITimer = new DispatcherTimer();
m_DITimer.Interval = TimeSpan.FromMilliseconds(500);
m_DITimer.Tick += (sender, args) => SignoStateTimer_Tick();
m_DITimer.Start();
}
else if (ConfigurationManager.AppSettings["Camera1GPIO"] == "1")
{
VzClientSDK.VzLPRClient_Setup();
Login();
m_DITimer = new DispatcherTimer();
m_DITimer.Interval = TimeSpan.FromMilliseconds(500);
m_DITimer.Tick += (sender, args) => SignoStateTimer_Tick();
m_DITimer.Start();
}
if (ConfigurationManager.AppSettings["Relay2Enable"] == "1")
{
try
{
if (!socket.Connected)
socket.Connect(new IPEndPoint(IPAddress.Parse(ConfigurationManager.AppSettings["Relay2IP"]), 8080));
if (socket.Connected)
{
tcpThread = new Thread(TCPReceived);
tcpThread.IsBackground = true;
tcpThread.Start(socket);
//启动后关掉全部继电器
byte[] cmd = new byte[] { 0x6A, 0xA6, 0x05, 0x01, 0x00, 0xFF, 0xFF, 0x04 };
socket.Send(cmd);
log.Info("控制器连接成功,断开全部开关。");
delay2timer.Tick += new EventHandler(Delay2_Timer_Tick);
delay2timer.Interval = TimeSpan.FromSeconds(0.5);
delay2timer.Start();
log.Info("打开DI DO查询定时器");
}
}
catch (Exception ex)
{
log.Info("控制器连接失败:" + ex.Message);
}
}
ComponentDispatcher.ThreadPreprocessMessage += ComponentDispatcher_ThreadPreprocessMessage;
}
#region 串口继电器
//继电器定时器,发送命令直到收到反馈或超时
private void RelayTimer_Tick(byte[] relayCmd)
{
if (m_RelayPort.IsOpen)
{
if (m_DIORet == "010F000000045408")
{
m_DOTimer.Stop();
m_DIORet = string.Empty;
m_TimerTickCount = 0;
log.Info("DO收到继电器反馈");
return;
}
m_RelayPort.Write(relayCmd, 0, relayCmd.Length);
log.Info("发送命令给继电器:" + Convert.ToString(relayCmd[7], 2).PadLeft(4, '0'));
//log.Info("发送命令给继电器:" + ByteArrayToHexString(relayCmd));
}
else
{
log.Warn("继电器串口未打开");
}
if (m_TimerTickCount++ > 10)
{
m_TimerTickCount = 0;
m_DOTimer.Stop();
log.Warn("继电器超时未响应");
}
}
//道闸状态定时器,一直查询道闸状态,并发消息给主APP
private void SignoStateTimer_Tick()
{
if (m_RelayPort.IsOpen)
{
if (m_DIORet.StartsWith("010201"))
{
SignoState = m_DIORet.Substring(7, 1);
}
m_RelayPort.Write(m_DICmd, 0, m_DICmd.Length);
}
if (handle1 != 0)
{
int[] test = new int[1];
int i = 0;
GCHandle hObject = GCHandle.Alloc(test, GCHandleType.Pinned);
IntPtr pObject = hObject.AddrOfPinnedObject();
VzClientSDK.VzLPRClient_GetGPIOValue(handle1, 0, pObject);
if (test[0] == 0)
{
//gpio2Status = 0x30;
SendMessageToApp("双髻鲨汽车衡称重软件", "Gpio," + "0");
}
if (test[0] == 1) i += 1;
VzClientSDK.VzLPRClient_GetGPIOValue(handle1, 1, pObject);
if (test[0] == 1) i += 2;
if (hObject.IsAllocated)
hObject.Free();
SignoState = i.ToString();
}
}
//继电器串口接收数据线程
private void RecvRelayPortData()
{
m_RelayPort.DataReceived += (sender, e) =>
{
try
{
byte[] RecvDatas = new byte[m_RelayPort.BytesToRead];
m_RelayPort.Read(RecvDatas, 0, RecvDatas.Length);
m_DIORet = ByteArrayToHexString(RecvDatas);
}
catch (Exception ex)
{
log.Error(ex.Message);
}
};
}
#endregion
#region 车牌识别相机
private int[] Login()
{
if (ConfigurationManager.AppSettings["Camera1Enable"] == "1" && handle1 == 0)
{
var uname = ConfigurationManager.AppSettings["Camera1Username"];
var pwd = ConfigurationManager.AppSettings["Camera1Password"];
handle1 = VzClientSDK.VzLPRClient_Open(ConfigurationManager.AppSettings["Camera1IP"], 80, uname, pwd);
if (handle1 != 0)
{
log.Info("Camera1 Login Success");
stat1 = 1;
//获取车牌信息
m_PlateResultCB1 = new VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK(OnPlateResult);
VzClientSDK.VzLPRClient_SetPlateInfoCallBack(handle1, m_PlateResultCB1, IntPtr.Zero, 1);
//相机扩展显示屏
if (ConfigurationManager.AppSettings["Camera1LEDEnable"] == "1")
{
//打开485串口
VzClientSDK.VZDEV_SERIAL_RECV_DATA_CALLBACK serial_recv_ = null;
serial_handle1 = VzClientSDK.VzLPRClient_SerialStart(handle1, 0, serial_recv_, IntPtr.Zero);
if (serial_handle1 == 0)
{
log.Info("相机1的485串口1打开失败!");
}
//发送初始化数据
SendMsgToCameraLED(serial_handle1, "车牌识别", "自动称重", DateTime.Now.ToString(), "双髻鲨汽车衡称重", "", "g");
}
}
else
{
log.Info("Camera1 Login Failed");
}
}
if (ConfigurationManager.AppSettings["Camera2Enable"] == "1" && handle2 == 0)
{
var uname = ConfigurationManager.AppSettings["Camera2Username"];
var pwd = ConfigurationManager.AppSettings["Camera2Password"];
handle2 = VzClientSDK.VzLPRClient_Open(ConfigurationManager.AppSettings["Camera2IP"], 80, uname, pwd);
if (handle2 != 0)
{
log.Info("Camera2 Login Success");
stat2 = 1;
//获取车牌信息
m_PlateResultCB2 = new VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK(OnPlateResult);
VzClientSDK.VzLPRClient_SetPlateInfoCallBack(handle2, m_PlateResultCB2, IntPtr.Zero, 1);
//相机扩展显示屏
if (ConfigurationManager.AppSettings["Camera2LEDEnable"] == "1")
{
//打开485串口
VzClientSDK.VZDEV_SERIAL_RECV_DATA_CALLBACK serial_recv_ = null;
serial_handle2 = VzClientSDK.VzLPRClient_SerialStart(handle2, 0, serial_recv_, IntPtr.Zero);
if (serial_handle2 == 0)
{
log.Info("相机2的485串口1打开失败!");
}
//发送初始化数据
SendMsgToCameraLED(serial_handle2, "车牌识别", "自动称重", DateTime.Now.ToString(), "双髻鲨汽车衡称重", "", "g");
}
}
else
{
log.Info("Camera2 Login Failed");
}
}
return new int[] { handle1, handle2, serial_handle1, serial_handle2 };
}
private int OnPlateResult(int handle, IntPtr pUserData, IntPtr pResult, uint uNumPlates,
VzClientSDK.VZ_LPRC_RESULT_TYPE eResultType, IntPtr pImgFull, IntPtr pImgPlateClip)
{
try
{
if (eResultType != VzClientSDK.VZ_LPRC_RESULT_TYPE.VZ_LPRC_RESULT_REALTIME)
{
VzClientSDK.TH_PlateResult result = (VzClientSDK.TH_PlateResult)Marshal.PtrToStructure(pResult, typeof(VzClientSDK.TH_PlateResult));
string strLicense = new string(result.license);
strLicense = strLicense.Replace("\0", "");
if (strLicense == "_无_") return 0;
if (strLicense == "无牌车") return 0;
if (InWeighing) return 0;
//模糊匹配
ConfigurationManager.RefreshSection("appSettings");
if ("1" == ConfigurationManager.AppSettings["FuzzyMatching"])
{
string[] plateList = ConfigurationManager.AppSettings["FuzzyPlateNo"].Split(',');
bool isMatch = false;
foreach (var plate in plateList)
{
string regexStr;
regexStr = plate.Replace("0", "[0,D,Q]");
isMatch = Regex.IsMatch(strLicense, regexStr);
if (isMatch) { strLicense = plate; break; }
regexStr = plate.Replace("D", "[0,D]");
isMatch = Regex.IsMatch(strLicense, regexStr);
if (isMatch) { strLicense = plate; break; }
regexStr = plate.Replace("Q", "[0,Q]");
isMatch = Regex.IsMatch(strLicense, regexStr);
if (isMatch) { strLicense = plate; break; }
regexStr = plate.Replace("0", "[0,D,Q]");
isMatch = Regex.IsMatch(strLicense, regexStr);
if (isMatch) { strLicense = plate; break; }
regexStr = plate.Replace("8", "[8,B]");
isMatch = Regex.IsMatch(strLicense, regexStr);
if (isMatch) { strLicense = plate; break; }
regexStr = plate.Replace("B", "[8,B]");
isMatch = Regex.IsMatch(strLicense, regexStr);
if (isMatch) { strLicense = plate; break; }
regexStr = plate.Replace("E", "[E,F]");
isMatch = Regex.IsMatch(strLicense, regexStr);
if (isMatch) { strLicense = plate; break; }
regexStr = plate.Replace("F", "[E,F]");
isMatch = Regex.IsMatch(strLicense, regexStr);
if (isMatch) { strLicense = plate; break; }
}
}
string tempPicPath = string.Empty;
string strIP = string.Empty;
try
{
byte[] strDecIP = new byte[32];
VzClientSDK.VzLPRClient_GetDeviceIP(handle, ref strDecIP[0], 32);
strIP = Encoding.Default.GetString(strDecIP).TrimEnd('\0');
log.Info($"路径地址:{LPRSavePath}/{strLicense}/");
//string tempPicPath = Environment.CurrentDirectory + "\\Snap\\Temp\\" + strLicense + ".jpg";
var directoryPath = $"{LPRSavePath}/{strLicense}/";
if (!Directory.Exists(directoryPath)) Directory.CreateDirectory(directoryPath);
tempPicPath = $"{directoryPath}{strLicense}-{DateTime.Now.ToString("yyyyMMddHHmm")}.jpg";
// string tempPicPath = LPRSavePath + strLicense + ".jpg";
VzClientSDK.VzLPRClient_ImageSaveToJpeg(pImgFull, tempPicPath, 100);
}
catch (Exception ex)
{
log.Info($"OnPlateResult -Create Image Error:{ ex.Message}");
}
if (strIP == ConfigurationManager.AppSettings["Camera1IP"])
{
SendMessageToApp("双髻鲨汽车衡称重软件", "Plate," + strLicense + ",A," + tempPicPath);
m_DevNo = "A";
}
else if (strIP == ConfigurationManager.AppSettings["Camera2IP"])
{
SendMessageToApp("双髻鲨汽车衡称重软件", "Plate," + strLicense + ",B," + tempPicPath);
m_DevNo = "B";
}
m_PlateNo = strLicense;
log.Info(strIP + " 检测到车牌 " + strLicense);
}
}
catch (Exception e)
{
log.Info($"OnPlateResult Error:{ e.Message}");
}
return 0;
}
private void SendMsgToCameraLED(int handle, string line1, string line2, string line3, string line4, string tts, string rgb)
{
log.Info($"SendMsgToCameraLED :handle:{handle},line1:{line1},line2:{line2},line3:{line3},line4:{line4},tts:{tts},rgb:{rgb}");
line1 = Str2Hex(line1);
line2 = Str2Hex(line2);
line3 = Str2Hex(line3);
line4 = Str2Hex(line4);
tts = Str2Hex(tts);
log.Info($"To Hex :line1:{line1},line2:{line2},line3:{line3},line4:{line4},tts:{tts}");
string line1Len = Convert.ToString(line1.Length / 3, 16).ToUpper().PadLeft(2, '0');
string line2Len = Convert.ToString(line2.Length / 3, 16).ToUpper().PadLeft(2, '0');
string line3Len = Convert.ToString(line3.Length / 3, 16).ToUpper().PadLeft(2, '0');
string line4Len = Convert.ToString(line4.Length / 3, 16).ToUpper().PadLeft(2, '0');
string ttsLen = Convert.ToString(tts.Length / 3, 16).ToUpper().PadLeft(2, '0');
log.Info($"To String :line1Len:{line1Len},line2Len:{line2Len},line3Len:{line3Len},line4Len:{line4Len},ttsLen:{ttsLen}");
string strHead = "00 64 FF FF 6E DL 00 04 ";
string strLine1 = "00 01 01 05 00 R G 00 00 DL DATA";
string strLine2 = "01 01 01 05 00 R G 00 00 DL DATA";
string strLine3 = "02 01 01 05 00 R G 00 00 DL DATA";
string strLine4 = "03 01 01 05 00 R G 00 00 DL DATA";
string strTTS = "0A VTL DATA";
if (rgb == "r")
{
strLine1 = strLine1.Replace("R", "FF").Replace("G", "00");
strLine2 = strLine2.Replace("R", "FF").Replace("G", "00");
strLine3 = strLine3.Replace("R", "FF").Replace("G", "00");
strLine4 = strLine4.Replace("R", "FF").Replace("G", "00");
}
else if (rgb == "g")
{
strLine1 = strLine1.Replace("R", "00").Replace("G", "FF");
strLine2 = strLine2.Replace("R", "00").Replace("G", "FF");
strLine3 = strLine3.Replace("R", "00").Replace("G", "FF");
strLine4 = strLine4.Replace("R", "00").Replace("G", "FF");
}
strLine1 = strLine1.Replace("DL", line1Len).Replace("DATA", line1);
strLine2 = strLine2.Replace("DL", line2Len).Replace("DATA", line2);
strLine3 = strLine3.Replace("DL", line3Len).Replace("DATA", line3);
strLine4 = strLine4.Replace("DL", line4Len).Replace("DATA", line4);
strTTS = strTTS.Replace("VTL", ttsLen).Replace("DATA", tts);
string data = strLine1 + "0D " + strLine2 + "0D " + strLine3 + "0D " + strLine4 + "00 " + strTTS + "00 ";
string dataLen = Convert.ToString(data.Length / 3 + 2, 16).ToUpper().PadLeft(2, '0');
strHead = strHead.Replace("DL", dataLen);
data = strHead + data;
string strcrc = CRC.ToModbusCRC16(data, true);
strcrc = strcrc.Insert(2, " ");
data = data + strcrc;
byte[] send_buf = new byte[1024];
string new_content = data.Insert(data.Length, " ");
int txt_len = new_content.Length;
char[] txt_buf = new_content.ToCharArray();
log.Info($"new_content :new_content:{new_content}");
int index = 0;
char[] strHex = new char[3];
byte uc;
for (int i = 0; i < txt_len - 2; i += 3)
{
if (txt_buf[i + 2] != ' ')
{
log.Info($"16 进制数据输入格式不正确txt_buf :{txt_buf[i + 2]}");
MessageBox.Show("16 进制数据输入格式不正确");
return;
}
strHex[0] = txt_buf[i];
strHex[1] = txt_buf[i + 1];
strHex[2] = (char)0;
for (int j = 0; j < 2; j++)
{
if (strHex[j] < '0' || (strHex[j] > '9' && strHex[j] < 'A') || (strHex[j] > 'F' &&
strHex[j] < 'a') || strHex[j] > 'f')
{
log.Info($"16 进制数据输入格式不正确strHex :{strHex[j]}");
MessageBox.Show("16 进制数据输入格式不正确");
return;
}
}
string hex_value = new string(strHex);
uc = byte.Parse(hex_value, System.Globalization.NumberStyles.HexNumber);
send_buf[index] = uc;
index++;
}
GCHandle hObject = GCHandle.Alloc(send_buf, GCHandleType.Pinned);
IntPtr pObject = hObject.AddrOfPinnedObject();
VzClientSDK.VzLPRClient_SerialSend(handle, pObject, index);
if (hObject.IsAllocated)
hObject.Free();
}
private string Str2Hex(string s)
{
string result = string.Empty;
byte[] arrByte = Encoding.GetEncoding("GB2312").GetBytes(s);
for (int i = 0; i < arrByte.Length; i++)
{
result += Convert.ToString(arrByte[i], 16) + " "; //Convert.ToString(byte, 16)把byte转化成十六进制string
}
return result.ToUpper();
}
#endregion
#region 远程读卡器 旧版
//private void OpenRFPort()
//{
// if (ConfigurationManager.AppSettings["RF1Enable"] == "1")
// {
// m_RF1PortName = ConfigurationManager.AppSettings["RF1Uart"];
// int port = Convert.ToInt32(m_RF1PortName.Substring(3, 1));
// /*
// 1.工作模式 0:应答,1:主动 -> 实时切换
// 2.协议选择【bit0】0:6C,1:6B 【bit1】0:韦根,1:RS232 -> 设置为10,也就是2
// 3.查询区域,6C卡有效,固定设置为5:单张查询
// 4.读取起始地址,固定设置为0:从第一个字开始读
// 5.要读取的字数,RS232有效,固定设置为1:读取一个字
// 6.主动模式+单张查询间隔时间,设置为5,表示5秒的间隔
// */
// byte[] Parameter = new byte[6] { 1, 2, 5, 0, 1, 5 };
// m_RF1OpenRet = StaticClassReaderB.OpenComPort(port, ref m_RF1ComAdr, 5, ref m_RF1ComIndex);
// m_IsActiveScan = true;
// if (m_RF1OpenRet == 0)
// {
// StaticClassReaderB.BuzzerAndLEDControl(ref m_RF1ComAdr, 1, 1, 2, m_RF1ComIndex);
// StaticClassReaderB.SetWorkMode(ref m_RF1ComAdr, Parameter, m_RF1ComIndex);
// byte powerDbm = Convert.ToByte(ConfigurationManager.AppSettings["RF1Power"]);
// StaticClassReaderB.SetPowerDbm(ref m_RF1ComAdr, powerDbm, m_RF1ComIndex);
// log.Info("车辆标签串口1打开成功");
// }
// else
// {
// log.Error("车辆标签串口1打开失败!错误代码:" + m_RF1OpenRet.ToString());
// }
// }
// if (ConfigurationManager.AppSettings["RF2Enable"] == "1")
// {
// m_RF2PortName = ConfigurationManager.AppSettings["RF2Uart"];
// int port = Convert.ToInt32(m_RF2PortName.Substring(3, 1));
// /*
// 1.工作模式 0:应答,1:主动 -> 实时切换
// 2.协议选择【bit0】0:6C,1:6B 【bit1】0:韦根,1:RS232 -> 设置为10,也就是2
// 3.查询区域,6C卡有效,固定设置为5:单张查询
// 4.读取起始地址,固定设置为0:从第一个字开始读
// 5.要读取的字数,RS232有效,固定设置为1:读取一个字
// 6.主动模式+单张查询间隔时间,设置为5,表示5秒的间隔
// */
// byte[] Parameter = new byte[6] { 1, 2, 5, 0, 1, 5 };
// m_RF2OpenRet = StaticClassReaderB.OpenComPort(port, ref m_RF2ComAdr, 5, ref m_RF2ComIndex);
// if (m_RF2OpenRet == 0)
// {
// StaticClassReaderB.BuzzerAndLEDControl(ref m_RF2ComAdr, 1, 1, 2, m_RF2ComIndex);
// StaticClassReaderB.SetWorkMode(ref m_RF2ComAdr, Parameter, m_RF2ComIndex);
// byte powerDbm = Convert.ToByte(ConfigurationManager.AppSettings["RF2Power"]);
// StaticClassReaderB.SetPowerDbm(ref m_RF2ComAdr, powerDbm, m_RF2ComIndex);
// log.Info("车辆标签串口2打开成功");
// }
// else
// {
// log.Error("车辆标签串口2打开失败!错误代码:" + m_RF2OpenRet.ToString());
// }
// }
//}
//private void RFTimer_Tick()
//{
// if (m_RF1OpenRet == 0)
// {
// byte[] ScanModeData = new byte[100];
// int Totallen = 0;
// int fCmdRet = StaticClassReaderB.ReadActiveModeData(ScanModeData, ref Totallen, m_RF1ComIndex);
// if (fCmdRet == 0)
// {
// //读取到卡,设置为应答模式
// PassiveScan();
// byte[] daw = new byte[12]; //epc长度12
// Array.Copy(ScanModeData, 4, daw, 0, 12);
// string strEPC = ByteArrayToHexString(daw);
// CarLabelModel carLabel = SQLDataAccess.LoadCarLabel(strEPC);
// if (carLabel != null)
// {
// log.Info("读卡器1," + strEPC + "," + carLabel.PlateNo);
// SendMessageToApp("双髻鲨汽车衡称重软件", "Plate," + carLabel.PlateNo + ",A");
// }
// else
// {
// log.Info("读卡器1," + strEPC + ",未查询到车号");
// ActiveScan();
// }
// }
// }
// if (m_RF2OpenRet == 0)
// {
// byte[] ScanModeData = new byte[100];
// int Totallen = 0;
// int fCmdRet = StaticClassReaderB.ReadActiveModeData(ScanModeData, ref Totallen, m_RF2ComIndex);
// if (fCmdRet == 0)
// {
// //读取到卡,设置为应答模式
// PassiveScan();
// byte[] daw = new byte[12]; //epc长度12
// Array.Copy(ScanModeData, 4, daw, 0, 12);
// string strEPC = ByteArrayToHexString(daw);
// CarLabelModel carLabel = SQLDataAccess.LoadCarLabel(strEPC);
// if (carLabel != null)
// {
// log.Info("读卡器2," + strEPC + "," + carLabel.PlateNo);
// SendMessageToApp("双髻鲨汽车衡称重软件", "Plate," + carLabel.PlateNo + ",B");
// }
// else
// {
// log.Info("读卡器2," + strEPC + ",未查询到车号");
// ActiveScan();
// }
// }
// }
//}
//private void ActiveScan()
//{
// byte[] Parameter = new byte[6] { 1, 2, 5, 0, 1, 5 };
// StaticClassReaderB.SetWorkMode(ref m_RF1ComAdr, Parameter, m_RF1ComIndex);
// StaticClassReaderB.SetWorkMode(ref m_RF2ComAdr, Parameter, m_RF2ComIndex);
// m_IsActiveScan = true;
// log.Info("RF主动模式");
//}
//private void PassiveScan()
//{
// byte[] Parameter = new byte[6] { 0, 2, 5, 0, 1, 5 };
// StaticClassReaderB.SetWorkMode(ref m_RF1ComAdr, Parameter, m_RF1ComIndex);
// StaticClassReaderB.SetWorkMode(ref m_RF2ComAdr, Parameter, m_RF2ComIndex);
// m_IsActiveScan = false;
// log.Info("RF被动模式");
//}
#endregion
#region 远程读卡器 第二版
private void OpenRFPort()
{
if (ConfigurationManager.AppSettings["RF1Enable"] == "1")
{
m_RF1Port.PortName = ConfigurationManager.AppSettings["RF1Uart"];
m_RF1Port.BaudRate = 57600;
try
{
m_RF1Port.Open();
if (m_RF1Port.IsOpen)
{
Thread recvRF1PortDataThread = new Thread(new ThreadStart(RecvRF1PortData)) { IsBackground = true };
recvRF1PortDataThread.Start();
log.Info("打开RF1串口:" + m_RF1Port.PortName);
}
}
catch (Exception ex)
{
log.Error(ex.Message);
}
}
if (ConfigurationManager.AppSettings["RF2Enable"] == "1")
{
m_RF2Port.PortName = ConfigurationManager.AppSettings["RF2Uart"];
m_RF2Port.BaudRate = 57600;
try
{
m_RF2Port.Open();
if (m_RF2Port.IsOpen)
{
Thread recvRF2PortDataThread = new Thread(new ThreadStart(RecvRF2PortData)) { IsBackground = true };
recvRF2PortDataThread.Start();
log.Info("打开RF2串口:" + m_RF2Port.PortName);
}
}
catch (Exception ex)
{
log.Error(ex.Message);
}
}
}
//RF1串口接收数据线程
private void RecvRF1PortData()
{
m_RF1Port.DataReceived += (sender, e) =>
{
try
{
byte[] RecvDatas = new byte[m_RF1Port.BytesToRead];
m_RF1Port.Read(RecvDatas, 0, RecvDatas.Length);
string strEPC = ByteArrayToHexString(RecvDatas);
m_EpcStrAppend += strEPC;
if (!m_EpcStrAppend.StartsWith("CCFF"))
{
m_EpcStrAppend = m_EpcStrAppend.Substring(m_EpcStrAppend.IndexOf("CCFF"));
}
if (m_EpcStrAppend.Length < 46)
{
log.Info("append: " + m_EpcStrAppend);
return;
}
if (!m_EpcStrAppend.StartsWith("CCFF"))
{
log.Info("NOT FIND CCFF");
return;
}
strEPC = m_EpcStrAppend.Substring(18, 24);
m_EpcStrAppend = string.Empty;
CarLabelModel carLabel = SQLDataAccess.LoadCarLabel(strEPC);
if (carLabel != null)
{
if (!InWeighing && carLabel.PlateNo != m_PlateNo)
{
log.Info("读卡器1," + strEPC + "," + carLabel.PlateNo);
m_PlateNo = carLabel.PlateNo;
SendMessageToApp("双髻鲨汽车衡称重软件", "Plate," + carLabel.PlateNo + ",A");
}
}
else
{
log.Info("读卡器1," + strEPC + ",未查询到车号");
}
}
catch (Exception ex)
{
log.Error(ex.Message);
}
};
}
private void RecvRF2PortData()
{
m_RF2Port.DataReceived += (sender, e) =>
{
try
{
byte[] RecvDatas = new byte[m_RF2Port.BytesToRead];
m_RF2Port.Read(RecvDatas, 0, RecvDatas.Length);
string strEPC = ByteArrayToHexString(RecvDatas);
m_EpcStrAppend += strEPC;
if (m_EpcStrAppend.Length < 42)
{
//m_EpcStrAppend += strEPC;
//log.Info(m_EpcStrAppend);
return;
}
strEPC = m_EpcStrAppend.Substring(18, 24);
m_EpcStrAppend = string.Empty;
//if (strEPC.Length < 24)
//{
// log.Info(strEPC);
// return;
//}
//strEPC = strEPC.Substring(18, 24);
CarLabelModel carLabel = SQLDataAccess.LoadCarLabel(strEPC);
if (carLabel != null)
{
if (!InWeighing && carLabel.PlateNo != m_PlateNo)
{
log.Info("读卡器2," + strEPC + "," + carLabel.PlateNo);
m_PlateNo = carLabel.PlateNo;
SendMessageToApp("双髻鲨汽车衡称重软件", "Plate," + carLabel.PlateNo + ",B");
}
}
else
{
log.Info("读卡器2," + strEPC + ",未查询到车号");
}
}
catch (Exception ex)
{
log.Error(ex.Message);
}
};
}
#endregion
#region 远程读卡器 网络版
public void SendSio(ProtocolPacket protocolPacket)
{
if (IsConnectedSio)
{
RcpBase.ShowBytePack(protocolPacket);
SioBase.Send(protocolPacket.ToArray());
}
}
private void SioBase_onStatus(object sender, StatusEventArgs e)
{
try
{
switch ((StatusType)e.Status)
{
case StatusType.CONNECT_OK:
try
{
int intVer = Convert.ToInt32(e.Msg);
}
catch { }
log.Info("CONNECTED OK> " + e.Msg + "(" + SioBase.ToString() + ")");
break;
case StatusType.CONNECT_FAIL:
log.Info("ERROR> " + e.Msg + "(" + SioBase.ToString() + ")");
break;
case StatusType.DISCONNECT_OK:
log.Info("DISCONNECT OK> " + e.Msg + "(" + SioBase.ToString() + ")");
break;
case StatusType.DISCONNECT_EXCEPT:
log.Info("ERROR> " + e.Msg + "(" + SioBase.ToString() + ")");
break;
default:
break;
}
}
catch (Exception ex)
{
log.Info(ex.ToString());
}
}
private void SioBase_onReceived(object sender, ReceivedEventArgs e)
{
RcpBase.ReciveBytePkt(e.Data);
}
private void RcpBase_RxRspParsed(object sender, ProtocolEventArgs e)
{
try
{
log.Info("Rx> " + TagInfo.ByteArrayToHexString(e.Data));
__ParseRsp(e.Protocol);
}
catch (Exception ex)
{
log.Info(ex.ToString());
}
}
private void SioBase2_onStatus(object sender, StatusEventArgs e)
{
try
{
switch ((StatusType)e.Status)
{
case StatusType.CONNECT_OK:
try
{
int intVer = Convert.ToInt32(e.Msg);
}
catch { }
log.Info("CONNECTED OK> " + e.Msg + "(" + SioBase2.ToString() + ")");
break;
case StatusType.CONNECT_FAIL:
log.Info("ERROR> " + e.Msg + "(" + SioBase2.ToString() + ")");
break;
case StatusType.DISCONNECT_OK:
log.Info("DISCONNECT OK> " + e.Msg + "(" + SioBase2.ToString() + ")");
break;
case StatusType.DISCONNECT_EXCEPT:
log.Info("ERROR> " + e.Msg + "(" + SioBase2.ToString() + ")");
break;
default:
break;
}
}
catch (Exception ex)
{
log.Info(ex.ToString());
}
}
private void SioBase2_onReceived(object sender, ReceivedEventArgs e)
{
RcpBase2.ReciveBytePkt(e.Data);
}
private void RcpBase2_RxRspParsed(object sender, ProtocolEventArgs e)
{
try
{
log.Info("Rx> " + TagInfo.ByteArrayToHexString(e.Data));
__ParseRsp2(e.Protocol);
}
catch (Exception ex)
{
log.Info(ex.ToString());
}
}
private int GetCodelen(byte iData)
{
return (((iData >> 3) + 1) * 2);
}
private string GetRssi(byte rssi)
{
int rssidBm = (sbyte)rssi; // rssidBm is negative && in bytes
rssidBm -= Convert.ToInt32("-20", 10);
rssidBm -= Convert.ToInt32("3", 10);
return rssidBm.ToString();
}
private void __ParseRsp(ProtocolPacket protocolPacket)
{
switch (protocolPacket.Code)
{
case RcpBase.RCP_CMD_INFO:
if (protocolPacket.Length > 30 && (protocolPacket.Type & 0x7f) == 0)
{
#region ---Parameter---
string strInfo = Encoding.ASCII.GetString(protocolPacket.Payload, 0, protocolPacket.Length);
log.Info("Type:" + RcpBase.Mode + RcpBase.Type + " - Version:" + RcpBase.Version + " - Address: " + RcpBase.Address);
#endregion
}
break;
case RcpBase.RCP_MM_READ_C_UII:
if (protocolPacket.Type == 2 || protocolPacket.Type == 5)
{
int pcepclen = GetCodelen(protocolPacket.Payload[1]);
int datalen = protocolPacket.Length - 2;//去掉天线号去掉rssi
TagInfo cp = new TagInfo
{
TagType = TagType.TYPE_6C,
Length = datalen,//去掉天线号去掉RSSI
Antenna = protocolPacket.Payload[0],
PCData = TagInfo.GetData(protocolPacket.Payload, 1, 2),
EPCData = TagInfo.GetData(protocolPacket.Payload, 3, pcepclen - 2),
Rssi = GetRssi(protocolPacket.Payload[protocolPacket.Length - 1]) + "dBm"
};
if ((datalen - pcepclen) > 0) cp.DataBytes = TagInfo.GetData(protocolPacket.Payload, 1 + pcepclen, datalen - pcepclen);
//txtCard.Text = cp.EPCString;
//log.Info(cp.EPCString);
CarLabelModel carLabel = SQLDataAccess.LoadCarLabel(cp.EPCString);
if (carLabel != null)
{
//log.Info($"carLabel.PlateNo:{carLabel.PlateNo},InWeighing:{InWeighing},m_PlateNo:{m_PlateNo}");
if (!InWeighing && carLabel.PlateNo != m_PlateNo)
{
m_PlateNo = carLabel.PlateNo;
//log.Info($"protocolPacket.Address:{ByteArrayToHexString(protocolPacket.Address)},RF3IP:{ConfigurationManager.AppSettings["RF3IP"]},RF4IP:{ConfigurationManager.AppSettings["RF4IP"]}");
//if (ByteArrayToHexString(protocolPacket.Address) == ConfigurationManager.AppSettings["RF3IP"])
//{
log.Info("读卡器1," + cp.EPCString + "," + carLabel.PlateNo);
SendMessageToApp("双髻鲨汽车衡称重软件", "Plate," + carLabel.PlateNo + ",A");
//}
//else if (ByteArrayToHexString(protocolPacket.Address) == ConfigurationManager.AppSettings["RF4IP"])
//{
// log.Info("读卡器2," + cp.EPCString + "," + carLabel.PlateNo);
// SendMessageToApp("双髻鲨汽车衡称重软件", "Plate," + carLabel.PlateNo + ",B");
//}
}
}
else
{
log.Info("卡号: " + cp.EPCString + " 未查询到车号");
}
}
break;
case RcpBase.RCP_MM_READ_C_DT:
if (protocolPacket.Type == 0)
{
int pcepclen = GetCodelen(protocolPacket.Payload[1]);
int datalen = protocolPacket.Length - pcepclen - 1;//去掉天线号去掉PC+EPc
TagInfo cp = new TagInfo
{
TagType = TagType.TYPE_6C,
Length = datalen,
Antenna = protocolPacket.Payload[0],
PCData = TagInfo.GetData(protocolPacket.Payload, 1, 2),
EPCData = TagInfo.GetData(protocolPacket.Payload, 3, pcepclen - 2),
DataBytes = TagInfo.GetData(protocolPacket.Payload, 1 + pcepclen, datalen)
};
}
break;
case RcpBase.RCP_MM_WRITE_C_DT:
if (protocolPacket.Type == 0)
{
int pcepclen = GetCodelen(protocolPacket.Payload[1]);
int datalen = protocolPacket.Length - pcepclen - 1;//去掉天线号去掉PC+EPc
TagInfo cp = new TagInfo
{
TagType = TagType.TYPE_6C,
Length = datalen,
Antenna = protocolPacket.Payload[0],
PCData = TagInfo.GetData(protocolPacket.Payload, 1, 2),
EPCData = TagInfo.GetData(protocolPacket.Payload, 3, pcepclen - 2)
};
}
break;
case RcpBase.RCP_MM_GET_ACCESS_EPC_MATCH:
break;
case RcpBase.RCP_MM_SET_ACCESS_EPC_MATCH:
break;
default:
break;
}
}
private void __ParseRsp2(ProtocolPacket protocolPacket)
{
switch (protocolPacket.Code)
{
case RcpBase.RCP_CMD_INFO:
if (protocolPacket.Length > 30 && (protocolPacket.Type & 0x7f) == 0)
{
#region ---Parameter---
string strInfo = Encoding.ASCII.GetString(protocolPacket.Payload, 0, protocolPacket.Length);
log.Info("Type:" + RcpBase.Mode + RcpBase.Type + " - Version:" + RcpBase.Version + " - Address: " + RcpBase.Address);
#endregion
}
break;
case RcpBase.RCP_MM_READ_C_UII:
if (protocolPacket.Type == 2 || protocolPacket.Type == 5)
{
int pcepclen = GetCodelen(protocolPacket.Payload[1]);
int datalen = protocolPacket.Length - 2;//去掉天线号去掉rssi
TagInfo cp = new TagInfo
{
TagType = TagType.TYPE_6C,
Length = datalen,//去掉天线号去掉RSSI
Antenna = protocolPacket.Payload[0],
PCData = TagInfo.GetData(protocolPacket.Payload, 1, 2),
EPCData = TagInfo.GetData(protocolPacket.Payload, 3, pcepclen - 2),
Rssi = GetRssi(protocolPacket.Payload[protocolPacket.Length - 1]) + "dBm"
};
if ((datalen - pcepclen) > 0) cp.DataBytes = TagInfo.GetData(protocolPacket.Payload, 1 + pcepclen, datalen - pcepclen);
//txtCard.Text = cp.EPCString;
//log.Info(cp.EPCString);
CarLabelModel carLabel = SQLDataAccess.LoadCarLabel(cp.EPCString);
if (carLabel != null)
{
//log.Info($"carLabel.PlateNo:{carLabel.PlateNo},InWeighing:{InWeighing},m_PlateNo:{m_PlateNo}");
if (!InWeighing && carLabel.PlateNo != m_PlateNo)
{
m_PlateNo = carLabel.PlateNo;
//log.Info($"protocolPacket.Address:{ByteArrayToHexString(protocolPacket.Address)},RF3IP:{ConfigurationManager.AppSettings["RF3IP"]},RF4IP:{ConfigurationManager.AppSettings["RF4IP"]}");
//if (ByteArrayToHexString(protocolPacket.Address) == ConfigurationManager.AppSettings["RF3IP"])
//{
// log.Info("读卡器1," + cp.EPCString + "," + carLabel.PlateNo);
// SendMessageToApp("双髻鲨汽车衡称重软件", "Plate," + carLabel.PlateNo + ",A");
//}
//else if (ByteArrayToHexString(protocolPacket.Address) == ConfigurationManager.AppSettings["RF4IP"])
//{
log.Info("读卡器2," + cp.EPCString + "," + carLabel.PlateNo);
SendMessageToApp("双髻鲨汽车衡称重软件", "Plate," + carLabel.PlateNo + ",B");
//}
}
}
else
{
log.Info("卡号: " + cp.EPCString + " 未查询到车号");
}
}
break;
case RcpBase.RCP_MM_READ_C_DT:
if (protocolPacket.Type == 0)
{
int pcepclen = GetCodelen(protocolPacket.Payload[1]);
int datalen = protocolPacket.Length - pcepclen - 1;//去掉天线号去掉PC+EPc
TagInfo cp = new TagInfo
{
TagType = TagType.TYPE_6C,
Length = datalen,
Antenna = protocolPacket.Payload[0],
PCData = TagInfo.GetData(protocolPacket.Payload, 1, 2),
EPCData = TagInfo.GetData(protocolPacket.Payload, 3, pcepclen - 2),
DataBytes = TagInfo.GetData(protocolPacket.Payload, 1 + pcepclen, datalen)
};
}
break;
case RcpBase.RCP_MM_WRITE_C_DT:
if (protocolPacket.Type == 0)
{
int pcepclen = GetCodelen(protocolPacket.Payload[1]);
int datalen = protocolPacket.Length - pcepclen - 1;//去掉天线号去掉PC+EPc
TagInfo cp = new TagInfo
{
TagType = TagType.TYPE_6C,
Length = datalen,
Antenna = protocolPacket.Payload[0],
PCData = TagInfo.GetData(protocolPacket.Payload, 1, 2),
EPCData = TagInfo.GetData(protocolPacket.Payload, 3, pcepclen - 2)
};
}
break;
case RcpBase.RCP_MM_GET_ACCESS_EPC_MATCH:
break;
case RcpBase.RCP_MM_SET_ACCESS_EPC_MATCH:
break;
default:
break;
}
}
#endregion
#region 继电器网络版
private void Delay2_Timer_Tick(object sender, EventArgs e)
{
try
{
if (ioSwitch)
{
ioSwitch = false;
socket.Send(checkRelay);
}
else
{
ioSwitch = true;
socket.Send(checkGPIO);
}
}
catch (Exception ex)
{
log.Info("控制器连接失败:" + ex.Message);
}
}
private void TCPReceived(object obj)
{
string str;
while (true)
{
Socket receiveSocket = obj as Socket;
try
{
if (receiveSocket.Available > 0)
{
int result = receiveSocket.Receive(buffer);
if (result == 0)
{
break;
}
else
{
str = ByteArrayToHexString(buffer);
if (str.StartsWith("6AA60406"))
{
RealyStatus = buffer[5];
}
if (str.StartsWith("6AA60407"))
{
GPIOStatus = buffer[5];
}
}
}
}
catch (Exception ex)
{
log.Info("服务器异常:" + ex.Message);
}
}
}
private int checksum(byte[] src)
{
int sum = 0;
for (int i = 0; i < src.Length; i++)
{
sum += src[i];
}
return sum;
}
#endregion
/*
public object getSHM_LPR() {
ShareMem MemDB = new ShareMem();
ShareMem MemDB2 = new ShareMem();
MemDB.Init("shared", 1024 * 8);
MemDB2.Init("shared_len", 5 * 8);
byte[] a = new byte[4];
MemDB2.Read(ref a, 0, 4);
int len = System.BitConverter.ToInt32(a, 0);
byte[] b = new byte[len];
MemDB.Read(ref b, 0, len);
object c = MemDB.BytesToStuct(b);
return c;
}
*/
public ShareMem.MAIN_LPR_OVER_WEIGHT_DATA getOverLpr()
{
ShareMem MemDB = new ShareMem();
ShareMem MemDB2 = new ShareMem();
ShareMem MemDB3 = new ShareMem();
MemDB.Init("shared_over_mz", 10 * 8);
MemDB2.Init("shared_over_count", 10 * 8);
MemDB3.Init("shared_over_axle_num", 10 * 8);
byte[] mz = new byte[10];
byte[] overWeight = new byte[10];
byte[] axleNum = new byte[10];
MemDB.Read(ref mz, 0, 10);
MemDB2.Read(ref overWeight, 0, 10);
MemDB3.Read(ref axleNum, 0, 10);
ShareMem.MAIN_LPR_OVER_WEIGHT_DATA obj;
obj.mz = System.Text.Encoding.Default.GetString(mz).TrimEnd();
obj.axleNum = System.Text.Encoding.Default.GetString(axleNum).TrimEnd();
obj.overWeightCount = System.Text.Encoding.Default.GetString(overWeight).TrimEnd();
return obj;
}
public string getWeighingComplete()
{
ShareMem MemDB = new ShareMem();
MemDB.Init("shared_weighing_complete", 10 * 8);
byte[] mzBytes = new byte[10];
MemDB.Read(ref mzBytes, 0, 10);
string mz = System.Text.Encoding.Default.GetString(mzBytes).TrimEnd();
return mz;
}
//接收其他APP传来的消息
private void ComponentDispatcher_ThreadPreprocessMessage(ref MSG msg, ref bool handled)
{
try
{
if (msg.message == CLOSE_APP)
{
if (m_LprMode == "2")
{
VzClientSDK.VzLPRClient_Cleanup();
}
Thread.Sleep(100);
Current.Shutdown();
}
if (msg.message == OVER_WEIGHT)
{
VzClientSDK.VzLPRClient_Setup();
int[] tmp_handle = Login();
ShareMem.MAIN_LPR_OVER_WEIGHT_DATA obj = getOverLpr();
Configuration AWSConfig = ConfigurationManager.OpenExeConfiguration("TruckScale.exe");
AppSettingsSection AWSSection = (AppSettingsSection)AWSConfig.GetSection("appSettings");
string unit = AWSSection.Settings["WeighingUnit"].Value.ToUpper();
log.Info($"obj.overWeightCount:{obj.overWeightCount}");
if (ConfigurationManager.AppSettings["CameraLEDMode"] == "0")
{
if (double.Parse(obj.overWeightCount) > 0)
{
if (ConfigurationManager.AppSettings["Camera1LEDEnable"] == "1") SendMsgToCameraLED(tmp_handle[2], "车号:" + m_PlateNo, "轴数:" + obj.axleNum, "重量:" + obj.mz + unit, "超载:" + obj.overWeightCount + unit, "", "r");
if (ConfigurationManager.AppSettings["Camera2LEDEnable"] == "1") SendMsgToCameraLED(tmp_handle[3], "车号:" + m_PlateNo, "轴数:" + obj.axleNum, "重量:" + obj.mz + unit, "超载" + obj.overWeightCount + unit, "", "r");
}
else
{
if (ConfigurationManager.AppSettings["Camera1LEDEnable"] == "1") SendMsgToCameraLED(tmp_handle[2], "车号:" + m_PlateNo, "轴数:" + obj.axleNum, "重量:" + obj.mz + "T", "超载:" + obj.overWeightCount + "T", "", "g");
if (ConfigurationManager.AppSettings["Camera2LEDEnable"] == "1") SendMsgToCameraLED(tmp_handle[3], "车号:" + m_PlateNo, "轴数:" + obj.axleNum, "重量:" + obj.mz + "T", "超载" + obj.overWeightCount + "T", "", "g");
}
}
}
if (msg.message == WEIGHING_COMPLETE)
{
/*
VzClientSDK.VzLPRClient_Setup();
int[] tmp_handle = Login();
string mz = System.Text.Encoding.Default.GetString(mzBytes).TrimEnd();
// 朝内模式
if (ConfigurationManager.AppSettings["CameraLEDMode"] == "0") {
if (ConfigurationManager.AppSettings["Camera1LEDEnable"] == "1") SendMsgToCameraLED(tmp_handle[2], m_PlateNo, "重量:" + mz, "缓慢下磅", "注意安全", "", "r");
if (ConfigurationManager.AppSettings["Camera2LEDEnable"] == "1") SendMsgToCameraLED(tmp_handle[3], m_PlateNo, "重量:" + mz, "缓慢下磅", "注意安全", "", "g");
}
*/
}
if (msg.message == READY_TO_WEIGH)
{
VzClientSDK.VzLPRClient_Setup();
int[] tmp_handle = Login();
//主程序称重完成后,发过来继续进行车牌识别的命令
log.Info("收到双髻鲨汽车衡称重软件命令:准备好称重,继续识别车牌");
InWeighing = false;
m_PlateNo = "";
if (ConfigurationManager.AppSettings["Camera1LEDEnable"] == "1") SendMsgToCameraLED(tmp_handle[2], "车牌识别", "自动称重", DateTime.Now.ToString(), "双髻鲨汽车衡称重", "", "r");
if (ConfigurationManager.AppSettings["Camera2LEDEnable"] == "1") SendMsgToCameraLED(tmp_handle[3], "车牌识别", "自动称重", DateTime.Now.ToString(), "双髻鲨汽车衡称重", "", "g");
if (handle1 != 0 && m_DevNo == "A") VzClientSDK.VzLPRClient_ForceTrigger(handle1);
if (handle2 != 0 && m_DevNo == "B") VzClientSDK.VzLPRClient_ForceTrigger(handle2);
SendMsgToApp("ZXLPR", 0x08F0);
}
if (msg.message == GET_PLATE)
{
VzClientSDK.VzLPRClient_Setup();
int[] tmp_handle = Login();
if (ConfigurationManager.AppSettings["CameraLEDMode"] == "1")
{
if (ConfigurationManager.AppSettings["Camera1LEDEnable"] == "1") SendMsgToCameraLED(tmp_handle[2], m_PlateNo, "等待称重", "缓慢上磅", "注意安全", "", "r");
if (ConfigurationManager.AppSettings["Camera2LEDEnable"] == "1") SendMsgToCameraLED(tmp_handle[3], m_PlateNo, "等待称重", "缓慢上磅", "注意安全", "", "g");
}
else
{
if (ConfigurationManager.AppSettings["Camera1LEDEnable"] == "1") SendMsgToCameraLED(tmp_handle[2], m_PlateNo, "缓慢移动", "居中停稳", "正在称重", "", "r");
if (ConfigurationManager.AppSettings["Camera2LEDEnable"] == "1") SendMsgToCameraLED(tmp_handle[3], m_PlateNo, "缓慢移动", "居中停稳", "正在称重", "", "g");
}
}
if (msg.message == IS_WEIGHING)
{
VzClientSDK.VzLPRClient_Setup();
int[] tmp_handle = Login();
//主程序接收到车牌信息后,发过来不再进行车牌识别的命令
log.Info("收到双髻鲨汽车衡称重软件命令:正在称重,停止识别车牌");
InWeighing = true;
//朝外模式
if (ConfigurationManager.AppSettings["CameraLEDMode"] == "1")
{
if (ConfigurationManager.AppSettings["Camera1LEDEnable"] == "1") SendMsgToCameraLED(tmp_handle[2], m_PlateNo, "正在称重", "保持车距", "秩序上磅", "", "g");
if (ConfigurationManager.AppSettings["Camera2LEDEnable"] == "1") SendMsgToCameraLED(tmp_handle[3], m_PlateNo, "正在称重", "保持车距", "秩序上磅", "", "r");
}
}
if (msg.message >= RELAY_MIN && msg.message <= RELAY_MAX)
{
if (m_RelayPort.IsOpen)
{
var bit = msg.message & 0x0F;
m_DOCmd[7] = ((byte)(bit == 13 ? 1 : bit == 14 ? 2 : bit));
CRCCalc(m_DOCmd.Take(8).ToArray());
m_DOTimer.Start();
}
if (ConfigurationManager.AppSettings["Relay2Enable"] == "1")
{
//
int i = msg.message & 0x0F;
switch (i)
{
case 0:
controlRelay[4] = 0x00;
controlRelay[6] = 0x3C;
controlRelay[7] = Convert.ToByte(checksum(controlRelay.Skip(2).Take(5).ToArray()));
try
{
socket.Send(controlRelay);
}
catch (Exception ex)
{
log.Info("控制器连接失败:" + ex.Message);
}
break;
case 1:
controlRelay[4] = 0x00;
controlRelay[6] = 0x38;
controlRelay[7] = Convert.ToByte(checksum(controlRelay.Skip(2).Take(5).ToArray()));
try
{
socket.Send(controlRelay);
}
catch (Exception ex)
{
log.Info("控制器连接失败:" + ex.Message);
}
controlRelay[4] = 0x01;
controlRelay[6] = 0x04;
controlRelay[7] = Convert.ToByte(checksum(controlRelay.Skip(2).Take(5).ToArray()));
try
{
socket.Send(controlRelay);
}
catch (Exception ex)
{
log.Info("控制器连接失败:" + ex.Message);
}
break;
case 2:
controlRelay[4] = 0x00;
controlRelay[6] = 0x34;
controlRelay[7] = Convert.ToByte(checksum(controlRelay.Skip(2).Take(5).ToArray()));
try
{
socket.Send(controlRelay);
}
catch (Exception ex)
{
log.Info("控制器连接失败:" + ex.Message);
}
controlRelay[4] = 0x01;
controlRelay[6] = 0x08;
controlRelay[7] = Convert.ToByte(checksum(controlRelay.Skip(2).Take(5).ToArray()));
try
{
socket.Send(controlRelay);
}
catch (Exception ex)
{
log.Info("控制器连接失败:" + ex.Message);
}
break;
case 3:
controlRelay[4] = 0x00;
controlRelay[6] = 0x30;
controlRelay[7] = Convert.ToByte(checksum(controlRelay.Skip(2).Take(5).ToArray()));
try
{
socket.Send(controlRelay);
}
catch (Exception ex)
{
log.Info("控制器连接失败:" + ex.Message);
}
controlRelay[4] = 0x01;
controlRelay[6] = 0x0C;
controlRelay[7] = Convert.ToByte(checksum(controlRelay.Skip(2).Take(5).ToArray()));
try
{
socket.Send(controlRelay);
}
catch (Exception ex)
{
log.Info("控制器连接失败:" + ex.Message);
}
break;
case 12:
controlRelay[4] = 0x00;
controlRelay[6] = 0x0C;
controlRelay[7] = Convert.ToByte(checksum(controlRelay.Skip(2).Take(5).ToArray()));
try
{
socket.Send(controlRelay);
}
catch (Exception ex)
{
log.Info("控制器连接失败:" + ex.Message);
}
controlRelay[4] = 0x01;
controlRelay[6] = 0x30;
controlRelay[7] = Convert.ToByte(checksum(controlRelay.Skip(2).Take(5).ToArray()));
try
{
socket.Send(controlRelay);
}
catch (Exception ex)
{
log.Info("控制器连接失败:" + ex.Message);
}
break;
case 13:
controlRelay[4] = 0x00;
controlRelay[6] = 0x08;
controlRelay[7] = Convert.ToByte(checksum(controlRelay.Skip(2).Take(5).ToArray()));
try
{
socket.Send(controlRelay);
}
catch (Exception ex)
{
log.Info("控制器连接失败:" + ex.Message);
}
controlRelay[4] = 0x01;
controlRelay[6] = 0x34;
controlRelay[7] = Convert.ToByte(checksum(controlRelay.Skip(2).Take(5).ToArray()));
try
{
socket.Send(controlRelay);
}
catch (Exception ex)
{
log.Info("控制器连接失败:" + ex.Message);
}
break;
case 14:
controlRelay[4] = 0x00;
controlRelay[6] = 0x04;
controlRelay[7] = Convert.ToByte(checksum(controlRelay.Skip(2).Take(5).ToArray()));
try
{
socket.Send(controlRelay);
}
catch (Exception ex)
{
log.Info("控制器连接失败:" + ex.Message);
}
controlRelay[4] = 0x01;
controlRelay[6] = 0x38;
controlRelay[7] = Convert.ToByte(checksum(controlRelay.Skip(2).Take(5).ToArray()));
try
{
socket.Send(controlRelay);
}
catch (Exception ex)
{
log.Info("控制器连接失败:" + ex.Message);
}
break;
default:
break;
}
}
if (ConfigurationManager.AppSettings["Plate2Enable"] == "1")
{
//
int i = msg.message & 0x0F;
VzClientSDK.VzLPRClient_Setup();
int[] tmp_handle = Login();
switch (i)
{
// 全落
case 0:
log.Info("0x08F0 第一个 开:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[0], 1, 1));
Thread.Sleep(500);
log.Info("0x08F0 第二个 开:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[1], 1, 1));
Thread.Sleep(500);
log.Info("0x08F0 第一个 闭:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[0], 1, 0));
Thread.Sleep(500);
log.Info("0x08F0 第二个 闭:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[1], 1, 0));
break;
// 抬一
case 1:
log.Info("0x08F1 第一个 开:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[0], 0, 1));
Thread.Sleep(500);
log.Info("0x08F1 第一个 闭:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[0], 0, 0));
//VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[0], 0, 0);
break;
// 抬二
case 2:
log.Info("0x08F2 第二个 开:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[1], 0, 1));
//VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[1], 0, 1);
Thread.Sleep(500);
log.Info("0x08F2 第二个 闭:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[1], 0, 0));
break;
// 全抬
case 3:
log.Info("0x08F3 第一个 开:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[0], 0, 1));
Thread.Sleep(500);
log.Info("0x08F3 第二个 开:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[1], 0, 1));
Thread.Sleep(500);
log.Info("0x08F3 第一个 闭:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[0], 0, 0));
Thread.Sleep(500);
log.Info("0x08F3 第二个 闭:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[1], 0, 0));
break;
// 全落
case 12:
log.Info("0x08F0 第一个 开:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[0], 1, 1));
Thread.Sleep(500);
log.Info("0x08F0 第二个 开:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[1], 1, 1));
Thread.Sleep(500);
log.Info("0x08F0 第一个 闭:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[0], 1, 0));
Thread.Sleep(500);
log.Info("0x08F0 第二个 闭:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[1], 1, 0));
break;
// 抬二
case 13:
log.Info("第一个 开:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[0], 0, 1));
Thread.Sleep(500);
log.Info("第一个 闭:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[0], 0, 0));
break;
// 抬一
case 14:
log.Info("第二个 开:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[1], 0, 1));
//VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[1], 0, 1);
Thread.Sleep(500);
log.Info("第二个 闭:" + VzClientSDK.VzLPRClient_SetIOOutput(tmp_handle[1], 0, 0));
break;
case 10:
// 朝外模式
//if(ConfigurationManager.AppSettings["CameraLEDMode"] == "1")
//{
// if (ConfigurationManager.AppSettings["Camera1LEDEnable"] == "1") SendMsgToCameraLED(serial_handle1, m_PlateNo, "等待称重", "缓慢上磅", "注意安全", "", "g");
// if (ConfigurationManager.AppSettings["Camera2LEDEnable"] == "1") SendMsgToCameraLED(serial_handle2, m_PlateNo, "等待称重", "缓慢上磅", "注意安全", "", "r");
//}
// 朝内模式
//else
// {
// if (ConfigurationManager.AppSettings["Camera1LEDEnable"] == "1") SendMsgToCameraLED(serial_handle1, m_PlateNo, "等待称重", "缓慢上磅", "注意安全", "", "g");
// if (ConfigurationManager.AppSettings["Camera2LEDEnable"] == "1") SendMsgToCameraLED(serial_handle2, m_PlateNo, "等待称重", "缓慢上磅", "注意安全", "", "r");
//}
break;
default:
break;
}
}
if (ConfigurationManager.AppSettings["Camera1LEDEnable"] == "1")
{
if (m_PlateNo != "")
{
if (m_DevNo == "A")
{
// 朝外模式
//if(ConfigurationManager.AppSettings["CameraLEDMode"] == "1")
//{
// SendMsgToCameraLED(serial_handle1, m_PlateNo, "等待称重", "缓慢上磅", "注意安全", "", "g");
// if (ConfigurationManager.AppSettings["Camera2LEDEnable"] == "1") SendMsgToCameraLED(serial_handle2, m_PlateNo, "等待称重", "缓慢上磅", "注意安全", "", "r");
// }
// 朝内模式
//else
// {
// SendMsgToCameraLED(serial_handle1, m_PlateNo, "缓慢移动", "居中停稳", "正在称重", "", "g");
// if (ConfigurationManager.AppSettings["Camera2LEDEnable"] == "1") SendMsgToCameraLED(serial_handle2, m_PlateNo, "缓慢移动", "居中停稳", "正在称重", "", "r");
//}
}
}
}
if (ConfigurationManager.AppSettings["Camera2LEDEnable"] == "1")
{
if (m_PlateNo != "")
{
if (m_DevNo == "B")
{
// 朝外模式
//if(ConfigurationManager.AppSettings["CameraLEDMode"] == "1")
//{
// SendMsgToCameraLED(serial_handle2, m_PlateNo, "等待称重", "缓慢上磅", "注意安全", "", "g");
// if (ConfigurationManager.AppSettings["Camera1LEDEnable"] == "1") SendMsgToCameraLED(serial_handle1, m_PlateNo, "等待称重", "缓慢上磅", "注意安全", "", "r");
//}
// 朝内模式
//else
//{
// SendMsgToCameraLED(serial_handle2, m_PlateNo, "缓慢移动", "居中停稳", "正在称重", "", "g");
// if (ConfigurationManager.AppSettings["Camera1LEDEnable"] == "1") SendMsgToCameraLED(serial_handle1, m_PlateNo, "缓慢移动", "居中停稳", "正在称重", "", "r");
//}
}
}
}
}
if (msg.message == GREENON)
{
if (m_RelayPort.IsOpen)
{
//m_DOCmd[7] = (byte)(0x08F0 & 0x0F);
m_DOCmd[7] = (byte)(1);
CRCCalc(m_DOCmd.Take(8).ToArray());
//m_RelayPort.Write(m_DOCmd, 0, m_DOCmd.Length);
m_DOTimer.Start();
}
}
if (msg.message == REDON)
{
if (m_RelayPort.IsOpen)
{
//m_DOCmd[7] = (byte)(0x08FC & 0x0F);
CRCCalc(m_DOCmd.Take(8).ToArray());
m_RelayPort.Write(m_DOCmd, 0, m_DOCmd.Length);
//m_DOTimer.Start();
}
}
}
catch (Exception e)
{
log.Info($"ComponentDispatcher_ThreadPreprocessMessage Error:{ e.Message}");
}
}
//给其他APP发送消息
private void SendMessageToApp(string appName, string msg)
{
Process[] procs = Process.GetProcesses();
foreach (Process p in procs)
{
if (p.ProcessName.Equals(appName))
{
// 获取目标进程句柄
IntPtr hWnd = p.MainWindowHandle;
// 封装消息
byte[] sarr = Encoding.Default.GetBytes(msg);
int len = sarr.Length;
IPCHelper.COPYDATASTRUCT cds;
cds.dwData = (IntPtr)0;
cds.cbData = len + 1;
cds.lpData = msg;
// 发送消息
IPCHelper.SendMessage(hWnd, IPCHelper.WM_COPYDATA, IntPtr.Zero, ref cds);
}
}
}
private void SendMsgToApp(string appName, int msg)
{
Process[] proc = Process.GetProcessesByName(appName);
if (proc.Length > 0)
{
int threadID = Process.GetProcessById(proc[0].Id).Threads[0].Id;
IPCHelper.PostThreadMessage(threadID, msg, IntPtr.Zero, IntPtr.Zero);
}
}
//CRC校验
private void CRCCalc(byte[] data)
{
byte[] crcbuf = data;
//计算并填写CRC校验码
int crc = 0xffff;
int len = crcbuf.Length;
for (int n = 0; n < len; n++)
{
byte i;
crc = crc ^ crcbuf[n];
for (i = 0; i < 8; i++)
{
int TT;
TT = crc & 1;
crc = crc >> 1;
crc = crc & 0x7fff;
if (TT == 1)
{
crc = crc ^ 0xa001;
}
crc = crc & 0xffff;
}
}
m_DOCmd[8] = (byte)(crc & 0xff);
m_DOCmd[9] = (byte)((crc >> 8) & 0xff);
}
private string ByteArrayToHexString(byte[] data)
{
StringBuilder sb = new StringBuilder(data.Length * 3);
foreach (byte b in data)
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
return sb.ToString().ToUpper();
}
/// <summary>
/// 4字节转成整型数(低位前, 高位后)
/// </summary>
/// <param name="buff">字节数组</param>
/// <param name="start">起始索引位(从0开始计)</param>
/// <param name="len">长度</param>
/// <returns>整型数</returns>
private long ByteToLong(byte[] buff, int start, int len)
{
long val = 0;
for (int i = 0; i < len && i < 4; i++)
{
long lng = buff[i + start];
val += (lng << (8 * i));
}
return val;
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/darky22/miaojialing.git
git@gitee.com:darky22/miaojialing.git
darky22
miaojialing
称重软件系统过磅汽车衡车牌识别停车门禁智慧城市共享地磅公磅收费
master

搜索帮助