code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
""" Copyright (C) 2015-2021 Alibaba Group Holding Limited MicroPython's driver for CHT8305 Author: HaaS Date: 2021/09/14 """ from micropython import const from utime import sleep_ms from driver import I2C CHT8305_REG_TEMP = 0x00 CHT8305_REG_HUMI = 0x01 # The register address in CHT8305 controller. class CHT8305Error(Exception): def __init__(self, value=0, msg="cht8305 common error"): self.value = value self.msg = msg def __str__(self): return "Error code:%d, Error message: %s" % (self.value, str(self.msg)) __repr__ = __str__ class CHT8305(object): """ This class implements cht8305 chip's functions. """ def __init__(self, i2cDev): self._i2cDev = None if not isinstance(i2cDev, I2C): raise ValueError("parameter is not an I2C object") # make CHT8305's internal object points to i2cDev self._i2cDev = i2cDev def getTemperature(self): """Get temperature.""" # make sure CHT8305's internal object is valid before I2C operation if self._i2cDev is None: raise ValueError("invalid I2C object") # send temperature register to CHT8305 reg = bytearray([CHT8305_REG_TEMP]) self._i2cDev.write(reg) # wait for 30ms sleep_ms(30) readData = bytearray(2) # read temperature from CHT8305 self._i2cDev.read(readData) # convert the temperature data to actual value value = (readData[0] << 8) | readData[1] if (value & 0xFFFC): temperature = (165.0 * float(value)) / 65536.0 - 40.0 else: raise CHT8305Error("failed to get temperature.") return temperature def getHumidity(self): """Get humidity.""" # make sure CHT8305's internal object is valid before I2C operation if self._i2cDev is None: raise ValueError("invalid I2C object") # send humidity register to CHT8305 reg = bytearray([CHT8305_REG_HUMI]) self._i2cDev.write(reg) sleep_ms(30) # read humidity from CHT8305 readData = bytearray(2) self._i2cDev.read(readData) # convert the humidity data to actual value value = (readData[0] << 8) | readData[1] if (value & 0xFFFE): humidity = ((125.0 * float(value)) / 65535.0) - 6.0 else: raise CHT8305Error("failed to get humidity.") return humidity def getTempHumidity(self): """Get temperature and humidity.""" # make sure CHT8305's internal object is valid before I2C operation if self._i2cDev is None: raise ValueError("invalid I2C object") temphumidity = [0, 1] # send temperature register to CHT8305 reg = bytearray([CHT8305_REG_TEMP]) self._i2cDev.write(reg) sleep_ms(30) # 4 bytes means read temperature and humidity back in one read operation readData = bytearray(4) self._i2cDev.read(readData) #print("rawdata %d-%d-%d-%d" %(readData[0],readData[1],readData[2],readData[3])) # convert the temperature and humidity data to actual value value = (readData[0] << 8) | readData[1] if (value & 0xFFFC): temphumidity[0] = (165.0 * float(value)) / 65536.0 - 40.0 else: raise CHT8305Error("failed to get temperature.") value = (readData[2] << 8) | readData[3] if (value & 0xFFFE): temphumidity[1] = ((125.0 * float(value)) / 65535.0) - 6.0 else: raise CHT8305Error("failed to get humidity.") return temphumidity if __name__ == "__main__": ''' The below i2c configuration is needed in your board.json. "cht8305": { "type": "I2C", "port": 1, "addrWidth": 7, "freq": 400000, "mode": "master", "devAddr": 64 } ''' print("Testing cht8305 ...") i2cDev = I2C() i2cDev.open("cht8305") cht8305Dev = CHT8305(i2cDev) temperature = cht8305Dev.getTemperature() print("The temperature is: %f" % temperature) humidity = cht8305Dev.getHumidity() print("The humidity is: %f" % humidity) i2cDev.close() print("Test cht8305 done!")
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/floriculture/haaseduk1/code/cht8305.py
Python
apache-2.0
4,277
""" Copyright (C) 2015-2021 Alibaba Group Holding Limited """ from driver import I2C import kv class HAASEDUK1(object): def __init__(self): self.i2cDev = None # 获取版本号 # 返回值为1,代表k1c # 返回值为0,代表k1 def getHWID(self): hwId = -1 result = kv.geti("HAASEDU_NAME") if (result != None): if (result == 1): print("HAASEDUK1 hw version is 1.1") return 1 elif (result == 0): print("HAASEDUK1 hw version is 1.0") return 0 else: pass # kv中不存在HAASEDU_NAME键值对,则通过外围传感器进行判断 # 读取QMI8610传感器device identifier register的值 self.i2cDev = I2C() self.i2cDev.open("qmi8610") buf = bytearray(1) buf[0] = 0 self.i2cDev.memRead(buf, 0, 8) # register address:0 - FIS device identifier register address self.i2cDev.close() if buf[0] == 0xfc: hwId = 1 else: # 读取QMI8610传感器chip id register的值 self.i2cDev.open("qmp6988") buf[0] = 0xD1 # chip id register self.i2cDev.write(buf) self.i2cDev.read(buf) self.i2cDev.close() if buf[0] == 0x5C: hwId = 1 else: # 读取QMC6310传感器chip id register的值 self.i2cDev.open("qmc6310") buf[0] = 0x00 # chip id register self.i2cDev.write(buf) self.i2cDev.read(buf) self.i2cDev.close() if buf[0] == 0x80: hwId = 1 if hwId == 1: kv.seti("HAASEDU_NAME", 1) print("HAASEDUK1 hw version is 1.1") return 1 else: kv.seti("HAASEDU_NAME", 0) print("HAASEDUK1 hw version is 1.0") return 0
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/floriculture/haaseduk1/code/haaseduk1.py
Python
apache-2.0
1,984
# -*- encoding: utf-8 -*- ''' @File : main.py @Description: 温湿度上云 @Author : ethan.lcz @version : 1.0 ''' from aliyunIoT import Device # aliyunIoT组件是连接阿里云物联网平台的组件 import netmgr as nm # Wi-Fi功能所在库 import utime # 延时API所在组件 from driver import I2C # I2C总线驱动库 from driver import GPIO # ESP32和使用GPIO控制LED from haaseduk1 import HAASEDUK1 # 引入haaseduk1库,目标用于区分K1版本 import ujson # json字串解析库 # 物联网平台连接标志位 iot_connected = False # 物联网设备实例 device = None # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 空调和加湿器状态变量 airconditioner = 0 humidifier = 0 airconditioner_value = 0 humidifier_value = 0 humitureDev = 0 board = HAASEDUK1() # 新建HAASEDUK1对象 hwID = board.getHWID() # 获取开发板ID i2cObj = I2C() if (hwID == 1): from cht8305 import CHT8305 # HaaS EDU K1C上的温湿度传感器采用的是CHT8305 i2cObj.open("cht8305") # 按照board.json中名为"cht8305"的设备节点的配置参数(主设备I2C端口号,从设备地址,总线频率等)初始化I2C类型设备对象 humitureDev = CHT8305(i2cObj) # 初始化CHT8305传感器 # print("cht8305 inited!") else: from si7006 import SI7006 # HaaS EDU K1上的温湿度传感器采用的是SI7006 i2cObj.open("si7006") # 按照board.json中名为"si7006"的设备节点的配置参数(主设备I2C端口号,从设备地址,总线频率等)初始化I2C类型设备对象 humitureDev = SI7006(i2cObj) # 初始化SI7006传感器 version = humitureDev.getVer() # 获取SI7006的版本信息 chipID = humitureDev.getID() # 获取SI7006 ID信息 # print("si7006 version:%d, chipID:%d" , version, chipID) # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): nm.init() nm.disconnect() wifi_connected = nm.getStatus() print("start to connect " , wifiSsid) nm.connect(wifiSsid, wifiPassword) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) while True : if wifi_connected == 5: # nm.getStatus()返回5代表连线成功 break else: wifi_connected = nm.getStatus() # 获取Wi-Fi连接路由器的状态信息 utime.sleep(0.5) print("Wi-Fi connected") print('DeviceIP:' + nm.getInfo()['ip']) # 打印Wi-Fi的IP地址信息 # 通过温湿度传感器读取温湿度信息 def get_temp_humi(): global humitureDev ''' # 如果需要同时获取温湿度信息,可以呼叫getTempHumidity,实例代码如下: humniture = humitureDev.getTempHumidity() # 获取温湿度传感器测量到的温湿度值 temperature = humniture[0] # get_temp_humidity返回的字典中的第一个值为温度值 humidity = humniture[1] # get_temp_humidity返回的字典中的第二个值为相对湿度值 ''' temperature = humitureDev.getTemperature() # 获取温度测量结果 # print("The temperature is: %.1f" % temperature) humidity = humitureDev.getHumidity() # 获取相对湿度测量结果 # print("The humidity is: %d" % humidity) return temperature, humidity # 返回读取到的温度值和相对湿度值 # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): global airconditioner, humidifier, airconditioner_value, humidifier_value # {"airconditioner":1} or {"humidifier":1} or {"airconditioner":1, "humidifier":1} payload = ujson.loads(request['params']) # print (payload) # 获取dict状态字段 注意要验证键存在 否则会抛出异常 if "airconditioner" in payload.keys(): airconditioner_value = payload["airconditioner"] if (airconditioner_value): print("打开空调") else: print("关闭空调") if "humidifier" in payload.keys(): humidifier_value = payload["humidifier"] if (humidifier_value): print("打开加湿器") else: print("关闭加湿器") # print(airconditioner_value, humidifier_value) airconditioner.write(airconditioner_value) # 控制空调开关 humidifier.write(humidifier_value) # 控制加湿器开关 # 要将更改后的状态同步上报到云平台 prop = ujson.dumps({ 'airconditioner': airconditioner_value, 'humidifier': humidifier_value, }) upload_data = {'params': prop} # 上报空调和加湿器属性到云端 device.postProps(upload_data) # 连接物联网平台 def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) # 上传温度信息和湿度信息到物联网平台 def upload_temperature_and_Humidity(): global device while True: data = get_temp_humi() # 读取温度信息和湿度信息 # 生成上报到物联网平台的属性值字串 prop = ujson.dumps({ 'CurrentTemperature': data[0], 'CurrentHumidity': data[1] }) print('uploading data: ', prop) upload_data = {'params': prop} # 上传温度和湿度信息到物联网平台 device.postProps(upload_data) utime.sleep(2) if __name__ == '__main__': # 硬件初始化 # 初始化 GPIO airconditioner = GPIO() humidifier = GPIO() humidifier.open('led_g') # 加湿器使用board.json中led_g节点定义的GPIO,对应HaaS EDU K1上的绿灯 airconditioner.open('led_b') # 空调使用board.json中led_b节点定义的GPIO,对应HaaS EDU K1上的蓝灯 # 请替换物联网平台申请到的产品和设备信息,可以参考文章:https://blog.csdn.net/HaaSTech/article/details/114360517 # global productKey, deviceName, deviceSecret ,on_request, on_play get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_temperature_and_Humidity() humitureDev.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/floriculture/haaseduk1/code/main.py
Python
apache-2.0
7,502
""" Copyright (C) 2015-2021 Alibaba Group Holding Limited MicroPython's drive for SI7006 Author: HaaS Date: 2021/09/09 """ from driver import I2C from utime import sleep_ms # The commands provided by SI7006 Si7006_MEAS_REL_HUMIDITY_MASTER_MODE = 0xE5 Si7006_MEAS_REL_HUMIDITY_NO_MASTER_MODE = 0xF5 Si7006_MEAS_TEMP_MASTER_MODE = 0xE3 Si7006_MEAS_TEMP_NO_MASTER_MODE = 0xF3 Si7006_READ_OLD_TEMP = 0xE0 Si7006_RESET = 0xFE Si7006_READ_ID_LOW_0 = 0xFA Si7006_READ_ID_LOW_1 = 0x0F Si7006_READ_ID_HIGH_0 = 0xFC Si7006_READ_ID_HIGH_1 = 0xC9 Si7006_READ_Firmware_Revision_0 = 0x84 Si7006_READ_Firmware_Revision_1 = 0xB8 class SI7006Error(Exception): def __init__(self, value=0, msg="si7006 common error"): self.value = value self.msg = msg def __str__(self): return "Error code:%d, Error message: %s" % (self.value, str(self.msg)) __repr__ = __str__ class SI7006(object): """ This class implements SI7006 chip's functions. """ # i2cDev should be an I2C object and it should be opened before __init__ is called def __init__(self, i2cDev): self._i2cDev = None if not isinstance(i2cDev, I2C): raise ValueError("parameter is not an I2C object") # make SI7006's internal object points to i2cDev self._i2cDev = i2cDev def getVer(self): """ Get the firmware version of the chip. """ # make sure SI7006's internal object is valid before I2C operation if self._i2cDev is None: raise ValueError("invalid I2C object") # send read firmware version command to SI7006 reg = bytearray([Si7006_READ_Firmware_Revision_0, Si7006_READ_Firmware_Revision_1]) self._i2cDev.write(reg) sleep_ms(30) version = bytearray(1) # read the version info back self._i2cDev.read(version) return version[0] def getID(self): """Get the chip ID.""" # make sure SI7006's internal object is valid before I2C operation if self._i2cDev is None: raise ValueError("invalid I2C object") # send read chip id‘s lower part command to SI7006 reg = bytearray([Si7006_READ_ID_LOW_0, Si7006_READ_ID_LOW_1]) self._i2cDev.write(reg) sleep_ms(30) id_buf_low = bytearray(4) # read the id info back self._i2cDev.read(id_buf_low) # send read chip id‘s higher part command to SI7006 reg = bytearray([Si7006_READ_ID_HIGH_0, Si7006_READ_ID_HIGH_1]) id_buf_high = bytearray(4) self._i2cDev.read(id_buf_high) return id_buf_low + id_buf_high def getTemperature(self): """Get temperature.""" # make sure SI7006's internal object is valid before I2C operation if self._i2cDev is None: raise ValueError("invalid I2C object") # send measure temperature command to SI7006 reg = bytearray([Si7006_MEAS_TEMP_NO_MASTER_MODE]) self._i2cDev.write(reg) # wait for 30ms to wait for the measure finish according to SI7006's datasheet sleep_ms(30) readData = bytearray(2) # read the temperature measure result self._i2cDev.read(readData) value = (readData[0] << 8 | readData[1]) # convert to actual temperature if (value & 0xFFFC): temperature = (175.72 * value) / 65536.0 - 46.85 return round(temperature, 1) else: raise SI7006Error("failed to get temperature.") def getHumidity(self): """Get humidity.""" # make sure SI7006's internal object is valid before I2C operation if self._i2cDev is None: raise ValueError("invalid I2C object") # send measure humidity command to SI7006 reg = bytearray([Si7006_MEAS_REL_HUMIDITY_NO_MASTER_MODE]) self._i2cDev.write(reg) # wait for 30ms to wait for the measure finish according to SI7006's datasheet sleep_ms(30) readData = bytearray(2) self._i2cDev.read(readData) value = (readData[0] << 8) | readData[1] # convert to actual humidity if (value & 0xFFFE): humidity = (125.0 * value) / 65535.0 - 6.0 return round(humidity) else: raise SI7006Error("failed to get humidity.") def getTempHumidity(self): """Get temperature and humidity.""" # make sure SI7006's internal object is valid before I2C operation if self._i2cDev is None: raise ValueError("invalid I2C object") # read tempperature and humidity in sequence temphumidity = [0, 0] temphumidity[0] = self.getTemperature() temphumidity[1] = self.getHumidity() return temphumidity if __name__ == "__main__": ''' The below i2c configuration is needed in your board.json. "si7006": { "type": "I2C", "port": 1, "addrWidth": 7, "freq": 400000, "mode": "master", "devAddr": 64 } ''' print("Testing si7006 ...") i2cDev = I2C() i2cDev.open("si7006") si7006Dev = SI7006(i2cDev) version = si7006Dev.getVer() print("si7006 version is: %d" % version) chipID = si7006Dev.getID() print("si7006 chip id is:", chipID) temperature = si7006Dev.getTemperature() print("The temperature is: %f" % temperature) humidity = si7006Dev.getHumidity() print("The humidity is: %d" % humidity) i2cDev.close() print("Test si7006 done!")
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/floriculture/haaseduk1/code/si7006.py
Python
apache-2.0
5,698
# -*- encoding: utf-8 -*- ''' @File : main.py @Description: 温湿度上云 @Author : ethan.lcz @version : 1.0 ''' from ulinksdk.aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import utime # 延时API所在组件 from driver import I2C # I2C总线驱动库 from driver import GPIO # ESP32和使用GPIO控制LED import sht3x # SHT3X-DIS温湿度传感器驱动库 import ujson # json字串解析库 # 空调和加湿器状态变量 airconditioner = 0 humidifier = 0 airconditioner_value = 0 humidifier_value = 0 # 物联网平台连接标志位 iot_connected = False # 三元组信息 productKey = "产品密钥" deviceName = "设备名字" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 物联网平台连接标志位 iot_connected = False wlan = None # 物联网设备实例 device = None i2cObj = None humitureDev = None # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wlan wifi_connected = False wlan = network.WLAN(network.STA_IF) #创建WLAN对象 wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if not wifi_connected: wlan.active(True) #激活界面 wlan.scan() #扫描接入点 #print("start to connect ", wifiSsid) wlan.connect(wifiSsid, wifiPassword) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) while True: wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected: # Wi-Fi连接成功则退出while循环 break else: utime.sleep(0.5) print("wifi_connected:", wifi_connected) ifconfig = wlan.ifconfig() #获取接口的IP/netmask/gw/DNS地址 print(ifconfig) utime.sleep(0.5) # 通过温湿度传感器读取温湿度信息 def get_temp_humi(): global humitureDev ''' # 如果需要同时获取温湿度信息,可以呼叫getTempHumidity,实例代码如下: humniture = humitureDev.getTempHumidity() # 获取温湿度传感器测量到的温湿度值 temperature = humniture[0] # get_temp_humidity返回的字典中的第一个值为温度值 humidity = humniture[1] # get_temp_humidity返回的字典中的第二个值为相对湿度值 ''' temperature = humitureDev.getTemperature() # 获取温度测量结果 # print("The temperature is: %.1f" % temperature) humidity = humitureDev.getHumidity() # 获取相对湿度测量结果 # print("The humidity is: %d" % humidity) return temperature, humidity # 返回读取到的温度值和相对湿度值 # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): global airconditioner, humidifier, airconditioner_value, humidifier_value # {"airconditioner":1} or {"humidifier":1} or {"airconditioner":1, "humidifier":1} payload = ujson.loads(request['params']) # print (payload) # 获取dict状态字段 注意要验证键存在 否则会抛出异常 if "airconditioner" in payload.keys(): airconditioner_value = payload["airconditioner"] if (airconditioner_value): print("打开空调") else: print("关闭空调") if "humidifier" in payload.keys(): humidifier_value = payload["humidifier"] if (humidifier_value): print("打开加湿器") else: print("关闭加湿器") # print(airconditioner_value, humidifier_value) airconditioner.write(airconditioner_value) # 控制空调开关 humidifier.write(humidifier_value) # 控制加湿器开关 # 要将更改后的状态同步上报到云平台 prop = ujson.dumps({ 'airconditioner': airconditioner_value, 'humidifier': humidifier_value, }) upload_data = {'params': prop} # 上报空调和加湿器属性到云端 device.postProps(upload_data) def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) # 上传温度信息和湿度信息到物联网平台 def upload_temperature_and_Humidity(): global device while True: data = get_temp_humi() # 读取温度信息和湿度信息 # 生成上报到物联网平台的属性值字串 prop = ujson.dumps({ 'CurrentTemperature': data[0], 'CurrentHumidity': data[1] }) print('uploading data: ', prop) upload_data = {'params': prop} # 上传温度和湿度信息到物联网平台 device.postProps(upload_data) utime.sleep(2) if __name__ == '__main__': # 硬件初始化 i2cObj = I2C() i2cObj.open("sht3x") # 按照board.json中名为"sht3x"的设备节点的配置参数(主设备I2C端口号,从设备地址,总线频率等)初始化I2C类型设备对象 humitureDev = sht3x.SHT3X(i2cObj) # 初始化SHT3X-DIS传感器 # 初始化 GPIO airconditioner = GPIO() humidifier = GPIO() humidifier.open('led_g') # 加湿器使用board.json中led_g节点定义的GPIO,对应esp32外接的的绿灯 airconditioner.open('led_b') # 空调使用board.json中led_b节点定义的GPIO,对应esp32外接的上的蓝灯 # 请替换物联网平台申请到的产品和设备信息,可以参考文章:https://blog.csdn.net/HaaSTech/article/details/114360517 nic = network.LAN() nic.active(1) connect_lk(productKey, deviceName, deviceSecret) upload_temperature_and_Humidity() i2cObj.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/floriculture/stm32/code/main.py
Python
apache-2.0
7,339
""" Copyright (C) 2015-2021 Alibaba Group Holding Limited MicroPython's driver for CHT8305 Author: HaaS Date: 2021/09/14 """ from micropython import const import utime from driver import I2C ''' # sht3x commands definations # read serial number: CMD_READ_SERIALNBR 0x3780 # read status register: CMD_READ_STATUS 0xF32D # clear status register: CMD_CLEAR_STATUS 0x3041 # enabled heater: CMD_HEATER_ENABLE 0x306D # disable heater: CMD_HEATER_DISABLE 0x3066 # soft reset: CMD_SOFT_RESET 0x30A2 # accelerated response time: CMD_ART 0x2B32 # break, stop periodic data acquisition mode: CMD_BREAK 0x3093 # measurement: polling, high repeatability: CMD_MEAS_POLLING_H 0x2400 # measurement: polling, medium repeatability: CMD_MEAS_POLLING_M 0x240B # measurement: polling, low repeatability: CMD_MEAS_POLLING_L 0x2416 ''' class SHT3X(object): # i2cDev should be an I2C object and it should be opened before __init__ is called def __init__(self, i2cDev): self._i2cDev = None if not isinstance(i2cDev, I2C): raise ValueError("parameter is not an I2C object") # make AHB21B's internal object points to _i2cDev self._i2cDev = i2cDev self.start() def start(self): # make sure AHB21B's internal object is valid before I2C operation if self._i2cDev is None: raise ValueError("invalid I2C object") # send clear status register command - 0x3041 - CMD_CLEAR_STATUS cmd = bytearray(2) cmd[0] = 0x30 cmd[1] = 0x41 self._i2cDev.write(cmd) # wait for 20ms utime.sleep_ms(20) return 0 def getTempHumidity(self): if self._i2cDev is None: raise ValueError("invalid I2C object") tempHumidity = [-1, 2] # start measurement: polling, medium repeatability - 0x240B - CMD_MEAS_POLLING_M # if you want to adjust measure repeatability, you can send the following commands: # high repeatability: 0x2400 - CMD_MEAS_POLLING_H # low repeatability: 0x2416 - CMD_MEAS_POLLING_L cmd = bytearray(2) cmd[0] = 0x24 cmd[1] = 0x0b self._i2cDev.write(cmd) # must wait for a little before the measurement finished utime.sleep_ms(20) dataBuffer = bytearray(6) # read the measurement result self._i2cDev.read(dataBuffer) # print(dataBuffer) # calculate real temperature and humidity according to SHT3X-DIS' data sheet temp = (dataBuffer[0]<<8) | dataBuffer[1] humi = (dataBuffer[3]<<8) | dataBuffer[4] tempHumidity[1] = humi * 0.0015259022 tempHumidity[0] = -45.0 + (temp) * 175.0 / (0xFFFF - 1) return tempHumidity def getTemperature(self): data = self.getTempHumidity() return data[0] def getHumidity(self): data = self.getTempHumidity() return data[1] def stop(self): if self._i2cDev is None: raise ValueError("invalid I2C object") # stop periodic data acquisition mode cmd = bytearray(3) cmd[0] = 0x30 cmd[1] = 0x93 self._i2cDev.write(cmd) # wait for a little while utime.sleep_ms(20) self._i2cDev = None return 0 def __del__(self): print('sht3x __del__')
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/floriculture/stm32/code/sht3x.py
Python
apache-2.0
3,599
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : cloudAI.py @Description: 云端AI @Author : jiangyu @version : 1.0 ''' from aliyunIoT import Device import utime # 延时函数在utime库中 import ujson as json class CloudAI : def __gesture_cb(self, dict) : ''' Reply list : handGestureReply : 手势识别 ''' gesture = 'NA' if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': score = ext_dict['score'] if score > 0.4 : gesture = ext_dict['type'] print("recognize hand gesture : " + gesture) self.__cb('handGestureReply', gesture) def __license_plate_cb(self, dict) : plateNumber = 'NA' if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': g_confidence = ext_dict['confidence'] if g_confidence > 0.7 : plateNumber = ext_dict['plateNumber'] print('detect: ' + plateNumber) self.__cb('ocrCarNoReply', plateNumber) def __fruits_cb(self, dict) : fruit_name = 'NA' if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': i = 0 fruits_list = ext_dict['fruitList'] while (i < len(fruits_list)) : g_score = fruits_list[i]['score'] fruit_name = fruits_list[i]['name'] if g_score > 0.6: print('detect: ' + fruit_name) i += 1 self.__cb('detectFruitsReply', fruit_name) def __pedestrian_cb(self, dict) : detected = False if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': i = 0 data = ext_dict['data'] data_dict = json.loads(data) elements_list = data_dict['elements'] while (i < len(elements_list)) : g_score = elements_list[i]['score'] if g_score > 0.6: print('Pedestrian Detected') detected = True i += 1 self.__cb('DetectPedestrianReply', detected) def __businesscard_cb(self, dict) : card_info = {} if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': card_info['name'] = ext_dict['name'] print("name : " + card_info['name']) if card_info['name'] == '' : card_info['name'] = 'unknown' phoneNumbers_list = ext_dict['cellPhoneNumbers'] print("phoneNumbers : ") print(phoneNumbers_list) if len(phoneNumbers_list) : card_info['phoneNumbers'] = phoneNumbers_list[0] else : card_info['phoneNumbers'] = 'unknown' email_list = ext_dict['emails'] print("email_list: ") print(email_list) if len(email_list) : card_info['email'] = email_list[0] else : card_info['email'] = 'unknown' self.__cb('recognizeBusinessCardReply', card_info) def __rubblish_cb(self, dict) : name = 'NA' if dict != None: ext = dict['ext'] extDict = json.loads(ext) result = extDict['result'] if result == 'success': i = 0 elements = extDict['elements'] while (i < len(elements)) : gScore = elements[i]['categoryScore'] if gScore > 0.8: name = elements[i]['category'] print('detect: ' + name) break i += 1 self.__cb('classifyingRubbishReply', name) def __object_cb(self, dict) : name = 'NA' if dict != None: ext = dict['ext'] extDict = json.loads(ext) result = extDict['result'] if result == 'success': i = 0 elements = extDict['elements'] while (i < len(elements)) : gScore = elements[i]['score'] if gScore > 0.25: name = elements[i]['type'] print('detect: ' + name) break i += 1 self.__cb('detectObjectReply', name) def __vehicletype_cb(self, dict) : name = 'NA' detect = False if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': i = 0 item_list = ext_dict['items'] name = 'NA' while (i < len(item_list)) : g_score = item_list[i]['score'] name = item_list[i]['name'] # 这里可以修改识别的可信度,目前设置返回可信度大于85%才认为识别正确 if g_score > 0.85 and name != 'others': print('detect: ' + name) detect = True self.__cb('recognizeVehicleReply', name) break i += 1 if detect == False: self.__cb('recognizeVehicleReply', 'NA') def __vehiclelogo_cb(self, dict) : num = 0 if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': item_list = ext_dict['elements'] num = len(item_list) if num > 0: print('detect: ' + str(num) + ' vehicle') detected = True if detected == False: print('do not detect!') self.__cb('recognizeLogoReply', num) def __cb_lk_service(self, data): self.g_lk_service = True print('download <----' + str(data)) if data != None : params = data['params'] params_dict = json.loads(params) command = params_dict['commandName'] if command == 'handGestureReply' : self.__gesture_cb(params_dict) elif command == 'ocrCarNoReply' : self.__license_plate_cb(params_dict) elif command == 'DetectPedestrianReply' : self.__pedestrian_cb(params_dict) elif command == 'detectFruitsReply' : self.__fruits_cb(params_dict) elif command == 'recognizeBusinessCardReply' : self.__businesscard_cb(params_dict) elif command == 'classifyingRubbishReply' : self.__rubblish_cb(params_dict) elif command == 'detectObjectReply' : self.__object_cb(params_dict) elif command == 'recognizeVehicleReply' : self.__vehicletype_cb(params_dict) elif command == 'recognizeLogoReply' : self.__vehiclelogo_cb(params_dict) else : print('unknown command reply') def __cb_lk_connect(self, data): print('link platform connected') self.g_lk_connect = True def __connect_iot(self) : self.device = Device() self.device.on(Device.ON_CONNECT, self.__cb_lk_connect) self.device.on(Device.ON_SERVICE, self.__cb_lk_service) self.device.connect(self.__dev_info) while True: if self.g_lk_connect: break def __init__(self, dev_info, callback) : self.__dev_info = dev_info self.__cb = callback self.g_lk_connect = False self.g_lk_service = False self.__connect_iot() def getDevice(self) : return self.device def __upload_request(self, command, frame) : # 上传图片到LP fileName = 'test.jpg' start = utime.ticks_ms() fileid = self.device.uploadContent(fileName, frame, None) if fileid != None: ext = { 'filePosition':'lp', 'fileName': fileName, 'fileId': fileid } ext_str = json.dumps(ext) all_params = {'id': 1, 'version': '1.0', 'params': { 'eventType': 'haas.faas', 'eventName': command, 'argInt': 1, 'ext': ext_str }} all_params_str = json.dumps(all_params) #print(all_params_str) upload_file = { 'topic': '/sys/' + self.__dev_info['productKey'] + '/' + self.__dev_info['deviceName'] + '/thing/event/hli_event/post', 'qos': 1, 'payload': all_params_str } # 上传完成通知HaaS聚合平台 print('upload--->' + str(upload_file)) self.g_lk_service = False self.device.publish(upload_file) i = 0 while (self.g_lk_service == False and i < 200) : utime.sleep_ms(10) i = i + 1 continue else: print('filedid is none, upload content fail') time_diff = utime.ticks_diff(utime.ticks_ms(), start) print('recognize time : %d' % time_diff) def recognizeGesture(self, frame) : self.__upload_request('handGesture', frame) def recognizeLicensePlate(self, frame) : self.__upload_request('ocrCarNo', frame) def detectPedestrian(self, frame) : self.__upload_request('detectPedestrian', frame) def detectFruits(self, frame) : self.__upload_request('detectFruits', frame) def recognizeBussinessCard(self, frame) : self.__upload_request('recognizeBusinessCard', frame) def recognizeVehicleType(self, frame) : self.__upload_request('recognizeVehicle', frame) def detectVehicleCongestion(self, frame) : self.__upload_request('vehicleCongestionDetect', frame) def classifyRubbish(self, frame) : self.__upload_request('classifyingRubbish', frame) def detectObject(self, frame) : self.__upload_request('detectObject', frame)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/fruit_scale/m5stack/code/cloudAI.py
Python
apache-2.0
10,770
from machine import Pin from driver import GPIO import utime class Hx711(object): def __init__(self, clkObj, dataObj): self.clkObj = None self.dataObj = None if not isinstance(clkObj, GPIO): raise ValueError("parameter is not an GPIO object") if not isinstance(dataObj, GPIO): raise ValueError("parameter is not an GPIO object") self.clk = Pin(clkObj.port(), Pin.OUT) self.data = Pin(dataObj.port(), Pin.IN, Pin.PULL_DOWN) def getValue(self): count = 0 self.clk.value(0) while(self.data.value()): utime.sleep_ms(1) for i in range(24): self.clk.value(1) count = count<<1 self.clk.value(0) if(self.data.value()): count += 1 self.clk.value(1) count ^= 0x800000 self.clk.value(0) return count class EleScale(Hx711): # capValue = 429.5是理论值,可通过调整该参数进行校准, # 如果测量值偏大则适当增大capValue,如果测量值偏小则减小该值。 def __init__(self, clkObj, dataObj, capValue = 429.5): Hx711.__init__(self, clkObj, dataObj) self.noLoadOffset = self.__hx711Read(10) self.capValue = capValue def __hx711Read(self, times = 3): # times必须 >= 3 cnt = 3 if (times <= 3) else times if (cnt % 2): cut = cnt // 2 else: cut = (cnt // 2) -1 idx = 0 data = [0] * cnt while (idx < cnt): data[idx] = self.getValue() idx += 1 data.sort() # 取中位数作为结果返回 return round(sum(data[cut:-cut]) / (len(data[cut:-cut]))) def getWeight(self): data = self.__hx711Read(9) - self.noLoadOffset if (data <= 0): weight = 0.0 else: weight = data / self.capValue return weight
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/fruit_scale/m5stack/code/ele_scale.py
Python
apache-2.0
1,971
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- from driver import GPIO from cloudAI import * import display # 显示库 import network # 网络库 import ucamera # 摄像头库 import utime # 延时函数在utime库中 import sntp # 网络时间同步库 import ele_scale # 引入电子秤驱动库 import _thread # 线程库 # 全局变量 disp = None frame = None detected = False fruit = dict() weight_prev = 0.0 fruit_name = None fruit_weight = 0.0 fruit_price = 0.0 # 价格表 unit_price = { "苹果":{"Apple": 5.0}, "香蕉":{"Banana": 3.0}, "橙子":{"Orange": 2.0}, "桃":{"Peach": 3.0} } # 设备实例 clkDev = None dataDev = None scaleDev = None # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 三元组信息 productKey = "产品key" deviceName = "设备名称" deviceSecret = "设备密钥" key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } def connect_wifi(ssid, pwd): global disp # 初始化网络 wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(ssid, pwd) while True: print('Wi-Fi is connecting...') # 显示网络连接中 disp.text(20, 30, 'Wi-Fi is connecting...', disp.RED) # 网络连接成功后,更新显示字符 if (wlan.isconnected() == True): print('Wi-Fi is connected') disp.textClear(20, 30, 'Wi-Fi is connecting...') disp.text(20, 30, 'Wi-Fi is connected', disp.RED) ip = wlan.ifconfig()[0] disp.text(20, 50, ip, disp.RED) print('IP:', ip) break utime.sleep_ms(500) utime.sleep(2) # NTP时间更新,如果更新不成功,将不能进行识别 def ntp_update(): global disp print('NTP update start...') disp.text(20, 70, 'NTP update start...', disp.RED) sntp.setTime() disp.textClear(20, 70, 'NTP update start...') disp.text(20, 70, 'NTP update done', disp.RED) print('NTP update done') # lcd init def lcd_init(): global disp disp = display.TFT() disp.clear() disp.font(disp.FONT_DejaVu18) # 初始化摄像头 def ucamera_init(): ucamera.init('uart', 33, 32) ucamera.setProp(ucamera.SET_FRAME_SIZE, ucamera.SIZE_320X240) # 初始化电子秤设备 def scale_init(): global clkDev, dataDev, scaleDev clkDev = GPIO() clkDev.open("hx711_clk") dataDev = GPIO() dataDev.open("hx711_data") scaleDev = ele_scale.EleScale(clkDev, dataDev, 430.0) # AI识别完成回调函数 def recognize_cb(cmd, result) : global detected, unit_price, fruit detected = False if (cmd == 'detectFruitsReply'): if result != 'NA' : fruit = unit_price[result] detected = True else: print('unknown command reply') # LCD显示线程 def display_th(): global disp, frame, detected, fruit, fruit_name, fruit_weight, fruit_price while True: if frame != None: if detected == True: fruit_name = list(fruit.keys())[0] # 水果价格:xxx元/斤 fruit_price = list(fruit.values())[0] * fruit_weight / 500.0 display_msg0 = "{}: {:.1f}g".format(fruit_name, fruit_weight) display_msg1 = "price: {:.1f}".format(fruit_price) disp.clear() disp.text(40, 80, display_msg0, disp.RED) disp.text(40, 100, display_msg1, disp.RED) utime.sleep(10) else: disp.image(0, 0, frame, 0) utime.sleep_ms(100) def main(): global key_info, frame, detected, wifiSsid, wifiPassword global scaleDev, weight_prev, fruit_weight lcd_init() connect_wifi(wifiSsid, wifiPassword) ntp_update() # 实例化AI引擎 ai_engine = CloudAI(key_info, recognize_cb) ucamera_init() scale_init() try: # 启动显示线程 _thread.start_new_thread(display_th, ()) except: print("Error: unable to start thread") while True: frame = ucamera.capture() weight_cur = scaleDev.getWeight() print("weight_cur:%.1f"%weight_cur) if ((weight_prev < 50) and (weight_cur >= 50)): weight_prev = weight_cur fruit_weight = weight_cur print("fruit_weight:%.1f"%weight_cur) utime.sleep(1) if (frame): ai_engine.detectFruits(frame) elif ((weight_prev >= 50) and (weight_cur < 50)): weight_prev = weight_cur detected = False utime.sleep_ms(100) if __name__ == '__main__': main()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/fruit_scale/m5stack/code/main.py
Python
apache-2.0
4,836
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : cloudAI.py @Description: 云端AI @Author : jiangyu @version : 1.0 ''' from aliyunIoT import Device import utime # 延时函数在utime库中 import ujson as json class CloudAI : def __gesture_cb(self, dict) : ''' Reply list : handGestureReply : 手势识别 ''' gesture = 'NA' if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': score = ext_dict['score'] if score > 0.4 : gesture = ext_dict['type'] print("recognize hand gesture : " + gesture) self.__cb('handGestureReply', gesture) def __license_plate_cb(self, dict) : plateNumber = 'NA' if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': g_confidence = ext_dict['confidence'] if g_confidence > 0.7 : plateNumber = ext_dict['plateNumber'] print('detect: ' + plateNumber) self.__cb('ocrCarNoReply', plateNumber) def __fruits_cb(self, dict) : fruit_name = 'NA' if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': i = 0 fruits_list = ext_dict['fruitList'] while (i < len(fruits_list)) : g_score = fruits_list[i]['score'] fruit_name = fruits_list[i]['name'] if g_score > 0.6: print('detect: ' + fruit_name) i += 1 self.__cb('detectFruitsReply', fruit_name) def __pedestrian_cb(self, dict) : detected = False if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': i = 0 data = ext_dict['data'] data_dict = json.loads(data) elements_list = data_dict['elements'] while (i < len(elements_list)) : g_score = elements_list[i]['score'] if g_score > 0.6: print('Pedestrian Detected') detected = True i += 1 self.__cb('DetectPedestrianReply', detected) def __businesscard_cb(self, dict) : card_info = {} if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': card_info['name'] = ext_dict['name'] print("name : " + card_info['name']) if card_info['name'] == '' : card_info['name'] = 'unknown' phoneNumbers_list = ext_dict['cellPhoneNumbers'] print("phoneNumbers : ") print(phoneNumbers_list) if len(phoneNumbers_list) : card_info['phoneNumbers'] = phoneNumbers_list[0] else : card_info['phoneNumbers'] = 'unknown' email_list = ext_dict['emails'] print("email_list: ") print(email_list) if len(email_list) : card_info['email'] = email_list[0] else : card_info['email'] = 'unknown' self.__cb('recognizeBusinessCardReply', card_info) def __rubblish_cb(self, dict) : name = 'NA' if dict != None: ext = dict['ext'] extDict = json.loads(ext) result = extDict['result'] if result == 'success': i = 0 elements = extDict['elements'] while (i < len(elements)) : gScore = elements[i]['categoryScore'] if gScore > 0.8: name = elements[i]['category'] print('detect: ' + name) break i += 1 self.__cb('classifyingRubbishReply', name) def __object_cb(self, dict) : name = 'NA' if dict != None: ext = dict['ext'] extDict = json.loads(ext) result = extDict['result'] if result == 'success': i = 0 elements = extDict['elements'] while (i < len(elements)) : gScore = elements[i]['score'] if gScore > 0.25: name = elements[i]['type'] print('detect: ' + name) break i += 1 self.__cb('detectObjectReply', name) def __vehicletype_cb(self, dict) : name = 'NA' detect = False if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': i = 0 item_list = ext_dict['items'] name = 'NA' while (i < len(item_list)) : g_score = item_list[i]['score'] name = item_list[i]['name'] # 这里可以修改识别的可信度,目前设置返回可信度大于85%才认为识别正确 if g_score > 0.85 and name != 'others': print('detect: ' + name) detect = True self.__cb('recognizeVehicleReply', name) break i += 1 if detect == False: self.__cb('recognizeVehicleReply', 'NA') def __vehiclelogo_cb(self, dict) : num = 0 if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': item_list = ext_dict['elements'] num = len(item_list) if num > 0: print('detect: ' + str(num) + ' vehicle') detected = True if detected == False: print('do not detect!') self.__cb('recognizeLogoReply', num) def __cb_lk_service(self, data): self.g_lk_service = True print('download <----' + str(data)) if data != None : params = data['params'] params_dict = json.loads(params) command = params_dict['commandName'] if command == 'handGestureReply' : self.__gesture_cb(params_dict) elif command == 'ocrCarNoReply' : self.__license_plate_cb(params_dict) elif command == 'DetectPedestrianReply' : self.__pedestrian_cb(params_dict) elif command == 'detectFruitsReply' : self.__fruits_cb(params_dict) elif command == 'recognizeBusinessCardReply' : self.__businesscard_cb(params_dict) elif command == 'classifyingRubbishReply' : self.__rubblish_cb(params_dict) elif command == 'detectObjectReply' : self.__object_cb(params_dict) elif command == 'recognizeVehicleReply' : self.__vehicletype_cb(params_dict) elif command == 'recognizeLogoReply' : self.__vehiclelogo_cb(params_dict) else : print('unknown command reply') def __cb_lk_connect(self, data): print('link platform connected') self.g_lk_connect = True def __connect_iot(self) : self.device = Device() self.device.on(Device.ON_CONNECT, self.__cb_lk_connect) self.device.on(Device.ON_SERVICE, self.__cb_lk_service) self.device.connect(self.__dev_info) while True: if self.g_lk_connect: break def __init__(self, dev_info, callback) : self.__dev_info = dev_info self.__cb = callback self.g_lk_connect = False self.g_lk_service = False self.__connect_iot() def getDevice(self) : return self.device def __upload_request(self, command, frame) : # 上传图片到LP fileName = 'test.jpg' start = utime.ticks_ms() fileid = self.device.uploadContent(fileName, frame, None) if fileid != None: ext = { 'filePosition':'lp', 'fileName': fileName, 'fileId': fileid } ext_str = json.dumps(ext) all_params = {'id': 1, 'version': '1.0', 'params': { 'eventType': 'haas.faas', 'eventName': command, 'argInt': 1, 'ext': ext_str }} all_params_str = json.dumps(all_params) #print(all_params_str) upload_file = { 'topic': '/sys/' + self.__dev_info['productKey'] + '/' + self.__dev_info['deviceName'] + '/thing/event/hli_event/post', 'qos': 1, 'payload': all_params_str } # 上传完成通知HaaS聚合平台 print('upload--->' + str(upload_file)) self.g_lk_service = False self.device.publish(upload_file) i = 0 while (self.g_lk_service == False and i < 200) : utime.sleep_ms(10) i = i + 1 continue else: print('filedid is none, upload content fail') time_diff = utime.ticks_diff(utime.ticks_ms(), start) print('recognize time : %d' % time_diff) def recognizeGesture(self, frame) : self.__upload_request('handGesture', frame) def recognizeLicensePlate(self, frame) : self.__upload_request('ocrCarNo', frame) def detectPedestrian(self, frame) : self.__upload_request('detectPedestrian', frame) def detectFruits(self, frame) : self.__upload_request('detectFruits', frame) def recognizeBussinessCard(self, frame) : self.__upload_request('recognizeBusinessCard', frame) def recognizeVehicleType(self, frame) : self.__upload_request('recognizeVehicle', frame) def detectVehicleCongestion(self, frame) : self.__upload_request('vehicleCongestionDetect', frame) def classifyRubbish(self, frame) : self.__upload_request('classifyingRubbish', frame) def detectObject(self, frame) : self.__upload_request('detectObject', frame)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/fruits_recognization/esp32/code/cloudAI.py
Python
apache-2.0
10,770
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : main.py @Description: 水果识别案例 @Author : luokui & jiangyu @version : 2.0 ''' import display # 显示库 import network # 网络库 import ucamera # 摄像头库 import utime # 延时函数在utime库中 import sntp # 网络时间同步库 import _thread # 线程库 from cloudAI import * # Wi-Fi SSID和Password设置 SSID='Your-AP-SSID' PWD='Your-AP-Password' # HaaS设备三元组 productKey = "Your-ProductKey" deviceName = "Your-devicename" deviceSecret = "Your-deviceSecret" detected = False fruit_name = '' key_info = { 'region' : 'cn-shanghai' , 'productKey': productKey , 'deviceName': deviceName , 'deviceSecret': deviceSecret , 'keepaliveSec': 60 } def connect_wifi(ssid, pwd): # 引用全局变量 global disp # 初始化网络 wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(ssid, pwd) while True: print('Wi-Fi is connecting...') # 显示网络连接中 disp.text(20, 30, 'Wi-Fi is connecting...', disp.RED) # 网络连接成功后,更新显示字符 if (wlan.isconnected() == True): print('Wi-Fi is connected') disp.textClear(20, 30, 'Wi-Fi is connecting...') disp.text(20, 30, 'Wi-Fi is connected', disp.RED) ip = wlan.ifconfig()[0] print('IP: %s' %ip) disp.text(20, 50, ip, disp.RED) # NTP时间更新,如果更新不成功,将不能进行识别 print('NTP start') disp.text(20, 70, 'NTP start...', disp.RED) sntp.setTime() print('NTP done') disp.textClear(20, 70, 'NTP start...') disp.text(20, 70, 'NTP done', disp.RED) break utime.sleep_ms(500) utime.sleep(2) # 因暂时不支持中文,将识别结果从中文转为英文 def translateName(name): if name == '橙子' or name == '桔子': name = 'Orange' elif name == '苹果': name = 'Apple' elif name == '香蕉': name = 'Banana' else: name = 'Fruits' return name def recognize_cb(commandReply, result) : global detected, fruit_name detected = False if commandReply == 'detectFruitsReply' : if result != 'NA' : fruit_name = translateName(result) detected = True else : print('unknown command reply') # 识别线程函数 def recognizeThread(): global frame while True: if frame != None: engine.detectFruits(frame) utime.sleep_ms(1000) else: utime.sleep_ms(1000) # 显示线程函数 def displayThread(): # 引用全局变量 global disp, frame, detected, gesture # 定义清屏局部变量 clearFlag = False # 定义显示文本局部变量 textShowFlag = False while True: # 采集摄像头画面 # print('start to capture') frame = ucamera.capture() # print('end to capture') if frame != None: if detected == True: # 清除屏幕内容 disp.clear() # 设置文字字体 disp.font(disp.FONT_DejaVu40) # 显示识别结果 disp.text(40, 80, fruit_name, disp.RED) disp.text(40, 120, 'Deteted!!!', disp.RED) utime.sleep_ms(1000) textShowFlag = False else: # 显示图像 # print('start to display') disp.image(0, 20, frame, 0) utime.sleep_ms(100) if textShowFlag == False: # 设置显示字体 disp.font(disp.FONT_DejaVu18) # 显示文字 disp.text(2, 0, 'Recognizing...', disp.WHITE) textShowFlag = True def main(): # 全局变量 global disp, frame, detected, engine # 创建lcd display对象 disp = display.TFT() frame = None detected = False # 连接网络 connect_wifi(SSID, PWD) engine = CloudAI(key_info, recognize_cb) # 初始化摄像头 ucamera.init('uart', 33, 32) ucamera.setProp(ucamera.SET_FRAME_SIZE, ucamera.SIZE_320X240) try: # 启动显示线程 _thread.start_new_thread(displayThread, ()) # 设置比对线程stack _thread.stack_size(20 * 1024) # 启动比对线程 _thread.start_new_thread(recognizeThread, ()) except: print("Error: unable to start thread") while True: utime.sleep_ms(1000) if __name__ == '__main__': main()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/fruits_recognization/esp32/code/main.py
Python
apache-2.0
4,771
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : main.py @Description: 燃气检测和报警灯控制 @Author : ethan.lcz @version : 1.0 ''' from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import utime # 延时API所在组件 import ujson # json字串解析库 from driver import GPIO # LED需使用GPIO进行控制 from driver import ADC # ADC类,通过微处理器的ADC模块读取ADC通道输入电压 import mq2 # 引入MQ2传感器驱动库 import ujson # json库 adcObj = 0 # ADC类型的外设对象 mq2Dev = 0 # MQ2燃气传感器对象 alarmLed = 0 # 报警LED对象 alarmOn = 0 # 记录报警状态 # 物联网平台连接标志位 iot_connected = False # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" wlan = None # 物联网设备实例 device = None # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wlan wifi_connected = False wlan = network.WLAN(network.STA_IF) #创建WLAN对象 wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if not wifi_connected: wlan.active(True) #激活界面 wlan.scan() #扫描接入点 #print("start to connect ", wifiSsid) wlan.connect(wifiSsid, wifiPassword) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) while True: wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected: # Wi-Fi连接成功则退出while循环 break else: utime.sleep(0.5) print("wifi_connected:", wifi_connected) ifconfig = wlan.ifconfig() #获取接口的IP/netmask/gw/DNS地址 print(ifconfig) utime.sleep(0.5) # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): global alarmOn # print(request) # {"alarmLight":1} or {"alarmLight":0} payload = ujson.loads(request['params']) # 获取dict状态字段 注意要验证键存在 否则会抛出异常 if "alarmLight" in payload.keys(): print(payload) alarmOn = payload["alarmLight"] if (alarmOn): print("开始报警") else: print("结束报警") # 根据云端设置的报警灯状态改变本地LED状态 led_control(alarmOn) # 要将更改后的状态同步上报到云平台 data = ujson.dumps({'alarmLight': alarmOn,}) uploadData = { 'params': data } # 上报本地报警灯状态到云端 device.postProps(uploadData) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) def led_control(on): global alarmLed if on == 0: alarmLed.write(0) # GPIO写入0,执行灭灯操作 else: alarmLed.write(1) # GPIO写入 1,执行亮灯报警动作 # 上传燃气传感器检测电压信息和报警信息到物联网平台 def upload_gas_detector_state(): global device, alarmOn, mq2Dev gasVoltage = 0 # 无限循环 while True: gasVoltage = mq2Dev.getVoltage() # 呼叫mq2传感器库提供的getVoltage函数获取电压值,单位:mV data = ujson.dumps({ 'gasVoltage': gasVoltage, 'alarmLight': alarmOn }) # 生成上报到物联网平台的属性值字串,此处的属性标识符"gasVoltage"和"alarmLight"必须和物联网平台的属性一致 # "gasVoltage" - 代表燃气传感器测量到的电压值 # "alarmLight" - 代表报警灯的当前状态 uploadData = {'params': data} # 上传燃气传感器检测电压信息和报警信息到物联网平台 device.postProps(uploadData) # 每2秒钟上报一次 utime.sleep(2) if __name__ == '__main__': # 硬件初始化 # 初始化 ADC adcObj = ADC() # ADC通道对象 adcObj.open("mq2") # 按照board.json中名为"mq2"节点的配置初始化ADC设备对象 mq2Dev = mq2.MQ2(adcObj) # 初始化MQ2设备对象 # 初始化LED所连接GPIO alarmLed = GPIO() alarmLed.open('led') # LED报警灯使用board.json中名为led的节点中定义的GPIO进行控制 led_control(alarmOn) # 关闭报警灯 # 请替换物联网平台申请到的产品和设备信息,可以参考文章:https://blog.csdn.net/HaaSTech/article/details/114360517 # global productKey, deviceName, deviceSecret ,on_request, on_play get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_gas_detector_state() adcObj.close() alarmLed.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/gas_detector/ESP-C3-32S-Kit/code/main.py
Python
apache-2.0
6,231
from driver import ADC class MQ2(object): def __init__(self, adcObj): self.adcObj = None if not isinstance(adcObj, ADC): raise ValueError("parameter is not an ADC object") self.adcObj = adcObj def getVoltage(self): if self.adcObj is None: raise ValueError("invalid ADC object") value = self.adcObj.readVoltage() return value
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/gas_detector/ESP-C3-32S-Kit/code/mq2.py
Python
apache-2.0
426
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : main.py @Description: 燃气检测和报警灯控制 @Author : ethan.lcz @version : 1.0 ''' from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import utime # 延时API所在组件 import ujson # json字串解析库 from driver import GPIO # LED需使用GPIO进行控制 from driver import ADC # ADC类,通过微处理器的ADC模块读取ADC通道输入电压 import mq2 # 引入MQ2传感器驱动库 import ujson # json库 adcObj = 0 # ADC类型的外设对象 mq2Dev = 0 # MQ2燃气传感器对象 alarmLed = 0 # 报警LED对象 alarmOn = 0 # 记录报警状态 # 物联网平台连接标志位 iot_connected = False # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" wlan = None # 物联网设备实例 device = None # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wlan wifi_connected = False wlan = network.WLAN(network.STA_IF) #创建WLAN对象 wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if not wifi_connected: wlan.active(True) #激活界面 wlan.scan() #扫描接入点 #print("start to connect ", wifiSsid) wlan.connect(wifiSsid, wifiPassword) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) while True: wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected: # Wi-Fi连接成功则退出while循环 break else: utime.sleep(0.5) print("wifi_connected:", wifi_connected) ifconfig = wlan.ifconfig() #获取接口的IP/netmask/gw/DNS地址 print(ifconfig) utime.sleep(0.5) # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): global alarmOn # print(request) # {"alarmLight":1} or {"alarmLight":0} payload = ujson.loads(request['params']) # 获取dict状态字段 注意要验证键存在 否则会抛出异常 if "alarmLight" in payload.keys(): print(payload) alarmOn = payload["alarmLight"] if (alarmOn): print("开始报警") else: print("结束报警") # 根据云端设置的报警灯状态改变本地LED状态 led_control(alarmOn) # 要将更改后的状态同步上报到云平台 data = ujson.dumps({'alarmLight': alarmOn,}) uploadData = { 'params': data } # 上报本地报警灯状态到云端 device.postProps(uploadData) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) def led_control(on): global alarmLed if on == 0: alarmLed.write(0) # GPIO写入0,执行灭灯操作 else: alarmLed.write(1) # GPIO写入 1,执行亮灯报警动作 # 上传燃气传感器检测电压信息和报警信息到物联网平台 def upload_gas_detector_state(): global device, alarmOn, mq2Dev gasVoltage = 0 # 无限循环 while True: gasVoltage = mq2Dev.getVoltage() # 呼叫mq2传感器库提供的getVoltage函数获取电压值,单位:mV data = ujson.dumps({ 'gasVoltage': gasVoltage, 'alarmLight': alarmOn }) # 生成上报到物联网平台的属性值字串,此处的属性标识符"gasVoltage"和"alarmLight"必须和物联网平台的属性一致 # "gasVoltage" - 代表燃气传感器测量到的电压值 # "alarmLight" - 代表报警灯的当前状态 uploadData = {'params': data} # 上传燃气传感器检测电压信息和报警信息到物联网平台 device.postProps(uploadData) # 每2秒钟上报一次 utime.sleep(2) if __name__ == '__main__': # 硬件初始化 # 初始化 ADC adcObj = ADC() # ADC通道对象 adcObj.open("mq2") # 按照board.json中名为"mq2"节点的配置初始化ADC设备对象 mq2Dev = mq2.MQ2(adcObj) # 初始化MQ2设备对象 # 初始化LED所连接GPIO alarmLed = GPIO() alarmLed.open('led') # LED报警灯使用board.json中名为led的节点中定义的GPIO进行控制 led_control(alarmOn) # 关闭报警灯 # 请替换物联网平台申请到的产品和设备信息,可以参考文章:https://blog.csdn.net/HaaSTech/article/details/114360517 # global productKey, deviceName, deviceSecret ,on_request, on_play get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_gas_detector_state() adcObj.close() alarmLed.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/gas_detector/ESP-S3-12K-Kit/code/main.py
Python
apache-2.0
6,231
from driver import ADC class MQ2(object): def __init__(self, adcObj): self.adcObj = None if not isinstance(adcObj, ADC): raise ValueError("parameter is not an ADC object") self.adcObj = adcObj def getVoltage(self): if self.adcObj is None: raise ValueError("invalid ADC object") value = self.adcObj.readVoltage() return value
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/gas_detector/ESP-S3-12K-Kit/code/mq2.py
Python
apache-2.0
426
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : main.py @Description: 燃气检测和报警灯控制 @Author : ethan.lcz @version : 1.0 ''' from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import utime # 延时API所在组件 import ujson # json字串解析库 from driver import GPIO # LED需使用GPIO进行控制 from driver import ADC # ADC类,通过微处理器的ADC模块读取ADC通道输入电压 import mq2 # 引入MQ2传感器驱动库 import ujson # json库 adcObj = 0 # ADC类型的外设对象 mq2Dev = 0 # MQ2燃气传感器对象 alarmLed = 0 # 报警LED对象 alarmOn = 0 # 记录报警状态 # 物联网平台连接标志位 iot_connected = False # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" wlan = None # 物联网设备实例 device = None # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wlan wifi_connected = False wlan = network.WLAN(network.STA_IF) #创建WLAN对象 wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if not wifi_connected: wlan.active(True) #激活界面 wlan.scan() #扫描接入点 #print("start to connect ", wifiSsid) wlan.connect(wifiSsid, wifiPassword) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) while True: wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected: # Wi-Fi连接成功则退出while循环 break else: utime.sleep(0.5) print("wifi_connected:", wifi_connected) ifconfig = wlan.ifconfig() #获取接口的IP/netmask/gw/DNS地址 print(ifconfig) utime.sleep(0.5) # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): global alarmOn # print(request) # {"alarmLight":1} or {"alarmLight":0} payload = ujson.loads(request['params']) # 获取dict状态字段 注意要验证键存在 否则会抛出异常 if "alarmLight" in payload.keys(): print(payload) alarmOn = payload["alarmLight"] if (alarmOn): print("开始报警") else: print("结束报警") # 根据云端设置的报警灯状态改变本地LED状态 led_control(alarmOn) # 要将更改后的状态同步上报到云平台 data = ujson.dumps({'alarmLight': alarmOn,}) uploadData = { 'params': data } # 上报本地报警灯状态到云端 device.postProps(uploadData) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) def led_control(on): global alarmLed if on == 0: alarmLed.write(0) # GPIO写入0,执行灭灯操作 else: alarmLed.write(1) # GPIO写入 1,执行亮灯报警动作 # 上传燃气传感器检测电压信息和报警信息到物联网平台 def upload_gas_detector_state(): global device, alarmOn, mq2Dev gasVoltage = 0 # 无限循环 while True: gasVoltage = mq2Dev.getVoltage() # 呼叫mq2传感器库提供的getVoltage函数获取电压值,单位:mV data = ujson.dumps({ 'gasVoltage': gasVoltage, 'alarmLight': alarmOn }) # 生成上报到物联网平台的属性值字串,此处的属性标识符"gasVoltage"和"alarmLight"必须和物联网平台的属性一致 # "gasVoltage" - 代表燃气传感器测量到的电压值 # "alarmLight" - 代表报警灯的当前状态 uploadData = {'params': data} # 上传燃气传感器检测电压信息和报警信息到物联网平台 device.postProps(uploadData) # 每2秒钟上报一次 utime.sleep(2) if __name__ == '__main__': # 硬件初始化 # 初始化 ADC adcObj = ADC() # ADC通道对象 adcObj.open("mq2") # 按照board.json中名为"mq2"节点的配置初始化ADC设备对象 mq2Dev = mq2.MQ2(adcObj) # 初始化MQ2设备对象 # 初始化LED所连接GPIO alarmLed = GPIO() alarmLed.open('led') # LED报警灯使用board.json中名为led的节点中定义的GPIO进行控制 led_control(alarmOn) # 关闭报警灯 # 请替换物联网平台申请到的产品和设备信息,可以参考文章:https://blog.csdn.net/HaaSTech/article/details/114360517 # global productKey, deviceName, deviceSecret ,on_request, on_play get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_gas_detector_state() adcObj.close() alarmLed.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/gas_detector/esp32/code/main.py
Python
apache-2.0
6,231
from driver import ADC class MQ2(object): def __init__(self, adcObj): self.adcObj = None if not isinstance(adcObj, ADC): raise ValueError("parameter is not an ADC object") self.adcObj = adcObj def getVoltage(self): if self.adcObj is None: raise ValueError("invalid ADC object") value = self.adcObj.readVoltage() return value
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/gas_detector/esp32/code/mq2.py
Python
apache-2.0
426
# -*- encoding: utf-8 -*- ''' @File : main.py @Description: 燃气检测和报警灯控制 @Author : victor.wang @version : 1.0 ''' from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import netmgr as nm # Wi-Fi 功能所在库 import utime # 延时API所在组件 import ujson # json字串解析库 from driver import GPIO # LED需使用GPIO进行控制 from driver import ADC # ADC类,通过微处理器的ADC模块读取ADC通道输入电压 import mq2 # 引入MQ2传感器驱动库 import ujson # json库 adcObj = 0 # ADC类型的外设对象 mq2Dev = 0 # MQ2燃气传感器对象 alarmLed = 0 # 报警LED对象 alarmOn = 0 # 记录报警状态 # 物联网平台连接标志位 iot_connected = False # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 物联网设备实例 device = None # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wifiSsid, wifiPassword nm.init() print("start to connect ", wifiSsid) nm.connect(wifiSsid, wifiPassword) while True: wifi_connected = nm.getStatus() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected == 5: # Wi-Fi连接成功则退出while循环 info = nm.getInfo() print("\n") print("wifi 连接成功:") print(" SSID:", info["ssid"]) print(" IP:", info["ip"]) print(" MAC:", info["mac"]) print(" RSSI:", info["rssi"]) break else: print("wifi 连接失败") utime.sleep(0.5) print('sleep for 1s') utime.sleep(1) # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): global alarmOn # print(request) # {"alarmLight":1} or {"alarmLight":0} payload = ujson.loads(request['params']) # 获取dict状态字段 注意要验证键存在 否则会抛出异常 if "alarmLight" in payload.keys(): print(payload) alarmOn = payload["alarmLight"] if (alarmOn): print("开始报警") else: print("结束报警") # 根据云端设置的报警灯状态改变本地LED状态 led_control(alarmOn) # 要将更改后的状态同步上报到云平台 data = ujson.dumps({'alarmLight': alarmOn,}) uploadData = { 'params': data } # 上报本地报警灯状态到云端 device.postProps(uploadData) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) def led_control(on): global alarmLed if on == 0: alarmLed.write(0) # GPIO写入0,执行灭灯操作 else: alarmLed.write(1) # GPIO写入 1,执行亮灯报警动作 # 上传燃气传感器检测电压信息和报警信息到物联网平台 def upload_gas_detector_state(): global device, alarmOn, mq2Dev gasVoltage = 0 # 无限循环 while True: gasVoltage = mq2Dev.getVoltage() # 呼叫mq2传感器库提供的getVoltage函数获取电压值,单位:mV data = ujson.dumps({ 'gasVoltage': gasVoltage, 'alarmLight': alarmOn }) # 生成上报到物联网平台的属性值字串,此处的属性标识符"gasVoltage"和"alarmLight"必须和物联网平台的属性一致 # "gasVoltage" - 代表燃气传感器测量到的电压值 # "alarmLight" - 代表报警灯的当前状态 uploadData = {'params': data} # 上传燃气传感器检测电压信息和报警信息到物联网平台 print("reporting data to cloud: ",data) device.postProps(uploadData) # 每2秒钟上报一次 utime.sleep(2) if __name__ == '__main__': # 硬件初始化 # 初始化 ADC adcObj = ADC() # ADC通道对象 adcObj.open("mq2") # 按照board.json中名为"mq2"节点的配置初始化ADC设备对象 mq2Dev = mq2.MQ2(adcObj) # 初始化MQ2设备对象 # 初始化LED所连接GPIO alarmLed = GPIO() alarmLed.open('led') # LED报警灯使用board.json中名为led的节点中定义的GPIO进行控制 led_control(alarmOn) # 关闭报警灯 # 请替换物联网平台申请到的产品和设备信息,可以参考README.md # global productKey, deviceName, deviceSecret ,on_request, on_play get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_gas_detector_state() adcObj.close() alarmLed.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/gas_detector/haas200/code/main.py
Python
apache-2.0
5,962
from driver import ADC class MQ2(object): def __init__(self, adcObj): self.adcObj = None if not isinstance(adcObj, ADC): raise ValueError("parameter is not an ADC object") self.adcObj = adcObj def getVoltage(self): if self.adcObj is None: raise ValueError("invalid ADC object") value = self.adcObj.readVoltage() return value
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/gas_detector/haas200/code/mq2.py
Python
apache-2.0
410
# coding=utf-8 from driver import ADC from driver import GPIO import network import ujson import utime as time import modem from aliyunIoT import Device import kv #当iot设备连接到物联网平台的时候触发'connect' 事件 def on_connect(data): global module_name,default_ver,productKey,deviceName,deviceSecret,on_trigger,on_download,on_verify,on_upgrade print('***** connect lp succeed****') data_handle = {} data_handle['device_handle'] = device.getDeviceHandle() #当连接断开时,触发'disconnect'事件 def on_disconnect(): print('linkkit is disconnected') #上传报警灯状态 warning_data = {} #当iot云端下发属性设置时,触发'props'事件 def on_props(request): params=request['params'] params=eval(params) warn = params["alarmLight"] warning_data["alarmLight"]= warn warning_data_str=ujson.dumps(warning_data) data1={ 'params':warning_data_str } device.postProps(data1) #当iot云端调用设备service时,触发'service'事件 def on_service(id,request): print('clound req id is {} , req is {}'.format(id,request)) #当设备跟iot平台通信过程中遇到错误时,触发'error'事件 def on_error(err): print('err msg is {} '.format(err)) #网络连接的回调函数 def on_4g_cb(args): global g_connect_status pdp = args[0] netwk_sta = args[1] if netwk_sta == 1: g_connect_status = True else: g_connect_status = False #网络连接 def connect_network(): global net,on_4g_cb,g_connect_status #NetWorkClient该类是一个单例类,实现网络管理相关的功能,包括初始化,联网,状态信息等. net = network.NetWorkClient() g_register_network = False if net._stagecode is not None and net._stagecode == 3 and net._subcode == 1: g_register_network = True else: g_register_network = False if g_register_network: #注册网络连接的回调函数on(self,id,func); 1代表连接,func 回调函数 ;return 0 成功 net.on(1,on_4g_cb) net.connect(None) else: print('网络注册失败') while True: if g_connect_status: print('网络连接成功') break time.sleep_ms(20) #动态注册回调函数 def on_dynreg_cb(data): global deviceSecret,device_dyn_resigter_succed deviceSecret = data device_dyn_resigter_succed = True # 连接物联网平台 def dyn_register_device(productKey,productSecret,deviceName): global on_dynreg_cb,device,deviceSecret,device_dyn_resigter_succed key = '_amp_customer_devicesecret' deviceSecretdict = kv.get(key) print("deviceSecretdict:",deviceSecretdict) if isinstance(deviceSecretdict,str): deviceSecret = deviceSecretdict if deviceSecretdict is None or deviceSecret is None: key_info = { 'productKey': productKey , 'productSecret': productSecret , 'deviceName': deviceName } # 动态注册一个设备,获取设备的deviceSecret #下面的if防止多次注册,当前若是注册过一次了,重启设备再次注册就会卡住, if not device_dyn_resigter_succed: device.register(key_info,on_dynreg_cb) def upload_value(n): global value_data value_data["gasVoltage"]= n value_data_str=ujson.dumps(value_data) data={ 'params':value_data_str } device.postProps(data) if __name__ == '__main__': ICCID=None g_connect_status = False net = None device = None deviceSecret = None deviceName = None #复制产品证书内容替换 productKey = "your-productKey" productSecret = "your-productSecret" device_dyn_resigter_succed = False # 连接网络 connect_network() # 获取设备的IMEI 作为deviceName 进行动态注册 deviceName = modem.info.getDevImei() #获取设备的ICCID ICCID=modem.sim.getIccid() #初始化物联网平台Device类,获取device实例 device = Device() if deviceName is not None and len(deviceName) > 0 : #动态注册一个设备 dyn_register_device(productKey,productSecret,deviceName) else: print("获取设备IMEI失败,无法进行动态注册") while deviceSecret is None: time.sleep(0.2) print('动态注册成功:' + deviceSecret) key_info = { 'region' : 'cn-shanghai' , 'productKey': productKey , 'deviceName': deviceName , 'deviceSecret': deviceSecret , 'keepaliveSec': 60, } #打印设备信息 print(key_info) #device.ON_CONNECT 是事件,on_connect是事件处理函数/回调函数 device.on(device.ON_CONNECT,on_connect) device.on(device.ON_DISCONNECT,on_disconnect) device.on(device.ON_PROPS,on_props) device.on(device.ON_SERVICE,on_service) device.on(device.ON_ERROR,on_error) device.connect(key_info) #主程序 #气体传感器 adc=ADC() adc.open("ADC1") value_data = {} while True: value=adc.readVoltage() print('v:',value) print('--------------------------------------------') upload_value(value) time.sleep(1) adc.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/gas_detector/haas506/code/main.py
Python
apache-2.0
5,335
# -*- encoding: utf-8 -*- ''' @File : main.py @Description: 燃气检测和报警灯控制 @Author : ethan.lcz @version : 1.0 ''' from aliyunIoT import Device # aliyunIoT组件是连接阿里云物联网平台的组件 import utime # 延时API所在组件 import ujson # json字串解析库 from driver import GPIO # 开发板 LED使用GPIO进行控制 from driver import ADC # ADC类,通过微处理器的ADC模块读取ADC通道输入电压 import netmgr as nm # netmgr是Wi-Fi网络连接的组件 import mq2 # 引入MQ2传感器驱动库 import ujson # json库 adcObj = 0 # ADC类型的外设对象 mq2Dev = 0 # MQ2燃气传感器对象 alarmLed = 0 # 报警LED对象 alarmOn = 0 # 记录报警状态 # 物联网平台连接标志位 iot_connected = False # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" wlan = None # 物联网设备实例 device = None # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): nm.init() nm.disconnect() wifi_connected = nm.getStatus() print("start to connect " + wifiSsid) nm.connect(wifiSsid, wifiPassword) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) while True : if wifi_connected == 5: # nm.getStatus()返回5代表连线成功 break else: wifi_connected = nm.getStatus() # 获取Wi-Fi连接路由器的状态信息 utime.sleep(0.5) print("wifi_connected: " + wifi_connected) print("Wi-Fi connected") print('DeviceIP:' + nm.getInfo()['ip']) # 打印Wi-Fi的IP地址信息 # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): global alarmOn # print(request) # {"alarmLight":1} or {"alarmLight":0} payload = ujson.loads(request['params']) # 获取dict状态字段 注意要验证键存在 否则会抛出异常 if "alarmLight" in payload.keys(): print(payload) alarmOn = payload["alarmLight"] if (alarmOn): print("开始报警") else: print("结束报警") # 根据云端设置的报警灯状态改变本地LED状态 led_control(alarmOn) # 要将更改后的状态同步上报到云平台 data = ujson.dumps({'alarmLight': alarmOn,}) uploadData = { 'params': data } # 上报本地报警灯状态到云端 device.postProps(uploadData) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) def led_control(on): global alarmLed if on == 0: alarmLed.write(0) # GPIO写入0,执行灭灯操作 else: alarmLed.write(1) # GPIO写入 1,执行亮灯报警动作 # 上传燃气传感器测量结果和报警灯状态到物联网平台 def upload_gas_detector_state(): global device, alarmOn, mq2Dev gasVoltage = 0 # 无限循环 while True: gasVoltage = mq2Dev.getVoltage() # 呼叫mq2传感器库提供的getVoltage函数获取电压值,单位:mV data = ujson.dumps({ 'gasVoltage': gasVoltage, 'alarmLight': alarmOn }) # 生成上报到物联网平台的属性值字串,此处的属性标识符"gasVoltage"和"alarmLight"必须和物联网平台的属性一致 # "gasVoltage" - 代表燃气传感器测量到的电压值 # "alarmLight" - 代表报警灯的当前状态 print('reporting data to cloud:', data) uploadData = {'params': data} # 上传燃气传感器测量结果和报警灯状态到物联网平台 device.postProps(uploadData) # 每2秒钟上报一次 utime.sleep(2) if __name__ == '__main__': # 硬件初始化 # 初始化 ADC adcObj = ADC() # ADC通道对象 adcObj.open("mq2") # 按照board.json中名为"mq2"节点的配置初始化ADC设备对象 mq2Dev = mq2.MQ2(adcObj) # 初始化MQ2设备对象 # 初始化红色LED所连接GPIO alarmLed = GPIO() alarmLed.open('led') # LED报警灯使用board.json中名为led的节点中定义的GPIO进行控制 led_control(alarmOn) # 关闭报警灯 # 请替换物联网平台申请到的产品和设备信息,可以参考文章:https://blog.csdn.net/HaaSTech/article/details/114360517 # global productKey, deviceName, deviceSecret ,on_request, on_play get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_gas_detector_state() adcObj.close() alarmLed.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/gas_detector/haaseduk1/code/main.py
Python
apache-2.0
5,926
from driver import ADC class MQ2(object): def __init__(self, adcObj): self.adcObj = None if not isinstance(adcObj, ADC): raise ValueError("parameter is not an ADC object") self.adcObj = adcObj def getVoltage(self): if self.adcObj is None: raise ValueError("invalid ADC object") value = self.adcObj.readVoltage() return value
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/gas_detector/haaseduk1/code/mq2.py
Python
apache-2.0
410
# -*- encoding: utf-8 -*- ''' @File : main.py @Description: 燃气检测和报警灯控制 @Author : victor.wang @version : 1.0 ''' from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import netmgr as nm # Wi-Fi 功能所在库 import utime # 延时API所在组件 import ujson # json字串解析库 from driver import GPIO # LED需使用GPIO进行控制 from driver import ADC # ADC类,通过微处理器的ADC模块读取ADC通道输入电压 import mq2 # 引入MQ2传感器驱动库 import ujson # json库 adcObj = 0 # ADC类型的外设对象 mq2Dev = 0 # MQ2燃气传感器对象 alarmLed = 0 # 报警LED对象 alarmOn = 0 # 记录报警状态 # 物联网平台连接标志位 iot_connected = False # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 物联网设备实例 device = None # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wifiSsid, wifiPassword nm.init() print("start to connect ", wifiSsid) nm.connect(wifiSsid, wifiPassword) while True: wifi_connected = nm.getStatus() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected == 5: # Wi-Fi连接成功则退出while循环 info = nm.getInfo() print("\n") print("wifi 连接成功:") print(" SSID:", info["ssid"]) print(" IP:", info["ip"]) print(" MAC:", info["mac"]) print(" RSSI:", info["rssi"]) break else: print("wifi 连接失败") utime.sleep(0.5) print('sleep for 1s') utime.sleep(1) # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): global alarmOn # print(request) # {"alarmLight":1} or {"alarmLight":0} payload = ujson.loads(request['params']) # 获取dict状态字段 注意要验证键存在 否则会抛出异常 if "alarmLight" in payload.keys(): print(payload) alarmOn = payload["alarmLight"] if (alarmOn): print("开始报警") else: print("结束报警") # 根据云端设置的报警灯状态改变本地LED状态 led_control(alarmOn) # 要将更改后的状态同步上报到云平台 data = ujson.dumps({'alarmLight': alarmOn,}) uploadData = { 'params': data } # 上报本地报警灯状态到云端 device.postProps(uploadData) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) def led_control(on): global alarmLed if on == 0: alarmLed.write(0) # GPIO写入0,执行灭灯操作 else: alarmLed.write(1) # GPIO写入 1,执行亮灯报警动作 # 上传燃气传感器检测电压信息和报警信息到物联网平台 def upload_gas_detector_state(): global device, alarmOn, mq2Dev gasVoltage = 0 # 无限循环 while True: gasVoltage = mq2Dev.getVoltage() # 呼叫mq2传感器库提供的getVoltage函数获取电压值,单位:mV data = ujson.dumps({ 'gasVoltage': gasVoltage, 'alarmLight': alarmOn }) # 生成上报到物联网平台的属性值字串,此处的属性标识符"gasVoltage"和"alarmLight"必须和物联网平台的属性一致 # "gasVoltage" - 代表燃气传感器测量到的电压值 # "alarmLight" - 代表报警灯的当前状态 uploadData = {'params': data} # 上传燃气传感器检测电压信息和报警信息到物联网平台 print("reporting data to cloud: ",data) device.postProps(uploadData) # 每2秒钟上报一次 utime.sleep(2) if __name__ == '__main__': # 硬件初始化 # 初始化 ADC adcObj = ADC() # ADC通道对象 adcObj.open("mq2") # 按照board.json中名为"mq2"节点的配置初始化ADC设备对象 mq2Dev = mq2.MQ2(adcObj) # 初始化MQ2设备对象 # 初始化LED所连接GPIO alarmLed = GPIO() alarmLed.open('led') # LED报警灯使用board.json中名为led的节点中定义的GPIO进行控制 led_control(alarmOn) # 关闭报警灯 # 请替换物联网平台申请到的产品和设备信息,可以参考README.md # global productKey, deviceName, deviceSecret ,on_request, on_play get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_gas_detector_state() adcObj.close() alarmLed.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/gas_detector/stm32/code/main.py
Python
apache-2.0
6,140
from driver import ADC class MQ2(object): def __init__(self, adcObj): self.adcObj = None if not isinstance(adcObj, ADC): raise ValueError("parameter is not an ADC object") self.adcObj = adcObj def getVoltage(self): if self.adcObj is None: raise ValueError("invalid ADC object") value = self.adcObj.readVoltage() return value
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/gas_detector/stm32/code/mq2.py
Python
apache-2.0
410
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : cloudAI.py @Description: 云端AI @Author : jiangyu @version : 1.0 ''' from aliyunIoT import Device import utime # 延时函数在utime库中 import ujson as json class CloudAI : def __gesture_cb(self, dict) : ''' Reply list : handGestureReply : 手势识别 ''' gesture = 'NA' if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': score = ext_dict['score'] if score > 0.4 : gesture = ext_dict['type'] print("recognize hand gesture : " + gesture) self.__cb('handGestureReply', gesture) def __license_plate_cb(self, dict) : plateNumber = 'NA' if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': g_confidence = ext_dict['confidence'] if g_confidence > 0.7 : plateNumber = ext_dict['plateNumber'] print('detect: ' + plateNumber) self.__cb('ocrCarNoReply', plateNumber) def __fruits_cb(self, dict) : fruit_name = 'NA' if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': i = 0 fruits_list = ext_dict['fruitList'] while (i < len(fruits_list)) : g_score = fruits_list[i]['score'] fruit_name = fruits_list[i]['name'] if g_score > 0.6: print('detect: ' + fruit_name) i += 1 self.__cb('detectFruitsReply', fruit_name) def __pedestrian_cb(self, dict) : detected = False if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': i = 0 data = ext_dict['data'] data_dict = json.loads(data) elements_list = data_dict['elements'] while (i < len(elements_list)) : g_score = elements_list[i]['score'] if g_score > 0.6: print('Pedestrian Detected') detected = True i += 1 self.__cb('DetectPedestrianReply', detected) def __businesscard_cb(self, dict) : card_info = {} if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': card_info['name'] = ext_dict['name'] print("name : " + card_info['name']) if card_info['name'] == '' : card_info['name'] = 'unknown' phoneNumbers_list = ext_dict['cellPhoneNumbers'] print("phoneNumbers : ") print(phoneNumbers_list) if len(phoneNumbers_list) : card_info['phoneNumbers'] = phoneNumbers_list[0] else : card_info['phoneNumbers'] = 'unknown' email_list = ext_dict['emails'] print("email_list: ") print(email_list) if len(email_list) : card_info['email'] = email_list[0] else : card_info['email'] = 'unknown' self.__cb('recognizeBusinessCardReply', card_info) def __rubblish_cb(self, dict) : name = 'NA' if dict != None: ext = dict['ext'] extDict = json.loads(ext) result = extDict['result'] if result == 'success': i = 0 elements = extDict['elements'] while (i < len(elements)) : gScore = elements[i]['categoryScore'] if gScore > 0.8: name = elements[i]['category'] print('detect: ' + name) break i += 1 self.__cb('classifyingRubbishReply', name) def __object_cb(self, dict) : name = 'NA' if dict != None: ext = dict['ext'] extDict = json.loads(ext) result = extDict['result'] if result == 'success': i = 0 elements = extDict['elements'] while (i < len(elements)) : gScore = elements[i]['score'] if gScore > 0.25: name = elements[i]['type'] print('detect: ' + name) break i += 1 self.__cb('detectObjectReply', name) def __vehicletype_cb(self, dict) : name = 'NA' detect = False if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': i = 0 item_list = ext_dict['items'] name = 'NA' while (i < len(item_list)) : g_score = item_list[i]['score'] name = item_list[i]['name'] # 这里可以修改识别的可信度,目前设置返回可信度大于85%才认为识别正确 if g_score > 0.85 and name != 'others': print('detect: ' + name) detect = True self.__cb('recognizeVehicleReply', name) break i += 1 if detect == False: self.__cb('recognizeVehicleReply', 'NA') def __vehiclelogo_cb(self, dict) : num = 0 if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': item_list = ext_dict['elements'] num = len(item_list) if num > 0: print('detect: ' + str(num) + ' vehicle') detected = True if detected == False: print('do not detect!') self.__cb('recognizeLogoReply', num) def __cb_lk_service(self, data): self.g_lk_service = True print('download <----' + str(data)) if data != None : params = data['params'] params_dict = json.loads(params) command = params_dict['commandName'] if command == 'handGestureReply' : self.__gesture_cb(params_dict) elif command == 'ocrCarNoReply' : self.__license_plate_cb(params_dict) elif command == 'DetectPedestrianReply' : self.__pedestrian_cb(params_dict) elif command == 'detectFruitsReply' : self.__fruits_cb(params_dict) elif command == 'recognizeBusinessCardReply' : self.__businesscard_cb(params_dict) elif command == 'classifyingRubbishReply' : self.__rubblish_cb(params_dict) elif command == 'detectObjectReply' : self.__object_cb(params_dict) elif command == 'recognizeVehicleReply' : self.__vehicletype_cb(params_dict) elif command == 'recognizeLogoReply' : self.__vehiclelogo_cb(params_dict) else : print('unknown command reply') def __cb_lk_connect(self, data): print('link platform connected') self.g_lk_connect = True def __connect_iot(self) : self.device = Device() self.device.on(Device.ON_CONNECT, self.__cb_lk_connect) self.device.on(Device.ON_SERVICE, self.__cb_lk_service) self.device.connect(self.__dev_info) while True: if self.g_lk_connect: break def __init__(self, dev_info, callback) : self.__dev_info = dev_info self.__cb = callback self.g_lk_connect = False self.g_lk_service = False self.__connect_iot() def getDevice(self) : return self.device def __upload_request(self, command, frame) : # 上传图片到LP fileName = 'test.jpg' start = utime.ticks_ms() fileid = self.device.uploadContent(fileName, frame, None) if fileid != None: ext = { 'filePosition':'lp', 'fileName': fileName, 'fileId': fileid } ext_str = json.dumps(ext) all_params = {'id': 1, 'version': '1.0', 'params': { 'eventType': 'haas.faas', 'eventName': command, 'argInt': 1, 'ext': ext_str }} all_params_str = json.dumps(all_params) #print(all_params_str) upload_file = { 'topic': '/sys/' + self.__dev_info['productKey'] + '/' + self.__dev_info['deviceName'] + '/thing/event/hli_event/post', 'qos': 1, 'payload': all_params_str } # 上传完成通知HaaS聚合平台 print('upload--->' + str(upload_file)) self.g_lk_service = False self.device.publish(upload_file) i = 0 while (self.g_lk_service == False and i < 200) : utime.sleep_ms(10) i = i + 1 continue else: print('filedid is none, upload content fail') time_diff = utime.ticks_diff(utime.ticks_ms(), start) print('recognize time : %d' % time_diff) def recognizeGesture(self, frame) : self.__upload_request('handGesture', frame) def recognizeLicensePlate(self, frame) : self.__upload_request('ocrCarNo', frame) def detectPedestrian(self, frame) : self.__upload_request('detectPedestrian', frame) def detectFruits(self, frame) : self.__upload_request('detectFruits', frame) def recognizeBussinessCard(self, frame) : self.__upload_request('recognizeBusinessCard', frame) def recognizeVehicleType(self, frame) : self.__upload_request('recognizeVehicle', frame) def detectVehicleCongestion(self, frame) : self.__upload_request('vehicleCongestionDetect', frame) def classifyRubbish(self, frame) : self.__upload_request('classifyingRubbish', frame) def detectObject(self, frame) : self.__upload_request('detectObject', frame)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/gesture_recognization/m5stack/code/cloudAI.py
Python
apache-2.0
10,770
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : main.py @Description: 静态手势识别案例 @Author : 江遇 @version : 2.0 ''' import display # 显示库 import uai # AI识别库 import network # 网络库 import ucamera # 摄像头库 import utime # 延时函数在utime库中 import _thread # 线程库 import sntp # 网络时间同步库 from cloudAI import * # Wi-Fi SSID和Password设置 SSID='Your-AP-SSID' PWD='Your-AP-Password' # HaaS设备三元组 productKey = "Your-ProductKey" deviceName = "Your-devicename" deviceSecret = "Your-deviceSecret" detected = False gesture = '' key_info = { 'region' : 'cn-shanghai' , 'productKey': productKey , 'deviceName': deviceName , 'deviceSecret': deviceSecret , 'keepaliveSec': 60 } def connect_wifi(ssid, pwd): # 引用全局变量 global disp # 初始化网络 wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(ssid, pwd) while True: print('Wi-Fi is connecting...') # 显示网络连接中 disp.text(20, 30, 'Wi-Fi is connecting...', disp.RED) # 网络连接成功后,更新显示字符 if (wlan.isconnected() == True): print('Wi-Fi is connected') disp.textClear(20, 30, 'Wi-Fi is connecting...') disp.text(20, 30, 'Wi-Fi is connected', disp.RED) ip = wlan.ifconfig()[0] print('IP: %s' %ip) disp.text(20, 50, ip, disp.RED) # NTP时间更新,如果更新不成功,将不能进行识别 print('NTP start') disp.text(20, 70, 'NTP start...', disp.RED) sntp.setTime() print('NTP done') disp.textClear(20, 70, 'NTP start...') disp.text(20, 70, 'NTP done', disp.RED) break utime.sleep_ms(500) utime.sleep(2) def gesture_cb(commandReply, result) : global detected, gesture gesture = 'NA' detected = False if commandReply == 'handGestureReply' : if result != 'NA' : gesture = result detected = True else : print('unknown command reply') # 识别线程函数 def recognizeThread(): global frame while True: if frame != None: engine.recognizeGesture(frame) utime.sleep_ms(1000) else: utime.sleep_ms(1000) # 显示线程函数 def displayThread(): # 引用全局变量 global disp, frame, detected, gesture # 定义清屏局部变量 clearFlag = False # 定义显示文本局部变量 textShowFlag = False while True: # 采集摄像头画面 # print('start to capture') frame = ucamera.capture() # print('end to capture') if frame != None: if detected == True: # 清除屏幕内容 disp.clear() # 设置文字字体 disp.font(disp.FONT_DejaVu40) # 显示识别结果 disp.text(10, 50, 'detect: ' + gesture, disp.RED) utime.sleep_ms(1000) textShowFlag = False else: # 显示图像 # print('start to display') disp.image(0, 20, frame, 0) utime.sleep_ms(100) if textShowFlag == False: # 设置显示字体 disp.font(disp.FONT_DejaVu18) # 显示文字 disp.text(2, 0, 'Recognizing...', disp.WHITE) textShowFlag = True def main(): # 全局变量 global disp, frame, detected, gesture, engine # 创建lcd display对象 disp = display.TFT() frame = None detected = False # 连接网络 connect_wifi(SSID, PWD) engine = CloudAI(key_info, gesture_cb) # 初始化摄像头 ucamera.init('uart', 33, 32) ucamera.setProp(ucamera.SET_FRAME_SIZE, ucamera.SIZE_320X240) try: # 启动显示线程 _thread.start_new_thread(displayThread, ()) # 设置比对线程stack _thread.stack_size(20 * 1024) # 启动比对线程 _thread.start_new_thread(recognizeThread, ()) except: print("Error: unable to start thread") while True: utime.sleep_ms(1000) if __name__ == '__main__': main()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/gesture_recognization/m5stack/code/main.py
Python
apache-2.0
4,442
# coding=utf-8 import network import ujson import utime as time import modem from aliyunIoT import Device import kv global deviceName,g_connect_status,device_dyn_resigter_succed,netw g_connect_status = False netw = None device = None deviceSecret = None device_dyn_resigter_succed = False #初始化物联网平台Device类,获取device实例 device = Device() # 定义升级包的下载和安装路径,其中url,hash_type和hash 会通过服务端推送被保存下来 info = { 'url': '', 'store_path': '/data/pyamp/app.zip', 'install_path': '/data/pyamp/', 'length': 0, 'hash_type': '', 'hash': '' } # 当iot设备连接到物联网平台的时候触发'connect' 事件 def on_connect(data): global module_name,default_ver,productKey,deviceName,deviceSecret,on_trigger,on_download,on_verify,on_upgrade print('***** connect lp succeed****') data_handle = {} data_handle['device_handle'] = device.getDeviceHandle() #当iot云端下发属性设置时,触发'props'事件 def on_props(request): print('clound req data is {}'.format(request)) #当连接断开时,触发'disconnect'事件 def on_disconnect(): print('linkkit is disconnected') #当iot云端调用设备service时,触发'service'事件 def on_service(id,request): print('clound req id is {} , req is {}'.format(id,request)) #当设备跟iot平台通信过程中遇到错误时,触发'error'事件 def on_error(err): print('err msg is {} '.format(err)) #网络连接的回调函数 def on_4g_cb(args): global g_connect_status pdp = args[0] netwk_sta = args[1] if netwk_sta == 1: g_connect_status = True else: g_connect_status = False #网络连接 def connect_network(): global netw,on_4g_cb,g_connect_status netw = network.NetWorkClient() g_register_network = False if netw._stagecode is not None and netw._stagecode == 3 and netw._subcode == 1: g_register_network = True else: g_register_network = False if g_register_network: #注册网络连接的回调函数on(self,id,func); 1代表连接,func 回调函数 ;return 0 成功 netw.on(1,on_4g_cb) netw.connect(None) else: print('网络注册失败') while True: if g_connect_status: print('网络连接成功') break time.sleep_ms(20) #动态注册回调函数 def on_dynreg_cb(data): global deviceSecret,device_dyn_resigter_succed deviceSecret = data device_dyn_resigter_succed = True # 连接物联网平台 def dyn_register_device(productKey,productSecret,deviceName): global on_dynreg_cb,device,deviceSecret,device_dyn_resigter_succed key = '_amp_customer_devicesecret' deviceSecretdict = kv.get(key) print("deviceSecretdict:",deviceSecretdict) if isinstance(deviceSecretdict,str): deviceSecret = deviceSecretdict if deviceSecretdict is None or deviceSecret is None: key_info = { 'productKey': productKey , 'productSecret': productSecret , 'deviceName': deviceName } # 动态注册一个设备,获取设备的deviceSecret #下面的if防止多次注册,当前若是注册过一次了,重启设备再次注册就会卡住, if not device_dyn_resigter_succed: device.register(key_info,on_dynreg_cb) def connect(productKey, productSecret): global deviceName,g_connect_status,device_dyn_resigter_succed deviceName = None # 获取设备的IMEI 作为deviceName 进行动态注册 deviceName = modem.info.getDevImei() # 连接网络 connect_network() if deviceName is not None and len(deviceName) > 0 : #动态注册一个设备 dyn_register_device(productKey,productSecret,deviceName) else: print("获取设备IMEI失败,无法进行动态注册") while deviceSecret is None: time.sleep(0.2) print('动态注册成功:' + deviceSecret) key_info = { 'region' : 'cn-shanghai' , 'productKey': productKey , 'deviceName': deviceName , 'deviceSecret': deviceSecret , 'keepaliveSec': 60, } #打印设备信息 print(key_info) #device.ON_CONNECT 是事件,on_connect是事件处理函数/回调函数 device.on(device.ON_CONNECT,on_connect) device.on(device.ON_DISCONNECT,on_disconnect) device.on(device.ON_PROPS,on_props) device.on(device.ON_SERVICE,on_service) device.on(device.ON_ERROR,on_error) device.connect(key_info) def up_data(d): d_str = ujson.dumps(d) data={ 'params':d_str } device.postProps(data)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/gps_location_and_voicecall/code/aliyun.py
Python
apache-2.0
4,730
# !/usr/bin/python3 # -- coding: utf-8 -- # @Time : 2022/6/13 11:00 AM # @Author : grady from modem import voiceCall from audio import Audio import utime as time from driver import GPIO from driver import UART import aliyun import _thread ############################### # 更改产品信息 productKey = "xxxxxxxx" productSecret = "xxxxxxxx" # 更改电话号码 # 需要发拨打的目标电话号码,长度为11的字符串格式 tele_phone = 'xxxxxxxxxxx' ############################### global flag flag = 0 # 实例化key1 key1 = GPIO(10, 10) key1.open("KEY1") # gbs初始化 gps_module = UART() gps_module.open("serial1") gps_module.setBaudRate(9600) # gps模块的波特率是9600 readBuf = bytearray(512) # 创建一个字节数组,用于接受串口数据 # 按键中断回调函数 def key1_callback(args): global flag, tele_phone if flag == 0: flag = 1 # 拨打电话 print('=== call ===') # 将yourphone改为用户电话号码,文本格式,加'' vc.callStart(tele_phone) time.sleep(1) elif flag == 1: flag = 0 # 挂断电话 print('----callend----') vc.callEnd() else: pass key1.disableIrq() key1.clearIrq() def enable_key(): # 开启中断 key1.enableIrq(key1_callback) # 接听回调 def voice_callback(args): if args[0] == 10: print('voicecall incoming call, PhoneNO.: ', args[6]) elif args[0] == 11: print('voicecall connected, PhoneNO.: ', args[6]) elif args[0] == 12: print('voicecall disconnect') elif args[0] == 13: print('voicecall is waiting, PhoneNO.: ', args[6]) elif args[0] == 14: print('voicecall dialing, PhoneNO.: ', args[6]) elif args[0] == 15: print('voicecall alerting, PhoneNO.: ', args[6]) elif args[0] == 16: print('voicecall holding, PhoneNO.: ', args[6]) # 纬度 def latitude(d, h): if d == "": return 0 hemi = "" if h == "N" else "-" # 度 deg = int(d[0:2]) # 分 min = str(float(d[2:]) / 60)[1:] return hemi + str(deg) + min # 经度 def longitude(d, h): if d == "": return 0 hemi = "" if h == "E" else "-" # 度 deg = int(d[0:3]) # 分 min = str(float(d[3:]) / 60)[1:] return hemi + str(deg) + min location_data = {} def gps(): while True: if flag == 1: # 串口读 size = gps_module.read(readBuf) data = readBuf # print(readBuf) # 将字节数据转化成字符串数据 data_str = data.decode() # 判断是否有数据 且数据中是否包含"$GNRMC" if size != 0 and "$GNRMC" in data_str and "$GNVTG" in data_str: # 删除"\r\n"后,字符串变为列表 data_list = data_str.split('\r\n') for i in range(len(data_list)): if "$GNRMC" in data_list[i]: # print(data_list[i]) # 删除"," result = data_list[i].split(',') # print(result) # $GNRMC,075622.000,A,3116.56922,N,12044.12475,E,0.00,0.00,020422,,,A,V*01 # ['$GNRMC', '075622.000', 'A', '3116.56922', 'N', '12044.12475', 'E', '0.00', '0.00', '020422', '', '', 'A', 'V*01'] # 在GNRMC中取数据 if len(result) == 14: lat = latitude(result[3], result[4]) long = longitude(result[5], result[6]) print("lat:", lat) print("long:", long) location_data['lat'] = lat location_data['long'] = long aliyun.up_data(location_data) else: pass time.sleep(1) if __name__ == '__main__': aliyun.connect(productKey, productSecret) # 连接阿里云 # 拨打电话实例化 vc = voiceCall() ad = Audio() ad.set_pa() # 电话功能需要预先开启功放 ad.setVolume(10) # 设置音量 time.sleep(1) # 设置自动应答 vc.setCallback(voice_callback) # 设置监听回调函数 vc.setAutoAnswer(5000) # 设置自动应答时间 ms print('-----start-----') _thread.start_new_thread(gps, ()) # 开启gps线程 # 打开按键使能 enable_key()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/gps_location_and_voicecall/code/main.py
Python
apache-2.0
4,491
""" Copyright (C) 2015-2021 Alibaba Group Holding Limited """ from driver import I2C import kv class HAASEDUK1(object): def __init__(self): self.i2cDev = None # 获取版本号 # 返回值为1,代表k1c # 返回值为0,代表k1 def getHWID(self): hwId = -1 result = kv.geti("HAASEDU_NAME") if (result != None): if (result == 1): print("HAASEDUK1 hw version is 1.1") return 1 elif (result == 0): print("HAASEDUK1 hw version is 1.0") return 0 else: pass # kv中不存在HAASEDU_NAME键值对,则通过外围传感器进行判断 # 读取QMI8610传感器device identifier register的值 self.i2cDev = I2C() self.i2cDev.open("qmi8610") buf = bytearray(1) buf[0] = 0 self.i2cDev.memRead(buf, 0, 8) # register address:0 - FIS device identifier register address self.i2cDev.close() if buf[0] == 0xfc: hwId = 1 else: # 读取QMI8610传感器chip id register的值 self.i2cDev.open("qmp6988") buf[0] = 0xD1 # chip id register self.i2cDev.write(buf) self.i2cDev.read(buf) self.i2cDev.close() if buf[0] == 0x5C: hwId = 1 else: # 读取QMC6310传感器chip id register的值 self.i2cDev.open("qmc6310") buf[0] = 0x00 # chip id register self.i2cDev.write(buf) self.i2cDev.read(buf) self.i2cDev.close() if buf[0] == 0x80: hwId = 1 if hwId == 1: kv.seti("HAASEDU_NAME", 1) print("HAASEDUK1 hw version is 1.1") return 1 else: kv.seti("HAASEDU_NAME", 0) print("HAASEDUK1 hw version is 1.0") return 0
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/haas_radio/haaseduk1/code/haaseduk1.py
Python
apache-2.0
1,984
import utime import sh1106 from driver import SPI from driver import GPIO from tea5767 import Radio import framebuf from driver import I2C from haaseduk1 import HAASEDUK1 from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import ujson # json字串解析库 board = HAASEDUK1() # 新建HAASEDUK1对象 hwID = board.getHWID() # 获取开发板ID import netmgr as nm # netmgr是Wi-Fi网络连接的组件 import utime muteFlag = 0 searchFlag = 0 oled = None K1 = None K2 = None K3 = None K4 = None radio = None keyEvents = {'K1':False, 'K2':False, 'K3':False, 'K4':False} # 按键K1~K4的初始化 def keyInit(): global K1, K2, K3, K4 K1 = GPIO() K1.open("KEY_1") K1.on(k1Handler) K2 = GPIO() K2.open("KEY_2") K2.on(k2Handler) K3 = GPIO() K3.open("KEY_3") K3.on(k3Handler) K4 = GPIO() K4.open("KEY_4") K4.on(k4Handler) def k1Handler(obj): global radio print('K1 pressed') keyEvents['K1'] = True radio.set_frequency(87.5) def k2Handler(obj): global radio print('K2 pressed') keyEvents['K2'] = True radio.change_freqency(0.1) def k3Handler(obj): global radio print('K3 pressed') keyEvents['K3'] = True radio.search(True, dir=1, adc=5) def k4Handler(obj): global radio print('K4 pressed') keyEvents['K4'] = True radio.change_freqency(-0.1) # 检查是否有按键按下事件处于pending状态 def keyEventsPending(): if all(value == False for value in keyEvents.values()): return False return True # 清除按键事件 def clearKeyEvents(): keyEvents['K1'] = False keyEvents['K2'] = False keyEvents['K3'] = False keyEvents['K4'] = False pass #初始化自带oled屏幕模块 def oled_init(): spi1 = SPI() spi1.open("oled_spi") gpio_dc = GPIO() gpio_dc.open("oled_dc") gpio_res = GPIO() gpio_res.open("oled_res") global oled oled = sh1106.SH1106_SPI(width=132, height=64, spi=spi1, dc = gpio_dc, res = gpio_res) oled.fill(0) #清屏背景黑色 oled.text('HaaS Radio', 30, 5) oled.text('k1:reset k2: +0.1', 2, 22) oled.text('K3:scan k4: -0.1', 2, 42) oled.show() # # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): nm.init() nm.disconnect() wifi_connected = nm.getStatus() # print("start to connect " + wifiSsid) nm.connect('ALIYUN_322219_test', '@AliYun@Iot@123') # 连接到指定的路由器(路由器名称为wifi_ssid, 密码为:wifi_password) while True : if wifi_connected == 5: # nm.getStatus()返回5代表连线成功 break else: wifi_connected = nm.getStatus() # 获取Wi-Fi连接路由器的状态信息 utime.sleep(0.5) # print("wifi_connected: " + wifi_connected) print("Wi-Fi connected") print('DeviceIP:' + nm.getInfo()['ip']) # 打印Wi-Fi的IP地址信息 # 物联网平台连接标志位 iot_connected = False # 物联网设备实例 device = None # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" wlan = None # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): global device global radio, muteFlag, searchFlag print(request) payload = ujson.loads(request['params']) # 获取dict状态字段 注意要验证键存在 否则会抛出异常 if "SearchFrequency" in payload.keys(): print(payload) search = payload["SearchFrequency"] if (search): searchFlag = 1 radio.search(True, dir=1, adc=5) else: searchFlag = 0 if "Mute" in payload.keys(): print(payload) mute = payload["Mute"] if (mute): radio.mute(1) muteFlag = 1 else: radio.mute(0) muteFlag = 0 if "Frequency" in payload.keys(): print(payload) frequency = payload["SetFrequency"] radio.set_frequency(frequency) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) # 上传当前信息到物联网平台 def upload_state(): global device global radio, muteFlag, searchFlag # 上传信息到物联网平台 upload_data = {'params': ujson.dumps({ 'Frequency': radio.frequency, 'ADCLevel': radio.signal_adc_level, 'Mute': muteFlag, 'SearchFrequency': searchFlag }) } device.postProps(upload_data) if __name__ == '__main__': #硬件初始化 oled_init() keyInit() i2cDev = I2C() i2cDev.open("tea5767") radio = Radio(i2cDev) get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) while True: # print('Frequency: FM {}\nReady: {}\nStereo: {}\nADC level: {}'.format( # radio.frequency, radio.is_ready, radio.is_stereo, radio.signal_adc_level # )) oled.fill(0) oled.text('FM: {}'.format(radio.frequency), 20, 5) oled.text('Ready: {}'.format(radio.is_ready), 20, 20) oled.text('Stereo: {}'.format(radio.frequency), 20, 35) oled.text('ADC: {}'.format(radio.signal_adc_level), 20, 50) oled.show() upload_state() utime.sleep(1)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/haas_radio/haaseduk1/code/main.py
Python
apache-2.0
6,592
from micropython import const import utime import framebuf from driver import SPI from driver import GPIO # register definitions SET_SCAN_DIR = const(0xc0) LOW_COLUMN_ADDRESS = const(0x00) HIGH_COLUMN_ADDRESS = const(0x10) SET_PAGE_ADDRESS = const(0xB0) SET_CONTRAST = const(0x81) SET_ENTIRE_ON = const(0xa4) SET_NORM_INV = const(0xa6) SET_DISP = const(0xae) SET_MEM_ADDR = const(0x20) SET_COL_ADDR = const(0x21) SET_PAGE_ADDR = const(0x22) SET_DISP_START_LINE = const(0x40) SET_SEG_REMAP = const(0xa0) SET_MUX_RATIO = const(0xa8) SET_COM_OUT_DIR = const(0xc0) SET_DISP_OFFSET = const(0xd3) SET_COM_PIN_CFG = const(0xda) SET_DISP_CLK_DIV = const(0xd5) SET_PRECHARGE = const(0xd9) SET_VCOM_DESEL = const(0xdb) SET_CHARGE_PUMP = const(0x8d) class SH1106: def __init__(self, width, height): self.width = width self.height = height self.pages = self.height // 8 self.buffer = bytearray(self.pages * self.width) fb = framebuf.FrameBuffer( self.buffer, self.width, self.height, framebuf.MVLSB) self.framebuf = fb # set shortcuts for the methods of framebuf self.fill = fb.fill self.fillRect = fb.fill_rect self.hline = fb.hline self.vline = fb.vline self.line = fb.line self.rect = fb.rect self.pixel = fb.pixel self.scroll = fb.scroll self.text = fb.text self.blit = fb.blit # print("init done") self.initDisplay() def initDisplay(self): self.reset() for cmd in ( SET_DISP | 0x00, # 关闭显示 SET_DISP_CLK_DIV, 0x80, # 设置时钟分频因子 SET_MUX_RATIO, self.height - 1, # 设置驱动路数 路数默认0x3F(1/64) SET_DISP_OFFSET, 0x00, # 设置显示偏移 偏移默认为0 SET_DISP_START_LINE | 0x00, # 设置显示开始行[5:0] SET_CHARGE_PUMP, 0x14, # 电荷泵设置 bit2,开启/关闭 # 设置内存地址模式 [1:0],00,列地址模式;01,行地址模式;10,页地址模式;默认10; SET_MEM_ADDR, 0x02, SET_SEG_REMAP | 0x01, # 段重定义设置,bit0:0,0->0;1,0->127; # 设置COM扫描方向;bit3:0,普通模式;1,重定义模式 COM[N-1]->COM0;N:驱动路数 SET_COM_OUT_DIR | 0x08, SET_COM_PIN_CFG, 0x12, # 设置COM硬件引脚配置 [5:4]配置 SET_PRECHARGE, 0xf1, # 设置预充电周期 [3:0],PHASE 1;[7:4],PHASE 2; # 设置VCOMH 电压倍率 [6:4] 000,0.65*vcc;001,0.77*vcc;011,0.83*vcc; SET_VCOM_DESEL, 0x30, SET_CONTRAST, 0xff, # 对比度设置 默认0x7F(范围1~255,越大越亮) SET_ENTIRE_ON, # 全局显示开启;bit0:1,开启;0,关闭;(白屏/黑屏) SET_NORM_INV, # 设置显示方式;bit0:1,反相显示;0,正常显示 SET_DISP | 0x01): # 开启显示 self.write_cmd(cmd) self.fill(1) self.show() def poweroff(self): self.write_cmd(SET_DISP | 0x00) def poweron(self): self.write_cmd(SET_DISP | 0x01) def rotate(self, flag, update=True): if flag: self.write_cmd(SET_SEG_REMAP | 0x01) # mirror display vertically self.write_cmd(SET_SCAN_DIR | 0x08) # mirror display hor. else: self.write_cmd(SET_SEG_REMAP | 0x00) self.write_cmd(SET_SCAN_DIR | 0x00) if update: self.show() def sleep(self, value): self.write_cmd(SET_DISP | (not value)) def contrast(self, contrast): self.write_cmd(SET_CONTRAST) self.write_cmd(contrast) def invert(self, invert): self.write_cmd(SET_NORM_INV | (invert & 1)) def show(self): for page in range(self.height // 8): self.write_cmd(SET_PAGE_ADDRESS | page) self.write_cmd(LOW_COLUMN_ADDRESS) self.write_cmd(HIGH_COLUMN_ADDRESS) page_buffer = bytearray(self.width) for i in range(self.width): page_buffer[i] = self.buffer[self.width * page + i] self.write_data(page_buffer) def setBuffer(self, buffer): for i in range(len(buffer)): self.buffer[i] = buffer[i] def drawXBM(self, x, y, w, h, bitmap): x_byte = (w//8) + (w % 8 != 0) for nbyte in range(len(bitmap)): for bit in range(8): if(bitmap[nbyte] & (0b10000000 >> bit)): p_x = (nbyte % x_byte)*8+bit p_y = nbyte//x_byte self.pixel(x + p_x, y + p_y, 1) # 以屏幕GRAM的原始制式去填充Buffer def drawBuffer(self, x, y, w, h, bitmap): y_byte = (h//8) + (h % 8 != 0) for nbyte in range(len(bitmap)): for bit in range(8): if(bitmap[nbyte] & (1 << bit)): p_y = (nbyte % y_byte)*8+bit p_x = nbyte//y_byte self.pixel(x + p_x, y + p_y, 1) def fillRect(self, x, y, w, h, c): self.fillRect(x, y, w, h, c) def fillCircle(self, x0, y0, r, c): x = 0 y = r deltax = 3 deltay = 2 - r - r d = 1 - r #print(x) #print(y) #print(deltax) #print(deltay) #print(d) self.pixel(x + x0, y + y0, c) self.pixel(x + x0, -y + y0, c) for i in range(-r + x0, r + x0): self.pixel(i, y0, c) while x < y: if d < 0: d += deltax deltax += 2 x = x +1 else: d += (deltax + deltay) deltax += 2 deltay += 2 x = x +1 y = y -1 for i in range(-x + x0, x + x0): self.pixel(i, -y + y0, c) self.pixel(i, y + y0, c) for i in range(-y + x0, y + x0): self.pixel(i, -x + y0, c) self.pixel(i, x + y0, c) def drawCircle(self, x0, y0, r, w, c): self.fillCircle(x0, y0, r, c) self.fillCircle(x0, y0, r -w, 0) def reset(self, res): if res is not None: res.write(1) utime.sleep_ms(1) res.write(0) utime.sleep_ms(20) res.write(1) utime.sleep_ms(20) class SH1106_I2C(SH1106): def __init__(self, width, height, i2c, res=None, addr=0x3c): self.i2c = i2c self.addr = addr self.res = res self.temp = bytearray(2) super().__init__(width, height) def write_cmd(self, cmd): self.temp[0] = 0x80 # Co=1, D/C#=0 self.temp[1] = cmd self.i2c.write(self.temp) def write_data(self, buf): send_buf = bytearray(1 + len(buf)) send_buf[0] = 0x40 for i in range(len(buf)): send_buf[i+1] = buf[i] print(send_buf) self.i2c.write(send_buf) def reset(self): super().reset(self.res) class SH1106_SPI(SH1106): def __init__(self, width, height, spi, dc, res=None, cs=None): self.spi = spi self.dc = dc self.res = res self.cs = cs super().__init__(width, height) def write_cmd(self, cmd): if self.cs is not None: self.cs.write(1) self.dc.write(0) self.cs.write(0) self.spi.write(bytearray([cmd])) self.cs.write(1) else: self.dc.write(0) self.spi.write(bytearray([cmd])) def write_data(self, buf): if self.cs is not None: self.cs.write(1) self.dc.write(1) self.cs.write(0) self.spi.write(buf) self.cs.write(1) else: self.dc.write(1) self.spi.write(buf) def reset(self): super().reset(self.res)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/haas_radio/haaseduk1/code/sh1106.py
Python
apache-2.0
7,916
import time class Radio: FREQ_RANGE_US = (87.5, 108.0) FREQ_RANGE_JP = (76.0, 91.0) ADC = (0, 5, 7, 10) ADC_BIT = (0, 1, 2, 3) def __init__(self, i2c, freq=0.0, band='US', stereo=True, soft_mute=True, noise_cancel=True, high_cut=True): self._i2c = i2c self.frequency = freq self.band_limits = band self.standby_mode = False self.mute_mode = False self.soft_mute_mode = soft_mute self.search_mode = False self.search_direction = 1 self.search_adc_level = 7 self.stereo_mode = stereo self.stereo_noise_cancelling_mode = noise_cancel self.high_cut_mode = high_cut self.is_ready = False self.is_stereo = False self.signal_adc_level = 0 self.update() def set_frequency(self, freq): self.frequency = freq self.update() def change_freqency(self, change): self.frequency += change self.search_direction = 1 if change >= 0 else 0 self.update() def search(self, mode, dir=1, adc=7): self.search_mode = mode self.search_direction = dir self.search_adc_level = adc if adc in Radio.ADC else 7 self.update() def mute(self, mode): self.mute_mode = mode self.update() def standby(self, mode): self.standby_mode = mode self.update() def read(self): buf = bytearray(5) self._i2c.read(buf) freqB = int((buf[0] & 0x3f) << 8 | buf[1]) self.frequency = round((freqB * 32768 / 4 - 225000) / 1000000, 1) self.is_ready = int(buf[0] >> 7) == 1 self.is_stereo = int(buf[2] >> 7) == 1 self.signal_adc_level = int(buf[3] >> 4) def update(self): if self.band_limits == 'JP': self.frequency = min(max(self.frequency, Radio.FREQ_RANGE_JP[0]), Radio.FREQ_RANGE_JP[1]) else: self.band_limits = 'US' self.frequency = min(max(self.frequency, Radio.FREQ_RANGE_US[0]), Radio.FREQ_RANGE_US[1]) freqB = 4 * (self.frequency * 1000000 + 225000) / 32768 buf = bytearray(5) buf[0] = int(freqB) >> 8 | self.mute_mode << 7 | self.search_mode << 6 buf[1] = int(freqB) & 0xff buf[2] = self.search_direction << 7 | 1 << 4 | self.stereo_mode << 3 try: buf[2] += Radio.ADC_BIT[Radio.ADC.index(self.search_adc_level)] << 5 except: pass buf[3] = self.standby_mode << 6 | (self.band_limits == 'JP') << 5 | 1 << 4 buf[3] += self.soft_mute_mode << 3 | self.high_cut_mode << 2 | self.stereo_noise_cancelling_mode << 1 buf[4] = 0 self._i2c.write(buf) time.sleep_ms(50) self.read()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/haas_radio/haaseduk1/code/tea5767.py
Python
apache-2.0
2,775
from driver import ADC class HCHO(object): def __init__(self, adcObj): self.adcObj = None if not isinstance(adcObj, ADC): raise ValueError("parameter is not an ADC object") self.adcObj = adcObj def getPPM(self): if self.adcObj is None: raise ValueError("invalid ADC object") min = 400 max = 0 value = 0 total = 0 i = 0 for i in range(32): value = self.adcObj.readVoltage() total += value # print(value) if (min >= value): min = value if (max <= value): max = value analogVoltage = (total - min - max) / 30 analogVoltage += 23 analogVoltage /= 1000.0 ppm = 3.125 * analogVoltage - 1.25 #linear relationship(0.4V for 0 ppm and 2V for 5ppm) if ppm < 0 : ppm = 0 return ppm
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/hcho_detector/ESP-C3-32S-Kit/code/hcho.py
Python
apache-2.0
950
# -*- encoding: utf-8 -*- from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import utime # 延时API所在组件 import ujson # json字串解析库 from driver import ADC # ADC类,通过微处理器的ADC模块读取ADC通道输入电压 import hcho # 甲醛hcho传感器类 adcObj = 0 # ADC通道对象 uartObj = 0 # UART通道对象 hchoDev = 0 # 物联网平台连接标志位 iot_connected = False wlan = None # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 三元组信息 productKey = "产品密钥" #需要填入物联网云平台申请到的productKey信息 deviceName = "设备名称" #需要填入物联网云平台申请到的deviceName信息 deviceSecret = "设备密钥" #需要填入物联网云平台申请到的deviceSecret信息 # 物联网设备实例 device = None def hcho_init(): global adcObj,hchoDev global uartObj adcObj = ADC() adcObj.open("hcho") hchoDev = hcho.HCHO(adcObj) def get_hcho_value(): global hchoDev return hchoDev.getPPM() # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wlan wifi_connected = False wlan.active(True) #激活界面 wlan.scan() #扫描接入点 #print("start to connect ", wifiSsid) wlan.connect(wifiSsid, wifiPassword) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) while True: wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected: # Wi-Fi连接成功则退出while循环 break else: utime.sleep(0.5) print("wifi_connected:", wifi_connected) ifconfig = wlan.ifconfig() #获取接口的IP/netmask/gw/DNS地址 print(ifconfig) utime.sleep(0.5) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): pass def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) # 上传甲醛浓度信息到物联网平台 def upload_hcho_detector_state(): global device # 无限循环 while True: data = get_hcho_value() H_str = "Hcho : " + str(round(data,2))+'ppm' print('Hcho :' + str(round(data,2)) +'ppm') # "HCHO" - 代表甲醛传感器测量到的浓度值 upload_data = {'params': ujson.dumps({ 'HCHO': round(data,2), }) } # 上传甲醛浓度信息到物联网平台 device.postProps(upload_data) # 每2秒钟上报一次 utime.sleep(2) if __name__ == '__main__': # 运行此demo之前务必保证模块已经上电5分钟以上 hcho_init() wlan = network.WLAN(network.STA_IF) #创建WLAN对象 # global productKey, deviceName, deviceSecret ,on_request, on_play get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_hcho_detector_state()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/hcho_detector/ESP-C3-32S-Kit/code/main.py
Python
apache-2.0
4,335
from driver import ADC class HCHO(object): def __init__(self, adcObj): self.adcObj = None if not isinstance(adcObj, ADC): raise ValueError("parameter is not an ADC object") self.adcObj = adcObj def getPPM(self): if self.adcObj is None: raise ValueError("invalid ADC object") min = 400 max = 0 value = 0 total = 0 i = 0 for i in range(32): value = self.adcObj.readVoltage() total += value # print(value) if (min >= value): min = value if (max <= value): max = value analogVoltage = (total - min - max) / 30 analogVoltage += 23 analogVoltage /= 1000.0 ppm = 3.125 * analogVoltage - 1.25 #linear relationship(0.4V for 0 ppm and 2V for 5ppm) if ppm < 0 : ppm = 0 return ppm
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/hcho_detector/ESP-S3-12K-Kit/code/hcho.py
Python
apache-2.0
950
# -*- encoding: utf-8 -*- from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import utime # 延时API所在组件 import ujson # json字串解析库 from driver import ADC # ADC类,通过微处理器的ADC模块读取ADC通道输入电压 import hcho # 甲醛hcho传感器类 adcObj = 0 # ADC通道对象 uartObj = 0 # UART通道对象 hchoDev = 0 # 物联网平台连接标志位 iot_connected = False wlan = None # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 三元组信息 productKey = "产品密钥" #需要填入物联网云平台申请到的productKey信息 deviceName = "设备名称" #需要填入物联网云平台申请到的deviceName信息 deviceSecret = "设备密钥" #需要填入物联网云平台申请到的deviceSecret信息 # 物联网设备实例 device = None def hcho_init(): global adcObj,hchoDev global uartObj adcObj = ADC() adcObj.open("hcho") hchoDev = hcho.HCHO(adcObj) def get_hcho_value(): global hchoDev return hchoDev.getPPM() # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wlan wifi_connected = False wlan.active(True) #激活界面 wlan.scan() #扫描接入点 #print("start to connect ", wifiSsid) wlan.connect(wifiSsid, wifiPassword) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) while True: wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected: # Wi-Fi连接成功则退出while循环 break else: utime.sleep(0.5) print("wifi_connected:", wifi_connected) ifconfig = wlan.ifconfig() #获取接口的IP/netmask/gw/DNS地址 print(ifconfig) utime.sleep(0.5) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): pass def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) # 上传甲醛浓度信息到物联网平台 def upload_hcho_detector_state(): global device # 无限循环 while True: data = get_hcho_value() H_str = "Hcho : " + str(round(data,2))+'ppm' print('Hcho :' + str(round(data,2)) +'ppm') # "HCHO" - 代表甲醛传感器测量到的浓度值 upload_data = {'params': ujson.dumps({ 'HCHO': round(data,2), }) } # 上传甲醛浓度信息到物联网平台 device.postProps(upload_data) # 每2秒钟上报一次 utime.sleep(2) if __name__ == '__main__': # 运行此demo之前务必保证模块已经上电5分钟以上 hcho_init() wlan = network.WLAN(network.STA_IF) #创建WLAN对象 # global productKey, deviceName, deviceSecret ,on_request, on_play get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_hcho_detector_state()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/hcho_detector/ESP-S3-12K-Kit/code/main.py
Python
apache-2.0
4,335
from driver import ADC class HCHO(object): def __init__(self, adcObj): self.adcObj = None if not isinstance(adcObj, ADC): raise ValueError("parameter is not an ADC object") self.adcObj = adcObj def getPPM(self): if self.adcObj is None: raise ValueError("invalid ADC object") min = 400 max = 0 value = 0 total = 0 i = 0 for i in range(32): value = self.adcObj.readVoltage() total += value # print(value) if (min >= value): min = value if (max <= value): max = value analogVoltage = (total - min - max) / 30 analogVoltage += 23 analogVoltage /= 1000.0 ppm = 3.125 * analogVoltage - 1.25 #linear relationship(0.4V for 0 ppm and 2V for 5ppm) if ppm < 0 : ppm = 0 return ppm
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/hcho_detector/esp32/code/hcho.py
Python
apache-2.0
950
# -*- encoding: utf-8 -*- from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import utime # 延时API所在组件 import ujson # json字串解析库 from driver import ADC # ADC类,通过微处理器的ADC模块读取ADC通道输入电压 import hcho # 甲醛hcho传感器类 adcObj = 0 # ADC通道对象 uartObj = 0 # UART通道对象 hchoDev = 0 # 物联网平台连接标志位 iot_connected = False wlan = None # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 三元组信息 productKey = "产品密钥" #需要填入物联网云平台申请到的productKey信息 deviceName = "设备名称" #需要填入物联网云平台申请到的deviceName信息 deviceSecret = "设备密钥" #需要填入物联网云平台申请到的deviceSecret信息 # 物联网设备实例 device = None def hcho_init(): global adcObj,hchoDev global uartObj adcObj = ADC() adcObj.open("hcho") hchoDev = hcho.HCHO(adcObj) def get_hcho_value(): global hchoDev return hchoDev.getPPM() # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wlan wifi_connected = False wlan.active(True) #激活界面 wlan.scan() #扫描接入点 #print("start to connect ", wifiSsid) wlan.connect(wifiSsid, wifiPassword) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) while True: wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected: # Wi-Fi连接成功则退出while循环 break else: utime.sleep(0.5) print("wifi_connected:", wifi_connected) ifconfig = wlan.ifconfig() #获取接口的IP/netmask/gw/DNS地址 print(ifconfig) utime.sleep(0.5) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): pass def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) # 上传甲醛浓度信息到物联网平台 def upload_hcho_detector_state(): global device # 无限循环 while True: data = get_hcho_value() H_str = "Hcho : " + str(round(data,2))+'ppm' print('Hcho :' + str(round(data,2)) +'ppm') # "HCHO" - 代表甲醛传感器测量到的浓度值 upload_data = {'params': ujson.dumps({ 'HCHO': round(data,2), }) } # 上传甲醛浓度信息到物联网平台 device.postProps(upload_data) # 每2秒钟上报一次 utime.sleep(2) if __name__ == '__main__': # 运行此demo之前务必保证模块已经上电5分钟以上 hcho_init() wlan = network.WLAN(network.STA_IF) #创建WLAN对象 # 请替换物联网平台申请到的产品和设备信息,可以参考文章:https://blog.csdn.net/HaaSTech/article/details/114360517 # global productKey, deviceName, deviceSecret ,on_request, on_play get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_hcho_detector_state()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/hcho_detector/esp32/code/main.py
Python
apache-2.0
4,475
from driver import ADC class HCHO(object): def __init__(self, adcObj): self.adcObj = None if not isinstance(adcObj, ADC): raise ValueError("parameter is not an ADC object") self.adcObj = adcObj def getPPM(self): if self.adcObj is None: raise ValueError("invalid ADC object") min = 400 max = 0 value = 0 total = 0 i = 0 for i in range(32): value = self.adcObj.readVoltage() total += value # print(value) if (min >= value): min = value if (max <= value): max = value analogVoltage = (total - min - max) / 30 analogVoltage += 23 analogVoltage /= 1000.0 ppm = 3.125 * analogVoltage - 1.25 #linear relationship(0.4V for 0 ppm and 2V for 5ppm) if ppm < 0 : ppm = 0 return ppm
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/hcho_detector/haas200/code/hcho.py
Python
apache-2.0
939
# -*- encoding: utf-8 -*- from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import netmgr as nm # Wi-Fi 功能所在库 import utime # 延时API所在组件 import ujson # json字串解析库 from driver import ADC # ADC类,通过微处理器的ADC模块读取ADC通道输入电压 import hcho # 甲醛hcho传感器类 adcObj = 0 # ADC通道对象 uartObj = 0 # UART通道对象 hchoDev = 0 # 物联网平台连接标志位 iot_connected = False wlan = None # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 三元组信息 productKey = "产品密钥" #需要填入物联网云平台申请到的productKey信息 deviceName = "设备名称" #需要填入物联网云平台申请到的deviceName信息 deviceSecret = "设备密钥" #需要填入物联网云平台申请到的deviceSecret信息 # 物联网设备实例 device = None def hcho_init(): global adcObj,hchoDev global uartObj adcObj = ADC() adcObj.open("hcho") hchoDev = hcho.HCHO(adcObj) def get_hcho_value(): global hchoDev return hchoDev.getPPM() # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wifiSsid, wifiPassword nm.init() print("start to connect ", wifiSsid) nm.connect(wifiSsid, wifiPassword) while True: wifi_connected = nm.getStatus() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected == 5: # Wi-Fi连接成功则退出while循环 info = nm.getInfo() print("\n") print("wifi 连接成功:") print(" SSID:", info["ssid"]) print(" IP:", info["ip"]) print(" MAC:", info["mac"]) print(" RSSI:", info["rssi"]) break else: print("wifi 连接失败") utime.sleep(0.5) print('sleep for 1s') utime.sleep(1) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): pass def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) # 上传甲醛浓度信息到物联网平台 def upload_hcho_detector_state(): global device # 无限循环 while True: data = get_hcho_value() H_str = "Hcho : " + str(round(data,2))+'ppm' print('Hcho :' + str(round(data,2)) +'ppm') # "HCHO" - 代表甲醛传感器测量到的浓度值 upload_data = {'params': ujson.dumps({ 'HCHO': round(data,2), }) } # 上传甲醛浓度信息到物联网平台 device.postProps(upload_data) # 每2秒钟上报一次 utime.sleep(2) if __name__ == '__main__': # 运行此demo之前务必保证模块已经上电5分钟以上 hcho_init() get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_hcho_detector_state()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/hcho_detector/haas200/code/main.py
Python
apache-2.0
4,159
# coding=utf-8 import network import ujson import utime as time import modem from aliyunIoT import Device import kv from driver import UART #当iot设备连接到物联网平台的时候触发'connect' 事件 def on_connect(data): global module_name,default_ver,productKey,deviceName,deviceSecret,on_trigger,on_download,on_verify,on_upgrade print('***** connect lp succeed****') data_handle = {} data_handle['device_handle'] = device.getDeviceHandle() #当连接断开时,触发'disconnect'事件 def on_disconnect(): print('linkkit is disconnected') #当iot云端下发属性设置时,触发'props'事件 def on_props(request): print('clound req data is {}'.format(request)) #当iot云端调用设备service时,触发'service'事件 def on_service(id,request): print('clound req id is {} , req is {}'.format(id,request)) #当设备跟iot平台通信过程中遇到错误时,触发'error'事件 def on_error(err): print('err msg is {} '.format(err)) #网络连接的回调函数 def on_4g_cb(args): global g_connect_status pdp = args[0] netwk_sta = args[1] if netwk_sta == 1: g_connect_status = True else: g_connect_status = False #网络连接 def connect_network(): global net,on_4g_cb,g_connect_status #NetWorkClient该类是一个单例类,实现网络管理相关的功能,包括初始化,联网,状态信息等. net = network.NetWorkClient() g_register_network = False if net._stagecode is not None and net._stagecode == 3 and net._subcode == 1: g_register_network = True else: g_register_network = False if g_register_network: #注册网络连接的回调函数on(self,id,func); 1代表连接,func 回调函数 ;return 0 成功 net.on(1,on_4g_cb) net.connect(None) else: print('网络注册失败') while True: if g_connect_status: print('网络连接成功') break time.sleep_ms(20) #动态注册回调函数 def on_dynreg_cb(data): global deviceSecret,device_dyn_resigter_succed deviceSecret = data device_dyn_resigter_succed = True # 连接物联网平台 def dyn_register_device(productKey,productSecret,deviceName): global on_dynreg_cb,device,deviceSecret,device_dyn_resigter_succed key = '_amp_customer_devicesecret' deviceSecretdict = kv.get(key) print("deviceSecretdict:",deviceSecretdict) if isinstance(deviceSecretdict,str): deviceSecret = deviceSecretdict if deviceSecretdict is None or deviceSecret is None: key_info = { 'productKey': productKey , 'productSecret': productSecret , 'deviceName': deviceName } # 动态注册一个设备,获取设备的deviceSecret #下面的if防止多次注册,当前若是注册过一次了,重启设备再次注册就会卡住, if not device_dyn_resigter_succed: device.register(key_info,on_dynreg_cb) PPM_data = {} def upload_PPM(): global PPM_data,PPM PPM_data["hcho"]= PPM PPM_data_str=ujson.dumps(PPM_data) data={ 'params':PPM_data_str } device.postProps(data) if __name__ == '__main__': ICCID=None g_connect_status = False net = None device = None deviceSecret = None deviceName = None #复制产品证书内容替换 productKey = "your-productKey" productSecret = "your-productSecret" device_dyn_resigter_succed = False # 连接网络 connect_network() # 获取设备的IMEI 作为deviceName 进行动态注册 deviceName = modem.info.getDevImei() #获取设备的ICCID ICCID=modem.sim.getIccid() #初始化物联网平台Device类,获取device实例 device = Device() if deviceName is not None and len(deviceName) > 0 : #动态注册一个设备 dyn_register_device(productKey,productSecret,deviceName) else: print("获取设备IMEI失败,无法进行动态注册") while deviceSecret is None: time.sleep(0.2) print('动态注册成功:' + deviceSecret) key_info = { 'region' : 'cn-shanghai' , 'productKey': productKey , 'deviceName': deviceName , 'deviceSecret': deviceSecret , 'keepaliveSec': 60, } #打印设备信息 print(key_info) #device.ON_CONNECT 是事件,on_connect是事件处理函数/回调函数 device.on(device.ON_CONNECT,on_connect) device.on(device.ON_DISCONNECT,on_disconnect) device.on(device.ON_PROPS,on_props) device.on(device.ON_SERVICE,on_service) device.on(device.ON_ERROR,on_error) device.connect(key_info) #主程序 time.sleep(2) #UART初始化 uart1=UART() uart1.open("serial1") readBuf=bytearray(9) writeBuf=bytearray(9) writeBuf = bytearray([0xFF,0x01,0x78,0x40,0x00,0x00,0x00,0x00,0x47]) uart1.write(writeBuf) while True: #读取传感器数据并上传 readSize=uart1.read(readBuf) print(readBuf) PPM = (int(readBuf[4])*256+int(readBuf[5]))/1000 print(PPM) upload_PPM() time.sleep(1)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/hcho_detector/haas506/code/main.py
Python
apache-2.0
5,247
from driver import ADC class HCHO(object): def __init__(self, adcObj): self.adcObj = None if not isinstance(adcObj, ADC): raise ValueError("parameter is not an ADC object") self.adcObj = adcObj def getPPM(self): if self.adcObj is None: raise ValueError("invalid ADC object") min = 400 max = 0 value = 0 total = 0 i = 0 for i in range(32): value = self.adcObj.readVoltage() total += value # print(value) if (min >= value): min = value if (max <= value): max = value analogVoltage = (total - min - max) / 30 analogVoltage += 23 analogVoltage /= 1000.0 #linear relationship(0.4V for 0 ppm and 2V for 5ppm) ppm = 3.125 * analogVoltage - 1.25 if ppm < 0 : ppm = 0 return ppm
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/hcho_detector/haaseduk1/code/hcho.py
Python
apache-2.0
946
# -*- encoding: utf-8 -*- from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import netmgr as nm # Wi-Fi功能所在库 import utime # 延时API所在组件 import ujson # json字串解析库 from driver import ADC # ADC类,通过微处理器的ADC模块读取ADC通道输入电压 import hcho # 甲醛hcho传感器类 adcObj = 0 # ADC通道对象 uartObj = 0 # UART通道对象 # 物联网平台连接标志位 iot_connected = False # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 三元组信息 productKey = "产品密钥" #需要填入物联网云平台申请到的productKey信息 deviceName = "设备名称" #需要填入物联网云平台申请到的deviceName信息 deviceSecret = "设备密钥" #需要填入物联网云平台申请到的deviceSecret信息 # 物联网设备实例 device = None hchoDev = 0 def hcho_init(): global adcObj,hchoDev adcObj = ADC() adcObj.open("hcho") hchoDev = hcho.HCHO(adcObj) def get_hcho_value(): global hchoDev return hchoDev.getPPM() # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): nm.init() nm.disconnect() wifi_connected = nm.getStatus() print("start to connect " , wifiSsid) nm.connect(wifiSsid, wifiPassword) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) while True : if wifi_connected == 5: # nm.getStatus()返回5代表连线成功 break else: wifi_connected = nm.getStatus() # 获取Wi-Fi连接路由器的状态信息 utime.sleep(0.5) print("wifi_connected: " , wifi_connected) print("Wi-Fi connected") print('DeviceIP:' + nm.getInfo()['ip']) # 打印Wi-Fi的IP地址信息 # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): pass # 连接物联网平台 def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 ret = device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) # 上传甲醛浓度信息到物联网平台 def upload_hcho_detector_state(): global device # 无限循环 while True: data = get_hcho_value() H_str = "Hcho : " + str(round(data,2))+'ppm' print('Hcho :' + str(round(data,2)) +'ppm') # "HCHO" - 代表甲醛传感器测量到的浓度值 upload_data = {'params': ujson.dumps({ 'HCHO': round(data,2), })} # 上传甲醛浓度信息到物联网平台 device.postProps(upload_data) # 每2秒钟上报一次 utime.sleep(2) if __name__ == '__main__': # 运行此demo之前务必保证模块已经上电5分钟以上 hcho_init() # 请替换物联网平台申请到的产品和设备信息,可以参考文章:https://blog.csdn.net/HaaSTech/article/details/114360517 # global productKey, deviceName, deviceSecret ,on_request, on_play get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_hcho_detector_state()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/hcho_detector/haaseduk1/code/main.py
Python
apache-2.0
4,234
from driver import ADC class HCHO(object): def __init__(self, adcObj): self.adcObj = None if not isinstance(adcObj, ADC): raise ValueError("parameter is not an ADC object") self.adcObj = adcObj def getPPM(self): if self.adcObj is None: raise ValueError("invalid ADC object") min = 400 max = 0 value = 0 total = 0 i = 0 for i in range(32): value = self.adcObj.readVoltage() total += value # print(value) if (min >= value): min = value if (max <= value): max = value analogVoltage = (total - min - max) / 30 analogVoltage += 23 analogVoltage /= 1000.0 ppm = 3.125 * analogVoltage - 1.25 #linear relationship(0.4V for 0 ppm and 2V for 5ppm) if ppm < 0 : ppm = 0 return ppm
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/hcho_detector/stm32/code/hcho.py
Python
apache-2.0
939
# -*- encoding: utf-8 -*- from ulinksdk.aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import utime # 延时API所在组件 import ujson # json字串解析库 from driver import ADC # ADC类,通过微处理器的ADC模块读取ADC通道输入电压 import hcho # 甲醛hcho传感器类 adcObj = 0 # ADC通道对象 uartObj = 0 # UART通道对象 hchoDev = 0 # 物联网平台连接标志位 iot_connected = False wlan = None # 三元组信息 productKey = "产品密钥" deviceName = "设备名字" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 物联网设备实例 device = None def hcho_init(): global adcObj,hchoDev global uartObj adcObj = ADC() adcObj.open("hcho") hchoDev = hcho.HCHO(adcObj) def get_hcho_value(): global hchoDev return hchoDev.getPPM() # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wlan wifi_connected = False wlan.active(True) #激活界面 wlan.scan() #扫描接入点 #print("start to connect ", wifiSsid) wlan.connect(wifiSsid, wifiPassword) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) while True: wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected: # Wi-Fi连接成功则退出while循环 break else: utime.sleep(0.5) print("wifi_connected:", wifi_connected) ifconfig = wlan.ifconfig() #获取接口的IP/netmask/gw/DNS地址 print(ifconfig) utime.sleep(0.5) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): pass def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) # 上传甲醛浓度信息到物联网平台 def upload_hcho_detector_state(): global device # 无限循环 while True: data = get_hcho_value() H_str = "Hcho : " + str(round(data,2))+'ppm' print('Hcho :' + str(round(data,2)) +'ppm') # "HCHO" - 代表甲醛传感器测量到的浓度值 upload_data = {'params': ujson.dumps({ "HCHO": round(data,2) }) } # 上传甲醛浓度信息到物联网平台 device.postProps(upload_data) #print(upload_data) # 每2秒钟上报一次 utime.sleep(2) if __name__ == '__main__': # 运行此demo之前务必保证模块已经上电5分钟以上 hcho_init() #wlan = network.WLAN(network.STA_IF) #创建WLAN对象 # global productKey, deviceName, deviceSecret ,on_request, on_play #get_wifi_status() ##联网 nic = network.LAN() nic.active(1) connect_lk(productKey, deviceName, deviceSecret) upload_hcho_detector_state()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/hcho_detector/stm32/code/main.py
Python
apache-2.0
4,243
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : bodyCalculator.py @Description: bmi身体数据计算 @Author : aoyi @version : 1.0 ''' MALE = 1 FEMALE = 2 ACTIVITY_SEDENTARY = 1 ACTIVITY_MILD_INTENSITY = 2 ACTIVITY_MIDDLE_INTENSITY = 3 ACTIVITY_HIGH_INTENSITY = 4 ACTIVITY_HEAVY_PHYSICAL_LABOR = 5 BMI_UNDERWEIGHT = 18.5 BMI_NORMAL = 24 BMI_OVERWEIGHT = 27 class BodyCalculator : def __init__(self) : self.height = 1#避免bmi计算时,除0错误 self.weight = 0 self.age = 0 self.gender = 0 self.activity_intensity = 0 self.bmi = 0 self.bmr = 0 self.tdee = 0 def set_height(self, height): if height > 0: self.height = height / 100 def set_weight(self, weight): if weight > 0: self.weight = weight def set_age(self, age): if age > 0: self.age = age def set_gender(self, gender): if gender > 0 and gender < 3: self.gender = gender def set_activity_intensity(self, activity_intensity): if activity_intensity >= ACTIVITY_SEDENTARY and activity_intensity <= ACTIVITY_HEAVY_PHYSICAL_LABOR: self.activity_intensity = activity_intensity def calc_body_data(self): if ACTIVITY_SEDENTARY == self.activity_intensity: multi_factor = 1.2 elif ACTIVITY_MILD_INTENSITY == self.activity_intensity: multi_factor = 1.375 elif ACTIVITY_MIDDLE_INTENSITY == self.activity_intensity: multi_factor = 1.55 elif ACTIVITY_HIGH_INTENSITY == self.activity_intensity: multi_factor = 1.725 elif ACTIVITY_HEAVY_PHYSICAL_LABOR == self.activity_intensity: multi_factor = 1.9 else: multi_factor = 1 if MALE == self.gender: self.bmr = (10 * self.weight) + (6.25 * self.height * 100) - (5 * self.age) + 5 elif FEMALE == self.gender: self.bmr = (10 * self.weight) + (6.25 * self.height * 100) - (5 * self.age) - 161 else: print('gender illegeal') self.bmr = round(self.bmr, 2) self.tdee = round(self.bmr * multi_factor, 2) self.bmi = round(self.weight / (self.height * self.height), 2) print('height:' + str(self.height) + ' weight:' + str(self.weight) + ' bmi :' + str(self.bmi) + ' bmr :' + str(self.bmr)+ ' tdee :' + str(self.tdee)) def set_body_data(self, data): if 'Height' in data.keys(): self.set_height(data['Height']) if 'Weight' in data.keys(): self.set_weight(data['Weight']) if 'Age' in data.keys(): self.set_age(data['Age']) if 'Gender' in data.keys(): self.set_gender(data['Gender']) if 'Activity_intensity' in data.keys(): self.set_activity_intensity(data['Activity_intensity']) self.calc_body_data() def generate_diet_suggestion(self, total_food_calorie): if 0 == self.bmi or 0 == self.bmr or 0 == self.tdee: suggest_str = '信息不全,请补充' else: if self.bmi > 0 and self.bmi < BMI_UNDERWEIGHT : suggest_str = 'bmi = ' + str(self.bmi) + ',体重过轻,请增加每日饮食摄入。\n建议每日摄入大于' + str(self.tdee + 500) + '卡路里,今日已摄入'+ str(total_food_calorie) + '卡路里' elif self.bmi > BMI_UNDERWEIGHT and self.bmi < BMI_NORMAL: suggest_str = 'bmi = ' + str(self.bmi) + ', 正常,请保持,建议每日摄入' + str(self.tdee - 500) + '卡路里。\n今日已摄入'+ str(total_food_calorie) + '卡路里' elif self.bmi > BMI_NORMAL and self.bmi < BMI_OVERWEIGHT: suggest_str = 'bmi = ' + str(self.bmi) + ', 处于超重范围,需要减少摄入。\n建议每日摄入小于' + str(self.tdee - 500) + '卡路里。今日已摄入'+ str(total_food_calorie) + '卡路里' elif self.bmi > BMI_OVERWEIGHT: suggest_str = 'bmi = ' + str(self.bmi) + ', 处于肥胖范围,需要减少摄入。\n建议每日摄入小于' + str(self.tdee - 1000) + '卡路里。今日已摄入'+ str(total_food_calorie) + '卡路里' else: suggest_str = '信息不全,请补充' print('生成的饮食建议' + suggest_str) return suggest_str def get_body_bmi(self): return self.bmi
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/health_management/m5stack/code/bodyCalculator.py
Python
apache-2.0
4,471
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : cloudAI.py @Description: 云端AI @Author : jiangyu @version : 1.0 ''' from aliyunIoT import Device import utime # 延时函数在utime库中 import ujson as json class CloudAI : def __gesture_cb(self, dict) : ''' Reply list : handGestureReply : 手势识别 ''' gesture = 'NA' if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': score = ext_dict['score'] if score > 0.4 : gesture = ext_dict['type'] print("recognize hand gesture : " + gesture) self.__cb('handGestureReply', gesture) def __action_cb(self, dict) : ''' Reply list : actionReply : 动作识别 ''' action = 'NA' if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) i = 0 elements_list = ext_dict['elements'] while (i < len(elements_list)) : g_score = elements_list[i]['score'] label = elements_list[i]['label'] if g_score > 0.5: print("recognize action: " + label) action = label break i += 1 self.__cb('recognizeActionReply', action) def __license_plate_cb(self, dict) : plateNumber = 'NA' if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': g_confidence = ext_dict['confidence'] if g_confidence > 0.7 : plateNumber = ext_dict['plateNumber'] print('detect: ' + plateNumber) self.__cb('ocrCarNoReply', plateNumber) def __fruits_cb(self, dict) : fruit_name = 'NA' if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': i = 0 fruits_list = ext_dict['fruitList'] while (i < len(fruits_list)) : g_score = fruits_list[i]['score'] fruit_name = fruits_list[i]['name'] if g_score > 0.6: print('detect: ' + fruit_name) i += 1 self.__cb('detectFruitsReply', fruit_name) def __pedestrian_cb(self, dict) : detected = False if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': i = 0 data = ext_dict['data'] data_dict = json.loads(data) elements_list = data_dict['elements'] while (i < len(elements_list)) : g_score = elements_list[i]['score'] if g_score > 0.6: print('Pedestrian Detected') detected = True i += 1 self.__cb('DetectPedestrianReply', detected) def __businesscard_cb(self, dict) : card_info = {} if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': card_info['name'] = ext_dict['name'] print("name : " + card_info['name']) if card_info['name'] == '' : card_info['name'] = 'unknown' phoneNumbers_list = ext_dict['cellPhoneNumbers'] print("phoneNumbers : ") print(phoneNumbers_list) if len(phoneNumbers_list) : card_info['phoneNumbers'] = phoneNumbers_list[0] else : card_info['phoneNumbers'] = 'unknown' email_list = ext_dict['emails'] print("email_list: ") print(email_list) if len(email_list) : card_info['email'] = email_list[0] else : card_info['email'] = 'unknown' self.__cb('recognizeBusinessCardReply', card_info) def __rubblish_cb(self, dict) : name = 'NA' if dict != None: ext = dict['ext'] extDict = json.loads(ext) result = extDict['result'] if result == 'success': i = 0 elements = extDict['elements'] while (i < len(elements)) : gScore = elements[i]['categoryScore'] if gScore > 0.8: name = elements[i]['category'] print('detect: ' + name) break i += 1 self.__cb('classifyingRubbishReply', name) def __object_cb(self, dict) : name = 'NA' if dict != None: ext = dict['ext'] extDict = json.loads(ext) result = extDict['result'] if result == 'success': i = 0 elements = extDict['elements'] while (i < len(elements)) : gScore = elements[i]['score'] if gScore > 0.25: name = elements[i]['type'] print('detect: ' + name) break i += 1 self.__cb('detectObjectReply', name) def __vehicletype_cb(self, dict) : name = 'NA' detect = False if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': i = 0 item_list = ext_dict['items'] name = 'NA' while (i < len(item_list)) : g_score = item_list[i]['score'] name = item_list[i]['name'] # 这里可以修改识别的可信度,目前设置返回可信度大于85%才认为识别正确 if g_score > 0.85 and name != 'others': print('detect: ' + name) detect = True self.__cb('recognizeVehicleReply', name) break i += 1 if detect == False: self.__cb('recognizeVehicleReply', 'NA') def __vehiclelogo_cb(self, dict) : num = 0 if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': item_list = ext_dict['elements'] num = len(item_list) if num > 0: print('detect: ' + str(num) + ' vehicle') detected = True if detected == False: print('do not detect!') self.__cb('recognizeLogoReply', num) def __food_cb(self, dict) : name = 'NA' detect = False if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': i = 0 item_list = ext_dict['elements'] name = 'NA' while (i < len(item_list)) : g_score = item_list[i]['score'] name = item_list[i]['category'] calorie = item_list[i]['calorie'] print('detect: ' + name + ' calorie:' + calorie + ' score: ' + str(g_score)) # 这里可以修改识别的可信度,目前设置返回可信度大于85%才认为识别正确 if name != '其他类': print('detect: ' + name + ' calorie:' + calorie) detect = True self.__cb('recognizeFoodReply', name, calorie) break i += 1 if detect == False: self.__cb('recognizeFoodReply', 'NA', '0') def __cb_lk_service(self, data): self.g_lk_service = True print('download <----' + str(data)) if data != None : params = data['params'] params_dict = json.loads(params) command = params_dict['commandName'] if command == 'handGestureReply' : self.__gesture_cb(params_dict) elif command == 'recognizeActionReply' : self.__action_cb(params_dict) elif command == 'ocrCarNoReply' : self.__license_plate_cb(params_dict) elif command == 'DetectPedestrianReply' : self.__pedestrian_cb(params_dict) elif command == 'detectFruitsReply' : self.__fruits_cb(params_dict) elif command == 'recognizeBusinessCardReply' : self.__businesscard_cb(params_dict) elif command == 'classifyingRubbishReply' : self.__rubblish_cb(params_dict) elif command == 'detectObjectReply' : self.__object_cb(params_dict) elif command == 'recognizeVehicleReply' : self.__vehicletype_cb(params_dict) elif command == 'recognizeLogoReply' : self.__vehiclelogo_cb(params_dict) elif command == 'recognizeFoodReply' : self.__food_cb(params_dict) else : print('unknown command reply') def __cb_lk_connect(self, data): print('link platform connected') self.g_lk_connect = True # 接收云端下发的属性设置 def __on_props(self, request): try: props = eval(request['params']) print("on recv props : " + str(props)) self.__cb('on_props', props, 0) except Exception as e: print(e) def __connect_iot(self) : self.device = Device() self.device.on(Device.ON_CONNECT, self.__cb_lk_connect) self.device.on(Device.ON_SERVICE, self.__cb_lk_service) self.device.on(Device.ON_PROPS, self.__on_props) self.device.connect(self.__dev_info) while True: if self.g_lk_connect: break def __init__(self, dev_info, callback) : self.__dev_info = dev_info self.__cb = callback self.g_lk_connect = False self.g_lk_service = False self.__connect_iot() def getDevice(self) : return self.device def __upload_request(self, command, frame, enlarge = 1) : # 上传图片到LP fileName = 'test.jpg' start = utime.ticks_ms() fileid = self.device.uploadContent(fileName, frame, None) if fileid != None: ext = { 'filePosition':'lp', 'fileName': fileName, 'fileId': fileid, 'enlarge':enlarge} ext_str = json.dumps(ext) all_params = {'id': 1, 'version': '1.0', 'params': { 'eventType': 'haas.faas', 'eventName': command, 'argInt': 1, 'ext': ext_str }} all_params_str = json.dumps(all_params) #print(all_params_str) upload_file = { 'topic': '/sys/' + self.__dev_info['productKey'] + '/' + self.__dev_info['deviceName'] + '/thing/event/hli_event/post', 'qos': 1, 'payload': all_params_str } # 上传完成通知HaaS聚合平台 print('upload--->' + str(upload_file)) self.g_lk_service = False self.device.publish(upload_file) i = 0 while (self.g_lk_service == False and i < 200) : utime.sleep_ms(10) i = i + 1 continue else: print('filedid is none, upload content fail') time_diff = utime.ticks_diff(utime.ticks_ms(), start) print('recognize time : %d' % time_diff) def recognizeGesture(self, frame) : self.__upload_request('handGesture', frame) def recognizeAction(self, frame) : self.__upload_request('recognizeAction', frame, 2) def recognizeLicensePlate(self, frame) : self.__upload_request('ocrCarNo', frame) def recognizeFood(self, frame) : self.__upload_request('recognizeFood', frame, 2) def recognizeTrainTicket(self, frame) : self.__upload_request('recognizeTrainTicket', frame) def detectPedestrian(self, frame) : self.__upload_request('detectPedestrian', frame) def detectFruits(self, frame) : self.__upload_request('detectFruits', frame) def recognizeBussinessCard(self, frame) : self.__upload_request('recognizeBusinessCard', frame) def recognizeVehicleType(self, frame) : self.__upload_request('recognizeVehicle', frame) def detectVehicleCongestion(self, frame) : self.__upload_request('vehicleCongestionDetect', frame) def classifyRubbish(self, frame) : self.__upload_request('classifyingRubbish', frame) def detectObject(self, frame) : self.__upload_request('detectObject', frame)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/health_management/m5stack/code/cloudAI.py
Python
apache-2.0
13,436
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : main.py @Description: 菜品识别 @Author : aoyi @version : 1.0 ''' import display # 显示库 import network # 网络库 import ucamera # 摄像头库 import utime # 延时函数在utime库中 import _thread # 线程库 import sntp # 网络时间同步库 from cloudAI import * from bodyCalculator import * DIET_SUGGEST = "Diet_suggest" UPLOAD_BMI = "BMI" UPLOAD_FOOD_NAME = "Food_name" UPLOAD_CALORIES = "Calories" UPLOAD_START_ENROLL = "Start_enroll" UPLOAD_DATE = "Date" # Wi-Fi SSID和Password设置 SSID='请输入您的路由器名称' PWD='请输入您的路由器密码' # HaaS设备三元组 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" detected = False food_name = '' key_info = { 'region' : 'cn-shanghai' , 'productKey': productKey , 'deviceName': deviceName , 'deviceSecret': deviceSecret , 'keepaliveSec': 60 } def connect_wifi(ssid, pwd): # 引用全局变量 global disp # 初始化网络 wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(ssid, pwd) while True: print('Wi-Fi is connecting...') # 显示网络连接中 disp.text(20, 30, 'Wi-Fi is connecting...', disp.RED) # 网络连接成功后,更新显示字符 if (wlan.isconnected() == True): print('Wi-Fi is connected') disp.textClear(20, 30, 'Wi-Fi is connecting...') disp.text(20, 30, 'Wi-Fi is connected', disp.RED) ip = wlan.ifconfig()[0] print('IP: %s' %ip) disp.text(20, 50, ip, disp.RED) # NTP时间更新,如果更新不成功,将不能进行识别 print('NTP start') disp.text(20, 70, 'NTP start...', disp.RED) sntp.setTime() print('NTP done') disp.textClear(20, 70, 'NTP start...') disp.text(20, 70, 'NTP done', disp.RED) break utime.sleep_ms(500) utime.sleep(2) def food_cb(commandReply, result, calorie): global detected, food_name, total_food_calorie, Start_enroll food_name = 'NA' detected = False if commandReply == 'recognizeFoodReply' : if result != 'NA' : food_name = result Start_enroll = 0 total_food_calorie = total_food_calorie + int(calorie) print('detect food: ' + food_name + 'total calorie:' + str(total_food_calorie)) detected = True elif commandReply == 'on_props': body_calc.set_body_data(result) if 'Start_enroll' in result.keys(): Start_enroll = result['Start_enroll'] else: print('unknown command reply') post_default_value() # 识别线程函数 def recognizeThread(): global frame, Start_enroll while True: if frame != None and Start_enroll: engine.recognizeFood(frame) post_default_value() #engine.recognizeGesture(frame) utime.sleep_ms(6000) else: utime.sleep_ms(1000) # 显示线程函数 def displayThread(): # 引用全局变量 global disp, frame, detected, food_name # 定义清屏局部变量 clearFlag = False # 定义显示文本局部变量 textShowFlag = False while True: # 采集摄像头画面 # print('start to capture') frame = ucamera.capture() # print('end to capture') if frame != None: if detected == True: # 清除屏幕内容 disp.clear() # 设置文字字体 disp.font(disp.FONT_DejaVu40) # 显示识别结果 disp.text(10, 50, 'detect: ' + food_name, disp.RED) #disp.text(10, 50, 'detect pedestrain', disp.RED) utime.sleep_ms(2000) textShowFlag = False detected = False else: # 显示图像 # print('start to display') disp.image(0, 20, frame, 0) utime.sleep_ms(100) if textShowFlag == False: # 设置显示字体 disp.font(disp.FONT_DejaVu18) # 显示文字 disp.text(2, 0, 'Recognizing...', disp.WHITE) textShowFlag = True def post_props(data): global engine if isinstance(data,dict): data = {'params': json.dumps(data)} print('upload props-->' + str(data)) ret = engine.getDevice().postProps(data) return ret def post_default_value(): global food_name, total_food_calorie, Start_enroll, body_calc, last_date diet_suggestion = body_calc.generate_diet_suggestion(total_food_calorie) bmi = body_calc.get_body_bmi() date = str(utime.localtime()[1]) + '月' + str(utime.localtime()[2]) + '日' print(date) if last_date != date: total_food_calorie = 0 #日期变了,清空今日摄入卡路里数值 last_date = date value = {DIET_SUGGEST : diet_suggestion, UPLOAD_BMI : bmi, UPLOAD_FOOD_NAME : food_name, UPLOAD_CALORIES : total_food_calorie, UPLOAD_START_ENROLL: Start_enroll, UPLOAD_DATE: date} post_props(value) def main(): # 全局变量 global disp, frame, detected, food_name, engine, Start_enroll, body_calc, total_food_calorie, last_date # 创建lcd display对象 disp = display.TFT() frame = None detected = False Start_enroll = False last_date = ' ' total_food_calorie = 0 # 连接网络 connect_wifi(SSID, PWD) engine = CloudAI(key_info, food_cb) body_calc = BodyCalculator() # 初始化摄像头 ucamera.init('uart', 33, 32) ucamera.setProp(ucamera.SET_FRAME_SIZE, ucamera.SIZE_320X240) try: # 启动显示线程 _thread.start_new_thread(displayThread, ()) # 设置比对线程stack _thread.stack_size(20 * 1024) # 启动比对线程 _thread.start_new_thread(recognizeThread, ()) except: print("Error: unable to start thread") while True: utime.sleep_ms(1000) if __name__ == '__main__': main()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/health_management/m5stack/code/main.py
Python
apache-2.0
6,348
# -*- encoding: utf-8 -*- ''' @File : heartbeat.py @Description: 心率传感器驱动 @Author : victor.wang @version : 1.0 ''' from driver import ADC # ADC类,通过微处理器的ADC模块读取ADC通道输入电压 from driver import TIMER # 定时器类,用于定时调用心率传感器 class HEARTBEAT (object): def __init__(self, adcdev=None, rled=None, gled=None, bled=None, highBPM=150, lowBPM=100): if (not isinstance(adcdev, ADC)): raise ValueError("parameter is wrong") self.adcObj = adcdev self.rled=rled self.bled=bled self.gled=gled self.highBPM=highBPM self.lowBPM=lowBPM self.ledexist= (rled!=None and gled!=None and bled!=None) self.rate=[0 for _ in range(10)] self.sampleCounter = 0 # 心跳时间 self.lastBeatTime = 0 # IBIT self.P = 1800 # 用于确定心跳波形的最大值 self.T = 1800 # 用于确定心跳波形的最小值 self.thresh = 1800 # 用于确定心跳的瞬态值 self.amp = 150 # 心率波形的幅度 self.firstBeat = True # 第一次心跳 self.secondBeat = False # 第二次心跳 self.BPM=0; # 心率 self.Signal = 0 # 心跳信号 self.IBI = 600 # 心跳间隔 self.Pulse = False # 心跳波心是否为高 self.QS = False # 找到心跳 self.timerobj = TIMER(0) # 定时器 self.timerobj.open(period=2, mode=self.timerobj.PERIODIC, callback=self.getHeartbeat) def getHeartbeat(self, args): self.timerobj.stop() self.Signal = self.adcObj.readVoltage() # 读心跳传感器 self.sampleCounter +=2.5 # 记录时间 单位(ms)(理论值为2ms 2.5ms 为校准值) NUM = self.sampleCounter - self.lastBeatTime # 距上次心跳时间 # 确定心跳波形的波峰和波谷 if(self.Signal < self.thresh and NUM > (self.IBI/5)*3): # 去除dichrotic噪音 if (self.Signal < self.T): # self.T 是波谷值 self.T = self.Signal # 记录波谷值 if (self.Signal > self.thresh and self.Signal > self.P): self.P = self.Signal # self.P 是波峰 if (NUM > 250): if ((self.Signal > self.thresh) and (self.Pulse == False)): self.Pulse = True if self.ledexist: if self.BPM >= self.highBPM: # 如果心率过快,点亮红灯 self.rled.write(1) elif self.BPM <= self.lowBPM: # 如果心率过慢,点亮蓝灯 self.bled.write(1) else: # 如果心率合适,点亮绿灯 self.gled.write(1) self.IBI = self.sampleCounter - self.lastBeatTime # 心跳间隔 self.lastBeatTime = self.sampleCounter # 更新心跳间隔起始点 if(self.secondBeat): # 第二次心跳 self.secondBeat = False # 清除第二次心跳标识 for i in range(10): self.rate[i] = self.IBI if(self.firstBeat): # 第一次心跳 self.firstBeat = False # 清除第一次心跳标识 self.secondBeat = True # 置位第二次心跳标识 self.timerobj.start() return runningTotal = 0 for i in range(9): self.rate[i] = self.rate[i+1] # 丢弃最老的IBI值 runningTotal = runningTotal + self.rate[i] # 求和最老的9个IBI值 self.rate[9] = self.IBI runningTotal = runningTotal+self.rate[9] runningTotal = runningTotal/10 self.BPM = 60000/runningTotal # 计算心率 self.QS = True if ((self.Signal < self.thresh) and (self.Pulse == True)): if self.ledexist: self.rled.write(0) self.bled.write(0) self.gled.write(0) self.Pulse = False self.amp = self.P - self.T self.thresh = self.amp/2 + self.T self.P = self.thresh self.T = self.thresh if (NUM > 2500): # 如果2.5秒后还没检测到心跳 self.thresh = 1800 # thresh 设置为默认值 self.P = 1800 # P 设置为默认值 self.T = 1800 # T 设置为默认值 self.lastBeatTime = self.sampleCounter # 更新lastBeatTime self.firstBeat = True # 置位第一次心跳标识 self.secondBeat = False # 清除第二次心跳标识 self.timerobj.start() return def start(self): self.timerobj.start() def stop(self): self.timerobj.stop() def getBPM(self): return self.BPM
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/heartrate_detector/esp32/code/heartbeat.py
Python
apache-2.0
5,841
# -*- encoding: utf-8 -*- ''' @File : main.py @Description: 心率上云 @Author : victor.wang @version : 1.0 ''' from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import utime # 延时API所在组件 from driver import ADC # ADC类,通过微处理器的ADC模块读取ADC通道输入电压 from driver import GPIO # ESP32和使用GPIO控制LED import heartbeat # 心率传感器驱动库 import ujson # json字串解析库 # 物联网平台连接标志位 iot_connected = False # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifiSsid = " 填写您的路由器名称" wifiPassword = " 填写您的路由器密码" # 最大和最小心率值设定 BPM_high=150 # 最大运动心率 BPM_low=100 # 最小运动心率 # 物联网平台连接标志位 iot_connected = False wlan = None # 物联网设备实例 device = None # LED 心率传感器设备 redled=None blueled=None greenled=None adcobj = None buzzerobj = None heartbeatdev = None # 蜂鸣器控制变量 buzzeron =0 def buzzer_init(): global buzzerobj buzzerobj = GPIO() buzzerobj.open('buzzer') # board.json中buzzer节点定义的GPIO,对应esp32外接的上的蜂鸣器 print("buzzer inited!") def heartbeat_init(): global adcobj, heartbeatdev,redled, blueled, greenled, BPM_high, BPM_low redled = GPIO() blueled = GPIO() greenled = GPIO() redled.open('led_r') # board.json中led_r节点定义的GPIO,对应esp32外接的的红灯 blueled.open('led_b') # board.json中led_b节点定义的GPIO,对应esp32外接的上的蓝灯 greenled.open('led_g') # board.json中led_g节点定义的GPIO,对应esp32外接的上的绿灯 adcobj = ADC() adcobj.open("heartbeat") # 按照board.json中名为"heartbeat"的设备节点的配置参数(主设备adc端口号,从设备地址,采样率等)初始化adc类型设备对象 heartbeatdev = heartbeat.HEARTBEAT(adcdev=adcobj, rled=redled, bled=blueled, gled=greenled, highBPM=BPM_high, lowBPM=BPM_low) # 初始化心率传感器 print("heartbeat inited!") # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wlan wifi_connected = False wlan = network.WLAN(network.STA_IF) #创建WLAN对象 wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if not wifi_connected: wlan.active(True) #激活界面 wlan.scan() #扫描接入点 wlan.disconnect() #断开Wi-Fi #print("start to connect ", wifiSsid) wlan.connect(wifiSsid, wifiPassword) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) while True: wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected: # Wi-Fi连接成功则退出while循环 break else: utime.sleep(0.5) print("wifi_connected:", wifi_connected) ifconfig = wlan.ifconfig() #获取接口的IP/netmask/gw/DNS地址 print(ifconfig) utime.sleep(0.5) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): global buzzeron payload = ujson.loads(request['params']) # 获取dict状态字段 if "Buzzer" in payload.keys(): buzzeron = payload["Buzzer"] if(buzzeron): print("打开蜂鸣器") buzzerobj.write(buzzeron) # 控制蜂蜜器 # 要将更改后的状态同步上报到云平台 prop = ujson.dumps({ 'Buzzer': buzzeron, }) upload_data = {'params': prop} # 上报蜂鸣器属性到云端 device.postProps(upload_data) def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) def getBPM(): global heartbeatdev value = heartbeatdev.getBPM() return value def ajust(y): x=0 if (y<70): x=65 elif (y<80): x=75 elif (y<90): x=85 elif (y<100): x=95 elif (y<110): x=105 elif (y<120): x=115 elif (y<130): x=125 elif (y<140): x=135 elif (y<150): x=145 elif (y<160): x=155 elif (y<170): x=165 elif (y<180): x=175 else: x=200 return x # 上传心率到物联网平台 def upload_heartbeat(): global device while True: # 生成上报到物联网平台的属性值 value = getBPM() print ("心率:", value) value = ajust(value) prop = ujson.dumps({ 'HeartRate': value }) #print('uploading data: ', "\'HeartRate\':", value) # 上传心率值到物联网平台 upload_data = {'params': prop} device.postProps(upload_data) utime.sleep(2) if __name__ == '__main__': buzzer_init() # 请替换物联网平台申请到的产品和设备信息,可以参考README get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) print('sleep for 2s before start heartbeatsensor') utime.sleep(2) # 等待2s heartbeat_init() # 初始化心率心率传感器, 采样周期默认2ms heartbeatdev.start() # 启动心率传感器, 每隔2ms采集一次心跳 upload_heartbeat()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/heartrate_detector/esp32/code/main.py
Python
apache-2.0
6,821
from driver import PWM class BUZZER(object): def __init__(self, pwmObj,data=None): self.pwmObj = None if not isinstance(pwmObj, PWM): raise ValueError("parameter is not an PWM object") self.pwmObj = pwmObj if data is not None: self.setOptionDuty(data) def setOptionDuty(self,data): if self.pwmObj is None: raise ValueError("invalid PWM object") self.pwmObj.setOption(data) def start(self,data): if self.pwmObj is None: raise ValueError("invalid PWM object") self.setOptionDuty(data) def close(self,data): if self.pwmObj is None: raise ValueError("invalid PWM object") self.setOptionDuty(data)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/home_intrusion_alarm/esp32/code/buzzer.py
Python
apache-2.0
757
from driver import GPIO class IR(object): def __init__(self, gpioObj): self.gpioObj = None if not isinstance(gpioObj, GPIO): raise ValueError("parameter is not a GPIO object") self.gpioObj = gpioObj def irDetect(self): if self.gpioObj is None: raise ValueError("invalid GPIO object") value = self.gpioObj.read() return value
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/home_intrusion_alarm/esp32/code/ir.py
Python
apache-2.0
410
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : main.py @Author : guoliang.wgl @version : 1.0 @Description: home_intrusion_alarm案例 - 家庭红外入侵检测和报警系统 board.json - 硬件资源配置文件 ''' from buzzer import BUZZER from ir import IR from driver import PWM,GPIO import time from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import sntp import json # 物联网平台连接标志位 iot_connected = False wlan = None # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # 物联网设备实例 device = None # Wi-Fi SSID和Password设置 wifiSsid = "请输入您的路由器名称" wifiPassword = "请输入您的路由器密码" # 警报开关以及时间段控制(大于等于alarm_start 或者小于等于alarm_end ) do_alarm = 1 alarm_start = 23 alarm_end = 6 alarming = False FLAG_ALARM_CONTROL = "alarm_control" FLAG_ALARM_START = "alarm_start" FLAG_ALARM_END = "alarm_end" # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wlan wifi_connected = False wlan.active(True) #激活界面 wlan.scan() #扫描接入点 #print("start to connect ", wifiSsid) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) wlan.connect(wifiSsid, wifiPassword) while True: wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected: # Wi-Fi连接成功则退出while循环 break else: time.sleep(0.5) print("wifi_connected:", wifi_connected) ifconfig = wlan.ifconfig() #获取接口的IP/netmask/gw/DNS地址 print(ifconfig) time.sleep(0.5) # 判断当前时间是否在有效时间段内 def time_valid(): global alarm_start,alarm_end cur_hour = time.localtime()[3] return cur_hour >= alarm_start or cur_hour <= alarm_end # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): global do_alarm,alarm_start,alarm_end,post_default_value,FLAG_ALARM_CONTROL,FLAG_ALARM_START,FLAG_ALARM_END try: props = eval(request['params']) if FLAG_ALARM_CONTROL in props.keys(): do_alarm = props[FLAG_ALARM_CONTROL] print('on_props: do_alarm {}'.format(do_alarm)) elif FLAG_ALARM_START in props.keys(): alarm_start = props[FLAG_ALARM_START] print('on_props: alarm_start {}'.format(alarm_start)) elif FLAG_ALARM_END in props.keys(): alarm_end = props[FLAG_ALARM_END] print('on_props: alarm_end {}'.format(alarm_end)) post_default_value() except Excaption as e: print(e) def post_props(data): global device if isinstance(data,dict): data = {'params': json.dumps(data)} ret = device.postProps(data) return ret def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数 # 如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while True: if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') time.sleep(1) time.sleep(2) def post_default_value(): global do_alarm,alarm_start,alarm_end,FLAG_ALARM_CONTROL,FLAG_ALARM_START,FLAG_ALARM_END value = {FLAG_ALARM_CONTROL : do_alarm} post_props(value) value = {FLAG_ALARM_START : alarm_start} post_props(value) value = {FLAG_ALARM_END : alarm_end} post_props(value) if __name__ == '__main__': wlan = network.WLAN(network.STA_IF) #创建WLAN对象 # 请替换物联网平台申请到的产品和设备信息,可以参考文章:https://blog.csdn.net/HaaSTech/article/details/114360517 # global productKey, deviceName, deviceSecret ,on_request, on_play get_wifi_status() sntp.setTime() connect_lk(productKey, deviceName, deviceSecret) post_default_value() # 初始化蜂鸣器 pwmObj = PWM() pwmObj.open("buzzer") pwm_init_data = {'freq':2000, 'duty': 0} buzzer = BUZZER(pwmObj,data=pwm_init_data) # 初始化热释电红外传感器 gpioirDev = GPIO() gpioirDev.open("ir") ir = IR(gpioirDev) while True: if do_alarm == 1 and time_valid() and ir.irDetect() == 1: print('human detected, start buzzer') pwm_start_data = {'freq':2000, 'duty': 5} buzzer.start(pwm_start_data) alarming = True if do_alarm == 0 and alarming: print('close buzzer') pwm_start_data = {'freq':2000, 'duty': 0} buzzer.start(pwm_start_data) alarming = False time.sleep(0.1)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/home_intrusion_alarm/esp32/code/main.py
Python
apache-2.0
5,681
from driver import GPIO class BD(object): def __init__(self, gpioObj): self.gpioObj = None if not isinstance(gpioObj, GPIO): raise ValueError("parameter is not a GPIO object") self.gpioObj = gpioObj def irDetect(self): if self.gpioObj is None: raise ValueError("invalid GPIO object") value = self.gpioObj.read() return value
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/home_intrusion_alarm/haas506/code/bodyDetect.py
Python
apache-2.0
410
# coding=utf-8 from driver import GPIO from driver import PWM import network import ujson import utime as time import modem from aliyunIoT import Device import kv import sntp from bodyDetect import BD # 警报开关以及时间段控制(大于等于alarm_start 或者小于等于alarm_end ) alarming = False #当iot设备连接到物联网平台的时候触发'connect' 事件 def on_connect(data): global module_name,default_ver,productKey,deviceName,deviceSecret,on_trigger,on_download,on_verify,on_upgrade print('***** connect lp succeed****') data_handle = {} data_handle['device_handle'] = device.getDeviceHandle() #当连接断开时,触发'disconnect'事件 def on_disconnect(): print('linkkit is disconnected') #当iot云端下发属性设置时,触发'props'事件 def on_props(request): global do_alarm,alarm_start,alarm_end,FLAG_ALARM_CONTROL,FLAG_ALARM_START,FLAG_ALARM_END try: props = eval(request['params']) if FLAG_ALARM_CONTROL in props.keys(): do_alarm = props[FLAG_ALARM_CONTROL] print('on_props: do_alarm {}'.format(do_alarm)) elif FLAG_ALARM_START in props.keys(): alarm_start = props[FLAG_ALARM_START] print('on_props: alarm_start {}'.format(alarm_start)) elif FLAG_ALARM_END in props.keys(): alarm_end = props[FLAG_ALARM_END] print('on_props: alarm_end {}'.format(alarm_end)) post_default_value() except Excaption as e: print(e) value_data = {} do_alarm = 1 FLAG_ALARM_CONTROL = "alarm_control" FLAG_ALARM_START = "alarm_start" FLAG_ALARM_END = "alarm_end" def post_default_value(): global do_alarm,alarm_start,alarm_end,FLAG_ALARM_CONTROL,FLAG_ALARM_START,FLAG_ALARM_END value_data[FLAG_ALARM_CONTROL]=do_alarm value_data[FLAG_ALARM_START]=alarm_start value_data[FLAG_ALARM_END]=alarm_end data={ 'params':ujson.dumps(value_data) } device.postProps(data) print('---------------0----------------------') #当iot云端调用设备service时,触发'service'事件 def on_service(id,request): print('clound req id is {} , req is {}'.format(id,request)) #当设备跟iot平台通信过程中遇到错误时,触发'error'事件 def on_error(err): print('err msg is {} '.format(err)) #网络连接的回调函数 def on_4g_cb(args): global g_connect_status pdp = args[0] netwk_sta = args[1] if netwk_sta == 1: g_connect_status = True else: g_connect_status = False #网络连接 def connect_network(): global net,on_4g_cb,g_connect_status #NetWorkClient该类是一个单例类,实现网络管理相关的功能,包括初始化,联网,状态信息等. net = network.NetWorkClient() g_register_network = False if net._stagecode is not None and net._stagecode == 3 and net._subcode == 1: g_register_network = True else: g_register_network = False if g_register_network: #注册网络连接的回调函数on(self,id,func); 1代表连接,func 回调函数 ;return 0 成功 net.on(1,on_4g_cb) net.connect(None) else: print('网络注册失败') while True: if g_connect_status: print('网络连接成功') break time.sleep_ms(20) #动态注册回调函数 def on_dynreg_cb(data): global deviceSecret,device_dyn_resigter_succed deviceSecret = data device_dyn_resigter_succed = True # 连接物联网平台 def dyn_register_device(productKey,productSecret,deviceName): global on_dynreg_cb,device,deviceSecret,device_dyn_resigter_succed key = '_amp_customer_devicesecret' deviceSecretdict = kv.get(key) print("deviceSecretdict:",deviceSecretdict) if isinstance(deviceSecretdict,str): deviceSecret = deviceSecretdict if deviceSecretdict is None or deviceSecret is None: key_info = { 'productKey': productKey , 'productSecret': productSecret , 'deviceName': deviceName } # 动态注册一个设备,获取设备的deviceSecret #下面的if防止多次注册,当前若是注册过一次了,重启设备再次注册就会卡住, if not device_dyn_resigter_succed: device.register(key_info,on_dynreg_cb) alarm_start = 8 alarm_end = 20 # 判断当前时间是否在有效时间段内 def time_valid(): global alarm_start,alarm_end cur_hour = time.localtime()[3] return (cur_hour >= alarm_start) and (cur_hour <= alarm_end) def start_buzzers(duty_cycle): param = {'freq':3000, 'duty': duty_cycle } buzzers.setOption(param) if __name__ == '__main__': ICCID=None g_connect_status = False net = None device = None deviceSecret = None deviceName = None #复制产品证书内容替换 productKey = "your-productKey" productSecret = "your-productSecret" device_dyn_resigter_succed = False # 连接网络 connect_network() # 获取设备的IMEI 作为deviceName 进行动态注册 deviceName = modem.info.getDevImei() #获取设备的ICCID ICCID=modem.sim.getIccid() #初始化物联网平台Device类,获取device实例 device = Device() if deviceName is not None and len(deviceName) > 0 : #动态注册一个设备 dyn_register_device(productKey,productSecret,deviceName) else: print("获取设备IMEI失败,无法进行动态注册") while deviceSecret is None: time.sleep(0.2) print('动态注册成功:' + deviceSecret) key_info = { 'region' : 'cn-shanghai' , 'productKey': productKey , 'deviceName': deviceName , 'deviceSecret': deviceSecret , 'keepaliveSec': 60, } #打印设备信息 print(key_info) #device.ON_CONNECT 是事件,on_connect是事件处理函数/回调函数 device.on(device.ON_CONNECT,on_connect) device.on(device.ON_DISCONNECT,on_disconnect) device.on(device.ON_PROPS,on_props) device.on(device.ON_SERVICE,on_service) device.on(device.ON_ERROR,on_error) device.connect(key_info) # 初始化蜂鸣器 sntp.settime() #sntp 校时 time.sleep(2) buzzers = PWM() buzzers.open("buzzer") # 初始化人体传感器 radar=GPIO() radar.open('radar') bd = BD(radar) post_default_value() while True: print(''' 报警状态:{}, 报警工作时间:{}, 检测到人体活动:{} '''.format(do_alarm,time_valid(),bd.irDetect())) if do_alarm == 1 and time_valid() and bd.irDetect() == 1: print('human detected, start buzzer') start_buzzers(50) alarming = True else: print('-------------------') if do_alarm == 0 and alarming: print('close buzzer') start_buzzers(100) alarming = False else: pass time.sleep(1)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/home_intrusion_alarm/haas506/code/main.py
Python
apache-2.0
7,089
from driver import GPIO class IR(object): def __init__(self, gpioObj): self.gpioObj = None if not isinstance(gpioObj, GPIO): raise ValueError("parameter is not a GPIO object") self.gpioObj = gpioObj def irDetect(self): if self.gpioObj is None: raise ValueError("invalid GPIO object") value = self.gpioObj.read() return value
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/human_detector/esp32/code/ir.py
Python
apache-2.0
411
# -*- coding: UTF-8 -*- from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import ujson # json字串解析库 import utime # 延时API所在组件 from driver import GPIO # GPIO类,用于控制微处理器的输入输出功能 import ir # ir人体红外传感器类 gpioirDev = 0 gpioledDev = 0 irDev = 0 # 物联网平台连接标志位 iot_connected = False wlan = None # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # 物联网设备实例 device = None # Wi-Fi SSID和Password设置 wifiSsid = "请输入您的路由器名称" wifiPassword = "请输入您的路由器密码" # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wlan wifi_connected = False wlan.active(True) #激活界面 wlan.scan() #扫描接入点 #print("start to connect ", wifiSsid) wlan.connect(wifiSsid, wifiPassword) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) while True: wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected: # Wi-Fi连接成功则退出while循环 break else: utime.sleep(0.5) print("wifi_connected:", wifi_connected) ifconfig = wlan.ifconfig() #获取接口的IP/netmask/gw/DNS地址 print(ifconfig) utime.sleep(0.5) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): pass def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) def human_check_init(): global gpioirDev,gpioledDev,irDev gpioirDev = GPIO() gpioirDev.open("ir") irDev = ir.IR(gpioirDev) gpioledDev = GPIO() gpioledDev.open("led") def led_control(on): global gpioledDev if on == 0: gpioledDev.write(0) # GPIO写入0,灭灯 else: gpioledDev.write(1) # GPIO写入1,亮灯 def human_detector() : global gpioirDev,gpioledDev,irDev last_have_human = 0 # 记录初始值 while True : have_human = irDev.irDetect() # 获取传感器的值 if (have_human == 1) : print("human is here .....\r\n") if (last_have_human != have_human) : led_control(have_human) # 控制LED亮灭 # 生成上报到物联网平台的属性值字串,此处的属性标识符"LEDSwith"必须和物联网平台的属性一致 # "LEDSwitch" - 表示起夜灯的状态 upload_data = {'params': ujson.dumps({ 'LEDSwitch': have_human, }) } # 上传LED状态到物联网平台 device.postProps(upload_data) last_have_human = have_human # 记录当前状态 utime.sleep(1) # 休眠1秒 gpioirDev.close() gpioledDev.close() if __name__ == '__main__' : wlan = network.WLAN(network.STA_IF) #创建WLAN对象 # 请替换物联网平台申请到的产品和设备信息,可以参考文章:https://blog.csdn.net/HaaSTech/article/details/114360517 # global productKey, deviceName, deviceSecret ,on_request, on_play get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) human_check_init() human_detector()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/human_detector/esp32/code/main.py
Python
apache-2.0
4,669
from driver import GPIO class IR(object): def __init__(self, gpioObj): self.gpioObj = None if not isinstance(gpioObj, GPIO): raise ValueError("parameter is not a GPIO object") self.gpioObj = gpioObj def irDetect(self): if self.gpioObj is None: raise ValueError("invalid GPIO object") value = self.gpioObj.read() return value
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/human_detector/haas200/code/ir.py
Python
apache-2.0
408
# -*- coding: UTF-8 -*- from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import netmgr as nm # Wi-Fi 功能所在库 import ujson # json字串解析库 import utime # 延时API所在组件 from driver import GPIO # GPIO类,用于控制微处理器的输入输出功能 import ir # ir人体红外传感器类 gpioirDev = 0 gpioledDev_1 = 0 gpioledDev_2 = 0 gpioledDev_3 = 0 irDev = 0 # 物联网平台连接标志位 iot_connected = False wlan = None productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # 物联网设备实例 device = None # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wifiSsid, wifiPassword nm.init() print("start to connect ", wifiSsid) nm.connect(wifiSsid, wifiPassword) while True: wifi_connected = nm.getStatus() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected == 5: # Wi-Fi连接成功则退出while循环 info = nm.getInfo() print("\n") print("wifi 连接成功:") print(" SSID:", info["ssid"]) print(" IP:", info["ip"]) print(" MAC:", info["mac"]) print(" RSSI:", info["rssi"]) break else: print("wifi 连接失败") utime.sleep(0.5) print('sleep for 1s') utime.sleep(1) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): pass def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) def human_check_init(): global gpioirDev,gpioledDev_1,gpioledDev_2,gpioledDev_3,irDev gpioirDev = GPIO() gpioirDev.open("ir") irDev = ir.IR(gpioirDev) gpioledDev_1 = GPIO() gpioledDev_1.open("led01") gpioledDev_2 = GPIO() gpioledDev_2.open("led02") gpioledDev_3 = GPIO() gpioledDev_3.open("led03") def led_control(on): global gpioledDev_1 if on == 0: gpioledDev_1.write(0) # GPIO写入0,灭灯 gpioledDev_2.write(0) # GPIO写入0,灭灯 gpioledDev_3.write(0) # GPIO写入0,灭灯 else: gpioledDev_1.write(1) # GPIO写入1,亮灯 gpioledDev_2.write(1) # GPIO写入1,亮灯 gpioledDev_3.write(1) # GPIO写入1,亮灯 def human_detector() : global gpioirDev,gpioledDev_1,gpioledDev_2,gpioledDev_3,irDev last_have_human = 0 # 记录初始值 while True : have_human = irDev.irDetect() # 获取传感器的值 if (have_human == 1) : print("human is here .....\r\n") if (have_human == 0) : print("human is not here .....\r\n") if (last_have_human != have_human) : led_control(have_human) # 控制LED亮灭 # 生成上报到物联网平台的属性值字串,此处的属性标识符"LEDSwith"必须和物联网平台的属性一致 # "LEDSwitch" - 表示起夜灯的状态 upload_data = {'params': ujson.dumps({ 'LEDSwitch': have_human, }) } # 上传LED状态到物联网平台 device.postProps(upload_data) last_have_human = have_human # 记录当前状态 utime.sleep(1) # 休眠1秒 gpioirDev.close() gpioledDev_1.close() gpioledDev_2.close() gpioledDev_3.close() if __name__ == '__main__' : # 请替换物联网平台申请到的产品和设备信息,可以参考README get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) human_check_init() human_detector()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/human_detector/haas200/code/main.py
Python
apache-2.0
5,011
# coding=utf-8 from driver import GPIO import network import ujson import utime as time import modem from aliyunIoT import Device import kv #当iot设备连接到物联网平台的时候触发'connect' 事件 def on_connect(data): global module_name,default_ver,productKey,deviceName,deviceSecret,on_trigger,on_download,on_verify,on_upgrade print('***** connect lp succeed****') data_handle = {} data_handle['device_handle'] = device.getDeviceHandle() #当连接断开时,触发'disconnect'事件 def on_disconnect(): print('linkkit is disconnected') #当iot云端下发属性设置时,触发'props'事件 def on_props(request): params=request['params'] params=eval(params) light = params["light"] led1.write(light) #当iot云端调用设备service时,触发'service'事件 def on_service(id,request): print('clound req id is {} , req is {}'.format(id,request)) #当设备跟iot平台通信过程中遇到错误时,触发'error'事件 def on_error(err): print('err msg is {} '.format(err)) #网络连接的回调函数 def on_4g_cb(args): global g_connect_status pdp = args[0] netwk_sta = args[1] if netwk_sta == 1: g_connect_status = True else: g_connect_status = False #网络连接 def connect_network(): global net,on_4g_cb,g_connect_status #NetWorkClient该类是一个单例类,实现网络管理相关的功能,包括初始化,联网,状态信息等. net = network.NetWorkClient() g_register_network = False if net._stagecode is not None and net._stagecode == 3 and net._subcode == 1: g_register_network = True else: g_register_network = False if g_register_network: #注册网络连接的回调函数on(self,id,func); 1代表连接,func 回调函数 ;return 0 成功 net.on(1,on_4g_cb) net.connect(None) else: print('网络注册失败') while True: if g_connect_status: print('网络连接成功') break time.sleep_ms(20) #动态注册回调函数 def on_dynreg_cb(data): global deviceSecret,device_dyn_resigter_succed deviceSecret = data device_dyn_resigter_succed = True # 连接物联网平台 def dyn_register_device(productKey,productSecret,deviceName): global on_dynreg_cb,device,deviceSecret,device_dyn_resigter_succed key = '_amp_customer_devicesecret' deviceSecretdict = kv.get(key) print("deviceSecretdict:",deviceSecretdict) if isinstance(deviceSecretdict,str): deviceSecret = deviceSecretdict if deviceSecretdict is None or deviceSecret is None: key_info = { 'productKey': productKey , 'productSecret': productSecret , 'deviceName': deviceName } # 动态注册一个设备,获取设备的deviceSecret #下面的if防止多次注册,当前若是注册过一次了,重启设备再次注册就会卡住, if not device_dyn_resigter_succed: device.register(key_info,on_dynreg_cb) def upload_led(led): global led_data led_data["light"]= led led_data_str=ujson.dumps(led_data) data={ 'params':led_data_str } device.postProps(data) if __name__ == '__main__': ICCID=None g_connect_status = False net = None device = None deviceSecret = None deviceName = None #复制产品证书内容替换 productKey = "your-productKey" productSecret = "your-productSecret" device_dyn_resigter_succed = False # 连接网络 connect_network() # 获取设备的IMEI 作为deviceName 进行动态注册 deviceName = modem.info.getDevImei() #获取设备的ICCID ICCID=modem.sim.getIccid() #初始化物联网平台Device类,获取device实例 device = Device() if deviceName is not None and len(deviceName) > 0 : #动态注册一个设备 dyn_register_device(productKey,productSecret,deviceName) else: print("获取设备IMEI失败,无法进行动态注册") while deviceSecret is None: time.sleep(0.2) print('动态注册成功:' + deviceSecret) key_info = { 'region' : 'cn-shanghai' , 'productKey': productKey , 'deviceName': deviceName , 'deviceSecret': deviceSecret , 'keepaliveSec': 60, } #打印设备信息 print(key_info) #device.ON_CONNECT 是事件,on_connect是事件处理函数/回调函数 device.on(device.ON_CONNECT,on_connect) device.on(device.ON_DISCONNECT,on_disconnect) device.on(device.ON_PROPS,on_props) device.on(device.ON_SERVICE,on_service) device.on(device.ON_ERROR,on_error) device.connect(key_info) #传感器操作 led1=GPIO() led1.open("led1") radar=GPIO() radar.open('radar') led_data = {} while True: #当检测到人体活动,相应的引脚会输出高电平 if radar.read()==1: print("---------------------------detect body-------------------------------") led1.write(1) upload_led(1) else: print("no body") led1.write(0) upload_led(0) time.sleep(1)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/human_detector/haas506/code/main.py
Python
apache-2.0
5,314
from driver import GPIO class IR(object): def __init__(self, gpioObj): self.gpioObj = None if not isinstance(gpioObj, GPIO): raise ValueError("parameter is not a GPIO object") self.gpioObj = gpioObj def irDetect(self): if self.gpioObj is None: raise ValueError("invalid GPIO object") value = self.gpioObj.read() return value
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/human_detector/haaseduk1/code/ir.py
Python
apache-2.0
410
# -*- coding: UTF-8 -*- from aliyunIoT import Device # aliyunIoT组件是连接阿里云物联网平台的组件 import netmgr as nm # Wi-Fi功能所在库 import ujson # json字串解析库 import utime # 延时API所在组件 from driver import GPIO # GPIO类,用于控制微处理器的输入输出功能 import ir # ir人体红外传感器类 gpioirDev = 0 gpioledDev = 0 irDev = 0 # 物联网平台连接标志位 iot_connected = False wlan = None # Wi-Fi SSID和Password设置 wifiSsid = "请输入您的路由器名称" wifiPassword = "请输入您的路由器密码" # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # 物联网设备实例 device = None # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): nm.init() nm.disconnect() wifi_connected = nm.getStatus() print("start to connect " + wifiSsid) nm.connect(wifiSsid, wifiPassword) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) while True : if wifi_connected == 5: # nm.getStatus()返回5代表连线成功 break else: wifi_connected = nm.getStatus() # 获取Wi-Fi连接路由器的状态信息 utime.sleep(0.5) print("wifi_connected: " + str(wifi_connected)) print("Wi-Fi connected") print('DeviceIP:' + nm.getInfo()['ip']) # 打印Wi-Fi的IP地址信息 # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): pass def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) def human_check_init(): global gpioirDev,gpioledDev,irDev gpioirDev = GPIO() gpioirDev.open("ir") irDev = ir.IR(gpioirDev) gpioledDev = GPIO() gpioledDev.open("led") def led_control(on): global gpioledDev if on == 0: gpioledDev.write(0) # GPIO写入0,灭灯 else: gpioledDev.write(1) # GPIO写入1,亮灯 def human_detector() : global gpioirDev,gpioledDev,irDev last_have_human = 0 # 记录初始值 while True : have_human = irDev.irDetect() # 获取传感器的值 if (have_human == 1) : print("human is here ...\r\n") if (last_have_human != have_human) : led_control(have_human) # 控制LED亮灭 # 生成上报到物联网平台的属性值字串,此处的属性标识符"LEDSwith"必须和物联网平台的属性一致 # "LEDSwitch" - 表示起夜灯的状态 upload_data = {'params': ujson.dumps({ 'LEDSwitch': have_human, }) } # 上传LED状态到物联网平台 device.postProps(upload_data) last_have_human = have_human # 记录当前状态 utime.sleep(1) # 休眠1秒 gpioirDev.close() gpioledDev.close() if __name__ == '__main__' : # 请替换物联网平台申请到的产品和设备信息,可以参考文章:https://blog.csdn.net/HaaSTech/article/details/114360517 # global productKey, deviceName, deviceSecret ,on_request, on_play get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) human_check_init() human_detector()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/human_detector/haaseduk1/code/main.py
Python
apache-2.0
4,507
from driver import GPIO class IR(object): def __init__(self, gpioObj): self.gpioObj = None if not isinstance(gpioObj, GPIO): raise ValueError("parameter is not a GPIO object") self.gpioObj = gpioObj def irDetect(self): if self.gpioObj is None: raise ValueError("invalid GPIO object") value = self.gpioObj.read() return value
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/human_detector/stm32/code/ir.py
Python
apache-2.0
408
# -*- coding: UTF-8 -*- from ulinksdk.aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 #import netmgr as nm # Wi-Fi 功能所在库 import network import ujson # json字串解析库 import utime # 延时API所在组件 from driver import GPIO # GPIO类,用于控制微处理器的输入输出功能 import ir # ir人体红外传感器类 gpioirDev = 0 gpioledDev_1 = 0 gpioledDev_2 = 0 gpioledDev_3 = 0 irDev = 0 # 物联网平台连接标志位 iot_connected = False wlan = None # 三元组信息 productKey = "产品密钥" deviceName = "设备名字" deviceSecret = "设备密钥" # 物联网设备实例 device = None # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wifiSsid, wifiPassword nm.init() print("start to connect ", wifiSsid) nm.connect(wifiSsid, wifiPassword) while True: wifi_connected = nm.getStatus() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected == 5: # Wi-Fi连接成功则退出while循环 info = nm.getInfo() print("\n") print("wifi 连接成功:") print(" SSID:", info["ssid"]) print(" IP:", info["ip"]) print(" MAC:", info["mac"]) print(" RSSI:", info["rssi"]) break else: print("wifi 连接失败") utime.sleep(0.5) print('sleep for 1s') utime.sleep(1) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): pass def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) def human_check_init(): global gpioirDev,gpioledDev_1,gpioledDev_2,gpioledDev_3,irDev gpioirDev = GPIO() gpioirDev.open("ir") irDev = ir.IR(gpioirDev) gpioledDev_1 = GPIO() gpioledDev_1.open("led01") gpioledDev_2 = GPIO() gpioledDev_2.open("led02") gpioledDev_3 = GPIO() gpioledDev_3.open("led03") def led_control(on): global gpioledDev_1 if on == 0: gpioledDev_1.write(0) # GPIO写入0,灭灯 gpioledDev_2.write(0) # GPIO写入0,灭灯 gpioledDev_3.write(0) # GPIO写入0,灭灯 else: gpioledDev_1.write(1) # GPIO写入1,亮灯 gpioledDev_2.write(1) # GPIO写入1,亮灯 gpioledDev_3.write(1) # GPIO写入1,亮灯 def human_detector() : global gpioirDev,gpioledDev_1,gpioledDev_2,gpioledDev_3,irDev last_have_human = 0 # 记录初始值 while True : have_human = irDev.irDetect() # 获取传感器的值 #have_human = 0 if (have_human == 1) : print("human is here .....\r\n") if (have_human == 0) : print("human is not here .....\r\n") if (last_have_human != have_human) : led_control(have_human) # 控制LED亮灭 # 生成上报到物联网平台的属性值字串,此处的属性标识符"LEDSwith"必须和物联网平台的属性一致 # "LEDSwitch" - 表示起夜灯的状态 upload_data = {'params': ujson.dumps({ 'LEDSwitch': have_human, }) } # 上传LED状态到物联网平台 device.postProps(upload_data) last_have_human = have_human # 记录当前状态 utime.sleep(1) # 休眠1秒 gpioirDev.close() gpioledDev_1.close() gpioledDev_2.close() gpioledDev_3.close() if __name__ == '__main__' : # 请替换物联网平台申请到的产品和设备信息,可以参考README nic = network.LAN() nic.active(1) connect_lk(productKey, deviceName, deviceSecret) human_check_init() human_detector()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/human_detector/stm32/code/main.py
Python
apache-2.0
5,098
from driver import GPIO import utime as time import audio import radar #创建并打开一个GPIO实例 gpiorDev=GPIO() gpiorDev.open('radar') #创建一个radar实例 radarDev=radar.RADAR(gpiorDev) #创建并打开一个Audio实例 aud=audio.Audio() #开启音频播放使能 aud.set_pa() #设置音量 aud.setVolume(5) #循环检测是否有人经过 while True: if radarDev.detect()==1: print("detect body") aud.play('/data/pyamp/detect_body.mp3') else: print("no body") time.sleep(2)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/human_existence_detector/haas506/code/main.py
Python
apache-2.0
536
from driver import GPIO class RADAR(object): def __init__(self, gpioObj): self.gpioObj = None if not isinstance(gpioObj, GPIO): raise ValueError("parameter is not a GPIO object") self.gpioObj = gpioObj def detect(self): if self.gpioObj is None: raise ValueError("invalid GPIO object") value = self.gpioObj.read() return value
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/human_existence_detector/haas506/code/radar.py
Python
apache-2.0
437
from driver import PWM class BUZZER(object): def __init__(self, pwmObj): self.pwmObj = None if not isinstance(pwmObj, PWM): raise ValueError("parameter is not an PWM object") self.pwmObj = pwmObj def setOptionDuty(self,data): if self.pwmObj is None: raise ValueError("invalid PWM object") self.pwmObj.setOption(data) def start(self,obj): if self.pwmObj is None: raise ValueError("invalid PWM object") self.pwmObj.open(obj) def close(self): if self.pwmObj is None: raise ValueError("invalid PWM object") self.pwmObj.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/human_ir_temperature/esp32/code/buzzer.py
Python
apache-2.0
668
######### from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import ujson ################## from driver import I2C,PWM,TIMER import utime from ssd1306 import SSD1306_I2C import buzzer import mlx90614 import time INVALUDE_TEMP = 1037 # 失效测量值 LOWER_LEVEL = 30 # 最小有效测温阈值 【30 60】 HIGH_LEVEL = 60 # 最大有效测温阈值 ABNORMAL_TEMP = 35 # 异常温度设定阈值 【30 ... 60】 E_CAL_TEMP_INVALID = 1 E_CAL_TEMP_FINISH = 2 E_CAL_TEMP_HIGH = 3 E_CAL_TEMPING = 4 E_CAL_TEMP_START = 5 timer_interval_100ms = 100 #ms cal_temp_timer = 100 #10s = (100*timer_interval_100ms) high_timer = 50 #5s = (50*timer_interval_100ms) TEMP_CAL_TIMER = (cal_temp_timer) #有效测量时间 TEMP_CAL_TIMER_HIGH = (high_timer) #异常温度,有效测量时间 timer_interval_1000ms = 1000 stay_long = 5 # 5s (5*timer_interval_1000ms) DISPLAY_STAY_LONG = (stay_long) # 测量出有效温度后 屏幕持续显示时间 mlx90614Dev = 0 oled = 0 object_temp = 0.00 ambient_temp = 0.00 cal_hightemp_cnt = 0 cal_temp_cnt = 0 last_temp = 0 valid_temp = 0 blink = 0 display_time_cnt = 0 event_display = 0 start_cal_temp = 1 time_is_start = 0 displaytime_flag = 0 obj_buzzer = 0 pwmObj = 0 temptimerObj = 0 oledtimerObj = 0 displaytimerObj = 0 ######### # 物联网平台连接标志位 iot_connected = False wlan = None # 三元组信息 productKey = "产品密钥" #需要填入物联网云平台申请到的productKey信息 deviceName = "设备名称" #需要填入物联网云平台申请到的deviceName信息 deviceSecret = "设备密钥" #需要填入物联网云平台申请到的deviceSecret信息 # 物联网设备实例 device = None # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wlan wifi_connected = False wlan.active(True) #激活界面 wlan.scan() #扫描接入点 #print("start to connect ", wifiSsid) wlan.connect(wifiSsid, wifiPassword) # 连接到指定路由器名称和密码 while True: wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected: # Wi-Fi连接成功则退出while循环 break else: utime.sleep(0.5) print("wifi_connected:", wifi_connected) ifconfig = wlan.ifconfig() #获取接口的IP/netmask/gw/DNS地址 print(ifconfig) utime.sleep(0.5) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): pass def report_event(): upload_data = {'params': ujson.dumps({ 'object_temp': object_temp, }) } # 上传测到的人体异常温度信息到物联网平台 device.postProps(upload_data) def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 如果收到物联网平台发送的属性控制消息 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) ######### # init function def buzzer_init(): global obj_buzzer pwmObj = PWM() pwmObj.open("buzzer") print("buzzer inited!") obj_buzzer = buzzer.BUZZER(pwmObj) # define init freq and duty data_r = {'freq':2000, 'duty': 99} obj_buzzer.setOptionDuty(data_r) def buzzer_start(): data_r = {'freq':2000, 'duty': 95} obj_buzzer.setOptionDuty(data_r) def buzzer_stop(): data_r = {'freq':2000, 'duty': 99} obj_buzzer.setOptionDuty(data_r) #初始化oled模块 def oled_init(): global oled i2cObj = I2C() i2cObj.open("ssd1306") print("ssd1306 inited!") oled = SSD1306_I2C(128, 64, i2cObj) oled.fill(0) #清屏背景黑色 oled.text('2022-01-03', 30, 5) oled.text('12:00:00', 30, 22) oled.text(str('----------------------'),3,32) oled.text('connecting', 30, 40) oled.show() # 初始化mlx90614传感器 def mlx9061_init(): global mlx90614Dev i2cObj1 = I2C() i2cObj1.open("mlx90614") print("mlx90614 inited!") mlx90614Dev = mlx90614.MLX90614(i2cObj1) def display(): global oled,blink,display_time_cnt,start_cal_temp,time_is_start,displaytime_flag # i_am_temp = int(ambient_temp) i_obj_temp = int(object_temp) if i_obj_temp == INVALUDE_TEMP : return print("display ",event_display, display_time_cnt) oled.fill(0) #清屏背景黑色 if event_display == E_CAL_TEMP_HIGH: print('display high event') display_time_cnt += 1 if display_time_cnt >= DISPLAY_STAY_LONG : displaytime_flag = 1 oled_timer_stop() time_is_start = 0 start_cal_temp = 1 buzzer_stop() else : oled.text('hot'+'['+str('%d'%ABNORMAL_TEMP)+']', 20,20) oled.text(str('Cal:'+'%.2f'%valid_temp)+' C',20,40) elif event_display == E_CAL_TEMPING: if blink == 0: blink = 1 oled.text('checking', 40, 20) else: blink = 0 oled.text('', 60, 10) oled.text(str('hum:'+'%.2f'%object_temp)+' C',20,35) oled.text(str('amb:'+'%.2f'%ambient_temp)+' C',20,50) elif event_display == E_CAL_TEMP_FINISH: print('display finish enent') display_time_cnt += 1 if display_time_cnt >= DISPLAY_STAY_LONG : displaytime_flag = 1 oled_timer_stop() time_is_start = 0 start_cal_temp = 1 else : oled.text('Cal', 30, 20) oled.text(str('%.2f'%valid_temp)+' C',30,40) elif event_display == E_CAL_TEMP_INVALID: print('display ivalid enent') displaytime_flag = 1 oled_timer_stop() time_is_start = 0 oled.show() def read_ir_temp(): global ambient_temp,object_temp,mlx90614Dev ambient_temp = mlx90614Dev.read_ambient_temp() object_temp = mlx90614Dev.read_object_temp() # print("{0:>5.2f}C | {1:>5.2f}C".format(ambient_temp, object_temp), end='\r') # print("\r") def is_abnormal(obj_temp): global cal_hightemp_cnt,cal_temp_cnt,last_temp,valid_temp i_obj_temp = int(obj_temp) if i_obj_temp == INVALUDE_TEMP : return if i_obj_temp >= HIGH_LEVEL or i_obj_temp <= LOWER_LEVEL: last_temp = i_obj_temp cal_hightemp_cnt = 0 cal_temp_cnt = 0 return E_CAL_TEMP_INVALID else: if last_temp >= HIGH_LEVEL or last_temp <= LOWER_LEVEL: last_temp = i_obj_temp cal_temp_cnt = 1 cal_hightemp_cnt = 1 return E_CAL_TEMP_START #开始测温 if i_obj_temp >= ABNORMAL_TEMP: if last_temp < ABNORMAL_TEMP: cal_hightemp_cnt = 1 #重新开始测,第一次测到高温 else: cal_hightemp_cnt += 1 #连续测到高温 else: cal_hightemp_cnt = 0 #测到正常温度 cal_temp_cnt += 1 last_temp = i_obj_temp if cal_hightemp_cnt >= TEMP_CAL_TIMER_HIGH: cal_hightemp_cnt = 0 #连续测到10s高温,那么认定高温 valid_temp = obj_temp return E_CAL_TEMP_HIGH if cal_temp_cnt >= TEMP_CAL_TIMER: cal_temp_cnt = 0 valid_temp = obj_temp return E_CAL_TEMP_FINISH #连续15S,那么结束测温 return E_CAL_TEMPING def readtemp_callback(args): global event_display,display_time_cnt,start_cal_temp,time_is_start,displaytime_flag,last_temp if start_cal_temp == 1: read_ir_temp() else: return event_display = is_abnormal(object_temp) # print("{0:>5.2f}C | {1:>5.2f}C".format(ambient_temp, object_temp), end='\r') # print("\r") if event_display == E_CAL_TEMP_START: if time_is_start == 0: time_is_start = 1 oled_timer_restart() displaytime_flag = 0 print("start") display_time_cnt = 0 elif event_display == E_CAL_TEMP_HIGH: start_cal_temp = 0 last_temp = 0 print("high") buzzer_start() # 当前温度异常,上报当前温度 report_event() print("{0:>5.2f}C | {1:>5.2f}C".format(ambient_temp, object_temp), end='\r') print("\r") elif event_display == E_CAL_TEMP_FINISH: start_cal_temp = 0 last_temp = 0 print("finish") print("{0:>5.2f}C | {1:>5.2f}C".format(ambient_temp, object_temp), end='\r') print("\r") elif event_display == E_CAL_TEMP_INVALID: start_cal_temp = 1 def oleddisplay_callback(args): display() def display_time(timeArray): global displaytime_flag # print('flag :',displaytime_flag) if displaytime_flag == 1: oled.fill(0) oled.text(str('%d-%02d-%02d'%(timeArray[0],timeArray[1],timeArray[2])),30,5) oled.text(str('%02d:%02d:%02d'%(timeArray[3],timeArray[4],timeArray[5])),30,22) oled.text(str('----------------------'),3,32) oled.text('ready', 40, 40) oled.show() def displaytime_callback(args): timeArray = time.localtime() display_time(timeArray) def oled_timer_stop(): oledtimerObj.stop() print('time stop:') def oled_timer_start(): oledtimerObj.start() def oled_timer_restart(): print('------------------') ret1 = oledtimerObj.reload() print('reload time:',ret1) def temp_timer_stop(): temptimerObj.stop() def temp_timer_start(): temptimerObj.start() def timer_init(): global temptimerObj,oledtimerObj,displaytimerObj temptimerObj = TIMER(0) temptimerObj.open(mode=temptimerObj.PERIODIC, period=timer_interval_100ms, callback=readtemp_callback) temptimerObj.start() oledtimerObj = TIMER(1) oledtimerObj.open(mode=oledtimerObj.PERIODIC, period=1000, callback=oleddisplay_callback) displaytimerObj = TIMER(2) displaytimerObj.open(mode=displaytimerObj.PERIODIC, period=1000, callback=displaytime_callback) if __name__ == '__main__' : mlx9061_init() oled_init() ########## wlan = network.WLAN(network.STA_IF) #创建WLAN对象 get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) ########## buzzer_init() timer_init() while True: utime.sleep(2)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/human_ir_temperature/esp32/code/main.py
Python
apache-2.0
11,278
import ustruct from driver import I2C class SensorBase: def read16(self, register): data=bytearray(2) self._i2cDev.memRead(data,register,8) return ustruct.unpack('<H', data)[0] def read_temp(self, register): temp = self.read16(register) temp *= .02 temp -= 273.15 return temp def read_ambient_temp(self): return self.read_temp(self._REGISTER_TA) def read_object_temp(self): return self.read_temp(self._REGISTER_TOBJ1) def read_object2_temp(self): if self.dual_zone: return self.read_temp(self._REGISTER_TOBJ2) else: raise RuntimeError("Device only has one thermopile") @property def ambient_temp(self): return self.read_ambient_temp() @property def object_temp(self): return self.read_object_temp() @property def object2_temp(self): return self.read_object2_temp() class MLX90614(SensorBase): _REGISTER_TA = 0x06 _REGISTER_TOBJ1 = 0x07 _REGISTER_TOBJ2 = 0x08 def __init__(self, i2cDev, address=0x5a): self._i2cDev = None if not isinstance(i2cDev, I2C): raise ValueError("parameter is not an I2C object") self._i2cDev = i2cDev _config1=bytearray(2) self._i2cDev.memRead(_config1,0x25,8) _dz = ustruct.unpack('<H', _config1)[0] & (1<<6) self.dual_zone = True if _dz else False
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/human_ir_temperature/esp32/code/mlx90614.py
Python
apache-2.0
1,453
from micropython import const import framebuf from driver import I2C # register definitions SET_CONTRAST = const(0x81) SET_ENTIRE_ON = const(0xa4) SET_NORM_INV = const(0xa6) SET_DISP = const(0xae) SET_MEM_ADDR = const(0x20) SET_COL_ADDR = const(0x21) SET_PAGE_ADDR = const(0x22) SET_DISP_START_LINE = const(0x40) SET_SEG_REMAP = const(0xa0) SET_MUX_RATIO = const(0xa8) SET_COM_OUT_DIR = const(0xc0) SET_DISP_OFFSET = const(0xd3) SET_COM_PIN_CFG = const(0xda) SET_DISP_CLK_DIV = const(0xd5) SET_PRECHARGE = const(0xd9) SET_VCOM_DESEL = const(0xdb) SET_CHARGE_PUMP = const(0x8d) class SSD1306(framebuf.FrameBuffer): def __init__(self, width, height, external_vcc): self.width = width self.height = height self.external_vcc = external_vcc self.pages = self.height // 8 self.buffer = bytearray(self.pages * self.width) super().__init__(self.buffer, self.width, self.height, framebuf.MONO_VLSB) self.init_display() def init_display(self): for cmd in ( SET_DISP | 0x00, # off # address setting SET_MEM_ADDR, 0x00, # horizontal # resolution and layout SET_DISP_START_LINE | 0x00, SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0 SET_MUX_RATIO, self.height - 1, SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0 SET_DISP_OFFSET, 0x00, SET_COM_PIN_CFG, 0x02 if self.height == 32 else 0x12, # timing and driving scheme SET_DISP_CLK_DIV, 0x80, SET_PRECHARGE, 0x22 if self.external_vcc else 0xf1, SET_VCOM_DESEL, 0x30, # 0.83*Vcc # display SET_CONTRAST, 0xff, # maximum SET_ENTIRE_ON, # output follows RAM contents SET_NORM_INV, # not inverted # charge pump SET_CHARGE_PUMP, 0x10 if self.external_vcc else 0x14, SET_DISP | 0x01): # on self.write_cmd(cmd) self.fill(0) self.show() def poweroff(self): self.write_cmd(SET_DISP | 0x00) def poweron(self): self.write_cmd(SET_DISP | 0x01) def contrast(self, contrast): self.write_cmd(SET_CONTRAST) self.write_cmd(contrast) def invert(self, invert): self.write_cmd(SET_NORM_INV | (invert & 1)) def show(self): x0 = 0 x1 = self.width - 1 if self.width == 64: # displays with width of 64 pixels are shifted by 32 x0 += 32 x1 += 32 self.write_cmd(SET_COL_ADDR) self.write_cmd(x0) self.write_cmd(x1) self.write_cmd(SET_PAGE_ADDR) self.write_cmd(0) self.write_cmd(self.pages - 1) self.write_data(self.buffer) class SSD1306_I2C(SSD1306): def __init__(self, width, height, i2cDev, external_vcc=False): self._i2cDev = None if not isinstance(i2cDev, I2C): raise ValueError("parameter is not an I2C object") self._i2cDev = i2cDev self.temp = bytearray(2) super().__init__(width, height, external_vcc) def write_cmd(self, cmd): self.temp[0] = 0x80 # Co=1, D/C#=0 self.temp[1] = cmd self._i2cDev.write(self.temp) def write_data(self, buf): send_buf = bytearray(1 + len(buf)) send_buf[0] = 0x40 for i in range(len(buf)): send_buf[i+1] = buf[i] self._i2cDev.write(send_buf)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/human_ir_temperature/esp32/code/ssd1306.py
Python
apache-2.0
3,565
import lvgl as lv RESOURCES_ROOT = "S:/data/pyamp/" lvglInitialized = False class HumiturePanel: container = None scr = None humidityValue = None humidityLable = None def __init__(self): self.createPage() def createPage(self): global lvglInitialized if lvglInitialized == False: import display_driver lvglInitialized = True # init scr self.scr = lv.obj() self.scr.set_style_bg_color(lv.color_black(), 0) self.container = lv.obj(self.scr) self.container.set_style_bg_opa(0, 0) self.container.set_style_border_opa(0, 0) self.container.set_style_radius(0, 0) self.container.clear_flag(lv.obj.FLAG.SCROLLABLE) self.container.set_size(lv.SIZE.CONTENT, lv.SIZE.CONTENT) self.container.set_flex_flow(lv.FLEX_FLOW.COLUMN) self.container.set_style_align(lv.ALIGN.CENTER, 0) self.container.set_style_pad_left(0, 0) # create temperature item self.createTemperatureItem(self.container, RESOURCES_ROOT + "temperature.png", RESOURCES_ROOT + "centigrade_l.png", "Temperature") self.createInterval(self.container, 25) # create humidity item self.createHumidityItem(self.container, RESOURCES_ROOT + "humidity.png", "Humidity") # load content lv.scr_load(self.scr) def showHumiture(self, temperature, humidity): self.showTemperature(temperature) self.showHumidity(humidity) def showTemperature(self, temperature): self.temperatureLable.set_text(str(int(temperature))) def showHumidity(self, humidity): self.humidityLable.set_text(str(int(humidity)) + " %") def createTemperatureItem(self, parent, iconPath, unityPath, tips): col_dsc = [lv.GRID.CONTENT, 5, lv.GRID.CONTENT, lv.GRID.CONTENT, lv.GRID_TEMPLATE.LAST] row_dsc = [lv.GRID.CONTENT, lv.GRID.CONTENT, lv.GRID_TEMPLATE.LAST] cont = lv.obj(parent) cont.set_style_bg_opa(0, 0) cont.set_style_border_opa(0, 0) cont.set_style_pad_all(0, 0) cont.set_size(lv.SIZE.CONTENT, lv.SIZE.CONTENT) cont.set_style_grid_column_dsc_array(col_dsc, 0) cont.set_style_grid_row_dsc_array(row_dsc, 0) cont.set_layout(lv.LAYOUT_GRID.value) img = lv.img(cont) img.set_src(iconPath) img.set_grid_cell(lv.GRID_ALIGN.START, 0, 1, lv.GRID_ALIGN.CENTER, 0, 2) self.temperatureLable = lv.label(cont) self.temperatureLable.set_text("None") self.temperatureLable.set_style_text_color(lv.color_white(), 0) self.temperatureLable.set_style_text_font(lv.font_montserrat_48, 0) self.temperatureLable.set_style_pad_all(0, 0) self.temperatureLable.set_grid_cell(lv.GRID_ALIGN.START, 2, 1, lv.GRID_ALIGN.CENTER, 0, 1) iconImg = lv.img(cont) iconImg.set_src(unityPath) iconImg.set_zoom(205) iconImg.set_style_pad_bottom(0, 0) iconImg.set_grid_cell(lv.GRID_ALIGN.START, 3, 1, lv.GRID_ALIGN.CENTER, 0, 1) tip = lv.label(cont) tip.set_text(tips) tip.set_style_text_color(lv.color_make(0xCC, 0xCC, 0xCC), 0) tip.set_grid_cell(lv.GRID_ALIGN.START, 2, 2, lv.GRID_ALIGN.START, 1, 1) def createHumidityItem(self, parent, iconPath, tips): col_dsc = [lv.GRID.CONTENT, 5, lv.GRID.CONTENT, lv.GRID.CONTENT, lv.GRID_TEMPLATE.LAST] row_dsc = [lv.GRID.CONTENT, lv.GRID.CONTENT, lv.GRID_TEMPLATE.LAST] cont = lv.obj(parent) cont.set_style_bg_opa(0, 0) cont.set_style_border_opa(0, 0) cont.set_style_pad_all(0, 0) cont.set_size(lv.SIZE.CONTENT, lv.SIZE.CONTENT) cont.set_style_grid_column_dsc_array(col_dsc, 0) cont.set_style_grid_row_dsc_array(row_dsc, 0) cont.set_layout(lv.LAYOUT_GRID.value) img = lv.img(cont) img.set_src(iconPath) img.set_grid_cell(lv.GRID_ALIGN.START, 0, 1, lv.GRID_ALIGN.CENTER, 0, 2) self.humidityLable = lv.label(cont) self.humidityLable.set_text("None %") self.humidityLable.set_style_text_color(lv.color_white(), 0) self.humidityLable.set_style_text_font(lv.font_montserrat_48, 0) self.humidityLable.set_style_pad_all(0, 0) self.humidityLable.set_grid_cell(lv.GRID_ALIGN.START, 2, 1, lv.GRID_ALIGN.CENTER, 0, 1) tip = lv.label(cont) tip.set_text(tips) tip.set_style_text_color(lv.color_make(0xCC, 0xCC, 0xCC), 0) tip.set_grid_cell(lv.GRID_ALIGN.START, 2, 2, lv.GRID_ALIGN.START, 1, 1) def createInterval(self, parent, size): interval = lv.obj(parent) interval.set_style_bg_opa(0, 0) interval.set_style_border_opa(0, 0) interval.set_height(int(size)) interval.set_width(0)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/humiture_panel/m5stack/code/humiturePanel.py
Python
apache-2.0
4,853
from humiturePanel import HumiturePanel import utime import sht3x from driver import I2C # 创建I2C对象,用于创建I2C类型的温湿度设备 i2cObj = I2C() # 打开I2C对象 i2cObj.open("sht3x") # 创建SHT3X温湿度传感器对象 humitureDev = sht3x.SHT3X(i2cObj) print('create humiture device') humiturePage = HumiturePanel() print('create humiture panel') while True: temperature = humitureDev.getTemperature() humidity = humitureDev.getHumidity() print('temperature:', temperature) print('humidity:', humidity) humiturePage.showHumiture(temperature, humidity) utime.sleep(1) i2cObj.close() delete humitureDev
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/humiture_panel/m5stack/code/main.py
Python
apache-2.0
654
""" Copyright (C) 2015-2021 Alibaba Group Holding Limited MicroPython's driver for CHT8305 Author: HaaS Date: 2021/09/14 """ from micropython import const import utime from driver import I2C ''' # sht3x commands definations # read serial number: CMD_READ_SERIALNBR 0x3780 # read status register: CMD_READ_STATUS 0xF32D # clear status register: CMD_CLEAR_STATUS 0x3041 # enabled heater: CMD_HEATER_ENABLE 0x306D # disable heater: CMD_HEATER_DISABLE 0x3066 # soft reset: CMD_SOFT_RESET 0x30A2 # accelerated response time: CMD_ART 0x2B32 # break, stop periodic data acquisition mode: CMD_BREAK 0x3093 # measurement: polling, high repeatability: CMD_MEAS_POLLING_H 0x2400 # measurement: polling, medium repeatability: CMD_MEAS_POLLING_M 0x240B # measurement: polling, low repeatability: CMD_MEAS_POLLING_L 0x2416 ''' class SHT3X(object): # i2cDev should be an I2C object and it should be opened before __init__ is called def __init__(self, i2cDev): self._i2cDev = None if not isinstance(i2cDev, I2C): raise ValueError("parameter is not an I2C object") # make AHB21B's internal object points to _i2cDev self._i2cDev = i2cDev self.start() def start(self): # make sure AHB21B's internal object is valid before I2C operation if self._i2cDev is None: raise ValueError("invalid I2C object") # send clear status register command - 0x3041 - CMD_CLEAR_STATUS cmd = bytearray(2) cmd[0] = 0x30 cmd[1] = 0x41 self._i2cDev.write(cmd) # wait for 20ms utime.sleep_ms(20) return 0 def getTempHumidity(self): if self._i2cDev is None: raise ValueError("invalid I2C object") tempHumidity = [-1, 2] # start measurement: polling, medium repeatability - 0x240B - CMD_MEAS_POLLING_M # if you want to adjust measure repeatability, you can send the following commands: # high repeatability: 0x2400 - CMD_MEAS_POLLING_H # low repeatability: 0x2416 - CMD_MEAS_POLLING_L cmd = bytearray(2) cmd[0] = 0x24 cmd[1] = 0x0b self._i2cDev.write(cmd) # must wait for a little before the measurement finished utime.sleep_ms(20) dataBuffer = bytearray(6) # read the measurement result self._i2cDev.read(dataBuffer) # print(dataBuffer) # calculate real temperature and humidity according to SHT3X-DIS' data sheet temp = (dataBuffer[0]<<8) | dataBuffer[1] humi = (dataBuffer[3]<<8) | dataBuffer[4] tempHumidity[1] = humi * 0.0015259022 tempHumidity[0] = -45.0 + (temp) * 175.0 / (0xFFFF - 1) return tempHumidity def getTemperature(self): data = self.getTempHumidity() return data[0] def getHumidity(self): data = self.getTempHumidity() return data[1] def stop(self): if self._i2cDev is None: raise ValueError("invalid I2C object") # stop periodic data acquisition mode cmd = bytearray(3) cmd[0] = 0x30 cmd[1] = 0x93 self._i2cDev.write(cmd) # wait for a little while utime.sleep_ms(20) self._i2cDev = None return 0 def __del__(self): print('sht3x __del__') if __name__ == "__main__": ''' The below i2c configuration is needed in your board.json. "sht3x": { "type": "I2C", "port": 1, "addrWidth": 7, "freq": 400000, "mode": "master", "devAddr": 68 }, ''' print("Testing sht3x ...") i2cDev = I2C() i2cDev.open("sht3x") sht3xDev = SHT3X(i2cDev) ''' # future usage: i2cDev = I2C("sht3x") sht3xDev = sht3x.SHT3X(i2cDev) ''' temperature = sht3xDev.getTemperature() print("The temperature is: %f" % temperature) humidity = sht3xDev.getHumidity() print("The humidity is: %f" % humidity) print("Test sht3x done!")
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/humiture_panel/m5stack/code/sht3x.py
Python
apache-2.0
4,279
# -*- coding: UTF-8 -*- import net import http import ujson class LBS(): def __init__(self): self.requesturl = '' self.url = 'http://apilocate.amap.com/position' self.accesstype = 0 #input your key here self.key = 'yourKey' self.cdma = 0 self.output = 'json' self.bts = '' self.nearbts = '' self.htp = http.client() pass def get_lbs(self): nbrinfo = net.getCellInfo() srvinfo = net.getState() #gsm if len(srvinfo[0]) > 0: pass if len(srvinfo[1]) > 0: pass #lte if len(srvinfo[2]) > 0: srv = srvinfo[2] self.bts = str(hex(srv[2]))[2:] + ',' + str(srv[3]) +','+ str(srv[6])+ ',' + str(srv[1]) + ',' + str(srv[7]) pass if len(nbrinfo[0]) > 0: pass if len(nbrinfo[1]) > 0: pass if len(nbrinfo[2]) > 0: nbr = nbrinfo[2] print(nbr,nbrinfo,len(nbr)) for i in range(len(nbr)): self.nearbts += str(hex(nbr[i][2]))[2:] + ',' + str(nbr[i][3]) + ',' + str(nbr[i][6]) + ',' + str(nbr[i][1]) + ',' + str(nbr[i][7]) if i != (len(nbr) - 1): self.nearbts += '|' pass self.requesturl += self.url + '?' + 'accesstype=' + str(self.accesstype) + '&key=' + self.key + '&cdma=' + str(self.cdma) + '&output=' + self.output + '&bts=' + self.bts + '&nearbts=' + self.nearbts print(self.requesturl) ret = self.htp.get(self.requesturl) if ret < 0: return None retstr = self.htp.get_response() self.htp.close() locationstr = None lat = None lon = None try: retdict = ujson.loads(retstr) try: if int(retdict['infocode']) != 10000: return None try: locationstr = retdict['result']['location'] tmpstr = locationstr.split(',') lon = tmpstr[0] lat = tmpstr[1] print('content:',retdict) except KeyError: return None finally: return lon,lat except KeyError: return None finally: return lon,lat except ValueError: return None finally: return lon,lat ''' 响应: content: {'result': {'citycode': '0512', 'type': '4', 'city': '苏州市', 'poi': '中国工商银行(苏州独墅湖支行)', 'desc': '江苏省 苏州市 虎丘区 仁爱路 靠近中国工商银行(苏州独墅湖支行)', 'adcode': '320505', 'street': '仁爱路', 'radius': '550', 'location': '120.7394987,31.2744203', 'road': '仁爱路', 'country': '中国', 'province': '江苏省'}, 'status': '1', 'infocode': '10000', 'info': 'OK'} '''
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/lbs_demo/haas506/code/lbs.py
Python
apache-2.0
2,988
import utime as time import network from lbs import LBS g_connect_status = False def on_4g_cb(args): global g_connect_status pdp = args[0] netwk_sta = args[1] if netwk_sta == 1: g_connect_status = True else: g_connect_status = False def connect_network(): global net,on_4g_cb,g_connect_status net = network.NetWorkClient() g_register_network = False if net._stagecode is not None and net._stagecode == 3 and net._subcode == 1: g_register_network = True else: g_register_network = False if g_register_network: net.on(1,on_4g_cb) net.connect(None) else: print('network register failed') while True: if g_connect_status: print('network register successed') break time.sleep_ms(20) if __name__ == '__main__': connect_network() getlbs = LBS() lbstr = getlbs.get_lbs() print(lbstr)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/lbs_demo/haas506/code/main.py
Python
apache-2.0
945
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : cloudAI.py @Description: 云端AI @Author : jiangyu @version : 1.0 ''' from aliyunIoT import Device import utime # 延时函数在utime库中 import ujson as json class CloudAI : def __gesture_cb(self, dict) : ''' Reply list : handGestureReply : 手势识别 ''' gesture = 'NA' if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': score = ext_dict['score'] if score > 0.4 : gesture = ext_dict['type'] print("recognize hand gesture : " + gesture) self.__cb('handGestureReply', gesture) def __license_plate_cb(self, dict) : plateNumber = 'NA' if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': g_confidence = ext_dict['confidence'] if g_confidence > 0.7 : plateNumber = ext_dict['plateNumber'] print('detect: ' + plateNumber) self.__cb('ocrCarNoReply', plateNumber) def __fruits_cb(self, dict) : fruit_name = 'NA' if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': i = 0 fruits_list = ext_dict['fruitList'] while (i < len(fruits_list)) : g_score = fruits_list[i]['score'] fruit_name = fruits_list[i]['name'] if g_score > 0.6: print('detect: ' + fruit_name) i += 1 self.__cb('detectFruitsReply', fruit_name) def __pedestrian_cb(self, dict) : detected = False if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': i = 0 data = ext_dict['data'] data_dict = json.loads(data) elements_list = data_dict['elements'] while (i < len(elements_list)) : g_score = elements_list[i]['score'] if g_score > 0.6: print('Pedestrian Detected') detected = True i += 1 self.__cb('DetectPedestrianReply', detected) def __businesscard_cb(self, dict) : card_info = {} if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': card_info['name'] = ext_dict['name'] print("name : " + card_info['name']) if card_info['name'] == '' : card_info['name'] = 'unknown' phoneNumbers_list = ext_dict['cellPhoneNumbers'] print("phoneNumbers : ") print(phoneNumbers_list) if len(phoneNumbers_list) : card_info['phoneNumbers'] = phoneNumbers_list[0] else : card_info['phoneNumbers'] = 'unknown' email_list = ext_dict['emails'] print("email_list: ") print(email_list) if len(email_list) : card_info['email'] = email_list[0] else : card_info['email'] = 'unknown' self.__cb('recognizeBusinessCardReply', card_info) def __rubblish_cb(self, dict) : name = 'NA' if dict != None: ext = dict['ext'] extDict = json.loads(ext) result = extDict['result'] if result == 'success': i = 0 elements = extDict['elements'] while (i < len(elements)) : gScore = elements[i]['categoryScore'] if gScore > 0.8: name = elements[i]['category'] print('detect: ' + name) break i += 1 self.__cb('classifyingRubbishReply', name) def __object_cb(self, dict) : name = 'NA' if dict != None: ext = dict['ext'] extDict = json.loads(ext) result = extDict['result'] if result == 'success': i = 0 elements = extDict['elements'] while (i < len(elements)) : gScore = elements[i]['score'] if gScore > 0.25: name = elements[i]['type'] print('detect: ' + name) break i += 1 self.__cb('detectObjectReply', name) def __vehicletype_cb(self, dict) : name = 'NA' detect = False if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': i = 0 item_list = ext_dict['items'] name = 'NA' while (i < len(item_list)) : g_score = item_list[i]['score'] name = item_list[i]['name'] # 这里可以修改识别的可信度,目前设置返回可信度大于85%才认为识别正确 if g_score > 0.85 and name != 'others': print('detect: ' + name) detect = True self.__cb('recognizeVehicleReply', name) break i += 1 if detect == False: self.__cb('recognizeVehicleReply', 'NA') def __vehiclelogo_cb(self, dict) : num = 0 if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': item_list = ext_dict['elements'] num = len(item_list) if num > 0: print('detect: ' + str(num) + ' vehicle') detected = True if detected == False: print('do not detect!') self.__cb('recognizeLogoReply', num) def __cb_lk_service(self, data): self.g_lk_service = True print('download <----' + str(data)) if data != None : params = data['params'] params_dict = json.loads(params) command = params_dict['commandName'] if command == 'handGestureReply' : self.__gesture_cb(params_dict) elif command == 'ocrCarNoReply' : self.__license_plate_cb(params_dict) elif command == 'DetectPedestrianReply' : self.__pedestrian_cb(params_dict) elif command == 'detectFruitsReply' : self.__fruits_cb(params_dict) elif command == 'recognizeBusinessCardReply' : self.__businesscard_cb(params_dict) elif command == 'classifyingRubbishReply' : self.__rubblish_cb(params_dict) elif command == 'detectObjectReply' : self.__object_cb(params_dict) elif command == 'recognizeVehicleReply' : self.__vehicletype_cb(params_dict) elif command == 'recognizeLogoReply' : self.__vehiclelogo_cb(params_dict) else : print('unknown command reply') def __cb_lk_connect(self, data): print('link platform connected') self.g_lk_connect = True def __connect_iot(self) : self.device = Device() self.device.on(Device.ON_CONNECT, self.__cb_lk_connect) self.device.on(Device.ON_SERVICE, self.__cb_lk_service) self.device.connect(self.__dev_info) while True: if self.g_lk_connect: break def __init__(self, dev_info, callback) : self.__dev_info = dev_info self.__cb = callback self.g_lk_connect = False self.g_lk_service = False self.__connect_iot() def getDevice(self) : return self.device def __upload_request(self, command, frame) : # 上传图片到LP fileName = 'test.jpg' start = utime.ticks_ms() fileid = self.device.uploadContent(fileName, frame, None) if fileid != None: ext = { 'filePosition':'lp', 'fileName': fileName, 'fileId': fileid } ext_str = json.dumps(ext) all_params = {'id': 1, 'version': '1.0', 'params': { 'eventType': 'haas.faas', 'eventName': command, 'argInt': 1, 'ext': ext_str }} all_params_str = json.dumps(all_params) #print(all_params_str) upload_file = { 'topic': '/sys/' + self.__dev_info['productKey'] + '/' + self.__dev_info['deviceName'] + '/thing/event/hli_event/post', 'qos': 1, 'payload': all_params_str } # 上传完成通知HaaS聚合平台 print('upload--->' + str(upload_file)) self.g_lk_service = False self.device.publish(upload_file) i = 0 while (self.g_lk_service == False and i < 200) : utime.sleep_ms(10) i = i + 1 continue else: print('filedid is none, upload content fail') time_diff = utime.ticks_diff(utime.ticks_ms(), start) print('recognize time : %d' % time_diff) def recognizeGesture(self, frame) : self.__upload_request('handGesture', frame) def recognizeLicensePlate(self, frame) : self.__upload_request('ocrCarNo', frame) def detectPedestrian(self, frame) : self.__upload_request('detectPedestrian', frame) def detectFruits(self, frame) : self.__upload_request('detectFruits', frame) def recognizeBussinessCard(self, frame) : self.__upload_request('recognizeBusinessCard', frame) def recognizeVehicleType(self, frame) : self.__upload_request('recognizeVehicle', frame) def detectVehicleCongestion(self, frame) : self.__upload_request('vehicleCongestionDetect', frame) def classifyRubbish(self, frame) : self.__upload_request('classifyingRubbish', frame) def detectObject(self, frame) : self.__upload_request('detectObject', frame)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/license_plate_recognization/esp32/code/cloudAI.py
Python
apache-2.0
10,770
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : main.py @Description: 车牌识别案例 @Author : luokui & jiangyu @version : 2.0 ''' import display # 显示库 import network # 网络库 import ucamera # 摄像头库 import utime # 延时函数在utime库中 import _thread # 线程库 import sntp # 网络时间同步库 from cloudAI import * # Wi-Fi SSID和Password设置 SSID='Your-AP-SSID' PWD='Your-AP-Password' # HaaS设备三元组 productKey = "Your-ProductKey" deviceName = "Your-devicename" deviceSecret = "Your-deviceSecret" detected = False plateNumber = '' key_info = { 'region' : 'cn-shanghai' , 'productKey': productKey , 'deviceName': deviceName , 'deviceSecret': deviceSecret , 'keepaliveSec': 60 } def connect_wifi(ssid, pwd): # 引用全局变量 global disp # 初始化网络 wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(ssid, pwd) while True: print('Wi-Fi is connecting...') # 显示网络连接中 disp.text(20, 30, 'Wi-Fi is connecting...', disp.RED) # 网络连接成功后,更新显示字符 if (wlan.isconnected() == True): print('Wi-Fi is connected') disp.textClear(20, 30, 'Wi-Fi is connecting...') disp.text(20, 30, 'Wi-Fi is connected', disp.RED) ip = wlan.ifconfig()[0] print('IP: %s' %ip) disp.text(20, 50, ip, disp.RED) # NTP时间更新,如果更新不成功,将不能进行识别 print('NTP start') disp.text(20, 70, 'NTP start...', disp.RED) sntp.setTime() print('NTP done') disp.textClear(20, 70, 'NTP start...') disp.text(20, 70, 'NTP done', disp.RED) break utime.sleep_ms(500) utime.sleep(2) def recognize_cb(commandReply, result) : global detected, plateNumber plateNumber = 'NA' detected = False if commandReply == 'ocrCarNoReply' : if result != 'NA' : plateNumber = result detected = True else : print('unknown command reply') # 识别线程函数 def recognizeThread(): global frame while True: if frame != None: engine.recognizeLicensePlate(frame) utime.sleep_ms(1000) else: utime.sleep_ms(1000) # 显示线程函数 def displayThread(): # 引用全局变量 global disp, frame, detected, plateNumber # 定义清屏局部变量 clearFlag = False # 定义显示文本局部变量 textShowFlag = False while True: # 采集摄像头画面 # print('start to capture') frame = ucamera.capture() # print('end to capture') if frame != None: if detected == True: # 清除屏幕内容 disp.clear() # 设置文字字体 disp.font(disp.FONT_DejaVu40) # 显示识别结果 disp.text(25, 90, plateNumber, disp.RED) disp.text(25, 130, 'Recognized!!!', disp.RED) utime.sleep_ms(1000) textShowFlag = False else: # 显示图像 # print('start to display') disp.image(0, 20, frame, 0) utime.sleep_ms(100) if textShowFlag == False: # 设置显示字体 disp.font(disp.FONT_DejaVu18) # 显示文字 disp.text(2, 0, 'Recognizing...', disp.WHITE) textShowFlag = True def main(): # 全局变量 global disp, frame, detected, gesture, engine # 创建lcd display对象 disp = display.TFT() frame = None detected = False # 连接网络 connect_wifi(SSID, PWD) engine = CloudAI(key_info, recognize_cb) # 初始化摄像头 ucamera.init('uart', 33, 32) ucamera.setProp(ucamera.SET_FRAME_SIZE, ucamera.SIZE_320X240) try: # 启动显示线程 _thread.start_new_thread(displayThread, ()) # 设置比对线程stack _thread.stack_size(20 * 1024) # 启动比对线程 _thread.start_new_thread(recognizeThread, ()) except: print("Error: unable to start thread") while True: utime.sleep_ms(1000) if __name__ == '__main__': main()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/license_plate_recognization/esp32/code/main.py
Python
apache-2.0
4,492
from driver import GPIO from time import sleep class Buzzer: def __init__(self, io_name) -> None: self.gpio = GPIO() ret = self.gpio.open(io_name) if ret < 0: raise Exception("Error opening gpio ", io_name, " ret=", ret) ret = self.gpio.write(0) if ret < 0: raise Exception("Error writing init value 1 to gpio ", io_name, " ret=", ret) def beep(self, duration_ms): self.gpio.write(1) sleep(duration_ms / 1000) self.gpio.write(0)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/local_gesture_recognize/esp32/code/buzzer.py
Python
apache-2.0
528
# 本地手势识别 ###################### #### 请修改此处信息 #### PRODUCT_KEY = '这里填写产品PK' DEVICE_NAME = '这里填入设备名称DN' DEVICE_SECRET = '这里填入设备密钥DS' WIFI_SSID = 'WiFi名称' WIFI_PWD = 'WiFi密码' ###################### # 导入框架模块 from time import sleep import ujson as json import network import kv from aliyunIoT import Device # 导入工程内驱动模块 from buzzer import Buzzer from paj7620 import Gesture # 关闭固件内一分钟上云 MQTT 通道以释放内存 kv.set('app_upgrade_channel', 'disable') buzzer = Buzzer("Buzzer") def beep_ok(): buzzer.beep(500) def beep_error(): buzzer.beep(100) sleep(0.1) buzzer.beep(100) sleep(0.1) buzzer.beep(100) def beep_gesture(): buzzer.beep(20) # 连接WiFi print("Connecting to WiFi...") wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.scan() wlan.connect(WIFI_SSID, WIFI_PWD) while True: if wlan.isconnected(): break print("Waiting for WiFi connection...") sleep(1) print(wlan.ifconfig()) print("WiFi Connected") isIotConnected = False def on_connect(data): global isIotConnected print("ON_CONNECT: ", data) isIotConnected = True # 连接物联网平台 print("Connecting to IoT LinkPlatform...") device = Device() device.on(Device.ON_CONNECT, on_connect) device.connect({ 'region': "cn-shanghai", 'productKey': PRODUCT_KEY, 'deviceName': DEVICE_NAME, 'deviceSecret': DEVICE_SECRET, 'keepaliveSec': 60 }) while True: if isIotConnected: print('IoT Platform connected') break else: print('Waiting for IoT Platform connection...') sleep(1) def post_gesture_event(name): device.publish({ 'topic': '/sys/' + PRODUCT_KEY + '/' + DEVICE_NAME + '/thing/event/gesture/post', 'payload': json.dumps({ "id": "6", "version": "1.0", "params": { "name": name } }), 'qos': 1 }) def post_gesture_property(value): device.postProps({ 'params': json.dumps({ 'lastGesture': value }) }) # 定义手势处理函数 def handle_wave(): print("WAVE") post_gesture_event("WAVE") post_gesture_property(9) beep_gesture() def handle_up(): print("UP") post_gesture_event("UP") post_gesture_property(1) beep_gesture() def handle_down(): print("DOWN") post_gesture_event("DOWN") post_gesture_property(2) beep_gesture() def handle_left(): print("LEFT") post_gesture_event("LEFT") post_gesture_property(3) beep_gesture() def handle_right(): print("RIGHT") post_gesture_event("RIGHT") post_gesture_property(4) beep_gesture() def handle_forward(): print("FORWARD") post_gesture_event("FORWARD") post_gesture_property(5) beep_gesture() def handle_backward(): print("BACKWARD") post_gesture_event("BACKWARD") post_gesture_property(6) beep_gesture() def handle_clockwise(): print("CLOCKWISE") post_gesture_event("CLOCKWISE") post_gesture_property(7) beep_gesture() def handle_anticlockwise(): print("ANTICLOCKWISE") post_gesture_event("ANTICLOCKWISE") post_gesture_property(8) beep_gesture() # 初始化手势处理模块 print("Initializing gesture recognizer...") try: gesture = Gesture("PAJ7620_I2C", "PAJ7620_IRQ", { Gesture.WAVE: handle_wave, Gesture.UP: handle_up, Gesture.DOWN: handle_down, Gesture.LEFT: handle_left, Gesture.RIGHT: handle_right, Gesture.FORWARD: handle_forward, Gesture.BACKWARD: handle_backward, Gesture.CLOCKWISE: handle_clockwise, Gesture.ANTICLOCKWISE: handle_anticlockwise }) print("Done") beep_ok() except IOError as e: print("Gesture initialize error:", e) beep_error() # 主程序不退出 while True: sleep(0.01)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/local_gesture_recognize/esp32/code/main.py
Python
apache-2.0
3,980
from driver import I2C from driver import GPIO from time import sleep from uasyncio import run class Gesture: WAVE = 0 UP = 1 DOWN = 2 LEFT = 4 RIGHT = 8 FORWARD = 16 BACKWARD = 32 CLOCKWISE = 64 ANTICLOCKWISE = 128 _REG_INIT_LIST = [ [0xEF, 0x00], [0x41, 0x00], [0x42, 0x00], [0x37, 0x07], [0x38, 0x17], [0x39, 0x06], [0x42, 0x01], [0x46, 0x2D], [0x47, 0x0F], [0x48, 0x3C], [0x49, 0x00], [0x4A, 0x1E], [0x4C, 0x22], [0x51, 0x10], [0x5E, 0x10], [0x60, 0x27], [0x80, 0x42], [0x81, 0x44], [0x82, 0x04], [0x8B, 0x01], [0x90, 0x06], [0x95, 0x0A], [0x96, 0x0C], [0x97, 0x05], [0x9A, 0x14], [0x9C, 0x3F], [0xA5, 0x19], [0xCC, 0x19], [0xCD, 0x0B], [0xCE, 0x13], [0xCF, 0x64], [0xD0, 0x21], [0xEF, 0x01], [0x02, 0x0F], [0x03, 0x10], [0x04, 0x02], [0x25, 0x01], [0x27, 0x39], [0x28, 0x7F], [0x29, 0x08], [0x3E, 0xFF], [0x5E, 0x3D], [0x65, 0x96], [0x67, 0x97], [0x69, 0xCD], [0x6A, 0x01], [0x6D, 0x2C], [0x6E, 0x01], [0x72, 0x01], [0x73, 0x35], [0x74, 0x00], [0x77, 0x01], [0xEF, 0x00], [0x41, 0xFF], [0x42, 0x01], [0xEF, 0x00], [0x41, 0x00], [0x42, 0x00], [0x48, 0x3C], [0x49, 0x00], [0x51, 0x10], [0x83, 0x20], [0x9f, 0xf9], [0xEF, 0x01], [0x01, 0x1E], [0x02, 0x0F], [0x03, 0x10], [0x04, 0x02], [0x41, 0x40], [0x43, 0x30], [0x65, 0x96], [0x66, 0x00], [0x67, 0x97], [0x68, 0x01], [0x69, 0xCD], [0x6A, 0x01], [0x6b, 0xb0], [0x6c, 0x04], [0x6D, 0x2C], [0x6E, 0x01], [0x74, 0x00], [0xEF, 0x00], [0x41, 0xFF], [0x42, 0x01] ] def __init__(self, i2c_name, irq_name, handler_func_map) -> None: self.i2c = I2C() ret = self.i2c.open(i2c_name) if ret < 0: raise Exception("Error open I2C ", i2c_name, " ret=", ret) self.irq = GPIO() ret = self.irq.open(irq_name) if ret < 0: raise Exception("Error open GPIO ", irq_name, " as IQR:", ret) self.handlerFuncMap = handler_func_map sleep(0.01) self._select_bank(0) self._select_bank(0) reg0 = self._read_reg(0) if reg0 != 0x20: raise Exception("Unexpected value", reg0, " in wake-up reg:0x00") for rvPair in self._REG_INIT_LIST: self._write_reg(rvPair) self.irq.on(self._irq_handler) def _select_bank(self, bank) -> None: ret = self.i2c.write(bytearray([0xEF, bank])) if ret < 0: raise Exception("selectBank: write data error, ret=", ret) def _write_reg(self, pair) -> None: ret = self.i2c.write(bytearray([pair[0], pair[1]])) if ret < 0: raise Exception("selectBank: write data error, ret=", ret) def _read_reg(self, addr) -> int: ret = self.i2c.write(bytearray([addr])) if ret < 0: raise Exception("readReg: write addr error, ret=", ret) value = bytearray(1) ret = self.i2c.read(value) if ret < 0: raise Exception("readReg: read data error, ret=", ret) return value[0] async def _cb(self, func): func() def _irq_handler(self, data) -> None: reg43 = self._read_reg(0x43) if reg43 == Gesture.WAVE: reg44 = self._read_reg(0x44) if reg44 != 0x01: return func = self.handlerFuncMap.get(reg43) if callable(func): run(self._cb(func))
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/local_gesture_recognize/esp32/code/paj7620.py
Python
apache-2.0
3,541
######### from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import ujson ################## import utime # 延时函数在utime库中 from math import pi from driver import I2C import pca9685 robotDev = None ######### # 物联网平台连接标志位 iot_connected = False wlan = None # 三元组信息 productKey = "产品密钥" #需要填入物联网云平台申请到的productKey信息 deviceName = "设备名称" #需要填入物联网云平台申请到的deviceName信息 deviceSecret = "设备密钥" #需要填入物联网云平台申请到的deviceSecret信息 # 物联网设备实例 device = None # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wlan wifi_connected = False wlan.active(True) #激活界面 wlan.scan() #扫描接入点 #print("start to connect ", wifiSsid) wlan.connect(wifiSsid, wifiPassword) # 连接到指定路由器名称和密码 while True: wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected: # Wi-Fi连接成功则退出while循环 break else: utime.sleep(0.5) print("wifi_connected:", wifi_connected) ifconfig = wlan.ifconfig() #获取接口的IP/netmask/gw/DNS地址 print(ifconfig) utime.sleep(0.5) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): payload = ujson.loads(request['params']) # print (payload) # 获取dict状态字段 注意要验证键存在 否则会抛出异常 if "operate_machine" in payload.keys(): value = payload["operate_machine"] if value == 1: left_ctrl() print("左移") elif value == 2: right_ctrl() print("右移") elif value == 3: front_ctrl() print("前移") elif value == 4: back_ctrl() print("后移") elif value == 5: catch_ctrl() print("夹住") elif value == 6: uncatch_ctrl() print("放开") else: print("No operate") def report_event(): upload_data = {'params': ujson.dumps({'onoff': 0,})} # 上传开关状态到物联网平台 device.postProps(upload_data) def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 如果收到物联网平台发送的属性控制消息 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) ######### def pca9685_init(): global robotDev i2cObj = I2C() i2cObj.open("pca9685") robotDev=pca9685.PCA9685(i2cObj) print('pca9865 inited') def left_ctrl(): robotDev.setServo(0,-pi/2) def right_ctrl(): robotDev.setServo(0,pi/2) def front_ctrl(): robotDev.setServo(1,-pi/2) def back_ctrl(): robotDev.setServo(1,pi/2) def catch_ctrl(): robotDev.setServo(3,-pi/2) def uncatch_ctrl(): robotDev.setServo(3,0) if __name__ == '__main__': pca9685_init() ########## wlan = network.WLAN(network.STA_IF) #创建WLAN对象 get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) ########## while True: utime.sleep(1)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/machine_arm/esp32/code/main.py
Python
apache-2.0
4,411
import time from ustruct import pack from math import pi from driver import I2C import math class PCA9685: def __init__(self, i2cDev): self._i2c = None if not isinstance(i2cDev, I2C): raise ValueError("parameter is not an I2C object") self._i2c = i2cDev self.freq = 50 #50hz == 20ms self.ontime = 410 self.setFreq(self.freq) def setFreq(self,freq = None): prescale = int(25000000.0 / 4096.0 / freq + 0.5) self._i2c.memWrite(b'\x10',0x00,8) self._i2c.memWrite(pack('B',prescale),0xfe,8) self._i2c.memWrite(b'\x00',0x00,8) time.sleep_us(5) self._i2c.memWrite(b'\xa1',0x00,8) def pwm(self,index, on=None, off=None): self._i2c.memWrite(pack('<HH',on,off),0x06 + (index*4),8) def reset(self, index): self.pwm(index, 0 , 4095) def setServo(self,index,pos): if pos > 0: value = 205*(pos/(pi/2)) self.offtime = self.ontime + 306 + int(value) elif pos < 0: value = 205*((-pos)/(pi/2)) self.offtime = self.ontime + 306 - int(value) else: self.offtime = self.ontime + 306 self.pwm(index,self.ontime,self.offtime)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/machine_arm/esp32/code/pca9685.py
Python
apache-2.0
1,217
# -*- encoding: utf-8 -*- from music import MusicPlayer player = MusicPlayer() player.createPage() print('Music Player started') my_music = { "title":"spring_short", "album":"Darius", "album_url": '', "url":"file://data/pyamp/spring.mp3", "duration":30, "favorite": False } player.addToList(my_music) print('add new music into play list')
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/music_player/code/main.py
Python
apache-2.0
366
import lvgl as lv from axp192 import * from audio import Player RESOURCES_ROOT = "S:/data/pyamp/" functionImage = [ RESOURCES_ROOT + 'images/' + "prev.png", RESOURCES_ROOT + 'images/' + "play.png", RESOURCES_ROOT + 'images/' + "next.png", RESOURCES_ROOT + 'images/' + "favorite.png"] musicData = [ { "title":"Counting Stars", "album":"OneRepublic", "album_url": RESOURCES_ROOT + "album_one_republic.jpg", "url":"file://data/pyamp/long.mp3", "duration":11, "favorite": False }, { "title":"Aube", "album":"Darius", "album_url": RESOURCES_ROOT + "album_darius.jpg", "url":"file://data/pyamp/spring.mp3", "duration":155, "favorite": False }, ] lvglInitialized = False currentMusic = 0 start = False anim = None playedTime = None slider = None anim_timeline = None player = None durationTime = 0 currentValue = 0 image = [None, None, None, None] albumCover = None songTitle = None albumTitle = None totalTime = None def setLabelValue(label, value): global slider global anim global start global anim_timeline global durationTime minute = value / 60 second = value % 60 # if (slider.is_dragged() == True): # print("drag: %d" % value) # start = False # # lv.anim_timeline_stop(anim_timeline) # lv.anim_timeline_del(anim_timeline) # anim_timeline = None # # slider.set_value(value, lv.ANIM.ON) # anim.set_time((durationTime - currentValue) * 1000) # anim.set_values(currentValue, durationTime) # anim_timeline = lv.anim_timeline_create() # lv.anim_timeline_add(anim_timeline, 0, anim) label.set_text('%02d:%02d'%(minute, second)) def setSpentTime(slider, value): global playedTime global currentValue global durationTime global image global start global anim_timeline global player global albumCover global songTitle global albumTitle global totalTime global currentMusic global musicData if (value >= durationTime): # currentMusic += 1 # if (len(musicData) == currentMusic): # currentMusic = 0 start = False reset_music() else: currentValue = value setLabelValue(playedTime, value) slider.set_value(value, lv.ANIM.ON) def cb(data): print(data) def reset_music(): global albumCover global songTitle global albumTitle global totalTime global musicData global currentMusic global durationTime global slider global anim global image global start global currentValue global anim_timeline global playedTime global player if (anim_timeline != None): lv.anim_timeline_stop(anim_timeline) lv.anim_timeline_del(anim_timeline) anim_timeline = None albumCover.set_src(musicData[currentMusic]["album_url"]) songTitle.set_text(musicData[currentMusic]["title"]) albumTitle.set_text(musicData[currentMusic]["album"]) durationTime = musicData[currentMusic]["duration"] currentValue = 0 slider.set_range(0, durationTime) slider.set_value(0, lv.ANIM.ON) anim.set_time(durationTime * 1000) anim.set_values(0, durationTime) anim_timeline = lv.anim_timeline_create() lv.anim_timeline_add(anim_timeline, 0, anim) setLabelValue(totalTime, durationTime) setLabelValue(playedTime, 0) if (player != None): player.pause() player.close() player = None if (start == False): image[1].set_src(RESOURCES_ROOT + "images/play.png") else: image[1].set_src(RESOURCES_ROOT + "images/pause.png") lv.anim_timeline_start(anim_timeline) player = Player() player.open() player.play(musicData[currentMusic]["url"], sync=False) player.on(cb) if (musicData[currentMusic]["favorite"] == False): image[3].set_src(RESOURCES_ROOT + "images/favorite.png") else: image[3].set_src(RESOURCES_ROOT + "images/favorited.png") def controller_click_cb(e, func): global anim global start global anim_timeline global durationTime global player global image global currentValue global musicData global currentMusic print(func, anim_timeline) if (func == "play"): if (start == False): start = True if (currentValue == durationTime): currentValue = 0 anim.set_time((durationTime - currentValue) * 1000) anim.set_values(currentValue, durationTime) anim_timeline = lv.anim_timeline_create() lv.anim_timeline_add(anim_timeline, 0, anim) lv.anim_timeline_start(anim_timeline) image[1].set_src(RESOURCES_ROOT + "images/pause.png") print('start to play') if (player == None): player = Player() player.open() player.play(musicData[currentMusic]["url"], sync=False) player.on(cb) else: player.resume() # state = player.getState() # print(state) # if (state == 2): # player.resume() # image[1].set_src(RESOURCES_ROOT + "images/pause.png") # else: # player.pause() # image[1].set_src(RESOURCES_ROOT + "images/play.png") else: start = False image[1].set_src(RESOURCES_ROOT + "images/play.png") lv.anim_timeline_stop(anim_timeline) lv.anim_timeline_del(anim_timeline) anim_timeline = None anim.set_time((durationTime - currentValue) * 1000) anim.set_values(currentValue, durationTime) anim_timeline = lv.anim_timeline_create() lv.anim_timeline_add(anim_timeline, 0, anim) player.pause() print('music puaused') elif (func == "fav"): print('favorite pressed') if (musicData[currentMusic]["favorite"] == False): image[3].set_src(RESOURCES_ROOT + "images/favorited.png") musicData[currentMusic]["favorite"] = True else: musicData[currentMusic]["favorite"] = False image[3].set_src(RESOURCES_ROOT + "images/favorite.png") elif (func == "next"): print('switch to next song') currentMusic += 1 if (len(musicData) == currentMusic): currentMusic = 0 reset_music() elif (func == "prev"): print('switch to previous song') currentMusic -= 1 if (currentMusic < 0): currentMusic = len(musicData) - 1 reset_music() class MusicPlayer: def createPage(self): global anim global playedTime global durationTime global slider global player global image global currentMusic global albumCover global songTitle global albumTitle global totalTime global anim_timeline global lvglInitialized if lvglInitialized == False: axp = Axp192() axp.setSpkEnable(1) import display_driver lvglInitialized = True print("Enter Music") # init scr scr = lv.obj() win = lv.obj(scr) win.set_size(scr.get_width(), scr.get_height()) win.set_style_border_opa(0, 0) win.set_style_radius(0, 0) win.set_style_bg_color(lv.color_black(), 0) win.clear_flag(lv.obj.FLAG.SCROLLABLE) albumCover = lv.img(win) albumCover.set_style_pad_left(12, 0) albumCover.set_style_pad_top(10, 0) songTitle = lv.label(win) songTitle.set_style_text_font(lv.font_montserrat_20, 0) songTitle.set_style_text_color(lv.color_white(), 0) songTitle.align_to(albumCover, lv.ALIGN.TOP_LEFT, 130, 3) albumTitle = lv.label(win) albumTitle.set_style_text_font(lv.font_montserrat_16, 0) albumTitle.set_style_text_color(lv.color_make(0xCC, 0xCC, 0xCC), 0) albumTitle.align_to(songTitle, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 12) props = [lv.STYLE.BG_COLOR, 0] transition_dsc = lv.style_transition_dsc_t() transition_dsc.init(props, lv.anim_t.path_linear, 300, 0, None) style_main = lv.style_t() style_indicator = lv.style_t() style_pressed_color = lv.style_t() style_main.init() style_main.set_bg_opa(lv.OPA.COVER) style_main.set_bg_color(lv.color_make(0x66, 0x66, 0x66)) style_main.set_radius(lv.RADIUS.CIRCLE) style_main.set_line_dash_width(1) style_indicator.init() style_indicator.set_bg_opa(lv.OPA.COVER) style_indicator.set_bg_color(lv.color_white()) style_indicator.set_radius(lv.RADIUS.CIRCLE) style_indicator.set_transition(transition_dsc) style_pressed_color.init() style_pressed_color.set_bg_color(lv.color_white()) # Create a slider and add the style slider = lv.slider(win) slider.remove_style_all() # Remove the styles coming from the theme slider.add_style(style_main, lv.PART.MAIN) slider.add_style(style_indicator, lv.PART.INDICATOR) slider.add_style(style_pressed_color, lv.PART.INDICATOR | lv.STATE.PRESSED) slider.align_to(albumTitle, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 25) slider.set_size(140, 1) anim = lv.anim_t() anim.init() anim.set_var(slider) playedTime = lv.label(win) setLabelValue(playedTime, 0) playedTime.set_style_text_font(lv.font_montserrat_16, 0) playedTime.set_style_text_color(lv.color_white(), 0) playedTime.align_to(slider, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 15) totalTime = lv.label(win) totalTime.set_style_text_font(lv.font_montserrat_16, 0) totalTime.set_style_text_color(lv.color_white(), 0) totalTime.align_to(slider, lv.ALIGN.OUT_BOTTOM_RIGHT, 0, 15) func_col_dsc = [80, 80, 80, 80, lv.GRID_TEMPLATE.LAST] func_row_dsc = [40, lv.GRID_TEMPLATE.LAST] funcContainer = lv.obj(win) funcContainer.set_style_bg_opa(0x00, 0) funcContainer.set_style_border_opa(0x00, 0) funcContainer.set_layout(lv.LAYOUT_GRID.value) funcContainer.set_grid_dsc_array(func_col_dsc, func_row_dsc) funcContainer.set_grid_align(lv.GRID_ALIGN.SPACE_BETWEEN, lv.GRID_ALIGN.SPACE_BETWEEN) funcContainer.set_align(lv.ALIGN.BOTTOM_MID) funcContainer.set_size(320, 70) for i in range(4): image[i] = lv.img(funcContainer) image[i].set_src(functionImage[i]) image[i].add_flag(lv.obj.FLAG.CLICKABLE) image[i].set_ext_click_area(20) image[i].set_grid_cell(lv.GRID_ALIGN.CENTER, i, 1, lv.GRID_ALIGN.CENTER, 0, 1) if (i == 0): image[i].add_event_cb(lambda e: controller_click_cb(e, "prev"), lv.EVENT.CLICKED, None) elif (i == 1): image[i].add_event_cb(lambda e: controller_click_cb(e, "play"), lv.EVENT.CLICKED, None) elif (i == 2): image[i].add_event_cb(lambda e: controller_click_cb(e, "next"), lv.EVENT.CLICKED, None) elif (i == 3): image[i].add_event_cb(lambda e: controller_click_cb(e, "fav"), lv.EVENT.CLICKED, None) anim.set_custom_exec_cb(lambda a1, val: setSpentTime(slider, val)) reset_music() # load content lv.scr_load(scr) def addToList(self, musicItem): musicData.append(musicItem) def removeFromList(self, musicItem): for i in range(0, len(musicData)): '''ignore favorite item, because it might be modified runtime''' if musicData[i]['title'] == musicItem['title'] \ and musicData[i]['album'] == musicItem['album'] \ and musicData[i]['album_url'] == musicItem['album_url'] \ and musicData[i]['url'] == musicItem['url'] \ and musicData[i]['duration'] == musicItem['duration']: musicData.remove(musicData[i]) break
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/music_player/code/music.py
Python
apache-2.0
12,399
# -*- encoding: utf-8 -*- ''' @File : main.py @Description: 声音上云 @Author : victor.wang @version : 1.0 ''' from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import utime # 延时API所在组件 from driver import ADC # ADC类,通过微处理器的ADC模块读取ADC通道输入电压 from driver import GPIO # ESP32和使用GPIO控制LED import noise # 声音传感器驱动库 import ujson # json字串解析库 # LED 蜂鸣器控制变量 redledon = 0 blueledon = 0 greenledon =0 buzzeron =0 voice_value = 0 # 物联网平台连接标志位 iot_connected = False # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 物联网平台连接标志位 iot_connected = False wlan = None # 物联网设备实例 device = None # LED 蜂鸣器 声音传感器设备 redled=None blueled=None greenled=None buzzer=None adcobj = None voicedetectordev = None def led_init(): global redled, blueled, greenled redled = GPIO() blueled = GPIO() greenled = GPIO() redled.open('led_r') # board.json中led_r节点定义的GPIO,对应esp32外接的的红灯 blueled.open('led_b') # board.json中led_b节点定义的GPIO,对应esp32外接的上的蓝灯 greenled.open('led_g') # board.json中led_g节点定义的GPIO,对应esp32外接的上的绿灯 print("led inited!") def buzzer_init(): global buzzer buzzer=GPIO() buzzer.open('buzzer') print("buzzer inited!") def voice_init(): global adcobj, voicedetectordev adcobj = ADC() adcobj.open("voice") # 按照board.json中名为"voice"的设备节点的配置参数(主设备adc端口号,从设备地址,采样率等)初始化adc类型设备对象 voicedetectordev = noise.Noise(adcobj) # 初始化声音传感器 print("voice inited!") # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wlan wifi_connected = False wlan = network.WLAN(network.STA_IF) #创建WLAN对象 wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if not wifi_connected: wlan.active(True) #激活界面 wlan.scan() #扫描接入点 wlan.disconnect() #断开Wi-Fi #print("start to connect ", wifiSsid) wlan.connect(wifiSsid, wifiPassword) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) while True: wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected: # Wi-Fi连接成功则退出while循环 break else: utime.sleep(0.5) print("wifi_connected:", wifi_connected) ifconfig = wlan.ifconfig() #获取接口的IP/netmask/gw/DNS地址 print(ifconfig) utime.sleep(0.5) # 通过声音传感器检测声音分贝大小 def get_voice(): global voicedetectordev voice = voicedetectordev.getVoltage() # 获取温度测量结果 return voice # 返回读取到的声音大小 # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): global redledon, blueledon, greenledon, buzzeron, voice_value payload = ujson.loads(request['params']) # 获取dict状态字段 注意要验证键存在 否则会抛出异常 if "light_up_green_led" in payload.keys(): greenledon = payload["light_up_green_led"] if (greenledon): print("点亮绿灯") if "light_up_blue_led" in payload.keys(): blueledon = payload["light_up_blue_led"] if (blueledon): print("点亮蓝灯") if "light_up_red_led" in payload.keys(): redledon = payload["light_up_red_led"] if (redledon): print("点亮红灯") if "switch_on_buzzer" in payload.keys(): buzzeron = payload["switch_on_buzzer"] if (buzzeron): print("打开蜂鸣器") redled.write(redledon) # 控制红灯 blueled.write(blueledon) # 控制蓝灯 greenled.write(greenledon) # 控制绿灯 buzzer.write(buzzeron) # 控制蜂蜜器 # 要将更改后的状态同步上报到云平台 prop = ujson.dumps({ 'light_up_green_led': greenledon, 'light_up_blue_led': blueledon, 'light_up_red_led':redledon, 'switch_on_buzzer':buzzeron, }) upload_data = {'params': prop} # 上报led和蜂鸣器属性到云端 device.postProps(upload_data) def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) # 上传声音大小到物联网平台 def upload_voice(): global device while True: data = get_voice() # 读取声音大小信息 # 生成上报到物联网平台的属性值字串 prop = ujson.dumps({ 'SoundDecibelValue': data }) print('uploading data: ', prop) upload_data = {'params': prop} # 上传声音信息到物联网平台 device.postProps(upload_data) utime.sleep(2) if __name__ == '__main__': # 硬件初始化 voice_init() led_init() buzzer_init() # 请替换物联网平台申请到的产品和设备信息,可以参考文章:https://blog.csdn.net/HaaSTech/article/details/114360517 get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_voice()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/noise_detector/esp32/code/main.py
Python
apache-2.0
6,981
''' Copyright (C) 2015-2022 Alibaba Group Holding Limited MicroPython's driver for Noise Author: HaaS Date: 2022/03/23 ''' from driver import ADC class Noise(object): def __init__(self, adcObj, avgSz=100): self.adcObj = None if not isinstance(adcObj, ADC): raise ValueError('parameter is not an ADC object') self.adcObj = adcObj self.avgSz = avgSz self.avgVec = [0] * self.avgSz self.avgVecIdx = -1 self.init() # 初始化均值数组,后续通过计算平滑均值曲线值与当前值进行比较 def init(self): # init avg vector for idx in range(self.avgSz): voltage = self.adcObj.readVoltage() self.avgVec[idx] = voltage # 获取当前电压值 mV def getVoltage(self): return self.adcObj.readVoltage() # 单次检查当前声音分贝是否超过阈值,changed 为 True 表示有变化,voltage 为当前电压值(mV) def checkNoise(self, voltage, threshold=400): self.avgVecIdx = (self.avgVecIdx + 1) % self.avgSz self.avgVec[self.avgVecIdx] = voltage avg = sum(self.avgVec) / self.avgSz changed = abs(voltage - avg) > threshold return changed
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/noise_detector/esp32/code/noise.py
Python
apache-2.0
1,262
# coding=utf-8 from driver import ADC from driver import GPIO from driver import PWM import network import ujson import utime as time import modem from aliyunIoT import Device import kv import math import _thread #当iot设备连接到物联网平台的时候触发'connect' 事件 def on_connect(data): global module_name,default_ver,productKey,deviceName,deviceSecret,on_trigger,on_download,on_verify,on_upgrade print('***** connect lp succeed****') data_handle = {} data_handle['device_handle'] = device.getDeviceHandle() #当连接断开时,触发'disconnect'事件 def on_disconnect(): print('linkkit is disconnected') red = 0 green = 0 blue = 0 bu = 0 #当iot云端下发属性设置时,触发'props'事件 def on_props(request): global switch_buzzers,switch_red,switch_green,switch_blue,red,green,blue,bu params=request['params'] params=eval(params) if "buzzer" in params: switch_buzzers = params["buzzer"] if switch_buzzers and switch_buzzers != bu: print("buzzer - on") bu = switch_buzzers if "red_led" in params: switch_red = params["red_led"] if switch_red and switch_red != red: print("red_led - on") red = switch_red if "green_led" in params: switch_green = params["green_led"] if switch_green and switch_green != green: print("green_led - on") green = switch_green if "blue_led" in params: switch_blue = params["blue_led"] if switch_blue and switch_blue != blue: print("blue_led - on") blue = switch_blue params.clear() #当iot云端调用设备service时,触发'service'事件 def on_service(id,request): print('clound req id is {} , req is {}'.format(id,request)) #当设备跟iot平台通信过程中遇到错误时,触发'error'事件 def on_error(err): print('err msg is {} '.format(err)) #网络连接的回调函数 def on_4g_cb(args): global g_connect_status pdp = args[0] netwk_sta = args[1] if netwk_sta == 1: g_connect_status = True else: g_connect_status = False #网络连接 def connect_network(): global net,on_4g_cb,g_connect_status #NetWorkClient该类是一个单例类,实现网络管理相关的功能,包括初始化,联网,状态信息等. net = network.NetWorkClient() g_register_network = False if net._stagecode is not None and net._stagecode == 3 and net._subcode == 1: g_register_network = True else: g_register_network = False if g_register_network: #注册网络连接的回调函数on(self,id,func); 1代表连接,func 回调函数 ;return 0 成功 net.on(1,on_4g_cb) net.connect(None) else: print('网络注册失败') while True: if g_connect_status: print('网络连接成功') break time.sleep_ms(20) #动态注册回调函数 def on_dynreg_cb(data): global deviceSecret,device_dyn_resigter_succed deviceSecret = data device_dyn_resigter_succed = True # 连接物联网平台 def dyn_register_device(productKey,productSecret,deviceName): global on_dynreg_cb,device,deviceSecret,device_dyn_resigter_succed key = '_amp_customer_devicesecret' deviceSecretdict = kv.get(key) print("deviceSecretdict:",deviceSecretdict) if isinstance(deviceSecretdict,str): deviceSecret = deviceSecretdict if deviceSecretdict is None or deviceSecret is None: key_info = { 'productKey': productKey , 'productSecret': productSecret , 'deviceName': deviceName } # 动态注册一个设备,获取设备的deviceSecret #下面的if防止多次注册,当前若是注册过一次了,重启设备再次注册就会卡住, if not device_dyn_resigter_succed: device.register(key_info,on_dynreg_cb) volume_data = {} def upload_volume(n): global volume_data volume_data["sound"]= n volume_data_str=ujson.dumps(volume_data) data={ 'params':volume_data_str } device.postProps(data) warn_data = {} def upload_warn(): global warn_data warn_data["buzzer"]= 0 warn_data["red_led"]= 0 warn_data["green_led"]= 0 warn_data["blue_led"]= 0 warn_data_str=ujson.dumps(warn_data) data={ 'params':warn_data_str } device.postProps(data) data.clear() #蜂鸣器 buzzers = PWM() buzzers.open("buzzer") switch_buzzers = 0 buzzer = 0 def start_buzzers(): global switch_buzzers,buzzer if switch_buzzers == 1 and buzzer == 0: param = {'freq':3000,'duty':50} buzzers.setOption(param) buzzer = 1 if switch_buzzers == 0 and buzzer == 1: param = {'freq':3000,'duty':100} buzzers.setOption(param) buzzer = 0 #红灯 led_red = GPIO() led_red.open('red') switch_red = 0 def red_led(): global switch_red led_red.write(switch_red) #绿灯 led_green = GPIO() led_green.open('green') switch_green = 0 def green_led(): global switch_green led_green.write(switch_green) #蓝灯 led_blue = GPIO() led_blue.open('blue') switch_blue = 0 def blue_led(): global switch_blue led_blue.write(switch_blue) def warning(): global switch_blue,switch_green,switch_red,switch_buzzers while True: time.sleep_ms(200) start_buzzers() red_led() green_led() blue_led() if __name__ == '__main__': ICCID=None g_connect_status = False net = None device = None deviceSecret = None deviceName = None #替换下列产品信息 ################################### productKey = "your-productKey" productSecret = "your-productSecret" ################################### device_dyn_resigter_succed = False # 连接网络 connect_network() # 获取设备的IMEI 作为deviceName 进行动态注册 deviceName = modem.info.getDevImei() #获取设备的ICCID ICCID=modem.sim.getIccid() #初始化物联网平台Device类,获取device实例 device = Device() if deviceName is not None and len(deviceName) > 0 : #动态注册一个设备 dyn_register_device(productKey,productSecret,deviceName) else: print("获取设备IMEI失败,无法进行动态注册") while deviceSecret is None: time.sleep(0.2) print('动态注册成功:' + deviceSecret) key_info = { 'region' : 'cn-shanghai' , 'productKey': productKey , 'deviceName': deviceName , 'deviceSecret': deviceSecret , 'keepaliveSec': 60, } #打印设备信息 print(key_info) #device.ON_CONNECT 是事件,on_connect是事件处理函数/回调函数 device.on(device.ON_CONNECT,on_connect) device.on(device.ON_DISCONNECT,on_disconnect) device.on(device.ON_PROPS,on_props) device.on(device.ON_SERVICE,on_service) device.on(device.ON_ERROR,on_error) device.connect(key_info) #主程序 time.sleep(2) # 检测光照 adc=ADC() adc.open("ADC1") upload_warn() # 创建警报线程 _thread.start_new_thread(warning, ()) while True: volume=adc.readVoltage() DB = 20*(math.log((volume/0.775), 10)) upload_volume(DB) print(DB) time.sleep_ms(500)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/noise_detector/haas506/code/main.py
Python
apache-2.0
7,474
# -*- encoding: utf-8 -*- ''' @File : main.py @Description: 声音上云 @Author : victor.wang @version : 1.0 ''' from ulinksdk.aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import utime # 延时API所在组件 from driver import ADC # ADC类,通过微处理器的ADC模块读取ADC通道输入电压 from driver import GPIO # ESP32和使用GPIO控制LED import noise # 声音传感器驱动库 import ujson # json字串解析库 # LED 蜂鸣器控制变量 redledon = 0 blueledon = 0 greenledon =0 buzzeron =0 voice_value = 0 # 物联网平台连接标志位 iot_connected = False # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 物联网平台连接标志位 iot_connected = False wlan = None # 物联网设备实例 device = None # LED 蜂鸣器 声音传感器设备 redled=None blueled=None greenled=None buzzer=None adcobj = None voicedetectordev = None def led_init(): global redled, blueled, greenled redled = GPIO() blueled = GPIO() greenled = GPIO() redled.open('led_r') # board.json中led_r节点定义的GPIO,对应esp32外接的的红灯 blueled.open('led_b') # board.json中led_b节点定义的GPIO,对应esp32外接的上的蓝灯 greenled.open('led_g') # board.json中led_g节点定义的GPIO,对应esp32外接的上的绿灯 print("led inited!") def buzzer_init(): global buzzer buzzer=GPIO() buzzer.open('buzzer') print("buzzer inited!") def voice_init(): global adcobj, voicedetectordev adcobj = ADC() adcobj.open("voice") # 按照board.json中名为"voice"的设备节点的配置参数(主设备adc端口号,从设备地址,采样率等)初始化adc类型设备对象 voicedetectordev = noise.Noise(adcobj) # 初始化声音传感器 print("voice inited!") # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wlan wifi_connected = False wlan = network.WLAN(network.STA_IF) #创建WLAN对象 wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if not wifi_connected: wlan.active(True) #激活界面 wlan.scan() #扫描接入点 wlan.disconnect() #断开Wi-Fi #print("start to connect ", wifiSsid) wlan.connect(wifiSsid, wifiPassword) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) while True: wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected: # Wi-Fi连接成功则退出while循环 break else: utime.sleep(0.5) print("wifi_connected:", wifi_connected) ifconfig = wlan.ifconfig() #获取接口的IP/netmask/gw/DNS地址 print(ifconfig) utime.sleep(0.5) # 通过声音传感器检测声音分贝大小 def get_voice(): global voicedetectordev voice = voicedetectordev.getVoltage() # 获取温度测量结果 return voice # 返回读取到的声音大小 # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): global redledon, blueledon, greenledon, buzzeron, voice_value payload = ujson.loads(request['params']) # 获取dict状态字段 注意要验证键存在 否则会抛出异常 if "light_up_green_led" in payload.keys(): greenledon = payload["light_up_green_led"] if (greenledon): print("点亮绿灯") if "light_up_blue_led" in payload.keys(): blueledon = payload["light_up_blue_led"] if (blueledon): print("点亮蓝灯") if "light_up_red_led" in payload.keys(): redledon = payload["light_up_red_led"] if (redledon): print("点亮红灯") if "switch_on_buzzer" in payload.keys(): buzzeron = payload["switch_on_buzzer"] if (buzzeron): print("打开蜂鸣器") redled.write(redledon) # 控制红灯 blueled.write(blueledon) # 控制蓝灯 greenled.write(greenledon) # 控制绿灯 buzzer.write(buzzeron) # 控制蜂蜜器 # 要将更改后的状态同步上报到云平台 prop = ujson.dumps({ 'light_up_green_led': greenledon, 'light_up_blue_led': blueledon, 'light_up_red_led':redledon, 'switch_on_buzzer':buzzeron, }) upload_data = {'params': prop} # 上报led和蜂鸣器属性到云端 device.postProps(upload_data) def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) # 上传声音大小到物联网平台 def upload_voice(): global device while True: data = get_voice() # 读取声音大小信息 # 生成上报到物联网平台的属性值字串 prop = ujson.dumps({ 'SoundDecibelValue': data }) print('uploading data: ', prop) upload_data = {'params': prop} # 上传声音信息到物联网平台 device.postProps(upload_data) utime.sleep(2) if __name__ == '__main__': # 硬件初始化 voice_init() led_init() buzzer_init() nic = network.LAN() nic.active(1) connect_lk(productKey, deviceName, deviceSecret) upload_voice()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/noise_detector/stm32/code/main.py
Python
apache-2.0
6,868
''' Copyright (C) 2015-2022 Alibaba Group Holding Limited MicroPython's driver for Noise Author: HaaS Date: 2022/03/23 ''' from driver import ADC class Noise(object): def __init__(self, adcObj, avgSz=100): self.adcObj = None if not isinstance(adcObj, ADC): raise ValueError('parameter is not an ADC object') self.adcObj = adcObj self.avgSz = avgSz self.avgVec = [0] * self.avgSz self.avgVecIdx = -1 self.init() # 初始化均值数组,后续通过计算平滑均值曲线值与当前值进行比较 def init(self): # init avg vector for idx in range(self.avgSz): voltage = self.adcObj.readVoltage() self.avgVec[idx] = voltage # 获取当前电压值 mV def getVoltage(self): return self.adcObj.readVoltage() # 单次检查当前声音分贝是否超过阈值,changed 为 True 表示有变化,voltage 为当前电压值(mV) def checkNoise(self, voltage, threshold=400): self.avgVecIdx = (self.avgVecIdx + 1) % self.avgSz self.avgVec[self.avgVecIdx] = voltage avg = sum(self.avgVec) / self.avgSz changed = abs(voltage - avg) > threshold return changed
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/noise_detector/stm32/code/noise.py
Python
apache-2.0
1,262
from driver import PWM class BUZZER(object): def __init__(self, pwmObj): self.pwmObj = None if not isinstance(pwmObj, PWM): raise ValueError("parameter is not an PWM object") self.pwmObj = pwmObj def setOptionDuty(self,data): if self.pwmObj is None: raise ValueError("invalid PWM object") self.pwmObj.setOption(data) def start(self,obj): if self.pwmObj is None: raise ValueError("invalid PWM object") self.pwmObj.open(obj) def close(self): if self.pwmObj is None: raise ValueError("invalid PWM object") self.pwmObj.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/obstacle_avoidance/esp32/code/buzzer.py
Python
apache-2.0
668
from time import sleep_us,ticks_us from driver import GPIO class HCSR04(): def __init__(self,trigObj,echoObj): self.trig = None self.echo = None if not isinstance(trigObj, GPIO): raise ValueError("parameter is not a GPIO object") if not isinstance(echoObj, GPIO): raise ValueError("parameter is not a GPIO object") self.trig = trigObj self.echo = echoObj def measureDistance(self): distance=0 self.trig.write(1) sleep_us(20) self.trig.write(0) while self.echo.read() == 0: pass if self.echo.read() == 1: ts=ticks_us() #开始时间 while self.echo.read() == 1: #等待脉冲高电平结束 pass te=ticks_us() #结束时间 tc=te-ts #回响时间(单位us,1us=1*10^(-6)s) distance=(tc*170)/10000 #距离计算 (单位为:cm) return distance
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/obstacle_avoidance/esp32/code/hcsr04.py
Python
apache-2.0
1,047
# -*- coding: UTF-8 -*- from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import ujson # json字串解析库 import utime # 延时API所在组件 from driver import GPIO # GPIO类,用于控制微处理器的输入输出功能 import hcsr04 # hcsr04超声波传感器类 from micropython import const import buzzer import kv kv.set('app_upgrade_channel', 'disable') disDev = 0 echoDev = 0 trigDev = 0 buzzerdev = None # 安全距离,单位是5厘米 ALARM_DISTANCE = const(5) # 物联网平台连接标志位 iot_connected = False wlan = None # 三元组信息 productKey = "Your-productKey" deviceName = "Your-deviceName" deviceSecret = "Your-deviceSecret" # 物联网设备实例 device = None # Wi-Fi SSID和Password设置 wifiSsid = "Your-wifiSsid" wifiPassword = "Your-wifiPassword" # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wlan wifi_connected = False wlan.active(True) # 激活界面 wlan.scan() # 扫描接入点 wlan.disconnect() # 断开Wi-Fi #print("start to connect ", wifiSsid) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) wlan.connect(wifiSsid, wifiPassword) while True: wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected: # Wi-Fi连接成功则退出while循环 break else: utime.sleep(0.5) print("wifi_connected:", wifi_connected) ifconfig = wlan.ifconfig() # 获取接口的IP/netmask/gw/DNS地址 print(ifconfig) utime.sleep(0.5) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): pass def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) def buzzer_init(): global buzzerdev buzzerdev = GPIO() # 使用board.json中buzzer节点定义的GPIO,对应esp32外接的上蜂鸣器 buzzerdev.open('buzzer') print("buzzer inited!") def obstacle_avoidance_init(): # obstacle init function global disDev, echoDev, trigDev echoDev = GPIO() echoDev.open("echo") trigDev = GPIO() trigDev.open("trig") disDev = hcsr04.HCSR04(trigDev, echoDev) def obstacle_detector(): global disDev, echoDev, trigDev, buzzerdev while True: # 无限循环 distance = disDev.measureDistance() print('distance = ', distance) if(distance < ALARM_DISTANCE): buzzerdev.write(1) upload_data = {'params': ujson.dumps({ 'distance': distance, }) } # 上传状态到物联网平台 device.postProps(upload_data) else: buzzerdev.write(0) utime.sleep(1) # 打印完之后休眠1秒 echoDev.close() trigDev.close() if __name__ == '__main__': wlan = network.WLAN(network.STA_IF) # 创建WLAN对象 get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) buzzer_init() obstacle_avoidance_init() obstacle_detector()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/obstacle_avoidance/esp32/code/main.py
Python
apache-2.0
4,346
# coding=utf-8 from driver import GPIO from driver import PWM import network import _thread import ujson import utime as time import modem from aliyunIoT import Device import kv #当iot设备连接到物联网平台的时候触发'connect' 事件 def on_connect(data): global module_name,default_ver,productKey,deviceName,deviceSecret,on_trigger,on_download,on_verify,on_upgrade print('***** connect lp succeed****') data_handle = {} data_handle['device_handle'] = device.getDeviceHandle() #当连接断开时,触发'disconnect'事件 def on_disconnect(): print('linkkit is disconnected') #当iot云端下发属性设置时,触发'props'事件 def on_props(request): global safe_distance params=request['params'] params=eval(params) if "safe_distance" in params: safe_distance = params["safe_distance"] print('safe_distance:',safe_distance) upload_safe_distance(safe_distance) #当iot云端调用设备service时,触发'service'事件 def on_service(id,request): print('clound req id is {} , req is {}'.format(id,request)) #当设备跟iot平台通信过程中遇到错误时,触发'error'事件 def on_error(err): print('err msg is {} '.format(err)) #网络连接的回调函数 def on_4g_cb(args): global g_connect_status pdp = args[0] netwk_sta = args[1] if netwk_sta == 1: g_connect_status = True else: g_connect_status = False #网络连接 def connect_network(): global net,on_4g_cb,g_connect_status #NetWorkClient该类是一个单例类,实现网络管理相关的功能,包括初始化,联网,状态信息等. net = network.NetWorkClient() g_register_network = False if net._stagecode is not None and net._stagecode == 3 and net._subcode == 1: g_register_network = True else: g_register_network = False if g_register_network: #注册网络连接的回调函数on(self,id,func); 1代表连接,func 回调函数 ;return 0 成功 net.on(1,on_4g_cb) net.connect(None) else: print('网络注册失败') while True: if g_connect_status: print('网络连接成功') break time.sleep_ms(20) #动态注册回调函数 def on_dynreg_cb(data): global deviceSecret,device_dyn_resigter_succed deviceSecret = data device_dyn_resigter_succed = True # 连接物联网平台 def dyn_register_device(productKey,productSecret,deviceName): global on_dynreg_cb,device,deviceSecret,device_dyn_resigter_succed key = '_amp_customer_devicesecret' deviceSecretdict = kv.get(key) print("deviceSecretdict:",deviceSecretdict) if isinstance(deviceSecretdict,str): deviceSecret = deviceSecretdict if deviceSecretdict is None or deviceSecret is None: key_info = { 'productKey': productKey , 'productSecret': productSecret , 'deviceName': deviceName } # 动态注册一个设备,获取设备的deviceSecret #下面的if防止多次注册,当前若是注册过一次了,重启设备再次注册就会卡住, if not device_dyn_resigter_succed: device.register(key_info,on_dynreg_cb) distance_data = {} def upload_distance(n): global distance_data distance_data["distance"]= n distance_data_str=ujson.dumps(distance_data) data={ 'params':distance_data_str } device.postProps(data) warn_data = {} def upload_safe_distance(safe): global warn_data warn_data["safe_distance"]= safe warn_data_str=ujson.dumps(warn_data) data1={ 'params':warn_data_str } device.postProps(data1) #蜂鸣器 buzzers = PWM() buzzers.open("buzzer") switch_buzzers = 0 buzzer = 0 def start_buzzers(): global switch_buzzers,buzzer while True: time.sleep_ms(200) if switch_buzzers == 1 and buzzer == 0: param = {'freq':3000,'duty':50} buzzers.setOption(param) buzzer = 1 if switch_buzzers == 0 and buzzer == 1: param = {'freq':3000,'duty':100} buzzers.setOption(param) buzzer = 0 #超声波测距 def getData(): TRIG.write(0) #set period,above 50ms time.sleep_ms(500) TRIG.write(1) #Set TRIG as LOW time.sleep_us(10) #Delay of 10us TRIG.write(0) #Set TRIG as HIGH while ECHO.read()==0: #Check if Echo is LOW pass pulse_start = time.ticks_us() #Time of the last LOW pulse while ECHO.read()==1: #Check whether Echo is HIGH pass pulse_end = time.ticks_us() #Time of the last HIGH pulse #print("pulse_duration",time.ticks_diff(pulse_end,pulse_start)) # us pulse_duration = time.ticks_diff(pulse_end,pulse_start)/10000 #pulse duration: s d=pulse_duration*340/2 return d if __name__ == '__main__': ICCID=None g_connect_status = False net = None device = None deviceSecret = None deviceName = None #替换下列产品信息 ################################### productKey = "your-productKey" productSecret = "your-productSecret" ################################### device_dyn_resigter_succed = False # 连接网络 connect_network() # 获取设备的IMEI 作为deviceName 进行动态注册 deviceName = modem.info.getDevImei() #获取设备的ICCID ICCID=modem.sim.getIccid() #初始化物联网平台Device类,获取device实例 device = Device() if deviceName is not None and len(deviceName) > 0 : #动态注册一个设备 dyn_register_device(productKey,productSecret,deviceName) else: print("获取设备IMEI失败,无法进行动态注册") while deviceSecret is None: time.sleep(0.2) print('动态注册成功:' + deviceSecret) key_info = { 'region' : 'cn-shanghai' , 'productKey': productKey , 'deviceName': deviceName , 'deviceSecret': deviceSecret , 'keepaliveSec': 60, } #打印设备信息 print(key_info) #device.ON_CONNECT 是事件,on_connect是事件处理函数/回调函数 device.on(device.ON_CONNECT,on_connect) device.on(device.ON_DISCONNECT,on_disconnect) device.on(device.ON_PROPS,on_props) device.on(device.ON_SERVICE,on_service) device.on(device.ON_ERROR,on_error) device.connect(key_info) #主程序 time.sleep(2) safe_distance = 50 print('safe_distance:',safe_distance) upload_safe_distance(safe_distance) #creat instances TRIG = GPIO() ECHO = GPIO() TRIG.open('trig') # Set pin as GPIO out ECHO.open('echo') # Set pin as GPIO in _thread.start_new_thread(start_buzzers, ()) try: while True: dis = getData() if dis > 20 and dis < 600: print ("distance:%0.2f cm" % dis) if dis < safe_distance: switch_buzzers = 1 upload_distance(dis) else: switch_buzzers = 0 else: switch_buzzers = 0 print ("Out Of Range") except KeyboardInterrupt: print("exit")
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/obstacle_avoidance/haas506/code/main.py
Python
apache-2.0
7,691
from driver import PWM class BUZZER(object): def __init__(self, pwmObj): self.pwmObj = None if not isinstance(pwmObj, PWM): raise ValueError("parameter is not an PWM object") self.pwmObj = pwmObj def setOptionDuty(self,data): if self.pwmObj is None: raise ValueError("invalid PWM object") self.pwmObj.setOption(data) def start(self,obj): if self.pwmObj is None: raise ValueError("invalid PWM object") self.pwmObj.open(obj) def close(self): if self.pwmObj is None: raise ValueError("invalid PWM object") self.pwmObj.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/obstacle_avoidance/stm32/code/buzzer.py
Python
apache-2.0
668
from time import sleep_us,ticks_us from driver import GPIO class HCSR04(): def __init__(self,trigObj,echoObj): self.trig = None self.echo = None if not isinstance(trigObj, GPIO): raise ValueError("parameter is not a GPIO object") if not isinstance(echoObj, GPIO): raise ValueError("parameter is not a GPIO object") self.trig = trigObj self.echo = echoObj def measureDistance(self): distance=0 self.trig.write(1) sleep_us(20) self.trig.write(0) while self.echo.read() == 0: pass if self.echo.read() == 1: ts=ticks_us() #开始时间 while self.echo.read() == 1: #等待脉冲高电平结束 pass te=ticks_us() #结束时间 tc=te-ts #回响时间(单位us,1us=1*10^(-6)s) distance=(tc*170)/10000 #距离计算 (单位为:cm) return distance
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/obstacle_avoidance/stm32/code/hcsr04.py
Python
apache-2.0
1,047
# -*- coding: UTF-8 -*- from ulinksdk.aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import ujson # json字串解析库 import utime # 延时API所在组件 from driver import GPIO # GPIO类,用于控制微处理器的输入输出功能 import hcsr04 # hcsr04超声波传感器类 from micropython import const import buzzer #import kv #kv.set('app_upgrade_channel', 'disable') disDev = 0 echoDev = 0 trigDev = 0 buzzerdev = None # 安全距离 ALARM_DISTANCE = const(0) # 物联网平台连接标志位 iot_connected = False wlan = None # 三元组信息 productKey = "产品密钥" deviceName = "设备名字" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 物联网设备实例 device = None # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): global wlan wifi_connected = False wlan.active(True) # 激活界面 wlan.scan() # 扫描接入点 wlan.disconnect() # 断开Wi-Fi #print("start to connect ", wifiSsid) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) wlan.connect(wifiSsid, wifiPassword) while True: wifi_connected = wlan.isconnected() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected: # Wi-Fi连接成功则退出while循环 break else: utime.sleep(0.5) print("wifi_connected:", wifi_connected) ifconfig = wlan.ifconfig() # 获取接口的IP/netmask/gw/DNS地址 print(ifconfig) utime.sleep(0.5) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): pass def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 配置收到云端属性控制指令的回调函数,如果收到物联网平台发送的属性控制消息,则调用on_props函数 device.on(Device.ON_PROPS, on_props) # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while(True): if iot_connected: print('物联网平台连接成功') break else: print('sleep for 1 s') utime.sleep(1) print('sleep for 2s') utime.sleep(2) def buzzer_init(): global buzzerdev buzzerdev = GPIO() # 使用board.json中buzzer节点定义的GPIO,对应esp32外接的上蜂鸣器 buzzerdev.open('buzzer') print("buzzer inited!") def obstacle_avoidance_init(): # obstacle init function global disDev, echoDev, trigDev echoDev = GPIO() echoDev.open("echo") trigDev = GPIO() trigDev.open("trig") disDev = hcsr04.HCSR04(trigDev, echoDev) def obstacle_detector(): global disDev, echoDev, trigDev, buzzerdev while True: # 无限循环 distance = disDev.measureDistance() print('distance = ', distance) if(distance < ALARM_DISTANCE): buzzerdev.write(1) upload_data = {'params': ujson.dumps({ 'LEDSwitch': distance, }) } # 上传状态到物联网平台 device.postProps(upload_data) else: buzzerdev.write(0) utime.sleep(1) # 打印完之后休眠1秒 echoDev.close() trigDev.close() if __name__ == '__main__': nic = network.LAN() nic.active(1) connect_lk(productKey, deviceName, deviceSecret) buzzer_init() print("buzzer init success!!") obstacle_avoidance_init() obstacle_detector()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/obstacle_avoidance/stm32/code/main.py
Python
apache-2.0
4,353
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : cloudAI.py @Description: 云端AI @Author : jiangyu @version : 1.0 ''' from aliyunIoT import Device import utime # 延时函数在utime库中 import ujson as json class CloudAI : def __gesture_cb(self, dict) : ''' Reply list : handGestureReply : 手势识别 ''' gesture = 'NA' if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': score = ext_dict['score'] if score > 0.4 : gesture = ext_dict['type'] print("recognize hand gesture : " + gesture) self.__cb('handGestureReply', gesture) def __license_plate_cb(self, dict) : plateNumber = 'NA' if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': g_confidence = ext_dict['confidence'] if g_confidence > 0.7 : plateNumber = ext_dict['plateNumber'] print('detect: ' + plateNumber) self.__cb('ocrCarNoReply', plateNumber) def __fruits_cb(self, dict) : fruit_name = 'NA' if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': i = 0 fruits_list = ext_dict['fruitList'] while (i < len(fruits_list)) : g_score = fruits_list[i]['score'] fruit_name = fruits_list[i]['name'] if g_score > 0.6: print('detect: ' + fruit_name) i += 1 self.__cb('detectFruitsReply', fruit_name) def __pedestrian_cb(self, dict) : detected = False if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': i = 0 data = ext_dict['data'] data_dict = json.loads(data) elements_list = data_dict['elements'] while (i < len(elements_list)) : g_score = elements_list[i]['score'] if g_score > 0.6: print('Pedestrian Detected') detected = True i += 1 self.__cb('DetectPedestrianReply', detected) def __businesscard_cb(self, dict) : card_info = {} if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': card_info['name'] = ext_dict['name'] print("name : " + card_info['name']) if card_info['name'] == '' : card_info['name'] = 'unknown' phoneNumbers_list = ext_dict['cellPhoneNumbers'] print("phoneNumbers : ") print(phoneNumbers_list) if len(phoneNumbers_list) : card_info['phoneNumbers'] = phoneNumbers_list[0] else : card_info['phoneNumbers'] = 'unknown' email_list = ext_dict['emails'] print("email_list: ") print(email_list) if len(email_list) : card_info['email'] = email_list[0] else : card_info['email'] = 'unknown' self.__cb('recognizeBusinessCardReply', card_info) def __rubblish_cb(self, dict) : name = 'NA' if dict != None: ext = dict['ext'] extDict = json.loads(ext) result = extDict['result'] if result == 'success': i = 0 elements = extDict['elements'] while (i < len(elements)) : gScore = elements[i]['categoryScore'] if gScore > 0.8: name = elements[i]['category'] print('detect: ' + name) break i += 1 self.__cb('classifyingRubbishReply', name) def __object_cb(self, dict) : name = 'NA' if dict != None: ext = dict['ext'] extDict = json.loads(ext) result = extDict['result'] if result == 'success': i = 0 elements = extDict['elements'] while (i < len(elements)) : gScore = elements[i]['score'] if gScore > 0.25: name = elements[i]['type'] print('detect: ' + name) break i += 1 self.__cb('detectObjectReply', name) def __vehicletype_cb(self, dict) : name = 'NA' detect = False if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': i = 0 item_list = ext_dict['items'] name = 'NA' while (i < len(item_list)) : g_score = item_list[i]['score'] name = item_list[i]['name'] # 这里可以修改识别的可信度,目前设置返回可信度大于85%才认为识别正确 if g_score > 0.85 and name != 'others': print('detect: ' + name) detect = True self.__cb('recognizeVehicleReply', name) break i += 1 if detect == False: self.__cb('recognizeVehicleReply', 'NA') def __vehiclelogo_cb(self, dict) : num = 0 if dict != None: ext = dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': item_list = ext_dict['elements'] num = len(item_list) if num > 0: print('detect: ' + str(num) + ' vehicle') detected = True if detected == False: print('do not detect!') self.__cb('recognizeLogoReply', num) def __cb_lk_service(self, data): self.g_lk_service = True print('download <----' + str(data)) if data != None : params = data['params'] params_dict = json.loads(params) command = params_dict['commandName'] if command == 'handGestureReply' : self.__gesture_cb(params_dict) elif command == 'ocrCarNoReply' : self.__license_plate_cb(params_dict) elif command == 'DetectPedestrianReply' : self.__pedestrian_cb(params_dict) elif command == 'detectFruitsReply' : self.__fruits_cb(params_dict) elif command == 'recognizeBusinessCardReply' : self.__businesscard_cb(params_dict) elif command == 'classifyingRubbishReply' : self.__rubblish_cb(params_dict) elif command == 'detectObjectReply' : self.__object_cb(params_dict) elif command == 'recognizeVehicleReply' : self.__vehicletype_cb(params_dict) elif command == 'recognizeLogoReply' : self.__vehiclelogo_cb(params_dict) else : print('unknown command reply') def __cb_lk_connect(self, data): print('link platform connected') self.g_lk_connect = True def __connect_iot(self) : self.device = Device() self.device.on(Device.ON_CONNECT, self.__cb_lk_connect) self.device.on(Device.ON_SERVICE, self.__cb_lk_service) self.device.connect(self.__dev_info) while True: if self.g_lk_connect: break def __init__(self, dev_info, callback) : self.__dev_info = dev_info self.__cb = callback self.g_lk_connect = False self.g_lk_service = False self.__connect_iot() def getDevice(self) : return self.device def __upload_request(self, command, frame) : # 上传图片到LP fileName = 'test.jpg' start = utime.ticks_ms() fileid = self.device.uploadContent(fileName, frame, None) if fileid != None: ext = { 'filePosition':'lp', 'fileName': fileName, 'fileId': fileid } ext_str = json.dumps(ext) all_params = {'id': 1, 'version': '1.0', 'params': { 'eventType': 'haas.faas', 'eventName': command, 'argInt': 1, 'ext': ext_str }} all_params_str = json.dumps(all_params) #print(all_params_str) upload_file = { 'topic': '/sys/' + self.__dev_info['productKey'] + '/' + self.__dev_info['deviceName'] + '/thing/event/hli_event/post', 'qos': 1, 'payload': all_params_str } # 上传完成通知HaaS聚合平台 print('upload--->' + str(upload_file)) self.g_lk_service = False self.device.publish(upload_file) i = 0 while (self.g_lk_service == False and i < 200) : utime.sleep_ms(10) i = i + 1 continue else: print('filedid is none, upload content fail') time_diff = utime.ticks_diff(utime.ticks_ms(), start) print('recognize time : %d' % time_diff) def recognizeGesture(self, frame) : self.__upload_request('handGesture', frame) def recognizeLicensePlate(self, frame) : self.__upload_request('ocrCarNo', frame) def detectPedestrian(self, frame) : self.__upload_request('detectPedestrian', frame) def detectFruits(self, frame) : self.__upload_request('detectFruits', frame) def recognizeBussinessCard(self, frame) : self.__upload_request('recognizeBusinessCard', frame) def recognizeVehicleType(self, frame) : self.__upload_request('recognizeVehicle', frame) def detectVehicleCongestion(self, frame) : self.__upload_request('vehicleCongestionDetect', frame) def classifyRubbish(self, frame) : self.__upload_request('classifyingRubbish', frame) def detectObject(self, frame) : self.__upload_request('detectObject', frame)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/pedestrian_detection/esp32/code/cloudAI.py
Python
apache-2.0
10,770
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : main.py @Description: 人体检测案例 @Author : luokui & jiangyu @version : 2.0 ''' import display # 显示库 import network # 网络库 import ucamera # 摄像头库 import utime # 延时函数在utime库中 import _thread # 线程库 import sntp # 网络时间同步库 from cloudAI import * # Wi-Fi SSID和Password设置 SSID='Your-AP-SSID' PWD='Your-AP-Password' # HaaS设备三元组 productKey = "Your-ProductKey" deviceName = "Your-devicename" deviceSecret = "Your-deviceSecret" detected = False key_info = { 'region' : 'cn-shanghai' , 'productKey': productKey , 'deviceName': deviceName , 'deviceSecret': deviceSecret , 'keepaliveSec': 60 } def connect_wifi(ssid, pwd): # 引用全局变量 global disp # 初始化网络 wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(ssid, pwd) while True: print('Wi-Fi is connecting...') # 显示网络连接中 disp.text(20, 30, 'Wi-Fi is connecting...', disp.RED) # 网络连接成功后,更新显示字符 if (wlan.isconnected() == True): print('Wi-Fi is connected') disp.textClear(20, 30, 'Wi-Fi is connecting...') disp.text(20, 30, 'Wi-Fi is connected', disp.RED) ip = wlan.ifconfig()[0] print('IP: %s' %ip) disp.text(20, 50, ip, disp.RED) # NTP时间更新,如果更新不成功,将不能进行识别 print('NTP start') disp.text(20, 70, 'NTP start...', disp.RED) sntp.setTime() print('NTP done') disp.textClear(20, 70, 'NTP start...') disp.text(20, 70, 'NTP done', disp.RED) break utime.sleep_ms(500) utime.sleep(2) def recognize_cb(commandReply, result) : global detected detected = False if commandReply == 'DetectPedestrianReply' : detected = result else : print('unknown command reply') # 识别线程函数 def recognizeThread(): global frame while True: if frame != None: engine.detectPedestrian(frame) utime.sleep_ms(1000) else: utime.sleep_ms(1000) # 显示线程函数 def displayThread(): # 引用全局变量 global disp, frame, detected, gesture # 定义清屏局部变量 clearFlag = False # 定义显示文本局部变量 textShowFlag = False while True: # 采集摄像头画面 # print('start to capture') frame = ucamera.capture() # print('end to capture') if frame != None: if detected == True: # 清除屏幕内容 disp.clear() # 设置文字字体 disp.font(disp.FONT_DejaVu40) # 显示识别结果 disp.text(40, 80, 'Pedestrian', disp.RED) disp.text(40, 120, 'Deteted!!!', disp.RED) utime.sleep_ms(1000) textShowFlag = False else: # 显示图像 # print('start to display') disp.image(0, 20, frame, 0) utime.sleep_ms(100) if textShowFlag == False: # 设置显示字体 disp.font(disp.FONT_DejaVu18) # 显示文字 disp.text(2, 0, 'Recognizing...', disp.WHITE) textShowFlag = True def main(): # 全局变量 global disp, frame, detected, engine # 创建lcd display对象 disp = display.TFT() frame = None detected = False # 连接网络 connect_wifi(SSID, PWD) engine = CloudAI(key_info, recognize_cb) # 初始化摄像头 ucamera.init('uart', 33, 32) ucamera.setProp(ucamera.SET_FRAME_SIZE, ucamera.SIZE_320X240) try: # 启动显示线程 _thread.start_new_thread(displayThread, ()) # 设置比对线程stack _thread.stack_size(20 * 1024) # 启动比对线程 _thread.start_new_thread(recognizeThread, ()) except: print("Error: unable to start thread") while True: utime.sleep_ms(1000) if __name__ == '__main__': main()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/pedestrian_detection/esp32/code/main.py
Python
apache-2.0
4,365
# -*- encoding: utf-8 -*- from driver import GPIO from uln2003 import * if __name__ == '__main__': relay_dev = GPIO() relay_dev.open('relay') a = GPIO() a.open('uln2003_a') a_ = GPIO() a_.open('uln2003_a_') b = GPIO() b.open('uln2003_b') b_ = GPIO() b_.open('uln2003_b_') motor_dev= ULN2003(a, a_, b, b_) while True: relay_val = 0 # 正转 for i in range(0, 64): relay_dev.write(relay_val) if relay_val == 0: relay_val = 1 else: relay_val = 0 for j in range(0, 16): motor_dev.motorCw(4) # 反转 for i in range(0, 64): relay_dev.write(relay_val) if relay_val == 0: relay_val = 1 else: relay_val = 0 for j in range(0, 16): motor_dev.motorCcw(4)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/playing_with_cats/nodemcu32s/code/main.py
Python
apache-2.0
927
""" Copyright (C) 2015-2021 Alibaba Group Holding Limited MicroPython's driver for ULN2003 Author: HaaS Date: 2022/03/15 """ from driver import GPIO from utime import sleep_ms from micropython import const import math class ULN2003(object): """ This class implements uln2003 chip's defs. """ def __init__(self, a, a_, b, b_): self._a = None self._a_ = None self._b = None self._b_ = None if not isinstance(a, GPIO): raise ValueError("parameter is not an GPIO object") if not isinstance(a_, GPIO): raise ValueError("parameter is not an GPIO object") if not isinstance(b, GPIO): raise ValueError("parameter is not an GPIO object") if not isinstance(b_, GPIO): raise ValueError("parameter is not an GPIO object") # make ULN2003's internal object points to gpio self._a = a self._a_ = a_ self._b = b self._b_ = b_ def motorCw(self, speed=4): self._a.write(1) self._a_.write(0) self._b.write(0) self._b_.write(0) sleep_ms(speed) self._a.write(0) self._a_.write(1) self._b.write(0) self._b_.write(0) sleep_ms(speed) self._a.write(0) self._a_.write(0) self._b.write(1) self._b_.write(0) sleep_ms(speed) self._a.write(0) self._a_.write(0) self._b.write(0) self._b_.write(1) sleep_ms(speed) def motorCcw(self, speed=4): self._a.write(0) self._a_.write(0) self._b.write(0) self._b_.write(1) sleep_ms(speed) self._a.write(0) self._a_.write(0) self._b.write(1) self._b_.write(0) sleep_ms(speed) self._a.write(0) self._a_.write(1) self._b.write(0) self._b_.write(0) sleep_ms(speed) self._a.write(1) self._a_.write(0) self._b.write(0) self._b_.write(0) sleep_ms(speed) def motorStop(self): self._a.write(0) self._a_.write(0) self._b.write(0) self._b_.write(0)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/playing_with_cats/nodemcu32s/code/uln2003.py
Python
apache-2.0
2,207