CAN frame over MQTT (need to convert hex string to byte array) - c

I am implementing a MQTT communication. I want to send CAN frames over MQTT through a graphical interfaces (realized in python). I am able to send messages from the GUI to one topic and I am able to see messages arrived on the same topic (using paho library) when I use the board. The function is below and the topic is diagnostic_request/topic:
void onMessageArrived
(
const char* topic,
const uint8_t* payload,
size_t payloadLen,
void* context
)
{
//LE_FATAL("The publisher received a message!");
//GIMP
char payloadStr[payloadLen + 1];
memcpy(payloadStr, payload, payloadLen);
payloadStr[payloadLen] = '\0';
LE_INFO("Received message! topic: \"%s\", payload: \"%s\"", topic, payloadStr);
//GIMP principio di conversione
if (strcmp(subscribeTopic, topic)==0)
LE_INFO("Sei sul topic di richiesta diagnostica!");
can_send();
}
At this point I have a difficulty. My can_send function (that works!) is:
int can_send(void)
{
const char* subscribeTopic = "diagnostic_request/topic";
LE_FATAL_IF(
mqtt_Subscribe(MQTTSession, subscribeTopic, MQTT_QOS0_TRANSMIT_ONCE) != LE_OK,
"failed to subscribe to %s",
subscribeTopic);
LE_INFO("Subscribed to topic (%s)", subscribeTopic);
int nbytesWrite;
// USE SEND STANDARD FRAME
frameWrite.can_id = 0x750; //codice identificativo di una richiesta diagnostica per centralina simulata
frameWrite.can_id &= CAN_SFF_MASK;
frameWrite.can_dlc = 8;
//strcpy((char *)frameWrite.data, "MGATE");
frameWrite.data[0] = 0x03;
frameWrite.data[1] = 0x22;
frameWrite.data[2] = 0xF1;
frameWrite.data[3] = 0x89;
frameWrite.data[4] = 0x00;
frameWrite.data[5] = 0x00;
frameWrite.data[6] = 0x00;
frameWrite.data[7] = 0x00;
if ((nbytesWrite = write(sdw, &frameWrite, sizeof(frameWrite))) != sizeof(frameWrite))
{
canwrite = false;
LE_INFO ("Writing error, nbytesWrite = %d", nbytesWrite);
return SOCK_WRITING_ERROR;
}
canwrite = true;
return 0;
}
So I have to call can_send in the onMessageArrived function when is statement is ok. I am able to see when I send a publish on diagnostic_request/topic. The only problem is to send the payloadStr value to the can_send function and unpackage it in the frameWrite.data[]. Can someone help me to understand how to modify the can_send function in order that the values
frameWrite.data[0] = 0x03;
frameWrite.data[1] = 0x22;
frameWrite.data[2] = 0xF1;
frameWrite.data[3] = 0x89;
frameWrite.data[4] = 0x00;
frameWrite.data[5] = 0x00;
frameWrite.data[6] = 0x00;
frameWrite.data[7] = 0x00;
are values that I send through mqtt in the payloadStr? I send a string of 8 bytes but I can't unpackage it.
Any help will be appreciated
Regards

