You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
using System;using System.Text;using nanoFramework.Runtime.Events;using Windows.Devices.SerialCommunication;using Windows.Storage.Streams;namespace nf.RDM6300
{/// <summary>/// Rdm630 RFID Reader/// </summary>/// <remarks><![CDATA[/// RDM630 pin layout:/// /// 10 9 8 7 6/// │ │ │ │ │/// █████████████████████████/// █████████████████████████/// █████████████████████████/// █████████████████████████/// │ │ │ │ │ /// 1 2 3 4 5 ////// 1 TX (Data out) -> Netduino pin 0 or 2 (COM1 or COM2)/// 2 RX (Data in) -> Netduino pin 1 or 3 (COM1 or COM2), but since it's read-only, may be left empty/// 3 Unused/// 4 GND -> Netduino Gnd/// 5 +5V(DC) -> Netduino +5V/// 6 ANT1 -> Antenna (polarity doesn't matter)/// 7 ANT2 -> Antenna (polarity doesn't matter)/// 8 GND -> Netduino Gnd (but if pin 4 is already connected, this may be left empty)/// 9 +5V(DC) -> Netduino +5V (but if pin 5 is already connected, this may be left empty)/// 10 LED -> A led if you want to have a led signalling when there's a transfer/// ]]></remarks>publicclassRdm630{/// <summary>/// Contains a reference to the serial port the Rdm630 is connected to/// </summary>privateSerialDevice_Serial;/// <summary>/// A read buffer of 14 bytes. Since every block of data has 14 bytes, this should be enough./// </summary>privatebyte[]_ReadBuffer=newbyte[14];/// <summary>/// The current position on the _ReadBuffer/// </summary>privatebyte_ReadPosition;/// <summary>/// Table to convert integers from the serial bus to a hex digit quickly/// </summary>privatestring_SerialConversionTable="------------------------------------------------0123456789-------ABCDEF";/// <summary>/// Contains the last successfull RFID tag/// </summary>privatestring_LastSuccessfullRead;/// <summary>/// Triggered when data has been received/// </summary>publiceventNativeEventHandlerDataReceived;/// <summary>/// The most recent scanned tag/// </summary>publicstringTag{get{returnthis._LastSuccessfullRead;}}/// <summary>/// Rdm630 RFID Reader/// </summary>/// <param name="Port">The serial port the Rdm630 is connected to</param>publicRdm630(stringPort){//this._Serial = new SerialPort(Port, 9600, Parity.None, 8, StopBits.One);//this._Serial.ReadTimeout = 1000;//this._Serial.DataReceived += new SerialDataReceivedEventHandler(_Serial_DataReceived);//this._Serial.Open();//// set parameters_Serial= SerialDevice.FromId(Port);
_Serial.BaudRate =9600;
_Serial.Parity = SerialParity.None;
_Serial.StopBits = SerialStopBitCount.One;
_Serial.Handshake = SerialHandshake.None;
_Serial.DataBits =8;this._Serial.DataReceived +=new SerialDataReceivedEventHandler(_Serial_DataReceived);}/// <summary>/// Triggers when there is new data on the serial port/// </summary>/// <param name="Sender">The sender of the event, which is the SerialPort object</param>/// <param name="EventData">A SerialDataReceivedEventArgs object that contains the event data</param>privatevoid_Serial_DataReceived(objectSender,SerialDataReceivedEventArgsEventData){// Reads the whole buffer from the serial portbyte[]ReadBuffer=newbyte[this._Serial.BytesToRead];// this._Serial.Read(ReadBuffer, 0, ReadBuffer.Length);DataReaderinputDataReader=new DataReader(_Serial.InputStream);
inputDataReader.InputStreamOptions = InputStreamOptions.Partial;varbytesRead= inputDataReader.Load(_Serial.BytesToRead);
inputDataReader.ReadBytes(ReadBuffer);// Loops through all bytesfor(uintIndex=0;Index< ReadBuffer.Length;++Index){// Start byteif(ReadBuffer[Index]==2)this._ReadPosition =0;// Adds the digit to the global read bufferthis._ReadBuffer[this._ReadPosition]= ReadBuffer[Index];// Increases the position of the global read buffer++this._ReadPosition;// global read buffer is full, lets validateif(this._ReadPosition ==this._ReadBuffer.Length){// Resets the read positionthis._ReadPosition =0;// Announces we got a full set of bytesthis._Rdm630_DataReceived();}}}/// <summary>/// Triggers when a full RFID tag is scanned/// </summary>privatevoid_Rdm630_DataReceived(){// Validates the start and stop byte (should be 2 & 3)if(this._ReadBuffer[0]!=2||this._ReadBuffer[13]!=3)return;// Fetches the 10 digitsstringDigits="";for(intIndex=0;Index<10;++Index){// Index + 1 since the first byte is the start byteDigits+=this._SerialConversionTable[this._ReadBuffer[Index+1]];}// Fetches the checksum from the bufferstringBufferCheckSum="";BufferCheckSum+=this._SerialConversionTable[this._ReadBuffer[11]];BufferCheckSum+=this._SerialConversionTable[this._ReadBuffer[12]];// Calculates the checksum from the digitsuintCalcCheckSum=0;for(intIndex=0;Index<10;Index=Index+2){CalcCheckSum=CalcCheckSum^ Tools.Hex2Dec(Digits.Substring(Index,2));}// Do both checksums match?if(Tools.Hex2Dec(BufferCheckSum)==CalcCheckSum){this._LastSuccessfullRead =Digits;if(this.DataReceived !=null)this.DataReceived(0,0,new DateTime());}}}/// <summary>/// Generic, useful tools/// </summary>publicstaticclassTools{/// <summary>Contains the name of the hardware provider</summary>privatestaticstring_HardwareProvider="";/// <summary>Escapes all non-visible characters</summary>/// <param name="Input">Input text</param>/// <returns>Output text</returns>publicstaticstringEscape(stringInput){if(Input==null)return"";char[]Buffer= Input.ToCharArray();stringRetValue="";for(inti=0;i< Buffer.Length;++i){if(Buffer[i]==13)RetValue+="\\r";elseif(Buffer[i]==10)RetValue+="\\n";elseif(Buffer[i]==92)RetValue+="\\\\";elseif(Buffer[i]<32|| Buffer[i]>126)RetValue+="\\"+ Tools.Dec2Hex((int)Buffer[i],2);elseRetValue+= Buffer[i];}returnRetValue;}/// <summary>/// Converts a Hex string to a number/// </summary>/// <param name="HexNumber">The Hex string (ex.: "0F")</param>/// <returns>The decimal value</returns>publicstaticuintHex2Dec(stringHexNumber){// Always in upper caseHexNumber= HexNumber.ToUpper();// Contains all Hex posibilitiesstringConversionTable="0123456789ABCDEF";// Will contain the return valueuintRetVal=0;// Will increaseuintMultiplier=1;for(intIndex= HexNumber.Length -1;Index >= 0;--Index){RetVal+=(uint)(Multiplier*(ConversionTable.IndexOf(HexNumber[Index])));Multiplier=(uint)(Multiplier* ConversionTable.Length);}returnRetVal;}/// <summary>/// Converts a byte array to a char array/// </summary>/// <param name="Input">The byte array</param>/// <returns>The char array</returns>publicstaticchar[]Bytes2Chars(byte[]Input){char[]Output=newchar[Input.Length];for(intCounter=0;Counter< Input.Length;++Counter)
Output[Counter]=(char)Input[Counter];returnOutput;}/// <summary>/// Converts a char array to a byte array/// </summary>/// <param name="Input">The char array</param>/// <returns>The byte array</returns>publicstaticbyte[]Chars2Bytes(char[]Input){byte[]Output=newbyte[Input.Length];for(intCounter=0;Counter< Input.Length;++Counter)
Output[Counter]=(byte)Input[Counter];returnOutput;}/// <summary>/// Changes a number into a string and add zeros in front of it, if required/// </summary>/// <param name="Number">The input number</param>/// <param name="Digits">The amount of digits it should be</param>/// <param name="Character">The character to repeat in front (default: 0)</param>/// <returns>A string with the right amount of digits</returns>publicstaticstringZeroFill(stringNumber,intDigits,charCharacter='0'){boolNegative=false;if(Number.Substring(0,1)=="-"){Negative=true;Number= Number.Substring(1);}for(intCounter= Number.Length;Counter<Digits;++Counter){Number=Character+Number;}if(Negative)Number="-"+Number;returnNumber;}/// <summary>/// Changes a number into a string and add zeros in front of it, if required/// </summary>/// <param name="Number">The input number</param>/// <param name="MinLength">The amount of digits it should be</param>/// <param name="Character">The character to repeat in front (default: 0)</param>/// <returns>A string with the right amount of digits</returns>publicstaticstringZeroFill(intNumber,intMinLength,charCharacter='0'){return ZeroFill(Number.ToString(), MinLength, Character);// In 4.2 it should be possible to replace this with the following line,// but due to a bug (http://netmf.codeplex.com/workitem/1322) it isn't.// return Number.toString("d" + MinLength.toString());}/// <summary>/// URL-encode according to RFC 3986/// </summary>/// <param name="Input">The URL to be encoded.</param>/// <returns>Returns a string in which all non-alphanumeric characters except -_.~ have been replaced with a percent (%) sign followed by two hex digits.</returns>publicstaticstringRawUrlEncode(stringInput){stringRetValue="";for(intCounter=0;Counter< Input.Length;++Counter){byteCharCode=(byte)(Input.ToCharArray()[Counter]);if(CharCode==0x2d// -||CharCode==0x5f// _||CharCode==0x2e// .||CharCode==0x7e// ~||(CharCode>0x2f&&CharCode<0x3a)// 0-9||(CharCode>0x40&&CharCode<0x5b)// A-Z||(CharCode>0x60&&CharCode<0x7b)// a-z){RetValue+= Input.Substring(Counter,1);}else{// Calculates the hex value in some wayRetValue+="%"+ Dec2Hex(CharCode,2);}}returnRetValue;}/// <summary>/// URL-decode according to RFC 3986/// </summary>/// <param name="Input">The URL to be decoded.</param>/// <returns>Returns a string in which original characters</returns>publicstaticstringRawUrlDecode(stringInput){stringRetValue="";for(intCounter=0;Counter< Input.Length;++Counter){stringChar= Input.Substring(Counter,1);if(Char=="%"){// Encoded characterstringHexValue= Input.Substring(++Counter,2);++Counter;RetValue+=(char)Hex2Dec(HexValue);}else{// Normal characterRetValue+=Char;}}returnRetValue;}/// <summary>/// Encodes a string according to the BASE64 standard/// </summary>/// <param name="Input">The input string</param>/// <returns>The output string</returns>publicstaticstringBase64Encode(stringInput){// Pairs of 3 8-bit bytes will become pairs of 4 6-bit bytes// That's the whole trick of base64 encoding :-)intBlocks= Input.Length /3;// The amount of original pairsif(Blocks*3< Input.Length)++Blocks;// Fixes rounding issues; always round upintBytes=Blocks*4;// The length of the base64 output// These characters will be used to represent the 6-bit bytes in ASCIIchar[]Base64_Characters="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".ToCharArray();// Converts the input string to characters and creates the output arraychar[]InputChars= Input.ToCharArray();char[]OutputChars=newchar[Bytes];// Converts the blocks of bytesfor(intBlock=0;Block<Blocks;++Block){// Fetches the input pairsbyteInput0=(byte)(InputChars.Length >Block*3? InputChars[Block*3]:0);byteInput1=(byte)(InputChars.Length >Block*3+1? InputChars[Block*3+1]:0);byteInput2=(byte)(InputChars.Length >Block*3+2? InputChars[Block*3+2]:0);// Generates the output pairsbyteOutput0=(byte)(Input0>>2);// The first 6 bits of the 1st bytebyteOutput1=(byte)(((Input0&0x3)<<4)+(Input1>>4));// The last 2 bits of the 1st byte followed by the first 4 bits of the 2nd bytebyteOutput2=(byte)(((Input1&0xf)<<2)+(Input2>>6));// The last 4 bits of the 2nd byte followed by the first 2 bits of the 3rd bytebyteOutput3=(byte)(Input2&0x3f);// The last 6 bits of the 3rd byte// This prevents 0-bytes at the endif(InputChars.Length <Block*3+2)Output2=64;if(InputChars.Length <Block*3+3)Output3=64;// Converts the output pairs to base64 characters
OutputChars[Block*4]= Base64_Characters[Output0];
OutputChars[Block*4+1]= Base64_Characters[Output1];
OutputChars[Block*4+2]= Base64_Characters[Output2];
OutputChars[Block*4+3]= Base64_Characters[Output3];}returnnewstring(OutputChars);}/// <summary>/// Converts a number to a Hex string/// </summary>/// <param name="Input">The number</param>/// <param name="MinLength">The minimum length of the return string (filled with 0s)</param>/// <returns>The Hex string</returns>publicstaticstringDec2Hex(intInput,intMinLength=0){
#ifMF_FRAMEWORK_VERSION_V4_2||MF_FRAMEWORK_VERSION_V4_3// Since NETMF 4.2 int.toString() exists, so we can do this:return Input.ToString("x"+ MinLength.ToString());
#else// Contains all Hex posibilitiesstringConversionTable="0123456789ABCDEF";// Starts the conversionstringRetValue="";intCurrent=0;intNext= Input;do{if(Next >= ConversionTable.Length){// The current digitCurrent=(Next/ ConversionTable.Length);if(Current* ConversionTable.Length >Next)--Current;// What's leftNext=Next-(Current* ConversionTable.Length);}else{// The last digitCurrent=Next;// Nothing leftNext=-1;}RetValue+= ConversionTable[Current];}while(Next!=-1);return Tools.ZeroFill(RetValue, MinLength);
#endif
}/// <summary>/// Converts a 16-bit array to an 8 bit array/// </summary>/// <param name="Data">The 16-bit array</param>/// <returns>The 8-bit array</returns>publicstaticbyte[]UShortsToBytes(ushort[]Data){byte[]RetVal=newbyte[Data.Length *2];intBytePos=0;for(intShortPos=0;ShortPos< Data.Length;++ShortPos){
RetVal[BytePos++]=(byte)(Data[ShortPos]>>8);
RetVal[BytePos++]=(byte)(Data[ShortPos]&0x00ff);}returnRetVal;}/// <summary>/// Converts an 8-bit array to a 16 bit array/// </summary>/// <param name="Data">The 8-bit array</param>/// <returns>The 16-bit array</returns>publicstaticushort[]BytesToUShorts(byte[]Data){ushort[]RetVal=newushort[Data.Length /2];intBytePos=0;for(intShortPos=0;ShortPos< RetVal.Length;++ShortPos){
RetVal[ShortPos]=(ushort)((Data[BytePos++]<<8)+ Data[BytePos++]);}returnRetVal;}/// <summary>Calculates an XOR Checksum</summary>/// <param name="Data">Input data</param>/// <returns>XOR Checksum</returns>publicstaticbyteXorChecksum(stringData){return Tools.XorChecksum(Tools.Chars2Bytes(Data.ToCharArray()));}/// <summary>Calculates an XOR Checksum</summary>/// <param name="Data">Input data</param>/// <returns>XOR Checksum</returns>publicstaticbyteXorChecksum(byte[]Data){byteChecksum=0;for(intPos=0;Pos< Data.Length;++Pos)Checksum ^= Data[Pos];returnChecksum;}/// <summary>/// Rounds a value to a certain amount of digits/// </summary>/// <param name="Input">The input number</param>/// <param name="Digits">Amount of digits after the .</param>/// <returns>The rounded value (as float or double gave precision errors, hence the String type)</returns>publicstaticstringRound(floatInput,intDigits=2){intMultiplier=1;for(inti=0;i<Digits;++i)Multiplier *= 10;stringRounded=((int)(Input*Multiplier)).ToString();return(Rounded.Substring(0, Rounded.Length -2)+"."+ Rounded.Substring(Rounded.Length -2)).TrimEnd(newchar[]{'0','.'});}/// <summary>A generic event handler when receiving a string</summary>/// <param name="text">The actual string</param>/// <param name="time">Timestamp of the event</param>publicdelegatevoid StringEventHandler(stringtext,DateTimetime);}}