//////////////////////////////////////
///////////////This project is example of work with Impinj R420 reader
///////////////The example provided as is, without any kind of warranty of any kind
///////////////Author: Dmitry Konnov: konnov72@gmail.com
//////////////////////////////////////
using System;
using System.IO;
using System.IO.Ports;
using System.Collections.Generic;
using System.Timers;
using System.Threading;
using Impinj.OctaneSdk;
using System.Net;
using System.Net.Sockets;
/*
"Antenna1 Tick: --", 1, 8
"Antenna2 Tick: --", 1, 9
"Antenna1 : --", 1, 10
"Antenna2 : --", 1, 11
"COM PORT : --", 1, 12
"MULTI-TAGS : ", 1, 13
"COM Tick : "1, 14
"MES BAGS : "1, 15
"INNOVA BAGS: ",1, 16
*/
namespace ConsoleRfidReaderApp
{
public class PortChat
{
private static object LockingVar = new object();
private static object LockingCOMPortVar = new object();
private static System.Timers.Timer GlocalTimer;
static bool _continue = true;
static SerialPort _serialPort;
// Create an instance of the ImpinjReader class.
static ImpinjReader reader = new ImpinjReader();
static string G_lastTag = "";
static int GLastTagSeen = 0;
static DateTime G_LastLocalTime;//Last time when last production tag seen
static DateTime G_Antenna1LastLocalTime;
static DateTime G_Antenna2LastLocalTime;
static DateTime G_LastCOMPortTime = DateTime.Now;
static FileStream fs_operations;
static StreamWriter sw_operations;
static FileStream fs_errors;
static StreamWriter sw_errors;
static FileStream fs_mulitags;
static StreamWriter sw_mulitags;
static FileStream fs_PrintedTags;
static StreamWriter sw_PrintedTags;
static string GLastComPortMessage = "";
static bool G_MultitagAlarm = false;
static bool G_MultitagBlink = false;
static bool G_ComPortBlink = false;
static bool G_NoMajicTagAlarm1 = false;
static bool G_NoMajicTagAlarm2 = false;
static DateTime G_LastMajicTickTime1; //Last time when majic tag is seen
static DateTime G_LastMajicTickTime2; //Last time when majic tag is seen
static bool G_IgnoretagBlink = false;
static string G_MesBagCount = "0";
static string G_InnovaBagCount = "0";
static string G_NoTagCount = "-";
const string GControlTag = "E00000000000000000000000";//Ignoring this tag. but need for Reader agility
static List<string> G_MulitagList = new List<string>();
static List<string> G_PrintedTagList = new List<string>();
static List<string> G_IgnoreList;
static int G_LastTagAntennaPortNumber = 0;
static double G_LastTagRSSI = 0;
static string G_HeartBtCount = "0";
static int G_getstatCounter = 0;
static bool G_AutostopOnMultiTag = false;
static bool G_CageIsBusy = false;
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
public static void Main()
{
try
{
Thread readThread = new Thread(Read);
try
{
string app_location = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
if (!Directory.Exists(app_location + "\\logs"))
Directory.CreateDirectory(app_location + "\\logs");
fs_operations = new FileStream(app_location + "\\logs\\operations.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
sw_operations = new StreamWriter(fs_operations);
fs_operations.Seek(0, SeekOrigin.End);
fs_errors = new FileStream(app_location + "\\logs\\errors.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
sw_errors = new StreamWriter(fs_errors);
fs_errors.Seek(0, SeekOrigin.End);
fs_mulitags = new FileStream(app_location + "\\logs\\mulitags.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
fs_mulitags.Seek(0, SeekOrigin.End);
sw_mulitags = new StreamWriter(fs_mulitags);
fs_PrintedTags = new FileStream(app_location + "\\logs\\printedtags.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
fs_PrintedTags.Seek(0, SeekOrigin.End);
sw_PrintedTags = new StreamWriter(fs_PrintedTags);
sw_PrintedTags.WriteLine("start");
sw_PrintedTags.Flush();
if (!File.Exists(app_location + "\\ignoretags.txt"))
File.Create(app_location + "\\ignoretags.txt").Close();
var MyIni = new IniFile();
if (!MyIni.KeyExists("LastGoodTag"))
{
MyIni.Write("LastGoodTag", "");
MyIni.Write("Antenna1Tx", "25");
MyIni.Write("Antenna1Rx", "-50");
MyIni.Write("Antenna2Tx", "25");
MyIni.Write("Antenna2Rx", "-50");
MyIni.Write("AutostopOnMultiTag", "0");
}
int Ant1Tx = 0;
int Ant1Rx = 0;
int Ant2Tx = 0;
int Ant2Rx = 0;
int.TryParse(MyIni.Read("Antenna1Tx"), out Ant1Tx);
int.TryParse(MyIni.Read("Antenna1Rx"), out Ant1Rx);
int.TryParse(MyIni.Read("Antenna2Tx"), out Ant2Tx);
int.TryParse(MyIni.Read("Antenna2Rx"), out Ant2Rx);
int AutostopOnMultiTag = 0;
int.TryParse(MyIni.Read("AutostopOnMultiTag"), out AutostopOnMultiTag);
G_AutostopOnMultiTag = AutostopOnMultiTag == 0;
var a_listfile = File.ReadLines(app_location + "\\ignoretags.txt");
G_IgnoreList = new List<string>(a_listfile);
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
// Create a new SerialPort object with default settings.
_serialPort = new SerialPort();
// Allow the user to set the appropriate properties.
_serialPort.PortName = SetPortName("COM4");
_serialPort.BaudRate = 9600;
_serialPort.Parity = Parity.None;
_serialPort.DataBits = 8;
_serialPort.StopBits = StopBits.One;
_serialPort.Handshake = Handshake.None;
// Set the read/write timeouts
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
try
{
_serialPort.Open();
readThread.Start();
// Connect to the reader.
// Pass in a reader hostname or IP address as a
// command line argument when running the example
string hostname = "192.168.1.201";
reader.Connect(hostname);
// Get the default settings
// We'll use these as a starting point
// and then modify the settings we're
// interested in.
Settings settings = reader.QueryDefaultSettings();
// Tell the reader to include the antenna number
// in all tag reports. Other fields can be added
// to the reports in the same way by setting the
// appropriate Report.IncludeXXXXXXX property.
settings.Report.IncludeAntennaPortNumber = true;
settings.Report.IncludeLastSeenTime = true;
settings.Report.IncludeSeenCount = true;
// The reader can be set into various modes in which reader
// dynamics are optimized for specific regions and environments.
// The following mode, AutoSetDenseReader, monitors RF noise and interference and then automatically
// and continuously optimizes the reader’s configuration
settings.ReaderMode = ReaderMode.DenseReaderM4;// ReaderMode.AutoSetDenseReader; DenseReaderM4
settings.SearchMode = SearchMode.DualTarget;
settings.Session = 2;
// Enable antenna #1. Disable all others.
settings.Antennas.DisableAll();
settings.Antennas.GetAntenna(1).IsEnabled = true;
settings.Antennas.GetAntenna(2).IsEnabled = true;
// Set the Transmit Power and
// Receive Sensitivity to the maximum.
//settings.Antennas.GetAntenna(1).MaxTxPower = true;
//settings.Antennas.GetAntenna(1).MaxRxSensitivity = true;
// You can also set them to specific values like this...
settings.Antennas.GetAntenna(1).TxPowerInDbm = Ant1Tx;// 25;//32
settings.Antennas.GetAntenna(1).RxSensitivityInDbm = Ant1Rx;// - 65; //-70
settings.Antennas.GetAntenna(2).TxPowerInDbm = Ant2Tx;// 25;//32
settings.Antennas.GetAntenna(2).RxSensitivityInDbm = Ant2Rx;// - 65; //-70
settings.Report.IncludeSeenCount = true;
settings.Report.IncludePeakRssi = true;
// Apply the newly modified settings.
reader.ApplySettings(settings);
// Assign the TagsReported event handler.
// This specifies which method to call
// when tags reports are available.
reader.TagsReported += OnTagsReported;
// Start reading.
reader.Start();
G_LastLocalTime = DateTime.Now;
sw_operations.AutoFlush = true;
sw_mulitags.AutoFlush = true;
sw_errors.AutoFlush = true;
sw_operations.WriteLine("Start reading at : {0}", G_LastLocalTime.ToLongTimeString());
sw_operations.Flush();
GlocalTimer = new System.Timers.Timer(1000);
GlocalTimer.Elapsed += OnTimerEvent;
GlocalTimer.AutoReset = true;
GlocalTimer.Enabled = true;
Console.Clear();
WriteScreen("RFID example @", 1, 1, false);
WriteScreen(string.Format("Antenna1 TxPower: {0}", settings.Antennas.GetAntenna(1).TxPowerInDbm), 1, 3, false);
WriteScreen(string.Format("Antenna1 RxSensitivity: {0}", settings.Antennas.GetAntenna(1).RxSensitivityInDbm), 1, 4, false);
WriteScreen(string.Format("Antenna2 TxPower: {0}", settings.Antennas.GetAntenna(2).TxPowerInDbm), 1, 5, false);
WriteScreen(string.Format("Antenna2 RxSensitivity: {0}", settings.Antennas.GetAntenna(2).RxSensitivityInDbm), 1, 6, false);
WriteScreen("Antenna1 : --", 1, 10, false);
WriteScreen("Antenna2 : --", 1, 11, false);
WriteScreen("COM PORT : --", 1, 12, false);
WriteScreen("MULTI-TAGS : ", 1, 13, false);
WriteScreen("COM Tick : ", 1, 14, false);
WriteScreen("MES BAGS : ", 1, 15, false, true, ConsoleColor.Gray);
WriteScreen("INNOVA BAGS: ", 1, 16, false, true, ConsoleColor.Gray);
WriteScreen("NO TAG : ", 1, 17, false, true, ConsoleColor.Gray);
WriteScreen("HEART BEAT : ", 1, 18, false, true, ConsoleColor.Gray);
_serialPort.WriteLine(MyIni.Read("LastGoodTag"));
_serialPort.WriteLine("Test");//if Com port works the message will return back
}
catch (OctaneSdkException ex)
{
sw_errors.WriteLine(string.Format("Main: {0}", ex.Message));
sw_errors.Flush();
// Handle Octane SDK errors.
Console.WriteLine("Octane SDK exception: {0}", ex.Message);
}
catch (Exception ex)
{
sw_errors.WriteLine(string.Format("Main: {0}", ex.Message));
sw_errors.Flush();
Console.WriteLine("Exception : {0}", ex.Message);
}
while (true)
{
System.Threading.Thread.Sleep(100);
}
// Stop reading.
reader.Stop();
// Disconnect from the reader.
reader.Disconnect();
}
finally
{
sw_operations.Flush();
sw_errors.Flush();
sw_mulitags.Flush();
sw_PrintedTags.Flush();
readThread.Join();
_serialPort.Close();
}
}
catch (Exception ex)
{
sw_errors.WriteLine(string.Format("Main: {0}", ex.Message));
sw_errors.Flush();
// Handle other .NET errors.
Console.WriteLine("Exception : {0}", ex.Message);
}
}
private static void OnTimerEvent(Object source, ElapsedEventArgs e)
{
try
{
/* if (G_getstatCounter == 10)
WriteCOMPort("MESCount");
if (G_getstatCounter == 20)
WriteCOMPort("InnovaCount");
if (G_getstatCounter == 40)
WriteCOMPort("NoTagCount");
if (G_getstatCounter == 60)
{
WriteCOMPort("HeartBtCount");
G_getstatCounter = 0;
}
G_getstatCounter++;
*/
if (G_MultitagAlarm)
G_MultitagBlink = !G_MultitagBlink;
WriteScreen(string.Format("MULTI-TAGS : {0}", G_MulitagList.Count), 1, 13, false, G_MultitagBlink, ConsoleColor.Red);
if (DateTime.Now.Subtract(G_LastLocalTime).TotalMilliseconds < 3000)
{
DisplayAntennaInfo(G_LastTagAntennaPortNumber, G_lastTag, G_LastTagRSSI);
}
else
{
DisplayAntennaInfo(1, "");
DisplayAntennaInfo(2, "");
}
if (DateTime.Now.Subtract(G_LastMajicTickTime1).TotalMilliseconds > 999)
{
G_NoMajicTagAlarm1 = true;
DisplayAntennaTick(1, ConsoleColor.Red);
}
if (DateTime.Now.Subtract(G_LastMajicTickTime2).TotalMilliseconds > 999)
{
G_NoMajicTagAlarm2 = true;
DisplayAntennaTick(2, ConsoleColor.Red);
}
WriteScreen(string.Format("TAG SEEN : {0} ", GLastTagSeen), 1, 9, false);
WriteScreen(string.Format("MES BAGS : {0} ", G_MesBagCount), 1, 15, false, true, ConsoleColor.Gray);
WriteScreen(string.Format("INNOVA BAGS: {0} ", G_InnovaBagCount), 1, 16, false, true, ConsoleColor.Gray);
WriteScreen(string.Format("NO TAG : {0} ", G_NoTagCount), 1, 17, false, true, ConsoleColor.Gray);
WriteScreen(string.Format("HEART BEAT : {0} ", G_HeartBtCount), 1, 18, false, true, ConsoleColor.Gray);
ConsoleColor a_colr = ConsoleColor.White;
string a_rdstate = "ON";
if (G_CageIsBusy)
{
a_colr = ConsoleColor.Red;
a_rdstate = "OFF";
}
WriteScreen(string.Format("SCANNING : {0} ", a_rdstate), 1, 19, false, true, a_colr);
GLastTagSeen = 0;
G_IgnoretagBlink = !G_IgnoretagBlink;
G_ComPortBlink = !G_ComPortBlink;
ConsoleColor a_comcolor = ConsoleColor.Green;
if (DateTime.Now.Subtract(G_LastCOMPortTime).TotalMilliseconds > 29000)
WriteCOMPort("Test");
else if (DateTime.Now.Subtract(G_LastCOMPortTime).TotalMilliseconds > 30000) //alarm
{
sw_operations.WriteLineAsync(string.Format("{0} COM PORT not responding. Alarm!!! printing tags not possible", DateTime.Now.ToLongTimeString()));
a_comcolor = ConsoleColor.Red;
}
WriteScreen(string.Format("COM Tick : {0} ", G_LastCOMPortTime), 1, 14, false, G_ComPortBlink, a_comcolor);
//dont give G_PrintedTagList grow in memory.
if (G_PrintedTagList.Count > 3)
G_PrintedTagList.RemoveAt(0);
}
catch(System.Exception ex)
{
sw_errors.WriteLine(string.Format("OnTimerEvent: {0}", ex.Message));
sw_errors.Flush();
}
}
static void OnTagsReported(ImpinjReader sender, TagReport report)
{
try
{
// This event handler is called asynchronously
// when tag reports are available.
// Loop through each tag in the report
// and print the data.
foreach (Tag tag in report)
{
string a_epc = tag.Epc.ToString();
//removing empty spaces, cos Innova will not print
a_epc = a_epc.Replace(" ", "");
if (G_IgnoreList.IndexOf(a_epc) != -1)
{
return;
}
if (a_epc == "")
return;
//Ignoring GControlTag. This is about senvitivity of reader //&& ( G_LastLocalTime.Subtract(DateTime.Now).Milliseconds > 1000)
if (GControlTag == a_epc)
{
DisplayAntennaTick(tag.AntennaPortNumber);
return;
}
if (G_lastTag == a_epc)
{
GLastTagSeen++;
return;
}
if (G_PrintedTagList.IndexOf(a_epc) != -1)
{
//sw_operations.WriteLineAsync(string.Format("{0} NOT PRINTING Tag (PrintedTagList) MES tag {1}", DateTime.Now.ToLongTimeString(), a_epc));
return;
}
if (G_CageIsBusy)
return;
//we get here if new tag came
//new and last tag seen in 0.5 interval
double a_lastEventSec = DateTime.Now.Subtract(G_LastLocalTime).TotalSeconds;
// if new tag appeared earlier than 5 sec from begining of prev. tag
if (a_lastEventSec < 2)//&& (a_lastEventSec < 5) //(G_lastTag != "") &&
{
if (G_MulitagList.IndexOf(a_epc) == -1)
{
G_MultitagAlarm = true;
G_MulitagList.Add(a_epc);
sw_mulitags.WriteLineAsync(string.Format("{0} {1} appeared in {2} sec", DateTime.Now.ToLongTimeString(), a_epc, a_lastEventSec));
}
return;
}
//if (G_MulitagList.IndexOf(a_epc) != -1)
// sw_operations.WriteAsync(string.Format("{0} Not printing multitag(MulitagList) detected MES tag {1}", DateTime.Now.ToLongTimeString(), a_epc));
WriteCOMPort(a_epc);
G_PrintedTagList.Add(a_epc);//first detected tag is believed to be printed
sw_operations.WriteLineAsync(string.Format("{0} WriteCOM PORT {1} ", DateTime.Now.ToLongTimeString(), a_epc));
G_LastLocalTime = DateTime.Now;
G_lastTag = a_epc;
G_LastTagAntennaPortNumber = tag.AntennaPortNumber;
G_LastTagRSSI = tag.PeakRssiInDbm;
}
}
catch (System.Exception ex)
{
sw_errors.WriteLine(string.Format("OnTagsReported: {0}", ex.Message));
sw_errors.Flush();
}
}
protected static void DisplayAntennaTick(int p_AntennaNum, ConsoleColor p_Color = ConsoleColor.Green)
{
try
{
if (p_AntennaNum == 1)
{
G_NoMajicTagAlarm1 = false; // string.Format( {0} ", DateTime.Now.ToLongTimeString())
WriteScreen("Antenna1 :", 1, 10, false, G_IgnoretagBlink, p_Color);
G_LastMajicTickTime1 = DateTime.Now;
}
else if (p_AntennaNum == 2)
{
G_NoMajicTagAlarm2 = false;
WriteScreen("Antenna2 :", 1, 11, false, G_IgnoretagBlink, p_Color);
G_LastMajicTickTime2 = DateTime.Now;
}
}
catch (System.Exception ex)
{
sw_errors.WriteLine(string.Format("DisplayAntennaTick: {0}", ex.Message));
sw_errors.Flush();
}
}
protected static void DisplayAntennaInfo(int p_AntennaNum, string p_TagId, double p_RSSI = 0)
{
try
{
int a_line = 9 + p_AntennaNum; //Ant 1 == line 10
string a_disp_str = string.Format(": {0} RSSI: {1}", p_TagId, p_RSSI);
if (p_TagId == "")
a_disp_str = "";
WriteScreen(a_disp_str.PadRight(100), 11, a_line);
}
catch (System.Exception ex)
{
sw_errors.WriteLine(string.Format("DisplayAntennaInfo: {0}", ex.Message));
sw_errors.Flush();
}
}
public static void Read()
{
try
{
while (_continue)
{
try
{
string message = _serialPort.ReadLine();
message = message.Replace("\r\n", "").Replace("\r", "").Replace("\n","");
if (message.Length > 0)
{
//(message == "Tick")
G_LastCOMPortTime = DateTime.Now;
if (message.IndexOf("MESCount=") == 0)
{
G_MesBagCount = message.Remove(0, 9);
}
else if (message.IndexOf("InnovaCount=") == 0)
{
G_InnovaBagCount = message.Remove(0, 12);
}
else if (message.IndexOf("NoTagCount=") == 0)
{
G_NoTagCount = message.Remove(0, 11);
}
else if (message.IndexOf("HeartBtCount=") == 0)
{
G_HeartBtCount = message.Remove(0, 13);
}
else if (message.IndexOf("Receiving Box") > 0)
{
G_CageIsBusy = false;
}
else
{
if (message.Length < GLastComPortMessage.Length)
message = message.PadRight(GLastComPortMessage.Length);
if (message.IndexOf("PRINT_MES") > 0)
{
G_CageIsBusy = true;
int p_FirstSpace = message.IndexOf(" ");
string a_printed_tag = message;
a_printed_tag = a_printed_tag.Remove(p_FirstSpace, a_printed_tag.Length - p_FirstSpace);
if ((G_PrintedTagList.IndexOf(a_printed_tag) == -1) || (G_PrintedTagList.Count == 0))
{
if ((a_printed_tag != "") && (a_printed_tag != "0"))
{
G_PrintedTagList.Add(a_printed_tag);
sw_PrintedTags.WriteLine(a_printed_tag);
sw_PrintedTags.Flush();
}
}
/*else
{
sw_errors.WriteLine(string.Format("Tag {0} MES reported this tag printing more than once", a_printed_tag));
}
*/
/*if (G_MulitagList.Count > 0)
{
WriteCOMPort("Stop");
if (G_AutostopOnMultiTag)
{
G_MulitagList.Clear();
G_MultitagAlarm = false;
WriteScreen(string.Format("MULTI-TAGS : Autostop at: {0} MultiTagCount = {1}", DateTime.Now.ToLongTimeString(), G_MulitagList.Count), 1, 13);
}
}*/
}
WriteScreen(string.Format(": {0}", message), 12, 12, false);
sw_operations.WriteLine(string.Format("{0} {1} : {2}", DateTime.Now.ToLongTimeString(), DateTime.Now.Millisecond, message));
sw_operations.Flush();
GLastComPortMessage = message;
}
}
}
catch (TimeoutException ex)
{
sw_errors.WriteLine(string.Format("{0} procedure Read.COM Port: TimeoutException: {1}", DateTime.Now.ToLongTimeString(), ex.Message));
sw_errors.Flush();
}
}
}
catch (System.Exception ex)
{
sw_errors.WriteLine(string.Format("Read: {0}", ex.Message));
sw_errors.Flush();
}
}
private static void WriteCOMPort(string p_Message)
{
try
{
lock(LockingCOMPortVar)
{
_serialPort.WriteLine(p_Message);
}
}
catch (System.Exception ex)
{
sw_errors.WriteLine(string.Format("WriteCOMPort: {0}", ex.Message));
sw_errors.Flush();
}
}
// Display Port values and prompt user to enter a port.
public static string SetPortName(string defaultPortName)
{
try
{
string portName;
Console.WriteLine("Available Ports:");
foreach (string s in SerialPort.GetPortNames())
{
Console.WriteLine(" {0}", s);
}
Console.Write("Enter COM port number # (Default: {0}): ", defaultPortName);
portName = Console.ReadLine();
if (portName == "" || !(portName.ToLower()).StartsWith("com"))
{
return defaultPortName;
}
return portName;
}
catch(System.Exception ex)
{
sw_errors.WriteLine(string.Format("SetPortName: {0}", ex.Message));
sw_errors.Flush();
return ex.Message;
}
}
protected static void WriteScreen(string s, int x, int y, bool p_doLog = false, bool p_UseColor = false, ConsoleColor p_Color = ConsoleColor.White)
{
try
{
lock (LockingVar)
{
if (p_UseColor)
Console.ForegroundColor = p_Color;
int OrigRow = Console.CursorTop;
int origCol = Console.CursorLeft;
int width = Console.WindowWidth;
x = x % width;
try
{
Console.SetCursorPosition(x, y);
Console.Write(s);
}
catch (ArgumentOutOfRangeException e)
{
}
finally
{
try
{
Console.SetCursorPosition(OrigRow, origCol);
Console.ResetColor();
}
catch (ArgumentOutOfRangeException e) { }
}
}
}
catch (System.Exception ex)
{
sw_errors.WriteLine(string.Format("WriteScreen: {0}", ex.Message));
sw_errors.Flush();
}
}
}
}
No comments:
Post a Comment