Taking the approach of "write the test first".....
int convertNybble (char const hex)
{
if (hex >= '0' && hex <= '9')
{
return hex - '0';
}
else if (hex >= 'a' && hex <= 'f')
{
return 10 + (hex - 'a');
}
else if (hex >= 'A' && hex <= 'F')
{
return 10 + (hex - 'A');
}
return -1; // invalid hex character
}
#define ERR_NOT_EVEN_NUMBER_OF_DIGITS -1
#define ERR_STRING_TOO_LONG -2
#define ERR_INVALID_CHAR -3
int preparePayload(char const* hexString, unsigned char* canBuffer, size_t const bufLen)
{
size_t hexLen = strlen(hexString);
if (0 != (hexLen % 2))
{
// Expect an even number of digits.
return ERR_NOT_EVEN_NUMBER_OF_DIGITS;
}
size_t payloadLen = hexLen / 2;
// buffer will contain payload-length, followed by payload data.
// so payloadLen+1 must be able to fit into bufLen - fail if payloadLen+1 > bufLen, which is the same as payloadLen >= bufLen
if (payloadLen >= bufLen)
{
// will not be able to fit the decoded string into the payload buffer
return ERR_STRING_TOO_LONG;
}
unsigned char* bufEnd = canBuffer;
bufEnd += bufLen;
*canBuffer++ = (unsigned char)payloadLen;
while (payloadLen > 0)
{
payloadLen--;
int hexDigit[2];
hexDigit[0] = convertNybble(*hexString++);
hexDigit[1] = convertNybble(*hexString++);
if ((hexDigit[0] < 0) || (hexDigit[1] < 0))
{
return ERR_INVALID_CHAR;
}
*canBuffer++ = (hexDigit[0] << 4) | hexDigit[1];
}
// fill any leftovers with zero
while (canBuffer < bufEnd)
{
*canBuffer++ = 0;
}
return (0);
}
int performTests()
{
char const* testStr[5] =
{
"12345",
"0123456789ABCDEF",
"#ABC",
"0AF9",
"0123456789ABCD"
};
#define MARKER 0xFF
#define PAYLOAD_LEN 8
unsigned char payload[PAYLOAD_LEN+1];
payload[PAYLOAD_LEN] = MARKER;
int decodeResult = preparePayload(testStr[0], payload, PAYLOAD_LEN);
if (ERR_NOT_EVEN_NUMBER_OF_DIGITS != decodeResult) { return -1; } //not expected result
decodeResult = preparePayload(testStr[1], payload, PAYLOAD_LEN);
if (ERR_STRING_TOO_LONG != decodeResult) { return -1; }
decodeResult = preparePayload(testStr[2], payload, PAYLOAD_LEN);
if (ERR_INVALID_CHAR != decodeResult) { return -1; }
// here we are checking the character decoding
decodeResult = preparePayload(testStr[3], payload, PAYLOAD_LEN);
if (0 != decodeResult) { return -1; }
if (payload[0] != 2) { return -1; }
if (payload[1] != 0x0A) { return -1; }
if (payload[2] != 0xF9) { return -1; }
if (payload[3] != 0) { return -1; }
if (payload[7] != 0) { return -1; }
// payload contains - 02 0a f9 00 00 00 00 00 00
// here we are checking the limit of the payload capacity
decodeResult = preparePayload(testStr[4], payload, PAYLOAD_LEN);
if (0 != decodeResult) { return -1; }
// payload contains - 07 01 23 45 67 89 ab cd
// check we haven't overrun the buffer
if (payload[8] != MARKER) { return -1; }
// all tests pass
return 0;
}
int main()
{
int testResult = performTests();
return testResult;
}
You can then embody the decoder as follows:
convertNybble, preparePayload etc as above....
int canbusSend(unsigned char const* canbusPayload)
{
//etc
// - copy payloadBytes to frameWrite.data....
//etc
}
void onMessageArrived
(
const char* topic,
const uint8_t* mqttPayload,
size_t payloadLen,
void* context
)
{
#define CANBUS_PAYLOAD_BUFFER_LEN 8
unsigned char canbusPayload[CANBUS_PAYLOAD_BUFFER_LEN];
int decodeResult = preparePayload((char const*)mqttPayload, canbusPayload, CANBUS_PAYLOAD_BUFFER_LEN);
if (0 == decodeResult)
{
int canbusSendResult = canbusSend(canbusPayload);
// TODO : report error if failed
}
else
{
//TODO : report error
}
}

Related

how can I read socket by blocking&none-multiplexing&sync mode?

