LoginSignup
0
1

More than 1 year has passed since last update.

Cloud Firestoreにraspberry piからデータを追加する

Last updated at Posted at 2021-08-21

はじめに

FirebaseにRaspberry Piからデータを突っ込む方法を記載します。

環境

  • macOS Big Sur 11.5
  • Raspberry Pi Zero WH(Raspberry Pi OS)
  • Firestore
  • macOS(Python):3.8.5
  • RaspBerryPi(Python):3.7.5

Firebase環境の構築等は今回は説明を省略します。Firebaseの状態は以下の通りです。
firebaseImg.jpg

手順

  1. macでFirebaseにデータを追加する
  2. RaspBerryPiでFirebaseにデータを追加する

1. macでFirebaseにデータを追加する

1-1. ドキュメントのフィールド値を決める
定期的に温度をFirebaseに上げる仕組みとするため、具体的に以下のようにFirebaseの値を決める

  • Collection: Environment
  • Document: 自動
  • Field: temperatura,time

1-2. Firebaseへアクセスする環境を整える

reportTemperature
import time
import datetime
import os
import csv

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
from firebase_admin import storage

cred = credentials.Certificate("Firebase秘密鍵")

app = firebase_admin.initialize_app(cred)

db = firestore.client()

today = datetime.datetime.fromtimestamp(time.time())
date  = today.strftime('%Y%m%d%H%M%S')

data = {
     u'time':date,
     u'temparature':35.5 #この値はデバイスから取得するよう変更が必要
}

db.collection(u'environment').add(data)

2. RaspBerryPiでFirebaseにデータを追加する

2-1. macでFirebaseにデータを追加するにデータを追加するで作成したreportTemperatureをraspberry piにアップロードする

今回は、「reportTemperature.py」と「Firebase秘密鍵」の2種類

scp -P 22 reportTemperature.py pi@raspberrypi.local:/home/pi
scp -P 22 Firebase秘密鍵 pi@raspberrypi.local:/home/pi

2-2. Raspberry Pi でも1-2の初期設定を行う
2-3. Raspberry Pi をテザリングまたはWirelessLANで繋ぐ
テザリングまたはWirelessLANの設定は、@hishi さんのRaspberry Pi Zero(W, WH)のセットアップを参照
2-4. 動作確認を行う

まとめ

先人の情報を使用して、ほとんど困らずに温度を更新する仕組みができた。Firebaseのデータベース定義について、定石がわからないが、今回のデータではドキュメント名を自動でふり、そのフィールドに時間と温度を持たせることでコレクションとして扱うことにした。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1