Official reference client implementation for Cumulocity SmartREST on u-blox C027.

Dependencies:   C027_Support C12832 LM75B MMA7660 MbedSmartRest mbed-rtos mbed

Fork of MbedSmartRestMain by Vincent Wochnik

config/ConfigSync.cpp

Committer:
xinlei
Date:
2016-08-08
Revision:
139:f8ab852e83e7
Parent:
137:a52821cdb108

File content as of revision 139:f8ab852e83e7:

#include <stdio.h>
#include "Storage.h"
#include "ConfigSync.h"
#include "SmartRestConf.h"
#include "logging.h"

// default connectivity checking interval [minutes].
#define INTERVAL_KEY "interval"
#define DEFAULT_INTERVAL "20"

static bool validateConfiguration(const Dict& d)
{
        const Dict::Item *p = d.get(INTERVAL_KEY);
        if (p) {
                int v = 0, n = 0;
                sscanf(p->value, "%d%n", &v, &n);
                if (v > 0 && n == strlen(p->value))
                        return true;
                else
                        return false;
        } else
                return false;
}

int ConfigSync::read(char *buf, size_t maxLen, char *status, size_t num)
{
        static const char *fmt = "130,%ld,\"%s\",%.*s\r\n";
        int l = 0;
        if (changed) {
                changed = false;
                char s[(MAX_KEY_LEN+MAX_VALUE_LEN+4)*dict.size()+1];
                dict.dump(s);
                const char *p = dict.get("interval")->value;
                l = snprintf(buf, maxLen, fmt, deviceID, s, MAX_VALUE_LEN, p);
                snprintf(status, num, "%s", "Sync Config");
        }
        return l;
}

bool ConfigSync::updateConfiguration(const char *buf)
{
        // compromise for the platform, which requires a conf report despite
        // the conf is updated or NOT. More appropriately would be setting
        // `changed=true` inside the `if` block, when the conf is actually updated.
        changed = true; 
        bool b = cp.parse(buf);
        if (b && validateConfiguration(cp.dict)) {
                dict = cp.dict;
                saveConfiguration();
                return true;
        } else {
                return false;
        }
}

void ConfigSync::resetConfiguration()
{
        dict.clear();
        dict.set(INTERVAL_KEY, DEFAULT_INTERVAL);
        changed = true;
}

void ConfigSync::loadConfiguration()
{
        char buf[(MAX_KEY_LEN+MAX_VALUE_LEN+4)*MAX_ITEM_SIZE+1];
        resetConfiguration();
        int l = loadConfigFile(buf, sizeof(buf));
        if (l > 0)
                updateConfiguration(buf);
        else
                saveConfiguration();
}

void ConfigSync::saveConfiguration() const
{
        char s[(MAX_KEY_LEN+MAX_VALUE_LEN+3)*dict.size()+1];
        size_t l = dict.dump(s);
        if (l) {
                if (!saveConfigFile(s, l))
                        aError("Save config.\n");
        }
}