I want to repeatedly request one specific url by maximum performance. I copied below source from github, but I think it isn't optimized for my case, so I have to tune it.
Which Option is best in my case?
block vs non-block
sync vs async
I think non-multiplexing is right, so I've to change select() function to the other one. Is this right?
char response[RESPONSE_SIZE + 1];
char *p = response, *q;
char *end = response + RESPONSE_SIZE;
char *body = 0;
enum {
length, chunked, connection
};
int encoding = 0;
int remaining = 0;
while (1) {
fd_set reads;
FD_ZERO(&reads);
FD_SET(server, &reads);
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 200;
if (FD_ISSET(server, &reads)) {
int bytes_received = SSL_read(ssl, p, end - p);
p += bytes_received;
*p = 0;
if (!body && (body = strstr(response, "\r\n\r\n"))) {
*body = 0;
body += 4;
printf("Received Headers:\n%s\n", response);
q = strstr(response, "\nContent-Length: ");
if (q) {
encoding = length;
q = strchr(q, ' ');
q += 1;
remaining = strtol(q, 0, 10);
} else {
q = strstr(response, "\nTransfer-Encoding: chunked");
if (q) {
encoding = chunked;
remaining = 0;
} else {
encoding = connection;
}
}
printf("\nReceived Body:\n");
}
if (body) {
if (encoding == length) {
if (p - body >= remaining) {
printf("%.*s", remaining, body);
break;
}
} else if (encoding == chunked) {
do {
if (remaining == 0) {
if ((q = strstr(body, "\r\n"))) {
remaining = strtol(body, 0, 16);
if (!remaining) goto finish;
body = q + 2;
} else {
break;
}
}
if (p - body >= remaining) {
printf("%.*s", remaining, body);
body += remaining + 2;
remaining = 0;
}
} while (!remaining);
}
} //if (body)
} //if FDSET
} //end while(1)
finish:
buffer[0] = '\0';
printf("\nClosing socket...\n");

Command line argument causing heap corruption

