微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用AWS Lambda在AWS IoT上模拟传感器

如何解决使用AWS Lambda在AWS IoT上模拟传感器

我正在使用AWS,并且想尝试使用AWS Lambda(更具体地说是Python功能)来模拟IoT设备。

我以来自亚马逊here的简单啤酒服务示例sbs.py为例,对其进行了一些修改以使其适合lambda:

import json
import random
import datetime
import boto3
import time
import sys

def lambda_handler(event,context) :
    return {"body" : 
            main()}

deviceNames = ['SBS01','SBS02','SBS03','SBS04','SBS05']

iot = boto3.client('iot-data');

# generate Flow values
def getFlowValues():
    data = {}
    data['deviceValue'] = random.randint(60,100)
    data['deviceParameter'] = 'Flow'
    data['deviceid'] = random.choice(deviceNames)
    data['dateTime'] = datetime.datetime.Now().strftime("%Y-%m-%d %H:%M:%s")
    return data

# generate Temperature values
def getTemperatureValues():
    data = {}
    data['deviceValue'] = random.randint(15,35)
    data['deviceParameter'] = 'Temperature'
    data['deviceid'] = random.choice(deviceNames)
    data['dateTime'] = datetime.datetime.Now().strftime("%Y-%m-%d %H:%M:%s")
    return data

# generate Humidity values
def getHumidityValues():
    data = {}
    data['deviceValue'] = random.randint(50,90)
    data['deviceParameter'] = 'Humidity'
    data['deviceid'] = random.choice(deviceNames)
    data['dateTime'] = datetime.datetime.Now().strftime("%Y-%m-%d %H:%M:%s")
    return data

# generate Sound values
def getSoundValues():
    data = {}
    data['deviceValue'] = random.randint(100,140)
    data['deviceParameter'] = 'Sound'
    data['deviceid'] = random.choice(deviceNames)
    data['dateTime'] = datetime.datetime.Now().strftime("%Y-%m-%d %H:%M:%s")
    return response

# Generate each parameter's data input in varying proportions
def main():
    for i in range(3):
        rnd = random.random()
        if (0 <= rnd < 0.20):
            data = json.dumps(getFlowValues())
            print(data)
            response = iot.publish(
                 topic='/sbs/devicedata/flow',payload=data
            ) 
        elif (0.20<= rnd < 0.55):
            data = json.dumps(getTemperatureValues())
            print(data)
            response = iot.publish(
                 topic='/sbs/devicedata/temperature',payload=data
            )
        elif (0.55<= rnd < 0.70):
            data = json.dumps(getHumidityValues())
            print(data)
            response = iot.publish(
                 topic='/sbs/devicedata/humidity',payload=data
            )
        else:
            data = json.dumps(getSoundValues())
            print(data)
            response = iot.publish(
                 topic='/sbs/devicedata/sound',payload=data     
        
    )
    
    return response

,我正在尝试使用AWS lambda控制台中的测试功能来测试此功能。我已将AWSIoTFullAcess策略附加到lambda函数,以便它应具有执行IoT服务所需的一切权利。

函数运行是因为我可以看到CloudWatch日志中打印的数据。但是,物联网核心内部什么也没有发生,除了Lambda抛出的错误消息“运行时间超过3秒”之外,我在CloudWatch中看不到任何错误消息。

有什么主意吗?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。