LoginSignup
3

More than 1 year has passed since last update.

posted at

updated at

アレクサとRaspberryPiで部屋の照明を操作する

はじめに

スマートスイッチは、便利ではあるもののまだまだ普及しておらず、買うとなると少々ためらう価格設定です。
ですが、プログラミングが少しできれば、RaspberryPiとモーターを使って手軽に安く自作することができます。
しかも、セールの時に買ったAlexaを私は持ってるので、これを使えば声で簡単に操作できそうです。
よって、今回はその方法についてまとめました。
プログラミングができなくても手順通りやれば作れるので、よかったら挑戦してみてください(自己責任で)。
※室内からの操作を想定しています。外出先から操作したい場合は、IFTTTなどを使って改造してみてください。

環境

  • OS : Raspbian Buster
    ※RaspbianはRaspberryPiOSに改名されましたが、私の手元にあるRaspberryPiにはRaspbianBuster時代のものをインストールしてあります。
  • 実行デバイス : Raspberry Pi 4B (4GB)
  • Alexa : Echo Dot 第3世代
  • DCサーボモーター : Tower Pro SG92R Micro servo

全体図

LightSwitcher_Image.png

回路図

LightSwitcher_Diagram.png

事前準備

事前準備1

下記の記事を参考に、Alexaにデバイスを登録します。
AmazonEcho (Alexa) と RaspberryPi を連携して声だけでPS4を操作する

事前準備2

プロジェクトはこちらからダウンロードできます。
https://github.com/GuiltyWorks/LightSwticher

プロジェクトを実行したいRaspberryPiでgit cloneします。

git clone https://github.com/GuiltyWorks/LightSwticher

下記のコマンドを実行し、5 Interfacing Options -> P8 Remote GPIOからRemote GPIOをenabledにしてください。

sudo raspi-config

以降の事前準備の作業は、setup.shを実行することで省略できます。

Dockerのインストール

curl -fsSL https://get.docker.com -o get-docker.sh && sudo sh get-docker.sh

pigpioのインストール

sudo apt install -y pigpio && pip3 install pigpio

pigpioデーモンの起動(起動していない場合 or デーモンの起動を自動化していない場合)

sudo gpiod

pigpioデーモンの起動の自動化

sudo systemctl enable pigpiod.service && sudo reboot

事前準備3

Node.jsとnpmとnのインストール

sudo apt install -y nodejs npm
sudo npm install -g n
sudo n stable
sudo apt purge -y nodejs npm

Node-REDのインストール

bash <(curl -sL https://raw.githubusercontent.com/node-red/linux-installers/master/deb/update-nodejs-and-nodered)

Node-REDデーモンの起動の自動化

sudo systemctl enable nodered.service && sudo reboot

事前準備4(Dockerを使わない場合)

Dockerを使わない場合、pip3で必要なライブラリをインストールします。

pip3 install -r requirements.txt

コード

light_switcher.py
from flask import Flask, request
from flask_restx import Api, Resource, fields
import pigpio, time

status = None

pi = pigpio.pi()

app = Flask(__name__)
api = Api(app, version="1.0", title="LightSwitcher API Document", description="LightSwitcher is an API server that controls DC serbo motors connected to a RaspberryPi", doc="/doc/", default="Default Endpoint", default_label="default")

response_model = api.model("LightSwitcherResponse", {
    "status": fields.String(description="Status of light")
})
expect_model = api.model("LightSwitcherExpect", {
    "param": fields.String(description="Parameter for switching light")
})

@api.route("/")
@api.expect(expect_model)
class Switch(Resource):
    @api.marshal_with(response_model)
    def post(self):
        if request.json["param"] == "ON":
            pi.set_servo_pulsewidth(18, 1150)
            time.sleep(0.25)
            pi.set_servo_pulsewidth(18, 1500)
            status = 1
            print(status)
            return {"status": str(status)}
        elif request.json["param"] == "OFF":
            pi.set_servo_pulsewidth(19, 1500)
            time.sleep(0.25)
            pi.set_servo_pulsewidth(19, 1150)
            status = 0
            print(status)
            return {"status": str(status)}

        print("Error")
        return {"status": str(-1)}

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=80, debug=False)

FlaskとFlask-RESTXでAPIサーバーをたてて、pigpioでDCサーボモーターを動かしています。

フロー1.jpg
Node-REDのフローです。

alexa-home.jpg
alexa-homeノードのプロパティです。

switch.jpg
switchノードのプロパティです。

template1.jpg
上のtemplateノードのプロパティです。

template2.jpg
下のtemplateノードのプロパティです。

http_request1.jpg
http requestノードのプロパティです。
URLのhttp://192.168.11.20/は、RaspberryPiの固定プライベートIPアドレスです。
http://localhost/でもたぶん動くと思います。
自分(RaspberryPi)から自分(RaspberryPi)にPOSTリクエストを送信するためです。

debug1.jpg
debugノードのプロパティです。

実行方法

docker build -t light_switcher .

Dockerイメージをビルドします。

docker run -d -p 80:80 --net host light_switcher

docker runして実行します。
私の場合、cronで起動時に実行させています。

Dockerを使いたくない場合

python3 light_switcher.py

普通にPython3で実行しましょう。

実行結果

LightSwitcher.gif
「アレクサ、ライト、オン」というと、無骨な声で「はい」と返ってきて、照明がつきます。

さいごに

照明のスイッチまで3歩ですが、立ち上がらずに部屋の照明を操作できるのでとても便利です。
楽をするためにめちゃめちゃ努力する、やっぱりこれこそプログラミングの醍醐味ですね。

参考文献

声で部屋の電気のON/OFFをしたい(後編:音声認識しちゃうよ)
AmazonEcho (Alexa) と RaspberryPi を連携して声だけでPS4を操作する

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
What you can do with signing up
3