IoTサービスへのデータ送信 (Spresense)
サンプルソースコード
概要
IIJ IoTの基本動作である、データ送信を実装してみます。
当サンプルでは、httpプロトコルを使用して、定期的にIIJ IoTサービスにデータ送信を行います。
今回は、乱数値を送信しています。
ソースコード
spresense_iijiot_datasend.ino
#include <LTE.h>
#include <LTEClient.h>
#include <ArduinoHttpClient.h>
#include <Arduino_JSON.h>
//--- TODO: 使用するSIMのAPN情報に書き換えてください。
const char apn[] = "iot.iijmobile.jp"; // "h.iijmobile.biz";
const char lte_user[] = "mobile@iot";
const char lte_pass[] = "iot";
//---
const int delay_sec = 60;
const char* iij_iot_host = "gw.iot.iij.jp";
const char* iij_iot_path = "/v1";
LTE lteAccess;
LTEClient client;
/*
setup関数
*/
void setup() {
Serial.begin(115200);
Serial.println("\nstart.");
delay(3000);
while (true) {
//LTE接続
if (lteAccess.begin() == LTE_SEARCHING) {
if (lteAccess.attach(apn, lte_user, lte_pass) == LTE_READY) {
Serial.println("attach succeeded.");
break;
}
Serial.println("An error occurred, shutdown and try again.");
lteAccess.shutdown();
sleep(1);
}
}
//乱数を初期化
randomSeed(lteAccess.getTime());
}
/*
IIJ IoTサービスにデータ送信する
引数
const char* ns : 送信する namespace値
const char* name : 送信する name値
const double value : 送信する value値
戻り値
bool true:送信成功 false:送信失敗
*/
bool send_data(const char* ns, const char* name, const double value) {
//JSONオブジェクトを作成
JSONVar body;
if (ns != nullptr && strlen(ns) > 0) {
body["namespace"] = ns;
}
body["name"] = name;
body["value"] = value;
//JSONを文字列に変換
String body_string = JSON.stringify(body);
Serial.println("POST: " + body_string);
//JSON文字列をIIJ IoTサービスにPOST
HttpClient http(client, iij_iot_host, 80);
http.beginRequest();
http.post(iij_iot_path);
http.sendHeader("Content-type", "application/json");
http.sendHeader("Content-length", body_string.length());
http.beginBody();
http.print(body_string);
http.endRequest();
int status_code = http.responseStatusCode();
return status_code >= 200 && status_code < 300;
}
/*
loop関数
*/
void loop() {
//乱数を生成する
int value = random(10000);
//データ送信する
bool ok = send_data("spresense", "test", value);
Serial.println(ok ? "OK" : "NG");
//待つ
delay(delay_sec * 1000L);
}
実行結果
Spresenseは、LTE回線接続後、60秒ごとに乱数をデータ送信します。結果はシリアルモニタに出力されます。
start.
attach succeeded.
POST: {"namespace":"spresense","name":"test","value":6012}
OK
POST: {"namespace":"spresense","name":"test","value":538}
OK
IIJ IoTサービスのコントロールパネルにログインし、デバイスモニタリングの画面を確認すると、送信したデータのグラフが表示されていることが確認できます。

各種情報へのリンク
IIJ IoTサービスマニュアル
Spresense
Arduino_JSON
ArduinoHttpClient