This commit is contained in:
Adi Azulay 2020-10-26 14:14:35 -07:00
Родитель a5800095f4
Коммит 085d153c53
18 изменённых файлов: 519 добавлений и 8 удалений

136
.gitignore поставляемый Normal file
Просмотреть файл

@ -0,0 +1,136 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that dont work, or not
# install all needed dependencies.
#Pipfile.lock
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
.rpi-venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# Azure Functions artifacts
bin
obj
appsettings.json
local.settings.json
.python_packages
host.json
proxies.json
# VS Code
.vscode

Просмотреть файл

@ -0,0 +1,11 @@
#!/bin/bash
# Setup Virtual Environment
echo "Python virtual environment creation script"
python -m venv ./.venv
echo "Virtual evnironment created"
source ./.venv/Scripts/activate
echo "Virtual enviornment activated"
pip install -r requirements.txt
echo CONNECTION_STRING= >> .env
echo "Dependencies installed"
sleep 5

Просмотреть файл

@ -0,0 +1,34 @@
from azure.iot.device import IoTHubDeviceClient, Message
import os
import json
import random
from dotenv import load_dotenv
from time import sleep
load_dotenv('./.env')
device_id = 'Raspberry Pi'
CONNECTION_STRING = os.getenv("CONNECTION_STRING")
if __name__ == '__main__':
try:
client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
while True:
# Generate a random value to send.
value = random.randrange(0, 100)
# Build a json string
data_to_send = json.dumps({'id': device_id, 'value': value})
message = Message(data_to_send)
client.send_message(message)
print('message sent')
# Wait 30 seconds between data points
sleep(30)
except KeyboardInterrupt:
print("Sample Stopped")

Просмотреть файл

@ -0,0 +1,2 @@
azure.iot.device
dotenv

Просмотреть файл

@ -0,0 +1,5 @@
.git*
.vscode
local.settings.json
test
.venv

Просмотреть файл

@ -0,0 +1,5 @@
# DO NOT include azure-functions-worker in this file
# The Python Worker is managed by Azure Functions platform
# Manually managing azure-functions-worker may cause unexpected issues
azure-functions

Просмотреть файл

@ -0,0 +1,24 @@
from typing import List
import logging
import uuid
import json
import azure.functions as func
def main(events: List[func.EventHubEvent], telemetry: func.Out[str]):
for event in events:
logging.info('Python EventHub trigger processed an event: %s',
event.get_body().decode('utf-8'))
message = json.loads(event.get_body().decode('utf-8'))
rowKey = str(uuid.uuid4())
data = {
"Name": message['id'],
"Value": message['value'],
"PartitionKey": message['id'],
"RowKey": rowKey
}
telemetry.set(json.dumps(data))

Просмотреть файл

@ -0,0 +1,23 @@
{
"scriptFile": "__init__.py",
"bindings": [
{
"type": "eventHubTrigger",
"name": "events",
"direction": "in",
"eventHubName": "recipes-hub",
"connection": "IoTHubConnectionString",
"cardinality": "many",
"consumerGroup": "$Default",
"dataType": "binary"
},
{
"type": "table",
"name": "telemetry",
"tableName": "messages",
"partitionKey": "id",
"connection": "AzureWebJobsStorage",
"direction": "out"
}
]
}

Просмотреть файл

@ -0,0 +1 @@
{"id": "Raspberry Pi", "value": 55}

Просмотреть файл

@ -0,0 +1,51 @@
# https://github.com/Azure/azure-iot-sdk-python/blob/master/azure-iot-device/samples/async-hub-scenarios/receive_message.py
import threading
import asyncio
import time
import os
import json
from six.moves import input
import dotenv
from azure.iot.device.aio import IoTHubDeviceClient
dotenv.load_dotenv('./.env')
device_id = 'Raspberry Pi'
CONNECTION_STRING = os.getenv("CONNECTION_STRING")
def message_receiver(message):
print(message.data.decode())
data = message.data.decode()
if data == "on":
print("is on")
# define behavior for halting the application
def stdin_listener():
while True:
selection = input("Press Q to quit\n")
if selection == "Q" or selection == "q":
print("Quitting...")
break
async def main():
client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
await client.connect()
client.on_message_received = message_receiver
loop = asyncio.get_running_loop()
user_finished = loop.run_in_executor(None, stdin_listener)
await user_finished
await client.disconnect()
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print ("Client Stopped")

