W10 Core IoT Workshop

IoT and Windows are Better than ever with the new IoT Core for Raspberry Pi.

In this workshop we’ll have deploy Universal Windows Platform Code to a Raspberry Pi and begin communicating with the cloud and cloud services in the form of an Azure IoT Hub.

The steps include:
1. Gathering the materials
2. Preparing the Raspberry Pi
3. Installing our software
4. Connecting our LED and PushButton
5. Connecting to our raspberry pi
6. Deploying our push button app
7. Connecting our app to IoT Hub
8. Connecting our app to weather data

1. Gathering the materials

For this workshop you’ll need about $55 worth of hardware, but all the software is free.

Hardware:
1 Raspberry Pi 3 (It has built in Wifi!)
1 Micro USB to USB Cable
1 Breadboard
4 Female/Male Jumper Wires
1 Push Button Switch
1 led
1 200 ohm resistor for said led
1 Monitor with HDMI out

Software:
Windows 10 Machine version 10.0.10240 or better.
Visual Studio 2015 Update 2
The Windows 10 IoT Core Dashboard
Git

Here's my little setup
Here’s my little setup

2. Preparing Our Pi

The windows developer site has very clear instructions for setting up your device with the proper operating system so lets hop over there.

developer.microsoft.com

If you follow these instructions all the way to Step 4 of 4 you’re ready for step 5 on our workshop. So skip ahead if you followed along there.

I’m working with a raspberry pi three so my selection screen looks like this:

selection

3. Install the dashboard and Flash the OS
Next we’ll download the dashboard as prompted by the site

Then we’ll download the ISO of the raspberry pi image we want to use, then click through installer.

Once installed we can use the IoT Dashboard to flash the image onto our SD card in the form of a .ffu

Then we’ll connect the device to the network by selecting configure device.

Really though the instructions are super clear RIGHT HERE

4. Install/Update Visual Studio

We need Visual studio Update 2 to build our IoT Application, so make sure you’re up to date!

Or go here to install it: https://www.visualstudio.com/vs-2015-product-editions

Seriously though, they did an awesome job with the documentation.
If you followed along to their step 4 you’re ready for our step 5.

5. Connecting our LED and PushButton

Now that we have our pi configured and Visual Studio up to date, let’s plug in our neat hardware!

Here’s an overview of the pin layout for the raspberry pi 3:
gpiopins

And the wiring diagram for the led + push button looks like this:

wiringdiagram

Sweet, lets light it up!

6. Connecting to our raspberry pi

We need our raspberry pi’s IP address before we try to deploy our code.
Power it up with a micro USB cord and connect it to a monitor with HDMI and see the landing page for your machine.

With the Windows IOT Core Come a super helpful web portal that allows you to configure your machine through a browser.

Navigate to that IP:
http://you.have.an.ip:8080/
https://192.168.1.145:8080/ is the IP address of my machine when I tried this

You’ll be prompted with a login panel.
The default user name is:
Administrator
The default password is:
p@ssw0rd

Here’s what you should see in the portal:
coreportal

From here you can configure the name/password, get network info like the MAC address under Networking, and even test out some samples.

Sweet! This is one of my favorite Window IoT Features.

7. Deploying our push button app

The pi is setup, our computer is updated with the newest build tools, now its time to deploy some code!

Go here and clone this repo to a dev directory:
https://github.com/timmyreilly/RaspberryPiWorkshop

And setup visual studio debugging by right clicking on PushButton project like this:
properties

Then under debug set the remote machine ip to the ip you collect from the IoT Dashboard or from the raspberry pi itself by plugging in a monitor.
findip
You will then need to rebuild your solution, and restore nuget packages.

Poke around for a minute, put a break point in the buttonPin_ValueChanged method and step around to see what’s going on with the push button.

8. Connecting our app to IoT Hub

Next we’re going to turn on the IoT Hub Connection.
Go into the azure portal and create a new IoT Hub like this:
iothubone
Then create a new device called MyDevice in the IoT Hub.

More information about the IoT Hub can be found RIGHT HERE.

Then we’ll want to add our connecting strings to the app at the very bottom of MainPage.xaml.cs


static string iotHubUri = "YOURHUB.azure-devices.net";
static string deviceKey = "TOKENasQOPUesD1BmSOMETHINGCOMPLICATED";
static string deviceId = "MyDevice"; // your device name

Next we’ll uncomment this line of code on line 78:

SendDeviceToCloudMessagesAsync();

