メニュー

Expand
Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

Amazon AWS IoTおよびLambda経由でESP8266でSMSまたはMMS(日本未対応)を送信する方法

Let's make the Internet of Things a little more outgoing today. We're going to make an Espressif ESP8266 send a SMS or MMS message with Twilio using Amazon AWS IoT and Lambda. We'll demonstrate connecting to AWS IoT with MQTT over Websockets, publishing to an MQTT topic from the ESP8266, and triggering Lambda functions from certain messages published on the MQTT topic.

面白そうでしょう? モノのインターネットという新たな世界にダイブしましょう!

Twilioアカウントにサインイン(またはサインアップ)する

Either create a new Twilio account (sign up for a free Twilio trial here), or sign into your existing Twilio account. You'll need to enter values from the console in a few places, and you will also need details on a purchased number - so keep a tab handy.

SMS(およびMMS)対応電話番号を検索または購入する

For this demo, you'll require a SMS and MMS enabled number you either purchase or already own.

First, enter the Twilio Console. Second, select the hash tag/Phone Numbers ('#') section on the left side, and navigate to your current active numbers.

In 'Capabilities', you'll see the functions available with your current Twilio phone numbers. This guide requires numbers with SMS and optionally MMS capabilities.

SMS機能に対応したTwilio電話番号を確認する

If you don't yet have a number with SMS or MMS capabilities, you'll need to buy one. Navigate to the 'Buy a Number' link and click the SMS - and optionally the MMS - checkbox:

SMS対応Twilio電話番号を購入する

ESP8266で、Amazon AWS IoTを使用する

インターネットにおけるパーソナルな「モノ」が通信をし、この種の短命な性質のデバイスが状態を維持する方法について思い悩んだことはありませんか? お手持ちの様々な「モノ」からの全データの収集、分析を容易にするサービスであるAmazonのAWS IoTにアクセスします。

We're going to revolve our sample application around the lightweight communications protocol MQTT, the Message Queue Telemetry Transport protocol, tunneled over a persistant WebSocket connection from an ESP8266. While MQTT can be used directly on AWS IoT, client credentialling is more difficult for the ESP8266's 64 KiB of RAM, and MQTT over WebSockets is a very usable substitute.

AWS IoT、Lambda、およびESP8266を使用してメッセージを送信する

AWS IoTのセットアップ

必要に応じて、Amazon AWSアカウントにログインし、使用しているAmazonリージョン内でAWS IoTコンソールに移動します。

First, we need to add a new Device to IoT. In the left pane of the Dashboard, under 'Registry' select 'Things':

AWS IoTで新規Thingを登録します。

Give a nice name to your thing, and add a new 'Type' as well (you can create Types from the same screen under the advanced options). We named our Thing Type 'ESP8266', for the eventual swarm of WiFi connected ESP-Things we expect to deploy.

Our next stop is to find our new Thing's HTTPS endpoint and shadow update topic. Click the big grey left arrow to go back to the console, then under the same subheading in the left sidebar of the console, select 'Things' again. You should see your new Thing:

Amazon AWS IoT THingを選択する

Click on your Thing, then click the 'Interact' link in the sidebar. The HTTPS endpoint is at the very top; you'll eventually need it for the ESP8266 steps.

HTTPSエンドポイントとMQTTシャドウアップデート

Copy that and keep it in a handy place. Also, copy the 'Update to this thing shadow' MQTT topic, which is at the top of the MQTT section.

Device shadows in AWS IoT are persistant data stores where you can park configuration or other information your thing needs to consume. Although we aren't using the Shadow functionality for this example we've added the reference in the ESP8266 code so you can add it easily. That topic should be pasted directly into the ESP8266 code when we get to the configuration section.

Thingにポリシーを追加すると、「twilio」MQTTトピック上に購読、公開できるようになります。

Navigate with the grey arrow again to return to the main console. Click 'Security' then 'Policies', then 'Create a Policy'. Name it something useful, 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.

IoTポリシーを作成する

新規IAMユーザーをセットアップする