I'm trying to write a buffer using C, it was supposed to take in contents from an input file and output it to another text file. However, when I try to debug it in Visual Studio 2019, it always trigger a breakpoint at if ((fi = fopen(argv[1],"r")) == NULL){...} of my test file, it also detected a critical error of C0000374. My command line argument is buffer.exe ass1.pls a
My test file : platy_bt.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include "buffer.h"
/*check for ANSI C compliancy */
#define ANSI_C 0
#if defined(__STDC__)
#undef ANSI_C
#define ANSI_C 1
#endif
/* Declaration of an error printing function with
* variable number of arguments
*/
void err_printf(char *fmt, ...);
/* Declaration of a buffer contents display function */
void display (Buffer *ptr_Buffer);
long get_filesize(char *fname);
int main(int argc, char **argv){
pBuffer ptr_Buffer; /* pointer to Buffer structure */
FILE *fi; /* input file handle */
int loadsize = 0; /* the size of the file loaded in the buffer */
int ansi_c = !ANSI_C; /* ANSI C compliancy flag */
char symbol; /* symbol read from input file */
/* Check if the compiler option is set to compile ANSI C */
/* __DATE__, __TIME__, __LINE__, __FILE__, __STDC__ are predefined preprocessor macros*/
if(ansi_c){
err_printf("Date: %s Time: %s",__DATE__, __TIME__);
err_printf("ERROR: Compiler is not ANSI C compliant!\n");
exit(1);
}
/* missing file name or/and mode parameter */
if (argc <= 2){
err_printf("\nDate: %s Time: %s",__DATE__, __TIME__);
err_printf("\nRuntime error at line %d in file %s\n", __LINE__, __FILE__);
err_printf("%s\b\b\b\b%s%s",argv[0],": ","Missing parameters.");
err_printf("Usage: platybt source_file_name mode");
exit(1);
}
/* create a source code input buffer */
switch(*argv[2]){
case 'f': case 'a': case 'm': break;
default:
err_printf("%s%s%s",argv[0],": ","Wrong mode parameter.");
exit(1);
}
/*create the input buffer */
ptr_Buffer = b_allocate(0,0,*argv[2]);
if (ptr_Buffer == NULL){
err_printf("%s%s%s",argv[0],": ","Cannot allocate buffer.");
exit(1);
}
/* open the source file */
if ((fi = fopen(argv[1],"r")) == NULL){
err_printf("%s%s%s%s",argv[0],": ", "Cannot open file: ",argv[1]);
exit (1);
}
/* load a source file into the input buffer */
printf("Reading file %s ....Please wait\n",argv[1]);
loadsize = b_load (fi,ptr_Buffer);
if(loadsize == RT_FAIL_1)
err_printf("%s%s%s",argv[0],": ","Error in loading buffer.");
/*if the input file has not been completely loaded, find the file size and print the last symbol loaded */
if (loadsize == LOAD_FAIL){
printf("The input file %s %s\n", argv[1],"has not been completely loaded.");
symbol = (char)fgetc(fi);
printf("Last character read from the input file is: %c %d\n", symbol, symbol);
printf("Input file size: %ld\n", get_filesize(argv[1]));
}
/* close source file */
fclose(fi);
/* display the contents of the input buffer */
display(ptr_Buffer);
/* compact the buffer
* add end-of-file character (EOF) to the buffer
* display again
*/
if(!b_compact(ptr_Buffer,EOF)){
err_printf("%s%s%s",argv[0],": ","Error in compacting buffer.");
}
display(ptr_Buffer);
/* free the dynamic memory used by the buffer */
b_free(ptr_Buffer);
/* make the buffer invalid
It is not necessary here because the function terminates anyway,
but will prevent run-time errors and crashes in future expansions
*/
ptr_Buffer = NULL;
/*return success */
return (0);
}
/* error printing function with variable number of arguments*/
void err_printf( char *fmt, ... ){
/*Initialize variable list */
va_list ap;
va_start(ap, fmt);
(void)vfprintf(stderr, fmt, ap);
va_end(ap);
/* Move to new line */
if( strchr(fmt,'\n') == NULL )
fprintf(stderr,"\n");
}
void display (Buffer *ptr_Buffer){
printf("\nPrinting buffer parameters:\n\n");
printf("The capacity of the buffer is: %d\n",b_capacity(ptr_Buffer));
printf("The current size of the buffer is: %d\n", b_addcoffset(ptr_Buffer));
printf("The operational mode of the buffer is: %d\n",b_mode(ptr_Buffer));
printf("The increment factor of the buffer is: %lu\n",b_incfactor(ptr_Buffer));
printf("The first symbol in the buffer is: %c\n", b_addcoffset(ptr_Buffer)?*b_location(ptr_Buffer, 0):' ');
printf("The value of the flags field is: %04hX\n",ptr_Buffer->flags);
printf("\nPrinting buffer contents:\n\n");
b_rewind(ptr_Buffer);
if (!b_print(ptr_Buffer,1)) printf("empty buffer\n");
}
long get_filesize(char *fname){
FILE *input;
long flength;
input = fopen(fname, "r");
if(input == NULL){
err_printf("%s%s","Cannot open file: ",fname);
return 0;
}
fseek(input, 0L, SEEK_END);
flength = ftell(input);
fclose(input);
return flength;
}
<!-- -->
My buffer.c
#include "buffer.h";
#include <string.h>;
#include <stdlib.h>;
Buffer* b_allocate(short init_capacity, char inc_factor, char o_mode) {
char* characterArray;
if(init_capacity <0 || init_capacity >= SHRT_MAX) {
printf("Capacity exceed the limit, must be between 0 and %d.", SHRT_MAX);
return NULL;
}
else {
pBuffer bufferStructure = (pBuffer) calloc(init_capacity, sizeof(Buffer));
if (init_capacity == 0) {
init_capacity = DEFAULT_INIT_CAPACITY;
if (o_mode=='a' || o_mode== 'm') {
inc_factor = DEFAULT_INC_FACTOR;
bufferStructure->inc_factor = inc_factor;
}
else {
if (o_mode== 'f') {
inc_factor = 0;
bufferStructure->inc_factor = inc_factor;
}
}
characterArray = (char *) malloc(DEFAULT_INIT_CAPACITY);
}
else {
characterArray = (char*) malloc(init_capacity);
}
bufferStructure->cb_head = characterArray;
if (inc_factor == 0 && init_capacity != 0) {
bufferStructure->mode = 0;
bufferStructure->inc_factor = 0;
}
switch (o_mode) {
case 'f':
bufferStructure->mode = 0;
bufferStructure->inc_factor = 0;
break;
case 'a':
if (inc_factor >= 1 && inc_factor <= 255) {
bufferStructure->mode = 1;
bufferStructure->inc_factor = inc_factor;
break;
}
else {
if (inc_factor != 0) {
return NULL;
break;
}
}
case 'm':
if (inc_factor >= 1 && inc_factor <= 100) {
bufferStructure->mode = -1;
bufferStructure->inc_factor = inc_factor;
break;
}
else {
if (inc_factor != 0) {
return NULL;
break;
}
}
}
bufferStructure->capacity = 200;
bufferStructure->flags = DEFAULT_FLAGS;
bufferStructure->addc_offset = 0;
bufferStructure->getc_offset = 0;
bufferStructure->markc_offset;
return bufferStructure;
}
}
pBuffer b_addc(pBuffer const pBD, char symbol) {
int inc_factor = pBD->inc_factor - '0';
int newCapacity = 0;
int availableSpace =0;
long newIncrement = 0;
pBD->flags &= RESET_R_FLAG;
char* ptr;
if (pBD->addc_offset <= pBD->capacity) {
pBD->cb_head[pBD->addc_offset] = symbol;
pBD->addc_offset++;
return pBD;
}
else {
switch (pBD->mode) {
case 0:
return NULL;
break;
case 1:
newCapacity = pBD->capacity + inc_factor;
if (newCapacity > 0 && newCapacity < (SHRT_MAX - 1)) {
if (realloc(pBD->cb_head, newCapacity)) {
pBD->flags |= SET_R_FLAG;
pBD->cb_head[pBD->addc_offset] = symbol;
pBD->addc_offset++;
pBD->capacity = (short)newCapacity;
ptr = realloc(pBD->cb_head, newCapacity);
pBD->cb_head = ptr;
return pBD;
}
else {
return NULL;
}
}
else {
if (newCapacity > 0 && newCapacity >= (SHRT_MAX - 1)) {
newCapacity = SHRT_MAX - 1;
if (realloc(pBD->cb_head, newCapacity)) {
pBD->flags |= SET_R_FLAG;
pBD->cb_head[pBD->addc_offset] = symbol;
pBD->addc_offset++;
pBD->capacity = (short) newCapacity;
ptr = realloc(pBD->cb_head, newCapacity);
pBD->cb_head = ptr;
return pBD;
}
else {
return NULL;
}
}
else {
if (newCapacity <= 0) {
return NULL;
}
}
}
break;
case -1:
if (pBD->capacity >= SHRT_MAX -1) {
return NULL;
}
else {
availableSpace = SHRT_MAX - 1 - pBD->capacity;
newIncrement = (long)(availableSpace * inc_factor/100);
newCapacity = (short)(pBD->capacity + newIncrement);
if (newCapacity >= SHRT_MAX-1) {
newCapacity = SHRT_MAX - 1;
}
else {
if (newCapacity > 0 && newCapacity < SHRT_MAX - 1) {
if (realloc(pBD->cb_head, newCapacity)) {
pBD->flags |= SET_R_FLAG;
pBD->cb_head[pBD->addc_offset] = symbol;
pBD->addc_offset++;
pBD->capacity = (short)newCapacity;
ptr = realloc(pBD->cb_head, newCapacity);
pBD->cb_head = ptr;
return pBD;
}
else {
return NULL;
}
}
}
}
break;
}
}
}
int b_clear(Buffer* const pBD) {
pBD->addc_offset = 0;
pBD->getc_offset = 0;
pBD->markc_offset = 0;
pBD->flags = DEFAULT_FLAGS;
return 1;
}
void b_free(Buffer* const pBD) {
free(pBD->cb_head);
free(pBD);
}
short b_capacity(Buffer* const pBD) {
if (pBD->capacity != 0) {
return pBD->capacity;
}
else {
return -1;
}
}
short b_addcoffset(Buffer* const pBD) {
if (pBD->addc_offset != 0 ) {
return pBD->addc_offset;
}
else {
return -1;
}
}
short b_markc(pBuffer const pBD, short mark) {
if (mark<0 || mark > pBD->addc_offset) {
return -1;
}
else {
pBD->markc_offset = mark;
return pBD->markc_offset;
}
}
short b_getcoffset(Buffer* const pBD) {
if (pBD->getc_offset >=0) {
return pBD->getc_offset;
}
else {
return -1;
}
}
int b_mode(Buffer* const pBD) {
if (pBD->mode) {
return pBD->mode;
}
else {
printf("Not found");
}
}
size_t b_incfactor(Buffer* const pBD) {
unsigned char inc_factor = pBD->inc_factor;
size_t inc_factor_value = inc_factor;
if (pBD->inc_factor) {
return inc_factor_value;
}
else {
return 0x100;
}
}
char b_getc(Buffer* const pBD) {
if (pBD->getc_offset > pBD->addc_offset) {
return -2;
}
else {
if (pBD->getc_offset == pBD->addc_offset) {
pBD->flags &= RESET_EOB;
pBD->flags |= SET_EOB;
pBD->getc_offset++;
return 0;
}
else {
pBD->flags &= RESET_EOB;
pBD->getc_offset++;
return pBD->cb_head[pBD->getc_offset];
}
}
}
int b_print(Buffer* const pBD, char nl) {
while (b_eob(pBD)==0) {
printf("%c", b_getc(pBD));
}
if (nl != 0) {
printf("\n");
}
return nl;
}
int b_eob(Buffer* const pBD) {
if ((pBD->flags & CHECK_EOB) > 0) {
return pBD->flags & CHECK_EOB;
}
else {
if ((pBD->flags & CHECK_EOB) == 0) {
return 0;
}
else {
return -1;
}
}
}
char b_rflag(Buffer* const pBD) {
if ((pBD->flags & CHECK_R_FLAG) > 0) {
return pBD->flags & CHECK_R_FLAG ;
}
else {
if ((pBD->flags & CHECK_R_FLAG) == 0) {
return 0;
}
else {
return -1;
}
}
}
int b_isfull(Buffer* const pBD) {
if (pBD->addc_offset == pBD->capacity) {
return 0;
}
else {
if (pBD->addc_offset < pBD->capacity) {
return 1;
}
else {
return -1;
}
}
}
int b_isempty(Buffer* const pBD) {
if (pBD->addc_offset == 0) {
return 1;
}
else {
if (pBD->addc_offset > 0) {
return 0;
}
else {
return -1;
}
}
}
char* b_location(Buffer* const pBD, short loc_offset) {
if ( loc_offset > pBD->addc_offset) {
return NULL;
}
else {
return &pBD->cb_head[loc_offset];
}
}
int b_load(FILE* const fi, Buffer* const pBD) {
while (!feof(fi)) {
char symbol = (char)fgetc(fi);
if (b_addc(pBD, symbol) != NULL) {
}
else {
ungetc(symbol, fi);
return LOAD_FAIL;
}
}
return pBD->addc_offset;
}
Buffer* b_compact(Buffer* const pBD, char symbol) {
short newCapacity = pBD->addc_offset+1;
char * ptr = (char *)realloc(pBD, newCapacity);
pBD->cb_head = ptr;
pBD->capacity = (short)newCapacity;
pBD->cb_head[pBD->addc_offset] = symbol;
pBD->addc_offset++;
pBD->flags &= RESET_R_FLAG;
pBD->flags |= SET_R_FLAG;
return pBD;
}
short b_retract(Buffer* const pBD) {
if (pBD->getc_offset <= 0) {
return -1;
}
else {
pBD->getc_offset--;
return pBD->getc_offset;
}
}
short b_reset(Buffer* const pBD) {
if (pBD->getc_offset > pBD->addc_offset || pBD->markc_offset < 0) {
return -1;
}
else {
pBD->getc_offset = pBD->markc_offset;
}
return pBD->getc_offset;
}
int b_rewind(Buffer* const pBD) {
pBD->getc_offset = 0;
pBD->markc_offset = 0;
return 0;
}
<!-- -->
My buffer.h
#ifndef BUFFER_H_
#define BUFFER_H_
/*#pragma warning(1:4001) *//*to enforce C89 type comments - to make //comments an warning */
/*#pragma warning(error:4001)*//* to enforce C89 comments - to make // comments an error */
/* standard header files */
#include <stdio.h> /* standard input/output */
#include <malloc.h> /* for dynamic memory allocation*/
#include <limits.h> /* implementation-defined data type ranges and limits */
/* constant definitions */
#define RT_FAIL_1 (-1) /* operation failure return value 1 */
#define RT_FAIL_2 (-2) /* operation failure return value 2 */
#define LOAD_FAIL (-2) /* load fail return value */
#define DEFAULT_INIT_CAPACITY 200 /* default initial buffer capacity */
#define DEFAULT_INC_FACTOR 15 /* default increment factor */
/* You should add your own constant definitions here */
/* Add your bit-masks constant definitions here */
#define DEFAULT_FLAGS 0xFFF9
#define SET_EOB 0x0002
#define RESET_EOB 0xFFFD
#define CHECK_EOB 0x0002
#define SET_R_FLAG 0x0004
#define RESET_R_FLAG 0xFFFB
#define CHECK_R_FLAG 0x0004
#define DEFAULTZ 0x0000 /* 0000 0000 0000 0000 */
#define SET_LSB 0x0001 /* 0000 0000 0000 0001 */
#define RESET_LSB 0xFFFE /* 1111 1111 1111 1110 */
#define CHK_LSB 0x0001 /* 0000 0000 0000 0001 */
/* user data type declarations */
typedef struct BufferDescriptor {
char *cb_head; /* pointer to the beginning of character array (character buffer) */
short capacity; /* current dynamic memory size (in bytes) allocated to character buffer */
char inc_factor; /* character array increment factor */
char mode; /* operational mode indicator*/
unsigned short flags; /* contains character array reallocation flag and end-of-buffer flag */
short addc_offset; /* the offset (in chars) to the add-character location */
short getc_offset; /* the offset (in chars) to the get-character location */
short markc_offset; /* the offset (in chars) to the mark location */
} Buffer, *pBuffer;
/*typedef Buffer *pBuffer;*/
/* function declarations */
/*
Place your function declarations here.
Do not include the function header comments here.
Place them in the buffer.c file
*/
Buffer* b_allocate(short init_capacity, char inc_factor, char o_mode);
pBuffer b_addc(pBuffer const pBD, char symbol);
int b_clear(Buffer* const pBD);
void b_free(Buffer* const pBD);
int b_isfull(Buffer* const pBD);
short b_addcoffset(Buffer* const pBD);
short b_capacity(Buffer* const pBD);
short b_markc(pBuffer const pBD, short mark);
int b_mode(Buffer* const pBD);
size_t b_incfactor(Buffer* const pBD);
int b_load(FILE* const fi, Buffer* const pBD);
int b_isempty(Buffer* const pBD);
char b_getc(Buffer* const pBD);
int b_eob(Buffer* const pBD);
int b_print(Buffer* const pBD, char nl);
Buffer* b_compact(Buffer* const pBD, char symbol);
char b_rflag(Buffer* const pBD);
short b_retract(Buffer* const pBD);
short b_reset(Buffer* const pBD);
short b_getcoffset(Buffer* const pBD);
int b_rewind(Buffer* const pBD);
char* b_location(Buffer* const pBD, short loc_offset);
If I try to countinue with debugging, it output : Unhandled exception at 0x774DFA1D (ntdll.dll) in buffer.exe: 0xC0000374: A heap has been corrupted (parameters: 0x7751B960). and Unhandled exception at 0x7743C5D7 (ntdll.dll) in buffer.exe: 0xC0000005: Access violation reading location 0x00985A7A.. If I build this and run it in release mode, it cause assertion violation.

