Firmware over the air algorithm - c

I'm doing firmware over the air update, but I don't know how long will it take to download the firmware and upgrade the device. So what I have tried is to go into infinite loop while(1) and check if the firmware is finished upgrading. That fcked up the devices on the street... The other option is to do timeout but for how long? It's unpredictable.
The question is, how to ensure realiability and do it correctly?
Here is what I have tried:
signed char wait_commands(vu32 timeout, char*command, const char *result_command, int valueToCheck)
{
char *result = NULL;
timer_1sec = 0;
while(timer_1sec < timeout)
{
if( GSMGetString(tempdata, 5) == OK)
{
result = strstr(tempdata, command);
if ( result != NULL)
{
int value;
if ( result_command != NULL)
{
if( valueToCheck != -1)
{
if (sscanf(result, result_command, &value) > 0)
{
if (value != valueToCheck)
{
return FEHLER;
}
else
{
return OK;
}
}
}
}
else
{
return OK;
}
}
}
}
return FEHLER;
}
u8 isUpdated(void)
{
char *currentFirmwareVersion = "BG96MAR02A07M1G_01.019.01.019";
while (GSMCommand("+QGMR", tempdata, 20) != AT_OK)
;
if (strncmp(tempdata, currentFirmwareVersion, strlen(currentFirmwareVersion))==0)
{
isBG96Updated = 1;
}
else
{
isBG96Updated = 0;
}
return isBG96Updated;
}
signed char updateBG96FirmwareVersion(vu32 timeout)
{
char *url = "\"http://10.10.169.1/dfota/upgrade.bin\"";
char command[150] = {0};
signed char res = FEHLER;
if(isUpdated())
return OK;
sprintf(command, "AT+QFOTADL=%s", url);
PutStringUART(UART_GSM, command);
PutCharUART(UART_GSM, '\r');
res = wait_commands(timeout, "\"FOTA\",\"HTTPSTART\"", NULL, -1);
res = wait_commands(timeout, "\"FOTA\",\"END\"", "\"FOTA\",\"END\",%d", 0);
return res;
}

I have no experience with the Quectel BG96 chip, specifically, but it appears to support DFOTA, and there is also an official guide that you can view/download here.
This guide contains the AT commands necessary to upgrade the firmware over-the-air. Plus, I think it may clarify your doubts about the upgrade procedure.

Related

Correct closing DBus connection

Could you explain how to close DBus connection correctly/ Below is my variant:
int P_dbus_proto_init(DBusConnection **dbus_conn, const char *name, dbus_MessageHandler mh, int num_rules, const char **rules)
{
int rc = 0;
DBusError dbus_err;
dbus_error_init(&dbus_err);
*dbus_conn = dbus_bus_get(DBUS_BUS_SYSTEM, &dbus_err);
if (dbus_error_is_set(&dbus_err))
{
FILTER_LOG_ERROR("Connection Error (%s)\n", dbus_err.message);
dbus_error_free(&dbus_err);
return -1;
}
rc = dbus_bus_request_name(*dbus_conn, name, DBUS_NAME_FLAG_REPLACE_EXISTING, &dbus_err);
if (dbus_error_is_set(&dbus_err) || (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != rc))
{
FILTER_LOG_ERROR("Connection Error (%s)\n", dbus_err.message);
dbus_error_free(&dbus_err);
return -1;
}
dbus_connection_add_filter(*dbus_conn, mh, NULL, NULL);
if (dbus_error_is_set(&dbus_err))
{
FILTER_LOG_ERROR("Add Filter Error (%s)\n", dbus_err.message);
dbus_error_free(&dbus_err);
return -1;
}
for(int i = 0; i < num_rules; i++)
{
dbus_bus_add_match(*dbus_conn, rules[i], &dbus_err);
if (dbus_error_is_set(&dbus_err))
{
FILTER_LOG_ERROR("Match Error (%s)\n", dbus_err.message);
dbus_error_free(&dbus_err);
return -1;
}
}
return 0;
}
static const char* rules[] = {
"interface='acl_management.method'",
};
And how I use it:
DBusConnection *dbus_conn;
if (P_dbus_proto_init(&dbus_conn, "com.bla-bla-bla.acl", P_dbus_proto_job, 1, rules) == 0)
{
while (dbus_connection_read_write_dispatch(dbus_conn, 5000))
{
if(p_ctx->execute.n_nl_exit_app == 0) //My app can be terminated by n_nl_exit_app flag
{
break;
}
}
dbus_connection_close(dbus_conn);// Should I do it or not?
dbus_connection_unref(dbus_conn);// Should I do it or not?
}
From dbus.freedesktop.org docs I cannot understand how to do it correctly. I can terminate my app by turn on 'n_nl_exit_app' flag - should I call dbus_connection_closein this case?

