• Home
  • Archive
  • Tools
  • Contact Us

The Customize Windows

Technology Journal

  • Cloud Computing
  • Computer
  • Digital Photography
  • Windows 7
  • Archive
  • Cloud Computing
  • Virtualization
  • Computer and Internet
  • Digital Photography
  • Android
  • Sysadmin
  • Electronics
  • Big Data
  • Virtualization
  • Downloads
  • Web Development
  • Apple
  • Android
Advertisement
You are here: Home » Sending Commands to IBM Watson IoT to Trigger Event on Device

By Abhishek Ghosh April 13, 2019 6:49 pm Updated on April 13, 2019

Sending Commands to IBM Watson IoT to Trigger Event on Device

Advertisement

Till now we were mostly sending data from ESP32 like devices to IBM Watson IoT. Opposite direction of commands often a practical need, such as to control a LED connected to device. In this context, knowledge of cURL commands (here is cURL for Windows, other way is using Windows 10 bash) for testing required. IBM has “HTTP Messaging APIs for devices” and ”
Extending device management”. We already know about HTTP POST and sent HTTP POST request from ESP32. Current use-case is reverse – we will use command line from some computer or server towards IBM Watson IoT to trigger event on device. The required two authentication parameters are the authentication token (which works as password) and API key (which works as username). API key can be collected from the web UI of IBM Watson IoT.

 

How To Send Commands to IBM Watson IoT to Trigger Event on Device

 

Documentation on this topic exists on official website (s) :

Vim
1
2
3
4
5
https://console.bluemix.net/docs/services/IoT/applications/api.html
https://console.bluemix.net/docs/services/IoT/GA_information_management/ga_im_index_scenario.html
https://console.bluemix.net/docs/services/IoT/devices/device_cmd_api.html
https://console.bluemix.net/docs/services/IoT/devices/device_mgmt/custom_actions.html
https://docs.internetofthings.ibmcloud.com/apis/swagger/v0002/http-messaging.html

Obviously, if we can use HTTP POST request from command line interface, we can create simple web applications for versatile control. Here is a sample code for ESP32 Arduino :

Advertisement

---

Vim
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#include <WiFi.h>
#include <WiFiMulti.h>
#include <PubSubClient.h>
#include <HTTPClient.h>
#include <base64.h>
#define USE_SERIAL Serial
#include <Ticker.h>
 
// <------- CHANGE PARAMETERS BELOW THIS LINE ------------>
 
const char* ssid = "change-it";
const char* password = "change-it";
 
#define ORG "change-it"
#define DEVICE_TYPE "your-custom-name"
#define DEVICE_ID "custom-name-change"
#define TOKEN "your-token"
 
 
#define DEVICE_BUTTON 0 // ESP32 onboard boot push button
#define DEVICE_RELAY 2 // Onboard LED. Pin to control with command
#define DEVICE_GREEN_LED 12 // optional
#define DEVICE_RED_LED 14 // optional
 
// <------- CHANGE PARAMETERS ABOVE THIS LINE ------------>
// <------- STOP EDITING ------------>
 
Ticker ledBlinker;
 
char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char authMethod[] = "use-token-auth";
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;
 
#define CMD_STATE "/gpio/"  
 
// use the '+' wildcard so it subscribes to any command with any message format
const char commandTopic[] = "iot-2/cmd/+/fmt/+";
 
void gotMsg(char* topic, byte* payload, unsigned int payloadLength);
 
WiFiClient wifiClient;
PubSubClient client(server, 1883, gotMsg, wifiClient);
 
int buttonPressDuration;
 
void setup() {
Serial.begin(115200); Serial.println();
 
pinMode(DEVICE_RELAY, OUTPUT);
pinMode(DEVICE_GREEN_LED, OUTPUT);
pinMode(DEVICE_RED_LED, OUTPUT);
 
ledBlinker.attach(0.1, ledBlink); // fast blink indicates Wifi connecting
wifiConnect();
ledBlinker.attach(0.4, ledBlink); // slower blink indicates MQTT connecting
mqttConnect();
ledBlinker.detach();
digitalWrite(DEVICE_GREEN_LED, LOW); // low is led on to show connected
pinMode(DEVICE_BUTTON, INPUT);
attachInterrupt(DEVICE_BUTTON, buttonPress, CHANGE);
}
 