Arduino - Serial Communication not working

I'm having problem getting in to the second Serial.available loop of my code located in the Package. Please, let me know, if you see anything wrong with the code.
Arduino Code
Inputs:
1. "Package" -> I get +1 back from the Serial Monitor
2. "5&12!23!34!59!70!" -> I get 0 back from the Serial Monitor. For this one, I'm supposed to see, 5 12 23 34 59 70
Please, let me know, if you see anything wrong in this code and why is the Serial.available not functional in the Package?
String incoming;
String readIncoming;
int i=0;
typedef struct {
int npins;
int addr[512];
}
measureList;
measureList list;
void setup() {
Serial.begin(9600);
Serial.println("Serial conection started");
incoming = ""; list.npins = 6;
}
void loop() {
while(Serial.available() > 0) {
incoming = Serial.readString();
if(incoming == "HI") { Serial.println("Steven"); }
if(incoming == "SampleAll") { SampleAll(); }
if(incoming == "Package") { Serial.println("+1"); Package(); }
}
}
void Package(void)
{
while(1)
{
if(Serial.available()>0 & i<= list.npins)
{
char recieved = Serial.read();
if (recieved != '&' & i == 0){incoming = incoming + recieved;}
if (recieved == '&' & i == 0){list.npins = incoming.toInt(); Serial.println(list.npins); incoming=""; i = 1;}
if (recieved != '!' & recieved != '&' & i > 0){incoming = incoming + recieved; }
if (recieved == '!' & recieved != '&' & i > 0){ list.addr[i] = incoming.toInt(); Serial.println(list.addr[i]);incoming = ""; i = i + 1;}
if (i == list.npins) {break;}
}
}
}