While not strictly necessary (you can use your main AWS account's credentials), it's much safer to set up a new IAM User with IoT permissions for this example. Go to the IAM console and select 'Users' in the left side pane. At the top, click the blue 'Add User' button.

「Twilio_IoT_User」のような何らかの名前をユーザーにつけて、ボックスをクリックしてProgrammatic Accessを追加します:

AWS IoTに対してIAMユーザーを追加する

Click through to the 'Permissions' step and select 'Attach Existing Policies Directly'. You can be more discreet; we added every policy related to IoT as seen in the below image:

AWS IoT IAMユーザー権限

One more thing - download the CSV with the user credentials from the success screen. We'll eventually use those credentials on our ESP8266 to connect to AWS IoT.

And now you've got an IoT IAM User for your thing to use! Navigate back to the IoT Console.

「Twilio」 MQTTトピックを購読します。

Back in AWS IoT, click the 'Test' subheading in the left pane. In the 'Subscribe to a Topic' field, enter the topic 'twilio' (lowercase, one word) with a 'Quality of Service' of 0.

You can test subscribing to the topic straight from the test console; try publishing a message now and you should see it appear on the same screen. Of course, it's just an echo chamber - there are no other things to communicate with, so you're alone with the topic right now.

Don't despair, we'll get something to listen soon - but for now let's set up debugging in case something goes wrong with IoT during the next steps. Do not close this browser tab; you'll want it to eventually verify your ESP8266 is subscribed.

CloudWatchをセットアップしてログを取得する

Select the 'Gear' 'Settings' option from the left pane. There, update CloudWatch Logs to turn it on, probably with the '*Log level' of 'Debug (most verbose)'.

まだこれはそんなに有用なものではありませんが、IoTとLambdaの間で細工をすると便利なものに早変わりします。

これで、2番目のパートへの準備は万端です。 ESP8266上でコードを走らせましょう!

ESP8266でAWS IoT Cloudと会話する

コードをすぐに見たいって? このリンクをクリックして、直接GitHubのリポジトリーに移動できます。

As always, note that hardware development can sometimes have more variables than software development. At a minimum, you'll need to purchase an ESP8266 for this guide. Additionally, for the ease of development, this guide targets the Arduino IDE.

The ESP-8266 Arduino tie-in includes the Xtensa gcc toolchain, provides the Arduino libraries, and makes it easy to program the ESP-8266. While we understand that many of you work outside of the Arduino ecosystem, it's the easiest way to get us all on the same footing. Connecting to AWS IoT using a different toolchain or setup is outside the scope of this article. While we are unable to help in other setups, please leave a comment on Stack Overflow and perhaps the community can assist you or learn something new from you.

基板の選択

The repository for Arduino on ESP8266 has a nice list of tested boards. If you haven't yet selected a board for development, it would be best to pick one of the vetted boards. Eliminating another possible variable is best until you get the setup working.

To develop this guide, we used a Sparkfun Thing and Sparkfun's Basic FTDI breakout for programming. The Sparkfun Thing overloads the DTR pin for programming, which causes problems with the hardware serial port when monitoring from inside the Arduino App. 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.

Arduinoにライブラリーを追加します。

今日はいくつかのライブラリーについて学びます:

Two of these libraries can be installed automatically using Arduino's Library Manager, but the others must be added manually. For a complete overview of library management on Arduino, see the official documentation.

検索によりLibrary Manager経由で追加する
  • ArduinoJSON
  • WebSockets
Arduinoに手動で追加する

The easiest way to get these libraries into Arduino is to install directly from the zip file once you download.

これは、Arduino IDE内のZIPライブラリーインストーラーから直接完了できる場合があります。

「Sketch」メニュー -> 「Add ZIP Library」 -> ダウンロードされたZIPファイルを選択します

ZIP LibraryをArduinoに追加する

ダウンロードリンク:

ESP8266のコード例を構築する

GitHubリポジトリーから.inoファイルを開きます。 基板用にビルドができるようになる前に、以下のスニペットのように一部のコードを変更することが必要です。

        
        
        
        
        Wi-Fi、AWSへの接続、およびメッセージを送信するためのTwilioの使用に向けて基板をセットアップする

        ご自身の環境用のESP8266 AWS IoTの例をカスタマイズする

        Wi-Fi、AWSへの接続、およびメッセージを送信するためのTwilioの使用に向けて基板をセットアップする

        You'll want to use the HTTPS endpoint and Shadow Update topic from earlier, along with the credentials for your IAM user. And, of course, don't forget to include the Amazon region.

        In the Twilio related fields, enter a number you own along with the message you'd like to see. Add your_device_number from a phone you have access to for when it's eventually all wired up.

        これで、コンパイルと実行ができるはずです。

        失敗した場合は、以下を確認してください。

        • Did you install all the packages correctly? If you think you did, can you run their example code?
        • Is your board connected properly? Have you selected the proper options?
        • シリアルポートはコンピューターに正しく表示されていますか?

        With any luck, you'll get it going - and if you carefully monitor the 'twilio' MQTT topic in the AWS IoT Test tab you left open, you should soon see a nice JSON message from the ESP8266. Furthermore, if you are using the serial monitor to debug, you should see some messages approximating my (successful) run:

        .
        .
        Connected to WiFi, IP address: 192.168.1.155
        Websocket layer connected.
        MQTT layer connected.
        MQTT subscribed
        MQTT subscribed
        

        If you've got that far, you're actually in very good shape - even if it doesn't look like it yet. If you do have serial monitoring, there is one more test we can perform before moving onto Lambda integration.

        ASW IoTのMQTTテストクライアントでESP8266をテストする

        Back in the AWS IoT MQTT Client, subscribe to the device shadow topic, the same string you should use for shadow_topic on the board itself. Send a message and you'll hopefully see it pop up in your serial monitor, along with some debugging information on the ESP8266. In a fully featured application, you can use the Device Shadow to persist state across power loss (or very long sleep states!), but for now it's sufficient to see the ESP8266 respond.

        以下は、「twilio」トピック上で正常受信されたESP8266のメッセージ出力になります。

        Message #3 arrived: qos 0, retained 0, dup 0, packetid 0
        Payload Current Remaining Heap Size: 20096Hello Internet of a Single Thing...
        

        Amazon Lambda: クライド内の脳髄

        Although we have previously demonstrated sending messages with Twilio directly from an ESP8266, today we're going to pass particular messages through our 'twilio' MQTT topic using a rule to call Lambda functions. Since our eventual application will have two way communication - both incoming and outgoing messages - we'll also introduce how to trigger Lambda functions from within AWS IoT.

        ASW IoTからLambdaをトリガーする

        If you'd like a more detailed explanation of how to work with Lambda functions, along with a primer on loading external libraries (and the Twilio Python Helper library), try our guide on receiving and replying to SMS or MMS messages with Amazon Lambda. If not, start by creating a new Lambda function in the same region as you've set up AWS IoT (the blank template is fine), and configure it to use AWS IoT as a trigger. Check the box for 'Enable Trigger' and name it something memorable (with a matching description). The 'IoT Type' should be set to 'Custom IoT Rule'.

        The SQL statement is where things get interesting. This statement configures exactly when the Lambda function will react to messages on your MQTT topic. Since your application will undoubtedly be adding additional functionality (such as device to device communication), you can avoid invoking Lambda for most messages.

        このガイドで使用すべきSQLステートメントは下記のとおりです:

        SELECT * FROM 'twilio' WHERE Type='Outgoing'
        

        以下は、このステートメントが行う内容になります:

        • 「twilio」MQTTトピック上のJSONオブジェクトから全プロパティーおよびタイプを選択する
        • ... that have a JSON Object with the property 'Type'
        • ... where 'Type' has a value of 'Outgoing'
        • ... それらをLambdaに渡します。

        このようになります:

        Amazon LambdaとAWS IoTを統合する

        SQLバージョンを変更する

        When our ESP8266 publishes messages to the 'twilio' MQTT topic, it will null terminate the strings. That's incompatible with Amazon's 2016-03-23 SQL version.

        Return to the AWS IoT console, and click the 'Rules' link in the left sidepane. You should then see the new rule you've created; click it to see details.

        「Rule query statement」セクションで、「Edit」リンクをクリックし、「Using SQL version」を「2015-10-08」に切り替えます:

        AWS IoT内のAmazon SQLバージョンセレクター

        「Update」ボタンをクリックすると、ルールの発行準備が整っているはずです。

        Adding some Python Code to Lambda

        After creating the function, you're now ready to add some code. On your computer, create a new folder and install the Twilio Python Library manually inside. From the GitHub repository, bring in everything from the 'Lambda Function Send SMS' directory (see our earlier guide for detailed help). Zip the contents of that directory up.

        Now, inside Lambda, change to the 'Code' tab, and select 'Upload a .ZIP File' from the 'Code entry type' pulldown. Select the zip file you just created, and upload it. Ensure you are using the Python 2.7 Runtime.

        In the 'Configuration' tab, change the 'Handler' to 'twilio_functions.iot_handler'. This is pointing to the twilio_functions.py file you just opened, and telling AWS to call the iot_handler() function.

              
              
              
              
              MQTTトピックのメッセージを使用して、TwilioでLambdaからMMSまたはSMSの送信をトリガーします。

              LambdaからSMSまたはMMSを送信する

              MQTTトピックのメッセージを使用して、TwilioでLambdaからMMSまたはSMSの送信をトリガーします。

              Last, you need to set two environmental variables inside Lambda. This can be done from the 'Code' tab.

              Twilio Consoleから下記の値を取得して設定します。

              • AUTH_TOKEN (認証トークン)
              • ACCOUNT_SID - (アカウントSID、例: ACXXXXXXXXXXXXXXXXXXXXXX)

              そして50行以下のコードで、TwilioのMessaging APIへの接続は完了です!

              AWS IoT Twilioインテグレーションのテスト

              It may not seem like it, but you've now got the entire application integrated. MQTT messages published the the 'twilio' topic that match our query will be passed to Lambda, which will extract the necessary fields to send a SMS or MMS message.

              Since we know that the integration between the ESP8266 and AWS IoT is working, testing is simple: power cycle your ESP8266. If you still have the Test MQTT Client open, you should soon see a message published on the 'twilio' topic from the ESP8266 - and this time, you should shortly receive an MMS from your Lambda function.

              小さなパーツで大きなThingを

              And that's a wrap - your Thing -> AWS IoT -> Lambda code is nicely packaged and ready for your custom modifications. The next part is up to you - what will you do now that your swarm of things can send a text message?

              Use your (low) powers for good, and let us know what you've built on Twitter. And if you're ready to push on now, move onto our next article on receiving and replying to messages using the same integration that we've set up today.

              Paul Kamp David Prothero Kat King
              Rate this page:

              ヘルプが必要ですか?

              誰しもが一度は考える「コーディングって難しい」。そんな時は、お問い合わせフォームから質問してください。 または、Stack Overflow でTwilioタグのついた情報から欲しいものを探してみましょう。