int lastHeartBeat;
 
void loop() {
if (buttonPressDuration > 0) {
   doCommand(digitalRead(DEVICE_RELAY) ? "off" : "on");
   buttonPressDuration = 0;
}
 
if (!client.loop()) {
   mqttConnect();
}
if (millis()-lastHeartBeat > 10000) {
   Serial.print("loop: gpio "); Serial.print(DEVICE_RELAY); Serial.print(" current state ");
   Serial.println(digitalRead(DEVICE_RELAY) ? "On" : "Off");
   digitalWrite(DEVICE_GREEN_LED, HIGH); // flicker LED to show its active
   delay(200);
   digitalWrite(DEVICE_GREEN_LED, LOW);
   lastHeartBeat = millis();
}
}
 
void gotMsg(char* topic, byte* payload, unsigned int payloadLength) {
Serial.print("gotMsg: invoked for topic: "); Serial.println(topic);
if (String(topic).indexOf(CMD_STATE) > 0) {
   String cmd = "";
   for (int i=0; i<payloadLength; i++) {
     cmd += (char)payload[i];
   }
   doCommand(cmd);
} else {
   Serial.print("gotMsg: unexpected topic: "); Serial.println(topic);
}
}
 
void doCommand(String cmd) {
int currentState = digitalRead(DEVICE_RELAY);
int newState = (cmd == "on");
digitalWrite(DEVICE_RELAY, newState);
Serial.print("Relay switched from ");
Serial.print(currentState ? "On" : "Off");Serial.print(" to "); Serial.println(newState ? "On" : "Off");
}
 
unsigned long startPress = 0;
 
void buttonPress() {
int currentState = digitalRead(DEVICE_BUTTON);
if (currentState == 0) { // 0 is pressed, 1 is released
   startPress = millis();
} else {
   int diff = millis() - startPress;
   if (diff > 100) { // debounce
     buttonPressDuration = diff;
   }
}
Serial.print("Button "); Serial.print(currentState ? "released" : "pressed");
Serial.print(" duration="); Serial.println(buttonPressDuration);
}
 
void ledBlink() {
  digitalWrite(DEVICE_GREEN_LED, ! digitalRead(DEVICE_GREEN_LED));
}
 
void wifiConnect() {
Serial.print("Connecting to "); Serial.print(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(".");
}
Serial.print("\nWiFi connected, IP address: "); Serial.println(WiFi.localIP());
}
 
void mqttConnect() {
if (!!!client.connected()) {
   Serial.print("Reconnecting MQTT client to "); Serial.println(server);
   while (!!!client.connect(clientId, authMethod, token)) {
     Serial.print(".");
     delay(500);
   }
   Serial.println();
}
 
subscribeTo(commandTopic);
}
 
void subscribeTo(const char* topic) {
Serial.print("subscribe to "); Serial.print(topic);
if (client.subscribe(topic)) {
   Serial.println(" OK");
} else {
   Serial.println(" FAILED");
}
}

The above code is adapted for ESP32 from this recipe :

Vim
1
https://developer.ibm.com/recipes/tutorials/build-your-own-watson-controlled-kettle/

Sending Commands to IBM Watson IoT to Trigger Event on Device

Here, if we press the on-board button of ESP32, the on-board LED on ESP32 will glow. The above is reference diagram of attaching external push button for need more than basic.

We can remotely control it using cURL in this format :

Vim
1
2
3
4
5
6
7
8
# switch ON
curl -u <yourApiKey>:<yourApiPassword> -H "Content-Type: text/plain" -v -X
   POST http://<yourOrg>.messaging.internetofthings.ibmcloud.com:1883/api/v0002/
   application/types/<yourDeviceType>/devices/<yourDeviceId>/commands/gpio -d "on"
