Own fork of MbedSmartRestMain

Dependencies:   C027_Support C12832 LM75B MMA7660 MbedSmartRest mbed-rtos mbed

Fork of MbedSmartRestMain by Cumulocity Official

operation/OperationExecutor.cpp

Committer:
vwochnik
Date:
2014-10-30
Revision:
65:a62dbef2f924
Parent:
64:31a640c32399
Child:
66:31c754c36ed7

File content as of revision 65:a62dbef2f924:

#include "OperationExecutor.h"
#include "ComposedRecord.h"
#include "CharValue.h"
#include "IntegerValue.h"
#include <string.h>
#include <stdio.h>

OperationExecutor::OperationExecutor(AbstractSmartRest& client, SmartRestTemplate& tpl, long& deviceId, DeviceIO& io) :
    _client(client),
    _tpl(tpl),
    _deviceId(deviceId),
    _io(io)
{
    _init = false;
}

bool OperationExecutor::init()
{
    if (_init)
        return false;
    
    // Get operation by id
    // USAGE: 112,<OPERATION/ID>
    if (!_tpl.add("10,112,GET,/devicecontrol/operations/%%,,application/vnd.com.nsn.cumulocity.operation+json,%%,UNSIGNED,\r\n"))
        return false;

    // Relay operation response
    // Response: 211,<OPERATION/ID>,<STATUS>
    if (!_tpl.add("11,220,,\"$.c8y_Relay\",\"$.id\",\"$.c8y_Relay.relayState\"\r\n"))
        return false;

    _init = true;
    return true;
}

bool OperationExecutor::executeOperation(OperationStore::Operation& op)
{
    uint8_t ret; bool found, relayState;
    ComposedRecord record;
    ParsedRecord received;
    
    IntegerValue msgId(112);
    IntegerValue operationId(op.identifier);
    if ((!record.add(msgId)) || (!record.add(operationId)))
        return false;
    
    if (_client.send(record) != SMARTREST_SUCCESS) {
        _client.stop();
        return false;
    }
    
    found = false;
    while ((ret = _client.receive(received)) == SMARTREST_SUCCESS) {
        if ((received.values() == 4) &&
            (received.value(0).valueType() == VALUE_INTEGER) &&
            (received.value(0).integerValue() == 220) &&
            (received.value(2).valueType() == VALUE_INTEGER) &&
            (received.value(2).integerValue() == op.identifier) &&
            (received.value(3).valueType() == VALUE_CHARACTER)) {
            relayState = (strcmp("CLOSED", received.value(3).characterValue()) == 0);
            found = true;
            break;
        }
    }
    _client.stop();

    if (!found)
        return false;

    return executeRelayStateUpdate(relayState);
}

bool OperationExecutor::executeRelayStateUpdate(bool relayState)
{
    if (relayState)
        _io.deviceFeedback().closeRelay();
    else
        _io.deviceFeedback().openRelay();
    return true;
}