WATCHDOG

WATCHDOG

INTRODUCTION

For those embedded systems that can’t be constantly watched by a human, watchdog timers may be the solution.

The watchdog timer is an important device in the embedded system , which is used to develop reliable products. Most of the embedded systems need to be self-reliant in order to restart and restore the system if any software bug disturbs the system. It is not always possible for human operators to wait for rebooting the system for every software problem. The watchdog timer is a piece of hardware that provides ultimate solutions for the real-time industries, which used to detect system abnormalities automatically and to reset the processor.

attiny10-blinker_yamaguchi_flash

 

 

Watchdog Timers(WDT)

A watchdog timer is a piece of hardware that can be used to automatically detect software anomalies and reset the processor if any occur. Generally speaking, a watchdog timer is based on a counter that counts down from some initial value to zero. The embedded software selects the counter’s initial value and periodically restarts it. If the counter ever reaches zero before the software restarts it, the software is presumed to be malfunctioning and the processor’s reset signal is asserted. The processor (and the embedded software it’s running) will be restarted as if a human operator had cycled the power.

Figure 1 shows a typical arrangement. As shown, the watchdog timer is a chip external to the processor. However, it could also be included within the same chip as the CPU. This is done in many micro-controllers. In either case, the output from the watchdog timer is tied directly to the processor’s reset signal.

image1

kicking the dog

The process of restarting the watchdog timer’s counter is sometimes called “kicking the dog.” The appropriate visual metaphor is that of a man being attacked by a vicious dog. If he keeps kicking the dog, it can’t ever bite him. But he must keep kicking the dog at regular intervals to avoid a bite. Similarly, the software must restart the watchdog timer at a regular rate, or risk being restarted.

Advantage of Watchdog Timers:

  • Resets automatically without human intervention.

  • Detects the errors in the program and reboot the system

  • Cost sensitive

  • Saves the time and money

  • No need to place the employers to monitor the software debugs.

  • Increases the system performance.

SUMMARY

A number of considerations must go into any design that uses a watchdog as a monitor. Once the timeout period is determined, the system software must be analyzed to determine where to locate the watchdog restart instructions. For an effective design, the number of watchdog restarts should be kept to a minimum, and some consideration should be given to the likelihood of incorrectly executing a restart. As mentioned previously, some system software is too convoluted or data-dependent to ensure that all software flow paths are covered by a watchdog restart. This may dictate that a self-diagnostic software approach might be required. If there is an expected failure mechanism such as a periodic EMI burst or power supply glitch, the watchdog timeout should consider this period.

 

 

Pushpraj Kumar 🙂

MySQL C – API programming

MySQL C – API programming

MySQL is a leading open source database management system. It is a multi user, multithreaded database management system. MySQL is especially popular on the web.

Basic Structure of C Programs that uses MySQL C API 1. All programs must include <mysql/mysql.h> as the last include.2. Define MYSQL type variable. NOTE: THERE CAN BE ONLY ONE MYSQL VARIABLE.3. Initialize MYSQL type variable with mysql_init()4. Load any options, if required, by using mysql_options(). If you don’t need don’t call. You can call this fuction multiple times if you require. If you call this, call this before mysql_real_connect() and after mysql_init().5. Connect by calling mysql_real_connect()

6. Call the business logic and MySQL API’s

7. Close the MYSQL type variable.

mysqlwithc

 

Template of program

#include <mysql/mysql.h><return_type> <function_name>(parameters)

{

MYSQL mysql; mysql_init(&mysql);

mysql_options(&mysql,MYSQL_OPT_COMPRESS,0);      

/*call only if required otherwise omit*/

mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,”Pushpraj”);        

 /*call only if required otherwise omit*/

mysql_real_connect(….);      

/* now call other API’s*/

mysql_close(&mysql);

}

 Compiling and Running in UNIX :- 

To Compile :-  $gcc mysql_app.c -o mysql_app -I/usr/local/include -L/usr/local/lib/mysql –lmysqlclient

To Run :-  $./mysql_app

Examples:-

1. Test the connection.

#include </usr/include/mysql/my_global.h>

#include </usr/include/mysql/mysql.h>

int main(int argc, char **argv)

{

printf(“MySQL client version: %s\n”, mysql_get_client_info());

  exit(0);

}

Description:-  “mysql_get_client_info()”, this mysql function collects the version information of mysql.

2. Create table and insert data into table.

#include <my_global.h>

#include <mysql.h>

void finish_with_error(MYSQL *con){

  fprintf(stderr, “%s\n”, mysql_error(con));

  mysql_close(con);

  exit(1);       

}

 

int main(int argc, char **argv)

{

  MYSQL *con = mysql_init(NULL);

  if (con == NULL) {

      fprintf(stderr, “%s\n”, mysql_error(con));

      exit(1);

  } 

if (mysql_real_connect(con, “192.168.2.50”, “username”, “password”,”db-Name”, port-No, NULL, 0) == NULL)

  {

      finish_with_error(con);

  }   

 

  if (mysql_query(con, “DROP TABLE IF EXISTS Dell”)) {

      finish_with_error(con);

  }

  if (mysql_query(con, “CREATE TABLE Dell(Id INT, Name TEXT, Price INT)”)) {     

      finish_with_error(con);

  }

  if (mysql_query(con, “INSERT INTO Dell VALUES(1,’vostro14′,26042)”)) {

      finish_with_error(con);

  }

  if (mysql_query(con, “INSERT INTO Dell VALUES(2,’inspiron15′,37000)”)) {

      finish_with_error(con);

  }

  if (mysql_query(con, “INSERT INTO Dell VALUES(3,’inspiron16′,40000)”)) {

      finish_with_error(con);

  }

  if (mysql_query(con, “INSERT INTO Dell VALUES(4,’ vostro15′,29000)”)) {

      finish_with_error(con);

  }

  if (mysql_query(con, “INSERT INTO Dell VALUES(5,’express’,69000)”)) {

      finish_with_error(con);

  }

  mysql_close(con);

  exit(0);

}

