Skip to content

Commit bafdcc8

Browse files
IBM IoT sample (#13)
* IBM deviceSample's cpp & Cmake files * Create README.md * Create sample.json * Info files updated * Update sample.json * Copyright and GUID fixed * Update sample.json * Update README.md Co-authored-by: JoeOster <[email protected]>
1 parent f21759d commit bafdcc8

File tree

5 files changed

+369
-0
lines changed

5 files changed

+369
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
cmake_minimum_required (VERSION 3.0)
2+
3+
project (ibm-device)
4+
5+
set(CMAKE_CXX_STANDARD "11")
6+
7+
set(IOT_SDK_FOLDER "$ENV{HOME}/iot-c")
8+
9+
include_directories(
10+
"${IOT_SDK_FOLDER}/paho.mqtt.c/src"
11+
"${IOT_SDK_FOLDER}/paho.mqtt.c/build/output"
12+
"${IOT_SDK_FOLDER}/build"
13+
"${IOT_SDK_FOLDER}/src/wiotp/sdk"
14+
)
15+
16+
file(GLOB LIB_SRC ${IOT_SDK_FOLDER}/src/wiotp/sdk/*.c ${IOT_SDK_FOLDER}/src/wiotp/sdk/*.h)
17+
18+
add_library(iotp STATIC ${LIB_SRC})
19+
20+
set(device_sample_files cpp/deviceSample.c)
21+
22+
add_executable(ibm-device ${device_sample_files})
23+
24+
target_link_libraries(ibm-device iotp paho-mqtt3as pthread ssl crypto)
25+
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
Copyright Intel Corporation
2+
3+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4+
5+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6+
7+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8+
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# `IBM Device` Sample
2+
3+
`IBM Device` sample shows how-to develop a device code using Watson IoT Platform iot-c device client library, connect and interact with Watson IoT Platform Service.
4+
5+
| Optimized for | Description
6+
|:--- |:---
7+
| OS | Linux* Ubuntu* 16.04, Linux* Ubuntu* 18.04,
8+
| Software | Paho MQTT C library, OpenSSL development package
9+
| What you will learn | Use protocol MQTT to send events from a device
10+
11+
## Purpose
12+
This is a simple sample you could use for a test of IBM device connection. This project shows how-to develop a device code using Watson IoT Platform iot-c device client library, connect and interact with Watson IoT Platform Service.
13+
14+
## Key Implementation Details
15+
This sample includes the function/code snippets to perform the following actions:
16+
- Initiliaze client library
17+
- Configure device from configuration parameters specified in a configuration file
18+
- Set client logging
19+
- Enable error handling routines
20+
- Send device events to WIoTP service
21+
- Receive and process commands from WIoTP service
22+
23+
##License
24+
Code sample uses Eclipse Public License - v1.0
25+
26+
##Building the `IBM Device` Sample
27+
28+
### On a Linux* System
29+
30+
The detailed instructions on how to install the custom provided all dependency libraries for Linux can be [found here](https://github.com/ibm-watson-iot/iot-c#build-instructions).
31+
32+
Perform the following steps:
33+
1. Run in the terminal:
34+
```
35+
cd $ENV{HOME}
36+
git clone https://github.com/ibm-watson-iot/iot-c.git
37+
cd iot-c
38+
make
39+
sudo make -C paho.mqtt.c install
40+
sudo make install
41+
```
42+
> Note! By default the directory to install the 'iot-c' library is $ENV{HOME}. Otherwise you should enter valid path to this library as variable IOT_SDK_FOLDER in CMakeLists.txt file.
43+
44+
2. Run the following lines from the sample folder 'ibm-device':
45+
```
46+
mkdir build
47+
cd build
48+
cmake ..
49+
make all
50+
```
51+
3. Run the program using:
52+
```
53+
ibm-device deviceSample --config <path_to_downloaded_configuration_file>
54+
```
55+
4. Clean the program using:
56+
```
57+
make clean
58+
```
59+
## Running the Sample
60+
61+
Configure IoT device on [IBM Watson IoT Platform Page](https://ibm-watson-iot.github.io/iot-c/device/).
62+
63+
### Application Parameters
64+
65+
The samples uses path to configuration file as a parameter.
66+
Download the configuration file with all the credentials according to [instructions](https://ibm-watson-iot.github.io/iot-c/device/).
67+
68+
### Example of Output
69+
70+
TBD
Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
/*******************************************************************************
2+
* Copyright (c) 2018 IBM Corp.
3+
*
4+
* All rights reserved. This program and the accompanying materials
5+
* are made available under the terms of the Eclipse Public License v1.0
6+
* and Eclipse Distribution License v1.0 which accompany this distribution.
7+
*
8+
* The Eclipse Public License is available at
9+
* http://www.eclipse.org/legal/epl-v10.html
10+
* and the Eclipse Distribution License is available at
11+
* http://www.eclipse.org/org/documents/edl-v10.php.
12+
*
13+
* Contributors:
14+
* Ranjan Dasgupta - Initial drop of deviceSample.c
15+
*
16+
*******************************************************************************/
17+
18+
/*
19+
* This sample shows how-to develop a device code using Watson IoT Platform
20+
* iot-c device client library, connect and interact with Watson IoT Platform Service.
21+
*
22+
* This sample includes the function/code snippets to perform the following actions:
23+
* - Initiliaze client library
24+
* - Configure device from configuration parameters specified in a configuration file
25+
* - Set client logging
26+
* - Enable error handling routines
27+
* - Send device events to WIoTP service
28+
* - Receive and process commands from WIoTP service
29+
*
30+
* SYNTAX:
31+
* deviceSample --config <config_file_path>
32+
*
33+
* Pre-requisite:
34+
* 1. This sample requires a device configuration file.
35+
* Refer to "Device Confioguration File" section of iot-c docs for details.
36+
* 2. Register type and id (specified in the configuration file) with IBM Watson IoT Platform service.
37+
*
38+
*/
39+
40+
#include <stdio.h>
41+
#include <signal.h>
42+
#include <memory.h>
43+
#include <stdlib.h>
44+
#include <unistd.h>
45+
46+
/* Include header file of IBM Watson IoT platform C Client for devices */
47+
#include "iotp_device.h"
48+
49+
char *configFilePath = NULL;
50+
volatile int interrupt = 0;
51+
char *progname = "deviceSample";
52+
int useEnv = 0;
53+
int testCycle = 0;
54+
55+
/* Usage text */
56+
void usage(void) {
57+
fprintf(stderr, "Usage: %s --config config_file_path\n", progname);
58+
exit(1);
59+
}
60+
61+
/* Signal handler - to support CTRL-C to quit */
62+
void sigHandler(int signo) {
63+
signal(SIGINT, NULL);
64+
fprintf(stdout, "Received signal: %d\n", signo);
65+
interrupt = 1;
66+
}
67+
68+
/* Get and process command line options */
69+
void getopts(int argc, char** argv)
70+
{
71+
int count = 1;
72+
73+
while (count < argc)
74+
{
75+
if (strcmp(argv[count], "--config") == 0)
76+
{
77+
if (++count < argc)
78+
configFilePath = argv[count];
79+
else
80+
usage();
81+
}
82+
if (strcmp(argv[count], "--useEnv") == 0) {
83+
useEnv = 1;
84+
}
85+
if (strcmp(argv[count], "--testCycle") == 0) {
86+
if (++count < argc)
87+
testCycle = atoi(argv[count]);
88+
else
89+
usage();
90+
}
91+
count++;
92+
}
93+
}
94+
95+
/*
96+
* Device command callback function
97+
* Device developers can customize this function based on their use case
98+
* to handle device commands sent by WIoTP.
99+
* Set this callback function using API setCommandHandler().
100+
*/
101+
void deviceCommandCallback (char* type, char* id, char* commandName, char *format, void* payload, size_t payloadSize)
102+
{
103+
fprintf(stdout, "Received device command:\n");
104+
fprintf(stdout, "Type=%s ID=%s CommandName=%s Format=%s Len=%d\n",
105+
type?type:"", id?id:"", commandName?commandName:"", format?format:"", (int)payloadSize);
106+
fprintf(stdout, "Payload: %s\n", payload?(char *)payload:"");
107+
108+
/* Device developers - add your custom code to process device commands */
109+
}
110+
111+
void logCallback (int level, char * message)
112+
{
113+
if ( level > 0 )
114+
fprintf(stdout, "%s\n", message? message:"NULL");
115+
fflush(stdout);
116+
}
117+
118+
void MQTTTraceCallback (int level, char * message)
119+
{
120+
if ( level > 0 )
121+
fprintf(stdout, "%s\n", message? message:"NULL");
122+
fflush(stdout);
123+
}
124+
125+
/* Main program */
126+
int main(int argc, char *argv[])
127+
{
128+
int rc = 0;
129+
int cycle = 0;
130+
131+
/*
132+
* DEV_NOTES:
133+
* Specifiy variable for WIoT client object
134+
*/
135+
IoTPConfig *config = NULL;
136+
IoTPDevice *device = NULL;
137+
138+
/* check for args */
139+
if ( argc < 2 )
140+
usage();
141+
142+
/* Set signal handlers */
143+
signal(SIGINT, sigHandler);
144+
signal(SIGTERM, sigHandler);
145+
146+
/* get argument options */
147+
getopts(argc, argv);
148+
149+
/* Set IoTP Client log handler */
150+
rc = IoTPConfig_setLogHandler(IoTPLog_FileDescriptor, stdout);
151+
if ( rc != 0 ) {
152+
fprintf(stderr, "WARN: Failed to set IoTP Client log handler: rc=%d\n", rc);
153+
exit(1);
154+
}
155+
156+
/* Create IoTPConfig object using configuration options defined in the configuration file. */
157+
rc = IoTPConfig_create(&config, configFilePath);
158+
if ( rc != 0 ) {
159+
fprintf(stderr, "ERROR: Failed to initialize configuration: rc=%d\n", rc);
160+
exit(1);
161+
}
162+
163+
/* read additional config from environment */
164+
if ( useEnv == 1 ) {
165+
IoTPConfig_readEnvironment(config);
166+
}
167+
168+
/* Create IoTPDevice object */
169+
rc = IoTPDevice_create(&device, config);
170+
if ( rc != 0 ) {
171+
fprintf(stderr, "ERROR: Failed to configure IoTP device: rc=%d\n", rc);
172+
exit(1);
173+
}
174+
175+
/* Set MQTT Trace handler */
176+
rc = IoTPDevice_setMQTTLogHandler(device, &MQTTTraceCallback);
177+
if ( rc != 0 ) {
178+
fprintf(stderr, "WARN: Failed to set MQTT Trace handler: rc=%d\n", rc);
179+
}
180+
181+
/* Invoke connection API IoTPDevice_connect() to connect to WIoTP. */
182+
rc = IoTPDevice_connect(device);
183+
if ( rc != 0 ) {
184+
fprintf(stderr, "ERROR: Failed to connect to Watson IoT Platform: rc=%d\n", rc);
185+
fprintf(stderr, "ERROR: Returned error reason: %s\n", IOTPRC_toString(rc));
186+
exit(1);
187+
}
188+
189+
/*
190+
* Set device command callback using API IoTPDevice_setCommandsHandler().
191+
* Refer to deviceCommandCallback() function DEV_NOTES for details on
192+
* how to process device commands received from WIoTP.
193+
*/
194+
IoTPDevice_setCommandsHandler(device, deviceCommandCallback);
195+
196+
/*
197+
* Invoke device command subscription API IoTPDevice_subscribeToCommands().
198+
* The arguments for this API are commandName, format, QoS
199+
* If you want to subscribe to all commands of any format, set commandName and format to "+"
200+
*/
201+
char *commandName = "+";
202+
char *format = "+";
203+
IoTPDevice_subscribeToCommands(device, commandName, format);
204+
205+
206+
/* Use IoTPDevice_sendEvent() API to send device events to Watson IoT Platform. */
207+
208+
/* Sample event - this sample device will send this event once in every 10 seconds. */
209+
char *data = "{\"d\" : {\"SensorID\": \"Test\", \"Reading\": 7 }}";
210+
211+
while(!interrupt)
212+
{
213+
fprintf(stdout, "Send status event\n");
214+
rc = IoTPDevice_sendEvent(device,"status", data, "json", QoS0, NULL);
215+
fprintf(stdout, "RC from publishEvent(): %d\n", rc);
216+
217+
if ( testCycle > 0 ) {
218+
cycle += 1;
219+
if ( cycle >= testCycle ) {
220+
break;
221+
}
222+
}
223+
sleep(10);
224+
}
225+
226+
fprintf(stdout, "Publish event cycle is complete.\n");
227+
228+
/* Disconnect device */
229+
rc = IoTPDevice_disconnect(device);
230+
if ( rc != IOTPRC_SUCCESS ) {
231+
fprintf(stderr, "ERROR: Failed to disconnect from Watson IoT Platform: rc=%d\n", rc);
232+
exit(1);
233+
}
234+
235+
/* Destroy client */
236+
IoTPDevice_destroy(device);
237+
238+
/* Clear configuration */
239+
IoTPConfig_clear(config);
240+
241+
return 0;
242+
243+
}
244+
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"guid": "CF755377-7B46-47D3-89A3-AB624692B2E8",
3+
"name": "IBM Device",
4+
"categories": ["Toolkit/Intel® oneAPI IoT Toolkit/IoT Connection Tools"],
5+
"description": "This project shows how-to develop a device code using Watson IoT Platform iot-c device client library, connect and interact with Watson IoT Platform Service.",
6+
"dependencies": ["iot-c|https://github.com/ibm-watson-iot/iot-c"],
7+
"languages": [{"cpp":{}}],
8+
"os": ["linux"],
9+
"ciTests": {
10+
"linux": [
11+
{ "id": "ibm-device",
12+
"env": [],
13+
"steps": [
14+
"mkdir build",
15+
"cd build",
16+
"cmake ..",
17+
"make"
18+
]
19+
}
20+
]
21+
}
22+
}

0 commit comments

Comments
 (0)