/// <summary> /// Caculate basic stats and save the packet to a stream /// </summary> /// <param name="envelope"></param> private void SavePacket( PacketData.PacketWrapper envelope ) { // Debug.WriteLineIf((int)envelope.RadioID != (int)_theReaderID.Handle, String.Format("Expected: {0}, Actual: {1}", (int)_theReaderID.Handle, (int)envelope.RadioID), "ERROR"); Debug.Assert( envelope.ReaderName == Name ); PacketData.PacketBase packet = envelope.Packet; PacketData.PacketType type = envelope.PacketType; switch ( type ) { case PacketData.PacketType.CMD_BEGIN: { LastUsedAntenna = null; LastCommandResult = null; PacketData.cmd_beg cmd_beg = packet as PacketData.cmd_beg; Debug.Assert( cmd_beg != null ); #pragma warning disable 420 // reference to a volatile field is valid for Interlocked call System.Threading.Interlocked.Increment( ref _rawCommandCount ); #pragma warning restore 420 } break; case PacketData.PacketType.CMD_END: { PacketData.cmd_end cmd_end = packet as PacketData.cmd_end; Debug.Assert( cmd_end != null ); LastCommandResult = cmd_end.Result; if ( cmd_end.Result != 0 ) CommandErrors++; } break; case PacketData.PacketType.ANTENNA_CYCLE_BEGIN: { PacketData.ant_cyc_beg cyc_beg = packet as PacketData.ant_cyc_beg; Debug.Assert( cyc_beg != null ); #pragma warning disable 420 // reference to a volatile field is valid for Interlocked call System.Threading.Interlocked.Increment( ref _rawAntennaCycleCount ); #pragma warning restore 420 // PacketLogger.Comment(String.Format("Start of Cycle {0} Command={1}", RawCycleCount - 1, RawCommandCount - 1)); lock ( _tagInventoryData ) { foreach ( TagInventory ti in TagInventoryData ) { ti.cycleReadCount = 0; ti.totalCycleCount = RawAntennaCycleCount; } } } break; case PacketData.PacketType.ANTENNA_CYCLE_BEGIN_DIAG: { PacketData.ant_cyc_beg_diag cyc_beg_diag = packet as PacketData.ant_cyc_beg_diag; Debug.Assert( cyc_beg_diag != null ); } break; case PacketData.PacketType.ANTENNA_CYCLE_END: { PacketData.ant_cyc_end cyc_end = packet as PacketData.ant_cyc_end; Debug.Assert( cyc_end != null ); // PacketLogger.Comment(String.Format("End of Cycle {0}", RawCycleCount - 1)); } break; case PacketData.PacketType.ANTENNA_CYCLE_END_DIAG: { PacketData.ant_cyc_end_diag cyc_end_diag = packet as PacketData.ant_cyc_end_diag; Debug.Assert( cyc_end_diag != null ); } break; case PacketData.PacketType.ANTENNA_BEGIN: { PacketData.ant_beg ant_beg = packet as PacketData.ant_beg; Debug.Assert( ant_beg != null ); #pragma warning disable 420 // reference to a volatile field is valid for Interlocked call System.Threading.Interlocked.Increment( ref _rawAntennaCount ); #pragma warning restore 420 LastUsedAntenna = ant_beg.antenna; } break; case PacketData.PacketType.ANTENNA_END: { PacketData.ant_end ant_end = packet as PacketData.ant_end; Debug.Assert( ant_end != null ); LastUsedAntenna = null; } break; case PacketData.PacketType.ANTENNA_BEGIN_DIAG: { PacketData.ant_beg_diag ant_beg_diag = packet as PacketData.ant_beg_diag; Debug.Assert( ant_beg_diag != null ); } break; case PacketData.PacketType.ANTENNA_END_DIAG: { PacketData.ant_end_diag ant_end_diag = packet as PacketData.ant_end_diag; Debug.Assert( ant_end_diag != null ); } break; case PacketData.PacketType.INVENTORY_CYCLE_BEGIN: { PacketData.inv_cyc_beg inv_cyc_beg = packet as PacketData.inv_cyc_beg; Debug.Assert( inv_cyc_beg != null ); #pragma warning disable 420 // reference to a volatile field is valid for Interlocked call System.Threading.Interlocked.Increment( ref _rawInventoryCycleCount ); #pragma warning restore 420 // PacketLogger.Comment(String.Format("Start of Cycle {0} Command={1}", RawCycleCount - 1, RawCommandCount - 1)); } break; case PacketData.PacketType.INVENTORY_CYCLE_END: { PacketData.inv_cyc_end inv_cyc_end = packet as PacketData.inv_cyc_end; Debug.Assert( inv_cyc_end != null ); } break; case PacketData.PacketType.CARRIER_INFO: { PacketData.carrier_info carrier_info = packet as PacketData.carrier_info; Debug.Assert( carrier_info != null ); } break; case PacketData.PacketType.INVENTORY_CYCLE_END_DIAGS: { PacketData.inv_cyc_end_diag inv_cyc_end_diag = packet as PacketData.inv_cyc_end_diag; Debug.Assert( inv_cyc_end_diag != null ); } break; case PacketData.PacketType.ISO18K6C_INVENTORY_ROUND_BEGIN: { PacketData.inv_rnd_beg inv_rnd_beg = packet as PacketData.inv_rnd_beg; Debug.Assert( inv_rnd_beg != null ); #pragma warning disable 420 // reference to a volatile field is valid for Interlocked call System.Threading.Interlocked.Increment( ref _rawRoundCount ); #pragma warning restore 420 // reference to a volatile field is valid for Interlocked call } break; case PacketData.PacketType.ISO18K6C_INVENTORY_ROUND_BEGIN_DIAG: { PacketData.inv_rnd_beg_diag inv_rnd_beg_diag = packet as PacketData.inv_rnd_beg_diag; Debug.Assert( inv_rnd_beg_diag != null ); } break; case PacketData.PacketType.ISO18K6C_INVENTORY_ROUND_END_DIAG: { PacketData.inv_rnd_end_diag inv_rnd_end_diag = packet as PacketData.inv_rnd_end_diag; Debug.Assert( inv_rnd_end_diag != null ); } break; case PacketData.PacketType.ISO18K6C_INVENTORY: { PacketData.inventory epc = packet as PacketData.inventory; Debug.Assert( epc != null ); BitVector32 flags = new BitVector32( epc.flags ); bool badCrc = flags[ PacketData.PacketBase.crcResult ] != 0; if ( badCrc ) { #pragma warning disable 420 // reference to a volatile field is valid for Interlocked call System.Threading.Interlocked.Increment( ref _cRCErrors ); #pragma warning restore 420 } else { #pragma warning disable 420 // reference to a volatile field is valid for Interlocked call System.Threading.Interlocked.Increment( ref _rawInventoryCount ); #pragma warning restore 420 rfidTag key = new rfidTag( epc.inventory_data ); if ( _sessionTagList.AddOrIncrementTagCount( key ) == 1 ) { _requestTagList.Add( key, 1 ); _periodTagList.Add( key, 1 ); } else { if ( _requestTagList.AddOrIncrementTagCount( key ) == 1 ) { _periodTagList.Add( key, 1 ); } else { _periodTagList.AddOrIncrementTagCount( key ); } } string epcData = BitConverter.ToString( epc.inventory_data, 0, epc.inventory_data.Length - flags[ PacketData.PacketBase.paddingBytes ] ); int CycleSlotNumber = RawAntennaCycleCount == 0 ? 0 : RawAntennaCycleCount - 1; KeyList<TagInventory> epcDataKey = new KeyList<TagInventory>( "tagIdData", epcData ); _inventoryMatrix.AddTagCycle( epcData, CycleSlotNumber ); TagInventory tagInventory = new TagInventory( ); lock ( _tagInventoryData ) { LastUsedAntenna = epc.logic_ant; if ( !TagInventoryData.Contains( epcDataKey ) ) // new tag ID { // PacketLogger.Comment(String.Format("First Read of Tag {0} Command={1}, Cycle={2}", epcData, RawCommandCount - 1, RawCycleCount - 1)); tagInventory.tagIdData = epcData; tagInventory.readCount = 1; tagInventory.cycleReadCount = 1; tagInventory.firstReadTime = epc.ms_ctr; tagInventory.lastReadTime = epc.ms_ctr; tagInventory.firstCommand = RawCommandCount - 1; tagInventory.lastCommand = RawCommandCount - 1; tagInventory.actualCycleCount = 1; tagInventory.totalCycleCount = RawAntennaCycleCount; tagInventory.cycleReadCount = 1; tagInventory.sumOfCommandReads = 0; //tagInventory.readRate = 0; //tagInventory.readerCycleCount; //tagInventory.firstReaderCycle; //tagInventory.lastReaderCycle; //tagInventory.antennaCycleCount; //tagInventory.firstAntennaCycle; //tagInventory.lastAntennaCycle; tagInventory.port0reads = 0; tagInventory.port1reads = 0; tagInventory.port2reads = 0; tagInventory.port3reads = 0; tagInventory.port4reads = 0; tagInventory.port5reads = 0; tagInventory.port6reads = 0; tagInventory.port7reads = 0; tagInventory.port8reads = 0; tagInventory.port9reads = 0; tagInventory.port10reads = 0; tagInventory.port11reads = 0; tagInventory.port12reads = 0; tagInventory.port13reads = 0; tagInventory.port14reads = 0; tagInventory.port15reads = 0; if ( LastUsedAntenna != null ) { switch ( LastUsedAntenna ) { case 0: tagInventory.port0reads = 1; break; case 1: tagInventory.port1reads = 1; break; case 2: tagInventory.port2reads = 1; break; case 3: tagInventory.port3reads = 1; break; case 4: tagInventory.port4reads = 1; break; case 5: tagInventory.port5reads = 1; break; case 6: tagInventory.port6reads = 1; break; case 7: tagInventory.port7reads = 1; break; case 8: tagInventory.port8reads = 1; break; case 9: tagInventory.port9reads = 1; break; case 10: tagInventory.port10reads = 1; break; case 11: tagInventory.port11reads = 1; break; case 12: tagInventory.port12reads = 1; break; case 13: tagInventory.port13reads = 1; break; case 14: tagInventory.port14reads = 1; break; case 15: tagInventory.port15reads = 1; break; default: break; } } // tagInventory.inventoryRoundCount; // tagInventory.firstinventoryRound; // tagInventory.lastinventoryRound; TagInventoryData.Add( tagInventory ); } else { tagInventory = ( TagInventory ) TagInventoryData[ epcDataKey ]; tagInventory.readCount++; if ( tagInventory.lastCommand == CycleSlotNumber ) { tagInventory.cycleReadCount += 1; } else { tagInventory.cycleReadCount = 1; tagInventory.actualCycleCount++; tagInventory.lastCommand = CycleSlotNumber; } tagInventory.totalCycleCount = RawAntennaCycleCount; tagInventory.lastReadTime = epc.ms_ctr; // if (tagInventory.lastReadTime > tagInventory.firstReadTime) //{ // tagInventory.readRate = (float)(tagInventory.ReadCount) / (float)((tagInventory.LastReadTime - tagInventory.FirstReadTime) / 100); //} //tagInventory.commandCount = 1; //tagInventory.firstCommand; //tagInventory.lastCommand; //tagInventory.readerCycleCount; //tagInventory.firstReaderCycle; //tagInventory.lastReaderCycle; //tagInventory.antennaCycleCount; //tagInventory.firstAntennaCycle; //tagInventory.lastAntennaCycle; if ( LastUsedAntenna != null ) { switch ( LastUsedAntenna ) { case 0: tagInventory.port0reads += 1; break; case 1: tagInventory.port1reads += 1; break; case 2: tagInventory.port2reads += 1; break; case 3: tagInventory.port3reads += 1; break; case 4: tagInventory.port4reads += 1; break; case 5: tagInventory.port5reads += 1; break; case 6: tagInventory.port6reads += 1; break; case 7: tagInventory.port7reads += 1; break; case 8: tagInventory.port8reads += 1; break; case 9: tagInventory.port9reads += 1; break; case 10: tagInventory.port10reads += 1; break; case 11: tagInventory.port11reads += 1; break; case 12: tagInventory.port12reads += 1; break; case 13: tagInventory.port13reads += 1; break; case 14: tagInventory.port14reads += 1; break; case 15: tagInventory.port15reads += 1; break; default: break; } } //tagInventory.inventoryRoundCount ; //tagInventory.firstinventoryRound ; //tagInventory.lastinventoryRound ; tagInventory.dataRead = ""; //clark 2011.4. copied from R1000 Tracer TagInventoryData[epcDataKey] = tagInventory; } } } } break; case PacketData.PacketType.ISO18K6C_INVENTORY_DIAG: break; case PacketData.PacketType.ISO18K6C_TAG_ACCESS: { PacketData.Iso18k6c_access access = packet as PacketData.Iso18k6c_access; Debug.Assert( access != null ); BitVector32 flags = new BitVector32( access.flags ); bool badCrc = flags[ PacketData.PacketBase.accessCRCFlag ] == ( int ) PacketData.PacketBase.CrcResultValues.Bad; if ( badCrc ) { #pragma warning disable 420 // reference to a volatile field is valid for Interlocked call System.Threading.Interlocked.Increment( ref _cRCErrors ); #pragma warning restore 420 } else { if ( flags[ PacketData.PacketBase.accessErrorFlag ] == ( int ) PacketData.PacketBase.ISO_18000_6C_ErrorFlag.AccessSucceeded ) { #pragma warning disable 420 // reference to a volatile field is valid for Interlocked call System.Threading.Interlocked.Increment( ref _commonAccessCount ); #pragma warning restore 420 } // Update Requests Here - todo // envelope.RecordReadRequest( ( int ) TagBank, TagMemoryLocation, TagMemoryLength, TagPassword ); //Clark 2011.2.18 Copied from R1000 Tracer PacketData.PacketWrapper[] RecentPacketArray = new PacketData.PacketWrapper[RecentPacketList.Count]; RecentPacketList.CopyTo(RecentPacketArray); for (int i = (RecentPacketArray.Length) - 1; i >= 0; i--) { if (RecentPacketArray[i].PacketType == PacketData.PacketType.ISO18K6C_INVENTORY) { PacketData.PacketBase pa = RecentPacketArray[i].Packet; PacketData.inventory epc = (PacketData.inventory)pa; string epcData = BitConverter.ToString(epc.inventory_data, 0, epc.inventory_data.Length);// - flags[PacketData.PacketBase.paddingBytes]); KeyList<TagInventory> epcDataKey = new KeyList<TagInventory>("tagIdData", epcData); //Console.WriteLine(epcData); TagInventory tagInventory = new TagInventory(); lock (_tagInventoryData) { if (TagInventoryData.Contains(epcDataKey)) { tagInventory = (TagInventory)TagInventoryData[epcDataKey]; BitVector32 accessflags = new BitVector32(access.flags); if (access.data.Length >= 2) { if (accessflags[PacketData.PacketBase.accessErrorFlag] == (int)PacketData.PacketBase.ISO_18000_6C_ErrorFlag.AccessSucceeded) { //int Count = TagAccessReqCount * 2; //if (TagAccessReqCount > 8) //{ // Count = 16; // TagAccessReqCount -= 8; //} //tagInventory.dataRead += BitConverter.ToString(access.data, 0, Count);// TagAccessReqCount * 2);//access.data.GetLength(0)); tagInventory.dataRead += BitConverter.ToString(access.data, 0, TagAccessReqCount * 2);//access.data.GetLength(0)); } else tagInventory.dataRead = ""; TagInventoryData[epcDataKey] = tagInventory; } //Console.WriteLine(BitConverter.ToString(access.data, 0, access.data.Length)); } } break; } } } } break; case PacketData.PacketType.FREQUENCY_HOP_DIAG: break; case PacketData.PacketType.DEBUG: { PacketData.debug debugPacket = packet as PacketData.debug; Debug.Assert(debugPacket != null); } break; case PacketData.PacketType.COMMAND_ACTIVE: { PacketData.command_active commandActive = packet as PacketData.command_active; Debug.Assert(commandActive != null); } break; case PacketData.PacketType.NONCRITICAL_FAULT: break; case PacketData.PacketType.U_N_D_F_I_N_E_D: default: break; } // Save the packet FileHandler.WritePacket( envelope ); RecentPacketList.Add( new PacketData.PacketWrapper( envelope ) ); if ( EnableLogging ) { //Write Log PacketLogger.Log( envelope ); } } //private void SavePacket(PacketData.PacketWrapper envelope)
public Int32 MyCallback ( UInt32 bufferLength, IntPtr pBuffer, IntPtr context ) { Byte[ ] packetBuffer = new Byte[ bufferLength ]; Marshal.Copy( pBuffer, packetBuffer, 0, ( Int32 ) bufferLength ); String errorMessage = null; PacketData.PacketBase packet = null; PacketData.PacketType type = PacketData.ParsePacket ( packetBuffer, out packet, out errorMessage ); SysLogger.WriteToLog = true; PacketData.PacketWrapper envelope = null; long elapsedSesionTime = ElapsedMilliseconds; if ( packet == null || type == PacketData.PacketType.U_N_D_F_I_N_E_D || errorMessage != null ) { BadPacket badPacket = new BadPacket( ); #pragma warning disable 420 // reference to a volatile field is valid for Interlocked call badPacket.badPacketSequence = System.Threading.Interlocked.Increment( ref _commonBadIndex ); #pragma warning restore 420 badPacket.packetTime = DateTime.UtcNow; badPacket.rawPacketData = packetBuffer.Clone( ) as byte[ ]; badPacket.errorMessage = errorMessage; using ( MemoryStream data = new MemoryStream( 256 ) ) { badPacket.WriteTo( data ); envelope = new PacketData.PacketWrapper( new PacketData.CommandPsuedoPacket( "BadPacket", data.ToArray( ) ), PacketData.PacketType.U_N_D_F_I_N_E_D ); } envelope.IsPseudoPacket = true; envelope.PacketNumber = badPacket.PacketSequence; envelope.Timestamp = badPacket.packetTime; envelope.ReaderIndex = ( int ) _theReaderID.Handle; envelope.ReaderName = _theReaderID.Name; envelope.CommandNumber = _processedInventoryIndex; envelope.ElapsedTimeMs = elapsedSesionTime; } else { envelope = new PacketData.PacketWrapper ( packet, type, packetBuffer, _commonRequestIndex, elapsedSesionTime, ( int ) this.ReaderHandle, Name ); Debug.Assert( envelope.PacketType == type ); } if ( VirtualReaderQueue != null ) { lock ( VirtualReaderQueue ) { VirtualReaderQueue.Enqueue( envelope ); } } lock ( PacketQueue ) { PacketQueue.Enqueue( envelope ); } #pragma warning disable 420 // reference to a volatile field is valid for Interlocked call int queueSize = Interlocked.Increment( ref _queueCount ); #pragma warning restore 420 _maxQueueSize = queueSize > _maxQueueSize ? queueSize : _maxQueueSize; if (queueSize > MAX_QUEUE_SIZE) { int loopCount = 0; while (queueSize > TARGET_QUEUE_SIZE && loopCount < 1000) { loopCount++; QueueEvent.Set(); Thread.Sleep(QUEUE_SLEEP_MS); queueSize = _queueCount; } // Write an informational entry to the event log. SysLogger.LogMessage(String.Format("Queue Size = {0}\nMax Queue Size = {1}\nSleep Count = {2}\nPacket Count = {3}", queueSize, _maxQueueSize, loopCount, ProcessedPacketCount)); } return FunctionController.GetActionRequest( ) != FunctionControl.RequestedAction.Abort ? 0 : 1; }
/// <summary> /// /// </summary> /// <param name="PacketBuffer"></param> private bool PacketCallBackFromReader( int readerIndex, Byte[ ] PacketBuffer ) { uint myHandle = this._theReaderID._handle; Debug.Assert( readerIndex == myHandle ); String errorMessage = null; PacketData.PacketBase packet = null; //!! TODO: fix output SysLogger.WriteToLog = ation != Library; PacketData.PacketType type = PacketData.ParsePacket( PacketBuffer, out packet, out errorMessage ); SysLogger.WriteToLog = true; PacketData.PacketWrapper envelope = null; long elapsedSesionTime = ElapsedMilliseconds; if ( packet == null || type == PacketData.PacketType.U_N_D_F_I_N_E_D || errorMessage != null ) { BadPacket badPacket = new BadPacket( ); #pragma warning disable 420 // reference to a volatile field is valid for Interlocked call badPacket.badPacketSequence = System.Threading.Interlocked.Increment( ref _commonBadIndex ); #pragma warning restore 420 badPacket.packetTime = DateTime.UtcNow; badPacket.rawPacketData = PacketBuffer.Clone( ) as byte[ ]; badPacket.errorMessage = errorMessage; using ( MemoryStream data = new MemoryStream( 256 ) ) { badPacket.WriteTo( data ); envelope = new PacketData.PacketWrapper( new PacketData.CommandPsuedoPacket( "BadPacket", data.ToArray( ) ), PacketData.PacketType.U_N_D_F_I_N_E_D ); } envelope.IsPseudoPacket = true; envelope.PacketNumber = badPacket.PacketSequence; envelope.Timestamp = badPacket.packetTime; envelope.ReaderIndex = ( int ) _theReaderID.Handle; envelope.ReaderName = _theReaderID.Name; envelope.CommandNumber = _processedInventoryIndex; envelope.ElapsedTimeMs = elapsedSesionTime; } else { envelope = new PacketData.PacketWrapper( packet, type, PacketBuffer, _commonRequestIndex, elapsedSesionTime, readerIndex, Name ); Debug.Assert( envelope.PacketType == type ); } lock ( PacketQueue ) { PacketQueue.Enqueue( envelope ); } #pragma warning disable 420 // reference to a volatile field is valid for Interlocked call int queueSize = Interlocked.Increment( ref _queueCount ); #pragma warning restore 420 _maxQueueSize = queueSize > _maxQueueSize ? queueSize : _maxQueueSize; //if ( queueSize > MAX_QUEUE_SIZE ) //{ // int loopCount = 0; // while ( queueSize > TARGET_QUEUE_SIZE && loopCount < 1000 ) // { // loopCount++; // QueueEvent.Set( ); // Thread.Sleep( QUEUE_SLEEP_MS ); // queueSize = _queueCount; // } // // Write an informational entry to the event log. // SysLogger.LogMessage( String.Format( "Queue Size = {0}\nMax Queue Size = {1}\nSleep Count = {2}\nPacket Count = {3}", queueSize, _maxQueueSize, loopCount, ProcessedPacketCount ) ); //} return FunctionController.GetActionRequest( ) != FunctionControl.RequestedAction.Abort; }
} // MonitorInventory(Object context, BackgroundWorker worker, int refreshMS, int singulationLimit, int readerCycleLimit) /// <summary> /// Read Tag memory /// </summary> /// <param name="context"></param> /// <param name="worker"></param> /// <param name="refreshMS"></param> /// <returns></returns> //public ReportBase TagAccess(Object context, BackgroundWorker worker, int refreshMS, int r_iTagAccessReqCount)//??把计??//Add LargeRead command public ReportBase TagAccess(Object context, BackgroundWorker worker, int refreshMS, int r_iTagAccessReqCount, int r_iTagAccessReqCountRead)//??把计??//Add LargeRead command { #if DEBUG System.Diagnostics.Debug.WriteLine( String.Format( "{0}() ThreadID = {1}", System.Reflection.MethodInfo.GetCurrentMethod( ).Name, Thread.CurrentThread.ManagedThreadId ) ); #endif if ( IsDisposed ) throw new ObjectDisposedException( "LakeChabotReader" ); if ( Mode != rfidReader.OperationMode.BoundToReader ) return new rfidSimpleReport( context, OperationOutcome.FailByContext, new rfidException( rfidErrorCode.ReaderIsNotBound, "Reader must be bound before tag can be read." ) ); if ( _control.State != FunctionControl.FunctionState.Idle ) return new rfidSimpleReport( context, OperationOutcome.FailByContext, new Exception( "Cannot read the tag, the prior task has not completed" ) ); if ( null == worker ) return new rfidSimpleReport( context, OperationOutcome.FailByApplicationError, new ArgumentNullException( "worker", "BackgroundWorker is required" ) ); if ( refreshMS < MIN_REFRESH_MS || refreshMS > MAX_REFRESH_MS ) return new rfidSimpleReport( context, OperationOutcome.FailByApplicationError, new ArgumentOutOfRangeException( "refreshMS", refreshMS, string.Format( "Value must be between {0} and {1}", MIN_REFRESH_MS, MAX_REFRESH_MS ) ) ); // Tag Read is never in continuous mode rfid.Constants.RadioOperationMode priorMode = ReaderOperationMode; if ( priorMode != rfid.Constants.RadioOperationMode.NONCONTINUOUS ) { ReaderOperationMode = rfid.Constants.RadioOperationMode.NONCONTINUOUS; } _refreshRateMS = refreshMS; _bgdWorker = worker; _requestTagList.Clear( ); _periodTagList.Clear( ); #pragma warning disable 420 // reference to a volatile field is valid for Interlocked call System.Threading.Interlocked.Exchange( ref _commonAccessCount, 0 ); #pragma warning restore 420 rfidOperationReport report = new rfidOperationReport( context, ElapsedMilliseconds, RequestCount, RawAntennaCycleCount, RawInventoryCycleCount, BadPacketCount, CRCErrorCount, RawPacketCount, RawRoundCount, RawInventoryCount, SessionUniqueTags, RequestUniqueTags, CurrentUniqueTags, SessionDuration ); _control.StartAction( ); //_managedAccess.Callback = PacketCallBackFromReader; PerformanceCounter processorUtilizationCounter = null; try { processorUtilizationCounter = new PerformanceCounter( "Processor", "% Processor Time", "_Total", "." ); } catch ( Exception ) { } //ReaderInterfaceThreadClass threadClass = new ReaderInterfaceThreadClass(_managedAccess, (int)ReaderHandle, TagAccessDataSet);//??把计??//Add LargeRead command ReaderInterfaceThreadClass threadClass = new ReaderInterfaceThreadClass(_managedAccess, (int)ReaderHandle, TagAccessDataSet, TagAccessReadSet);//??把计??//Add LargeRead command threadClass._reader = this; // HACK Thread runnerThread = new Thread(new ThreadStart(threadClass.AccessThreadProc)); runnerThread.Name = "AccessTag"; runnerThread.IsBackground = true; runnerThread.Priority = ThreadPriority.BelowNormal; runnerThread.Start( ); int notused = FileHandler.TotalPacketCount; // Make sure the file is created; // Wait for thread to be in ready state int counter = 500; while ( counter-- > 0 && ( int ) ( runnerThread.ThreadState & System.Threading.ThreadState.WaitSleepJoin ) == 1 ) { Thread.Sleep( 10 ); } if ( !runnerThread.IsAlive ) { return new rfidSimpleReport( context, OperationOutcome.FailByApplicationError, new ApplicationException( "BackgroundWorker thread could not be started." ) ); } ReaderRequest readerRequest = new ReaderRequest( ); readerRequest.reader = _theReaderID.Name; #pragma warning disable 420 // reference to a volatile field is valid for Interlocked call readerRequest.requestSequence = System.Threading.Interlocked.Increment( ref _commonRequestIndex ); #pragma warning restore 420 readerRequest.requestName = rfidReader.GetNameForRequest( rfidReader.ReaderRequestType.TagAccess ); readerRequest.startTime = GetSessionRelativeDateTime( report.StartTimeMS ); readerRequest.requestStartTime = report.StartTimeMS; readerRequest.startingPacketCount = RawPacketCount; readerRequest.startingTagCount = RawInventoryCount; MemoryStream data = new MemoryStream( ); readerRequest.WriteTo( data ); PacketData.PacketWrapper pseudoPacket = new PacketData.PacketWrapper( new PacketData.CommandPsuedoPacket( readerRequest.requestName, data.ToArray( ) ), PacketData.PacketType.U_N_D_F_I_N_E_D ); pseudoPacket.IsPseudoPacket = true; pseudoPacket.ReaderName = _theReaderID.Name; pseudoPacket.ReaderIndex = ( int ) _theReaderID.Handle; FileHandler.WritePacket( pseudoPacket ); //clark 2011.2.18 Record that user request data length TagAccessReqCount = r_iTagAccessReqCount; TagAccessReqCountRead = r_iTagAccessReqCountRead;//把计?? DateTime ReportDue = DateTime.Now.AddMilliseconds( refreshMS ); threadClass.StartEvent.Set( ); while ( runnerThread.IsAlive ) { CounterSample sample = CounterSample.Empty; if ( processorUtilizationCounter != null ) { try { sample = processorUtilizationCounter.NextSample( ); } catch ( Exception ) { } } ProcessQueuedPackets( ); QueueEvent.WaitOne( 30, true ); QueueEvent.Reset( ); DateTime now = DateTime.Now; if ( ReportDue.Ticks <= now.Ticks ) { //Debug.WriteLine(String.Format("Reporing Progress Now (Elapsed Milliseconds {0})", ElapsedMilliseconds)); _bgdWorker.ReportProgress( 0, report.GetProgressReport( ElapsedMilliseconds, RequestCount, RawAntennaCycleCount, RawInventoryCycleCount, BadPacketCount, CRCErrorCount, RawPacketCount, RawRoundCount, RawInventoryCount, SessionUniqueTags, RequestUniqueTags, CurrentUniqueTags, SessionDuration ) ); _periodTagList.Clear( ); ReportDue = now.AddMilliseconds( refreshMS ); } if ( !runnerThread.IsAlive ) break; if ( FunctionController.GetActionRequest( ) == FunctionControl.RequestedAction.Abort ) { threadClass.Stop = true; Result abortError = Result.OK; try { abortError = LakeChabotReader.MANAGED_ACCESS.API_ControlAbort(); } catch ( Exception e ) { Debug.WriteLine( String.Format( "Error attempting to abort: {0}", e.Message ) ); } break; } if ( FunctionController.GetActionRequest( ) == FunctionControl.RequestedAction.Stop ) { threadClass.Stop = true; Result stopError = Result.OK; try { stopError = LakeChabotReader.MANAGED_ACCESS.API_ControlCancel(); } catch ( Exception e ) { Debug.WriteLine( String.Format( "Error attempting to stop: {0}", e.Message ) ); } if ( Result.OK != stopError ) { // Try to abort } break; } if ( FunctionController.State == FunctionControl.FunctionState.Paused ) { do { Thread.Sleep( refreshMS ); } while ( FunctionController.State == FunctionControl.FunctionState.Paused ); } if ( !runnerThread.IsAlive ) break; float processorUtilization = 0; if ( processorUtilizationCounter != null && sample != CounterSample.Empty ) { try { CounterSample.Calculate( sample, processorUtilizationCounter.NextSample( ) ); } catch ( Exception ) { } } // Debug.WriteLine(String.Format("Processor Util: {0}", processorUtilization)); if ( processorUtilization > ( float ) TARGET_MAX_USAGE_PERCENT ) _packetSleepMS += SLEEP_ADD_SUBTRACT_MS; else _packetSleepMS -= _packetSleepMS <= MIN_SLEEP_TIME_MS ? 0 : SLEEP_ADD_SUBTRACT_MS; } runnerThread.Join( ); // Get any leftover packets ProcessQueuedPackets( ); if ( LastCommandResult != 0 ) MacClearError( ); OperationOutcome outcome = OperationOutcome.Success; string result = threadClass.Result; if ( !( result == null || result == "" || result == "OK" ) ) { switch ( _control.State ) { case FunctionControl.FunctionState.Stopping: outcome = OperationOutcome.SuccessWithUserCancel; break; case FunctionControl.FunctionState.Aborting: outcome = OperationOutcome.FailByUserAbort; break; // case FunctionControl.FunctionState.Running: // outcome = OperationOutcome.FailByReaderError; // report.ErrorMessage = result; // break; case FunctionControl.FunctionState.Idle: case FunctionControl.FunctionState.Paused: case FunctionControl.FunctionState.Unknown: default: outcome = OperationOutcome.Unknown; break; } } _control.Finished( ); report.OperationCompleted( outcome, ElapsedMilliseconds, RequestCount, RawAntennaCycleCount, RawInventoryCycleCount, BadPacketCount, CRCErrorCount, RawPacketCount, RawRoundCount, RawInventoryCount, SessionUniqueTags, RequestUniqueTags, CurrentUniqueTags, SessionDuration ); // reset the mode ReaderOperationMode = priorMode; if ( EnableLogging ) { //Push data from buffer to file. And clear buffer. PacketLogger.Flush(); } return report; }