tag:blogger.com,1999:blog-367063218020128492024-03-12T21:18:40.145-07:00kilomonBUILD | MONITOR | AUTOMATEDanhttp://www.blogger.com/profile/01422027852211426218noreply@blogger.comBlogger11125tag:blogger.com,1999:blog-36706321802012849.post-60135948482159589362018-02-14T16:33:00.001-08:002018-02-14T16:34:13.937-08:00Powershell - Collecting and Reporting on SQL Instances<h2 style="height: 0px;">
Generate a list of every SQL Instance on your Servers</h2>
<div>
<br /></div>
<div>
To be successful as a Systems Administrator, you need to be able to collect information about your environment. This little guide will show you a simple and effective way to collect and report on every SQL Instance that is installed on a server in your domain.</div>
<h3>
Overview</h3>
<div>
I like to write functions and automated collection scripts, so I can have up to date reports. Sometimes it makes more sense to take someone else's code if for no reason other than saving time and effort. </div>
<div>
<br /></div>
<div>
I have been using <a href="https://gallery.technet.microsoft.com/scriptcenter/Get-SQLInstance-9a3245a0" target="_blank">Boe Prox's useful Get-SQLInstance</a> for several years and thought I would share how I use it. Get-SQLInstance supports SQL versions 2000 - 2016.</div>
<h3>
Prereqs</h3>
<div>
<ul>
<li>You need an account with Administrative permissions on every server you want to run the script against</li>
<li>The account must have the ability to query AD for server names</li>
<li>Download Get-SQLInstance from <a href="https://gallery.technet.microsoft.com/scriptcenter/Get-SQLInstance-9a3245a0">https://gallery.technet.microsoft.com/scriptcenter/Get-SQLInstance-9a3245a0</a></li>
</ul>
</div>
<div>
<ul>
<li>Create a script folder and a report folder</li>
<ul>
<li>Examples would be c:\scripts and c:\reports</li>
</ul>
<li>Place the Get-SQLInstance in the scripts folder</li>
<ul>
<li>It can be a great strategy to keep your scripts on a file share, so they can be accessed from any machine you wish.</li>
</ul>
<li>Open Powershell or Powershell ISE</li>
</ul>
<h3>
AD Domain</h3>
</div>
<div>
<ul>
<li>Using Powershell ISE, create a new .ps1 named Report-SqlInstances.ps1 and place it in your scripts folder</li>
<li>Paste the following code into the editor and save</li>
</ul>
<div>
My apologies for the interesting color coding.</div>
<div>
<div>
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?skin=desert"></script>
<br />
<pre class="prettyprint"># Load the Get-SQLInstance cmdlet
. C:\scripts\Get-SQLInstance.ps1
# Create a list of all server names on the AD domain
$servers = Get-ADComputer -filter 'OperatingSystem -like "*server*"'
# Count the total number of servers to scan for SQL
$count = $servers.count
$i = 1
# Create an object to hold all our SQL data that will be returned
$output = @()
foreach ($server in $servers){
# Output the server name and the count
Write-Host "[$i : $count] $($server.Name)"
# Ping the server once prior to attempting to connect
# This speeds up the script a bit
if ((ping $server.name -n 1) -match 'reply'){
$data = Get-SQLInstance -Computername $server.Name
# If any SQL data was found, add it to the output object
if ($data){
$output += $data
}
}
else {
Write-Host " No Response" -ForegroundColor Yellow
}
# Increment the counter
$i++
}
# Export the list to a CSV file
$output | Export-CSV -Path c:\reports\sqllist.csv -NoTypeInformation
</pre>
</div>
</div>
<h3>
Stand Alone Servers</h3>
<div>
<ul>
<li>To report on a single server, run this from the console</li>
</ul>
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?skin=desert"></script>
<br />
<pre class="prettyprint">Get-SQLInstance -ComputerName "YOUR SERVERNAME" | Export-CSV -Path c:\reports\sqlinfo.csv -NoTypeInformation</pre>
</div>
</div>
<h3>
Potential Improvements</h3>
<div>
There are some things I typically like to add to any report script. I am giving a list here to give you an idea of what you might like to add. </div>
<h4>
Performance</h4>
<div>
<ul>
<li>Job concurrency using Start-Job</li>
</ul>
<h4>
Usability</h4>
<ul>
<li>Use an input file such as a .TXT or .CSV to gather server names to process</li>
<li>Automatic creation of Excel file</li>
<li>Email report in HTML format</li>
<li>Writing data to a reporting DB such as Microsoft SQL Server</li>
<li>Logging to Window Events or a log file</li>
<ul>
<li>This can include information, warning, and errors</li>
</ul>
</ul>
</div>
Danhttp://www.blogger.com/profile/01422027852211426218noreply@blogger.com0tag:blogger.com,1999:blog-36706321802012849.post-73910025160539670842018-02-14T09:12:00.000-08:002018-02-14T21:23:38.371-08:00Creating a PC Fan Power Hub<h2 style="height: 0px;">
DIY PC Fan Hub</h2>
<div>
<br /></div>
<div>
I recently ran out of fan power headers on my PC motherboard. A quick search online and about $12 later, I had a <a href="http://amzn.to/2H8EPXa" target="_blank">fan hub</a> heading my way. A few days later I had the fan hub installed in about 5 minutes and all my fans were adding to the office noise. The thing is... I couldn't stop thinking about how easy it would be to make.</div>
<h3>
Overview</h3>
<div>
Fast forward a couple months and I find myself in need of a way to hook up some 120mm fans for cooling purposes. This time I want to find out if building my own fan hub is worth the effort.</div>
<div>
<br /></div>
<div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-mN82owne67c/WoRi5sRxrwI/AAAAAAAAARI/E_lCPwp5ujshWA7lZZIYK54qFFVRK9YjACK4BGAYYCw/s1600/pcfanhub_0008.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="360" src="https://2.bp.blogspot.com/-mN82owne67c/WoRi5sRxrwI/AAAAAAAAARI/E_lCPwp5ujshWA7lZZIYK54qFFVRK9YjACK4BGAYYCw/s640/pcfanhub_0008.JPG" width="640" /></a></div>
I have four 120mm PC fans that need to be powered. I would like to have the option of adding more fans later. I want to keep it cheap and simple. I will use a 12V wall wart and will add switch to power on and off. I had considered throwing a Nodemcu on it and making it a Smart fan hub. It might be a fun little project, but I have several Sonoff switches that I hacked and programmed for use with Alexa. You can see the Sonoff series at <a href="http://blog.kilomon.com/2018/01/hacking-sonoff-wifi-switch.html">http://blog.kilomon.com/2018/01/hacking-sonoff-wifi-switch.html</a><br />
<br />
<i>DISCLAIMER: I am not an electrical engineer, so don't assume I know what I am talking about :)</i></div>
<div>
<h3>
Prep</h3>
</div>
<h4>
Sourcing the Parts</h4>
<div>
The 4 pin CPU connector that you see on your motherboard is the <a href="https://www.molex.com/molex/products/datasheet.jsp?part=active/0470531000_PCB_HEADERS.xml&channel=Products&Lang=en-US" target="_blank">Molex KK 47053-1000</a>. I spent a considerable amount of time trying to find a knock off brand at a reasonable price. Individual prices ranged for 0.29 - $0.45 each. not including shipping and tax. I could go the bulk route using Mouser or Digikey, but that seems overkill. If you know of a more affordable source, drop me a comment.</div>
<div>
<br /></div>
<div>
The 3 pin connector was easier to find. (Some options I found <a href="http://amzn.to/2CegBHt" target="_blank">http://amzn.to/2CegBHt</a> <a href="http://amzn.to/2H4CPPQ" target="_blank">http://amzn.to/2H4CPPQ</a>)<br />
<br />
In the end, I made a compromise. I bought these <a href="http://amzn.to/2H7gNMp" target="_blank">3 pin connectors</a> and will report on them when they arrive. In the meantime, I will use some standard 2.54mm PCB pin headers that I always have available. If you don't own any 2.54mm pin headers, its worth having some. They have become the de facto standard for creating shields and break out boards for MCU's.<br />
<h4>
Parts I Used</h4>
<div>
Purchasing all these parts will cost more than an off-the-shelf fan hub. I had these parts on hand and so there was no cost to me. However, if you purchase these parts, you will be able to use them for many other projects.<br />
<br />
I estimate the final cost of the parts I used to be around $3 (not including the fans).</div>
<ul>
<li><a href="http://amzn.to/2EIgh98" target="_blank">120mm PC Fan</a> (3 Pin)</li>
<li><a href="http://amzn.to/2Cl1lsn" target="_blank">2A 12VDC Power Adapter</a></li>
<ul>
<li>You should calculate your power needs</li>
<li> Running 10 of these fans the amp usage calculates to 1.6A.</li>
</ul>
<li>Snap-able Male Pin Headers (some options below)</li>
<ul>
<li><a href="http://amzn.to/2Cf9FKc" target="_blank">100 Piece 40 Pin Male Headers</a></li>
<li><a href="http://amzn.to/2Ch4b1E" target="_blank">Pin Header Kit</a></li>
<li><a href="http://amzn.to/2HaN5Ge" target="_blank">90 Degree Pin Headers</a></li>
</ul>
<li>Double Sided Prototype Board (some options below)</li>
<ul>
<li><a href="http://amzn.to/2CiZYKY" target="_blank">Prototype Board Kit with pin headers and terminal blocks</a></li>
<li><a href="http://amzn.to/2soONAx" target="_blank">Prototype Board Kit</a></li>
<li><a href="http://amzn.to/2CiYakM" target="_blank">Stripboard</a> would be ideal for this project, but costs a bit more</li>
</ul>
<li><a href="http://amzn.to/2HbbJqk" target="_blank">PCB Mount DC Power Jack</a> (bread board style pins are easier, but this is what I have)</li>
<ul>
</ul>
<li><a href="http://amzn.to/2BubJBw" target="_blank">Small Slide Switch</a> </li>
<li><a href="http://amzn.to/2HclmVw" target="_blank">Rubber Feet</a> or <a href="http://amzn.to/2HbqDga" target="_blank">Mounting Tape/Pads</a></li>
<li><a href="http://amzn.to/2ElF9U2" target="_blank">22 AWG Hook Up Wire</a></li>
<li><br /></li>
</ul>
<h4>
Tools I Used</h4>
</div>
<div>
<ul>
<li><a href="http://amzn.to/2BHKDHH" target="_blank">Wire Cutter/Stripper Combo</a></li>
<li><a href="http://amzn.to/2GVL3Kc" target="_blank">Needle Nose Pliers</a></li>
<li><a href="http://amzn.to/2nRfdWi" target="_blank">Soldering Iron Station</a></li>
<li><a href="http://amzn.to/2sdpZLQ" target="_blank">Soldering Iron Tip Cleaner</a></li>
<li><a href="http://amzn.to/2E79r9H" target="_blank">Rotating Circuit Board Holder</a></li>
<li><a href="http://amzn.to/2E52kTg" target="_blank">Third Hand</a></li>
<li><a href="http://amzn.to/2EC6FNe" target="_blank">Mounting Putty</a> or Tape (for sticking things to the protoboard for soldering)</li>
<li><a href="http://amzn.to/2GTHhkz" target="_blank">Hot Glue Gun</a></li>
<li><a href="http://amzn.to/2EmdnHQ" target="_blank">Hot Glue</a></li>
</ul>
<h3>
Some Design Options</h3>
<div>
There are some other ideas I thought of incorporating into this project:</div>
<div>
<ul>
<li>Power Indicating LED</li>
<li>Power regulation and power conditioning (power supply fundamentals)</li>
<li>SATA or Molex connector for use inside a PC</li>
</ul>
</div>
<h3>
Wiring</h3>
</div>
<div>
This is about as simple as you can get. This design has no power regulation and assumes the user is smart enough not to hook more than 12V and that they take precaution not overload their power adapter/wallwart.<br />
<br />
Essentially, the male header pins are placed on power rails and power is controlled by the SPDT sliding switch.<br />
<a href="http://4.bp.blogspot.com/-hF2ofxPXVlQ/WoUVVL1Y-KI/AAAAAAAAASA/g5NRBOLCTg8LR2ThvPaLpJwhcPxLTRzNgCK4BGAYYCw/s1600/fanhub_diagram.PNG" imageanchor="1"><img border="0" height="430" src="https://4.bp.blogspot.com/-hF2ofxPXVlQ/WoUVVL1Y-KI/AAAAAAAAASA/g5NRBOLCTg8LR2ThvPaLpJwhcPxLTRzNgCK4BGAYYCw/s640/fanhub_diagram.PNG" width="640" /></a></div>
<div>
<h3>
Assembly</h3>
</div>
<div>
<ul>
<li>Start by snapping your male headers into 3 pins or 4 pins based on your fan connector</li>
<ul>
<li>I tried both 90 pins and standard pins. I decided on standard pins.</li>
</ul>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-n4QLy4jKtI8/WoRi46j9EZI/AAAAAAAAAPg/yyCw9miw8ScomHvScPr_ezm-gdpn_bFnQCK4BGAYYCw/s1600/pcfanhub_0005.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="360" src="https://3.bp.blogspot.com/-n4QLy4jKtI8/WoRi46j9EZI/AAAAAAAAAPg/yyCw9miw8ScomHvScPr_ezm-gdpn_bFnQCK4BGAYYCw/s640/pcfanhub_0005.JPG" width="640" /></a></div>
<ul>
<li>Place the pin headers on the protoboard to find a good fit. I liked a 2 hole spacing.</li>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-EepN2zWppf8/WoRi589_zQI/AAAAAAAAARY/jMjnMLUgMzcY9psT2a-Xve9kXOGN-uJkQCK4BGAYYCw/s1600/pcfanhub_0007.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="360" src="https://1.bp.blogspot.com/-EepN2zWppf8/WoRi589_zQI/AAAAAAAAARY/jMjnMLUgMzcY9psT2a-Xve9kXOGN-uJkQCK4BGAYYCw/s640/pcfanhub_0007.JPG" width="640" /></a></div>
<ul>
<li>Test connecting the fans to see how things fit</li>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-cxWU8o2QBC4/WoRi5NOYMCI/AAAAAAAAAP0/Hsjn8YwwcGQ3sB_qJLX-aun3rbi4qIpGwCK4BGAYYCw/s1600/pcfanhub_0006.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="360" src="https://3.bp.blogspot.com/-cxWU8o2QBC4/WoRi5NOYMCI/AAAAAAAAAP0/Hsjn8YwwcGQ3sB_qJLX-aun3rbi4qIpGwCK4BGAYYCw/s640/pcfanhub_0006.JPG" width="640" /></a></div>
<div>
<ul>
<li>Next place the DC barrel jack and SPDT switch on the protoboard to make sure things fit (you can see I considered placing an LED as a power indicator)</li>
<li>TIP: If you have a DC barrel jack with lugs like shown in my pictures, place it on its side and hot glue to the board</li>
</ul>
</div>
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-K3KlsuFevPM/WoRi539CfWI/AAAAAAAAARQ/AAlTOqfFyxgHjwO39rde6hA1781X9fRywCK4BGAYYCw/s1600/pcfanhub_0012.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="360" src="https://4.bp.blogspot.com/-K3KlsuFevPM/WoRi539CfWI/AAAAAAAAARQ/AAlTOqfFyxgHjwO39rde6hA1781X9fRywCK4BGAYYCw/s640/pcfanhub_0012.JPG" width="640" /></a></div>
<div>
<ul>
<li>Once you like the placement, start wiring things up.</li>
</ul>
</div>
<div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-AfUahuWZOGY/WoRi5NU1FZI/AAAAAAAAAPo/l2PkyeXD_0wk92J5gDgAd-QIOJxl16l2wCK4BGAYYCw/s1600/pcfanhub_0014.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="360" src="https://4.bp.blogspot.com/-AfUahuWZOGY/WoRi5NU1FZI/AAAAAAAAAPo/l2PkyeXD_0wk92J5gDgAd-QIOJxl16l2wCK4BGAYYCw/s640/pcfanhub_0014.JPG" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-M5IVY0VZqy8/WoRi5rrv5DI/AAAAAAAAAQ4/5W4OUpaNXTUq6kKXVKrw6Utiu1vEUDxNwCK4BGAYYCw/s1600/pcfanhub_0013.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="360" src="https://4.bp.blogspot.com/-M5IVY0VZqy8/WoRi5rrv5DI/AAAAAAAAAQ4/5W4OUpaNXTUq6kKXVKrw6Utiu1vEUDxNwCK4BGAYYCw/s640/pcfanhub_0013.JPG" width="640" /></a></div>
<br />
<ul>
<li>Use some mounting putty or tape to hold the pin headers while soldering</li>
<ul>
<li>Here you can see gaffers tape wrapped around the board to hold the pins</li>
</ul>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-lxDX9L-AcTQ/WoRi5FIQJ1I/AAAAAAAAAQo/4yq36AyZAQA0yCXBJHZAK1SneZD-ZUqVQCK4BGAYYCw/s1600/pcfanhub_0016.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="360" src="https://3.bp.blogspot.com/-lxDX9L-AcTQ/WoRi5FIQJ1I/AAAAAAAAAQo/4yq36AyZAQA0yCXBJHZAK1SneZD-ZUqVQCK4BGAYYCw/s640/pcfanhub_0016.JPG" width="640" /></a></div>
<div>
<ul>
<li>Using stripped bare 22AWG wire, I created the power rails</li>
</ul>
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div>
<ul>
<li>Once the first side of power rails was soldered, I test things</li>
</ul>
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-ROOYIKUaR6Q/WoRi5suqcjI/AAAAAAAAARU/xLJn65bEgAQcRJIPfQil247IXHPutxk8gCK4BGAYYCw/s1600/pcfanhub_0017.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="360" src="https://3.bp.blogspot.com/-ROOYIKUaR6Q/WoRi5suqcjI/AAAAAAAAARU/xLJn65bEgAQcRJIPfQil247IXHPutxk8gCK4BGAYYCw/s640/pcfanhub_0017.JPG" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-m6Q-wlgIaPA/WoRi5YoeLaI/AAAAAAAAAQw/9QySMBgfTnk26LkFmEFmOks_KULQeg9_ACK4BGAYYCw/s1600/pcfanhub_0018.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="360" src="https://2.bp.blogspot.com/-m6Q-wlgIaPA/WoRi5YoeLaI/AAAAAAAAAQw/9QySMBgfTnk26LkFmEFmOks_KULQeg9_ACK4BGAYYCw/s640/pcfanhub_0018.JPG" width="640" /></a></div>
<div>
<ul>
<li>Happy with the first test, I soldered the bare wire power rails on the second row of pin headers</li>
<ul>
<li>Please note I placed jumpers between the rails on the top side of the board</li>
</ul>
</ul>
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-uQVoxHUjDao/WoRi5lYOdjI/AAAAAAAAAQ8/CZ1CyidngdgGEKyQmPGC1uLsZRTMONGFQCK4BGAYYCw/s1600/pcfanhub_0021.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="360" src="https://3.bp.blogspot.com/-uQVoxHUjDao/WoRi5lYOdjI/AAAAAAAAAQ8/CZ1CyidngdgGEKyQmPGC1uLsZRTMONGFQCK4BGAYYCw/s640/pcfanhub_0021.JPG" width="640" /></a></div>
<br />
<ul>
<li>After testing a fan on the second row of pin headers, I hot glued the power rails for some added protection and add rubber feet for stability</li>
<ul>
<li>Note that I did not hot glue around the switch solder joints just in case I decide to add that power indicating LED</li>
</ul>
</ul>
<div class="separator" style="clear: both; text-align: center;">
</div>
<h3>
Result</h3>
</div>
<div>
The fan hub is working great. It could be made better with an enclosure of some type. I have connected it to one of my <a href="http://blog.kilomon.com/2018/01/hacking-sonoff-wifi-switch.html" target="_blank">hacked Sonoff's</a>. I am now controlling my fans with Alexa and Alexa routines.</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<i><br /></i></div>
Danhttp://www.blogger.com/profile/01422027852211426218noreply@blogger.com0tag:blogger.com,1999:blog-36706321802012849.post-43626272020748696412018-02-09T20:59:00.001-08:002018-02-10T15:12:48.423-08:00Creating Alexa Skills for IoT and Nodemcu - Part 3 Alexa and Lambda<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-pvtPc3T3Xq0/WnizCMqUXsI/AAAAAAAAAGA/zsX9jX4A47oDRPRFX-G4v3W8sW57iPluwCPcBGAYYCw/s1600/nodemcu_alexa_diagram_2.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="734" data-original-width="881" height="531" src="https://2.bp.blogspot.com/-pvtPc3T3Xq0/WnizCMqUXsI/AAAAAAAAAGA/zsX9jX4A47oDRPRFX-G4v3W8sW57iPluwCPcBGAYYCw/s640/nodemcu_alexa_diagram_2.PNG" width="640" /></a></div>
<h2>
Reading Nodemcu IoT Data with Alexa</h2>
<div>
This is the final post in a series aimed at connecting Alexa to a Nodemcu that is collecting temperature and humidity data. </div>
<div>
<br /></div>
<div>
<a href="http://blog.kilomon.com/2018/02/creating-alexa-skills-for-iot-nodemcu.html">Go to Part 1 - Design</a></div>
<div>
<a href="http://blog.kilomon.com/2018/02/creating-alexa-skills-for-iot-and.html">Go to Part 2 - AWS IoT</a></div>
<h3>
Overview</h3>
<div>
I recommend reviewing my first post in this series, so you can understand the game plan... but here's the short version. We will create and configure three separate services in AWS. An Alexa Skill for voice commands, a AWS Lambda function that will act as a middle man, and AWS IoT for storing the current state of the Nodemcu sensors.</div>
<div>
<br /></div>
<div>
<i>DISCLAIMER: This guide uses a work around to allow Nodemcu to communicate directly with AWS IoT. The work around uses API keys that will be written in cleartext on the Nodemcu. Proceed at your own discretion.</i></div>
<div>
<h3>
Goals</h3>
</div>
<div>
<ul>
<li>Create a AWS Lambda function that will collect the Nodemcu data that was sent to AWS IoT</li>
</ul>
<ul>
<ul>
<li>This will be written in Python</li>
</ul>
</ul>
<ul>
<li>Create an Alexa Skill to read data gathered by the Lambda function</li>
</ul>
<ul>
<li>Setup a security policy to provide Lambda access to Thing Shadow state in AWS IoT</li>
</ul>
<h3>
Prep</h3>
</div>
<div>
I considered showing how to setup the appropriate accounts on AWS and Amazon Developer, but it seems there are plenty of good resources to show how to do that. Put your google-fu skills to work or take a wild stab at it.</div>
<div>
<br />
<ul>
<li>A Nodemcu sending data to AWS IoT Thing Shadow <a href="http://blog.kilomon.com/2018/02/creating-alexa-skills-for-iot-and.html">Part 2 - AWS IoT</a></li>
</ul>
<ul>
<li>An AWS Account from creating Lambda functions (free tier allows 1M messages a month)</li>
</ul>
<ul><ul>
<li>This would have been setup to complete Part 2</li>
</ul>
</ul>
<ul>
<li>An Amazon Developer account for creating Alexa Skills</li>
</ul>
<ul>
<li>(Optional) Echo Dot - <a href="http://amzn.to/2EeGNaP">http://amzn.to/2EeGNaP</a></li>
</ul>
<ul><ul>
<li>You can test everything using the Alexa Skills Kit or <a href="https://echosim.io/welcome" target="_blank">Echosim.io</a> if you don't have an Echo Dot</li>
</ul>
</ul>
</div>
<div>
You can find the parts and components I used to build the sensor in <a href="http://blog.kilomon.com/2018/02/creating-alexa-skills-for-iot-and.html">Part 2 - AWS IoT</a></div>
<div>
<h3>
Steps - Alexa Skill</h3>
<span style="font-family: inherit;"><span style="font-size: small; font-weight: 400;">In the </span><a href="http://blog.kilomon.com/2018/02/creating-alexa-skills-for-iot-and.html" style="font-weight: 400;">previous post</a><span style="font-size: small; font-weight: 400;">, we configured our Nodemcu to send temperature and humidity data to an AWS IoT Thing Shadow. Our next step is to get that data to a web service that Alexa can access and read it. Amazon recommends using AWS Lambda.</span></span><br />
<h4>
Creating the Skill</h4>
<ul>
<li><span style="font-family: inherit;"><span style="font-size: small; font-weight: normal;">Open the Developer Console at <a href="https://developer.amazon.com/" style="font-family: inherit;">https://developer.amazon.com</a><span style="font-family: inherit;"> > Alexa > Alexa Skills Kit - Get Started</span></span></span></li>
<li><span style="font-family: inherit;"><span style="font-size: small; font-weight: normal;">Add a New Skill > Ensure Custom Interaction Model is selected</span></span></li>
<li><span style="font-family: inherit;"><span style="font-size: small; font-weight: normal;">Create a Skill Name such as Sensor Reader</span></span></li>
<ul>
<li><span style="font-family: inherit;"><span style="font-size: small; font-weight: normal;">Note that if you intend on releasing a skill for public use this Name will be search-able by other Alexa users.</span></span></li>
</ul>
<li><span style="font-size: small; font-weight: normal;">Create an Invocation Name such as sensor reader</span></li>
<ul>
<li><span style="font-weight: normal;"><span style="font-size: small;">The Invocation Name is how you will trigger the Skill when giving commands to Alexa such as "Alexa, ask sensor reader what the temperature is in the office"</span></span></li>
</ul>
</ul>
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-NfMZIjwNjgU/Wn3OmRMhOkI/AAAAAAAAAL0/oUfLC0wXDEY1-KA1wCL94CdlqqD_bmOCACK4BGAYYCw/s1600/alexa_skillcreation_1.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: inherit; font-size: small; font-weight: normal;"><img border="0" src="https://2.bp.blogspot.com/-NfMZIjwNjgU/Wn3OmRMhOkI/AAAAAAAAAL0/oUfLC0wXDEY1-KA1wCL94CdlqqD_bmOCACK4BGAYYCw/s1600/alexa_skillcreation_1.PNG" /></span></a></div>
<div>
<br />
<ul>
<li><span style="font-weight: normal;"><span style="font-size: small;">Select Save and copy the Application Id to your text editor for use in later steps</span></span></li>
<li><span style="font-weight: normal;"><span style="font-size: small;">Select Next</span></span></li>
</ul>
</div>
</div>
<h4>
The Interaction Model</h4>
<h3>
<div>
<span style="font-size: small; font-weight: normal;">I want the skill to tell me the temperature and humidity of a specific room. To do this we need to build an Interaction Model that tells the Skill how to respond.</span></div>
<div>
<span style="font-size: small; font-weight: normal;"><br /></span>
<span style="font-size: small; font-weight: normal;">If you would like a better understanding of how Interaction Models work, an in depth reference is found at </span><a href="https://developer.amazon.com/docs/custom-skills/custom-interaction-model-reference.html" style="font-size: medium; font-weight: normal;" target="_blank">https://developer.amazon.com/docs/custom-skills/custom-interaction-model-reference.html</a></div>
<div>
<div>
<span style="font-size: small; font-weight: normal;"><br /></span></div>
<div>
<span style="font-size: small; font-weight: normal;">Here is a simple explanation of the parts in the Interaction Model:</span></div>
<div>
<span style="font-size: small;"> Utterance:<span style="font-weight: normal;"> The words you speak to Alexa "Alexa, ask Sensor Reader what is the temperature in Office"</span></span></div>
<div>
<span style="font-size: small;"> Intent: </span><span style="font-size: small; font-weight: normal;">The Alexa Skill that Alexa determines will fulfill your request/utterance</span></div>
<div>
<span style="font-size: small;"> Slot Type:</span><span style="font-size: small; font-weight: normal;"> Essentially the Key in a key : value pair</span></div>
</div>
<div>
<br /></div>
</h3>
<h4>
Creating the Intent Schema</h4>
<h3>
<div>
</div>
<div>
<ul>
<li><span style="font-size: small; font-weight: normal;">Paste the following JSON into the Intent Schema field</span></li>
</ul>
</div>
</h3>
<h3>
<div>
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?skin=desert"></script>
<br />
<pre class="prettyprint" style="margin: 0px;"><span style="font-size: small;"><span style="font-weight: 400;">{
"intents": [
{
"intent": "AMAZON.CancelIntent"
},
{
"intent": "AMAZON.HelpIntent"
},
{
"intent": "AMAZON.StopIntent"
},
{
"slots": [
{
"name": "room",
"type": "LIST_OF_ROOMS"
}
],
"intent": "getTemperature"
},
{
"slots": [
{
"name": "room",
"type": "LIST_OF_ROOMS"
}
],
"intent": "getHumidity"
}
]
}</span></span></pre>
</div>
</h3>
<h3>
<div>
<pre class="prettyprint"></pre>
</div>
</h3>
<h4>
Creating Slot Types</h4>
<h3>
<div>
<span style="font-size: small; font-weight: normal;">In my example I have Nodemcu's in 3 rooms. If you are using just one Nodemcu you can change to values below to fit your needs.</span></div>
<div>
<ul>
<li><span style="font-size: small; font-weight: normal;">Select Add Slot Type and enter the following</span></li>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-bN8uQ55QsLY/Wn3W2gR-j7I/AAAAAAAAAME/c8ZdaXh1k903Zz5XXE9D5Pv2OLqBzzimQCK4BGAYYCw/s1600/alexa_slots.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://4.bp.blogspot.com/-bN8uQ55QsLY/Wn3W2gR-j7I/AAAAAAAAAME/c8ZdaXh1k903Zz5XXE9D5Pv2OLqBzzimQCK4BGAYYCw/s1600/alexa_slots.PNG" /></a></div>
</div>
</h3>
<h4>
Creating Sample Utterances</h4>
<h3>
<div>
</div>
<div>
<span style="font-weight: normal;"><span style="font-size: small;">The utterance determines which intent will be triggered. In simple terms, the utterance will determine whether Alexa will read the temperature or the humidity.</span></span></div>
<div>
<ul style="font-size: medium; font-weight: 400;">
<li>In the Sample Utterances field enter the following</li>
</ul>
</div>
<div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-U4XQpk7d4Es/Wn3g8WmARGI/AAAAAAAAAMU/LpbJ2Vq04pAypr7oN3_pph47CkLSg1fvwCK4BGAYYCw/s1600/alexa_utterances.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em; text-align: center;"><img border="0" src="https://1.bp.blogspot.com/-U4XQpk7d4Es/Wn3g8WmARGI/AAAAAAAAAMU/LpbJ2Vq04pAypr7oN3_pph47CkLSg1fvwCK4BGAYYCw/s1600/alexa_utterances.PNG" /></a></div>
<ul>
<li><span style="font-size: small;"><span style="font-weight: 400;">Copy the Skill ID found at under your Skill name, to your text editor</span></span></li>
</ul>
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-NfgvBKgobdU/Wn3rerP9-eI/AAAAAAAAAM4/D_lQjAYEfFUecIddcJx4J3Ovuk_n2wc8ACK4BGAYYCw/s1600/alexa_skillid.PNG" imageanchor="1" style="font-size: medium; font-weight: 400; margin-left: 1em; margin-right: 1em;"><img border="0" src="https://3.bp.blogspot.com/-NfgvBKgobdU/Wn3rerP9-eI/AAAAAAAAAM4/D_lQjAYEfFUecIddcJx4J3Ovuk_n2wc8ACK4BGAYYCw/s1600/alexa_skillid.PNG" /></a></div>
<div>
<span style="font-size: small;"><span style="font-weight: 400;"><br /></span></span></div>
<div>
<ul>
<li><span style="font-weight: normal;"><span style="font-size: small;">Leave this web tab open. We need to open AWS IAM to setup a user for Lambda</span></span></li>
</ul>
<h3>
</h3>
</div>
</h3>
<h3>
Steps - Lambda User</h3>
<div>
Lambda will require an account to authenticate and interact with the IoT Thing Shadow. I will set the policy to allow the Lambda function to access the Shadow state of all my Things in IoT.<br />
<br />
<ul>
<li>Open IAM from the AWS Console > Policies > Create Policy</li>
<ul>
<li>Service: IoT</li>
<li>Actions: GetThingShadow</li>
<li>Resources : All resources</li>
<ul>
<li>If you have one Thing you can set the policy to allow access to only that Thing</li>
</ul>
<li>Select Review Policy</li>
<li>Name the policy</li>
<ul>
<li>I used lambda_getAllThingShadows</li>
</ul>
<li>Create policy</li>
</ul>
</ul>
<ul>
<li>Now go to Users</li>
<li>Add User > Name the User > Select Programmatic Access > Next: Permissions</li>
</ul>
<div>
<a href="http://2.bp.blogspot.com/-R7eMjEn1-LY/Wn46ku_bZuI/AAAAAAAAANU/RxvA0236PYEEvknrukoTyALRPpf-gX5QwCK4BGAYYCw/s1600/iam_lambdauser.PNG" imageanchor="1"><img border="0" src="https://2.bp.blogspot.com/-R7eMjEn1-LY/Wn46ku_bZuI/AAAAAAAAANU/RxvA0236PYEEvknrukoTyALRPpf-gX5QwCK4BGAYYCw/s1600/iam_lambdauser.PNG" /></a></div>
</div>
<ul>
<li>Attach existing policies directly</li>
<li>Search for your policy > Check the box next the policy > Next: Preview</li>
<li>Create User</li>
<li>Copy the the Access key ID and Secret access key to your text editor</li>
</ul>
<div>
<a href="http://3.bp.blogspot.com/-eCFI_bfcL4Q/Wn49-7DbXII/AAAAAAAAANs/LV0SVC3Rky8GrCf-iyYGKMnA00LIoZbPQCK4BGAYYCw/s1600/iam_lambdakey.PNG" imageanchor="1"><img border="0" src="https://3.bp.blogspot.com/-eCFI_bfcL4Q/Wn49-7DbXII/AAAAAAAAANs/LV0SVC3Rky8GrCf-iyYGKMnA00LIoZbPQCK4BGAYYCw/s1600/iam_lambdakey.PNG" /></a></div>
<br />
<h3>
Steps - AWS Lambda</h3>
<div>
I will be honest, coming from a data center infrastructure background, AWS Lambda is blowing my mind! The concept of server-less and container-less programs is amazing.</div>
<h3>
<div style="font-size: medium; font-weight: 400;">
Alright, let's create a some Lambda functions in Python to read the state of the Nodemcu Thing Shadow. </div>
<div>
<ul>
<li><span style="font-size: small;"><span style="font-weight: 400;">Open the AWS Console <a href="https://console.aws.amazon.com/">https://console.aws.amazon.com/</a></span></span></li>
<li><span style="font-size: small; font-weight: normal;">Search Lambda and select Lambda</span></li>
<li><span style="font-size: small; font-weight: normal;">Select Create Function > Author from Scratch (because that's how we roll)</span></li>
<li><span style="font-size: small; font-weight: normal;">Enter a Name, I used getNodemcuData</span></li>
<li><span style="font-size: small; font-weight: normal;">In Runtime select Python 3.6</span></li>
<li><span style="font-size: small; font-weight: normal;">In the Role section, select Create a custom role</span></li>
<ul>
<li><span style="font-size: small; font-weight: normal;">IAM Role: lambda_basic_execution</span></li>
<li><span style="font-size: small; font-weight: normal;">Policy Name: Create a new Role Policy</span></li>
<li><span style="font-size: small; font-weight: normal;">Allow</span></li>
</ul>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-o1kx8xjZ00w/Wn3jdQV4EqI/AAAAAAAAAMg/qg7Ebon9LwYHPFjpb2aabH6Uz2cCW1JFgCK4BGAYYCw/s1600/lambda_rolepolicy.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://1.bp.blogspot.com/-o1kx8xjZ00w/Wn3jdQV4EqI/AAAAAAAAAMg/qg7Ebon9LwYHPFjpb2aabH6Uz2cCW1JFgCK4BGAYYCw/s1600/lambda_rolepolicy.PNG" /></a></div>
<div>
<span style="font-size: small;"><span style="font-weight: 400;"><br /></span></span></div>
</div>
<div>
<ul>
<li><span style="font-size: small;"><span style="font-weight: 400;">You will be redirected back to Author from scratch</span></span></li>
<ul>
<li><span style="font-size: small;"><span style="font-weight: 400;">Role: should be set to Choose an existing role</span></span></li>
<li><span style="font-size: small;"><span style="font-weight: 400;">Existing Role: lambda_basic_execution</span></span></li>
</ul>
<li><span style="font-size: small;"><span style="font-weight: 400;">Create function</span></span></li>
<li><span style="font-size: small;"><span style="font-weight: 400;">Copy the function ARN (Amazon Resource Name) to your text editor</span></span></li>
<li><span style="font-size: small;"><span style="font-weight: 400;">In the Designer, assign Alexa Skills Kit as the trigger</span></span></li>
<li><span style="font-size: small;"><span style="font-weight: 400;">In the Configure triggers pane, paste the Skill ID from the Alexa Skill we created.</span></span></li>
<li><span style="font-size: small;"><span style="font-weight: 400;">Select Add</span></span></li>
</ul>
</div>
</h3>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-gk89qr6dVPg/Wn3sJoZHBhI/AAAAAAAAANE/Y7aXqDAYX1E36Uw9k6E5PumQoGHCZnSsgCK4BGAYYCw/s1600/lambda_trigger.PNG" imageanchor="1" style="display: inline !important; margin-left: 1em; margin-right: 1em; text-align: center;"><img border="0" src="https://1.bp.blogspot.com/-gk89qr6dVPg/Wn3sJoZHBhI/AAAAAAAAANE/Y7aXqDAYX1E36Uw9k6E5PumQoGHCZnSsgCK4BGAYYCw/s1600/lambda_trigger.PNG" /></a></div>
<h3>
<ul>
<li><span style="font-weight: normal;"><span style="font-size: small;">Select Save </span></span></li>
<li><span style="font-weight: normal;"><span style="font-size: small;">Scroll down to Environment variables</span></span></li>
<li><span style="font-size: small;"><span style="font-weight: 400;">Input the secret key id and access key that you copied from the User you created in IAM</span></span></li>
<ul>
<li><span style="font-size: small;"><span style="font-weight: 400;">Key: SECRET_KEY | Value: secret key</span></span></li>
<li><span style="font-size: small;"><span style="font-weight: 400;">Key: ACCESS_KEY | Value: your access key id</span></span></li>
</ul>
<li><span style="font-size: small;"><span style="font-weight: 400;">Select Save</span></span></li>
</ul>
<ul>
</ul>
</h3>
<h3>
Lambda - Python Code</h3>
<div>
We will use the AWS boto3 Python module. Boto3 has a simple client function to allow a connection to the AWS IoT Thing Shadow(s). We will also use Lambda's built in key/value encryption feature to securely add your API access key and access secret.<br />
<br />
Paste the following into the Lamba programming pane<br />
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?skin=desert"></script>
<br />
<pre class="prettyprint">import boto3
import os
import json
def lambda_handler(event, context):
# Determine which Thing Shadow to read
room = event["request"]["intent"]["slots"]["room"]["value"]
if room == "bedroom":
thingShadow = "node_bedroom"
elif room == "kitchen":
thingShadow = "node_kitchen"
elif room == "office":
thingShadow = "node_office"
# Connect to AWS IoT REST API
client = boto3.client(
'iot-data',
region_name='us-east-1',
aws_access_key_id=os.environ['ACCESS_KEY'],
aws_secret_access_key=os.environ['SECRET_KEY']
)
# Read the current data in the Thing Shadow
shadowState = client.get_thing_shadow(thingName=thingShadow)
streamingBody = shadowState["payload"]
shadowJSON = json.loads(streamingBody.read())
# Determine temperature or humidity
intent = event["request"]["intent"]["name"]
if intent == "getTemperature":
dataType = "temperature"
description = " degrees"
elif intent == "getHumidity":
dataType = "humidity"
description = " percent"
# Create the response that will be sent to Alexa
alexaString = str(shadowJSON["state"]["reported"][dataType]) + description
# Send the response back to Alexa
return {
"version": "1.0",
"response": {
"outputSpeech": {
"type": "PlainText",
"text": alexaString
}
}
}</pre>
</div>
<h3>
Steps - Final Alexa Configuration</h3>
<div>
Its about to get real! We need to connect this Skill to the Lambda function we created.</div>
<div>
<ul>
<li>Go back to the Alexa Skill Kit... you should still have that tab open right?</li>
<li>In Configuration, select AWS Lambda ARN</li>
<li>In Default, paste the Lambda ARN</li>
<li>The remaining settings can be left as defaults</li>
<li>Select Next</li>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-gk49qT5azoY/Wn3nRmbghvI/AAAAAAAAAMs/TfsAZQlg10EZxCN8y0Qw_kawP6PJDFcKwCK4BGAYYCw/s1600/alexa_configarn.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://2.bp.blogspot.com/-gk49qT5azoY/Wn3nRmbghvI/AAAAAAAAAMs/TfsAZQlg10EZxCN8y0Qw_kawP6PJDFcKwCK4BGAYYCw/s1600/alexa_configarn.PNG" /></a></div>
</div>
<div>
<h3>
Testing</h3>
</div>
<div>
Okay. That was not too bad. Let's see the fruits of our labor.</div>
<div>
<br /></div>
<div>
<ul>
<li>You should have the Test screen up</li>
<li>Set Testing to Enabled for you account</li>
</ul>
<div>
<a href="http://1.bp.blogspot.com/-1HSvkodzUp8/Wn5BeZKXt8I/AAAAAAAAAN4/6ms1BRQWylwpEs26Hh93O8F1owPAxLknwCK4BGAYYCw/s1600/alexa_enabletesting.PNG" imageanchor="1"><img border="0" src="https://1.bp.blogspot.com/-1HSvkodzUp8/Wn5BeZKXt8I/AAAAAAAAAN4/6ms1BRQWylwpEs26Hh93O8F1owPAxLknwCK4BGAYYCw/s1600/alexa_enabletesting.PNG" /></a></div>
</div>
<div>
<br /></div>
<div>
<ul>
<li>In Service Simulator you should see the Lambda ARN you setup in Configuration</li>
<li>Now we can simulate speaking to Alexa and triggering our Lambda function</li>
<li>If all goes well, this is what you should see</li>
</ul>
<div>
<a href="http://2.bp.blogspot.com/-ZDGKUiRBzPE/Wn5CKamQANI/AAAAAAAAAOE/EYKZUnq15L8Bmts7XWiUzp0GU7M3EEPAQCK4BGAYYCw/s1600/alexa_tempsuccess.PNG" imageanchor="1"><img border="0" src="https://2.bp.blogspot.com/-ZDGKUiRBzPE/Wn5CKamQANI/AAAAAAAAAOE/EYKZUnq15L8Bmts7XWiUzp0GU7M3EEPAQCK4BGAYYCw/s1600/alexa_tempsuccess.PNG" /></a></div>
</div>
<div>
<br /></div>
<div>
The tests are successful. Try asking for the humidity also.</div>
<h3>
Alexa Setup for your Echo Dot</h3>
<div>
<ul>
<li>Open the Alexa App on your smart phone/device</li>
<li>Go to Skills > Your Skills</li>
<li>Now press on the Dev Skill tab you should see the Skill you created</li>
</ul>
<div>
If the skill is there you are ready to interact with your Echo device</div>
</div>
<div>
<br /></div>
<div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-X88cPUPCX5U/Wn5zN6TXJWI/AAAAAAAAAOc/YnbEjfvLJtExVnkZbNAB32xyaN1IwpzbQCK4BGAYYCw/s1600/alexa_skillinapp.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="400" src="https://3.bp.blogspot.com/-X88cPUPCX5U/Wn5zN6TXJWI/AAAAAAAAAOc/YnbEjfvLJtExVnkZbNAB32xyaN1IwpzbQCK4BGAYYCw/s400/alexa_skillinapp.png" width="225" /></a></div>
<br /></div>
<div>
<br /></div>
<div>
Bada Bing... Bada Boom.</div>
<h3>
Result</h3>
<div>
This has been a great project to get my feet wet with Alexa, AWS IoT, and AWS Lambda. There ideas are flowing at the moment.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<iframe allowfullscreen='allowfullscreen' webkitallowfullscreen='webkitallowfullscreen' mozallowfullscreen='mozallowfullscreen' width='320' height='266' src='https://www.blogger.com/video.g?token=AD6v5dxzywdDEWVnqnb8LAkU5tK0IQXZ0LVYzwftvEbVat0B6uuf6MPH_olk2S9ooOE6KGswXd7GKdK2Vo6eZN98' class='b-hbp-video b-uploaded' frameborder='0'></iframe></div>
<h3 style="clear: both; text-align: left;">
Next Time</h3>
<div>
I want to get more in depth into the features that Lambda can provide to Alexa. I'd like to get some historical data going and see if I can use Alexa to give me a useful review of the Nodemcu sensors through out my house.</div>
<br /></div>
Danhttp://www.blogger.com/profile/01422027852211426218noreply@blogger.com1tag:blogger.com,1999:blog-36706321802012849.post-83887572595162116822018-02-07T17:28:00.000-08:002018-02-09T08:06:14.912-08:00Creating Alexa Skills for IoT and Nodemcu - Part 2 AWS IoT<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-G1agROqdVho/WnigVg0WmYI/AAAAAAAAAFw/uUjG70wGI_4FEq2BTdoO921EjjgL-4ZeQCPcBGAYYCw/s1600/nodemcu_0001.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="900" data-original-width="1600" height="360" src="https://2.bp.blogspot.com/-G1agROqdVho/WnigVg0WmYI/AAAAAAAAAFw/uUjG70wGI_4FEq2BTdoO921EjjgL-4ZeQCPcBGAYYCw/s640/nodemcu_0001.JPG" width="640" /></a></div>
<h2>
Connecting Nodemcu to AWS IoT</h2>
This is part two of a series of posts showing how I setup a AWS based solution to allow Alexa to read data collected by Nodemcu with DHT temperature and humidity sensors. The design is discussed in <a href="http://blog.kilomon.com/2018/02/creating-alexa-skills-for-iot-nodemcu.html">part one </a>of this series.<br />
<br />
<a href="http://blog.kilomon.com/2018/02/creating-alexa-skills-for-iot-nodemcu.html">Go to Part 1 - Design</a><br />
<h3>
Overview</h3>
<div>
I recommend reviewing my first post in this series, so you can understand the gameplan... but here's the short version. We will create and configure three separate services in AWS. An Alexa Skill for voice commands, a AWS Lambda function that will act as a middle man, and AWS IoT for storing the current state of the Nodemcu sensors.</div>
<div>
<br /></div>
<div>
<i>DISCLAIMER: This guide uses a work around to allow Nodemcu to communicate directly with AWS IoT. The work around uses API keys that will be written in cleartext on the Nodemcu. Proceed at your own discretion.</i></div>
<h3>
Goals</h3>
<div>
<ul>
<li>Configure an IoT Thing</li>
<li>Setup a security policy and user that can write data to the Thing Shadow via the REST API</li>
<ul>
<li>Ensure the policy limits access to only one Thing Shadow and is set to write only</li>
</ul>
<li>Wire up our Nodemcu and DHT sensor</li>
<li>Collect sensor data and write it to the Thing Shadow</li>
</ul>
</div>
<h3>
Prep</h3>
<h4>
Parts and Components</h4>
<div>
<i>I have linked the tools and components I used to build this project. I personally own each item linked below.</i></div>
<div>
<ul>
<li>(1) Nodemcu <a href="http://amzn.to/2E8xF7t">http://amzn.to/2E8xF7t</a></li>
<li>(1) DHT11 <a href="http://amzn.to/2nGV1XN">http://amzn.to/2nGV1XN</a> or DHT22 <a href="http://amzn.to/2C2O47P">http://amzn.to/2C2O47P</a></li>
<li>(1) 4.7K - 10K Resistor <span style="color: #0000ee;"><u>http://amzn.to/2C4xTH4</u></span>(only needed if you have a 4 pin DHT sensor)</li>
<li>Breadboard Jumper Wires <a href="http://amzn.to/2nGuYjy">http://amzn.to/2nGuYjy</a></li>
<li>(1) Breadboard <a href="http://amzn.to/2sayXcw">http://amzn.to/2sayXcw </a>(small cheap ones work great for simple experiments with Nodemcu)</li>
<li>USB Micro B cable <a href="http://amzn.to/2BMAj1h">http://amzn.to/2BMAj1h</a> (the same that a android phone uses)</li>
<li>USB Power Adapter <a href="http://amzn.to/2C2sXCw">http://amzn.to/2C2sXCw</a></li>
</ul>
<h4>
Tools</h4>
</div>
<div>
<ul>
<li>Arduino IDE</li>
<li>Some good music</li>
</ul>
</div>
<h4>
AWS</h4>
<div>
I considered showing how to setup the appropriate accounts on AWS, but it seems there are plenty of good resources to show how to do that. Put your google-fu skills to work or take a wild stab at it.</div>
<div>
<ul>
<li>Create an AWS Account</li>
</ul>
<div>
AWS IoT is free for 12 months at 250K messages a month.</div>
<h3>
Steps - AWS IoT</h3>
</div>
<div>
AWS IoT refers to devices as Things. We will setup our Nodemcu with DHT11/22 as a Thing within AWS IoT.</div>
<div>
<ul>
<li>Login to the AWS Console > Select US East (N. Virginia)</li>
<li>Search AWS IoT > Select AWS IoT</li>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-q_ECZH4ARjc/WnuGdCOPwdI/AAAAAAAAAK0/1PrpyTC3ELYaQHgCjJ6b-tAgmDWp8LHTQCK4BGAYYCw/s1600/nodemcu_awsiotchoice.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://1.bp.blogspot.com/-q_ECZH4ARjc/WnuGdCOPwdI/AAAAAAAAAK0/1PrpyTC3ELYaQHgCjJ6b-tAgmDWp8LHTQCK4BGAYYCw/s1600/nodemcu_awsiotchoice.PNG" /></a></div>
<ul>
<li>Select Manage > Things > Create > Create a single thing</li>
</ul>
</div>
<div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-FgW9kkzbxec/WntN1Wn9wQI/AAAAAAAAAI8/-wa_K9E_MSIRz4x-d79mLuGXx6MxkZBFwCLcBGAs/s1600/thing_create.PNG" imageanchor="1" style="display: inline !important; margin-left: 1em; margin-right: 1em; text-align: center;"><img border="0" data-original-height="99" data-original-width="793" height="79" src="https://1.bp.blogspot.com/-FgW9kkzbxec/WntN1Wn9wQI/AAAAAAAAAI8/-wa_K9E_MSIRz4x-d79mLuGXx6MxkZBFwCLcBGAs/s640/thing_create.PNG" width="640" /></a><a href="http://3.bp.blogspot.com/-wT2DAnRRHLE/WntOmQD02mI/AAAAAAAAAJI/R9W7lprjRRkpbC-GS92jd3cLI_WGFkVaQCK4BGAYYCw/s1600/thing_create2.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://3.bp.blogspot.com/-wT2DAnRRHLE/WntOmQD02mI/AAAAAAAAAJI/R9W7lprjRRkpbC-GS92jd3cLI_WGFkVaQCK4BGAYYCw/s1600/thing_create2.PNG" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
</div>
<ul>
<li>Enter device information > Next </li>
<ul>
<li>I am sticking to the bare minimum for this guide, so I will enter a name only</li>
<li>Type allows you to assign a template that includes attributes specific to your device</li>
<li>Groups are for easier management of your devices</li>
</ul>
</ul>
<ul>
<li>Create thing without certificate</li>
<ul>
<li>Remember we will be using the AWS IoT SDK to establish connectivity because the Nodemcu does not support TLS 1.2</li>
<li>The more robust approach would be to put a IoT hub/broker into the solution.</li>
</ul>
<li>You can select the Thing from the Manage > Things pane. From here you can view things such are the Amazon Resource Name and Shadow state.</li>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-Pk06kJDyKn8/WnteuucsRUI/AAAAAAAAAJk/RO4uWkqNAX8aFvw3K_uTEYIEdwUBVDo6gCK4BGAYYCw/s1600/thing_details.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://4.bp.blogspot.com/-Pk06kJDyKn8/WnteuucsRUI/AAAAAAAAAJk/RO4uWkqNAX8aFvw3K_uTEYIEdwUBVDo6gCK4BGAYYCw/s1600/thing_details.PNG" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
</div>
<ul>
<li>Leave you web browser tab open, because we will be coming back to AWS IoT in future steps.</li>
</ul>
At this point we have a Thing defined in AWS IoT. Don't get all excited yet. We next need to setup AWS access controls using the IAM console.<br />
<br />
<h3>
Steps - Setup Access Controls</h3>
<div>
What we need to do here is create a API user and security profile that will allow the Nodemcu to connect to IoT, update the Thing Shadow, and have the ability to do nothing else.</div>
<h4>
Creat the Security Policy</h4>
<div>
<ul>
<li>Use the same method you found AWS IoT to find and access AWS IAM</li>
<li>Select Policies > Create Policy</li>
<li>In the visual editor</li>
<ul>
<li>Choose a service > Search IoT > Select IoT</li>
<li>Actions > Search Shadow > Select UpdateThingShadow</li>
<li>Resources > Specific > Add ARN > and paste the ARN for the Thing as shown in the screen host above > Add > Review Policy</li>
<li>Name the Policy > Create the Policy</li>
<ul>
<li>Because this policy is for a one to one relationship I make the name very explicit such as "node_office_UpdateThingShadow"</li>
</ul>
</ul>
</ul>
<h4>
Create the User</h4>
</div>
<div>
<ul>
<li>From the main console page of IAM, Select Users > Add User</li>
<li>Enter a name that your Nodemcu will use > Select Programmatic sccess > Next Permissions</li>
<li>Select Attach existing policies directly > Search the Policy name you created above and Select it > Next Review > Create User</li>
<li>Now you need to make note of the Access key ID and Secret access key</li>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-9Dq7mDWik4g/WnuYX_BxhiI/AAAAAAAAALU/lfhFtwRLo9II2LtCX9FHbm1Z7uE9xaofACK4BGAYYCw/s1600/iam_apiuser.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://2.bp.blogspot.com/-9Dq7mDWik4g/WnuYX_BxhiI/AAAAAAAAALU/lfhFtwRLo9II2LtCX9FHbm1Z7uE9xaofACK4BGAYYCw/s1600/iam_apiuser.PNG" /></a></div>
<div>
<br /></div>
</div>
<div>
You can always come back to grab the key info again.</div>
<div>
<br /></div>
<div>
Alrighty! Our IoT Thing Shadow is ready and we have an API user that can write data to that Shadow. Let's get the Nodemcu wired up and programmed so we can see a result.</div>
<h3>
Steps - Setup the Nodemcu with DHT Sensor</h3>
</div>
<div>
<ul>
<li>Wire up the Nodemcu and DHT sensor</li>
</ul>
</div>
<div>
Here is a diagram of the physical wiring. Omit the 4.7K - 10K resistor if you have a 3 pin DHT. The small breadboards I linked above will fit the Nodemcu and a couple sensors perfectly.They also have double-sided tape for mounting your experiments easily.</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/--8dvXLyD3uM/WntultTv-5I/AAAAAAAAAJw/A_b5EuO0MmYDDXtQgj4VZynL-qKLwH3PwCLcBGAs/s1600/nodemcu_dht_fritz.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="609" data-original-width="537" height="640" src="https://2.bp.blogspot.com/--8dvXLyD3uM/WntultTv-5I/AAAAAAAAAJw/A_b5EuO0MmYDDXtQgj4VZynL-qKLwH3PwCLcBGAs/s640/nodemcu_dht_fritz.PNG" width="563" /></a></div>
We can move on to setting up Arduino to program the Nodemcu.<br />
<h3>
Steps - Setup Arduino</h3>
<div>
These steps require ESP8266 2.3.0 library to be installed in Arduino. You can review those steps in my blog post <a href="http://blog.kilomon.com/2018/02/hacking-sonoff-wifi-switch-part-2.html">Hacking the Sonoff Wifi Switch - Part 2</a>.</div>
<div>
<br /></div>
<div>
<ul>
<li>Open Arduino > Sketch > Include Library > Manage Libraries</li>
<li>Search and install "AWS-SDK-ESP8266"</li>
<ul>
<li>There is more info available on <a href="https://github.com/Schm1tz1/aws-sdk-arduino-esp8266">Roman Schmitz github page</a></li>
</ul>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-CBDE5XwHpiQ/Wnt_hwPs7II/AAAAAAAAAKM/s-J2-w423Dk_-bl76e99Kku5vddB9cEDwCK4BGAYYCw/s1600/arduino_installaws.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://1.bp.blogspot.com/-CBDE5XwHpiQ/Wnt_hwPs7II/AAAAAAAAAKM/s-J2-w423Dk_-bl76e99Kku5vddB9cEDwCK4BGAYYCw/s1600/arduino_installaws.PNG" /></a></div>
<div>
<ul>
<li>Search and install "DHT sensor library" by Adafruit</li>
<ul>
<li>I have not yet tried the "DHT sensor library for ESPx" if you have used it drop me a comment.</li>
</ul>
</ul>
</div>
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-JgKl1wpCFrw/WnuAuIUQgTI/AAAAAAAAAKY/3bA89QIOuzsd_G-PYL4n7mZoltTPkbcmACK4BGAYYCw/s1600/arduino_installdht.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://2.bp.blogspot.com/-JgKl1wpCFrw/WnuAuIUQgTI/AAAAAAAAAKY/3bA89QIOuzsd_G-PYL4n7mZoltTPkbcmACK4BGAYYCw/s1600/arduino_installdht.PNG" /></a><a href="http://3.bp.blogspot.com/-Cv87B7SaPSU/WnuBjyzyF0I/AAAAAAAAAKk/1Vqcmxt35-g9SVgZUoZcF94qWBodxvcUgCK4BGAYYCw/s1600/arduino_installunifiedsensor.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://3.bp.blogspot.com/-Cv87B7SaPSU/WnuBjyzyF0I/AAAAAAAAAKk/1Vqcmxt35-g9SVgZUoZcF94qWBodxvcUgCK4BGAYYCw/s1600/arduino_installunifiedsensor.PNG" /></a></div>
<br />
<br />
<br />
<br />
<li>And "Adafruit Unified Sensor"</li>
<br />
<div>
<br /></div>
<div>
We are ready to review the code and program the Nodemcu.</div>
<h3>
Code</h3>
<div>
Credit goes to Roman Schmitz for the orignal AWS code example. I have just modified it to take DHT data and send it to the IoT in the correct JSON format.</div>
<div>
<br /></div>
<div>
Also I want to say thanks to the esp8266 library team. The dateTimeProvider and httpClient functions are saving me a lot of lines of code.<br />
<br />
<i>ONE LAST MENTION ABOUT SECURITY: It is not a good idea to include keys, secrets, or passwords directly in code. While there are some ways to store credentials outside of the main body of this sketch it won't fix the issue that all the sensitive data will be placed in cleartext on the Nodemcu. <a href="https://mongoose-os.com/">Mongoose OS</a> features flash encryption, but I havent tried it out on a Nodemcu yet.</i><br />
<br />
You will need the following info to use this sketch:<br />
<br />
<ul>
<li>Thing HTTPS API endpoint</li>
<ul>
<li>Manage > Things > your_thing > Interact</li>
</ul>
<li>Thing Shadow path in the format "<span style="font-family: "courier new" , "courier" , monospace;">/things/your_thing/shadow</span>"</li>
<li>AWS API Key ID</li>
<li>AWS API Secret Key</li>
</ul>
</div>
<div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<h4 style="text-align: left;">
What are we doing here?</h4>
<div style="text-align: left;">
This sketch will connect your Nodemcu to your wifi network, configure the AWS client, collect the current temperature and humidity, and write that to the Thing Shadow in IoT. This is repeated every 60000 milliseconds or 60 seconds. </div>
<div style="text-align: left;">
<br /></div>
<div style="text-align: left;">
You can change the delay to suit your needs (especially during testing), but before you change the delay you should calculate the how many connections your device(s) will be making to IoT. 250K messages per month is the magic number.</div>
<div style="text-align: left;">
<br /></div>
<br />
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?skin=desert"></script>
<br />
<pre class="prettyprint">#include <ESP8266WiFi.h>
#include <AmazonIOTClient.h>
#include <ESP8266AWSImplementations.h>
#include <AWSFoundationalTypes.h>
#include <DHT.h>
Esp8266HttpClient httpClient;
Esp8266DateTimeProvider dateTimeProvider;
AmazonIOTClient iotClient;
ActionError actionError;
// DHT Sensor setup
#define DHTPIN D1
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
char *ssid="YOUR SSID";
char *password="YOUR PASSWORD";
void setup() {
Serial.begin(115200);
delay(10);
// LED on nodemcu
pinMode(BUILTIN_LED, OUTPUT);
// DHT Sensor
dht.begin();
// Connect to WAP
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
iotClient.setAWSRegion("us-east-1");
iotClient.setAWSEndpoint("amazonaws.com");
iotClient.setAWSDomain("YOUR REST THING API ENDPOINT");
iotClient.setAWSPath("YOUR THING SHADOW PATH");
iotClient.setAWSKeyID("YOUR ACCESS KEY ID");
iotClient.setAWSSecretKey("YOUR SECRET ACCESS KEY");
iotClient.setHttpClient(&httpClient);
iotClient.setDateTimeProvider(&dateTimeProvider);
}
void loop(){
float t = dht.readTemperature(true);
char temp[10];
dtostrf(t,1,2,temp);
float h = dht.readHumidity();
char hum[10];
dtostrf(h,1,2,hum);
MinimalString shadow = ("{\"state\":{\"reported\":{\"temperature\":" + String(temp) + ",\"humidity\":" + String(hum) + "}}}").c_str();
char* result = iotClient.update_shadow(shadow, actionError);
Serial.print(result);
delay(60000);
}</pre>
</div>
<div>
<h3>
Steps - Program the Nodemcu</h3>
</div>
<div>
<ul>
<li>In Arduino, insert the sketch code and input your wifi creds and api keys</li>
<li>Nodemcu programming settings are as follows</li>
<ul>
<li>Board NodeMCU 1.0 (ESP-12E Module)</li>
<li>I use all other defaults</li>
<li>Of course make sure your COM is set</li>
</ul>
<li>Open Serial Monitor on your COM</li>
<li>Upload the code</li>
<li>Watch serial monitor for a minute and make sure it is outputting as expected.</li>
<li>Disconnect the Nodemcu from power and reconnect</li>
</ul>
<h4>
Program Result</h4>
</div>
<div>
If things go well you will see the Nodemcu connect to your wifi and output its IP. Then it will show the connections it is making to AWS IoT.</div>
<h3>
Result</h3>
<div>
Now if everything is working as expected we will see the Thing Shadow being updated.</div>
<div>
<ul>
<li>Navigate back to AWS IoT > Manage > Things > Your Thing > Shadow</li>
</ul>
<div>
<a href="http://3.bp.blogspot.com/-2Z1in2q9AEA/Wnuj6CsRnXI/AAAAAAAAALk/R9RdsD6Ljrw-Bukkp2GzMWTXQmbow7WTgCK4BGAYYCw/s1600/nodemcu_shadowupdate.PNG" imageanchor="1"><img border="0" src="https://3.bp.blogspot.com/-2Z1in2q9AEA/Wnuj6CsRnXI/AAAAAAAAALk/R9RdsD6Ljrw-Bukkp2GzMWTXQmbow7WTgCK4BGAYYCw/s1600/nodemcu_shadowupdate.PNG" /></a></div>
</div>
<div>
<br /></div>
<div>
Coolio. We are so totally going to make this work.</div>
<div>
<h3>
Next Steps</h3>
</div>
<div>
In the next post we will cap things off by creating a way for Alexa to read these values to us. If you want to see the whole concept and design diagram check out part one of this series.</div>
<div>
<br /></div>
<div>
<a href="http://blog.kilomon.com/2018/02/creating-alexa-skills-for-iot-nodemcu.html">Go to Part 1 - Design</a></div>
<div>
<br /></div>
Danhttp://www.blogger.com/profile/01422027852211426218noreply@blogger.com16tag:blogger.com,1999:blog-36706321802012849.post-41055212759903071242018-02-05T13:00:00.000-08:002018-02-07T19:44:35.195-08:00Creating Alexa Skills for IoT and Nodemcu - Part 1 Design<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-G1agROqdVho/WnigVg0WmYI/AAAAAAAAAFs/UbwCsFVtpfAMhtf3PjqjUnUtcYHqGcvYACK4BGAYYCw/s1600/nodemcu_0001.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="225" src="https://3.bp.blogspot.com/-G1agROqdVho/WnigVg0WmYI/AAAAAAAAAFs/UbwCsFVtpfAMhtf3PjqjUnUtcYHqGcvYACK4BGAYYCw/s400/nodemcu_0001.JPG" width="400" /></a></div>
<h2>
Let's Make Alexa Interact with Nodemcu</h2>
<div>
In this post I will we create a solution that allows Alexa to read sensor data collected by a Nodemcu and a DHT11/DHT22 sensor.<br />
<br />
<a href="http://blog.kilomon.com/2018/02/creating-alexa-skills-for-iot-and.html">Go to Part 2</a></div>
<h3>
Overview</h3>
<div>
I collect temperature and humidity data with Nodemcu and DHT11/DHT22 sensors throughout my house. I have been storing the data in <a href="https://graphiteapp.org/">Graphite</a>, which is a proven time-series database solution. Graphite is traditionally used in the context of monitoring IT systems such as server and application performance. I visualize the sensor information with <a href="https://grafana.com/">Grafana</a>. </div>
<div>
<br /></div>
<div>
This is great for me, but let's say my wife wants to know the temperature in our daughter's room... I would quickly learn that what seems great to me does not create a simple experience for others. So how would I go about making a method that my wife would actually use? My answer is Alexa.</div>
<div>
<br /></div>
<div>
I will use a the inexpensive ESP8266 based Nodemcu and a DHT11 or DHT22 sensor to collect temperature and humidity data. We will use Arduino to do the programming and some AWS services to create a service that we can send temperature and humidity data to, so that Alexa can interact with it.</div>
<div>
<br /></div>
<div>
<i><b>A WORD OF CAUTION:</b> A few different AWS services are used in this guide. These can be used free, but make sure you understand how AWS calculates billing for any service you use.</i></div>
<div>
<br /></div>
<h3>
Goals</h3>
<div>
<ul>
<li>Collect Temperature and Humidity using Nodemcu and DHT11 or DHT22</li>
<li>Use Alexa to retrieve and read the current temperature or humidity</li>
<li>Use "free" cloud services</li>
</ul>
<h3>
Design</h3>
The following design will meet the goals of the project without deploying servers or containers.<br />
<div>
<br /></div>
<div>
Here is the proposed solution:</div>
<div>
<ol>
<li>Each Nodemcu will have a Thing Shadow created in <a href="https://aws.amazon.com/iot/">AWS IoT</a>. The Nodemcu will write temperature and humidity to AWS IoT Thing Shadow using the AWS IoT SDK.</li>
<li>When the user asks Alexa "what is the current" temperature or humidity for a room, Alexa will call on an Alexa Skill.</li>
<li>The Alexa Skill will connect to <a href="https://aws.amazon.com/lambda/">AWS Lambda</a>. The Lambda code will use python to connect to AWS IoT and gather the current state of the Thing Shadow.</li>
<li>The state of the Thing Shadow will be returned to Alexa and read aloud.</li>
</ol>
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-pvtPc3T3Xq0/WnizCMqUXsI/AAAAAAAAAF8/ppf8DeED2RQgZUAfLhycJVQlTkBkw3g2QCK4BGAYYCw/s1600/nodemcu_alexa_diagram_2.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="532" src="https://3.bp.blogspot.com/-pvtPc3T3Xq0/WnizCMqUXsI/AAAAAAAAAF8/ppf8DeED2RQgZUAfLhycJVQlTkBkw3g2QCK4BGAYYCw/s640/nodemcu_alexa_diagram_2.PNG" width="640" /></a></div>
<h3>
</h3>
</div>
<div>
<h4>
Security Design Considerations</h4>
<div>
A requirement of AWS IoT thing interaction is certificate based encrypted communications. At the time of this post, Nodemcu does not support the required TLS 1.2 encryption. The AWS IoT SDK is used as a work around to get a one way stream of sensor data into AWS IoT.</div>
<div>
<br /></div>
<div>
This is not ideal, because credentials will have to be included in the sketch. When we place credentials on our Nodemcu, they are written in clear text. Even if you encrypt or obfuscate the creds, they will still be written to the Nodemcu in clear text. You should be aware of this and consider the potential implications.</div>
<div>
<br /></div>
<div>
An option I have not yet tested is <a href="https://mongoose-os.com/">Mongoose OS</a>. It supports AWS IoT encryption for ESP8266 and I will most likely post some material on using Mongoose OS in the future. Another option is an IoT hub/broker such as <a href="https://aws.amazon.com/greengrass/">AWS Greengrass</a> that supports AWS IoT encryption requirements.</div>
<h3>
Next Steps</h3>
<div>
In the next part of this guide we will setup our Nodemcu hardware and DHT sensor.<br />
<br />
<a href="http://blog.kilomon.com/2018/02/creating-alexa-skills-for-iot-and.html">Go to Part 2</a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
Danhttp://www.blogger.com/profile/01422027852211426218noreply@blogger.com1tag:blogger.com,1999:blog-36706321802012849.post-14658522891153747832018-02-02T10:10:00.000-08:002018-02-07T13:47:55.761-08:00Hacking the Sonoff Wifi Switch - Part 3 Alexa Smart Home<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-v_YlDfycDbE/WnSPHJoUAVI/AAAAAAAAAEg/rw7fyi4q0Mg-MIF-kNDyqeD8XWG650k1QCK4BGAYYCw/s1600/sonoff_hack_0012.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="225" src="https://3.bp.blogspot.com/-v_YlDfycDbE/WnSPHJoUAVI/AAAAAAAAAEg/rw7fyi4q0Mg-MIF-kNDyqeD8XWG650k1QCK4BGAYYCw/s400/sonoff_hack_0012.JPG" width="400" /></a></div>
<h2>
</h2>
<h2>
Controlling Sonoff with Alexa</h2>
<div>
This post will build our previous work with the Sonoff Wifi Switch. We'll focus on using an Arduino library called fauxmo to allow Alexa to interact with the Sonoff.</div>
<div>
<br /></div>
<div>
<a href="http://blog.kilomon.com/2018/01/hacking-sonoff-wifi-switch.html">Go to Part 1</a></div>
<div>
<a href="http://blog.kilomon.com/2018/02/hacking-sonoff-wifi-switch-part-2.html">Go to Part 2</a></div>
<h3>
Overview</h3>
<div>
I have been controlling appliances such as lights and aquaponics equipment using MQTT with Node-RED and also Blynk. Both work well. When I recieved an Echo Plus as a gift for Christmas I quickly understood the potential that the Alexa service had. It is simple to use and for those of us that like getting under the hood, functional short comings can be overcome with the creation of Alexa Skills and some type of internet accessible service to handle logic and automation (AWS Lambda, Node-RED, etc). </div>
<div>
<br /></div>
<div>
Echo Dot can be had a reasonable price currently. You can also keep tabs on the Alexa development pages. They have been giving out Echo Dot's to Skill creators that meet certain criteria.</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
This guide will use the <a href="https://bitbucket.org/xoseperez/fauxmoesp">FauxmoESP</a> library to expose the Sonoff to Alexa on your local network. FauxmoESP is a port of the python fauxmo library and enables ESP8266 to emulate a Belkin WeMo device. The advantage here is that Alexa has an established method that it uses to interact with Belkin WeMo devices. Check out <a href="https://bitbucket.org/xoseperez/fauxmoesp">Xose Perez's documentation</a> for details.</div>
<div>
<br /></div>
<div>
Alexa will then be able to control the Sonoff using standard voice commands or through Alexa Routines. This is a simple working example and not an in depth review of Alexa.</div>
<div>
<h3>
Goals</h3>
</div>
<div>
<ul>
<li>Program the Sonoff Wifi Switch with code that will expose it to the Alexa Discovery processes</li>
<li>Discover the device and add it to Smart Home</li>
<li>Control the Sonoff with voice commands</li>
<li>Control the Sonoff with a routine</li>
</ul>
<div>
<h3>
Prep</h3>
</div>
</div>
<div>
<ul>
<li>Hacked Sonoff (<a href="http://blog.kilomon.com/2018/01/hacking-sonoff-wifi-switch.html">steps in Part 1 of this series</a>)</li>
<li>Modded USB to Serial UART Adapter (<a href="http://blog.kilomon.com/2018/02/hacking-sonoff-wifi-switch-part-2.html">steps in Part 2 of this series</a>)</li>
<li>Arduino IDE</li>
<li>Echo Dot or another Echo device, setup and ready for use</li>
<li>Alexa App</li>
</ul>
<div>
<h3>
Setup Steps</h3>
</div>
<div>
<i>If you did not follow the previous posts in this series you will need to go back and follow the steps to install the ESP8266 libraries in Arduino.</i></div>
<div>
<ul>
<li>Download the current FauxmoESP library at <a href="https://bitbucket.org/xoseperez/fauxmoesp/downloads/">https://bitbucket.org/xoseperez/fauxmoesp/downloads/</a></li>
<li>Open the Arduino IDE > Sketch > Include Library > Add .ZIP Library...</li>
<li>Navigate to the downloaded fauxmo library and Click Open</li>
<li>Connect your Sonoff to your computer using the Modded USB to Serial UART adapter and prepare your programming settings as shown <a href="http://blog.kilomon.com/2018/02/hacking-sonoff-wifi-switch-part-2.html">in Part 2 of this series</a></li>
<li>Program the Sonoff with the following code</li>
</ul>
<h3>
Code</h3>
</div>
<div>
This code is a slightly altered version of the example sketch that comes with FauxmoESP. You will need to insert your wifi SSID/PASS and also the name you wish to give your Sonoff, such as, "Desk Light".</div>
<br />
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?skin=desert"></script>
<br />
<pre class="prettyprint">#include <arduino.h="">
#include <esp8266wifi.h="">
#include <fauxmoesp.h="">
#define WIFI_SSID "YOUR SSID"
#define WIFI_PASS "YOUR PASS"
#define SERIAL_BAUDRATE 115200
#define RELAY_PIN 12
#define LED_PIN 13
fauxmoESP fauxmo;
void wifiSetup() {
// Set WIFI module to STA mode
WiFi.mode(WIFI_STA);
// Connect
Serial.printf("[WIFI] Connecting to %s ", WIFI_SSID);
WiFi.begin(WIFI_SSID, WIFI_PASS);
// Wait
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(100);
}
Serial.println();
// Connected!
Serial.printf("[WIFI] STATION Mode, SSID: %s, IP address: %s\n", WiFi.SSID().c_str(), WiFi.localIP().toString().c_str());
}
void callback(uint8_t device_id, const char * device_name, bool state) {
Serial.print("Device "); Serial.print(device_name);
Serial.print(" state: ");
if (state) {
Serial.println("ON");
} else {
Serial.println("OFF");
}
//Switching action on detection of device name
if ( (strcmp(device_name, "YOUR DEVICE NAME") == 0) ) {
if (!state){
digitalWrite(RELAY_PIN, LOW);
} else {
digitalWrite(RELAY_PIN, HIGH);
}
}
}
void setup() {
// turn on LED
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW); // low turns LED on
// setup relay pin
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, LOW);
// Init serial port and clean garbage
Serial.begin(SERIAL_BAUDRATE);
// Wifi
wifiSetup();
// Fauxmo
fauxmo.addDevice("YOUR DEVICE NAME");
fauxmo.onMessage(callback);
}
void loop() {
fauxmo.handle();
}
</pre>
<h3>
Alexa Steps</h3>
</div>
<div>
<ul>
<li>Verify that the code is working as expected by using the Arduino Serial Monitor</li>
<ul>
<li>The Sonoff should be connecting to wifi and displaying its IP</li>
</ul>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-q30mRsPQxBo/WnSdoD35KnI/AAAAAAAAAE4/7pObM_hbJjodO_Izcw2dnlXIMKQ2omqxwCK4BGAYYCw/s1600/sonoff_alexa_serialmon.PNG" imageanchor="1"><img border="0" height="94" src="https://4.bp.blogspot.com/-q30mRsPQxBo/WnSdoD35KnI/AAAAAAAAAE4/7pObM_hbJjodO_Izcw2dnlXIMKQ2omqxwCK4BGAYYCw/s640/sonoff_alexa_serialmon.PNG" width="640" /></a></div>
<div>
<br /></div>
<ul>
<li>Disconnect the Sonoff from the USB to Serial UART adapter</li>
<li>Plug in the Sonoff to a wall outlet and connect an appliance such as a lamp</li>
<li>Now we need to discover the Sonoff using the command "Alexa, discover new devices."</li>
<ul>
<li>Alexa will state the device name that was discovered</li>
</ul>
<li>You can now test that things are working by using the commands, "Alexa, turn on <device name>" and "Alexa, turn off <device name>"</li>
<li>Devices can be viewed, modified, and removed using the Alexa app > Smart Home</li>
<ul>
<li>Using groups is very helpful in scenarios in which you would like to control many Sonoff's with the same command or routine</li>
</ul>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://3.bp.blogspot.com/-F-Fl7zuB27A/WnSih3OstQI/AAAAAAAAAFE/2l5Ijowa3qsk_2WjIaDgjIgcVjjQGxfZwCLcBGAs/s1600/Screenshot_alexa_01.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" data-original-height="1600" data-original-width="900" height="400" src="https://3.bp.blogspot.com/-F-Fl7zuB27A/WnSih3OstQI/AAAAAAAAAFE/2l5Ijowa3qsk_2WjIaDgjIgcVjjQGxfZwCLcBGAs/s400/Screenshot_alexa_01.png" width="225" /></a></div>
<a href="https://1.bp.blogspot.com/-4F-pf6Gxm3g/WnSih1BZTjI/AAAAAAAAAFI/IV9QoBqyF3w0mvW4VZycIA2NepTukDl8QCLcBGAs/s1600/Screenshot_alexa_02.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em; text-align: center;"><img border="0" data-original-height="1600" data-original-width="900" height="400" src="https://1.bp.blogspot.com/-4F-pf6Gxm3g/WnSih1BZTjI/AAAAAAAAAFI/IV9QoBqyF3w0mvW4VZycIA2NepTukDl8QCLcBGAs/s400/Screenshot_alexa_02.png" width="225" /></a><br />
<br />
<div>
<br /></div>
<ul>
<li>To create a routine use the Alexa app > Routines</li>
<ul>
<li>I primarily use time schedules to control routines.</li>
</ul>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-1t6fpMyu9Rc/WnSiiEf-s0I/AAAAAAAAAFM/42CpO66WuBcTZSOtxtsthlhi0u4y2CJ-gCLcBGAs/s1600/Screenshot_alexa_03.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1600" data-original-width="900" height="400" src="https://2.bp.blogspot.com/-1t6fpMyu9Rc/WnSiiEf-s0I/AAAAAAAAAFM/42CpO66WuBcTZSOtxtsthlhi0u4y2CJ-gCLcBGAs/s400/Screenshot_alexa_03.png" width="225" /></a></div>
<div>
<br /></div>
<h3>
Result</h3>
</div>
<div>
While this took very little effort... this is pretty awesome. You can control your device via a cloud based service without exposing the device to the internet and without the effort and maintenance of deploying a server or container to handle protocols and automation.</div>
<div>
<br /></div>
<div>
I currently have 12 Sonoff Wifi Switches, all controlled by Alexa. I have had very little issues over the last month of use. I have one Sonoff that occassionally loses its connection to Wifi. The only thing I find lacking at the moment is a more complex routine builder, but I will try to address that in the next post.</div>
<div>
<h3>
Next Time</h3>
</div>
<div>
I have some ideas to utilize AWS Lambda and Alexa Skills to create more advanced time schedules.</div>
<div>
<br /></div>
<div>
<div>
<a href="http://blog.kilomon.com/2018/01/hacking-sonoff-wifi-switch.html">Go to Part 1</a></div>
<div>
<a href="http://blog.kilomon.com/2018/02/hacking-sonoff-wifi-switch-part-2.html">Go to Part 2</a></div>
</div>
<div>
<br /></div>
<div>
<br /></div>
Danhttp://www.blogger.com/profile/01422027852211426218noreply@blogger.com4tag:blogger.com,1999:blog-36706321802012849.post-36321413299684830292018-02-01T10:14:00.000-08:002018-02-06T13:29:49.062-08:00Hacking the Sonoff Wifi Switch - Part 2<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-vTNUtYxmBqo/WnNczJvsMYI/AAAAAAAAADw/XwrhCqIsTUsjKF7xMC2eX6fhWYubrBvWACK4BGAYYCw/s1600/sonoff_hack_20002.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="225" src="https://2.bp.blogspot.com/-vTNUtYxmBqo/WnNczJvsMYI/AAAAAAAAADw/XwrhCqIsTUsjKF7xMC2eX6fhWYubrBvWACK4BGAYYCw/s400/sonoff_hack_20002.JPG" width="400" /></a></div>
<br />
<h2>
Programming the Sonoff Wifi Switch</h2>
<div>
In my last post, I showed how to mod the Sonoff Wifi Switch for easy programming using Arduino (or any other ESP8266 programming utility). In this post, I'll show how I setup my physical programming hardware and get custom code onto the Sonoff using the Arduino IDE.<br />
<br />
<div>
<a href="http://blog.kilomon.com/2018/01/hacking-sonoff-wifi-switch.html">Go to Part 1</a></div>
<a href="http://blog.kilomon.com/2018/02/hacking-sonoff-wifi-switch-part-3-alexa.html">Go to Part 3</a></div>
<div>
<h3>
Overview</h3>
</div>
<div>
Programming the ESP8266 based Sonoff is relatively simple. It will require a connection between the Sonoff and the programmer, which in this case is a PC, Raspberry PI, or Mac. A simple, cheap USB to Serial UART adapter will connect the computer to the Sonoff for programming.<br />
<br />
<i><b>A WORD OF CAUTION</b></i>: <i>These devices are designed to work on your home mains power. You should understand the implications of connecting a device you altered to mains power. Do not ever work on a device that is connect to a mains power source. Do not attempt to program the Sonoff while it is connected to a mains power source.</i></div>
<div>
<div>
<h3>
Goals</h3>
<h3>
<div style="font-size: medium; font-weight: 400;">
</div>
<div style="font-size: medium; font-weight: 400;">
<ul>
<li>Make an easy method to connect each Sonoff to the programmer</li>
<ul>
<li>Allow the Sonoff to be programmed without requiring disassembly of the enclosure</li>
</ul>
<li>Attach a switch for easily putting the Sonoff in flash mode</li>
<li>Program and test the Sonoff using Arduino</li>
<ul>
<li>Connect to local wireless</li>
<li>Test the builtin LED</li>
<li>Test the relay</li>
</ul>
</ul>
</div>
</h3>
<h3>
Prep</h3>
</div>
<div>
<i>I have linked the tools and components I used to build this project. I personally own each item linked below. </i></div>
<h4>
Tools I Used</h4>
<div>
<ul>
<li>Wire Cutter\Stripper Combo - <a href="http://amzn.to/2BHKDHH">http://amzn.to/2BHKDHH</a></li>
<li>Small Needle Nose Pliers - <a href="http://amzn.to/2GVL3Kc">http://amzn.to/2GVL3Kc</a></li>
<li>Soldering Iron - <a href="http://amzn.to/2nRfdWi">http://amzn.to/2nRfdWi</a></li>
<li>Solder</li>
<li>Tip Cleaner - <a href="http://amzn.to/2sdpZLQ">http://amzn.to/2sdpZLQ</a></li>
<li>Third Hand for Soldering - <a href="http://amzn.to/2E52kTg">http://amzn.to/2E52kTg</a></li>
<li>2.5mm Pin Crimping Tool - <a href="http://amzn.to/2EpegPe">http://amzn.to/2EpegPe</a> (this works, but is not a great tool)</li>
<li>Label Maker (optional) - <a href="http://amzn.to/2BfuaK6">http://amzn.to/2BfuaK6</a></li>
</ul>
<h4>
Parts and Pieces</h4>
</div>
<div>
<ul>
<li>Modded Sonoff Wifi Switch(s)</li>
<li>JST Type 2.5mm Male Connector - <a href="http://amzn.to/2GUqQV8">http://amzn.to/2GUqQV8</a></li>
<li>2.5mm Male to Female Header wires - <a href="http://amzn.to/2GUu6Qc">http://amzn.to/2GUu6Qc</a></li>
<li>SPST Switch - purchased from an electronics surplus sale</li>
<li>USB to Serial UART adapter - <a href="http://amzn.to/2Be35qr">http://amzn.to/2Be35qr</a></li>
</ul>
<div>
<h3>
Assembly Steps</h3>
<div>
<ul>
<li>Pick 4 female jumper wires. 4" - 8" is a good range to work with</li>
<ul>
<li>You may want to use the color code from the last <a href="http://blog.kilomon.com/2018/01/hacking-sonoff-wifi-switch.html">post</a> to keep things in order</li>
</ul>
<li>Cut one end off of each jumper and strip about 1/16" off</li>
<ul>
<li>Keep one female header connecter on each wire</li>
<li>These female connectors will attach to the USB to Serial UART adapter pins</li>
</ul>
<li>Solder the SPST switch on the GND wire</li>
<ul>
<li>It doesn't really matter where you cut the GND wire. Just pick a spot that will leave you enough length to strip and solder the wire to the SPST</li>
</ul>
<li>Crimp a JST 2.5mm pin to each stripper wire and insert into the male JST type connector</li>
<li>Connect your wires to the USB to Serial UART adapter</li>
<ul>
<li>Remember that in serial communication TX connects to RX and RX connects to TX</li>
<li>Refer to the last <a href="http://blog.kilomon.com/2018/01/hacking-sonoff-wifi-switch.html">post</a> to if you used the color code that I did for RX, TX, VCC, and GND</li>
</ul>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-3eaAun6HyCk/WnNc5-4gHpI/AAAAAAAAAD4/ZG-SDuGs3v0Y8CEpAqDZLP74X67Ln3GrACK4BGAYYCw/s1600/sonoff_hack_20002.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="360" src="https://1.bp.blogspot.com/-3eaAun6HyCk/WnNc5-4gHpI/AAAAAAAAAD4/ZG-SDuGs3v0Y8CEpAqDZLP74X67Ln3GrACK4BGAYYCw/s640/sonoff_hack_20002.JPG" width="640" /></a></div>
<div>
<br /></div>
<h3>
Connection Steps</h3>
</div>
</div>
</div>
</div>
<div>
The Sonoff needs to be placed in flash mode before it can be programmed. The button on the Sonoff must be pressed when power from the UART adapter is attached. I was able to do this by plugging the USB cable into the computer, holding the Sonoff with the button pressed and the UART adapter in the same hand, and then plugging the USB cable into the UART adapter with the other hand. At that point you can release the button on the Sonoff.</div>
<div>
<br /></div>
<div>
This is clumsy, so I think its worth the effort to put a switch on the GND to make the process less of a contortion act.</div>
<div>
<ul>
<li>Connect the USB to Serial UART adapter to the Sonoff using the JST type connector</li>
<li>Switch the SPST switch to the off position</li>
<ul>
<li>You will know that the Sonoff has power if the green LED turns on</li>
</ul>
<li>Connect a USB cable between the computer and the USB to Serial UART adapter</li>
<li>Press and hold the Sonoff button then switch the SPST to ON</li>
<li>Release the Sonoff button and you are ready for programming</li>
<ul>
<li>The Sonoff LED should remain off when in flash mode</li>
</ul>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-xOpgHpRKn2Y/WnNdEdLTtfI/AAAAAAAAAEA/0fuNIdbjZBQ61ZZIF4m6oMYYzsK-HxxeACK4BGAYYCw/s1600/sonoff_hack_20001.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="360" src="https://2.bp.blogspot.com/-xOpgHpRKn2Y/WnNdEdLTtfI/AAAAAAAAAEA/0fuNIdbjZBQ61ZZIF4m6oMYYzsK-HxxeACK4BGAYYCw/s640/sonoff_hack_20001.JPG" width="640" /></a></div>
<div>
<br /></div>
<h3>
Arduino Steps</h3>
<div>
The Arduino IDE needs a couple things configured prior to testing custom code on the Sonoff.<br />
<br />
I am making an assumption that you have programmed with Arduino before. If you haven't go have a look at one the many detailed tutorials out there.</div>
<div>
<ul>
<li>Open the Arduino IDE</li>
<li>Go to File > Preferences and locate Additional Board Manager URLs:</li>
<li>Paste this into the field http://arduino.esp8266.com/stable/package_esp8266com_index.json and select OK</li>
<ul>
<li>This will allow you to download the ESP8266 module via the Arduino Library Manager</li>
</ul>
</ul>
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-jrxRDPVLhBg/WnNNtijJ_9I/AAAAAAAAACs/pyNXQPaPwP0gcwRNB72YXV8JBpBVN3ObwCK4BGAYYCw/s1600/sonoff_boardman.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://1.bp.blogspot.com/-jrxRDPVLhBg/WnNNtijJ_9I/AAAAAAAAACs/pyNXQPaPwP0gcwRNB72YXV8JBpBVN3ObwCK4BGAYYCw/s1600/sonoff_boardman.PNG" /></a></div>
<div>
<br /></div>
<div>
<ul>
<li>Go to Tools > Boards:... > Boards Manager</li>
<li>In the Search field enter esp8266 and Install esp8266 by ESP8266 Community</li>
<ul>
<li>I have been using version 2.3.0, because 2.4.0 has been giving me headaches with other esp8266 libraries.</li>
</ul>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-YnUSVJ11Byc/WnNPoFbtl-I/AAAAAAAAADA/w1i9TYaus9AwdnP5zveM_LO3JPhpB7b9gCK4BGAYYCw/s1600/sonoff_libman.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="304" src="https://3.bp.blogspot.com/-YnUSVJ11Byc/WnNPoFbtl-I/AAAAAAAAADA/w1i9TYaus9AwdnP5zveM_LO3JPhpB7b9gCK4BGAYYCw/s640/sonoff_libman.PNG" width="640" /></a></div>
<h3 style="clear: both; text-align: left;">
Code</h3>
</div>
</div>
<div>
I used a simple code written by Rui Santos at <a href="http://randomnerdtutorials.com/">http://randomnerdtutorials.com</a>. It sets the Sonoff up as a web server that you can connect to with your web browser. Then you can interact with the LED and the RELAY. It's an easy test that will let us know things are in working order.</div>
<div>
<br /></div>
<div>
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?skin=desert"></script>
<br />
<pre class="prettyprint">/*********
Rui Santos
Complete project details at http://randomnerdtutorials.com
*********/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
MDNSResponder mdns;
// Replace with your network credentials
const char* ssid = "YOUR SSID";
const char* password = "YOUR PASS";
ESP8266WebServer server(80);
String webPage = "";
int gpio13Led = 13;
int gpio12Relay = 12;
void setup(void){
webPage += "<h1>SONOFF Web Server</h1><p><a href=\"on\"><button>ON</button></a>&nbsp;<a href=\"off\"><button>OFF</button></a></p>";
// preparing GPIOs
pinMode(gpio13Led, OUTPUT);
digitalWrite(gpio13Led, HIGH);
pinMode(gpio12Relay, OUTPUT);
digitalWrite(gpio12Relay, HIGH);
Serial.begin(115200);
delay(5000);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (mdns.begin("esp8266", WiFi.localIP())) {
Serial.println("MDNS responder started");
}
server.on("/", [](){
server.send(200, "text/html", webPage);
});
server.on("/on", [](){
server.send(200, "text/html", webPage);
digitalWrite(gpio13Led, LOW);
digitalWrite(gpio12Relay, HIGH);
delay(1000);
});
server.on("/off", [](){
server.send(200, "text/html", webPage);
digitalWrite(gpio13Led, HIGH);
digitalWrite(gpio12Relay, LOW);
delay(1000);
});
server.begin();
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient();</pre>
}<br />
<h3>
Program the Sonoff</h3>
<div>
<i>REMINDER: Do not plug the Sonoff into your mains while programming</i></div>
<br />
<ul>
<li>Insert your SSID and password into the code</li>
<li>Use the following settings to program the Sonoff</li>
<ul>
<li>Board: Generic ESP8266 Module</li>
<li>Flash Mode: DOUT</li>
<li>Upload: 115200</li>
<li>I have found all other defaulted settings to work fine for me</li>
</ul>
<li>Open the Serial Monitor and then Upload the code</li>
<ul>
<li>If all goes well, you should see the LED's on the UART adapter blinking as data is being transferred to the Sonoff in addition to the progress in the Arduino console.</li>
<li>If you have problems, I would check your TX - RX connections and that your programming setting in Arduino are correct.</li>
<li>I found that if you program with Flash Mode set to DIO, it will appear to program fine, but then the ESP8266 will not run the code properly.</li>
</ul>
<li>In the Serial Monitor you should see that the Sonoff has connected to Wifi and is ready for HTTP connections</li>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-zWuDi2XY_fs/WnNU3KMOuVI/AAAAAAAAADU/4lLqM-yYJbMcoH-5jAlKstGs8X4zIJuPgCK4BGAYYCw/s1600/sonoff_serialmon.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://4.bp.blogspot.com/-zWuDi2XY_fs/WnNU3KMOuVI/AAAAAAAAADU/4lLqM-yYJbMcoH-5jAlKstGs8X4zIJuPgCK4BGAYYCw/s400/sonoff_serialmon.PNG" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
</div>
<ul>
<li>Open a web browser and use the IP presented in the Serial Monitor to navigate to the Sonoff web page. In my case its http://10.0.0.250</li>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-USK6RtgFL9Q/WnNVnjp9B-I/AAAAAAAAADg/UXRDGj7TGB4X_-8s6IVq-0om5gVllkacwCK4BGAYYCw/s1600/sonoff_web.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="146" src="https://1.bp.blogspot.com/-USK6RtgFL9Q/WnNVnjp9B-I/AAAAAAAAADg/UXRDGj7TGB4X_-8s6IVq-0om5gVllkacwCK4BGAYYCw/s320/sonoff_web.PNG" width="320" /></a></div>
<div>
<br /></div>
<br />
<div>
<ul>
<li>Now, <i>without the Sonoff plug into your mains,</i> select the ON button. You should hear the RELAY click and see the LED turn on.</li>
<li>Select the OFF button. You should hear the RELAY click and see the LED turn off.</li>
<li>If you intend to program several Sonoff Wifi Switches you should label the Sonoff after it is programmed.</li>
</ul>
</div>
<br />
<h3>
Result</h3>
<div>
You now have a hacked Sonoff Wifi Switch that you can program with any custom code you choose. I have used various methods to control the Sonoff, including MQTT with Node-RED and Blynk with great results.</div>
<div>
<h3>
Next Time</h3>
<div>
For me, the most enjoyable method of controlling the Sonoff has been using Alexa. In my next Sonoff post we will use Alexa to enable voice commands and simple routines to control the Sonoff.</div>
</div>
<br />
<div>
<a href="http://blog.kilomon.com/2018/02/hacking-sonoff-wifi-switch-part-3-alexa.html">Go to Part 3</a><br />
<a href="http://blog.kilomon.com/2018/01/hacking-sonoff-wifi-switch.html">Go to Part 1</a></div>
<br />
<div>
<div>
</div>
</div>
</div>
Danhttp://www.blogger.com/profile/01422027852211426218noreply@blogger.com0tag:blogger.com,1999:blog-36706321802012849.post-40317395242134052162018-01-30T13:27:00.002-08:002018-02-07T08:29:06.368-08:00Hacking the Sonoff Wifi Switch - Part 1<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-k3BB9-u-rY8/WnNgPgNufAI/AAAAAAAAAEQ/L6G6tpIpIM0BMvdp-OPAg9T-9_XT-IeoQCK4BGAYYCw/s1600/sonoff_hack_0012.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="225" src="https://2.bp.blogspot.com/-k3BB9-u-rY8/WnNgPgNufAI/AAAAAAAAAEQ/L6G6tpIpIM0BMvdp-OPAg9T-9_XT-IeoQCK4BGAYYCw/s400/sonoff_hack_0012.JPG" width="400" /></a></div>
<h2>
Making the Sonoff Easy to Program</h2>
<div>
The release of the ESP8266 has generated a lot of interest in the microcontroller community. Nodemcu and other cheap MCU's with built in wifi have really opened the door for consumers/makers to create cost effective IoT solutions. One significant reason ESP8266 based devices are taking off is due to the fact that Arduino libraries have been created and are well maintained.</div>
<div>
<br /></div>
<div>
Sonoff Wifi Switches, which are based on the ESP8266, are getting a lot of attention and for good reason. They are cheap and very hackable. <i>I should mention that Sonoff has its own cloud service for controlling these wireless switches</i>. </div>
<div>
<br /></div>
<div>
Here is my take on hacking the Sonoff.<br />
<div>
<br /></div>
<div>
<a href="http://blog.kilomon.com/2018/02/hacking-sonoff-wifi-switch-part-2.html">Go to Part 2</a><br />
<a href="http://blog.kilomon.com/2018/02/hacking-sonoff-wifi-switch-part-3-alexa.html">Go to Part 3</a></div>
</div>
<div>
<h3>
Overview</h3>
</div>
<div>
I have been playing around with a small DIY aquaponics system in my home office. So far its a success, but I would like to have more control. Currently, I have 2 Sonoff wireless switches (both with custom code) controlling grow lights and aquarium lights. I would like to control each of the pumps that move water from the fish aquariums to grow beds. This will allow me to try out some different fill and drain cycles.<br />
<br />
JST type connectors will be used to make it easy to connect a USB to Serial UART adapter to the Sonoff.<br />
<br />
<i><b>A WORD OF CAUTION</b></i>: <i>These devices are designed to work on your home mains power. You should understand the implications of connecting a device you altered to mains power. Do not ever work on a device that is connect to a mains power source. Do not attempt to program the Sonoff while it is connected to a mains power source.</i><br />
<i><br /></i>
<i>This hack essentially removes the enclosures ability to insulate. Proceed at your own risk. </i></div>
<div>
<h4>
Why not use an off the shelf solution?</h4>
</div>
<div>
Using a standard Alexa compatible smart plug or the "out of box" Sonoff devices limits you to very rudementary schedules and routines. I have been using some off the shelf smart plugs for simple things with good success, but I need something a tad more sophisticated for this project.<br />
<h4>
Why use connectors at all?</h4>
</div>
<div>
I programmed my first Sonoff by soldering wires with female pin header connectors. Then the female connectors were connected directly to a USB to Serial UART adapter for programming. This worked, but you end up having to keep a pin out handy each time you want to connect things. I wanted something that would not take any effort.</div>
<div>
<br /></div>
<div>
I had thought of potentially connecting and mounting the required USB to Serial UART adapter inside the Sonoff enclosure. I think it could be done. However, this would double the cost of each switch.</div>
<div>
<br /></div>
<div>
Another option that seems attractive is using the "shield" approach. By attaching pin header rows to the enclosure it would be possible turn the USB to Serial UART board into a shield. It would be easy to attach and detach the USB to Serial UART board anytime you needed. It would expose pins that are connected to a circuit that draws power via a mains power source, so that would take some considering.</div>
<div>
<h3>
Goals</h3>
</div>
<div>
<ul>
<li>Convert the Sonoff Wifi Switch into a programmable device.</li>
<li>Make an easy method to connect each Sonoff to the programmer.</li>
<ul>
<li>Allow the Sonoff to be programmed without requiring disassembly of the enclosure.</li>
</ul>
<li>Extend the usefulness of the Sonoff by increasing the number of devices that can be controlled.</li>
</ul>
<h3>
Prep</h3>
</div>
<div>
<i>I have linked the tools and components I used to build this project. I personally own each item linked below. </i></div>
<h4>
Tools I Used</h4>
<div>
<ul>
<li>Utility Knife </li>
<li>Wire Cutter\Stripper Combo - <a href="http://amzn.to/2BHKDHH">http://amzn.to/2BHKDHH</a></li>
<li>Small Needle Nose Pliers - <a href="http://amzn.to/2GVL3Kc">http://amzn.to/2GVL3Kc</a></li>
<li>Soldering Iron - <a href="http://amzn.to/2nRfdWi">http://amzn.to/2nRfdWi</a></li>
<li>Solder</li>
<li>Tip Cleaner - <a href="http://amzn.to/2sdpZLQ">http://amzn.to/2sdpZLQ</a></li>
<li>Rotating Circuit Board Holder - <a href="http://amzn.to/2E79r9H">http://amzn.to/2E79r9H</a></li>
<li>Third Hand for Soldering - <a href="http://amzn.to/2E52kTg">http://amzn.to/2E52kTg</a></li>
<li>Drill - <a href="http://amzn.to/2E5eXtt">http://amzn.to/2E5eXtt</a></li>
<li>Step-Bit - <a href="http://amzn.to/2BI0E0f">http://amzn.to/2BI0E0f</a></li>
<li>Hot Glue Gun - <a href="http://amzn.to/2GTHhkz">http://amzn.to/2GTHhkz</a></li>
<li>Precision Screw driver set - <a href="http://amzn.to/2nIjonN">http://amzn.to/2nIjonN</a></li>
<li>Phillips Screw Driver</li>
<li>2.5mm Pin Crimping Tool - <a href="http://amzn.to/2EpegPe">http://amzn.to/2EpegPe</a> (this works, but is not a great tool)</li>
<li>Marker</li>
</ul>
<h4>
Parts and Pieces</h4>
</div>
<div>
<ul>
<li>Sonoff Wifi Switch(s) - Single <a href="http://amzn.to/2nKhhzZ">http://amzn.to/2nKhhzZ</a> 8-Pack <a href="http://amzn.to/2BJNC2v">http://amzn.to/2BJNC2v </a></li>
<li>2 Prong Extension Cables (mine have 3 sockets. purchased at Lowes for around $1.40 ea)</li>
<li>5/16" Rubber Grommets - <a href="http://amzn.to/2GUtkmg">http://amzn.to/2GUtkmg</a></li>
<li>JST Type 2.5mm Female Connectors - <a href="http://amzn.to/2GUqQV8">http://amzn.to/2GUqQV8</a></li>
<li>22 Gauge Hookup Wire (preferably stranded) - <a href="http://amzn.to/2ElF9U2">http://amzn.to/2ElF9U2</a></li>
</ul>
<h3>
Steps</h3>
<div>
<ul>
<li>Disassembly</li>
<ul>
<li>Open the packing and set the screws and end covers to the side.</li>
<li>To open the enclosure, use a pocket knife or utility knife to cut the small seal and pry the shell open.</li>
</ul>
</ul>
</div>
<div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://4.bp.blogspot.com/-51thWSudQu0/WnDFF_XgavI/AAAAAAAAAAQ/6OALjrnCdkEtG-uoPB8TAyT9TBSFjLpkACLcBGAs/s1600/sonoff_hack_0002.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="" border="0" data-original-height="900" data-original-width="1600" height="358" src="https://4.bp.blogspot.com/-51thWSudQu0/WnDFF_XgavI/AAAAAAAAAAQ/6OALjrnCdkEtG-uoPB8TAyT9TBSFjLpkACLcBGAs/s640/sonoff_hack_0002.JPG" title="Sonoff Unboxing" width="640" /></a></div>
</div>
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-hcmWxoN-6KU/WnDFGzQeFwI/AAAAAAAAAAc/492Zh0k0HPEygl4JQKG16YLt24p9Y5MaQCLcBGAs/s1600/sonoff_hack_0004.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="900" data-original-width="1600" height="360" src="https://2.bp.blogspot.com/-hcmWxoN-6KU/WnDFGzQeFwI/AAAAAAAAAAc/492Zh0k0HPEygl4JQKG16YLt24p9Y5MaQCLcBGAs/s640/sonoff_hack_0004.JPG" width="640" /></a></div>
<div>
<ul>
<li>Drill a 5/16" hole in the side of the enclosure.</li>
<ul>
<li>I used a step-bit, but a 5/16" drill bit would work fine</li>
<li>It is necessary to drill the hole where there will be no internal components in the way. I use the last "f" in the Sonoff labeling as a reference. </li>
<li>Please look at the next picture to see the hole placement that I used.</li>
</ul>
</ul>
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-0Bcp8C8-7Qw/WnDFHLYCMFI/AAAAAAAAAAk/Bjaw0x9vGx0734DlLC5pv-f2BwVXNwuQwCLcBGAs/s1600/sonoff_hack_0006.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em; text-align: center;"><img border="0" data-original-height="900" data-original-width="1600" height="360" src="https://2.bp.blogspot.com/-0Bcp8C8-7Qw/WnDFHLYCMFI/AAAAAAAAAAk/Bjaw0x9vGx0734DlLC5pv-f2BwVXNwuQwCLcBGAs/s640/sonoff_hack_0006.JPG" width="640" /></a></div>
<div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<ul>
<li style="text-align: left;">Insert a 5/16" rubber grommet into the drilled hole</li>
</ul>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://4.bp.blogspot.com/-RMUb2wtOPhQ/WnDFHieSwSI/AAAAAAAAAAo/QsTQnAzig30IE66UGtkXaSmF2mPk6Fq_gCLcBGAs/s1600/sonoff_hack_0007.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="900" data-original-width="1600" height="360" src="https://4.bp.blogspot.com/-RMUb2wtOPhQ/WnDFHieSwSI/AAAAAAAAAAo/QsTQnAzig30IE66UGtkXaSmF2mPk6Fq_gCLcBGAs/s640/sonoff_hack_0007.JPG" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<br />
<ul>
<li> Cut 4 - hookup wires @ 2" for VCC, GND, TX, and RX</li>
<ul>
<li>I used red = VCC, green = GND, white = TX, black = RX</li>
<li>This wires will be trimmed to as desired later.</li>
</ul>
<li>Strip about 1/16" off each end of every wire</li>
<li>Solder the hookup wire to the Sonoff PCB</li>
<ul>
<li>This is probably the clearest pin out of the PCB I have found <a href="https://ubidots.com/blog/wp-content/uploads/hsp_files/SONOFF-PINOUT.jpg">Sonoff Pinout</a></li>
<li>Solder your hookup wires to using your color scheme to match the pinout</li>
<li>Using a PCB holder and a third hand makes the process very easy</li>
</ul>
</ul>
<div>
<ul>
<li>Run your hookup wires through the hole you drilled</li>
<li>Place the PCB back into the top shell of the enclosure</li>
<ul>
<li>Pay attention to where the button and LED go. The button must go through the small button hole. The LED fits into a cup that is only visible from the inside.</li>
</ul>
</ul>
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-EdFtnQQ0U0g/WnDFICL6z3I/AAAAAAAAAAs/7HP58uWj-JcBsKSj-QhHP8QK0odpp89DwCLcBGAs/s1600/sonoff_hack_0008.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="900" data-original-width="1600" height="360" src="https://1.bp.blogspot.com/-EdFtnQQ0U0g/WnDFICL6z3I/AAAAAAAAAAs/7HP58uWj-JcBsKSj-QhHP8QK0odpp89DwCLcBGAs/s640/sonoff_hack_0008.JPG" width="640" /></a></div>
<br />
<br />
<ul>
<li>Cut the hookup wire to a length that works for you and attach the JST style 2.5mm pins to the hookup wires using a 2.5mm crimper.</li>
<ul>
<li>I picked a length that would allow me to hot glue the connector to the enclosure.</li>
<li>Using cheap crimpers and connector kits can sometimes be frustrating. Spend sometime getting to know your crimper and pins.</li>
<li>If you don't have much experience with crimping pins, practice on some loose wire.</li>
<li>Stranded wire is preferred when using JST type pins, but I have never had an issue using solid hookup wire with JST type 2.5mm pins.</li>
</ul>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://3.bp.blogspot.com/-IgXlHHjy0LA/WnDFKvffdjI/AAAAAAAAABA/bRQqOY9gR2En5_E5yGP7NnJa9k1LaheKwCLcBGAs/s1600/sonoff_hack_0013.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="900" data-original-width="1600" height="360" src="https://3.bp.blogspot.com/-IgXlHHjy0LA/WnDFKvffdjI/AAAAAAAAABA/bRQqOY9gR2En5_E5yGP7NnJa9k1LaheKwCLcBGAs/s640/sonoff_hack_0013.JPG" width="640" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<ul>
<li style="text-align: left;">Decide your pin order and insert the pins into the JST 2.5mm female connector.</li>
<li style="text-align: left;">Hot glue the JST type female connector to the enclosure</li>
</ul>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://3.bp.blogspot.com/-fiqfAuLdpN4/WnDFIpJjTyI/AAAAAAAAAAw/qo4_32QUiEs7iHbdf9vWxOEgN4HASGpigCLcBGAs/s1600/sonoff_hack_0009.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="900" data-original-width="1600" height="360" src="https://3.bp.blogspot.com/-fiqfAuLdpN4/WnDFIpJjTyI/AAAAAAAAAAw/qo4_32QUiEs7iHbdf9vWxOEgN4HASGpigCLcBGAs/s640/sonoff_hack_0009.JPG" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
</div>
<ul>
<li>Cut the extension cord at a spot that is convenient for your plans.</li>
<ul>
<li>I cut mine 12" from the 2 prong plug</li>
</ul>
<li>Mark the LINE wire with a marker.</li>
<ul>
<li>The LINE wire is connected to the smaller of the two prongs</li>
<li>This will help you when connecting to the Sonoff terminal block</li>
</ul>
<li>Strip about 1/8" on each wire</li>
<ul>
<li>You may want to tin the ends of these wires to make it easier to get the wires into the terminal blocks. DO NOT TWIST the wire... it doesn't work well with the terminal blocks on the Sonoff.</li>
</ul>
<li>Loosen the screws on the terminal blocks and insert the wires making sure that the LINE wire is inserted into the L labeled terminal.</li>
<ul>
<li>The 2 prong plug connects to the input of the Sonoff.</li>
</ul>
</ul>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-X2sMoRhHZ1A/WnDFJJjtxFI/AAAAAAAAAA0/06tNRlhmpD4Xk_DpCEE1gSX0-d-fbhHMwCLcBGAs/s1600/sonoff_hack_0010.JPG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"></a><a href="https://2.bp.blogspot.com/-nLpuVr8IcIc/WnDFJsR3kaI/AAAAAAAAAA4/rNajp7FZnKo_7UvSryj_3Q2V4o73_y4eQCLcBGAs/s1600/sonoff_hack_0011.JPG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"></a><a href="https://1.bp.blogspot.com/-X2sMoRhHZ1A/WnDFJJjtxFI/AAAAAAAAAA0/06tNRlhmpD4Xk_DpCEE1gSX0-d-fbhHMwCLcBGAs/s1600/sonoff_hack_0010.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1600" data-original-width="900" height="200" src="https://1.bp.blogspot.com/-X2sMoRhHZ1A/WnDFJJjtxFI/AAAAAAAAAA0/06tNRlhmpD4Xk_DpCEE1gSX0-d-fbhHMwCLcBGAs/s200/sonoff_hack_0010.JPG" width="111" /><img border="0" data-original-height="900" data-original-width="1600" height="223" src="https://2.bp.blogspot.com/-nLpuVr8IcIc/WnDFJsR3kaI/AAAAAAAAAA4/rNajp7FZnKo_7UvSryj_3Q2V4o73_y4eQCLcBGAs/s400/sonoff_hack_0011.JPG" width="400" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<ul>
<li style="text-align: left;">Screw the end plates/caps on each end of the enclosure.</li>
<ul>
<li style="text-align: left;">Don't go over board or you may strip out the plastic</li>
</ul>
</ul>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-y1YHAODnVJQ/WnDFKMMCfUI/AAAAAAAAAA8/up5GBMD5JD4W-S1sOhtqoRbQXpU-2plngCLcBGAs/s1600/sonoff_hack_0012.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="900" data-original-width="1600" height="360" src="https://1.bp.blogspot.com/-y1YHAODnVJQ/WnDFKMMCfUI/AAAAAAAAAA8/up5GBMD5JD4W-S1sOhtqoRbQXpU-2plngCLcBGAs/s640/sonoff_hack_0012.JPG" width="640" /></a></div>
<br />
<br />
<h3>
Result</h3>
<div class="separator" style="clear: both; text-align: center;">
</div>
The result is a Sonoff that is ready to be programmed using a USB to Serial UART adapter and the Arduino IDE. I can hook up 3 appliances to a single Sonoff Wifi Switch.<br />
<h3>
...UPDATE</h3>
<div>
I found that wiring up a few of the Sonoff Wifi Switches with short cables was useful. I used the same 2 prong extensions with 3 sockets. I now have a mix of 6' and 1' switches.</div>
<div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-QeYwbey2Lk4/WnIWiXfNkoI/AAAAAAAAAB8/q2m5YDidhMgM9RbooIQREEb-nqVzHHhPwCK4BGAYYCw/s1600/Sonoff_hack_1foot.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="288" src="https://3.bp.blogspot.com/-QeYwbey2Lk4/WnIWiXfNkoI/AAAAAAAAAB8/q2m5YDidhMgM9RbooIQREEb-nqVzHHhPwCK4BGAYYCw/s640/Sonoff_hack_1foot.jpg" width="640" /></a></div>
</div>
<h3>
Next Time</h3>
<div>
We will setup a cheap USB to Serial UART adapter to plug in to the Sonoff, program the Sonoff, and control an appliance.<br />
<br />
<a href="http://blog.kilomon.com/2018/02/hacking-sonoff-wifi-switch-part-2.html">Go to Part 2</a><br />
<a href="http://blog.kilomon.com/2018/02/hacking-sonoff-wifi-switch-part-3-alexa.html">Go to Part 3</a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<br /></div>
Danhttp://www.blogger.com/profile/01422027852211426218noreply@blogger.com9tag:blogger.com,1999:blog-36706321802012849.post-10637499055958205642017-10-13T16:32:00.000-07:002017-10-15T09:57:49.457-07:00Connecting Python to the GDAX Websocket Feed<h2>
Reading the GDAX Feed using Python</h2>
<div>
<a href="https://www.gdax.com/">GDAX</a> provides a <a href="https://docs.gdax.com/?python#websocket-feed">public websocket service </a>which allows anyone to read real-time GDAX data. This is a great service when you consider that it is free to anyone that has the skills to utilize it. This feed could be used for automated trading purposes or for performing real-time calculations that are not included in the GDAX web UI.</div>
<div>
<br /></div>
<div>
In this case, there is not an official GDAX Python module. There are some notable modules on GitHub which you could utilize. We will put together some code using the well established websocket module.</div>
<div>
<br /></div>
<div>
<i><b>A WORD OF CAUTION</b></i>: <i>Coinbase handles financial assets. Always use the sandbox when testing code and ideas. Use appropriate security measures when using API credentials. </i></div>
<div>
<h3>
Goals</h3>
<div>
<ul><span style="font-weight: normal;">
<li>Create a subscription request in JSON format</li>
<li>Send the subscription request to wss://ws-feed.gdax.com</li>
<li>Display the results</li>
<li>Display the execution duration in seconds each time </li>
</span></ul>
<h3>
Prep</h3>
<div>
<ol><span style="font-weight: normal;">
<li>Install the python websocket and json modules</li>
<li>Choose the GDAX Channels to join</li>
</span></ol>
</div>
<h3>
Python Code</h3>
<div>
I will be subscribing to the Litecoin ticker using the code below. Feel free to use the currency of your choice.</div>
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?skin=desert"></script>
<br />
<pre class="prettyprint">from websocket import create_connection
import json, time
# Tracking execution time
start = time.time()
# Create connection
ws = create_connection("wss://ws-feed.gdax.com")
# Create subscription message
message = {
"type": "subscribe",
"channels": [{"name": "ticker", "product_ids": ["LTC-USD"]}]
}
# Send subscribe Message
ws.send(json.dumps(message))
result = ws.recv()
print result
ws.close()
# execution time
print "\nExecution Time: " + str(time.time() - start)</pre>
</div>
</div>
<div>
<h3>
Notes</h3>
<h3>
<div style="font-size: medium; font-weight: normal;">
<ul><span style="font-weight: normal;">
<li>The subscribe message needs to be sent once</li>
<li>Omit the ws.close() statement to keep the websocket connection open</li>
<li>Run the ws.recv() command to read the feed</li>
</span></ul>
</div>
</h3>
<h3>
Result</h3>
</div>
<div>
<pre class="prettyprint">{"type":"ticker","sequence":585932452,"product_id":"LTC-USD","price":"58.72000000","open_24h":"57.90000000","volume_24h":"920408.37260391","low_24h":"55.25000000","high_24h":"60.96000000","volume_30d":"17232432.91842303","best_bid":"58.71","best_ask":"58.72"}
Execution Time: 0.608999967575</pre>
<h3>
And Then?</h3>
<div>
In a future post, we will look at how to store this feed data, perform useful calculations, and then visualize the data.
</div>
</div>
Danhttp://www.blogger.com/profile/01422027852211426218noreply@blogger.com1tag:blogger.com,1999:blog-36706321802012849.post-88723842392826135022017-09-08T16:10:00.001-07:002018-02-10T15:03:40.488-08:00Coinbase Interaction with Python<h2>
Get Coinbase balances using code? Lets do it. </h2>
<div>
Let's build on the experience from my previous <a href="http://blog.kilomon.com/2017/09/gdax-interaction-with-python.html">post</a> on connecting to GDAX with Python. If I can connect to both my Coinbase Wallets and my GDAX accounts... I will be well on my way to understanding my cryptocurrency portfolio in ways that are not provided in the web UI.<br />
<br />
The good news is that there is a official python Coinbase module.</div>
<div>
<br /></div>
<div>
<i><b>A WORD OF CAUTION</b></i>: <i>Coinbase handles financial assets. Always use the sandbox when testing code and ideas. Its never a good idea to put secrets in your code. Use appropriate security measures when using API credentials. I recommend using a tool such as bcrypt to protect your secrets.</i></div>
<h3>
Goals</h3>
<div>
<ul><span style="font-weight: normal;">
<li>Securely authenticate to Coinbase REST service using official Coinbase module</li>
<li>Get a list of accounts/wallets for the authenticated user</li>
<li>Get a list of all transactions for all accounts</li>
<li>Display the results</li>
<li>Display the execution duration in seconds</li>
</span></ul>
</div>
<h3>
Prep</h3>
<div>
<ol><span style="font-weight: normal;">
<li>Login to Coinbase and generate an API key. I specifically set my API key to have all available "read" permissions.</li>
<li>I recommend using the "Allowed IP Addresses" option during API key creation.</li>
<li>Save the key and secret in a secure location, such as your favorite password manager.</li>
<li>Install the <a href="https://developers.coinbase.com/docs/wallet/guides/bitcoin-wallet">Coinbase API for python </a></li>
</span></ol>
</div>
<h3>
Python Code</h3>
<div>
<span style="font-weight: normal;"> I am using the example code from the Coinbase <a href="https://developers.coinbase.com/api/v2">documentation</a> as a starting point.</span></div>
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?skin=desert"></script>
<br />
<pre class="prettyprint">import time
from coinbase.wallet.client import Client
# Tracking execution time
start = time.time()
# Authenticate with Coinbase
client = Client(
'YOUR KEY',
'YOUR SECRET',
api_version='2017-09-01')
# Gather account data
accounts = client.get_accounts()
# Display balance and transactions for each account
for account in accounts.data:
balance = account.balance
print "%s: %s %s" % (account.name, balance.amount, balance.currency)
print account.get_transactions()
print "\nExecution Time: " + str(time.time() - start)</pre>
<h3>
Notes<span style="font-weight: normal;"> </span></h3>
<ul>
<li>You can verify the API version from the API key creation page.</li>
<li>Remember to secure your secret and passphrase after (or even during) testing using bcrypt/scrypt/pbkdf2</li>
<li>JSON is formatted by the <span style="font-family: "courier new" , "courier" , monospace;">coinbase </span>module</li>
<li>Execution time is presented in seconds</li>
</ul>
<h3>
Result</h3>
<div>
<span style="font-weight: normal;">Here is a sample of the output I received. I have masked some data, so just live with it.</span></div>
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?skin=desert"></script>
<br />
<pre class="prettyprint">LTC Wallet: 0.00372555 LTC
{
"data": [
{
"amount": {
"amount": "-1.00000000",
"currency": "LTC"
},
"created_at": "XXXX-XX-XXTXX:XX:XXX",
"description": null,
"details": {
"subtitle": "to GDAX",
"title": "Transferred litecoin"
},
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"instant_exchange": false,
"native_amount": {
"amount": "-81.65",
"currency": "USD"
},
"resource": "transaction",
"resource_path": "/v2/accounts/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/transactions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"status": "completed",
"type": "exchange_deposit",
"updated_at": "XXXX-XX-XXTXX:XX:XXX"
},
...
Execution Time: 1.54399991035</pre>
<h3 style="white-space: normal;">
<span style="font-family: inherit;">
And Then?</span></h3>
<div style="white-space: normal;">
<span style="font-family: inherit;">Next time, let's leverage both the GDAX REST API and the Coinbase API to see the value of my investments. We will play with live market data and wallet balances to calculate the profit/loss of my cryptocurrency purchases.</span></div>
Danhttp://www.blogger.com/profile/01422027852211426218noreply@blogger.com0tag:blogger.com,1999:blog-36706321802012849.post-66398236334052268542017-09-08T08:35:00.000-07:002017-09-08T16:16:47.721-07:00GDAX Interaction with Python<h2>
Get GDAX balances using code? Lets do it. </h2>
<span style="font-weight: normal;">I was checking out the Coinbase <a href="https://www.gdax.com/">GDAX</a> REST API the other day and I immediately had some ideas of how I could use it. I am not a software developer by trade, but even for a scripter like myself, a quick review of the GDAX <a href="https://docs.gdax.com/#api">documentation</a> proved to be understandable. It was time well spent and I recommend you have a gander prior to executing the code in this post. </span><br />
<br />
We are going to use Python in this example. Why Python? Because I make the decisions here.<br />
<br />
<div>
<span style="font-weight: normal;">
<i><b>
A WORD OF CAUTION</b></i>: <i>GDAX handles financial assets. Always use the sandbox when testing code and ideas. Use appropriate security measures when using API credentials. </i></span><br />
<h3>
Goals</h3>
<div>
<ul><span style="font-weight: normal;">
<li>Securely authenticate to the GDAX REST API</li>
<li>Get a list of accounts for the authenticated user</li>
<li>Display the accounts details in prettified format</li>
<li>Display the execution duration in seconds</li>
</span></ul>
</div>
<h3>
Prep</h3>
<div>
<ol><span style="font-weight: normal;">
<li>Login to GDAX and generate an API key. I specifically set my API key with "view" permissions.</li>
<li>Save the Passphrase, key, and secret in a secure location, such as your favorite password manager.</li>
</span></ol>
</div>
<h3>
Python Code</h3>
</div>
<span style="font-weight: normal;">
The example below is copied from the GDAX documentation. I then sprinkled a few extra seasonings. You will need to insert your passphrase, key, and secret in the "Credentials" section.<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?skin=desert"></script><br />
</span><br />
<pre class="prettyprint"><span style="font-weight: normal;">import json, hmac, hashlib, time, requests, base64
from requests.auth import AuthBase
# Tracking execution time
start = time.time()
# Create custom authentication for Exchange
class CoinbaseExchangeAuth(AuthBase):
def __init__(self, api_key, secret_key, passphrase):
self.api_key = api_key
self.secret_key = secret_key
self.passphrase = passphrase
def __call__(self, request):
timestamp = str(time.time())
message = timestamp + request.method + request.path_url + (request.body or '')
hmac_key = base64.b64decode(self.secret_key)
signature = hmac.new(hmac_key, message, hashlib.sha256)
signature_b64 = signature.digest().encode('base64').rstrip('\n')
request.headers.update({
'CB-ACCESS-SIGN': signature_b64,
'CB-ACCESS-TIMESTAMP': timestamp,
'CB-ACCESS-KEY': self.api_key,
'CB-ACCESS-PASSPHRASE': self.passphrase,
'Content-Type': 'application/json'
})
return request
# Credentials - ADD YOUR API KEY CREDS IN THIS SECTION
API_KEY = "YOUR API KEY"
SECRET_KEY = "YOUR SECRET KEY"
API_PASSPHRASE = "YOUR API PASSPHRASE"
# Get accounts
api_url = 'https://api.gdax.com/'
auth = CoinbaseExchangeAuth(API_KEY,SECRET_KEY,API_PASSPHRASE)
r = requests.get(api_url + 'accounts', auth=auth)
# Output account data and code execution time
print json.dumps(r.json(),indent=4)
print "\nExecution Time: " + str(time.time() - start)
</span></pre>
<span style="font-weight: normal;">
</span>
<br />
<h3>
Notes</h3>
<div>
<ul><span style="font-weight: normal;">
<li>My initial testing was done using the Public <a href="https://public.sandbox.gdax.com/">Sandbox</a>. The code above will connect to the your live account.</li>
<li>Remember to secure your secret and passphrase after (or even during) testing using bcrypt/scrypt/pbkdf2</li>
<li>JSON is formatted with indentation for ease of reading</li>
<li>Execution time is presented in seconds</li>
</span></ul>
</div>
<h3>
Results</h3>
<div>
<span style="font-weight: normal;">Success! There is nothing special here folks, but it is a starting point. Some account info has been masked to "protect the innocent".</span></div>
<span style="font-weight: normal;">
</span>
<pre class="prettyprint"><span style="font-weight: normal;">[
{
"available": "0.0000000000000000",
"balance": "0.0000000000000000",
"profile_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"currency": "USD",
"hold": "0.0000000000000000",
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
},
{
"available": "12.9900000000000000",
"balance": "12.9900000000000000",
"profile_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"currency": "LTC",
"hold": "0.0000000000000000",
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
},
{
"available": "7.1605267800000000",
"balance": "7.1605267800000000",
"profile_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"currency": "ETH",
"hold": "0.0000000000000000",
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
},
{
"available": "0.0000000000000000",
"balance": "0.0000000000000000",
"profile_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"currency": "BTC",
"hold": "0.0000000000000000",
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}
]
Execution Time: 0.315999984741</span></pre>
<span style="font-weight: normal;">
<pre class="prettyprint"></pre>
<h3>
And Then?
</h3>
<div>
Next time, we'll play with the Coinbase API to check wallets and transaction history.</div>
</span>Danhttp://www.blogger.com/profile/01422027852211426218noreply@blogger.com0