the invention of t88

工作、資格取得、データ分析のことなど

ラズパイで取得したデータをAmbientに上げる

水耕栽培器IoT化(第7回)

前回までで立ち上げた、温湿度センサとCO2センサで取得したデータをネットに上げます。 データを保存します。あまつさえ可視化します。Ambientを使って。

https://ambidata.io/

AmbientはIoTデーターの可視化サービスです。
マイコンなどから送られるセンサーデーターを受信し、蓄積し、可視化(グラフ化)します。

Ambient初期登録

Ambientを使ってみる – Ambient に沿って。

ユーザ登録する

メールアドレス、パスワードを登録するだけ。

チャネルを作る

チャネル、というのが一つのグループ単位のようです。

1つ作成し、設定でチャネル名を変更してみた。 f:id:take213uv:20181228062139p:plain

pythonスクリプトを改良する

これまで作成したセンサ読み取り用スクリプトを一つのスクリプトにまとめます。 併せて、Ambientへのデータ送信機能を付け足します。

import Adafruit_DHT as DHT
from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN

import serial
import time
import subprocess
import slider_utils as slider
import getrpimodel

import ambient

'''
温湿度センサ
'''
# センサー種類
SENSOR_TYPE = DHT.DHT22
# GPIOポート
DHT_GPIO = 22

# 測定
h,t = DHT.read_retry(SENSOR_TYPE, DHT_GPIO)

# 四捨五入
h = Decimal(h).quantize(Decimal('0.1'), rounding=ROUND_HALF_UP)
t = Decimal(t).quantize(Decimal('0.1'), rounding=ROUND_HALF_UP)



'''
CO2濃度センサ
'''
# setting
if getrpimodel.model() == "3 Model B":
  serial_dev = '/dev/ttyS0'
  stop_getty = 'sudo systemctl stop serial-getty@ttyS0.service'
  start_getty = 'sudo systemctl start serial-getty@ttyS0.service'
else:
  serial_dev = '/dev/ttyAMA0'
  stop_getty = 'sudo systemctl stop serial-getty@ttyAMA0.service'
  start_getty = 'sudo systemctl start serial-getty@ttyAMA0.service'

def mh_z19():
  try:
    ser = serial.Serial(serial_dev,
                        baudrate=9600,
                        bytesize=serial.EIGHTBITS,
                        parity=serial.PARITY_NONE,
                        stopbits=serial.STOPBITS_ONE,
                        timeout=1.0)
    while 1:
      result=ser.write("\xff\x01\x86\x00\x00\x00\x00\x00\x79")
      s=ser.read(9)
      if len(s) >= 4 and s[0] == "\xff" and s[1] == "\x86":
        return {'co2': ord(s[2])*256 + ord(s[3])}
      break
  except IOError:
    slider.io_error_report()
  except:
    slider.unknown_error_report()

def read():
  p = subprocess.call(stop_getty, stdout=subprocess.PIPE, shell=True)
  result = mh_z19()
  p = subprocess.call(start_getty, stdout=subprocess.PIPE, shell=True)
  if result is not None:
    return {'CO2': result["co2"]}

value = read()
c = value["CO2"]


'''
Ambient
'''
ambi = ambient.Ambient(8637, "ライトキー")
r = ambi.send({"d1":t,"d2":h,"d3":c})

インスタンス作って、.sendで送るだけ。めちゃくちゃ簡単ですね。

スクリプトを実行すると、こんな感じでデータがあがっています。

f:id:take213uv:20190101021850p:plain

cronを使って定期送信させる

定期的にデータを取得したいので、cronを使います。
crontab -e でcrontabファイルを開いて、その中に

*/5 * * * * sudo python data_logging.py  

と書き込み。これで5分ごとスクリプトが走ります。

仕上げ

設定でグラフタイトルを変更。

f:id:take213uv:20190101022931p:plain

公開設定に変更。
https://ambidata.io/ch/channel.html?id=8637

おわりに

Ambientを使うことですごく簡単にセンサデータのロギングや可視化が出来ました。 あとはカメラのデータについて対応すれば、いよいよ水耕栽培器立ち上げです。


前の記事:ラズパイ×MH-Z19でCO2濃度測定
次の記事:ラズパイのカメラ画像をGoogle Driveに上げる
水耕栽培器IoT化 目次