Browse Source

串口bug修复

Lishi
747575620@qq.com 2 years ago
parent
commit
aed36ea18e
5 changed files with 138 additions and 76 deletions
  1. +18
    -18
      HKCardOUT/Logic/Service/HKCore.cs
  2. +34
    -18
      HKCardOUT/ViewModels/RootViewModel.cs
  3. +2
    -2
      HKCardOUT/Views/RootView.xaml
  4. +80
    -34
      UHFHelper/UHF_RS485_Helper.cs
  5. +4
    -4
      test/Form1.cs

+ 18
- 18
HKCardOUT/Logic/Service/HKCore.cs View File

@@ -26,27 +26,27 @@ namespace HKCardOUT.Logic.Service
if (!DataBus.IsTest)
if (!Main.GetInstance.GetIsSwipe(input.Location.AsInt())) return false;
var Old = DbContext.Context.Queryable<SaleLog>().Where(t => t.CardNo == input.CardNo).Where(t => t.CreateTime.Day == DateTime.Now.Day).ToList();
if (Old.Count > 3) return false;
//if (Old.Count > 3) return false;

var AM = DataBus.AM.Split(",").Select(t => t.AsInt()).ToList();
var PM = DataBus.PM.Split(",").Select(t => t.AsInt()).ToList();
var AT = DataBus.AT.Split(",").Select(t => t.AsInt()).ToList();
//var AM = DataBus.AM.Split(",").Select(t => t.AsInt()).ToList();
//var PM = DataBus.PM.Split(",").Select(t => t.AsInt()).ToList();
//var AT = DataBus.AT.Split(",").Select(t => t.AsInt()).ToList();

var condition1 = (DateTime.Now.Hour >= AM[0] && DateTime.Now.Hour < AM[1]);
var condition2 = (DateTime.Now.Hour >= PM[0] && DateTime.Now.Hour < PM[1]);
var condition3 = (DateTime.Now.Hour >= AT[0] && DateTime.Now.Hour < AT[1]);
HKLog.HKLogImport.WriteInfo($"当前刷卡时间_条件1:{condition1}_条件2:{condition2}_条件3:{condition3}");
if (condition1 || condition2 || condition3)
//var condition1 = (DateTime.Now.Hour >= AM[0] && DateTime.Now.Hour < AM[1]);
//var condition2 = (DateTime.Now.Hour >= PM[0] && DateTime.Now.Hour < PM[1]);
//var condition3 = (DateTime.Now.Hour >= AT[0] && DateTime.Now.Hour < AT[1]);
//HKLog.HKLogImport.WriteInfo($"当前刷卡时间_条件1:{condition1}_条件2:{condition2}_条件3:{condition3}");
if (true)
{
var AMDay = Old.Where(t => t.CreateTime.Hour >= AM[0] && t.CreateTime.Hour < AM[1]).Count();
HKLog.HKLogImport.WriteInfo($"卡号{input.CardNo}上午消费次数:{AMDay}");
if (AMDay > 0) return false;
var PMDay = Old.Where(t => t.CreateTime.Hour >= PM[0] && t.CreateTime.Hour < PM[1]).Count();
HKLog.HKLogImport.WriteInfo($"卡号{input.CardNo}中午消费次数:{AMDay}");
if (PMDay > 0) return false;
var ATDay = Old.Where(t => t.CreateTime.Hour >= AT[0] && t.CreateTime.Hour < AT[1]).Count();
HKLog.HKLogImport.WriteInfo($"卡号{input.CardNo}下午消费次数:{AMDay}");
if (ATDay > 0) return false;
//var AMDay = Old.Where(t => t.CreateTime.Hour >= AM[0] && t.CreateTime.Hour < AM[1]).Count();
//HKLog.HKLogImport.WriteInfo($"卡号{input.CardNo}上午消费次数:{AMDay}");
//if (AMDay > 0) return false;
//var PMDay = Old.Where(t => t.CreateTime.Hour >= PM[0] && t.CreateTime.Hour < PM[1]).Count();
//HKLog.HKLogImport.WriteInfo($"卡号{input.CardNo}中午消费次数:{AMDay}");
//if (PMDay > 0) return false;
//var ATDay = Old.Where(t => t.CreateTime.Hour >= AT[0] && t.CreateTime.Hour < AT[1]).Count();
//HKLog.HKLogImport.WriteInfo($"卡号{input.CardNo}下午消费次数:{AMDay}");
//if (ATDay > 0) return false;


var entity = DbContext.Context.Insertable(input).CallEntityMethod(t => t.Create()).ExecuteReturnEntity();


+ 34
- 18
HKCardOUT/ViewModels/RootViewModel.cs View File

@@ -12,6 +12,7 @@ using StyletIoC;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
@@ -32,6 +33,8 @@ namespace HKCardOUT.ViewModels
public event ReadCardFunc ReadFunc;
private readonly object locker = new object();
private IContainer Container;
private Thread thread1;
readonly System.Timers.Timer timer1 = new();
public RootViewModel(IContainer Container)
{
this.Container = Container;
@@ -49,13 +52,15 @@ namespace HKCardOUT.ViewModels
/// <param name="e"></param>
private void RootViewModel_Closed(object sender, CloseEventArgs e)
{
ti.Stop();
ti.Dispose();
if (timer1!=null)
{
timer1.Stop();
timer1.Dispose();
}
UHF_RS485_Helper.GetInstance().Close();
}

System.Timers.Timer ti = new();

private void RootViewModel_Activated(object sender, ActivationEventArgs e)
{
ReadFunc -= ReadCard;
@@ -72,35 +77,46 @@ namespace HKCardOUT.ViewModels
HandyControl.Controls.Growl.InfoGlobal("串口打开失败");

}
//开启循环监听数据
ti.Interval = 500;
ti.Elapsed += Ti_Elapsed;
ti.Start();
thread1 = new(new ThreadStart(GetData))
{
IsBackground = true
};
thread1.Start();
}
private void Ti_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
/// <summary>
/// 读取信息
/// </summary>
public void GetData()
{
DataBus.StoreInfo.Devices.ForEach(item =>
//开启循环监听数据
timer1.Interval = 500;
timer1.Elapsed += (o, a) =>
{
if (!UHF_RS485_Helper.GetInstance().GetSerialPortState())
{
HandyControl.Controls.Growl.InfoGlobal("串口打开失败");
ti.Stop();
timer1.Stop();
return;
}
else
{
var res = UHF_RS485_Helper.GetInstance().ReadCard(item.Address.AsInt()).Result;
if (res != null)
DataBus.StoreInfo.Devices.ForEach(item =>
{
//var stopwatch = Stopwatch.StartNew();
//stopwatch.Restart();
var res = UHF_RS485_Helper.GetInstance().ReadCard(item.Address.AsInt());

if (res != null)
{
if (!res.ResData.IsMatch(new Regex("0{20}")))
ReadFunc?.Invoke(res);
ReadFunc?.Invoke(res);
}
//Debug.WriteLine("打印时间:"+ item.Address.AsInt() + "_"+stopwatch.ElapsedMilliseconds);
});
}
});
};
timer1.Start();
}