STM32F103RB Nucleo transmit and receive usart

I have some problems with transmiting and receiving using usart. First informations that I want transmit are writen to circle buffer. Then indormations are send but some informations are lost.
Variables
enum {
BUF_SIZE = 100
};
char BUF_T[BUF_SIZE], BUF_R[BUF_SIZE];
uint8_t R_EMPTY = 0, R_BUSY = 0, T_EMPTY = 0, T_BUSY = 0;
Transmiting
void Send(void) {
uint8_t index = T_EMPTY;
for (int i = 0; i < 10; i++) {
BUF_T[index] = i+'0';
index++;
if (index >= BUF_SIZE) {
index = 0;
}
}
__disable_irq();
if (T_BUSY == T_EMPTY
&& __HAL_UART_GET_FLAG(&huart2,UART_FLAG_TXE) == SET) {
T_EMPTY = index;
T_BUSY++;
uint8_t tmp = BUF_T[T_BUSY];
if (T_BUSY >= BUF_SIZE) {
T_BUSY = 0;
}
HAL_UART_Transmit_IT(&huart2, (uint8_t*) &tmp, 1);
} else {
T_EMPTY = index;
}
__enable_irq();
}
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) {
//if (huart->Instance == USART2) {
if (T_BUSY != T_EMPTY) {
__disable_irq();
T_BUSY++;
uint8_t tmp = BUF_T[T_BUSY];
if (T_BUSY >= BUF_SIZE) {
T_BUSY = 0;
}
HAL_UART_Transmit_IT(&huart2, (uint8_t*) &tmp, 1);
__enable_irq();
}else {
Send();
}
//}
}
Screen from hterm
On picture can be seen that from time to time one char is lost. I don't understant why?
Regarding receiving can somebody tell mi if it OK?
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
//if (huart->Instance == USART2) {
uint8_t tmp = BUF_R[R_EMPTY];
R_EMPTY++;
if (R_EMPTY >= BUF_SIZE) {
R_EMPTY = 0;
}
HAL_UART_Receive_IT(&huart2, (uint8_t*) &tmp, 1);
//}
}