To see what’s happening in the event hub there is a small console application that we’ll run alongside to see what’s making into the cloud.

You can find that code here:
https://github.com/timmyreilly/IoTHubConsoleReader
Open that in visual studio and replace the connection string with the one provided in the Azure Portal.


string connectionString = "HostName=YOURHUBNAME.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=YOURSECRETOKENqf"

Sweet, now run both those apps at the same time, push the button, and see the glory that is Internet of things.

9. Connecting our app to weather data

Now that we’ve got it talking to the cloud, lets listen to what the clouds have to say!

We’re going to use forecast.io to provide weather data to our app, then use Speech. Synthesis to read it out over a the audio jack.

Navigate to forecast.io and signup register an account, then copy the complicated token highlighted here:

forecast

And replace what you see at line 168:

private const string FORECAST_URL = "https://api.forecast.io/forecast/YOURSECRETOKEN/";

Then if you want to be more specific about where you’re getting weather data replace the string on line 76.

var words = await GetWeatherString("37.8267,-122.423")

Make sure that the code in lines 72 through 81 are uncommented.

Deploy the app, press the button, and listen to the weather like never before!

It’s all very simple code and ready to be spun into lots of fun projects.
Here’s a list of all the ones that me and my friends could thing of:
Tap into the band app cloud
Morse code
Dance party
Send a random act of kindness
Tap into yammer
Time to finish breast feeding start and stop button
Random stats button
Gives you weather, or distance walked
Morse code each other
Send bro to someone random – twilio
Launch a middle
Listener recognition and ignore
Competitive button clicking
Obscure metadata
Best reflexes tester

Hope you had fun getting started with Windows IoT!

This workshop wouldn’t be possible without the help provided by the community. Here are some of the helpful posts that help me learn:
Windows 10 IoT Core Speech Recognition
Windows 10 IoT Core Speech Synthesis
All The ms-iot samples

Feel free to ask me questions in the comments or on twitter @timmyreilly

TOMATOES IN PROGRESS
TOMATOES IN PROGRESS

Flask-SocketIO, Background Threads , Jquery, Python Demo

This week I’ve been making progress on the Huggable Cloud Pillow website.

In the process I’ve learned about some sweet stuff you can do with Javascript, Python, and Flask-SocketIO.

The first thing to take note of is Flask.

Flask is the tiny server that allows us to host websites using Python to deliver content to the client. While on the server side you can manage complicated back ends or other processes using Python in conjunction with Flask.

This type of development is nice, because you can start seeing results right away but can take on big projects easily.

It might not be the most robust Framework, but its great for small projects…

If you want to get into Flask Web Development checkout this extensive MVA.

Small and simple, Flask is static on its own. This allows us to present static content, like templates and images easily and deals with input from the user using RESTful calls to receive input. This is great for static things with lots of user actions, but if we want something a bit more dynamic we’re going to need another tool.

In this case I’ve found Flask-SocketIO, similar to Flask-Sockets but with a few key differences highlighted by the creator (Miguel Grinberg) here.

Sockets are great for is providing live information with low latency. Basically, you can get info on the webpage without reloading or waiting for long-polling.

There are lots of ways you can extend this functionality to sharing rooms and providing communication with users and all sorts of fun stuff that is highlighted on GitHub with a great chunk of sample code. The following demo is based off of these samples.

For my project, I need the webpage to regularly check for differences in the state of the cloud and present them to the client, while also changing the image the user sees.

At first I tried to implement it using sockets passing information back and forth, but that wasn’t very stable.

The solution I’ve found, uses a background thread that is constantly running while the Flask-SocketIO Application is running, it provides a loop that I use to constantly check state of our queue.

Let’s break it down…
a. I need my website to display the current state of the cloud.
b. The Flask application can get the state by query our azure queue.
c. Once we determine a change of state we can display that information to the webpage.
d. To display the new state to the webpage we need to use a socket.
e. And pass the msg to be displayed.

This demo intends to break down problem a, c, d, and e.

I’ve created this little guide to help another developer get going quickly, with a nice piece of code available on GitHub.

The five steps to this little demo project are as follows:
1. Install Flask-SocketIO into our Virtual Environment
2. Create our background thread
3. Have it emit the current state to our client
4. Call the background thread when our page render_template’s
5. Have the Javascript Catch the emit and format our HTML.
Celebrate! Its Friday!

1.

Flask-SocketIO is a python package that is available for download using

