private StateChanges Idle()
{
int no_token_timeout = T_NO_TOKEN + 10 * m_TS;
BacnetMstpFrameTypes frame_type;
byte destination_address;
byte source_address;
int msg_length;
while (m_port != null)
{
//get message
GetMessageStatus status = GetNextMessage(no_token_timeout, out frame_type, out destination_address, out source_address, out msg_length);
if (status == GetMessageStatus.Good)
{
try
{
if (destination_address == m_TS || destination_address == 0xFF)
{
switch (frame_type)
{
case BacnetMstpFrameTypes.FRAME_TYPE_POLL_FOR_MASTER:
if (destination_address == 0xFF)
QueueFrame(BacnetMstpFrameTypes.FRAME_TYPE_REPLY_TO_POLL_FOR_MASTER, source_address);
else
{
//respond to PFM
SendFrame(BacnetMstpFrameTypes.FRAME_TYPE_REPLY_TO_POLL_FOR_MASTER, source_address);
}
break;
case BacnetMstpFrameTypes.FRAME_TYPE_TOKEN:
if (destination_address != 0xFF)
{
m_frame_count = 0;
m_sole_master = false;
return StateChanges.ReceivedToken;
}
break;
case BacnetMstpFrameTypes.FRAME_TYPE_TEST_REQUEST:
if (destination_address == 0xFF)
QueueFrame(BacnetMstpFrameTypes.FRAME_TYPE_TEST_RESPONSE, source_address);
else
{
//respond to test
SendFrame(BacnetMstpFrameTypes.FRAME_TYPE_TEST_RESPONSE, source_address);
}
break;
case BacnetMstpFrameTypes.FRAME_TYPE_BACNET_DATA_NOT_EXPECTING_REPLY:
case BacnetMstpFrameTypes.FRAME_TYPE_BACNET_DATA_EXPECTING_REPLY:
//signal upper layer
if (MessageRecieved != null)
{
BacnetAddress remote_address = new BacnetAddress(BacnetAddressTypes.MSTP, 0, new byte[] { source_address });
try
{
MessageRecieved(this, m_local_buffer, MSTP.MSTP_HEADER_LENGTH, msg_length, remote_address);
}
catch (Exception ex)
{
Trace.TraceError("Exception in MessageRecieved event: " + ex.Message);
}
}
if (frame_type == BacnetMstpFrameTypes.FRAME_TYPE_BACNET_DATA_EXPECTING_REPLY)
{
m_reply_source = source_address;
m_reply = null;
m_reply_mutex.Reset();
return StateChanges.ReceivedDataNeedingReply;
}
break;
}
}
}
finally
{
RemoveCurrentMessage(msg_length);
}
}
else if (status == GetMessageStatus.Timeout)
{
/* GenerateToken */
m_PS = (byte)((m_TS + 1) % (m_max_master + 1));
m_NS = (byte)m_TS;
m_token_count = 0;
return StateChanges.GenerateToken;
}
else if (status == GetMessageStatus.ConnectionClose)
{
Trace.WriteLine("No connection", null);
}
else if (status == GetMessageStatus.ConnectionError)
{
Trace.WriteLine("Connection Error", null);
}
else
{
Trace.WriteLine("Garbage", null);
}
}
return StateChanges.Reset;
}