rest - dl3ebb/OpenIot GitHub Wiki
In smaller setups, an MQTT broker may not be necessary. OpenIot provides a built-in REST server that allows you to query or set the status using any browser.
The following example demonstrates the use of the REST connector:
/**
* Demo of the REST Server usage
*/
#define SWITCH_PIN 25
#define LED_PIN 32
#define WLAN_SSID "your_ssid"
#define WLAN_PASSWD "your_passwd"
#include <OpenIot.h>
#include <Connector/DigitalInConnector.h>
#include <Connector/DigitalOutConnector.h>
#include <Connector/RestConnector.h>
#include <Logger/SerialLogger.h>
#include <Modules/Wifi.h>
void setup() {
serialLogger->setBaudrate(115200);
openIot.setLogger(serialLogger);
wifi->setEnablePrimary(true);
wifi->setSsid1(WLAN_SSID);
wifi->setPassword1(WLAN_PASSWD);
restConnector->setEnable(true);
/**
* Create the Elements and register them to the connectors
*/
BoolElement *switch1 = new BoolElement("Switch1");
digitalInConnector->registerElement(switch1, SWITCH_PIN, true);
restConnector->registerElement(switch1, "Switch1");
BoolElement *led1 = new BoolElement("Led1");
digitalOutConnector->registerElement(led1, LED_PIN);
restConnector->registerElement(led1, "Led1");
eventManager.addListener<NewBoolValueEvent>(NewBoolValue, "Switch1", [led1](NewBoolValueEvent *event) {
led1->setValue(event->newValue);
});
openIot.setup("OpenIotRest", 1);
}
void loop() {
openIot.loop();
}
The REST connector is enabled with the configuration:
restConnector->setEnable(true);
Next, the elements are registered with the REST connector:
restConnector->registerElement(switch1, "Switch1");
for the switch and
restConnector->registerElement(led1, "Led1");
for the LED.
With this configuration done, the device, upon startup, will output the following in the console:
INFO - ---- Rest settings : ------
INFO - Enabled : true
Now, you can query or control the elements via GET requests from any browser. The URL follows this pattern: <IPAddress>/api/<ElementId>
. A request without any content will return the current status of the element, while appending /<Value>
will set the value of the element.
For example, if the device has the IP address 10.103.229.124
, you can query the status of the LED with:
http://10.103.229.124/api/Led1
This will return the status of the LED (either OFF or ON).
To turn the LED on, you can use:
http://10.103.229.124/api/Led1/on
The device will respond with "OK" once the command is processed.
| ← Previous Page (MQTT) | ↑ Tutorial Main Page | Next Page (NTP) → |