LoginSignup
9
9

More than 5 years have passed since last update.

Product for Google IoT Solutions - Firebaseとraspberry piをリアルタイムで通信してみる

Last updated at Posted at 2016-01-05

概要

  • Product for Google IoT Solutions - Firebaseを触ってみた に、Firebaseを利用して、クライアント(ブラウザ)とサービス(firebase)の間に、リアルタイムで通信してみました。
  • 今回は、IoTを考えて、デバイス(例:raspberry pi+switch button) <-> サービス <-> クライアント(例:ブラウザ)の構成で、リアルタイム通信を行います。
  • 具体的は、switchボタンを押して、ブラウザは、ボタンのon/offを検知できることです。

システム構成

無題の図形描画.png

  • switchボタンを、raspberry piと接続して、ボタンを押す時に、raspberry piから検知できます。(具体的なやり方は、後に説明します。)
  • raspberry piは、ネットワーク経由して、firebaseサーバーと接続します。
  • ブラウザも、ネットワーク経由して、firebaseサーバーと接続します。

Firebaseサーバーとクライアント(ブラウザ)

raspberry pi

aa

OS構成

pi@raspberrypi:~ $ uname -a
Linux raspberrypi 4.1.13-v7+ #826 SMP PREEMPT Fri Nov 13 20:19:03 GMT 2015 armv7l GNU/Linux

pi@raspberrypi:~ $ cat /etc/debian_version
8.0

switchボタン接続

  • 実物
    ボード接続

  • 平面図
    raspberrypi-typeb.png

    • GPIO-18番(pin: 12番)は、switchボタンと接続します。
    • GND(pin: 6番)は、switchボタンと接続します。

nodejsとnpm

  • nodejsバージョン
    • 5.3.0
  • npmパッケージ
    • firebase : 2.3.2
    • pi-gpio : 0.0.8 - Raspberry PiのGPIOへアクセスするためのライブラリ

実装

var gpio = require('pi-gpio');
var Firebase = require('firebase');

var pin = 12;
var host = "<firebase APP URL>";
var myFirebaseRef = new Firebase(host);

gpio.open(pin, "input", function(err) {
    intervalId = setInterval( function(){
        gpio.read(pin, function(err, v) {
            if ( v == 1 ) {
                myFirebaseRef.set({'title': 'button off'});
                console.log('button off');
            } else {
                myFirebaseRef.set({'title': 'button on'});
                console.log('button on');
            };
        });
    }, 100);
});

説明

  • raspberry piと接続しているPIN12番(GPIO 18番)です。
  • 0.1秒に、1回に12番のpinから、データを読み込みます。
  • 1の場合は、switchボタンがoffです。
    • firebaseのtitle値を、'button off'に設定します。
  • 0の場合は、switchボタンが押されて、onに表示されます。
    • firebaseのtitle値を、'button on'に設定します。

デモ

demo

9
9
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
9
9