锐单电子商城 , 一站式电子元器件采购平台!
  • 电话:400-990-0325

传感器模拟器——python

时间:2022-06-27 13:56:14 光开关传感器

传感器模拟器——python

在综合实践课程中,传感器需要用于物联网应用,但在这个阶段调试简单的传感器太浪费时间
如果需要使用传感器,可以用这个来模拟(调试简单的传感器太浪费时间)

开发语言 数据类型 数据库 数据类型
python json MySQL json

简介:
统一的数据格式json,模拟传感器生成的数据发送到数据库,字段可以自行修改,值可以随机生成,最后有时间延迟,延迟时间也是随机的。如果需要添加其他通信方式,例如mqtt,请参考我的其他文章。感谢使用,欢迎指正!

import  jsonimport  pymysqlimport  timeimport  randomfirstdataofvoice =  '{"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  time1def  getsensor():        sensor=random.choice(['voice',  'pir'])        return  sensordef  getdata():        data=random.choice(['bathroom',  'kitchen'])        return  datadef  getvalue(sensorType):        if(sensorType=="voice"):                value=random.randint(25,100)                if(value>65):                        value=4095                if(sensorType=="pir"):        value=random.randint(0,1)    return valuedef 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 timesdef main():  while True:      sqlsave(datamaker(data2))      print(data2)      time.sleep(random.randint(1,5))if __name__ == '__main__':  main()
锐单商城拥有海量元器件数据手册IC替代型号,打造电子元器件IC百科大全!

相关文章