pip install Flask-SocketIO

Make sure you instal it into a Virtual Environment. Check out my earlier tutorial if you need help with this step.

*Edit Here’s the top part of the “main.py” for reference:

#main.py
from gevent import monkey
monkey.patch_all()

import time
from threading import Thread
from flask import Flask, render_template, session, request
from flask.ext.socketio import SocketIO, emit, join_room, disconnect

app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
thread = None

2.

Create our background thread.
You’ll see in the sample code from Flask-SocketIO’s github a simple way to send data to the client regardless of their requests.

For this example we’ll be changing the current time every second and display that to our client.

Background Thread:

def background_stuff():
     """ python code in main.py """
     print 'In background_stuff'
     while True:
         time.sleep(1)
         t = str(time.clock())
         socketio.emit('message', {'data': 'This is data', 'time': t}, namespace='/test')

3

This is the emit statement from above, but is the meat of our interface with SocketIO. Notice how it breaks down…

socketio.emit('message', {'data': 'This is data', 'time': t}, namespace='/test')
socektio.emit('tag', 'data', namespace)

This emit will be sending to the client (Javascript) a message called ‘message’.

When the Javascript catches this message it will be able to pull from the python dicionary msg.data and msg.time to get the result of this package.

4

So how do we call background_stuff?

We can call it wherever we want, but for this simple example we’ll put it right in our ‘/’ base route. So when we navigate to 127.0.0.1:5000 (Local Host) we’ll see the result of our background thread call.

Here’s our route:

@app.route('/')
def index():
    global thread
    if thread is None:
        thread = Thread(target=background_stuff)
        thread.start()
    return render_template('index.html')

Pretty simple… Notice global thread and target=background_stuff

Creating different background threads is a good way to iterate through your changes.

5

Next step is catching this on the other side…

So for our Javascript…

we’ll be using the socket.on method.

socket.on('message', function(msg){
    $('#test').html('<p>' + msg.time + '</p>');
});

When we receive the emit labeled ‘message’ we’ll pick up the msg from the second parameter and have it be available to our JQuery work.

Here’s the small piece of HTML that we’re selecting to edit.

<body>
    <p id='test'>Hello</p>
</body>

I’ve posted all of this code at github.

Feel free to download it and start working with dynamic sites using SocketIO. Please let me know if you have any questions!

Code for SF's Hackathon gave out awesome tattoos!
Code for SF’s Hackathon gave out awesome tattoos!

Quick Edits Using VS Code

I’ve been working in Visual Studio pretty heavily in the last two weeks, but every once in a while I need to make quick edits to my .gitignore file, which isn’t in my project directory.

I usually open up a small text editor right from PowerShell and now that VS Code is out I thought ‘why not use that?’

Here’s how you can easily open files using code from PowerShell in three steps:

1.Find the path to VS Code
2. Edit your PowerShell profile
3. Open Files!

1. Find the VS Code Path

First thing we need to do is find where VS Code is in our directory.

If you have Code pinned to your start menu or on your desktop simply right click the icon and ‘select open file location’.

File explorer should now open to the location of the .exe.
Right click the Code.exe file and select ‘properties’.

If you selected a Shortcut Icon you should see a screen like this:

vscodeshortcutpath

If you navigated to the actual location in directory of VS Code it should look like this:

vscodelocationpath

Now right click and copy the path.

In my case: C:\Users\tireilly\AppData\Local\Code\app-0.1.0

2. Edit our PowerShell profile

To edit our profile we need to find the Microsoft.PowerShell_profile.ps1 file.

My file is located here:

profilelocationpowershell

I open the file in notepad to make my edits:

notepadpowershellprofile

Now that we have our profile open we’ll create an alias for labeled code followed by the path to our .exe
eg: Set-Alias code ‘C:\Users\user\AppData\Local\Code\app-0.1.0\Code.exe

noticed how I added the Code.exe to the path so the program will launch!

Here’s a photo of my current PowerShell profile for reference:

powershellprofile

Now we can save and close this file and open a new PowerShell window!

3. Edit some files!

Let’s edit our PowerShell profile with Code this time!

symmetryisgood

Something oddly satisfying about getting exactly what you want with words.

codeeditorpowershellprofile

And there we go. The brand new Code editor at your fingertips whenever you need it!

Let me know if you have any comment or questions!

Amazing Dude
Professor Chang Yun is an excellent man with an amazing imagine cup record. His mentorship has led teams to US finals for 8 years straight. With 6 teams making it into the World Finals.

