ihex.c

00001 #include <unistd.h>
00002 #include <strings.h>
00003 #include <stdio.h>
00004 #include <string.h>
00005 
00006 #include <inttypes.h>
00007 
00008 int hexfile_parse(char *line, unsigned int *type, unsigned int *addr, unsigned char *buffer)
00009 {
00010         unsigned int row_len = 0;
00011         unsigned int row_index = 7;
00012         unsigned int i;
00013         int tmp;
00014         
00015         uint8_t cksum = 0;
00016         int retval = 0;
00017         
00018         retval = sscanf(line, ":%2x%4x%2x", &row_len, addr, type);
00019         
00020         cksum += row_len;
00021         cksum += *addr >> 8;
00022         cksum += *addr & 0xFF;
00023         cksum += *type;
00024         
00025         i = 0;
00026         if (retval == 3)
00027         {
00028                 while(i < row_len)
00029                 {
00030                         
00031                         if (sscanf(&line[row_index], "%2x", &tmp) == 1)
00032                         {
00033                                 cksum += tmp;
00034                                 buffer[i++] = (unsigned char) tmp;
00035                                 row_index += 2;
00036                         }
00037                         else return -1;
00038                 }
00039                 if (sscanf(&line[row_index], "%2x", &tmp) == 1)
00040                 {
00041                         if ((cksum + (uint8_t) tmp) == 0) return row_len;
00042                 }
00043         }
00044         return -1;
00045 }
00046 
00047 int hexfile_out(char *line, unsigned int type, unsigned int address, unsigned char *data, unsigned int bytes)
00048 {
00049         uint8_t cksum = 0;
00050         uint8_t i = 0;
00051         char tmp[8];
00052         
00053         sprintf(line, ":%2.2X%4.4X%2.2X", bytes, address, type);        
00054         cksum -= bytes;
00055         cksum -= address >> 8;
00056         cksum -= address & 0xFF;
00057         cksum -= type;
00058 
00059         for (i=0; i<bytes; i++)
00060         {
00061                 sprintf(tmp, "%2.2X", data[i]);
00062                 strcat(line, tmp);
00063                 cksum -= data[i];
00064         }
00065         sprintf(tmp, "%2.2X\r\n", cksum);
00066         strcat(line, tmp);
00067         
00068         return strlen(line);
00069 }
00070 

Generated on Mon Apr 11 14:23:37 2011 for Contiki 2.5 by  doxygen 1.6.1