SWUpdate library to be used with RPC.
Fork of SWUpdate by
SWUpdate.cpp
- Committer:
- WiredHome
- Date:
- 2014-04-21
- Revision:
- 0:e221363f7942
- Child:
- 1:208de08b1a19
File content as of revision 0:e221363f7942:
// Software Update via Ethernet from forum - // http://mbed.org/forum/mbed/topic/1183/ #include "mbed.h" #include "SWUpdate.h" #include "HTTPClient.h" #include "HTTPText.h" #include "HTTPFile.h" #include <stdio.h> extern "C" void mbed_reset(); #define DEBUG "SWup" #include <cstdio> #if (defined(DEBUG) && !defined(TARGET_LPC11U24)) #define DBG(x, ...) std::printf("[DBG %s %3d] "x"\r\n", DEBUG, __LINE__, ##__VA_ARGS__); #define WARN(x, ...) std::printf("[WRN %s %3d] "x"\r\n", DEBUG, __LINE__, ##__VA_ARGS__); #define ERR(x, ...) std::printf("[ERR %s %3d] "x"\r\n", DEBUG, __LINE__, ##__VA_ARGS__); #define INFO(x, ...) std::printf("[INF %s %3d] "x"\r\n", DEBUG, __LINE__, ##__VA_ARGS__); #else #define DBG(x, ...) #define WARN(x, ...) #define ERR(x, ...) #define INFO(x, ...) #endif bool SoftwareUpdate(const char *url, const char * name, Reboot_T reboot) { HTTPClient http; //http.setTimeout( 15000 ); char fqurl[150]; // fully qualified url char verfn[32]; // local version file char fwfn[32]; bool result = false; // many things can go wrong, assume failure //char *verfn = "/local/VERSION.TXT"; char buf[50]; INFO("SoftwareUpdate(%s,%s)", url, name); snprintf(verfn, 32, "/local/%s.ver", name); /* Read installed version string */ int inst_ver = -1; FILE *fv = fopen(verfn, "r"); if (fv) { fscanf(fv, "%d", &inst_ver); fclose(fv); } INFO(" Installed version: %d", inst_ver); /* Download latest version string */ HTTPText server_ver("test message"); snprintf(fqurl, 150, "%s/%s.txt", url, name); HTTPResult r = http.get(fqurl, buf, sizeof(buf)); if (r == HTTP_OK) { int latest_ver = -1; INFO(" read {%s}", buf); sscanf(buf, "%d", &latest_ver); INFO(" web version: %d", latest_ver); if (inst_ver != latest_ver) { INFO(" Downloading new firmware..."); sprintf(fwfn, "/local/%s%d.BIN", name, latest_ver); snprintf(fqurl, 150, "%s/%s.bin", url, name); HTTPFile latest(fwfn); r = http.get(fqurl, &latest); if (r == HTTP_OK) { sprintf(fwfn, "/local/%s%d.BIN", name, inst_ver); INFO(" Firmware downloaded, removing old version (%s).", fwfn); // if (remove(fwfn)) { ERR(" *** Failed to remove old version. ***"); // } INFO("Updating stored version number."); fv = fopen(verfn, "w"); if (fv) { int fr = fputs(buf, fv); if (fr < 0) { ERR("Failed (%d) to update stored version number.", fr); fclose( fv ); } else { fclose( fv ); if (reboot == AUTO_REBOOT) { WARN("Resetting...\n"); wait_ms(200); mbed_reset(); } result = true; } } } else { WARN("Couldn't download lastest firmware.\n"); } } } else { WARN("Couldn't check latest firmware version.\n"); } return result; }