ESP8266、Amazon SWS IoTおよびLambdaを使用してSMS機能付きTwilioお天気ステーションを構築する
Today we're going to look at how to build an ESP8266 weather station which uses Twilio Programmable SMS to send weather updates. Our station will reply to incoming SMS messages with weather reports as well as send daily scheduled outgoing SMS weather reports. We'll use AWS IoT as a persistent preference store and MQTT broker and a combination of AWS Lambda and API Gateway to send and receive messages with Twilio.
必要なもの:
手順については順を追って説明していきますが、構築を完成させるには以下のものが必要になります:
- Twilioアカウント
- AWSアカウント
- ESP8266 (良い選択です)
- DHT11 (または22) 湿度センサー (このようなもの)
- ベアセンサーには、4.7kまたは10kの抵抗が必要です。 (Adafruit製品に含まれています)
- BMP180 (or 085) 気圧センサー (こんな感じです)
- オス-オスのジャンパー線(こういうものです)
- はんだ付け不要なブレッドボード(例)
お使いのESP8266開発基板(またはブレークアウト)に応じて、下記も必要になるかもしれません:
- 3.3v シリアルTTLアダプター (1-2x, 一例).
And of course, our code: Click here for the repository.
なぜお天気ステーションなのか?
We've written four guides about using Twilio (and in two cases, an ESP8266) with the AWS ecosystem:
- Receive and Reply to SMS or MMS Messages with Lambda in Python
- Pythonを使用して、Lambda上でTwilioのWebhookリクエストを検証する
- ESP8266、AWS Lambda、およびAWS IoTを使用してSMSおよびMMS(日本未対応)を送信する
- ESP8266、AWS Lambda、およびAWS IoTを使用してSMSおよびMMS(日本未対応)を受信、返信する
This tutorial wraps all of them up with an end-to-end application that does something useful - watches the weather wherever you want it to. Remote monitoring is a major IoT application, and hopefully this station gives you some ideas for your own product.
This build allows us to put something together which incorporates the requirements of many applications you might end up building next. We're going to look at receiving messages via Webhooks from Twilio, sending messages via the Twilio Python Helper Library and AWS Lambda, persisting device state with AWS IoT, and connecting everything over MQTT topics.
お天気ステーションのアーキテクチャー
Our architecture is unchanged from our Receiving and Replying to MMS and SMS messages with a ESP8266 and AWS post.
メッセージの送信:
メッセージの受信:
In addition, we'll be adding a handler for 'Help' and 'Set Preference' messages, which will come in over SMS. These will return TwiML to Twilio at the Lambda step in the above diagram. Any successful preference changes will happen in the background on the MQTT topic.
Twilioアカウントにサインインする
Our weather station will communicate with you - or whomever you give the number - completely over SMS. We'll eventually have messages moving both ways - originating from the ESP8266 and pushed to you, as well as messages initiated by you to the 'weather station'.
Log into your Twilio account now - and if you don't have one here is a link to sign up for a free Twilio trial. Keep that browser tab handy - you will need to refer back to it later.
SMSに対応した電話番号を検索する
For this demo, you'll require a SMS capable number you already own (or purchase now).
Go to the Twilio Console and select the hash tag/Phone Numbers ('#') section on the left side. Navigate to your currently active numbers.
Under capabilities, you'll want to look for one with SMS capabilities, as shown in the below image:
If you don't yet have a number with the SMS icon, you'll need to buy one. Navigate to the 'Buy a Number' link and click the SMS checkbox:
購入後は、Consoleのタブはそのままにしておいて、一旦Amazon Web Servicesに移動します。
Amazon Web Serviceにログイン、またはサインアップする
A lot of the weather station's infrastructure will use AWS products. AWS will handle passing messages to and from the ESP8266, persisting state in a power loss for the ESP, helping the end user change settings, and handling webhook requests from Twilio.
Supporting Your Things with AWS IoT
While our weather station server is the ESP8266, our station will be a lot more reliable if we have a service backing it. That's the role AWS IoT will play.
Importantly, IoT provides a way for us to save and persist preferences. When the ESP8266 power cycles, it will start up with whatever defaults are programmed into the flash. AWS IoT gives us the concept of Thing Shadows, where a Thing can query the current preferences whenever it needs to - and we'll use it to change the station settings at startup.
Also essential to our infrastructure, AWS IoT acts as the MQTT message broker. There will be multiple MQTT topics dedicated to AWS IoT reserved topics, and we will add the topics 'twilio' and 'twilio/delta' to handle messages and setting changes, respectively.
AWS IoTを設定する
If you haven't yet, you'll need to add a new 'Device' and a few other things to IoT. We discuss how to perform these steps in greater detail in our sending messages with IoT, Lambda and the ESP8266 article, but we'll cover the steps briefly now. If you have performed these steps already, feel free to skip ahead to Watching MQTT Cross-Traffic.
- AWS IoTダッシュボードの左側のペインの「Registry」配下で「Things」を選択します。
- Thingに好きな名前をつけます (例: 「Twilio_ESP8266_Weather_Station」)
- フレーム上部の大きな灰色の戻る矢印を使用して、「Things」に戻ります。
- 新規に作成された「Thing」をクリックします。
- サイドバー上の「Interact」をクリックします。
- エンドポイントを保存し、後々の使用に備えて「Update to this thing shadow」トピックをどこかに(テキスト文書で?)保存します。
後々(IoTセットアップの終盤も含まれます)使用しますので、このフレームは開いたままにしておいてTwilio consoleフレームに参加するか、安全な場所にコピーしておきます。
初期シャドウステートを設定する
ステートそのものは何でもかまいませんが、初期シャドウステートをThingに送信することが必要です。
- 左側のサイドバーの「Shadow」をクリックします。
- 「Shadow Document」の隣の「Edit」ボタンをクリックします
- 次のコードをペーストします。
{ "desired": { "units": "imperial", "alt": 60, "tz": -500, "t_num": "+18005551212", "m_num": "+18005551212", "alarm": 1234567890 } }
保存を行うと、初期ポリシーが得られますが、心配には及びません。 後々これを適したパラメーターに変更します。
「twilio」および「twilio/delta」トピックにおける公開/購読のポリシーを追加する
Use the big grey arrow again and return to the main console.
Click 'Security' then 'Policies', then 'Create a Policy'. Name it something memorable, and use an action of 'iot:*' with a Resource ARN replacing the last bit with 'twilio'. This will allow your Thing to publish and subscribe to the 'twilio' channel, and should also allow the same rights on any channels nested under /twilio
.
MQTTクロストラフィックを監視する
When everything is eventually plumbed together, there will be a lot of action on the MQTT topics. While you're in the AWS IoT Console, you should add two new tabs to your persistant collection.
- 左側のサイドバーから、「テスト」を選択します。
- 「このThingシャドウに更新」トピックを(上記の手順から)購読します。
/delta
が追加されたupdate
トピックである「delta」トピックを購読します。- 新規タブを開き、追加のトピックの購読を「テスト」します(他のタブは開いたままにしておきます)
- 「Twilio」トピックを購読します。
- 「twilio/delta」トピックを購読します。
限られたRAMを考慮に入れる
RAM on the ESP8266 is limited to 64 kB for instructions and 96 kB for data. The 'kilo' istead of 'giga' or even 'mega' is our hint to reduce the amount of data the ESP8266 is required to handle.
When there is an update to the Thing Shadow, AWS will send various parameters which are not needed in our setup. We're going to take advantage of an AWS IoT rule which allows us to extract only what's essential.
Under Rules, click the 'Create' button. Use a name of 'main_weather_preferences' and your choice of description. In the fields that follow, here's what to use:
- 属性: ステート
- トピック: 直前のセクションと同様の/deltaトピックで、
/delta
が追加されたupdate
トピックです。
Thingタイプ用のデルタトピックでは'Twilio_ESP8266_Weather_Station'という名前で表示されます:
「Republish messages to an AWS IoT Topic」のアクションを追加し、トピック名として「twilio/delta」を指定します。
Create that rule and you'll be well on your way to having a user-adaptable weather station! Now updates to the weather station normally passed on the update/delta
topic will have the core extracted for processing by the ESP8266.
APIゲートウェイでAPIを模倣する
In the last section, you set up a framework for the ESP8266 to stay connected to AWS. We also need a plan for the outside world to talk to our weather station.
When you send a text message to a Twilio number, Twilio forwards it to a webhook at a URI you define. In order to expose a resource with AWS, we use the API Gateway service.
We first went covered this process in our receiving and replying to SMS and MMS messages using Amazon Lambda guide, but we will describe it briefly here.
- From the API Gateway console, use the 'Create API' button.
- Name and describe your API a friendly name and description (for your own reference), then create it.
- Create a new resource 'message' (at '/message')
message
にPOSTメソッドを作成します。- Select 'Mock' as your 'Integration type'.
For now, that's it for API Gateway. We'll be returning later when Lambda is ready.
強く推奨 - 新規IAMユーザーをセットアップする
While you can use your main AWS account's credentials for the weather station, best practice with the ESP8266 is to create a new IAM user with IoT permissions. Go to the IAM console, select 'Users' in the left pane and click the blue 'Add User' button.
ユーザーに名前をつけて、ボックスをクリックしプログラムからのアクセスを追加します。
Click through to the 'Permissions' step and select 'Attach Existing Policies Directly'. Add every IoT permission, as we did in this picture:
Download the CSV with the user credentials from the success screen. Those will be used in the settings at the top of the .ino
file the ESP8266 uses.
Lambdaを使用して、メッセージを送信する
While the ESP8266 does have the capability to use the Twilio API directly to send messages (with a few shortcuts, like verifying a certificate fingerprint), we're going to use the AWS infrastructure to send messages via a Lambda function. To demonstrate the flexibility of this approach, we're going to use the same setup as we did in the sending SMS and MMS Messages with the ESP8266 and Lambda article.
ここでやるべきことを簡単に説明しますが、各手順の詳細については先の記事を参考にしてください。
Having Outgoing Messages Trigger Lambda
- Create a new Lambda function in the same region as you've set up AWS IoT (use the blank template). Configure it to use AWS IoT as a trigger.
- Check the box for 'Enable Trigger' and name it something memorable. 'IoT Type' should be 'Custom IoT Rule'.
- Lambdaのトリガーに使用するSQLステートメントは:
SELECT * FROM 'twilio' WHERE Type='Outgoing'
- Here's how you do that from the configuration screen:
- 「Next」をクリックして、functionステージに移動します。
空白のファンクションをそのままにしておきます。
- Runtimeを「Python 2.7」に変更します。
- 「Handler」フィールドに後々アップロードするコードに向けての準備として「twilio_functions.iot_handler」を設定します。
- ファンクション名を「myTwilioSendMessage」とし、お好みの説明文を入力してください。
- Use 'Create new role from template(s)' using the AWS IoT Button Permissions, and naming the role something memorable.
これで準備はOKです - 空のFunctionを作成しましょう!
SQLバージョンを変更する
AWS IoTコンソールに一旦戻り(新規タブでもかまいません) - AWSとESP8266がうまく協調動作するために済ませておくべきことがもうひとつあります。
- 左側のサイドペインから「Rules」リンクをクリックします。
- それから
send
Lambdaファンクション用に作成した新規ルールを確認しそれをクリック、詳細を確認してください。 - 「Rule query statement」セクションで、「Edit」リンクをクリックし、「Using SQL version」を「2015-10-08」に切り替えます:
「Update」ボタンをクリックすれば、ESP8266がルールを開始する準備は万端です。
Add some Python Code to Lambda
さぁ、コードを書くときがやってきました。
- お使いのコンピューターで新規フォルダーを作成し、中にTwilio Python Libraryを手動でインストールしてください。
- From the GitHub repository, bring in everything from the 'Lambda Function Send SMS' directory (see our earlier guide for detailed help on adding external packages, and read the companion article if you want more details on that function). Zip the contents of that directory up.
- Inside Lambda, select 'Upload a .ZIP File' on the 'Code' tab. Using 'Upload', select the zip file you just created and upload it by saving.
- Double check you're using the Python 2.7 runtime, and that the Handler is set to 'twilio_functions.iot_handler'.
最新のヘルパーライブラリーではインラインでコードを編集できませんので、更新をオフラインする際に問題が生じたら、再度アップロードを行なってください。
環境変数を設定する
In Lambda, Environmental Variables are set on the 'Code' tab. From the Twilio Console (you do have the tab still open, right?), find your authorization token and account ID to populate:
- AUTH_TOKEN
- ACCOUNT_SID
And with that, you should have the plumbing set to send messages from the weather station. You can double check the 'Triggers' tab to make sure that IoT is triggering this function based upon the SQL query we already entered.
If that checks out, we can move on...
Lambdaを使用してSMS-Treeを構築する
We're going to model the user facing portion of the Weather Station as a SMS-Tree, much like the Phone Trees Twilio makes so easy to create. Philosophically, our SMS-Tree will be stateless and idempotent - that is, performing actions will not require multiple steps and running the same command multiple times will leave the device in the same state.
権限付与とセキュリティーについては、いくつかのメカニズムを採用しています:
- WebhookがTwilioから送信されたものかどうか検証するため、Python Twilioヘルパーライブラリーの助けを借りています(詳細記事も参考にしてください)。
- 設定の変更が行える「マスターナンバー」を使用します(
master_number
以外のステータスは他のユーザーが表示できます)。
ユーザーの目に触れるLambdaファンクションを作成する
Using similar steps, create a new blank Lambda function named 'twilioWeatherStation' with no trigger. The 'Handler' should be set to 'twilio_functions.twilio_webhook_handler', and create a zip file which contains the code in the 'Lambda Function Weather' directory and the Twilio Python Helper Library. For details on loading external libraries into Lambda, see this article.
このファンクションには5つの環境変数が必要です:
- AUTH_TOKEN - Consoleから取得する、Twilioの認証トークン
- AWS_TOPIC - 'twilio' (引用符を含みません)
- THING_NAME - 好きな名前をつけられます。 この例では 'Twilio_ESP8266_Weather_Station' です。
- AWS_IOT_REGION - 上記のThingの地域です
- REQUEST_URL - API GatewayのリクエストURLで、これはTwilioと一致させますので、今は空欄のままにしておきます。
Under role, select 'Create a New Role From Template', selecting 'AWS IoT Button permissions'. Give that role a descriptive name - such as 'twilio_weather' - and continue. Next we'll give that role some special permissions.
LambdaでMQTTトピックをポストできるようにし、デバイスシャドウを更新します
Since this Lambda function is both publishing to MQTT topics as well as updating and checking the Thing Shadow, it is going to need extra permissions. We're going to enable them through IAM using an inline policy.
- ご自身の名前のプルダウンの「My Security Credentials」を使用して、IAMに移動します。
- 左側のサイドバーで「Roles」リンクをクリックします。
- このLambdaファンクションに割り当てられたロールを探し、クリックします。
- 「Inline Policies」直下の「Create Role Policy」ボタンをクリックします:
- add an inline policy which allows this function free reign in IoT:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "iot:*" ], "Resource": [ "*" ] } ] }
これで、Lambda FunctionはIoTで必要なアクションをなんでも実行できるようになりました - 今回このお天気ステーションでは、これをたくさん使用します。
続いて、Lambdaのサーバーコードの機能について、詳しく見ていくことにしましょう。
SMS-Treeファンクションとは何か
SMS-Treeはユーザーに、設定変更を手助けし、お天気レポートの送信を行います。
ヘルプ
We build a number of 'Help' responses to guide our users when updating settings. There will be a general help message, individual help on each specific setting, and an overview of the currently set settings.
Both '?' and 'help' are used to retrieve help. Note that by default for a ten-digit phone number Twilio will handle any incoming SMS with a body of 'help'. 'help' messages with multiple words will still be passed through to Lambda.
Set
If the user is authorized, we allow her to change the settings which affect the behavior of the station. We have included some very basic input validity checks to ensure, for example, that settings which require numbers are only set to numbers.
「s」および「set」の両方がset
コマンドの実行に使用されます。
Report
If the message is not a 'Help' or a 'Set' message, we pass it through to the ESP8266. The logic there is simple - for any SMS or MMS it receives, it will send back the last weather report.
API GatewayからLambdaをトリガーする
Go back to the API Gateway console, and navigate to the API we were building up before. We're going to use it now to trigger our new Lambda function.
The receiving and replying to SMS and MMS messages from Lambda article has the full steps you'll need to perform to have a working API for Twilio to call, but we'll summarize here.
- In 'Method Request', add
X-Twilio-Signature
HTTP Request Header to pass through to Lambda. - In 'Integration Request', remove any Body Mapping Templates and add one for
application/x-www-form-urlencoded
with a template of:
#set($httpPost = $input.path('$').split("&")) { "twilioSignature": "$input.params('X-Twilio-Signature')", #foreach( $kvPair in $httpPost ) #set($kvTokenised = $kvPair.split("=")) #if( $kvTokenised.size() > 1 ) "$kvTokenised[0]" : "$kvTokenised[1]"#if( $foreach.hasNext ),#end #else "$kvTokenised[0]" : ""#if( $foreach.hasNext ),#end #end #end }
- In 'Integration Response', remove any Body Mapping Templates and add a new one in HTTP status code
200
forapplication/xml
. Use this two line template:
#set($inputRoot = $input.path('$')) $inputRoot
- 「Method Response」では、HTTPステータス200についてすべての既存のレスポンス本文を削除し、
application/xml
に一つ追加します。
ここで、「Action」プルダウンメニューから「Deploy API」を選択します:
「prod」という名前の新規ステージを追加し、好きな説明文を入力します。
When you deploy, Amazon will assign a URL to the new /message
route. Copy the entire thing, including the /message
. Back in the weather station Lambda function's 'Code' tab, paste the exact URL into the REQUEST_URL environmental variable.
続いて、まだハードウェアは追加していません(!)が、すべてを接続してTwilioでテストしてみましょう。
TwilioのWebhook URLを構成する
In the Twilio Console browser tab, navigate to the Numbers Section in the sidebar (#). Select the number you set up in the beginning of this tutorial.
Under 'Messaging' and in 'A Message Comes In', select 'Webhook' and paste the API Gateway URL into the text box (highlighted below). Ensure 'HTTP POST' is selected.
予備のWebhook URL
多くのアプリケーションでは最初のWebhookの失敗時の対策を講じておくことが望まれますが、今回のお天気ステーションに関しては大目に見ることにしましょう。
Just be aware - when you are building a Twilio application and the primary Webhook fails (sends back a 5xx
HTTP response or times out), Twilio will failver to the backup web hook. That extra piece of machinery is perfect for ensuring you maximize the number of 9s in your uptime.
ヘルプ (Help) または設定 (Settings) を得るため、Twilio番号にメッセージを送信する
先に触れたように、まだハードウェアは追加されていないのでお天気についてはお預けですが、setおよびhelpの機能については試すことができます。
本文に疑問符(「?」)をひとつ入力し、お手持ちの携帯電話からTwilio番号にメッセージを送ってみてください。
すべてうまく機能していれば、本アプリケーションの「Hello, World!」が表示されます - これはさまざまなヘルプトピックについての、Lambdaからわかりやすい(が、ちょっとぎこちないですね!)メッセージです。
また、タイムゾーン(分単位)を表す「tz」など、変数を設定(「set」)することができます。
set tz -480
(太平洋標準時: -8時間 x 60分)set tz 540
(日本標準時: +9時間 x 60分).
何かリアクションが返ってくることを願いましょう。
If not, trace back through the chain, starting with the Twilio Debugger. For each step in the chain, check the logs - after the debugger, check CloudWatch for any Lambda or API Gateway logs, and finally (for 'set' messages only), check for MQTT messages in the Test MQTT clients.
If it all works, most of the software is done - it's time to move to the board. It's time - let's build the actual station itself!
ESP8266 お天気ステーション - 基板とソフトウェア
At this point, we're ready to put together the ESP8266 part of the chain. If you haven't yet purchased a board, the repository for Arduino on ESP8266 has a nice list of tested boards. We'll be building the weather station on a solderless breadboard with pre-made jumper wires. That in mind, we'd suggest sticking with a full sized development board until it's working... after that you can decide if you'd like to miniaturize the setup.
To develop this guide, we used a Sparkfun Thing and Sparkfun's Basic FTDI breakout. The Sparkfun Thing overloads the DTR pin for ease of programming. This causes problems with the hardware serial port when monitoring from inside the Arduino IDE. We find it easier to use SoftwareSerial for simple text debugging, but have left the choice of serial port (or none) as a setting in the code - you can use the USE_SOFTWARE_SERIAL and USE_HARDWARE_SERIAL to tell the preprocessor how to compile serial support in the code.
Arduino IDE
For the greatest ease of use, we developed the ESP8266 code for this tutorial in the Arduino IDE. Help building the station using another toolchain is outside the scope of this tutorial. While we encourage you to try, please use Arduino to get a working setup first.
ArduinoにESP8266サポートを追加する
If you haven't added new board support to Arduino before, we'll walk through that now - feel free to skip ahead if the ESP8266 is already added to your setup.
お好みに応じて、新規URLを「Additional Board URLs」セクションに追加します: "http://arduino.esp8266.com/stable/package_esp8266com_index.json"。
Next, in the 'Tools' menu, select 'Boards Manager'. It will automatically update - after a second, search for the ESP8266 and install the most recent version.
Arduinoにライブラリーを追加します。
We're relying on quite a few libraries for the guide today:
- AdafruitからのAdafruit BMP085 Unified
- AdafruitからのAdafruit Unified Sensor
- AdafruitによるDHT Sensor Library
- Fabrice WeinbergによるNTPClient
- aws-mqtt-websockets from GitHub user odelot
- Markus SettlerによるArduino WebSockets
- Benoit BlanchonからのArduinoJSON
- AWS-SDK-Arduino from Sander van de Graaf forked from AWS Labs
- Eclipse Paho Embedded Client (MQTT用)
Using Arduino's Library Manager is possible for two of the libraries, but the others must be added manually. For a complete overview of library management on Arduino, see the official documentation.
スルーライブラリーマネージャーを追加する(検索)
- Adafruit BMP085 Unified
- Adafruit Unified Sensor
- DHTセンサーライブラリー
- NTPClient
- ArduinoJSON
- WebSockets
Arduinoに手動で追加する
The easiest way to install these libraries in the Arduino IDE is to install from a downloaded zip file.
これは、Arduino IDE内のZIPライブラリーインストーラーから直接完了できる場合があります。
「Sketch」メニュー -> 「Add ZIP Library」 -> ダウンロードされたZIPファイルを選択します
ダウンロードリンク:
お天気ステーションのコードをコンパイルする
We've bottled up much of the complexity of the weather station in the TwilioLambdaHelper (first seen in this article) and TwilioWeatherStation classes. In those classes, we manage a lot of the heartbeat functions which need to be fired off on certain timers. We also wrap up things like managing time and reading the sensors.
.inoファイルの先頭には、コンパイル前に変更が必要な設定が多くあります。
Edit in your WiFi credentials, the AWS key & secret for a properly credentialed IAM user (did you create a new one earlier?), the AWS region of the IoT device, and the HTTPS AWS endpoint. Change the shadow_topic to the Thing Shadow update topic listed in the Interact tab of your IoT Thing (you probably still have that tab open).
Although it looks like there are a number of extra settings, they are actually optional. When the ESP8266 connects, it will report to AWS IoT with its current state. IoT will report back on what needs to change. The ESP8266 will change its settings, and send another report on state (which this time will be met with no changes).
お好みに応じて変更することをお勧めしますが、これらはリファレンスとしては有用です。
コンパイルしてみましょう - そしてこれで、ハードウェアを構築し、基板に(プログラムを)焼き込む準備が整いました!
ESP8266お天気ステーション - ハードウェア
This part might be a little tricky since we will all be using different boards. With the current setup, you will need to use I2C to connect the BMP Pressure sensor. If you need to move the DHT sensor, update the DHTPIN
setting in the code.
DHT11データピン | ESP8266 GPIO0 |
BMP180 SCLピン | ESP8266 SCLピン |
BMP180 SCAピン | ESP8266 SCAピン |
Depending on the DHT11 sensor you purchase, you will need to add a 4.7kΩ resistor between data and 3.3 volts. These resistors start with Yellow, Violet and Red in a 4-band resistor, and it is drawn on the schematic. Don't add a second one if it is already onboard.
Remember: Change the exact setup to fit the board and parts you useyou use, and change the pins in the code if you move them around. We drew up a schematic and a possible breadboard layout with Fritzing - but this is based on what we purchased!
回路図:
Note: this schematic is for the SparkFun Thing development board. You might have to vary it for your own hardware! Boards which don't relabel the pins should have a final circuit something like our diagram.
One colleague has a NodeMCU board and was succesful with the following setup (GPIO pins are in parentheses; they are not labeled on the board):
- D1 (GPIO5): SCL
- D2 (GPIO4): SDA
- D3: DHT11のDATAピン
レイアウトの一例:
接続し、コードをアップロードする
Triple check your connections, then plug everything in. If you don't let out any magic smoke, you're well on your way! (If you did, don't worry about it - it's a rite of passage with hardware - hopefully you've got extras.)
Use the 'Tools' menu in Arduino to select your ESP8266. We have had the most success keeping our station connected with a speed of 160 MHz. Choose the proper port and try a slower serial speed such as 115200 for uploading.
And with a compile and an upload hopefully everything just works the first time! You've now got a weather station which updates every 3 minutes with barometric pressure, humidity and temperature.
お天気ステーションの設定変更
There are at least three avenues to change the settings on the station, and you should set the initial state depending on what seems easiest:
Shadow Stateから直接に
- IoTコンソールから、「Things」を選択し、お天気ステーションをクリック、そして左側のサイドバーの「Shadow」にアクセスします。
- 「Shadow Document」配下の「Edit」リンクをクリックします。
- Modify the keys and values directly (there are six, as seen in the Lambda code).
- 「保存」時は、変更は様々なMQTTトピックに発行されます。
マスターの携帯電話からのSMS
- お天気ステーションに「set <param> <value>」または「s <key> <value?」という内容のSMSを送信します。
- If authorized and making a valid request, the changes will be published to the various MQTT topics.
Shadow State Update Channelへの発行
- /updateトピックに正しく書式化されたJSONを送信します。
- ここで詳しく触れられているように、JSONオブジェクト本文に「Desired」が存在する場合、シャドウステートは更新されます。
- 更新時は、変更はさまざまなMQTTトピックに公開されます。
遠隔監視: お天気が更新されました!関連トピック
さぁ、お楽しみタイムです!
We've built this remote monitoring application together which will keep a close eye on the weather. The sky - whether blue or grey - is the limit, and the station is now yours to customize and make your own. Add voice, add MMS support with weather icons, even add video (got video working on an ESP8266? We're hiring...).
We've got a nice selection of Add-ons with some amazing partners as well. You'll really enjoy how easy the integration is - perhaps see if anything would work well for your application.
Whatever you build, we'd love to hear about it. Drop us a line on Twitter and show us what you've built!
ヘルプが必要ですか?
誰しもが一度は考える「コーディングって難しい」。そんな時は、お問い合わせフォームから質問してください。 または、Stack Overflow でTwilioタグのついた情報から欲しいものを探してみましょう。