protected override void OnViewLoaded()
{
//广告初始化


+ 2
- 2
HKCardOUT/Views/RootView.xaml View File

@@ -67,12 +67,12 @@
ElementStyle="{StaticResource CenterAlignmentStyle}"
Header="卡号"
HeaderStyle="{StaticResource SaleLogHeader}" />
<DataGridTextColumn
<!--<DataGridTextColumn
Width="200"
Binding="{Binding Money}"
ElementStyle="{StaticResource CenterAlignmentStyle}"
Header="金额"
HeaderStyle="{StaticResource SaleLogHeader}" />
HeaderStyle="{StaticResource SaleLogHeader}" />-->
<DataGridTextColumn
Width="200"
Binding="{Binding Location}"


+ 80
- 34
UHFHelper/UHF_RS485_Helper.cs View File

@@ -56,16 +56,21 @@ namespace UHFHelper
_serialPort.Dispose();
_serialPort = null;
}



/// <summary>
/// 读卡方法,返回读卡器数据
/// </summary>
/// <param name="adr">设备读取地址</param>
/// <returns></returns>
public async Task<DKoutput?> ReadCard(int adr)
public DKoutput? ReadCard(int adr)
{
if (_serialPort == null) return null;
DKoutput dKoutput = new();
var readByte = ReadByte(adr);
var result = await SendMessageAsync(readByte, TimeSpan.FromSeconds(2), 18);
_serialPort.Write(readByte, 0, readByte.Length);
var result = SendMessage(readByte, 2000, 18);
if (result == null)
{
return null;
@@ -124,12 +129,10 @@ namespace UHFHelper
/// <param name="timeout">超时时间</param>
/// <param name="count">串口回复字节数</param>
/// <returns></returns>
public byte[]? SendMessage(byte[] msg, TimeSpan timeout, int count)
public byte[]? SendMessage(byte[] msg, long timeout, int count)
{
if (_serialPort == null) return null;
var stopwatch = Stopwatch.StartNew();
var originalWriteTimeout = _serialPort.WriteTimeout;
var originalReadTimeout = _serialPort.ReadTimeout;
try
{
_serialPort.DiscardInBuffer();
@@ -139,18 +142,20 @@ namespace UHFHelper
int offset = 0;
while (tmpCount > 0)
{
var readCount = _serialPort.Read(buffer, offset, tmpCount);
if (readCount==6)
if (stopwatch.ElapsedMilliseconds >= timeout)
{
tmpCount = 0;
continue;
return null;
}
offset += readCount;
tmpCount -= readCount;
if (stopwatch.ElapsedMilliseconds>=2000)
int res = _serialPort.BytesToRead;
if (res > 0)
{
return null;
var readCount = _serialPort.Read(buffer, offset, tmpCount);
if (buffer.Skip(0).Take(1).ToArray().ByteArrayToHexString() == "05")
{
return null;
}
offset += readCount;
tmpCount -= readCount;
}
}
return buffer;
@@ -158,46 +163,87 @@ namespace UHFHelper
{
return null;
}
finally
{
_serialPort.ReadTimeout = originalReadTimeout;
_serialPort.WriteTimeout = originalWriteTimeout;
}
}

private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
/// <summary>
/// 发送数据
/// </summary>
public void SendMessage(int adr)
{
throw new NotImplementedException();
var readByte = ReadByte(adr);
if (_serialPort == null) return;
_serialPort.Write(readByte, 0, readByte.Length);
}

/// <summary>
/// 发送数据
/// 读取数据
/// </summary>
/// <param name="msg">数据</param>
/// <param name="timeout">超时时间</param>
/// <param name="count">串口回复字节数</param>
/// <returns></returns>
public async Task<byte[]?> SendMessageAsync(byte[] msg, TimeSpan timeout, int count)
public byte[]? GetMessage(int count,long timeout)
{
var sendTask = Task.Run(() => SendMessage(msg, timeout, count));
if (_serialPort == null) return null;
var stopwatch = Stopwatch.StartNew();
try
{
await Task.WhenAny(sendTask, Task.Delay(timeout));
_serialPort.DiscardInBuffer();
var tmpCount = count;
byte[] buffer = new byte[tmpCount];
int offset = 0;
while (tmpCount > 0)
{

var readCount = _serialPort.Read(buffer, offset, tmpCount);
if (readCount == 6)
{
tmpCount = 0;
continue;
}
offset += readCount;
tmpCount -= readCount;
if (stopwatch.ElapsedMilliseconds >= timeout)
{
return null;
}
}
return buffer;
}
catch (TaskCanceledException)
catch (Exception ex)
{
return null;
}
return await sendTask;
}

private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
throw new NotImplementedException();
}

///// <summary>
///// 发送数据
///// </summary>
///// <param name="msg">数据</param>
///// <param name="timeout">超时时间</param>
///// <param name="count">串口回复字节数</param>
///// <returns></returns>
//public async Task<byte[]?> SendMessageAsync(byte[] msg, TimeSpan timeout, int count)
//{
// var sendTask = Task.Run(() => SendMessage(msg, timeout, count));
// //try
// //{
// // await Task.WhenAny(sendTask, Task.Delay(timeout));
// //}
// //catch (TaskCanceledException)
// //{
// // return null;
// //}
// return await sendTask;
//}

/// <summary>
/// 发出蜂鸣声音3次,代表扣款成功!
/// </summary>
public async void OpenBeep(int addr)
public void OpenBeep(int addr)
{
byte[] sendData = new byte[]{ 0x07, (byte)addr, 0x33, 0x08, 0x02, 0x03, 0x33,0xB1 };
await SendMessageAsync(sendData, TimeSpan.FromSeconds(1), 6);
}
}



+ 4
- 4
test/Form1.cs View File

@@ -66,7 +66,7 @@ namespace test
// ³õʼ»¯
UHF_RS485_Helper.GetInstance().Open(new SerialParam
{
PortName = "COM5",
PortName = "COM8",
BaudRate = 57600,
DataBits = 8
});
@@ -76,11 +76,11 @@ namespace test
}
}

private async void button6_Click(object sender, EventArgs e)
private void button6_Click(object sender, EventArgs e)
{
if (UHF_RS485_Helper.GetInstance().GetSerialPortState())
{
var oldss = await UHF_RS485_Helper.GetInstance().ReadCard(01);
var oldss = UHF_RS485_Helper.GetInstance().ReadCard(01);
var sss = oldss?.ResData;
textBox4.Text = sss;
label2.Text = sss;
@@ -104,7 +104,7 @@ namespace test
{
foreach (var item in add)
{
var oldss = UHF_RS485_Helper.GetInstance().ReadCard(item).Result;
var oldss = UHF_RS485_Helper.GetInstance().ReadCard(item);
if (oldss != null)
{
//lvi.SubItems.Add(oldss.ResData ?? "ÎÞ");


Loading…
Cancel
Save