我使用 Azure Custom Vision 和 Raspberry Pi 创建了一个基于人们存在的室温控制自动化系统项目。 我已成功将 DHT11 温度传感器数据、图像中人数的摄像头传感器数据发送到 Azure IoT 中心。下一步是如何将数据从 Azure IoT Hub 获取到 Azure Functions 并将数据添加到本地数据库。之后,您还可以对正在监控的设备执行开/关操作。
我的期望是,在Azure IoT Hub接收到数据并在遥测消息中提供数据证明后,Azure Functions也可以接收到数据,可以将数据添加到本地数据库,并使用此数据Azure Functions可以对设备执行开/关形式的操作。受到监控。
通过Event Hub trigger,我们可以从Azure IoT Hub获取数据。此函数触发对发送到事件中心事件流的事件的响应。
import logging
from azure.functions import EventHubEvent
from typing import List
def main(events: List[EventHubEvent]):
for event in events:
logging.info('Python EventHub trigger processed an event: %s',
event.get_body().decode('utf-8'))
from typing import List
import json
import logging
import pymysql
from azure.functions import EventHubEvent
# MySQL connection details
MYSQL_HOST = '127.0.0.1'
MYSQL_USER = 'root'
MYSQL_PASSWORD = 'Password'
MYSQL_DB = 'quickstartdb'
def create_table_if_not_exists(cursor):
# Define your table schema here
table_schema = """
CREATE TABLE IF NOT EXISTS event_data2 (
id INT AUTO_INCREMENT PRIMARY KEY,
event_data JSON
)
"""
cursor.execute(table_schema)
def insert_event_data(cursor, event_data):
# Insert JSON event data into the table
insert_query = "INSERT INTO event_data2 (event_data) VALUES (%s)"
cursor.execute(insert_query, (json.dumps(event_data),))
def main(events: List[EventHubEvent]):
# Create a MySQL connection
connection = pymysql.connect(
host=MYSQL_HOST,
user=MYSQL_USER,
password=MYSQL_PASSWORD,
db=MYSQL_DB,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
try:
with connection.cursor() as cursor:
# Create table if not exists
create_table_if_not_exists(cursor)
# Process each event
for event in events:
event_data = json.loads(event.get_body().decode('utf-8'))
# Log the event data
logging.info('Python EventHub trigger processed an event: %s', event_data)
# Insert JSON event data into MySQL
insert_event_data(cursor, event_data)
# Commit the changes
connection.commit()
finally:
# Close the MySQL connection
connection.close()
功能日志:
MySQL:
另一种方法: