diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..67f45ed --- /dev/null +++ b/.clang-format @@ -0,0 +1,4 @@ +BasedOnStyle: llvm +ColumnLimit: 79 +IndentWidth: 2 +SortIncludes: false diff --git a/.github/workflows/pythonapp.yml b/.github/workflows/pythonapp.yml index 9cae2ef..cea5195 100644 --- a/.github/workflows/pythonapp.yml +++ b/.github/workflows/pythonapp.yml @@ -13,6 +13,12 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 + - name: Lint source + uses: DoozyX/clang-format-lint-action@v0.5 + with: + source: '.' + extensions: 'h,cpp,ino' + clangFormatVersion: 9 - name: Set up Python 3.7 uses: actions/setup-python@v1 with: diff --git a/ESPWebThingAdapter.h b/ESPWebThingAdapter.h index 5214b7f..bb4cbdb 100644 --- a/ESPWebThingAdapter.h +++ b/ESPWebThingAdapter.h @@ -28,8 +28,8 @@ class WebThingAdapter { public: - WebThingAdapter(String _name, IPAddress _ip, uint16_t _port = 80): server(_port), name(_name), ip(_ip.toString()), port(_port) { - } + WebThingAdapter(String _name, IPAddress _ip, uint16_t _port = 80) + : server(_port), name(_name), ip(_ip.toString()), port(_port) {} void begin() { name.toLowerCase(); @@ -41,57 +41,74 @@ class WebThingAdapter { MDNS.addServiceTxt("webthing", "tcp", "path", "/"); DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*"); - DefaultHeaders::Instance().addHeader("Access-Control-Allow-Methods", "PUT, GET, OPTIONS"); + DefaultHeaders::Instance().addHeader("Access-Control-Allow-Methods", + "PUT, GET, OPTIONS"); - this->server.onNotFound(std::bind(&WebThingAdapter::handleUnknown, this, std::placeholders::_1)); + this->server.onNotFound(std::bind(&WebThingAdapter::handleUnknown, this, + std::placeholders::_1)); - this->server.on("/", HTTP_GET, std::bind(&WebThingAdapter::handleThings, this, std::placeholders::_1)); + this->server.on("/", HTTP_GET, + std::bind(&WebThingAdapter::handleThings, this, + std::placeholders::_1)); - ThingDevice* device = this->firstDevice; + ThingDevice *device = this->firstDevice; while (device != nullptr) { String deviceBase = "/things/" + device->id; - ThingProperty* property = device->firstProperty; + ThingProperty *property = device->firstProperty; while (property != nullptr) { String propertyBase = deviceBase + "/properties/" + property->id; - this->server.on(propertyBase.c_str(), HTTP_GET, std::bind(&WebThingAdapter::handleThingGetItem, this, std::placeholders::_1, property)); + this->server.on(propertyBase.c_str(), HTTP_GET, + std::bind(&WebThingAdapter::handleThingGetItem, this, + std::placeholders::_1, property)); this->server.on(propertyBase.c_str(), HTTP_PUT, - std::bind(&WebThingAdapter::handleThingPropertyPut, this, std::placeholders::_1, property), - NULL, - std::bind(&WebThingAdapter::handleBody, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5) - ); - - property = (ThingProperty*) property->next; + std::bind(&WebThingAdapter::handleThingPropertyPut, + this, std::placeholders::_1, property), + NULL, + std::bind(&WebThingAdapter::handleBody, this, + std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3, std::placeholders::_4, + std::placeholders::_5)); + + property = (ThingProperty *)property->next; } - ThingEvent* event = device->firstEvent; + ThingEvent *event = device->firstEvent; while (event != nullptr) { String eventBase = deviceBase + "/events/" + event->id; - this->server.on(eventBase.c_str(), HTTP_GET, std::bind(&WebThingAdapter::handleThingGetItem, this, std::placeholders::_1, event)); - event = (ThingEvent*) event->next; + this->server.on(eventBase.c_str(), HTTP_GET, + std::bind(&WebThingAdapter::handleThingGetItem, this, + std::placeholders::_1, event)); + event = (ThingEvent *)event->next; } - this->server.on((deviceBase + "/properties").c_str(), HTTP_GET, std::bind(&WebThingAdapter::handleThingGetAll, this, std::placeholders::_1, device->firstProperty)); - this->server.on((deviceBase + "/events").c_str(), HTTP_GET, std::bind(&WebThingAdapter::handleThingGetAll, this, std::placeholders::_1, device->firstEvent)); - this->server.on(deviceBase.c_str(), HTTP_GET, std::bind(&WebThingAdapter::handleThing, this, std::placeholders::_1, device)); + this->server.on((deviceBase + "/properties").c_str(), HTTP_GET, + std::bind(&WebThingAdapter::handleThingGetAll, this, + std::placeholders::_1, device->firstProperty)); + this->server.on((deviceBase + "/events").c_str(), HTTP_GET, + std::bind(&WebThingAdapter::handleThingGetAll, this, + std::placeholders::_1, device->firstEvent)); + this->server.on(deviceBase.c_str(), HTTP_GET, + std::bind(&WebThingAdapter::handleThing, this, + std::placeholders::_1, device)); device = device->next; - } this->server.begin(); } #ifndef WITHOUT_WS - void sendChangedPropsOrEvents(ThingDevice* device, const char* type, ThingItem* rootItem) { + void sendChangedPropsOrEvents(ThingDevice *device, const char *type, + ThingItem *rootItem) { // Prepare one buffer per device DynamicJsonDocument message(1024); message["messageType"] = type; JsonObject prop = message.createNestedObject("data"); bool dataToSend = false; - ThingItem* item = rootItem; + ThingItem *item = rootItem; while (item != nullptr) { - ThingPropertyValue* value = item->changedValueOrNull(); + ThingPropertyValue *value = item->changedValueOrNull(); if (value) { dataToSend = true; this->serializeThingItem(item, prop); @@ -102,7 +119,7 @@ class WebThingAdapter { String jsonStr; serializeJson(message, jsonStr); // Inform all connected ws clients of a Thing about changed properties - ((AsyncWebSocket*)device->ws)->textAll(jsonStr); + ((AsyncWebSocket *)device->ws)->textAll(jsonStr); } } #endif @@ -112,19 +129,20 @@ class WebThingAdapter { MDNS.update(); #endif #ifndef WITHOUT_WS - // * Send changed properties as defined in "4.5 propertyStatus message" - // * Send events as defined in "4.7 event message" - // Do this by looping over all devices and properties/events - ThingDevice* device = this->firstDevice; - while (device != nullptr) { - sendChangedPropsOrEvents(device, "propertyStatus", device->firstProperty); - sendChangedPropsOrEvents(device, "event", device->firstEvent); - device = device->next; - } + // * Send changed properties as defined in "4.5 propertyStatus message" + // * Send events as defined in "4.7 event message" + // Do this by looping over all devices and properties/events + ThingDevice *device = this->firstDevice; + while (device != nullptr) { + sendChangedPropsOrEvents(device, "propertyStatus", + device->firstProperty); + sendChangedPropsOrEvents(device, "event", device->firstEvent); + device = device->next; + } #endif } - void addDevice(ThingDevice* device) { + void addDevice(ThingDevice *device) { if (this->lastDevice == nullptr) { this->firstDevice = device; this->lastDevice = device; @@ -132,14 +150,18 @@ class WebThingAdapter { this->lastDevice->next = device; this->lastDevice = device; } - // Initiate the websocket instance - #ifndef WITHOUT_WS - AsyncWebSocket* ws = new AsyncWebSocket("/things/" + device->id); +// Initiate the websocket instance +#ifndef WITHOUT_WS + AsyncWebSocket *ws = new AsyncWebSocket("/things/" + device->id); device->ws = ws; - // AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len, ThingDevice* device - ws->onEvent(std::bind(&WebThingAdapter::handleWS, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5, std::placeholders::_6, device)); + // AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType + // type, void * arg, uint8_t *data, size_t len, ThingDevice* device + ws->onEvent(std::bind( + &WebThingAdapter::handleWS, this, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, + std::placeholders::_5, std::placeholders::_6, device)); this->server.addHandler(ws); - #endif +#endif } private: @@ -148,13 +170,13 @@ class WebThingAdapter { String name; String ip; uint16_t port; - ThingDevice* firstDevice = nullptr; - ThingDevice* lastDevice = nullptr; + ThingDevice *firstDevice = nullptr; + ThingDevice *lastDevice = nullptr; char body_data[ESP_MAX_PUT_BODY_SIZE]; bool b_has_body_data = false; bool verifyHost(AsyncWebServerRequest *request) { - AsyncWebHeader* header = request->getHeader("Host"); + AsyncWebHeader *header = request->getHeader("Host"); if (header == nullptr) { request->send(403); return false; @@ -171,29 +193,36 @@ class WebThingAdapter { return false; } - #ifndef WITHOUT_WS - void sendErrorMsg(DynamicJsonDocument &prop, AsyncWebSocketClient& client, int status, const char* msg) { - prop["error"] = msg; - prop["status"] = status; - String jsonStr; - serializeJson(prop, jsonStr); - client.text(jsonStr.c_str(), jsonStr.length()); +#ifndef WITHOUT_WS + void sendErrorMsg(DynamicJsonDocument &prop, AsyncWebSocketClient &client, + int status, const char *msg) { + prop["error"] = msg; + prop["status"] = status; + String jsonStr; + serializeJson(prop, jsonStr); + client.text(jsonStr.c_str(), jsonStr.length()); } - void handleWS(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *rawData, size_t len, ThingDevice* device) { + void handleWS(AsyncWebSocket *server, AsyncWebSocketClient *client, + AwsEventType type, void *arg, uint8_t *rawData, size_t len, + ThingDevice *device) { // Ignore all except data packets - if(type != WS_EVT_DATA) return; + if (type != WS_EVT_DATA) + return; // Only consider non fragmented data - AwsFrameInfo * info = (AwsFrameInfo*)arg; - if(!info->final || info->index != 0 || info->len != len) return; + AwsFrameInfo *info = (AwsFrameInfo *)arg; + if (!info->final || info->index != 0 || info->len != len) + return; // Web Thing only specifies text, not binary websocket transfers - if(info->opcode != WS_TEXT) return; + if (info->opcode != WS_TEXT) + return; - // In theory we could just have one websocket for all Things and react on the server->url() to route data. - // Controllers will however establish a separate websocket connection for each Thing anyway as of in the - // spec. For now each Thing stores its own Websocket connection object therefore. + // In theory we could just have one websocket for all Things and react on + // the server->url() to route data. Controllers will however establish a + // separate websocket connection for each Thing anyway as of in the spec. + // For now each Thing stores its own Websocket connection object therefore. // Parse request DynamicJsonDocument newProp(1024); @@ -214,7 +243,7 @@ class WebThingAdapter { if (messageType == "setProperty") { for (auto kv : data) { - ThingProperty* property = device->findProperty(kv.key().c_str()); + ThingProperty *property = device->findProperty(kv.key().c_str()); if (property) { setThingProperty(data, property); } @@ -226,7 +255,7 @@ class WebThingAdapter { // of subscribed properties per websocket connection otherwise } } - #endif +#endif void handleUnknown(AsyncWebServerRequest *request) { if (!verifyHost(request)) { @@ -239,11 +268,12 @@ class WebThingAdapter { if (!verifyHost(request)) { return; } - AsyncResponseStream *response = request->beginResponseStream("application/json"); + AsyncResponseStream *response = + request->beginResponseStream("application/json"); DynamicJsonDocument buf(1024); JsonArray things = buf.to(); - ThingDevice* device = this->firstDevice; + ThingDevice *device = this->firstDevice; while (device != nullptr) { JsonObject descr = things.createNestedObject(); this->serializeDevice(descr, device); @@ -253,11 +283,12 @@ class WebThingAdapter { serializeJson(things, *response); request->send(response); - } - void serializePropertyOrEvent(JsonObject descr, ThingDevice* device, const char* type, bool isProp, ThingItem* item) { - String basePath = "/things/" + device->id + "/"+ type + "/"; + void serializePropertyOrEvent(JsonObject descr, ThingDevice *device, + const char *type, bool isProp, + ThingItem *item) { + String basePath = "/things/" + device->id + "/" + type + "/"; JsonObject props = descr.createNestedObject(type); while (item != nullptr) { JsonObject prop = props.createNestedObject(item->id); @@ -307,14 +338,15 @@ class WebThingAdapter { } if (isProp) { - ThingProperty* property = (ThingProperty*)item; + ThingProperty *property = (ThingProperty *)item; const char **enumVal = property->propertyEnum; - bool hasEnum = (property->propertyEnum != nullptr) && ((*property->propertyEnum) != nullptr); + bool hasEnum = (property->propertyEnum != nullptr) && + ((*property->propertyEnum) != nullptr); if (hasEnum) { enumVal = property->propertyEnum; JsonArray propEnum = prop.createNestedArray("enum"); - while (property->propertyEnum != nullptr && (*enumVal) != nullptr){ + while (property->propertyEnum != nullptr && (*enumVal) != nullptr) { propEnum.add(*enumVal); enumVal++; } @@ -325,7 +357,9 @@ class WebThingAdapter { prop["@type"] = item->atType; } - // 2.9 Property object: A links array (An array of Link objects linking to one or more representations of a Property resource, each with an implied default rel=property.) + // 2.9 Property object: A links array (An array of Link objects linking + // to one or more representations of a Property resource, each with an + // implied default rel=property.) JsonArray inline_links = prop.createNestedArray("links"); JsonObject inline_links_prop = inline_links.createNestedObject(); inline_links_prop["href"] = basePath + item->id; @@ -334,7 +368,7 @@ class WebThingAdapter { } } - void serializeDevice(JsonObject descr, ThingDevice* device) { + void serializeDevice(JsonObject descr, ThingDevice *device) { descr["id"] = device->id; descr["title"] = device->title; descr["@context"] = "https://iot.mozilla.org/schemas"; @@ -344,13 +378,14 @@ class WebThingAdapter { } // TODO: descr["base"] = ??? - JsonObject securityDefinitions = descr.createNestedObject("securityDefinitions"); + JsonObject securityDefinitions = + descr.createNestedObject("securityDefinitions"); JsonObject nosecSc = securityDefinitions.createNestedObject("nosec_sc"); nosecSc["scheme"] = "nosec"; descr["security"] = "nosec_sc"; JsonArray typeJson = descr.createNestedArray("@type"); - const char** type = device->type; + const char **type = device->type; while ((*type) != nullptr) { typeJson.add(*type); type++; @@ -373,28 +408,30 @@ class WebThingAdapter { { JsonObject links_prop = links.createNestedObject(); links_prop["rel"] = "alternate"; - char buffer [33]; + char buffer[33]; itoa(port, buffer, 10); - links_prop["href"] = "ws://" + ip + ":" + buffer + "/things/" + device->id; + links_prop["href"] = + "ws://" + ip + ":" + buffer + "/things/" + device->id; } #endif - ThingProperty* property = device->firstProperty; + ThingProperty *property = device->firstProperty; if (property) { serializePropertyOrEvent(descr, device, "properties", true, property); } - ThingEvent* event = device->firstEvent; + ThingEvent *event = device->firstEvent; if (event) { serializePropertyOrEvent(descr, device, "events", false, event); } } - void handleThing(AsyncWebServerRequest *request, ThingDevice*& device) { + void handleThing(AsyncWebServerRequest *request, ThingDevice *&device) { if (!verifyHost(request)) { return; } - AsyncResponseStream *response = request->beginResponseStream("application/json"); + AsyncResponseStream *response = + request->beginResponseStream("application/json"); DynamicJsonDocument buf(1024); JsonObject descr = buf.to(); @@ -404,7 +441,7 @@ class WebThingAdapter { request->send(response); } - void serializeThingItem(ThingItem* item, JsonObject prop) { + void serializeThingItem(ThingItem *item, JsonObject prop) { switch (item->type) { case NO_STATE: break; @@ -423,11 +460,12 @@ class WebThingAdapter { } } - void handleThingGetItem(AsyncWebServerRequest *request, ThingItem* item) { + void handleThingGetItem(AsyncWebServerRequest *request, ThingItem *item) { if (!verifyHost(request)) { return; } - AsyncResponseStream *response = request->beginResponseStream("application/json"); + AsyncResponseStream *response = + request->beginResponseStream("application/json"); DynamicJsonDocument doc(256); JsonObject prop = doc.to(); @@ -436,8 +474,9 @@ class WebThingAdapter { request->send(response); } - void handleThingGetAll(AsyncWebServerRequest *request, ThingItem* rootItem) { - AsyncResponseStream *response = request->beginResponseStream("application/json"); + void handleThingGetAll(AsyncWebServerRequest *request, ThingItem *rootItem) { + AsyncResponseStream *response = + request->beginResponseStream("application/json"); DynamicJsonDocument doc(256); JsonObject prop = doc.to(); @@ -450,16 +489,18 @@ class WebThingAdapter { request->send(response); } - void handleBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) { - if (total >= ESP_MAX_PUT_BODY_SIZE || index + len >= ESP_MAX_PUT_BODY_SIZE) { - return; // cannot store this size.. + void handleBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, + size_t index, size_t total) { + if (total >= ESP_MAX_PUT_BODY_SIZE || + index + len >= ESP_MAX_PUT_BODY_SIZE) { + return; // cannot store this size.. } // copy to internal buffer memcpy(&body_data[index], data, len); b_has_body_data = true; } - void setThingProperty(const JsonObject newProp, ThingProperty* property) { + void setThingProperty(const JsonObject newProp, ThingProperty *property) { const JsonVariant newValue = newProp[property->id]; switch (property->type) { @@ -490,7 +531,8 @@ class WebThingAdapter { } } - void handleThingPropertyPut(AsyncWebServerRequest *request, ThingProperty* property) { + void handleThingPropertyPut(AsyncWebServerRequest *request, + ThingProperty *property) { if (!verifyHost(request)) { return; } @@ -511,16 +553,16 @@ class WebThingAdapter { setThingProperty(newProp, property); - AsyncResponseStream *response = request->beginResponseStream("application/json"); + AsyncResponseStream *response = + request->beginResponseStream("application/json"); serializeJson(newProp, *response); request->send(response); b_has_body_data = false; memset(body_data, 0, sizeof(body_data)); } - }; -#endif // ESP +#endif // ESP #endif diff --git a/EthernetWebThingAdapter.h b/EthernetWebThingAdapter.h index 0cd727f..07147a9 100644 --- a/EthernetWebThingAdapter.h +++ b/EthernetWebThingAdapter.h @@ -41,12 +41,7 @@ MDNS mdns(udp); static const bool DEBUG = false; -enum HTTPMethod { - HTTP_ANY, - HTTP_GET, - HTTP_PUT, - HTTP_OPTIONS -}; +enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_PUT, HTTP_OPTIONS }; enum ReadState { STATE_READ_METHOD, @@ -60,9 +55,11 @@ enum ReadState { class WebThingAdapter { public: - WebThingAdapter(String _name, uint32_t _ip, uint16_t _port = 80): name(_name), port(_port), server(_port) + WebThingAdapter(String _name, uint32_t _ip, uint16_t _port = 80) + : name(_name), port(_port), server(_port) #ifdef CONFIG_MDNS - , mdns(udp) + , + mdns(udp) #endif { ip = ""; @@ -80,10 +77,7 @@ class WebThingAdapter { #ifdef CONFIG_MDNS mdns.begin(Ethernet.localIP(), name.c_str()); - mdns.addServiceRecord("_webthing", - port, - MDNSServiceTCP, - "\x06path=/"); + mdns.addServiceRecord("_webthing", port, MDNSServiceTCP, "\x06path=/"); #endif server.begin(); } @@ -130,7 +124,7 @@ class WebThingAdapter { return; } - switch(state) { + switch (state) { case STATE_READ_METHOD: if (c == ' ') { if (methodRaw == "GET") { @@ -209,7 +203,7 @@ class WebThingAdapter { } } - void addDevice(ThingDevice* device) { + void addDevice(ThingDevice *device) { if (this->lastDevice == nullptr) { this->firstDevice = device; this->lastDevice = device; @@ -218,6 +212,7 @@ class WebThingAdapter { this->lastDevice = device; } } + private: String name, ip; uint16_t port; @@ -281,7 +276,7 @@ class WebThingAdapter { return; } - ThingDevice* device = this->firstDevice; + ThingDevice *device = this->firstDevice; while (device != nullptr) { String deviceBase = "/things/" + device->id; @@ -298,7 +293,7 @@ class WebThingAdapter { } else if (uri == deviceBase + "/events") { handleThingGetAll(device->firstEvent); } else { - ThingProperty* property = device->firstProperty; + ThingProperty *property = device->firstProperty; while (property != nullptr) { String propertyBase = deviceBase + "/properties/" + property->id; if (uri == propertyBase) { @@ -311,7 +306,7 @@ class WebThingAdapter { } return; } - property = (ThingProperty*)property->next; + property = (ThingProperty *)property->next; } } } @@ -320,9 +315,7 @@ class WebThingAdapter { handleError(); } - void sendOk() { - client.println("HTTP/1.1 200 OK"); - } + void sendOk() { client.println("HTTP/1.1 200 OK"); } void sendHeaders() { client.println("Access-Control-Allow-Origin: *"); @@ -338,7 +331,7 @@ class WebThingAdapter { DynamicJsonDocument buf(1024); JsonArray things = buf.to(); - ThingDevice* device = this->firstDevice; + ThingDevice *device = this->firstDevice; while (device != nullptr) { JsonObject descr = things.createNestedObject(); this->serializeDevice(descr, device); @@ -351,8 +344,10 @@ class WebThingAdapter { client.stop(); } - void serializePropertyOrEvent(JsonObject descr, ThingDevice* device, const char* type, bool isProp, ThingItem* item) { - String basePath = "/things/" + device->id + "/"+ type + "/"; + void serializePropertyOrEvent(JsonObject descr, ThingDevice *device, + const char *type, bool isProp, + ThingItem *item) { + String basePath = "/things/" + device->id + "/" + type + "/"; JsonObject props = descr.createNestedObject(type); while (item != nullptr) { JsonObject prop = props.createNestedObject(item->id); @@ -402,14 +397,15 @@ class WebThingAdapter { } if (isProp) { - ThingProperty* property = (ThingProperty*)item; + ThingProperty *property = (ThingProperty *)item; const char **enumVal = property->propertyEnum; - bool hasEnum = (property->propertyEnum != nullptr) && ((*property->propertyEnum) != nullptr); + bool hasEnum = (property->propertyEnum != nullptr) && + ((*property->propertyEnum) != nullptr); if (hasEnum) { enumVal = property->propertyEnum; JsonArray propEnum = prop.createNestedArray("enum"); - while (property->propertyEnum != nullptr && (*enumVal) != nullptr){ + while (property->propertyEnum != nullptr && (*enumVal) != nullptr) { propEnum.add(*enumVal); enumVal++; } @@ -420,7 +416,9 @@ class WebThingAdapter { prop["@type"] = item->atType; } - // 2.9 Property object: A links array (An array of Link objects linking to one or more representations of a Property resource, each with an implied default rel=property.) + // 2.9 Property object: A links array (An array of Link objects linking + // to one or more representations of a Property resource, each with an + // implied default rel=property.) JsonArray inline_links = prop.createNestedArray("links"); JsonObject inline_links_prop = inline_links.createNestedObject(); inline_links_prop["href"] = basePath + item->id; @@ -429,7 +427,7 @@ class WebThingAdapter { } } - void serializeDevice(JsonObject descr, ThingDevice* device) { + void serializeDevice(JsonObject descr, ThingDevice *device) { descr["id"] = device->id; descr["title"] = device->title; descr["@context"] = "https://iot.mozilla.org/schemas"; @@ -439,13 +437,14 @@ class WebThingAdapter { } // TODO: descr["base"] = ??? - JsonObject securityDefinitions = descr.createNestedObject("securityDefinitions"); + JsonObject securityDefinitions = + descr.createNestedObject("securityDefinitions"); JsonObject nosecSc = securityDefinitions.createNestedObject("nosec_sc"); nosecSc["scheme"] = "nosec"; descr["security"] = "nosec_sc"; JsonArray typeJson = descr.createNestedArray("@type"); - const char** type = device->type; + const char **type = device->type; while ((*type) != nullptr) { typeJson.add(*type); type++; @@ -464,18 +463,18 @@ class WebThingAdapter { links_prop["href"] = "/things/" + device->id + "/events"; } - ThingProperty* property = device->firstProperty; + ThingProperty *property = device->firstProperty; if (property) { serializePropertyOrEvent(descr, device, "properties", true, property); } - ThingEvent* event = device->firstEvent; + ThingEvent *event = device->firstEvent; if (event) { serializePropertyOrEvent(descr, device, "events", false, event); } } - void handleThing(ThingDevice* device) { + void handleThing(ThingDevice *device) { sendOk(); sendHeaders(); @@ -488,7 +487,7 @@ class WebThingAdapter { client.stop(); } - void serializeThingItem(ThingItem* item, JsonObject prop) { + void serializeThingItem(ThingItem *item, JsonObject prop) { switch (item->type) { case NO_STATE: break; @@ -507,7 +506,7 @@ class WebThingAdapter { } } - void handleThingGetItem(ThingItem* item) { + void handleThingGetItem(ThingItem *item) { sendOk(); sendHeaders(); @@ -519,7 +518,7 @@ class WebThingAdapter { client.stop(); } - void handleThingGetAll(ThingItem* rootItem) { + void handleThingGetAll(ThingItem *rootItem) { sendOk(); sendHeaders(); @@ -535,7 +534,7 @@ class WebThingAdapter { client.stop(); } - void setThingProperty(const JsonObject newProp, ThingProperty* property) { + void setThingProperty(const JsonObject newProp, ThingProperty *property) { const JsonVariant newValue = newProp[property->id]; switch (property->type) { @@ -566,7 +565,7 @@ class WebThingAdapter { } } - void handleThingPropertyPut(ThingProperty* property) { + void handleThingPropertyPut(ThingProperty *property) { sendOk(); sendHeaders(); DynamicJsonDocument newBuffer(256); @@ -601,7 +600,6 @@ class WebThingAdapter { content = ""; retries = 0; } - }; #endif // neither ESP32 nor ESP8266 defined diff --git a/Thing.h b/Thing.h index 6945c95..afc16d2 100644 --- a/Thing.h +++ b/Thing.h @@ -16,19 +16,13 @@ #include #endif -enum ThingPropertyType { - NO_STATE, - BOOLEAN, - NUMBER, - INTEGER, - STRING -}; +enum ThingPropertyType { NO_STATE, BOOLEAN, NUMBER, INTEGER, STRING }; union ThingPropertyValue { bool boolean; double number; signed long long integer; - String* string; + String *string; }; class ThingItem { @@ -37,7 +31,7 @@ class ThingItem { String description; ThingPropertyType type; String atType; - ThingItem* next = nullptr; + ThingItem *next = nullptr; bool readOnly = false; String unit = ""; @@ -46,12 +40,9 @@ class ThingItem { double maximum = -1; double multipleOf = -1; - ThingItem(const char* id_, const char* description_, ThingPropertyType type_, const char* atType_): - id(id_), - description(description_), - type(type_), - atType(atType_) { - } + ThingItem(const char *id_, const char *description_, ThingPropertyType type_, + const char *atType_) + : id(id_), description(description_), type(type_), atType(atType_) {} void setValue(ThingPropertyValue newValue) { this->value = newValue; @@ -59,18 +50,16 @@ class ThingItem { } /** - * Returns the property value if it has been changed via {@link setValue} since - * the last call or returns a nullptr. + * Returns the property value if it has been changed via {@link setValue} + * since the last call or returns a nullptr. */ - ThingPropertyValue* changedValueOrNull() { - ThingPropertyValue* v = this->hasChanged ? &this->value : nullptr; + ThingPropertyValue *changedValueOrNull() { + ThingPropertyValue *v = this->hasChanged ? &this->value : nullptr; this->hasChanged = false; return v; } - ThingPropertyValue getValue() { - return this->value; - } + ThingPropertyValue getValue() { return this->value; } private: ThingPropertyValue value = {false}; @@ -79,11 +68,11 @@ class ThingItem { class ThingProperty : public ThingItem { public: - const char** propertyEnum = nullptr; + const char **propertyEnum = nullptr; - ThingProperty(const char* id_, const char* description_, ThingPropertyType type_, const char* atType_) : - ThingItem(id_, description_, type_, atType_) { - } + ThingProperty(const char *id_, const char *description_, + ThingPropertyType type_, const char *atType_) + : ThingItem(id_, description_, type_, atType_) {} }; using ThingEvent = ThingItem; @@ -93,42 +82,42 @@ class ThingDevice { String id; String title; String description; - const char** type; - #if !defined(WITHOUT_WS) && (defined(ESP8266) || defined(ESP32)) - AsyncWebSocket* ws = nullptr; - #endif - ThingDevice* next = nullptr; - ThingProperty* firstProperty = nullptr; - ThingEvent* firstEvent = nullptr; - - ThingDevice(const char* _id, const char* _title, const char** _type): - id(_id), - title(_title), - type(_type) { - } + const char **type; +#if !defined(WITHOUT_WS) && (defined(ESP8266) || defined(ESP32)) + AsyncWebSocket *ws = nullptr; +#endif + ThingDevice *next = nullptr; + ThingProperty *firstProperty = nullptr; + ThingEvent *firstEvent = nullptr; + + ThingDevice(const char *_id, const char *_title, const char **_type) + : id(_id), title(_title), type(_type) {} ~ThingDevice() { - #if !defined(WITHOUT_WS) && (defined(ESP8266) || defined(ESP32)) - if (ws) delete ws; - #endif +#if !defined(WITHOUT_WS) && (defined(ESP8266) || defined(ESP32)) + if (ws) + delete ws; +#endif } - ThingProperty* findProperty(const char* id) { - ThingProperty* p = this->firstProperty; + ThingProperty *findProperty(const char *id) { + ThingProperty *p = this->firstProperty; while (p) { - if (!strcmp(p->id.c_str(), id)) return p; - p = (ThingProperty*)p->next; + if (!strcmp(p->id.c_str(), id)) + return p; + p = (ThingProperty *)p->next; } return nullptr; } - void addProperty(ThingProperty* property) { - property->next = firstProperty; - firstProperty = property; + void addProperty(ThingProperty *property) { + property->next = firstProperty; + firstProperty = property; } - void addEvent(ThingEvent* event) { - event->next = firstEvent; - firstEvent = event; + + void addEvent(ThingEvent *event) { + event->next = firstEvent; + firstEvent = event; } }; diff --git a/WiFi101WebThingAdapter.h b/WiFi101WebThingAdapter.h index 907a1e9..028ec49 100644 --- a/WiFi101WebThingAdapter.h +++ b/WiFi101WebThingAdapter.h @@ -29,12 +29,7 @@ static const bool DEBUG = false; -enum HTTPMethod { - HTTP_ANY, - HTTP_GET, - HTTP_PUT, - HTTP_OPTIONS -}; +enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_PUT, HTTP_OPTIONS }; enum ReadState { STATE_READ_METHOD, @@ -48,7 +43,8 @@ enum ReadState { class WebThingAdapter { public: - WebThingAdapter(String _name, uint32_t _ip, uint16_t _port = 80): name(_name), port(_port), server(_port), mdns(udp) { + WebThingAdapter(String _name, uint32_t _ip, uint16_t _port = 80) + : name(_name), port(_port), server(_port), mdns(udp) { ip = ""; for (int i = 0; i < 4; i++) { ip += _ip & 0xff; @@ -64,10 +60,7 @@ class WebThingAdapter { mdns.begin(WiFi.localIP(), name.c_str()); - mdns.addServiceRecord("_webthing", - port, - MDNSServiceTCP, - "\x06path=/"); + mdns.addServiceRecord("_webthing", port, MDNSServiceTCP, "\x06path=/"); server.begin(); } @@ -113,7 +106,7 @@ class WebThingAdapter { return; } - switch(state) { + switch (state) { case STATE_READ_METHOD: if (c == ' ') { if (methodRaw == "GET") { @@ -192,7 +185,7 @@ class WebThingAdapter { } } - void addDevice(ThingDevice* device) { + void addDevice(ThingDevice *device) { if (this->lastDevice == nullptr) { this->firstDevice = device; this->lastDevice = device; @@ -201,6 +194,7 @@ class WebThingAdapter { this->lastDevice = device; } } + private: String name, ip; uint16_t port; @@ -262,7 +256,7 @@ class WebThingAdapter { return; } - ThingDevice* device = this->firstDevice; + ThingDevice *device = this->firstDevice; while (device != nullptr) { String deviceBase = "/things/" + device->id; @@ -279,7 +273,7 @@ class WebThingAdapter { } else if (uri == deviceBase + "/events") { handleThingGetAll(device->firstEvent); } else { - ThingProperty* property = device->firstProperty; + ThingProperty *property = device->firstProperty; while (property != nullptr) { String propertyBase = deviceBase + "/properties/" + property->id; if (uri == propertyBase) { @@ -292,7 +286,7 @@ class WebThingAdapter { } return; } - property = (ThingProperty*)property->next; + property = (ThingProperty *)property->next; } } } @@ -301,9 +295,7 @@ class WebThingAdapter { handleError(); } - void sendOk() { - client.println("HTTP/1.1 200 OK"); - } + void sendOk() { client.println("HTTP/1.1 200 OK"); } void sendHeaders() { client.println("Access-Control-Allow-Origin: *"); @@ -319,7 +311,7 @@ class WebThingAdapter { DynamicJsonDocument buf(1024); JsonArray things = buf.to(); - ThingDevice* device = this->firstDevice; + ThingDevice *device = this->firstDevice; while (device != nullptr) { JsonObject descr = things.createNestedObject(); this->serializeDevice(descr, device); @@ -332,8 +324,10 @@ class WebThingAdapter { client.stop(); } - void serializePropertyOrEvent(JsonObject descr, ThingDevice* device, const char* type, bool isProp, ThingItem* item) { - String basePath = "/things/" + device->id + "/"+ type + "/"; + void serializePropertyOrEvent(JsonObject descr, ThingDevice *device, + const char *type, bool isProp, + ThingItem *item) { + String basePath = "/things/" + device->id + "/" + type + "/"; JsonObject props = descr.createNestedObject(type); while (item != nullptr) { JsonObject prop = props.createNestedObject(item->id); @@ -383,14 +377,15 @@ class WebThingAdapter { } if (isProp) { - ThingProperty* property = (ThingProperty*)item; + ThingProperty *property = (ThingProperty *)item; const char **enumVal = property->propertyEnum; - bool hasEnum = (property->propertyEnum != nullptr) && ((*property->propertyEnum) != nullptr); + bool hasEnum = (property->propertyEnum != nullptr) && + ((*property->propertyEnum) != nullptr); if (hasEnum) { enumVal = property->propertyEnum; JsonArray propEnum = prop.createNestedArray("enum"); - while (property->propertyEnum != nullptr && (*enumVal) != nullptr){ + while (property->propertyEnum != nullptr && (*enumVal) != nullptr) { propEnum.add(*enumVal); enumVal++; } @@ -401,7 +396,9 @@ class WebThingAdapter { prop["@type"] = item->atType; } - // 2.9 Property object: A links array (An array of Link objects linking to one or more representations of a Property resource, each with an implied default rel=property.) + // 2.9 Property object: A links array (An array of Link objects linking + // to one or more representations of a Property resource, each with an + // implied default rel=property.) JsonArray inline_links = prop.createNestedArray("links"); JsonObject inline_links_prop = inline_links.createNestedObject(); inline_links_prop["href"] = basePath + item->id; @@ -410,7 +407,7 @@ class WebThingAdapter { } } - void serializeDevice(JsonObject descr, ThingDevice* device) { + void serializeDevice(JsonObject descr, ThingDevice *device) { descr["id"] = device->id; descr["title"] = device->title; descr["@context"] = "https://iot.mozilla.org/schemas"; @@ -420,13 +417,14 @@ class WebThingAdapter { } // TODO: descr["base"] = ??? - JsonObject securityDefinitions = descr.createNestedObject("securityDefinitions"); + JsonObject securityDefinitions = + descr.createNestedObject("securityDefinitions"); JsonObject nosecSc = securityDefinitions.createNestedObject("nosec_sc"); nosecSc["scheme"] = "nosec"; descr["security"] = "nosec_sc"; JsonArray typeJson = descr.createNestedArray("@type"); - const char** type = device->type; + const char **type = device->type; while ((*type) != nullptr) { typeJson.add(*type); type++; @@ -445,18 +443,18 @@ class WebThingAdapter { links_prop["href"] = "/things/" + device->id + "/events"; } - ThingProperty* property = device->firstProperty; + ThingProperty *property = device->firstProperty; if (property) { serializePropertyOrEvent(descr, device, "properties", true, property); } - ThingEvent* event = device->firstEvent; + ThingEvent *event = device->firstEvent; if (event) { serializePropertyOrEvent(descr, device, "events", false, event); } } - void handleThing(ThingDevice* device) { + void handleThing(ThingDevice *device) { sendOk(); sendHeaders(); @@ -469,7 +467,7 @@ class WebThingAdapter { client.stop(); } - void serializeThingItem(ThingItem* item, JsonObject prop) { + void serializeThingItem(ThingItem *item, JsonObject prop) { switch (item->type) { case NO_STATE: break; @@ -488,7 +486,7 @@ class WebThingAdapter { } } - void handleThingGetItem(ThingItem* item) { + void handleThingGetItem(ThingItem *item) { sendOk(); sendHeaders(); @@ -500,7 +498,7 @@ class WebThingAdapter { client.stop(); } - void handleThingGetAll(ThingItem* rootItem) { + void handleThingGetAll(ThingItem *rootItem) { sendOk(); sendHeaders(); @@ -516,7 +514,7 @@ class WebThingAdapter { client.stop(); } - void setThingProperty(const JsonObject newProp, ThingProperty* property) { + void setThingProperty(const JsonObject newProp, ThingProperty *property) { const JsonVariant newValue = newProp[property->id]; switch (property->type) { @@ -547,7 +545,7 @@ class WebThingAdapter { } } - void handleThingPropertyPut(ThingProperty* property) { + void handleThingPropertyPut(ThingProperty *property) { sendOk(); sendHeaders(); DynamicJsonDocument newBuffer(256); @@ -582,7 +580,6 @@ class WebThingAdapter { content = ""; retries = 0; } - }; #endif // neither ESP32 nor ESP8266 defined diff --git a/examples/LED/LED.ino b/examples/LED/LED.ino index b059653..34b8c50 100644 --- a/examples/LED/LED.ino +++ b/examples/LED/LED.ino @@ -13,25 +13,25 @@ #include "Thing.h" #include "WebThingAdapter.h" -//TODO: Hardcode your wifi credentials here (and keep it private) -const char* ssid = "public"; -const char* password = ""; +// TODO: Hardcode your wifi credentials here (and keep it private) +const char *ssid = "public"; +const char *password = ""; #if defined(LED_BUILTIN) const int ledPin = LED_BUILTIN; #else -const int ledPin = 13; // manually configure LED pin +const int ledPin = 13; // manually configure LED pin #endif -WebThingAdapter* adapter; +WebThingAdapter *adapter; -const char* ledTypes[] = {"OnOffSwitch", "Light", nullptr}; +const char *ledTypes[] = {"OnOffSwitch", "Light", nullptr}; ThingDevice led("led", "Built-in LED", ledTypes); ThingProperty ledOn("on", "", BOOLEAN, "OnOffProperty"); bool lastOn = false; -void setup(void){ +void setup(void) { pinMode(ledPin, OUTPUT); digitalWrite(ledPin, HIGH); Serial.begin(115200); @@ -75,7 +75,7 @@ void setup(void){ Serial.println(led.id); } -void loop(void){ +void loop(void) { adapter->update(); bool on = ledOn.getValue().boolean; digitalWrite(ledPin, on ? LOW : HIGH); // active low led diff --git a/examples/LEDLamp/LEDLamp.ino b/examples/LEDLamp/LEDLamp.ino index 729ef73..d0152cf 100644 --- a/examples/LEDLamp/LEDLamp.ino +++ b/examples/LEDLamp/LEDLamp.ino @@ -13,24 +13,26 @@ #include #include -const char* ssid = "......"; -const char* password = ".........."; +const char *ssid = "......"; +const char *password = ".........."; #if defined(LED_BUILTIN) const int lampPin = LED_BUILTIN; #else -const int lampPin = 13; // manually configure LED pin +const int lampPin = 13; // manually configure LED pin #endif -WebThingAdapter* adapter; +WebThingAdapter *adapter; -const char* lampTypes[] = {"OnOffSwitch", "Light", nullptr}; +const char *lampTypes[] = {"OnOffSwitch", "Light", nullptr}; ThingDevice lamp("lamp", "My Lamp", lampTypes); -ThingProperty lampOn("on", "Whether the lamp is turned on", BOOLEAN, "OnOffProperty"); -ThingProperty lampLevel("level", "The level of light from 0-100", NUMBER, "BrightnessProperty"); +ThingProperty lampOn("on", "Whether the lamp is turned on", BOOLEAN, + "OnOffProperty"); +ThingProperty lampLevel("level", "The level of light from 0-100", NUMBER, + "BrightnessProperty"); -void setup(void){ +void setup(void) { pinMode(lampPin, OUTPUT); digitalWrite(lampPin, HIGH); Serial.begin(115200); @@ -64,7 +66,7 @@ void setup(void){ #endif } -void loop(void){ +void loop(void) { adapter->update(); if (lampOn.getValue().boolean) { int level = map(lampLevel.getValue().number, 0, 100, 255, 0); diff --git a/examples/LevelSensor/LevelSensor.ino b/examples/LevelSensor/LevelSensor.ino index f9d732c..459ce8a 100644 --- a/examples/LevelSensor/LevelSensor.ino +++ b/examples/LevelSensor/LevelSensor.ino @@ -12,10 +12,11 @@ #include #include -const char* deviceTypes[] = {"MultiLevelSensor", "Sensor", nullptr}; -ThingDevice device("AnalogSensorDevice", "Analog Sensor plugged in single pin", deviceTypes); +const char *deviceTypes[] = {"MultiLevelSensor", "Sensor", nullptr}; +ThingDevice device("AnalogSensorDevice", "Analog Sensor plugged in single pin", + deviceTypes); ThingProperty property("level", "Analog Input pin", NUMBER, "LevelProperty"); -WebThingAdapter* adapter = NULL; +WebThingAdapter *adapter = NULL; const int sensorPin = A0; @@ -23,22 +24,20 @@ double lastValue = 0; int setupNetwork() { Serial.println(__FUNCTION__); - //TODO: update with actual MAC address - uint8_t ETHERNET_MAC[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; + // TODO: update with actual MAC address + uint8_t ETHERNET_MAC[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; uint8_t error = Ethernet.begin(ETHERNET_MAC); - if (error == 0) - { - printf("error: %s\n",__FUNCTION__); + if (error == 0) { + printf("error: %s\n", __FUNCTION__); return -1; } return 0; } - void setup(void) { Serial.begin(115200); Serial.println(__FUNCTION__); - while (0 != setupNetwork()){ + while (0 != setupNetwork()) { delay(5000); } IPAddress ip = Ethernet.localIP(); @@ -60,7 +59,7 @@ void setup(void) { void loop(void) { const int threshold = 1; int value = analogRead(sensorPin); - double percent = (double) 100. - (value/1024.*100.); + double percent = (double)100. - (value / 1024. * 100.); if (abs(percent - lastValue) >= threshold) { Serial.print("log: Value: "); Serial.print(value); diff --git a/examples/PlatformIO/BME280/platformio.ini b/examples/PlatformIO/BME280/platformio.ini old mode 100755 new mode 100644 diff --git a/examples/PlatformIO/BME280/src/BME280.cpp b/examples/PlatformIO/BME280/src/BME280.cpp old mode 100755 new mode 100644 index ac23cb5..c7fd349 --- a/examples/PlatformIO/BME280/src/BME280.cpp +++ b/examples/PlatformIO/BME280/src/BME280.cpp @@ -43,44 +43,40 @@ #define PIN_STATE_LOW LOW #endif -WebThingAdapter* adapter; +WebThingAdapter *adapter; -const char* bme280Types[] = {"TemperatureSensor", nullptr}; +const char *bme280Types[] = {"TemperatureSensor", nullptr}; ThingDevice weather("bme280", "BME280 Weather Sensor", bme280Types); ThingProperty weatherTemp("temperature", "", NUMBER, "TemperatureProperty"); ThingProperty weatherHum("humidity", "", NUMBER, nullptr); ThingProperty weatherPres("pressure", "", NUMBER, nullptr); -BME280I2C::Settings settings( - BME280::OSR_X1, - BME280::OSR_X1, - BME280::OSR_X1, - BME280::Mode_Forced, - BME280::StandbyTime_1000ms, - BME280::Filter_Off, - BME280::SpiEnable_False, - (BME280I2C::I2CAddr) 0x76 // I2C address. I2C specific. -); +BME280I2C::Settings + settings(BME280::OSR_X1, BME280::OSR_X1, BME280::OSR_X1, + BME280::Mode_Forced, BME280::StandbyTime_1000ms, + BME280::Filter_Off, BME280::SpiEnable_False, + (BME280I2C::I2CAddr)0x76 // I2C address. I2C specific. + ); BME280I2C bme(settings); void readBME280Data() { - float temp(NAN), hum(NAN), pres(NAN); - BME280::TempUnit tempUnit(BME280::TempUnit_Celsius); - BME280::PresUnit presUnit(BME280::PresUnit_Pa); - bme.read(pres, temp, hum, tempUnit, presUnit); - - ThingPropertyValue value; - value.number = pres; - weatherPres.setValue(value); - value.number = temp; - weatherTemp.setValue(value); - value.number = hum; - weatherHum.setValue(value); + float temp(NAN), hum(NAN), pres(NAN); + BME280::TempUnit tempUnit(BME280::TempUnit_Celsius); + BME280::PresUnit presUnit(BME280::PresUnit_Pa); + bme.read(pres, temp, hum, tempUnit, presUnit); + + ThingPropertyValue value; + value.number = pres; + weatherPres.setValue(value); + value.number = temp; + weatherTemp.setValue(value); + value.number = hum; + weatherHum.setValue(value); } void setup() { - //Initialize serial: + // Initialize serial: // Serial.begin(9600); // check for the presence of the shield: @@ -88,14 +84,15 @@ void setup() { if (WiFi.status() == WL_NO_SHIELD) { // Serial.println("WiFi shield not present"); // don't continue: - while (true); + while (true) + ; } // configure the LED pin for output mode pinMode(LED_BUILTIN, OUTPUT); Wire.begin(); - while(!bme.begin()) { + while (!bme.begin()) { // Serial.println("Could not find BME280I2C sensor!"); delay(1000); } @@ -103,9 +100,11 @@ void setup() { // Serial.println("Starting in provisioning mode..."); // Start in provisioning mode: // 1) This will try to connect to a previously associated access point. - // 2) If this fails, an access point named "wifi101-XXXX" will be created, where XXXX - // is the last 4 digits of the boards MAC address. Once you are connected to the access point, - // you can configure an SSID and password by visiting http://wifi101/ + // 2) If this fails, an access point named "wifi101-XXXX" will be created, + // where XXXX + // is the last 4 digits of the boards MAC address. Once you are connected + // to the access point, you can configure an SSID and password by + // visiting http://wifi101/ WiFi.beginProvision(); while (WiFi.status() != WL_CONNECTED) { diff --git a/examples/PlatformIO/LED/src/LED.cpp b/examples/PlatformIO/LED/src/LED.cpp index 24e509e..1a8bf80 100644 --- a/examples/PlatformIO/LED/src/LED.cpp +++ b/examples/PlatformIO/LED/src/LED.cpp @@ -13,25 +13,25 @@ #include "Thing.h" #include "WebThingAdapter.h" -//TODO: Hardcode your wifi credentials here (and keep it private) -const char* ssid = "public"; -const char* password = ""; +// TODO: Hardcode your wifi credentials here (and keep it private) +const char *ssid = "public"; +const char *password = ""; #if defined(LED_BUILTIN) const int ledPin = LED_BUILTIN; #else -const int ledPin = 13; // manually configure LED pin +const int ledPin = 13; // manually configure LED pin #endif -WebThingAdapter* adapter; +WebThingAdapter *adapter; -const char* ledTypes[] = {"OnOffSwitch", "Light", nullptr}; +const char *ledTypes[] = {"OnOffSwitch", "Light", nullptr}; ThingDevice led("led", "Built-in LED", ledTypes); ThingProperty ledOn("on", "", BOOLEAN, "OnOffProperty"); bool lastOn = false; -void setup(void){ +void setup(void) { pinMode(ledPin, OUTPUT); digitalWrite(ledPin, HIGH); Serial.begin(115200); @@ -72,7 +72,7 @@ void setup(void){ Serial.println(led.id); } -void loop(void){ +void loop(void) { adapter->update(); bool on = ledOn.getValue().boolean; digitalWrite(ledPin, on ? LOW : HIGH); // active low led @@ -83,4 +83,3 @@ void loop(void){ } lastOn = on; } - diff --git a/examples/PlatformIO/TextDisplay/src/TextDisplay.cpp b/examples/PlatformIO/TextDisplay/src/TextDisplay.cpp index b166cb6..0a33045 100644 --- a/examples/PlatformIO/TextDisplay/src/TextDisplay.cpp +++ b/examples/PlatformIO/TextDisplay/src/TextDisplay.cpp @@ -23,8 +23,8 @@ All text above, and the splash screen must be included in any redistribution #include #include -const char* ssid = "..."; -const char* password = "..."; +const char *ssid = "..."; +const char *password = "..."; #include #include @@ -32,12 +32,13 @@ const char* password = "..."; #include // If using software SPI (the default case): -#define OLED_MOSI 2 -#define OLED_CLK 16 -#define OLED_DC 0 -#define OLED_CS 13 +#define OLED_MOSI 2 +#define OLED_CLK 16 +#define OLED_DC 0 +#define OLED_CS 13 #define OLED_RESET 15 -Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, (int8_t)OLED_DC, OLED_RESET, OLED_CS); +Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, (int8_t)OLED_DC, OLED_RESET, + OLED_CS); /* Uncomment this block to use hardware SPI #define OLED_DC 6 @@ -51,15 +52,15 @@ const int textWidth = 6; const int width = 128; const int height = 64; -WebThingAdapter* adapter; +WebThingAdapter *adapter; -const char* textDisplayTypes[] = {"TextDisplay", nullptr}; +const char *textDisplayTypes[] = {"TextDisplay", nullptr}; ThingDevice textDisplay("textDisplay", "Text display", textDisplayTypes); ThingProperty text("text", "", STRING, nullptr); String lastText = "moz://a iot"; -void displayString(const String& str) { +void displayString(const String &str) { int len = str.length(); int strWidth = len * textWidth; int strHeight = textHeight; @@ -81,7 +82,8 @@ void displayString(const String& str) { void setup() { Serial.begin(115200); - // by default, we'll generate the high voltage from the 3.3v line internally! (neat!) + // by default, we'll generate the high voltage from the 3.3v line internally! + // (neat!) display.begin(SSD1306_SWITCHCAPVCC); // display the splashscreen as requested :) @@ -122,4 +124,3 @@ void loop() { adapter->update(); displayString(lastText); } - diff --git a/examples/RGBLamp/RGBLamp.ino b/examples/RGBLamp/RGBLamp.ino index e649890..f201187 100644 --- a/examples/RGBLamp/RGBLamp.ino +++ b/examples/RGBLamp/RGBLamp.ino @@ -14,29 +14,34 @@ #include #include -//TODO: Hardcode your wifi credentials here (and keep it private) -const char* ssid = "public"; -const char* password = ""; +// TODO: Hardcode your wifi credentials here (and keep it private) +const char *ssid = "public"; +const char *password = ""; /// Only used for monitoring, can be removed it's not part of our "thing" #if defined(LED_BUILTIN) const int ledPin = LED_BUILTIN; #else -const int ledPin = 13; // manually configure LED pin +const int ledPin = 13; // manually configure LED pin #endif -//for optional properties -//const char * valEnum[5] = {"RED", "GREEN", "BLACK", "white", nullptr}; -//const char * valEnum[5] = {"#db4a4a", "#4adb58", "000000", "ffffff", nullptr}; +// for optional properties +// const char * valEnum[5] = {"RED", "GREEN", "BLACK", "white", nullptr}; +// const char * valEnum[5] = {"#db4a4a", "#4adb58", "000000", "ffffff", +// nullptr}; -WebThingAdapter* adapter; +WebThingAdapter *adapter; -const char* deviceTypes[] = {"Light", "OnOffSwitch", "ColorControl", nullptr}; -ThingDevice device("dimmable-color-light", "Dimmable Color Light", deviceTypes); +const char *deviceTypes[] = {"Light", "OnOffSwitch", "ColorControl", nullptr}; +ThingDevice device("dimmable-color-light", "Dimmable Color Light", + deviceTypes); -ThingProperty deviceOn("on", "Whether the led is turned on", BOOLEAN, "OnOffProperty"); -ThingProperty deviceLevel("level", "The level of light from 0-100", NUMBER, "BrightnessProperty"); -ThingProperty deviceColor("color", "The color of light in RGB", STRING, "ColorProperty"); +ThingProperty deviceOn("on", "Whether the led is turned on", BOOLEAN, + "OnOffProperty"); +ThingProperty deviceLevel("level", "The level of light from 0-100", NUMBER, + "BrightnessProperty"); +ThingProperty deviceColor("color", "The color of light in RGB", STRING, + "ColorProperty"); bool lastOn = false; String lastColor = "#ffffff"; @@ -45,7 +50,6 @@ const unsigned char redPin = 12; const unsigned char greenPin = 13; const unsigned char bluePin = 14; - void setupLamp(void) { pinMode(redPin, OUTPUT); digitalWrite(redPin, HIGH); @@ -93,13 +97,13 @@ void setup(void) { deviceLevel.setValue(levelValue); device.addProperty(&deviceLevel); - //optional properties - //deviceColor.propertyEnum = valEnum; - //deviceColor.readOnly = true; - //deviceColor.unit = "HEX"; + // optional properties + // deviceColor.propertyEnum = valEnum; + // deviceColor.readOnly = true; + // deviceColor.unit = "HEX"; ThingPropertyValue colorValue; - colorValue.string = &lastColor; //default color is white + colorValue.string = &lastColor; // default color is white deviceColor.setValue(colorValue); device.addProperty(&deviceColor); @@ -115,19 +119,20 @@ void setup(void) { #endif } -void update(String* color, int const level) { - if (!color) return; - float dim = level/100.; - int red,green,blue; +void update(String *color, int const level) { + if (!color) + return; + float dim = level / 100.; + int red, green, blue; if (color && (color->length() == 7) && color->charAt(0) == '#') { - const char* hex = 1+(color->c_str()); // skip leading '#' - sscanf(0+hex, "%2x", &red); - sscanf(2+hex, "%2x", &green); - sscanf(4+hex, "%2x", &blue); + const char *hex = 1 + (color->c_str()); // skip leading '#' + sscanf(0 + hex, "%2x", &red); + sscanf(2 + hex, "%2x", &green); + sscanf(4 + hex, "%2x", &blue); } - analogWrite(redPin, red*dim); - analogWrite(greenPin, green*dim ); - analogWrite(bluePin, blue*dim ); + analogWrite(redPin, red * dim); + analogWrite(greenPin, green * dim); + analogWrite(bluePin, blue * dim); } void loop(void) { diff --git a/examples/TextDisplay/TextDisplay.ino b/examples/TextDisplay/TextDisplay.ino index b166cb6..0a33045 100644 --- a/examples/TextDisplay/TextDisplay.ino +++ b/examples/TextDisplay/TextDisplay.ino @@ -23,8 +23,8 @@ All text above, and the splash screen must be included in any redistribution #include #include -const char* ssid = "..."; -const char* password = "..."; +const char *ssid = "..."; +const char *password = "..."; #include #include @@ -32,12 +32,13 @@ const char* password = "..."; #include // If using software SPI (the default case): -#define OLED_MOSI 2 -#define OLED_CLK 16 -#define OLED_DC 0 -#define OLED_CS 13 +#define OLED_MOSI 2 +#define OLED_CLK 16 +#define OLED_DC 0 +#define OLED_CS 13 #define OLED_RESET 15 -Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, (int8_t)OLED_DC, OLED_RESET, OLED_CS); +Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, (int8_t)OLED_DC, OLED_RESET, + OLED_CS); /* Uncomment this block to use hardware SPI #define OLED_DC 6 @@ -51,15 +52,15 @@ const int textWidth = 6; const int width = 128; const int height = 64; -WebThingAdapter* adapter; +WebThingAdapter *adapter; -const char* textDisplayTypes[] = {"TextDisplay", nullptr}; +const char *textDisplayTypes[] = {"TextDisplay", nullptr}; ThingDevice textDisplay("textDisplay", "Text display", textDisplayTypes); ThingProperty text("text", "", STRING, nullptr); String lastText = "moz://a iot"; -void displayString(const String& str) { +void displayString(const String &str) { int len = str.length(); int strWidth = len * textWidth; int strHeight = textHeight; @@ -81,7 +82,8 @@ void displayString(const String& str) { void setup() { Serial.begin(115200); - // by default, we'll generate the high voltage from the 3.3v line internally! (neat!) + // by default, we'll generate the high voltage from the 3.3v line internally! + // (neat!) display.begin(SSD1306_SWITCHCAPVCC); // display the splashscreen as requested :) @@ -122,4 +124,3 @@ void loop() { adapter->update(); displayString(lastText); } -