http://http://diytec.web.fc2.com/mark2r2/

Dependencies:   EthernetNetIf NTPClient_NetServices mbed ConfigFile

Files at this revision

API Documentation at this revision

Comitter:
mark2r2
Date:
Tue Sep 20 12:46:26 2011 +0000
Commit message:
V1.0

Changed in this revision

ClockControl/ClockControl.cpp Show annotated file Show diff for this revision Revisions of this file
ClockControl/ClockControl.h Show annotated file Show diff for this revision Revisions of this file
ConfigFile.lib Show annotated file Show diff for this revision Revisions of this file
EthernetNetIf.lib Show annotated file Show diff for this revision Revisions of this file
FirmwareUpdater.cpp Show annotated file Show diff for this revision Revisions of this file
FirmwareUpdater.h Show annotated file Show diff for this revision Revisions of this file
GPS/GPS.cpp Show annotated file Show diff for this revision Revisions of this file
GPS/GPS.h Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC1768/HTTPClient.ar Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC1768/dbg/dbg.h Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC1768/services/http/client/HTTPClient.h Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC1768/services/http/client/HTTPData.h Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC1768/services/http/client/data/HTTPFile.h Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC1768/services/http/client/data/HTTPMap.h Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC1768/services/http/client/data/HTTPStream.h Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC1768/services/http/client/data/HTTPText.h Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC1768/services/http/util/base64.h Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC1768/services/http/util/url.h Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC2368/HTTPClient.ar Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC2368/dbg/dbg.h Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC2368/services/http/client/HTTPClient.h Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC2368/services/http/client/HTTPData.h Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC2368/services/http/client/data/HTTPFile.h Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC2368/services/http/client/data/HTTPMap.h Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC2368/services/http/client/data/HTTPStream.h Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC2368/services/http/client/data/HTTPText.h Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC2368/services/http/util/base64.h Show annotated file Show diff for this revision Revisions of this file
HTTPClient/LPC2368/services/http/util/url.h Show annotated file Show diff for this revision Revisions of this file
MODDMA/CONFIG.h Show annotated file Show diff for this revision Revisions of this file
MODDMA/ChangeLog.c Show annotated file Show diff for this revision Revisions of this file
MODDMA/DATALUTS.cpp Show annotated file Show diff for this revision Revisions of this file
MODDMA/INIT.cpp Show annotated file Show diff for this revision Revisions of this file
MODDMA/MODDMA.cpp Show annotated file Show diff for this revision Revisions of this file
MODDMA/MODDMA.h Show annotated file Show diff for this revision Revisions of this file
MODDMA/SETUP.cpp Show annotated file Show diff for this revision Revisions of this file
MODDMA/example1.h Show annotated file Show diff for this revision Revisions of this file
MODDMA/example2.h Show annotated file Show diff for this revision Revisions of this file
MODDMA/example3.h Show annotated file Show diff for this revision Revisions of this file
MODDMA/example4.h Show annotated file Show diff for this revision Revisions of this file
MODDMA/iomacros.h Show annotated file Show diff for this revision Revisions of this file
NTPClient.lib Show annotated file Show diff for this revision Revisions of this file
Pachube/Pachube.cpp Show annotated file Show diff for this revision Revisions of this file
Pachube/Pachube.h Show annotated file Show diff for this revision Revisions of this file
Pachube/PachubeV2CSV.cpp Show annotated file Show diff for this revision Revisions of this file
Pachube/PachubeV2CSV.h Show annotated file Show diff for this revision Revisions of this file
TextLCD/TextLCD.cpp Show annotated file Show diff for this revision Revisions of this file
TextLCD/TextLCD.h Show annotated file Show diff for this revision Revisions of this file
adcdma.c Show annotated file Show diff for this revision Revisions of this file
appconf.cpp Show annotated file Show diff for this revision Revisions of this file
appconf.h Show annotated file Show diff for this revision Revisions of this file
buzzer.c Show annotated file Show diff for this revision Revisions of this file
config_env.c Show annotated file Show diff for this revision Revisions of this file
display.c Show annotated file Show diff for this revision Revisions of this file
firmware_upgrade.c Show annotated file Show diff for this revision Revisions of this file
geiger.h Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed.bld Show annotated file Show diff for this revision Revisions of this file
md5.c Show annotated file Show diff for this revision Revisions of this file
md5.h Show annotated file Show diff for this revision Revisions of this file
pachube.c Show annotated file Show diff for this revision Revisions of this file
pin_assign.c Show annotated file Show diff for this revision Revisions of this file
twitter.c Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/ClockControl/ClockControl.cpp	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,37 @@
+#include "ClockControl.h"
+
+void setPLL0Frequency(unsigned char clkSrc, unsigned short M, unsigned char N)
+{
+      LPC_SC->CLKSRCSEL = clkSrc;
+      LPC_SC->PLL0CFG   = (((unsigned int)N-1) << 16) | M-1;
+      LPC_SC->PLL0CON   = 0x01;             
+      LPC_SC->PLL0FEED  = 0xAA;
+      LPC_SC->PLL0FEED  = 0x55;
+      while (!(LPC_SC->PLL0STAT & (1<<26)));
+    
+      LPC_SC->PLL0CON   = 0x03;
+      LPC_SC->PLL0FEED  = 0xAA;
+      LPC_SC->PLL0FEED  = 0x55;
+}
+
+void setPLL1Frequency(unsigned char clkSrc, unsigned short M, unsigned char N)
+{
+      LPC_SC->CLKSRCSEL = clkSrc;
+      LPC_SC->PLL1CFG   = (((unsigned int)N-1) << 16) | M-1;
+      LPC_SC->PLL1CON   = 0x01;             
+      LPC_SC->PLL1FEED  = 0xAA;
+      LPC_SC->PLL1FEED  = 0x55;
+      while (!(LPC_SC->PLL1STAT & (1<<26)));
+    
+      LPC_SC->PLL1CON   = 0x03;
+      LPC_SC->PLL1FEED  = 0xAA;
+      LPC_SC->PLL1FEED  = 0x55;
+}
+
+unsigned int setSystemFrequency(unsigned char clkDivider, unsigned char clkSrc, unsigned short M, unsigned char N)
+{
+    setPLL0Frequency(clkSrc, M, N);
+    LPC_SC->CCLKCFG = clkDivider - 1;
+    SystemCoreClockUpdate();
+    return SystemCoreClock;
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/ClockControl/ClockControl.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,14 @@
+/* mbed PowerControl Library
+  * Copyright (c) 2010 Michael Wei
+  */ 
+  
+//shouldn't have to include, but fixes weird problems with defines
+#include "LPC1768/LPC17xx.h"
+
+#ifndef MBED_CLOCKCONTROL_H 
+#define MBED_CLOCKCONTROL_H 
+
+unsigned int setSystemFrequency(unsigned char clkDivider, unsigned char clkSrc, unsigned short M, unsigned char N);
+void setPLL0Frequency(unsigned char clkSrc, unsigned short M, unsigned char N);
+void setPLL1Frequency(unsigned char clkSrc, unsigned short M, unsigned char N);
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/ConfigFile.lib	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/shintamainjp/code/ConfigFile/#f6ceafabe9f8
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/EthernetNetIf.lib	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/donatien/code/EthernetNetIf/#bc7df6da7589
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FirmwareUpdater.cpp	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,548 @@
+/*******************************************************************************
+modify 
+2011/08
+        - Create version text file when read error.
+        - Use commonClient.
+        - Reset HTTP request headers whe GET.
+        - Delete LOG when over 100KB.
+2011/07
+        - '\n' -> '\r\n' (when write to LOG)
+        - Add MD5 checksum.
+        - Add fclose(fp) when error & return
+
+*******************************************************************************/
+
+/**
+ * =============================================================================
+ * Firmware updater (Version 0.0.2)
+ * =============================================================================
+ * Copyright (c) 2010 Shinichiro Nakamura (CuBeatSystems)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ * =============================================================================
+ */
+
+#include "FirmwareUpdater.h"
+#include "md5.h"            //  2011/07
+
+#include <stdio.h>
+#include <stdarg.h>
+
+extern "C" void mbed_reset();
+
+const std::string FirmwareUpdater::EXT_BIN = ".bin";
+const std::string FirmwareUpdater::EXT_BINTMP = ".b__";
+const std::string FirmwareUpdater::EXT_TXT = ".txt";
+const std::string FirmwareUpdater::EXT_TXTTMP = ".t__";
+const std::string FirmwareUpdater::EXT_MD5 = ".md5";        //  2011/07
+const std::string FirmwareUpdater::EXT_MD5TMP = ".m__";     //  2011/07
+
+/**
+ * Create.
+ *
+ * @param url URL for firmware. Do not include a target file name.
+ * @param name An application name. Do not include a extention.
+ * @param log True if logging.
+ */
+//FirmwareUpdater::FirmwareUpdater(std::string url, std::string name, bool log)
+FirmwareUpdater::FirmwareUpdater(std::string url, std::string name, HTTPClient *pclient, bool log) //  2011/08
+        : url(url), name(name), log(log), local("local") {
+    client = pclient;           //  2011/08
+    client->setTimeout(10000);  //  2011/08
+
+    /*
+     * A file name on the mbed local file system should keep '8 + 3' types of name.
+     */
+    if (MAXNAMELEN < name.length()) {
+        LOG("ERR : Invalid firmware name '%s' found. The maximum length is %d.\r\n", name.c_str(), MAXNAMELEN);
+        error("ERR : Invalid firmware name '%s' found. The maximum length is %d.\r\n", name.c_str(), MAXNAMELEN);
+    }
+}
+
+/**
+ * Dispose.
+ */
+FirmwareUpdater::~FirmwareUpdater() {
+}
+
+/**
+ * Get a URL.
+ *
+ * @return URL.
+ */
+const std::string FirmwareUpdater:: getURL() const {
+    return url;
+}
+
+/**
+ * Get a name.
+ *
+ * @return name.
+ */
+const std::string FirmwareUpdater:: getName() const {
+    return name;
+}
+
+/**
+ * Checking a new firmware.
+ * Compare versions of the software between local storage on mbed and on webserver.
+ *
+ * @return Return 0 if a new firmware exists.
+ */
+int FirmwareUpdater::exist() {
+    int ver_local, ver_server;
+
+    /*
+     * Fetch the version from a local.
+     */
+    std::string file_local = "/local/" + name + EXT_TXT;
+    ver_local = readVersionFromFile(file_local.c_str());
+    if (ver_local < 0) {
+        return -1;
+    }
+
+    /*
+     * Fetch the version from a server.
+     */
+    std::string file_server = url + "/" + name + EXT_TXT;
+    ver_server = readVersionFromURL(file_server.c_str());
+    if (ver_server < 0) {
+        return -2;
+    }
+
+    return (ver_local < ver_server) ? 0 : 1;
+}
+
+/**
+ * Execute update.
+ *
+ * @return Return 0 if it succeed.
+ */
+int FirmwareUpdater::execute() {
+    /*
+     * Fetch the files.
+     */
+    std::string serv_txt = url + "/" + name + EXT_TXT;
+    std::string file_txttmp = "/local/" + name + EXT_TXTTMP;
+    if (fetch(serv_txt, file_txttmp) != 0) {
+        LOG("ERR : Aborted...\r\n");
+        return -1;
+    }
+    std::string serv_bin = url + "/" + name + EXT_BIN;
+    std::string file_bintmp = "/local/" + name + EXT_BINTMP;
+    if (fetch(serv_bin, file_bintmp) != 0) {
+        LOG("ERR : Aborted...\r\n");
+        return -2;
+    }
+    std::string serv_md5 = url + "/" + name + EXT_MD5;
+    std::string file_md5tmp = "/local/" + name + EXT_MD5TMP;
+    if (fetch(serv_md5, file_md5tmp) != 0) {
+        LOG("ERR : Aborted...\r\n");
+        return -8;
+    }
+
+    /*
+     * Check the firmware versions.
+     */
+    std::string file_txt = "/local/" + name + EXT_TXT;
+    int ver_old = readVersionFromFile(file_txt.c_str());
+    int ver_new = readVersionFromFile(file_txttmp.c_str());
+    if (ver_old < 0) {
+        LOG("ERR : Could not read the previous firmware version.\r\n");
+        LOG("ERR : Aborted...\r\n");
+        return -3;
+    }
+    if (ver_new < 0) {
+        LOG("ERR : Could not read the new firmware version.\r\n");
+        LOG("ERR : Aborted...\r\n");
+        return -4;
+    }
+    if (ver_new < ver_old) {
+        LOG("ERR : Ignore the new firmware. (old=%d, new=%d)\r\n", ver_old, ver_new);
+        LOG("ERR : Aborted...\r\n");
+        return -5;
+    }
+    /*
+     * MD5 check sum
+     *  2011/07
+     *
+     */
+    char md5str[33];
+    int readret = readMd5FromFile(file_md5tmp.c_str(), md5str);
+    if (readret < 0) {
+        LOG("ERR : Could not read the new firmware MD5.\r\n");
+        LOG("ERR : Aborted...\r\n");
+        return -9;
+    }
+    
+    #define BUFF_SIZE 1024
+
+    MD5 md5;
+    FILE *fp;
+    size_t len;
+    unsigned char buff[BUFF_SIZE];
+    
+    fp = fopen(file_bintmp.c_str(),"rb");
+    if ( fp == NULL ) {
+        LOG("ERR : Could not read the new firmware bin.\r\n");
+        LOG("ERR : Aborted...\r\n");
+        return -10;
+    }
+    while (len = fread(buff, 1, BUFF_SIZE, fp)) {
+        md5.update( buff, len);
+    }
+    fclose( fp );
+    md5.finalize();
+    
+    string hash;
+    hash = md5.hexdigest();
+    if (strncmp(md5str, hash.c_str(), 32) != 0) {
+        LOG("ERR : MD5 checksum error. Server MD5=%s, calc MD5 from binary=%s\r\n", md5str, hash.c_str() );
+        LOG("ERR : Aborted...\r\n");
+        return -11;
+    }
+
+    
+    
+    LOG("INFO: Firmware updating... (%d -> %d)\r\n", ver_old, ver_new);
+
+    /*
+     * Cleanup the previous versions.
+     *
+     * Note:
+     *  A file time stamp on mbed is always '12:00 01/01/2008'.
+     *  mbed can't sense updated firmware when the file name is same as previous version.
+     *
+     *  So I decided to cleanup all bin files.
+     *  And the new firmware name is 'name-VERSION.bin'.
+     *  To remove previous versions at first means 'start critical section on the system'.
+     */
+    //cleanupAllBinFiles();
+    cleanupAllBbkFiles();   //  2011/07
+    BackupBinFiles();       //  2011/07
+
+    /*
+     * Copy it.
+     */
+    char nn[32];
+    createNewBinName(ver_new, nn, sizeof(nn));
+    std::string file_bin = "/local/" + std::string(nn) + EXT_BIN;
+    if (copy(file_bintmp, file_bin) != 0) {
+        return -7;
+    }
+    if (copy(file_txttmp, file_txt) != 0) {
+        return -6;
+    }
+    /*
+     * Delete the temporary files.
+     */
+    remove(file_txttmp.c_str());
+    remove(file_bintmp.c_str());
+    remove(file_md5tmp.c_str());    //  2011/07
+    return 0;
+}
+
+/**
+ * Reset system.
+ */
+void FirmwareUpdater::reset() {
+    mbed_reset();
+}
+
+/**
+ * Fetch a file.
+ *
+ * @param src_url URL of a source file.
+ * @param local_file Local file name.
+ *
+ * @return Return 0 if it succeed.
+ */
+int FirmwareUpdater::fetch(std::string src_url, std::string local_file) {
+    /*
+     * Fetch the source file from URL to a temporary file on local.
+     */
+    HTTPFile file(local_file.c_str());
+    client->resetRequestHeaders();                  //  2011/08
+    int r = client->get(src_url.c_str(), &file);    //  2011/08
+    if (r != HTTP_OK) {
+        LOG("ERR : Fetch '%s' to '%s'.\r\n", src_url.c_str(), local_file.c_str());
+        return -1;
+    }
+    LOG("INFO: Fetched '%s' to '%s'.\r\n", src_url.c_str(), local_file.c_str());
+    return 0;
+}
+
+/**
+ * Copy a file.
+ *
+ * @param local_file1 Source file.
+ * @param local_file2 Destination file.
+ *
+ * @return Return 0 if it succeed.
+ */
+int FirmwareUpdater::copy(std::string local_file1, std::string local_file2) {
+    LOG("INFO: File copying... (%s->%s)\r\n", local_file1.c_str(), local_file2.c_str());
+    FILE *rp = fopen(local_file1.c_str(), "rb");
+    if (rp == NULL) {
+        LOG("ERR : File '%s' open failed.\r\n", local_file1.c_str());
+        return -1;
+    }
+    remove(local_file2.c_str());
+    FILE *wp = fopen(local_file2.c_str(), "wb");
+    if (wp == NULL) {
+        LOG("ERR : File '%s' open failed.\r\n", local_file2.c_str());
+        fclose(rp);
+        return -2;
+    }
+    int c;
+    while ((c = fgetc(rp)) != EOF) {
+        fputc(c, wp);
+    }
+
+    fclose(rp);
+    fclose(wp);
+    LOG("INFO: File copied. (%s->%s)\r\n", local_file1.c_str(), local_file2.c_str());
+    return 0;
+}
+
+/**
+ * Output a message to a log file.
+ *
+ * @param format ...
+ */
+void FirmwareUpdater::LOG(const char* format, ...) {
+    if (log) {
+        FILE *fplog = fopen("/local/update.log", "a");
+
+        if (fplog != NULL) {
+            char buf[BUFSIZ];
+            va_list p;
+            va_start(p, format);
+            vsnprintf(buf, sizeof(buf) - 1, format, p);
+            fprintf(fplog, "%s", buf);
+            // printf("%s", buf); /* If you want to check a message from a console. */
+            va_end(p);
+            fclose(fplog);
+        }
+    }
+}
+
+/**
+ * Cleanup all bin files.
+ */
+int FirmwareUpdater::cleanupAllBinFiles(void) {
+    struct dirent *p;
+    DIR *dir = opendir("/local");
+    if (dir == NULL) {
+        return -1;
+    }
+    while ((p = readdir(dir)) != NULL) {
+        char *str = p->d_name;
+        if ((strstr(str, ".bin") != NULL) || (strstr(str, ".BIN") != NULL)) {
+            char buf[BUFSIZ];
+            snprintf(buf, sizeof(buf) - 1, "/local/%s", str);
+            if (remove(buf) == 0) {
+                LOG("INFO: Deleted '%s'.\r\n", buf);
+            } else {
+                LOG("ERR : Delete '%s' failed.\r\n", buf);
+            }
+        }
+    }
+    closedir(dir);
+    return 0;
+}
+
+/**
+ * Cleanup all bbk(binary backup) files.
+ *   2011/07
+ */
+int FirmwareUpdater::cleanupAllBbkFiles(void) {
+    struct dirent *p;
+    DIR *dir = opendir("/local");
+    if (dir == NULL) {
+        return -1;
+    }
+    while ((p = readdir(dir)) != NULL) {
+        char *str = p->d_name;
+        if ((strstr(str, ".bbk") != NULL) || (strstr(str, ".BBK") != NULL)) {
+            char buf[BUFSIZ];
+            snprintf(buf, sizeof(buf) - 1, "/local/%s", str);
+            if (remove(buf) == 0) {
+                LOG("INFO: Deleted '%s'.\r\n", buf);
+            } else {
+                LOG("ERR : Delete '%s' failed.\r\n", buf);
+            }
+        }
+    }
+    closedir(dir);
+    return 0;
+}
+
+/**
+ * Backup BIN files.
+ *   2011/07
+ */
+int FirmwareUpdater::BackupBinFiles() {
+    struct dirent *p;
+    DIR *dir = opendir("/local");
+    if (dir == NULL) {
+        return -1;
+    }
+    while ((p = readdir(dir)) != NULL) {
+        char *str = p->d_name;
+        if ((strstr(str, ".bin") != NULL) || (strstr(str, ".BIN") != NULL)) {
+            char buf[BUFSIZ], bakname[BUFSIZ];
+            int len;
+            snprintf(buf, sizeof(buf) - 1, "/local/%s", str);
+            len = strlen(buf);
+#if 0
+            int dotpos=0;
+            for (int i=len-1; i>=0; i--) {
+                if (buf[i]=='.') {
+                    dotpos = i;
+                    break;
+                }
+            }
+            strncpy(bakname,buf, dotpos); bakname[dotpos]='\0'; strcat(bakname,".BBK");
+#endif
+            for (int i=0; i<len; i++) {
+                bakname[i] = buf[i];
+                if (bakname[i]=='.') {
+                    bakname[i+1] = '\0';
+                    strcat(bakname, "BBK");
+                    break;
+                }
+            }
+                
+            LOG("INFO: Copy '%s'->'%s'.\r\n", buf,bakname);
+            if (copy(buf,bakname) == 0) {
+                remove(buf);
+                LOG("INFO: Remove '%s'.\r\n", buf);
+            } else {
+                LOG("ERR : Copy '%s'->'%s' failed.\r\n", buf,bakname);
+            }
+        }
+    }
+    closedir(dir);
+    return 0;
+}
+
+/**
+ * Create a new binary file name.
+ *
+ * @param ver Version.
+ * @param buf A pointer to a buffer.
+ * @param siz A size of the buffer.
+ *
+ * @return Return 0 if it succeed.
+ */
+int FirmwareUpdater::createNewBinName(const int ver, char *buf, size_t siz) {
+    if (siz <= name.length()) {
+        return -1;
+    }
+    snprintf(buf, siz - 1, "%s", name.c_str());
+    char nb[32];
+    snprintf(nb, sizeof(nb) - 1, "-%d", ver);
+    if (strlen(buf) + strlen(nb) <= MAXNAMELEN) {
+        strcat(buf, nb);
+        return 0;
+    } else {
+        strcpy(buf + (MAXNAMELEN - strlen(nb)), nb);
+        return 0;
+    }
+}
+
+/**
+ * Read a version from a file.
+ *
+ * @param filename file name.
+ * @return A version.
+ */
+int FirmwareUpdater::readVersionFromFile(const char *filename) {
+    int ver;
+
+    remove("/local/update.log");        //   2011/08
+
+    FILE *fp = fopen(filename, "rb");
+    if (fp == NULL) {
+        fp = fopen(filename, "wt");     //  2011/08
+        if (fp == NULL) {               //  2011/08
+            LOG("ERR : Version file '%s' write open failed.\r\n", filename);
+            return -1;
+        }
+        fprintf(fp, "1\r\n");          //  2011/08
+        fclose(fp);                     //  2011/08
+        return 1;                      //  2011/08
+    }
+    if (fscanf(fp, "%d", &ver) != 1) {
+        fclose(fp);     //  2011/07
+        LOG("ERR : Version file '%s' is invalid.\r\n", filename);
+        return -2;
+    }
+    fclose(fp);
+    LOG("INFO: Version file '%s': Version %d.\r\n", filename, ver);
+    return ver;
+}
+
+/**
+ * Read a version from a URL.
+ *
+ * @param url URL.
+ * @return A version.
+ */
+int FirmwareUpdater::readVersionFromURL(const char *url) {
+    int ver;
+    HTTPText text;
+    client->resetRequestHeaders();                  //  2011/08
+    HTTPResult r = client->get(url, &text);         //  2011/08
+    if (r != HTTP_OK) {
+        LOG("ERR : Version file '%s' open failed.\r\n", url);
+        return -1;
+    }
+    if (sscanf(text.gets(), "%d", &ver) != 1) {
+        LOG("ERR : Version file '%s' is invalid.\r\n", url);
+        return -2;
+    }
+    LOG("INFO: Version file '%s': Version %d.\r\n", url, ver);
+    return ver;
+}
+
+/**
+ * Read a MD5 from a file.
+ *  2011/07
+ * @param filename file name.
+ * @param md5str MD5 string.
+ * @return Error code.
+ */
+int FirmwareUpdater::readMd5FromFile(const char *filename, char *md5str) {
+    int ret=0;
+    FILE *fp = fopen(filename, "rb");
+    if (fp == NULL) {
+        LOG("ERR : MD5 file '%s' open failed.\r\n", filename);
+        return -1;
+    }
+    if (fscanf(fp, "%32s", md5str) != 1) {
+        fclose(fp);
+        LOG("ERR : MD5 file '%s' is invalid.\r\n", filename);
+        return -2;
+    }
+    fclose(fp);
+    LOG("INFO: MD5 file '%s': Checksum %s.\r\n", filename, md5str);
+    return ret;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FirmwareUpdater.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,219 @@
+/*******************************************************************************
+modify 
+ 2011/08
+        - Use commonClient.
+ 2011/07
+        - Add MD5 checksum.
+
+*******************************************************************************/
+
+
+/**
+ * =============================================================================
+ * Firmware updater (Version 0.0.2)
+ * =============================================================================
+ * Copyright (c) 2010 Shinichiro Nakamura (CuBeatSystems)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ * =============================================================================
+ */
+
+#ifndef FIRMWARE_UPDATER_H
+#define FIRMWARE_UPDATER_H
+
+#include "mbed.h"
+#include "HTTPClient.h"
+#include "LocalFileSystem.h"
+#include <string>
+
+/**
+ * @code
+ * #include "mbed.h"
+ * #include "FirmwareUpdater.h"
+ * #include "EthernetNetIf.h"
+ *
+ * EthernetNetIf eth;
+ * FirmwareUpdater fwup("http://mbed.org/media/uploads/shintamainjp/", "firm", true);
+ *
+ * // There are 2 files for the firmware.
+ * //  1. firm.txt : firmware version file.
+ * //  2. firm.bin : firmware binary file.
+ *
+ * int main() {
+ *     eth.setup();
+ *     if (fwup.exist() == 0) {
+ *         printf("Found a new firmware.\n");
+ *         if (fwup.execute() == 0) {
+ *             printf("Update succeed.\n");
+ *             printf("Resetting this system...\n\n\n\n\n");
+ *             fwup.reset();
+ *         } else {
+ *             printf("Update failed!\n");
+ *         }
+ *     }
+ * }
+ * @endcode
+ */
+class FirmwareUpdater {
+public:
+    /**
+     * Create.
+     *
+     * @param url URL for firmware. Do not include a target file name.
+     * @param name An application name. Do not include a extention.
+     * @param log True if logging.
+     */
+//    FirmwareUpdater(std::string url, std::string name, bool log = false);
+    FirmwareUpdater(std::string url, std::string name, HTTPClient *pclient, bool log = false);  //  2011/08
+
+    /**
+     * Dispose.
+     */
+    ~FirmwareUpdater();
+
+    /**
+     * Get a URL.
+     *
+     * @return URL.
+     */
+    const std::string getURL() const;
+
+    /**
+     * Get a name.
+     *
+     * @return name.
+     */
+    const std::string getName() const;
+
+    /**
+     * Checking a new firmware.
+     * Compare versions of the software between local storage on mbed and on webserver.
+     *
+     * @return Return 0 if a new firmware exists.
+     */
+    int exist();
+
+    /**
+     * Execute update.
+     *
+     * @return Return 0 if it succeed.
+     */
+    int execute();
+
+    /**
+     * Reset system.
+     */
+    void reset();
+
+private:
+    static const int MAXNAMELEN = 8;
+    static const std::string EXT_BIN;
+    static const std::string EXT_BINTMP;
+    static const std::string EXT_TXT;
+    static const std::string EXT_TXTTMP;
+    static const std::string EXT_MD5;       //  2011/07
+    static const std::string EXT_MD5TMP;    //  2011/07
+    const std::string url;
+    const std::string name;
+    const bool log;
+    LocalFileSystem local;
+    HTTPClient *client;
+
+    /**
+     * Fetch a file.
+     *
+     * @param src_url URL of a source file.
+     * @param local_file Local file name.
+     *
+     * @return Return 0 if it succeed.
+     */
+    int fetch(std::string src_url, std::string local_file);
+
+    /**
+     * Copy a file.
+     *
+     * @param local_file1 Source file.
+     * @param local_file2 Destination file.
+     *
+     * @return Return 0 if it succeed.
+     */
+    int copy(std::string local_file1, std::string local_file2);
+
+    /**
+     * Output a message to a log file.
+     *
+     * @param format ...
+     */
+    void LOG(const char* format, ...);
+
+    /**
+     * Cleanup all bin files.
+     */
+    int cleanupAllBinFiles(void);
+    
+    /**
+     * Cleanup all bbk(binary backup) files.
+     *   2011/07
+     */
+    int cleanupAllBbkFiles(void);
+
+    /**
+     * Backup BIN files.
+     *   2011/07
+     */
+    int BackupBinFiles(void);
+
+    /**
+     * Create a new binary file name.
+     *
+     * @param ver Version.
+     * @param buf A pointer to a buffer.
+     * @param siz A size of the buffer.
+     *
+     * @return Return 0 if it succeed.
+     */
+    int createNewBinName(const int ver, char *buf, size_t siz);
+
+    /**
+     * Read a version from a file.
+     *
+     * @param filename file name.
+     * @return A version.
+     */
+    int readVersionFromFile(const char *filename);
+
+    /**
+     * Read a version from a URL.
+     *
+     * @param url URL.
+     * @return A version.
+     */
+    int readVersionFromURL(const char *url);
+    
+    /**
+     * Read a MD5 from a file.
+     *  2011/07
+     * @param filename file name.
+     * @param md5str MD5 string.
+     * @return Error code.
+     */
+    int readMd5FromFile(const char *filename, char *md5str);
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/GPS/GPS.cpp	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,81 @@
+/* mbed EM-406 GPS Module Library
+ * Copyright (c) 2008-2010, sford
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+ 
+#include "GPS.h"
+
+GPS::GPS(PinName tx, PinName rx) : _gps(tx, rx) {
+    _gps.baud(4800);    
+    longitude = 0.0;
+    latitude = 0.0;        
+}
+
+int GPS::sample() {
+    float time;
+    char ns, ew;
+    int lock;
+
+    while(1) {        
+        getline();
+
+        // Check if it is a GPGGA msg (matches both locked and non-locked msg)
+        if(sscanf(msg, "GPGGA,%f,%f,%c,%f,%c,%d", &time, &latitude, &ns, &longitude, &ew, &lock) >= 1) { 
+            if(!lock) {
+                longitude = 0.0;
+                latitude = 0.0;        
+                return 0;
+            } else {
+                if(ns == 'S') {    latitude  *= -1.0; }
+                if(ew == 'W') {    longitude *= -1.0; }
+                float degrees = trunc(latitude / 100.0f);
+                float minutes = latitude - (degrees * 100.0f);
+                latitude = degrees + minutes / 60.0f;    
+                degrees = trunc(longitude / 100.0f * 0.01f);
+                minutes = longitude - (degrees * 100.0f);
+                longitude = degrees + minutes / 60.0f;
+                return 1;
+            }
+        }
+    }
+}
+
+float GPS::trunc(float v) {
+    if(v < 0.0) {
+        v*= -1.0;
+        v = floor(v);
+        v*=-1.0;
+    } else {
+        v = floor(v);
+    }
+    return v;
+}
+
+void GPS::getline() {
+    while(_gps.getc() != '$');    // wait for the start of a line
+    for(int i=0; i<256; i++) {
+        msg[i] = _gps.getc();
+        if(msg[i] == '\r') {
+            msg[i] = 0;
+            return;
+        }
+    }
+    printf("Overflowed message limit");
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/GPS/GPS.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,57 @@
+/* mbed EM-406 GPS Module Library
+ * Copyright (c) 2008-2010, sford
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include "mbed.h"
+
+#ifndef MBED_GPS_H
+#define MBED_GPS_H
+
+/**  A GPS interface for reading from a Globalsat EM-406 GPS Module */
+class GPS {
+public:
+
+    /** Create the GPS interface, connected to the specified serial port
+     */    
+    GPS(PinName tx, PinName rx);
+    
+    /** Sample the incoming GPS data, returning whether there is a lock
+     * 
+     * @return 1 if there was a lock when the sample was taken (and therefore .longitude and .latitude are valid), else 0
+     */
+    int sample();
+    
+    /** The longitude (call sample() to set) */
+    float longitude;
+
+    /** The latitude (call sample() to set) */
+    float latitude;
+    
+private:
+    float trunc(float v);
+    void getline();
+    
+    Serial _gps;
+    char msg[256];
+
+};
+
+#endif
Binary file HTTPClient/LPC1768/HTTPClient.ar has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPClient/LPC1768/dbg/dbg.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,94 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+ 
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+ 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+/** \file
+Debugging helpers header file
+*/
+
+//#ifdef DBG_H
+//#define DBG_H
+
+#ifdef __LWIP_DEBUG
+#define __DEBUG
+#endif
+
+/*!
+  \def __DEBUG
+  To define to enable debugging in one file
+*/
+
+#ifdef __DEBUG
+
+#ifndef __DEBUGSTREAM
+#define __DEBUGSTREAM
+
+
+class DebugStream
+{
+public:
+static void debug(const char* format, ...);
+static void release();
+static void breakPoint(const char* file, int line);
+private:
+
+};
+
+#undef DBG
+#undef DBG_END
+#undef BREAK
+
+///Debug output (if enabled), same syntax as printf, with heading info
+#define DBG(...) do{ DebugStream::debug("[%s:%s@%d] ", __FILE__, __FUNCTION__, __LINE__); DebugStream::debug(__VA_ARGS__); } while(0);
+
+///Debug output (if enabled), same syntax as printf, no heading info
+#define DBGL(...) do{ DebugStream::debug(__VA_ARGS__); } while(0);
+#define DBG_END DebugStream::release
+
+///Break point usin serial debug interface (if debug enbaled)
+#define BREAK() DebugStream::breakPoint(__FILE__, __LINE__)
+#endif
+
+#else
+#undef DBG
+#undef DBG_END
+#undef BREAK
+#define DBG(...)
+#define DBG_END()
+#define BREAK()
+#endif
+
+#ifdef __LWIP_DEBUG
+#ifndef __SNPRINTF
+#define __SNPRINTF
+#include "mbed.h"
+
+//int snprintf(char *str, int size, const char *format, ...);
+#endif
+#endif
+
+#ifdef __LWIP_DEBUG
+#undef __DEBUG
+#endif
+
+//#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPClient/LPC1768/services/http/client/HTTPClient.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,306 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+ 
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+ 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+/** \file
+HTTP Client header file
+*/
+
+#ifndef HTTP_CLIENT_H
+#define HTTP_CLIENT_H
+
+class HTTPData;
+
+#include "core/net.h"
+#include "api/TCPSocket.h"
+#include "api/DNSRequest.h"
+#include "HTTPData.h"
+#include "mbed.h"
+
+#include <string>
+using std::string;
+
+#include <map>
+using std::map;
+
+///HTTP client results
+enum HTTPResult
+{
+  HTTP_OK, ///<Success
+  HTTP_PROCESSING, ///<Processing
+  HTTP_PARSE, ///<URI Parse error
+  HTTP_DNS, ///<Could not resolve name
+  HTTP_PRTCL, ///<Protocol error
+  HTTP_NOTFOUND, ///<HTTP 404 Error
+  HTTP_REFUSED, ///<HTTP 403 Error
+  HTTP_ERROR, ///<HTTP xxx error
+  HTTP_TIMEOUT, ///<Connection timeout
+  HTTP_CONN ///<Connection error
+};
+
+#include "core/netservice.h"
+
+///A simple HTTP Client
+/**
+The HTTPClient is composed of:
+- The actual client (HTTPClient)
+- Classes that act as a data repository, each of which deriving from the HTTPData class (HTTPText for short text content, HTTPFile for file I/O, HTTPMap for key/value pairs, and HTTPStream for streaming purposes)
+*/
+class HTTPClient : protected NetService
+{
+public:
+  ///Instantiates the HTTP client
+  HTTPClient();
+  virtual ~HTTPClient();
+  
+  ///Provides a basic authentification feature (Base64 encoded username and password)
+  void basicAuth(const char* user, const char* password); //Basic Authentification
+  
+  //High Level setup functions
+  ///Executes a GET Request (blocking)
+  /**
+  Executes a GET request on the URI uri
+  @param uri : URI on which to execute the request
+  @param pDataIn : pointer to an HTTPData instance that will collect the data returned by the request, can be NULL
+  Blocks until completion
+  */
+  HTTPResult get(const char* uri, HTTPData* pDataIn); //Blocking
+  
+  ///Executes a GET Request (non blocking)
+  /**
+  Executes a GET request on the URI uri
+  @param uri : URI on which to execute the request
+  @param pDataIn : pointer to an HTTPData instance that will collect the data returned by the request, can be NULL
+  @param pMethod : callback function
+  The function returns immediately and calls the callback on completion or error
+  */
+  HTTPResult get(const char* uri, HTTPData* pDataIn, void (*pMethod)(HTTPResult)); //Non blocking
+  
+  ///Executes a GET Request (non blocking)
+  /**
+  Executes a GET request on the URI uri
+  @param uri : URI on which to execute the request
+  @param pDataIn : pointer to an HTTPData instance that will collect the data returned by the request, can be NULL
+  @param pItem : instance of class on which to execute the callback method
+  @param pMethod : callback method
+  The function returns immediately and calls the callback on completion or error
+  */
+  template<class T> 
+  HTTPResult get(const char* uri, HTTPData* pDataIn, T* pItem, void (T::*pMethod)(HTTPResult)) //Non blocking
+  {
+    setOnResult(pItem, pMethod);
+    doGet(uri, pDataIn);
+    return HTTP_PROCESSING;
+  }
+  
+  ///Executes a POST Request (blocking)
+  /**
+  Executes a POST request on the URI uri
+  @param uri : URI on which to execute the request
+  @param dataOut : a HTTPData instance that contains the data that will be posted
+  @param pDataIn : pointer to an HTTPData instance that will collect the data returned by the request, can be NULL
+  Blocks until completion
+  */
+  HTTPResult post(const char* uri, const HTTPData& dataOut, HTTPData* pDataIn); //Blocking
+  
+  ///Executes a POST Request (non blocking)
+  /**
+  Executes a POST request on the URI uri
+  @param uri : URI on which to execute the request
+  @param dataOut : a HTTPData instance that contains the data that will be posted
+  @param pDataIn : pointer to an HTTPData instance that will collect the data returned by the request, can be NULL
+  @param pMethod : callback function
+  The function returns immediately and calls the callback on completion or error
+  */
+  HTTPResult post(const char* uri, const HTTPData& dataOut, HTTPData* pDataIn, void (*pMethod)(HTTPResult)); //Non blocking
+  
+  ///Executes a POST Request (non blocking)
+  /**
+  Executes a POST request on the URI uri
+  @param uri : URI on which to execute the request
+  @param dataOut : a HTTPData instance that contains the data that will be posted
+  @param pDataIn : pointer to an HTTPData instance that will collect the data returned by the request, can be NULL
+  @param pItem : instance of class on which to execute the callback method
+  @param pMethod : callback method
+  The function returns immediately and calls the callback on completion or error
+  */
+  template<class T> 
+  HTTPResult post(const char* uri, const HTTPData& dataOut, HTTPData* pDataIn, T* pItem, void (T::*pMethod)(HTTPResult)) //Non blocking  
+  {
+    setOnResult(pItem, pMethod);
+    doPost(uri, dataOut, pDataIn);
+    return HTTP_PROCESSING;
+  }
+
+  ///Executes a GET Request (non blocking)
+  /**
+  Executes a GET request on the URI uri
+  @param uri : URI on which to execute the request
+  @param pDataIn : pointer to an HTTPData instance that will collect the data returned by the request, can be NULL
+  The function returns immediately and calls the previously set callback on completion or error
+  */  
+  void doGet(const char* uri, HTTPData* pDataIn);  
+  
+  ///Executes a POST Request (non blocking)
+  /**
+  Executes a POST request on the URI uri
+  @param uri : URI on which to execute the request
+  @param dataOut : a HTTPData instance that contains the data that will be posted
+  @param pDataIn : pointer to an HTTPData instance that will collect the data returned by the request, can be NULL
+  @param pMethod : callback function
+  The function returns immediately and calls the previously set callback on completion or error
+  */
+  void doPost(const char* uri, const HTTPData& dataOut, HTTPData* pDataIn); 
+  
+  ///Setups the result callback
+  /**
+  @param pMethod : callback function
+  */
+  void setOnResult( void (*pMethod)(HTTPResult) );
+  
+  ///Setups the result callback
+  /**
+  @param pItem : instance of class on which to execute the callback method
+  @param pMethod : callback method
+  */
+  class CDummy;
+  template<class T> 
+  void setOnResult( T* pItem, void (T::*pMethod)(HTTPResult) )
+  {
+    m_pCb = NULL;
+    m_pCbItem = (CDummy*) pItem;
+    m_pCbMeth = (void (CDummy::*)(HTTPResult)) pMethod;
+  }
+
+  ///Setups timeout
+  /**
+  @param ms : time of connection inactivity in ms after which the request should timeout
+  */
+  void setTimeout(int ms);
+  
+  virtual void poll(); //Called by NetServices
+  
+  ///Gets last request's HTTP response code
+  /**
+  @return The HTTP response code of the last request
+  */
+  int getHTTPResponseCode();
+  
+  ///Sets a specific request header
+  void setRequestHeader(const string& header, const string& value);
+  
+  ///Gets a response header
+  string& getResponseHeader(const string& header);
+  
+  ///Clears request headers
+  void resetRequestHeaders();
+  
+protected:
+  void resetTimeout();
+  
+  void init();
+  void close();
+  
+  void setup(const char* uri, HTTPData* pDataOut, HTTPData* pDataIn); //Setup request, make DNS Req if necessary
+  void connect(); //Start Connection
+  
+  int  tryRead(); //Read data and try to feed output
+  void readData(); //Data has been read
+  void writeData(); //Data has been written & buf is free
+  
+  void onTCPSocketEvent(TCPSocketEvent e);
+  void onDNSReply(DNSReply r);
+  void onResult(HTTPResult r); //Called when exchange completed or on failure
+  void onTimeout(); //Connection has timed out
+  
+private:
+  HTTPResult blockingProcess(); //Called in blocking mode, calls Net::poll() until return code is available
+
+  bool readHeaders(); //Called first when receiving data
+  bool writeHeaders(); //Called to create req
+  int readLine(char* str, int maxLen, bool* pIncomplete = NULL);
+  
+  enum HTTP_METH
+  {
+    HTTP_GET,
+    HTTP_POST,
+    HTTP_HEAD
+  };
+  
+  HTTP_METH m_meth;
+  
+  CDummy* m_pCbItem;
+  void (CDummy::*m_pCbMeth)(HTTPResult);
+  
+  void (*m_pCb)(HTTPResult);
+  
+  TCPSocket* m_pTCPSocket;
+  map<string, string> m_reqHeaders;
+  map<string, string> m_respHeaders;
+  
+  Timer m_watchdog;
+  int m_timeout;
+  
+  DNSRequest* m_pDnsReq;
+  
+  Host m_server;
+  string m_path;
+  
+  bool m_closed;
+  
+  enum HTTPStep
+  {
+   // HTTP_INIT,
+    HTTP_WRITE_HEADERS,
+    HTTP_WRITE_DATA,
+    HTTP_READ_HEADERS,
+    HTTP_READ_DATA,
+    HTTP_READ_DATA_INCOMPLETE,
+    HTTP_DONE,
+    HTTP_CLOSED
+  };
+  
+  HTTPStep m_state;
+  
+  HTTPData* m_pDataOut;
+  HTTPData* m_pDataIn;
+  
+  bool m_dataChunked; //Data is encoded as chunks
+  int m_dataPos; //Position in data
+  int m_dataLen; //Data length
+  char* m_buf;
+  char* m_pBufRemaining; //Remaining
+  int m_bufRemainingLen; //Data length in m_pBufRemaining
+  
+  int m_httpResponseCode;
+  
+  HTTPResult m_blockingResult; //Result if blocking mode
+  
+};
+
+//Including data containers here for more convenience
+#include "data/HTTPFile.h"
+#include "data/HTTPStream.h"
+#include "data/HTTPText.h"
+#include "data/HTTPMap.h"
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPClient/LPC1768/services/http/client/HTTPData.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,58 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+ 
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+ 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+#ifndef HTTP_DATA_H
+#define HTTP_DATA_H
+
+#include "core/net.h"
+
+#include <string>
+using std::string;
+
+class HTTPData //This is a simple interface for HTTP data storage (impl examples are Key/Value Pairs, File, etc...)
+{
+public:
+  HTTPData();
+  virtual ~HTTPData();
+  
+  virtual void clear() = 0;
+
+protected:
+  friend class HTTPClient;
+  virtual int read(char* buf, int len) = 0;
+  virtual int write(const char* buf, int len) = 0;
+  
+  virtual string getDataType() = 0; //Internet media type for Content-Type header
+  virtual void setDataType(const string& type) = 0; //Internet media type from Content-Type header
+  
+  virtual bool getIsChunked() = 0; //For Transfer-Encoding header
+  virtual void setIsChunked(bool chunked) = 0; //From Transfer-Encoding header
+  
+  virtual int getDataLen() = 0; //For Content-Length header
+  virtual void setDataLen(int len) = 0; //From Content-Length header, or if the transfer is chunked, next chunk length
+  
+private:
+
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPClient/LPC1768/services/http/client/data/HTTPFile.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,81 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+ 
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+ 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+/** \file
+HTTP File data source/sink header file
+*/
+
+#ifndef HTTP_FILE_H
+#define HTTP_FILE_H
+
+#include "../HTTPData.h"
+#include "mbed.h"
+
+///HTTP Client data container for files
+/**
+This class provides file access/storage for HTTP requests and responses' data payloads.
+
+
+*/
+class HTTPFile : public HTTPData //Read or Write data from a file
+{
+public:
+  ///Instantiates data source/sink with file in param.
+  /**
+  Uses file at path @a path.
+  It will be opened when some data has to be read/written from/to it and closed when this operation is complete or on destruction of the instance.
+  Note that the file will be opened with mode "w" for writing and mode "r" for reading, so the file will be cleared between each request if you are using it for writing.
+  
+  @note
+  Note that to use this you must instantiate a proper file system (such as the LocalFileSystem or the SDFileSystem).
+  */
+  HTTPFile(const char* path);
+  virtual ~HTTPFile();
+  
+  ///Forces file closure
+  virtual void clear();
+
+protected:
+  virtual int read(char* buf, int len);
+  virtual int write(const char* buf, int len);
+  
+  virtual string getDataType(); //Internet media type for Content-Type header
+  virtual void setDataType(const string& type); //Internet media type from Content-Type header
+  
+  virtual bool getIsChunked(); //For Transfer-Encoding header
+  virtual void setIsChunked(bool chunked); //From Transfer-Encoding header  virtual
+  
+  virtual int getDataLen(); //For Content-Length header
+  virtual void setDataLen(int len); //From Content-Length header
+  
+private:
+  bool openFile(const char* mode); //true on success, false otherwise
+  void closeFile();
+
+  FILE* m_fp;
+  string m_path;
+  int m_len;
+  bool m_chunked;
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPClient/LPC1768/services/http/client/data/HTTPMap.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,89 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+ 
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+ 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+/** \file
+HTTP Map data source/sink header file
+*/
+
+#ifndef HTTP_MAP_H
+#define HTTP_MAP_H
+
+#include "../HTTPData.h"
+#include "mbed.h"
+
+#include <map>
+using std::map;
+
+typedef map<string, string> Dictionary;
+
+///HTTP Client data container for key/value pairs
+/**
+This class simplifies the use of key/value pairs requests and responses used widely among web APIs.
+Note that HTTPMap inherits from std::map<std::string,std::string>.
+You can therefore use any public method of that class, including the square brackets operator ( [ ] ) to access a value.
+
+The data is encoded or decoded to/from a key/value pairs-formatted string, after url-encoding/decoding.
+*/
+class HTTPMap : public HTTPData, public Dictionary //Key/Value pairs
+{
+public:
+  ///Instantiates map
+  /**
+  @param keyValueSep Key/Value separator (defaults to "=")
+  @param pairSep Pairs separator (defaults to "&")
+  */
+  HTTPMap(const string& keyValueSep = "=", const string& pairSep = "&");
+  virtual ~HTTPMap();
+  
+ /* string& operator[](const string& key);
+  int count();*/
+
+  ///Clears the content
+  virtual void clear();  
+  
+protected:
+  virtual int read(char* buf, int len);
+  virtual int write(const char* buf, int len);
+  
+  virtual string getDataType(); //Internet media type for Content-Type header
+  virtual void setDataType(const string& type); //Internet media type from Content-Type header
+  
+  virtual bool getIsChunked(); //For Transfer-Encoding header
+  virtual void setIsChunked(bool chunked); //From Transfer-Encoding header
+  
+  virtual int getDataLen(); //For Content-Length header
+  virtual void setDataLen(int len); //From Content-Length header
+  
+private:
+  void generateString();
+  void parseString();
+  //map<string, string> m_map;
+  string m_buf;
+  int m_len;
+  bool m_chunked;
+  
+  string m_keyValueSep;
+  string m_pairSep;
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPClient/LPC1768/services/http/client/data/HTTPStream.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,83 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+ 
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+ 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+#ifndef HTTP_STREAM_H
+#define HTTP_STREAM_H
+
+#include "../HTTPData.h"
+#include "mbed.h"
+
+/** \file
+HTTP Stream data source/sink header file
+*/
+
+typedef uint8_t byte;
+
+///HTTP Client Streaming tool
+/**
+This class allows you to stream data from the web using a persisting HTTP connection.
+To use it properly you must use a non-blocking HTTPClient method.
+*/
+class HTTPStream : public HTTPData //Streaming buf
+{
+public:
+  ///Instantiates the object
+  HTTPStream();
+  virtual ~HTTPStream();
+  
+  ///Starts to read into buffer
+  /**
+  Passes a buffer of address @a buf and size @a size to the instance.
+  When it receives data it will be stored in this buffer.
+  When the buffer is full it throttles the client until this function is called again.
+  */
+  void readNext(byte* buf, int size);
+  
+  ///Returns whether there is data available to read
+  bool readable();
+  
+  ///Returns the actual length of the payload written in the buffer
+  int readLen();
+  
+  virtual void clear();
+      
+protected:
+  virtual int read(char* buf, int len);
+  virtual int write(const char* buf, int len);
+  
+  virtual string getDataType(); //Internet media type for Content-Type header
+  virtual void setDataType(const string& type); //Internet media type from Content-Type header
+
+  virtual bool getIsChunked(); //For Transfer-Encoding header
+  virtual void setIsChunked(bool chunked); //From Transfer-Encoding header
+  
+  virtual int getDataLen(); //For Content-Length header
+  virtual void setDataLen(int len); //From Content-Length header, or if the transfer is chunked, next chunk length
+  
+private:
+  byte* m_buf;
+  int m_size; //Capacity
+  int m_len; //Length
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPClient/LPC1768/services/http/client/data/HTTPText.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,101 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+ 
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+ 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+/** \file
+HTTP Text data source/sink header file
+*/
+
+#ifndef HTTP_TEXT_H
+#define HTTP_TEXT_H
+
+#include "../HTTPData.h"
+#include "mbed.h"
+
+#define DEFAULT_MAX_MEM_ALLOC 512 //Avoid out-of-memory problems
+
+///HTTP Client data container for text
+/**
+This is a simple "Text" data repository for HTTP requests.
+*/
+class HTTPText : public HTTPData //Simple Text I/O
+{
+public:
+  ///Instantiates the object.
+  /**
+  @param encoding encoding of the data, it defaults to text/html.
+  @param maxSize defines the maximum memory size that can be allocated by the object. It defaults to 512 bytes.
+  */
+  HTTPText(const string& encoding = "text/html", int maxSize = DEFAULT_MAX_MEM_ALLOC);
+  virtual ~HTTPText();
+  
+  ///Gets text
+  /**
+  Returns the text in the container as a zero-terminated char*.
+  The array returned points to the internal buffer of the object and remains owned by the object.
+  */
+  const char* gets() const;
+  
+  //Puts text
+  /**
+  Sets the text in the container using a zero-terminated char*.
+  */
+  void puts(const char* str);
+  
+  ///Gets text
+  /**
+  Returns the text in the container as string.
+  */
+  string& get();
+  
+  ///Puts text
+  /**
+  Sets the text in the container as string.
+  */
+  void set(const string& str);
+  
+  ///Clears the content.
+  /**
+  If this container is used as a data sink, it is cleared by the HTTP Client at the beginning of the request.
+  */
+  virtual void clear();
+  
+protected:
+  virtual int read(char* buf, int len);
+  virtual int write(const char* buf, int len);
+  
+  virtual string getDataType(); //Internet media type for Content-Type header
+  virtual void setDataType(const string& type); //Internet media type from Content-Type header
+
+  virtual bool getIsChunked(); //For Transfer-Encoding header
+  virtual void setIsChunked(bool chunked); //From Transfer-Encoding header
+  
+  virtual int getDataLen(); //For Content-Length header
+  virtual void setDataLen(int len); //From Content-Length header, or if the transfer is chunked, next chunk length
+  
+private:
+  string m_buf;
+  string m_encoding;
+  int m_maxSize;
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPClient/LPC1768/services/http/util/base64.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,57 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+ 
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+ 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+#ifndef BASE64_H
+#define BASE64_H
+
+#include <string>
+using std::string;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//Originaly from Rolf's iputil.h
+
+unsigned int base64enc_len(const char *str);
+
+void base64enc(const char *input, unsigned int length, char *output);
+
+#ifdef __cplusplus
+}
+#endif
+
+class Base64
+{
+public:
+  static string encode(const string& str)
+  {
+    char* out = new char[ base64enc_len(str.c_str()) ];
+    base64enc(str.c_str(), str.length(), out);
+    string res(out);
+    delete[] out;
+    return res;
+  }
+};
+
+#endif /* LWIP_UTILS_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPClient/LPC1768/services/http/util/url.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,88 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+ 
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+ 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+#ifndef URL_H
+#define URL_H
+
+#include "core/ipaddr.h"
+
+#include <string>
+using std::string;
+
+#include "mbed.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+char *url_encode(char *str);
+char *url_decode(char *str);
+
+#ifdef __cplusplus
+}
+#endif
+
+class Url
+{
+public:
+  static string encode(const string& url)
+  {
+    char* c_res = url_encode( (char*) url.c_str() );
+    string res(c_res);
+    free(c_res); //Alloc'ed in url_encode()
+    return res;
+  }
+  
+  static string decode(const string& url)
+  {
+    char* c_res = url_decode( (char*) url.c_str() );
+    string res(c_res);
+    free(c_res); //Alloc'ed in url_decode()
+    return res;
+  }
+  
+  Url();
+
+  string getProtocol();
+  string getHost();
+  bool getHostIp(IpAddr* ip); //If host is in IP form, return true & proper object by ptr
+  uint16_t getPort();
+  string getPath();
+  
+  void setProtocol(string protocol);
+  void setHost(string host);
+  void setPort(uint16_t port);
+  void setPath(string path);
+  
+  void fromString(string str);
+  string toString();
+
+private:
+  string m_protocol;
+  string m_host;
+  uint16_t m_port;
+  string m_path;
+  
+};
+
+#endif /* LWIP_UTILS_H */
Binary file HTTPClient/LPC2368/HTTPClient.ar has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPClient/LPC2368/dbg/dbg.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,94 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+ 
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+ 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+/** \file
+Debugging helpers header file
+*/
+
+//#ifdef DBG_H
+//#define DBG_H
+
+#ifdef __LWIP_DEBUG
+#define __DEBUG
+#endif
+
+/*!
+  \def __DEBUG
+  To define to enable debugging in one file
+*/
+
+#ifdef __DEBUG
+
+#ifndef __DEBUGSTREAM
+#define __DEBUGSTREAM
+
+
+class DebugStream
+{
+public:
+static void debug(const char* format, ...);
+static void release();
+static void breakPoint(const char* file, int line);
+private:
+
+};
+
+#undef DBG
+#undef DBG_END
+#undef BREAK
+
+///Debug output (if enabled), same syntax as printf, with heading info
+#define DBG(...) do{ DebugStream::debug("[%s:%s@%d] ", __FILE__, __FUNCTION__, __LINE__); DebugStream::debug(__VA_ARGS__); } while(0);
+
+///Debug output (if enabled), same syntax as printf, no heading info
+#define DBGL(...) do{ DebugStream::debug(__VA_ARGS__); } while(0);
+#define DBG_END DebugStream::release
+
+///Break point usin serial debug interface (if debug enbaled)
+#define BREAK() DebugStream::breakPoint(__FILE__, __LINE__)
+#endif
+
+#else
+#undef DBG
+#undef DBG_END
+#undef BREAK
+#define DBG(...)
+#define DBG_END()
+#define BREAK()
+#endif
+
+#ifdef __LWIP_DEBUG
+#ifndef __SNPRINTF
+#define __SNPRINTF
+#include "mbed.h"
+
+//int snprintf(char *str, int size, const char *format, ...);
+#endif
+#endif
+
+#ifdef __LWIP_DEBUG
+#undef __DEBUG
+#endif
+
+//#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPClient/LPC2368/services/http/client/HTTPClient.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,306 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+ 
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+ 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+/** \file
+HTTP Client header file
+*/
+
+#ifndef HTTP_CLIENT_H
+#define HTTP_CLIENT_H
+
+class HTTPData;
+
+#include "core/net.h"
+#include "api/TCPSocket.h"
+#include "api/DNSRequest.h"
+#include "HTTPData.h"
+#include "mbed.h"
+
+#include <string>
+using std::string;
+
+#include <map>
+using std::map;
+
+///HTTP client results
+enum HTTPResult
+{
+  HTTP_OK, ///<Success
+  HTTP_PROCESSING, ///<Processing
+  HTTP_PARSE, ///<URI Parse error
+  HTTP_DNS, ///<Could not resolve name
+  HTTP_PRTCL, ///<Protocol error
+  HTTP_NOTFOUND, ///<HTTP 404 Error
+  HTTP_REFUSED, ///<HTTP 403 Error
+  HTTP_ERROR, ///<HTTP xxx error
+  HTTP_TIMEOUT, ///<Connection timeout
+  HTTP_CONN ///<Connection error
+};
+
+#include "core/netservice.h"
+
+///A simple HTTP Client
+/**
+The HTTPClient is composed of:
+- The actual client (HTTPClient)
+- Classes that act as a data repository, each of which deriving from the HTTPData class (HTTPText for short text content, HTTPFile for file I/O, HTTPMap for key/value pairs, and HTTPStream for streaming purposes)
+*/
+class HTTPClient : protected NetService
+{
+public:
+  ///Instantiates the HTTP client
+  HTTPClient();
+  virtual ~HTTPClient();
+  
+  ///Provides a basic authentification feature (Base64 encoded username and password)
+  void basicAuth(const char* user, const char* password); //Basic Authentification
+  
+  //High Level setup functions
+  ///Executes a GET Request (blocking)
+  /**
+  Executes a GET request on the URI uri
+  @param uri : URI on which to execute the request
+  @param pDataIn : pointer to an HTTPData instance that will collect the data returned by the request, can be NULL
+  Blocks until completion
+  */
+  HTTPResult get(const char* uri, HTTPData* pDataIn); //Blocking
+  
+  ///Executes a GET Request (non blocking)
+  /**
+  Executes a GET request on the URI uri
+  @param uri : URI on which to execute the request
+  @param pDataIn : pointer to an HTTPData instance that will collect the data returned by the request, can be NULL
+  @param pMethod : callback function
+  The function returns immediately and calls the callback on completion or error
+  */
+  HTTPResult get(const char* uri, HTTPData* pDataIn, void (*pMethod)(HTTPResult)); //Non blocking
+  
+  ///Executes a GET Request (non blocking)
+  /**
+  Executes a GET request on the URI uri
+  @param uri : URI on which to execute the request
+  @param pDataIn : pointer to an HTTPData instance that will collect the data returned by the request, can be NULL
+  @param pItem : instance of class on which to execute the callback method
+  @param pMethod : callback method
+  The function returns immediately and calls the callback on completion or error
+  */
+  template<class T> 
+  HTTPResult get(const char* uri, HTTPData* pDataIn, T* pItem, void (T::*pMethod)(HTTPResult)) //Non blocking
+  {
+    setOnResult(pItem, pMethod);
+    doGet(uri, pDataIn);
+    return HTTP_PROCESSING;
+  }
+  
+  ///Executes a POST Request (blocking)
+  /**
+  Executes a POST request on the URI uri
+  @param uri : URI on which to execute the request
+  @param dataOut : a HTTPData instance that contains the data that will be posted
+  @param pDataIn : pointer to an HTTPData instance that will collect the data returned by the request, can be NULL
+  Blocks until completion
+  */
+  HTTPResult post(const char* uri, const HTTPData& dataOut, HTTPData* pDataIn); //Blocking
+  
+  ///Executes a POST Request (non blocking)
+  /**
+  Executes a POST request on the URI uri
+  @param uri : URI on which to execute the request
+  @param dataOut : a HTTPData instance that contains the data that will be posted
+  @param pDataIn : pointer to an HTTPData instance that will collect the data returned by the request, can be NULL
+  @param pMethod : callback function
+  The function returns immediately and calls the callback on completion or error
+  */
+  HTTPResult post(const char* uri, const HTTPData& dataOut, HTTPData* pDataIn, void (*pMethod)(HTTPResult)); //Non blocking
+  
+  ///Executes a POST Request (non blocking)
+  /**
+  Executes a POST request on the URI uri
+  @param uri : URI on which to execute the request
+  @param dataOut : a HTTPData instance that contains the data that will be posted
+  @param pDataIn : pointer to an HTTPData instance that will collect the data returned by the request, can be NULL
+  @param pItem : instance of class on which to execute the callback method
+  @param pMethod : callback method
+  The function returns immediately and calls the callback on completion or error
+  */
+  template<class T> 
+  HTTPResult post(const char* uri, const HTTPData& dataOut, HTTPData* pDataIn, T* pItem, void (T::*pMethod)(HTTPResult)) //Non blocking  
+  {
+    setOnResult(pItem, pMethod);
+    doPost(uri, dataOut, pDataIn);
+    return HTTP_PROCESSING;
+  }
+
+  ///Executes a GET Request (non blocking)
+  /**
+  Executes a GET request on the URI uri
+  @param uri : URI on which to execute the request
+  @param pDataIn : pointer to an HTTPData instance that will collect the data returned by the request, can be NULL
+  The function returns immediately and calls the previously set callback on completion or error
+  */  
+  void doGet(const char* uri, HTTPData* pDataIn);  
+  
+  ///Executes a POST Request (non blocking)
+  /**
+  Executes a POST request on the URI uri
+  @param uri : URI on which to execute the request
+  @param dataOut : a HTTPData instance that contains the data that will be posted
+  @param pDataIn : pointer to an HTTPData instance that will collect the data returned by the request, can be NULL
+  @param pMethod : callback function
+  The function returns immediately and calls the previously set callback on completion or error
+  */
+  void doPost(const char* uri, const HTTPData& dataOut, HTTPData* pDataIn); 
+  
+  ///Setups the result callback
+  /**
+  @param pMethod : callback function
+  */
+  void setOnResult( void (*pMethod)(HTTPResult) );
+  
+  ///Setups the result callback
+  /**
+  @param pItem : instance of class on which to execute the callback method
+  @param pMethod : callback method
+  */
+  class CDummy;
+  template<class T> 
+  void setOnResult( T* pItem, void (T::*pMethod)(HTTPResult) )
+  {
+    m_pCb = NULL;
+    m_pCbItem = (CDummy*) pItem;
+    m_pCbMeth = (void (CDummy::*)(HTTPResult)) pMethod;
+  }
+
+  ///Setups timeout
+  /**
+  @param ms : time of connection inactivity in ms after which the request should timeout
+  */
+  void setTimeout(int ms);
+  
+  virtual void poll(); //Called by NetServices
+  
+  ///Gets last request's HTTP response code
+  /**
+  @return The HTTP response code of the last request
+  */
+  int getHTTPResponseCode();
+  
+  ///Sets a specific request header
+  void setRequestHeader(const string& header, const string& value);
+  
+  ///Gets a response header
+  string& getResponseHeader(const string& header);
+  
+  ///Clears request headers
+  void resetRequestHeaders();
+  
+protected:
+  void resetTimeout();
+  
+  void init();
+  void close();
+  
+  void setup(const char* uri, HTTPData* pDataOut, HTTPData* pDataIn); //Setup request, make DNS Req if necessary
+  void connect(); //Start Connection
+  
+  int  tryRead(); //Read data and try to feed output
+  void readData(); //Data has been read
+  void writeData(); //Data has been written & buf is free
+  
+  void onTCPSocketEvent(TCPSocketEvent e);
+  void onDNSReply(DNSReply r);
+  void onResult(HTTPResult r); //Called when exchange completed or on failure
+  void onTimeout(); //Connection has timed out
+  
+private:
+  HTTPResult blockingProcess(); //Called in blocking mode, calls Net::poll() until return code is available
+
+  bool readHeaders(); //Called first when receiving data
+  bool writeHeaders(); //Called to create req
+  int readLine(char* str, int maxLen, bool* pIncomplete = NULL);
+  
+  enum HTTP_METH
+  {
+    HTTP_GET,
+    HTTP_POST,
+    HTTP_HEAD
+  };
+  
+  HTTP_METH m_meth;
+  
+  CDummy* m_pCbItem;
+  void (CDummy::*m_pCbMeth)(HTTPResult);
+  
+  void (*m_pCb)(HTTPResult);
+  
+  TCPSocket* m_pTCPSocket;
+  map<string, string> m_reqHeaders;
+  map<string, string> m_respHeaders;
+  
+  Timer m_watchdog;
+  int m_timeout;
+  
+  DNSRequest* m_pDnsReq;
+  
+  Host m_server;
+  string m_path;
+  
+  bool m_closed;
+  
+  enum HTTPStep
+  {
+   // HTTP_INIT,
+    HTTP_WRITE_HEADERS,
+    HTTP_WRITE_DATA,
+    HTTP_READ_HEADERS,
+    HTTP_READ_DATA,
+    HTTP_READ_DATA_INCOMPLETE,
+    HTTP_DONE,
+    HTTP_CLOSED
+  };
+  
+  HTTPStep m_state;
+  
+  HTTPData* m_pDataOut;
+  HTTPData* m_pDataIn;
+  
+  bool m_dataChunked; //Data is encoded as chunks
+  int m_dataPos; //Position in data
+  int m_dataLen; //Data length
+  char* m_buf;
+  char* m_pBufRemaining; //Remaining
+  int m_bufRemainingLen; //Data length in m_pBufRemaining
+  
+  int m_httpResponseCode;
+  
+  HTTPResult m_blockingResult; //Result if blocking mode
+  
+};
+
+//Including data containers here for more convenience
+#include "data/HTTPFile.h"
+#include "data/HTTPStream.h"
+#include "data/HTTPText.h"
+#include "data/HTTPMap.h"
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPClient/LPC2368/services/http/client/HTTPData.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,58 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+ 
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+ 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+#ifndef HTTP_DATA_H
+#define HTTP_DATA_H
+
+#include "core/net.h"
+
+#include <string>
+using std::string;
+
+class HTTPData //This is a simple interface for HTTP data storage (impl examples are Key/Value Pairs, File, etc...)
+{
+public:
+  HTTPData();
+  virtual ~HTTPData();
+  
+  virtual void clear() = 0;
+
+protected:
+  friend class HTTPClient;
+  virtual int read(char* buf, int len) = 0;
+  virtual int write(const char* buf, int len) = 0;
+  
+  virtual string getDataType() = 0; //Internet media type for Content-Type header
+  virtual void setDataType(const string& type) = 0; //Internet media type from Content-Type header
+  
+  virtual bool getIsChunked() = 0; //For Transfer-Encoding header
+  virtual void setIsChunked(bool chunked) = 0; //From Transfer-Encoding header
+  
+  virtual int getDataLen() = 0; //For Content-Length header
+  virtual void setDataLen(int len) = 0; //From Content-Length header, or if the transfer is chunked, next chunk length
+  
+private:
+
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPClient/LPC2368/services/http/client/data/HTTPFile.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,81 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+ 
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+ 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+/** \file
+HTTP File data source/sink header file
+*/
+
+#ifndef HTTP_FILE_H
+#define HTTP_FILE_H
+
+#include "../HTTPData.h"
+#include "mbed.h"
+
+///HTTP Client data container for files
+/**
+This class provides file access/storage for HTTP requests and responses' data payloads.
+
+
+*/
+class HTTPFile : public HTTPData //Read or Write data from a file
+{
+public:
+  ///Instantiates data source/sink with file in param.
+  /**
+  Uses file at path @a path.
+  It will be opened when some data has to be read/written from/to it and closed when this operation is complete or on destruction of the instance.
+  Note that the file will be opened with mode "w" for writing and mode "r" for reading, so the file will be cleared between each request if you are using it for writing.
+  
+  @note
+  Note that to use this you must instantiate a proper file system (such as the LocalFileSystem or the SDFileSystem).
+  */
+  HTTPFile(const char* path);
+  virtual ~HTTPFile();
+  
+  ///Forces file closure
+  virtual void clear();
+
+protected:
+  virtual int read(char* buf, int len);
+  virtual int write(const char* buf, int len);
+  
+  virtual string getDataType(); //Internet media type for Content-Type header
+  virtual void setDataType(const string& type); //Internet media type from Content-Type header
+  
+  virtual bool getIsChunked(); //For Transfer-Encoding header
+  virtual void setIsChunked(bool chunked); //From Transfer-Encoding header  virtual
+  
+  virtual int getDataLen(); //For Content-Length header
+  virtual void setDataLen(int len); //From Content-Length header
+  
+private:
+  bool openFile(const char* mode); //true on success, false otherwise
+  void closeFile();
+
+  FILE* m_fp;
+  string m_path;
+  int m_len;
+  bool m_chunked;
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPClient/LPC2368/services/http/client/data/HTTPMap.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,89 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+ 
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+ 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+/** \file
+HTTP Map data source/sink header file
+*/
+
+#ifndef HTTP_MAP_H
+#define HTTP_MAP_H
+
+#include "../HTTPData.h"
+#include "mbed.h"
+
+#include <map>
+using std::map;
+
+typedef map<string, string> Dictionary;
+
+///HTTP Client data container for key/value pairs
+/**
+This class simplifies the use of key/value pairs requests and responses used widely among web APIs.
+Note that HTTPMap inherits from std::map<std::string,std::string>.
+You can therefore use any public method of that class, including the square brackets operator ( [ ] ) to access a value.
+
+The data is encoded or decoded to/from a key/value pairs-formatted string, after url-encoding/decoding.
+*/
+class HTTPMap : public HTTPData, public Dictionary //Key/Value pairs
+{
+public:
+  ///Instantiates map
+  /**
+  @param keyValueSep Key/Value separator (defaults to "=")
+  @param pairSep Pairs separator (defaults to "&")
+  */
+  HTTPMap(const string& keyValueSep = "=", const string& pairSep = "&");
+  virtual ~HTTPMap();
+  
+ /* string& operator[](const string& key);
+  int count();*/
+
+  ///Clears the content
+  virtual void clear();  
+  
+protected:
+  virtual int read(char* buf, int len);
+  virtual int write(const char* buf, int len);
+  
+  virtual string getDataType(); //Internet media type for Content-Type header
+  virtual void setDataType(const string& type); //Internet media type from Content-Type header
+  
+  virtual bool getIsChunked(); //For Transfer-Encoding header
+  virtual void setIsChunked(bool chunked); //From Transfer-Encoding header
+  
+  virtual int getDataLen(); //For Content-Length header
+  virtual void setDataLen(int len); //From Content-Length header
+  
+private:
+  void generateString();
+  void parseString();
+  //map<string, string> m_map;
+  string m_buf;
+  int m_len;
+  bool m_chunked;
+  
+  string m_keyValueSep;
+  string m_pairSep;
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPClient/LPC2368/services/http/client/data/HTTPStream.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,83 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+ 
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+ 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+#ifndef HTTP_STREAM_H
+#define HTTP_STREAM_H
+
+#include "../HTTPData.h"
+#include "mbed.h"
+
+/** \file
+HTTP Stream data source/sink header file
+*/
+
+typedef uint8_t byte;
+
+///HTTP Client Streaming tool
+/**
+This class allows you to stream data from the web using a persisting HTTP connection.
+To use it properly you must use a non-blocking HTTPClient method.
+*/
+class HTTPStream : public HTTPData //Streaming buf
+{
+public:
+  ///Instantiates the object
+  HTTPStream();
+  virtual ~HTTPStream();
+  
+  ///Starts to read into buffer
+  /**
+  Passes a buffer of address @a buf and size @a size to the instance.
+  When it receives data it will be stored in this buffer.
+  When the buffer is full it throttles the client until this function is called again.
+  */
+  void readNext(byte* buf, int size);
+  
+  ///Returns whether there is data available to read
+  bool readable();
+  
+  ///Returns the actual length of the payload written in the buffer
+  int readLen();
+  
+  virtual void clear();
+      
+protected:
+  virtual int read(char* buf, int len);
+  virtual int write(const char* buf, int len);
+  
+  virtual string getDataType(); //Internet media type for Content-Type header
+  virtual void setDataType(const string& type); //Internet media type from Content-Type header
+
+  virtual bool getIsChunked(); //For Transfer-Encoding header
+  virtual void setIsChunked(bool chunked); //From Transfer-Encoding header
+  
+  virtual int getDataLen(); //For Content-Length header
+  virtual void setDataLen(int len); //From Content-Length header, or if the transfer is chunked, next chunk length
+  
+private:
+  byte* m_buf;
+  int m_size; //Capacity
+  int m_len; //Length
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPClient/LPC2368/services/http/client/data/HTTPText.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,101 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+ 
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+ 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+/** \file
+HTTP Text data source/sink header file
+*/
+
+#ifndef HTTP_TEXT_H
+#define HTTP_TEXT_H
+
+#include "../HTTPData.h"
+#include "mbed.h"
+
+#define DEFAULT_MAX_MEM_ALLOC 512 //Avoid out-of-memory problems
+
+///HTTP Client data container for text
+/**
+This is a simple "Text" data repository for HTTP requests.
+*/
+class HTTPText : public HTTPData //Simple Text I/O
+{
+public:
+  ///Instantiates the object.
+  /**
+  @param encoding encoding of the data, it defaults to text/html.
+  @param maxSize defines the maximum memory size that can be allocated by the object. It defaults to 512 bytes.
+  */
+  HTTPText(const string& encoding = "text/html", int maxSize = DEFAULT_MAX_MEM_ALLOC);
+  virtual ~HTTPText();
+  
+  ///Gets text
+  /**
+  Returns the text in the container as a zero-terminated char*.
+  The array returned points to the internal buffer of the object and remains owned by the object.
+  */
+  const char* gets() const;
+  
+  //Puts text
+  /**
+  Sets the text in the container using a zero-terminated char*.
+  */
+  void puts(const char* str);
+  
+  ///Gets text
+  /**
+  Returns the text in the container as string.
+  */
+  string& get();
+  
+  ///Puts text
+  /**
+  Sets the text in the container as string.
+  */
+  void set(const string& str);
+  
+  ///Clears the content.
+  /**
+  If this container is used as a data sink, it is cleared by the HTTP Client at the beginning of the request.
+  */
+  virtual void clear();
+  
+protected:
+  virtual int read(char* buf, int len);
+  virtual int write(const char* buf, int len);
+  
+  virtual string getDataType(); //Internet media type for Content-Type header
+  virtual void setDataType(const string& type); //Internet media type from Content-Type header
+
+  virtual bool getIsChunked(); //For Transfer-Encoding header
+  virtual void setIsChunked(bool chunked); //From Transfer-Encoding header
+  
+  virtual int getDataLen(); //For Content-Length header
+  virtual void setDataLen(int len); //From Content-Length header, or if the transfer is chunked, next chunk length
+  
+private:
+  string m_buf;
+  string m_encoding;
+  int m_maxSize;
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPClient/LPC2368/services/http/util/base64.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,57 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+ 
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+ 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+#ifndef BASE64_H
+#define BASE64_H
+
+#include <string>
+using std::string;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//Originaly from Rolf's iputil.h
+
+unsigned int base64enc_len(const char *str);
+
+void base64enc(const char *input, unsigned int length, char *output);
+
+#ifdef __cplusplus
+}
+#endif
+
+class Base64
+{
+public:
+  static string encode(const string& str)
+  {
+    char* out = new char[ base64enc_len(str.c_str()) ];
+    base64enc(str.c_str(), str.length(), out);
+    string res(out);
+    delete[] out;
+    return res;
+  }
+};
+
+#endif /* LWIP_UTILS_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPClient/LPC2368/services/http/util/url.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,88 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+ 
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+ 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+#ifndef URL_H
+#define URL_H
+
+#include "core/ipaddr.h"
+
+#include <string>
+using std::string;
+
+#include "mbed.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+char *url_encode(char *str);
+char *url_decode(char *str);
+
+#ifdef __cplusplus
+}
+#endif
+
+class Url
+{
+public:
+  static string encode(const string& url)
+  {
+    char* c_res = url_encode( (char*) url.c_str() );
+    string res(c_res);
+    free(c_res); //Alloc'ed in url_encode()
+    return res;
+  }
+  
+  static string decode(const string& url)
+  {
+    char* c_res = url_decode( (char*) url.c_str() );
+    string res(c_res);
+    free(c_res); //Alloc'ed in url_decode()
+    return res;
+  }
+  
+  Url();
+
+  string getProtocol();
+  string getHost();
+  bool getHostIp(IpAddr* ip); //If host is in IP form, return true & proper object by ptr
+  uint16_t getPort();
+  string getPath();
+  
+  void setProtocol(string protocol);
+  void setHost(string host);
+  void setPort(uint16_t port);
+  void setPath(string path);
+  
+  void fromString(string str);
+  string toString();
+
+private:
+  string m_protocol;
+  string m_host;
+  uint16_t m_port;
+  string m_path;
+  
+};
+
+#endif /* LWIP_UTILS_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MODDMA/CONFIG.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,95 @@
+/*
+    Copyright (c) 2010 Andy Kirkham
+ 
+    Permission is hereby granted, free of charge, to any person obtaining a copy
+    of this software and associated documentation files (the "Software"), to deal
+    in the Software without restriction, including without limitation the rights
+    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+    copies of the Software, and to permit persons to whom the Software is
+    furnished to do so, subject to the following conditions:
+ 
+    The above copyright notice and this permission notice shall be included in
+    all copies or substantial portions of the Software.
+ 
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+    THE SOFTWARE.
+*/
+
+#ifdef NOCOMPILE
+
+#ifndef MODDMA_CONFIG_H
+#define MODDMA_CONFIG_H
+
+#include "mbed.h"
+
+namespace AjK {
+
+// Forward reference.
+class MODDMA;
+
+class  MODDMA_Channel_CFG_t {
+public:
+
+    // *****************************************
+    // From GPDMA by NXP MCU SW Application Team
+    // *****************************************
+    
+    uint32_t ChannelNum;        //!< DMA channel number, should be in range from 0 to 7. 
+    uint32_t TransferSize;      //!< Length/Size of transfer 
+    uint32_t TransferWidth;     //!< Transfer width - used for TransferType is GPDMA_TRANSFERTYPE_m2m only 
+    uint32_t SrcMemAddr;        //!< Physical Src Addr, used in case TransferType is chosen as MODDMA::GPDMA_TRANSFERTYPE::m2m or MODDMA::GPDMA_TRANSFERTYPE::m2p 
+    uint32_t DstMemAddr;        //!< Physical Destination Address, used in case TransferType is chosen as MODDMA::GPDMA_TRANSFERTYPE::m2m or MODDMA::GPDMA_TRANSFERTYPE::p2m 
+    uint32_t TransferType;      //!< Transfer Type
+    uint32_t SrcConn;           ///!< Peripheral Source Connection type, used in case TransferType is chosen as
+    uint32_t DstConn;           //!< Peripheral Destination Connection type, used in case TransferType is chosen as
+    uint32_t DMALLI;            //!< Linker List Item structure data address if there's no Linker List, set as '0'
+    
+    // Mbed specifics.
+    
+    MODDMA_Channel_CFG_t() {
+        isrIntTCStat  = new FunctionPointer;
+        isrIntErrStat = new FunctionPointer;
+    }
+    
+    ~MODDMA_Channel_CFG_t() {
+        delete(isrIntTCStat);
+        delete(isrIntErrStat);
+    }
+        
+    class MODDMA_Channel_CFG_t * channelNum(uint32_t n)    { ChannelNum = n;    return this; }
+    class MODDMA_Channel_CFG_t * transferSize(uint32_t n)  { TransferSize = n;  return this; }
+    class MODDMA_Channel_CFG_t * transferWidth(uint32_t n) { TransferWidth = n; return this; }
+    class MODDMA_Channel_CFG_t * srcMemAddr(uint32_t n)    { SrcMemAddr = n;    return this; }
+    class MODDMA_Channel_CFG_t * dstMemAddr(uint32_t n)    { DstMemAddr = n;    return this; }
+    class MODDMA_Channel_CFG_t * transferType(uint32_t n)  { TransferType = n;  return this; }
+    class MODDMA_Channel_CFG_t * srcConn(uint32_t n)       { SrcConn = n;       return this; }
+    class MODDMA_Channel_CFG_t * dstConn(uint32_t n)       { DstConn = n;       return this; }
+    class MODDMA_Channel_CFG_t * dmaLLI(uint32_t n)        { DMALLI = n;        return this; }
+    
+    uint32_t channelNum(void) { return ChannelNum; }
+    
+    FunctionPointer *isrIntTCStat;                        
+    FunctionPointer *isrIntErrStat;                        
+};
+
+/**
+ * @brief GPDMA Linker List Item structure type definition
+ */
+class GPDMA_LLI_t 
+{
+public:
+    uint32_t SrcAddr;    //!< Source Address 
+    uint32_t DstAddr;    //!< Destination address 
+    uint32_t NextLLI;    //!< Next LLI address, otherwise set to '0' 
+    uint32_t Control;    //!< GPDMA Control of this LLI 
+};
+
+}; // namespace AjK ends.
+
+#endif 
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MODDMA/ChangeLog.c	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,74 @@
+/* $Id:$
+
+1.12- 14 Mar 2011
+
+    * Added example4.h that demonstrates alternately sending
+      two buffers (double buffering) to the DAC. All those
+      people building MP3 players may find this of interest.
+      
+1.11- 13 Mar 2011
+
+    * Fixed a silly typo in the documentation of example3.h
+    
+1.10- 13 Mar 2011
+
+    * The rescheduling showed the timer being stopped and restarted
+      to perform a new scheduled grab. This was changed to show the 
+      timer free running and the reschedules being setup.
+
+1.9 - 13 Mar 2011
+
+    * Improved example3.h to add rescheduling additional grabs
+      based on the timer setup.
+      
+1.8 - 13 Mar 2011
+
+    * Renamed example files to .h
+    * Added pseudo g2m and m2g transferTypes to support GPIO 
+      "memory moves" but triggered by peripheral timer. To 
+      support this new operating mode added example3.h
+    
+1.7 - 13 Mar 2011
+
+    * Remove the test at the beginning of the channel setup.
+    
+1.6 - 8 Mar 2011
+      
+    * Fixed a typo bug. Reported by Wim van der Vegt
+      http://mbed.org/forum/mbed/topic/1798/?page=1#comment-9845
+      
+1.5 - 5 Feb 2011
+
+    * Found a bug in the NXP library that I had copied over.
+      http://mbed.org/forum/mbed/topic/1798
+    * Added example2.cpp to support that forum thread.
+      
+1.4 - 23/11/2010
+
+    * Added some extra overloaded methods to make calling certain
+      userland API methods simpler.
+      
+1.3 - 23/10/2010
+
+    * Added the LLI class wrapper.
+    * Added checking channel's LLI for non-null before auto-disable
+      of a channel with the ISR.
+    * Tested with MODSERIAL which is now natively MODDMA "aware".
+      MODSERIAL can now, using MODDMA, send blocks of bytes out
+      of it's TX port under DMA control.
+        
+1.2 - 23/10/2010
+
+    * Improved the IRQ callback attachment API to make 
+      easier attachments when creating configurations.
+      
+1.1 - 23/10/2010
+
+    * Tidied up example1.cpp
+    * Removed some unneeded methoids that cause compiler errs.
+    
+1.0 - 23/11/2010
+
+    * First release
+
+*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MODDMA/DATALUTS.cpp	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,147 @@
+/*
+    Copyright (c) 2010 Andy Kirkham
+ 
+    Permission is hereby granted, free of charge, to any person obtaining a copy
+    of this software and associated documentation files (the "Software"), to deal
+    in the Software without restriction, including without limitation the rights
+    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+    copies of the Software, and to permit persons to whom the Software is
+    furnished to do so, subject to the following conditions:
+ 
+    The above copyright notice and this permission notice shall be included in
+    all copies or substantial portions of the Software.
+ 
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+    THE SOFTWARE.
+*/
+
+#include "MODDMA.h"
+
+#ifndef MBED_H
+#include "mbed.h"
+#endif
+
+#ifndef MODDMA_CONFIG_H
+#include "CONFIG.h"
+#endif
+
+namespace AjK {
+
+uint32_t
+MODDMA::LUTPerAddr(int n)
+{
+    const uint32_t lut[] = { 
+          (uint32_t)&LPC_SSP0->DR         // SSP0 Tx
+        , (uint32_t)&LPC_SSP0->DR         // SSP0 Rx
+        , (uint32_t)&LPC_SSP1->DR         // SSP1 Tx
+        , (uint32_t)&LPC_SSP1->DR         // SSP1 Rx
+        , (uint32_t)&LPC_ADC->ADGDR       // ADC
+        , (uint32_t)&LPC_I2S->I2STXFIFO   // I2S Tx
+        , (uint32_t)&LPC_I2S->I2SRXFIFO   // I2S Rx
+        , (uint32_t)&LPC_DAC->DACR        // DAC
+        , (uint32_t)&LPC_UART0->THR       // UART0 Tx
+        , (uint32_t)&LPC_UART0->RBR       // UART0 Rx
+        , (uint32_t)&LPC_UART1->THR       // UART1 Tx
+        , (uint32_t)&LPC_UART1->RBR       // UART1 Rx
+        , (uint32_t)&LPC_UART2->THR       // UART2 Tx
+        , (uint32_t)&LPC_UART2->RBR       // UART2 Rx
+        , (uint32_t)&LPC_UART3->THR       // UART3 Tx
+        , (uint32_t)&LPC_UART3->RBR       // UART3 Rx
+        , (uint32_t)&LPC_TIM0->MR0        // MAT0.0
+        , (uint32_t)&LPC_TIM0->MR1        // MAT0.1
+        , (uint32_t)&LPC_TIM1->MR0        // MAT1.0
+        , (uint32_t)&LPC_TIM1->MR1        // MAT1.1
+        , (uint32_t)&LPC_TIM2->MR0        // MAT2.0
+        , (uint32_t)&LPC_TIM2->MR1        // MAT2.1
+        , (uint32_t)&LPC_TIM3->MR0        // MAT3.0
+        , (uint32_t)&LPC_TIM3->MR1        // MAT3.1   
+    };
+    return lut[n & 0xFF];    
+}
+
+uint32_t
+MODDMA::Channel_p(int channel)
+{
+    const uint32_t lut[] = {
+          (uint32_t)LPC_GPDMACH0
+        , (uint32_t)LPC_GPDMACH1
+        , (uint32_t)LPC_GPDMACH2
+        , (uint32_t)LPC_GPDMACH3
+        , (uint32_t)LPC_GPDMACH4
+        , (uint32_t)LPC_GPDMACH5
+        , (uint32_t)LPC_GPDMACH6
+        , (uint32_t)LPC_GPDMACH7
+    };
+    return lut[channel & 0xFF];
+}
+
+uint8_t
+MODDMA::LUTPerBurst(int n)
+{
+    const uint8_t lut[] = {
+          (uint8_t)_4       // SSP0 Tx 
+        , (uint8_t)_4       // SSP0 Rx
+        , (uint8_t)_4       // SSP1 Tx
+        , (uint8_t)_4       // SSP1 Rx
+        , (uint8_t)_1       // ADC
+        , (uint8_t)_32      // I2S channel 0
+        , (uint8_t)_32      // I2S channel 1
+        , (uint8_t)_1       // DAC
+        , (uint8_t)_1       // UART0 Tx
+        , (uint8_t)_1       // UART0 Rx
+        , (uint8_t)_1       // UART1 Tx
+        , (uint8_t)_1       // UART1 Rx
+        , (uint8_t)_1       // UART2 Tx
+        , (uint8_t)_1       // UART2 Rx
+        , (uint8_t)_1       // UART3 Tx
+        , (uint8_t)_1       // UART3 Rx
+        , (uint8_t)_1       // MAT0.0
+        , (uint8_t)_1       // MAT0.1
+        , (uint8_t)_1       // MAT1.0
+        , (uint8_t)_1       // MAT1.1
+        , (uint8_t)_1       // MAT2.0
+        , (uint8_t)_1       // MAT2.1
+        , (uint8_t)_1       // MAT3.0
+        , (uint8_t)_1       // MAT3.1
+    };
+    return lut[n & 0xFFF];
+}
+
+uint8_t
+MODDMA::LUTPerWid(int n)
+{
+    const uint8_t lut[] = {
+          (uint8_t)byte      // SSP0 Tx
+        , (uint8_t)byte      // SSP0 Rx
+        , (uint8_t)byte      // SSP1 Tx
+        , (uint8_t)byte      // SSP1 Rx
+        , (uint8_t)word      // ADC
+        , (uint8_t)word      // I2S channel 0
+        , (uint8_t)word      // I2S channel 1
+        , (uint8_t)word      // DAC 
+        , (uint8_t)byte      // UART0 Tx
+        , (uint8_t)byte      // UART0 Rx
+        , (uint8_t)byte      // UART1 Tx
+        , (uint8_t)byte      // UART1 Rx
+        , (uint8_t)byte      // UART2 Tx
+        , (uint8_t)byte      // UART2 Rx
+        , (uint8_t)byte      // UART3 Tx
+        , (uint8_t)byte      // UART3 Rx  
+        , (uint8_t)word      // MAT0.0
+        , (uint8_t)word      // MAT0.1
+        , (uint8_t)word      // MAT1.0
+        , (uint8_t)word      // MAT1.1
+        , (uint8_t)word      // MAT2.0
+        , (uint8_t)word      // MAT2.1
+        , (uint8_t)word      // MAT3.0
+        , (uint8_t)word      // MAT3.1  
+    };
+    return lut[n & 0xFFF];
+}
+
+}; // namespace AjK ends
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MODDMA/INIT.cpp	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,69 @@
+/*
+    Copyright (c) 2010 Andy Kirkham
+ 
+    Permission is hereby granted, free of charge, to any person obtaining a copy
+    of this software and associated documentation files (the "Software"), to deal
+    in the Software without restriction, including without limitation the rights
+    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+    copies of the Software, and to permit persons to whom the Software is
+    furnished to do so, subject to the following conditions:
+ 
+    The above copyright notice and this permission notice shall be included in
+    all copies or substantial portions of the Software.
+ 
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+    THE SOFTWARE.
+*/
+
+#include "MODDMA.h"
+
+namespace AjK {
+
+extern uint32_t oldDMAHandler;
+extern "C" void MODDMA_IRQHandler(void);
+extern class MODDMA *moddma_p;
+
+void
+MODDMA::init(bool isConstructorCalling, int Channels, int Tc, int Err)
+{
+    if (isConstructorCalling) {    
+        if (LPC_SC->PCONP & (1UL << 29)) {
+            if (LPC_GPDMA->DMACConfig & 1) {
+                error("Only one instance of MODDMA can exist.");
+            }
+        }
+        LPC_SC->PCONP |= (1UL << 29);
+        LPC_GPDMA->DMACConfig = 1;
+        moddma_p = this;
+        for (int i = 0; i < 8; i++) {
+            setups[i] = (MODDMA_Config *)NULL;
+        }        
+    }
+    
+    // Reset channel configuration register(s)
+    if (Channels & 0x01) LPC_GPDMACH0->DMACCConfig = 0;
+    if (Channels & 0x02) LPC_GPDMACH1->DMACCConfig = 0;
+    if (Channels & 0x04) LPC_GPDMACH2->DMACCConfig = 0;
+    if (Channels & 0x08) LPC_GPDMACH3->DMACCConfig = 0;
+    if (Channels & 0x10) LPC_GPDMACH4->DMACCConfig = 0;
+    if (Channels & 0x20) LPC_GPDMACH5->DMACCConfig = 0;
+    if (Channels & 0x40) LPC_GPDMACH6->DMACCConfig = 0;
+    if (Channels & 0x80) LPC_GPDMACH7->DMACCConfig = 0;
+
+    /* Clear DMA interrupt and error flag */
+    LPC_GPDMA->DMACIntTCClear = Tc;
+    LPC_GPDMA->DMACIntErrClr  = Err;
+    
+    if (isConstructorCalling) {    
+        oldDMAHandler = NVIC_GetVector(DMA_IRQn);
+        NVIC_SetVector(DMA_IRQn, (uint32_t)MODDMA_IRQHandler);
+        NVIC_EnableIRQ(DMA_IRQn);
+    }
+}
+
+}; // namespace AjK ends
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MODDMA/MODDMA.cpp	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,157 @@
+/*
+    Copyright (c) 2010 Andy Kirkham
+ 
+    Permission is hereby granted, free of charge, to any person obtaining a copy
+    of this software and associated documentation files (the "Software"), to deal
+    in the Software without restriction, including without limitation the rights
+    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+    copies of the Software, and to permit persons to whom the Software is
+    furnished to do so, subject to the following conditions:
+ 
+    The above copyright notice and this permission notice shall be included in
+    all copies or substantial portions of the Software.
+ 
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+    THE SOFTWARE.
+*/
+#include "iomacros.h"
+#include "MODDMA.h"
+
+namespace AjK {
+
+// Create a "hook" for our ISR to make callbacks. Set by init()
+class MODDMA *moddma_p = (class MODDMA *)NULL;
+
+void
+MODDMA::Enable(CHANNELS ChannelNumber)
+{
+    LPC_GPDMACH_TypeDef *pChannel = (LPC_GPDMACH_TypeDef *)Channel_p( ChannelNumber );
+    pChannel->DMACCConfig |= _E;
+}
+
+bool
+MODDMA::Enabled(CHANNELS ChannelNumber)
+{
+    LPC_GPDMACH_TypeDef *pChannel = (LPC_GPDMACH_TypeDef *)Channel_p( ChannelNumber );    
+    return (bool)(pChannel->DMACCConfig & _E);
+}
+
+void
+MODDMA::Disable(CHANNELS ChannelNumber)
+{
+    LPC_GPDMACH_TypeDef *pChannel = (LPC_GPDMACH_TypeDef *)Channel_p( ChannelNumber );
+    pChannel->DMACCConfig &= ~(_E);
+}
+
+bool
+MODDMA::isActive(CHANNELS ChannelNumber)
+{
+    LPC_GPDMACH_TypeDef *pChannel = (LPC_GPDMACH_TypeDef *)Channel_p( ChannelNumber );
+    return (bool)( pChannel->DMACCConfig & CxConfig_A() ) ;
+}
+
+void 
+MODDMA::haltChannel(CHANNELS ChannelNumber)
+{
+    LPC_GPDMACH_TypeDef *pChannel = (LPC_GPDMACH_TypeDef *)Channel_p( ChannelNumber );
+    pChannel->DMACCConfig |= CxConfig_H();
+}
+
+uint32_t 
+MODDMA::getControl(CHANNELS ChannelNumber)
+{
+    LPC_GPDMACH_TypeDef *pChannel = (LPC_GPDMACH_TypeDef *)Channel_p( ChannelNumber );
+    return pChannel->DMACCControl;
+}
+
+uint32_t oldDMAHandler = 0;
+typedef void (*MODDMA_FN)(void);
+
+extern "C" void MODDMA_IRQHandler(void) {
+    uint32_t channel_mask;
+        
+    if (moddma_p == (class MODDMA *)NULL) {
+        if (oldDMAHandler) {
+            ((MODDMA_FN)oldDMAHandler)();
+            return;
+        }
+        else {
+            error("Interrupt without instance");
+        }
+    }
+    
+    for (int channel_number = 0; channel_number < 8; channel_number++) {
+        channel_mask = (1UL << channel_number);
+        if (LPC_GPDMA->DMACIntStat & channel_mask) {
+            if (LPC_GPDMA->DMACIntTCStat & channel_mask) {
+                if (moddma_p->setups[channel_number] != (MODDMA_Config *)NULL) {
+                    moddma_p->setIrqProcessingChannel((MODDMA::CHANNELS)channel_number);
+                    moddma_p->setIrqType(MODDMA::TcIrq);
+                    moddma_p->setups[channel_number]->isrIntTCStat->call();
+                    moddma_p->isrIntTCStat.call();
+                    // The user callback should clear the IRQ. But if they forget
+                    // then the Mbed will lockup. So, check to see if the IRQ has
+                    // been dismissed, if not, we will dismiss it here.
+                    if (LPC_GPDMA->DMACIntTCStat & channel_mask) {
+                        LPC_GPDMA->DMACIntTCClear = channel_mask;
+                    }
+                    // If the user has left the channel enabled, disable it.
+                    // Note, we don't check Active here as it may block inside
+                    // an ISR, we just shut it down immediately. If the user
+                    // must wait for completion they should implement their
+                    // own ISR. But only disable if the LLI linked list register
+                    // is null otherwise we can crap out a series of transfers.
+                    if (moddma_p->Enabled( (MODDMA::CHANNELS)channel_number )) {
+                        if (moddma_p->lli( (MODDMA::CHANNELS)channel_number ) == 0 ) {
+                            moddma_p->Disable( (MODDMA::CHANNELS)channel_number ); 
+                        }
+                    }
+                }            
+            }
+            
+            if (LPC_GPDMA->DMACIntErrStat & channel_mask) {
+                if (moddma_p->setups[channel_number] != (MODDMA_Config *)NULL) {
+                    moddma_p->setIrqProcessingChannel((MODDMA::CHANNELS)channel_number);
+                    moddma_p->setIrqType(MODDMA::ErrIrq);
+                    moddma_p->setups[channel_number]->isrIntErrStat->call();
+                    moddma_p->isrIntErrStat.call();
+                    // The user callback should clear the IRQ. But if they forget
+                    // then the Mbed will lockup. So, check to see if the IRQ has
+                    // been dismissed, if not, we will dismiss it here.
+                    if (LPC_GPDMA->DMACIntErrStat & channel_mask) {
+                        LPC_GPDMA->DMACIntErrClr = channel_mask;
+                    }
+                    // If the user has left the channel enabled, disable it.
+                    // Not, we don't check Active here as it may block inside
+                    // an ISR, we just shut it down immediately. If the user
+                    // must wait for completion they should implement their
+                    // own ISR. But only disable if the LLI linked list register
+                    // is null otherwise we can crap out a series of transfers.
+                    if (moddma_p->Enabled( (MODDMA::CHANNELS)channel_number )) {
+                        if (moddma_p->lli( (MODDMA::CHANNELS)channel_number ) == 0 ) {
+                            moddma_p->Disable( (MODDMA::CHANNELS)channel_number ); 
+                        }
+                    }
+                }            
+            }
+        }
+    }
+    
+    /* IRQ should be handled by now, check to make sure. */
+    if (LPC_GPDMA->DMACIntStat) {
+        ((MODDMA_FN)oldDMAHandler)();
+        LPC_GPDMA->DMACIntTCClear = (uint32_t)0xFF; /* If not, clear anyway! */
+    }
+    if (LPC_GPDMA->DMACIntErrStat) {
+        ((MODDMA_FN)oldDMAHandler)();
+        LPC_GPDMA->DMACIntErrClr = (uint32_t)0xFF; /* If not, clear anyway! */
+    }
+}
+
+}; // namespace AjK ends
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MODDMA/MODDMA.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,693 @@
+/*
+    Copyright (c) 2010 Andy Kirkham
+ 
+    Permission is hereby granted, free of charge, to any person obtaining a copy
+    of this software and associated documentation files (the "Software"), to deal
+    in the Software without restriction, including without limitation the rights
+    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+    copies of the Software, and to permit persons to whom the Software is
+    furnished to do so, subject to the following conditions:
+ 
+    The above copyright notice and this permission notice shall be included in
+    all copies or substantial portions of the Software.
+ 
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+    THE SOFTWARE.
+    
+    @file          MODDMA.h 
+    @purpose       Adds DMA controller and multiple transfer configurations
+    @version       see ChangeLog.c
+    @date          Nov 2010
+    @author        Andy Kirkham    
+*/
+
+#ifndef MODDMA_H
+#define MODDMA_H
+
+/** @defgroup API The MODDMA API */
+/** @defgroup MISC Misc MODSERIAL functions */
+/** @defgroup INTERNALS MODSERIAL Internals */
+
+#include "mbed.h"
+#include "iomacros.h"
+
+namespace AjK {
+
+/**
+ * @brief The MODDMA configuration system
+ * @author Andy Kirkham
+ * @see http://mbed.org/cookbook/MODDMA_Config
+ * @see MODDMA
+ * @see API 
+ *
+ * <b>MODDMA_Config</b> defines a configuration that can be passed to the MODDMA controller
+ * instance to perform a GPDMA data transfer.
+ */
+class  MODDMA_Config {
+protected:
+
+    // *****************************************
+    // From GPDMA by NXP MCU SW Application Team
+    // *****************************************
+    
+    uint32_t ChannelNum;        //!< DMA channel number, should be in range from 0 to 7. 
+    uint32_t TransferSize;      //!< Length/Size of transfer 
+    uint32_t TransferWidth;     //!< Transfer width - used for TransferType is GPDMA_TRANSFERTYPE_m2m only 
+    uint32_t SrcMemAddr;        //!< Physical Src Addr, used in case TransferType is chosen as MODDMA::GPDMA_TRANSFERTYPE::m2m or MODDMA::GPDMA_TRANSFERTYPE::m2p 
+    uint32_t DstMemAddr;        //!< Physical Destination Address, used in case TransferType is chosen as MODDMA::GPDMA_TRANSFERTYPE::m2m or MODDMA::GPDMA_TRANSFERTYPE::p2m 
+    uint32_t TransferType;      //!< Transfer Type
+    uint32_t SrcConn;           //!< Peripheral Source Connection type, used in case TransferType is chosen as
+    uint32_t DstConn;           //!< Peripheral Destination Connection type, used in case TransferType is chosen as
+    uint32_t DMALLI;            //!< Linker List Item structure data address if there's no Linker List, set as '0'
+    uint32_t DMACSync;          //!< DMACSync if required.
+    
+    // Mbed specifics.
+
+public: 
+   
+    MODDMA_Config() {
+        isrIntTCStat  = new FunctionPointer;
+        isrIntErrStat = new FunctionPointer;
+        ChannelNum    = 0xFFFF;
+        TransferSize  = 0;
+        TransferWidth = 0;
+        SrcMemAddr    = 0;
+        DstMemAddr    = 0;
+        TransferType  = 0;
+        SrcConn       = 0;
+        DstConn       = 0;
+        DMALLI        = 0;
+        DMACSync      = 0;
+    }
+    
+    ~MODDMA_Config() {
+        delete(isrIntTCStat);
+        delete(isrIntErrStat);
+    }
+        
+    class MODDMA_Config * channelNum(uint32_t n)    { ChannelNum = n & 0x7;  return this; }
+    class MODDMA_Config * transferSize(uint32_t n)  { TransferSize = n;      return this; }
+    class MODDMA_Config * transferWidth(uint32_t n) { TransferWidth = n;     return this; }
+    class MODDMA_Config * srcMemAddr(uint32_t n)    { SrcMemAddr = n;        return this; }
+    class MODDMA_Config * dstMemAddr(uint32_t n)    { DstMemAddr = n;        return this; }
+    class MODDMA_Config * transferType(uint32_t n)  { TransferType = n;      return this; }
+    class MODDMA_Config * srcConn(uint32_t n)       { SrcConn = n;           return this; }
+    class MODDMA_Config * dstConn(uint32_t n)       { DstConn = n;           return this; }
+    class MODDMA_Config * dmaLLI(uint32_t n)        { DMALLI = n;            return this; }
+    class MODDMA_Config * dmacSync(uint32_t n)      { DMACSync = n;          return this; }
+    
+    uint32_t channelNum(void)    { return ChannelNum;    }
+    uint32_t transferSize(void)  { return TransferSize;  }
+    uint32_t transferWidth(void) { return TransferWidth; }
+    uint32_t srcMemAddr(void)    { return SrcMemAddr;    }
+    uint32_t dstMemAddr(void)    { return DstMemAddr;    }
+    uint32_t transferType(void)  { return TransferType;  }
+    uint32_t srcConn(void)       { return SrcConn;       }
+    uint32_t dstConn(void)       { return DstConn;       }
+    uint32_t dmaLLI(void)        { return DMALLI;        }
+    uint32_t dmacSync(void)      { return DMACSync; }
+    
+    /**
+     * Attach a callback to the TC IRQ configuration.
+     *
+     * @param fptr A function pointer to call
+     * @return this
+     */
+    class MODDMA_Config * attach_tc(void (*fptr)(void)) {  
+        isrIntTCStat->attach(fptr); 
+        return this;
+    }
+    
+    /**
+     * Attach a callback to the ERR IRQ configuration.
+     *
+     * @param fptr A function pointer to call
+     * @return this
+     */
+    class MODDMA_Config * attach_err(void (*fptr)(void)) {  
+        isrIntErrStat->attach(fptr);         
+        return this;
+    }
+    
+    /**
+     * Attach a callback to the TC IRQ configuration.
+     *
+     * @param tptr A template pointer to the calling object
+     * @param mptr A method pointer within the object to call.
+     * @return this
+     */
+    template<typename T>
+    class MODDMA_Config * attach_tc(T* tptr, void (T::*mptr)(void)) {  
+        if((mptr != NULL) && (tptr != NULL)) {
+            isrIntTCStat->attach(tptr, mptr);
+        }
+        return this;
+    }
+    
+    /**
+     * Attach a callback to the ERR IRQ configuration.
+     *
+     * @param tptr A template pointer to the calling object
+     * @param mptr A method pointer within the object to call.
+     * @return this
+     */
+    template<typename T>
+    class MODDMA_Config * attach_err(T* tptr, void (T::*mptr)(void)) {  
+        if((mptr != NULL) && (tptr != NULL)) {
+            isrIntErrStat->attach(tptr, mptr);
+        }
+        return this;
+    }
+    FunctionPointer *isrIntTCStat;                        
+    FunctionPointer *isrIntErrStat;                        
+};
+
+/**
+ * @brief The MODDMA configuration system (linked list items)
+ * @author Andy Kirkham
+ * @see http://mbed.org/cookbook/MODDMA_Config
+ * @see MODDMA
+ * @see MODDMA_Config
+ * @see API 
+ */
+class MODDMA_LLI {
+public:
+    class MODDMA_LLI *srcAddr(uint32_t n) { SrcAddr = n; return this; }
+    class MODDMA_LLI *dstAddr(uint32_t n) { DstAddr = n; return this; }
+    class MODDMA_LLI *nextLLI(uint32_t n) { NextLLI = n; return this; }
+    class MODDMA_LLI *control(uint32_t n) { Control = n; return this; }
+    uint32_t srcAddr(void) { return SrcAddr; }
+    uint32_t dstAddr(void) { return DstAddr; }
+    uint32_t nextLLI(void) { return NextLLI; }
+    uint32_t control(void) { return Control; }
+
+    uint32_t SrcAddr;    //!< Source Address 
+    uint32_t DstAddr;    //!< Destination address 
+    uint32_t NextLLI;    //!< Next LLI address, otherwise set to '0' 
+    uint32_t Control;    //!< GPDMA Control of this LLI 
+};
+
+
+
+ /**
+ * @brief MODDMA GPDMA Controller
+ * @author Andy Kirkham
+ * @see http://mbed.org/cookbook/MODDMA
+ * @see example1.cpp
+ * @see API 
+ *
+ * <b>MODDMA</b> defines a GPDMA controller and multiple DMA configurations that allow for DMA
+ * transfers from memory to memory, memory to peripheral or peripheral to memory.
+ *
+ * At the heart of the library is the MODDMA class that defines a single instance controller that
+ * manages all the GPDMA hardware registers and interrupts. The controller can accept multiple
+ * configurations that define the channel transfers. Each configuration specifies the source and 
+ * destination information and other associated parts to maintain the transfer process.
+ *
+ * Standard example:
+ * @code
+ * #include "mbed.h"
+ * #include "MODDMA.h"
+ *
+ * DigitalOut led1(LED1);
+ * Serial pc(USBTX, USBRX); // tx, rx
+ * MODDMA dma;
+ *
+ * int main() {
+ *
+ *     // Create a string buffer to send directly to a Uart/Serial
+ *     char s[] = "***DMA*** ABCDEFGHIJKLMNOPQRSTUVWXYZ ***DMA***";
+ *
+ *     // Create a transfer configuarion
+ *     MODDMA_Config *config = new MODDMA_Config;
+ *
+ *     // Provide a "minimal" setup for demo purposes.
+ *     config
+ *      ->channelNum    ( MODDMA::Channel_0 )   // The DMA channel to use.
+ *      ->srcMemAddr    ( (uint32_t) &s )       // A pointer to the buffer to send.
+ *      ->transferSize  ( sizeof(s) )           // The size of that buffer.
+ *      ->transferType  ( MODDMA::m2p )         // Source is memory, destination is peripheral
+ *      ->dstConn       ( MODDMA::UART0_Tx )    // Specifically, peripheral is Uart0 TX (USBTX, USBRX)
+ *    ; // config end.
+ *
+ *    // Pass the configuration to the MODDMA controller.
+ *    dma.Setup( config );
+ *
+ *    // Enable the channel and begin transfer.
+ *    dma.Enable( config->channelNum() );
+ *
+ *    while(1) {
+ *         led1 = !led1;
+ *         wait(0.25);
+ *     }
+ * }
+ * @endcode
+ */
+class MODDMA
+{
+public:
+
+    //! Channel definitions.
+    enum CHANNELS {
+          Channel_0 = 0     /*!< Channel 0 */ 
+        , Channel_1         /*!< Channel 1 */ 
+        , Channel_2         /*!< Channel 2 */ 
+        , Channel_3         /*!< Channel 3 */ 
+        , Channel_4         /*!< Channel 4 */ 
+        , Channel_5         /*!< Channel 5 */ 
+        , Channel_6         /*!< Channel 6 */ 
+        , Channel_7         /*!< Channel 7 */ 
+    };
+    
+    //! Interrupt callback types.
+    enum IrqType_t {
+          TcIrq = 0     /*!< Terminal Count interrupt */
+        , ErrIrq        /*!< Error interrupt */
+    };
+    
+    //! Return status codes.
+    enum Status {
+          Ok            = 0     /*!< Ok, suceeded */
+        , Error         = -1    /*!< General error */
+        , ErrChInUse    = -2    /*!< Specific error, channel in use */
+    };
+    
+    //! DMA Connection number definitions 
+    enum GPDMA_CONNECTION {
+          SSP0_Tx       = 0UL   /*!< SSP0 Tx */
+        , SSP0_Rx       = 1UL   /*!< SSP0 Rx */
+        , SSP1_Tx       = 2UL   /*!< SSP1 Tx */
+        , SSP1_Rx       = 3UL   /*!< SSP1 Rx */
+        , ADC           = 4UL   /*!< ADC */
+        , I2S_Channel_0 = 5UL   /*!< I2S channel 0 */
+        , I2S_Channel_1 = 6UL   /*!< I2S channel 1 */
+        , DAC           = 7UL   /*!< DAC */
+        , UART0_Tx      = 8UL   /*!< UART0 Tx */
+        , UART0_Rx      = 9UL   /*!< UART0 Rx */
+        , UART1_Tx      = 10UL  /*!< UART1 Tx */
+        , UART1_Rx      = 11UL  /*!< UART1 Rx */
+        , UART2_Tx      = 12UL  /*!< UART2 Tx */
+        , UART2_Rx      = 13UL  /*!< UART2 Rx */
+        , UART3_Tx      = 14UL  /*!< UART3 Tx */
+        , UART3_Rx      = 15UL  /*!< UART3 Rx */
+        , MAT0_0        = 16UL  /*!< MAT0.0 */
+        , MAT0_1        = 17UL  /*!< MAT0.1 */
+        , MAT1_0        = 18UL  /*!< MAT1.0 */
+        , MAT1_1        = 19UL  /*!< MAT1.1 */
+        , MAT2_0        = 20UL  /**< MAT2.0 */
+        , MAT2_1        = 21UL  /*!< MAT2.1 */
+        , MAT3_0        = 22UL  /*!< MAT3.0 */
+        , MAT3_1        = 23UL  /*!< MAT3.1 */
+    };
+
+    //! GPDMA Transfer type definitions 
+    enum  GPDMA_TRANSFERTYPE {
+          m2m = 0UL     /*!< Memory to memory - DMA control */
+        , m2p = 1UL     /*!< Memory to peripheral - DMA control */
+        , p2m = 2UL     /*!< Peripheral to memory - DMA control */
+        , p2p = 3UL     /*!< Src peripheral to dest peripheral - DMA control */         
+        , g2m = 4UL     /*!< Psuedo special case for reading "peripheral GPIO" that's memory mapped. */
+        , m2g = 5UL     /*!< Psuedo Special case for writing "peripheral GPIO" that's memory mapped. */        
+    };   
+
+    //! Burst size in Source and Destination definitions */
+    enum GPDMA_BSIZE {
+          _1    = 0UL   /*!< Burst size = 1 */
+        , _4    = 1UL   /*!< Burst size = 4 */
+        , _8    = 2UL   /*!< Burst size = 8 */
+        , _16   = 3UL   /*!< Burst size = 16 */
+        , _32   = 4UL   /*!< Burst size = 32 */
+        , _64   = 5UL   /*!< Burst size = 64 */
+        , _128  = 6UL   /*!< Burst size = 128 */
+        , _256  = 7UL   /*!< Burst size = 256 */
+    };
+    
+    //! Width in Src transfer width and Dest transfer width definitions */
+    enum GPDMA_WIDTH {
+          byte     = 0UL    /*!< Width = 1 byte */
+        , halfword = 1UL    /*!< Width = 2 bytes */
+        , word     = 2UL    /*!< Width = 4 bytes */
+    };
+    
+    //! DMA Request Select Mode definitions. */
+    enum GPDMA_REQSEL {
+          uart  = 0UL   /*!< UART TX/RX is selected */
+        , timer = 1UL   /*!< Timer match is selected */
+    };
+
+    //! GPDMA Control register bits.
+    enum Config {
+          _E = 1        /*!< DMA Controller enable */
+        , _M = 2        /*!< AHB Master endianness configuration */
+    };    
+
+    //! GPDMA Channel config register bits.
+    enum CConfig {
+          _CE  = (1UL << 0)     /*!< Channel enable */
+        , _IE  = (1UL << 14)    /*!< Interrupt error mask */
+        , _ITC = (1UL << 15)    /*!< Terminal count interrupt mask */
+        , _L   = (1UL << 16)    /*!< Lock */
+        , _A   = (1UL << 17)    /*!< Active */
+        , _H   = (1UL << 18)    /*!< Halt */
+    };
+    
+    /**
+     * The MODDMA constructor is used to initialise the DMA controller object.
+     */    
+    MODDMA() { init(true); }
+    
+    /**
+     * The MODDMA destructor.
+     */    
+    ~MODDMA() {}
+    
+    /**
+     * Used to setup the DMA controller to prepare for a data transfer.
+     *
+     * @ingroup API
+     * @param isConstructorCalling Set true when called from teh constructor
+     * @param 
+     */
+    void init(bool isConstructorCalling, int Channels = 0xFF, int Tc = 0xFF, int Err = 0xFF);
+    
+    /**
+     * Used to setup and enable the DMA controller.
+     *
+     * @see Setup
+     * @see Enable
+     * @ingroup API
+     * @param c A pointer to an instance of MODDMA_Config to setup.
+     */
+    uint32_t Prepare(MODDMA_Config *c) {
+        uint32_t u = Setup(c);
+        if (u) Enable(c);
+        return u;
+    }
+    
+    /**
+     * Used to setup the DMA controller to prepare for a data transfer.
+     *
+     * @ingroup API
+     * @param c A pointer to an instance of MODDMA_Config to setup.
+     */
+    uint32_t Setup(MODDMA_Config *c);
+    
+    /**
+     * Enable and begin data transfer.
+     *
+     * @ingroup API
+     * @param ChannelNumber Type CHANNELS, the channel number to enable
+     */
+    void Enable(CHANNELS ChannelNumber);
+    
+    /**
+     * Enable and begin data transfer (overloaded function)
+     *
+     * @ingroup API
+     * @param ChannelNumber Type uin32_t, the channel number to enable
+     */
+    void Enable(uint32_t ChannelNumber) { Enable((CHANNELS)(ChannelNumber & 0x7)); }
+    
+    /**
+     * Enable and begin data transfer (overloaded function)
+     *
+     * @ingroup API
+     * @param config A pointer to teh configuration
+     */
+    void Enable(MODDMA_Config *config) { Enable( config->channelNum() ); }
+        
+    
+    /**
+     * Disable a channel and end data transfer.
+     *
+     * @ingroup API
+     * @param ChannelNumber Type CHANNELS, the channel number to enable
+     */
+    void Disable(CHANNELS ChannelNumber);
+    
+    /**
+     * Disable a channel and end data transfer (overloaded function)
+     *
+     * @ingroup API
+     * @param ChannelNumber Type uin32_t, the channel number to disable
+     */
+    void Disable(uint32_t ChannelNumber) { Disable((CHANNELS)(ChannelNumber & 0x7)); }
+    
+    /**
+     * Is the specified channel enabled?
+     *
+     * @ingroup API
+     * @param ChannelNumber Type CHANNELS, the channel number to test
+     * @return bool true if enabled, false otherwise.
+     */
+    bool Enabled(CHANNELS ChannelNumber);
+    
+    /**
+     * Is the specified channel enabled? (overloaded function)
+     *
+     * @ingroup API
+     * @param ChannelNumber Type uin32_t, the channel number to test
+     * @return bool true if enabled, false otherwise.
+     */
+    bool Enabled(uint32_t ChannelNumber) { return Enabled((CHANNELS)(ChannelNumber & 0x7)); }
+    
+    __INLINE uint32_t IntStat(uint32_t n)            { return (1UL << n) & 0xFF; }
+    __INLINE uint32_t IntTCStat_Ch(uint32_t n)       { return (1UL << n) & 0xFF; }
+    __INLINE uint32_t IntTCClear_Ch(uint32_t n)      { return (1UL << n) & 0xFF; }
+    __INLINE uint32_t IntErrStat_Ch(uint32_t n)      { return (1UL << n) & 0xFF; }
+    __INLINE uint32_t IntErrClr_Ch(uint32_t n)       { return (1UL << n) & 0xFF; }
+    __INLINE uint32_t RawIntErrStat_Ch(uint32_t n)   { return (1UL << n) & 0xFF; }
+    __INLINE uint32_t EnbldChns_Ch(uint32_t n)       { return (1UL << n) & 0xFF; }
+    __INLINE uint32_t SoftBReq_Src(uint32_t n)       { return (1UL << n) & 0xFFFF; }
+    __INLINE uint32_t SoftSReq_Src(uint32_t n)       { return (1UL << n) & 0xFFFF; }
+    __INLINE uint32_t SoftLBReq_Src(uint32_t n)      { return (1UL << n) & 0xFFFF; }
+    __INLINE uint32_t SoftLSReq_Src(uint32_t n)      { return (1UL << n) & 0xFFFF; }
+    __INLINE uint32_t Sync_Src(uint32_t n)           { return (1UL << n) & 0xFFFF; }
+    __INLINE uint32_t ReqSel_Input(uint32_t n)       { return (1UL << (n - 8)) & 0xFF; }
+    
+
+    __INLINE uint32_t CxControl_TransferSize(uint32_t n)     { return (n & 0xFFF) << 0; }
+    __INLINE uint32_t CxControl_SBSize(uint32_t n)           { return (n & 0x7) << 12; }
+    __INLINE uint32_t CxControl_DBSize(uint32_t n)           { return (n & 0x7) << 15; }
+    __INLINE uint32_t CxControl_SWidth(uint32_t n)           { return (n & 0x7) << 18; }
+    __INLINE uint32_t CxControl_DWidth(uint32_t n)           { return (n & 0x7) << 21; }
+    __INLINE uint32_t CxControl_SI()                         { return (1UL << 26); }
+    __INLINE uint32_t CxControl_DI()                         { return (1UL << 27); }
+    __INLINE uint32_t CxControl_Prot1()                      { return (1UL << 28); }
+    __INLINE uint32_t CxControl_Prot2()                      { return (1UL << 29); }
+    __INLINE uint32_t CxControl_Prot3()                      { return (1UL << 30); }
+    __INLINE uint32_t CxControl_I()                          { return (1UL << 31); }
+    __INLINE uint32_t CxControl_E()                          { return (1UL << 0); }
+    __INLINE uint32_t CxConfig_SrcPeripheral(uint32_t n)     { return (n & 0x1F) << 1; }
+    __INLINE uint32_t CxConfig_DestPeripheral(uint32_t n)    { return (n & 0x1F) << 6; }
+    __INLINE uint32_t CxConfig_TransferType(uint32_t n)      { return (n & 0x7) << 11; }
+    __INLINE uint32_t CxConfig_IE()                          { return (1UL << 14); }
+    __INLINE uint32_t CxConfig_ITC()                         { return (1UL << 15); }
+    __INLINE uint32_t CxConfig_L()                           { return (1UL << 16); }
+    __INLINE uint32_t CxConfig_A()                           { return (1UL << 17); }
+    __INLINE uint32_t CxConfig_H()                           { return (1UL << 18); }
+    
+    /**
+     * A store for up to 8 (8 channels) of configurations.
+     * @see MODDMA_Config
+     */
+    MODDMA_Config *setups[8];
+    
+    /**
+     * Get a pointer to the current configuration the ISR is servicing.
+     *
+     * @ingroup API
+     * @return MODDMA_Config * A pointer to the setup the ISR is currently servicing.
+     */
+    MODDMA_Config *getConfig(void) { return setups[IrqProcessingChannel]; }
+    
+    /**
+     * Set which channel the ISR is currently servicing.
+     *
+     * *** USED INTERNALLY. DO NOT CALL FROM USER PROGRAMS ***
+     *
+     * Must be public so the extern "C" ISR can use it.
+     */
+    void setIrqProcessingChannel(CHANNELS n) { IrqProcessingChannel = n; }
+    
+    /**
+     * Gets which channel the ISR is currently servicing.
+     *
+     * @ingroup API
+     * @return CHANNELS The current channel the ISR is servicing.
+     */
+    CHANNELS irqProcessingChannel(void) { return IrqProcessingChannel; }
+    
+    /**
+     * Sets which type of IRQ the ISR is making a callback for.
+     *
+     * *** USED INTERNALLY. DO NOT CALL FROM USER PROGRAMS ***
+     *
+     * Must be public so the extern "C" ISR can use it.
+     */ 
+    void setIrqType(IrqType_t n) { IrqType = n; }
+    
+    /**
+     * Get which type of IRQ the ISR is calling you about,
+     * terminal count or error.
+     */
+    IrqType_t irqType(void) { return IrqType; }
+    
+    /**
+     * Clear the interrupt after handling.
+     *
+     * @param CHANNELS The channel the IQR occured on.
+     */
+    void clearTcIrq(CHANNELS n) { LPC_GPDMA->DMACIntTCClear = (uint32_t)(1UL << n); } 
+    
+    /**
+     * Clear the interrupt the ISR is currently handing..
+     */
+    void clearTcIrq(void) { clearTcIrq( IrqProcessingChannel ); }
+    
+    /**
+     * Clear the error interrupt after handling.
+     *
+     * @ingroup API
+     * @param CHANNELS The channel the IQR occured on.
+     */
+    void clearErrIrq(CHANNELS n) { LPC_GPDMA->DMACIntTCClear = (uint32_t)(1UL << n); } 
+    
+    /**
+     * Clear the error interrupt the ISR is currently handing.
+     * @ingroup API
+     */
+    void clearErrIrq(void) { clearErrIrq( IrqProcessingChannel ); }
+   
+    /**
+     * Is the supplied channel currently active?
+     *
+     * @ingroup API
+     * @param CHANNELS The channel to inquire about.
+     * @return bool true if active, false otherwise.
+     */     
+    bool isActive(CHANNELS ChannelNumber);
+    
+    /**
+     * Halt the supplied channel. 
+     *
+     * @ingroup API
+     * @param CHANNELS The channel to halt.
+     */
+    void haltChannel(CHANNELS ChannelNumber);
+    
+    /**
+     * get a channels control register. 
+     *
+     * @ingroup API
+     * @param CHANNELS The channel to get the control register for.
+     */
+    uint32_t getControl(CHANNELS ChannelNumber);
+    
+    /**
+     * Wait for channel transfer to complete and then halt.
+     *
+     * @ingroup API
+     * @param CHANNELS The channel to wait for then halt.
+     */
+    void haltAndWaitChannelComplete(CHANNELS n) { haltChannel(n); while (isActive(n)); }
+    
+    /**
+     * Attach a callback to the TC IRQ controller.
+     *
+     * @ingroup API
+     * @param fptr A function pointer to call
+     * @return this
+     */
+    void attach_tc(void (*fptr)(void)) {  
+        isrIntTCStat.attach(fptr);         
+    }
+    
+    /**
+     * Attach a callback to the TC IRQ controller.
+     *
+     * @ingroup API
+     * @param tptr A template pointer to the calling object
+     * @param mptr A method pointer within the object to call.
+     * @return this
+     */
+    template<typename T>
+    void attach_tc(T* tptr, void (T::*mptr)(void)) {  
+        if((mptr != NULL) && (tptr != NULL)) {
+            isrIntTCStat.attach(tptr, mptr);         
+        }        
+    }
+       
+    /**
+     * The MODDMA controllers terminal count interrupt callback.
+     */
+    FunctionPointer isrIntTCStat;                        
+    
+    /**
+     * Attach a callback to the ERR IRQ controller.
+     *
+     * @ingroup API
+     * @param fptr A function pointer to call
+     * @return this
+     */
+    void attach_err(void (*fptr)(void)) {  
+        isrIntErrStat.attach(fptr);                 
+    }
+    
+    /**
+     * Attach a callback to the ERR IRQ controller.
+     *
+     * @ingroup API
+     * @param tptr A template pointer to the calling object
+     * @param mptr A method pointer within the object to call.
+     * @return this
+     */
+    template<typename T>
+    void attach_err(T* tptr, void (T::*mptr)(void)) {  
+        if((mptr != NULL) && (tptr != NULL)) {
+            isrIntErrStat.attach(tptr, mptr);         
+        }
+    }
+    
+    /**
+     * Get the Linked List index regsiter for the requested channel.
+     *
+     * @param channelNum The channel number.
+     * @return uint32_t The value of the DMACCLLI register
+     */
+    uint32_t lli(CHANNELS ChannelNumber, MODDMA_LLI *set = 0) { 
+        LPC_GPDMACH_TypeDef *pChannel = (LPC_GPDMACH_TypeDef *)Channel_p( ChannelNumber & 0x7 );
+        if (set) pChannel->DMACCLLI = (uint32_t)set;
+        return pChannel->DMACCLLI; 
+    }
+    
+    /**
+     * The MODDMA controllers error interrupt callback.
+     */
+    FunctionPointer isrIntErrStat;                        
+    
+    uint32_t Channel_p(int channel);
+    
+protected:
+   
+    // Data LUTs.
+    uint32_t LUTPerAddr(int n);
+    uint8_t  LUTPerBurst(int n);
+    uint8_t  LUTPerWid(int n);    
+    //uint32_t Channel_p(int channel);
+    
+    CHANNELS IrqProcessingChannel;
+    
+    IrqType_t IrqType;
+};
+
+}; // namespace AjK ends.
+
+using namespace AjK;
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MODDMA/SETUP.cpp	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,194 @@
+/*
+    Copyright (c) 2010 Andy Kirkham
+ 
+    Permission is hereby granted, free of charge, to any person obtaining a copy
+    of this software and associated documentation files (the "Software"), to deal
+    in the Software without restriction, including without limitation the rights
+    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+    copies of the Software, and to permit persons to whom the Software is
+    furnished to do so, subject to the following conditions:
+ 
+    The above copyright notice and this permission notice shall be included in
+    all copies or substantial portions of the Software.
+ 
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+    THE SOFTWARE.
+*/
+
+#include "MODDMA.h"
+
+namespace AjK {
+
+uint32_t
+MODDMA::Setup(MODDMA_Config *config)
+{
+    LPC_GPDMACH_TypeDef *pChannel = (LPC_GPDMACH_TypeDef *)Channel_p( config->channelNum() );
+    
+    setups[config->channelNum() & 0x7] = config;
+    
+    // Reset the Interrupt status
+    LPC_GPDMA->DMACIntTCClear = IntTCClear_Ch( config->channelNum() );
+    LPC_GPDMA->DMACIntErrClr  = IntErrClr_Ch ( config->channelNum() );
+
+    // Clear DMA configure
+    pChannel->DMACCControl = 0x00;
+    pChannel->DMACCConfig  = 0x00;
+
+    // Assign Linker List Item value 
+    pChannel->DMACCLLI = config->dmaLLI();
+
+    // Set value to Channel Control Registers 
+    switch (config->transferType()) {
+    
+        // Memory to memory
+        case m2m:
+            // Assign physical source and destination address
+            pChannel->DMACCSrcAddr  = config->srcMemAddr();
+            pChannel->DMACCDestAddr = config->dstMemAddr();
+            pChannel->DMACCControl
+                = CxControl_TransferSize(config->transferSize()) 
+                | CxControl_SBSize(_32) 
+                | CxControl_DBSize(_32) 
+                | CxControl_SWidth(config->transferWidth()) 
+                | CxControl_DWidth(config->transferWidth()) 
+                | CxControl_SI() 
+                | CxControl_DI() 
+                | CxControl_I();
+            break;
+        
+        // Memory to peripheral
+        case m2p:
+            // Assign physical source
+            pChannel->DMACCSrcAddr = config->srcMemAddr();
+            // Assign peripheral destination address
+            pChannel->DMACCDestAddr = (uint32_t)LUTPerAddr(config->dstConn());
+            pChannel->DMACCControl
+                = CxControl_TransferSize((uint32_t)config->transferSize()) 
+                | CxControl_SBSize((uint32_t)LUTPerBurst(config->dstConn())) 
+                | CxControl_DBSize((uint32_t)LUTPerBurst(config->dstConn())) 
+                | CxControl_SWidth((uint32_t)LUTPerWid(config->dstConn())) 
+                | CxControl_DWidth((uint32_t)LUTPerWid(config->dstConn())) 
+                | CxControl_SI() 
+                | CxControl_I();
+            break;
+            
+        // Peripheral to memory
+        case p2m:
+            // Assign peripheral source address
+            pChannel->DMACCSrcAddr = (uint32_t)LUTPerAddr(config->srcConn());
+            // Assign memory destination address
+            pChannel->DMACCDestAddr = config->dstMemAddr();
+            pChannel->DMACCControl
+                = CxControl_TransferSize((uint32_t)config->transferSize()) 
+                | CxControl_SBSize((uint32_t)LUTPerBurst(config->srcConn())) 
+                | CxControl_DBSize((uint32_t)LUTPerBurst(config->srcConn())) 
+                | CxControl_SWidth((uint32_t)LUTPerWid(config->srcConn())) 
+                | CxControl_DWidth((uint32_t)LUTPerWid(config->srcConn())) 
+                | CxControl_DI() 
+                | CxControl_I();
+            break;
+            
+        // Peripheral to peripheral
+        case p2p:
+            // Assign peripheral source address
+            pChannel->DMACCSrcAddr = (uint32_t)LUTPerAddr(config->srcConn());
+            // Assign peripheral destination address
+            pChannel->DMACCDestAddr = (uint32_t)LUTPerAddr(config->dstConn());
+            pChannel->DMACCControl
+                = CxControl_TransferSize((uint32_t)config->transferSize()) 
+                | CxControl_SBSize((uint32_t)LUTPerBurst(config->srcConn())) 
+                | CxControl_DBSize((uint32_t)LUTPerBurst(config->dstConn())) 
+                | CxControl_SWidth((uint32_t)LUTPerWid(config->srcConn())) 
+                | CxControl_DWidth((uint32_t)LUTPerWid(config->dstConn())) 
+                | CxControl_I();
+            break;
+            
+        // GPIO to memory
+        case g2m:
+            // Assign GPIO source address
+            pChannel->DMACCSrcAddr = config->srcMemAddr();
+            // Assign memory destination address
+            pChannel->DMACCDestAddr = config->dstMemAddr();
+            pChannel->DMACCControl
+                = CxControl_TransferSize((uint32_t)config->transferSize()) 
+                | CxControl_SBSize((uint32_t)LUTPerBurst(config->srcConn())) 
+                | CxControl_DBSize((uint32_t)LUTPerBurst(config->srcConn())) 
+                | CxControl_SWidth((uint32_t)LUTPerWid(config->srcConn())) 
+                | CxControl_DWidth((uint32_t)LUTPerWid(config->srcConn())) 
+                | CxControl_DI() 
+                | CxControl_I();
+            break;
+            
+        // Memory to GPIO
+        case m2g:
+            // Assign physical source
+            pChannel->DMACCSrcAddr = config->srcMemAddr();
+            // Assign peripheral destination address
+            pChannel->DMACCDestAddr = config->dstMemAddr();
+            pChannel->DMACCControl
+                = CxControl_TransferSize((uint32_t)config->transferSize()) 
+                | CxControl_SBSize((uint32_t)LUTPerBurst(config->dstConn())) 
+                | CxControl_DBSize((uint32_t)LUTPerBurst(config->dstConn())) 
+                | CxControl_SWidth((uint32_t)LUTPerWid(config->dstConn())) 
+                | CxControl_DWidth((uint32_t)LUTPerWid(config->dstConn())) 
+                | CxControl_SI() 
+                | CxControl_I();
+            break;
+            
+        // Do not support any more transfer type, return ERROR
+        default:
+            return 0;
+    }
+
+     // Re-Configure DMA Request Select for source peripheral 
+    if (config->srcConn() > 15) {
+        LPC_SC->RESERVED9 |= (1 << (config->srcConn() - 16));
+    } 
+    else {
+        LPC_SC->RESERVED9 &= ~(1 << (config->srcConn() - 8));
+    }
+
+    // Re-Configure DMA Request Select for destination peripheral
+    if (config->dstConn() > 15) {
+        LPC_SC->RESERVED9 |= (1 << (config->dstConn() - 16));
+    } 
+    else {
+        LPC_SC->RESERVED9 &= ~(1 << (config->dstConn() - 8));
+    }
+
+    // Enable DMA channels, little endian 
+    LPC_GPDMA->DMACConfig = _E;
+    while (!(LPC_GPDMA->DMACConfig & _E));
+
+    // Calculate absolute value for Connection number
+    uint32_t tmp1 = config->srcConn(); tmp1 = ((tmp1 > 15) ? (tmp1 - 8) : tmp1);
+    uint32_t tmp2 = config->dstConn(); tmp2 = ((tmp2 > 15) ? (tmp2 - 8) : tmp2);
+
+    if (config->dmacSync()) {
+        uint32_t tmp3 = config->dmacSync(); tmp3 = ((tmp3 > 15) ? (tmp3 - 8) : tmp3);
+        LPC_GPDMA->DMACSync |= Sync_Src( tmp3 );
+    }
+    
+    uint32_t tfer_type = (uint32_t)config->transferType();
+    if (tfer_type == g2m || tfer_type == m2g) {
+        tfer_type -= 2; // Adjust psuedo transferType to a real transferType.
+    }
+    
+    // Configure DMA Channel, enable Error Counter and Terminate counter
+    pChannel->DMACCConfig 
+        = CxConfig_IE() 
+        | CxConfig_ITC() 
+        | CxConfig_TransferType(tfer_type) 
+        | CxConfig_SrcPeripheral(tmp1) 
+        | CxConfig_DestPeripheral(tmp2);
+
+    return pChannel->DMACCControl;
+}
+
+}; // namespace AjK ends
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MODDMA/example1.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,89 @@
+#include "mbed.h"
+#include "MODDMA.h"
+#include "MODSERIAL.h"
+
+DigitalOut led1(LED1);
+DigitalOut led2(LED2);
+DigitalOut led3(LED3);
+DigitalOut led4(LED4);
+MODDMA dma;
+MODSERIAL pc(USBTX, USBRX);
+
+// Function prototypes for IRQ callbacks.
+// See definitions following main() below.
+void dmaTCCallback(void);
+void dmaERRCallback(void);
+void TC0_callback(void);
+void ERR0_callback(void);
+
+int main() {
+    char s[] = "**DMA** ABCDEFGHIJKLMNOPQRSTUVWXYZ **DMA**";
+    
+    pc.baud(PC_BAUD);
+    
+    dma.attach_tc( &dmaTCCallback );
+    dma.attach_err( &dmaERRCallback );
+    
+    MODDMA_Config *config = new MODDMA_Config;
+    config
+     ->channelNum    ( MODDMA::Channel_0 )
+     ->srcMemAddr    ( (uint32_t) &s )
+     ->dstMemAddr    ( 0 )
+     ->transferSize  ( sizeof(s) )
+     ->transferType  ( MODDMA::m2p )
+     ->transferWidth ( 0 )
+     ->srcConn       ( 0 )
+     ->dstConn       ( MODDMA::UART0_Tx )
+     ->dmaLLI        ( 0 )
+     ->attach_tc     ( &TC0_callback )
+     ->attach_err    ( &ERR0_callback )
+    ; // config end
+    
+    // Setup the configuration.
+    dma.Setup(config);
+    
+    //dma.Enable( MODDMA::Channel_0 );
+    //dma.Enable( config->channelNum() );
+    dma.Enable( config );
+    
+    while (1) {
+        led1 = !led1;
+        wait(0.25);        
+    }
+}
+
+// Main controller TC IRQ callback
+void dmaTCCallback(void) {
+    led2 = 1;
+}
+
+// Main controller ERR IRQ callback
+void dmaERRCallback(void) {
+    error("Oh no! My Mbed exploded! :( Only kidding, find the problem");
+}
+
+// Configuration callback on TC
+void TC0_callback(void) {
+    MODDMA_Config *config = dma.getConfig();
+    dma.haltAndWaitChannelComplete( (MODDMA::CHANNELS)config->channelNum());
+    dma.Disable( (MODDMA::CHANNELS)config->channelNum() );
+    
+    // Configurations have two IRQ callbacks for TC and Err so you 
+    // know which you are processing. However, if you want to use 
+    // a single callback function you can tell what type of IRQ 
+    // is being processed thus:-
+    if (dma.irqType() == MODDMA::TcIrq)  {
+        led3 = 1;
+        dma.clearTcIrq();
+    }
+    if (dma.irqType() == MODDMA::ErrIrq) {
+        led4 = 1;
+        dma.clearErrIrq();
+    }
+}
+
+// Configuration cakllback on Error
+void ERR0_callback(void) {
+    error("Oh no! My Mbed exploded! :( Only kidding, find the problem");
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MODDMA/example2.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,138 @@
+/*
+ * This example was provided to support Mbed forum thread:-
+ * http://mbed.org/forum/mbed/topic/1798
+ */
+ 
+#include "mbed.h"
+#include "MODDMA.h"
+
+#define SAMPLE_BUFFER_LENGTH 32
+
+DigitalOut led1(LED1);
+DigitalOut led2(LED2);
+
+MODDMA dma;
+Serial pc(USBTX, USBRX);
+
+// ISR set's this when transfer complete.
+bool dmaTransferComplete = false;
+
+// Function prototypes for IRQ callbacks.
+// See definitions following main() below.
+void TC0_callback(void);
+void ERR0_callback(void);
+
+int main() {
+
+    // Create a buffer to hold the ADC samples and clear it.
+    // Note, we are going to sample two ADC inputs so they
+    // end up in this buffer "interleaved". So you will want
+    // a buffer twice this size to a real life given sample
+    // frequency. See the printf() output for details.
+    uint32_t adcInputBuffer[SAMPLE_BUFFER_LENGTH];    
+    memset(adcInputBuffer, 0, sizeof(adcInputBuffer));
+    
+    // We use the ADC irq to trigger DMA and the manual says
+    // that in this case the NVIC for ADC must be disabled.
+    NVIC_DisableIRQ(ADC_IRQn);
+    
+    // Power up the ADC and set PCLK
+    LPC_SC->PCONP    |=  (1UL << 12);
+    LPC_SC->PCLKSEL0 &= ~(3UL << 24); // PCLK = CCLK/4 96M/4 = 24MHz
+    
+    // Enable the ADC, 12MHz,  ADC0.0 & .1
+    LPC_ADC->ADCR  = (1UL << 21) | (1UL << 8) | (3UL << 0); 
+    
+    // Set the pin functions to ADC
+    LPC_PINCON->PINSEL1 &= ~(3UL << 14);  /* P0.23, Mbed p15. */
+    LPC_PINCON->PINSEL1 |=  (1UL << 14);
+    LPC_PINCON->PINSEL1 &= ~(3UL << 16);  /* P0.24, Mbed p16. */
+    LPC_PINCON->PINSEL1 |=  (1UL << 16);
+    
+    // Setup the serial port to print out results.
+//    pc.baud(115200);
+    pc.baud(460800);
+    pc.printf("ADC with DMA example\n");
+    pc.printf("====================\n");
+    
+    // Prepare an ADC configuration.
+    MODDMA_Config *conf = new MODDMA_Config;
+    conf
+     ->channelNum    ( MODDMA::Channel_0 )
+     ->srcMemAddr    ( 0 )
+     ->dstMemAddr    ( (uint32_t)adcInputBuffer )
+     ->transferSize  ( SAMPLE_BUFFER_LENGTH )
+     ->transferType  ( MODDMA::p2m )
+     ->transferWidth ( MODDMA::word )
+     ->srcConn       ( MODDMA::ADC )
+     ->dstConn       ( 0 )
+     ->dmaLLI        ( 0 )
+     ->attach_tc     ( &TC0_callback )
+     ->attach_err    ( &ERR0_callback )
+    ; // end conf.
+    
+    // Prepare configuration.
+    dma.Setup( conf );
+    
+    // Enable configuration.
+    dma.Enable( conf );
+    
+    // Enable ADC irq flag (to DMA).
+    // Note, don't set the individual flags,
+    // just set the global flag.
+    LPC_ADC->ADINTEN = 0x100;
+
+    // Enable burst mode on inputs 0 and 1.
+    LPC_ADC->ADCR |= (1UL << 16); 
+    
+    while (1) {
+        // When transfer complete do this block.
+        if (dmaTransferComplete) {
+            delete conf; // No memory leaks, delete the configuration.
+            dmaTransferComplete = false;
+            for (int i = 0; i < SAMPLE_BUFFER_LENGTH; i++) {
+                int channel = (adcInputBuffer[i] >> 24) & 0x7;
+                int iVal = (adcInputBuffer[i] >> 4) & 0xFFF;
+                double fVal = 3.3 * (double)((double)iVal) / ((double)0x1000); // scale to 0v to 3.3v
+                pc.printf("Array index %02d : ADC input channel %d = 0x%03x %01.3f volts\n", i, channel, iVal, fVal);                  
+            }
+        }
+        
+        // Just flash LED1 for something to do.
+        led1 = !led1;
+        wait(0.25);        
+    }
+}
+
+// Configuration callback on TC
+void TC0_callback(void) {
+    
+    MODDMA_Config *config = dma.getConfig();
+    
+    // Disbale burst mode and switch off the IRQ flag.
+    LPC_ADC->ADCR &= ~(1UL << 16);
+    LPC_ADC->ADINTEN = 0;    
+    
+    // Finish the DMA cycle by shutting down the channel.
+    dma.haltAndWaitChannelComplete( (MODDMA::CHANNELS)config->channelNum());
+    dma.Disable( (MODDMA::CHANNELS)config->channelNum() );
+    
+    // Tell main() while(1) loop to print the results.
+    dmaTransferComplete = true;            
+    
+    // Switch on LED2 to show transfer complete.
+    led2 = 1;        
+    
+    // Clear DMA IRQ flags.
+    if (dma.irqType() == MODDMA::TcIrq) dma.clearTcIrq();    
+    if (dma.irqType() == MODDMA::ErrIrq) dma.clearErrIrq();
+}
+
+// Configuration callback on Error
+void ERR0_callback(void) {
+    // Switch off burst conversions.
+    LPC_ADC->ADCR |= ~(1UL << 16);
+    LPC_ADC->ADINTEN = 0;
+    error("Oh no! My Mbed EXPLODED! :( Only kidding, go find the problem");
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MODDMA/example3.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,131 @@
+/*
+ * Demonstrates capturing the GPIO P0.4 to P0.7 "nibble" to memory 
+ * using GPDMA. The transfers from port pins to memory buffer are
+ * triggered using Timer1 MAT1.0 match compare.
+ *
+ * In this example all inputs have pullups. So with nothing connected
+ * the P0.4/7 reads as 0xF. Connecting a wire from one or more of the four 
+ * inputs to ground will show up in the captured buffer sequence.
+ */
+ 
+#include "mbed.h"
+#include "MODDMA.h"
+#include "iomacros.h" // within MODDMA library.
+
+// How long between grabbing GPIO FIO0PIN register.
+// Value is in microseconds. (500000 is half a second).
+#define SAMPLE_PERIOD   500000
+
+#define NUM_OF_SAMPLES  5
+
+Serial pc(USBTX, USBRX);
+
+DigitalOut led1(LED1);
+DigitalOut led2(LED2);
+DigitalOut led3(LED3);
+
+uint32_t buffer[NUM_OF_SAMPLES];
+
+bool dmaTransferComplete;
+
+MODDMA dma;
+MODDMA_Config *conf;
+
+void TC0_callback(void);
+void ERR0_callback(void);
+
+int main() {
+    volatile int life_counter = 0;
+     
+    // Macros defined in iomacros.h, saves messing with DigitalIn
+    p30_AS_INPUT; p30_MODE( PIN_PULLUP ); // P0.4
+    p29_AS_INPUT; p29_MODE( PIN_PULLUP ); // P0.5
+    p8_AS_INPUT;  p8_MODE( PIN_PULLUP );  // P0.6
+    p7_AS_INPUT;  p7_MODE( PIN_PULLUP );  // P0.7
+    
+    // Clear the buffer.
+    memset(buffer, 0, sizeof(buffer));
+    
+    // Setup the serial port to print out results.
+    pc.baud(115200);
+    pc.printf("Starting up...\n");
+    
+    // Set-up timer1 as a periodic timer.
+    LPC_SC->PCONP    |= (1UL << 2); // TIM1 On
+    LPC_SC->PCLKSEL0 |= (3UL << 4); // CCLK/8 = 12MHz
+    LPC_TIM1->PR      = 11;         // TC clocks at 1MHz.
+    LPC_TIM1->MCR     = 2;          // Reset TCR to zero on match.
+    LPC_TIM1->MR0     = SAMPLE_PERIOD;
+    
+    // Prepare the GPDMA system.
+    conf = new MODDMA_Config;
+    conf
+     ->channelNum    ( MODDMA::Channel_0 )
+     ->srcMemAddr    ( (uint32_t)&LPC_GPIO0->FIOPIN )
+     ->dstMemAddr    ( (uint32_t)&buffer[0] )
+     ->transferSize  ( NUM_OF_SAMPLES )
+     ->transferType  ( MODDMA::g2m ) // pseudo transfer code MODDMA understands.
+     ->transferWidth ( MODDMA::word )
+     ->srcConn       ( MODDMA::MAT1_0 )
+     ->dmacSync      ( MODDMA::MAT1_0 ) 
+     ->attach_tc     ( TC0_callback )
+     ->attach_err    ( ERR0_callback )
+    ; // end conf.
+    
+    // Prepare configuration.
+    if (!dma.Setup( conf )) {
+        error("Doh!");
+    }
+    
+    // Enable GPDMA to be ready for the TIM1 "ticks".       
+    dma.Enable( conf );
+    
+    // Begin.
+    LPC_TIM1->TCR = 1;
+       
+    while (1) { 
+        if (life_counter++ > 1000000) {
+            led1 = !led1; // Show some sort of life.
+            life_counter = 0;
+        }
+        
+        if (dmaTransferComplete) {
+            dmaTransferComplete = false;
+            for (int i = 0; i < NUM_OF_SAMPLES; i++) {
+                int val = (buffer[i] >> 4) & 0xF; 
+                pc.printf("Buffer index %d = 0x%x\n", i, val);
+            }
+            pc.printf("Done.\n");
+            
+            // Schedule another grab.
+            if (dma.Setup( conf )) {        
+                dma.Enable( conf );                
+            }            
+        }
+    }       
+}
+
+// Configuration callback on TC
+void TC0_callback(void) {
+    
+    // Just show sample sequence grab complete.
+    led3 = !led3; 
+        
+    // Get configuration pointer.
+    MODDMA_Config *config = dma.getConfig();
+    
+    // Finish the DMA cycle by shutting down the channel.
+    dma.Disable( (MODDMA::CHANNELS)config->channelNum() );
+    
+    // Tell main() while(1) loop to print the results.
+    dmaTransferComplete = true;            
+    
+    // Clear DMA IRQ flags.
+    if (dma.irqType() == MODDMA::TcIrq) dma.clearTcIrq();    
+    if (dma.irqType() == MODDMA::ErrIrq) dma.clearErrIrq();    
+}
+
+// Configuration callback on Error
+void ERR0_callback(void) {
+    error("Oh no! My Mbed EXPLODED! :( Only kidding, go find the problem");
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MODDMA/example4.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,156 @@
+/*
+ * Demonstrates sending a buffer repeatedly to the DAC using DMA.
+ * Connect an oscilloscope to Mbed pin 18. This example doesn't
+ * output anything else (nothing on any serial ports).
+ */
+#include "mbed.h"
+#include "MODDMA.h"
+
+// Make the buffer size match the number of degrees
+// in a circle since we are going to output a sinewave.
+#define BUFFER_SIZE 360
+
+// Set DAC output power mode.
+#define DAC_POWER_MODE  (1 << 16)
+
+DigitalOut led1(LED1);
+DigitalOut led3(LED3);
+DigitalOut led4(LED4);
+
+int buffer[2][BUFFER_SIZE];
+
+AnalogOut signal(p18);
+
+MODDMA dma;
+MODDMA_Config *conf0, *conf1;
+
+void TC0_callback(void);
+void ERR0_callback(void);
+
+void TC1_callback(void);
+void ERR1_callback(void);
+
+int main() {
+    volatile int life_counter = 0;
+    
+    // Create a sinewave buffer for testing.
+    for (int i =   0; i <=  90; i++) buffer[0][i] =  (512 * sin(3.14159/180.0 * i)) + 512;                
+    for (int i =  91; i <= 180; i++) buffer[0][i] =  buffer[0][180 - i];
+    for (int i = 181; i <= 270; i++) buffer[0][i] =  512 - (buffer[0][i - 180] - 512);
+    for (int i = 271; i <  360; i++) buffer[0][i] =  512 - (buffer[0][360 - i] - 512);
+    
+    // Adjust the sinewave buffer for use with DAC hardware.
+    for (int i = 0; i < 360; i++) {
+        buffer[0][i] = DAC_POWER_MODE | ((buffer[0][i] << 6) & 0xFFC0);
+        buffer[1][i] = buffer[0][i]; // Just create a copy of buffer0 to continue sinewave.
+    }
+    
+    // Prepare the GPDMA system for buffer0.
+    conf0 = new MODDMA_Config;
+    conf0
+     ->channelNum    ( MODDMA::Channel_0 )
+     ->srcMemAddr    ( (uint32_t) &buffer[0] )
+     ->dstMemAddr    ( MODDMA::DAC )
+     ->transferSize  ( 360 )
+     ->transferType  ( MODDMA::m2p )
+     ->dstConn       ( MODDMA::DAC )
+     ->attach_tc     ( &TC0_callback )
+     ->attach_err    ( &ERR0_callback )     
+    ; // config end
+    
+    
+    // Prepare the GPDMA system for buffer1.
+    conf1 = new MODDMA_Config;
+    conf1
+     ->channelNum    ( MODDMA::Channel_1 )
+     ->srcMemAddr    ( (uint32_t) &buffer[1] )
+     ->dstMemAddr    ( MODDMA::DAC )
+     ->transferSize  ( 360 )
+     ->transferType  ( MODDMA::m2p )
+     ->dstConn       ( MODDMA::DAC )
+     ->attach_tc     ( &TC1_callback )
+     ->attach_err    ( &ERR1_callback )     
+    ; // config end
+
+    
+    // Calculating the transfer frequency:
+    // By default, the Mbed library sets the PCLK_DAC clock value
+    // to 24MHz. One complete sinewave cycle in each buffer is 360
+    // points long. So, for a 1Hz wave we would need to transfer 360
+    // values per second. That would be 24000000/360 which is approx
+    // 66,666. But that's no good! The count val is only 16bits in size
+    // so bare this in mind. If you need to go slower you will need to
+    // alter PCLK_DAC from CCLK/4 to CCLK/8.
+    // For our demo we are going to have the sinewave run at 1kHz.
+    // That's 24000000/360000 which is approx 66. Experimentation
+    // however showed 65 to get closer to 1kHz (on my Mbed and scope 
+    // at least).
+    LPC_DAC->DACCNTVAL = 65; // 6500 for 10Hz
+
+    // Prepare first configuration.
+    if (!dma.Prepare( conf0 )) {
+        error("Doh!");
+    }
+    
+    // Begin (enable DMA and counter). Note, don't enable
+    // DBLBUF_ENA as we are using DMA double buffering.
+    LPC_DAC->DACCTRL |= (3UL << 2);
+    
+    while (1) { 
+        // There's not a lot to do as DMA and interrupts are
+        // now handling the buffer transfers. So we'll just
+        // flash led1 to show the Mbed is alive and kicking.
+        if (life_counter++ > 1000000) {
+            led1 = !led1; // Show some sort of life.
+            life_counter = 0;
+        }
+    } 
+}
+
+// Configuration callback on TC
+void TC0_callback(void) {
+    
+    // Just show sending buffer0 complete.
+    led3 = !led3; 
+        
+    // Get configuration pointer.
+    MODDMA_Config *config = dma.getConfig();
+    
+    // Finish the DMA cycle by shutting down the channel.
+    dma.Disable( (MODDMA::CHANNELS)config->channelNum() );
+   
+    // Swap to buffer1
+    dma.Prepare( conf1 );
+
+    // Clear DMA IRQ flags.
+    if (dma.irqType() == MODDMA::TcIrq) dma.clearTcIrq(); 
+}
+
+// Configuration callback on Error
+void ERR0_callback(void) {
+    error("Oh no! My Mbed EXPLODED! :( Only kidding, go find the problem");
+}
+
+// Configuration callback on TC
+void TC1_callback(void) {
+    
+    // Just show sending buffer1 complete.
+    led4 = !led4; 
+        
+    // Get configuration pointer.
+    MODDMA_Config *config = dma.getConfig();
+    
+    // Finish the DMA cycle by shutting down the channel.
+    dma.Disable( (MODDMA::CHANNELS)config->channelNum() );
+    
+    // Swap to buffer0
+    dma.Prepare( conf0 );
+    
+    // Clear DMA IRQ flags.
+    if (dma.irqType() == MODDMA::TcIrq) dma.clearTcIrq(); 
+}
+
+// Configuration callback on Error
+void ERR1_callback(void) {
+    error("Oh no! My Mbed EXPLODED! :( Only kidding, go find the problem");
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MODDMA/iomacros.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,418 @@
+/*
+    Copyright (c) 2011 Andy Kirkham
+ 
+    Permission is hereby granted, free of charge, to any person obtaining a copy
+    of this software and associated documentation files (the "Software"), to deal
+    in the Software without restriction, including without limitation the rights
+    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+    copies of the Software, and to permit persons to whom the Software is
+    furnished to do so, subject to the following conditions:
+ 
+    The above copyright notice and this permission notice shall be included in
+    all copies or substantial portions of the Software.
+ 
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+    THE SOFTWARE.
+*/
+
+#ifndef IOMACROS_H
+#define IOMACROS_H
+
+#ifndef __LPC17xx_H__
+#include "LPC17xx.h"
+#endif
+
+#define PIN_PULLUP      0UL
+#define PIN_REPEAT      1UL
+#define PIN_NONE        2UL
+#define PIN_PULLDOWN    3UL
+
+/* p5 is P0.9 */
+#define p5_SEL_MASK     ~(3UL << 18)
+#define p5_SET_MASK     (1UL << 9)
+#define p5_CLR_MASK     ~(p5_SET_MASK)
+#define p5_AS_OUTPUT    LPC_PINCON->PINSEL0&=p5_SEL_MASK;LPC_GPIO0->FIODIR|=p5_SET_MASK
+#define p5_AS_INPUT     LPC_GPIO0->FIOMASK &= p5_CLR_MASK; 
+#define p5_SET          LPC_GPIO0->FIOSET = p5_SET_MASK
+#define p5_CLR          LPC_GPIO0->FIOCLR = p5_SET_MASK
+#define p5_IS_SET       (bool)(LPC_GPIO0->FIOPIN & p5_SET_MASK)
+#define p5_IS_CLR       !(p5_IS_SET)
+#define p5_MODE(x)      LPC_PINCON->PINMODE0&=p5_SEL_MASK;LPC_PINCON->PINMODE0|=((x&0x3)<<18)
+
+/* p6 is P0.8 */
+#define p6_SEL_MASK     ~(3UL << 16)
+#define p6_SET_MASK     (1UL <<  8)
+#define p6_CLR_MASK     ~(p6_SET_MASK)
+#define p6_AS_OUTPUT    LPC_PINCON->PINSEL0&=p6_SEL_MASK;LPC_GPIO0->FIODIR|=p6-SET_MASK
+#define p6_AS_INPUT     LPC_GPIO0->FIOMASK &= p6_CLR_MASK; 
+#define p6_SET          LPC_GPIO0->FIOSET = p6_SET_MASK
+#define p6_CLR          LPC_GPIO0->FIOCLR = p6_SET_MASK
+#define p6_IS_SET       (bool)(LPC_GPIO0->FIOPIN & p6_SET_MASK)
+#define p6_IS_CLR       !(p6_IS_SET)
+#define p6_MODE(x)      LPC_PINCON->PINMODE0&=p6_SEL_MASK;LPC_PINCON->PINMODE0|=((x&0x3)<<16)    
+
+/* p7 is P0.7 */
+#define p7_SEL_MASK     ~(3UL << 14)
+#define p7_SET_MASK     (1UL <<  7)
+#define p7_CLR_MASK     ~(p7_SET_MASK)
+#define p7_AS_OUTPUT    LPC_PINCON->PINSEL0&=p7_SEL_MASK;LPC_GPIO0->FIODIR|=p7_SET_MASK
+#define p7_AS_INPUT     LPC_GPIO0->FIOMASK &= p7_CLR_MASK; 
+#define p7_SET          LPC_GPIO0->FIOSET = p7_SET_MASK
+#define p7_CLR          LPC_GPIO0->FIOCLR = p7_SET_MASK
+#define p7_IS_SET       (bool)(LPC_GPIO0->FIOPIN & p7_SET_MASK)
+#define p7_IS_CLR       !(p7_IS_SET)
+#define p7_MODE(x)      LPC_PINCON->PINMODE0&=p7_SEL_MASK;LPC_PINCON->PINMODE0|=((x&0x3)<<14)    
+
+/* p8 is P0.6 */
+#define p8_SEL_MASK     ~(3UL << 12)
+#define p8_SET_MASK     (1UL <<  6)
+#define p8_CLR_MASK     ~(p8_SET_MASK)
+#define p8_AS_OUTPUT    LPC_PINCON->PINSEL0&=p8_SEL_MASK;LPC_GPIO0->FIODIR|=p8_SET_MASK
+#define p8_AS_INPUT     LPC_GPIO0->FIOMASK &= p8_CLR_MASK; 
+#define p8_SET          LPC_GPIO0->FIOSET = p8_SET_MASK
+#define p8_CLR          LPC_GPIO0->FIOCLR = p8_SET_MASK
+#define p8_IS_SET       (bool)(LPC_GPIO0->FIOPIN & p8_SET_MASK)
+#define p8_IS_CLR       !(p8_IS_SET)
+#define p8_MODE(x)      LPC_PINCON->PINMODE0&=p8_SEL_MASK;LPC_PINCON->PINMODE0|=((x&0x3)<<12)    
+
+/* p9 is P0.0 */
+#define p9_SEL_MASK     ~(3UL <<  0)
+#define p9_SET_MASK     (1UL <<  0)
+#define p9_CLR_MASK     ~(p9_SET_MASK)
+#define p9_AS_OUTPUT    LPC_PINCON->PINSEL0&=p9_SEL_MASK;LPC_GPIO0->FIODIR|=p9_SET_MASK
+#define p9_AS_INPUT     LPC_GPIO0->FIOMASK &= p9_CLR_MASK; 
+#define p9_SET          LPC_GPIO0->FIOSET = p9_SET_MASK
+#define p9_CLR          LPC_GPIO0->FIOCLR = p9_SET_MASK
+#define p9_IS_SET       (bool)(LPC_GPIO0->FIOPIN & p9_SET_MASK)
+#define p9_IS_CLR       !(p9_IS_SET)
+#define p9_MODE(x)      LPC_PINCON->PINMODE0&=p9_SEL_MASK;LPC_PINCON->PINMODE0|=((x&0x3)<<0)    
+
+/* p10 is P0.1 */
+#define p10_SEL_MASK    ~(3UL <<  2)
+#define p10_SET_MASK    (1UL <<  1)
+#define p10_CLR_MASK    ~(p10_SET_MASK)
+#define p10_AS_OUTPUT   LPC_PINCON->PINSEL0&=p10_SEL_MASK;LPC_GPIO0->FIODIR|=p10_SET_MASK
+#define p10_AS_INPUT    LPC_GPIO0->FIOMASK &= p10_CLR_MASK; 
+#define p10_SET         LPC_GPIO0->FIOSET = p10_SET_MASK
+#define p10_CLR         LPC_GPIO0->FIOCLR = p10_SET_MASK
+#define p10_IS_SET      (bool)(LPC_GPIO0->FIOPIN & p10_SET_MASK)
+#define p10_IS_CLR      !(p10_IS_SET)
+#define p10_MODE(x)     LPC_PINCON->PINMODE0&=p10_SEL_MASK;LPC_PINCON->PINMODE0|=((x&0x3)<<2)
+
+/* p11 is P0.18 */
+#define p11_SEL_MASK    ~(3UL << 4)
+#define p11_SET_MASK    (1UL <<  18)
+#define p11_CLR_MASK    ~(p11_SET_MASK)
+#define p11_AS_OUTPUT   LPC_PINCON->PINSEL1&=p11_SEL_MASK;LPC_GPIO0->FIODIR|=p11_SET_MASK
+#define p11_AS_INPUT    LPC_GPIO0->FIOMASK &= p11_CLR_MASK; 
+#define p11_SET         LPC_GPIO0->FIOSET = p11_SET_MASK
+#define p11_CLR         LPC_GPIO0->FIOCLR = p11_SET_MASK
+#define p11_IS_SET      (bool)(LPC_GPIO0->FIOPIN & p11_SET_MASK)
+#define p11_IS_CLR      !(p11_IS_SET)
+#define p11_MODE(x)     LPC_PINCON->PINMODE1&=p11_SEL_MASK;LPC_PINCON->PINMODE1|=((x&0x3)<<4)
+
+/* p12 is P0.17 */
+#define p12_SEL_MASK    ~(3UL << 2)
+#define p12_SET_MASK    (1UL << 17)
+#define p12_CLR_MASK    ~(p12_SET_MASK)
+#define p12_AS_OUTPUT   LPC_PINCON->PINSEL1&=p12_SEL_MASK;LPC_GPIO0->FIODIR|=p12_SET_MASK
+#define p12_AS_INPUT    LPC_GPIO0->FIOMASK &= p12_CLR_MASK; 
+#define p12_SET         LPC_GPIO0->FIOSET = p12_SET_MASK
+#define p12_CLR         LPC_GPIO0->FIOCLR = p12_SET_MASK
+#define p12_IS_SET      (bool)(LPC_GPIO0->FIOPIN & p12_SET_MASK)
+#define p12_IS_CLR      !(p12_IS_SET)
+#define p12_MODE(x)     LPC_PINCON->PINMODE1&=p12_SEL_MASK;LPC_PINCON->PINMODE1|=((x&0x3)<<2)
+
+/* p13 is P0.15 */
+#define p13_SEL_MASK    ~(3UL << 30)
+#define p13_SET_MASK    (1UL << 15)
+#define p13_CLR_MASK    ~(p13_SET_MASK)
+#define p13_AS_OUTPUT   LPC_PINCON->PINSEL0&=p13_SEL_MASK;LPC_GPIO0->FIODIR|=p13_SET_MASK
+#define p13_AS_INPUT    LPC_GPIO0->FIOMASK &= p13_CLR_MASK; 
+#define p13_SET         LPC_GPIO0->FIOSET = p13_SET_MASK
+#define p13_CLR         LPC_GPIO0->FIOCLR = p13_SET_MASK
+#define p13_IS_SET      (bool)(LPC_GPIO0->FIOPIN & p13_SET_MASK)
+#define p13_IS_CLR      !(p13_IS_SET)
+#define p13_MODE(x)     LPC_PINCON->PINMODE0&=p13_SEL_MASK;LPC_PINCON->PINMODE0|=((x&0x3)<<30)
+
+/* p14 is P0.16 */
+#define p14_SEL_MASK    ~(3UL << 0)
+#define p14_SET_MASK    (1UL << 16)
+#define p14_CLR_MASK    ~(p14_SET_MASK)
+#define p14_AS_OUTPUT   LPC_PINCON->PINSEL1&=p14_SEL_MASK;LPC_GPIO0->FIODIR|=p14_SET_MASK
+#define p14_AS_INPUT    LPC_GPIO0->FIOMASK &= p14_CLR_MASK; 
+#define p14_SET         LPC_GPIO0->FIOSET = p14_SET_MASK
+#define p14_CLR         LPC_GPIO0->FIOCLR = p14_SET_MASK
+#define p14_IS_SET      (bool)(LPC_GPIO0->FIOPIN & p14_SET_MASK)
+#define p14_IS_CLR      !(p14_IS_SET)
+#define p14_MODE(x)     LPC_PINCON->PINMODE1&=p14_SEL_MASK;LPC_PINCON->PINMODE1|=((x&0x3)<<0)
+
+/* p15 is P0.23 */
+#define p15_SEL_MASK    ~(3UL << 14)
+#define p15_SET_MASK    (1UL << 23)
+#define p15_CLR_MASK    ~(p15_SET_MASK)
+#define p15_AS_OUTPUT   LPC_PINCON->PINSEL1&=p15_SEL_MASK;LPC_GPIO0->FIODIR|=p15_SET_MASK
+#define p15_AS_INPUT    LPC_GPIO0->FIOMASK &= p15_CLR_MASK; 
+#define p15_SET         LPC_GPIO0->FIOSET = p15_SET_MASK
+#define p15_CLR         LPC_GPIO0->FIOCLR = p15_SET_MASK
+#define p15_IS_SET      (bool)(LPC_GPIO0->FIOPIN & p15_SET_MASK)
+#define p15_IS_CLR      !(p15_IS_SET)
+#define p15_MODE(x)     LPC_PINCON->PINMODE1&=p15_SEL_MASK;LPC_PINCON->PINMODE1|=((x&0x3)<<14)
+
+/* p16 is P0.24 */
+#define p16_SEL_MASK    ~(3UL << 16)
+#define p16_SET_MASK    (1UL <<  24)
+#define p16_CLR_MASK    ~(p16_SET_MASK)
+#define p16_AS_OUTPUT   LPC_PINCON->PINSEL1&=p16_SEL_MASK;LPC_GPIO0->FIODIR|=p16_SET_MASK
+#define p16_AS_INPUT    LPC_GPIO0->FIOMASK &= p16_CLR_MASK; 
+#define p16_SET         LPC_GPIO0->FIOSET = p16_SET_MASK
+#define p16_CLR         LPC_GPIO0->FIOCLR = p16_SET_MASK
+#define p16_IS_SET      (bool)(LPC_GPIO0->FIOPIN & p16_SET_MASK)
+#define p16_IS_CLR      !(p16_IS_SET)
+#define p16_MODE(x)     LPC_PINCON->PINMODE1&=p16_SEL_MASK;LPC_PINCON->PINMODE1|=((x&0x3)<<16)
+
+/* p17 is P0.25 */
+#define p17_SEL_MASK    ~(3UL <<  18)
+#define p17_SET_MASK    (1UL <<  25)
+#define p17_CLR_MASK    ~(p17_SET_MASK)
+#define p17_AS_OUTPUT   LPC_PINCON->PINSEL1&=p17_SEL_MASK;LPC_GPIO0->FIODIR|=p17_SET_MASK
+#define p17_AS_INPUT    LPC_GPIO0->FIOMASK &= p17_CLR_MASK; 
+#define p17_SET         LPC_GPIO0->FIOSET = p17_SET_MASK
+#define p17_CLR         LPC_GPIO0->FIOCLR = p17_SET_MASK
+#define p17_IS_SET      (bool)(LPC_GPIO0->FIOPIN & p17_SET_MASK)
+#define p17_IS_CLR      !(p17_IS_SET)
+#define p17_MODE(x)     LPC_PINCON->PINMODE1&=p17_SEL_MASK;LPC_PINCON->PINMODE1|=((x&0x3)<<18)
+
+/* p18 is P0.26 */
+#define p18_SEL_MASK    ~(3UL << 20)
+#define p18_SET_MASK    (1UL << 26)
+#define p18_CLR_MASK    ~(p18_SET_MASK)
+#define p18_AS_OUTPUT   LPC_PINCON->PINSEL1&=p18_SEL_MASK;LPC_GPIO0->FIODIR|=p18_SET_MASK
+#define p18_AS_INPUT    LPC_GPIO0->FIOMASK &= p18_CLR_MASK; 
+#define p18_SET         LPC_GPIO0->FIOSET = p18_SET_MASK
+#define p18_CLR         LPC_GPIO0->FIOCLR = p18_SET_MASK
+#define p18_IS_SET      (bool)(LPC_GPIO0->FIOPIN & p18_SET_MASK)
+#define p18_IS_CLR      !(p18_IS_SET)
+#define p18_MODE(x)     LPC_PINCON->PINMODE1&=p18_SEL_MASK;LPC_PINCON->PINMODE1|=((x&0x3)<<20)
+
+/* p19 is P1.30 */
+#define p19_SEL_MASK    ~(3UL << 28)
+#define p19_SET_MASK    (1UL << 30)
+#define p19_AS_OUTPUT   LPC_PINCON->PINSEL3&=p19_SEL_MASK;LPC_GPIO1->FIODIR|=p19_SET_MASK
+#define p19_AS_INPUT    LPC_GPIO1->FIOMASK &= p19_CLR_MASK; 
+#define p19_SET         LPC_GPIO1->FIOSET = p19_SET_MASK
+#define p19_CLR         LPC_GPIO1->FIOCLR = p19_SET_MASK
+#define p19_IS_SET      (bool)(LPC_GPIO1->FIOPIN & p19_SET_MASK)
+#define p19_IS_CLR      !(p19_IS_SET)
+#define p19_MODE(x)     LPC_PINCON->PINMODE3&=p19_SEL_MASK;LPC_PINCON->PINMODE3|=((x&0x3)<<28)
+
+/* p20 is P1.31 */
+#define p20_SEL_MASK    ~(3UL << 30)
+#define p20_SET_MASK    (1UL << 31)
+#define p20_CLR_MASK    ~(p20_SET_MASK)
+#define p20_AS_OUTPUT   LPC_PINCON->PINSEL3&=p20_SEL_MASK;LPC_GPIO1->FIODIR|=p20_SET_MASK
+#define p20_AS_INPUT    LPC_GPIO1->FIOMASK &= p20_CLR_MASK; 
+#define p20_SET         LPC_GPIO1->FIOSET = p20_SET_MASK
+#define p20_CLR         LPC_GPIO1->FIOCLR = p20_SET_MASK
+#define p20_IS_SET      (bool)(LPC_GPIO1->FIOPIN & p20_SET_MASK)
+#define p20_IS_CLR      !(p20_IS_SET)
+#define p20_MODE(x)     LPC_PINCON->PINMODE3&=p20_SEL_MASK;LPC_PINCON->PINMODE3|=((x&0x3)<<30)
+
+/* p21 is P2.5 */
+#define p21_SEL_MASK    ~(3UL << 10)
+#define p21_SET_MASK    (1UL << 5)
+#define p21_CLR_MASK    ~(p21_SET_MASK)
+#define p21_AS_OUTPUT   LPC_PINCON->PINSEL4&=p21_SEL_MASK;LPC_GPIO2->FIODIR|=p21_SET_MASK
+#define p21_AS_INPUT    LPC_GPIO2->FIOMASK &= p21_CLR_MASK; 
+#define p21_SET         LPC_GPIO2->FIOSET = p21_SET_MASK
+#define p21_CLR         LPC_GPIO2->FIOCLR = p21_SET_MASK
+#define p21_IS_SET      (bool)(LPC_GPIO2->FIOPIN & p21_SET_MASK)
+#define p21_IS_CLR      !(p21_IS_SET)
+#define p21_TOGGLE      p21_IS_SET?p21_CLR:p21_SET
+#define p21_MODE(x)     LPC_PINCON->PINMODE4&=p21_SEL_MASK;LPC_PINCON->PINMODE4|=((x&0x3)<<10)
+
+/* p22 is P2.4 */
+#define p22_SEL_MASK    ~(3UL << 8)
+#define p22_SET_MASK    (1UL << 4)
+#define p22_CLR_MASK    ~(p22_SET_MASK)
+#define p22_AS_OUTPUT   LPC_PINCON->PINSEL4&=p22_SEL_MASK;LPC_GPIO2->FIODIR|=p22_SET_MASK
+#define p22_AS_INPUT    LPC_GPIO2->FIOMASK &= p22_CLR_MASK; 
+#define p22_SET         LPC_GPIO2->FIOSET = p22_SET_MASK
+#define p22_CLR         LPC_GPIO2->FIOCLR = p22_SET_MASK
+#define p22_IS_SET      (bool)(LPC_GPIO2->FIOPIN & p22_SET_MASK)
+#define p22_IS_CLR      !(p22_IS_SET)
+#define p22_TOGGLE      p22_IS_SET?p22_CLR:p22_SET
+#define p22_MODE(x)     LPC_PINCON->PINMODE4&=p22_SEL_MASK;LPC_PINCON->PINMODE4|=((x&0x3)<<8)
+
+/* p23 is P2.3 */
+#define p23_SEL_MASK    ~(3UL << 6)
+#define p23_SET_MASK    (1UL << 3)
+#define p23_CLR_MASK    ~(p23_SET_MASK)
+#define p23_AS_OUTPUT   LPC_PINCON->PINSEL4&=p23_SEL_MASK;LPC_GPIO2->FIODIR|=p23_SET_MASK
+#define p23_AS_INPUT    LPC_GPIO2->FIOMASK &= p23_CLR_MASK; 
+#define p23_SET         LPC_GPIO2->FIOSET = p23_SET_MASK
+#define p23_CLR         LPC_GPIO2->FIOCLR = p23_SET_MASK
+#define p23_IS_SET      (bool)(LPC_GPIO2->FIOPIN & p23_SET_MASK)
+#define p23_IS_CLR      !(p23_IS_SET)
+#define p23_TOGGLE      p23_IS_SET?p23_CLR:p23_SET
+#define p23_MODE(x)     LPC_PINCON->PINMODE4&=p23_SEL_MASK;LPC_PINCON->PINMODE4|=((x&0x3)<<6)
+
+/* p24 is P2.2 */
+#define p24_SEL_MASK    ~(3UL << 4)
+#define p24_SET_MASK    (1UL << 2)
+#define p24_CLR_MASK    ~(p24_SET_MASK)
+#define p24_AS_OUTPUT   LPC_PINCON->PINSEL4&=p24_SEL_MASK;LPC_GPIO2->FIODIR|=p24_SET_MASK
+#define p24_AS_INPUT    LPC_GPIO2->FIOMASK &= p24_CLR_MASK; 
+#define p24_SET         LPC_GPIO2->FIOSET = p24_SET_MASK
+#define p24_CLR         LPC_GPIO2->FIOCLR = p24_SET_MASK
+#define p24_IS_SET      (bool)(LPC_GPIO2->FIOPIN & p24_SET_MASK)
+#define p24_IS_CLR      !(p24_IS_SET)
+#define p24_TOGGLE      p24_IS_SET?p24_CLR:p24_SET
+#define p24_MODE(x)     LPC_PINCON->PINMODE4&=p24_SEL_MASK;LPC_PINCON->PINMODE4|=((x&0x3)<<4)
+
+/* p25 is P2.1 */
+#define p25_SEL_MASK    ~(3UL << 2)
+#define p25_SET_MASK    (1UL << 1)
+#define p25_CLR_MASK    ~(p25_SET_MASK)
+#define p25_AS_OUTPUT   LPC_PINCON->PINSEL4&=p25_SEL_MASK;LPC_GPIO2->FIODIR|=p25_SET_MASK
+#define p25_AS_INPUT    LPC_GPIO2->FIOMASK &= p25_CLR_MASK; 
+#define p25_SET         LPC_GPIO2->FIOSET = p25_SET_MASK
+#define p25_CLR         LPC_GPIO2->FIOCLR = p25_SET_MASK
+#define p25_IS_SET      (bool)(LPC_GPIO2->FIOPIN & p25_SET_MASK)
+#define p25_IS_CLR      !(p25_IS_SET)
+#define p25_MODE(x)     LPC_PINCON->PINMODE4&=p25_SEL_MASK;LPC_PINCON->PINMODE4|=((x&0x3)<<2)
+
+/* p26 is P2.0 */
+#define p26_SEL_MASK    ~(3UL << 0)
+#define p26_SET_MASK    (1UL << 0)
+#define p26_CLR_MASK    ~(p26_SET_MASK)
+#define p26_AS_OUTPUT   LPC_PINCON->PINSEL4&=p26_SEL_MASK;LPC_GPIO2->FIODIR|=p26_SET_MASK
+#define p26_AS_INPUT    LPC_GPIO2->FIOMASK &= p26_CLR_MASK; 
+#define p26_SET         LPC_GPIO2->FIOSET = p26_SET_MASK
+#define p26_CLR         LPC_GPIO2->FIOCLR = p26_SET_MASK
+#define p26_IS_SET      (bool)(LPC_GPIO2->FIOPIN & p26_SET_MASK)
+#define p26_IS_CLR      !(p26_IS_SET)
+#define p26_MODE(x)     LPC_PINCON->PINMODE4&=p26_SEL_MASK;LPC_PINCON->PINMODE4|=((x&0x3)<<0)
+
+/* p27 is P0.11 */
+#define p27_SEL_MASK    ~(3UL << 22)
+#define p27_SET_MASK    (1UL << 11)
+#define p27_CLR_MASK    ~(p27_SET_MASK)
+#define p27_AS_OUTPUT   LPC_PINCON->PINSEL0&=p27_SEL_MASK;LPC_GPIO0->FIODIR|=p27_SET_MASK
+#define p27_AS_INPUT    LPC_GPIO0->FIOMASK &= p27_CLR_MASK; 
+#define p27_SET         LPC_GPIO0->FIOSET = p27_SET_MASK
+#define p27_CLR         LPC_GPIO0->FIOCLR = p27_SET_MASK
+#define p27_IS_SET      (bool)(LPC_GPIO0->FIOPIN & p27_SET_MASK)
+#define p27_IS_CLR      !(p27_IS_SET)
+#define p27_MODE(x)     LPC_PINCON->PINMODE0&=p27_SEL_MASK;LPC_PINCON->PINMODE0|=((x&0x3)<<22)
+
+/* p28 is P0.10 */
+#define p28_SEL_MASK    ~(3UL << 20)
+#define p28_SET_MASK    (1UL <<  10)
+#define p28_CLR_MASK    ~(p28_SET_MASK)
+#define p28_AS_OUTPUT   LPC_PINCON->PINSEL0&=p28_SEL_MASK;LPC_GPIO0->FIODIR|=p28_SET_MASK
+#define p28_AS_INPUT    LPC_GPIO0->FIOMASK &= p28_CLR_MASK; 
+#define p28_SET         LPC_GPIO0->FIOSET = p28_SET_MASK
+#define p28_CLR         LPC_GPIO0->FIOCLR = p28_SET_MASK
+#define p28_IS_SET      (bool)(LPC_GPIO0->FIOPIN & p28_SET_MASK)
+#define p28_IS_CLR      !(p28_IS_SET)
+#define p28_MODE(x)     LPC_PINCON->PINMODE0&=p28_SEL_MASK;LPC_PINCON->PINMODE0|=((x&0x3)<<20)
+
+/* p29 is P0.5 */
+#define p29_SEL_MASK    ~(3UL << 10)
+#define p29_SET_MASK    (1UL << 5)
+#define p29_CLR_MASK    ~(p29_SET_MASK)
+#define p29_AS_OUTPUT   LPC_PINCON->PINSEL0&=p29_SEL_MASK;LPC_GPIO0->FIODIR|=p29_SET_MASK
+#define p29_AS_INPUT    LPC_GPIO0->FIOMASK &= p29_CLR_MASK; 
+#define p29_SET         LPC_GPIO0->FIOSET = p29_SET_MASK
+#define p29_CLR         LPC_GPIO0->FIOCLR = p29_SET_MASK
+#define p29_IS_SET      (bool)(LPC_GPIO0->FIOPIN & p29_SET_MASK)
+#define p29_IS_CLR      !(p29_IS_SET)
+#define p29_TOGGLE      p29_IS_SET?p29_CLR:p29_SET
+#define p29_MODE(x)     LPC_PINCON->PINMODE0&=p29_SEL_MASK;LPC_PINCON->PINMODE0|=((x&0x3)<<10)
+
+/* p30 is P0.4 */
+#define p30_SEL_MASK    ~(3UL << 8)
+#define p30_SET_MASK    (1UL << 4)
+#define p30_CLR_MASK    ~(p30_SET_MASK)
+#define p30_AS_OUTPUT   LPC_PINCON->PINSEL0&=p30_SEL_MASK;LPC_GPIO0->FIODIR|=p30_SET_MASK
+#define p30_AS_INPUT    LPC_GPIO0->FIOMASK &= p30_CLR_MASK; 
+#define p30_SET         LPC_GPIO0->FIOSET = p30_SET_MASK
+#define p30_CLR         LPC_GPIO0->FIOCLR = p30_SET_MASK
+#define p30_IS_SET      (bool)(LPC_GPIO0->FIOPIN & p30_SET_MASK)
+#define p30_IS_CLR      !(p30_IS_SET)
+#define p30_MODE(x)     LPC_PINCON->PINMODE0&=p30_SEL_MASK;LPC_PINCON->PINMODE0|=((x&0x3)<<8)
+
+/* The following definitions are for the four Mbed LEDs.
+    LED1 = P1.18
+    LED2 = P1.20
+    LED3 = P1.21
+    LED4 = P1.23 */
+
+#define P1_18_SEL_MASK  ~(3UL << 4)
+#define P1_18_SET_MASK  (1UL << 18)
+#define P1_18_CLR_MASK  ~(P1_18_SET_MASK)
+#define P1_18_AS_OUTPUT LPC_PINCON->PINSEL3&=P1_18_SEL_MASK;LPC_GPIO1->FIODIR|=P1_18_SET_MASK
+#define P1_18_AS_INPUT  LPC_GPIO1->FIOMASK &= P1_18_CLR_MASK; 
+#define P1_18_SET       LPC_GPIO1->FIOSET = P1_18_SET_MASK
+#define P1_18_CLR       LPC_GPIO1->FIOCLR = P1_18_SET_MASK
+#define P1_18_IS_SET    (bool)(LPC_GPIO1->FIOPIN & P1_18_SET_MASK)
+#define P1_18_IS_CLR    !(P1_18_IS_SET)
+#define LED1_USE        P1_18_AS_OUTPUT;P1_18_AS_INPUT
+#define LED1_ON         P1_18_SET
+#define LED1_OFF        P1_18_CLR
+#define LED1_IS_ON      P1_18_IS_SET
+#define LED1_TOGGLE     P1_18_IS_SET?LED1_OFF:LED1_ON
+
+#define P1_20_SEL_MASK  ~(3UL << 8)
+#define P1_20_SET_MASK  (1UL << 20)
+#define P1_20_CLR_MASK  ~(P1_20_SET_MASK)
+#define P1_20_AS_OUTPUT LPC_PINCON->PINSEL3&=P1_20_SEL_MASK;LPC_GPIO1->FIODIR|=P1_20_SET_MASK
+#define P1_20_AS_INPUT  LPC_GPIO1->FIOMASK &= P1_20_CLR_MASK; 
+#define P1_20_SET       LPC_GPIO1->FIOSET = P1_20_SET_MASK
+#define P1_20_CLR       LPC_GPIO1->FIOCLR = P1_20_SET_MASK
+#define P1_20_IS_SET    (bool)(LPC_GPIO1->FIOPIN & P1_20_SET_MASK)
+#define P1_20_IS_CLR    !(P1_20_IS_SET)    
+#define LED2_USE        P1_20_AS_OUTPUT;P1_20_AS_INPUT
+#define LED2_ON         P1_20_SET
+#define LED2_OFF        P1_20_CLR
+#define LED2_IS_ON      P1_20_IS_SET
+#define LED2_TOGGLE     P1_20_IS_SET?LED2_OFF:LED2_ON
+
+#define P1_21_SEL_MASK  ~(3UL << 10)
+#define P1_21_SET_MASK  (1UL << 21)
+#define P1_21_CLR_MASK  ~(P1_21_SET_MASK)
+#define P1_21_AS_OUTPUT LPC_PINCON->PINSEL3&=P1_21_SEL_MASK;LPC_GPIO1->FIODIR|=P1_21_SET_MASK
+#define P1_21_AS_INPUT  LPC_GPIO1->FIOMASK &= P1_21_CLR_MASK; 
+#define P1_21_SET       LPC_GPIO1->FIOSET = P1_21_SET_MASK
+#define P1_21_CLR       LPC_GPIO1->FIOCLR = P1_21_SET_MASK
+#define P1_21_IS_SET    (bool)(LPC_GPIO1->FIOPIN & P1_21_SET_MASK)
+#define P1_21_IS_CLR    !(P1_21_IS_SET)
+#define LED3_USE        P1_21_AS_OUTPUT;P1_21_AS_INPUT
+#define LED3_ON         P1_21_SET
+#define LED3_OFF        P1_21_CLR
+#define LED3_IS_ON      P1_21_IS_SET
+#define LED3_TOGGLE     P1_21_IS_SET?LED3_OFF:LED3_ON
+
+#define P1_23_SEL_MASK  ~(3UL << 14)
+#define P1_23_SET_MASK  (1UL << 23)
+#define P1_23_CLR_MASK  ~(P1_23_SET_MASK)
+#define P1_23_AS_OUTPUT LPC_PINCON->PINSEL3&=P1_23_SEL_MASK;LPC_GPIO1->FIODIR|=P1_23_SET_MASK
+#define P1_23_AS_INPUT  LPC_GPIO1->FIOMASK &= P1_23_CLR_MASK; 
+#define P1_23_SET       LPC_GPIO1->FIOSET = P1_23_SET_MASK
+#define P1_23_CLR       LPC_GPIO1->FIOCLR = P1_23_SET_MASK
+#define P1_23_IS_SET    (bool)(LPC_GPIO1->FIOPIN & P1_23_SET_MASK)
+#define P1_23_IS_CLR    !(P1_23_IS_SET)    
+#define LED4_USE        P1_23_AS_OUTPUT;P1_23_AS_INPUT
+#define LED4_ON         P1_23_SET
+#define LED4_OFF        P1_23_CLR
+#define LED4_IS_ON      P1_23_IS_SET
+#define LED4_TOGGLE     P1_23_IS_SET?LED4_OFF:LED4_ON
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/NTPClient.lib	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/donatien/code/NTPClient/#7c3f1199256a
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Pachube/Pachube.cpp	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,17 @@
+/**
+ * Pachube API interface driver. (Version 0.0.1)
+ *
+ * Copyright (C) 2010 Shinichiro Nakamura (CuBeatSystems)
+ * http://shinta.main.jp/
+ */
+
+#include "Pachube.h"
+
+const std::string Pachube::REQUESTHEADER = "X-PachubeApiKey";
+const std::string Pachube::URLBASE_V2 = "http://api.pachube.com/v2";
+
+Pachube::Pachube(std::string APIKEY) : APIKEY(APIKEY) {
+}
+
+Pachube::~Pachube() {
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Pachube/Pachube.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,177 @@
+/*******************************************************************************
+modify 
+2011/08
+        - Use commonClient.
+
+*******************************************************************************/
+
+/**
+ * Pachube API interface driver. (Version 0.0.1)
+ *
+ * Copyright (C) 2010 Shinichiro Nakamura (CuBeatSystems)
+ * http://shinta.main.jp/
+ */
+
+#ifndef _PACHUBE_H_
+#define _PACHUBE_H_
+
+#include <string>
+#include "HTTPClient.h"
+
+class Pachube {
+public:
+
+    explicit Pachube(std::string APIKEY);
+
+    virtual ~Pachube();
+
+    /*
+     * =================================================================
+     *  Environments (feeds)
+     * =================================================================
+     */
+
+    /**
+     * List all available feeds: GET /v2/feeds
+     *
+     * @param page Integer indicating which page of results you are requesting.
+     * @param per_page Integer defining how many results to return per page (1 to 1000).
+     * @param content String parameter ('full' or 'summary') describing whether we want full or summary results. Full results means all datastream values are returned, summary just returns the environment meta data for each feed.
+     * @param q Full text search parameter. Should return any feeds matching this string.
+     * @param tag Returns feeds containing datastreams tagged with the search query.
+     * @param user Returns feeds created by the user specified.
+     * @param units Returns feeds containing datastreams with units specified by the search query.
+     * @param status Possible values ('live', 'frozen', or 'all'). Whether to search for only live feeds, only frozen feeds, or all feeds. Defaults to all.
+     * @param order Order of returned feeds. Possible values ('created_at', 'retrieved_at', or 'relevance').
+     */
+    virtual int listAllAvailableFeeds(
+        int page,
+        int per_page,
+        std::string content,
+        std::string q,
+        std::string tag,
+        std::string user,
+        std::string units,
+        std::string status,
+        std::string order,
+        std::string &datatext) = 0;
+
+    /**
+     * Create new feed: POST /v2/feeds
+     */
+    virtual int createNewFeed(void) = 0;
+
+    /**
+     * Read feed: GET /v2/feeds/<feed_id>
+     */
+    virtual int readFeed(int feed_id, std::string &datatext) = 0;
+
+    /**
+     * Update feed: PUT /v2/feeds/<feed_id>
+     */
+    virtual int updateFeed(int feed_id) = 0;
+
+    /**
+     * Delete feed: DELETE /v2/feeds/<feed_id>
+     */
+    virtual int deleteFeed(int feed_id) = 0;
+
+    /*
+     * =================================================================
+     *  Datastreams
+     * =================================================================
+     */
+
+    /**
+     * Create new datastream: POST /v2/feeds/<feed_id>/datastreams
+     *
+     * @param feed_id Feed ID.
+     * @param stream_id Stream ID text.
+     * @param value value.
+     *
+     * @return Return code from a web server.
+     */
+    virtual int createNewDataStream(int feed_id, std::string stream_id, std::string value) = 0;
+
+    /**
+     * Read datastream - GET /v2/feeds/<feed_id>/datastreams/<datastream_id>
+     *
+     * @param feed_id Feed ID.
+     * @param stream_id Stream ID text.
+     *
+     * @return Return code from a web server.
+     */
+    virtual int readDataStream(int feed_id, std::string stream_id, std::string &datatext) = 0;
+
+    /**
+     * Update datastream: PUT /v2/feeds/<feed_id>/datastreams/<datastream_id>
+     *
+     * @param feed_id Feed ID.
+     * @param stream_id Stream ID text.
+     * @param value value.
+     *
+     * @return Return code from a web server.
+     */
+//    virtual int updateDataStream(int feed_id, std::string stream_id, std::string value) = 0;
+    virtual int updateDataStream(int feed_id, std::string stream_id, std::string value, HTTPClient *pClient) = 0;   //  2011/08
+
+    /**
+     * Delete datastream: DELETE /v2/feeds/<feed_id>/datastreams/<datastream_id>
+     *
+     * @param feed_id Feed ID.
+     * @param stream_id Stream ID text.
+     *
+     * @return Return code from a web server.
+     */
+    virtual int deleteDataStream(int feed_id, std::string stream_id) = 0;
+
+protected:
+    const std::string APIKEY;
+    static const std::string REQUESTHEADER;
+    static const std::string URLBASE_V2;
+};
+
+#endif
+
+/*
+Pachube v2 API Documentation
+http://api.pachube.com/v2/
+
+# Environments (feeds)
+
+o   * List all available feeds: GET /v2/feeds
+o   * Create new feed: POST /v2/feeds
+o   * Read feed: GET /v2/feeds/<feed_id>
+o   * Update feed: PUT /v2/feeds/<feed_id>
+o   * Delete feed: DELETE /v2/feeds/<feed_id>
+
+# Datastreams
+
+o   * Create new datastream: POST /v2/feeds/<feed_id>/datastreams
+o   * Read datastream - GET /v2/feeds/<feed_id>/datastreams/<datastream_id>
+o   * Update datastream: PUT /v2/feeds/<feed_id>/datastreams/<datastream_id>
+o   * Delete datastream: DELETE /v2/feeds/<feed_id>/datastreams/<datastream_id>
+
+# Datapoints
+
+    * Create datapoint: POST /v2/feeds/<feed_id>/datastreams/<datastream_id>/datapoints
+    * Read datapoint: GET /v2/feeds/<feed_id>/datastreams/<datastream_id>/datapoints/<timestamp>
+    * Update datapoint: PUT /v2/feeds/<feed_id>/datastreams/<datastream_id>/datapoints/<timestamp>
+    * Delete datapoint: DELETE /v2/feeds/<feed_id>/datastreams/<datastream_id>/datapoints/<timestamp>
+
+# Triggers
+
+    * List triggers: GET /v2/triggers
+    * Create trigger: POST /v2/triggers
+    * Read trigger: GET /v2/triggers/<trigger_id>
+    * Update trigger: PUT /v2/triggers/<trigger_id>
+    * Delete trigger: DELETE /v2/triggers/<trigger_id>
+
+# Users
+
+    * List all users: GET /v2/users
+    * Create user: POST /v2/users
+    * Read user: GET /v2/users/<user_id>
+    * Update user: PUT /v2/users/<user_id>
+    * Delete user: DELETE /v2/users/<user_id>
+*/
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Pachube/PachubeV2CSV.cpp	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,273 @@
+/*******************************************************************************
+modify 
+2011/08
+        - Use commonClient.
+
+*******************************************************************************/
+
+/**
+ * Pachube API interface driver. (Version 0.0.1)
+ *
+ * Copyright (C) 2010 Shinichiro Nakamura (CuBeatSystems)
+ * http://shinta.main.jp/
+ */
+
+#include "PachubeV2CSV.h"
+#include "EthernetNetIf.h"
+#include "HTTPClient.h"
+
+PachubeV2CSV::PachubeV2CSV(std::string APIKEY) : Pachube(APIKEY) {
+}
+
+PachubeV2CSV::~PachubeV2CSV() {
+}
+
+/*
+ * =================================================================
+ *  Environments (feeds)
+ * =================================================================
+ */
+
+/**
+ * List all available feeds: GET /v2/feeds
+ */
+int PachubeV2CSV::listAllAvailableFeeds(
+        int page,
+        int per_page,
+        std::string content,
+        std::string q,
+        std::string tag,
+        std::string user,
+        std::string units,
+        std::string status,
+        std::string order,
+        std::string &datatext) {
+    HTTPClient client;
+    client.setRequestHeader(Pachube::REQUESTHEADER, APIKEY);
+
+    HTTPText text("text/csv");
+    text.set("");
+    HTTPText data;
+    
+    /*
+     * Example: http://api.pachube.com/v2/feeds
+     */
+    char tmp[32];
+    sprintf(tmp, "?page=%d&per_page=%d", page, per_page);
+    string URL = Pachube::URLBASE_V2 + "/feeds.csv" + std::string(tmp);
+    
+    if (content.length() > 0) {
+        URL = URL + "&content=" + content;
+    }
+    if (q.length() > 0) {
+        URL = URL + "&q=" + q;
+    }
+    if (tag.length() > 0) {
+        URL = URL + "&tag=" + tag;
+    }
+    if (user.length() > 0) {
+        URL = URL + "&user=" + user;
+    }
+    if (units.length() > 0) {
+        URL = URL + "&units=" + units;
+    }
+    if (status.length() > 0) {
+        URL = URL + "&status=" + status;
+    }
+    if (order.length() > 0) {
+        URL = URL + "&order=" + order;
+    }
+
+    HTTPResult result = client.get(URL.c_str(), &data);
+    datatext = data.get();
+    
+    return client.getHTTPResponseCode();
+}
+
+/**
+ * Create new feed: POST /v2/feeds
+ */
+int PachubeV2CSV::createNewFeed(void) {
+    error("CSV is not supported for creating Environments because it cannot represent the required parameters due to its very simple format.");
+    return 404;
+}
+
+/**
+ * Read feed: GET /v2/feeds/<feed_id>
+ */
+int PachubeV2CSV::readFeed(int feed_id, std::string &datatext) {
+    HTTPClient client;
+    client.setRequestHeader(Pachube::REQUESTHEADER, APIKEY);
+
+    HTTPText text("text/csv");
+    text.set("");
+    HTTPText data;
+
+    /*
+     * Example: http://api.pachube.com/v2/feeds/1977
+     */
+    char feed_id_char[32];
+    sprintf(feed_id_char, "%d", feed_id);
+    const string URL = Pachube::URLBASE_V2 + "/feeds/" + std::string(feed_id_char) + ".csv";
+
+    HTTPResult result = client.get(URL.c_str(), &data);
+    datatext = data.get();
+    return client.getHTTPResponseCode();
+}
+
+/**
+ * Update feed: PUT /v2/feeds/<feed_id>
+ */
+int PachubeV2CSV::updateFeed(int feed_id) {
+    HTTPClient client;
+    client.setRequestHeader(Pachube::REQUESTHEADER, APIKEY);
+
+    HTTPText text("text/csv");
+    text.set("");
+
+    /*
+     * Example: http://api.pachube.com/v2/feeds/1977?_method=put
+     */
+    char feed_id_char[32];
+    sprintf(feed_id_char, "%d", feed_id);
+    const string URL = Pachube::URLBASE_V2 + "/feeds/" + std::string(feed_id_char) + "?_method=put";
+
+    HTTPResult result = client.post(URL.c_str(), text, NULL);
+    return client.getHTTPResponseCode();
+}
+
+/**
+ * Delete feed: DELETE /v2/feeds/<feed_id>
+ */
+int PachubeV2CSV::deleteFeed(int feed_id) {
+    HTTPClient client;
+    client.setRequestHeader(Pachube::REQUESTHEADER, APIKEY);
+
+    HTTPText text("text/csv");
+    text.set("");
+
+    /*
+     * Example: http://api.pachube.com/v2/feeds/1977?_method=delete
+     */
+    char feed_id_char[32];
+    sprintf(feed_id_char, "%d", feed_id);
+    const string URL = Pachube::URLBASE_V2 + "/feeds/" + std::string(feed_id_char) + "?_method=delete";
+
+    HTTPResult result = client.post(URL.c_str(), text, NULL);
+    return client.getHTTPResponseCode();
+}
+
+/*
+ * =================================================================
+ *  Datastreams
+ * =================================================================
+ */
+
+/**
+ * Create new datastream: POST /v2/feeds/<feed_id>/datastreams
+ *
+ * @param feed_id Feed ID.
+ * @param stream_id Stream ID text.
+ * @param value value.
+ *
+ * @return Return code from a web server.
+ */
+int PachubeV2CSV::createNewDataStream(int feed_id, std::string stream_id, std::string value) {
+    HTTPClient client;
+    client.setRequestHeader(Pachube::REQUESTHEADER, APIKEY);
+
+    std::string data = stream_id + "," + value;
+    HTTPText text("text/csv");
+    text.set(data);
+
+    /*
+     * Example: http://api.pachube.com/v2/feeds/1977/datastreams
+     */
+    char feed_id_char[32];
+    sprintf(feed_id_char, "%d", feed_id);
+    const string URL = Pachube::URLBASE_V2 + "/feeds/" + std::string(feed_id_char) + "/datastreams";
+
+    HTTPResult result = client.post(URL.c_str(), text, NULL);
+    return client.getHTTPResponseCode();
+}
+
+/**
+ * Read datastream - GET /v2/feeds/<feed_id>/datastreams/<datastream_id>
+ *
+ * @param feed_id Feed ID.
+ * @param stream_id Stream ID text.
+ *
+ * @return Return code from a web server.
+ */
+int PachubeV2CSV::readDataStream(int feed_id, std::string stream_id, std::string &datatext) {
+    HTTPClient client;
+    client.setRequestHeader(Pachube::REQUESTHEADER, APIKEY);
+
+    HTTPText text("text/csv");
+    text.set("");
+    HTTPText data;
+
+    /*
+     * Example: http://api.pachube.com/v2/feeds/1977/datastreams/energy
+     */
+    char feed_id_char[32];
+    sprintf(feed_id_char, "%d", feed_id);
+    const string URL = Pachube::URLBASE_V2 + "/feeds/" + std::string(feed_id_char) + "/datastreams/" + stream_id + ".csv";
+
+    HTTPResult result = client.get(URL.c_str(), &data);
+    datatext = data.get();
+    return client.getHTTPResponseCode();
+}
+
+/**
+ * Update datastream: PUT /v2/feeds/<feed_id>/datastreams/<datastream_id>
+ *
+ * @param feed_id Feed ID.
+ * @param stream_id Stream ID text.
+ * @param value value.
+ *
+ * @return Return code from a web server.
+ */
+//int PachubeV2CSV::updateDataStream(int feed_id, std::string stream_id, std::string value) {
+int PachubeV2CSV::updateDataStream(int feed_id, std::string stream_id, std::string value, HTTPClient *client) { //  2011/08
+    //HTTPClient client;
+    client->setRequestHeader(Pachube::REQUESTHEADER, APIKEY);   //  2011/08
+
+    HTTPText text("text/csv");
+    text.set(value);
+
+    /*
+     * Example: http://api.pachube.com/v2/feeds/1977/datastreams/energy?_method=put
+     */
+    char feed_id_char[32];
+    sprintf(feed_id_char, "%d", feed_id);
+    const string URL = Pachube::URLBASE_V2 + "/feeds/" + std::string(feed_id_char) + "/datastreams/" + stream_id + "?_method=put";
+    HTTPResult result = client->post(URL.c_str(), text, NULL);
+    return client->getHTTPResponseCode();   // 2011/08
+}
+
+/**
+ * Delete datastream: DELETE /v2/feeds/<feed_id>/datastreams/<datastream_id>
+ *
+ * @param feed_id Feed ID.
+ * @param stream_id Stream ID text.
+ *
+ * @return Return code from a web server.
+ */
+int PachubeV2CSV::deleteDataStream(int feed_id, std::string stream_id) {
+    HTTPClient client;
+    client.setRequestHeader(Pachube::REQUESTHEADER, APIKEY);
+
+    HTTPText text("text/csv");
+    text.set("");
+
+    /*
+     * Example: http://api.pachube.com/v2/feeds/1977/datastreams/energy?_method=delete
+     */
+    char feed_id_char[32];
+    sprintf(feed_id_char, "%d", feed_id);
+    const string URL = Pachube::URLBASE_V2 + "/feeds/" + std::string(feed_id_char) + "/datastreams/" + stream_id + "?_method=delete";
+
+    HTTPResult result = client.post(URL.c_str(), text, NULL);
+    return client.getHTTPResponseCode();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Pachube/PachubeV2CSV.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,130 @@
+/*******************************************************************************
+modify 
+2011/08
+        - Use commonClient.
+
+*******************************************************************************/
+
+/**
+ * Pachube API interface driver. (Version 0.0.1)
+ *
+ * Copyright (C) 2010 Shinichiro Nakamura (CuBeatSystems)
+ * http://shinta.main.jp/
+ */
+
+#ifndef _PACHUBE_V2_CSV_H_
+#define _PACHUBE_V2_CSV_H_
+
+#include "Pachube.h"
+#include "HTTPClient.h"
+
+class PachubeV2CSV : public Pachube {
+public:
+
+    explicit PachubeV2CSV(std::string APIKEY);
+
+    virtual ~PachubeV2CSV();
+
+    /*
+     * =================================================================
+     *  Environments (feeds)
+     * =================================================================
+     */
+
+    /**
+     * List all available feeds: GET /v2/feeds
+     *
+     * @param page Integer indicating which page of results you are requesting.
+     * @param per_page Integer defining how many results to return per page (1 to 1000).
+     * @param content String parameter ('full' or 'summary') describing whether we want full or summary results. Full results means all datastream values are returned, summary just returns the environment meta data for each feed.
+     * @param q Full text search parameter. Should return any feeds matching this string.
+     * @param tag Returns feeds containing datastreams tagged with the search query.
+     * @param user Returns feeds created by the user specified.
+     * @param units Returns feeds containing datastreams with units specified by the search query.
+     * @param status Possible values ('live', 'frozen', or 'all'). Whether to search for only live feeds, only frozen feeds, or all feeds. Defaults to all.
+     * @param order Order of returned feeds. Possible values ('created_at', 'retrieved_at', or 'relevance').
+     */
+    virtual int listAllAvailableFeeds(
+        int page,
+        int per_page,
+        std::string content,
+        std::string q,
+        std::string tag,
+        std::string user,
+        std::string units,
+        std::string status,
+        std::string order,
+        std::string &datatext);
+
+    /**
+     * Create new feed: POST /v2/feeds
+     */
+    virtual int createNewFeed(void);
+
+    /**
+     * Read feed: GET /v2/feeds/<feed_id>
+     */
+    virtual int readFeed(int feed_id, std::string &datatext);
+
+    /**
+     * Update feed: PUT /v2/feeds/<feed_id>
+     */
+    virtual int updateFeed(int feed_id);
+
+    /**
+     * Delete feed: DELETE /v2/feeds/<feed_id>
+     */
+    virtual int deleteFeed(int feed_id);
+
+    /*
+     * =================================================================
+     *  Datastreams
+     * =================================================================
+     */
+
+    /**
+     * Create new datastream: POST /v2/feeds/<feed_id>/datastreams
+     *
+     * @param feed_id Feed ID.
+     * @param stream_id Stream ID text.
+     * @param value value.
+     *
+     * @return Return code from a web server.
+     */
+    virtual int createNewDataStream(int feed_id, std::string stream_id, std::string value);
+
+    /**
+     * Read datastream - GET /v2/feeds/<feed_id>/datastreams/<datastream_id>
+     *
+     * @param feed_id Feed ID.
+     * @param stream_id Stream ID text.
+     *
+     * @return Return code from a web server.
+     */
+    virtual int readDataStream(int feed_id, std::string stream_id, std::string &datatext);
+
+    /**
+     * Update datastream: PUT /v2/feeds/<feed_id>/datastreams/<datastream_id>
+     *
+     * @param feed_id Feed ID.
+     * @param stream_id Stream ID text.
+     * @param value value.
+     *
+     * @return Return code from a web server.
+     */
+//    virtual int updateDataStream(int feed_id, std::string stream_id, std::string value);
+    virtual int updateDataStream(int feed_id, std::string stream_id, std::string value, HTTPClient *pClient);   //  2011/08
+
+    /**
+     * Delete datastream: DELETE /v2/feeds/<feed_id>/datastreams/<datastream_id>
+     *
+     * @param feed_id Feed ID.
+     * @param stream_id Stream ID text.
+     *
+     * @return Return code from a web server.
+     */
+    virtual int deleteDataStream(int feed_id, std::string stream_id);
+
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TextLCD/TextLCD.cpp	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,159 @@
+/* mbed TextLCD Library, for a 4-bit LCD based on HD44780
+ * Copyright (c) 2007-2010, sford, http://mbed.org
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include "TextLCD.h"
+#include "mbed.h"
+
+TextLCD::TextLCD(PinName rs, PinName e, PinName d4, PinName d5,
+                 PinName d6, PinName d7, LCDType type) : _rs(rs),
+        _e(e), _d(d4, d5, d6, d7),
+        _type(type) {
+
+    _e  = 1;
+    _rs = 0;            // command mode
+
+    wait(0.015);        // Wait 15ms to ensure powered up
+
+    // send "Display Settings" 3 times (Only top nibble of 0x30 as we've got 4-bit bus)
+    for (int i=0; i<3; i++) {
+        writeByte(0x3);
+        wait(0.00164);  // this command takes 1.64ms, so wait for it
+    }
+    writeByte(0x2);     // 4-bit mode
+    wait(0.000040f);    // most instructions take 40us
+
+    writeCommand(0x28); // Function set 001 BW N F - -
+    writeCommand(0x0C);
+    writeCommand(0x6);  // Cursor Direction and Display Shift : 0000 01 CD S (CD 0-left, 1-right S(hift) 0-no, 1-yes
+    cls();
+}
+
+void TextLCD::character(int column, int row, int c) {
+    int a = address(column, row);
+    writeCommand(a);
+    writeData(c);
+}
+
+void TextLCD::cls() {
+    writeCommand(0x01); // cls, and set cursor to 0
+    wait(0.00164f);     // This command takes 1.64 ms
+    locate(0, 0);
+}
+
+void TextLCD::locate(int column, int row) {
+    _column = column;
+    _row = row;
+}
+
+int TextLCD::_putc(int value) {
+    if (value == '\n') {
+        _column = 0;
+        _row++;
+        if (_row >= rows()) {
+            _row = 0;
+        }
+    } else {
+        character(_column, _row, value);
+        _column++;
+        if (_column >= columns()) {
+            _column = 0;
+            _row++;
+            if (_row >= rows()) {
+                _row = 0;
+            }
+        }
+    }
+    return value;
+}
+
+int TextLCD::_getc() {
+    return -1;
+}
+
+void TextLCD::writeByte(int value) {
+    _d = value >> 4;
+    wait(0.000040f); // most instructions take 40us
+    _e = 0;
+    wait(0.000040f);
+    _e = 1;
+    _d = value >> 0;
+    wait(0.000040f);
+    _e = 0;
+    wait(0.000040f);  // most instructions take 40us
+    _e = 1;
+}
+
+void TextLCD::writeCommand(int command) {
+    _rs = 0;
+    writeByte(command);
+}
+
+void TextLCD::writeData(int data) {
+    _rs = 1;
+    writeByte(data);
+}
+
+int TextLCD::address(int column, int row) {
+    switch (_type) {
+        case LCD20x4:
+            switch (row) {
+                case 0:
+                    return 0x80 + column;
+                case 1:
+                    return 0xc0 + column;
+                case 2:
+                    return 0x94 + column;
+                case 3:
+                    return 0xd4 + column;
+            }
+        case LCD16x2B:
+            return 0x80 + (row * 40) + column;
+        case LCD16x2:
+        case LCD20x2:
+        default:
+            return 0x80 + (row * 0x40) + column;
+    }
+}
+
+int TextLCD::columns() {
+    switch (_type) {
+        case LCD20x4:
+        case LCD20x2:
+            return 20;
+        case LCD16x2:
+        case LCD16x2B:
+        default:
+            return 16;
+    }
+}
+
+int TextLCD::rows() {
+    switch (_type) {
+        case LCD20x4:
+            return 4;
+        case LCD16x2:
+        case LCD16x2B:
+        case LCD20x2:
+        default:
+            return 2;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TextLCD/TextLCD.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,111 @@
+/* mbed TextLCD Library, for a 4-bit LCD based on HD44780
+ * Copyright (c) 2007-2010, sford, http://mbed.org
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#ifndef MBED_TEXTLCD_H
+#define MBED_TEXTLCD_H
+
+#include "mbed.h"
+
+/** A TextLCD interface for driving 4-bit HD44780-based LCDs
+ *
+ * Currently supports 16x2, 20x2 and 20x4 panels
+ *
+ * @code
+ * #include "mbed.h"
+ * #include "TextLCD.h"
+ * 
+ * TextLCD lcd(p10, p12, p15, p16, p29, p30); // rs, e, d4-d7
+ * 
+ * int main() {
+ *     lcd.printf("Hello World!\n");
+ * }
+ * @endcode
+ */
+class TextLCD : public Stream {
+public:
+
+    /** LCD panel format */
+    enum LCDType {
+        LCD16x2     /**< 16x2 LCD panel (default) */
+        , LCD16x2B  /**< 16x2 LCD panel alternate addressing */
+        , LCD20x2   /**< 20x2 LCD panel */
+        , LCD20x4   /**< 20x4 LCD panel */
+    };
+
+    /** Create a TextLCD interface
+     *
+     * @param rs    Instruction/data control line
+     * @param e     Enable line (clock)
+     * @param d4-d7 Data lines for using as a 4-bit interface
+     * @param type  Sets the panel size/addressing mode (default = LCD16x2)
+     */
+    TextLCD(PinName rs, PinName e, PinName d4, PinName d5, PinName d6, PinName d7, LCDType type = LCD16x2);
+
+#if DOXYGEN_ONLY
+    /** Write a character to the LCD
+     *
+     * @param c The character to write to the display
+     */
+    int putc(int c);
+
+    /** Write a formated string to the LCD
+     *
+     * @param format A printf-style format string, followed by the
+     *               variables to use in formating the string.
+     */
+    int printf(const char* format, ...);
+#endif
+
+    /** Locate to a screen column and row
+     *
+     * @param column  The horizontal position from the left, indexed from 0
+     * @param row     The vertical position from the top, indexed from 0
+     */
+    void locate(int column, int row);
+
+    /** Clear the screen and locate to 0,0 */
+    void cls();
+
+    int rows();
+    int columns();
+
+protected:
+
+    // Stream implementation functions
+    virtual int _putc(int value);
+    virtual int _getc();
+
+    int address(int column, int row);
+    void character(int column, int row, int c);
+    void writeByte(int value);
+    void writeCommand(int command);
+    void writeData(int data);
+
+    DigitalOut _rs, _e;
+    BusOut _d;
+    LCDType _type;
+
+    int _column;
+    int _row;
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/adcdma.c	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,152 @@
+/*************************************************************
+
+ History
+ 2011/07/26 - Add "shape_mode" option. 
+
+
+*************************************************************/
+#include "MODDMA.h"
+
+#define SAMPLE_BUFFER_LENGTH 256
+
+extern int shape_mode;
+
+// for ADC DMA read
+static MODDMA dma;
+static MODDMA_Config *conf = new MODDMA_Config;
+static uint32_t adcInputBuffer[SAMPLE_BUFFER_LENGTH];   
+
+/******************
+To read ADC DMA
+*******************/
+// Configuration callback on TC
+void TC0_callback(void) {
+    
+  MODDMA_Config *config = dma.getConfig();
+
+  // Disbale burst mode and switch off the IRQ flag.
+  LPC_ADC->ADCR &= ~(1UL << 16);
+  LPC_ADC->ADINTEN = 0;    
+    
+  // Finish the DMA cycle by shutting down the channel.
+  dma.haltAndWaitChannelComplete( (MODDMA::CHANNELS)config->channelNum());
+  dma.Disable( (MODDMA::CHANNELS)config->channelNum() );
+
+  // Clear DMA IRQ flags.
+  if (dma.irqType() == MODDMA::TcIrq) dma.clearTcIrq();    
+  if (dma.irqType() == MODDMA::ErrIrq) dma.clearErrIrq();
+
+  int m=0,max=0,n=0;
+  int downtrend=0;
+  int errata=0;
+
+  for (int i = 0; i < SAMPLE_BUFFER_LENGTH; i++) {
+      int channel = (adcInputBuffer[i] >> 24) & 0x7;
+      int iVal = (adcInputBuffer[i] >> 4) & 0xFFF;
+//      double fVal = 3.3 * (double)((double)iVal) / ((double)0x1000); // scale to 0v to 3.3v
+//      pc.printf("Array index %02d : ADC input channel %d = 0x%03x %01.3f volts\n", i, channel, iVal, fVal);
+
+    if( channel == 0 ){
+
+        n = iVal;
+
+//PEAKMAX
+        if(!downtrend){
+            max= n>max ? n:max;
+            if(n<max){
+                downtrend=1;
+            }
+        }else{
+            if (n>max+100)
+                errata=1;
+        }
+
+//Accumulation
+        m+=n;
+
+        if (shape_mode) {       //  2011/07/26
+            double fVal = 3.3 * (double)((double)n) / ((double)0x1000);
+            printf("%01.3f\n",fVal);
+        }
+     }    
+
+      if(n==0 && max !=0) break;
+  }
+
+    if(!errata){
+        if (shape_mode) {       //  2011/07/26
+            double fm = 3.3 * (double)((double)m) / ((double)0x1000);
+            double fmax = 3.3 * (double)((double)max) / ((double)0x1000);
+            printf("%01.3f,%01.3f\n",fm,fmax);
+        }
+        printf("%d,%d\n",m,max);
+
+        if (shape_mode) {       //  2011/07/26
+            printf("-----\n");
+        }
+    }
+}
+
+// Configuration callback on Error
+void ERR0_callback(void) {
+    // Switch off burst conversions.
+    LPC_ADC->ADCR |= ~(1UL << 16);
+    LPC_ADC->ADINTEN = 0;
+    error("Oh no! My Mbed EXPLODED! :( Only kidding, go find the problem");
+}
+
+void read_dma_data()
+{
+    memset(adcInputBuffer, 0, sizeof(adcInputBuffer));
+    
+    // Prepare configuration.
+    dma.Setup( conf );
+    
+    // Enable configuration.
+    dma.Enable( conf );
+    
+    // Enable ADC irq flag (to DMA).
+    // Note, don't set the individual flags,
+    // just set the global flag.
+    LPC_ADC->ADINTEN = 0x100;
+
+    // Enable burst mode on inputs 0 and 1.
+    LPC_ADC->ADCR |= (1UL << 16); 
+    return;
+}
+
+void setup_adcdma()
+{
+  // We use the ADC irq to trigger DMA and the manual says
+  // that in this case the NVIC for ADC must be disabled.
+  NVIC_DisableIRQ(ADC_IRQn);
+    
+  // Power up the ADC and set PCLK
+  LPC_SC->PCONP    |=  (1UL << 12);
+  LPC_SC->PCLKSEL0 &= ~(3UL << 24); // PCLK = CCLK/4 96M/4 = 24MHz
+   
+  // Enable the ADC, 12MHz
+  LPC_ADC->ADCR  = (1UL << 21) | (1UL << 8) | (1UL << 0);
+  
+  // Set the pin functions to ADC
+  LPC_PINCON->PINSEL1 &= ~(3UL << 14);  /* P0.23, Mbed p15. */
+  LPC_PINCON->PINSEL1 |=  (1UL << 14);
+
+// Prepare an ADC configuration.
+//  MODDMA_Config *conf = new MODDMA_Config;
+
+  conf
+   ->channelNum    ( MODDMA::Channel_0 )
+   ->srcMemAddr    ( 0 )
+   ->dstMemAddr    ( (uint32_t)adcInputBuffer )
+   ->transferSize  ( SAMPLE_BUFFER_LENGTH )
+   ->transferType  ( MODDMA::p2m )
+   ->transferWidth ( MODDMA::word )
+   ->srcConn       ( MODDMA::ADC )
+   ->dstConn       ( 0 )
+   ->dmaLLI        ( 0 )
+   ->attach_tc     ( &TC0_callback )
+   ->attach_err    ( &ERR0_callback )
+  ; // end conf.
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/appconf.cpp	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,166 @@
+/*************************************************************
+
+ History
+ 2011/08/23 - Add nsvlong0,cpmlong0.
+ 2011/08/03 - variable stream number.
+
+
+*************************************************************/
+/**
+ * =============================================================================
+ * Application configuration for 'Expansion Board One' example no.2
+ * http://mbed.org/users/shintamainjp/notebook/starboard_expbrd-one_ex2_en/
+ * =============================================================================
+ * Copyright (c) 2010 Shinichiro Nakamura (CuBeatSystems)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ * =============================================================================
+ */
+
+#include "appconf.h"
+#include "ConfigFile.h"
+
+#define KEY_PACHUBE_APIKEY   "PACHUBE_APIKEY"
+#define KEY_PACHUBE_FEEDID   "PACHUBE_FEEDID"
+#define KEY_STREAM_NSV0      "nsv0"      //  2011/08/03
+#define KEY_STREAM_CPM0      "cpm0"      //  2011/08/03
+#ifdef DUALGM
+#define KEY_STREAM_NSV1      "nsv1"      //  2011/08/03
+#define KEY_STREAM_CPM1      "cpm1"      //  2011/08/03
+#endif
+#define KEY_STREAM_NSVLONG0   "nsvlong0"   //  2011/08/23
+#define KEY_STREAM_CPMLONG0   "cpmlong0"   //  2011/08/23
+
+//#define KEY_PACHUBE_INTERVAL "PACHUBE_INTERVAL"
+
+/**
+ * Initialize configuration.
+ *
+ * @param p A pointer to a application config.
+ */
+void appconf_init(appconf_t *p) {
+    memset(p->apikey, 0, sizeof(p->apikey));
+    memset(p->feedid, 0, sizeof(p->feedid));
+    p->stream_nsv0 = -1; //default value 2011/08/03
+    p->stream_cpm0 = -1; //default value 2011/08/03
+#ifdef DUALGM
+    p->stream_nsv1 = 2; //default value 2011/08/03
+    p->stream_cpm1 = 3; //default value 2011/08/03
+#endif
+    p->stream_nsvlong0 = 0; //default value 2011/08/23
+    p->stream_cpmlong0 = 1; //default value 2011/08/23
+
+//    p->interval = 0;
+}
+
+/**
+ * Read configuration.
+ *
+ * @param filename Filename.
+ * @param p A pointer to a application config.
+ * @return Return zero if it succeed.
+ */
+int appconf_read(char *filename, appconf_t *p) {
+    ConfigFile cf;
+    if (!cf.read(filename)) {
+        return -1;
+    }
+    if (!cf.getValue(KEY_PACHUBE_APIKEY, p->apikey, sizeof(p->apikey))) {
+        return -2;
+    }    
+    if (!cf.getValue(KEY_PACHUBE_FEEDID, p->feedid, sizeof(p->feedid))) {
+        return -3;
+    }
+/*
+    char buf[64];
+    if (!cf.getValue(KEY_PACHUBE_INTERVAL, buf, sizeof(buf))) {
+        return -4;
+    } else {
+        if (sscanf(buf, "%d", &(p->interval)) != 1) {
+            return -5;
+        }
+    }
+*/
+// 2011/08/03 begin
+    char buf[64];
+    if(cf.getValue(KEY_STREAM_NSV0, buf, sizeof(buf))) {
+      if(sscanf(buf, "%d", &(p->stream_nsv0)) !=1) {
+        return -5;
+      }
+   }
+
+    if(cf.getValue(KEY_STREAM_CPM0, buf, sizeof(buf))) {
+      if(sscanf(buf, "%d", &(p->stream_cpm0)) !=1) {
+        return -6;
+      }
+   }
+#ifdef DUALGM
+    if(cf.getValue(KEY_STREAM_NSV1, buf, sizeof(buf))) {
+      if(sscanf(buf, "%d", &(p->stream_nsv1)) !=1) {
+        return -7;
+      }
+   }
+
+    if(cf.getValue(KEY_STREAM_CPM1, buf, sizeof(buf))) {
+      if(sscanf(buf, "%d", &(p->stream_cpm1)) !=1) {
+        return -8;
+      }
+   }
+#endif
+// 2011/08/03 end
+    if(cf.getValue(KEY_STREAM_NSVLONG0, buf, sizeof(buf))) {     //  2011/08/23
+      if(sscanf(buf, "%d", &(p->stream_nsvlong0)) !=1) {         //  2011/08/23
+        return -9;                                              //  2011/08/23
+      }                                                         //  2011/08/23
+   }                                                            //  2011/08/23
+    if(cf.getValue(KEY_STREAM_CPMLONG0, buf, sizeof(buf))) {     //  2011/08/23
+      if(sscanf(buf, "%d", &(p->stream_cpmlong0)) !=1) {         //  2011/08/23
+        return -10;                                              //  2011/08/23
+      }                                                         //  2011/08/23
+   }                                                            //  2011/08/23
+    return 0;
+}
+
+/**
+ * Write configuration.
+ *
+ * @param filename Filename.
+ * @param p A pointer to a application config.
+ * @return Return zero if it succeed.
+ */
+int appconf_write(char *filename, appconf_t *p) {
+    ConfigFile cf;
+    if (!cf.setValue(KEY_PACHUBE_APIKEY, p->apikey)) {
+        return -1;
+    }
+    if (!cf.setValue(KEY_PACHUBE_FEEDID, p->feedid)) {
+        return -2;
+    }
+/*
+    char buf[64];
+    snprintf(buf, sizeof(buf) - 1, "%d", p->interval);
+    if (!cf.setValue(KEY_PACHUBE_INTERVAL, buf)) {
+        return -3;
+    }
+*/
+    if (!cf.write(filename)) {
+        return -4;
+    }
+    return 0;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/appconf.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,74 @@
+/*************************************************************
+
+ History
+ 2011/08/23 - Add nsvlong0,cpmlong0.
+ 2011/08/03 - variable stream number.
+
+
+*************************************************************/
+
+/**
+ * =============================================================================
+ * Application configuration for 'Expansion Board One' example no.2
+ * http://mbed.org/users/shintamainjp/notebook/starboard_expbrd-one_ex2_en/
+ * =============================================================================
+ * Copyright (c) 2010 Shinichiro Nakamura (CuBeatSystems)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ * =============================================================================
+ */
+
+typedef struct {
+    char apikey[256];
+    char feedid[128];
+    int  stream_nsv0;   //  2011/08/03
+    int  stream_cpm0;   //  2011/08/03
+#ifdef DUALGM
+    int  stream_nsv1;   //  2011/08/03
+    int  stream_cpm1;   //  2011/08/03
+#endif
+    int  stream_nsvlong0;   //  2011/08/23
+    int  stream_cpmlong0;   //  2011/08/23
+//    int interval;
+} appconf_t;
+
+/**
+ * Initialize configuration.
+ *
+ * @param p A pointer to a application config.
+ */
+void appconf_init(appconf_t *p);
+
+/**
+ * Read configuration.
+ *
+ * @param filename Filename.
+ * @param p A pointer to a application config.
+ * @return Return zero if it succeed.
+ */
+int appconf_read(char *filename, appconf_t *p);
+
+/**
+ * Write configuration.
+ *
+ * @param filename Filename.
+ * @param p A pointer to a application config.
+ * @return Return zero if it succeed.
+ */
+int appconf_write(char *filename, appconf_t *p);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/buzzer.c	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,17 @@
+/*************************************************************
+
+ buzzer.c
+
+*************************************************************/
+#include "mbed.h"
+
+extern Timeout click;
+extern DigitalOut *buzzer;
+extern DigitalOut *outLED;
+
+void buzzer_off(){
+    *buzzer=0; 
+    *outLED=0; 
+    click.detach();
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/config_env.c	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,235 @@
+/*************************************************************
+
+ config_env.c  
+
+*************************************************************/
+#include "mbed.h"
+#include "TextLCD.h"
+#define CHUNK   1
+#define AVERAGE_MIN 10*60/CHUNK
+#define TMP_TEXT_BUF_SIZE (256)
+
+static char envini[] = "/local/env.ini";
+#define default_fwserver  "http://diytec.web.fc2.com/mark2r2/firmware"
+//char default_fwserver[] = "http://diytec.web.fc2.com/mark2r2/firmware";
+
+extern int mode,gps_mode;
+extern int shape_mode;
+extern int AnalogInput_pin_number;
+extern int GMInterrupt_pin_number;
+extern int LED_pin_number;
+extern int Buzzer_pin_number;
+extern int GPStx_pin_number;
+extern int GPSrx_pin_number;
+extern float carib;
+extern int updateinterval;
+extern int updatetype;  /* 0: no 1: twitter 2: pachube */
+extern int sound;    /* 0: off  1: on */
+extern float volt; /* voltage executed to GM tube */
+extern float offset_usv;
+extern TextLCD lcd;
+extern int firmware_update_interval;
+extern time_t tz_offset;
+extern Serial pc;
+extern int init_stabilize_time;
+extern int cpu_speed;
+
+extern float carib_cpm0;
+extern float carib_usv0;
+extern float carib_cpm1;
+extern float carib_usv1;
+extern unsigned int cpm_array_max;
+extern unsigned int long_cpm_array_max;
+
+void trim(char *retbuff, char *inbuff) {
+    int i,j,len;
+    
+    len=strlen(inbuff);
+    for(i=0,j=0;i<len; i++){
+        if(inbuff[i]>0x20) {
+            retbuff[j]=inbuff[i];
+            j++;
+        }
+    }
+    retbuff[j]='\0';
+
+
+}
+
+
+int GetStatus(char *path, char *tag, char *text){
+    char TmpText[TMP_TEXT_BUF_SIZE];
+    char TmpTag[TMP_TEXT_BUF_SIZE];
+    FILE *stm = fopen(path, "r");
+    
+    if(stm != NULL){
+        text[0] = '\0';
+        sprintf(TmpTag, "%s:%%s",tag);
+        
+        while(fgets(TmpText, TMP_TEXT_BUF_SIZE, stm) != NULL){
+            if(sscanf(TmpText, TmpTag, text)==EOF){
+                printf("error reading %s",tag);
+            }
+        }
+        fclose(stm);
+    }    
+    else {
+        printf("file open error: %s\r\n",path);
+        lcd.cls();
+        lcd.printf("open err: %s",path);
+        abort();
+    }    
+
+    return(0);
+}
+
+/*-----------
+//  
+    // See http://mbed.org/users/no2chem/notebook/mbed-clock-control--benchmarks/
+
+// NOTE:if the clock speed is down, the power consumption becomes low but the timer becomes slow.
+
+void cpu_setting() {                                //  2011/08/19
+    char msgs[80];
+
+    if(GetStatus(envfile,"cpu_speed",msgs)==0){      
+        int m = atoi(msgs);
+        if(m >= 6 && m <= 12){
+            cpu_speed=atof(msgs);
+        }
+     }
+}
+--------------*/
+
+#define IntVal       1   //int (positive only)
+#define IntVal_t1    2   //int (-1 is permitted)
+#define TimeVal      3   //time_t
+#define UintVal      4   //unsigned int
+#define FloatVal     5   //float
+#define FloatVal_t1  6   //float (negative permitted)
+#define FloatVal_t2  7   //float (negative & 0 permitted)
+
+static char gmfile[20];
+
+// For env.ini
+struct envGet {
+    char*   str;
+    int     envtype;
+    void*   datval;
+    char*   file_id;
+} EnvGetTable[] = {
+    {"mode", IntVal_t1, &mode, envini},
+    {"shape", IntVal, &shape_mode, envini},
+    {"gps", IntVal, &gps_mode, envini},
+    {"updateinterval",IntVal,&updateinterval, envini},
+    {"updatetype", IntVal, &updatetype, envini},
+    {"sound", IntVal, &sound, envini},
+    {"firmware_update_interval",IntVal,&firmware_update_interval, envini},
+    {"timezone",TimeVal, &tz_offset, envini},
+    {"init_stabilize_time", IntVal, &init_stabilize_time, envini},
+    {"GMInterrupt", IntVal, &GMInterrupt_pin_number, envini},
+    {"LED", IntVal, &LED_pin_number, envini},
+    {"Buzzer", IntVal, &Buzzer_pin_number, envini},
+    {"GPStx", IntVal, &GPStx_pin_number, envini},
+    {"GPSrx", IntVal, &GPSrx_pin_number, envini},
+    {"cpm_array_max", UintVal, &cpm_array_max, envini},
+    {"long_cpm_array_max", UintVal, &long_cpm_array_max, envini},
+    {"cariburation",FloatVal, &carib, gmfile},
+    {"voltage",FloatVal, &volt, gmfile},
+    {"offset_usv", FloatVal_t1, &offset_usv, gmfile},
+    {"cpm0", FloatVal, &carib_cpm0, gmfile},
+    {"usv0", FloatVal, &carib_usv0, gmfile},
+    {"cpm1", FloatVal, &carib_cpm1, gmfile},
+    {"usv1", FloatVal, &carib_usv1, gmfile},  
+    {"uSv0", FloatVal_t2, &carib_usv0, gmfile},
+    {"uSv1", FloatVal_t2, &carib_usv1, gmfile}
+};
+
+void environment_setting(char *fws){
+    char msgs[80];
+    char gmtype[50];
+
+    // GM tube characteristic feature reading //    
+    if(GetStatus(envini,"gmtype",gmtype)==0){
+        strcpy(gmfile,"/local/");
+        strcat(gmfile,gmtype);
+        printf("%s will be used for GM tube cariburation\n",gmfile);
+    
+        for(int i=0; i<sizeof(EnvGetTable)/sizeof(envGet) ; i++ ) {
+            if(GetStatus(EnvGetTable[i].file_id,EnvGetTable[i].str,msgs)==0){
+                switch(EnvGetTable[i].envtype) {
+                    case IntVal:
+                        if(atoi(msgs)>0){
+                            *((int*)EnvGetTable[i].datval)=atoi(msgs);
+                        }
+                        printf("%s=%d\r\n", EnvGetTable[i].str, *((int*)EnvGetTable[i].datval));
+                    break;
+                    case IntVal_t1:
+                        if(atoi(msgs)>0 || atoi(msgs)==-1){
+                            *((int*)EnvGetTable[i].datval)=atoi(msgs);
+                        }
+                        printf("%s=%d\r\n", EnvGetTable[i].str, *((int*)EnvGetTable[i].datval));
+                    break;
+                    case TimeVal:
+                        if(msgs[0] != '\0'){
+                            *((time_t*)EnvGetTable[i].datval)=atoi(msgs);
+                        }
+                        printf("%s=%d\r\n", EnvGetTable[i].str, *((time_t*)EnvGetTable[i].datval));
+                    break;
+                    case UintVal:
+                        if(atoi(msgs)>0){
+                            *((unsigned int*)EnvGetTable[i].datval)=atoi(msgs);
+                        }
+                        printf("%s=%d\r\n", EnvGetTable[i].str, *((unsigned int*)EnvGetTable[i].datval));
+                    break;
+                    case FloatVal:
+                        if(atof(msgs)>= 0){
+                            *((float*)EnvGetTable[i].datval)=atof(msgs);
+                        }
+                        printf("%s=%f\r\n", EnvGetTable[i].str, *((float*)EnvGetTable[i].datval));
+                    break;
+                     case FloatVal_t1:
+                        *((float*)EnvGetTable[i].datval)=atof(msgs);
+                        printf("%s=%f\r\n", EnvGetTable[i].str, *((float*)EnvGetTable[i].datval));
+                    break;              
+                     case FloatVal_t2:
+                        if(atof(msgs)> 0){
+                            *((float*)EnvGetTable[i].datval)=atof(msgs);
+                            printf("%s=%f\r\n", EnvGetTable[i].str, *((float*)EnvGetTable[i].datval));
+                        }                                                                                   
+                    break;              
+                    
+                }
+            }
+        }
+        
+        if(GetStatus(envini,"fwserver",msgs)==0){
+            if(strlen(msgs) <= 3){
+                strcpy(fws, default_fwserver);
+            } else {
+                trim(fws,msgs);
+            }
+        }
+        printf("fwserver=%s\r\n", fws);
+    
+        updateinterval*=(60/CHUNK);
+        tz_offset *= 3600;
+    
+        // override by 2 point cariburation
+        if (carib_cpm0 > 0 && carib_usv0 > 0 && 
+            carib_cpm1 > 0 && carib_usv1 > 0 &&
+            (carib_cpm0 < carib_cpm1 && carib_usv0 < carib_usv1) ||
+            (carib_cpm0 > carib_cpm1 && carib_usv0 > carib_usv1)) {
+            carib = (carib_cpm1 - carib_cpm0) / (carib_usv1 - carib_usv0);
+            offset_usv = carib_usv0 - (carib_cpm0 / carib);
+            printf("2 point cariburation=%f\r\n", carib);
+            printf("2 point offset_usv=%f\r\n", offset_usv);
+        }
+    
+        if( (updatetype == 0) && (cpm_array_max <10)) {
+        } else {
+            cpm_array_max = 10;
+        }
+        cpm_array_max *= 60/CHUNK;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/display.c	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,150 @@
+/*************************************************************
+
+ display.c
+
+*************************************************************/
+#include "mbed.h"
+#include "TextLCD.h"
+#include "GPS.h"
+#include "NTPClient.h"
+
+extern void calculate_sv();
+extern float cpm;
+extern float uSv;
+extern int LCD_writing;
+extern GPS* gps;
+extern TextLCD lcd;
+extern NTPResult ntpRet;
+extern time_t tz_offset;
+
+void debug_print()
+{
+
+    calculate_sv();
+#ifdef DEBUG
+    printf("cpm=%3.2f, %3.2fuSv/h\r\n",cpm,uSv);
+    for(int i=0;i<first_touch_index;i++){
+        printf("[%d]=%f\r\n",i,cpm_array[i]);
+    }
+    printf("first_touch_index=%d\r\n",first_touch_index);
+    printf("cpm_index=%d\r\n",cpm_index);
+#endif
+}
+
+/**************************************
+* calendar hyoji
+***************************************/
+void calendarHyoji(char *msg){
+    time_t ctTime;
+    struct tm *jst_time;
+    char tmp[100] = "\0";
+    
+    ctTime = time(NULL);
+    ctTime += tz_offset;
+    jst_time = localtime(&ctTime);
+    
+    sprintf(tmp,"%4d/%02d/%02d %02d:%02d",
+                jst_time->tm_year+1900,
+                (jst_time->tm_mon + 1),
+                jst_time->tm_mday, 
+                jst_time->tm_hour, 
+                jst_time->tm_min);
+    strcat(msg, tmp);    
+}
+/**************************************
+* fullcalendar hyoji
+***************************************/
+void fullcalendarHyoji(char *msg){
+    time_t ctTime;
+    struct tm *jst_time;
+    char tmp[100];
+    tmp[0] = '\0';
+    
+    ctTime = time(NULL);
+    ctTime += tz_offset;
+    jst_time = localtime(&ctTime);
+    
+    sprintf(tmp,"%4d/%02d/%02d,%02d:%02d:%02d,",jst_time->tm_year+1900,(jst_time->tm_mon + 1),jst_time->tm_mday, jst_time->tm_hour, jst_time->tm_min, jst_time->tm_sec);
+    strcat(msg, tmp);    
+}
+
+void LCD_out_sub(){
+    calculate_sv(); 
+    lcd.printf("\n%3dcpm/",((int)cpm < 1000 ? (int)cpm : 999));
+    if (uSv < 10.0) {
+        lcd.printf("%.3fuSv",uSv);
+    } else if (uSv < 100.0) {
+        lcd.printf("%.2fuSv",uSv);
+    } else {
+        lcd.printf("%.2fuSv",99.99);
+    }
+}
+
+
+/**************************************
+* LCD output kiokuchi wo LCD ni hyoji
+***************************************/
+void LCD_output(){
+    if(LCD_writing){
+        return;
+    }    
+    LCD_writing=1;
+    LCD_out_sub();
+    LCD_writing=0;
+}
+
+
+void LCD_time_and_output(){
+    char msg[256];
+    msg[0]='\0';
+
+    if(LCD_writing){
+        return;
+    }    
+    LCD_writing=1;
+    lcd.cls();
+    lcd.locate(0,0);
+
+    if ( ntpRet == NTP_OK) {
+      calendarHyoji(msg);
+    }
+    lcd.printf("%s",msg);
+    lcd.locate(0,0);
+    LCD_out_sub();
+    LCD_writing=0;
+}
+
+void LCD_cpm_output() {
+   if(LCD_writing){
+     return;
+   }    
+   LCD_writing=1;
+   lcd.cls();
+   lcd.locate(0,0);
+   calculate_sv(); 
+   lcd.printf("GM check mode\n%.3fcpm",cpm);
+   LCD_writing=0;
+}
+
+void printable_msg(char* msg){
+    char tmp[256];
+    tmp[0]= '\0';
+   
+    if(gps->longitude!=0 && gps->latitude!=0)
+        sprintf(msg,"%f,%f:",gps->longitude,gps->latitude);
+    
+    calculate_sv(); 
+ 
+    fullcalendarHyoji(tmp);
+    strcat(msg,tmp);
+    
+    strcat(msg," ");
+    sprintf(tmp,"%d",(int)cpm);
+    strcat(msg,tmp);
+    strcat(msg,"cpm,");
+    sprintf(tmp,"%.3f",uSv);
+    strcat(msg,tmp);
+    strcat(msg,"uSv\n");
+
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/firmware_upgrade.c	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,76 @@
+/****************************************
+* Firmware Updater *
+
+*****************************************/
+
+#include "mbed.h"
+#include "FirmwareUpdater.h"
+#include "TextLCD.h"
+
+extern TextLCD  lcd;
+extern FirmwareUpdater *fwup;
+
+void check_newfirm() {
+    int fwupret;
+    string getname;
+    
+    lcd.cls();
+    getname = fwup->getName();
+    lcd.printf("Cheking update.");
+    fwupret = fwup->exist();
+    
+    lcd.cls();lcd.locate(0,0);
+    switch (fwupret) {
+    case 0:
+        lcd.printf("Found new firmware.\nUpdateing.");
+        int execret = fwup->execute();
+
+        lcd.cls();lcd.locate(0,0);
+        switch (execret) {
+        case 0:
+            lcd.printf("Update succeed.\n");
+            lcd.printf("Resetting.\n");
+            wait(5);
+            fwup->reset();
+            break;
+        case -1:
+            lcd.printf("Can't get %s.txt", getname.c_str());
+            break;
+        case -2:
+            lcd.printf("Can't get %s.bin", getname.c_str());
+            break;
+        case -8:
+            lcd.printf("Can't get %s.md5", getname.c_str());
+            break;
+        case -3:
+            lcd.printf("Can't read local/%s.txt", getname.c_str());
+            break;
+        case -4:
+            lcd.printf("Can't read new %s.txt", getname.c_str());
+            break;
+        case -5:
+            lcd.printf("local is new,server is old", getname.c_str());
+            break;
+        case -9:
+            lcd.printf("Can't read new %s.md5", getname.c_str());
+            break;
+        case -10:
+            lcd.printf("Can't read new %s.bin", getname.c_str());
+            break;
+        case -11:
+            lcd.printf("MD5 checksum error", getname.c_str());
+            break;
+        }
+        break;
+    case -1:
+        lcd.printf("%s%s error.\n", getname.c_str(),".txt");
+        break;
+    case -2:
+        lcd.printf("F/W server error.\n");
+        break;
+    case 1:
+        lcd.printf("no update found.\n");
+        break;
+    }
+    wait(2);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/geiger.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,136 @@
+/*************************************************************
+
+ geiger.h
+ 
+*************************************************************/
+
+#define VERSION "1.0"
+#include "mbed.h"
+#include "TextLCD.h"
+#include "EthernetNetIf.h"
+#include "NTPClient.h"
+#include "HTTPClient.h"
+#include "ClockControl/ClockControl.h"
+#include "PachubeV2CSV.h"
+#include "appconf.h"
+#include "FirmwareUpdater.h"
+#define CONFIG_FILENAME "/local/PACHUBE.CFG"
+#include "GPS.h"
+
+
+#define TMP_TEXT_BUF_SIZE (256)
+#define CHUNK   1
+#define AVERAGE_MIN 10*60/CHUNK
+
+char BINNAME[] = "geiger";
+
+extern void buzzer_off(DigitalOut*);
+extern PinName pin_assign(int);
+extern void convertDoubleToChar(double , char *, size_t );
+extern void pachube_output(PachubeV2CSV*, HTTPClient *);
+extern int web_post(PachubeV2CSV *, int , int , double );
+extern void pachube_setup(appconf_t *);
+extern int GetStatus(char *, char *, char *);
+extern unsigned char GetFileLine(FILE *, char *);
+extern void environment_setting(char *);
+extern void buzzer_off();
+extern void check_newfirm();
+extern void TwitMsg(char *);
+extern void twitter_output(void);
+extern void twitter_setup();
+extern void calendarHyoji(char *);
+extern void fullcalendarHyoji(char *);
+extern void printable_msg(char* );
+extern void LCD_time_and_output();
+extern void LCD_cpm_output();
+extern void read_dma_data();
+extern void setup_adcdma();
+
+// for pin assignment and mode setting
+
+int mode=0,gps_mode=0;
+int shape_mode=0;
+int AnalogInput_pin_number=15;
+int GMInterrupt_pin_number=17;
+int GMbetaInterrupt_pin_number=16;
+int LED_pin_number=23;
+int Buzzer_pin_number=22;
+int GPStx_pin_number=13;
+int GPSrx_pin_number=14;
+
+extern "C" void mbed_reset();
+appconf_t appconf;
+int noInternet=1;
+NTPResult ntpRet=NTP_TIMEOUT;
+
+// display device
+Serial pc(USBTX, USBRX);
+TextLCD  lcd( p24, p26, p27, p28, p29, p30 ); // rs, e, d0-d3
+
+// local<-> global conversion
+AnalogIn *Sense15;
+GPS *gps;
+DigitalOut *buzzer;
+DigitalOut *outLED;
+FirmwareUpdater *fwup;
+
+//for average calculate arrays
+unsigned int cpm_array_max = 10;
+unsigned char cpm_array[AVERAGE_MIN];
+//current index for array
+int cpm_index=0;
+int first_touch_index=0;
+
+//for calc
+float cpm=0;
+float uSv=0;
+float peak_uSv=0;
+int cnt=0;
+float offset_usv=0;
+float carib_cpm0=-1;
+float carib_usv0=-1;
+float carib_cpm1=-1;
+float carib_usv1=-1;
+
+//for long term average
+unsigned int long_cpm_array_max = 60;
+unsigned int *long_cpm_array;
+int long_cpm_index=0;
+int long_first_touch_index=0;
+unsigned char count_second=0;
+float long_cpm=0;
+float long_uSv=0;
+
+
+//for setting (config_env.c)
+float carib=660;
+int console_output_flag=0;
+int updateinterval=10;
+int updateintervalcount=0;
+int updateflag=0; /* 0: Standalone 1: Twitter 2:Pachube */
+int updatetype=0;  /* 0: no 1: twitter 2: pachube */
+int sound=0;    /* 0: off  1: on */
+float voltagedivider=500; /* voltage_divider of the voltage by the board */
+float volt=400; /* voltage executed to GM tube */
+int firmware_update_interval=24;
+time_t tz_offset=9;
+char fwserver[256];
+int init_stabilize_time=30;
+int cpu_speed=12;    // 12=96MHz
+
+// Ethernet
+EthernetNetIf eth;
+Ethernet eth0;
+NTPClient ntp;
+
+
+// File access
+LocalFileSystem local("local");
+
+// Output display selection
+int LCD_writing=0;
+
+//buzzer
+Timeout click;
+
+HTTPClient commonClient;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,352 @@
+/*************************************************************
+
+ main.c
+
+*************************************************************/
+#include "geiger.h"
+
+void calculate_sv(){
+    cpm = 0;
+    for(int i=0; i<=first_touch_index; i++){
+        cpm += cpm_array[i];
+    }
+    cpm /= ((first_touch_index+1)*((float)CHUNK/60));
+    
+    uSv = cpm/carib + offset_usv;
+    if (uSv <0) uSv = 0;
+  
+    //peak usv set
+    if(peak_uSv<uSv){
+        peak_uSv=uSv;
+    }
+
+    // for long term average
+    long_cpm=0;
+    unsigned long cpm_sum=0;
+    for (int i=0; i<= long_first_touch_index; i++) {
+        cpm_sum += long_cpm_array[i];
+    }
+    cpm_sum *= 60;
+    long_cpm = (float)cpm_sum / ((long_first_touch_index)*60+count_second);
+    long_uSv = long_cpm/carib + offset_usv;
+    
+#ifdef DEBUG
+    pc.printf("cpm=%3d,usv=%.3f,longcpm=%ld,long_usv=%.3f\r\n",(int)cpm,uSv,(long)long_cpm,long_uSv);
+#endif
+
+}
+
+void next_geiger_countup(){
+ 
+    cnt = 0;
+    if(++cpm_index>=cpm_array_max){
+        cpm_index=0;
+    }  
+    //first touch index count up
+    if(cpm_index>first_touch_index){
+        first_touch_index=cpm_index;
+    }
+    cpm_array[cpm_index]=cnt;
+
+    // for long term average
+    if (++count_second >= 60) {
+        if (++long_cpm_index >= long_cpm_array_max+1) {
+            long_cpm_index = 0;
+        }
+        long_cpm_array[long_cpm_index] = 0;
+        count_second = 0;
+
+        if(long_cpm_index > long_first_touch_index){
+            long_first_touch_index = long_cpm_index;
+        }
+    }
+
+}
+
+
+// Timer -- called every 1 min.
+Ticker timer;
+
+void attime(){
+
+    next_geiger_countup();
+    if(++updateintervalcount > updateinterval){
+        updateflag=1;
+        updateintervalcount=0;
+    }
+}
+
+
+void geiger()
+{
+    if(mode==1){
+        read_dma_data();
+    }
+
+    cnt++;
+    cpm_array[cpm_index]=cnt;
+    long_cpm_array[long_cpm_index]++;
+    
+    *outLED=1;
+    if(sound==1) *buzzer=1;
+    click.attach(&buzzer_off,0.03);
+}
+
+void whereami() {
+     if(gps->sample()&& gps->longitude!=0 && gps->latitude!=0) {
+         printf("GPS:%f/%f,", gps->longitude, gps->latitude);
+     }
+}
+
+
+void console_output(){
+    char msg[256];
+    msg[0]='\0';
+    if(++console_output_flag>2){
+      printable_msg(msg);
+      printf("%s",msg);
+      console_output_flag=0;
+    }
+}
+
+//NTP setup
+void ntpget() {
+
+    Host server(IpAddr(), 123, "jp.pool.ntp.org");
+    lcd.cls();
+    lcd.locate(0,0);
+    lcd.printf("Get NTP.");
+    ntpRet = ntp.setTime(server);
+
+}
+
+void pulldown() {
+    DigitalIn dp05(p5);     dp05.mode(PullDown);
+    DigitalIn dp06(p6);     dp06.mode(PullDown);
+    DigitalIn dp07(p7);     dp07.mode(PullDown);
+    DigitalIn dp08(p8);     dp08.mode(PullDown);
+    DigitalIn dp09(p9);     dp09.mode(PullDown);
+    DigitalIn dp10(p10);    dp10.mode(PullDown);
+    DigitalIn dp11(p11);    dp11.mode(PullDown);
+    DigitalIn dp12(p12);    dp12.mode(PullDown);
+    DigitalIn dp13(p13);    dp13.mode(PullDown);
+    DigitalIn dp14(p14);    dp14.mode(PullDown);
+    DigitalIn dp15(p15);    dp15.mode(PullDown);
+    DigitalIn dp16(p16);    dp16.mode(PullDown);
+    DigitalIn dp17(p17);    dp17.mode(PullDown);
+    //DigitalIn dp18(p18);    dp18.mode(PullDown);
+    DigitalIn dp19(p19);    dp19.mode(PullDown);
+    DigitalIn dp20(p20);    dp20.mode(PullDown);
+    DigitalIn dp21(p21);    dp21.mode(PullDown);
+    //DigitalIn dp22(p22);    dp22.mode(PullDown);
+    //DigitalIn dp23(p23);    dp23.mode(PullDown);
+    //DigitalIn dp24(p24);    dp24.mode(PullDown);
+    DigitalIn dp25(p25);    dp25.mode(PullDown);
+    //DigitalIn dp26(p26);    dp26.mode(PullDown);
+    //DigitalIn dp27(p27);    dp27.mode(PullDown);
+    //DigitalIn dp28(p28);    dp28.mode(PullDown);
+    //DigitalIn dp29(p29);    dp29.mode(PullDown);
+    //DigitalIn dp30(p30);    dp30.mode(PullDown);
+}
+
+/****************  main  ***************************/
+
+int main() {
+    pulldown();
+
+    AnalogOut tri(p18);
+    tri = 0.0;
+
+    //cpu_setting();
+
+    // See http://mbed.org/users/no2chem/notebook/mbed-clock-control--benchmarks/
+    setSystemFrequency(0x3, 0x1, cpu_speed, 1); // Set clock freq 96MHz (full speed) 
+    SystemCoreClockUpdate();
+    pc.baud(460800);
+
+    EthernetErr ethErr;
+
+    environment_setting(fwserver);
+
+    // malloc for long average  
+    long_cpm_array = (unsigned int *)malloc((long_cpm_array_max+1) * sizeof(unsigned int) );
+    if (long_cpm_array == NULL) {
+        lcd.cls();
+        lcd.printf("Can't malloc for long_cpm_array");
+        pc.printf("Can't malloc for long_cpm_array");
+        abort();
+    }
+    
+    if (mode != -1) {
+        switch(updatetype){
+        case 0:
+            break;
+        case 1:
+            twitter_setup();
+            break;
+        case 2:
+            pachube_setup(&appconf);
+            break;
+        default:
+            lcd.cls();lcd.locate(0,0);
+            lcd.printf("No update to the internet\n");
+            break;
+        }
+        wait(0.5);
+    }
+    
+  // ******  Initializing objects ********
+    PachubeV2CSV web(appconf.apikey);
+    
+    if (mode==1) {
+        AnalogIn Sense15_(pin_assign(AnalogInput_pin_number));
+        Sense15=&Sense15_;
+    }
+
+    InterruptIn Geiger_signal(pin_assign(GMInterrupt_pin_number)); // Geiger signal
+
+    DigitalOut buzzer_(pin_assign(Buzzer_pin_number));
+    buzzer=&buzzer_;
+
+    DigitalOut outLED_(pin_assign(LED_pin_number));
+    outLED=&outLED_;
+
+    GPS gps_(pin_assign(GPStx_pin_number), pin_assign(GPSrx_pin_number));
+    gps=&gps_;
+   
+    if (mode != -1) {
+        printf("Version: %s\n",VERSION);
+        lcd.cls();
+        lcd.printf("Ver %s\n",VERSION);
+        wait(2);
+        
+        char msg[256] = "";
+        fullcalendarHyoji(msg);
+        printf("Self Clock: %s\n",msg);
+        
+        // Ethernet setup
+        fwup = new FirmwareUpdater(fwserver, BINNAME, &commonClient,true);
+    
+        if (eth0.link()) {
+            lcd.locate(0,0);lcd.cls();lcd.printf("Setting up the Internet(DHCP)\n");
+            ethErr = eth.setup();
+            lcd.cls(); lcd.locate(0,0);
+            if(ethErr){
+                lcd.printf("Please plug into the Internet.");
+                printf("Error %d in setup.\n", ethErr);
+            }else{
+                noInternet=0;
+                IpAddr ipadr = eth.getIp();
+                lcd.printf("IP=%d.%d.%d.%d\n",
+                    ipadr[0],ipadr[1],ipadr[2],ipadr[3]);
+                wait(2);
+                if(firmware_update_interval > 0) {
+                    check_newfirm();
+                }
+                ntpget();
+    
+                memset((char *)msg, '\0', 256);
+                fullcalendarHyoji(msg);
+                printf("NTP Clock:  %s\n",msg);
+            }
+        }
+    } // end if (mode != -1)
+
+    if (mode == 1) {
+        setup_adcdma(); 
+    }
+
+    // Geiger setup
+    float stepvolt;
+    const int step=40;
+    for (stepvolt=0; stepvolt<volt; ) {
+        lcd.cls();
+        lcd.printf("volt=%.0f\n", stepvolt);
+        tri = stepvolt/voltagedivider/3.3;
+        wait(0.5);
+        stepvolt+=step;
+    }
+    lcd.cls();
+    lcd.printf("volt=%.0f\n", volt);
+    tri = volt/voltagedivider/3.3;
+    wait(0.5);
+    
+    for(int i=10; i>0; i--) {
+        lcd.cls();
+        lcd.printf("Wait %2dsec for stabilize voltage",i);
+        wait(1);
+    }
+
+    Geiger_signal.rise(&geiger);
+    Geiger_signal.mode(PullDown);
+
+    // timer interrupt
+    timer.attach(&attime, CHUNK);
+
+    int firmware_update_term = firmware_update_interval * 60 / (updateinterval/60);
+    int firmware_update_counter=0;
+    
+    if (mode != -1) {
+        for(int i=init_stabilize_time; i>0; i--) {
+            lcd.cls();
+            lcd.printf("Wait %2dsec for stabilize cpm",i);
+            wait(1);
+        }
+    }
+
+    //************* Main Loop ******************//
+    while(1){
+
+        if (mode == -1) {
+            LCD_cpm_output();
+        } else if (mode != 3) {
+            LCD_time_and_output();
+        }
+//      console_output();
+
+        wait(1.0);
+        if(mode==2){
+            whereami();
+        }
+        if(mode != -1 && updateflag){
+            updateflag=0;
+            if (noInternet==1 && eth0.link()==1){
+                ethErr = eth.setup();
+                if(ethErr) {
+                } else {
+                    noInternet=0;
+                    ntpget();
+                }
+            }
+
+            if (!noInternet) {
+                switch(updatetype){
+                case 0:
+                    break;
+                case 1:          
+                    twitter_output();
+                    break;
+                case 2:
+                    printf("pachube\r\n");
+                    pachube_output(&web, &commonClient);
+                    printf("data uploaded to pachube\n");
+                    break;
+                default:
+                    break;
+                }
+        
+                if(firmware_update_interval > 0 &&
+                   firmware_update_counter++ >= firmware_update_term){
+                    if(fwup->exist()==0) {
+                        mbed_reset();
+                    } else {
+                        firmware_update_counter = 0;
+                    }
+                    ntpget();
+                }          
+            }// !noInternet
+        }//if update flag
+    }//while
+}//main
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed.bld	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/mbed/builds/e2ac27c8e93e
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/md5.c	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,356 @@
+/* MD5
+ converted to C++ class by Frank Thilo (thilo@unix-ag.org)
+ for bzflag (http://www.bzflag.org)
+
+   based on:
+
+   md5.h and md5.c
+   reference implemantion of RFC 1321
+
+   Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
+rights reserved.
+
+License to copy and use this software is granted provided that it
+is identified as the "RSA Data Security, Inc. MD5 Message-Digest
+Algorithm" in all material mentioning or referencing this software
+or this function.
+
+License is also granted to make and use derivative works provided
+that such works are identified as "derived from the RSA Data
+Security, Inc. MD5 Message-Digest Algorithm" in all material
+mentioning or referencing the derived work.
+
+RSA Data Security, Inc. makes no representations concerning either
+the merchantability of this software or the suitability of this
+software for any particular purpose. It is provided "as is"
+without express or implied warranty of any kind.
+
+These notices must be retained in any copies of any part of this
+documentation and/or software.
+
+*/
+
+/* interface header */
+#include "md5.h"
+
+/* system implementation headers */
+#include <stdio.h>
+#include <string.h>
+
+
+// Constants for MD5Transform routine.
+#define S11 7
+#define S12 12
+#define S13 17
+#define S14 22
+#define S21 5
+#define S22 9
+#define S23 14
+#define S24 20
+#define S31 4
+#define S32 11
+#define S33 16
+#define S34 23
+#define S41 6
+#define S42 10
+#define S43 15
+#define S44 21
+
+///////////////////////////////////////////////
+
+// F, G, H and I are basic MD5 functions.
+inline MD5::uint4 MD5::F(uint4 x, uint4 y, uint4 z) {
+  return x&y | ~x&z;
+}
+
+inline MD5::uint4 MD5::G(uint4 x, uint4 y, uint4 z) {
+  return x&z | y&~z;
+}
+
+inline MD5::uint4 MD5::H(uint4 x, uint4 y, uint4 z) {
+  return x^y^z;
+}
+
+inline MD5::uint4 MD5::I(uint4 x, uint4 y, uint4 z) {
+  return y ^ (x | ~z);
+}
+
+// rotate_left rotates x left n bits.
+inline MD5::uint4 MD5::rotate_left(uint4 x, int n) {
+  return (x << n) | (x >> (32-n));
+}
+
+// FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
+// Rotation is separate from addition to prevent recomputation.
+inline void MD5::FF(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) {
+  a = rotate_left(a+ F(b,c,d) + x + ac, s) + b;
+}
+
+inline void MD5::GG(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) {
+  a = rotate_left(a + G(b,c,d) + x + ac, s) + b;
+}
+
+inline void MD5::HH(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) {
+  a = rotate_left(a + H(b,c,d) + x + ac, s) + b;
+}
+
+inline void MD5::II(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) {
+  a = rotate_left(a + I(b,c,d) + x + ac, s) + b;
+}
+
+//////////////////////////////////////////////
+
+// default ctor, just initailize
+MD5::MD5()
+{
+  init();
+}
+
+//////////////////////////////////////////////
+
+// nifty shortcut ctor, compute MD5 for string and finalize it right away
+MD5::MD5(const std::string &text)
+{
+  init();
+  update(text.c_str(), text.length());
+  finalize();
+}
+
+//////////////////////////////
+
+void MD5::init()
+{
+  finalized=false;
+
+  count[0] = 0;
+  count[1] = 0;
+
+  // load magic initialization constants.
+  state[0] = 0x67452301;
+  state[1] = 0xefcdab89;
+  state[2] = 0x98badcfe;
+  state[3] = 0x10325476;
+}
+
+//////////////////////////////
+
+// decodes input (unsigned char) into output (uint4). Assumes len is a multiple of 4.
+void MD5::decode(uint4 output[], const uint1 input[], size_type len)
+{
+  for (unsigned int i = 0, j = 0; j < len; i++, j += 4)
+    output[i] = ((uint4)input[j]) | (((uint4)input[j+1]) << 8) |
+      (((uint4)input[j+2]) << 16) | (((uint4)input[j+3]) << 24);
+}
+
+//////////////////////////////
+
+// encodes input (uint4) into output (unsigned char). Assumes len is
+// a multiple of 4.
+void MD5::encode(uint1 output[], const uint4 input[], size_type len)
+{
+  for (size_type i = 0, j = 0; j < len; i++, j += 4) {
+    output[j] = input[i] & 0xff;
+    output[j+1] = (input[i] >> 8) & 0xff;
+    output[j+2] = (input[i] >> 16) & 0xff;
+    output[j+3] = (input[i] >> 24) & 0xff;
+  }
+}
+
+//////////////////////////////
+
+// apply MD5 algo on a block
+void MD5::transform(const uint1 block[blocksize])
+{
+  uint4 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
+  decode (x, block, blocksize);
+
+  /* Round 1 */
+  FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
+  FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
+  FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
+  FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
+  FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
+  FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
+  FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
+  FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
+  FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
+  FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
+  FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
+  FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
+  FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
+  FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
+  FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
+  FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
+
+  /* Round 2 */
+  GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
+  GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
+  GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
+  GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
+  GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
+  GG (d, a, b, c, x[10], S22,  0x2441453); /* 22 */
+  GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
+  GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
+  GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
+  GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
+  GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
+  GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
+  GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
+  GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
+  GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
+  GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
+
+  /* Round 3 */
+  HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
+  HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
+  HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
+  HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
+  HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
+  HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
+  HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
+  HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
+  HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
+  HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
+  HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
+  HH (b, c, d, a, x[ 6], S34,  0x4881d05); /* 44 */
+  HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
+  HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
+  HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
+  HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
+
+  /* Round 4 */
+  II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
+  II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
+  II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
+  II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
+  II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
+  II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
+  II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
+  II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
+  II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
+  II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
+  II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
+  II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
+  II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
+  II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
+  II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
+  II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
+
+  state[0] += a;
+  state[1] += b;
+  state[2] += c;
+  state[3] += d;
+
+  // Zeroize sensitive information.
+  memset(x, 0, sizeof x);
+}
+
+//////////////////////////////
+
+// MD5 block update operation. Continues an MD5 message-digest
+// operation, processing another message block
+void MD5::update(const unsigned char input[], size_type length)
+{
+  // compute number of bytes mod 64
+  size_type index = count[0] / 8 % blocksize;
+
+  // Update number of bits
+  if ((count[0] += (length << 3)) < (length << 3))
+    count[1]++;
+  count[1] += (length >> 29);
+
+  // number of bytes we need to fill in buffer
+  size_type firstpart = 64 - index;
+
+  size_type i;
+
+  // transform as many times as possible.
+  if (length >= firstpart)
+  {
+    // fill buffer first, transform
+    memcpy(&buffer[index], input, firstpart);
+    transform(buffer);
+
+    // transform chunks of blocksize (64 bytes)
+    for (i = firstpart; i + blocksize <= length; i += blocksize)
+      transform(&input[i]);
+
+    index = 0;
+  }
+  else
+    i = 0;
+
+  // buffer remaining input
+  memcpy(&buffer[index], &input[i], length-i);
+}
+
+//////////////////////////////
+
+// for convenience provide a verson with signed char
+void MD5::update(const char input[], size_type length)
+{
+  update((const unsigned char*)input, length);
+}
+
+//////////////////////////////
+
+// MD5 finalization. Ends an MD5 message-digest operation, writing the
+// the message digest and zeroizing the context.
+MD5& MD5::finalize()
+{
+  static unsigned char padding[64] = {
+    0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+  };
+
+  if (!finalized) {
+    // Save number of bits
+    unsigned char bits[8];
+    encode(bits, count, 8);
+
+    // pad out to 56 mod 64.
+    size_type index = count[0] / 8 % 64;
+    size_type padLen = (index < 56) ? (56 - index) : (120 - index);
+    update(padding, padLen);
+
+    // Append length (before padding)
+    update(bits, 8);
+
+    // Store state in digest
+    encode(digest, state, 16);
+
+    // Zeroize sensitive information.
+    memset(buffer, 0, sizeof buffer);
+    memset(count, 0, sizeof count);
+
+    finalized=true;
+  }
+
+  return *this;
+}
+
+//////////////////////////////
+
+// return hex representation of digest as string
+std::string MD5::hexdigest() const
+{
+  if (!finalized)
+    return "";
+
+  char buf[33];
+  for (int i=0; i<16; i++)
+    sprintf(buf+i*2, "%02x", digest[i]);
+  buf[32]=0;
+
+  return std::string(buf);
+}
+
+//////////////////////////////
+
+std::string md5(const std::string str)
+{
+    MD5 md5 = MD5(str);
+
+    return md5.hexdigest();
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/md5.h	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,118 @@
+/* MD5
+ converted to C++ class by Frank Thilo (thilo@unix-ag.org)
+ for bzflag (http://www.bzflag.org)
+
+   based on:
+
+   md5.h and md5.c
+   reference implementation of RFC 1321
+
+   Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
+rights reserved.
+
+License to copy and use this software is granted provided that it
+is identified as the "RSA Data Security, Inc. MD5 Message-Digest
+Algorithm" in all material mentioning or referencing this software
+or this function.
+
+License is also granted to make and use derivative works provided
+that such works are identified as "derived from the RSA Data
+Security, Inc. MD5 Message-Digest Algorithm" in all material
+mentioning or referencing the derived work.
+
+RSA Data Security, Inc. makes no representations concerning either
+the merchantability of this software or the suitability of this
+software for any particular purpose. It is provided "as is"
+without express or implied warranty of any kind.
+
+These notices must be retained in any copies of any part of this
+documentation and/or software.
+
+*/
+
+#ifndef BZF_MD5_H
+#define BZF_MD5_H
+
+#include <string>
+
+
+/** a small class for calculating MD5 hashes of strings or byte arrays
+ it is not meant to be fast or secure
+
+ usage: 1) feed it blocks of uchars with update()
+      2) finalize()
+      3) get hexdigest() string
+      or
+      MD5(std::string).hexdigest()
+
+ assumes that char is 8 bit and int is 32 bit
+*/
+class MD5
+{
+public:
+  typedef unsigned int size_type; // must be 32bit
+
+  MD5();
+  /**
+    take string, hash it and finalize
+    @param text the string to hash
+  */
+  MD5(const std::string& text);
+  /**
+    add text to hash
+    @param buf the text to add to the hash
+    @param text length
+  */
+  void update(const unsigned char *buf, size_type length);
+  /**
+    add text to hash
+    @param buf the text to add to the hash
+    @param text length
+  */
+  void update(const char *buf, size_type length);
+  /**
+    calculate the final hash value
+  */
+  MD5& finalize();
+  /**
+    @return the hash as hex string
+  */
+  std::string hexdigest() const;
+  
+  void init();
+  
+  /**
+    @return the hash as binary data, an array of 16 bytes.
+  */
+  const unsigned char* rawdigest() const { return digest; }
+
+private:
+  typedef unsigned char uint1; //  8bit
+  typedef unsigned int uint4;  // 32bit
+  enum {blocksize = 64}; // VC6 won't eat a const static int here
+
+  void transform(const uint1 block[blocksize]);
+  static void decode(uint4 output[], const uint1 input[], size_type len);
+  static void encode(uint1 output[], const uint4 input[], size_type len);
+
+  bool finalized;
+  uint1 buffer[blocksize]; // bytes that didn't fit in last 64 byte chunk
+  uint4 count[2];   // 64bit counter for number of bits (lo, hi)
+  uint4 state[4];   // digest so far
+  uint1 digest[16]; // the result
+
+  // low level logic operations
+  static inline uint4 F(uint4 x, uint4 y, uint4 z);
+  static inline uint4 G(uint4 x, uint4 y, uint4 z);
+  static inline uint4 H(uint4 x, uint4 y, uint4 z);
+  static inline uint4 I(uint4 x, uint4 y, uint4 z);
+  static inline uint4 rotate_left(uint4 x, int n);
+  static inline void FF(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac);
+  static inline void GG(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac);
+  static inline void HH(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac);
+  static inline void II(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac);
+};
+
+std::string md5(const std::string str);
+
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pachube.c	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,93 @@
+/*************************************************************
+
+ pachube.c
+ 
+*************************************************************/
+#include "PachubeV2CSV.h"
+#include "TextLCD.h"
+#include "appconf.h"
+#define PACHUBE_CODE_OK 200
+#define CONFIG_FILENAME "/local/PACHUBE.CFG"
+
+extern float uSv;
+extern float cpm;
+extern TextLCD lcd;
+extern int mode;
+extern appconf_t appconf;
+extern float long_cpm;
+extern float long_uSv;
+
+void convertDoubleToChar(double val, char *buf, size_t bufsiz) {
+    snprintf(buf, bufsiz, "%f", val);
+}
+
+void pachube_setup(appconf_t *appconf){
+        lcd.cls();
+        lcd.locate(0, 0);
+        lcd.printf("cfg file Reading...");
+        lcd.locate(0, 1);
+        lcd.printf("Setup: ");
+        appconf_init(appconf);
+        if (appconf_read(CONFIG_FILENAME, appconf) != 0) {
+            lcd.printf("[NG]");
+            error("Failure to read a configuration file.\n");
+        }
+        else{
+            lcd.printf("[OK]");
+            wait(1);
+        }
+        printf("pachube apikey %s\n",appconf->apikey);
+}
+
+int web_post(PachubeV2CSV *web, int feed_id, int stream_no, double value, HTTPClient *pClient) {
+    char value_text[16];
+    convertDoubleToChar(value, value_text, sizeof(value_text));
+    char stream_no_text[8];
+    stream_no_text[0] = "0123456789"[stream_no];
+    stream_no_text[1] = '\0';
+    return web->updateDataStream(feed_id, stream_no_text, std::string(value_text), pClient);
+
+}
+
+void pachube_output(PachubeV2CSV* web, HTTPClient *pClient){
+    int feed_id = atoi(appconf.feedid);
+    
+    if (appconf.stream_nsv0 >= 0) {
+        if (web_post(web, feed_id, appconf.stream_nsv0,(double)uSv*1000, pClient) != PACHUBE_CODE_OK) {
+          lcd.printf("Checking Pachube status:x");
+          printf("upload failed -stream1 \n");
+          wait(3);
+        } else {
+          printf("upload -stream1 \r\n");
+        }
+    }
+
+    if (appconf.stream_cpm0 >= 0) {
+        if (web_post(web, feed_id, appconf.stream_cpm0, (double)cpm, pClient) != PACHUBE_CODE_OK){
+          lcd.printf("Checking Pachube status:x");
+          printf("upload failed -stream2 \n");
+          wait(3);
+        } else {
+          printf("upload -stream2 \r\n");
+        }
+    }
+        
+    if (appconf.stream_nsvlong0 >= 0) {
+        if (web_post(web, feed_id, appconf.stream_nsvlong0, (double)long_uSv*1000, pClient) != PACHUBE_CODE_OK){  //  2011/08/23
+          lcd.printf("Checking Pachube status:x");
+          printf("upload failed -stream3 \n");
+          wait(3);
+        } else {
+          printf("upload -stream3 \r\n");
+        }
+    }
+    if (appconf.stream_cpmlong0 >= 0) {
+        if (web_post(web, feed_id, appconf.stream_cpmlong0, (double)long_cpm, pClient) != PACHUBE_CODE_OK){  //  2011/08/23
+          lcd.printf("Checking Pachube status:x");
+          printf("upload failed -stream4 \n");
+          wait(3);
+        } else {
+          printf("upload -stream4 \r\n");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pin_assign.c	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,66 @@
+/*************************************************************
+
+ pin_assign.c
+ 
+*************************************************************/
+#include "mbed.h"
+
+PinName pin_assign(int a){
+
+    switch(a){
+    case 5:
+        return(p5);
+    case 6:
+        return(p6);
+    case 7:
+        return(p7);
+    case 8:
+        return(p8);
+    case 9:
+        return(p9);
+    case 10:
+        return(p10);        
+    case 11:
+        return(p11);    
+    case 12:
+        return(p12);
+    case 13:
+        return(p13);
+    case 14:
+        return(p14);
+    case 15:
+        return(p15);
+    case 16:
+        return(p16);
+    case 17:
+        return(p17);
+    case 18:
+        return(p18);        
+    case 19:
+        return(p19);
+    case 20:
+        return(p20);
+    case 21:
+        return(p21);
+    case 22:
+        return(p22);
+    case 23:
+        return(p23);
+    case 24:
+        return(p24);
+    case 25:
+        return(p25);
+    case 26:
+        return(p26);
+    case 27:
+        return(p27);
+    case 28:
+        return(p28);        
+    case 29:
+        return(p29);
+    case 30:
+        return(p30);
+    default:
+        return(NC);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/twitter.c	Tue Sep 20 12:46:26 2011 +0000
@@ -0,0 +1,61 @@
+/***********************************
+
+ twitter.c
+
+***********************************/
+#include "mbed.h"
+#include "HTTPClient.h"
+#include "TextLCD.h"
+
+#define DEBUG
+
+//LCD
+extern TextLCD lcd;
+extern HTTPClient commonClient;
+
+extern void printable_msg(char*);
+extern int GetStatus(char *, char *, char *);
+
+char id[128];
+char password[128];
+
+/**************************************
+* Output to Twitter *
+***************************************/
+void twitter_output(void){
+    char msg[256];
+    msg[0]='\0';
+    printable_msg(msg);
+
+    HTTPMap h_msg;
+    h_msg["status"] = msg; //A good example of Key/Value pair use with Web APIs
+
+    commonClient.basicAuth(id, password);   //We use basic authentication, replace with you account's parameters
+#ifdef DEBUG
+//  printf("twitter\r\n");
+  printf("%s,%s\r\n",id,password);
+#endif
+    //No need to retieve data sent back by the server
+    HTTPResult r = commonClient.post("http://api.supertweet.net/1/statuses/update.xml", h_msg, NULL);
+
+#ifdef DEBUG
+    if( r == HTTP_OK ){
+        printf("%s",msg);
+        printf("Tweet sent with success!\n");
+    }else{
+        printf("Problem during tweeting, return code %d\n", r);
+    }
+#endif
+}
+
+void twitter_setup(){
+    GetStatus("/local/TWITTER.CFG","ID",id);
+    GetStatus("/local/TWITTER.CFG","PASS",password);
+    printf("twitter ID=%s, password=%s\r\n",id,password);
+    lcd.cls();
+    lcd.locate(0,0);
+    lcd.printf("Twitter ID=%s",id);
+    wait(2);
+}
+
+