Просмотреть файл

@ -0,0 +1,2 @@
azure-iot-device
python-dotenv

Просмотреть файл

@ -0,0 +1,5 @@
.git*
.vscode
local.settings.json
test
.venv

132
02_c2d_messages/messenger/.gitignore поставляемый Normal file
Просмотреть файл

@ -0,0 +1,132 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that dont work, or not
# install all needed dependencies.
#Pipfile.lock
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# Azure Functions artifacts
bin
obj
appsettings.json
local.settings.json
.python_packages
host.json
proxies.json

Просмотреть файл

@ -0,0 +1,39 @@
import logging
import os
import azure.functions as func
from azure.iot.hub import IoTHubRegistryManager
CONNECTION_STRING = os.getenv("IOT_HUB_CONNECTION_STRING")
DEVICE_ID = "rpi-test"
def send_message(data):
registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
props={}
props.update(contentType = "application/json")
registry_manager.send_c2d_message(DEVICE_ID, data, properties=props)
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
status = req.params.get('status')
if not status:
try:
req_body = req.get_json()
except ValueError:
pass
else:
status = req_body.get('status')
if status == "on":
data = ('on')
send_message(data)
return func.HttpResponse("Device turned on", status_code=200)
elif status == "off":
data = ('off')
send_message(data)
return func.HttpResponse("Device turned off", status_code=200)
else:
return func.HttpResponse("Send status on or off to change device status", status_code=200)

Просмотреть файл

@ -0,0 +1,20 @@
{
"scriptFile": "__init__.py",
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "$return"
}
]
}

Просмотреть файл

@ -0,0 +1,3 @@
{
"name": "Azure"
}

Просмотреть файл

@ -0,0 +1,6 @@
# DO NOT include azure-functions-worker in this file
# The Python Worker is managed by Azure Functions platform
# Manually managing azure-functions-worker may cause unexpected issues
azure-functions
azure-iot-hub

Просмотреть файл

@ -1,14 +1,26 @@
# Project
# Raspberry Pi Recipes for Azure
> This repo has been populated by an initial template to help get you started. Please
> make sure to update the content to build a great experience for community-building.
## Overview
As the maintainer of this project, please make a few updates:
Raspberry Pi recipes for Azure is a collection of samples that use use a Raspberry Pi and one or more Azure services. All the recipes included here represent end to end scenarios rather than just documenting how to interface with a single service. These are all written to get you up and running fast. Most take between 5 and 30 minutes to complete and require the least amount of hardware. All is code is designed to be adapted into other project, and many of these recipes can be combined.
- Improving this README.MD file to provide a great experience
- Updating SUPPORT.MD with content about this project's support experience
- Understanding the security reporting process in SECURITY.MD
- Remove this section from the README
If there is something you'd like to know how to do using Azure and a Raspberry Pi and you don't see it here open an issue and let us know. If you know how to do something cool with Azure and a Raspberry Pi open a PR and show us what you got!
> Note: We do our best to minimize the cost of services, but some of these samples will incur a small charge on your Azure account.
## Prerequisites
1. Free Azure Account
1. Basic understanding on Python
1. Raspberry Pi 3 or 4
1. Monitor/keyboard/mouse or ability to SSH into the Pi
## Contents
| Recipe | Description | Time | Prerequisites |
|--------|-------------|------|---------------|
| [01 IoT Hub d2c](./01_iot) | Send telemetry to Azure table storage using IoT Hub and Azure functions. | 15 Mins | None |
| [02 IoT Hub c2d](./02_c2d_messages) | Trigger events on your Raspberry Pi using Azure functions and IoT Hub | 15 mins | None
## Contributing