A client for the SmartREST protocol from Cumulocity.
Fork of MbedSmartRest by
MbedClient.cpp
- Committer:
- vwochnik
- Date:
- 2014-04-02
- Revision:
- 12:788dd934f283
- Parent:
- 10:478414cc15a4
- Child:
- 13:e76920d5e1ec
File content as of revision 12:788dd934f283:
#include "MbedClient.h" #include <stdlib.h> #include <stdio.h> #define STATE_INIT 0 #define STATE_IN_REQUEST 1 #define STATE_SENT_ID 2 #define STATE_SENT_DATA 3 #define STATE_REQ_COMPLETE 4 #define STATE_RECVD_RESPONSE 5 #define STATE_RECV_DATA 6 const char * const cXidHeader = "X-Id"; MbedClient::MbedClient(const char* url, const char* username, const char* password) : _url(url), _username(username), _password(password) { _state = STATE_INIT; _headers[0] = cXidHeader; _headers[1] = NULL; } MbedClient::~MbedClient() { if (_generator != NULL) delete _generator; } uint8_t MbedClient::beginRequest() { if (_state != STATE_INIT) return CLIENT_INTERNAL_ERROR; _client.basicAuth(_username, _password); _client.customHeaders(NULL, 0); _state = STATE_IN_REQUEST; return CLIENT_OK; } uint8_t MbedClient::sendIdentifier(const char* identifier) { if (_state != STATE_IN_REQUEST) return CLIENT_INTERNAL_ERROR; _headers[1] = identifier; _client.customHeaders(_headers, 1); _state = STATE_SENT_ID; return CLIENT_OK; } uint8_t MbedClient::sendData(DataGenerator& generator) { puts("Send called."); if ((_state != STATE_IN_REQUEST) && (_state != STATE_SENT_ID)) return CLIENT_INTERNAL_ERROR; puts("Setting gen."); _generator = new HTTPGeneratorWrapper(generator); _state = STATE_SENT_DATA; return CLIENT_OK; } uint8_t MbedClient::endRequest() { if ((_state != STATE_IN_REQUEST) && (_state != STATE_SENT_ID) && (_state != STATE_SENT_DATA)) return CLIENT_INTERNAL_ERROR; _state = STATE_REQ_COMPLETE; return CLIENT_OK; } uint8_t MbedClient::awaitResponse() { HTTPResult result; puts("Action"); if (_state != STATE_REQ_COMPLETE) return CLIENT_INTERNAL_ERROR; puts("Calling"); result = _client.post(_url, *_generator, &_buffer); if (result != 0) return CLIENT_CONNECTION_ERROR; char *p = _buffer._buf; while (p != _buffer._wptr) putchar(*p++); _state = STATE_RECVD_RESPONSE; return CLIENT_OK; } AbstractDataSource& MbedClient::receiveData() { return _buffer; } void MbedClient::stop() { _buffer.writeReset(); _headers[1] = NULL; if (_generator != NULL) delete _generator; _generator = NULL; _state = STATE_INIT; }