static teSL_Status eSL_WriteMessage(uint16 u16Type, uint16 u16Length, uint8 *pu8Data)
{
int n;
uint8 u8CRC;
u8CRC = u8SL_CalculateCRC(u16Type, u16Length, pu8Data);
DBG_vPrintf(DBG_SERIALLINK_COMMS, "(%d, %d, %02x)\n", u16Type, u16Length, u8CRC);
if (verbosity >= 10)
{
char acBuffer[4096];
int iPosition = 0, i;
iPosition = sprintf(&acBuffer[iPosition], "Host->Node 0x%04X (Length % 4d)", u16Type, u16Length);
for (i = 0; i < u16Length; i++)
{
iPosition += sprintf(&acBuffer[iPosition], " 0x%02X", pu8Data[i]);
}
INF_vPrintf(T_TRUE, "%s\n", acBuffer);
}
/* Send start character */
if (iSL_TxByte(T_TRUE, SL_START_CHAR) < 0) return E_SL_ERROR;
/* Send message type */
if (iSL_TxByte(T_FALSE, (u16Type >> 8) & 0xff) < 0) return E_SL_ERROR;
if (iSL_TxByte(T_FALSE, (u16Type >> 0) & 0xff) < 0) return E_SL_ERROR;
/* Send message length */
if (iSL_TxByte(T_FALSE, (u16Length >> 8) & 0xff) < 0) return E_SL_ERROR;
if (iSL_TxByte(T_FALSE, (u16Length >> 0) & 0xff) < 0) return E_SL_ERROR;
/* Send message checksum */
if (iSL_TxByte(T_FALSE, u8CRC) < 0) return E_SL_ERROR;
/* Send message payload */
for(n = 0; n < u16Length; n++)
{
if (iSL_TxByte(T_FALSE, pu8Data[n]) < 0) return E_SL_ERROR;
}
/* Send end character */
if (iSL_TxByte(T_TRUE, SL_END_CHAR) < 0) return E_SL_ERROR;
return E_SL_OK;
}
static int iSL_TxByte(bool_t bSpecialCharacter, uint8 u8Data)
{
if(!bSpecialCharacter && (u8Data < 0x10))
{
u8Data ^= 0x10;
if (eSerial_Write(SL_ESC_CHAR) != E_SERIAL_OK) return -1;
//DBG_vPrintf(DBG_SERIALLINK_COMMS, " 0x%02x", SL_ESC_CHAR);
}
//DBG_vPrintf(DBG_SERIALLINK_COMMS, " 0x%02x", u8Data);
return eSerial_Write(u8Data);
}
teSerial_Status eSerial_Write(const uint8 data)
{
int err, attempts = 0;
DBG_vPrintf(DGB_SERIAL, "TX 0x%02x\n", data);
err = write(serial_fd,&data,1);
if (err < 0)
{
if (errno == EAGAIN)/*try again*/
{
for (attempts = 0; attempts <= 5; attempts++)
{
usleep(1000);
err = write(serial_fd,&data,1);
if (err < 0)
{
if ((errno == EAGAIN) && (attempts == 5))
{
ERR_vPrintf(T_TRUE, "Error writing to module after %d attempts(%s)", attempts, strerror(errno));
exit(-1);
}
}
else
{
break;
}
}
}
else
{
ERR_vPrintf(T_TRUE, "Error writing to module(%s)", strerror(errno));
exit(-1);
}
}
return E_SERIAL_OK;
}