# switch OFF
curl -u <yourApiKey>:<yourApiPassword> -H "Content-Type: text/plain" -v -X
   POST http://<yourOrg>.messaging.internetofthings.ibmcloud.com:1883/api/v0002/
   application/types/<yourDeviceType>/devices/<yourDeviceId>/commands/gpio -d "off"

That is it. You need some work with command line by sending data to get used.

Tagged With http curl iot devices , ibm iot get latest event from device , ibm watson iot device command cache , iot watson api send command

This Article Has Been Shared 327 Times!

Facebook Twitter Pinterest

Abhishek Ghosh

About Abhishek Ghosh

Abhishek Ghosh is a Businessman, Surgeon, Author and Blogger. You can keep touch with him on Twitter - @AbhishekCTRL.

Here’s what we’ve got for you which might like :

Articles Related to Sending Commands to IBM Watson IoT to Trigger Event on Device

  • Introduction to MicroPython for ESP32

    Here is Introduction to MicroPython for ESP32. The Language Features of Python are Also Available in MicroPython Making ESP32 Super Powerful.

  • ESP32 Arduino : Create a Webpage to Control a Relay Module

    Here is How to Create a Webpage to Control a Relay Module Using ESP32 Arduino. This is a basic example which provides the base of advanced projects.

  • ESP32 Arduino and TM1637 Seven Segment LED Display

    TM1637 Seven Segment LED Display is Popular Thing in Arduino Prototyping World. Here is Some Words About Using TM1637 With ESP32 Arduino.

  • ESP32 Arduino Built-in Hall Sensor Code & Theory

    ESP32 has a Hall Effect Sensor near pin 22. Here is ESP32 Arduino Built-in Hall Sensor Code & Theory. Here is something about Hall Effect Sensor as well.

  • ESP32 MicroPython Setup with Adafruit Ampy

    Here is ESP32 MicroPython Setup with Adafruit Ampy for Windows, MacOS X and Linux. You need Python needs to be running and install few tools.

Additionally, performing a search on this website can help you. Also, we have YouTube Videos.

Take The Conversation Further ...

We'd love to know your thoughts on this article.
Meet the Author over on Twitter to join the conversation right now!

If you want to Advertise on our Article or want a Sponsored Article, you are invited to Contact us.

Contact Us

Subscribe To Our Free Newsletter

Get new posts by email:

Please Confirm the Subscription When Approval Email Will Arrive in Your Email Inbox as Second Step.

Search this website…

 

Popular Articles

Our Homepage is best place to find popular articles!

Here Are Some Good to Read Articles :

  • Cloud Computing Service Models
  • What is Cloud Computing?
  • Cloud Computing and Social Networks in Mobile Space
  • ARM Processor Architecture
  • What Camera Mode to Choose
  • Indispensable MySQL queries for custom fields in WordPress
  • Windows 7 Speech Recognition Scripting Related Tutorials

Social Networks

  • Pinterest (24.3K Followers)
  • Twitter (5.8k Followers)
  • Facebook (5.7k Followers)
  • LinkedIn (3.7k Followers)
  • YouTube (1.3k Followers)
  • GitHub (Repository)
  • GitHub (Gists)
Looking to publish sponsored article on our website?

Contact us

Recent Posts

  • What is Configuration Management February 5, 2023
  • What is ChatGPT? February 3, 2023
  • Zebronics Pixaplay 16 : Entry Level Movie Projector Review February 2, 2023
  • What is Voice User Interface (VUI) January 31, 2023
  • Proxy Server: Design Pattern in Programming January 30, 2023

About This Article

Cite this article as: Abhishek Ghosh, "Sending Commands to IBM Watson IoT to Trigger Event on Device," in The Customize Windows, April 13, 2019, February 6, 2023, https://thecustomizewindows.com/2019/04/sending-commands-to-ibm-watson-iot-to-trigger-event-on-device/.

Source:The Customize Windows, JiMA.in

PC users can consult Corrine Chorney for Security.

Want to know more about us? Read Notability and Mentions & Our Setup.

Copyright © 2023 - The Customize Windows | dESIGNed by The Customize Windows

Copyright  · Privacy Policy  · Advertising Policy  · Terms of Service  · Refund Policy

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT