传感器模拟器——python
在综合实践课程中,传感器需要用于物联网应用,但在这个阶段调试简单的传感器太浪费时间 如果需要使用传感器,可以用这个来模拟(调试简单的传感器太浪费时间)
开发语言 | 数据类型 | 数据库 | 数据类型 |
---|---|---|---|
python | json | MySQL | json |
统一的数据格式json,模拟传感器生成的数据发送到数据库,字段可以自行修改,值可以随机生成,最后有时间延迟,延迟时间也是随机的。如果需要添加其他通信方式,例如mqtt,请参考我的其他文章。感谢使用,欢迎指正!
import json import pymysql import time import random firstdataofvoice = '{"device":"kitchen","sensorType":"voice","get_data":"open","get_time":1,"get_value":145}' data2 = json.loads(firstdataofvoice) print(type(data2)) def gettime(): time1=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) return time1 def getsensor(): sensor=random.choice(['voice', 'pir']) return sensor def getdata(): data=random.choice(['bathroom', 'kitchen']) return data def getvalue(sensorType): if(sensorType=="voice"): value=random.randint(25,100) if(value>65): value=4095 if(sensorType=="pir"):
value=random.randint(0,1)
return value
def datamaker(progress):
print(type(progress))
progress['get_time']=gettime()
progress['sensorType']=getsensor()
progress['get_data']=getdata()
progress['get_value']=getvalue(progress['sensorType'])
if progress['get_value']==4095 or progress['get_value']==1:
progress['device']="open"
else:
progress['device']="close"
return progress
#MySQL保存
def sqlsave(jsonData):
# 打开数据库连接
db = pymysql.connect(host="192.168.174.128",user="root",password="password",database="test",charset='utf8')
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 插入语句
sql = "INSERT INTO datasensor (get_time,sensorType,device,get_data,get_value) \
VALUES ('%s','%s','%s','%s','%s');"\
%(jsonData['get_time'],jsonData['sensorType'],jsonData['get_data'],jsonData['device'],jsonData['get_value'],)
cursor.execute(sql)
db.commit()
print("数据库保存成功!")
# 关闭数据库连接
db.close()
def getrandom():
times=random.random(1,5)
return times
def main():
while True:
sqlsave(datamaker(data2))
print(data2)
time.sleep(random.randint(1,5))
if __name__ == '__main__':
main()