Here is How to Send an HTTP POST Request to IBM Watson IoT on Button Press from Arduino ESP32. The basic is dependent on our earlier two separate examples, first is the set of working examples of codes for IBM Watson IoT and second is the example of using a button press to make a LED turn on for a pre-defined time. Earlier, we had another example of using Blynk to send a basic push message on a button press. That Bylnk’s example was for satisfying peoples who want a quick fix in an easy way. That way is not methodical, it abstracts the software and hardware too much, also not reliable.
There is nothing new to say about how to setup ESP32 to use with Arduino IDE.
If you want the code, that is readily available on our GitHub repo. We want to say something on HTTP POST of IBM Watson IoT.
---
To securely send an event called myEvent
to the platform with organisation id ‘xfd8ls’, device id HTTPDevice
and device type HTTPdeviceType
we issue this POST request:
1 | https://xfd8ls.messaging.internetofthings.ibmcloud.com:8883/api/v0002/device/types/HTTPdeviceType/devices/HTTPDevice/events/myEvent |
From the above example, you have to keep polling the server to see if there was a message waiting. That is fine for some purposes. We can set the body of the message to:
1 | {"waitTimeSecs": 10} |
The number represents a number of seconds. This way you can effectively set your code to wait
for a command to arrive. This official guide talking about the thing we are doing but in complex way with Raspberry Pi :
1 | https://developer.ibm.com/recipes/tutorials/publish-device-events-to-ibm-iot-foundation-using-https/ |
And here is more detailed documentation :
1 | https://console.bluemix.net/docs/services/IoT/devices/api.html#api |
For our this code, you will get the raw data from the Recent Events tab on IBM Watson IoT Platform and also, the
Logs there will show authentication, connection and disconnection. These facts proves that remote server “understood” your button press. Also on Arduino IDE’s serial console, you will get meaningful output. This is a meaningful illustration :
Here are more useful docs :
1 2 | https://developer.ibm.com/recipes/tutorials/publish-device-events-to-ibm-iot-foundation-using-https/ https://www.ibm.com/support/knowledgecenter/en/SSQP8H/iot/platform/devices/api.html |
And here is the full code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 | // connects once upon pressing ESP32 boot pushbutton (GPIO 0) button and sends a message, closes connection // written by Dr. Abhishek Ghosh, https://thecustomizewindows.com // released under GNU GPL 3.0 const byte BUTTON=0; // boot button pin (built-in on ESP32) const byte LED=2; // onboard LED (built-in on ESP32) #include <WiFi.h> #include <WiFiMulti.h> #include <HTTPClient.h> #include <base64.h> #define USE_SERIAL Serial unsigned long buttonPushedMillis; // when button was released unsigned long ledTurnedOnAt; // when led was turned on unsigned long turnOnDelay = 20; // wait to turn on LED unsigned long turnOffDelay = 5000; // turn off LED after this time bool ledReady = false; // flag for when button is let go bool ledState = false; // for LED is on or not. const char* ssid = "your wifi hotspot"; const char* password = "password of the above"; #define ORG "your org on ibm" #define DEVICE_TYPE "name you given" #define DEVICE_ID "name you given" #define TOKEN "your token" #define EVENT "myEvent" // example // <------- CHANGE PARAMETERS ABOVE THIS LINE ------------> String urlPath = "/api/v0002/device/types/" DEVICE_TYPE "/devices/" DEVICE_ID "/events/" EVENT; String urlHost = ORG ".messaging.internetofthings.ibmcloud.com"; int urlPort = 8883; String authHeader; void setup() { pinMode(BUTTON, INPUT_PULLUP); pinMode(LED, OUTPUT); digitalWrite(LED, LOW); Serial.begin(115200); Serial.println(); initWifi(); authHeader = "Authorization: Basic " + base64::encode("use-token-auth:" TOKEN) + "\r\n"; } void loop() { // get the time at the start of this loop() unsigned long currentMillis = millis(); // check the button if (digitalRead(BUTTON) == LOW) { // update the time when button was pushed buttonPushedMillis = currentMillis; ledReady = true; } // make sure this code isn't checked until after button has been let go if (ledReady) { //this is typical millis code here: if ((unsigned long)(currentMillis - buttonPushedMillis) >= turnOnDelay) { // okay, enough time has passed since the button was let go. digitalWrite(LED, HIGH); doWiFiClientSecure(); // setup our next "state" ledState = true; // save when the LED turned on ledTurnedOnAt = currentMillis; // wait for next button press ledReady = false; } } // see if we are watching for the time to turn off LED if (ledState) { // okay, led on, check for now long if ((unsigned long)(currentMillis - ledTurnedOnAt) >= turnOffDelay) { ledState = false; digitalWrite(LED, LOW); } } } void doWiFiClientSecure() { WiFiClientSecure client; Serial.print("connect: "); Serial.println(urlHost); while ( ! client.connect(urlHost.c_str(), urlPort)) { Serial.print("."); } Serial.println("Connected"); String postData = String("{ \"d\": {\"aMessage\": \"") + millis()/1000 + "\"} }"; String msg = "POST " + urlPath + " HTTP/1.1\r\n" "Host: " + urlHost + "\r\n" "" + authHeader + "" "Content-Type: application/json\r\n" "Content-Length: " + postData.length() + "\r\n" "\r\n" + postData; client.print(msg); Serial.print(msg); Serial.print("\n*** Request sent, receiving response..."); while (!!!client.available()) { delay(50); Serial.print("."); } Serial.println(); Serial.println("Got response"); while(client.available()){ Serial.write(client.read()); } Serial.println(); Serial.println("closing connection"); client.stop(); } void initWifi() { Serial.print("Connecting to: "); Serial.print(WiFi.SSID()); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(250); Serial.print("."); } Serial.println(""); Serial.print("WiFi connected, IP address: "); Serial.println(WiFi.localIP()); } |