Why is config_read_file() returning config_false?

I have been using libconfig for config files in a project. When I remove the double quotes from sources by source_to_use, config_read_file() returns config_true and also has a syntax error. The syntax error will cause my getter for the source_to_use option to go to the default case. Also because of this my getter for the source array, will also go to the else case. Could this just be me making a simple syntax error with the libconfig format?
This is the config file I am using:
#config for walld
#colors
colors = TRUE;
source_to_use: "sources";
default:
[
"/home/seth/Pictures/kimi.png"
];
sources:
[
"/home/seth/.walld/persona",
"/home/seth/.walld/image-urls"
];
This is the function I have reading it:
settings* read_config(const char* config_file, const char* home_dir) {
settings* options = malloc(sizeof(settings));
config_t config;
config_setting_t* setting;
const char* source;
int colors;
config_init(&config);
if (config_read_file(&config, config_file) == CONFIG_TRUE) {
config_destroy(&config);
return NULL;
}
if (config_lookup_bool(&config, "colors", &colors)) {
options->colors = colors;
}
else {
options->colors = 0;
}
if (config_lookup_string(&config, "source_to_use", &source)) {
//NOP
}
else {
source = "default";
}
setting = config_lookup(&config, source);
if (setting != NULL) {
int count = config_setting_length(setting);
linked_node* entry_point = add_node_to_list(NULL, NULL);
linked_node* current = entry_point;
options->sources = entry_point;
for (int i = 0; i < count; i++) {
char* item = config_setting_get_string_elem(setting, i);
current = add_node_to_list(current, item);
}
}
else {
options->sources = malloc(sizeof(linked_node));
int char_count = snprintf(NULL, 0, "%s%s", home_dir, "/.walld/images");
if (char_count <= 0) {
//tough luck
abort();
}
char* default_folder = malloc(char_count + 1U);
if (default_folder == NULL) {
//tough luck
abort();
}
snprintf(default_folder, char_count + 1U, "%s%s", home_dir, "/.walld/images");
options->sources->image = default_folder;
}
config_destroy(&config);
return options;
}
In your read_config function, your first if is:
if (config_read_file(&config, config_file) == CONFIG_TRUE) {
config_destroy(&config);
return NULL;
}
The sense of the if is reversed, so you'll return a NULL if the read of the file is valid.
So, you want to reverse the sense of this if:
if (config_read_file(&config, config_file) != CONFIG_TRUE) {
config_destroy(&config);
return NULL;
}
Or you could [probably] use:
if (config_read_file(&config, config_file) == CONFIG_FALSE) {

C invalid memory access

I am new to C language and I'm trying to compare the characters a pointer points. But when I inspect my code with Intel Inspector for memory errors I am getting invalid memory access errors in this function.
Inspectors says that these two lines cause this.
for (int i = 0; currentPathParameter[i] != '\0'; ++i) {
if (currentPathParameter[i] == '/')
}
Whole function:
bool asteriskControl(char* currentPathParameter) {
int directory = 1;
for (int i = 0; currentPathParameter[i] != '\0'; ++i) {
if (currentPathParameter[i] == '/')
directory++;
}
if (asteriskCounter > directory) {
printf("Can not use '*' operator for the folder that the program is currently in.");
return false;
}
return true;}
This is the line that I call the function.
noAsteriskError = asteriskControl(currentPath);
I am passing currentPath to function and I initialize it here.
char* currentPath = NULL;
char erdem[12] = { 'e','r','d','e','m','/','h','a','k','a','n','\0' };
currentPath = strdup(erdem);
Minimal code example:
int asteriskCounter = 1;
bool asteriskControl(char* currentPathParameter) {
int directory = 1;
for (int i = 0; currentPathParameter[i] != '\0'; ++i) {
if (currentPathParameter[i] == '/')
directory++;
}
if (asteriskCounter > directory) {
printf("Can not use '*' operator for the folder that the program is currently in.");
return false;
}
return true;}
int main() {
char* currentPath = NULL;
char erdem[] = "erdem/hakan";
currentPath = strdup(erdem);
bool noAsteriskError = false;
if (asteriskCounter > 0)
if (currentPath != NULL) {
noAsteriskError = asteriskControl(currentPath);
}
else {
noAsteriskError = false;
}
else {
noAsteriskError = true;
}
return 0;}
Any help is appreciated.

Allocation of buffer in C

I am trying to create buffer to store infinity size of symbols.
I have this structure:
typedef struct buffer {
int bufferSize;
int literalSize;
int allocatedSize;
char *bufferPtr;
} bufferStruct;
In my file.h.
I have also functions for buffer:
bufferStruct *BufferInitialize(int size) {
bufferStruct *tempBuff;
tempBuff = (bufferStruct *)malloc(sizeof(bufferStruct));
if (tempBuff == NULL) {
exit(99); // MEMORY_ERROR
}
tempBuff->bufferSize = size;
tempBuff->literalSize = 0;
tempBuff->bufferPtr = NULL;
tempBuff->allocatedSize = 0;
return (tempBuff);
}
int addToBuffer(bufferStruct *buffer, char c) {
if (buffer == NULL) {
return 99; // MEMORY_ERROR
}
if (buffer->allocatedSize > buffer->literalSize) {
buffer->bufferPtr[buffer->literalSize++] = c;
} else {
buffer->bufferPtr = realloc(buffer->bufferPtr, (buffer->allocatedSize + buffer->bufferSize) * sizeof(char));
if (buffer->bufferPtr == NULL) {
return 99; // MEMORY_ERROR
}
buffer->allocatedSize += buffer->bufferSize;
buffer->bufferSize <<= 1; // bS = bS * 2
buffer->bufferPtr[buffer->literalSize++] = c;
}
return 0;
}
int bufferDestroy(bufferStruct *buffer) {
if (buffer == NULL) {
return 99; // MEMORY_ERROR
}
free(buffer->bufferPtr);
free(buffer);
return 0;
}
In my file.c I am trying to create buffer:
token *getNextToken(token *tokenT) {
token *actualToken = NULL;
char *bufferData = NULL;
int charFromFile;
eState state = stateInit;
bufferStruct *bufferT = NULL;
while ((charFromFile = fgetc(fp))) {
switch (state) {
case stateInit: {
if (isdigit(charFromFile)) {
bufferT = BufferInitialize(8);
addToBuffer(bufferT, charFromFile);
state = stateInt;
} else
if (isalpha(charFromFile) || (charFromFile == '_')) {
state = stateId;
bufferT = BufferInitialize(16);
addToBuffer(bufferT, charFromFile);
} else
if (isspace(charFromFile)) {
state = stateInit;
... some more conditions ... it's similar, a lot.
case stateInt: {
if (isdigit(charFromFile)) {
state = stateInt;
addToBuffer(bufferT, charFromFile);
} else
if ((charFromFile == 'e') || (charFromFile == 'E')) {
state = stateExp;
addToBuffer(bufferT, charFromFile);
} else
if (charFromFile = '.') {
state = stateDouble;
addToBuffer(bufferT, charFromFile);
} else {
bufferData = bufferT->bufferPtr;
//strcpy(actualToken->content, bufferData);
addToBuffer(bufferT, '\0');
bufferDestroy(bufferT);
actualToken->type = tokenInt;
return actualToken;
}
} break;
... other similar cases ...
}
}
}
The problem is when I am trying to do this, Visual studio give me error:
One or more multiply defined symbols found
Also gives me
already defined in main.obj
for every function I have.
I don't see the way out. What am I doing wrong ?
There are multiple issues in your code:
You should not put code in header files. The function BufferInitialize should not be located in file.h unless it is defined inline.
The test while (c = fgetc(fp)) is incorrect: you use an assignment as a test expression, it is very error prone, you should at least parenthesize the assignment expression, and probably test for EOF instead of '\0': while ((c = fgetc(fp)) != EOF). Furthermore, c must be defined as an int. Post actual code, not pseudo-code.
You initialize tempBuff->bufferSize to a potentially non zero value, whereas the allocatedSize is 0 and the buffer is unallocated. This seems incorrect.
There could be many more issues in your actual code, we cannot see what the code, how can be tell you about those? Always post a complete, compilable code that demonstrates the problem.

managing if statements

gcc 4.4.3 c89
I have some functions that initialize some hardware and return either true or false. If false then I have to uninitialize in the reverse order.
However, my code is looking very untidy with all the if statements.
For example each function can return either true of false. This is a sample. As you can see the code looks very untidy. I am just looking for any advice on how I can clean it up to make it more manageable and if possible scable?
Many thanks for any advice,
if(init_A() == TRUE) {
if(init_B() == TRUE) {
if(init_C() == TRUE) {
if(init_D() == TRUE) {
if(init_E() == TRUE) {
/* ALL STARTED OK */
}
else {
uninit_A();
uninit_B();
uninit_C();
uninit_D();
}
}
else {
uninit_A();
uninit_B();
uninit_C();
}
}
else {
uninit_A();
uninit_B();
}
}
else {
/* Failed to initialize B */
uninit_B();
}
}
else {
/* Failed to start */
}
if(init_A() != TRUE) {
goto EndA;
}
if(init_B() != TRUE) {
goto EndB;
}
if(init_C() != TRUE) {
goto EndC;
}
if(init_D() != TRUE) {
goto EndD;
}
if(init_E() != TRUE) {
goto EndE;
}
...
return;
EndE: uninitD();
EndD: uninitC();
EndC: uninitB();
EndB: uninitA();
EndA: return;
This is quite a common problem, where the "init" steps correspond to things like malloc() or lock(), and the "uninit" steps correspond to things like free() and unlock(). It is particularly an issue when resources have to be deallocated in strictly the reverse order in which they were allocated.
This is one case where the use of goto is justified:
int somefunc()
{
int retval = ERROR;
if (init_A() != TRUE)
goto out_a;
if (init_B() != TRUE)
goto out_b;
if (init_C() != TRUE)
goto out_c;
if (init_D() != TRUE)
goto out_d;
if (init_E() != TRUE)
goto out_e;
/* ALL STARTED OK */
/* ... normal processing here ... */
retval = OK;
uninit_E();
out_e:
uninit_D();
out_d:
uninit_C();
out_c:
uninit_B();
out_b:
uninit_A();
out_a:
return retval;
}
I would loop through an array of function pointers, call the functions in the loop, then if that function returned false, perform the corresponding uninit_* function.
Here's an example:
void (*inits[5]) (void);
void (*uninits[4]) (void);
int main(void) {
inits[0] = init_A;
inits[1] = init_B;
inits[2] = init_C;
inits[3] = init_D;
inits[4] = init_E;
uninits[0] = uninit_A;
uninits[1] = uninit_B;
uninits[2] = uninit_C;
uninits[3] = uninit_D;
for(int i = 0; i < 5; i++) {
if((*inits[i])() != TRUE) {
int j = (i < 4) ? i : 4;
while(j--) {
(*uninits[j])();
}
break;
}
}
return 1;
}
BOOL a = FALSE, b = FALSE, c = FALSE, d = FALSE, e = FALSE;
if ( (a = init_A()) && (b = init_B()) && (c = init_C()) && (d = init_D()) && (e = init_E()) )
{
}
else
{
if ( e ) uninit_E();
if ( d ) uninit_D();
if ( c ) uninit_C();
if ( b ) uninit_B();
if ( a ) uninit_A();
}
uninit functions are called in direct order, as in your code. If reverse order is required, just change this.
If your uninit_* functions can detect whether or not they need to do anything you can simply:
if (!init_A() || !init_B() || !init_C() || !init_D() )
{
uninit_C();
uninit_B();
uninit_A();
return FALSE;
}
Is that "reverse order"? For me reverse order is like this:
void uninit(int from) {
switch (from) {
/* ... */
case 3: uninit_C(); /* fall_through */
case 2: uninit_B(); /* fall_through */
case 1: uninit_A(); /* fall_through */
case 0: break;
}
}
And the init process would go like this
int count = 0;
if (init_A()) {
count++;
if (init_B()) {
count++;
if(init_C()) {
count++;
if(init_D()) {
count++;
if(init_E()) {
count++;
}
}
}
}
}
if (count == 5) /* ALL OK */;
uninit(count);
Limited understanding of C at work here, if you do decide to downvote, please tell me why.
#include <stdio.h>
int init_a() { return 1; }; // succeed
int init_b() { return 1; }; // succeed
int init_c() { return 0; }; // fail
void uninit_a() { printf("uninit_a()\n"); }
void uninit_b() { printf("uninit_b()\n"); }
void uninit_c() { printf("uninit_c()\n"); }
typedef struct _fp {
int (*init)();
void (*uninit)();
} fp;
int init() {
fp fps[] = {
(fp){&init_a, &uninit_a},
(fp){&init_b, &uninit_b},
(fp){&init_c, &uninit_c}
};
unsigned int i = 0, j;
for(; i < sizeof(fps) / sizeof(fp); ++i) {
if(!(*fps[i].init)()) {
for(j = 0; j < i; ++j) {
(*fps[j].uninit)();
}
return -1;
}
}
return 0;
}
int main() {
init();
return 0;
}
Output:
uninit_a()
uninit_b()
This is the same order that the code in original post would be executed in, but you may want to reverse it (inner loop).
What you perhaps are looking for is "scope bound resource management". C++ traditionally does that with constructors/destructors. But there is a way to do that differently (in C99 as well as in C++) by abusing the for-statement a bit. I wrote something up upon this line here:
scope bound resource management with for scopes.
I've not got a compiler to try this out. But something like this might work?
int (*init[])() = {init_A, init_B, init_C, init_D, init_E};
int (*uninit[])() = {uninit_A, uninit_B, uninit_C, uninit_D, uninit_E};
int main()
{
initfunction(init, 0)
return 0;
}
void initfunction((*init[])(), pos)
{
if(init[pos]() == TRUE)
initfunction(init, pos++)
else
return;
uninit[pos]();
}
int X = 0;
if(init_A() == TRUE) {
X++;
if(init_B() == TRUE) {
X++;
if(init_C() == TRUE) {
X++;
if(init_D() == TRUE) {
X++;
if(init_E() == TRUE) {
X++;
/* ALL STARTED OK */
}
}
}
}
}
/* You said reverse order which I took to mean this,
* though your did not do it this way. */
switch (X) {
case 5:
return SUCCESS;
case 4:
uninit_D();
case 3:
uninit_C();
case 2:
uninit_B();
case 1:
uninit_A();
return FAILURE;
}
Something I find myself doing to prevent myself from making errors in code like this is:
static int do_A(void);
static int do_B(void);
static int do_C(void);
static int do_D(void);
static int do_A(void) {
if (init_A() == FALSE) {
return FALSE;
}
if (do_B() == FALSE) {
uninit_A();
return FALSE;
}
return TRUE;
}
...
static int do_D(void) {
return init_D();
}
All of the other do_ functions should look similar to do_A.

Resources