
こちらの記事について、内容・翻訳・視点・長さなど、皆様のご意見をお送りください。今後の記事製作の参考にしたいと思います。

Thank you! Your feedback has been received.

There was a problem submitting your feedback, please try again later.

こちらの記事の感想をお聞かせください。
部品リスト
Qty | Product | 品番 | |
---|---|---|---|
1 | XinaBox SW03 気象センサモジュール for MPL3115A2 | 174-3746 | |
1 | XinaBox xCHIP Wi-Fi & Bluetooth Core Module CW02 | ||
1 | XinaBox インターフェース開発キット USB Programming Interface モジュール for FT232R | 174-3703 | |
1 | Zerynth Studio | ||
1 | OKdo Cloud | ||
前パートPart 1: Introduction and Simple Example では、Zerynth StudioでXinaBoxをプログラムする方法を説明した。このパートでは、XinaBoxからOKdo Cloudにデータを送信する方法、SW03センサーからデータを取得する方法、およびOKdo Cloudでダッシュボードを構築する方法を解説する。
その他必要なもの
- WiFiアクセス資格情報(SSIDおよびパスワード。今回はスマートフォンをWi-Fiホットスポットとして使用)
- OKdo Cloud のアカウント
OKdo Cloud とは?
OKdoは、IoTに焦点を当てた、新しくグローバルな技術系企業である。 OKdo Cloudはそのサービスの1つだ。 OKdo Cloudは、モノをネットワークに接続して双方向に通信するためのIoTクラウドプラットフォームを提供する。 OKdo CloudのGUIはシンプルで使いやすい。独自のダッシュボード(OKdo Cloudでは「Pinboard」と呼ぶ)を構築して、受信したすべてのデータを表示することができる。 OKdo CloudのAPIを利用すれば、わずか数ステップでモノを接続し、データを取得し、結果を視覚化することができる。そしてなにより嬉しいことに、OKdo Cloudは無料である。
OKdo Cloudの詳細については、以下のリンクを参照してほしい。
OKdo Cloudのアカウントを作成する
メールアドレス・ユーザー名・パスワードを入力して https://okdo.allthingstalk.com/ にサインアップする。
ログイン後、次のようなページが表示される。
okdo.comのプロジェクトページには、
「OKdo Cloudは、メンバーとデバイスを「Grounds」に編成します。これはデータアクセスとデバイスを管理するのに最適な形式です。 OKdo Cloudは、サインアップ後に「Playground」と呼ばれる最初のGroundを自動的に作成します。」
とある。
デバイスを接続してOKdo Cloudをセットアップする
自分のGroundを作成するか、デフォルトのGroundを使用する。
新しいGroundを作成するには、「+ NEW GROUND」をクリックする。名前を入力し、「CREATE」をクリックすると、次に進める。
「+ CONNECT A DEVICE」をクリックしたら「Your own device」を選択し、希望するデバイス名を入力する。その後、「CONNECT」をクリックする。
次に、新しい「Device Assets」を作成して、デバイスが送信したデータをOKdo Cloudが受信できるようにする。下図のように名前に「random」と入力し、タイプは「Number」を選択したら、「CREATE ASSET」をクリックすれば完了だ。
つぎは、XinaBoxからデータを受け取れるようにするための手順を解説する。
XinaBoxを接続する
この節でなにか不明な点があれば、まず前パートの Part 1: Introduction and Simple Example を参照してほしい。
XinaBoxのモジュールを下の画像のように接続する。
- CW02をUSBプログラミングインターフェイスモジュールIP01に接続する
-
SW03気象センサーをCW02に接続する
- XinaBoxをUSB経由でコンピューターに接続する
XinaBoxのプログラミング
この節でなにか不明な点があれば、まず前パートの Part 1: Introduction and Simple Example を参照してほしい。
Zerynth Studioを起動し、OKdo Cloud→Mqttのサンプルコードを利用するか、プロジェクトを作成して以下のコードをコピーする。
################################################################################
# MQTT at OKDO Cloud IoT
#
# Created at 2019-05-06 08:40:34.990336
#
################################################################################
import streams
from wireless import wifi
# choose a wifi chip (esp32)
from espressif.esp32net import esp32wifi as wifi_driver
# let's import the OKDO cloud modules; first the IoT module...
from okdo.iot import iot
# ...then the mqtt client
from okdo.iot import mqtt_client
# Let's define a global variable to store the publishing rate (in ms)
rate = 3000
# Customize the following variables
ssid = "SSID" # this is the SSID of the WiFi network
wifipwd = "Password" # this is the Password for WiFi
device_id = "device_id" # this is the device identifier. Can be obtained from the OKDO cloud dashboard
device_token = "device_token" # this is the device token. Can be obtained from the OKDO cloud dashboard
# Remember to add a device to your okdo cloud and define some assets:
# - a "rate" actuator, with type integer
# - a "random" sensor of type integer
def rate_cb(asset,value, previous_value):
global rate
value = int(value)
if value<1000:
value=1000
rate=value
print("Rate changed to",rate,"ms")
streams.serial()
try:
# Let's initialize the WiFi
wifi_driver.auto_init()
for _ in range(0,5):
# put your SSID and password here
try:
wifi.link(ssid,wifi.WIFI_WPA2,wifipwd)
break
except:
print("Trying to connect...")
sleep(2000)
else:
print("oops, can't attach to wifi!")
raise IOError
print("Connecting to OKDO IoT Cloud...")
# let's create a device passing the id, the token and the type of client
device = iot.Device(device_id,device_token,mqtt_client.MqttClient)
device.connect()
print("Device is connected")
# define the callbacks to call when an asset command is received
device.watch_command("rate",rate_cb)
# start the device
device.run()
print("Device is up and running")
while True:
# sleep as indicated by rate
sleep(rate)
x = random(0,100)
msg = device.publish_asset("random",x)
print("Published asset",msg)
# alternatively, you can publish more than one asset state at a time
# by providing them as a dictionary to the following function (uncomment to test)
# msg = device.publish_state({"random":x})
# print("Published state",msg)
except Exception as e:
print(e)
コードを見てほしい。関数「device.publish_asset(" random "、x)」は、ペイロード( "random":{value})を含むMQTTパケットをOKdo Cloudに送信する。 つまりこれは、OKdo Cloudにデータを送信する関数だ。
msg = device.publish_asset("random",x)
また、コードの中で変更するべき箇所が4点ある。それはSSID・パスワード・device_id・device_tokenだ。 SSIDとパスワードは、使用するWi-Fiネットワークのものを記述する。私は自分のスマートフォンをWi-Fiホットスポットとして使用した。もちろん、スマートフォンは4Gセルラーネットワーク経由でインターネットに接続されている。 そしてdevice_idおよびdevice_tokenは、クラウド内のデバイス認証に関する固有の情報だ。そのため、これらはデバイスごとに異なる。デバイスIDとデバイストークンはOKdo Cloudで取得できる。
ブラウザに戻ろう。作成したGround(私は「A Ground」とした)内で、左側の「DEVICE」タブを見つけ、前の節で設定したデバイスをクリックする。このとき、ページは下図のように表示されているだろう。
右上隅にある「Setting」から「Authentication」をクリックして、デバイスIDとトークンを表示する。これらは、数字・記号・小文字と大文字を含む固有の文字列で、OKdoによって割り当てられたものだ。下図のようなページで表示される。
以上4つの変更点を確認したら、以下のように各変数を変更する。
# Customize the following variables
ssid = "Rxxxxxxxs" # this is the SSID of the WiFi network
wifipwd = "axxxx" # this is the Password for WiFi
device_id = "MxxxxxxxxxxxxQ" # this is the device identifier. Can be obtained from the OKDO cloud dashboard
device_token = "maker:4QRxxxxxJo0" # this is the device token. Can be obtained from the OKDO cloud dashboard
Zerynth Studioでコードを確認してボードに書き込む。コンソールを開くと、下図のような結果が表示されるだろう。繰り返しになるが、ZerynthとXinaBoxのことでつまづいたら、Part 1: Introduction and Simple Example を参照してほしい。
OKdo Cloudに戻ろう。 「random」の左側に数字が表示される。「LIVE」または「CHARTS」をクリックすれば、時系列のプロットが確認できる(「LIVE」または「CHARTS」にデータが表示されない場合は、しばらく待ってからブラウザでページを更新するか、XinaBoxをPC USBに抜き差ししてみてほしい)。
「CHARTS」では、下図のようにプロットが表示されないことがある。その場合は、OKdo Cloudにデータを保存できるよう、「Data storage」機能をオンにすればよい。
Data storageをオンにするには、右上隅の「SETTINGS」→「Data」カテゴリの「Data storage」→「Store Device Data」の順にクリックする。すると機能が有効になったことを示す緑色の通知バーが下部に表示される。
すると、OKdo Cloudで過去のデータを含むすべてのデータをプロットできる。 (ここでも、データが表示されない場合はしばらく待ってからブラウザでページを更新するか、XinaBoxをPC USBに抜き差ししてみてほしい)
オンラインダッシュボード「Pinboard」の作成
OKdo Cloudの「Pinboard」では、表示するデータの選択と、どのようにデータを視覚化するかの設計が可能だ。下のビデオではPinboardの作成方法を紹介している。
SW03気象センサーからのデータ取得
SW03からのデータの取得は、すでにコードがあるので簡単だ。 Zerynth Studioで「Examples」から「SW03」と検索してコードをコピーすればよい。プロジェクト「environment data」をコピーし、XinaBoxに書き込む。結果はコンソールで表示できる。
コードは以下の通りだ。
##############################################
# This is an example for SW03 ambient
# temperature, altitude and pressure
# sensor.
#
# Ambient temperature, altitude and pressure
# is measured and printed out on the console.
##############################################
import streams
from xinabox.sw03 import sw03
streams.serial()
# SW03 instance
SW03 = sw03.SW03(I2C0)
# configure SW03
SW03.init()
while True:
temp = SW03.getTempC() # return temp in degree celcius
alt = SW03.getAltitude() # return alitude in meters
pres = SW03.getPressure() # return pressure in pascals
print('Temperature: ', temp, ' C')
print('Altitude : ', alt, ' m')
print('Pressure : ', pres, ' Pa')
sleep(1000)
コンソールにはつぎのように表示されるだろう:
SW03センサーで取得したデータをOKdo Cloudに送信する
データをOKdo Cloudに送信するコードとSW03センサーデータを取得するコードは別のため、ここで二つのコードをマージする。そうすれば、センサーデータがOKdo CloudのPinboardに表示できるようになる。マージした後のコードは次のとおりだ。
前述の通り、SSID・パスワード・device_id・device_tokenは変更する必要がある。
# xinabox_zerynth_okdo_mqtt
# Created at 2019-08-14 08:36:17.078318
#################### SETTING 1 <BEGIN> ####################
## Uploading data to OKDO Cloud
## Example: MQTT at OKDO Cloud IoT
import streams
from wireless import wifi
# choose a wifi chip (esp32)
from espressif.esp32net import esp32wifi as wifi_driver
# let's import the OKDO cloud modules; first the IoT module...
from okdo.iot import iot
# ...then the mqtt client
from okdo.iot import mqtt_client
# Let's define a global variable to store the publishing rate (in ms)
rate = 3000
# Customize the following variables
ssid = "Rxxxxxxxxxs" # this is the SSID of the WiFi network
wifipwd = "axxxxx4" # this is the Password for WiFi
device_id = "Qxxxxxxxxxxxxxx3" # this is the device identifier. Can be obtained from the OKDO cloud dashboard
device_token = "maker:4xxxxxxxxxxxP" # this is the device token. Can be obtained from the OKDO cloud dashboard
# Remember to add a device to your okdo cloud and define some assets:
# - a "rate" actuator, with type integer
# - a "random" sensor of type integer
def rate_cb(asset,value, previous_value):
global rate
value = int(value)
if value<1000:
value=1000
rate=value
print("Rate changed to",rate,"ms")
streams.serial()
#################### SETTING 1 <END> ####################
#################### SETTING 2 <BEGIN> ####################
## Collecting ambient temperature, altitude and pressure sensor.
## Example: environmental_data, for SW03 weather sensor
#import streams
from xinabox.sw03 import sw03
#streams.serial()
# SW03 instance
SW03 = sw03.SW03(I2C0)
# configure SW03
SW03.init()
#################### SETTING 2 <END> ####################
# As a counter
a=0
try:
# Let's initialize the WiFi
wifi_driver.auto_init()
for _ in range(0,5):
try:
wifi.link(ssid,wifi.WIFI_WPA2,wifipwd)
break
except:
print("Trying to connect...")
sleep(2000)
else:
print("oops, can't attach to wifi!")
raise IOError
print("Connecting to OKDO IoT Cloud...")
# let's create a device passing the id, the token and the type of client
device = iot.Device(device_id,device_token,mqtt_client.MqttClient)
device.connect()
print("Device is connected")
# define the callbacks to call when an asset command is received
device.watch_command("rate",rate_cb)
# start the device
device.run()
print("Device is up and running")
while True:
# sleep as indicated by rate
sleep(rate)
############ Modified code <BEGIN> ############
###### SW03 weather sensor <BEGIN> ######
temp = SW03.getTempC() # return temp in degree celcius
alt = SW03.getAltitude() # return alitude in meters
pres = SW03.getPressure() # return pressure in pascals
###### SW03 weather sensor <END> ######
a=a+1
print("#", a)
msg = device.publish_asset("temperature",temp)
print("Published asset: Temperature",msg)
msg = device.publish_asset("altitude",alt)
print("Published asset: Altitude",msg)
msg = device.publish_asset("pressure",pres)
print("Published asset: Pressure",msg)
print(".")
print(".")
# alternatively, you can publish more than one asset state at a time
# by providing them as a dictionary to the following function (uncomment to test)
# msg = device.publish_state({"random":x})
# print("Published state",msg)
############ Modified code <END> ############
except Exception as e:
print(e)
コンソールにはつぎのように表示されるだろう:
新たなPinboardがOKdo Cloud上に作成される。最後になるが、下のビデオはPinboardに表示される結果を詳細に解説している。
ライターのその他の記事
1. Building a Hill Fire Detection IoT with LoRa
2. Connecting XinaBox IoT with Zerynth to Cloud
Part 1: Introduction and Simple Example
Part 2: Uploading Data to OKdo Cloud and Visualising Data
3. XinaBox Weather Station with ubidots Cloud