2016年6月13日月曜日

RaspberryPI3とMilkCocoaを連携させてみる。

RaspberryPI3とMilkCocoaを連携させてみる。

Raspberry PI3で測定した温度をリアルタイムに表示する手段を探していたところMilkCocoaというサービスがあったので試してみました。

温度はDHT11を使ったので、Adafruit_Python_DHTを使いました。
Adafruit_Python_DHTの使い方は調べればでてくるのでそちらを参照。

MilkCocoaの準備

1.MilkCocoaでユーザー登録し、dashboardから新しいアプリを作るをクリック。

enter image description here

2.App Nameを入力し、新しいアプリを作るをクリック。

enter image description here

3.認証をクリックし、API Key認証新しいAPI KeyとAPI Secretのペアを生成するをクリック

enter image description here

4.データストアをクリックし、名前を入力。
ここではtempとした。
enter image description here

Raspberry PI側のPythonの準備

1.PythonSDKのインストール
 これを参考にインストール

2.APP_ID, API_KEY,SECRET,DB_NAME(datastore名)を以下のようにpythonのコード(dht11_milkcocoa.py)に入れる。
APP_IDは以下に記載のものです。
enter image description here

#! /usr/bin/python3

import Adafruit_DHT
import time
import milkcocoa.milkcocoa as milkcocoa

APP_ID = 'xxxxxx'
API_KEY = 'xxxxxx'
SECRET = 'xxxx'
DB_NAME = 'temp'

def add_count_record(temperature,humidity):
    try:
        mc_client = milkcocoa.Milkcocoa.connectWithApiKey(APP_ID, API_KEY, SECRET, useSSL=False)
        datastore = mc_client.datastore(DB_NAME)
        datastore.push({"temperature": temperature, "humidity": humidity})
    except Exception as e:
        print(e)

def main():
    counter = 0

    while True:
        counter += 1

        # 30秒ごとに検知回数をMilkcocoaに送信
        if counter == 30:
            humidity, temperature = Adafruit_DHT.read_retry(11, 4)
            add_count_record(temperature,humidity)
            print("Temp={0:0.1f}, Hum={1:0.1f}" .format(temperature,humidity))
            counter = 0

        time.sleep(1.0)

if __name__ == '__main__':
    main()

3.pythonを実行

$ sudo python3 ./dht11_milkcocoa.py

4.データストアの確認
リスト表示(更新)を押して以下のようにデータがでればMilkCocoaにデータが送られている。
enter image description here

MilkCocoaでのグラフ化

1.データストアでデータ可視化をクリック

2.DATASOURCESの下のAddをクリックし、以下を入力
 TYPE: Milkcocoa
 NAME: 温度(自由に記載OK)
 DATASTORE: temp
 API: push
enter image description here

3.ADD PANEで以下を追加
TYPE: Sparkline
TITLE: 温度(自由に記載可能)
VALUE: datasource[“Temp”][“value”][“temperature”]
INCLUDE LEGEND: YES
LEGEND: detection temperature/30sec

enter image description here

4.一度に表示する個数の設定。
以下の工具マークをクリックし、Columnsの値を設定することで表示するサンプル数を決められる。
enter image description here

参考
http://yura2.hateblo.jp/entry/2016/02/29/PIR%E3%82%BB%E3%83%B3%E3%82%B5(SB00412A-1)%E3%81%A8Milkcocoa%E3%81%A7%E7%B0%A1%E6%98%93%E8%A6%8B%E5%AE%88%E3%82%8A%E3%82%B7%E3%82%B9%E3%83%86%E3%83%A0%E3%82%92%E6%A7%8B%E7%AF%89

0 件のコメント :

コメントを投稿