Description:- mysql_init, allocates/intialises a Mysql object suitable for mysql_real_connect()establishes a connection to the database.We provide connection handler, host name, username ,password ,database name, port number , unix socket and client flag.

3. Create connection with Database & fetch the records.

#include <my_global.h>

#include <mysql.h>

void finish_with_error(MYSQL *con)

{

  fprintf(stderr, “%s\n”, mysql_error(con));

  mysql_close(con);

  exit(1);       

}

int main(int argc, char **argv)

{     

  MYSQL *con = mysql_init(NULL);

  if (con == NULL)

  {

      fprintf(stderr, “mysql_init() failed\n”);

      exit(1);

  } 

 

  if (mysql_real_connect(con, “192.168.2.50”, “username”, “password”,”db-Name”, port-No, NULL, 0) == NULL)

  {      finish_with_error(con);  }  

 

  if (mysql_query(con, “SELECT * FROM Dell”))

  {      finish_with_error(con);  }  

  MYSQL_RES *result = mysql_store_result(con);

  if (result == NULL)

  {      finish_with_error(con);  }  

  int num_fields = mysql_num_fields(result);

  MYSQL_ROW row;

  while ((row = mysql_fetch_row(result)))

  {

      for(int i = 0; i < num_fields; i++)

      {

          printf(“%s “, row[i] ? row[i] : “NULL”);

      }

      printf(“\n”);

  }

  mysql_free_result(result);

  mysql_close(con);

  exit(0);

}

Description:-

  • Create a connection:: mysql_real_connect(con, “192.168.2.50”, “username”, “password”,”db-Name”, port-No, NULL, 0)
  • Execute query:: mysql_query(con, “SELECT * FROM Dell”)
  • Get the result set:: MYSQL_RES *result = mysql_store_result(con)
  • Fetch all available rows one by one :: row = mysql_fetch_row(result)
  • Free the result set:: mysql_free_result(result)
  • Close the connection:: mysql_close(con);

Thanks

Pushpraj Kumar

How to create Backup using C,Best Practices while creating CSV or txt file using C

How to create   Backup  using c?

Backup   is  the  process  of  taking  the  backup of  Data  and  saving it on another location  for future Reference. This process includes

  1. Creating   CSV files or txt files  of   data on
    1. Daily basis
    2. Hourly basis.
    3. By particular Date.
  2. Making zip or creating   tar for all created the files.
  3. Uploading created tar file on server or on ftp or on our drive
  4. Again we have to download that .tar file in our application.
  5. Unzip that file to get all CSV/TXT file.
  6. Read all the Data from CSV/TXT file.

 

How to create CSV/TXT  File?

To create CSV/TXT File by using C –language, first we have to decide

  1. What  is  the  content  of  CSV  file.(Table Values)
  2. From where  we can  get those content.(In our case Database)
  3. Where we are going to store these files.(Output file Location)
  4. What is the Name of Our CSV File?(CSV file Name)

So  in  our Case to get the data from Database we have to do,

  1. Open  the Database.

int open = openDB(&db, (char *)conf->dbPath, conf->dbConnectionTimeout);

  1. Check  or validate  that  Db is  opened  or  not?

If( open != 0){   closeDb();           }

  1. Create your  SQL Query to get the data from Tables.

sprintf(query,”select * from <table-name> where <condition>”);

  1. Do  File Handling , create  the file and variable.

createFile(filePath)

char *writeData=NULL;

writeData = calloc(1024,sizeof(char));

  1. Fire the SQL Query on Specific Tables and get the value in variable.

result = executeQuery((char *)query, &db, &stmt);

strcat(writeData,sqlite3_column_name(*stmt,col));

 

  1. Do the Formatting while Data is appending in variable.

if(col >= cols -1)

{

       strcat(writeData,”\n

   }

  else

  {

        strcat(writeData,”,”);

   }

  1. Then check file is present or not , if not then create it .

if(!isFilePresent(filePath))

 {

    if(createFile(filePath))

      {

             printf(“File (%s) created!\n”,filePath);

       }

 }

  1. Lastly write the value of variable in File.

status = appendFile(filePath, &writeData);

  1. Release the memory of variable.

free(writeData);

  1. Finalize your Statement.

sqlite3_finalize(stmt);

  1. Close the Database.

closeDB(&db);

 

Flow of  creation.

  1. Read the value of DB Path, Opfilepath, log path from pushagentconfig file.
  2. Read   the value   from backlogconfig  file  ,Date and Time, FTP related information.
  3. Append both into single variable.
  4. According to that variable  fire query on database to get the timestamp
  5. After that according to that Starting timestamp   and ending timestamp.
  6. Then we are reading the type ,
  7. According to  given type we assign the value of interval variable day(86400),Hour(3600),

(last-start) timestamp

  1. After getting all the detail run the  for loop from start to end timestamp. by   assigning the interval.
  2. Append the   opFilepath, date and filename.
  3. Prepare the query and call  the  function Creating CSV  by passing Filename, Cols, stmt and length
  4. Then CreatingCSV   function called, in that function we declare one variable with some memory and appended all the data’s in that variable.
  5. Write the formatted content   of variable in file.
  6. Releasing the memory. By   this way one table data come into one csv   file with header.
  7. Again   for next table new filename, query will be created and the same process is   going on.
  8. After every single File creation, we are finalizing the statement making the query-variable content to null to reuse it.
  9. Lastly closing the Database.