GitHub’s Gitignore and Keeping DB Keys Safe

I’m working with a raspberry pi and I’m learning how to collect and manage sensor data.

There is a lot of data and that’s awesome, but dealing with remote persistent storage has helped me understand some good ways of keeping stuff organized and safe.

For example: ‘Keys’ or ‘Tokens’ (Not to be confused with the Late English writer Tolkien)

These are the keys to the door of your data.
To access the contents behind these doors, you must establish that you are the key-holder. One of the ways to do this in software is to create a long complicated string that can passed to the database so you can input or output data.

As long as you keep this token secret nobody will be able to mess with your data, or use it without having to pay for it.

Now this sounds pretty simple, but what if you use that token in code that is stored in a public repository on GitHub? This is essentially like printing a bunch of keys to your house and leaving them all over town. Not safe or smart.

So…

1. We need to keep these keys separate from the rest of your code.
2. We need to keep the file that contains those keys away from your public repository.

To do this I created a separate file called tokens.py that contains the strings of my tokens and a function called getStorageKey() that returns those strings.
Cool, we’ve satisfied our first goal.

Now we need to keep this file away from our repository. To do this we create a .gitignore file. This is a special ‘git’ file that allows us to specify which files will not be added to the remote repository.
To create a .gitignore file simply enter:

touch .gitignore

touch is a Unix command to create a file and update the access data, but not make any edits. Its the same as opening and closing without saving any changes.

After you’ve created this file you can edit it with any editor you like. I do it with sublime or VS Code because it helps me keep track of the separation occurring between visual studio and GitHub.

All you need to do is add on a separate lines the files you don’t want GitHub or just git to include.

When I first started all my .gitignore file had was:

tokens.py

Its expanded to include…

tokens.py
*.pyc

# the asterisk* acts as a wild card and will match any files with .pyc at the end
# anything that starts with a # is a comment and will be ignored from .gitignore

I saved this file (.gitignore) then added and committed it to the repository.

Now any files I add that end in .pyc or match tokens.py will not be added to my repository. And you will not be prompted to add them when you check git status.

What about files we’ve already have added???

If we add the rule after we added the file we want to ignore… We need to remove it from tracking on GitHub using the rm –cache command.

This will not remove it from your computer, but it will stop if from being tracked by GitHub, and will essentially be treated as if it was removed from your repository.

To pull this off simply type this command

git rm --cached filename.py

In this case I’m removing a file named ‘filename.py’.
After checking our git status we’ll see that this file is going to be removed.

Commit the changes and push to your remote repo.

You’ll see the files are still in your local directory, but are no longer in the remote or local repository. Hooray for keeping things safe!

Please let me know if you have any questions or comments.
The documentation is excellent and I recommend you spend some time reading through the resources below to round out your learning:

touch (Unix)
GitHub .gitignore
If you enter: ‘git ignore –help’ in your gitshell you can find more helpful documentation about using .gitignore
Setting up Code for Powershell
Setting up sublime for Powershell

SomeOfTheNorCalTeam
Evangelists in their natural habitat. Behind a booth and with a computer.

Python and Visual Studio in 5 minutes

Python is an excellent teaching programming language. It has all the tools to inspire students out of the box with plenty to grow on.

Development requires a basic understanding of computer science  but will teach essentials for large scale software development, object oriented design, polymorphism, and development environments.

I like python. The Zen is magnificent. It inspires me every time I practice and learn.

Microsoft arrives in the form of PTVS (Python Tools for Visual Studio) a powerful extension for Visual Studio that can be installed in all Versions of VS.

PTVS turns Visual Studio into a Python Dev Environment. Complete with Debugging, in window REPL (with autocomplete assistance), IntelliSense, configurable environments and virtual environments.

Its an extremely powerful tool.
While getting into PTVS I would recommend watching these two videos:


The second one especially will help you get a grip on how to configure development environments in Python, one of the most crucial parts of taking development to the next level.

Also, configuration of PIP, Setuptools, and virtualenv is all handled for you from there. Its freakin sweet. You can do all of this for free with Visual Studio Express.

Other helpful resources:
Python the Hard Way
Scott Hanselman’s Blog about PTVS
Pluralsight Subscribers
Python Tools for Visual Studio
Somasegar’s Post!

Let me know if you have any other questions!

9 Frisbees on Thumbtacks
We’ve started a Frisbee wall! FUNctional storage.