如何将工具数据从遥测Azure IoT Hub发送到Azure Functions?

问题描述 投票:0回答:1

我使用 Azure Custom Vision 和 Raspberry Pi 创建了一个基于人们存在的室温控制自动化系统项目。 我已成功将 DHT11 温度传感器数据、图像中人数的摄像头传感器数据发送到 Azure IoT 中心。下一步是如何将数据从 Azure IoT Hub 获取到 Azure Functions 并将数据添加到本地数据库。之后,您还可以对正在监控的设备执行开/关操作。

我的期望是,在Azure IoT Hub接收到数据并在遥测消息中提供数据证明后,Azure Functions也可以接收到数据,可以将数据添加到本地数据库,并使用此数据Azure Functions可以对设备执行开/关形式的操作。受到监控。

azure azure-functions azure-iot-hub azure-iot-edge azure-iot-sdk
1个回答
0
投票

通过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'))


enter image description here

  • 下面的 Azure 函数处理来自事件中心的事件并将所有事件数据插入 MySQL 数据库。在Azure中,我们必须使用Azure SQL和Azure MySQL。
  • 将 Azure 事件中心连接到 IoT 中心事件。

enter image description here


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()

功能日志: enter image description here

enter image description here

MySQL:

enter image description here

另一种方法:

enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.