writeLineEx(0, 1, "<%BASE_FILE_NAME%> OnModbusConfirmRegisters: Set %d registers beginning with 0x%X", (response[2]<<8) + response[3], (response[0]<<8) + response[1]);
}
void OnModbusReceive(byte buffer[], dword size)
{
// Test transaction identifier?
// Test unit/device identifier?
char str[20*3];
byte x[2];
byte mbuffer[8192];
dword i;
struct ModbusApHeader mbap;
memcpy_n2h(mbap, buffer);
if (size < 8) // No complete Modbus Application Header
{
writeLineEx(0, 2, "<%BASE_FILE_NAME%> OnModbusReceive Error: Tcp packet is too short: Length = %d", size);
return;
}
if (size != 6 + mbap.Length) // TCP packet not as large as specified in length field
{
writeLineEx(0, 2, "<%BASE_FILE_NAME%> OnModbusReceive Error: Size of Tcp packet is incorrect: Length = %d, has to be %d", size, 6 + mbap.Length);
return;
}
if (mbap.Protocol != 0) // Protocol is not Modbus (0x0000)
{
writeLineEx(0, 2, "<%BASE_FILE_NAME%> OnModbusReceive Error: Tcp packet is no Modbus packet: Protocol = %d", mbap.Protocol);
return;
}
// MBAP Header is OK :) Go on
if (mbap.FuncCode > 0x80) // Oh no, we got a exception!
{
switch(buffer[08]) // Let's have a look at the reason
{
case 0x01: // Illegal function code: Implementation failure!
writeLineEx(0, 3, "<%BASE_FILE_NAME%> OnModbusReceive Exception: Illegal function code (0x01). The function code %d is unknown by the server.", buffer[7] & 0x0F);
return;
case 0x02: // Illegal data address: Configuration failure!
writeLineEx(0, 3, "<%BASE_FILE_NAME%> OnModbusReceive Exception: Illegal data address (0x02). Please check your configuration!");
return;
case 0x03: // Illegal data value: Depends.
writeLineEx(0, 3, "<%BASE_FILE_NAME%> OnModbusReceive Exception: Illegal data value (0x03).");
return;
case 0x04: // Server failure: We can't do anything about that, can we?
writeLineEx(0, 3, "<%BASE_FILE_NAME%> OnModbusReceive Exception: Server failure (0x04). The server failed during execution.");
return;
case 0x05: // Acknowledge: That's ok.
writeLineEx(0, 1, "<%BASE_FILE_NAME%> OnModbusReceive Exception: Acknowledge (0x05). The server simply needs more time to generate the response.");
return;
case 0x06: // Server busy: We should resend the request.
writeLineEx(0, 3, "<%BASE_FILE_NAME%> OnModbusReceive Exception: Server busy (0x06). The request could not be accepted.");
return;
case 0x0A: // Gateway problem: We don't have gateways :)
writeLineEx(0, 3, "<%BASE_FILE_NAME%> OnModbusReceive Exception: Gateway problem (0x0A). Gateway paths not available.");
return;
case 0x0B: // Gateway problem: We don't have gateways :)
writeLineEx(0, 3, "<%BASE_FILE_NAME%> OnModbusReceive Exception: Gateway problem (0x0B). The targeted device failed to respond.");
return;
}
}
// Extract the PDU for further processing
size -= 8;
for (i = 0; i < size; i++)
mbuffer[i] = buffer[i+8];
// Let's give the PDU to the corresponding function