azureazure-functionsazure-iot-hub

How to solve my message body from IoT device can't receive by azure functions via vscode/local


how to solve this error? this error appear when my sensor detect people and try send data to the cloud. error read body from azure function

error text: this is the result: [2024-01-10T09:57:10.295Z] Executing 'Functions.AutomateHubTrigger' (Reason='(null)', Id=d286be5c-f5e8-4260-9c9e-a6e27de9b87c) [2024-01-10T09:57:10.300Z] Trigger Details: PartionId: 1, Offset: 4294979360, EnqueueTimeUtc: 2024-01-10T09:55:47.2540000+00:00, SequenceNumber: 110, Count: 1 [2024-01-10T09:57:10.306Z] Type of body: <class 'list'>, Content of body: [{'id': 'f6acfe2e-8725-2b54-777d-79b477db2796', 'topic': '/SUBSCRIPTIONS/D0E3660E-537C-4385-89F5-B2B0646AF52A/RESOURCEGROUPS/AUTOMATE/PROVIDERS/MICROSOFT.DEVICES/IOTHUBS/AUTOMATE-HUB', 'subject': 'devices/automate-device-id', 'eventType': 'Microsoft.Devices.DeviceTelemetry', 'data': {'properties': {}, 'systemProperties': {'iothub-connection-device-id': 'automate-device-id', 'iothub-connection-auth-method': '{"scope":"device","type":"sas","issuer":"iothub","acceptingIpFilterRule":null}', 'iothub-connection-auth-generation-id': '638364984370269801', 'iothub-enqueuedtime': '2024-01-10T09:55:47.0870000Z', 'iothub-message-source': 'Telemetry'}, 'body': 'eyJkYXRlIjogIjIwMjQtMDEtMTAiLCAidGltZSI6ICIxNjo1NTo0NiIsICJ0ZW1wZXJhdHVyZSI6IDM0LjAsICJwZW9wbGUiOiAwfQ=='}, 'dataVersion': '', 'metadataVersion': '1', 'eventTime': '2024-01-10T09:55:47.087Z'}] [2024-01-10T09:57:10.310Z] Executed 'Functions.AutomateHubTrigger' (Failed, Id=d286be5c-f5e8-4260-9c9e-a6e27de9b87c, Duration=15ms) [2024-01-10T09:57:10.314Z] System.Private.CoreLib: Exception while executing function: Functions.AutomateHubTrigger. System.Private.CoreLib: Result: Failure Exception: TypeError: list indices must be integers or slices, not str Stack: File "C:\Users\Viqram Wataf\AppData\Roaming\nvm\v10.24.0\node_modules\azure-functions-core-tools\bin\workers\python\3.9\WINDOWS\X64\azure_functions_worker\dispatcher.py", line 406, in _handle__invocation_request call_result = await self._loop.run_in_executor( File "C:\Program Files\Python 3.9.0\lib\concurrent\futures\thread.py", line 52, in run result = self.fn(*self.args, **self.kwargs) File "C:\Users\Viqram Wataf\AppData\Roaming\nvm\v10.24.0\node_modules\azure-functions-core-tools\bin\workers\python\3.9\WINDOWS\X64\azure_functions_worker\dispatcher.py", line 648, in _run_sync_func return ExtensionManager.get_sync_invocation_wrapper(context, File "C:\Users\Viqram Wataf\AppData\Roaming\nvm\v10.24.0\node_modules\azure-functions-core-tools\bin\workers\python\3.9\WINDOWS\X64\azure_functions_worker\extension.py", line 215, in raw_invocation_wrapper result = function(**args) File "C:\xampp\htdocs\tugas-akhir-project\Tugas-Akhir\azure_function\AutomateHubTrigger_init.py", line 29, in main date = body['date']

My expectation is that all bodies sent from app.py can be read by the Azure function and can be entered into my local database. code body from azure functions and insert into my local database. insert to database

this is my atribute table notification in my db. atribute db notification

init.py

import logging
import azure.functions as func
import mysql.connector
import time
from datetime import datetime
import json
import os
from azure.iot.hub import IoTHubRegistryManager
from azure.iot.hub.models import CloudToDeviceMethod
def main(event: func.EventHubEvent):

# Connect database MySQL
dbconnection = mysql.connector.connect(
    host = "127.0.0.1",
    user = "root",
    password = "",
    database = "roomdb"
)
cursor = dbconnection.cursor()

body = json.loads(event.get_body().decode('utf-8'))
device_id = event.iothub_metadata.get('automate-device-id')

# logging.info(f'Received message: {body} from {device_id}')

id = 1
date = body['date']
time = body['time']
temperature = body['temperature']
people = body['people']
detect_time = body['last_detected_time']
notification_type = ""
message = "You can view more via website"
room_id = 1
sql = ""

# Insert into database using the notifications
sql = "insert into notifications (id, date, time, value_temperature, number_of_people, notification_type, message, room_id) values (%s, %s, %s, %s, %s, %s, %s, %s)"
value = (id, date, time, temperature, people, notification_type, message, room_id)

cursor.execute(sql, value)
dbconnection.commit()
print(cursor.rowcount, 'Data Saved Successfully')

cursor.close()
dbconnection.close()

Solution

  • The issue concerns a data type mismatch between the received body and the expected data types in your Azure Function code.

    enter image description here

    enter image description here

    id = 1
    date = body[0]['data']['date']
    time = body[0]['data']['time']
    temperature = body[0]['data']['value_temperature']
    people = body[0]['data']['number_of_people']
    detect_time = body[0]['data']['last_detected_time']
    notification_type = ""
    message = "You can view more via website"
    room_id = 1
    
    

    enter image description here