A client for the SmartREST protocol from Cumulocity.

Dependencies:   SmartRest

Fork of MbedSmartRest by Vincent Wochnik

Revision:
5:ab909221d22d
Parent:
3:ce2f116369bd
Child:
7:26524a6a04a1
--- a/MbedClient.cpp	Mon Jan 27 08:44:55 2014 +0000
+++ b/MbedClient.cpp	Thu Jan 30 11:11:39 2014 +0000
@@ -1,29 +1,77 @@
 #include "MbedClient.h"
+#include <stdlib.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 = 0;
+    _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*)
+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)
 {
+    if ((_state != STATE_IN_REQUEST) && (_state != STATE_SENT_ID))
+        return CLIENT_INTERNAL_ERROR;
+    _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;
 }
 
 uint8_t MbedClient::awaitResponse()
 {
+    HTTPResult result;
+
+    if (_state != STATE_REQ_COMPLETE)
+        return CLIENT_INTERNAL_ERROR;
+    result = _client.post(_url, *_generator, &_buffer);
+    if (result != 0)
+        return CLIENT_CONNECTION_ERROR;
+    _state = STATE_RECVD_RESPONSE;
+    return CLIENT_OK;
 }
 
 AbstractDataSource& MbedClient::receiveData()
@@ -34,4 +82,8 @@
 void MbedClient::stop()
 {
     _buffer.writeReset();
+    _headers[1] = NULL;
+    if (_generator != NULL)
+        delete _generator;
+    _generator = NULL;
 }