This article is part of #25DaysOfServerless. New challenges will be published every day from Microsoft Cloud Advocates throughout the month of December. Find out more about how Microsoft Azure enables your Serverless functions.
Have an idea or a solution? Share your thoughts on Twitter!
Time for an Australian Christmas day BBQ on the beach.
Skippy the Kangaroo, and his mates, Kenny the Koala, and Willy the Wombat were very excited and looking forward to Christmas. ‘Only one more sleep’ said Kenny the Koala, ‘I have been very good all year’. Skippy and Willy looked at each other and rolled their eyes, ‘you have not been that good’ they thought. Skippy reminded his mates, ‘it’s not all about presents, my favourite part of Christmas is going to the beach, firing up the BBQ, having a nice cold beer, and relaxing with my friends and family. Let’s hope it a sunny day’.
Write an Internet or Things Serverless solution that helps Skippy, Kenny, and Willy know if it’s a warm day at the beach. You can use the Raspberry Pi Simulator (or a real Raspberry Pi) to send temperature data to Azure IoT Hub to trigger a Python Azure Function. The Azure Function will send a tweet to let our friends know the temperate is greater than 31 degrees (88 Fahrenheit) and it is time to head to the beach for a truly Australian Christmas day.
Create an Azure IoT Hub, Register a device and Test
The Azure IoT Raspberry Pi Simulator is a great way to get started building an Azure IoT Solution.
Follow the documentation to Connect Raspberry Pi online simulator to Azure IoT Hub. When you create an Azure IoT Hub be sure to select the Free Tier.
Event Hub Connection Information
When you have created your Azure IoT Hub then navigate to the Azure IoT Hub Built-in endpoints blade. You will need the Event Hub compatible name and the Event Hub compatible endpoint when you create the Python Azure Function.
Create a Python Azure Function
Install the following Visual Studio Code extensions
Follow the Tutorial: Create a Python function for Azure Functions tutorial.
- Select Python as the language for the function project
- Optional, but recommended, create a virtual environment
- Select Azure Event Hub trigger
- Name your Event Hub Trigger
- Create new local app settings
- Select your subscription
- When prompted to select an event hub namespace select Skip for now
- Paste the Azure IoT Hub Event Hub compatible name as the name of the event hub from which to trigger.glovebox-iothub 9 Select the $Default Event Hub consumer group
Configure the Azure IoT Hub Connection String
When the Visual Studio Code has finished creating the project open the function.json file. The connection property will be an empty string. Modify the value of the connection property to IotHubConnectionString.
Create the IoT Hub Connection String Environment Variable
Open the local.settings.json file and create a new property named IotHubConnectionString and set the value to the Azure IoT Hub Event Hub compatible endpoint.
Start the Azure Storage Local Emulator
Azure Functions need access to Azure Storage Emulator for logging and checkpointing. When developing functions it can be fast to use the Azure Storage Local Emulator.
To Install:
- On Windows install and start the Azure storage emulator
- On macOS and Linux install and start Azurite
Test the Python Azure Function
Now is a great time to test the Python Azure Function is triggered by new messages sent from the Raspberry Pi Simulator.
-
Ensure the Raspberry Pi Simulator is running and sending telemetry. Configure the Azure IoT Hub Device Connection string and click Run.
-
Open the init.py file and set a breakpoint on line 7.
Press F5 to start the Azure Function from Visual Studio Code.
The Function will start and when a collection of messages arrive from Azure IoT hub the breakpoint will be hit.
Process the Incoming Messages
Replace the Python code in the init.py file with the following code.
import logging
import json
import os
import azure.functions as func
def main(event: func.EventHubEvent):
data = event.get_body().decode('utf-8')
telemetry = json.loads(data)
for item in telemetry:
temperature = item.get("temperature")
if temperature is not None and type(temperature) is float and 31 < temperature < 40:
print(temperature)
The Python telemetry object is an array of JSON objects. The code loops through the JSON collection and validates that the temperature object is of type float and greater than 31 and less than 40.
Integrating the Azure Function with Twitter
Follow the Getting started with the Twitter API documentation.
- Create a Twitter Application.
-
Add the Twitter authorisation information to the local.settings.json file rather than the auth.py.
-
Load these environment variables when your Python Function starts and add
python from twython import Twython
to the function.
import logging import json from twython import Twython import os import azure.functions as func consumer_key = os.environ["consumer_key"] consumer_secret = os.environ["consumer_secret"] access_token = os.environ["access_token"] access_token_secret = os.environ["access_token_secret"] def main(event: func.EventHubEvent): data = event.get_body().decode('utf-8') telemetry = json.loads(data) for item in telemetry: temperature = item.get("temperature") if temperature is not None and type(temperature) is float and 31 < temperature < 40: print(temperature)
Install twython Python Twitter Library
1.
bash pip3 install twython
- Add twython to the project requirements file. This will be needed when you package up the solution and deploy to Azure.
Integrate with Twitter
-
Update the Pthyon code in the init.py file as follows:
import logging import json from twython import Twython import os import azure.functions as func consumer_key = os.environ["consumer_key"] consumer_secret = os.environ["consumer_secret"] access_token = os.environ["access_token"] access_token_secret = os.environ["access_token_secret"] twitter = Twython( consumer_key, consumer_secret, access_token, access_token_secret ) def sendTwitterMsg(): message = "Hey Skippy, Kenny, and Willy, time for an Australian Christmas Day on the beach #25DaysOfServerless" try: twitter.update_status(status=message) except: logging.info("problem tweeting from the Python Function") logging.info("Tweeted: %s" % message) def main(event: func.EventHubEvent): data = event.get_body().decode('utf-8') telemetry = json.loads(data) for item in telemetry: temperature = item.get("temperature") if temperature is not None and type(temperature) is float and 31 < temperature < 40: print(temperature)
Save the changes
Set a breakpoint in the
python def sendTwitterMsg():
function.Press F5 to rerun the function.
Ensure the Raspberry Pi Simulator is running and sending telemetry
Check Twitter, you should see your message telling Skippy, Kenny, and Willy they should head to the beach.
Finished 完了 fertig finito ख़त्म होना terminado
Want to submit your solution to this challenge? Build a solution locally and then PR this repo. If your solution doesn't involve code you can record a short video and submit it as a PR to the same repo. Make sure to tell us which challenge the solution is for. We're excited to see what you build! Do you have comments or questions? Add them to the comments area below.
Watch for surprises all during December as we celebrate 25 Days of Serverless. Stay tuned here on dev.to as we feature challenges and solutions! Sign up for a free account on Azure to get ready for the challenges!
Top comments (0)