Skip to content

Commit

Permalink
UART RingBuffer overflow and reported size fix (#1436)
Browse files Browse the repository at this point in the history
  • Loading branch information
xjikka authored Nov 27, 2024
1 parent a2f3b02 commit e99ff0c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
11 changes: 10 additions & 1 deletion src/driver/drv_uart.c
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ int g_uart_init_counter = 0;
int g_uart_manualInitCounter = -1;

void UART_InitReceiveRingBuffer(int size){
//XJIKKA 20241122 - Note that the actual usable buffer size must be g_recvBufSize-1,
//otherwise there would be no difference between an empty and a full buffer.
if(g_recvBuf!=0)
free(g_recvBuf);
g_recvBuf = (byte*)malloc(size);
Expand All @@ -130,7 +132,7 @@ void UART_InitReceiveRingBuffer(int size){
int UART_GetDataSize() {
return (g_recvBufIn >= g_recvBufOut
? g_recvBufIn - g_recvBufOut
: g_recvBufIn + (g_recvBufSize - g_recvBufOut) + 1);
: g_recvBufIn + (g_recvBufSize - g_recvBufOut)); //XJIKKA 20241122 fixed buffer size calculation on ring bufferroverflow
}

byte UART_GetByte(int idx) {
Expand All @@ -147,6 +149,13 @@ void UART_AppendByteToReceiveRingBuffer(int rc) {
g_recvBuf[g_recvBufIn++] = rc;
g_recvBufIn %= g_recvBufSize;
}
//XJIKKA 20241122 if the same pointer is reached (in and out), we must also advance
//the outbuffer pointer, otherwise UART_GetDataSize will return g_recvBufSize.
//This way now we always have the last (g_recvBufSize - 1) bytes
if (g_recvBufIn == g_recvBufOut) {
g_recvBufOut++;
g_recvBufOut %= g_recvBufSize;
}
}

#if PLATFORM_BK7231T | PLATFORM_BK7231N
Expand Down
2 changes: 1 addition & 1 deletion src/driver/drv_uart.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ byte UART_GetByte(int idx);
void UART_ConsumeBytes(int idx);
void UART_AppendByteToReceiveRingBuffer(int rc);
void UART_SendByte(byte b);
void UART_InitUART(int baud, int parity);
int UART_InitUART(int baud, int parity);
void UART_AddCommands();
void UART_RunEverySecond();

Expand Down

0 comments on commit e99ff0c

Please sign in to comment.