Segmentation fault: 11 in c program (dynamic memory allocation)

I have the following piece of code which allocates some memory.
Some used initialisations:
#define MEM_POOL_SIZE 600
typedef struct {
size size;
mem_status status;
} mem_chunk_header;
unsigned char* ptr;
When I call this function as follows
ma_malloc(600)
it should return NULL.
But I get a segmentation fault: 11.
I tried using GDB, but then I run into different problems...
void* ma_malloc(size tsize)
{
mem_chunk_header header;
unsigned char* searchPtr = ptr;
int oldSize = 0;
int stop = 0;
while(((searchPtr-ptr)/sizeof(unsigned char) < MEM_POOL_SIZE) && (stop >= 0))
{
if((*searchPtr = 0xFF) && ((getSize(searchPtr) >= (tsize))))
{
stop = -1;
}
else
{
if(getSize(searchPtr) == 0)
{
return NULL;
}
else
{
searchPtr += (getSize(searchPtr)+header.size);
}
}
}
if(stop == 0)
{
printf("%s\n","No free space available");
return NULL;
}
else
{
oldSize = getSize(searchPtr);
//Update header
*searchPtr = 0xAA;
*(searchPtr+1) = (unsigned char) ((tsize)/256);
*(searchPtr+2) = (unsigned char) ((tsize)%256);
//Update footer
updateFooter(searchPtr);
//New overhead
unsigned char* newPtr = (searchPtr+(getSize(searchPtr))+header.size);
unsigned char* nextPtr = (unsigned char*) (searchPtr+oldSize+header.size);
int leftoverSize = ((nextPtr-newPtr)/sizeof(unsigned char));
if(leftoverSize == 0)
{
//Do nothing
}
else
if(leftoverSize <= header.size)
{
unsigned int tempSize = getSize(searchPtr) + leftoverSize;
//Update header
*(searchPtr+1) = (unsigned char) (tempSize/256);
*(searchPtr+2) = (tempSize%256);
//footer
updateFooter(searchPtr);
}
else
{
//Update header
*newPtr = 0xFF;
*(newPtr+1) = (unsigned char) ((leftoverSize-header.size)/256);
*(newPtr+2) = (unsigned char) ((leftoverSize-header.size)%256);
//Update footer
updateFooter(newPtr);
}
}
return searchPtr;
}
I've been looking at this for a while now, but I can't see why it is giving me this error.

Resources