

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# Raspberry Pi と湿度センサーのセットアップ
<a name="iot-moisture-raspi-setup"></a>



microSD カードを Raspberry Pi に挿入し、モニター、キーボード、マウスを接続し、Wi-Fi を使用していない場合はイーサネットケーブルも接続します。電源ケーブルはまだ接続しないでください。

JST ジャンパーケーブルを湿度センサーに接続します。ジャンパーの反対側には次の 4 本のワイヤがあります。
+ 緑: I2C SCL
+ 白: I2C SDA
+ 赤: 電源 (3.5 V)
+ 黒: アース

右側にあるイーサネットジャックで Raspberry Pi を保持します。この向きでは、上部に 2 列の GPIO ピンがあります。次の順序で、湿度センサーのワイヤをピンの下の列に接続します。左端のピンから、赤 (電源)、白 (SDA)、緑 (SCL) を接続します。1 つのピンをスキップし、黒い (アース) ワイヤを接続します。詳細については、「[Python Computer Wiring](https://learn.adafruit.com/adafruit-stemma-soil-sensor-i2c-capacitive-moisture-sensor/python-circuitpython-test)」を参照してください。

電源ケーブルを Raspberry Pi に接続し、もう一方の端をコンセントに接続して電源を入れます。

**Raspberry Pi を設定します。**

1. [**Welcome to Raspberry Pi**] で、[**Next**] を選択します。

1. 国、言語、タイムゾーン、キーボードレイアウトを選択します。[**Next**] を選択します。

1. Raspberry Pi のパスワードを入力し、[**Next**] を選択します。

1. Wi-Fi ネットワークを選択し、[**Next**] を選択します。Wi-Fi ネットワークを使用していない場合は、[**Skip**] を選択します。

1. [**Next**] を選択して、ソフトウェアの更新を確認します。更新が完了したら、[**Restart**] を選択して Raspberry Pi を再起動します。

Raspberry Pi が起動したら、I2C インターフェイスを有効にします。

1. Raspbian デスクトップの左上隅にある Raspberry アイコンをクリックし、[**Preferences**]、[**Raspberry Pi Configuration**] の順に選択します。

1. [**Interfaces**] タブの [**I2C**] で、[**Enable**] を選択します。

1. [**OK**] を選択します。

Adafruit STEMMA 湿度センサーのライブラリは、CircuitPython 向けに記述されています。それらのライブラリを Raspberry Pi で実行するには、最新バージョンの Python 3 をインストールする必要があります。

1. コマンドプロンプトから次のコマンドを実行して、Raspberry Pi ソフトウェアを更新します。

   `sudo apt-get update`

   `sudo apt-get upgrade`

1. 次のコマンドを実行して、Python 3 のインストールを更新します。

   `sudo pip3 install --upgrade setuptools`

1. 次のコマンドを実行して、Raspberry Pi GPIO ライブラリをインストールします。

   `pip3 install RPI.GPIO`

1. 次のコマンドを実行して、Adafruit Blinka ライブラリをインストールします。

   `pip3 install adafruit-blinka`

   詳細については、「[Installing CircuitPython Libraries on Raspberry Pi](https://learn.adafruit.com/circuitpython-on-raspberrypi-linux/installing-circuitpython-on-raspberry-pi)」を参照してください。

1. 次のコマンドを実行して、Adafruit Seesaw ライブラリをインストールします。

   `sudo pip3 install adafruit-circuitpython-seesaw`

1. 次のコマンドを実行して、 AWS IoT Device SDK for Python をインストールします。

   `pip3 install AWSIoTPythonSDK`

これで、必要なすべてのライブラリが Raspberry Pi にインストールされました。**moistureSensor.py** という名前のファイルを作成し、次の Python コードをファイルにコピーします。

```
from adafruit_seesaw.seesaw import Seesaw
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient
from board import SCL, SDA

import logging
import time
import json
import argparse
import busio

# Shadow JSON schema:
#
# {
#   "state": {
#       "desired":{
#           "moisture":<INT VALUE>,
#           "temp":<INT VALUE>            
#       }
#   }
# }

# Function called when a shadow is updated
def customShadowCallback_Update(payload, responseStatus, token):

    # Display status and data from update request
    if responseStatus == "timeout":
        print("Update request " + token + " time out!")

    if responseStatus == "accepted":
        payloadDict = json.loads(payload)
        print("~~~~~~~~~~~~~~~~~~~~~~~")
        print("Update request with token: " + token + " accepted!")
        print("moisture: " + str(payloadDict["state"]["reported"]["moisture"]))
        print("temperature: " + str(payloadDict["state"]["reported"]["temp"]))
        print("~~~~~~~~~~~~~~~~~~~~~~~\n\n")

    if responseStatus == "rejected":
        print("Update request " + token + " rejected!")

# Function called when a shadow is deleted
def customShadowCallback_Delete(payload, responseStatus, token):

     # Display status and data from delete request
    if responseStatus == "timeout":
        print("Delete request " + token + " time out!")

    if responseStatus == "accepted":
        print("~~~~~~~~~~~~~~~~~~~~~~~")
        print("Delete request with token: " + token + " accepted!")
        print("~~~~~~~~~~~~~~~~~~~~~~~\n\n")

    if responseStatus == "rejected":
        print("Delete request " + token + " rejected!")


# Read in command-line parameters
def parseArgs():

    parser = argparse.ArgumentParser()
    parser.add_argument("-e", "--endpoint", action="store", required=True, dest="host", help="Your device data endpoint")
    parser.add_argument("-r", "--rootCA", action="store", required=True, dest="rootCAPath", help="Root CA file path")
    parser.add_argument("-c", "--cert", action="store", dest="certificatePath", help="Certificate file path")
    parser.add_argument("-k", "--key", action="store", dest="privateKeyPath", help="Private key file path")
    parser.add_argument("-p", "--port", action="store", dest="port", type=int, help="Port number override")
    parser.add_argument("-n", "--thingName", action="store", dest="thingName", default="Bot", help="Targeted thing name")
    parser.add_argument("-id", "--clientId", action="store", dest="clientId", default="basicShadowUpdater", help="Targeted client id")

    args = parser.parse_args()
    return args


# Configure logging
# AWSIoTMQTTShadowClient writes data to the log
def configureLogging():

    logger = logging.getLogger("AWSIoTPythonSDK.core")
    logger.setLevel(logging.DEBUG)
    streamHandler = logging.StreamHandler()
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    streamHandler.setFormatter(formatter)
    logger.addHandler(streamHandler)


# Parse command line arguments
args = parseArgs()

if not args.certificatePath or not args.privateKeyPath:
    parser.error("Missing credentials for authentication.")
    exit(2)

# If no --port argument is passed, default to 8883
if not args.port: 
    args.port = 8883


# Init AWSIoTMQTTShadowClient
myAWSIoTMQTTShadowClient = None
myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(args.clientId)
myAWSIoTMQTTShadowClient.configureEndpoint(args.host, args.port)
myAWSIoTMQTTShadowClient.configureCredentials(args.rootCAPath, args.privateKeyPath, args.certificatePath)

# AWSIoTMQTTShadowClient connection configuration
myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10) # 10 sec
myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5) # 5 sec

# Initialize Raspberry Pi's I2C interface
i2c_bus = busio.I2C(SCL, SDA)

# Intialize SeeSaw, Adafruit's Circuit Python library
ss = Seesaw(i2c_bus, addr=0x36)

# Connect to AWS IoT
myAWSIoTMQTTShadowClient.connect()

# Create a device shadow handler, use this to update and delete shadow document
deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(args.thingName, True)

# Delete current shadow JSON doc
deviceShadowHandler.shadowDelete(customShadowCallback_Delete, 5)

# Read data from moisture sensor and update shadow
while True:

    # read moisture level through capacitive touch pad
    moistureLevel = ss.moisture_read()

    # read temperature from the temperature sensor
    temp = ss.get_temp()

    # Display moisture and temp readings
    print("Moisture Level: {}".format(moistureLevel))
    print("Temperature: {}".format(temp))
    
    # Create message payload
    payload = {"state":{"reported":{"moisture":str(moistureLevel),"temp":str(temp)}}}

    # Update shadow
    deviceShadowHandler.shadowUpdate(json.dumps(payload), customShadowCallback_Update, 5)
    time.sleep(1)
```

このファイルを、見つけられる場所に保存します。以下のパラメータを使用して、コマンドラインから `moistureSensor.py` を実行します。

エンドポイント  
カスタム AWS IoT エンドポイント。詳細については、「[Device Shadow の REST API](device-shadow-rest-api.md)」を参照してください。

rootCA  
 AWS IoT ルート CA 証明書へのフルパス。

cert  
 AWS IoT デバイス証明書へのフルパス。

key  
 AWS IoT デバイス証明書のプライベートキーへのフルパス。

thingName  
モノの名前 (この場合は `RaspberryPi`)。

clientId  
MQTT クライアント ID。`RaspberryPi` を使用します。

コマンドラインは次のようになります。

`python3 moistureSensor.py --endpoint {{your-endpoint}} --rootCA ~/certs/AmazonRootCA1.pem --cert ~/certs/raspberrypi-certificate.pem.crt --key ~/certs/raspberrypi-private.pem.key --thingName RaspberryPi --clientId RaspberryPi`

センサーに触れたり、プランター内に置いたり、コップの水に入れたりして、センサーがさまざまなレベルの湿気にどのように反応するかを確認します。必要に応じて、`MoistureSensorRule` でしきい値を変更できます。湿度センサーの読み取り値がルールの SQL クエリステートメントで指定された値を下回ると、 は Amazon SNS トピックにメッセージ AWS IoT を発行します。湿度と温度データが含まれた E メールメッセージが届きます。

Amazon SNS からの E メールメッセージの受信を確認したら、**Ctrl\+C** を押して Python プログラムを停止します。Python プログラムが、料金がかかる量のメッセージを送信することはほとんどありませんが、終了したらプログラムを停止することをお勧めします。