This is a tutorial demonstrating how to make a Particle Photon send a SMS (Short Message Service) using Twilio. I have worked on a few projects in the past that read the states of all kinds of sensors and send push notifications to my iPhone. For instance, detecting if a door is open or close with a magnetic reed switch. I accomplished this by publishing events on the Particle Cloud and then created a PHP Heroku App to send the notification. I decided it would be nice to have a system in place that would send a SMS instead of the iPhone app. This way it would work universally with any mobile device.
OverviewWhen a sensor that is attached to the Particle Photon is tripped, it will then publish a private event to the Particle Cloud. We will set up a webhook for that event in the Particle Console that will post data from the event to a Heroku App written in PHP. The Heroku App will then communicate with Twilio's REST API and tell them to send the text message to the number of our choosing.
Here is a video of the finished project in action. I am using the Particle Tinker App to trigger the alert but you can replace this with any sensor you can think of.
PARTICLE SETUPStep 1 - Create a Particle.io AccountFirst thing is first, you will need to create an account with Particle.io in order to access their online Particle IDE and you will also need to purchase a Particle Photon if you don't already have one. For the sake of this tutorial I will assume you have a Photon and have NOT set it up before. If you already have an account and a working Photon skip down to "Step 3 - Start Coding".
- Fill out the form
- Click the "Sign Up" button
The easiest way to claim your Particle Photon with the Particle service is through their mobile app.
- Install the Particle App on your mobile device. It is available for both iPhone & Android (I will be demostrating the iOS app)
- Click the "Get Started" Button at the bottom of the screen and sign in.
- You should see "Setup a new device" menu. From the list, select "Photon":
- Follow the instruction on screen:
- Click "Ready" at the bottom of the screen.
- Again, follow the instruction on screen. If you are unsure of what to do press the "Show me how" button at the bottom of the screen to view a quick video.
- Once you return to the app wait for it to connect to the Photon.
- You will then be prompted to select your wifi network and input your password. Then click connect.
- Your device will then connect to the internet and the Particle Cloud.
- Once setup is complete you will be prompted to name your Photon. Im going to keep the auto generated name for mine, gerbil_doctor, but you can name yours what you'd like. Select Done.
- Now that your Photon is setup, the RGB LED in the center of the board should be breathing cyan and you will see it in your device list.
- If you have any issues with setup you can refer to Particle's troubleshooting page.
- Select your Photon from the the list.
- This is what the Tinker App looks like. You can select any pin to write or read from here. Pin D7 is connected to an on board blue led. If we make that pin HIGH it will turn the pin On and LOW will turn it Off. Let's try it.
- Tap the D7 pin.
- Choose "digitalWrite"
- Now tap the D7 pin and it will alternate between HIGH and LOW, turning the blue LED on and off. Congratulations, you're all setup.
Now that we have successfully created our account and setup our Photon it is time for the fun stuff, writing the code. By default, your Photon should have the Tinker App flashed to it. We will modify the Tinker App's code to publish an event whenever pin D7's state has changed. Which, if you remember, is connected to an on-board blue LED.
- Go to https://build.particle.io to access the online Particle IDE.
- Under "Example Apps" in the "Particle Apps" menu to the left you will see "Tinker" click on it.
- Then click "Use This Example"
- Select line 6 in the coding area. Add this,
int previousState = 0;
This variable will be used to keep track of the previous state of the pin. By doing this we will be able to ensure that our event code will only run once.
- Copy and Paste the following code to your main loop.
// Read the current state of D7 Pin.
int currentState = digitalRead(D7);
// Check if current state of D7 is different than previous state
if (currentState != previousState){
if(currentState){
// State is HIGH
Particle.publish("Twilio-SMS/{YOUR_PHONE_NUMBER_HERE}","The blue LED is now ON!", PRIVATE);
} else {
// State is LOW
Particle.publish("Twilio-SMS/{YOUR_PHONE_NUMBER_HERE}","The blue LED is now OFF!", PRIVATE);
}
// Update previousState variable
previousState = currentState;
}
- Replace
{YOUR_PHONE_NUMBER_HERE}
with your phone number in the following format +15555555555
- Your main loop should look like this...
- Now you are ready to verify your code by clicking the check mark.
- If all is well you will see "Great Work" at the bottom of the screen.
- You are ready to flash the code to your Photon. Do this by clicking the Lightning bolt in the top left of the screen.
- You will see your device flash magenta as it flashes your code. Just wait until your device starts breathing cyan again and you are done with the code.
Heroku is a cloud platform that lets companies build, deliver, monitor and scale apps. We are going to use it host a PHP app that will send commands to Twilio's REST API.
For the sake of the tutorial I am going to assume you are new to Heroku and have not created an account. In this section I will walk you through signup and installing the Heroku CLI and other dependancies that we will need. I am using a Mac, if you are a PC person, I'm sorry some steps may be different and you can refer to Heroku's documentation to help fill the gaps.
Step 1 - Create a Heroku Account- Go to https://signup.heroku.com/login to create an account.
- Once you are done with the sign up process you should be greeted by your Dashboard. This is where you will see a list of apps once you have created them. But for now we don't need to do anything here.
I'd like you to take a look at Getting Started on Heroku with PHP. If you would like more information on the following steps this is where you will find it.
By this point you should already have an account with Heroku and PHP should also be installed on your Mac by default.
Step 2a - Installing Composer Globally On Your MacComposer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.
- Open up terminal. If you are unfamiliar with Terminal the easiest way to open if you are on the latest versions of Mac OS is to press "cmd⌘ + spacebar" or click the magnifying glass in the top right corner of your desktop to open the spotlight search. Then type "Terminal" and press enter.
- Type the following commands one at a time.
curl -sS https://getcomposer.org/installer | php
- Composer will be downloaded. Now we will move it so we can use it globally.
mv composer.phar /usr/local/bin/composer
- To check that it is properly installed we will check the version.
composer --version
- If we see a version number than it is installed and we can move forward. If you have issues installing composer please refer to their website.
The heroku command-line interface (CLI) is a tool that wraps the Heroku Platform API, providing support for things like creating/renaming apps, running one-off dynos, taking backups, configuring add-ons and managing your app's state-all from the terminal.
- Download & Install the Heroku CLI here.
- Once Installed, open terminal again and type the following
heroku login
- Proceed to type in your login information. Once you have completed this you are all set with Heroku.
Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency. If you would like to learn more about git Atlassian has a good git tutorial here.
- Download Git & Install it to you computer. You can get it here.
- Confirm fit was installed by typing the following into terminal.
git --version
- If you see a version number you are all done with install ing Heroku and its dependancies.
We are going to create a folder in your documents folder to save your Heroku App and I will walk you through setting up composer and the dependancies we will need for app.
Step 3a - Create Folders To Save Your Project- Open Terminal
- Type
cd documents
mkdir Twilio-Alerts
- This will create a folder named "Twilio-Alerts" where we will save our app.
cd Twilio-Alerts
Now that we are in our apps folder we will initialize git.
- Type:
git init
Step 3c - Create Heroku AppNow we will create a new Heroku App.
- Type
heroku create
This will create the Heroku app with a randomly generated name. Mine is named "ancient-mountain-25217"
- Type
heroku git:remote -a ancient-mountain-25217
- replacing my apps name with the name of your app.
Our app is setup with Heroku and the git is initialized now we need to create a composer.json file with the dependancies needed for our app.
- In Terminal type
composer init
- You can skip the first few inputs by hitting Enter 6 times.
- It will ask you "Would you like to define your dependencies (require) interactively [yes]?" Type
yes
and hit enter.
- It should say "Search for a package: " Type
twilio/sdk
- leave the version blank and hit enter again, it will use the latest version.
- Hit enter again to skip over "Search for a package: "
- Now it will ask you "Would you like to define your dev dependencies (require-dev) interactively [yes]?" Type
Yes
- Type:
heroku/heroku-buildpack-php
- Press enter to skip the version input
- Press enter again to finish with the setup
- It will generate the JSON file and you can type
yes
to accept it.
- Type
yes
to add the vendor file to .gitignore
- Now type
composer update
to generate the composer.lock file
Now that we have setup our composer file to handle our dependancies we can push the git to heroku for the first time.
- Type
git add .
- Press enter
- Type
git commit -am "Initial push"
- Press enter
- Type
git push heroku master
- Once you see
remote: Verifying deploy... done.
you will now that it was successful in pushing your files to heroku.
I am using Sublime Text as my text editor to write PHP. You can use any text editor that you want though.
- Open Sublime Text
- Copy the following code into the editor.
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once 'vendor/autoload.php'; // Loads the library
use Twilio\Rest\Client;
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "your_sid";
$token = "your_access_token";
$client = new Client($sid, $token);
$strFrom = 'your_twilio_number';
if($_POST["event"]) {
$strTo = explode("/", $_POST["event"], 2)[1];
$msg = $_POST["data"];
$client->messages->create(
$strTo,
array(
'from' => $strFrom,
'body' => $msg,
)
);
echo "Success";
} else {
echo "Fail";
}
?>
- Save this file as
Index.php
in the Twilio-Alerts folder that we created located in your documents folder.
Twilio is a cloud communications platform as a service company. Twilio allows software developers to programmatically make and receive phone calls and send and receive text messages using its web service APIs. We are going to take advantage of the text messages API for this tutorial. As always I am assuming you have never used Twilio before and I will make this as easy as I can for you to follow.
Step 1 - Create A Twilio Account- Go to https://www.twilio.com/try-twilio to sign up for a account.
- Twilio will need to verify you are a human. Enter you phone number and they should text you a code.
- Enter the code that was sent to you via SMS and click Submit
- You will now see your Programmable SMS Dashboard, click "Get Started"
- Click "Get your first Twilio number"
- Twilio will automatically find a number for you in your local area. If you don't like this number you can search for a different one. Click "Choose this Number" when ready.
- You have successfully added a number click "Done"
- Now that we have acquired a Phone Number for our twilio account you can test out the texting ability on this dashboard. Simply enter a message in the "Body" field and click "Make request". You should receive a text message after a few seconds. You are now ready to move on to the final step.
Now that you have setup an account with Twilio, you are ready to connect everything together.
Step 1 - Connect Heroku App to TwilioSince we already have Twilio open we are going to start there.
- Click the home button in the top left of your screen.
- Copy your Account SID & Paste it into your
index.php
file where it says$sid = "your_sid";
Put it between the quotes. It should look something like this$sid = "xxxxxxxxxxxxxxxxxxxx";
.
- Now, Copy & Paste your Auth Token to where is says
$token = "your_access_token";
Again it should look something like this$token = "xxxxxxxxxxxxxxxxxxxxxx";
- Now we need to add your twilio number to Index.php. You can find your Twilio number by clicking on the number button in the left menu. Once you know your number enter it where it says
$strFrom = 'your_twilio_number';
Enter it in this format "+15555550000"
- Your index.php file should now look like this...
- Now our code is ready and we can push this to Heroku
- Open Terminal
- Navigate to the folder that your project is stored.
$ cd documents/Twilio-Alerts
- Type:
git add .
git commit -am "Updated index.php"
git push heroku master
Step 2 - Particle To HerokuIn order to launch our heroku app we are going to take advantage of Particle's webhook capability. A WebHook is an HTTP callback: an HTTP POST that occurs when something happens; a simple event-notification via HTTP POST. A web application implementing WebHooks will POST a message to a URL when certain things happen. In our case it will post the event name and data to our Heroku app when an event happens.
- Click "New Integration"
- Click "Webhook"
- In the "Event Name" Field, enter your event name that we put in the Tinker code. In this case it is
Twilio-SMS
- In the "URL" field enter the address to our Heroku App. The url to your app is
https://{YOUR-APP-NAME}.herokuapp.com
- Just replace "{YOUR-APP-HERE}" with your apps name. If you forget your apps name you can find it here.
- Click "Create Webhook" button.
Congratulations, you are all done! Only thing left now is to test that everything is working.
- Open the particle app on your phone
- Select your device name from the device list.
- Tap the pin D7
- Select digitalWrite()
- Now tap D7 as many times as you would like to toggle the Particle's blue LED on and off. Each time you should receive a text message at the phone number that you entered in the Photon's code.
As you can see by my last screen shot Twilio will allow you to send a SMS with some limitations. That is of course unless you upgrade to their paid tier which you can get pricing information here. Heroku also has its own limitations you can read about their pricing here. And of course here is Particle's pricing as well. All of these services that I am using offer a free version that you should be able to use just fine for hobby and development purposes.
This was my first tutorial I hope you enjoyed it and I look forward to see what you make with it, please share you projects with me. The applications for this are endless, you could use it to notify you of all sorts of things. For example, use this system with a reed switch and be notified if a window, door, or drawer is opened/closed. Use it with a weather station outside your house to notify you of the temperature, wind speed, or humidity. Create a scale and weight items like laundry detergent, milk, or a keg of beer and have the system notify you when they are running low. No one likes being without beer. Hope you found this informative and good luck.
If you want more tutorials like this one let me know.
Comments