Form1 Cs
Form1 Cs
Device;
using Rovinj.Reader;
using Rovinj.Reader.Silion;
using Rovinj.Tunnel;
using Rovinj.Tunnel.Plc;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Media;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
using TunnelDemo.Properties;
namespace TunnelDemo
{
public partial class Form1 : Form
{
private ITunnel tunnel;
private bool isAutoMode;//???????
private List<string> epcList = new List<string>();
private string tagsScanId;
private DateTime readerStartedTime = DateTime.Now;
private volatile bool isRecvTags;//??????????
private volatile bool isStartCheckTags;//????????
private bool isCheckTags;//??????
private Thread checkTagsThread;
private string barcode = string.Empty;
private Stopwatch stopwatch;
private DateTime startDate;
bool hasBarcodeRead;
double weight;
SerialPort serialPort;
string portName;
double previousWeight;
string previousBarCode;
public Form1()
{
InitializeComponent();
}
if (!Directory.Exists("log"))
Directory.CreateDirectory("log");
//??
Rovinj.Log.LogHelper.InitLogger(new Rovinj.Log.TextLog($"log\\
{DateTime.Now:yyyy-MM-dd}.log"));
hasBarcodeRead = false;
//Console.WriteLine("Program Starts");
//stopwatch = Stopwatch.StartNew();
////timer2.Start();
weight = 0;
portName = "COM3";
InitializeSerialPort(portName);
// Set the specific duration (e.g., 5 seconds)
//int specificDurationInSeconds = 5;
// Create a timer that checks the elapsed time every 100 milliseconds
//timer = new Timer(CheckElapsedTime, null, 0, 100);
//??
private void btn_Clear_Click(object sender, EventArgs e)
{
lblTagCount.Text = "0";
lblBoxCount.Text = "0";
listView1.Items.Clear();
epcList.Clear();
}
//??
private void button1_Click(object sender, EventArgs e)
{
try
{
if (btn_Connect.Text == "Connect")
{
double power = 30;
SilionReaderConfig readerConfig = new SilionReaderConfig()
{
Qvalue = 5,
Session = 1,
ReadTID = false,
Target = 0,
TagEncoding = 1,
IsFastRead = true,
QuickModeType = 3,
Antennas = new List<SilionAntennaConfig>(),
};
int antCount;
if (!int.TryParse(txtAntCount.Text, out antCount))//4??8???
antCount = 4;
if (radioButton4.Checked)
{
readerConnectionConfig.ConnectionMode =
ConnectionMode.Serial;
readerConnectionConfig.SerialPortName = txtReaderIp.Text;
}
else
{
readerConnectionConfig.ConnectionMode =
ConnectionMode.Network;
readerConnectionConfig.NetworkAddress = txtReaderIp.Text;
}
tunnel = TunnelFactory.CreateTunnel(TunnelType.SC201,
tunnelConfig); // Here it is initializing the tunnel object
if (tunnel == null)
{
MessageBox.Show("Connect failed!");
return;
}
tunnel.TagsReported += Tunnel_TagsReported;
tunnel.ReaderStateChanged += Tunnel_ReaderStateChanged;
tunnel.PlcStateChanged += Tunnel_PlcStateChanged;
tunnel.ErrorReceived += Tunnel_ErrorReceived;
tunnel.SetM(3, true);
if (tunnel.Open())
{
//tunnel.SetM(3, true);
SoundPlayer player = new
SoundPlayer(Resources.InitSuccess);
player.Play();
MessageBox.Show("Connect Success!");
btn_Connect.Text = "Close";
cmbPower.SelectedItem = Convert.ToDouble(30);
//cmbModes.SelectedItem = 0;
}
}
else
{
tunnel.Close();
MessageBox.Show("Connnect failed!");
}
//??
tunnel.Initialize();
}
else
{
CloseTunnel(null, null);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
int antCount;
if (!int.TryParse(txtAntCount.Text, out antCount))//4??8???
antCount = 4;
if (tunnel.SetReader(readerConfig))
{
if (chkReadTID.Checked)
tunnel.TunnelConfig.TagIdFieldName = "TID";
else
tunnel.TunnelConfig.TagIdFieldName = "EPC";
MessageBox.Show("?????????!");
}
else
{
MessageBox.Show("?????????!");
}
}
catch (Exception ex)
{
MessageBox.Show("?????????!" + ex.Message);
}
}
if (e.RunningState == 0)
{
isStartCheckTags = false;
Invoke(new Action(() =>
{
lblReaderState.BackColor = Color.Red;
btn_StartReader.Text = "Start Read";
timer1.Enabled = false;
lblTimeCost.Text = (e.CreateTime -
readerStartedTime).ToString(@"mm\:ss\.fff");
//txtBarcode.Focus();
}));
}
else if (e.RunningState == 1)
{
tagsScanId = e.ScanId;
readerStartedTime = DateTime.Now;//???????
epcList.Clear();
if (isAutoMode)//?????
isStartCheckTags = true;
//????
lblTagCount.Text = "0";
lblBoxCount.Text = "0";
listView1.Items.Clear();
//????
lblTimeCost.Text = "00:00.000";
timer1.Enabled = true;
//txtBarcode.Focus();
}));
}
else
{
Invoke(new Action(() => { lblReaderState.BackColor =
Color.DarkGray;
//txtBarcode.Focus();
}));
}
//}
isAutoMode = e.PlcStatus.AutoMode;
Invoke(new Action(() =>
{
lblAutoMode.BackColor = e.PlcStatus.AutoMode ? Color.Green :
Color.Red;
lblShield.BackColor = e.PlcStatus.Shield ? Color.Green : Color.Red;
lblOpenState.BackColor = e.PlcStatus.OpenDoor ? Color.Green :
Color.Red;
lblG1.BackColor = e.PlcStatus.G1 ? Color.Green : Color.Red;
lblG2.BackColor = e.PlcStatus.G2 ? Color.Green : Color.Red;
lblG3.BackColor = e.PlcStatus.G3 ? Color.Green : Color.Red;
lblG4.BackColor = e.PlcStatus.G4 ? Color.Green : Color.Red;
lblG5.BackColor = e.PlcStatus.G5 ? Color.Green : Color.Red;
lblG6.BackColor = e.PlcStatus.G6 ? Color.Green : Color.Red;
lblG7.BackColor = e.PlcStatus.G7 ? Color.Green : Color.Red;
lblG8.BackColor = e.PlcStatus.G8 ? Color.Green : Color.Red;
// Second Step when weight is in the tunnel and curtains are closed
if (e.PlcStatus.FrontDoorDown && e.PlcStatus.RearDoorDown)
{
//txtBarcode.Clear();
//previousBarCode = barcode;
//previousWeight = weight;
lblDoorClose.BackColor = Color.Green;
//hasBarcodeRead = false;
weight = 0;
barcode = string.Empty;
}
else
lblDoorClose.BackColor = Color.Red;
// This is third step when box is scanned and curtains are open and
box is released
//if (!e.PlcStatus.FrontDoorUp && !e.PlcStatus.RearDoorUp
// && !e.PlcStatus.FrontDoorDown && !e.PlcStatus.RearDoorDown)
//{
//}
//???????
private void Tunnel_ErrorReceived(ITunnel tunnel,
TunnelErrorReceivedEventArgs e)
{
Console.WriteLine($"????:{e.ErrorMessage},??:{e.Exception}");
}
//??????
private void Tunnel_TagsReported(ITunnel tunnel,
TunnelTagsReportedEventArgs e)
{
isRecvTags = true;
for (int i = 0; i < e.Tags.Count; i++)
{
Tag tag = e.Tags[i];
if (tag.ScanId != tagsScanId)
continue;
epcList.Add(tag.TID);
}
else
{
if (epcList.Contains(tag.EPC))
continue;
epcList.Add(tag.EPC);
}
//??
if (int.TryParse(txtBoxTagCount.Text, out int boxTagCount) &&
boxTagCount > 0)
lblBoxCount.Text = Math.Ceiling((double)epcList.Count /
boxTagCount).ToString();
//??????????????,???????????,?????????????????
private void CheckTagsThread()
{
while (isCheckTags)
{
if (!isStartCheckTags)
{
Thread.Sleep(10);
continue;
}
if (isRecvTags)
{
Thread.Sleep(10);
continue;
}
Thread.Sleep(10);
}
}
if (btn_Start.Text == "Stop")
{
tunnel.Stop();
btn_Start.Text = "Run";
isCheckTags = false;
if (checkTagsThread != null)
checkTagsThread.Join();
}
//??????
checkBox2.Checked = false;
tunnel.Close();
tunnel = null;
btn_Connect.Text = "Connect";
}
/// <summary>
/// ??
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_Start_Click(object sender, EventArgs e)
{
// focus of barcode
//txtBarcode.Focus();
if (tunnel == null)
return;
if (btn_Start.Text == "Run")
{
if (tunnel.Start())
{
btn_Start.Text = "Stop";
lblAutoMode.BackColor = Color.Red;
lblShield.BackColor = Color.Red;
lblOpenState.BackColor = Color.Red;
lblG1.BackColor = Color.Red;
lblG2.BackColor = Color.Red;
lblG3.BackColor = Color.Red;
lblG4.BackColor = Color.Red;
lblG5.BackColor = Color.Red;
lblG6.BackColor = Color.Red;
lblG7.BackColor = Color.Red;
lblG8.BackColor = Color.Red;
lblDoorOpen.BackColor = Color.Red;
lblDoorClose.BackColor = Color.Red;
isCheckTags = true;
checkTagsThread = new Thread(CheckTagsThread);
checkTagsThread.IsBackground = true;
checkTagsThread.Start();
}
}
else
{
tunnel.Stop();
btn_Start.Text = "Run";
isCheckTags = false;
if (checkTagsThread != null)
checkTagsThread.Join();
}
}
/// <summary>
/// ????
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_ReadTagSuccess_Click(object sender, EventArgs e)
{
if (tunnel == null)
return;
isStartCheckTags = false;
if (!tunnel.ReadTagsSuccess())
MessageBox.Show($"?{btn_ReadTagSuccess.Text}???????!");
}
/// <summary>
/// ????
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_ReadTagFailed_Click(object sender, EventArgs e)
{
if (tunnel == null)
return;
isStartCheckTags = false;
if (!tunnel.ReadTagsFailed())
MessageBox.Show($"?{btn_ReadTagFailed.Text}???????!");
}
if (!tunnel.OpenDoor())
MessageBox.Show($"?{btn_OpenDoor.Text}???????!");
}
if (!tunnel.CloseDoor())
MessageBox.Show($"?{btn_CloseDoor.Text}???????!");
}
//listView1.Clear();
//txtBarcode.Focus();
//string val = txtBarcode.Text;
if (!tunnel.ScanBarcodeSuccess())
MessageBox.Show($"?{btn_ScanSuccess.Text}???????!");
}
if (!tunnel.ScanBarcodeFailed())
MessageBox.Show($"?{btn_ScanFailed.Text}???????!");
}
if (!tunnel.WeighingCompleted())
MessageBox.Show($"?{btn_Weighed.Text}???????!");
}
/// <summary>
/// ?????????,????????????,????
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
tunnel.DemonstrationMode(checkBox2.Checked);
}
try
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = DateTime.Now.ToString("yyyyMMHHddmmss") +
".csv";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
FileStream fs = new FileStream(saveFileDialog.FileName,
FileMode.Create, FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
sw.Close();
fs.Close();
MessageBox.Show("????!");
}
}
catch (Exception ex)
{
MessageBox.Show("????!" + ex.Message);
}
}
weight = 0;
for (int i = 0; i < 6; i++)
{
int data = serialPort.BytesToRead;
byte[] buf = new byte[8];
int nread = serialPort.Read(buf, 0, 8);
string strRecv = Encoding.ASCII.GetString(buf);
string strWeight = new string(strRecv.Substring(1,
strRecv.Length - 1).Reverse().ToArray());
weight += Convert.ToDouble(strWeight);
}
weight = Math.Round((double)weight / 6, 2);
lblWeight.Text = weight.ToString();
}
}
// You may need to adjust the serial port settings based on your weight
machine specifications
// Other serial port settings (if needed)
serialPort.Handshake = Handshake.None;
serialPort.RtsEnable = true;
serialPort.DtrEnable = true;
//serialPort.ReadTimeout = 500; // Set an appropriate read timeout
//serialPort.WriteTimeout = 500; // Set an appropriate write timeout
}
//}