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
# coding=utf-8 # This is a sample Python script. from aliyunIoT import Device import ujson import network import utime as time from driver import GPIO from driver import UART t1 = 30 gas_threshold = 5.0 liq_mdcn_alarm = False gas_alarm = False version = 'v0.0.1' uart1 = UART('serail1') liq_level = GPIO() gpio = GPIO() '''0 1 means cloud ctrl,2 local ctrl''' cloud_ctrl = 2 g_connect_status = False ini_file_name = '/user/cfg.txt' 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 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('connect network failed') for i in range(30): if g_connect_status: print('connect network success') return True time.sleep(1) return False def read_cfg_file(): global t1,gas_threshold,ini_file_name try: f = open(ini_file_name,'r') except OSError: cfg_dict = {'gasstr':1.0,'t1':60} print('write',cfg_dict) f = open(ini_file_name,'w+') print(f) f.write(ujson.dumps(cfg_dict)) else: cfg_txt = f.read() cfg_dict = ujson.loads(cfg_txt) if isinstance(cfg_dict,dict) == False: print('cfg_dict not a dict') return print('read',cfg_dict) gas_threshold = cfg_dict['gasstr'] t1 = cfg_dict['t1'] print('gas',gas_threshold,'t1',t1) finally: f.close() print('close') return 0 def write_cfg_file(cloudstr): global t1,gas_threshold,ini_file_name if isinstance(cloudstr,str) == False: return try: f = open(ini_file_name,'r') except OSError: pass else: cfg_txt = f.read() f.close() finally: pass try: f = open(ini_file_name,'w+') except OSError: pass else: cfg_dict = ujson.loads(cfg_txt) cloud_dict = ujson.loads(cloudstr) if isinstance(cfg_dict,dict) == False: print('cfg_dict not a dict') return if isinstance(cloud_dict,dict) == False: print('cloud_dict not a dict') return for key in cloud_dict.keys(): if cfg_dict.get(key) != None: cfg_dict[key] = cloud_dict[key] if key == 'gasstr': gas_threshold = cfg_dict[key] if key == 't1': t1 = cfg_dict[key] f.seek(0) f.write(ujson.dumps(cfg_dict)) print(cfg_dict) pass finally: f.close() print('cloud cfg file close') return def on_connect(): print('linkkit is connected') def on_disconnect(): print('linkkit is disconnected') def on_props(request): print('clound req data is {}'.format(request)) global gpio global cloud_ctrl cloudmsg = ujson.loads(request) if 'powerstate' in cloudmsg: if cloudmsg['powerstate'] == 0: gpio.write(0) #pass cloud_ctrl = 0 print('led state {}'.format(cloudmsg['powerstate'])) else: cloud_ctrl = 1 gpio.write(1) #pass print('led state {}'.format(cloudmsg['powerstate'])) else: write_cfg_file(request) def on_service(id,request): print('clound req id is {} , req is {}'.format(id,request)) def on_error(err): print('err msg is {} '.format(err)) def gas_detec(): gas_val = 0.0 dotnum = 0 global uart1 len1 = 0 #sign = 0 uart1.open('serial1') readbuf1 = bytearray(9) writebuf1 = bytearray([0xd7]) readbuf2 = bytearray(13) writebuf2 = bytearray([0xff,0x01,0x87,0x00,0x00,0x00,0x00,0x00,0x78]) uart1.write(writebuf1) len1 = uart1.read(readbuf1) print('dotnum:',end='') print(readbuf1) if len1 != len(readbuf1): print('read dotnum err') uart1.close() return gas_val uart1.write(writebuf2) len1 = uart1.read(readbuf2) print('readlen:',len1,'dotnum:',end='') print(readbuf2) if len1 != len(readbuf2): print('read gas err') uart1.close() return gas_val uart1.close() dotnum = (readbuf1[6]&0xf0)>> 4 #sign = readbuf1[6]&0x0f gas_val = (readbuf2[2]*256.000 + readbuf2[3])*1.000/10**dotnum print('gasvalue:',end='') print(gas_val) return gas_val def liquid_level_detec(): lowval = liq_level.read() print('lowval',lowval) liq_meicn_remain = False if lowval == 1: liq_meicn_remain = True else: liq_meicn_remain = False return liq_meicn_remain def main(): global liq_level,cloud_ctrl,t1,liq_mdcn_alarm,gas_alarm ret = connect_network() print('network register sta {}'.format(ret)) productKey = 'xxx' productSecret = '' deviceName = 'haas505_demo_sn1' deviceSecret = 'xxx' key_info = { 'region' : 'cn-shanghai', 'productKey' : productKey, 'deviceName' : deviceName, 'deviceSecret' : deviceSecret, 'productSecret' : productSecret, 'keepaliveSec': 60 } device = Device() 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) send_info = {'ver':version,'name':key_info['deviceName']} post_data = {'params':ujson.dumps(send_info)} device.postProps(post_data) read_cfg_file() time.sleep(2) led1 = GPIO() pump = GPIO() '''liqid level detec prompt led''' led1.open('led1') '''liquid level detec io''' liq_level.open('liq_level') '''control pump relay''' pump.open('pump') pump.write(1) '''cloud_flg is cloud down data led''' gpio.open('cloud_flg') time_cnt = 0 gas_value = 0.00 liq_mdcn_re_flg_chg = False need_send = False while True: time.sleep_ms(1000) time_cnt += 1 liq_mdcn_re_flg = liquid_level_detec() if liq_mdcn_re_flg == False: led1.write(0) if liq_mdcn_re_flg_chg == True: liq_mdcn_re_flg_chg = False need_send = True pass else: led1.write(1) need_send = True liq_mdcn_re_flg_chg = True print('need send') '''need send data to cloud''' pass if time_cnt%10 == 0: gas_value = gas_detec() if gas_value > gas_threshold: '''need send data to cloud''' gas_alarm = True need_send = True print('need send') else: gas_alarm = False pass if liq_mdcn_re_flg == True: need_send = False pump.write(1) cloud_ctrl = 2 print('close pump') post_data = {'params':{'liq_mdcn_re':0,'gasval':100,'gasalarm':0,'powerstate':0}} post_data['params']['liq_mdcn_re'] = 0 gas_value = gas_detec() post_data['params']['gasval'] = int(gas_value*100) if gas_alarm == True: post_data['params']['gasalarm'] = 1 post_data['params']['powerstate'] = gpio.read() post_data_dict = {'params':ujson.dumps(post_data['params'])} device.postProps(post_data_dict) continue if gas_alarm == False: if time_cnt%t1 == 0: if pump.read() == 1 : pump.write(0) print('open pump') else: pump.write(1) print('close pump') else: pass if cloud_ctrl == 0: pump.write(1) cloud_ctrl = 2 time_cnt = 0 print('cloud close pump') elif cloud_ctrl == 1: pump.write(0) cloud_ctrl = 2 time_cnt = 0 print('cloud open pump') elif gas_alarm == True: pump.write(1) print('gas alarm close pump') if need_send == True: need_send = False post_data1 = {'params':{'liq_mdcn_re':0,'gasval':100,'gasalarm':0,'powerstate':0}} if liq_mdcn_re_flg == True: post_data1['params']['liq_mdcn_re'] = 0 else: post_data1['params']['liq_mdcn_re'] = 1 post_data1['params']['gasval'] = int(gas_value*100) if gas_alarm == True: post_data1['params']['gasalarm'] = 1 post_data1['params']['powerstate'] = gpio.read() post_data1_dict = {'params':ujson.dumps(post_data1['params'])} device.postProps(post_data1_dict) if __name__ == '__main__': main()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/air_detector/haas506/code/main.py
Python
apache-2.0
9,630
from micropython import const import ustruct import i2c_bus import utime as time # import deviceCfg _BTN_IRQ = const(0x46) def map_value(value, input_min, input_max, aims_min, aims_max): value = min(max(input_min, value), input_max) value_deal = (value - input_min) * (aims_max - aims_min) / \ (input_max - input_min) + aims_min return value_deal class Axp192: CURRENT_100MA = const(0b0000) CURRENT_190MA = const(0b0001) CURRENT_280MA = const(0b0010) CURRENT_360MA = const(0b0011) CURRENT_450MA = const(0b0100) CURRENT_550MA = const(0b0101) CURRENT_630MA = const(0b0110) CURRENT_700MA = const(0b0111) def __init__(self): self.addr = 0x34 self.i2c = i2c_bus.get(i2c_bus.M_BUS, device_in=True) def powerAll(self): regchar = self._regChar # axp: vbus limit off regchar(0x30, (self._read8bit(0x30) & 0x04) | 0x02) # AXP192 GPIO1:OD OUTPUT regchar(0x92, self._read8bit(0x92) & 0xf8) # AXP192 GPIO2:OD OUTPUT regchar(0x93, self._read8bit(0x93) & 0xf8) # AXP192 RTC CHG regchar(0x35, (self._read8bit(0x35) & 0x1c) | 0xa3) # ESP voltage:3.35V self.setESPVoltage(3350) # LCD backlight voltage:3.3V # self.setLCDBacklightVoltage(3300) # Periph power voltage preset (LCD_logic, SD card) self.setLDOVoltage(2, 3300) # Vibrator power voltage preset self.setLDOVoltage(3, 2000) # Eanble LCD SD power self.setLDOEnable(2, True) # Set charge current:100ma # self.setChargeCurrent(CURRENT_100MA) # self.setChargeCurrent(deviceCfg.get_bat_charge_current()) # AXP192 GPIO4 regchar(0x95, (self._read8bit(0x95) & 0x72) | 0x84) regchar(0x36, 0x4C) regchar(0x82, 0xff) self.setLCDReset(0) time.sleep(0.1) self.setLCDReset(1) time.sleep(0.1) # if deviceCfg.get_comx_status(): # self.setBusPowerMode(1) # disable M-Bus 5V output if use COM.X module. # else: self.setBusPowerMode(0) # enable M-Bus 5V output as default. def powerOff(self): self._regChar(0x32, self._regChar(0x32) | 0x80) # AXP192 Status getting function def getTempInAXP192(self): return (self._read12Bit(0x5e)) * 0.1 - 144.7 def getChargeState(self): return True if self._regChar(0x01) & 0x40 else False def getBatVoltage(self): return (self._read12Bit(0x78)) * 1.1 / 1000 def getBatCurrent(self): currentIn = self._read13Bit(0x7A) currentOut = self._read13Bit(0x7C) return (currentIn - currentOut) * 0.5 def getVinVoltage(self): return (self._read12Bit(0x56)) * 1.7 / 1000 def getVinCurrent(self): return (self._read12Bit(0x58)) * 0.625 def getVBusVoltage(self): return (self._read12Bit(0x5A)) * 1.7 / 1000 def getVBusCurrent(self): return (self._read12Bit(0x5C)) * 0.375 # AXP192 Status setting function def setChargeState(self, state): pass def setChargeCurrent(self, current): buf = self._regChar(0x33) buf = (buf & 0xf0) | (current & 0x0f) self._regChar(0x33, buf) def setBusPowerMode(self, mode): """ 0: M-BUS 5V output mode. 1: M-BUS 5V input mode. """ if mode == 0: self._regChar(0x91, (self._read8bit(0x91) & 0x0F) | 0xF0) self._regChar(0x90, (self._read8bit(0x90) & 0xF8) | 0x02) self._regChar(0x12, (self._read8bit(0x12) | 0x40)) else: self._regChar(0x12, self._read8bit(0x12) & 0xBF) self._regChar(0x90, (self._read8bit(0x90) & 0xF8) | 0x01) def setLDOVoltage(self, number, voltage): # print("number: " + str(number) + " voltage: " + str(voltage)) if voltage > 3300: vol = 15 else: vol = (int)((voltage / 100) - 18) regchar = self._regChar if number == 2: regchar(0x28, ((self._read8bit(0x28) & 0x0F) | (vol << 4))) if number == 3: regchar(0x28, ((self._read8bit(0x28) & 0xF0) | vol)) def setLDOEnable(self, number, state): mask = 0x01 if number < 2 or number > 3: return mask = mask << number if(state): self._regChar(0x12, self._read8bit(0x12) | mask) else: self._regChar(0x12, self._read8bit(0x12) & (~ mask)) def setDCVoltage(self, number, voltage): addr = [0, 0x26, 0x25, 0x27] regchar = self._regChar if number < 1 and number > 3: return vol = (int)(0 if voltage < 700 else (voltage - 700) / 25) regchar(addr[number], (self._read8bit( addr[number]) & 0x80) | (vol & 0x7F)) def disableAllIRQ(self): for i in [0x40, 0x41, 0x42, 0x43, 0x4a]: self._regChar(i, 0x00) def clearAllIRQ(self): for i in [0x44, 0x45, 0x46, 0x47, 0x4d]: self._regChar(i, 0xff) def enableBtnIRQ(self): self._regChar(0x42, 0x02) # ESP32 Voltage def setESPVoltage(self, voltage): if voltage >= 3000 and voltage <= 3400: self.setDCVoltage(1, voltage) # LCD backlight Voltage def setLCDBacklightVoltage(self, voltage): voltage = voltage * 1000 if voltage >= 2400 and voltage <= 3300: self.setDCVoltage(3, voltage) def setLCDEnable(self, state): self.setLDOEnable(2, state) # LCD Brightness def setLCDBrightness(self, brightness): vol = map_value(brightness, 0, 100, 2400, 3300) self.setDCVoltage(3, vol) # LCD Reset def setLCDReset(self, state): mask = 0x02 if state: self._regChar(0x96, self._read8bit(0x96) | mask) else: self._regChar(0x96, self._read8bit(0x96) & (~ mask)) # Set Power LED def setPowerLED(self, state): if state: self._regChar(0x94, self._read8bit(0x94) & 0xFD) else: self._regChar(0x94, self._read8bit(0x94) | 0x02) def setSpkEnable(self, state): gpio_bit = 0x04 data = self._read8bit(0x94) if state: data = data | gpio_bit else: data = data & (~gpio_bit) self._regChar(0x94, data) # It seem not useful for Vibration motor. # LDO3: 1.8v ~ 3.3v def setVibrationIntensity(self, value): vol = map_value(value, 0, 100, 1800, 3300) self.setLDOVoltage(3, vol) def setVibrationEnable(self, state): self.setLDOEnable(3, state) # I2C read and write function def _regChar(self, reg, value=None, buf=bytearray(1)): if value is None: self.i2c.readfrom_mem_into(self.addr, reg, buf) return buf[0] ustruct.pack_into('<b', buf, 0, value) return self.i2c.writeto_mem(self.addr, reg, buf) def _read8bit(self, reg): buf = bytearray(1) self.i2c.readfrom_mem_into(self.addr, reg, buf) return buf[0] def _read12Bit(self, reg): buf = bytearray(2) self.i2c.readfrom_mem_into(self.addr, reg, buf) return (buf[0] << 4) | buf[1] def _read13Bit(self, reg): buf = bytearray(2) self.i2c.readfrom_mem_into(self.addr, reg, buf) return (buf[0] << 5) | buf[1] def _read16Bit(self, reg): buf = bytearray(2) self.i2c.readfrom_mem_into(self.addr, reg, buf) return (buf[0] << 8) | buf[1] def deinit(self): pass
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/air_pressure_detection/esp32/code/axp192.py
Python
apache-2.0
7,601
import ubluetooth import json import gc import time import network from micropython import const _wlan = network.WLAN(network.STA_IF) _ble = ubluetooth.BLE() _bleNetConfigStatus = None _ble_adv_name = 'esp-node' _ble_tx = None _ble_rx = None _ble_msg = '' BLE_CONNECTED = const(0x00) BLE_DISCONNECTED = const(0x01) BLE_COMMINICATING = const(0x02) WIFI_IDLE = 1000 WIFI_CONNECTING = 1001 WIFI_GOT_IP = network.STAT_GOT_IP NUS_UUID = 0xFFA0 RX_UUID = 0xFFA2 TX_UUID = 0xFFA3 BLE_NUS = ubluetooth.UUID(NUS_UUID) BLE_RX = (ubluetooth.UUID(RX_UUID), ubluetooth.FLAG_WRITE) BLE_TX = (ubluetooth.UUID(TX_UUID), ubluetooth.FLAG_NOTIFY | ubluetooth.FLAG_READ) BLE_UART = (BLE_NUS, (BLE_TX, BLE_RX,)) SERVICES = [BLE_UART, ] def send(data): _ble.gatts_notify(0, _ble_tx, data + '\n') def advertiser(name): _name = bytes(name, 'UTF-8') _ble.gap_advertise(100, bytearray('\x02\x01\x02') + bytearray((len(_name) + 1, 0x09)) + _name) def ble_irq(event, data): global _ble_msg, _bleNetConfigStatus if event == 1: _bleNetConfigStatus = BLE_CONNECTED elif event == 2: _bleNetConfigStatus = BLE_DISCONNECTED advertiser("esp-node") elif event == 3: buffer = _ble.gatts_read(_ble_rx) _ble_msg += buffer.decode('hex').strip() _ble_msg = '{"cmd":' + _ble_msg.split('{"cmd":')[-1] if(_ble_msg.count('{') == _ble_msg.count('}')): try: cmdd = json.loads(_ble_msg) except Exception as e: pass else: if(cmdd['cmd'] == 'WiFiCon'): _wlan.active(True) if(_wlan.isconnected()): _wlan.disconnect() _wlan.connect(cmdd['param']['ssid'], cmdd['param']['pswd']) timeout = 5 if('timeout' in cmdd['param'].keys()): timeout = int(cmdd['param']['timeout']) while(True): status = _wlan.status() if(status == network.STAT_WRONG_PASSWORD): _bleNetConfigStatus = BLE_COMMINICATING ret = {'cmd': 'WiFiCon', 'ret': { 'state': 'STAT_WRONG_PASSWORD'}} send(json.dumps(ret).encode('hex')) _bleNetConfigStatus = BLE_CONNECTED break if(status == network.STAT_NO_AP_FOUND): _bleNetConfigStatus = BLE_COMMINICATING ret = {'cmd': 'WiFiCon', 'ret': { 'state': 'STAT_NO_AP_FOUND'}} send(json.dumps(ret).encode('hex')) _bleNetConfigStatus = BLE_CONNECTED break if(status == network.STAT_GOT_IP): _bleNetConfigStatus = BLE_COMMINICATING ret = {'cmd': 'WiFiCon', 'ret': { 'state': 'STAT_GOT_IP', 'ifconfig': _wlan.ifconfig()}} send(json.dumps(ret).encode('hex')) _bleNetConfigStatus = BLE_CONNECTED break if(status == 1001): pass if(timeout < 0): _bleNetConfigStatus = BLE_COMMINICATING ret = {'cmd': 'WiFiCon', 'ret': { 'state': 'STAT_CONNECT_TIMEOUT'}} send(json.dumps(ret).encode('hex')) _bleNetConfigStatus = BLE_CONNECTED break time.sleep(1) timeout -= 1 _ble_msg = '' gc.collect() def start(): global _ble, _ble_tx, _ble_rx, _bleNetConfigStatus _ble.active(True) ((_ble_tx, _ble_rx,), ) = _ble.gatts_register_services(SERVICES) _ble.irq(ble_irq) advertiser(_ble_adv_name) _bleNetConfigStatus = BLE_DISCONNECTED def stop(): global _ble, _bleNetConfigStatus _ble.irq(None) _ble.active(False) _bleNetConfigStatus = BLE_DISCONNECTED def getWLAN(): return _wlan def getBleStatus(): return _bleNetConfigStatus def getWiFiStatus(): return _wlan.status() def getWiFiConfig(): return _wlan.ifconfig()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/air_pressure_detection/esp32/code/bleNetConfig.py
Python
apache-2.0
4,533
""" Copyright (C) 2015-2021 Alibaba Group Holding Limited MicroPython's driver for QMP6988 Author: HaaS Date: 2021/09/14 """ from driver import I2C from utime import sleep_ms from micropython import const import math BSP280_CHIP_ID = const(0x58) BMP280_REGISTER_DIG_T1 = const(0x88) BMP280_REGISTER_DIG_T2 = const(0x8A) BMP280_REGISTER_DIG_T3 = const(0x8C) BMP280_REGISTER_DIG_P1 = const(0x8E) BMP280_REGISTER_DIG_P2 = const(0x90) BMP280_REGISTER_DIG_P3 = const(0x92) BMP280_REGISTER_DIG_P4 = const(0x94) BMP280_REGISTER_DIG_P5 = const(0x96) BMP280_REGISTER_DIG_P6 = const(0x98) BMP280_REGISTER_DIG_P7 = const(0x9A) BMP280_REGISTER_DIG_P8 = const(0x9C) BMP280_REGISTER_DIG_P9 = const(0x9E) BMP280_REGISTER_CHIPID = const(0xD0) BMP280_REGISTER_VERSION = const(0xD1) BMP280_REGISTER_SOFTRESET = const(0xE0) BMP280_REGISTER_CAL26 = const(0xE1) BMP280_REGISTER_CONTROL = const(0xF4) BMP280_REGISTER_CONFIG = const(0xF5) BMP280_REGISTER_PRESSUREDATA = const(0xF7) BMP280_REGISTER_TEMPDATA = const(0xFA) class bmp280Error(Exception): def __init__(self, value=0, msg="bmp280 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 BMP280(object): """ This class implements bmp280 chip's defs. """ def __init__(self, i2cDev): self._i2cDev = None if not isinstance(i2cDev, I2C): raise ValueError("parameter is not an I2C object") # make BMP280's internal object points to i2cDev self._i2cDev = i2cDev self.dig_T1 = 0 self.dig_T2 = 0 self.dig_T3 = 0 self.dig_P1 = 0 self.dig_P2 = 0 self.dig_P3 = 0 self.dig_P4 = 0 self.dig_P5 = 0 self.dig_P6 = 0 self.dig_P7 = 0 self.dig_P8 = 0 self.dig_P9 = 0 self.init() self.readCoefficients() self.writeReg(BMP280_REGISTER_CONTROL, 0x3f) self.t_fine = 0 def readCoefficients(self): self.dig_T1 = self.readReg16(BMP280_REGISTER_DIG_T1) self.dig_T2 = self.readReg16_INT16(BMP280_REGISTER_DIG_T2) self.dig_T3 = self.readReg16_INT16(BMP280_REGISTER_DIG_T3) self.dig_P1 = self.readReg16(BMP280_REGISTER_DIG_P1) self.dig_P2 = self.readReg16_INT16(BMP280_REGISTER_DIG_P2) self.dig_P3 = self.readReg16_INT16(BMP280_REGISTER_DIG_P3) self.dig_P4 = self.readReg16_INT16(BMP280_REGISTER_DIG_P4) self.dig_P5 = self.readReg16_INT16(BMP280_REGISTER_DIG_P5) self.dig_P6 = self.readReg16_INT16(BMP280_REGISTER_DIG_P6) self.dig_P7 = self.readReg16_INT16(BMP280_REGISTER_DIG_P7) self.dig_P8 = self.readReg16_INT16(BMP280_REGISTER_DIG_P8) self.dig_P9 = self.readReg16_INT16(BMP280_REGISTER_DIG_P9) # 写寄存器 def writeReg(self, addr, value): Reg = bytearray([addr, value]) self._i2cDev.write(Reg) #print("--> write addr " + hex(addr) + ", value = " + hex(value)) return 0 # 读寄存器 def readReg(self, addr, len): Reg = bytearray([addr]) self._i2cDev.write(Reg) sleep_ms(2) tmp = bytearray(len) self._i2cDev.read(tmp) #print("<-- read addr " + hex(addr) + ", value = " + hex(tmp[0])) return tmp def readReg16(self, addr): tmp = self.readReg(addr, 2) data = (tmp[1] << 8) + tmp[0] return data def readReg16_BE(self, addr): tmp = self.readReg(addr, 2) data = (tmp[0] << 8) + tmp[1] return data def readReg8(self, addr): tmp = self.readReg(addr, 1) data = tmp[0] return data def int16(self, dat): if dat > 32767: return dat - 65536 else: return dat def int32(self, dat): if dat > (1 << 31): return dat - (1 << 32) else: return dat def readReg16_INT16(self, addr): tmp = self.readReg(addr, 2) data = (tmp[1] << 8) + tmp[0] data = self.int16(data) # print("addr:0x%x" % addr) # print("tmp[0]:0x%x" % tmp[0]) # print("tmp[1]:0x%x" % tmp[1]) # print("data:%d" % data) return data def deviceCheck(self): ret = self.readReg(BMP280_REGISTER_CHIPID, 1)[0] #print("qmp6988 read chip id = " + hex(ret)) if (ret == BSP280_CHIP_ID): return 0 else: return 1 def getTemperature(self): adc_T = self.readReg16_BE(BMP280_REGISTER_TEMPDATA) adc_T <<= 8 adc_T |= self.readReg8(BMP280_REGISTER_TEMPDATA + 2) adc_T >>= 4 var1 = ((adc_T >> 3) - (self.dig_T1 << 1)) * (self.dig_T2) >> 11 var2 = (((((adc_T >> 4) - self.dig_T1) * ((adc_T >> 4) - self.dig_T1)) >> 12) * (self.dig_T3)) >> 14 self.t_fine = var1 + var2 t = ((self.t_fine * 5) + 128) >> 8 return t / 100 def getPressure(self): # before get pressure, needs to get temperature. self.getTemperature() adc_P = self.readReg16_BE(BMP280_REGISTER_PRESSUREDATA) adc_P <<= 8 adc_P |= self.readReg8(BMP280_REGISTER_PRESSUREDATA+2) adc_P >>= 4 var1 = self.t_fine - 128000 var2 = var1 * var1 * self.dig_P6 var2 = (var2) + (((var1 * self.dig_P5)) << 17) var2 = var2 + (self.dig_P4 << 35) var1 = ((var1 * var1 * self.dig_P3) >> 8) + \ ((var1 * self.dig_P2) << 12) var1 = (((1 << 47) + var1) * (self.dig_P1)) >> 33 p = 1048576 - adc_P p = (((p << 31) - var2) * 3125) / var1 var1 = ((self.dig_P9) * (p / (1 << 13)) * (p / (1 << 13))) / (1 << 25) var2 = (self.dig_P8 * p) / (1 << 19) p = ((p + var1 + var2) / (1 << 8)) + (self.dig_P7 << 4) return p / 256 def init(self): ret = self.deviceCheck() if (ret != 0): print("bmp280 init fail") return 0 else: pass
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/air_pressure_detection/esp32/code/bmp280.py
Python
apache-2.0
6,091
from machine import I2C from machine import Pin from micropython import const import struct #import unit #PORTA = (unit.PORTA) PAHUB0 = (0, None) PAHUB1 = (1, None) PAHUB2 = (2, None) PAHUB3 = (3, None) PAHUB4 = (4, None) PAHUB5 = (5, None) M_BUS = (21, 22) UINT8LE = const((0 << 6) | (1 << 4) | 1) UINT16LE = const((0 << 6) | (1 << 4) | 2) UINT32LE = const((0 << 6) | (1 << 4) | 4) INT8LE = const((0 << 6) | (0 << 4) | 1) INT16LE = const((0 << 6) | (0 << 4) | 2) INT32LE = const((0 << 6) | (0 << 4) | 4) UINT8BE = const((1 << 6) | (1 << 4) | 1) UINT16BE = const((1 << 6) | (1 << 4) | 2) UINT32BE = const((1 << 6) | (1 << 4) | 4) INT8BE = const((1 << 6) | (0 << 4) | 1) INT16BE = const((1 << 6) | (0 << 4) | 2) INT32BE = const((1 << 6) | (0 << 4) | 4) def get(port, pos=0, freq=400000, device_in=False): if port[1] is None: return Pahub_I2C(port[0]) if device_in or port == (21, 22): return I2C(1, sda=Pin(port[0]), scl=Pin(port[1]), freq=freq) else: return I2C(0, sda=Pin(port[0]), scl=Pin(port[1]), freq=freq) class easyI2C(): def __init__(self, port, addr, freq=400000): self.i2c = get(port, pos=0, freq=freq) self.addr = addr def write_u8(self, reg, data): buf = bytearray(1) buf[0] = data self.i2c.writeto_mem(self.addr, reg, buf) def write_u16(self, reg, data, byteorder='big'): buf = bytearray(2) encode = '<h' if byteorder == 'little' else '>h' struct.pack_into(encode, buf, 0, data) self.i2c.writeto_mem(self.addr, reg, buf) def write_u32(self, reg, data, byteorder='big'): buf = bytearray(4) encode = '<i' if byteorder == 'little' else '>i' struct.pack_into(encode, buf, 0, data) self.i2c.writeto_mem(self.addr, reg, buf) def read_u8(self, reg): return self.i2c.readfrom_mem(self.addr, reg, 1)[0] def read_u16(self, reg, byteorder='big'): buf = bytearray(2) self.i2c.readfrom_mem_into(self.addr, reg, buf) encode = '<h' if byteorder == 'little' else '>h' return struct.unpack(encode, buf)[0] def read_u32(self, reg, byteorder='big'): buf = bytearray(4) self.i2c.readfrom_mem_into(self.addr, reg, buf) encode = '<i' if byteorder == 'little' else '>i' return struct.unpack(encode, buf)[0] def read(self, num): return self.i2c.readfrom(self.addr, num) def read_reg(self, reg, num): return self.i2c.readfrom_mem(self.addr, reg, num) @staticmethod def _get_format_str(format_type): format_str = '>' if (format_type & (1 << 6)) else '<' format_str += {1: 'b', 2: 'h', 4: 'i'}.get(format_type & 0x0f) format_str = format_str.upper() if (format_type & (1 << 4)) else format_str return format_str def write_mem_data(self, reg, data, format_type): format_str = self._get_format_str(format_type) buf = bytearray(struct.pack(format_str, data)) self.i2c.writeto_mem(self.addr, reg, buf) def write_data(self, data, format_type): format_str = self._get_format_str(format_type) buf = bytearray(struct.pack(format_str, data)) self.i2c.writeto(self.addr, buf) def write_list(self, data): buf = bytearray(data) self.i2c.writeto(self.addr, buf) def write_mem_list(self, reg, data, num): buf = bytearray(data) self.i2c.writeto_mem(self.addr, reg, buf) def read_data(self, num, format_type): format_str = self._get_format_str(format_type) format_str = format_str[0] + format_str[1] * num buf = bytearray((format_type & 0x0f) * num) self.i2c.readfrom_into(self.addr, buf) return struct.unpack(format_str, buf) def read_mem_data(self, reg, num, format_type): format_str = self._get_format_str(format_type) format_str = format_str[0] + format_str[1] * num buf = bytearray((format_type & 0x0f) * num) self.i2c.readfrom_mem_into(self.addr, reg, buf) return struct.unpack(format_str, buf) def scan(self): return self.i2c.scan() def available(self): return self.i2c.is_ready(self.addr) class Pahub_I2C: def __init__(self, pos, port=(32, 33), freq=100000): # PORTA (32, 33) from units import _pahub self.pahub = _pahub.Pahub(port) self.i2c = get(port, freq=freq) self.pos = pos def readfrom(self, addr, num): self.pahub.select_only_on(self.pos) data = self.i2c.readfrom(addr, num) return data def readfrom_into(self, addr, buf): buf_in = bytearray(len(buf)) self.pahub.select_only_on(self.pos) self.i2c.readfrom_into(addr, buf_in) for i in range(len(buf)): buf[i] = buf_in[i] def readfrom_mem_into(self, addr, reg, buf): buf_in = bytearray(len(buf)) self.pahub.select_only_on(self.pos) self.i2c.readfrom_mem_into(addr, reg, buf_in) for i in range(len(buf)): buf[i] = buf_in[i] def readfrom_mem(self, addr, reg, num): self.pahub.select_only_on(self.pos) data = self.i2c.readfrom_mem(addr, reg, num) return data def writeto_mem(self, addr, reg, data): self.pahub.select_only_on(self.pos) self.i2c.writeto_mem(addr, reg, data) def writeto(self, addr, data): self.pahub.select_only_on(self.pos) self.i2c.writeto(addr, data) def is_ready(self, addr): self.pahub.select_only_on(self.pos) data = self.i2c.is_ready(addr) return data def scan(self): self.pahub.select_only_on(self.pos) data = self.i2c.scan() return data def available(self): return self.i2c.is_ready(self.addr) def deinit(self): pass class Unit(Exception): pass class UnitI2C: def __init__(self, port, freq, addr): self.i2c = easyI2C(port, addr, freq) def _check_device(self): if self.i2c.available() or self.i2c.available(): pass else: raise Unit("{} unit not found".format(self.__qualname__.upper())) def deinit(self): pass
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/air_pressure_detection/esp32/code/i2c_bus.py
Python
apache-2.0
6,200
import lvgl as lv import display_driver from bmp280 import * import ujson def set_value(indic, v): meter.set_indicator_value(indic, v) # 压力值转海拔高度 def convertPressure2Altitude(p, t): height = ((1-((p/101325)**(1/5.255)))*(t+273.15)/0.0065) return height # # A simple meter # meter = lv.meter(lv.scr_act()) meter.center() meter.set_size(200, 200) # Add a scale first scale = meter.add_scale() meter.set_scale_ticks(scale, 81, 2, 10, lv.palette_main(lv.PALETTE.GREY)) meter.set_scale_major_ticks(scale, 10, 4, 15, lv.color_black(), 10) meter.set_scale_range(scale, 300, 1100, 270, 135) indic = lv.meter_indicator_t() # Add arc color for 300-400 indic = meter.add_arc(scale, 3, lv.color_hex(0x0000CD), 0) meter.set_indicator_start_value(indic, 300) meter.set_indicator_end_value(indic, 400) # Add the tick lines color for 300-400 indic = meter.add_scale_lines(scale, lv.color_hex( 0x0000CD), lv.color_hex(0x0000CD), False, 0) meter.set_indicator_start_value(indic, 300) meter.set_indicator_end_value(indic, 400) # Add arc color for 400-500 indic = meter.add_arc(scale, 3, lv.color_hex(0x0000FF), 0) meter.set_indicator_start_value(indic, 400) meter.set_indicator_end_value(indic, 500) # Add the tick lines color for 400-500 indic = meter.add_scale_lines(scale, lv.color_hex( 0x0000FF), lv.color_hex(0x0000FF), False, 0) meter.set_indicator_start_value(indic, 400) meter.set_indicator_end_value(indic, 500) # Add arc color for 500-600 indic = meter.add_arc(scale, 3, lv.color_hex(0x1E90FF), 0) meter.set_indicator_start_value(indic, 500) meter.set_indicator_end_value(indic, 600) # Add the tick lines color for 500-600 indic = meter.add_scale_lines(scale, lv.color_hex( 0x1E90FF), lv.color_hex(0x1E90FF), False, 0) meter.set_indicator_start_value(indic, 500) meter.set_indicator_end_value(indic, 600) # Add arc color for 600-700 indic = meter.add_arc(scale, 3, lv.color_hex(0x00BFFF), 0) meter.set_indicator_start_value(indic, 600) meter.set_indicator_end_value(indic, 700) # Add the tick lines color for 600-700 indic = meter.add_scale_lines(scale, lv.color_hex( 0x00BFFF), lv.color_hex(0x00BFFF), False, 0) meter.set_indicator_start_value(indic, 600) meter.set_indicator_end_value(indic, 700) # Add arc color for 700-800 indic = meter.add_arc(scale, 3, lv.color_hex(0x7FFFAA), 0) meter.set_indicator_start_value(indic, 700) meter.set_indicator_end_value(indic, 800) # Add the tick lines color for 700-800 indic = meter.add_scale_lines(scale, lv.color_hex( 0x7FFFAA), lv.color_hex(0x7FFFAA), False, 0) meter.set_indicator_start_value(indic, 700) meter.set_indicator_end_value(indic, 800) # Add arc color for 800-900 indic = meter.add_arc(scale, 3, lv.color_hex(0x00FA9A), 0) meter.set_indicator_start_value(indic, 800) meter.set_indicator_end_value(indic, 900) # Add the tick lines color for 800-900 indic = meter.add_scale_lines(scale, lv.color_hex( 0x00FA9A), lv.color_hex(0x00FA9A), False, 0) meter.set_indicator_start_value(indic, 800) meter.set_indicator_end_value(indic, 900) # Add arc color for 900-1000 indic = meter.add_arc(scale, 3, lv.color_hex(0x3CB371), 0) meter.set_indicator_start_value(indic, 900) meter.set_indicator_end_value(indic, 1000) # Add the tick lines color for 900-1000 indic = meter.add_scale_lines(scale, lv.color_hex( 0x3CB371), lv.color_hex(0x3CB371), False, 0) meter.set_indicator_start_value(indic, 900) meter.set_indicator_end_value(indic, 1000) # Add arc color for 1000-1100 indic = meter.add_arc(scale, 3, lv.color_hex(0x2E8B57), 0) meter.set_indicator_start_value(indic, 1000) meter.set_indicator_end_value(indic, 1100) # Add the tick lines color for 1000-1100 indic = meter.add_scale_lines(scale, lv.color_hex( 0x2E8B57), lv.color_hex(0x2E8B57), False, 0) meter.set_indicator_start_value(indic, 1000) meter.set_indicator_end_value(indic, 1100) # Add a needle line indicator indic = meter.add_needle_line(scale, 4, lv.palette_main(lv.PALETTE.GREY), -10) style = lv.style_t() style.init() style.set_pad_all(2) style.set_x(70) style.set_y(220) style.set_text_color(lv.palette_main(lv.PALETTE.RED)) spans = lv.spangroup(lv.scr_act()) spans.set_width(300) spans.set_height(300) spans.add_style(style, 0) spans.set_overflow(lv.SPAN_OVERFLOW.CLIP) spans.set_mode(lv.SPAN_MODE.EXPAND) span = spans.new_span() if __name__ == "__main__": try: print("Testing bmp280") i2cDev = I2C() i2cDev.open("bmp280") baroDev = BMP280(i2cDev) while 1: # "pressure" - 代表气压传感器测量到的气压值 pressure = baroDev.getPressure() # "temprature" - 代表气压传感器测量到的温度值 temprature = baroDev.getTemperature() print(str(temprature) + ' 摄氏度') set_value(indic, int(int(pressure) / 100)) span.set_text(str(int(pressure) / 100) + ' hPa, ' + str(convertPressure2Altitude(pressure, temprature)) + ' m') print(str(int(pressure) / 100) + ' hPa') print(str(convertPressure2Altitude(pressure, temprature)) + ' m') # 每2秒钟上报一次 sleep_ms(2000) i2cDev.close() del baroDev print("Test bmp280 done") except OSError: print("make sure bmp280.py is in libs folder")
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/air_pressure_detection/esp32/code/main.py
Python
apache-2.0
5,326
print('enable OneMinuteOnCloud') import ubluetooth import uos as os import uerrno as errno import ujson as json import uzlib import upip_utarfile as tarfile import gc import time import machine import ussl import usocket import network _wlan = network.WLAN(network.STA_IF) _ble = ubluetooth.BLE() _ble_adv_name = 'esp-node' pull_code_state = [] file_buf = bytearray(128) def download_file_task(filelist): global pull_code_state for file_task in filelist: if('needunpack' in file_task.keys() and file_task['needunpack'] == True): gc.collect() print(gc.mem_free()) pull_code_state.append(install_pkg(file_task['url'], file_task['path'])) gc.collect() else: gc.collect() print(gc.mem_free()) pull_code_state.append(download_save_file(file_task['url'], file_task['path']+file_task['name'])) gc.collect() def download_save_file(file_url, fname): global file_buf f1 = url_open(file_url) if(isinstance(f1, (str, bytes, bytearray)) == True): print(f1) return f1 print(fname) _makedirs(fname) with open(fname, "wb") as outf: while True: sz = f1.readinto(file_buf) if not sz: break outf.write(file_buf, sz) outf.close() f1.close() del f1 print('download_save_file success') return 'SUCCESS' def install_pkg(package_url, install_path): gzdict_sz = 16 + 15 f1 = url_open(package_url) if(isinstance(f1, (str, bytes, bytearray)) == True): print(f1) return f1 try: f2 = uzlib.DecompIO(f1, gzdict_sz) f3 = tarfile.TarFile(fileobj=f2) install_tar(f3, install_path) except Exception as e: print(e) return("UNTAR_FILE_FAIL") finally: f1.close() del f3 del f2 gc.collect() print('install_pkg success') return 'SUCCESS' def url_open(url): proto, _, host, urlpath = url.split('/', 3) try: port = 443 if ":" in host: host, port = host.split(":") port = int(port) ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM) except OSError as e: print("Error:", "Unable to resolve %s (no Internet?)" % host, e) return 'HOST_RESOLVED_FAIL' print("Address infos:", ai) ai = ai[0] s = usocket.socket(ai[0], ai[1], ai[2]) try: s.connect(ai[-1]) if proto == "https:": s = ussl.wrap_socket(s, server_hostname=host) s.write("GET /%s HTTP/1.0\r\nHost: %s:%s\r\n\r\n" % (urlpath, host, port)) l = s.readline() protover, status, msg = l.split(None, 2) if status != b"200": if status == b"404" or status == b"301": return("Package not found") return(status) while True: l = s.readline() if not l: return("Unexpected EOF in HTTP headers") if l == b'\r\n': break except Exception as e: s.close() print(e) return('SOCKET_ERROR') return s def save_file(fname, subf): global file_buf with open(fname, "wb") as outf: while True: sz = subf.readinto(file_buf) if not sz: break outf.write(file_buf, sz) outf.close() def _makedirs(name, mode=0o777): ret = False s = "" comps = name.rstrip("/").split("/")[:-1] if comps[0] == "": s = "/" for c in comps: if s and s[-1] != "/": s += "/" s += c try: os.mkdir(s) ret = True except OSError as e: if e.args[0] != errno.EEXIST and e.args[0] != errno.EISDIR: print(e) ret = False return ret def install_tar(f, prefix): for info in f: print(info) fname = info.name try: fname = fname[fname.index("/") + 1:] except ValueError: fname = "" outfname = prefix + fname if info.type != tarfile.DIRTYPE: print("Extracting " + outfname) _makedirs(outfname) subf = f.extractfile(info) save_file(outfname, subf) def rmvdir(dir): for i in os.ilistdir(dir): if i[1] == 16384: rmvdir('{}/{}'.format(dir,i)) elif i[1] == 32678: os.remove('{}/{}'.format(dir,i[0])) os.rmdir(dir) def send(data): _ble.gatts_notify(0, _ble_tx, data + '\n') def advertiser(name): _name = bytes(name, 'UTF-8') _ble.gap_advertise(100, bytearray('\x02\x01\x02') + bytearray((len(_name) + 1, 0x09)) + _name) def ble_irq(event, data): global ble_msg if event == 1: print('Central connected') global pull_code_state if(pull_code_state!=[]): ret = {'cmd':'PullCode', 'ret':{'state':pull_code_state}} send(json.dumps(ret).encode('hex')) elif event == 2: print('Central disconnected') advertiser("esp-node") elif event == 3: buffer = _ble.gatts_read(_ble_rx) ble_msg += buffer.decode('hex').strip() ble_msg = '{"cmd":' + ble_msg.split('{"cmd":')[-1] # only save one cmd print(ble_msg) if(ble_msg.count('{') == ble_msg.count('}')): try: cmdd = json.loads(ble_msg) print(cmdd) if(cmdd['cmd'] == 'WiFiCon'): _wlan.active(True) if(_wlan.isconnected()): _wlan.disconnect() print(cmdd['param']['ssid'], cmdd['param']['pswd']) _wlan.connect(cmdd['param']['ssid'], cmdd['param']['pswd']) timeout = 5 if('timeout' in cmdd['param'].keys()): timeout = int(cmdd['param']['timeout']) while(True): status = _wlan.status() print(status) if(status == network.STAT_WRONG_PASSWORD): print('STAT_WRONG_PASSWORD') ret = {'cmd':'WiFiCon', 'ret':{'state':'STAT_WRONG_PASSWORD'}} send(json.dumps(ret).encode('hex')) break if(status == network.STAT_NO_AP_FOUND): print('STAT_NO_AP_FOUND') ret = {'cmd':'WiFiCon', 'ret':{'state':'STAT_NO_AP_FOUND'}} send(json.dumps(ret).encode('hex')) break if(status == network.STAT_GOT_IP): print('STAT_GOT_IP') ret = {'cmd':'WiFiCon', 'ret':{'state':'STAT_GOT_IP', 'ifconfig':_wlan.ifconfig()}} send(json.dumps(ret).encode('hex')) wificonf = {"ssid":cmdd['param']['ssid'],"pswd":cmdd['param']['pswd'],"autoConnect":True} with open('/WiFi.json', "w") as f: f.write(json.dumps(wificonf) + "\n") break if(status == 1001): print('scaning for ap ...') if(timeout < 0): print('STAT_CONNECT_TIMEOUT') ret = {'cmd':'WiFiCon', 'ret':{'state':'STAT_CONNECT_TIMEOUT'}} send(json.dumps(ret).encode('hex')) break time.sleep(1) timeout -= 1 if(cmdd['cmd'] == 'PullCode'): global pull_code_state if('main.py' in os.listdir('/data/pyamp')): os.remove('/data/pyamp/main.py') if(_wlan.isconnected() is False): print(_wlan.isconnected()) ret = {'cmd':'PullCode', 'ret':{'state':'NO_NETWORK'}} send(json.dumps(ret).encode('hex')) else: # _thread.start_new_thread(download_file_task, (cmdd['param']['filelist'], )) try: f = open('/afterlife.json', "w") f.write(json.dumps(cmdd) + "\n") f.close() except Exception as e: print(e) pass else: # see you afterlife ret = {'cmd':'PullCode', 'ret':{'state':'START_DOWNLOAD'}} send(json.dumps(ret).encode('hex')) if(cmdd['cmd'] == 'DeviceInfo'): with open('/DeviceInfo.json', "w") as f: f.write(cmdd['param'] + "\n") ret = {'cmd':'DeviceInfo', 'ret':{'state':'DeviceInfoRecved'}} send(json.dumps(ret).encode('hex')) if(cmdd['cmd'] == 'PullCodeCheck'): ret = {'cmd':'PullCode', 'ret':{'state':pull_code_state}} send(json.dumps(ret).encode('hex')) if(cmdd['cmd'] == 'Reset'): machine.reset() ble_msg = '' gc.collect() except Exception as e: pass if('WiFi.json' in os.listdir('/')): try: f = open('/WiFi.json', "r") wificonf = f.readline() wificonf = json.loads(wificonf) f.close() if('autoConnect' in wificonf.keys() and wificonf['autoConnect'] == True): print('autoConnect') _wlan.active(True) _wlan.connect(wificonf['ssid'], wificonf['pswd'],) if('main.py' in os.listdir('/data/pyamp')): os.remove('/WiFi.json') except Exception as e: print('try WiFi autoConnect, found') print(e) pass if('afterlife.json' in os.listdir('/')): try: f = open('/afterlife.json', "r") wish = f.readline() wish = json.loads(wish) f.close() print(wish) time.sleep(5) if(_wlan.isconnected() == False): pull_code_state = 'NO_NETWORK' print('NO_NETWORK') raise print('wifi connected') if('cmd' in wish.keys() and wish['cmd'] == 'PullCode'): download_file_task(wish['param']['filelist']) except Exception as e: raise (e) _ble.active(True) NUS_UUID = 0xFFA0 RX_UUID = 0xFFA2 TX_UUID = 0xFFA3 BLE_NUS = ubluetooth.UUID(NUS_UUID) BLE_RX = (ubluetooth.UUID(RX_UUID), ubluetooth.FLAG_WRITE) BLE_TX = (ubluetooth.UUID(TX_UUID), ubluetooth.FLAG_NOTIFY | ubluetooth.FLAG_READ) BLE_UART = (BLE_NUS, (BLE_TX, BLE_RX,)) SERVICES = [BLE_UART, ] _ble_tx = None _ble_rx = None ble_msg = '' ((_ble_tx, _ble_rx,), ) = _ble.gatts_register_services(SERVICES) _ble.irq(ble_irq) advertiser(_ble_adv_name) if('afterlife.json' in os.listdir('/')): os.remove('/afterlife.json') time.sleep(10)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/air_pressure_detection/esp32/code/oneMinuteOnCloud.py
Python
apache-2.0
11,221
# -*- encoding: utf-8 -*- ''' @File : Player.py @Time : 2021/12/08 20:32:10 @Author : zeta.zz @License : (C)Copyright 2015-2021, M5STACK @Desc : Player I2S driver. ''' from machine import I2S from machine import Pin from axp192 import Axp192 from micropython import const import io import math import struct import gc import urequests BCK_PIN = Pin(12) WS_PIN = Pin(0) SDOUT_PIN = Pin(2) PI = 3.141592653 I2S0 = const(0) F16B = const(16) F24B = const(24) F32B = const(32) class Player: def __init__(self): self.power = Axp192() self.power.powerAll() def open(self): pass def play(self, wav_file, rate=None, data_format=None, channel=None): """ Parameter: wav_file Return: False Not WAV format file """ if type(wav_file) is str: try: wav = open(wav_file, 'rb') except Exception as e: print('Audio file open caught exception: {} {}'.format( type(e).__name__, e)) return elif type(wav_file) is bytes: wav = io.BytesIO(len(wav_file)) wav.write(wav_file) wav.seek(0) else: return "Unknow file type" wav_head = wav.read(44) if wav_head[0:4] != b"RIFF" and wav_head[8:12] != b"WAVE": return "Wrong WAV format file" if rate and data_format and channel: channels = channel samplerate = rate dataformat = data_format else: channels = (wav_head[0x17] << 8) | (wav_head[0x16]) if channels == 1: channels = I2S.MONO elif channels == 2: channels = I2S.STEREO samplerate = (wav_head[0x1B] << 24) | (wav_head[0x1A] << 16) | ( wav_head[0x19] << 8) | (wav_head[0x18]) dataformat = (wav_head[0x23] << 8) | (wav_head[0x22]) audio_out = I2S( I2S0, sck=BCK_PIN, ws=WS_PIN, sd=SDOUT_PIN, mode=I2S.TX, bits=dataformat, format=channels, rate=samplerate, ibuf=3*1024) # advance to first byte of Data section in WAV file # wav.seek(44) # allocate sample arrays # memoryview used to reduce heap allocation in while loop wav_samples = bytearray(1024) wav_samples_mv = memoryview(wav_samples) # continuously read audio samples from the WAV file # and write them to an I2S DAC self.power.setSpkEnable(True) try: while True: # try: num_read = wav.readinto(wav_samples_mv) num_written = 0 if num_read == 0: # pos = wav.seek(44) # exit break else: while num_written < num_read: num_written += audio_out.write( wav_samples_mv[num_written:num_read]) except (KeyboardInterrupt, Exception) as e: print('Player caught exception: {} {}'.format(type(e).__name__, e)) self.power.setSpkEnable(False) raise finally: self.power.setSpkEnable(False) audio_out.deinit() wav.close() del wav del wav_samples_mv del wav_samples gc.collect() def playCloudWAV(self, url): """ Parameter: url: WAV format file URL Return: False None """ request = urequests.get(url) if (request.status_code) == 200: self.playWAV(request.content) else: return "Request WAV file fail" def playTone(self, freq, beta, rate=44100, data_format=F16B, channel=I2S.STEREO): """ Parameter: freq = frequency duration = time in secods Return: """ wave_data = io.BytesIO() freq_rate = (freq / rate) # Calculate a period of sine wave cycle = rate / freq for i in range(0, cycle): # 6.283185 = 2 * PI x = 6.283185 * freq_rate * i data = int(32767 * math.sin(x)) wave_data.write(bytes(struct.pack('h', data))) audio_out = I2S( I2S0, sck=BCK_PIN, ws=WS_PIN, sd=SDOUT_PIN, mode=I2S.TX, bits=data_format, format=channel, rate=rate, ibuf=3 * 1024) wave_data.seek(0) # One cycle sine wave data length length = (len(wave_data.read())) wave_data.seek(0) # Calculate how many cycles cycles = int((rate * beta) / cycle) wave_samples = bytearray(length) wave_samples_mv = memoryview(wave_samples) self.power.setSpkEnable(True) try: for i in range(0, cycles): num_read = wave_data.readinto(wave_samples_mv) num_written = 0 if num_read == 0: wave_data.seek(0) else: while num_written < num_read: num_written += audio_out.write( wave_samples_mv[num_written:num_read]) # print(num_written) except (KeyboardInterrupt, Exception) as e: print('Player caught exception: {} {}'.format(type(e).__name__, e)) self.power.setSpkEnable(False) raise finally: self.power.setSpkEnable(False) audio_out.deinit() wave_data.close() del wave_data del wave_samples_mv del wave_samples gc.collect()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/air_pressure_detection/esp32/code/pcm.py
Python
apache-2.0
5,864
from minicv import ML AI_ENGINE_ALIYUN = 1 AI_ENGINE_NATIVE = 2 class AI: def __init__(self, type=AI_ENGINE_NATIVE, accessKey=None, accessSecret=None, ossEndpoint=None, ossBucket=None): self.type = type self.ml = ML() if (self.type == AI_ENGINE_ALIYUN): self.ml.open(self.ml.ML_ENGINE_CLOUD) if not accessKey or not accessSecret: print('access key can not be null') return else: self.ml.config(accessKey, accessSecret, ossEndpoint, ossBucket) else: print('now only support cloud ai, not support nativate ai yet') print( "Please use example: ai = AI(AI.AI_ENGINE_CLOUD, 'Your-Access-Key', 'Your-Access-Secret')") # 人脸比对 def compareFace(self, imagePath, compareFacePath): self.ml.setInputData(imagePath, compareFacePath) self.ml.loadNet("FacebodyComparing") self.ml.predict() resp = self.ml.getPredictResponses(None) self.ml.unLoadNet() return resp # 人体检测 def detectPedestrian(self, imagePath): self.ml.setInputData(imagePath) self.ml.loadNet("DetectPedestrian") self.ml.predict() resp = self.ml.getPredictResponses(None) self.ml.unLoadNet() return resp # 水果检测 def detectFruits(self, imagePath): self.ml.setInputData(imagePath, None) self.ml.loadNet("DetectFruits") self.ml.predict() resp = self.ml.getPredictResponses(None) self.ml.unLoadNet() return resp # 车牌识别 def recognizeLicensePlate(self, imagePath): self.ml.setInputData(imagePath) self.ml.loadNet("RecognizeLicensePlate") self.ml.predict() resp = self.ml.getPredictResponses(None) self.ml.unLoadNet() return resp def __del__(self): try: self.ml.close() del self.type del self.ml except Exception: pass
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/air_pressure_detection/esp32/code/uai.py
Python
apache-2.0
2,051
from driver import ADC,GPIO from time import sleep_us class GP2Y10(object): def __init__(self, adcObj,gpioObj): self.adcObj = None self.gpioObj = None if not isinstance(adcObj, ADC): raise ValueError("parameter is not an ADC object") if not isinstance(gpioObj, GPIO): raise ValueError("parameter is not an GPIO object") self.adcObj = adcObj self.gpioObj = gpioObj self.gpioObj.write(1) def getDustVal(self): if self.adcObj is None: raise ValueError("invalid ADC object") self.gpioObj.write(0) sleep_us(280) value = self.adcObj.readVoltage() sleep_us(40) self.gpioObj.write(1) sleep_us(9680) return value
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/air_quality_monitor/esp32/code/gp2y10.py
Python
apache-2.0
773
# -*- coding: UTF-8 -*- from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import ujson # json字串解析库 import utime # 延时API所在组件 from driver import GPIO, ADC # driver类,用于控制微处理器的输入输出功能 import gp2y10 # dsm501a 空气质量传感器类 gp2y10Obj = 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() # 扫描接入点 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 device_init(): global gp2y10Obj gpioDev = GPIO() gpioDev.open("gp2y10led") adcDev = ADC() adcDev.open("gp2y10out") gp2y10Obj = gp2y10.GP2Y10(adcDev, gpioDev) print("gp2y10Obj inited!") def air_report(): global gp2y10Obj while True: # 无限循环 # 这里的数据仅表示从ADC上读到的数据,未实现到PM2.5的转换,仅作案例参考 dustValue = gp2y10Obj.getDustVal() print('dustValue = ', dustValue) # 生成上报到物联网平台的属性值字串,此处的属性标识符"pm25_value"必须和物联网平台的属性一致 upload_data = {'params': ujson.dumps({ 'pollen_value': 0, 'pm25_value': dustValue }) } # 上传状态到物联网平台 device.postProps(upload_data) utime.sleep(60) # 打印完之后休眠60秒 if __name__ == '__main__': wlan = network.WLAN(network.STA_IF) # 创建WLAN对象 get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) device_init() air_report()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/air_quality_monitor/esp32/code/main.py
Python
apache-2.0
3,959
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/alcohol_detector/haaseduk1/code/buzzer.py
Python
apache-2.0
757
# -*- encoding: utf-8 -*- from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import netmgr as nm # Wi-Fi 功能所在库 import utime # 延时API所在组件 import ujson # json字串解析库 from driver import GPIO # ADC类 from driver import SPI # ADC类 from driver import ADC # ADC类 from driver import PWM # PWM类 from mq3 import MQ3 # 酒精传感器类 from buzzer import BUZZER # 蜂鸣器类 import sh1106 # SH1106 OLED驱动库 import framebuf # framebuf基类,用于设置字体库 ALCOHOL_ALARM_VALUE = 800 adcObj= None pwmObj = None buzzerDev = None mq3Dev = None alarming = False # 物联网平台连接标志位 iot_connected = False wlan = None # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 三元组信息 productKey = "产品密钥" #需要填入物联网云平台申请到的productKey信息 deviceName = "设备名称" #需要填入物联网云平台申请到的deviceName信息 deviceSecret = "设备密钥" #需要填入物联网云平台申请到的deviceSecret信息 # 物联网设备实例 device = None def alcohol_init(): global adcObj, pwmObj, mq3Dev, buzzerDev, sn74hc595Dev global rclk, sclk, dio # 初始化酒精传感器 MQ3 adcObj = ADC() adcObj.open("mq3") mq3Dev = MQ3(adcObj) # 初始化蜂鸣器 pwmObj = PWM() pwmObj.open("buzzer") pwm_init_data = {'freq':2000, 'duty': 0} buzzerDev = BUZZER(pwmObj) def get_alcohol_value(): global mq3Dev vol = mq3Dev.getVoltage() return int(vol) # 等待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 # OLED初始化 def oledInit(): global oled # 字库文件存放于项目目录 font, 注意若用到了中英文字库则都需要放置 framebuf.set_font_path(framebuf.FONT_ASC12_8, '/data/font/ASC12_8') framebuf.set_font_path(framebuf.FONT_ASC16_8, '/data/font/ASC16_8') framebuf.set_font_path(framebuf.FONT_ASC24_12, '/data/font/ASC24_12') framebuf.set_font_path(framebuf.FONT_ASC32_16, '/data/font/ASC32_16') oled_spi = SPI() oled_spi.open("oled_spi") oled_res = GPIO() oled_res.open("oled_res") oled_dc = GPIO() oled_dc.open("oled_dc") #oled像素132*64 oled = sh1106.SH1106_SPI(132, 64, oled_spi, oled_dc, oled_res) # OLED显示 # text:显示的文本 # x:水平坐标 y:垂直坐标 # color:颜色 # clear: True-清屏显示 False-不清屏显示 # sz:字体大小 def oledShowText(text, x, y, color, clear, sz): global oled if clear: oled.fill(0) # 清屏 oled.text(text, x, y, color, size = sz) oled.show() 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_alarm(enable): if enable: if not alarming: buzzerDev.pwmObj.open("buzzer") pwm_option_data = {'freq':2000, 'duty': 50} buzzerDev.start(pwm_option_data) else: #pwm_option_data = {'freq':2000, 'duty': 0} #print("stop alarm:", pwm_option_data) #buzzerDev.close(pwm_option_data) buzzerDev.pwmObj.close() # 上传酒精浓度信息到物联网平台 def upload_alcohol_detector_state(): global device, alarming while True: data = get_alcohol_value() print('alcohol adc voltage:%d mv.' % data) if data < 0: print("Error: invalid alcohol adc voltage:", data) continue temp_str = "Alcohol:" temp_data_str = "%d" % data oledShowText(temp_str, 3, 1, 1, True, 16) oledShowText(temp_data_str, 40, 20, 1, False, 32) if (data > ALCOHOL_ALARM_VALUE): print("Info: alcohol detected, start alarm...") buzzer_alarm(True) alarming = True # "alcohol_adc_voltage" - 在云平台上创建产品时对应的酒精浓度属性的标识符 upload_data = {'params': ujson.dumps({ 'alcohol_adc_voltage': data, })} device.postProps(upload_data) utime.sleep(3) if alarming: print("Info: stop alarm...") buzzer_alarm(False) alarming = False utime.sleep(2) def alcohol_exit(): adcObj.close() pwmObj.close() oled.spi.close() oled.res.close() oled.dc.close() if __name__ == '__main__': # 如果想让酒精传感器有比较高的灵敏度,建议运行此模块前,先把酒精传感器上电预热24小时以上。 alcohol_init() oledInit() get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_alcohol_detector_state() alcohol_exit()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/alcohol_detector/haaseduk1/code/main.py
Python
apache-2.0
6,744
""" Copyright (C) 2015-2021 Alibaba Group Holding Limited MicroPython's driver for MQ3 Author: HaaS Date: 2022/03/15 """ from driver import ADC from utime import sleep_ms from micropython import const import math class MQ3(object): """ This class implements mq3 chip's defs. """ def __init__(self, adcObj): self._adcObj = None if not isinstance(adcObj, ADC): raise ValueError("parameter is not an adcObj 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/alcohol_detector/haaseduk1/code/mq3.py
Python
apache-2.0
682
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/alcohol_detector/haaseduk1/code/sh1106.py
Python
apache-2.0
7,916
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : main.py @Author : 杭漂 @version : 1.0 @Description: 通过跟HaaS Cloud控制台中“升级服务-应用升级”配合,实现设备端python应用的升级。 HaaS Cloud控制台网址:https://haas.iot.aliyun.com/welcome ''' import network # 网络库 import utime # 延时函数在utime库中 import time # 获取时间搓 import sntp # 网络时间同步库 import ujson as json import kv import machine from upgrade import * # Wi-Fi SSID和Password设置 SSID="Your-AP-SSID" PWD="Your-AP-Password" #三元组信息 ProductKey = "Your-ProductKey" DeviceName = "Your-DeviceName" DeviceSecret = "Your-DeviceSecret" key_info = { 'region' : 'cn-shanghai' , 'productKey': ProductKey , 'deviceName': DeviceName , 'deviceSecret': DeviceSecret , 'keepaliveSec': 60 } app_info = { 'appId':'', 'localAppVersion':'', 'appNewVersion':'', 'mac':'10:10:10:10:10:10', 'ip':'10.10.10.10' } def connect_wifi(ssid, pwd): global g_wifi_connected while True: try : # 初始化网络 wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(ssid, pwd) while True: print('Wi-Fi is connecting...') # 网络连接成功后,更新显示字符 if (wlan.isconnected() == True): g_wifi_connected = True print('Wi-Fi is connected') ip = wlan.ifconfig()[0] print('IP: %s' %ip) # NTP时间更新,如果更新不成功,将不能进行识别 print('NTP start') sntp.setTime() print('NTP done') return utime.sleep_ms(500) except(OSError): print("OSError except") except: print("unknow except") utime.sleep(3) def query_upgrade_result_cb(data): global engine print("upgrade_result_cb needUpgrade") #设备升级标志位和所需数据 kv.set('_amp_app_upgrade','enable') kv.set('_amp_wifi_ssid',SSID) kv.set('_amp_wifi_passwd',PWD) kv.set('_amp_pyapp_url',data['url']) #通知云端获取 app_info['localAppVersion'] = data['localAppVersion'] app_info['appNewVersion'] = data['version'] app_info['appId'] = data['appId'] engine.__pub_upgrade_result_event(app_info,200) #立刻重启设备更新应用 resetTime = 3 while True: print("Reset Device to upgarde app:",resetTime) time.sleep(2) resetTime = resetTime - 1 if resetTime == 0: print("您也可以使用手动按复位按钮,重启设备。") machine.reset() def get_app_info(): try: file_name = r'/data/pyamp/manifest.json' # 以只读方式打开文件 f = open(file_name) # 一次读取整个文件 content = f.read() print(content) app_dict = json.loads(content) app_info['localAppVersion'] = app_dict['version'] app_info['appId'] = app_dict['appid'] finally: f.close() def main() : # 全局变量 global engine,g_wifi_connected #清空升级标志位 kv.set('_amp_app_upgrade','disable') g_wifi_connected = False # 读取本地配置 get_app_info() # 连接网络 connect_wifi(SSID, PWD) while True: if g_wifi_connected == True: break utime.sleep_ms(50) # 链接阿里云物联网平台 engine = Upgrade(key_info,app_info,query_upgrade_result_cb) #发布应用查询请求 while True: utime.sleep_ms(50) if __name__ == '__main__': print("Python App Upgrade Program") main()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/app_upgrade/esp32/code/main.py
Python
apache-2.0
3,883
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : main.py @Author : 杭漂 @version : 1.0 @Description: 通过跟HaaS Cloud控制台中“升级服务-应用升级”配合,实现设备端python应用的升级,该文件为针对本案例测试应用升级使用。 ''' import utime import ujson as json # manifest.json文件注意事项: # 1、该文件内不要添加任何注释; # 2、关键字appName对应的值,只能使用英文字母、数字,长度不能超过16个字符,在HaaS Cloud平台全局范围内唯一; # 3、关键字appid对应的值,必须为16位的数字,且开头为88001000xxxxpppp,该appid在HaaS Cloud平台全局范围内唯一; # 4、关键字verison对应的值,只能使用数字和'.',必须是3段式,例如0.0.1,在相同appName下唯一; # 下面提到的$appName、$appid、$verison值必须跟升级包中manifest.json中一致。 # cd /${YourProjectPath}/src/code/testUpgrade/ # tar cvzf $appName-$appid-$verison.tar.gz * # Python升级包标准名字举例:python001-8800100099991000-0.0.9.tar.gz app_info = { 'appId':'', 'localAppVersion':'', 'appNewVersion':'', 'mac':'10:10:10:10:10:10', 'ip':'10.10.10.10' } def get_app_info(): try: file_name = r'/data/pyamp/manifest.json' # 以只读方式打开文件 f = open(file_name) # 一次读取整个文件 content = f.read() print(content) app_dict = json.loads(content) app_info['localAppVersion'] = app_dict['version'] app_info['appId'] = app_dict['appid'] finally: f.close() if __name__ == '__main__': get_app_info() while True: print("new version upgrade success.") utime.sleep(3)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/app_upgrade/esp32/code/testUpgrade/main.py
Python
apache-2.0
1,784
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : upgrade.py @Description: python应用升级能力实现 @Author : 杭漂 @version : 1.0 ''' from aliyunIoT import Device import ujson as json class Upgrade : def compareVersion(self,oldVersion,newVersion): old_list = oldVersion.split('.') new_list = newVersion.split('.') if (len(new_list) == 3) and (len(old_list) ==3) : if int(new_list[0]) > int(old_list[0]): return 1 elif (int(new_list[0]) == int(old_list[0])) and (int(new_list[1]) > int(old_list[1])): return 1 elif (int(new_list[0]) == int(old_list[0])) and (int(new_list[1]) == int(old_list[1])) and (int(new_list[2]) > int(old_list[2])): return 1 else: return 0 else: print("oldVersion(%s) or newVersion(%s) format mismatch,must x.x.x" % (oldVersion,newVersion)) return 0 def __cb_lk_service(self, data): print('service payload data ---->\n' + str(data)) if data != None: params = data['params'] if (data['service_id'].find("hli_service_upgrade_push") != -1): params_dict = json.loads(params) if params_dict['errorCode'] == '200': app_list = params_dict['app'] i = 0 while (i < len(app_list)) : appId = app_list[i]['appId'] if(appId == self.__app_info['appId']): version = app_list[i]['version'] if app_list[i]['rollingBack'] == 0 : url = app_list[i]['url'] version = app_list[i]['version'] needUpgrade = self.compareVersion(self.__app_info['localAppVersion'],version) if needUpgrade == 1: print("local version[%s] low,upgrade to [%s]." % (self.__app_info['localAppVersion'],version)) data_info = {'appId':appId,'url':url,'version':version,'localAppVersion':self.__app_info['localAppVersion']} self.__cb(data_info) i += 1 else : print("receive upgrade notice failed[%s]." % (params['errorCode'])) def __pub_query_upgrade_event(self,app_info) : self.__app_info = app_info appInfo1 = {'appId':app_info['appId'],'version':app_info['localAppVersion']} allParams = {'id': 1, 'version': '1.0', 'params': { 'mac':app_info['mac'], 'ip': app_info['ip'],'userScenario':'online', 'vendorId': 'HaaSPython','buildType':'eng','isSecurityOn':0 ,'firmwareVersion':'0.0.1','app':[appInfo1]}} all_params_str = json.dumps(allParams) query_upgrade_topic = '/sys/' + self.__dev_info['productKey'] + '/' + self.__dev_info['deviceName'] + '/thing/event/hli_event_upgrade_query/post' topic_info = { 'topic': query_upgrade_topic, 'qos': 1, 'payload': all_params_str } self.device.publish(topic_info) print('Topic发布成功:%s' % (query_upgrade_topic)) def __pub_upgrade_result_event(self,app_info,argInt) : self.__app_info = app_info ext = {'appId':app_info['appId'],'appNewVersion':app_info['appNewVersion'],'appOldVersion':app_info['localAppVersion']} ext_str = json.dumps(ext) # argInt,200:成功。404:包下载失败。405:包安装失败 allParams = {'id': 1, 'version': '1.0', 'params': \ { 'eventType':'haas.upgrade', 'eventName': 'app.result','argInt':argInt, 'ext': ext_str}} all_params_str = json.dumps(allParams) query_upgrade_topic = '/sys/' + self.__dev_info['productKey'] + '/' + self.__dev_info['deviceName'] + '/thing/event/hli_event/post' topic_info = { 'topic': query_upgrade_topic, 'qos': 1, 'payload': all_params_str } self.device.publish(topic_info) print('Topic发布成功:%s' % (query_upgrade_topic)) def __sub_upgrade_push_service(self) : upgrade_topic = '/sys/' + self.__dev_info['productKey'] + '/' + self.__dev_info['deviceName'] + '/thing/service/hli_service_upgrade_push' sub_topic = { 'topic': upgrade_topic, 'qos': 1 } ret = self.device.subscribe(sub_topic) if ret == 0 : print("subscribed topic success: %s" % (upgrade_topic)) else : print("subscribed topic failed: %s" % (upgrade_topic)) 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,app_info,callback) : self.__dev_info = dev_info self.__app_info = app_info self.__cb = callback self.g_lk_connect = False self.__connect_iot() #订阅应用升级服务 self.__sub_upgrade_push_service()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/app_upgrade/esp32/code/upgrade.py
Python
apache-2.0
5,433
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : irdistance.py @Description: 红外传感器驱动 @Author : 风裁 @version : 1.0 ''' from driver import GPIO class IRDISTANCE(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 objectDetection(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/auto_control_door/esp32/code/irdistance.py
Python
apache-2.0
597
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : main.py @Author : zhangheng @version : 1.0 @Description: 通过红外检测是否有人靠近,有人靠近则启动舵机执行开门操作,没人,则进行关门操作 board.json - 硬件资源配置文件,详情请参考:https://haas.iot.aliyun.com/haasapi/index.html#/Python/docs/zh-CN/haas_extended_api/driver/driver ''' from aliyunIoT import Device from driver import GPIO from driver import PWM import servo import irdistance import utime # 延时函数在utime库中 import sntp # 网络时间同步库 import network # 网络库 import _thread # 线程库 import ujson as json # Wi-Fi SSID和Password设置 SSID='xxx' PWD='xxx' # HaaS设备三元组 productKey = "xxx" deviceName = "xxx" deviceSecret = "xxx" g_lk_connect = False g_lk_service = False key_info = { 'region' : 'cn-shanghai' , 'productKey': productKey , 'deviceName': deviceName , 'deviceSecret': deviceSecret , 'keepaliveSec': 60 } def connect_wifi(ssid, pwd): # 引用全局变量 # 初始化网络 wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(ssid, pwd) while True: print('Wi-Fi is connecting...') # 网络连接成功后,更新显示字符 if (wlan.isconnected() == True): print('Wi-Fi is connected') ip = wlan.ifconfig()[0] print('IP: %s' %ip) # NTP时间更新,如果更新不成功,将不能进行识别 print('NTP start...') sntp.setTime() print('NTP done') break utime.sleep_ms(500) utime.sleep(2) def cb_lk_connect(data): global g_lk_connect print('link platform connected') g_lk_connect = True # 上报统计人数到云端 def postDeviceProps(): global dev,count value = {'total_person_count' : count} data = {'params': json.dumps(value)} ret = dev.postProps(data) if ret == 0 : print('累计人员数量上报成功') else : print('累计人员数量上报失败') # 接收云端下发的属性设置 # request格式: {"code": 0, "params_len": 17, "msg_id": 1828542828, "params": "{\"door_status\":0}"} def on_props(request): global door_status try: props = eval(request['params']) door_status = props['door_status'] print("door_status set value : " + str(door_status)) except Exception as e: print(e) def operatorDoorThread(): global detected,servoObj, closed,door_status closed = True # 开门后判断是否还有人 while True: if door_status == 1: openDoor() elif door_status == -1: closeDoor() else: if detected == True: openDoor() else: closeDoor() def openDoor(): global closed, servoObj if closed == True: print("open the door") servoObj.setOptionSero(90) # TODO 开门操作 closed = False def closeDoor(): global closed, servoObj if closed == False: utime.sleep_ms(200) print("close the door") # 操作关门 servoObj.setOptionSero(0) closed = True def objDetectThread(): global detected, count, door_status while True: # 无限循环 status = irDev.objectDetection() # 检测到物体 if status == 0: detected = True # 非常闭状态的才上报 if door_status != -1: count = count + 1 print("object detected, count = " + str(count)) postDeviceProps() # 检测到人后停5秒再检测,相当于模拟行人通过的时间 utime.sleep(5) # 没有检测到 elif status == 1: detected = False print('no object detected') # 没检测到人,则间隔500ms检测一次 utime.sleep_ms(500) def main(): global dev,irDev, servoObj, detected,count, door_status # 连接网络 connect_wifi(SSID, PWD) # 设备初始化 dev = Device() dev.on(Device.ON_CONNECT, cb_lk_connect) # 配置收到云端属性控制指令的回调函数 # 如果收到物联网平台发送的属性控制消息,则调用on_props函数 dev.on(Device.ON_PROPS, on_props) dev.connect(key_info) while True: if g_lk_connect: break detected = False count = 0 door_status = 0 print("init ir...") # 初始化红外 gpioDev = GPIO() gpioDev.open("ir") irDev = irdistance.IRDISTANCE(gpioDev) print("ir inited!") # 初始化舵机 print("init servo...") pwmObj = PWM() pwmObj.open("servo") print("buzzer inited!") servoObj = servo.SERVO(pwmObj) servoObj.setOptionSero(0) print("0") utime.sleep(2) try: # 启动红外检测 _thread.start_new_thread(objDetectThread, ()) # 启动舵机模拟开门/关门操作线程 _thread.start_new_thread(operatorDoorThread, ()) except Exception as e: print(e) 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/auto_control_door/esp32/code/main.py
Python
apache-2.0
5,356
""" HaaSPython PWM driver for servo 舵机传感器驱动 """ from driver import PWM class SERVO(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 setOptionSero(self,data): if self.pwmObj is None: raise ValueError("invalid PWM object") data_r = {'freq':50, 'duty': int(((data+90)*2/180+0.5)/20*100)} self.pwmObj.setOption(data_r) 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/auto_control_door/esp32/code/servo.py
Python
apache-2.0
664
# 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 _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') servo_data={} #当iot云端下发属性设置时,触发'props'事件 def on_props(request): global servo_data,door_status params=request['params'] params=eval(params) door_status=params["door_status"] servo_data["door_status"]= door_status servo_data_str=ujson.dumps(servo_data) data={ 'params':servo_data_str } device.postProps(data) #当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) count_data = {} def upload_count(): global count_data count_data["person_count"]= count count_data_str=ujson.dumps(count_data) data1={ 'params':count_data_str } device.postProps(data1) def setOptionSero(duty_cycle): global servo param2 = {'freq':50, 'duty': duty_cycle } servo.setOption(param2) def operatorDoor(): global detected, closed,door_status closed = True # 开门后判断是否还有人 while True: time.sleep_ms(50) if door_status == 1: openDoor() elif door_status == -1: closeDoor() else: if detected == True: openDoor() else: closeDoor() def openDoor(): global closed,servo if closed == True: print("open the door") setOptionSero(12) # TODO 开门操作 closed = False def closeDoor(): global closed,servo if closed == False: time.sleep_ms(200) print("close the door") # 操作关门 setOptionSero(5) closed = True def infrared_status(): global detected, count, door_status while True: # 无限循环 time.sleep_ms(50) status = infrared.read() # 检测到物体 if status == 0: detected = True # 非常闭状态的才上报 if door_status != -1: count = count + 1 print("object detected, count = " + str(count)) upload_count() # 检测到人后停5秒再检测,相当于模拟行人通过的时间 time.sleep(5) # 没有检测到 elif status == 1: detected = False print('no object detected') # 没检测到人,则间隔500ms检测一次 time.sleep_ms(500) 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) # 初始化红外 infrared = GPIO() print(infrared,'---------------------------') infrared.open("infrared") # 初始化舵机 servo = PWM() servo.open("pwm_lpg") #初始化数据 count = 0 detected = False door_status = 0 upload_count() time.sleep(2) try: # 启动红外检测 _thread.start_new_thread(infrared_status, ()) # 启动舵机模拟开门/关门操作线程 _thread.start_new_thread(operatorDoor, ()) except Exception as e: print(e) print("Error: unable to start thread") while True: time.sleep_ms(1000)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/auto_control_door/haas506/code/main.py
Python
apache-2.0
7,379
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.clkObj = clkObj self.dataObj = dataObj def getValue(self): if self.clkObj is None: raise ValueError("invalid GPIO object") if self.dataObj is None: raise ValueError("invalid GPIO object") count = 0 self.dataObj.write(1) self.clkObj.write(0) while(self.dataObj.read()): utime.sleep_ms(1) for i in range(24): self.clkObj.write(1) count = count<<1 self.clkObj.write(0) if(self.dataObj.read()): count += 1 self.clkObj.write(1) count ^= 0x800000 self.clkObj.write(0) return count
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/auto_feeder/haaseduk1/code/hx711.py
Python
apache-2.0
1,060
# -*- encoding: utf-8 -*- from driver import GPIO from driver import TIMER # 定时器类 from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import ujson # json字串解析库 import utime # 延时函数在utime库中 import hx711 # 引入hx711传感器驱动库 import uln2003 # 引入ULN2003步进电机驱动库 import netmgr as nm # 传感器对象 timerObj = None hx711Obj = None uln2003Obj = None # 设备实例 clkDev = None dataDev = None A = None A_ = None B = None B_ = None # 可供食用的宠物粮 available_food = 0.0 # 投喂次数 feeding_times = 0 # 三元组信息 productKey = "产品key" deviceName = "设备名称" deviceSecret ="设备密钥" # Wi-Fi SSID和Password设置 wifi_ssid = "请填写您的路由器名称" wifi_password = "请填写您的路由器密码" # 物联网平台连接标志位 iot_connected = False # 物联网设备实例 device = None # 设备初始化 def timer_init(): global timerObj timerObj = TIMER(0) timerObj.open(mode=timerObj.PERIODIC, period=20000, callback=timer_cb) timerObj.stop() def hx711_init(): global hx711Obj global clkDev, dataDev clkDev = GPIO() clkDev.open("hx711_clk") dataDev = GPIO() dataDev.open("hx711_data") hx711Obj = hx711.HX711(clkDev, dataDev) def uln2003_init(): global uln2003Obj global A, A_, B, B_ A = GPIO() A.open("uln2003_a") A_ = GPIO() A_.open("uln2003_a_") B = GPIO() B.open("uln2003_b") B_ = GPIO() B_.open("uln2003_b_") uln2003Obj = uln2003.ULN2003(A, A_, B, B_) # 关闭设备 def timer_deinit(): global timerObj timerObj.stop() timerObj.close() def hx711_deinit(): global clkDev, dataDev clkDev.close() dataDev.close() def uln2003_deinit(): global A, A_, B, B_ A.close() A_.close() B.close() B_.close() # 读取count次,除去最大最小值之后求平均作为一次测量结果 def hx711_read(count = 3): global hx711Obj # count必须>=3 cnt = 3 if (count <= 3) else count idx = 0 data = [0] * cnt while (idx < cnt): data[idx] = hx711Obj.getValue() idx += 1 data.sort() return round(sum(data[1:-1]) / (len(data) - 2)) # 步进电机控制 def uln2003_ctrl(cmd = 'stop', step = 0, speed = 4): global uln2003Obj step_tmp = step if (cmd is 'stop'): # 停止 uln2003Obj.motorStop() return while (step_tmp > 0): if (cmd is 'cw'): # 顺时针转动 uln2003Obj.motorCw(speed) elif (cmd is 'ccw'): # 逆时针转动 uln2003Obj.motorCcw(speed) step_tmp -= 1 # 定时器回调函数 def timer_cb(args): global feeding_times print("自动投喂一次...\n") # 驱动步进电机走512步,即电机转动一周 uln2003_ctrl('cw', 512, 4) feeding_times += 1 # 上传当前可供食用的宠物粮和累计投喂次数到物联网平台 def upload_msg(food, times): global device data = ujson.dumps({ 'available_food': food, 'feeding_times': times }) # 生成上报到物联网平台的属性值字串 # 此处的属性标识符"available_food"和"feeding_times"必须和物联网平台的属性一致 # "available_food" - 代表当前可供宠物食用的宠物粮 # "feeding_times" - 代表截止目前已投放的次数 uploadData = {'params': data} # 上传数据到物联网平台 device.postProps(uploadData) # 上传当前自动投喂开关状态到物联网平台 def upload_auto_feeding(feeding): global device data = ujson.dumps({ 'auto_feeding': feeding }) # "auto_feeding" - 自动投喂开关的状态: 1 -> open, 0 -> close uploadData = {'params': data} # 上传数据到物联网平台 device.postProps(uploadData) # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): nm.init() nm.disconnect() # 连接到指定的路由器(路由器名称为wifi_ssid, 密码为:wifi_password) nm.connect(wifi_ssid, wifi_password) while True : wifi_connected = nm.getStatus() # 获取Wi-Fi连接路由器的状态信息 if wifi_connected == 5: # nm.getStatus()返回5代表连线成功 break else: 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): global feeding_times # {'feeding_cmd': 1 or 0, 'clean_cmd': 1 or 0} payload = ujson.loads(request['params']) print("payload:%s"%payload) # 获取dict状态字段 注意要验证键存在 否则会抛出异常 if "feeding_cmd" in payload.keys(): feeding_cmd = payload["feeding_cmd"] if (feeding_cmd): print("手动投喂一次...\n") uln2003_ctrl('stop') uln2003_ctrl('cw', 512) feeding_times += 1 if "clean_cmd" in payload.keys(): clean_cmd = payload["clean_cmd"] if (clean_cmd): print("投喂计数清零\n") feeding_times = 0 if "auto_feeding" in payload.keys(): auto_feeding = payload["auto_feeding"] if (auto_feeding): timerObj.reload() timerObj.start() print("打开自动投喂\n") else: timerObj.stop() uln2003_ctrl('stop') print("关闭自动投喂\n") upload_auto_feeding(auto_feeding) # 连接物联网平台 def connect_lk(productKey, deviceName, deviceSecret): global device, iot_connected key_info = { 'region' : 'cn-shanghai' , #实例的区域 'productKey': productKey , #物联网平台的PK 'deviceName': deviceName , #物联网平台的DeviceName 'deviceSecret': 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) if __name__ == '__main__': get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_auto_feeding(0) timer_init() hx711_init() uln2003_init() # 计算hx711空载偏移量 hx711_offset = hx711_read(10) while True: hx711_data = hx711_read(5) if (hx711_data <= hx711_offset): available_food = 0.0 else: available_food = (hx711_data - hx711_offset) / 430.0 print("Amount of pet food delivered: %.1f g\n" %available_food) upload_msg(available_food, feeding_times) utime.sleep(2) timer_deinit() uln2003_deinit() hx711_deinit()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/auto_feeder/haaseduk1/code/main.py
Python
apache-2.0
7,663
""" 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/auto_feeder/haaseduk1/code/uln2003.py
Python
apache-2.0
2,207
import utime # 延时函数在utime库中 from driver import GPIO,I2C import sht3x from ssd1306 import SSD1306_I2C hum_s = 0 oled = None sht3xDev = None humi_gpio = None def sht3x_init(): global sht3xDev i2cDev = I2C() i2cDev.open("sht3x") sht3xDev = sht3x.SHT3X(i2cDev) def humi_ctrl_init(): global humi_gpio humi_gpio = GPIO() humi_gpio.open("hum_ctrl") def start_hum(): humi_gpio.write(0) def stop_hum(): humi_gpio.write(1) def oled_init(): global oled i2cObj = I2C() i2cObj.open("ssd1306") print("ssd1306 inited!") oled = SSD1306_I2C(128, 64, i2cObj) oled.fill(0) #清屏背景黑色 oled.text('welcome haas', 30, 5) oled.text('auto humi', 30, 22) oled.text(str('----------------------'),3,32) oled.text('', 30, 40) oled.show() def oled_data_show(status,humi,time_arr): global oled oled.fill(0) oled.text(str('%d-%02d-%02d'%(time_arr[0],time_arr[1],time_arr[2])),30,5) oled.text(str('%02d:%02d:%02d'%(time_arr[3],time_arr[4],time_arr[5])),30,22) oled.text(str('----------------------'),3,32) if status == 1: oled.text('open', 25, 40) oled.text(str('%02d'%(humi)+'%H'),75,40) elif status == 0: oled.text('close', 25, 40) oled.text(str('%02d'%(humi)+'%H'),75,40) oled.show() if __name__ == '__main__': sht3x_init() humi_ctrl_init() oled_init() while True: humidity = sht3xDev.getHumidity() if humidity <= 60.0: if hum_s == 0: hum_s = 1 print("start") start_hum() else : if hum_s == 1: hum_s = 0 print("stop") stop_hum() timeArray = utime.localtime() oled_data_show(hum_s,int(humidity),timeArray) utime.sleep(1)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/auto_humidifier/esp32/code/main.py
Python
apache-2.0
1,858
""" 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/auto_humidifier/esp32/code/sht3x.py
Python
apache-2.0
3,599
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/auto_humidifier/esp32/code/ssd1306.py
Python
apache-2.0
3,565
######### from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import ujson ################## import utime # 延时函数在utime库中 from driver import GPIO import relay,soil_moisture relayDev = None humiDev = None relayStatus = 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): global relayStatus payload = ujson.loads(request['params']) # print (payload) # 获取dict状态字段 注意要验证键存在 否则会抛出异常 if "onoff" in payload.keys(): value = payload["onff"] if value == 1: start_watering() relayStatus = 1 print("打开小水泵") report_event() elif value == 0: stop_watering() relayStatus = 0 print("关闭小水泵") report_event() else: print("无效参数") def report_event(): upload_data = {'params': ujson.dumps({'onoff': relayStatus})} # 上传开关状态到物联网平台 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 relay_init(): global relayDev gpioDev = GPIO() gpioDev.open("relay") relayDev = relay.Relay(gpioDev,1) def humi_init(): global humiDev gpioObj = GPIO() gpioObj.open("humidify") humiDev = soil_moisture.SoilMoisture(gpioObj) def start_watering(): relayDev.trigger() def stop_watering(): relayDev.untrigger() if __name__ == '__main__': curstatus = None laststatus = None relay_init() humi_init() ########## wlan = network.WLAN(network.STA_IF) #创建WLAN对象 get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) ########## while True: humidity = humiDev.moistureDetect() if humidity == 0: curstatus = 0 if curstatus != laststatus: stop_watering() relayStatus = 0 report_event() print("关闭小水泵") laststatus = curstatus elif humidity == 1: curstatus = 1 if curstatus != laststatus: start_watering() relayStatus = 1 report_event() print("打开小水泵") laststatus = curstatus utime.sleep(1)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/auto_watering/esp32/code/main.py
Python
apache-2.0
4,821
from driver import GPIO class Relay(): def __init__(self, gpioObj, trigger): self.gpioObj = None if not isinstance(gpioObj, GPIO): raise ValueError("parameter gpioObj is not a GPIO object") if (trigger != 0) and (trigger != 1): raise ValueError("parameter trigger should be 0 or 1") self.gpioObj = gpioObj self.trigger = trigger def trigger(self): if self.gpioObj is None: raise ValueError("invalid GPIO object") value = self.gpioObj.write(self.trigger) return value def untrigger(self): if self.gpioObj is None: raise ValueError("invalid GPIO object") value = self.gpioObj.write(1 - self.trigger) return value
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/auto_watering/esp32/code/relay.py
Python
apache-2.0
765
from driver import GPIO from driver import ADC class SoilMoisture(object): def __init__(self, DO, AO=None): self.DO = None self.AO = None if not isinstance(DO, GPIO): raise ValueError('parameter DO is not an GPIO object') if AO is not None and not isinstance(AO, ADC): raise ValueError('parameter AO should be ADC object or None') self.DO = DO self.AO = AO # 读取数字信号 def moistureDetect(self): return self.DO.read() # 读取模拟信号,电压 def getVoltage(self): if not self.AO: raise RuntimeError('Can not get voltage, AO is not inited') return self.AO.readVoltage()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/auto_watering/esp32/code/soil_moisture.py
Python
apache-2.0
715
#!/usr/bin/env python3 ''' @File : main.py @Description: 播报音箱 @Date : 2021年09月28日 @Author : ethan.lcz @version : 1.0.3 ''' from aliyunIoT import Device import network import http import ujson as json from speech_utils import ( Speaker, AUDIO_HEADER ) import time # 语音播放相关的音频资源文件定义 resDir = "/data/pyamp/resource/" tonepathConnected = AUDIO_HEADER + resDir + "connected.wav" tonepathPowerOn = AUDIO_HEADER + resDir + "poweron.wav" # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 回调函数状态 on_request = False on_play = False iot_connected = False # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): 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: time.sleep(0.5) print("wifi_connected:", wifi_connected) ifconfig = wlan.ifconfig() #获取接口的IP/netmask/gw/DNS地址 print(ifconfig) time.sleep(0.5) # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置service 事件接收函数(本案例是千里传音) def on_service(data): global on_request, on_play print('****** on service ********') serviceid = data['service_id'] data = json.loads(data['params']) # 语料下载服务 if serviceid == "SpeechPost": on_request = data # 语料播报服务 elif serviceid == "SpeechBroadcast": on_play = data else: pass # 连接物联网平台 def do_connect_lk(productKey, deviceName, deviceSecret,speaker): global device, iot_connected, on_request, on_play key_info = { 'region' : 'cn-shanghai' , #实例的区域 'productKey': productKey , #物联网平台的PK 'deviceName': deviceName , #物联网平台的DeviceName 'deviceSecret': deviceSecret , #物联网平台的deviceSecret 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 设定连接到物联网平台的回调函数,如果连接物联网平台下发控制服务请求指令,则调用on_service函数 device.on(Device.ON_SERVICE, on_service) print ("set on_connect and on_service callback, start connect") # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while True: if iot_connected: print("物联网平台连接成功") speaker.play(tonepathConnected) break else: print("sleep for 1 s") time.sleep(1) # 触发linkit sdk持续处理server端信息 while True: if on_request: print('get on request cmd') speaker.download_resource_file(on_request, resDir) on_request = False elif on_play: speaker.play_voice(on_play,resDir) on_play = False time.sleep(0.01) # 断开连接 device.close() if __name__ == '__main__': print("remote speaker demo version - 1.0.3") speaker = Speaker(resDir) # 初始化speaker speaker.play(tonepathPowerOn) # 播放开机启动提示音 get_wifi_status() # 确保wifi连接成功 do_connect_lk(productKey, deviceName, deviceSecret,speaker) # 启动千里传音服务
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/broadcast_speaker/esp32/code/main.py
Python
apache-2.0
4,523
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : speech_utils.py @Description: file description @Date : 2021/12/01 14:34:45 @Author : guoliang.wgl @version : 1.0 ''' import time import math import http import json import time import uos AUDIO_HEADER = '' from pcm import Player on_callback = False on_download = False cb_data = None class Speaker: tonenameSuffix = [".wav", ".mp3"] tonenameNumb = ["SYS_TONE_0", "SYS_TONE_1", "SYS_TONE_2", "SYS_TONE_3", "SYS_TONE_4", "SYS_TONE_5", "SYS_TONE_6", "SYS_TONE_7", "SYS_TONE_8", "SYS_TONE_9"] tonenameNumb1 = "SYS_TONE_yao" tonenameDot = "SYS_TONE_dian" tonenameUnit = ["SYS_TONE_MEASURE_WORD_ge", "SYS_TONE_MEASURE_WORD_shi", "SYS_TONE_MEASURE_WORD_bai", "SYS_TONE_MEASURE_WORD_qian"] tonenameHunit = ["SYS_TONE_MEASURE_WORD_wan", "SYS_TONE_MEASURE_WORD_yi", "SYS_TONE_MEASURE_WORD_sw", "SYS_TONE_MEASURE_WORD_bw", "SYS_TONE_MEASURE_WORD_qw"] def __init__(self,res_dir): self.toneDir = res_dir self._create_player() def _create_player(self): player = Player() player.open() self._player = player def play(self,path): self._player.play(path) def playlist(self,pathlist): for path in pathlist: self.play(AUDIO_HEADER + path) def play_voice(self,data,dir_info): format = data['format'] audioResFormat = 0 if (format == 'mp3'): audioResFormat = 1 speechs = data['speechs'] toneList = [] for speech in speechs: print(speech) # length = len(speech) if speech.endswith('}') and speech.startswith('{') and (speech[1] == '$'): speech_num = speech.strip('{').strip('$').strip('}') toneList = self.add_amount(speech_num,toneList,audioResFormat) else: toneList.append(self.toneDir + speech + self.tonenameSuffix[audioResFormat]) print(toneList) self.playlist(toneList) def add_amount(self,num_str, toneList, formatFlag): num_f = float(num_str) numb = int(num_f) deci = num_f - numb target = numb subTarget = 0 subNumber = None slot = 0 factor = 0 count = 0 prevSlotZero = False hundredMillionExist = False tenThousandExist = False if (numb < 0 or numb >= 1000000000000): print('amount overrange') return toneList if (deci < 0.0001 and deci > 0.0): deci = 0.0001 i = 2 while(i >= 0): factor = math.pow(10000,i) if target < factor: i = i -1 continue subTarget = int(target / factor) target %= factor if (subTarget == 0): i = i -1 continue if (i == 2): hundredMillionExist = True elif (i == 1): tenThousandExist = True subNumber = subTarget prevSlotZero = False depth = 3 while(depth >= 0): if(subNumber == 0): break factor = math.pow(10, depth) if ((hundredMillionExist == True or tenThousandExist == True) and i == 0): pass elif (hundredMillionExist == True and tenThousandExist == True and depth > 0 and subTarget < factor): pass elif (subTarget < factor): depth = depth - 1 continue slot = int(subNumber / factor) subNumber %= factor if (slot == 0 and depth == 0): depth = depth - 1 continue if ((subTarget < 20 and depth == 1) or (slot == 0 and prevSlotZero) or (slot == 0 and depth == 0)): pass else: toneList.append(self.toneDir + self.tonenameNumb[slot] + self.tonenameSuffix[formatFlag]) count += 1 if (slot == 0 and prevSlotZero == False): prevSlotZero = True elif (prevSlotZero == True and slot != 0): prevSlotZero = False if (slot > 0 and depth > 0) : toneList.append(self.toneDir + self.tonenameUnit[depth] + self.tonenameSuffix[formatFlag]) count += 1 depth = depth - 1 if (i > 0): toneList.append(self.toneDir + self.tonenameHunit[i - 1] + self.tonenameSuffix[formatFlag]) count += 1 i = i - 1 if (count == 0 and numb == 0): toneList.append(self.toneDir + self.tonenameNumb[0] + self.tonenameSuffix[formatFlag]) if (deci >= 0.0001) : toneList.append(self.toneDir + self.tonenameDot + self.tonenameSuffix[formatFlag]) deci ="{:.4f}".format(deci) deci_tmp = str(deci).strip().rstrip('0') deci_str = '' got_dot = False for j in range(len(deci_tmp)): if(got_dot): deci_str = deci_str + deci_tmp[j] elif deci_tmp[j] == '.': got_dot = True deciArray = deci_str for item in deciArray: if (item >= '0' and item <= '9'): print(self.tonenameNumb[int(item)]) toneList.append(self.toneDir + self.tonenameNumb[int(item)] + self.tonenameSuffix[formatFlag]) return toneList def download_resource_file(self,on_request,resDir): global on_callback,on_download,cb_data data = { 'url':on_request['url'], 'method': 'GET', 'headers': { }, 'timeout': 30000, 'params' : '' } def cb(data): global on_callback,cb_data on_callback = True cb_data = data http.request(data,cb) while True: if on_callback: on_callback = False break else: time.sleep(1) response = json.loads(cb_data['body']) audio = response['audios'][0] format = audio['format'] id = audio['id'] size = audio['size'] path = self.toneDir +id+'.'+format print('************ begin to download: ' + path) d_data = { 'url': audio['url'], 'filepath': path } def d_cb(data): global on_download on_download = True http.download(d_data,d_cb) while True: if on_download: on_download = False break else: time.sleep(1) print('download succeed :' + path)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/broadcast_speaker/esp32/code/speech_utils.py
Python
apache-2.0
6,971
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : main.py @Description: 播报音箱案例(本案例符合HaaS Python 2.0 API标准,请务必按照“HaaS EDU K1快速开始”(https://haas.iot.aliyun.com/haasapi/#/Python/docs/zh-CN/startup/HaaS_EDU_K1_startup)文章的说明烧录固件 @Date : 2022年02月11日 @Author : ethan.lcz @version : v2.0 ''' from aliyunIoT import Device import netmgr as nm import utime import ujson as json from speech_utils import ( Speaker, AUDIO_HEADER ) import time # 语音播放相关的音频资源文件定义 resDir = "/data/pyamp/resource/" tonepathConnected = AUDIO_HEADER + resDir + "connected.wav" tonepathPowerOn = AUDIO_HEADER + resDir + "poweron.wav" # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 回调函数状态 on_request = False on_play = False iot_connected = False # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): nm.init() wifi_connected = nm.getStatus() nm.disconnect() 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) # utime.sleep(5) print("Wi-Fi connected") print('DeviceIP:' + nm.getInfo()['ip']) # 打印Wi-Fi的IP地址信息 # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置service 事件接收函数(本案例是千里传音) def on_service(data): global on_request, on_play print('****** on service ********') serviceid = data['service_id'] data = json.loads(data['params']) # 语料下载服务 if serviceid == "SpeechPost": on_request = data # 语料播报服务 elif serviceid == "SpeechBroadcast": on_play = data else: pass # 连接物联网平台 def do_connect_lk(productKey, deviceName, deviceSecret,speaker): global device, iot_connected, on_request, on_play key_info = { 'region' : 'cn-shanghai' , #实例的区域 'productKey': productKey , #物联网平台的PK 'deviceName': deviceName , #物联网平台的DeviceName 'deviceSecret': deviceSecret , #物联网平台的deviceSecret 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 设定连接到物联网平台的回调函数,如果连接物联网平台下发控制服务请求指令,则调用on_service函数 device.on(Device.ON_SERVICE, on_service) print ("开始连接物联网平台") # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while True: if iot_connected: print("物联网平台连接成功") speaker.play(tonepathConnected) break else: print("sleep for 1 s") time.sleep(1) # 触发linkit sdk持续处理server端信息 while True: if on_request: print('get on request cmd') speaker.download_resource_file(on_request, resDir) # 语料下载 on_request = False elif on_play: speaker.play_voice(on_play,resDir) # 语料播报 on_play = False time.sleep(0.01) # 断开连接 device.close() if __name__ == '__main__': print("remote speaker demo version - v2.0") speaker = Speaker(resDir) # 初始化speaker speaker.play(tonepathPowerOn) # 播放开机启动提示音 get_wifi_status() # 确保wifi连接成功 do_connect_lk(productKey, deviceName, deviceSecret,speaker) # 启动千里传音服务
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/broadcast_speaker/haaseduk1/code/main.py
Python
apache-2.0
4,519
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : speech_utils.py @Description: 播报音箱库 @Date : 2022/02/11 14:34:45 @Author : guoliang.wgl @version : 1.0 ''' import time import math import http import json import time AUDIO_HEADER = 'fs:' from audio import Player, Snd on_callback = False on_download = False cb_data = None class Speaker: tonenameSuffix = [".wav", ".mp3"] tonenameNumb = ["SYS_TONE_0", "SYS_TONE_1", "SYS_TONE_2", "SYS_TONE_3", "SYS_TONE_4", "SYS_TONE_5", "SYS_TONE_6", "SYS_TONE_7", "SYS_TONE_8", "SYS_TONE_9"] tonenameNumb1 = "SYS_TONE_yao" tonenameDot = "SYS_TONE_dian" tonenameUnit = ["SYS_TONE_MEASURE_WORD_ge", "SYS_TONE_MEASURE_WORD_shi", "SYS_TONE_MEASURE_WORD_bai", "SYS_TONE_MEASURE_WORD_qian"] tonenameHunit = ["SYS_TONE_MEASURE_WORD_wan", "SYS_TONE_MEASURE_WORD_yi", "SYS_TONE_MEASURE_WORD_sw", "SYS_TONE_MEASURE_WORD_bw", "SYS_TONE_MEASURE_WORD_qw"] def __init__(self,res_dir): self.toneDir = res_dir self._create_player() def _create_player(self): Snd.init() player = Player() player.open() player.setVolume(8) self._player = player def play(self,path): self._player.play(path) self._player.waitComplete() def playlist(self,pathlist): for path in pathlist: self.play(AUDIO_HEADER + path) def play_voice(self,data,dir_info): format = data['format'] audioResFormat = 0 if (format == 'mp3'): audioResFormat = 1 speechs = data['speechs'] toneList = [] for speech in speechs: print(speech) # length = len(speech) if speech.endswith('}') and speech.startswith('{') and (speech[1] == '$'): speech_num = speech.strip('{').strip('$').strip('}') toneList = self.add_amount(speech_num,toneList,audioResFormat) else: toneList.append(self.toneDir + speech + self.tonenameSuffix[audioResFormat]) print(toneList) self.playlist(toneList) def add_amount(self,num_str, toneList, formatFlag): num_f = float(num_str) numb = int(num_f) deci = num_f - numb target = numb subTarget = 0 subNumber = None slot = 0 factor = 0 count = 0 prevSlotZero = False hundredMillionExist = False tenThousandExist = False if (numb < 0 or numb >= 1000000000000): print('amount overrange') return toneList if (deci < 0.0001 and deci > 0.0): deci = 0.0001 i = 2 while(i >= 0): factor = math.pow(10000,i) if target < factor: i = i -1 continue subTarget = int(target / factor) target %= factor if (subTarget == 0): i = i -1 continue if (i == 2): hundredMillionExist = True elif (i == 1): tenThousandExist = True subNumber = subTarget prevSlotZero = False depth = 3 while(depth >= 0): if(subNumber == 0): break factor = math.pow(10, depth) if ((hundredMillionExist == True or tenThousandExist == True) and i == 0): pass elif (hundredMillionExist == True and tenThousandExist == True and depth > 0 and subTarget < factor): pass elif (subTarget < factor): depth = depth - 1 continue slot = int(subNumber / factor) subNumber %= factor if (slot == 0 and depth == 0): depth = depth - 1 continue if ((subTarget < 20 and depth == 1) or (slot == 0 and prevSlotZero) or (slot == 0 and depth == 0)): pass else: toneList.append(self.toneDir + self.tonenameNumb[slot] + self.tonenameSuffix[formatFlag]) count += 1 if (slot == 0 and prevSlotZero == False): prevSlotZero = True elif (prevSlotZero == True and slot != 0): prevSlotZero = False if (slot > 0 and depth > 0) : toneList.append(self.toneDir + self.tonenameUnit[depth] + self.tonenameSuffix[formatFlag]) count += 1 depth = depth - 1 if (i > 0): toneList.append(self.toneDir + self.tonenameHunit[i - 1] + self.tonenameSuffix[formatFlag]) count += 1 i = i - 1 if (count == 0 and numb == 0): toneList.append(self.toneDir + self.tonenameNumb[0] + self.tonenameSuffix[formatFlag]) if (deci >= 0.0001) : toneList.append(self.toneDir + self.tonenameDot + self.tonenameSuffix[formatFlag]) deci ="{:.4f}".format(deci) deci_tmp = str(deci).strip().rstrip('0') deci_str = '' got_dot = False for j in range(len(deci_tmp)): if(got_dot): deci_str = deci_str + deci_tmp[j] elif deci_tmp[j] == '.': got_dot = True deciArray = deci_str for item in deciArray: if (item >= '0' and item <= '9'): print(self.tonenameNumb[int(item)]) toneList.append(self.toneDir + self.tonenameNumb[int(item)] + self.tonenameSuffix[formatFlag]) return toneList def download_resource_file(self,on_request,resDir): global on_callback,on_download,cb_data data = { 'url':on_request['url'], 'method': 'GET', 'headers': { }, 'timeout': 30000, 'params' : '' } def cb(data): global on_callback,cb_data on_callback = True cb_data = data http.request(data,cb) while True: if on_callback: on_callback = False break else: time.sleep(1) response = json.loads(cb_data['body']) audio = response['audios'][0] format = audio['format'] id = audio['id'] size = audio['size'] path = self.toneDir +id+'.'+format print('************ begin to download: ' + path) d_data = { 'url': audio['url'], 'filepath': path } def d_cb(data): global on_download on_download = True http.download(d_data,d_cb) while True: if on_download: on_download = False break else: time.sleep(1) print('download succeed :' + path)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/broadcast_speaker/haaseduk1/code/speech_utils.py
Python
apache-2.0
7,047
#!/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/bussiness_card_recognization/m5stack/code/cloudAI.py
Python
apache-2.0
10,770
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : main.py @Description: 名片识别案例 @Author : jiangyu @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 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, card_info detected = False if commandReply == 'recognizeBusinessCardReply' : if result != {} : card_info = result detected = True else : print('unknown command reply') # 识别线程函数 def recognizeThread(): global frame while True: if frame != None: engine.recognizeBussinessCard(frame) utime.sleep_ms(1000) else: utime.sleep_ms(1000) # 显示线程函数 def displayThread(): # 引用全局变量 global disp, frame, detected, card_info # 定义清屏局部变量 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_DejaVu24) # 显示识别结果 disp.text(10, 50, 'name: ' + card_info['name'], disp.RED) disp.text(10, 90, 'num:' + card_info['phoneNumbers'] , disp.RED) disp.text(10, 130, 'email:' + card_info['email'], 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/bussiness_card_recognization/m5stack/code/main.py
Python
apache-2.0
4,587
#!/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/classifying_rubbish/esp32/code/cloudAI.py
Python
apache-2.0
10,770
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : irdistance.py @Description: 红外传感器 @Author : 风裁 @version : 1.0 ''' from driver import GPIO class IRDISTANCE(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 objectDetection(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/classifying_rubbish/esp32/code/irdistance.py
Python
apache-2.0
591
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : main.py @Description: 垃圾分类识别案例 @Author : 杭漂 @version : 1.0 ''' from aliyunIoT import Device import display # 显示库 import network # 网络库 import ucamera # 摄像头库 import utime # 延时函数在utime库中 import sntp # 网络时间同步库 import _thread # 线程库 from cloudAI import * import irdistance from driver import GPIO # Wi-Fi SSID和Password设置 SSID='Your-AP-SSID' PWD='Your-AP-Password' # HaaS设备三元组 productKey = "Your-ProductKey" deviceName = "Your-devicename" deviceSecret = "Your-deviceSecret" detected = False gStartRecognize = False gName = '' 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, gName, gStartRecognize detected = False gName = 'NA' if commandReply == 'classifyingRubbishReply' : if result != 'NA' : gName = result detected = True else : print('unknown command reply') # 识别结束,复位识别标识符 gStartRecognize = False print('识别结束') # 红外检测线程 def infraRed_thread(): global gStartRecognize, gIrDev print('启动红外检测线程') while True: if gStartRecognize == False : status = gIrDev.objectDetection() if status == 0: gStartRecognize = True print('有物体进入') utime.sleep_ms(50) # 识别线程函数 def recognizeThread(): global gFrame while True: if gFrame != None and gStartRecognize == True: engine.classifyRubbish(gFrame) utime.sleep_ms(1000) else: utime.sleep_ms(1000) # 显示线程函数 def displayThread(): # 引用全局变量 global disp, gFrame, detected, gName # 定义清屏局部变量 clearFlag = False # 定义显示文本局部变量 textShowFlag = False while True: # 采集摄像头画面 # print('start to capture') gFrame = ucamera.capture() # print('end to capture') if gFrame != None: if detected == True: # 清除屏幕内容 disp.clear() # 设置文字字体 disp.font(disp.FONT_DejaVu40) # 显示识别结果 disp.text(20, 60, gName, disp.RED) disp.text(20, 100, 'Deteted!', disp.RED) utime.sleep_ms(1000) textShowFlag = False detected = False else: # 显示图像 # print('start to display') disp.image(0, 20, gFrame, 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, gFrame, detected, engine, gStartRecognize, gIrDev # 创建lcd display对象 disp = display.TFT() gFrame = None detected = False gStartRecognize = 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) # 初始化红外传感器 gpioDev = GPIO() gpioDev.open("ir") gIrDev = irdistance.IRDISTANCE(gpioDev) print("IR detector ...") try: # 启动显示线程 _thread.start_new_thread(displayThread, ()) # 启动红外检测线程 _thread.start_new_thread(infraRed_thread, ()) # 设置比对线程stack _thread.stack_size(16 * 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/classifying_rubbish/esp32/code/main.py
Python
apache-2.0
5,360
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- from aliyunIoT import Device from driver import I2C import utime # 延时函数在utime库中 from tcs34725 import * from driver import PWM import servo import utime # 延时函数在utime库中 import sntp # 网络时间同步库 import network # 网络库 import _thread # 线程库 import ujson as json # Wi-Fi SSID和Password设置 SSID='Your-AP-SSID' PWD='Your-AP-Password' # HaaS设备三元组 productKey = "Your-ProductKey" deviceName = "Your-devicename" deviceSecret = "Your-deviceSecret" g_lk_connect = False g_lk_service = False red_cnt = 0 orange_cnt = 0 yellow_cnt = 0 blue_cnt = 0 green_cnt = 0 other_cnt = 0 key_info = { 'region' : 'cn-shanghai' , 'productKey': productKey , 'deviceName': deviceName , 'deviceSecret': deviceSecret , 'keepaliveSec': 60 } def connect_wifi(ssid, pwd): # 初始化网络 wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(ssid, pwd) while True: print('Wi-Fi is connecting...') # 网络连接成功后,更新显示字符 if (wlan.isconnected() == True): print('Wi-Fi is connected') ip = wlan.ifconfig()[0] print('IP: %s' %ip) # NTP时间更新,如果更新不成功,将不能进行识别 print('NTP start...') sntp.setTime() print('NTP done') break utime.sleep_ms(500) utime.sleep(2) def cb_lk_connect(data): global g_lk_connect print('link platform connected') g_lk_connect = True # 上报统计人数到云端 def postDeviceProps(): global dev, red_cnt, orange_cnt, yellow_cnt, blue_cnt, green_cnt, other_cnt, Sorter_switch value = {'Sorter_switch' : Sorter_switch, 'Red_cnt': red_cnt, 'Orange_cnt': orange_cnt, 'Yellow_cnt': yellow_cnt, 'Blue_cnt': blue_cnt, 'Green_cnt':green_cnt, 'Other_cnt': other_cnt} data = {'params': json.dumps(value)} ret = dev.postProps(data) print('upload props-->' + str(data)) if ret == 0 : print('颜色识别结果上报成功') else : print('颜色识别结果上报失败') # 接收云端下发的属性设置 def on_props(request): global Sorter_switch try: props = eval(request['params']) Sorter_switch = props['Sorter_switch'] print("sorter_switch convert to : " + str(Sorter_switch)) except Exception as e: print(e) if __name__ == '__main__': global Sorter_switch, dev Sorter_switch = 0 # 连接网络 connect_wifi(SSID, PWD) # 设备初始化 dev = Device() dev.on(Device.ON_CONNECT, cb_lk_connect) # 配置收到云端属性控制指令的回调函数 # 如果收到物联网平台发送的属性控制消息,则调用on_props函数 dev.on(Device.ON_PROPS, on_props) dev.connect(key_info) while True: if g_lk_connect: break i2cObj = I2C() # 创建I2C设备对象 i2cObj.open('colorSensor') # 打开名为colorSensor的I2C设备节点 colorSensor = TCS34725(i2cObj) # 创建颜色传感器对象 print('colorSensor init done') # 初始化上层舵机 print("init top servo...") top_pwmObj = PWM() top_pwmObj.open("top_servo") top_servoObj = servo.SERVO(top_pwmObj) top_servoObj.setOptionSero(0) utime.sleep(1) print("top_servo inited") # 初始化下层舵机 print("init bottom servo...") bottom_pwmObj = PWM() bottom_pwmObj.open("bottom_servo") bottom_servoObj = servo.SERVO(bottom_pwmObj) bottom_servoObj.setOptionSero(0) utime.sleep(1) print("bottom_servo inited") while True: if Sorter_switch: top_servoObj.setOptionSero(-63) utime.sleep(2) top_servoObj.setOptionSero(-10) utime.sleep(2) r, g, b = colorSensor.getRGB() # 读取RGB测量结果 print('r:%d, g:%d, b:%d' % (r, g, b)) if r > 240 and r < 255 and g > 90 and g < 130 and b > 75 and b < 110:#red bottom_servoObj.setOptionSero(-50) red_cnt += 1 print('detect red, cnt:', str(red_cnt)) elif r > 240 and r < 255 and g > 205 and g < 245 and b > 105 and b < 145:#orange bottom_servoObj.setOptionSero(-30) orange_cnt += 1 print('detect orange, cnt:', str(orange_cnt)) elif r > 240 and r < 255 and g > 240 and g < 254 and b > 240 and b < 255:#yellow bottom_servoObj.setOptionSero(-10) yellow_cnt += 1 print('detect yellow, cnt:', str(yellow_cnt)) elif r > 240 and r < 255 and g > 250 and g < 255 and b > 180 and b < 220:#green bottom_servoObj.setOptionSero(10) green_cnt += 1 print('detect green, cnt:', str(green_cnt)) elif r > 125 and r < 170 and g > 230 and g < 255 and b > 220 and b < 255:#blue bottom_servoObj.setOptionSero(30) blue_cnt += 1 print('detect blue, cnt:', str(blue_cnt)) else: bottom_servoObj.setOptionSero(50) other_cnt += 1 print('detect others, cnt:', str(other_cnt)) utime.sleep(1) top_servoObj.setOptionSero(30) utime.sleep(2) postDeviceProps() else: utime.sleep(2)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/color_sorter/esp32/code/main.py
Python
apache-2.0
5,590
""" HaaSPython PWM driver for servo """ from driver import PWM class SERVO(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 setOptionSero(self,data): if self.pwmObj is None: raise ValueError("invalid PWM object") data_r = {'freq':50, 'duty': int(((data+90)*2/180+0.5)/20*100)} self.pwmObj.setOption(data_r) 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/color_sorter/esp32/code/servo.py
Python
apache-2.0
642
""" Copyright (C) 2015-2021 Alibaba Group Holding Limited `HaaS Python tcs34725` ==================================================== A driver for tcs34725 Color Sensor * Author(s): HaaS Group Implementation Notes -------------------- **Hardware:** * HaaS Python tcs34725: https://haas.iot.aliyun.com/solution/detail/hardware **Software and Dependencies:** * HaaS Python API documents: https://haas.iot.aliyun.com/haasapi/index.html#/ * HaaS Python Driver Libraries: https://github.com/alibaba/AliOS-Things/tree/master/haas_lib_bundles/python/libraries """ # The MIT License (MIT) # # Copyright (c) 2016 Adafruit Industries # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import time from driver import I2C TCS34725_ADDRESS = 0x29 TCS34725_ID = 0x12 # 0x44 = TCS34721/TCS34725, 0x4D = TCS34723/TCS34727 TCS34725_COMMAND_BIT = 0x80 TCS34725_ENABLE = 0x00 TCS34725_ENABLE_AIEN = 0x10 # RGBC Interrupt Enable TCS34725_ENABLE_WEN = 0x08 # Wait enable - Writing 1 activates the wait timer TCS34725_ENABLE_AEN = 0x02 # RGBC Enable - Writing 1 actives the ADC, 0 disables it TCS34725_ENABLE_PON = 0x01 # Power on - Writing 1 activates the internal oscillator, 0 disables it TCS34725_ATIME = 0x01 # Integration time TCS34725_WTIME = 0x03 # Wait time (if TCS34725_ENABLE_WEN is asserted) TCS34725_WTIME_2_4MS = 0xFF # WLONG0 = 2.4ms WLONG1 = 0.029s TCS34725_WTIME_204MS = 0xAB # WLONG0 = 204ms WLONG1 = 2.45s TCS34725_WTIME_614MS = 0x00 # WLONG0 = 614ms WLONG1 = 7.4s TCS34725_AILTL = 0x04 # Clear channel lower interrupt threshold TCS34725_AILTH = 0x05 TCS34725_AIHTL = 0x06 # Clear channel upper interrupt threshold TCS34725_AIHTH = 0x07 TCS34725_PERS = 0x0C # Persistence register - basic SW filtering mechanism for interrupts TCS34725_PERS_NONE = 0b0000 # Every RGBC cycle generates an interrupt TCS34725_PERS_1_CYCLE = 0b0001 # 1 clean channel value outside threshold range generates an interrupt TCS34725_PERS_2_CYCLE = 0b0010 # 2 clean channel values outside threshold range generates an interrupt TCS34725_PERS_3_CYCLE = 0b0011 # 3 clean channel values outside threshold range generates an interrupt TCS34725_PERS_5_CYCLE = 0b0100 # 5 clean channel values outside threshold range generates an interrupt TCS34725_PERS_10_CYCLE = 0b0101 # 10 clean channel values outside threshold range generates an interrupt TCS34725_PERS_15_CYCLE = 0b0110 # 15 clean channel values outside threshold range generates an interrupt TCS34725_PERS_20_CYCLE = 0b0111 # 20 clean channel values outside threshold range generates an interrupt TCS34725_PERS_25_CYCLE = 0b1000 # 25 clean channel values outside threshold range generates an interrupt TCS34725_PERS_30_CYCLE = 0b1001 # 30 clean channel values outside threshold range generates an interrupt TCS34725_PERS_35_CYCLE = 0b1010 # 35 clean channel values outside threshold range generates an interrupt TCS34725_PERS_40_CYCLE = 0b1011 # 40 clean channel values outside threshold range generates an interrupt TCS34725_PERS_45_CYCLE = 0b1100 # 45 clean channel values outside threshold range generates an interrupt TCS34725_PERS_50_CYCLE = 0b1101 # 50 clean channel values outside threshold range generates an interrupt TCS34725_PERS_55_CYCLE = 0b1110 # 55 clean channel values outside threshold range generates an interrupt TCS34725_PERS_60_CYCLE = 0b1111 # 60 clean channel values outside threshold range generates an interrupt TCS34725_CONFIG = 0x0D TCS34725_CONFIG_WLONG = 0x02 # Choose between short and long (12x) wait times via TCS34725_WTIME TCS34725_CONTROL = 0x0F # Set the gain level for the sensor TCS34725_ID = 0x12 # 0x44 = TCS34721/TCS34725, 0x4D = TCS34723/TCS34727 TCS34725_STATUS = 0x13 TCS34725_STATUS_AINT = 0x10 # RGBC Clean channel interrupt TCS34725_STATUS_AVALID = 0x01 # Indicates that the RGBC channels have completed an integration cycle TCS34725_CDATAL = 0x14 # Clear channel data TCS34725_CDATAH = 0x15 TCS34725_RDATAL = 0x16 # Red channel data TCS34725_RDATAH = 0x17 TCS34725_GDATAL = 0x18 # Green channel data TCS34725_GDATAH = 0x19 TCS34725_BDATAL = 0x1A # Blue channel data TCS34725_BDATAH = 0x1B TCS34725_INTEGRATIONTIME_2_4MS = 0xFF # 2.4ms - 1 cycle - Max Count: 1024 TCS34725_INTEGRATIONTIME_24MS = 0xF6 # 24ms - 10 cycles - Max Count: 10240 TCS34725_INTEGRATIONTIME_50MS = 0xEB # 50ms - 20 cycles - Max Count: 20480 TCS34725_INTEGRATIONTIME_101MS = 0xD5 # 101ms - 42 cycles - Max Count: 43008 TCS34725_INTEGRATIONTIME_154MS = 0xC0 # 154ms - 64 cycles - Max Count: 65535 TCS34725_INTEGRATIONTIME_240MS = 0x9C # 240ms - 100 cycles - Max Count: 65535 TCS34725_INTEGRATIONTIME_700MS = 0x00 # 700ms - 256 cycles - Max Count: 65535 TCS34725_GAIN_1X = 0x00 # No gain TCS34725_GAIN_4X = 0x01 # 2x gain TCS34725_GAIN_16X = 0x02 # 16x gain TCS34725_GAIN_60X = 0x03 # 60x gain # Lookup table for integration time delays. INTEGRATION_TIME_DELAY = { 0xFF: 0.0024, # 2.4ms - 1 cycle - Max Count: 1024 0xF6: 0.024, # 24ms - 10 cycles - Max Count: 10240 0xEB: 0.050, # 50ms - 20 cycles - Max Count: 20480 0xD5: 0.101, # 101ms - 42 cycles - Max Count: 43008 0xC0: 0.154, # 154ms - 64 cycles - Max Count: 65535 0x00: 0.700 # 700ms - 256 cycles - Max Count: 65535 } # Utility methods: def calculate_color_temperature(r, g, b): """Converts the raw R/G/B values to color temperature in degrees Kelvin.""" # 1. Map RGB values to their XYZ counterparts. # Based on 6500K fluorescent, 3000K fluorescent # and 60W incandescent values for a wide range. # Note: Y = Illuminance or lux X = (-0.14282 * r) + (1.54924 * g) + (-0.95641 * b) Y = (-0.32466 * r) + (1.57837 * g) + (-0.73191 * b) Z = (-0.68202 * r) + (0.77073 * g) + ( 0.56332 * b) # Check for divide by 0 (total darkness) and return None. if (X + Y + Z) == 0: return None # 2. Calculate the chromaticity co-ordinates xc = (X) / (X + Y + Z) yc = (Y) / (X + Y + Z) # Check for divide by 0 again and return None. if (0.1858 - yc) == 0: return None # 3. Use McCamy's formula to determine the CCT n = (xc - 0.3320) / (0.1858 - yc) # Calculate the final CCT cct = (449.0 * (n ** 3.0)) + (3525.0 *(n ** 2.0)) + (6823.3 * n) + 5520.33 return int(cct) def calculate_lux(r, g, b): """Converts the raw R/G/B values to luminosity in lux.""" illuminance = (-0.32466 * r) + (1.57837 * g) + (-0.73191 * b) return int(illuminance) class TCS34725(object): """TCS34725 color sensor.""" def __init__(self, *args, **Kwargs): """Initialize the TCS34725 sensor.""" # Setup I2C interface for the device. self._i2cDev = None if not isinstance(args[0], I2C): raise ValueError("parameter is not an I2C object") self._i2cDev = args[0] # default parameters gain=TCS34725_GAIN_60X integration_time=TCS34725_INTEGRATIONTIME_240MS # Make sure we're connected to the sensor. chip_id = self._readU8(TCS34725_ID) if chip_id != 0x44 and chip_id != 0x4D: print('chip id:' + str(chip_id)) raise RuntimeError('Failed to read TCS34725 chip ID, check your wiring.') # Set default integration time and gain. self.set_integration_time(integration_time) self.set_gain(gain) # Enable the device (by default, the device is in power down mode on bootup). self.enable() def _readU8(self, reg): """Read an unsigned 8-bit register.""" v = bytearray(1) self._i2cDev.memRead(v, TCS34725_COMMAND_BIT | reg, 8) return v[0] def _readU16LE(self, reg): """Read a 16-bit little endian register.""" v = bytearray(2) self._i2cDev.memRead(v, TCS34725_COMMAND_BIT | reg, 8) return (v[0] | (v[1] << 8)) def _write8(self, reg, value): """Write a 8-bit value to a register.""" v = bytearray([value]) self._i2cDev.memWrite(v, TCS34725_COMMAND_BIT | reg, 8) def enable(self): """Enable the chip.""" # Flip on the power and enable bits. self._write8(TCS34725_ENABLE, TCS34725_ENABLE_PON) time.sleep(0.01) self._write8(TCS34725_ENABLE, (TCS34725_ENABLE_PON | TCS34725_ENABLE_AEN)) time.sleep(0.01) def disable(self): """Disable the chip (power down).""" # Flip off the power on and enable bits. reg = self._readU8(TCS34725_ENABLE) reg &= ~(TCS34725_ENABLE_PON | TCS34725_ENABLE_AEN) self._write8(TCS34725_ENABLE, reg) def set_integration_time(self, integration_time): """Sets the integration time for the TC34725. Provide one of these constants: - TCS34725_INTEGRATIONTIME_2_4MS = 2.4ms - 1 cycle - Max Count: 1024 - TCS34725_INTEGRATIONTIME_24MS = 24ms - 10 cycles - Max Count: 10240 - TCS34725_INTEGRATIONTIME_50MS = 50ms - 20 cycles - Max Count: 20480 - TCS34725_INTEGRATIONTIME_101MS = 101ms - 42 cycles - Max Count: 43008 - TCS34725_INTEGRATIONTIME_154MS = 154ms - 64 cycles - Max Count: 65535 - TCS34725_INTEGRATIONTIME_700MS = 700ms - 256 cycles - Max Count: 65535 """ self._integration_time = integration_time self._write8(TCS34725_ATIME, integration_time) def get_integration_time(self): """Return the current integration time value. This will be one of the constants specified in the set_integration_time doc string. """ return self._readU8(TCS34725_ATIME) def set_gain(self, gain): """Adjusts the gain on the TCS34725 (adjusts the sensitivity to light). Use one of the following constants: - TCS34725_GAIN_1X = No gain - TCS34725_GAIN_4X = 2x gain - TCS34725_GAIN_16X = 16x gain - TCS34725_GAIN_60X = 60x gain """ self._write8(TCS34725_CONTROL, gain) def get_gain(self): """Return the current gain value. This will be one of the constants specified in the set_gain doc string. """ return self._readU8(TCS34725_CONTROL) def wait_for_valid(self): status = self._readU8(TCS34725_STATUS) while not (status & TCS34725_STATUS_AVALID): status = self._readU8(TCS34725_STATUS) pass print(self._readU8(TCS34725_STATUS)) def get_raw_data(self): """Reads the raw red, green, blue and clear channel values. Will return a 4-tuple with the red, green, blue, clear color values (unsigned 16-bit numbers). """ self.wait_for_valid() # Read each color register. r = self._readU16LE(TCS34725_RDATAL) g = self._readU16LE(TCS34725_GDATAL) b = self._readU16LE(TCS34725_BDATAL) c = self._readU16LE(TCS34725_CDATAL) # Delay for the integration time to allow for next reading immediately. #time.sleep(INTEGRATION_TIME_DELAY[self._integration_time]) return (r, g, b, c) def set_interrupt(self, enabled): """Enable or disable interrupts by setting enabled to True or False.""" enable_reg = self._readU8(TCS34725_ENABLE) if enabled: enable_reg |= TCS34725_ENABLE_AIEN else: enable_reg &= ~TCS34725_ENABLE_AIEN self._write8(TCS34725_ENABLE, enable_reg) time.sleep(1) def set_interrupt_limits(self, low, high): """Set the interrupt limits to provied unsigned 16-bit threshold values. """ self._write8(0x04, low & 0xFF) self._write8(0x05, low >> 8) self._write8(0x06, high & 0xFF) self._write8(0x07, high >> 8) def setInterrupt(self, enabled): self.set_interrupt(enabled) def setInterruptLimits(self, low, high): self.set_interrupt_limits(low, high) def getRawData(self): return self.get_raw_data() def getRGB(self): i = 1.0 r, g, b, c = self.get_raw_data() ''' r /= c g /= c b /= c return (int(r * 256), int(g * 256), int(b * 256)) ''' if (r >= g) and (r >= b): i = r/255 + 1 elif (g >= r) and (g >= b): i = g/255 + 1 elif (b >= g) and (b >= r): i = b/255 + 1 # print (i, r, g, b) if i != 0: r /= i g /= i b /= i if (r > 30): r -= 30 if (g > 30): g -= 30 if (b > 30): b -= 30 r = r * 255 / 225 g = g * 255 / 225 b = b * 255 / 225 if (r > 255): r = 255 if (g > 255): g = 255 if (b >= 255): b = 255 return (int(r), int(g), int(b)) def calculateLux(self, r, g, b): """Converts the raw R/G/B values to luminosity in lux.""" return calculate_lux(r, g, b) def calculateCT(self, r, g, b): return calculate_color_temperature(r, g, b)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/color_sorter/esp32/code/tcs34725.py
Python
apache-2.0
14,451
######### from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import ujson ################## import ws2812 import utime from driver import GPIO ws2812Dev = None ws2812status = 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): global ws2812status payload = ujson.loads(request['params']) if "onoff" in payload.keys(): value = payload["onff"] if value == 1: print("打开时钟") ws2812status = 1 elif value == 0: print("关闭时钟") ws2812_close() ws2812status = 0 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 ws2812_init(): global ws2812Dev gpioObj=GPIO() gpioObj.open("ws2812") ws2812Dev = ws2812.WS2812(gpioObj,24) print("ws2812 inited!") def ws2812_close(): ws2812Dev.close() if __name__ == '__main__': ws2812_init() ########## wlan = network.WLAN(network.STA_IF) #创建WLAN对象 get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) ########## while True: timeArray = utime.localtime() if ws2812status == 1: ws2812Dev.timeShow(0,100,0,timeArray[3],timeArray[4],timeArray[5]) utime.sleep(1)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/colorful_clock/esp32/code/main.py
Python
apache-2.0
3,875
""" Copyright (C) 2015-2021 Alibaba Group Holding Limited MicroPython's driver for ws2812 Author: HaaS Date: 2022/05/10 """ from driver import GPIO from machine import Pin from neopixel import NeoPixel import utime br = 1.0 class WS2812(object): def __init__(self,gpioObj,led_pixel=24): self.port_num = None if not isinstance(gpioObj, GPIO): raise ValueError("parameter is not an GPIO object") self.port_num = gpioObj.port() self.led_pixel = led_pixel self.pin = Pin(self.port_num, Pin.OUT) self.np = NeoPixel(self.pin, self.led_pixel) def set(self,r,g,b,index=0): if index >= self.led_pixel: raise ValueError("index is too large") self.np[index] = (r,g,b) self.np.write() def dot(self,r,g,b,t): r=int(br*r) g=int(br*g) b=int(br*b) for i in range(0,self.led_pixel): self.clear_array() self.np[i] = (r,g,b) self.np.write() utime.sleep_ms(t) def rainBow(self,t): r=100 g=0 b=0 for c in range(0,50): g=g+2 for i in range(0,self.led_pixel): self.np[i] = (r,g,b) self.np.write() utime.sleep_us(t) for c in range(0,50): r=r-2 for i in range(0,self.led_pixel): self.np[i] = (r,g,b) self.np.write() utime.sleep_us(t) for c in range(0,50): b=b+2 for i in range(0,self.led_pixel): self.np[i] = (r,g,b) self.np.write() utime.sleep_us(t) for c in range(0,50): g=g-2 for i in range(0,self.led_pixel): self.np[i] = (r,g,b) self.np.write() utime.sleep_us(t) for c in range(0,50): r=r+2 for i in range(0,self.led_pixel): self.np[i] = (r,g,b) self.np.write() utime.sleep_us(t) for c in range(0,50): b=b-2 for i in range(0,self.led_pixel): self.np[i] = (r,g,b) self.np.write() utime.sleep_us(t) def wipe(self,r,g,b,t): r=int(br*r) g=int(br*g) b=int(br*b) self.clear_array() for i in range(0,self.led_pixel): self.np[i] = (r,g,b) self.np.write() utime.sleep_ms(t) def clear_array(self): for i in range(0,self.led_pixel): self.np[i] = (0,0,0) def clear(self,index=None): if index == None: for i in range(0,self.led_pixel): self.np[i] = (0,0,0) if index >= self.led_pixel: raise ValueError("index is too large") else: self.np[index] = (0,0,0) self.np.write() # h-(0,23) m-(0,59) def timeShowCircle(self,pr,pg,pb,h,m): r=int(br*pr) g=int(br*pg) b=int(br*pb) ha = 0 ma = 0 if m == 0: ha = (h%12)*2 ma = 0 else: ha = (h%12)*2 + 1 ma = int(m/2.5) self.clear_array() for i in range(0,self.led_pixel-2): if i != ha and i != ma: self.np[i] = (r,g,b) if (i+1) != ha and (i+1) != ma: self.np[i+1] = (r,g,b) if (i+2) != ha and (i+2) != ma: self.np[i+2] = (r,g,b) self.np[ha] = (200,0,0) self.np[ma] = (0,200,0) self.np.write() if i != ha and i != ma: self.np[i] = (0,0,0) utime.sleep_ms(41) # h-(0,23) m-(0,59) def timeShow(self,pr,pg,pb,h,m,s): r=int(br*pr) g=int(br*pg) b=int(br*pb) ha = 0 ma = 0 if m == 0 or m < 30: ha = (h%12)*2 if m == 0: ma = 0 else: ma = int(m/2.5) else: ha = (h%12)*2 + 1 ma = int(m/2.5)+1 self.clear_array() i = int(s/2.5) if i != ha and i != ma: self.np[i] = (r,g,b) if (i+1) != ha and (i+1) != ma and i<self.led_pixel-1: self.np[i+1] = (r,g,b) if (i+2) != ha and (i+2) != ma and i<self.led_pixel-2: self.np[i+2] = (r,g,b) if i == 22: self.np[0] = (r,g,b) if i == 23: self.np[0] = (r,g,b) self.np[1] = (r,g,b) if ha != ma: self.np[ha] = (200,0,0) if ma==24: self.np[0] = (0,0,200) else: self.np[ma] = (0,0,200) else: self.np[ma] = (200,0,200) self.np.write() if i != ha and i != ma: self.np[i] = (0,0,0)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/colorful_clock/esp32/code/ws2812.py
Python
apache-2.0
4,876
# coding=utf-8 import network import ujson import utime as time import modem from aliyunIoT import Device import ota import kv #更改产品信息 ############################### productKey = "productKey" productSecret = "productSecret" ############################### 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() # 定义需要升级的模块和版本号 module_name = 'default' app_version = '1.0.1' # 定义升级包的下载和安装路径,其中url,hash_type和hash 会通过服务端推送被保存下来 info = { 'url': '', 'store_path': '/data/pyamp/app.zip', 'install_path': '/data/pyamp/', 'length': 0, 'hash_type': '', 'hash': '' } # ota 消息推送的接受函数 def on_trigger(data): global info # 保存服务端推送的ota信息 info['url'] = data['url'] info['length'] = data['length'] info['module_name'] = data['module_name'] info['version'] = data['version'] info['hash'] = data['hash'] info['hash_type'] = data['hash_type'] # 开始ota 包下载 dl_data = {} dl_data['url'] = info['url'] dl_data['store_path'] = info['store_path'] ota.download(dl_data) # ota 升级包下载结果回调函数 def on_download(data): global info if data >= 0: print('Ota download succeed') # 开始ota包校验 param = {} param['length'] = info['length'] param['store_path'] = info['store_path'] param['hash_type'] = info['hash_type'] param['hash'] = info['hash'] ota.verify(param) # ota 升级包校验结果回调函数 def on_verify(data): global info print(data) if data >= 0 : print('Ota verify succeed') print('Start Upgrade') # 开始ota升级 param = {} param['length'] = info['length'] param['store_path'] = info['store_path'] param['install_path'] = info['install_path'] ota.upgrade(param) # ota 升级包结果回调函数 def on_upgrade(data): if data >= 0 : print('Ota succeed') #ota升完级后 重启设备 reboot() connect_state = False def get_connect_state(): global connect_state return connect_state #当iot设备连接到物联网平台的时候触发'connect' 事件 def on_connect(data): global module_name,default_ver,productKey,deviceName,deviceSecret,on_trigger,on_download,on_verify,on_upgrade,connect_state print('***** connect lp succeed****') data_handle = {} data_handle['device_handle'] = device.getDeviceHandle() # 初始化ota服务 ota.init(data_handle) connect_state = True # ota 回调函数注册 ota.on(1,on_trigger) ota.on(2,on_download) ota.on(3,on_verify) ota.on(4,on_upgrade) report_info = { "device_handle": data_handle['device_handle'], "product_key": productKey , "device_name": deviceName , "module_name": module_name , "version": app_version } # 上报本机ota相关信息,上报版本信息返回以后程序返回,知道后台推送ota升级包,才会调用on_trigger函数 ota.report(report_info) def get_model(): global model return model model = 0 model_data = {} #当iot云端下发属性设置时,触发'props'事件 def on_props(request): global model print('clound req data is {}'.format(request)) # # # #获取消息中的params数据 params=request['params'] # #去除字符串的'',得到字典数据 params=eval(params) if "model" in params : model = params["model"] print('model',model) model_data['model'] = model up_data(model_data) #当连接断开时,触发'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 #NetWorkClient该类是一个单例类,实现网络管理相关的功能,包括初始化,联网,状态信息等. 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(): 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/counter/haas506/code/aliyun.py
Python
apache-2.0
7,662
# 每个字符是8x16(宽x高) 点阵, F2=[ 0x10,0xF0,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x3F,0x21,0x00,0x00,0x20,0x3F,0x20, #*"h",0*# 0x00,0x00,0x80,0x80,0x80,0x00,0x00,0x00,0x00,0x19,0x24,0x24,0x12,0x3F,0x20,0x00, #*"a",1*# 0x00,0x00,0x80,0x80,0x80,0x00,0x00,0x00,0x00,0x19,0x24,0x24,0x12,0x3F,0x20,0x00, #*"a",2*# 0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x33,0x24,0x24,0x24,0x24,0x19,0x00, #*"s",3*# 0x00,0xF8,0x88,0x88,0x88,0x08,0x08,0x00,0x00,0x19,0x20,0x20,0x20,0x11,0x0E,0x00, #*"5",4*# 0x00,0xE0,0x10,0x08,0x08,0x10,0xE0,0x00,0x00,0x0F,0x10,0x20,0x20,0x10,0x0F,0x00, #*"0",5*# 0x00,0xE0,0x10,0x88,0x88,0x90,0x00,0x00,0x00,0x0F,0x11,0x20,0x20,0x20,0x1F,0x00, #*"6",6*# ] #字符串 6x8点阵 F6x8=[ [0x00, 0x00, 0x00, 0x00, 0x00, 0x00],# sp [0x00, 0x00, 0x00, 0x2f, 0x00, 0x00],# ! [0x00, 0x00, 0x07, 0x00, 0x07, 0x00],# " [0x00, 0x14, 0x7f, 0x14, 0x7f, 0x14],# # [0x00, 0x24, 0x2a, 0x7f, 0x2a, 0x12],# $ [0x00, 0x62, 0x64, 0x08, 0x13, 0x23],# % [0x00, 0x36, 0x49, 0x55, 0x22, 0x50],# & [0x00, 0x00, 0x05, 0x03, 0x00, 0x00],# ' [0x00, 0x00, 0x1c, 0x22, 0x41, 0x00],# ( [0x00, 0x00, 0x41, 0x22, 0x1c, 0x00],# ) [0x00, 0x14, 0x08, 0x3E, 0x08, 0x14],# * [0x00, 0x08, 0x08, 0x3E, 0x08, 0x08],# + [0x00, 0x00, 0x00, 0xA0, 0x60, 0x00],# , [0x00, 0x08, 0x08, 0x08, 0x08, 0x08],# - [0x00, 0x00, 0x60, 0x60, 0x00, 0x00],# . [0x00, 0x20, 0x10, 0x08, 0x04, 0x02],# # [0x00, 0x3E, 0x51, 0x49, 0x45, 0x3E],# 0 [0x00, 0x00, 0x42, 0x7F, 0x40, 0x00],# 1 [0x00, 0x42, 0x61, 0x51, 0x49, 0x46],# 2 [0x00, 0x21, 0x41, 0x45, 0x4B, 0x31],# 3 [0x00, 0x18, 0x14, 0x12, 0x7F, 0x10],# 4 [0x00, 0x27, 0x45, 0x45, 0x45, 0x39],# 5 [0x00, 0x3C, 0x4A, 0x49, 0x49, 0x30],# 6 [0x00, 0x01, 0x71, 0x09, 0x05, 0x03],# 7 [0x00, 0x36, 0x49, 0x49, 0x49, 0x36],# 8 [0x00, 0x06, 0x49, 0x49, 0x29, 0x1E],# 9 [0x00, 0x00, 0x36, 0x36, 0x00, 0x00],# : [0x00, 0x00, 0x56, 0x36, 0x00, 0x00],# ; [0x00, 0x08, 0x14, 0x22, 0x41, 0x00],# < [0x00, 0x14, 0x14, 0x14, 0x14, 0x14],# = [0x00, 0x00, 0x41, 0x22, 0x14, 0x08],# > [0x00, 0x02, 0x01, 0x51, 0x09, 0x06],# ? [0x00, 0x32, 0x49, 0x59, 0x51, 0x3E],# @ [0x00, 0x7C, 0x12, 0x11, 0x12, 0x7C],# A [0x00, 0x7F, 0x49, 0x49, 0x49, 0x36],# B [0x00, 0x3E, 0x41, 0x41, 0x41, 0x22],# C [0x00, 0x7F, 0x41, 0x41, 0x22, 0x1C],# D [0x00, 0x7F, 0x49, 0x49, 0x49, 0x41],# E [0x00, 0x7F, 0x09, 0x09, 0x09, 0x01],# F [0x00, 0x3E, 0x41, 0x49, 0x49, 0x7A],# G [0x00, 0x7F, 0x08, 0x08, 0x08, 0x7F],# H [0x00, 0x00, 0x41, 0x7F, 0x41, 0x00],# I [0x00, 0x20, 0x40, 0x41, 0x3F, 0x01],# J [0x00, 0x7F, 0x08, 0x14, 0x22, 0x41],# K [0x00, 0x7F, 0x40, 0x40, 0x40, 0x40],# L [0x00, 0x7F, 0x02, 0x0C, 0x02, 0x7F],# M [0x00, 0x7F, 0x04, 0x08, 0x10, 0x7F],# N [0x00, 0x3E, 0x41, 0x41, 0x41, 0x3E],# O [0x00, 0x7F, 0x09, 0x09, 0x09, 0x06],# P [0x00, 0x3E, 0x41, 0x51, 0x21, 0x5E],# Q [0x00, 0x7F, 0x09, 0x19, 0x29, 0x46],# R [0x00, 0x46, 0x49, 0x49, 0x49, 0x31],# S [0x00, 0x01, 0x01, 0x7F, 0x01, 0x01],# T [0x00, 0x3F, 0x40, 0x40, 0x40, 0x3F],# U [0x00, 0x1F, 0x20, 0x40, 0x20, 0x1F],# V [0x00, 0x3F, 0x40, 0x38, 0x40, 0x3F],# W [0x00, 0x63, 0x14, 0x08, 0x14, 0x63],# X [0x00, 0x07, 0x08, 0x70, 0x08, 0x07],# Y [0x00, 0x61, 0x51, 0x49, 0x45, 0x43],# Z [0x00, 0x00, 0x7F, 0x41, 0x41, 0x00],# [ [0x00, 0x55, 0x2A, 0x55, 0x2A, 0x55],# 55 [0x00, 0x00, 0x41, 0x41, 0x7F, 0x00],# ] [0x00, 0x04, 0x02, 0x01, 0x02, 0x04],# ^ [0x00, 0x40, 0x40, 0x40, 0x40, 0x40],# _ [0x00, 0x00, 0x01, 0x02, 0x04, 0x00],# ' [0x00, 0x20, 0x54, 0x54, 0x54, 0x78],# a [0x00, 0x7F, 0x48, 0x44, 0x44, 0x38],# b [0x00, 0x38, 0x44, 0x44, 0x44, 0x20],# c [0x00, 0x38, 0x44, 0x44, 0x48, 0x7F],# d [0x00, 0x38, 0x54, 0x54, 0x54, 0x18],# e [0x00, 0x08, 0x7E, 0x09, 0x01, 0x02],# f [0x00, 0x18, 0xA4, 0xA4, 0xA4, 0x7C],# g [0x00, 0x7F, 0x08, 0x04, 0x04, 0x78],# h [0x00, 0x00, 0x44, 0x7D, 0x40, 0x00],# i [0x00, 0x40, 0x80, 0x84, 0x7D, 0x00],# j [0x00, 0x7F, 0x10, 0x28, 0x44, 0x00],# k [0x00, 0x00, 0x41, 0x7F, 0x40, 0x00],# l [0x00, 0x7C, 0x04, 0x18, 0x04, 0x78],# m [0x00, 0x7C, 0x08, 0x04, 0x04, 0x78],# n [0x00, 0x38, 0x44, 0x44, 0x44, 0x38],# o [0x00, 0xFC, 0x24, 0x24, 0x24, 0x18],# p [0x00, 0x18, 0x24, 0x24, 0x18, 0xFC],# q [0x00, 0x7C, 0x08, 0x04, 0x04, 0x08],# r [0x00, 0x48, 0x54, 0x54, 0x54, 0x20],# s [0x00, 0x04, 0x3F, 0x44, 0x40, 0x20],# t [0x00, 0x3C, 0x40, 0x40, 0x20, 0x7C],# u [0x00, 0x1C, 0x20, 0x40, 0x20, 0x1C],# v [0x00, 0x3C, 0x40, 0x30, 0x40, 0x3C],# w [0x00, 0x44, 0x28, 0x10, 0x28, 0x44],# x [0x00, 0x1C, 0xA0, 0xA0, 0xA0, 0x7C],# y [0x00, 0x44, 0x64, 0x54, 0x4C, 0x44],# z [0x14, 0x14, 0x14, 0x14, 0x14, 0x14]# horiz lines ] #字符串 8x16点阵 F8X16=[ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,# 0 0x00,0x00,0x00,0xF8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x33,0x30,0x00,0x00,0x00,#! 1 0x00,0x10,0x0C,0x06,0x10,0x0C,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,#" 2 0x40,0xC0,0x78,0x40,0xC0,0x78,0x40,0x00,0x04,0x3F,0x04,0x04,0x3F,0x04,0x04,0x00,## 3 0x00,0x70,0x88,0xFC,0x08,0x30,0x00,0x00,0x00,0x18,0x20,0xFF,0x21,0x1E,0x00,0x00,#$ 4 0xF0,0x08,0xF0,0x00,0xE0,0x18,0x00,0x00,0x00,0x21,0x1C,0x03,0x1E,0x21,0x1E,0x00,#% 5 0x00,0xF0,0x08,0x88,0x70,0x00,0x00,0x00,0x1E,0x21,0x23,0x24,0x19,0x27,0x21,0x10,#& 6 0x10,0x16,0x0E,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,#' 7 0x00,0x00,0x00,0xE0,0x18,0x04,0x02,0x00,0x00,0x00,0x00,0x07,0x18,0x20,0x40,0x00,#( 8 0x00,0x02,0x04,0x18,0xE0,0x00,0x00,0x00,0x00,0x40,0x20,0x18,0x07,0x00,0x00,0x00,#) 9 0x40,0x40,0x80,0xF0,0x80,0x40,0x40,0x00,0x02,0x02,0x01,0x0F,0x01,0x02,0x02,0x00,#* 10 0x00,0x00,0x00,0xF0,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x1F,0x01,0x01,0x01,0x00,#+ 11 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0xB0,0x70,0x00,0x00,0x00,0x00,0x00,#, 12 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,#- 13 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x00,0x00,0x00,#. 14 0x00,0x00,0x00,0x00,0x80,0x60,0x18,0x04,0x00,0x60,0x18,0x06,0x01,0x00,0x00,0x00,## 15 0x00,0xE0,0x10,0x08,0x08,0x10,0xE0,0x00,0x00,0x0F,0x10,0x20,0x20,0x10,0x0F,0x00,#0 16 0x00,0x10,0x10,0xF8,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,#1 17 0x00,0x70,0x08,0x08,0x08,0x88,0x70,0x00,0x00,0x30,0x28,0x24,0x22,0x21,0x30,0x00,#2 18 0x00,0x30,0x08,0x88,0x88,0x48,0x30,0x00,0x00,0x18,0x20,0x20,0x20,0x11,0x0E,0x00,#3 19 0x00,0x00,0xC0,0x20,0x10,0xF8,0x00,0x00,0x00,0x07,0x04,0x24,0x24,0x3F,0x24,0x00,#4 20 0x00,0xF8,0x08,0x88,0x88,0x08,0x08,0x00,0x00,0x19,0x21,0x20,0x20,0x11,0x0E,0x00,#5 21 0x00,0xE0,0x10,0x88,0x88,0x18,0x00,0x00,0x00,0x0F,0x11,0x20,0x20,0x11,0x0E,0x00,#6 22 0x00,0x38,0x08,0x08,0xC8,0x38,0x08,0x00,0x00,0x00,0x00,0x3F,0x00,0x00,0x00,0x00,#7 23 0x00,0x70,0x88,0x08,0x08,0x88,0x70,0x00,0x00,0x1C,0x22,0x21,0x21,0x22,0x1C,0x00,#8 24 0x00,0xE0,0x10,0x08,0x08,0x10,0xE0,0x00,0x00,0x00,0x31,0x22,0x22,0x11,0x0F,0x00,#9 25 0x00,0x00,0x00,0xC0,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x00,#: 26 0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x60,0x00,0x00,0x00,0x00,#; 27 0x00,0x00,0x80,0x40,0x20,0x10,0x08,0x00,0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x00,#< 28 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x00,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x00,#= 29 0x00,0x08,0x10,0x20,0x40,0x80,0x00,0x00,0x00,0x20,0x10,0x08,0x04,0x02,0x01,0x00,#> 30 0x00,0x70,0x48,0x08,0x08,0x08,0xF0,0x00,0x00,0x00,0x00,0x30,0x36,0x01,0x00,0x00,#? 31 0xC0,0x30,0xC8,0x28,0xE8,0x10,0xE0,0x00,0x07,0x18,0x27,0x24,0x23,0x14,0x0B,0x00,#@ 32 0x00,0x00,0xC0,0x38,0xE0,0x00,0x00,0x00,0x20,0x3C,0x23,0x02,0x02,0x27,0x38,0x20,#A 33 0x08,0xF8,0x88,0x88,0x88,0x70,0x00,0x00,0x20,0x3F,0x20,0x20,0x20,0x11,0x0E,0x00,#B 34 0xC0,0x30,0x08,0x08,0x08,0x08,0x38,0x00,0x07,0x18,0x20,0x20,0x20,0x10,0x08,0x00,#C 35 0x08,0xF8,0x08,0x08,0x08,0x10,0xE0,0x00,0x20,0x3F,0x20,0x20,0x20,0x10,0x0F,0x00,#D 36 0x08,0xF8,0x88,0x88,0xE8,0x08,0x10,0x00,0x20,0x3F,0x20,0x20,0x23,0x20,0x18,0x00,#E 37 0x08,0xF8,0x88,0x88,0xE8,0x08,0x10,0x00,0x20,0x3F,0x20,0x00,0x03,0x00,0x00,0x00,#F 38 0xC0,0x30,0x08,0x08,0x08,0x38,0x00,0x00,0x07,0x18,0x20,0x20,0x22,0x1E,0x02,0x00,#G 39 0x08,0xF8,0x08,0x00,0x00,0x08,0xF8,0x08,0x20,0x3F,0x21,0x01,0x01,0x21,0x3F,0x20,#H 40 0x00,0x08,0x08,0xF8,0x08,0x08,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,#I 41 0x00,0x00,0x08,0x08,0xF8,0x08,0x08,0x00,0xC0,0x80,0x80,0x80,0x7F,0x00,0x00,0x00,#J 42 0x08,0xF8,0x88,0xC0,0x28,0x18,0x08,0x00,0x20,0x3F,0x20,0x01,0x26,0x38,0x20,0x00,#K 43 0x08,0xF8,0x08,0x00,0x00,0x00,0x00,0x00,0x20,0x3F,0x20,0x20,0x20,0x20,0x30,0x00,#L 44 0x08,0xF8,0xF8,0x00,0xF8,0xF8,0x08,0x00,0x20,0x3F,0x00,0x3F,0x00,0x3F,0x20,0x00,#M 45 0x08,0xF8,0x30,0xC0,0x00,0x08,0xF8,0x08,0x20,0x3F,0x20,0x00,0x07,0x18,0x3F,0x00,#N 46 0xE0,0x10,0x08,0x08,0x08,0x10,0xE0,0x00,0x0F,0x10,0x20,0x20,0x20,0x10,0x0F,0x00,#O 47 0x08,0xF8,0x08,0x08,0x08,0x08,0xF0,0x00,0x20,0x3F,0x21,0x01,0x01,0x01,0x00,0x00,#P 48 0xE0,0x10,0x08,0x08,0x08,0x10,0xE0,0x00,0x0F,0x18,0x24,0x24,0x38,0x50,0x4F,0x00,#Q 49 0x08,0xF8,0x88,0x88,0x88,0x88,0x70,0x00,0x20,0x3F,0x20,0x00,0x03,0x0C,0x30,0x20,#R 50 0x00,0x70,0x88,0x08,0x08,0x08,0x38,0x00,0x00,0x38,0x20,0x21,0x21,0x22,0x1C,0x00,#S 51 0x18,0x08,0x08,0xF8,0x08,0x08,0x18,0x00,0x00,0x00,0x20,0x3F,0x20,0x00,0x00,0x00,#T 52 0x08,0xF8,0x08,0x00,0x00,0x08,0xF8,0x08,0x00,0x1F,0x20,0x20,0x20,0x20,0x1F,0x00,#U 53 0x08,0x78,0x88,0x00,0x00,0xC8,0x38,0x08,0x00,0x00,0x07,0x38,0x0E,0x01,0x00,0x00,#V 54 0xF8,0x08,0x00,0xF8,0x00,0x08,0xF8,0x00,0x03,0x3C,0x07,0x00,0x07,0x3C,0x03,0x00,#W 55 0x08,0x18,0x68,0x80,0x80,0x68,0x18,0x08,0x20,0x30,0x2C,0x03,0x03,0x2C,0x30,0x20,#X 56 0x08,0x38,0xC8,0x00,0xC8,0x38,0x08,0x00,0x00,0x00,0x20,0x3F,0x20,0x00,0x00,0x00,#Y 57 0x10,0x08,0x08,0x08,0xC8,0x38,0x08,0x00,0x20,0x38,0x26,0x21,0x20,0x20,0x18,0x00,#Z 58 0x00,0x00,0x00,0xFE,0x02,0x02,0x02,0x00,0x00,0x00,0x00,0x7F,0x40,0x40,0x40,0x00,#[ 59 0x00,0x0C,0x30,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x06,0x38,0xC0,0x00,#\ 60 0x00,0x02,0x02,0x02,0xFE,0x00,0x00,0x00,0x00,0x40,0x40,0x40,0x7F,0x00,0x00,0x00,#] 61 0x00,0x00,0x04,0x02,0x02,0x02,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,#^ 62 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,#_ 63 0x00,0x02,0x02,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,#` 64 0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x19,0x24,0x22,0x22,0x22,0x3F,0x20,#a 65 0x08,0xF8,0x00,0x80,0x80,0x00,0x00,0x00,0x00,0x3F,0x11,0x20,0x20,0x11,0x0E,0x00,#b 66 0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00,0x00,0x0E,0x11,0x20,0x20,0x20,0x11,0x00,#c 67 0x00,0x00,0x00,0x80,0x80,0x88,0xF8,0x00,0x00,0x0E,0x11,0x20,0x20,0x10,0x3F,0x20,#d 68 0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x1F,0x22,0x22,0x22,0x22,0x13,0x00,#e 69 0x00,0x80,0x80,0xF0,0x88,0x88,0x88,0x18,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,#f 70 0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x6B,0x94,0x94,0x94,0x93,0x60,0x00,#g 71 0x08,0xF8,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x3F,0x21,0x00,0x00,0x20,0x3F,0x20,#h 72 0x00,0x80,0x98,0x98,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,#i 73 0x00,0x00,0x00,0x80,0x98,0x98,0x00,0x00,0x00,0xC0,0x80,0x80,0x80,0x7F,0x00,0x00,#j 74 0x08,0xF8,0x00,0x00,0x80,0x80,0x80,0x00,0x20,0x3F,0x24,0x02,0x2D,0x30,0x20,0x00,#k 75 0x00,0x08,0x08,0xF8,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,#l 76 0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x20,0x3F,0x20,0x00,0x3F,0x20,0x00,0x3F,#m 77 0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x3F,0x21,0x00,0x00,0x20,0x3F,0x20,#n 78 0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x1F,0x20,0x20,0x20,0x20,0x1F,0x00,#o 79 0x80,0x80,0x00,0x80,0x80,0x00,0x00,0x00,0x80,0xFF,0xA1,0x20,0x20,0x11,0x0E,0x00,#p 80 0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x0E,0x11,0x20,0x20,0xA0,0xFF,0x80,#q 81 0x80,0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x20,0x20,0x3F,0x21,0x20,0x00,0x01,0x00,#r 82 0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x33,0x24,0x24,0x24,0x24,0x19,0x00,#s 83 0x00,0x80,0x80,0xE0,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0x1F,0x20,0x20,0x00,0x00,#t 84 0x80,0x80,0x00,0x00,0x00,0x80,0x80,0x00,0x00,0x1F,0x20,0x20,0x20,0x10,0x3F,0x20,#u 85 0x80,0x80,0x80,0x00,0x00,0x80,0x80,0x80,0x00,0x01,0x0E,0x30,0x08,0x06,0x01,0x00,#v 86 0x80,0x80,0x00,0x80,0x00,0x80,0x80,0x80,0x0F,0x30,0x0C,0x03,0x0C,0x30,0x0F,0x00,#w 87 0x00,0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x31,0x2E,0x0E,0x31,0x20,0x00,#x 88 0x80,0x80,0x80,0x00,0x00,0x80,0x80,0x80,0x80,0x81,0x8E,0x70,0x18,0x06,0x01,0x00,#y 89 0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x21,0x30,0x2C,0x22,0x21,0x30,0x00,#z 90 0x00,0x00,0x00,0x00,0x80,0x7C,0x02,0x02,0x00,0x00,0x00,0x00,0x00,0x3F,0x40,0x40,# 91 0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,#| 92 0x00,0x02,0x02,0x7C,0x80,0x00,0x00,0x00,0x00,0x40,0x40,0x3F,0x00,0x00,0x00,0x00,# 93 0x00,0x06,0x01,0x01,0x02,0x02,0x04,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,#~ 94 ] BMP1=[ 0x00,0x03,0x05,0x09,0x11,0xFF,0x11,0x89,0x05,0xC3,0x00,0xE0,0x00,0xF0,0x00,0xF8, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x44,0x28,0xFF,0x11,0xAA,0x44,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x83,0x01,0x38,0x44,0x82,0x92, 0x92,0x74,0x01,0x83,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7C,0x44,0xC7,0x01,0x7D, 0x7D,0x7D,0x7D,0x01,0x7D,0x7D,0x7D,0x7D,0x01,0x7D,0x7D,0x7D,0x7D,0x01,0xFF,0x00, 0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x00,0x00,0x00,0x00, 0x00,0x00,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x40,0x40,0x40,0x40,0x00,0x00, 0x6D,0x6D,0x6D,0x6D,0x6D,0x00,0x00,0x60,0x60,0x60,0x60,0x60,0x00,0x00,0x40,0x40, 0x40,0x40,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xDB,0xDB,0xDB,0xDB,0xDB,0x00,0x00, 0xDB,0xDB,0xDB,0xDB,0xDB,0x00,0x00,0xDB,0xDB,0xDB,0xDB,0xDB,0x00,0x00,0xDB,0xDB, 0xDB,0xDB,0xDB,0x00,0x00,0xDA,0xDA,0xDA,0xDA,0xDA,0x00,0x00,0xD8,0xD8,0xD8,0xD8, 0xD8,0x00,0x00,0xC0,0xC0,0xC0,0xC0,0xC0,0x00,0x00,0xC0,0xC0,0xC0,0xC0,0xC0,0x00, 0x00,0xC0,0xC0,0xC0,0xC0,0xC0,0x00,0x00,0xC0,0xC0,0xC0,0xC0,0xC0,0x00,0x00,0x80, 0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x06,0x06,0x06,0x06,0x06,0x00,0x00, 0x06,0x06,0x06,0x06,0x06,0x00,0x00,0x06,0x06,0x06,0x06,0x06,0x00,0x00,0x06,0x06, 0x06,0x06,0x06,0x00,0x00,0x06,0x06,0x06,0xE6,0x66,0x20,0x00,0x06,0x06,0x86,0x06, 0x06,0x00,0x00,0x06,0x06,0x06,0x06,0x86,0x00,0x00,0x06,0x06,0x06,0x06,0x06,0x00, 0x00,0x86,0x86,0x86,0x86,0x86,0x80,0x80,0x86,0x86,0x06,0x86,0x86,0xC0,0xC0,0x86, 0x86,0x86,0x06,0x06,0xD0,0x30,0x76,0x06,0x06,0x06,0x06,0x00,0x00,0x06,0x06,0x06, 0x06,0x06,0x00,0x00,0x06,0x06,0x06,0x06,0x06,0x00,0x00,0x06,0x06,0x06,0x06,0x06, 0x00,0x00,0x06,0x06,0x06,0x06,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x60,0x1C,0x00,0xFE,0x00,0x01, 0x02,0x00,0xC4,0x18,0x20,0x02,0x9E,0x63,0xB2,0x0E,0x00,0xFF,0x81,0x81,0xFF,0x00, 0x00,0x80,0x40,0x30,0x0F,0x00,0x00,0x00,0x00,0xFF,0x00,0x23,0xEA,0xAA,0xBF,0xAA, 0xEA,0x03,0x3F,0x00,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0E,0x0C,0x08,0x00,0x00,0x01,0x01,0x01, 0x01,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x81,0x80,0x80,0x81,0x80, 0x81,0x80,0x80,0x80,0x80,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00, 0x01,0x00,0x01,0x01,0x09,0x0C,0x0E,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0, 0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0x00, 0x00,0x1E,0x21,0x40,0x40,0x50,0x21,0x5E,0x00,0x1E,0x21,0x40,0x40,0x50,0x21,0x5E, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0xC1,0xC1,0xFF, 0xFF,0xC1,0xC1,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0x80,0xFC,0xF3,0xEF,0xF3,0xFC, 0x80,0xFF,0x80,0xEE,0xEE,0xEE,0xF5,0xFB,0xFF,0x9C,0xBE,0xB6,0xB6,0x88,0xFF,0x00 ] #像素:64*64 #列表大小:32*16 BMP2=[ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xC0, 0x60,0x38,0x08,0x0C,0x06,0xC2,0xE2,0x33,0x11,0xF9,0x11,0x33,0x73,0xE2,0x06,0x04, 0x0C,0x18,0x30,0xE0,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7F,0xF7, 0x00,0x00,0x00,0x00,0x00,0xC3,0x87,0x06,0x0C,0xFF,0x0C,0x18,0x18,0xF0,0xE0,0x00, 0x00,0x00,0x00,0x81,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01, 0x07,0x0C,0x18,0x30,0x30,0x61,0x63,0x46,0x46,0x5F,0x46,0x46,0x43,0x63,0x20,0x30, 0x18,0x0C,0x06,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x80,0xE0,0xE0,0xF0,0xE0,0xE0,0xC0,0x60,0x70,0x30,0x38,0x18,0x18,0x0C, 0x0C,0x0C,0x66,0x66,0x66,0x36,0x36,0x36,0x36,0x36,0x36,0x36,0x36,0x36,0x36,0x36, 0x66,0x66,0x0C,0x0C,0x0C,0x18,0x18,0x30,0x30,0x60,0xE0,0xE0,0x70,0x38,0x18,0x0C, 0xFC,0xFC,0x1C,0x04,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0xC7,0xFF,0x79,0x1B,0x03,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0xC3,0xC3,0xC7,0x06,0x0C,0x18,0x70,0xE0,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0xFF,0xFF,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x03,0x03,0x03,0x83,0xFF,0x7F,0x00,0x00, 0x00,0x00,0x00,0x03,0x07,0xFE,0xFC,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x80,0x80,0xC0, 0xC0,0xC0,0x60,0x60,0x30,0x30,0x18,0x1C,0x0E,0x06,0x03,0x03,0x01,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x0F,0x3F,0x78,0xE0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0, 0xFE,0xFE,0x06,0x0C,0x0C,0x0C,0x0C,0x0C,0x0C,0x0C,0x0C,0x0C,0x0C,0x0C,0x0C,0x0C, 0x1C,0x38,0xF0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xDC,0xFF,0xC3,0x01,0x01,0x01,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, ] #32-32.bmp BMP3=[ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF8,0x0E,0x02,0x9B,0xBD,0xFF,0x65,0xED,0xCB, 0x06,0x9C,0xF8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0xC0,0xC0,0xC0,0xC0,0xC0,0x60,0x61,0x23,0xF6,0xFD,0x7F,0x7F,0x7B,0x7D,0xF4, 0xF6,0x23,0x60,0x60,0xC0,0xC0,0x60,0x60,0xE0,0x60,0x20,0x00,0x00,0x00,0x00,0x00, 0x20,0xFF,0x8F,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x19,0x1B,0x06,0x0C,0x18,0x90,0xF0,0x20, 0x00,0x01,0x1F,0x7E,0xE0,0x80,0x80,0xA0,0xF0,0x30,0x20,0x20,0x20,0x20,0x20,0x20, 0x60,0xC0,0x80,0x80,0xF0,0xF0,0x18,0x18,0x08,0x0C,0x04,0x06,0x03,0x01,0x01,0x00, ]
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/counter/haas506/code/codetab.py
Python
apache-2.0
21,633
from ssd1306 import SSD1306_128_64 import utime as time from driver import TIMER from driver import GPIO import aliyun disp=SSD1306_128_64() time_d = [0x32, 0x35, 0x3a, 0x30, 0x30] # 倒计时 25:00 print('time_d',time_d) #model= 0 自动连续计时; model = 1 手动重启计时 model = 0 tomato_count = 0 count_data = {} #实例化key1 key1=GPIO(10,10) key1.open("KEY1") #按键中断回调函数 def key1_callback(args): global time_d time_d = [0x32, 0x35, 0x3a, 0x30, 0x30] ret = timer.start() disp.oled_showstr(0,6,' ',1) print(ret) key1.disableIrq() key1.clearIrq() def enable_key(): #开启中断 key1.enableIrq(key1_callback) # 初始化 disp.begin() #清屏 disp.clear() # 番茄时钟 OLED显示,每一秒刷一次 def down_time(args): global downtime_end,time_d,tomato_count,model if time_d[4] > 0x30: time_d[4] = time_d[4] - 1 else: time_d[4] = 0x39 if time_d[3] > 0x30: time_d[3] = time_d[3] - 1 else: time_d[3] = 0x35 if time_d[1] > 0x30: time_d[1] = time_d[1] - 1 else: time_d[1] = 0x39 if time_d[0] > 0x30: time_d[0] = time_d[0] - 1 else: downtime_end = 1 time_d[0] = 0x30 time_d[1] = 0x30 time_d[3] = 0x30 time_d[4] = 0x30 tomato_count += 1 #界面显示 disp.oled_showstr(0,0,"count:",2) disp.oled_showstr(55,0,str(tomato_count),2) disp.oled_showstr(85,0,"md:",2) disp.oled_showstr(110,0,str(model),2) count_data['count'] =tomato_count aliyun.up_data(count_data) print(model) print(type(model)) if model == 1: disp.oled_showstr(0,6,'push key to begin',1) timer.stop() elif model ==0 : time_d = [0x32, 0x35, 0x3a, 0x30, 0x30] #重置时间 disp.oled_showmun(70,3,time_d,2) disp.oled_showstr(0,3,"remain:",2) timer = TIMER(0) timer.open(period=1000, mode=TIMER.PERIODIC, callback=down_time) if __name__ == '__main__': global downtime_end models = model timer.stop() aliyun.connect() #连接阿里云 #打开按键使能 enable_key() while aliyun.get_connect_state() == False: time.sleep(0.1) print('push key to begin') #界面显示 disp.oled_showstr(0,6,'push key to begin',1) disp.oled_showstr(0,0,"count:",2) disp.oled_showstr(55,0,str(tomato_count),2) disp.oled_showstr(85,0,"md:",2) disp.oled_showstr(110,0,str(model),2) aliyun.up_data({'count':0}) aliyun.up_data({'model':0}) while True: time.sleep_ms(500) model = aliyun.get_model() if models != model: disp.oled_showstr(110,0,str(model),2) models = model
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/counter/haas506/code/main.py
Python
apache-2.0
3,157
import utime as time import codetab # Constants SSD1306_I2C_ADDRESS = 0x3C # 011110+SA0+RW - 0x3C or 0x3D SSD1306_SETCONTRAST = 0x81 SSD1306_DISPLAYALLON_RESUME = 0xA4 SSD1306_DISPLAYALLON = 0xA5 SSD1306_NORMALDISPLAY = 0xA6 SSD1306_INVERTDISPLAY = 0xA7 SSD1306_DISPLAYOFF = 0xAE SSD1306_DISPLAYON = 0xAF SSD1306_SETDISPLAYOFFSET = 0xD3 SSD1306_SETCOMPINS = 0xDA SSD1306_SETVCOMDETECT = 0xDB SSD1306_SETDISPLAYCLOCKDIV = 0xD5 SSD1306_SETPRECHARGE = 0xD9 SSD1306_SETMULTIPLEX = 0xA8 SSD1306_SETLOWCOLUMN = 0x00 SSD1306_SETHIGHCOLUMN = 0x10 SSD1306_SETSTARTLINE = 0x40 SSD1306_MEMORYMODE = 0x20 SSD1306_COLUMNADDR = 0x21 SSD1306_PAGEADDR = 0x22 SSD1306_COMSCANINC = 0xC0 SSD1306_COMSCANDEC = 0xC8 SSD1306_SEGREMAP = 0xA0 SSD1306_CHARGEPUMP = 0x8D SSD1306_EXTERNALVCC = 0x1 SSD1306_SWITCHCAPVCC = 0x2 # Scrolling constants SSD1306_ACTIVATE_SCROLL = 0x2F SSD1306_DEACTIVATE_SCROLL = 0x2E SSD1306_SET_VERTICAL_SCROLL_AREA = 0xA3 SSD1306_RIGHT_HORIZONTAL_SCROLL = 0x26 SSD1306_LEFT_HORIZONTAL_SCROLL = 0x27 SSD1306_VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL = 0x29 SSD1306_VERTICAL_AND_LEFT_HORIZONTAL_SCROLL = 0x2A class SSD1306Base(object): def __init__(self, width, height): self.width = width self.height = height self._pages = height//8 self._buffer = [0]*(width*self._pages) # Handle hardware I2C from driver import I2C self._i2c=I2C() self._i2c.open('OLED') def _initialize(self): raise NotImplementedError def writeCmd(self, command): """Send command byte to display.""" # I2C write. control = 0x00 # Co = 0, DC = 0 # writeBuf=bytearray(2) # writeBuf[0]=control # writeBuf[1]=command # self._i2c.write(writeBuf) writeBuf=bytearray(1) writeBuf[0]=command self._i2c.memWrite(writeBuf,control,8) def writeDat(self, data): """Send byte of data to display.""" # I2C write. control = 0x40 # Co = 0, DC = 0 # writeBuf=bytearray(2) # writeBuf[0]=control # writeBuf[1]=data # self._i2c.write(writeBuf) writeBuf=bytearray(1) writeBuf[0]=data self._i2c.memWrite(writeBuf,control,8) def begin(self, vccstate=SSD1306_SWITCHCAPVCC): """Initialize display.""" # Save vcc state. self._vccstate = vccstate # Reset and initialize display. # self.reset() self._initialize() # Turn on the display. self.writeCmd(SSD1306_DISPLAYON) # -------------------------------------------------------------- # Prototype : oled_fill(fill_data) # Parameters : fill_data,范围0x00-0xff # Description : 全屏填充,例如 0x00-全黑,0xff全亮 # -------------------------------------------------------------- def oled_fill(self,fill_data): for i in range(8): #page0-page1 self.writeCmd(0xb0+i) # low colum start address self.writeCmd(0x00) #high colum start address self.writeCmd(0x10) for i in range(128*64): self.writeDat(fill_data) # -------------------------------------------------------------- # Prototype : clear() # Parameters : none # Description : 全黑 # -------------------------------------------------------------- def clear(self): self.oled_fill(0x00) # -------------------------------------------------------------- # Prototype : oled_setPos(x,y) # Parameters : x,y -- 起始点坐标(x:0~127, y:0~7) # Description : 设置起始坐标 # -------------------------------------------------------------- def oled_setPos(self,x,y): self.writeCmd(0xb0+y) self.writeCmd(((x&0xf0)>>4)|0x10) self.writeCmd((x&0x0f)|0x01) # -------------------------------------------------------------- # Prototype : oled_showCN(x,y,n) # Parameters : x,y -- 起始点坐标(x:0~127, y:0~7); N:汉字在codetab.h中的索引 # Description : 显示codetab.py中的汉字,16*16点阵 # -------------------------------------------------------------- def oled_showCN(self,x,y,n): self.oled_setPos(x,y) adder=32*n for i in range(16): self.writeDat(codetab.F1[adder]) adder+=1 self.oled_setPos(x,y+1) for i in range(16): self.writeDat(codetab.F1[adder]) adder+=1 # -------------------------------------------------------------- # Prototype : oled_showStr(x,y,ch,TextSize) # Parameters : x,y -- 起始点坐标(x:0~127, y:0~7); ch[] -- 要显示的字符串; TextSize -- 字符大小(1:6*8 ; 2:8*16) # Description : 显示codetab.py中的ASCII字符,有6*8和8*16可选择 # -------------------------------------------------------------- def oled_showmun(self,x,y,ch,TextSize): c=0 j=0 if TextSize==1: while ch[j]!='\0': #ord()将字符转换成十进制,如'a'->97 c=ch[j]-32 if x>126: x=0 y+=1 self.oled_setPos(x,y) for i in range(6): self.writeDat(codetab.F6x8[c][i]) x+=6 j+=1 #防止index out of range if j==len(ch): break if TextSize==2: while ch[j]!='\0': #ord()将字符转换成十进制 c=ch[j]-32 if x>120: x=0 y+=1 self.oled_setPos(x,y) for i in range(8): self.writeDat(codetab.F8X16[c*16+i]) self.oled_setPos(x,y+1) for i in range(8): self.writeDat(codetab.F8X16[c*16+i+8]) x+=8 j+=1 #防止index out of range if j==len(ch): break def oled_showstr(self,x,y,ch,TextSize): c2=0 j=0 if TextSize==1: while ch[j]!='\0': #ord()将字符转换成十进制,如'a'->97 c2=ord(ch[j])-32 if x>126: x=0 y+=1 self.oled_setPos(x,y) for i in range(6): self.writeDat(codetab.F6x8[c2][i]) x+=6 j+=1 #防止index out of range if j==len(ch): break if TextSize==2: while ch[j]!='\0': #ord()将字符转换成十进制,如'a'->97 c2=ord(ch[j])-32 if x>120: x=0 y+=1 self.oled_setPos(x,y) for i in range(8): self.writeDat(codetab.F8X16[c2*16+i]) self.oled_setPos(x,y+1) for i in range(8): self.writeDat(codetab.F8X16[c2*16+i+8]) x+=8 j+=1 #防止index out of range if j==len(ch): break # # -------------------------------------------------------------- # Prototype : oled_showPicture(x0,y0,x1,y1,BMP) # Parameters : x0,y0 -- 起始点坐标(x0:0~127, y0:0~7); x1,y1 -- 起点对角线(结束点)的坐标(x1:1~128,y1:128) # Description : 显示BMP位图 # -------------------------------------------------------------- def oled_showPicture(self,x0,y0,x1,y1,BMP): i=0 if y1%8==0: y=y1/8 else: y=y1/8+1 for y in range(y0,y1): self.oled_setPos(x0,y) for x in range(x0,x1): self.writeDat(BMP[i]) i+=1 if i==len(BMP) : break # -------------------------------------------------------------- # Prototype : set_contrast(contrast) # Parameters : coontrast,取值范围为0-255 # Description : 对比度/亮度调节 # -------------------------------------------------------------- def set_contrast(self, contrast): if contrast < 0 or contrast > 255: raise ValueError('Contrast must be a value from 0 to 255 (inclusive).') self.writeCmd(SSD1306_SETCONTRAST) self.writeCmd(contrast) class SSD1306_128_64(SSD1306Base): def __init__(self): super(SSD1306_128_64, self).__init__(128, 64) def _initialize(self): # 128x64 pixel specific initialization. self.writeCmd(SSD1306_DISPLAYOFF) # 0xAE self.writeCmd(SSD1306_SETDISPLAYCLOCKDIV) # 0xD5 self.writeCmd(0x80) # the suggested ratio 0x80 self.writeCmd(SSD1306_SETMULTIPLEX) # 0xA8 self.writeCmd(0x3F) self.writeCmd(SSD1306_SETDISPLAYOFFSET) # 0xD3 self.writeCmd(0x0) # no offset self.writeCmd(SSD1306_SETSTARTLINE | 0x0) # line #0 self.writeCmd(SSD1306_CHARGEPUMP) # 0x8D if self._vccstate == SSD1306_EXTERNALVCC: self.writeCmd(0x10) else: self.writeCmd(0x14) self.writeCmd(SSD1306_MEMORYMODE) # 0x20 self.writeCmd(0x00) # 0x0 act like ks0108 self.writeCmd(SSD1306_SEGREMAP | 0x1) self.writeCmd(SSD1306_COMSCANDEC) self.writeCmd(SSD1306_SETCOMPINS) # 0xDA self.writeCmd(0x12) self.writeCmd(SSD1306_SETCONTRAST) # 0x81 if self._vccstate == SSD1306_EXTERNALVCC: self.writeCmd(0x9F) else: self.writeCmd(0xCF) self.writeCmd(SSD1306_SETPRECHARGE) # 0xd9 if self._vccstate == SSD1306_EXTERNALVCC: self.writeCmd(0x22) else: self.writeCmd(0xF1) self.writeCmd(SSD1306_SETVCOMDETECT) # 0xDB self.writeCmd(0x40) self.writeCmd(SSD1306_DISPLAYALLON_RESUME) # 0xA4 self.writeCmd(SSD1306_NORMALDISPLAY) # 0xA6 class SSD1306_128_32(SSD1306Base): def __init__(self): super(SSD1306_128_32, self).__init__(128, 32) def _initialize(self): self.writeCmd(SSD1306_DISPLAYOFF) # 0xAE self.writeCmd(SSD1306_SETDISPLAYCLOCKDIV) # 0xD5 self.writeCmd(0x80) # the suggested ratio 0x80 self.writeCmd(SSD1306_SETMULTIPLEX) # 0xA8 self.writeCmd(0x1F) self.writeCmd(SSD1306_SETDISPLAYOFFSET) # 0xD3 self.writeCmd(0x0) # no offset self.writeCmd(SSD1306_SETSTARTLINE | 0x0) # line #0 self.writeCmd(SSD1306_CHARGEPUMP) # 0x8D if self._vccstate == SSD1306_EXTERNALVCC: self.writeCmd(0x10) else: self.writeCmd(0x14) self.writeCmd(SSD1306_MEMORYMODE) # 0x20 self.writeCmd(0x00) # 0x0 act like ks0108 self.writeCmd(SSD1306_SEGREMAP | 0x1) self.writeCmd(SSD1306_COMSCANDEC) self.writeCmd(SSD1306_SETCOMPINS) # 0xDA self.writeCmd(0x02) self.writeCmd(SSD1306_SETCONTRAST) # 0x81 self.writeCmd(0x8F) self.writeCmd(SSD1306_SETPRECHARGE) # 0xd9 if self._vccstate == SSD1306_EXTERNALVCC: self.writeCmd(0x22) else: self.writeCmd(0xF1) self.writeCmd(SSD1306_SETVCOMDETECT) # 0xDB self.writeCmd(0x40) self.writeCmd(SSD1306_DISPLAYALLON_RESUME) # 0xA4 self.writeCmd(SSD1306_NORMALDISPLAY) # 0xA6 class SSD1306_96_16(SSD1306Base): def __init__(self): super(SSD1306_96_16, self).__init__(96, 16) def _initialize(self): self.writeCmd(SSD1306_DISPLAYOFF) # 0xAE self.writeCmd(SSD1306_SETDISPLAYCLOCKDIV) # 0xD5 self.writeCmd(0x60) # the suggested ratio 0x60 self.writeCmd(SSD1306_SETMULTIPLEX) # 0xA8 self.writeCmd(0x0F) self.writeCmd(SSD1306_SETDISPLAYOFFSET) # 0xD3 self.writeCmd(0x0) # no offset self.writeCmd(SSD1306_SETSTARTLINE | 0x0) # line #0 self.writeCmd(SSD1306_CHARGEPUMP) # 0x8D if self._vccstate == SSD1306_EXTERNALVCC: self.writeCmd(0x10) else: self.writeCmd(0x14) self.writeCmd(SSD1306_MEMORYMODE) # 0x20 self.writeCmd(0x00) # 0x0 act like ks0108 self.writeCmd(SSD1306_SEGREMAP | 0x1) self.writeCmd(SSD1306_COMSCANDEC) self.writeCmd(SSD1306_SETCOMPINS) # 0xDA self.writeCmd(0x02) self.writeCmd(SSD1306_SETCONTRAST) # 0x81 self.writeCmd(0x8F) self.writeCmd(SSD1306_SETPRECHARGE) # 0xd9 if self._vccstate == SSD1306_EXTERNALVCC: self.writeCmd(0x22) else: self.writeCmd(0xF1) self.writeCmd(SSD1306_SETVCOMDETECT) # 0xDB self.writeCmd(0x40) self.writeCmd(SSD1306_DISPLAYALLON_RESUME) # 0xA4 self.writeCmd(SSD1306_NORMALDISPLAY) # 0xA6
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/counter/haas506/code/ssd1306.py
Python
apache-2.0
13,867
import lvgl as lv isStarted = False isAnimationComplete = False arc = [None, None, None, None] anim = [None, None, None, None] timeCount = [1, 3, 5, 10] currentSelect = 0 minuteLabel = None secondLabel = None millionLabel = None anim_timeline = None startLabel = None currentValue = 0 lvglInitialized = False def setLabelValue(value): global currentValue global minuteLabel global secondLabel global millionLabel global startLabel currentValue = value currentMillionSecond = value * 20 minute = currentMillionSecond / 1000 / 60 minuteLabel.set_text('%02d'%minute) second = currentMillionSecond / 1000 % 60 secondLabel.set_text('%02d'%second) million = value % 60 millionLabel.set_text('%02d'%million) def set_time_value(obj, v): setLabelValue(v) obj.set_value(v) def reset_button_event_handler(e): global isStarted global isAnimationComplete global currentValue global timeCount global arc global anim global anim_timeline global startLabel if (isStarted): return isAnimationComplete = False currentValue = timeCount[currentSelect] * 60 * 50 arc[currentSelect].set_value(currentValue) anim[currentSelect] = lv.anim_t() anim[currentSelect].init() anim[currentSelect].set_var(arc[currentSelect]) anim[currentSelect].set_time(currentValue * 20) anim[currentSelect].set_values(currentValue, 0) anim[currentSelect].set_custom_exec_cb(lambda a1, val: set_time_value(arc[currentSelect], val)) anim_timeline = lv.anim_timeline_create() lv.anim_timeline_add(anim_timeline, 0, anim[currentSelect]) startLabel.set_text("START") setLabelValue(currentValue) def arc_event_handler(e, index): global isStarted global currentSelect global arc print("index: " + str(index) + " currentSelect: " + str(currentSelect)) print("isStarted: " + str(isStarted)) if (isStarted or currentSelect == index): return arc[currentSelect].set_value(0) arc[currentSelect].set_style_arc_width(2, lv.PART.INDICATOR) arc[currentSelect].set_style_arc_width(2, lv.PART.MAIN) currentSelect = index arc[currentSelect].set_style_arc_width(8, lv.PART.INDICATOR) arc[currentSelect].set_style_arc_width(8, lv.PART.MAIN) reset_button_event_handler(e) def start_button_event_handler(e): global isStarted global isAnimationComplete global anim_timeline global startLabel global anim global currentSelect global currentValue if (isAnimationComplete): return if (isStarted): isStarted = False lv.anim_timeline_stop(anim_timeline) lv.anim_timeline_del(anim_timeline) anim_timeline = None startLabel.set_text("RESUME") anim[currentSelect] = lv.anim_t() anim[currentSelect].init() anim[currentSelect].set_var(arc[currentSelect]) anim[currentSelect].set_time(currentValue * 20) anim[currentSelect].set_values(currentValue, 0) anim[currentSelect].set_custom_exec_cb(lambda a1, val: set_time_value(arc[currentSelect],val)) anim_timeline = lv.anim_timeline_create() lv.anim_timeline_add(anim_timeline, 0, anim[currentSelect]) else: isStarted = True lv.anim_timeline_start(anim_timeline) startLabel.set_text("PAUSE") class CountDown: def createPage(self, value1 = 1, value2 = 3, value3 = 5, value4 = 10): global isStarted global isAnimationComplete global arc global anim global timeCount global currentSelect global minuteLabel global secondLabel global millionLabel global anim_timeline global startLabel global currentValue global lvglInitialized if lvglInitialized == False: import display_driver lvglInitialized = True print("Enter count down") timeCount = [value1, value2, value3, value4] # 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) isStarted = False currentSelect = 0 # count down func_col_dsc = [40, 5, 30, 5, 20, lv.GRID_TEMPLATE.LAST] func_row_dsc = [30, lv.GRID_TEMPLATE.LAST] timeContainer = lv.obj(win) timeContainer.set_style_bg_opa(0, 0) timeContainer.set_style_border_opa(0, 0) timeContainer.set_layout(lv.LAYOUT_GRID.value) timeContainer.set_style_grid_column_dsc_array(func_col_dsc, 0) timeContainer.set_style_grid_row_dsc_array(func_row_dsc, 0) timeContainer.set_grid_align(lv.GRID_ALIGN.SPACE_BETWEEN, lv.GRID_ALIGN.SPACE_BETWEEN) timeContainer.set_style_pad_all(0, 0) timeContainer.set_size(240, 70) timeContainer.center() minuteLabel = lv.label(timeContainer) minuteLabel.set_style_text_font(lv.font_montserrat_48, 0) minuteLabel.set_style_text_color(lv.color_white(), 0) minuteLabel.set_grid_cell(lv.GRID_ALIGN.START, 0, 1, lv.GRID_ALIGN.CENTER, 0, 1) signLabel = lv.label(timeContainer) signLabel.set_style_text_font(lv.font_montserrat_48, 0) signLabel.set_style_text_color(lv.color_white(), 0) signLabel.set_text(":") signLabel.set_grid_cell(lv.GRID_ALIGN.CENTER, 1, 1, lv.GRID_ALIGN.CENTER, 0, 1) secondLabel = lv.label(timeContainer) secondLabel.set_style_text_font(lv.font_montserrat_48, 0) secondLabel.set_style_text_color(lv.color_white(), 0) secondLabel.set_grid_cell(lv.GRID_ALIGN.CENTER, 2, 1, lv.GRID_ALIGN.CENTER, 0, 1) signLabel = lv.label(timeContainer) signLabel.set_style_text_font(lv.font_montserrat_48, 0) signLabel.set_style_text_color(lv.color_white(), 0) signLabel.set_text(":") signLabel.set_grid_cell(lv.GRID_ALIGN.CENTER, 3, 1, lv.GRID_ALIGN.CENTER, 0, 1) millionLabel = lv.label(timeContainer) millionLabel.set_style_text_font(lv.font_montserrat_36, 0) millionLabel.set_style_text_color(lv.color_white(), 0) millionLabel.set_grid_cell(lv.GRID_ALIGN.END, 4, 1, lv.GRID_ALIGN.START, 0, 1) setLabelValue(timeCount[currentSelect] * 60 * 50) startButton = lv.btn(win) startButton.align(lv.ALIGN.CENTER, 0, 40) startButton.set_size(126, 54) startButton.set_style_radius(45, lv.PART.MAIN) startButton.set_style_shadow_opa(0, 0) startButton.set_style_bg_color(lv.color_make(0xFF, 0xA8, 0x48), lv.PART.MAIN) startButton.align(lv.ALIGN.BOTTOM_LEFT, 12, -12) startButton.add_event_cb(start_button_event_handler, lv.EVENT.CLICKED, None) startLabel = lv.label(startButton) startLabel.set_text("START") startLabel.set_style_text_color(lv.color_black(), 0) startLabel.set_style_text_font(lv.font_montserrat_20, 0) startLabel.center() resetButton = lv.btn(win) resetButton.align(lv.ALIGN.CENTER, 0, 40) resetButton.set_size(126, 54) resetButton.set_style_radius(45, lv.PART.MAIN) resetButton.set_style_shadow_opa(0, 0) resetButton.set_style_bg_color(lv.color_white(), lv.PART.MAIN) resetButton.align(lv.ALIGN.BOTTOM_RIGHT, -12, -12) resetButton.add_event_cb(reset_button_event_handler, lv.EVENT.CLICKED, None) resetLabel = lv.label(resetButton) resetLabel.set_text("REST") resetLabel.set_style_text_color(lv.color_black(), 0) resetLabel.set_style_text_font(lv.font_montserrat_20, 0) resetLabel.center() # select time col_dsc = [75, 75, 75, 75, lv.GRID_TEMPLATE.LAST] row_dsc = [60, 80, 60, lv.GRID_TEMPLATE.LAST] funcContainer = lv.obj(win) funcContainer.set_layout(lv.LAYOUT_GRID.value) funcContainer.set_style_bg_opa(0, 0) funcContainer.set_style_border_opa(0, 0) funcContainer.set_style_grid_column_dsc_array(col_dsc, 0) funcContainer.set_style_grid_row_dsc_array(row_dsc, 0) funcContainer.set_grid_align(lv.GRID_ALIGN.SPACE_BETWEEN, lv.GRID_ALIGN.SPACE_BETWEEN) funcContainer.set_size(300, 90) funcContainer.set_style_align(lv.ALIGN.TOP_MID, 0) maxMillionSecond = timeCount[0] * 60 * 50 arc[0] = lv.arc(funcContainer) arc[0].set_style_arc_color(lv.color_white(), lv.PART.INDICATOR) arc[0].set_style_arc_color(lv.color_make(0x33, 0x33, 0x33), lv.PART.MAIN) arc[0].set_range(0, maxMillionSecond) arc[0].set_size(55, 55) arc[0].set_rotation(90) arc[0].set_bg_angles(0, 360) arc[0].remove_style(None, lv.PART.KNOB) arc[0].set_value(maxMillionSecond) arc[0].set_style_arc_width(8, lv.PART.INDICATOR) arc[0].set_style_arc_width(8, lv.PART.MAIN) arc[0].set_grid_cell(lv.GRID_ALIGN.CENTER, 0, 1, lv.GRID_ALIGN.CENTER, 0, 1) arc[0].clear_flag(lv.obj.FLAG.CLICKABLE) totalTime = lv.label(funcContainer) totalTime.set_text(str(timeCount[0])) totalTime.set_style_text_font(lv.font_montserrat_18, 0) totalTime.set_style_text_color(lv.color_white(), 0) totalTime.set_grid_cell(lv.GRID_ALIGN.CENTER, 0, 1, lv.GRID_ALIGN.CENTER, 0, 1) totalTime.add_flag(lv.obj.FLAG.CLICKABLE) totalTime.add_event_cb(lambda e: arc_event_handler(e, 0), lv.EVENT.CLICKED, None) totalTime.set_ext_click_area(30) anim[0] = lv.anim_t() anim[0].init() anim[0].set_var(arc[0]) anim[0].set_time(maxMillionSecond * 20) anim[0].set_values(maxMillionSecond, 0) anim[0].set_custom_exec_cb(lambda a1, val: set_time_value(arc[0], val)) anim_timeline = lv.anim_timeline_create() lv.anim_timeline_add(anim_timeline, 0, anim[0]) arc[1] = lv.arc(funcContainer) arc[1].set_style_arc_color(lv.color_white(), lv.PART.INDICATOR) arc[1].set_style_arc_color(lv.color_make(0x33, 0x33, 0x33), lv.PART.MAIN) arc[1].set_range(0, maxMillionSecond) arc[1].set_size(55, 55) arc[1].set_rotation(90) arc[1].set_bg_angles(0, 360) arc[1].remove_style(None, lv.PART.KNOB) arc[1].set_value(0) arc[1].set_style_arc_width(2, lv.PART.INDICATOR) arc[1].set_style_arc_width(2, lv.PART.MAIN) arc[1].set_grid_cell(lv.GRID_ALIGN.CENTER, 1, 1, lv.GRID_ALIGN.CENTER, 0, 1) arc[1].clear_flag(lv.obj.FLAG.CLICKABLE) totalTime = lv.label(funcContainer) totalTime.set_text(str(timeCount[1])) totalTime.set_style_text_font(lv.font_montserrat_18, 0) totalTime.set_style_text_color(lv.color_white(), 0) totalTime.set_grid_cell(lv.GRID_ALIGN.CENTER, 1, 1, lv.GRID_ALIGN.CENTER, 0, 1) totalTime.add_flag(lv.obj.FLAG.CLICKABLE) totalTime.add_event_cb(lambda e: arc_event_handler(e, 1), lv.EVENT.CLICKED, None) totalTime.set_ext_click_area(30) arc[2] = lv.arc(funcContainer) arc[2].set_style_arc_color(lv.color_white(), lv.PART.INDICATOR) arc[2].set_style_arc_color(lv.color_make(0x33, 0x33, 0x33), lv.PART.MAIN) arc[2].set_range(0, maxMillionSecond) arc[2].set_size(55, 55) arc[2].set_rotation(90) arc[2].set_bg_angles(0, 360) arc[2].remove_style(None, lv.PART.KNOB) arc[2].set_value(0) arc[2].set_style_arc_width(2, lv.PART.INDICATOR) arc[2].set_style_arc_width(2, lv.PART.MAIN) arc[2].set_grid_cell(lv.GRID_ALIGN.CENTER, 2, 1, lv.GRID_ALIGN.CENTER, 0, 1) arc[2].clear_flag(lv.obj.FLAG.CLICKABLE) totalTime = lv.label(funcContainer) totalTime.set_text(str(timeCount[2])) totalTime.set_style_text_font(lv.font_montserrat_18, 0) totalTime.set_style_text_color(lv.color_white(), 0) totalTime.set_grid_cell(lv.GRID_ALIGN.CENTER, 2, 1, lv.GRID_ALIGN.CENTER, 0, 1) totalTime.add_flag(lv.obj.FLAG.CLICKABLE) totalTime.add_event_cb(lambda e: arc_event_handler(e, 2), lv.EVENT.CLICKED, None) totalTime.set_ext_click_area(30) arc[3] = lv.arc(funcContainer) arc[3].set_style_arc_color(lv.color_white(), lv.PART.INDICATOR) arc[3].set_style_arc_color(lv.color_make(0x33, 0x33, 0x33), lv.PART.MAIN) arc[3].set_range(0, maxMillionSecond) arc[3].set_size(55, 55) arc[3].set_rotation(90) arc[3].set_bg_angles(0, 360) arc[3].remove_style(None, lv.PART.KNOB) arc[3].set_value(0) arc[3].set_style_arc_width(2, lv.PART.INDICATOR) arc[3].set_style_arc_width(2, lv.PART.MAIN) arc[3].set_grid_cell(lv.GRID_ALIGN.CENTER, 3, 1, lv.GRID_ALIGN.CENTER, 0, 1) arc[3].clear_flag(lv.obj.FLAG.CLICKABLE) totalTime = lv.label(funcContainer) totalTime.set_text(str(timeCount[3])) totalTime.set_style_text_font(lv.font_montserrat_18, 0) totalTime.set_style_text_color(lv.color_white(), 0) totalTime.set_grid_cell(lv.GRID_ALIGN.CENTER, 3, 1, lv.GRID_ALIGN.CENTER, 0, 1) totalTime.add_flag(lv.obj.FLAG.CLICKABLE) totalTime.add_event_cb(lambda e: arc_event_handler(e, 3), lv.EVENT.CLICKED, None) totalTime.set_ext_click_area(30) # load content lv.scr_load(scr)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/counter/m5stack/code/countDown.py
Python
apache-2.0
13,526
from countDown import CountDown stopWatch = CountDown() # max value is 10 stopWatch.createPage(1, 10, 8, 9)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/counter/m5stack/code/main.py
Python
apache-2.0
110
""" Copyright (C) 2015-2021 Alibaba Group Holding Limited MicroPython's driver for BMP280 Author: HaaS Date: 2022/03/15 """ from driver import I2C from utime import sleep_ms from micropython import const import math BSP280_CHIP_ID = const(0x58) BMP280_REGISTER_DIG_T1 = const(0x88) BMP280_REGISTER_DIG_T2 = const(0x8A) BMP280_REGISTER_DIG_T3 = const(0x8C) BMP280_REGISTER_DIG_P1 = const(0x8E) BMP280_REGISTER_DIG_P2 = const(0x90) BMP280_REGISTER_DIG_P3 = const(0x92) BMP280_REGISTER_DIG_P4 = const(0x94) BMP280_REGISTER_DIG_P5 = const(0x96) BMP280_REGISTER_DIG_P6 = const(0x98) BMP280_REGISTER_DIG_P7 = const(0x9A) BMP280_REGISTER_DIG_P8 = const(0x9C) BMP280_REGISTER_DIG_P9 = const(0x9E) BMP280_REGISTER_CHIPID = const(0xD0) BMP280_REGISTER_VERSION = const(0xD1) BMP280_REGISTER_SOFTRESET = const(0xE0) BMP280_REGISTER_CAL26 = const(0xE1) BMP280_REGISTER_CONTROL = const(0xF4) BMP280_REGISTER_CONFIG = const(0xF5) BMP280_REGISTER_PRESSUREDATA = const(0xF7) BMP280_REGISTER_TEMPDATA = const(0xFA) class bmp280Error(Exception): def __init__(self, value=0, msg="bmp280 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 BMP280(object): """ This class implements bmp280 chip's defs. """ def __init__(self, i2cDev): self._i2cDev = None if not isinstance(i2cDev, I2C): raise ValueError("parameter is not an I2C object") # make BMP280's internal object points to i2cDev self._i2cDev = i2cDev self.dig_T1 = 0 self.dig_T2 = 0 self.dig_T3 = 0 self.dig_P1 = 0 self.dig_P2 = 0 self.dig_P3 = 0 self.dig_P4 = 0 self.dig_P5 = 0 self.dig_P6 = 0 self.dig_P7 = 0 self.dig_P8 = 0 self.dig_P9 = 0 self.init() self.readCoefficients() self.writeReg(BMP280_REGISTER_CONTROL, 0x3f) self.t_fine = 0 def readCoefficients(self): self.dig_T1 = self.readReg16(BMP280_REGISTER_DIG_T1) self.dig_T2 = self.readReg16_INT16(BMP280_REGISTER_DIG_T2) self.dig_T3 = self.readReg16_INT16(BMP280_REGISTER_DIG_T3) self.dig_P1 = self.readReg16(BMP280_REGISTER_DIG_P1) self.dig_P2 = self.readReg16_INT16(BMP280_REGISTER_DIG_P2) self.dig_P3 = self.readReg16_INT16(BMP280_REGISTER_DIG_P3) self.dig_P4 = self.readReg16_INT16(BMP280_REGISTER_DIG_P4) self.dig_P5 = self.readReg16_INT16(BMP280_REGISTER_DIG_P5) self.dig_P6 = self.readReg16_INT16(BMP280_REGISTER_DIG_P6) self.dig_P7 = self.readReg16_INT16(BMP280_REGISTER_DIG_P7) self.dig_P8 = self.readReg16_INT16(BMP280_REGISTER_DIG_P8) self.dig_P9 = self.readReg16_INT16(BMP280_REGISTER_DIG_P9) #写寄存器 def writeReg(self, addr, value): Reg = bytearray([addr, value]) self._i2cDev.write(Reg) #print("--> write addr " + hex(addr) + ", value = " + hex(value)) return 0 #读寄存器 def readReg(self, addr, len): Reg = bytearray([addr]) self._i2cDev.write(Reg) sleep_ms(2) tmp = bytearray(len) self._i2cDev.read(tmp) #print("<-- read addr " + hex(addr) + ", value = " + hex(tmp[0])) return tmp def readReg16(self, addr): tmp = self.readReg(addr, 2) data = (tmp[1] << 8) + tmp[0] return data def readReg16_BE(self, addr): tmp = self.readReg(addr, 2) data = (tmp[0] << 8) + tmp[1] return data def readReg8(self, addr): tmp = self.readReg(addr, 1) data = tmp[0] return data def int16(self, dat): if dat > 32767: return dat - 65536 else: return dat def int32(self, dat): if dat > (1 << 31): return dat - (1 << 32) else: return dat def readReg16_INT16(self, addr): tmp = self.readReg(addr, 2) data = (tmp[1] << 8) + tmp[0] data = self.int16(data) return data def deviceCheck(self): ret = self.readReg(BMP280_REGISTER_CHIPID, 1)[0] if (ret == BSP280_CHIP_ID): return 0 else: return 1 def getTemperature(self): adc_T = self.readReg16_BE(BMP280_REGISTER_TEMPDATA) adc_T <<= 8 adc_T |= self.readReg8(BMP280_REGISTER_TEMPDATA + 2) adc_T >>= 4 var1 = ((adc_T >> 3) - (self.dig_T1 << 1)) * (self.dig_T2) >> 11 var2 = (((((adc_T >> 4) - self.dig_T1) * ((adc_T >> 4) - self.dig_T1)) >> 12) * (self.dig_T3)) >> 14 self.t_fine = var1 + var2 t = ((self.t_fine * 5) + 128) >> 8 return t / 100 def getPressure(self): # before get pressure, needs to get temperature. self.getTemperature() adc_P = self.readReg16_BE(BMP280_REGISTER_PRESSUREDATA) adc_P <<= 8 adc_P |= self.readReg8(BMP280_REGISTER_PRESSUREDATA + 2) adc_P >>= 4 var1 = self.t_fine - 128000 var2 = var1 * var1 * self.dig_P6 var2 = (var2) + (((var1 * self.dig_P5)) << 17) var2 = var2 + (self.dig_P4 << 35) var1 = ((var1 * var1 * self.dig_P3) >> 8) + ( (var1 * self.dig_P2) << 12) var1 = (((1 << 47) + var1) * (self.dig_P1)) >> 33 p = 1048576 - adc_P p = (((p << 31) - var2) * 3125) / var1 var1 = ((self.dig_P9) * (p / (1 << 13)) * (p / (1 << 13))) / (1 << 25) var2 = (self.dig_P8 * p) / (1 << 19) p = ((p + var1 + var2) / (1 << 8)) + (self.dig_P7 << 4) return p / 256 def init(self): ret = self.deviceCheck() if (ret != 0): print("bmp280 init fail") return 0 else: pass
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/delivery_track/esp32/code/bmp280.py
Python
apache-2.0
5,883
from driver import UART from micropyGNSS import MicropyGNSS class GNSS(object): def __init__(self, uartObj): self.uartObj = None if not isinstance(uartObj, UART): raise ValueError("parameter is not a GPIO object") # 初始化定位模组串口 self.uartObj = uartObj self.gnss = MicropyGNSS(location_formatting='dd') def getLocation(self): if self.uartObj is None: raise ValueError("invalid UART object") # 创建定位信息解析器 sentence = bytearray(100) self.uartObj.write(sentence) recvsize = self.uartObj.read(sentence) if(recvsize): # print(sentence) # 解析地理位置信息 for c in sentence: self.gnss.update(chr(c)) print(self.gnss.longitude, self.gnss.latitude, self.gnss.altitude) return self.gnss
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/delivery_track/esp32/code/gnss.py
Python
apache-2.0
912
# -*- coding: UTF-8 -*- from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network # Wi-Fi功能所在库 import ujson # json字串解析库 import utime # 延时API所在组件 from driver import I2C # I2C类,用于控制微处理器的输入输出功能 from driver import UART # UART类,用于控制微处理器的输入输出功能 import bmp280 # bmp280气压温度传感器 import gnss # gnss 位置传感器 from micropython import const tempDev = 0 gnssDev = 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() # 扫描接入点 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 bmp280_check_init(): global tempDev i2cObj = I2C() i2cObj.open("bmp280") # 按照board.json中名为"bmp280"的设备节点的配置参数(主设备I2C端口号,从设备地址,总线频率等)初始化I2C类型设备对象 tempDev = bmp280.BMP280(i2cObj) # 初始化BMP280传感器 def gnss_check_init(): global gnssDev uartObj = UART() uartObj.open("gnss") gnssDev = gnss.GNSS(uartObj) print("gnss inited!") def delivery_detecting(): global tempDev, gnssDev temperature = 0 longitude = 0 latitude = 0 altitude = 0 while True: # 无限循环 temperature = tempDev.getTemperature() print('temperature = ', temperature) gnssDev.getLocation() location = gnssDev.getLocation() print(location.longitude, location.latitude, location.altitude) # 判断定位信息是否发生变化 if(longitude != location.longitude[0] or latitude != location.latitude[0] or altitude != location.altitude): longitude = location.longitude[0] latitude = location.latitude[0] altitude = location.altitude print(longitude, latitude, altitude) # 如果有变化,则上报地理位置信息至物联网平台 loc_data = { 'params': ujson.dumps({ 'GeoLocation': { 'Longitude': longitude, 'Latitude': latitude, 'Altitude': altitude, 'CoordinateSystem': 1 } }) } device.postProps(loc_data) upload_data = {'params': ujson.dumps({ 'temperature': temperature, }) } # 上传状态到物联网平台 device.postProps(upload_data) utime.sleep(1) # 打印完之后休眠1秒 if __name__ == '__main__': wlan = network.WLAN(network.STA_IF) # 创建WLAN对象 get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) bmp280_check_init() gnss_check_init() delivery_detecting()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/delivery_track/esp32/code/main.py
Python
apache-2.0
5,222
""" # MicropyGPS - a GPS NMEA sentence parser for Micropython/Python 3.X # Copyright (c) 2017 Michael Calvin McCoy (calvin.mccoy@protonmail.com) # The MIT License (MIT) - see LICENSE file """ """ MIT License Copyright (c) 2017 Calvin McCoy Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ # TODO: # Time Since First Fix # Distance/Time to Target # More Helper Functions # Dynamically limit sentences types to parse from math import floor, modf # Import utime or time for fix time handling try: # Assume running on MicroPython import utime except ImportError: # Otherwise default to time module for non-embedded implementations # Should still support millisecond resolution. import time class MicropyGNSS(object): """NMEA Sentence Parser. Creates object that stores all relevant GPS data and statistics. Parses sentences one character at a time using update(). """ # Max Number of Characters a valid sentence can be (based on GGA sentence) SENTENCE_LIMIT = 90 __HEMISPHERES = ('N', 'S', 'E', 'W') __NO_FIX = 1 __FIX_2D = 2 __FIX_3D = 3 __DIRECTIONS = ('N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW') __MONTHS = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') def __init__(self, local_offset=0, location_formatting='ddm'): """ Setup GPS Object Status Flags, Internal Data Registers, etc local_offset (int): Timzone Difference to UTC location_formatting (str): Style For Presenting Longitude/Latitude: Decimal Degree Minute (ddm) - 40° 26.767′ N Degrees Minutes Seconds (dms) - 40° 26′ 46″ N Decimal Degrees (dd) - 40.446° N """ ##################### # Object Status Flags self.sentence_active = False self.active_segment = 0 self.process_crc = False self.gps_segments = [] self.crc_xor = 0 self.char_count = 0 self.fix_time = 0 ##################### # Sentence Statistics self.crc_fails = 0 self.clean_sentences = 0 self.parsed_sentences = 0 ##################### # Logging Related self.log_handle = None self.log_en = False ##################### # Data From Sentences # Time self.timestamp = [0, 0, 0] self.date = [0, 0, 0] self.local_offset = local_offset # Position/Motion self._latitude = [0, 0.0, 'N'] self._longitude = [0, 0.0, 'W'] self.coord_format = location_formatting self.speed = [0.0, 0.0, 0.0] self.course = 0.0 self.altitude = 0.0 self.geoid_height = 0.0 # GPS Info self.satellites_in_view = 0 self.satellites_in_use = 0 self.satellites_used = [] self.last_sv_sentence = 0 self.total_sv_sentences = 0 self.satellite_data = dict() self.hdop = 0.0 self.pdop = 0.0 self.vdop = 0.0 self.valid = False self.fix_stat = 0 self.fix_type = 1 ######################################## # Coordinates Translation Functions ######################################## @property def latitude(self): """Format Latitude Data Correctly""" if self.coord_format == 'dd': decimal_degrees = self._latitude[0] + (self._latitude[1] / 60) return [decimal_degrees, self._latitude[2]] elif self.coord_format == 'dms': minute_parts = modf(self._latitude[1]) seconds = round(minute_parts[0] * 60) return [self._latitude[0], int(minute_parts[1]), seconds, self._latitude[2]] else: return self._latitude @property def longitude(self): """Format Longitude Data Correctly""" if self.coord_format == 'dd': decimal_degrees = self._longitude[0] + (self._longitude[1] / 60) return [decimal_degrees, self._longitude[2]] elif self.coord_format == 'dms': minute_parts = modf(self._longitude[1]) seconds = round(minute_parts[0] * 60) return [self._longitude[0], int(minute_parts[1]), seconds, self._longitude[2]] else: return self._longitude ######################################## # Logging Related Functions ######################################## def start_logging(self, target_file, mode="append"): """ Create GPS data log object """ # Set Write Mode Overwrite or Append mode_code = 'w' if mode == 'new' else 'a' try: self.log_handle = open(target_file, mode_code) except AttributeError: print("Invalid FileName") return False self.log_en = True return True def stop_logging(self): """ Closes the log file handler and disables further logging """ try: self.log_handle.close() except AttributeError: print("Invalid Handle") return False self.log_en = False return True def write_log(self, log_string): """Attempts to write the last valid NMEA sentence character to the active file handler """ try: self.log_handle.write(log_string) except TypeError: return False return True ######################################## # Sentence Parsers ######################################## def gprmc(self): """Parse Recommended Minimum Specific GPS/Transit data (RMC)Sentence. Updates UTC timestamp, latitude, longitude, Course, Speed, Date, and fix status """ # UTC Timestamp try: utc_string = self.gps_segments[1] if utc_string: # Possible timestamp found hours = (int(utc_string[0:2]) + self.local_offset) % 24 minutes = int(utc_string[2:4]) seconds = float(utc_string[4:]) self.timestamp = (hours, minutes, seconds) else: # No Time stamp yet self.timestamp = (0, 0, 0) except ValueError: # Bad Timestamp value present return False # Date stamp try: date_string = self.gps_segments[9] # Date string printer function assumes to be year >=2000, # date_string() must be supplied with the correct century argument to display correctly if date_string: # Possible date stamp found day = int(date_string[0:2]) month = int(date_string[2:4]) year = int(date_string[4:6]) self.date = (day, month, year) else: # No Date stamp yet self.date = (0, 0, 0) except ValueError: # Bad Date stamp value present return False # Check Receiver Data Valid Flag if self.gps_segments[2] == 'A': # Data from Receiver is Valid/Has Fix # Longitude / Latitude try: # Latitude l_string = self.gps_segments[3] lat_degs = int(l_string[0:2]) lat_mins = float(l_string[2:]) lat_hemi = self.gps_segments[4] # Longitude l_string = self.gps_segments[5] lon_degs = int(l_string[0:3]) lon_mins = float(l_string[3:]) lon_hemi = self.gps_segments[6] except ValueError: return False if lat_hemi not in self.__HEMISPHERES: return False if lon_hemi not in self.__HEMISPHERES: return False # Speed try: spd_knt = float(self.gps_segments[7]) except ValueError: return False # Course try: if self.gps_segments[8]: course = float(self.gps_segments[8]) else: course = 0.0 except ValueError: return False # TODO - Add Magnetic Variation # Update Object Data self._latitude = [lat_degs, lat_mins, lat_hemi] self._longitude = [lon_degs, lon_mins, lon_hemi] # Include mph and hm/h self.speed = [spd_knt, spd_knt * 1.151, spd_knt * 1.852] self.course = course self.valid = True # Update Last Fix Time self.new_fix_time() else: # Clear Position Data if Sentence is 'Invalid' self._latitude = [0, 0.0, 'N'] self._longitude = [0, 0.0, 'W'] self.speed = [0.0, 0.0, 0.0] self.course = 0.0 self.valid = False return True def gpgll(self): """Parse Geographic Latitude and Longitude (GLL)Sentence. Updates UTC timestamp, latitude, longitude, and fix status""" # UTC Timestamp try: utc_string = self.gps_segments[5] if utc_string: # Possible timestamp found hours = (int(utc_string[0:2]) + self.local_offset) % 24 minutes = int(utc_string[2:4]) seconds = float(utc_string[4:]) self.timestamp = (hours, minutes, seconds) else: # No Time stamp yet self.timestamp = (0, 0, 0) except ValueError: # Bad Timestamp value present return False # Check Receiver Data Valid Flag if self.gps_segments[6] == 'A': # Data from Receiver is Valid/Has Fix # Longitude / Latitude try: # Latitude l_string = self.gps_segments[1] lat_degs = int(l_string[0:2]) lat_mins = float(l_string[2:]) lat_hemi = self.gps_segments[2] # Longitude l_string = self.gps_segments[3] lon_degs = int(l_string[0:3]) lon_mins = float(l_string[3:]) lon_hemi = self.gps_segments[4] except ValueError: return False if lat_hemi not in self.__HEMISPHERES: return False if lon_hemi not in self.__HEMISPHERES: return False # Update Object Data self._latitude = [lat_degs, lat_mins, lat_hemi] self._longitude = [lon_degs, lon_mins, lon_hemi] self.valid = True # Update Last Fix Time self.new_fix_time() else: # Clear Position Data if Sentence is 'Invalid' self._latitude = [0, 0.0, 'N'] self._longitude = [0, 0.0, 'W'] self.valid = False return True def gpvtg(self): """Parse Track Made Good and Ground Speed (VTG) Sentence. Updates speed and course""" try: course = float(self.gps_segments[1]) spd_knt = float(self.gps_segments[5]) except ValueError: return False # Include mph and km/h self.speed = (spd_knt, spd_knt * 1.151, spd_knt * 1.852) self.course = course return True def gpgga(self): """Parse Global Positioning System Fix Data (GGA) Sentence. Updates UTC timestamp, latitude, longitude, fix status, satellites in use, Horizontal Dilution of Precision (HDOP), altitude, geoid height and fix status""" try: # UTC Timestamp utc_string = self.gps_segments[1] # Skip timestamp if receiver doesn't have on yet if utc_string: hours = (int(utc_string[0:2]) + self.local_offset) % 24 minutes = int(utc_string[2:4]) seconds = float(utc_string[4:]) else: hours = 0 minutes = 0 seconds = 0.0 # Number of Satellites in Use satellites_in_use = int(self.gps_segments[7]) # Get Fix Status fix_stat = int(self.gps_segments[6]) except (ValueError, IndexError): return False try: # Horizontal Dilution of Precision hdop = float(self.gps_segments[8]) except (ValueError, IndexError): hdop = 0.0 # Process Location and Speed Data if Fix is GOOD if fix_stat: # Longitude / Latitude try: # Latitude l_string = self.gps_segments[2] lat_degs = int(l_string[0:2]) lat_mins = float(l_string[2:]) lat_hemi = self.gps_segments[3] # Longitude l_string = self.gps_segments[4] lon_degs = int(l_string[0:3]) lon_mins = float(l_string[3:]) lon_hemi = self.gps_segments[5] except ValueError: return False if lat_hemi not in self.__HEMISPHERES: return False if lon_hemi not in self.__HEMISPHERES: return False # Altitude / Height Above Geoid try: altitude = float(self.gps_segments[9]) geoid_height = float(self.gps_segments[11]) except ValueError: altitude = 0 geoid_height = 0 # Update Object Data self._latitude = [lat_degs, lat_mins, lat_hemi] self._longitude = [lon_degs, lon_mins, lon_hemi] self.altitude = altitude self.geoid_height = geoid_height # Update Object Data self.timestamp = [hours, minutes, seconds] self.satellites_in_use = satellites_in_use self.hdop = hdop self.fix_stat = fix_stat # If Fix is GOOD, update fix timestamp if fix_stat: self.new_fix_time() return True def gpgsa(self): """Parse GNSS DOP and Active Satellites (GSA) sentence. Updates GPS fix type, list of satellites used in fix calculation, Position Dilution of Precision (PDOP), Horizontal Dilution of Precision (HDOP), Vertical Dilution of Precision, and fix status""" # Fix Type (None,2D or 3D) try: fix_type = int(self.gps_segments[2]) except ValueError: return False # Read All (up to 12) Available PRN Satellite Numbers sats_used = [] for sats in range(12): sat_number_str = self.gps_segments[3 + sats] if sat_number_str: try: sat_number = int(sat_number_str) sats_used.append(sat_number) except ValueError: return False else: break # PDOP,HDOP,VDOP try: pdop = float(self.gps_segments[15]) hdop = float(self.gps_segments[16]) vdop = float(self.gps_segments[17]) except ValueError: return False # Update Object Data self.fix_type = fix_type # If Fix is GOOD, update fix timestamp if fix_type > self.__NO_FIX: self.new_fix_time() self.satellites_used = sats_used self.hdop = hdop self.vdop = vdop self.pdop = pdop return True def gpgsv(self): """Parse Satellites in View (GSV) sentence. Updates number of SV Sentences,the number of the last SV sentence parsed, and data on each satellite present in the sentence""" try: num_sv_sentences = int(self.gps_segments[1]) current_sv_sentence = int(self.gps_segments[2]) sats_in_view = int(self.gps_segments[3]) except ValueError: return False # Create a blank dict to store all the satellite data from this sentence in: # satellite PRN is key, tuple containing telemetry is value satellite_dict = dict() # Calculate Number of Satelites to pull data for and thus how many segment positions to read if num_sv_sentences == current_sv_sentence: # Last sentence may have 1-4 satellites; 5 - 20 positions sat_segment_limit = ( sats_in_view - ((num_sv_sentences - 1) * 4)) * 5 else: # Non-last sentences have 4 satellites and thus read up to position 20 sat_segment_limit = 20 # Try to recover data for up to 4 satellites in sentence for sats in range(4, sat_segment_limit, 4): # If a PRN is present, grab satellite data if self.gps_segments[sats]: try: sat_id = int(self.gps_segments[sats]) except (ValueError, IndexError): return False try: # elevation can be null (no value) when not tracking elevation = int(self.gps_segments[sats+1]) except (ValueError, IndexError): elevation = None try: # azimuth can be null (no value) when not tracking azimuth = int(self.gps_segments[sats+2]) except (ValueError, IndexError): azimuth = None try: # SNR can be null (no value) when not tracking snr = int(self.gps_segments[sats+3]) except (ValueError, IndexError): snr = None # If no PRN is found, then the sentence has no more satellites to read else: break # Add Satellite Data to Sentence Dict satellite_dict[sat_id] = (elevation, azimuth, snr) # Update Object Data self.total_sv_sentences = num_sv_sentences self.last_sv_sentence = current_sv_sentence self.satellites_in_view = sats_in_view # For a new set of sentences, we either clear out the existing sat data or # update it as additional SV sentences are parsed if current_sv_sentence == 1: self.satellite_data = satellite_dict else: self.satellite_data.update(satellite_dict) return True ########################################## # Data Stream Handler Functions ########################################## def new_sentence(self): """Adjust Object Flags in Preparation for a New Sentence""" self.gps_segments = [''] self.active_segment = 0 self.crc_xor = 0 self.sentence_active = True self.process_crc = True self.char_count = 0 def update(self, new_char): """Process a new input char and updates GPS object if necessary based on special characters ('$', ',', '*') Function builds a list of received string that are validate by CRC prior to parsing by the appropriate sentence function. Returns sentence type on successful parse, None otherwise""" valid_sentence = False # Validate new_char is a printable char ascii_char = ord(new_char) if 10 <= ascii_char <= 126: self.char_count += 1 # Write Character to log file if enabled if self.log_en: self.write_log(new_char) # Check if a new string is starting ($) if new_char == '$': self.new_sentence() return None elif self.sentence_active: # Check if sentence is ending (*) if new_char == '*': self.process_crc = False self.active_segment += 1 self.gps_segments.append('') return None # Check if a section is ended (,), Create a new substring to feed # characters to elif new_char == ',': self.active_segment += 1 self.gps_segments.append('') # Store All Other printable character and check CRC when ready else: self.gps_segments[self.active_segment] += new_char # When CRC input is disabled, sentence is nearly complete if not self.process_crc: if len(self.gps_segments[self.active_segment]) == 2: try: final_crc = int( self.gps_segments[self.active_segment], 16) if self.crc_xor == final_crc: valid_sentence = True else: self.crc_fails += 1 except ValueError: pass # CRC Value was deformed and could not have been correct # Update CRC if self.process_crc: self.crc_xor ^= ascii_char # If a Valid Sentence Was received and it's a supported sentence, then parse it!! if valid_sentence: self.clean_sentences += 1 # Increment clean sentences received self.sentence_active = False # Clear Active Processing Flag if self.gps_segments[0] in self.supported_sentences: # parse the Sentence Based on the message type, return True if parse is clean if self.supported_sentences[self.gps_segments[0]](self): # Let host know that the GPS object was updated by returning parsed sentence type self.parsed_sentences += 1 return self.gps_segments[0] # Check that the sentence buffer isn't filling up with Garage waiting for the sentence to complete if self.char_count > self.SENTENCE_LIMIT: self.sentence_active = False # Tell Host no new sentence was parsed return None def new_fix_time(self): """Updates a high resolution counter with current time when fix is updated. Currently only triggered from GGA, GSA and RMC sentences""" try: self.fix_time = utime.ticks_ms() except NameError: self.fix_time = time.time() ######################################### # User Helper Functions # These functions make working with the GPS object data easier ######################################### def satellite_data_updated(self): """ Checks if the all the GSV sentences in a group have been read, making satellite data complete :return: boolean """ if self.total_sv_sentences > 0 and self.total_sv_sentences == self.last_sv_sentence: return True else: return False def unset_satellite_data_updated(self): """ Mark GSV sentences as read indicating the data has been used and future updates are fresh """ self.last_sv_sentence = 0 def satellites_visible(self): """ Returns a list of of the satellite PRNs currently visible to the receiver :return: list """ return list(self.satellite_data.keys()) def time_since_fix(self): """Returns number of millisecond since the last sentence with a valid fix was parsed. Returns 0 if no fix has been found""" # Test if a Fix has been found if self.fix_time == 0: return -1 # Try calculating fix time using utime; if not running MicroPython # time.time() returns a floating point value in secs try: current = utime.ticks_diff(utime.ticks_ms(), self.fix_time) except NameError: current = (time.time() - self.fix_time) * 1000 # ms return current def compass_direction(self): """ Determine a cardinal or inter-cardinal direction based on current course. :return: string """ # Calculate the offset for a rotated compass if self.course >= 348.75: offset_course = 360 - self.course else: offset_course = self.course + 11.25 # Each compass point is separated by 22.5 degrees, divide to find lookup value dir_index = floor(offset_course / 22.5) final_dir = self.__DIRECTIONS[dir_index] return final_dir def latitude_string(self): """ Create a readable string of the current latitude data :return: string """ if self.coord_format == 'dd': formatted_latitude = self.latitude lat_string = str( formatted_latitude[0]) + '° ' + str(self._latitude[2]) elif self.coord_format == 'dms': formatted_latitude = self.latitude lat_string = str(formatted_latitude[0]) + '° ' + str(formatted_latitude[1]) + "' " + str( formatted_latitude[2]) + '" ' + str(formatted_latitude[3]) else: lat_string = str( self._latitude[0]) + '° ' + str(self._latitude[1]) + "' " + str(self._latitude[2]) return lat_string def longitude_string(self): """ Create a readable string of the current longitude data :return: string """ if self.coord_format == 'dd': formatted_longitude = self.longitude lon_string = str( formatted_longitude[0]) + '° ' + str(self._longitude[2]) elif self.coord_format == 'dms': formatted_longitude = self.longitude lon_string = str(formatted_longitude[0]) + '° ' + str(formatted_longitude[1]) + "' " + str( formatted_longitude[2]) + '" ' + str(formatted_longitude[3]) else: lon_string = str( self._longitude[0]) + '° ' + str(self._longitude[1]) + "' " + str(self._longitude[2]) return lon_string def speed_string(self, unit='kph'): """ Creates a readable string of the current speed data in one of three units :param unit: string of 'kph','mph, or 'knot' :return: """ if unit == 'mph': speed_string = str(self.speed[1]) + ' mph' elif unit == 'knot': if self.speed[0] == 1: unit_str = ' knot' else: unit_str = ' knots' speed_string = str(self.speed[0]) + unit_str else: speed_string = str(self.speed[2]) + ' km/h' return speed_string def date_string(self, formatting='s_mdy', century='20'): """ Creates a readable string of the current date. Can select between long format: Januray 1st, 2014 or two short formats: 11/01/2014 (MM/DD/YYYY) 01/11/2014 (DD/MM/YYYY) :param formatting: string 's_mdy', 's_dmy', or 'long' :param century: int delineating the century the GPS data is from (19 for 19XX, 20 for 20XX) :return: date_string string with long or short format date """ # Long Format Januray 1st, 2014 if formatting == 'long': # Retrieve Month string from private set month = self.__MONTHS[self.date[1] - 1] # Determine Date Suffix if self.date[0] in (1, 21, 31): suffix = 'st' elif self.date[0] in (2, 22): suffix = 'nd' elif self.date[0] == (3, 23): suffix = 'rd' else: suffix = 'th' day = str(self.date[0]) + suffix # Create Day String year = century + str(self.date[2]) # Create Year String date_string = month + ' ' + day + ', ' + year # Put it all together else: # Add leading zeros to day string if necessary if self.date[0] < 10: day = '0' + str(self.date[0]) else: day = str(self.date[0]) # Add leading zeros to month string if necessary if self.date[1] < 10: month = '0' + str(self.date[1]) else: month = str(self.date[1]) # Add leading zeros to year string if necessary if self.date[2] < 10: year = '0' + str(self.date[2]) else: year = str(self.date[2]) # Build final string based on desired formatting if formatting == 's_dmy': date_string = day + '/' + month + '/' + year else: # Default date format date_string = month + '/' + day + '/' + year return date_string # All the currently supported NMEA sentences supported_sentences = {'GPRMC': gprmc, 'GLRMC': gprmc, 'BDGSA': gpgsa, 'GPGGA': gpgga, 'GLGGA': gpgga, 'BDGSV': gpgsv, 'GPVTG': gpvtg, 'GLVTG': gpvtg, 'GPGSA': gpgsa, 'GLGSA': gpgsa, 'GPGSV': gpgsv, 'GLGSV': gpgsv, 'GPGLL': gpgll, 'GLGLL': gpgll, 'GNGGA': gpgga, 'GNRMC': gprmc, 'GNVTG': gpvtg, 'GNGLL': gpgll, 'GNGSA': gpgsa, } if __name__ == "__main__": pass
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/delivery_track/esp32/code/micropyGNSS.py
Python
apache-2.0
30,723
#!/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/detect_object/esp32/code/cloudAI.py
Python
apache-2.0
10,770
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : main.py @Description: 物体识别案例 @Author : 杭漂 @version : 1.0 ''' from aliyunIoT import Device import display # 显示库 import network # 网络库 import ucamera # 摄像头库 import utime # 延时函数在utime库中 import sntp # 网络时间同步库 import _thread # 线程库 import ujson as json from driver import GPIO # Wi-Fi SSID和Password设置 SSID='Your-AP-SSID' PWD='Your-AP-Password' # HaaS设备三元组 productKey = "Your-ProductKey" deviceName = "Your-devicename" deviceSecret = "Your-deviceSecret" detected = False gStartRecognize = 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, object, gStartRecognize detected = False object = 'NA' if commandReply == 'detectObjectReply' : if result != 'NA' : object = result detected = True else : print('unknown command reply') # 识别结束,复位识别标识符 gStartRecognize = False print('识别结束') # 按键检测 def key_event_thread(): global gStartRecognize,gpio,gFrame, engine print('启动按钮监控线程') status = -1 while True: if gStartRecognize == False : status = gpio.read() # 通过接入GND模拟按钮被按 if status == 0: print('按下拍照按钮') if gFrame != None : # 开始识别 gStartRecognize = True engine.detectObject(gFrame) utime.sleep_ms(1000) elif status < 0 : gStartRecognize == False utime.sleep_ms(1000) # 显示线程函数 def displayThread(): # 引用全局变量 global disp, gFrame, detected, num # 定义清屏局部变量 clearFlag = False # 定义显示文本局部变量 textShowFlag = False while True: # 采集摄像头画面 # print('start to capture') gFrame = ucamera.capture() # print('end to capture') if gFrame != None: if detected == True: # 清除屏幕内容 disp.clear() # 设置文字字体 disp.font(disp.FONT_DejaVu40) # 显示识别结果 disp.text(20, 100, 'Object Deteted!', disp.RED) utime.sleep_ms(1000) textShowFlag = False detected = False else: # 显示图像 # print('start to display') disp.image(0, 20, gFrame, 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, detected, engine, gStartRecognize, gpio # 创建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) # 初始化拍照按钮 gpio = GPIO() gpio.open("photoButton") try: # 启动显示线程 _thread.start_new_thread(displayThread, ()) # 设置比对线程stack _thread.stack_size(20 * 1024) # 启动按键监控线程 _thread.start_new_thread(key_event_thread, ()) 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/detect_object/esp32/code/main.py
Python
apache-2.0
5,123
import lvgl as lv RESOURCES_ROOT = "S:/data/pyamp/images/" class Airpressure: scr = None iconImg = None airpressureLable = None unityLabel = None tipLabel = None date = None def __init__(self, screen): self.scr = screen self.createAirpressureItem(self.scr, RESOURCES_ROOT + "airpressure.png", "Air pressure") def createAirpressureItem(self, parent, iconPath, tips): self.iconImg = lv.img(parent) self.iconImg.set_src(iconPath) self.iconImg.align(lv.ALIGN.TOP_LEFT, 0, 0) self.airpressureLable = lv.label(parent) self.airpressureLable.set_text("None") self.airpressureLable.set_style_text_color(lv.color_white(), 0) self.airpressureLable.set_style_text_font(lv.font_montserrat_48, 0) self.airpressureLable.align_to(self.iconImg, lv.ALIGN.OUT_RIGHT_TOP, 0, 0) self.unityLabel = lv.label(parent) self.unityLabel.set_text(" PA") self.unityLabel.set_style_text_color(lv.color_white(), 0) self.unityLabel.set_style_text_font(lv.font_montserrat_18, 0) self.unityLabel.align_to(self.airpressureLable, lv.ALIGN.OUT_RIGHT_BOTTOM, 0, -5) self.tipLabel = lv.label(parent) self.tipLabel.set_text(tips) self.tipLabel.set_style_text_color(lv.color_make(0xCC, 0xCC, 0xCC), 0) self.tipLabel.set_style_text_font(lv.font_montserrat_14, 0) self.tipLabel.align_to(self.airpressureLable, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 0) # 设置日期 self.date = lv.label(parent) self.date.align(lv.ALIGN.TOP_LEFT, 0, 0) self.date.set_style_text_color(lv.color_white(), 0) self.date.set_style_text_font(lv.font_montserrat_18, 0) def setValue(self, pressure): self.airpressureLable.set_text(str(int(pressure))) def setXY(self, x, y): self.iconImg.align(lv.ALIGN.TOP_LEFT, x, y) self.airpressureLable.align_to(self.iconImg, lv.ALIGN.OUT_RIGHT_TOP, 0, 0) self.unityLabel.align_to(self.airpressureLable, lv.ALIGN.OUT_RIGHT_BOTTOM, 0, -5) self.tipLabel.align_to(self.airpressureLable, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 0) def setScale(self, scale): print("To be done") def setDate(self, time): self.date.set_text("{}-{:0>2d}-{:0>2d} {:0>2d}:{:0>2d}:{:0>2d}"\ .format(time[0], time[1], time[2],time[3], time[4], time[5]))
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/ele_barometer/eduk1c/code/airpressure.py
Python
apache-2.0
2,401
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- import utime import page_airpressure if __name__ == '__main__': # 初始化气压计 page_airpressure.qmp6988_init() import display_driver # 显示气压值 page_airpressure.load_page() while True: utime.sleep(2)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/ele_barometer/eduk1c/code/main.py
Python
apache-2.0
297
import lvgl as lv from driver import I2C from qmp6988 import QMP6988 from airpressure import Airpressure import _thread import utime RESOURCES_ROOT = "S:/data/pyamp/images/" # 设备实例 i2cDev = None qmp6988Dev = None # 全局变量 pressure_value = 0 def qmp6988_init(): global i2cDev, qmp6988Dev i2cDev = I2C() i2cDev.open("qmp6988") qmp6988Dev = QMP6988(i2cDev) def qmp6988_deinit(): global i2cDev i2cDev.close() def th0(): global qmp6988Dev, pressure_value while True: pressure_value = qmp6988Dev.getPressure() utime.sleep(2) def th1(): global airPressureObj while True: time = utime.localtime() airPressureObj.setDate(time) utime.sleep_ms(900) def update_air_pressure(obj, x, y): global pressure_value obj.setValue(pressure_value) obj.setXY(x, y) def set_scale(obj, v): obj.setScale(v) def load_page(): global airPressureObj scr = lv.obj() scr.align(lv.ALIGN.TOP_LEFT, 0, 0) scr.set_style_bg_color(lv.color_black(), 0) airPressureObj = Airpressure(scr) # 动画 a1 = lv.anim_t() a1.init() a1.set_var(airPressureObj) a1.set_values(10, 80) a1.set_time(10000) a1.set_repeat_count(lv.ANIM_REPEAT.INFINITE) a1.set_custom_exec_cb(lambda a, val: update_air_pressure(airPressureObj, val, 2*val)) lv.anim_t.start(a1) try: th0_id = _thread.start_new_thread(th0, ()) th1_id = _thread.start_new_thread(th1, ()) except: print("Create new thread failed!") lv.scr_load(scr)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/ele_barometer/eduk1c/code/page_airpressure.py
Python
apache-2.0
1,569
""" Copyright (C) 2015-2021 Alibaba Group Holding Limited MicroPython's driver for QMP6988 Author: HaaS Date: 2021/09/14 """ from driver import I2C from utime import sleep_ms from micropython import const import math QMP6988_CALC_INT = 1 QMP6988_CHIP_ID = const(0x5C) QMP6988_CHIP_ID_REG = const(0xD1) QMP6988_RESET_REG = const(0xE0) # Device reset register QMP6988_DEVICE_STAT_REG = const(0xF3) # Device state register QMP6988_CTRLMEAS_REG = const(0xF4) # Measurement Condition Control Register # data QMP6988_PRESSURE_MSB_REG = const(0xF7) # Pressure MSB Register QMP6988_TEMPERATURE_MSB_REG = const(0xFA) # Temperature MSB Reg # compensation calculation QMP6988_CALIBRATION_DATA_START = const(0xA0) # QMP6988 compensation coefficients QMP6988_CALIBRATION_DATA_LENGTH = const(25) SHIFT_RIGHT_4_POSITION = const(4) SHIFT_LEFT_2_POSITION = const(2) SHIFT_LEFT_4_POSITION = const(4) SHIFT_LEFT_5_POSITION = const(5) SHIFT_LEFT_8_POSITION = const(8) SHIFT_LEFT_12_POSITION = const(12) SHIFT_LEFT_16_POSITION = const(16) # power mode QMP6988_SLEEP_MODE = const(0x00) QMP6988_FORCED_MODE = const(0x01) QMP6988_NORMAL_MODE = const(0x03) QMP6988_CTRLMEAS_REG_MODE__POS = const(0) QMP6988_CTRLMEAS_REG_MODE__MSK = const(0x03) QMP6988_CTRLMEAS_REG_MODE__LEN = const(2) # oversampling QMP6988_OVERSAMPLING_SKIPPED = const(0x00) QMP6988_OVERSAMPLING_1X = const(0x01) QMP6988_OVERSAMPLING_2X = const(0x02) QMP6988_OVERSAMPLING_4X = const(0x03) QMP6988_OVERSAMPLING_8X = const(0x04) QMP6988_OVERSAMPLING_16X = const(0x05) QMP6988_OVERSAMPLING_32X = const(0x06) QMP6988_OVERSAMPLING_64X = const(0x07) QMP6988_CTRLMEAS_REG_OSRST__POS = const(5) QMP6988_CTRLMEAS_REG_OSRST__MSK = const(0xE0) QMP6988_CTRLMEAS_REG_OSRST__LEN = const(3) QMP6988_CTRLMEAS_REG_OSRSP__POS = const(2) QMP6988_CTRLMEAS_REG_OSRSP__MSK = const(0x1C) QMP6988_CTRLMEAS_REG_OSRSP__LEN = const(3) # filter QMP6988_FILTERCOEFF_OFF = const(0x00) QMP6988_FILTERCOEFF_2 = const(0x01) QMP6988_FILTERCOEFF_4 = const(0x02) QMP6988_FILTERCOEFF_8 = const(0x03) QMP6988_FILTERCOEFF_16 = const(0x04) QMP6988_FILTERCOEFF_32 = const(0x05) QMP6988_CONFIG_REG = const(0xF1) #IIR filter co-efficient setting Register QMP6988_CONFIG_REG_FILTER__POS = const(0) QMP6988_CONFIG_REG_FILTER__MSK = const(0x07) QMP6988_CONFIG_REG_FILTER__LEN = const(3) SUBTRACTOR = const(8388608) qmp6988_dict = {'Ctemp': 0.0, 'Ftemp': 0.0,'pressure': 0.0, 'altitude': 0.0} class qmp6988Error(Exception): def __init__(self, value=0, msg="qmp6988 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 QMP6988(object): """ This class implements qmp6988 chip's defs. """ def __init__(self, i2cDev): self._i2cDev = None if not isinstance(i2cDev, I2C): raise ValueError("parameter is not an I2C object") # make QMP6988's internal object points to i2cDev self._i2cDev = i2cDev self.init() self.ik_a0 = 0 self.ik_b00 = 0 self.ik_a1 = 0 self.ik_a2 = 0 self.ik_bt1 = 0 self.ik_bt2 = 0 self.ik_bp1 = 0 self.ik_b11 = 0 self.ik_bp2 = 0 self.ik_b12 = 0 self.ik_b21 = 0 self.ik_bp3 = 0 self.fk_a0 = 0.0 self.fk_b00 = 0.0 self.fk_a1 = 0.0 self.fk_a2 = 0.0 self.fk_bt1 = 0.0 self.fk_bt2 = 0.0 self.fk_bp1 = 0.0 self.fk_b11 = 0.0 self.fk_bp2 = 0.0 self.fk_b12 = 0.0 self.fk_b21 = 0.0 self.fk_bp3 = 0.0 self.power_mode = 0 self.temperature = 0 self.init() def int16(self, dat): #return int(dat) if dat > 32767: return dat - 65536 else: return dat def int32(self, dat): #return int(dat) if dat > (1 << 31): return dat - (1 << 32) else: return dat def int64(self, dat): #return int(dat) if dat > (1 << 63): return dat - (1 << 64) else: return dat #写寄存器 def writeReg(self, addr, value): Reg = bytearray([addr, value]) self._i2cDev.write(Reg) #print("--> write addr " + hex(addr) + ", value = " + hex(value)) return 0 #读寄存器 def readReg(self, addr, len): Reg = bytearray([addr]) self._i2cDev.write(Reg) sleep_ms(2) tmp = bytearray(len) self._i2cDev.read(tmp) #print("<-- read addr " + hex(addr) + ", value = " + hex(tmp[0])) return tmp def deviceCheck(self): ret = self.readReg(QMP6988_CHIP_ID_REG, 1)[0] #print("qmp6988 read chip id = " + hex(ret)) if (ret == QMP6988_CHIP_ID): return 0 else: return 1 def getCalibrationData(self): if (QMP6988_CALC_INT): pass else: Conv_A_S = [[-6.30E-03, 4.30E-04], [-1.90E-11, 1.20E-10], [1.00E-01, 9.10E-02], [1.20E-08, 1.20E-06], [3.30E-02, 1.90E-02], [2.10E-07, 1.40E-07], [-6.30E-10, 3.50E-10], [2.90E-13, 7.60E-13], [2.10E-15, 1.20E-14], [1.30E-16, 7.90E-17]] a_data_u8r = bytearray(QMP6988_CALIBRATION_DATA_LENGTH) for len in range(QMP6988_CALIBRATION_DATA_LENGTH): a_data_u8r[len] = self.readReg(QMP6988_CALIBRATION_DATA_START + len, 1)[0] COE_a0 = self.int32(((a_data_u8r[18] << SHIFT_LEFT_12_POSITION) | (a_data_u8r[19] << SHIFT_LEFT_4_POSITION) | (a_data_u8r[24] & 0x0f)) << 12) COE_a0 = self.int32(COE_a0 >> SHIFT_LEFT_12_POSITION) COE_a1 = self.int16((a_data_u8r[20] << SHIFT_LEFT_8_POSITION) | a_data_u8r[21]) COE_a2 = self.int16((a_data_u8r[22] << SHIFT_LEFT_8_POSITION) | a_data_u8r[23]) COE_b00 = self.int32((a_data_u8r[0] << SHIFT_LEFT_12_POSITION) | (a_data_u8r[1] << SHIFT_LEFT_4_POSITION) | ((a_data_u8r[24] & 0xf0) >> SHIFT_RIGHT_4_POSITION)) << 12 COE_b00 = self.int32(COE_b00 >> SHIFT_LEFT_12_POSITION) COE_bt1 = self.int16((a_data_u8r[2] << SHIFT_LEFT_8_POSITION) | a_data_u8r[3]) COE_bt2 = self.int16((a_data_u8r[4] << SHIFT_LEFT_8_POSITION) | a_data_u8r[5]) COE_bp1 = self.int16((a_data_u8r[6] << SHIFT_LEFT_8_POSITION) | a_data_u8r[7]) COE_b11 = self.int16((a_data_u8r[8] << SHIFT_LEFT_8_POSITION) | a_data_u8r[9]) COE_bp2 = self.int16((a_data_u8r[10] << SHIFT_LEFT_8_POSITION) | a_data_u8r[11]) COE_b12 = self.int16((a_data_u8r[12] << SHIFT_LEFT_8_POSITION) | a_data_u8r[13]) COE_b21 = self.int16((a_data_u8r[14] << SHIFT_LEFT_8_POSITION) | a_data_u8r[15]) COE_bp3 = self.int16((a_data_u8r[16] << SHIFT_LEFT_8_POSITION) | a_data_u8r[17]) """" print("<-----------calibration data-------------->") print("COE_a0[%d] COE_a1[%d] COE_a2[%d] COE_b00[%d]" %(COE_a0, COE_a1, COE_a2, COE_b00)) print("COE_bt1[%d] COE_bt2[%d] COE_bp1[%d] COE_b11[%d]" %(COE_bt1, COE_bt2, COE_bp1, COE_b11)) print("COE_bp2[%d] COE_b12[%d] COE_b21[%d] COE_bp3[%d]" %(COE_bp2, COE_b12, COE_b21, COE_bp3)) print("<-----------calibration data-------------->") """ if (QMP6988_CALC_INT): self.ik_a0 = COE_a0 # 20Q4 self.ik_b00 = COE_b00 # 20Q4 self.ik_a1 = self.int32(3608 * (COE_a1) - 1731677965) # 31Q23 self.ik_a2 = self.int32(16889 * (COE_a2) - 87619360) # 30Q47 self.ik_bt1 = self.int64(2982 * (COE_bt1) + 107370906) # 28Q15 self.ik_bt2 = self.int64(329854 * (COE_bt2) + 108083093) # 34Q38 self.ik_bp1 = self.int64(19923 * (COE_bp1) + 1133836764) # 31Q20 self.ik_b11 = self.int64(2406 * (COE_b11) + 118215883) # 28Q34 self.ik_bp2 = self.int64(3079 * (COE_bp2) - 181579595) # 29Q43 self.ik_b12 = self.int64(6846 * (COE_b12) + 85590281) # 29Q53 self.ik_b21 = self.int64(13836 * (COE_b21) + 79333336) # 29Q60 self.ik_bp3 = self.int64(2915 * (COE_bp3) + 157155561) # 28Q65 """ print("<----------- int calibration data -------------->") print("a0[%d] a1[%d] a2[%d] b00[%d]" %(self.ik_a0, self.ik_a1, self.ik_a2, self.ik_b00)) print("bt1[%d] bt2[%d] bp1[%d] b11[%d]" %(self.ik_bt1, self.ik_bt2, self.ik_bp1, self.ik_b11)) print("bp2[%d] b12[%d] b21[%d] bp3[%d]" %(self.ik_bp2, self.ik_b12, self.ik_b21, self.ik_bp3)) print("<----------- int calibration data -------------->") """ else: self.fk_a0 = COE_a0 / 16.0 self.fk_b00 = COE_b00 / 16.0 self.fk_a1 = Conv_A_S[0][0] + Conv_A_S[0][1] * COE_a1 / 32767.0 self.fk_a2 = Conv_A_S[1][0] + Conv_A_S[1][1] * COE_a2 / 32767.0 self.fk_bt1 = Conv_A_S[2][0] + Conv_A_S[2][1] * COE_bt1 / 32767.0 self.fk_bt2 = Conv_A_S[3][0] + Conv_A_S[3][1] * COE_bt2 / 32767.0 self.fk_bp1 = Conv_A_S[4][0] + Conv_A_S[4][1] * COE_bp1 / 32767.0 self.fk_b11 = Conv_A_S[5][0] + Conv_A_S[5][1] * COE_b11 / 32767.0 self.fk_bp2 = Conv_A_S[6][0] + Conv_A_S[6][1] * COE_bp2 / 32767.0 self.fk_b12 = Conv_A_S[7][0] + Conv_A_S[7][1] * COE_b12 / 32767.0 self.fk_b21 = Conv_A_S[8][0] + Conv_A_S[8][1] * COE_b21 / 32767.0 self.fk_bp3 = Conv_A_S[9][0] + Conv_A_S[9][1] * COE_bp3 / 32767.0 def convTx02e(self, dt): if (QMP6988_CALC_INT): wk1 = self.int64((self.ik_a1) * (dt)) # 31Q23+24-1=54 (54Q23) wk2 = self.int64(((self.ik_a2) * (dt)) >> 14) # 30Q47+24-1=53 (39Q33) wk2 = self.int64((wk2 * (dt)) >> 10) # 39Q33+24-1=62 (52Q23) wk2 = self.int64(((wk1 + wk2) // 32767) >> 19) # 54,52->55Q23 (20Q04) ret = self.int16((self.ik_a0 + wk2) >> 4) # 21Q4 -> 17Q0 return ret else: pass def getPressure02e(self, dp, tx): if (QMP6988_CALC_INT): wk1 = ((self.ik_bt1) * (tx)) # 28Q15+16-1=43 (43Q15) wk2 = self.int64((self.ik_bp1 * (dp)) >> 5) # 31Q20+24-1=54 (49Q15) wk1 += wk2 # 43,49->50Q15 wk2 = self.int64(((self.ik_bt2) * (tx)) >> 1) # 34Q38+16-1=49 (48Q37) wk2 = self.int64((wk2 * self.int64(tx)) >> 8) # 48Q37+16-1=63 (55Q29) wk3 = wk2 # 55Q29 wk2 = self.int64(((self.ik_b11) * (tx)) >> 4) # 28Q34+16-1=43 (39Q30) wk2 = self.int64((wk2 * (dp)) >> 1) # 39Q30+24-1=62 (61Q29) wk3 += wk2 # 55,61->62Q29 wk2 = self.int64(((self.ik_bp2) * (dp)) >> 13) # 29Q43+24-1=52 (39Q30) wk2 = self.int64((wk2 * (dp)) >> 1) # 39Q30+24-1=62 (61Q29) wk3 += wk2 # 62,61->63Q29 wk1 += self.int64(wk3 >> 14) # Q29 >> 14 -> Q15 wk2 = ((self.ik_b12) * (tx)) # 29Q53+16-1=45 (45Q53) wk2 = (wk2 * (tx)) >> 22 # 45Q53+16-1=61 (39Q31) wk2 = (wk2 * (dp)) > 1 # 39Q31+24-1=62 (61Q30) wk3 = wk2 # 61Q30 wk2 = (self.int64(self.ik_b21) * (tx)) >> 6 # 29Q60+16-1=45 (39Q54) wk2 = self.int64((wk2 * (dp)) >> 23) # 39Q54+24-1=62 (39Q31) wk2 = self.int64((wk2 * self.int64(dp)) >> 1) # 39Q31+24-1=62 (61Q20) wk3 += wk2 # 61,61->62Q30 wk2 = self.int64(((self.ik_bp3) * (dp)) >> 12) # 28Q65+24-1=51 (39Q53) wk2 = self.int64((wk2 * (dp)) >> 23) # 39Q53+24-1=62 (39Q30) wk2 = (wk2 * (dp)) # 39Q30+24-1=62 (62Q30) wk3 += wk2 # 62,62->63Q30 wk1 += self.int64(wk3 >> 15) # Q30 >> 15 = Q15 wk1 = self.int64(wk1 // 32767) wk1 = self.int64(wk1 >> 11) # Q15 >> 7 = Q4 wk1 += self.ik_b00 # Q4 + 20Q4 # wk1 >>= 4 # 28Q4 -> 24Q0 ret = self.int32(wk1) # print("wk1[%d] wk2[%d] ret[%d]" %(wk1, wk2, ret)) return ret else: pass def softwareReset(self): pass def setPowermode(self, power_mode): # print("qmp_set_powermode ") self.power_mode = power_mode data = self.readReg(QMP6988_CTRLMEAS_REG,1)[0] data = data & 0xfc if (power_mode == QMP6988_SLEEP_MODE): data |= 0x00 elif (power_mode == QMP6988_FORCED_MODE): data |= 0x01 elif (power_mode == QMP6988_NORMAL_MODE): data |= 0x03 self.writeReg(QMP6988_CTRLMEAS_REG, data) # print("qmp_set_powermode 0xf4=0x", data) sleep_ms(20) def setFilter(self, filter): data = (filter & 0x03) self.writeReg(QMP6988_CONFIG_REG, data) sleep_ms(20) def setOversamplingP(self, oversampling_p): data = self.readReg(QMP6988_CTRLMEAS_REG, 1)[0] data &= 0xe3 data |= self.int16(oversampling_p << 2) self.writeReg(QMP6988_CTRLMEAS_REG, data) sleep_ms(20) def setOversamplingT(self, oversampling_t): data = self.readReg(QMP6988_CTRLMEAS_REG, 1)[0] data &= 0x1f data |= self.int16(oversampling_t << 5) self.writeReg(QMP6988_CTRLMEAS_REG, data) sleep_ms(20) def calcAltitude(self, pressure, temp): altitude = (pow((101325 / pressure), 1 / 5.257) - 1) * (temp + 273.15) / 0.0065 return altitude def getData(self): global qmp6988_dict a_data_u8r = bytearray(6) # press a_data_u8r = self.readReg(QMP6988_PRESSURE_MSB_REG, 6) P_read = (a_data_u8r[0] << SHIFT_LEFT_16_POSITION) | (a_data_u8r[1] << SHIFT_LEFT_8_POSITION) | (a_data_u8r[2]) P_raw = self.int32(P_read - SUBTRACTOR) T_read = (a_data_u8r[3] << SHIFT_LEFT_16_POSITION) | (a_data_u8r[4] << SHIFT_LEFT_8_POSITION) | (a_data_u8r[5]) T_raw = self.int32(T_read - SUBTRACTOR) if (QMP6988_CALC_INT): T_int = self.convTx02e(T_raw) P_int = self.getPressure02e(P_raw, T_int) #self.temperature = float(T_int) / 256.0 Ctemp = float(T_int) / 256.0 Ftemp = (Ctemp * 9 / 5) + 32 Ftemp = round(Ftemp,2) #self.pressure = float(P_int) / 16.0 qmp6988_dict['Ctemp'] = Ctemp qmp6988_dict['Ftemp'] = Ftemp qmp6988_dict['pressure'] = float(P_int) / 16.0 #print("int temp = %f Pressure = %f " %(self.temperature, self.pressure)) else: Tr = self.fk_a0 + (self.fk_a1 * T_raw) + (self.fk_a2 * T_raw) *T_raw # Unit centigrade #self.temperature = float(Tr) / 256.0 qmp6988_dict['Ctemp'] = float(Tr) / 256.0 # compensation pressure, Unit Pa qmp6988_dict['pressure'] = self.fk_b00 + (self.fk_bt1 * Tr) + (self.fk_bp1 * P_raw) + (self.fk_b11 * Tr) *P_raw + (self.fk_bt2 * Tr) *Tr + (self.fk_bp2 * P_raw) *P_raw + (self.fk_b12 * P_raw) *(Tr *Tr) + (self.fk_b21 * P_raw) *(P_raw *Tr) + (self.fk_bp3 * P_raw) *(P_raw *P_raw) #print("float temp = %f Pressure = %f" %(self.temperature, self.pressure)) qmp6988_dict['altitude'] = self.calcAltitude(qmp6988_dict['pressure'], qmp6988_dict['Ctemp']) #print("altitude = ",self.altitude) return qmp6988_dict def getTemperature(self): return self.getData()['Ctemp'] def getTemperatureF(self): return self.getData()['Ftemp'] def getPressure(self): return self.getData()['pressure'] def getAltitude(self): return self.getData()['altitude'] def init(self): ret = self.deviceCheck() if (ret != 0): return 0 else: pass self.softwareReset() self.getCalibrationData() self.setPowermode(QMP6988_NORMAL_MODE) self.setFilter(QMP6988_FILTERCOEFF_OFF) self.setOversamplingP(QMP6988_OVERSAMPLING_2X) self.setOversamplingT(QMP6988_OVERSAMPLING_1X) if __name__ == "__main__": ''' The below i2c configuration is needed in your board.json. "qmp6988": { "type": "I2C", "port": 1, "addrWidth": 7, "freq": 100000, "mode": "master", "devAddr": 86 } ''' print("Testing qmp6988 ...") i2cDev = I2C() i2cDev.open("qmp6988") baroDev = QMC6988(i2cDev) pressure = baroDev.getPressure() print("pressure:%f" % (pressure)) i2cDev.close() del baroDev i2cDev.close() print("Test qmp6988 done!")
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/ele_barometer/eduk1c/code/qmp6988.py
Python
apache-2.0
16,991
"""2.9 inch E-paper display black/red version 2.""" from math import cos, sin, pi, radians from micropython import const from framebuf import FrameBuffer, GS8, MONO_HLSB, MONO_HMSB from utime import sleep_ms class Display(object): """Serial interface for 2.9 inch E-paper display. Note: All coordinates are zero based. """ # Command constants from display datasheet PANEL_SETTING = const(0x00) POWER_OFF = const(0x02) POWER_ON = const(0x04) DEEP_SLEEP = const(0x07) DATA_START_TRANSMISSION_1 = const(0x10) DISPLAY_REFRESH = const(0x12) DATA_START_TRANSMISSION_2 = const(0x13) VCOM_AND_DATA_INTERVAL_SETTING = const(0x50) TCON_RESOLUTION = const(0x61) GET_STATUS = const(0x71) def __init__(self, spi, cs, dc, rst, busy, width=128, height=296): """Constructor for Display. Args: spi (Class Spi): SPI interface for display cs (Class Pin): Chip select pin dc (Class Pin): Data/Command pin rst (Class Pin): Reset pin busy (Class Pin): Busy pin width (Optional int): Screen width (default 128) height (Optional int): Screen height (default 296) """ self.spi = spi self.cs = cs self.dc = dc self.rst = rst self.busy = busy self.width = width self.height = height self.byte_width = -(-width // 8) # Ceiling division self.buffer_length = self.byte_width * height # Buffers (black image and red or yellow image) self.blackimage = bytearray(self.buffer_length) self.ryimage = bytearray(self.buffer_length) # Frame Buffers (black image and red or yellow image) self.blackFB = FrameBuffer(self.blackimage, width, height, MONO_HLSB) self.ryFB = FrameBuffer(self.ryimage, width, height, MONO_HLSB) self.clear_buffers() # Initialize GPIO pins self.cs.init(self.cs.OUT, value=1) self.dc.init(self.dc.OUT, value=0) self.rst.init(self.rst.OUT, value=1) self.busy.init(self.busy.IN) self.reset() # Send initialization commands self.write_cmd(self.POWER_ON) self.ReadBusy() # Wait for display to indicate idle self.write_cmd(self.PANEL_SETTING, 0x0F, 0x89) self.write_cmd(self.TCON_RESOLUTION, 0x80, 0x01, 0x28) self.write_cmd(self.VCOM_AND_DATA_INTERVAL_SETTING, 0x77) def cleanup(self): """Clean up resources.""" self.clear() self.sleep() # self.spi.deinit() self.spi.close() print('display off') def clear(self, red=True, black=True): """Clear display. Args: red (bool): True (default) = clear red black (bool): True (default) = clear black """ self.ReadBusy() self.clear_buffers(red, black) self.present(red, black) self.write_cmd(self.DISPLAY_REFRESH) sleep_ms(200) self.ReadBusy() def clear_buffers(self, red=True, black=True): """Clear buffer. Args: red (bool): True (default) = clear red buffer black (bool): True (default) = clear black buffer """ if red: self.ryFB.fill(0xFF) if black: self.blackFB.fill(0xFF) def draw_bitmap(self, x, y, w, h, path='', bytebuf=bytearray(b''), red=False, invert=False, rotate=0): """Load MONO_HMSB bitmap from disc and draw to screen. Args: path (string): Image file path. x (int): x-coord of image. y (int): y-coord of image. w (int): Width of image. h (int): Height of image. red (bool): True = red image, False (Default) = black image. invert (bool): True = invert image, False (Default) = normal image. rotate(int): 0, 90, 180, 270 Notes: w x h cannot exceed 2048 """ if path == '' and bytebuf == bytearray(b''): return array_size = w * h buf = bytearray(b'') if path != '': with open(path, "rb") as f: buf = bytearray(f.read(array_size)) else: buf = bytebuf fb = FrameBuffer(buf, w, h, MONO_HMSB) if rotate == 0 and invert is True: # 0 degrees fb2 = FrameBuffer(bytearray(array_size), w, h, MONO_HMSB) for y1 in range(h): for x1 in range(w): fb2.pixel(x1, y1, fb.pixel(x1, y1) ^ 0x01) fb = fb2 elif rotate == 90: # 90 degrees byte_width = (w - 1) // 8 + 1 adj_size = h * byte_width fb2 = FrameBuffer(bytearray(adj_size), h, w, MONO_HMSB) for y1 in range(h): for x1 in range(w): if invert is True: fb2.pixel(y1, x1, fb.pixel(x1, (h - 1) - y1) ^ 0x01) else: fb2.pixel(y1, x1, fb.pixel(x1, (h - 1) - y1)) fb = fb2 elif rotate == 180: # 180 degrees fb2 = FrameBuffer(bytearray(array_size), w, h, MONO_HMSB) for y1 in range(h): for x1 in range(w): if invert is True: fb2.pixel(x1, y1, fb.pixel((w - 1) - x1, (h - 1) - y1) ^ 0x01) else: fb2.pixel(x1, y1, fb.pixel((w - 1) - x1, (h - 1) - y1)) fb = fb2 elif rotate == 270: # 270 degrees byte_width = (w - 1) // 8 + 1 adj_size = h * byte_width fb2 = FrameBuffer(bytearray(adj_size), h, w, MONO_HMSB) for y1 in range(h): for x1 in range(w): if invert is True: fb2.pixel(y1, x1, fb.pixel((w - 1) - x1, y1) ^ 0x01) else: fb2.pixel(y1, x1, fb.pixel((w - 1) - x1, y1)) fb = fb2 if red: self.ryFB.blit(fb, x, y) else: self.blackFB.blit(fb, x, y) def draw_bitmap_raw(self, path, x, y, w, h, red=False, invert=False, rotate=0): """Load raw bitmap from disc and draw to screen. Args: path (string): Image file path. x (int): x-coord of image. y (int): y-coord of image. w (int): Width of image. h (int): Height of image. red (bool): True = red image, False (Default) = black image. invert (bool): True = invert image, False (Default) = normal image. rotate(int): 0, 90, 180, 270 Notes: w x h cannot exceed 2048 """ if rotate == 90 or rotate == 270: w, h = h, w # Swap width & height if landscape buf_size = w * h with open(path, "rb") as f: if rotate == 0: buf = bytearray(f.read(buf_size)) elif rotate == 90: buf = bytearray(buf_size) for x1 in range(w - 1, -1, -1): for y1 in range(h): index = (w * y1) + x1 buf[index] = f.read(1)[0] elif rotate == 180: buf = bytearray(buf_size) for index in range(buf_size - 1, -1, -1): buf[index] = f.read(1)[0] elif rotate == 270: buf = bytearray(buf_size) for x1 in range(1, w + 1): for y1 in range(h - 1, -1, -1): index = (w * y1) + x1 - 1 buf[index] = f.read(1)[0] if invert: for i, _ in enumerate(buf): buf[i] ^= 0xFF fbuf = FrameBuffer(buf, w, h, GS8) if red: self.ryFB.blit(fbuf, x, y) else: self.blackFB.blit(fbuf, x, y) def draw_circle(self, x0, y0, r, red=False, invert=False): """Draw a circle. Args: x0 (int): X coordinate of center point. y0 (int): Y coordinate of center point. r (int): Radius. red (bool): True = red line, False (Default) = black line. invert (bool): True = clear line, False (Default) = draw line. """ f = 1 - r dx = 1 dy = -r - r x = 0 y = r self.draw_pixel(x0, y0 + r, red, invert) self.draw_pixel(x0, y0 - r, red, invert) self.draw_pixel(x0 + r, y0, red, invert) self.draw_pixel(x0 - r, y0, red, invert) while x < y: if f >= 0: y -= 1 dy += 2 f += dy x += 1 dx += 2 f += dx self.draw_pixel(x0 + x, y0 + y, red, invert) self.draw_pixel(x0 - x, y0 + y, red, invert) self.draw_pixel(x0 + x, y0 - y, red, invert) self.draw_pixel(x0 - x, y0 - y, red, invert) self.draw_pixel(x0 + y, y0 + x, red, invert) self.draw_pixel(x0 - y, y0 + x, red, invert) self.draw_pixel(x0 + y, y0 - x, red, invert) self.draw_pixel(x0 - y, y0 - x, red, invert) def draw_ellipse(self, x0, y0, a, b, red=False, invert=False): """Draw an ellipse. Args: x0, y0 (int): Coordinates of center point. a (int): Semi axis horizontal. b (int): Semi axis vertical. red (bool): True = red line, False (Default) = black line. invert (bool): True = clear line, False (Default) = draw line. Note: The center point is the center of the x0,y0 pixel. Since pixels are not divisible, the axes are integer rounded up to complete on a full pixel. Therefore the major and minor axes are increased by 1. """ a2 = a * a b2 = b * b twoa2 = a2 + a2 twob2 = b2 + b2 x = 0 y = b px = 0 py = twoa2 * y # Plot initial points self.draw_pixel(x0 + x, y0 + y, red, invert) self.draw_pixel(x0 - x, y0 + y, red, invert) self.draw_pixel(x0 + x, y0 - y, red, invert) self.draw_pixel(x0 - x, y0 - y, red, invert) # Region 1 p = round(b2 - (a2 * b) + (0.25 * a2)) while px < py: x += 1 px += twob2 if p < 0: p += b2 + px else: y -= 1 py -= twoa2 p += b2 + px - py self.draw_pixel(x0 + x, y0 + y, red, invert) self.draw_pixel(x0 - x, y0 + y, red, invert) self.draw_pixel(x0 + x, y0 - y, red, invert) self.draw_pixel(x0 - x, y0 - y, red, invert) # Region 2 p = round(b2 * (x + 0.5) * (x + 0.5) + a2 * (y - 1) * (y - 1) - a2 * b2) while y > 0: y -= 1 py -= twoa2 if p > 0: p += a2 - py else: x += 1 px += twob2 p += a2 - py + px self.draw_pixel(x0 + x, y0 + y, red, invert) self.draw_pixel(x0 - x, y0 + y, red, invert) self.draw_pixel(x0 + x, y0 - y, red, invert) self.draw_pixel(x0 - x, y0 - y, red, invert) def draw_hline(self, x, y, w, red=False, invert=False): """Draw a horizontal line. Args: x (int): Starting X position. y (int): Starting Y position. w (int): Width of line. red (bool): True = red line, False (Default) = black line. invert (bool): True = clear line, False (Default) = draw line. """ if self.is_off_grid(x, y, x + w - 1, y): return if red: self.ryFB.hline(x, y, w, int(invert)) else: self.blackFB.hline(x, y, w, int(invert)) def draw_letter(self, x, y, letter, font, red=False, invert=False, rotate=False): """Draw a letter. Args: x (int): Starting X position. y (int): Starting Y position. letter (string): Letter to draw. font (XglcdFont object): Font. red (bool): True = red font, False (Default) = black font invert (bool): Invert color rotate (int): Rotation of letter """ fbuf, w, h = font.get_letter(letter, invert=invert, rotate=rotate) # Check for errors if w == 0: return w, h # Offset y for 270 degrees and x for 180 degrees if rotate == 180: x -= w elif rotate == 270: y -= h if red: self.ryFB.blit(fbuf, x, y) else: self.blackFB.blit(fbuf, x, y) return w, h def draw_line(self, x1, y1, x2, y2, red=False, invert=False): """Draw a line using Bresenham's algorithm. Args: x1, y1 (int): Starting coordinates of the line x2, y2 (int): Ending coordinates of the line red (bool): True = red line, False (Default) = black line. invert (bool): True = clear line, False (Default) = draw line. """ # Check for horizontal line if y1 == y2: if x1 > x2: x1, x2 = x2, x1 self.draw_hline(x1, y1, x2 - x1 + 1, red, invert) return # Check for vertical line if x1 == x2: if y1 > y2: y1, y2 = y2, y1 self.draw_vline(x1, y1, y2 - y1 + 1, red, invert) return # Confirm coordinates in boundary if self.is_off_grid(min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2)): return if red: self.ryFB.line(x1, y1, x2, y2, int(invert)) else: self.blackFB.line(x1, y1, x2, y2, int(invert)) def draw_lines(self, coords, red=False, invert=False): """Draw multiple lines. Args: coords ([[int, int],...]): Line coordinate X, Y pairs red (bool): True = red line, False (Default) = black line. invert (bool): True = clear line, False (Default) = draw line. """ # Starting point x1, y1 = coords[0] # Iterate through coordinates for i in range(1, len(coords)): x2, y2 = coords[i] self.draw_line(x1, y1, x2, y2, red, invert) x1, y1 = x2, y2 def draw_pixel(self, x, y, red=False, invert=False): """Draw a single pixel. Args: x (int): X position. y (int): Y position. red (bool): True = red line, False (Default) = black line. invert (bool): True = clear line, False (Default) = draw line. """ if self.is_off_grid(x, y, x, y): return if red: self.ryFB.pixel(x, y, int(invert)) else: self.blackFB.pixel(x, y, int(invert)) def draw_polygon(self, sides, x0, y0, r, red=False, invert=False, rotate=0): """Draw an n-sided regular polygon. Args: sides (int): Number of polygon sides. x0, y0 (int): Coordinates of center point. r (int): Radius. red (bool): True = red line, False (Default) = black line. invert (bool): True = clear line, False (Default) = draw line. rotate (Optional float): Rotation in degrees relative to origin. Note: The center point is the center of the x0,y0 pixel. Since pixels are not divisible, the radius is integer rounded up to complete on a full pixel. Therefore diameter = 2 x r + 1. """ coords = [] theta = radians(rotate) n = sides + 1 for s in range(n): t = 2.0 * pi * s / sides + theta coords.append([int(r * cos(t) + x0), int(r * sin(t) + y0)]) # Cast to python float first to fix rounding errors self.draw_lines(coords, red, invert) def draw_rectangle(self, x, y, w, h, red=False, invert=False): """Draw a rectangle. Args: x (int): Starting X position. y (int): Starting Y position. w (int): Width of rectangle. h (int): Height of rectangle. red (bool): True = red line, False (Default) = black line. invert (bool): True = clear line, False (Default) = draw line. """ if red: self.ryFB.rect(x, y, w, h, int(invert)) else: self.blackFB.rect(x, y, w, h, int(invert)) def draw_text(self, x, y, text, font, red=False, invert=False, rotate=0, spacing=1): """Draw text. Args: x (int): Starting X position. y (int): Starting Y position. text (string): Text to draw. font (XglcdFont object): Font. red (bool): True = red font, False (Default) = black font invert (bool): Invert color rotate (int): Rotation of letter spacing (int): Pixels between letters (default: 1) """ for letter in text: # Get letter array and letter dimensions w, h = self.draw_letter(x, y, letter, font, red, invert, rotate) # Stop on error if w == 0 or h == 0: return if rotate == 0: # Fill in spacing if spacing: self.fill_rectangle(x + w, y, spacing, h, red, not invert) # Position x for next letter x += (w + spacing) elif rotate == 90: # Fill in spacing if spacing: self.fill_rectangle(x, y + h, w, spacing, red, not invert) # Position y for next letter y += (h + spacing) elif rotate == 180: # Fill in spacing if spacing: self.fill_rectangle(x - w - spacing, y, spacing, h, red, not invert) # Position x for next letter x -= (w + spacing) elif rotate == 270: # Fill in spacing if spacing: self.fill_rectangle(x, y - h - spacing, w, spacing, red, not invert) # Position y for next letter y -= (h + spacing) else: print("Invalid rotation.") return def draw_vline(self, x, y, h, red=False, invert=False): """Draw a vertical line. Args: x (int): Starting X position. y (int): Starting Y position. h (int): Height of line. red (bool): True = red line, False (Default) = black line. invert (bool): True = clear line, False (Default) = draw line. """ # Confirm coordinates in boundary if self.is_off_grid(x, y, x, y + h): return if red: self.ryFB.vline(x, y, h, int(invert)) else: self.blackFB.vline(x, y, h, int(invert)) def fill_circle(self, x0, y0, r, red=False, invert=False): """Draw a filled circle. Args: x0 (int): X coordinate of center point. y0 (int): Y coordinate of center point. r (int): Radius. red (bool): True = red line, False (Default) = black line. invert (bool): True = clear line, False (Default) = draw line. """ f = 1 - r dx = 1 dy = -r - r x = 0 y = r self.draw_vline(x0, y0 - r, 2 * r + 1, red, invert) while x < y: if f >= 0: y -= 1 dy += 2 f += dy x += 1 dx += 2 f += dx self.draw_vline(x0 + x, y0 - y, 2 * y + 1, red, invert) self.draw_vline(x0 - x, y0 - y, 2 * y + 1, red, invert) self.draw_vline(x0 - y, y0 - x, 2 * x + 1, red, invert) self.draw_vline(x0 + y, y0 - x, 2 * x + 1, red, invert) def fill_ellipse(self, x0, y0, a, b, red=False, invert=False): """Draw a filled ellipse. Args: x0, y0 (int): Coordinates of center point. a (int): Semi axis horizontal. b (int): Semi axis vertical. red (bool): True = red line, False (Default) = black line. invert (bool): True = clear line, False (Default) = draw line. Note: The center point is the center of the x0,y0 pixel. Since pixels are not divisible, the axes are integer rounded up to complete on a full pixel. Therefore the major and minor axes are increased by 1. """ a2 = a * a b2 = b * b twoa2 = a2 + a2 twob2 = b2 + b2 x = 0 y = b px = 0 py = twoa2 * y # Plot initial points self.draw_line(x0, y0 - y, x0, y0 + y, red, invert) # Region 1 p = round(b2 - (a2 * b) + (0.25 * a2)) while px < py: x += 1 px += twob2 if p < 0: p += b2 + px else: y -= 1 py -= twoa2 p += b2 + px - py self.draw_line(x0 + x, y0 - y, x0 + x, y0 + y, red, invert) self.draw_line(x0 - x, y0 - y, x0 - x, y0 + y, red, invert) # Region 2 p = round(b2 * (x + 0.5) * (x + 0.5) + a2 * (y - 1) * (y - 1) - a2 * b2) while y > 0: y -= 1 py -= twoa2 if p > 0: p += a2 - py else: x += 1 px += twob2 p += a2 - py + px self.draw_line(x0 + x, y0 - y, x0 + x, y0 + y, red, invert) self.draw_line(x0 - x, y0 - y, x0 - x, y0 + y, red, invert) def fill_rectangle(self, x, y, w, h, red=False, invert=False): """Draw a filled rectangle. Args: x (int): Starting X position. y (int): Starting Y position. w (int): Width of rectangle. h (int): Height of rectangle. red (bool): True = red line, False (Default) = black line. visble (bool): True (Default) = draw line, False = clear line. """ if self.is_off_grid(x, y, x + w - 1, y + h - 1): return if red: self.ryFB.fill_rect(x, y, w, h, int(invert)) else: self.blackFB.fill_rect(x, y, w, h, int(invert)) def fill_polygon(self, sides, x0, y0, r, red=False, invert=False, rotate=0): """Draw a filled n-sided regular polygon. Args: sides (int): Number of polygon sides. x0, y0 (int): Coordinates of center point. r (int): Radius. red (bool): True = red line, False (Default) = black line. visble (bool): True (Default) = draw line, False = clear line. rotate (Optional float): Rotation in degrees relative to origin. Note: The center point is the center of the x0,y0 pixel. Since pixels are not divisible, the radius is integer rounded up to complete on a full pixel. Therefore diameter = 2 x r + 1. """ # Determine side coordinates coords = [] theta = radians(rotate) n = sides + 1 for s in range(n): t = 2.0 * pi * s / sides + theta coords.append([int(r * cos(t) + x0), int(r * sin(t) + y0)]) # Starting point x1, y1 = coords[0] # Minimum Maximum X dict xdict = {y1: [x1, x1]} # Iterate through coordinates for row in coords[1:]: x2, y2 = row xprev, yprev = x2, y2 # Calculate perimeter # Check for horizontal side if y1 == y2: if x1 > x2: x1, x2 = x2, x1 if y1 in xdict: xdict[y1] = [min(x1, xdict[y1][0]), max(x2, xdict[y1][1])] else: xdict[y1] = [x1, x2] x1, y1 = xprev, yprev continue # Non horizontal side # Changes in x, y dx = x2 - x1 dy = y2 - y1 # Determine how steep the line is is_steep = abs(dy) > abs(dx) # Rotate line if is_steep: x1, y1 = y1, x1 x2, y2 = y2, x2 # Swap start and end points if necessary if x1 > x2: x1, x2 = x2, x1 y1, y2 = y2, y1 # Recalculate differentials dx = x2 - x1 dy = y2 - y1 # Calculate error error = dx >> 1 ystep = 1 if y1 < y2 else -1 y = y1 # Calcualte minimum and maximum x values for x in range(x1, x2 + 1): if is_steep: if x in xdict: xdict[x] = [min(y, xdict[x][0]), max(y, xdict[x][1])] else: xdict[x] = [y, y] else: if y in xdict: xdict[y] = [min(x, xdict[y][0]), max(x, xdict[y][1])] else: xdict[y] = [x, x] error -= abs(dy) if error < 0: y += ystep error += dx x1, y1 = xprev, yprev # Fill polygon for y, x in xdict.items(): self.draw_hline(x[0], y, x[1] - x[0] + 2, red, invert) def is_off_grid(self, xmin, ymin, xmax, ymax): """Check if coordinates extend past display boundaries. Args: xmin (int): Minimum horizontal pixel. ymin (int): Minimum vertical pixel. xmax (int): Maximum horizontal pixel. ymax (int): Maximum vertical pixel. Returns: boolean: False = Coordinates OK, True = Error. """ if xmin < 0: print('x-coordinate: {0} below minimum of 0.'.format(xmin)) return True if ymin < 0: print('y-coordinate: {0} below minimum of 0.'.format(ymin)) return True if xmax >= self.width: print('x-coordinate: {0} above maximum of {1}.'.format( xmax, self.width - 1)) return True if ymax >= self.height: print('y-coordinate: {0} above maximum of {1}.'.format( ymax, self.height - 1)) return True return False def present(self, red=True, black=True): """Present image to display. Args: red (bool): True (default) = present red buffer black (bool): True (default) = present black buffer """ if (black and self.blackimage is not None): self.write_cmd(self.DATA_START_TRANSMISSION_1) self.write_data(self.blackimage) if (red and self.ryimage is not None): self.write_cmd(self.DATA_START_TRANSMISSION_2) self.write_data(self.ryimage) self.write_cmd(self.DISPLAY_REFRESH) sleep_ms(200) self.ReadBusy() def sleep(self): """Put display to sleep.""" self.write_cmd(self.POWER_OFF) self.ReadBusy() self.write_cmd(self.DEEP_SLEEP, 0xA5) # def ReadBusy(self): # """Check if display busy.""" # self.write_cmd(self.GET_STATUS) # while self.busy.read() == 0: # 0: busy, 1: idle # self.write_cmd(self.GET_STATUS) # sleep_ms(200) # def reset(self): # """Perform reset.""" # self.rst.write(1) # sleep_ms(200) # self.rst.write(0) # sleep_ms(10) # self.rst.write(1) # sleep_ms(200) # def sleep(self): # """Put display to sleep.""" # self.write_cmd(self.POWER_OFF) # self.ReadBusy() # self.write_cmd(self.DEEP_SLEEP, 0xA5) # def write_cmd(self, command, *args): # """Write command to display. # Args: # command (byte): Display command code. # *args (optional bytes): Data to transmit. # """ # self.dc.write(0) # self.cs.write(0) # self.spi.write(bytearray([command])) # self.cs.write(1) # # Handle any passed data # if len(args) > 0: # self.write_data(bytearray(args)) # def write_data(self, data): # """Write data to display. # Args: # data (bytes): Data to transmit. # """ # self.dc.write(1) # self.cs.write(0) # self.spi.write(data) # self.cs.write(1) def ReadBusy(self): """Check if display busy.""" self.write_cmd(self.GET_STATUS) while self.busy.value() == 0: # 0: busy, 1: idle self.write_cmd(self.GET_STATUS) sleep_ms(200) def reset(self): """Perform reset.""" self.rst(1) sleep_ms(200) self.rst(0) sleep_ms(10) self.rst(1) sleep_ms(200) def write_cmd(self, command, *args): """Write command to display. Args: command (byte): Display command code. *args (optional bytes): Data to transmit. """ self.dc(0) self.cs(0) # print("send cmd") # print(command) self.spi.write(bytearray([command])) self.cs(1) # Handle any passed data if len(args) > 0: self.write_data(bytearray(args)) def write_data(self, data): """Write data to display. Args: data (bytes): Data to transmit. """ self.dc(1) self.cs(0) # print("send data") # print(data) self.spi.write(data) self.cs(1)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/electronic_price_tag/esp32/code/esp2in9bv2.py
Python
apache-2.0
30,483
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : main.py @Author : zeta.zz @version : 1.0 @Description: price_tag - 电子价签 board.json - 硬件资源配置文件 ''' from showPriceData import ShowData from machine import Pin from driver import GPIO import network import time import kv import gc from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import json import binascii # 物联网平台连接标志位 iot_connected = False wlan = None # 三元组信息 productKey = "Your-ProductKey" deviceName = "Your-devicename" deviceSecret = "Your-deviceSecret" # 物联网设备实例 device = None # Wi-Fi SSID和Password设置 wifiSsid = "Your-AP-SSID" wifiPassword = "Your-AP-Password" # 定义电子价签物联网模型参数 sal_update = 0 sal_pic = '' sal_offerta = '30' sal_price = '108.50' sal_name = 'AliOS-Things' arrayBuf = bytearray(b'') updating = 0 # 等待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 on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): # global post_default_value global arrayBuf, sal_update, sal_name, sal_price, sal_offerta, sal_pic, updating try: props = eval(request['params']) print(props) # 获取 sal_name 参数 if 'sal_name' in props.keys(): sal_name = props['sal_name'] print(sal_name) # 获取 sal_price 参数 if 'sal_price' in props.keys(): sal_price = props['sal_price'] print(sal_price) # 获取 sal_offerta 参数 if 'sal_offerta' in props.keys(): sal_offerta = props['sal_offerta'] print(sal_offerta) # 获取 sal_pic 参数 if 'sal_pic' in props.keys(): sal_pic = props['sal_pic'] # print(sal_pic) print("recevied sal pic") if 'sal_update' in props.keys(): sal_update = props['sal_update'] print(sal_update) # 判断是否需要更新 if sal_update == 1: if len(sal_pic) % 2 == 0: picBuf = binascii.unhexlify(sal_pic) # 改变显示图形buf arrayBuf = bytearray(picBuf) # print(arrayBuf) # 刷新屏幕 # 墨水屏刷新慢,加入保护 if updating == 0: updating = 1 gc.collect() priceTagObj.show(name=sal_name, sel='$ '+sal_price, offerta='-'+sal_offerta+'%', byteBuf=arrayBuf) gc.collect() updating = 0 # 上传更新设置, 图片更新后才会更新 sal_update = 0 post_default_value() except Exception 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('物联网平台连接成功') post_default_value() kv.set('app_upgrade_channel', 'disable') break else: print('sleep for 1 s') time.sleep(1) time.sleep(2) # 初始化物联网平台更新状态 def post_default_value(): # global sal_update value = {'sal_update' : sal_update} post_props(value) value = {'sal_name' : sal_name} post_props(value) value = {'sal_price' : sal_price} post_props(value) value = {'sal_offerta' : sal_offerta} post_props(value) if __name__ == '__main__': wlan = network.WLAN(network.STA_IF) #创建WLAN对象 get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) # 初始化墨水屏 # epaperDC = GPIO() # epaperDC.open("epaper_dc") # epaperCS = GPIO() # epaperCS.open("epaper_cs") # epaperRST = GPIO() # epaperRST.open("epaper_rst") # epaperBUSY = GPIO() # epaperBUSY.open("epaper_busy") # priceTagObj = ShowData(14500000, epaperDC, epaperCS, epaperRST, epaperBUSY) # priceTagObj = ShowData(14500000, Pin(18), Pin(23), Pin(17), Pin(5), Pin(16), Pin(4)) priceTagObj = ShowData(14500000, Pin(17), Pin(2), Pin(16), Pin(4)) # 初始化显示 updating = 1 gc.collect() priceTagObj.show(name=sal_name, sel='$ '+sal_price, offerta='-'+sal_offerta+'%') gc.collect() updating = 0 # buf test code # apple_pic = b'ffffffffffffffffffff1fffffffffffffffffffff1fffffffffffffffffffff1fffffffffffffffffffff1fffffffffffffffffffff1fffffffffffff1ffeffff1fffffffffffff03f8ffff1fffffffffffff00f8ffff1fffffffffc77fe0f1ffff1fffffffffc71ffcf1ffff1fffffffff8f1ffef1ffff1fffffffff0f8ffff1ffff1fffffffff1f87fff1ffff1fffffffff3fc6fff9ffff1fffffffff3fe2fff8ffff1fffffffff7fe0fff8ffff1fffffffff7ff0fff8ffff1fffffffff7ff07ffcffff1ffffffffffff03ffcffff1ffffffffffff01ffeffff1ffffffffffff00fffffff1ffffffffffff083ffffff1ffffffffffd01c0ffffff1fffffff3fc00080ffffff1fffffff0f000100feffff1fffffff0706080afcffff1fffffffc33f807ff8ffff1fffffffe37fc0fff8ffff1ffffffff1ffe0fff1ffff1ffffffff1ffe0fff1ffff1ffffffff8fff1ffe3ffff1ffffffff8fff1ffe3ffff1ffffffff8fff1ffe3ffff1ffffffff8fff1ffe3ffff1ffffffff9fff1fff3ffff1ffffffff0ffe0fff1ffff1fffff3ff0ffe0ff81ffff1fffff0fe07fc0ff00feff1fffff07851f043f08fcff1fffffc307000e007cf8ff1fffffe11f801f00fff0ff1ffffff13fe0ffc0fff1ff1ffffff8fff0ffe1ffe3ff1ffffff8fff0fff1ffe3ff1ffffff8fff9ffe1ffe3ff1ffffff8fff1fff3ffe3ff1ffffff8fff8fff1ffe3ff1ffffff8fff0ffe1ffe3ff1ffffff8fff0ffe1ffe3ff1ffffff17fe0ffc0fff1ff1fffffe17fc07fc0fff0ff1fffffc31f863f0c7ff8ff1fffff07020e040e08fcff1fffff0f801f003f00feff1fffff3fe07fc07f80ffff1ffffffff8fff1ffe3ffff1ffffffff8fff1ffe3ffff1ffffffff8fff1ffe3ffff1ffffffff8fff1fff3ffff1ffffffff1ffe0fff1ffff1ffffffff1ffe0fff1ffff1fffffffe17fc0fff8ffff1fffffffc33f847ff8ffff1fffffff07060e16fcffff1fffffff0f001f00feffff1fffffff3fc07f80ffffff1ffffffffff1fff1ffffff1ffffffffff1fff1ffffff1ffffffffff1fff1ffffff1ffffffffff9fff3ffffff1ffffffffff1fff1ffffff1ffffffffff1fff1ffffff1ffffffffff1fff1ffffff1fffffffffe1fff0ffffff1fffffffffe3fff8ffffff1fffffffff873ffcffffff1fffffffff070ffcffffff1fffffffff0f00ffffffff1fffffffff3f80ffffffff1fffffffffffe9ffffffff1fffffffffffffffffffff1fffffffffffffffffffff1fffffffffffffffffffff1fffffffffffffffffffff1fffffffffffffffffffff1f' # picBuf = binascii.unhexlify(apple_pic) # arrayBuf = bytearray(picBuf) # priceTagObj.show(name=sal_name, sel='$ '+sal_price, offerta='-'+sal_offerta+'%', byteBuf=arrayBuf) # gc.collect()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/electronic_price_tag/esp32/code/main.py
Python
apache-2.0
8,356
"""ESP2in9b v.2.""" from time import sleep from machine import SPI, Pin # from driver import SPI from xglcd_font import XglcdFont from esp2in9bv2 import Display # ############################################################################# # ############### HaaS Python price tag ############################ # ############################################################################# # ##| |####| |##| OFFERTA |######## # ##| product pic |####| ¥ 100.00 (sal) |##| -30% |######## # ##| (url) |####| (name) |##| (offerta) |######## # ############################################################################# # ---85pixel--- ---135pixel--- ---76pixel--- class ShowData(): # init hw params def __init__(self, baudrate, dc, cs, rst, busy): self.BAUDRATE = baudrate # self.SCK = sck # self.MOSI = mosi self.DC = dc self.CS = cs self.RST = rst self.BUSY = busy # self.epaperSPI = SPI() # self.epaperSPI.open("epaper") def show(self, name='AliOS-Things', sel='$ 108.50', offerta='-30%', byteBuf=bytearray(b'')): # init epaper spi = SPI(2, baudrate=self.BAUDRATE, sck=Pin(18), mosi=Pin(23)) display = Display(spi, dc=self.DC, cs=self.CS, rst=self.RST, busy=self.BUSY) # display = Display(spi=self.epaperSPI, dc=self.DC, cs=self.CS, rst=self.RST, busy=self.BUSY) # start draw Banner USE red color display.fill_rectangle(100, 0, 28, 296, red=True) # load fonts and draw Banner font unispace = XglcdFont('data/pyamp/fonts/Unispace12x24.c', 12, 24) text_width = unispace.measure_text("HaaS Python price tag") # print(text_width) display.draw_text(100, (296-text_width)//2, "HaaS Python price tag", unispace, red=True, invert=True, rotate=90) # start draw offerta Banner use black color display.fill_rectangle(0, 220, 100, 76) # load fonts and draw banner fonts ArcadePix = XglcdFont('data/pyamp/fonts/ArcadePix9x11.c', 9, 11) text_width = ArcadePix.measure_text("OFFERTA") # print(text_width) display.draw_text(70, (220+(76-text_width)//2), "OFFERTA", ArcadePix, invert=True, rotate=90) # start draw Split line display.fill_rectangle(30, 85, 5, 135) # load fonts # change name to ArcadePix # wendy = XglcdFont('fonts/Wendy7x8.c', 7, 8) # text_width = wendy.measure_text(name) # print(text_width) # display.draw_text(13, (220-text_width-4), name, wendy, rotate=90) text_width = ArcadePix.measure_text(name) # print(text_width) display.draw_text(13, (220-text_width-4), name, ArcadePix, rotate=90) # start load Product pic # this pic can update by cloud push if byteBuf != bytearray(b''): display.draw_bitmap(0, 0, 85, 85, bytebuf=byteBuf, rotate=90) else: display.draw_bitmap(0, 0, 85, 85, path="data/pyamp/images/alios.mono", rotate=90) # start load price # this price can update by cloud push espresso = XglcdFont('data/pyamp/fonts/EspressoDolce18x24.c', 18, 24) text_width = espresso.measure_text(sel) # print(text_width) display.draw_text(50, 110, sel, espresso, rotate=90) # start load offerta price espresso = XglcdFont('data/pyamp/fonts/EspressoDolce18x24.c', 18, 24) text_width = espresso.measure_text(offerta) # print(text_width) display.draw_text(30, 230, offerta, espresso, invert=True, rotate=90) # display show display.present() # sleep(10) # display.sleep() sleep(5) # display.clear() display.sleep() print('Done.') def close(self): display = Display(self.epaperSPI, dc=self.DC, cs=self.CS, rst=self.RST, busy=self.BUSY) display.cleanup() print('clean and close SPI')
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/electronic_price_tag/esp32/code/showPriceData.py
Python
apache-2.0
4,085
# -*- coding: utf-8 -*- """Utility to convert images to MONO_HMSB format.""" from PIL import Image from os import path import sys def error(msg): """Display error and exit.""" print (msg) sys.exit(-1) def set_bit(value, index, high=True): """Set the index:th bit of value. Args: value (int): Number that will have bit modified. index (int): Index of bit to set. high (bool): True (default) = set bit high, False = set bit low """ mask = 1 << index value &= ~mask if high: value |= mask return value def write_bin(f, pixel_list, width): """Save image in MONO_HMSB format.""" index = 0 list_bytes = [] image_byte = 0 windex = 0 for pix in pixel_list: image_byte = set_bit(image_byte, index, pix > 0) index += 1 windex += 1 if index > 7 or windex >= width: list_bytes.append(image_byte) image_byte = 0 index = 0 if windex >= width: windex = 0 f.write(bytearray(list_bytes)) if __name__ == '__main__': args = sys.argv if len(args) != 2: error('Please specify input file: ./img2monohmsb.py test.png') in_path = args[1] if not path.exists(in_path): error('File Not Found: ' + in_path) filename, ext = path.splitext(in_path) out_path = filename + '.mono' img = Image.open(in_path).convert('1') # Open and covert to monochrome pixels = list(img.getdata()) with open(out_path, 'wb') as f: write_bin(f, pixels, img.width) print('Saved: ' + out_path)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/electronic_price_tag/esp32/code/utils/img2monoHMSB.py
Python
apache-2.0
1,608
from os import path import sys import binascii if __name__ == '__main__': args = sys.argv if len(args) != 2: error('Please specify input file: ./img2monohmsb.py test.png') in_path = args[1] if not path.exists(in_path): error('File Not Found: ' + in_path) array_size = 85*85 with open(in_path, "rb") as f: buf = bytearray(f.read(array_size)) zztest = binascii.hexlify(buf) print(zztest)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/electronic_price_tag/esp32/code/utils/readMonoBuf.py
Python
apache-2.0
454
# -*- coding: utf-8 -*- """Utility to convert images to MONO_HMSB format.""" from PIL import Image from os import path import sys import binascii def error(msg): """Display error and exit.""" print (msg) sys.exit(-1) def set_bit(value, index, high=True): """Set the index:th bit of value. Args: value (int): Number that will have bit modified. index (int): Index of bit to set. high (bool): True (default) = set bit high, False = set bit low """ mask = 1 << index value &= ~mask if high: value |= mask return value def write_bin(f, pixel_list, width): """Save image in MONO_HMSB format.""" index = 0 list_bytes = [] image_byte = 0 windex = 0 for pix in pixel_list: image_byte = set_bit(image_byte, index, pix > 0) index += 1 windex += 1 if index > 7 or windex >= width: list_bytes.append(image_byte) image_byte = 0 index = 0 if windex >= width: windex = 0 f.write(bytearray(list_bytes)) if __name__ == '__main__': args = sys.argv if len(args) != 2: error('Please specify input file: ./img2monohmsb.py test.png') in_path = args[1] if not path.exists(in_path): error('File Not Found: ' + in_path) filename, ext = path.splitext(in_path) out_path = filename + '.mono' img = Image.open(in_path).convert('1') # Open and covert to monochrome pixels = list(img.getdata()) with open(out_path, 'wb') as f: write_bin(f, pixels, img.width) print('Saved: ' + out_path) array_size = 85*85 with open(out_path, "rb") as f: buf = bytearray(f.read(array_size)) zztest = binascii.hexlify(buf) print(zztest)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/electronic_price_tag/esp32/code/utils/showMonoBuf.py
Python
apache-2.0
1,793
"""XGLCD Font Utility.""" from math import floor from framebuf import FrameBuffer, MONO_VLSB class XglcdFont(object): """Font data in X-GLCD format. Attributes: letters: A bytearray of letters (columns consist of bytes) width: Maximum pixel width of font height: Pixel height of font start_letter: ASCII number of first letter height_bytes: How many bytes comprises letter height Note: Font files can be generated with the free version of MikroElektronika GLCD Font Creator: www.mikroe.com/glcd-font-creator The font file must be in X-GLCD 'C' format. To save text files from this font creator program in Win7 or higher you must use XP compatibility mode or you can just use the clipboard. """ def __init__(self, path, width, height, start_letter=32, letter_count=96): """Constructor for X-GLCD Font object. Args: path (string): Full path of font file width (int): Maximum width in pixels of each letter height (int): Height in pixels of each letter start_letter (int): First ACII letter. Default is 32. letter_count (int): Total number of letters. Default is 96. """ self.width = width self.height = height self.start_letter = start_letter self.letter_count = letter_count self.bytes_per_letter = (floor( (self.height - 1) / 8) + 1) * self.width + 1 self.__load_xglcd_font(path) def __load_xglcd_font(self, path): """Load X-GLCD font data from text file. Args: path (string): Full path of font file. """ bytes_per_letter = self.bytes_per_letter # Buffer to hold letter byte values self.letters = bytearray(bytes_per_letter * self.letter_count) mv = memoryview(self.letters) offset = 0 with open(path, 'r') as f: for line in f: # Skip lines that do not start with hex values line = line.strip() if len(line) == 0 or line[0:2] != '0x': continue # Remove comments comment = line.find('//') if comment != -1: line = line[0:comment].strip() # Remove trailing commas if line.endswith(','): line = line[0:len(line) - 1] # Convert hex strings to bytearray and insert in to letters mv[offset: offset + bytes_per_letter] = bytearray( int(b, 16) for b in line.split(',')) offset += bytes_per_letter def get_letter(self, letter, invert=False, rotate=0): """Convert letter byte data to pixels. Args: letter (string): Letter to return (must exist within font). invert (bool): True = white text, False (Default) black text. rotate (int): rotation (default: 0) Returns: (FrameBuffer): Pixel data in MONO_VLSB. (int, int): Letter width and height. """ # Get index of letter letter_ord = ord(letter) - self.start_letter # Confirm font contains letter if letter_ord >= self.letter_count: print('Font does not contain character: ' + letter) return b'', 0, 0 bytes_per_letter = self.bytes_per_letter offset = letter_ord * bytes_per_letter mv = memoryview(self.letters[offset:offset + bytes_per_letter]) # Get width of letter (specified by first byte) width = mv[0] height = self.height byte_height = (height - 1) // 8 + 1 # Support fonts up to 5 bytes high if byte_height > 6: print("Error: maximum font byte height equals 6.") return b'', 0, 0 array_size = width * byte_height ba = bytearray(mv[1:array_size + 1]) # Set inversion and re-order bytes if height > 1 byte pos = 0 ba2 = bytearray(array_size) if invert is True: # 0 bit is black/red so inverted is default for i in range(0, array_size, byte_height): ba2[pos] = ba[i] if byte_height > 1: ba2[pos + width] = ba[i + 1] if byte_height > 2: ba2[pos + width * 2] = ba[i + 2] if byte_height > 3: ba2[pos + width * 3] = ba[i + 3] if byte_height > 4: ba2[pos + width * 4] = ba[i + 4] if byte_height > 5: ba2[pos + width * 5] = ba[i + 5] pos += 1 else: # Use XOR to negate inversion for i in range(0, array_size, byte_height): ba2[pos] = ba[i] ^ 0xFF if byte_height > 1: ba2[pos + width] = ba[i + 1] ^ 0xFF if byte_height > 2: ba2[pos + width * 2] = ba[i + 2] ^ 0xFF if byte_height > 3: ba2[pos + width * 3] = ba[i + 3] ^ 0xFF if byte_height > 4: ba2[pos + width * 4] = ba[i + 4] ^ 0xFF if byte_height > 5: ba2[pos + width * 5] = ba[i + 5] ^ 0xFF pos += 1 fb = FrameBuffer(ba2, width, height, MONO_VLSB) if rotate == 0: # 0 degrees return fb, width, height elif rotate == 90: # 90 degrees byte_width = (width - 1) // 8 + 1 adj_size = height * byte_width fb2 = FrameBuffer(bytearray(adj_size), height, width, MONO_VLSB) for y in range(height): for x in range(width): fb2.pixel(y, x, fb.pixel(x, (height - 1) - y)) return fb2, height, width elif rotate == 180: # 180 degrees fb2 = FrameBuffer(bytearray(array_size), width, height, MONO_VLSB) for y in range(height): for x in range(width): fb2.pixel(x, y, fb.pixel((width - 1) - x, (height - 1) - y)) return fb2, width, height elif rotate == 270: # 270 degrees byte_width = (width - 1) // 8 + 1 adj_size = height * byte_width fb2 = FrameBuffer(bytearray(adj_size), height, width, MONO_VLSB) for y in range(height): for x in range(width): fb2.pixel(y, x, fb.pixel((width - 1) - x, y)) return fb2, height, width def measure_text(self, text, spacing=1): """Measure length of text string in pixels. Args: text (string): Text string to measure spacing (optional int): Pixel spacing between letters. Default: 1. Returns: int: length of text """ length = 0 for letter in text: # Get index of letter letter_ord = ord(letter) - self.start_letter offset = letter_ord * self.bytes_per_letter # Add length of letter and spacing length += self.letters[offset] + spacing return length
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/electronic_price_tag/esp32/code/xglcd_font.py
Python
apache-2.0
7,222
#!/usr/bin/env python # -*- encoding: utf-8 -*- import utime import ujson from aliyunIoT import Device import modbus as mb import yuanda_htb485 import zzio606 import network from driver import GPIO ############# wifi连网代码 ############ def connect_wifi(ssid, pwd): wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(ssid, pwd) ########## 4G.Cat1连网代码 ############ g_connect_status = False def on_4g_cb(args): print("4g callback.") 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_4g_network(): global on_4g_cb net = network.NetWorkClient() net_led = GPIO() net_led.open('net_led') 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({"apn":"CMNET"}) else: print('network register failed') while True: if g_connect_status==False: net_led.write(0) if g_connect_status: print('network register successed') #连上网之后,点亮cloud_led net_led.write(1) break utime.sleep_ms(20) return 0 ######## 物联网平台相关代码 ############ # Wi-Fi SSID和Password设置 # 三元组信息 productKey = "产品密钥" deviceName = "设备名字" deviceSecret = "设备密钥" device = None zzio606Obj = None switchList = ["switch0", "switch1", "switch2", "switch3", "switch4", "switch5"] # 物联网平台连接成功的回调函数 def on_connect(data): print("物联网平台连接成功") # 处理物联网平台下行指令 def on_props(request): global alarm_on, device, zzio606Obj, switchList payload = ujson.loads(request['params']) for i in range(0, len(switchList)): if switchList[i] in payload.keys(): print(switchList[i]) value = payload[switchList[i]] if (value): zzio606Obj.openChannel(i) else: zzio606Obj.closeChannel(i) prop = ujson.dumps({ switchList[i]: value, }) print(prop) upload_data = {'params': prop} device.postProps(upload_data) # 连接物联网平台 def connect_lk(productKey, deviceName, deviceSecret): global device key_info = { 'region': 'cn-shanghai', 'productKey': productKey, 'deviceName': deviceName, 'deviceSecret': deviceSecret, 'keepaliveSec': 60 } device = Device() device.on(Device.ON_CONNECT, on_connect) device.on(Device.ON_PROPS, on_props) device.connect(key_info) # 上传htb数据 def upload_htb_data(): global device, zzio606Obj htb485Obj = yuanda_htb485.HTB485(mb, 1) zzio606Obj = zzio606.ZZIO606(mb, 3) while True: if htb485Obj is None: break htb = htb485Obj.getHTB() # "humidity"/"temperature"/"brightness"必须和物联网平台的属性一致 upload_data = {'params': ujson.dumps({ 'humidity': htb[0], 'temperature': htb[1], "brightness":htb[3] }) } # 上传温度和湿度信息到物联网平台 device.postProps(upload_data) utime.sleep(2) mb.deinit() if __name__ == '__main__': # connect_wifi('KIDS', '12345678') connect_4g_network() mb.init('modbus_485_4800') utime.sleep(2) connect_lk(productKey, deviceName, deviceSecret) utime.sleep(2) upload_htb_data()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/environment_monitor_485/haas506/code/main.py
Python
apache-2.0
3,812
import utime import modbus as mb import yuanda_htb485 import zzio606 def test_htb485(): ret = mb.init('modbus_485_4800') if ret < 0: raise ValueError("init modbus failed.") htb485Obj = yuanda_htb485.HTB485(mb, 1) humidity = htb485Obj.getHumidity() temperature = htb485Obj.getTemperature() brightness = htb485Obj.getBrightness() htb = htb485Obj.getHTB() print("temperature:", temperature) print("humidity:", humidity) print("brightness:",brightness) print("htb:",htb) mb.deinit() def test_zzio606(): # mb.writeHoldingRegister(1, 0x03e8,2,200) ret = mb.init('modbus_485_4800') if ret < 0: raise ValueError("init modbus failed.") zzio606Obj = zzio606.ZZIO606(mb, 3) zzio606Obj.openChannel(0) utime.sleep(1) zzio606Obj.openChannel(1) utime.sleep(1) zzio606Obj.openChannel(2) utime.sleep(1) zzio606Obj.openChannel(3) utime.sleep(1) zzio606Obj.openChannel(4) utime.sleep(1) zzio606Obj.openChannel(5) status = zzio606Obj.getChannelStatus() print("status", status) utime.sleep(5) zzio606Obj.closeChannel(0) utime.sleep(1) zzio606Obj.closeChannel(1) utime.sleep(1) zzio606Obj.closeChannel(2) utime.sleep(1) zzio606Obj.closeChannel(3) utime.sleep(1) zzio606Obj.closeChannel(4) utime.sleep(1) zzio606Obj.closeChannel(5) utime.sleep(1) status = zzio606Obj.getChannelStatus() print("status", status)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/environment_monitor_485/haas506/code/test.py
Python
apache-2.0
1,506
import ustruct class HTB485(object): def __init__(self, mbObj, devAddr): self.mbObj = mbObj self.devAddr = devAddr def getHumidity(self): if self.mbObj is None: raise ValueError("invalid modbus object.") value = bytearray(4) ret = self.mbObj.readHoldingRegisters(self.devAddr, 0, 2, value, 200) if ret[0] < 0: raise ValueError("readHoldingRegisters failed. errno:", ret[0]) humidity = ustruct.unpack('hh',value) return humidity[0] def getTemperature(self): if self.mbObj is None: raise ValueError("invalid modbus object.") value = bytearray(4) ret = self.mbObj.readHoldingRegisters(self.devAddr, 0, 2, value, 200) if ret[0] < 0: raise ValueError("readHoldingRegisters failed. errno:", ret[0]) temperature = ustruct.unpack('hh',value) return temperature[1] def getBrightness(self): if self.mbObj is None: raise ValueError("invalid modbus object.") value = bytearray(4) ret = self.mbObj.readHoldingRegisters(self.devAddr, 2, 2, value, 200) if ret[0] < 0: raise ValueError("readHoldingRegisters failed. errno:", ret[0]) brightness = ustruct.unpack('hh',value) return brightness[1] def getHTB(self): if self.mbObj is None: raise ValueError("invalid modbus object.") value = bytearray(10) ret = self.mbObj.readHoldingRegisters(self.devAddr, 0, 5, value, 200) if ret[0] < 0: raise ValueError("readHoldingRegisters failed. errno:", ret[0]) htb = ustruct.unpack('hhhhh',value) return htb
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/environment_monitor_485/haas506/code/yuanda_htb485.py
Python
apache-2.0
1,739
class ZZIO606(object): def __init__(self, mbObj, devAddr): self.mbObj = mbObj self.devAddr = devAddr def openChannel(self, chid): if self.mbObj is None: raise ValueError("invalid modbus object.") ret = self.mbObj.writeCoil(self.devAddr, chid, 0xff00, 200) return ret[0] def closeChannel(self, chid): if self.mbObj is None: raise ValueError("invalid modbus object.") ret = self.mbObj.writeCoil(self.devAddr, chid, 0, 200) return ret[0] def getChannelStatus(self): if self.mbObj is None: raise ValueError("invalid modbus object.") status = bytearray(1) ret = self.mbObj.readCoils(self.devAddr, 0, 6, status, 200) if ret[0] < 0: raise ValueError("modbus readCoils failed, errno:", ret[0]) return status
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/environment_monitor_485/haas506/code/zzio606.py
Python
apache-2.0
880
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/epidemic_prevention_control/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 disDev = 0 echoDev = 0 trigDev = 0 # 安全距离,单位是5厘米 ALARM_DISTANCE = const(5) # 物联网平台连接标志位 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() # 扫描接入点 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 door_check_init(): global disDev, echoDev, trigDev echoDev = GPIO() echoDev.open("echo") trigDev = GPIO() trigDev.open("trig") disDev = hcsr04.HCSR04(trigDev, echoDev) def door_detector(): global disDev, echoDev, trigDev lastOpened = 0 while True: # 无限循环 distance = disDev.measureDistance() print('distance = ', distance) if(distance > ALARM_DISTANCE): thisOpened = 1 else: thisOpened = 0 if(lastOpened != thisOpened): print("door status changed: ", thisOpened) # 生成上报到物联网平台的属性值字串,此处的属性标识符"door_opened"必须和物联网平台的属性一致 # "door_opened" - 表示入户门开关状态 upload_data = {'params': ujson.dumps({ 'door_opened': thisOpened, }) } # 上传状态到物联网平台 device.postProps(upload_data) lastOpened = thisOpened 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) door_check_init() door_detector()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/epidemic_prevention_control/esp32/code/main.py
Python
apache-2.0
4,320
# 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): 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) status_data = {} def upload_status(n): global status_data status_data["open_door"]= n status_data_str=ujson.dumps(status_data) data={ 'params':status_data_str } device.postProps(data) #超声波测距 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) #creat instances TRIG = GPIO() ECHO = GPIO() TRIG.open('trig') # Set pin as GPIO out ECHO.open('echo') # Set pin as GPIO in door_status = 0 turn = 0 try: while True: dis = getData() if dis > 20 and dis < 600: if dis < 40: door_status = 0 if door_status != turn: print ("distance:%0.2f cm" % dis) print('door status changed:',door_status) upload_status(door_status) turn = door_status else: door_status = 1 if door_status != turn: print ("distance:%0.2f cm" % dis) print('door status changed:',door_status) upload_status(door_status) turn = door_status else: print ("Out Of Range") except KeyboardInterrupt: print("exit")
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/epidemic_prevention_control/haas506/code/main.py
Python
apache-2.0
7,004
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/epidemic_prevention_control/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 disDev = 0 echoDev = 0 trigDev = 0 # 安全距离,单位是5厘米 ALARM_DISTANCE = const(5) # 物联网平台连接标志位 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() # 扫描接入点 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 door_check_init(): global disDev, echoDev, trigDev echoDev = GPIO() echoDev.open("echo") trigDev = GPIO() trigDev.open("trig") disDev = hcsr04.HCSR04(trigDev, echoDev) def door_detector(): global disDev, echoDev, trigDev lastOpened = 0 while True: # 无限循环 distance = disDev.measureDistance() print('distance = ', distance) if(distance > ALARM_DISTANCE): thisOpened = 1 else: thisOpened = 0 if(lastOpened != thisOpened): print("door status changed: ", thisOpened) # 生成上报到物联网平台的属性值字串,此处的属性标识符"door_opened"必须和物联网平台的属性一致 # "door_opened" - 表示入户门开关状态 upload_data = {'params': ujson.dumps({ 'door_opened': thisOpened, }) } # 上传状态到物联网平台 device.postProps(upload_data) lastOpened = thisOpened utime.sleep(1) # 打印完之后休眠1秒 echoDev.close() trigDev.close() if __name__ == '__main__': nic = network.LAN() nic.active(1) connect_lk(productKey, deviceName, deviceSecret) door_check_init() door_detector()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/epidemic_prevention_control/stm32/code/main.py
Python
apache-2.0
4,445
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : main.py @Description: 人脸识别案例 @Author : luokui @version : 1.0 ''' from aliyunIoT import Device import display # 显示库 import uai # AI识别库 import network # 网络库 import ucamera # 摄像头库 import utime # 延时函数在utime库中 import _thread # 线程库 import sntp # 网络时间同步库 import ujson as json # Wi-Fi SSID和Password设置 SSID='Your-AP-SSID' PWD='Your-AP-Password' # HaaS设备三元组 productKey = "Your-ProductKey" deviceName = "Your-devicename" deviceSecret = "Your-deviceSecret" g_lk_connect = False g_lk_service = False g_confidence = 0 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 cb_lk_service(data): global g_lk_service, g_confidence, detected # dev.publish(compare_reply) # print(data) #resp = json.loads(data) if data != None: params = data['params'] params_dict = json.loads(params) # print(params_dict) ext = params_dict['ext'] ext_dict = json.loads(ext) result = ext_dict['result'] if result == 'success': g_confidence = ext_dict['confidence'] if g_confidence > 60: print('boss is comming!') detected = True else: # print('boss is not comming!') detected = False else: # print('boss is not comming!') detected = False g_lk_service = True # print('cb_lk_service done') def cb_lk_connect(data): global g_lk_connect print('link platform connected') g_lk_connect = True def compareFace(frame, fileName, productKey, devName, devSecret): start = utime.ticks_ms() global dev # 上传图片到LP fileid = dev.uploadContent(fileName, frame, None) # end = utime.ticks_ms() # print('uploadContent time : %d' %(end - start)) if fileid != None: # start = utime.ticks_ms() ext = { 'filePosition':'lp', 'fileName': fileName, 'fileId': fileid } ext_str = json.dumps(ext) all_params = {'id': 1, 'version': '1.0', 'params': { 'eventType': 'haas.faas', 'eventName': 'compareFace', 'argInt': 1, 'ext': ext_str }} all_params_str = json.dumps(all_params) #print(all_params_str) upload_file = { 'topic': '/sys/' + productKey + '/' + deviceName + '/thing/event/hli_event/post', 'qos': 1, 'payload': all_params_str } time_diff = utime.ticks_diff(utime.ticks_ms(), start) print('build str time : %d' % time_diff) start1 = utime.ticks_ms() # 上传完成通知HaaS聚合平台 # print(upload_file) dev.publish(upload_file) # end = utime.ticks_ms() # print('publish time : %d' %(end - start)) # start = utime.ticks_ms() while g_lk_service == False: continue time_diff = utime.ticks_diff(utime.ticks_ms(), start1) print('pub time : %d' % time_diff) else: print('filedid is none, upload content fail') time_diff = utime.ticks_diff(utime.ticks_ms(), start) print('get response time : %d' % time_diff) # 人脸比较线程函数 def comapreFaceThread(): global frame while True: if frame != None: compareFace(frame, 'face.jpg', productKey, deviceName, deviceSecret) utime.sleep_ms(1000) else: utime.sleep_ms(1000) # 显示线程函数 def displayThread(): # 引用全局变量 global disp, frame, detected # 定义清屏局部变量 clearFlag = False # 定义显示文本局部变量 textShowFlag = False while True: # 采集摄像头画面 # print('start to capture') frame = ucamera.capture() # print('end to capture') if frame != None: if detected == True: # 清除屏幕内容 if clearFlag == False: disp.clear() clearFlag = True # 设置文字字体 disp.font(disp.FONT_DejaVu40) # 显示识别结果 disp.text(40, 90, 'Recognize', disp.RED) disp.text(30, 130, 'successfully!', disp.RED) print('Recognize successfully!!!') 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 face...', disp.WHITE) textShowFlag = True clearFlag = False def main(): # 全局变量 global disp, dev, frame, detected # 创建lcd display对象 disp = display.TFT() frame = None detected = False # 连接网络 connect_wifi(SSID, PWD) # 设备初始化 dev = Device() dev.on(Device.ON_CONNECT, cb_lk_connect) dev.on(Device.ON_SERVICE, cb_lk_service) # dev.subscribe(compare_init) # dev.unsubscribe(compare_init) dev.connect(key_info) while True: if g_lk_connect: break # 初始化摄像头 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(comapreFaceThread, ()) 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/face_recognization/esp32/code/main.py
Python
apache-2.0
7,235
from motion import motion from mpu6886 import mpu6886 import utime # 延时函数在utime from driver import I2C # 驱动库 import network # Wi-Fi功能所在库 import ujson # json字串解析库 from aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 i2cObj = None mpu6886Dev = None # 物联网平台连接标志位 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_lp(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 get_data(): acc = mpu6886Dev.acceleration gyro = mpu6886Dev.gyro # print(acc) # print(gyro) return acc, gyro # 返回读取到的加速度、角速度值 def fall_detected(): upload_data = {'params': ujson.dumps({ 'isFall': 1, }) } # 上传状态到物联网平台 if (iot_connected): device.postProps(upload_data) if __name__ == '__main__': # 网络初始化 wlan = network.WLAN(network.STA_IF) # 创建WLAN对象 get_wifi_status() connect_lp(productKey, deviceName, deviceSecret) # 硬件初始化 i2cObj = I2C() # 按照board.json中名为"mpu6886"的设备节点的配置参数(主设备I2C端口号,从设备地址,总线频率等)初始化I2C类型设备对象 i2cObj.open("mpu6886") print("mpu6886 inited!") mpu6886Dev = mpu6886.MPU6886(i2cObj) # 初始化MPU6886传感器 # 获取跌倒检测的motion实例 motionObj = motion.Motion("fall", get_data, fall_detected) # 使能action检测,并以Dictionary格式传入灵敏度参数 sensitivity = {"ACCELERATION_LOW_THREADHOLD": 4, "ACCELERATION_UP_THREADHOLD": 30, "ANGULAR_VELOCITY_LOW_THREADHOLD": 1, "ANGULAR_VELOCITY_UP_THREADHOLD": 10} motionObj.enable(sensitivity) # 关闭action检测,可再次使能,支持传入新的灵敏度 # motionObj.disable() # i2cObj.close() # 关闭I2C设备对象 # del mpu6886Dev
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/fall_detection/esp32/code/main.py
Python
apache-2.0
4,299
ITER_NUM = 50 ACCELERATION_LOW_THREADHOLD = 4 # 加速度变化下限阈值,越大越灵敏 ACCELERATION_UP_THREADHOLD = 12 # 加速度变化上限阈值,越小越灵敏 ANGULAR_VELOCITY_LOW_THREADHOLD = 1 # 角速度变化下限阈值,越小越灵敏 ANGULAR_VELOCITY_UP_THREADHOLD = 40 # 角速度变化下限阈值,越大越灵敏 class fall_detection: def __init__(self, getData): self.ax_offset = 0.0 self.ay_offset = 0.0 self.az_offset = 0.0 self.gx_offset = 0.0 self.gy_offset = 0.0 self.gz_offset = 0.0 self.trigger1count = 0 self.trigger2count = 0 self.trigger1 = False self.trigger2 = False self.getData = getData self.calibrate() def calibrate(self): ax_sum = 0.0 ay_sum = 0.0 az_sum = 0.0 gx_sum = 0.0 gy_sum = 0.0 gz_sum = 0.0 for num in range(0, ITER_NUM): data = self.getData() # 读取传感器信息值 ax_sum += data[0][0] ay_sum += data[0][1] az_sum += data[0][2] gx_sum += data[1][0] gy_sum += data[1][1] gz_sum += data[1][2] self.ax_offset = ax_sum/ITER_NUM self.ay_offset = ay_sum/ITER_NUM self.az_offset = az_sum/ITER_NUM self.gx_offset = gx_sum/ITER_NUM self.gy_offset = gy_sum/ITER_NUM self.gz_offset = gz_sum/ITER_NUM print('Now you can start fall detection!') def detect(self): global ACCELERATION_LOW_THREADHOLD global ACCELERATION_UP_THREADHOLD global ANGULAR_VELOCITY_LOW_THREADHOLD global ANGULAR_VELOCITY_UP_THREADHOLD fall = False data = self.getData() # 读取传感器信息值 AcX = data[0][0] AcY = data[0][1] AcZ = data[0][2] GyX = data[1][0] GyY = data[1][1] GyZ = data[1][2] ax = (AcX-self.ax_offset) ay = (AcY-self.ay_offset) az = (AcZ-self.az_offset) gx = (GyX-self.gx_offset) gy = (GyY-self.gy_offset) gz = (GyZ-self.gz_offset) if hasattr(self, 'sensitivity'): if 'ACCELERATION_LOW_THREADHOLD' in self.sensitivity: ACCELERATION_LOW_THREADHOLD = float(self.sensitivity['ACCELERATION_LOW_THREADHOLD']) if 'ACCELERATION_UP_THREADHOLD' in self.sensitivity: ACCELERATION_UP_THREADHOLD = float(self.sensitivity['ACCELERATION_UP_THREADHOLD']) if 'ANGULAR_VELOCITY_LOW_THREADHOLD' in self.sensitivity: ANGULAR_VELOCITY_LOW_THREADHOLD = float(self.sensitivity['ANGULAR_VELOCITY_LOW_THREADHOLD']) if 'ANGULAR_VELOCITY_UP_THREADHOLD' in self.sensitivity: ANGULAR_VELOCITY_UP_THREADHOLD = float(self.sensitivity['ANGULAR_VELOCITY_UP_THREADHOLD']) # calculating accelerationChangelitute vector for 3 axis Raw_accelerationChange = pow(pow(ax, 2)+pow(ay, 2)+pow(az, 2), 0.5) # Multiplied by 10 to values are between 0 to 1 accelerationChange = Raw_accelerationChange * 10 # Trigger1 function # if accelerationChange breaks lower threshold if(accelerationChange <= ACCELERATION_LOW_THREADHOLD and self.trigger2 == False): self.trigger1 = True # print("TRIGGER 1 ACTIVATED") if (self.trigger1 == True): self.trigger1count = self.trigger1count + 1 # if accelerationChange breaks upper threshold if (accelerationChange >= ACCELERATION_UP_THREADHOLD): self.trigger2 = True # print("TRIGGER 2 ACTIVATED") self.trigger1 = False self.trigger1count = 0 if (self.trigger2 == True): self.trigger2count = self.trigger2count+1 angleChange = pow(pow(gx, 2)+pow(gy, 2)+pow(gz, 2), 0.5) # Trigger2 function # //if orientation changes by between 1-40 degrees if (angleChange >= ANGULAR_VELOCITY_LOW_THREADHOLD and angleChange <= ANGULAR_VELOCITY_UP_THREADHOLD): self.trigger2 = False self.trigger2count = 0 fall = True return fall if (fall == True): # //in event of a fall detection fall = False if (self.trigger2count >= 50): # //allow time for orientation change self.trigger2 = False self.trigger2count = 0 # print("TRIGGER 2 DECACTIVATED") if (self.trigger1count >= 5): # //allow time for accelerationChange to break upper threshold self.trigger1 = False self.trigger1count = 0 # print("TRIGGER 1 DECACTIVATED") return fall
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/fall_detection/esp32/code/motion/detections/fall_detection.py
Python
apache-2.0
4,794
import utime # 延时函数在utime ITER_NUM = 100 class tap_detection: def __init__(self, tap_detect_count, getData): self.ax_offset = 0.0 self.ay_offset = 0.0 self.az_offset = 0.0 self.triggercount = 0 self.untriggercount = 0 self.tapcount = 0 self.tap_detect_count = tap_detect_count if (self.tap_detect_count == 2): self.accelerator_up_threshold = 30.0 elif (self.tap_detect_count == 1): self.accelerator_up_threshold = 30.0 self.latency = 150 self.getData = getData self.calibrate() def calibrate(self): ax_sum = 0.0 ay_sum = 0.0 az_sum = 0.0 for num in range(0, ITER_NUM): data = self.getData() # 读取传感器信息值 ax_sum += data[0][0] ay_sum += data[0][1] az_sum += data[0][2] self.ax_offset = ax_sum/ITER_NUM self.ay_offset = ay_sum/ITER_NUM self.az_offset = az_sum/ITER_NUM self.accelerator_low_threshold = 0.0 for num in range(0, ITER_NUM): data = self.getData() # 读取传感器信息值 ax = data[0][0] ay = data[0][1] az = data[0][2] ax = (ax-self.ax_offset) ay = (ay-self.ay_offset) az = (az-self.az_offset) Raw_accelerationChange = pow(pow(ax, 2)+pow(ay, 2)+pow(az, 2), 0.5) # Multiplied by 10 to values are between 0 to 1 self.accelerator_low_threshold += Raw_accelerationChange * 10 self.accelerator_low_threshold = ( self.accelerator_low_threshold / ITER_NUM)*2 print('Now you can start tap detection!') def detect(self): fall = False data = self.getData() # 读取传感器信息值 AcX = data[0][0] AcY = data[0][1] AcZ = data[0][2] ax = (AcX-self.ax_offset) ay = (AcY-self.ay_offset) az = (AcZ-self.az_offset) # calculating accelerationChangelitute vector for 3 axis Raw_accelerationChange = pow(pow(ax, 2)+pow(ay, 2)+pow(az, 2), 0.5) # Multiplied by 10 to values are between 0 to 1 accelerationChange = Raw_accelerationChange * 10 if (fall == True): fall = False if hasattr(self, 'sensitivity'): if 'ACCELERATION_UP_THREADHOLD' in self.sensitivity: self.accelerator_up_threshold = float( self.sensitivity['ACCELERATION_UP_THREADHOLD']) # Trigger function # if accelerationChange breaks lower threshold if (self.tap_detect_count == 2): if(accelerationChange >= self.accelerator_low_threshold and accelerationChange <= self.accelerator_up_threshold): self.triggercount = self.triggercount+1 if (self.triggercount % 3 == 0): # catch one tap self.tapcount = self.tapcount+1 utime.sleep_ms(100) if (self.tapcount == self.tap_detect_count): # catched tap_detect_count self.triggercount = 0 self.tapcount = 0 fall = True else: self.untriggercount = self.untriggercount+1 if (self.untriggercount == 150): self.triggercount = 0 self.tapcount = 0 self.untriggercount = 0 elif (self.tap_detect_count == 1): if(accelerationChange >= self.accelerator_low_threshold and accelerationChange <= self.accelerator_up_threshold): self.triggercount = self.triggercount+1 if (self.triggercount % 5 == 0): # catch one tap self.tapcount = self.tapcount+1 utime.sleep_ms(100) if (self.tapcount == self.tap_detect_count): # catched tap_detect_count self.triggercount = 0 self.tapcount = 0 fall = True else: self.untriggercount = self.untriggercount+1 if (self.untriggercount == 150): self.triggercount = 0 self.tapcount = 0 self.untriggercount = 0 return fall
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/fall_detection/esp32/code/motion/detections/tap_detection.py
Python
apache-2.0
4,356
import utime # 延时函数在utime from .detections.fall_detection import fall_detection from .detections.tap_detection import tap_detection class Motion: def __init__(self, action, getData, onActionDetected): self.action = action if (action == "fall"): self.detectAction = fall_detection(getData) elif (action == "single_tap"): self.detectAction = tap_detection(1, getData) elif (action == "double_tap"): self.detectAction = tap_detection(2, getData) self.onActionDetected = onActionDetected # 使能action检测,若用户不指定灵敏度,则使用默认灵敏度 def enable(self, sensitivity=''): self.enableDetection = True if (sensitivity != ''): self.detectAction.sensitivity = sensitivity self.detect_action() # 关闭action检测 def disable(self): self.enableDetection = False def detect_action(self): while(self.enableDetection == True): isDetected = self.detectAction.detect() # 检测Action是否产生 if (isDetected == True): # Action被检测到 print(self.action, "detected!") if (hasattr(self, 'onActionDetected')): self.onActionDetected() utime.sleep_us(10)
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/fall_detection/esp32/code/motion/motion.py
Python
apache-2.0
1,377
""" HaaSPython I2C driver for MPU6886 6-axis motion tracking device """ # pylint: disable=import-error import ustruct import utime # from machine import I2C, Pin from driver import I2C from micropython import const # pylint: enable=import-error _CONFIG = const(0x1a) _GYRO_CONFIG = const(0x1b) _ACCEL_CONFIG = const(0x1c) _ACCEL_CONFIG2 = const(0x1d) _ACCEL_XOUT_H = const(0x3b) _ACCEL_XOUT_L = const(0x3c) _ACCEL_YOUT_H = const(0x3d) _ACCEL_YOUT_L = const(0x3e) _ACCEL_ZOUT_H = const(0x3f) _ACCEL_ZOUT_L = const(0x40) _TEMP_OUT_H = const(0x41) _TEMP_OUT_L = const(0x42) _GYRO_XOUT_H = const(0x43) _GYRO_XOUT_L = const(0x44) _GYRO_YOUT_H = const(0x45) _GYRO_YOUT_L = const(0x46) _GYRO_ZOUT_H = const(0x47) _GYRO_ZOUT_L = const(0x48) _PWR_MGMT_1 = const(0x6b) _WHO_AM_I = const(0x75) ACCEL_FS_SEL_2G = const(0b00000000) ACCEL_FS_SEL_4G = const(0b00001000) ACCEL_FS_SEL_8G = const(0b00010000) ACCEL_FS_SEL_16G = const(0b00011000) _ACCEL_SO_2G = 16384 # 1 / 16384 ie. 0.061 mg / digit _ACCEL_SO_4G = 8192 # 1 / 8192 ie. 0.122 mg / digit _ACCEL_SO_8G = 4096 # 1 / 4096 ie. 0.244 mg / digit _ACCEL_SO_16G = 2048 # 1 / 2048 ie. 0.488 mg / digit GYRO_FS_SEL_250DPS = const(0b00000000) GYRO_FS_SEL_500DPS = const(0b00001000) GYRO_FS_SEL_1000DPS = const(0b00010000) GYRO_FS_SEL_2000DPS = const(0b00011000) _GYRO_SO_250DPS = 131 _GYRO_SO_500DPS = 62.5 _GYRO_SO_1000DPS = 32.8 _GYRO_SO_2000DPS = 16.4 _TEMP_SO = 326.8 _TEMP_OFFSET = 25 SF_G = 1 SF_M_S2 = 9.80665 # 1 g = 9.80665 m/s2 ie. standard gravity SF_DEG_S = 1 SF_RAD_S = 0.017453292519943 # 1 deg/s is 0.017453292519943 rad/s class MPU6886: 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,address=0x68): self.address = address if 0x19 != self.whoami: raise RuntimeError("MPU6886 not found in I2C bus.") self._register_char(_PWR_MGMT_1, 0b10000000) # reset utime.sleep_ms(100) self._register_char(_PWR_MGMT_1, 0b00000001) # autoselect clock accel_fs=ACCEL_FS_SEL_2G gyro_fs=GYRO_FS_SEL_250DPS accel_sf=SF_M_S2 gyro_sf=SF_RAD_S gyro_offset=(0, 0, 0) self._accel_so = self._accel_fs(accel_fs) self._gyro_so = self._gyro_fs(gyro_fs) self._accel_sf = accel_sf self._gyro_sf = gyro_sf self._gyro_offset = gyro_offset @property def acceleration(self): """ Acceleration measured by the sensor. By default will return a 3-tuple of X, Y, Z axis acceleration values in m/s^2 as floats. Will return values in g if constructor was provided `accel_sf=SF_M_S2` parameter. """ so = self._accel_so sf = self._accel_sf xyz = self._register_three_shorts(_ACCEL_XOUT_H) return tuple([value / so * sf for value in xyz]) @property def gyro(self): """ X, Y, Z radians per second as floats. """ so = self._gyro_so sf = self._gyro_sf ox, oy, oz = self._gyro_offset xyz = self._register_three_shorts(_GYRO_XOUT_H) xyz = [value / so * sf for value in xyz] xyz[0] -= ox xyz[1] -= oy xyz[2] -= oz return tuple(xyz) @property def temperature(self): """ Die temperature in celcius as a float. """ temp = self._register_short(_TEMP_OUT_H) # return ((temp - _TEMP_OFFSET) / _TEMP_SO) + _TEMP_OFFSET return (temp / _TEMP_SO) + _TEMP_OFFSET @property def whoami(self): """ Value of the whoami register. """ return self._register_char(_WHO_AM_I) def calibrate(self, count=256, delay=0): ox, oy, oz = (0.0, 0.0, 0.0) self._gyro_offset = (0.0, 0.0, 0.0) n = float(count) while count: utime.sleep_ms(delay) gx, gy, gz = self.gyro ox += gx oy += gy oz += gz count -= 1 self._gyro_offset = (ox / n, oy / n, oz / n) return self._gyro_offset def _register_short(self, register, value=None, buf=bytearray(2)): if value is None: # cmd = bytearray(2) # cmd[0] = self.address # cmd[1] = register # self._i2cDev.write(cmd) # self._i2cDev.read(buf) self._i2cDev.memRead(buf,register,8) # print(buf[0]) # self.i2c.readfrom_mem_into(self.address, register, buf) return ustruct.unpack(">h", buf)[0] ustruct.pack_into(">h", buf, 0, value) # cmd = bytearray(2) # cmd[0] = self.address # cmd[1] = register # self._i2cDev.write(cmd) # self._i2cDev.write(buf) self._i2cDev.memWrite(buf,register,8) # return self.i2c.writeto_mem(self.address, register, buf) def _register_three_shorts(self, register, buf=bytearray(6)): # cmd = bytearray(2) # cmd[0] = self.address # cmd[1] = register # self._i2cDev.write(cmd) # self._i2cDev.read(buf) self._i2cDev.memRead(buf,register,8) # self.i2c.readfrom_mem_into(self.address, register, buf) return ustruct.unpack(">hhh", buf) def _register_char(self, register, value=None, buf=bytearray(1)): if value is None: # cmd = bytearray(2) # cmd[0] = self.address # cmd[1] = register # self._i2cDev.write(cmd) # self._i2cDev.read(buf) self._i2cDev.memRead(buf,register,8) # print(buf[0]) # self.i2c.readfrom_mem_into(self.address, register, buf) return buf[0] ustruct.pack_into("<b", buf, 0, value) # cmd = bytearray(2) # cmd[0] = self.address # cmd[1] = register # self._i2cDev.write(cmd) # self._i2cDev.write(buf) return self._i2cDev.memWrite(buf,register,8) # return self.i2c.writeto_mem(self.address, register, buf) def _accel_fs(self, value): self._register_char(_ACCEL_CONFIG, value) # Return the sensitivity divider if ACCEL_FS_SEL_2G == value: return _ACCEL_SO_2G elif ACCEL_FS_SEL_4G == value: return _ACCEL_SO_4G elif ACCEL_FS_SEL_8G == value: return _ACCEL_SO_8G elif ACCEL_FS_SEL_16G == value: return _ACCEL_SO_16G def _gyro_fs(self, value): self._register_char(_GYRO_CONFIG, value) # Return the sensitivity divider if GYRO_FS_SEL_250DPS == value: return _GYRO_SO_250DPS elif GYRO_FS_SEL_500DPS == value: return _GYRO_SO_500DPS elif GYRO_FS_SEL_1000DPS == value: return _GYRO_SO_1000DPS elif GYRO_FS_SEL_2000DPS == value: return _GYRO_SO_2000DPS def __enter__(self): return self def __exit__(self, exception_type, exception_value, traceback): pass
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/fall_detection/esp32/code/mpu6886/mpu6886.py
Python
apache-2.0
7,149
from driver import ADC class Fire(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/fire_detector/esp32/code/fire.py
Python
apache-2.0
428
# -*- encoding: utf-8 -*- 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 fire # fire火焰传感器类 adcDev = 0 # ADC通道对象 ledDev = 0 # 报警LED对象 alarm_on = 0 # 记录报警状态 # 物联网平台连接标志位 iot_connected = False wlan = None # 物联网设备实例 device = None # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" def alarm_control(on): global ledDev if on == 0: ledDev.write(0) # GPIO写入0,执行灭灯操作 else: ledDev.write(1) # GPIO写入 1,执行亮灯报警动作 # 等待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): global alarm_on, device # {"alarmState":1} or {"alarmState":0} payload = ujson.loads(request['params']) # 获取dict状态字段 注意要验证键存在 否则会抛出异常 if "alarmState" in payload.keys(): print(payload) alarm_on = payload["alarmState"] if (alarm_on): print("开始报警") else: print("结束报警") # 根据云端设置的报警灯状态改变本地LED状态 alarm_control(alarm_on) # 要将更改后的状态同步上报到云平台 prop = ujson.dumps({ 'alarmState': alarm_on, }) 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_fire_detector_state(): global device, alarm_on fireVoltage = 0 # 无限循环 while True: fireVoltage = fireDev.getVoltage() # 获取电压值 print("The fire status Voltage ",fireVoltage) # 生成上报到物联网平台的属性值字串,此处的属性标识符"fireVoltage"和"alarmState"必须和物联网平台的属性一致 # "fireVoltage" - 代表燃气传感器测量到的电压值 # "alarmState" - 代表报警灯的当前状态 upload_data = {'params': ujson.dumps({ 'fireVoltage': fireVoltage, 'alarmState': alarm_on }) } # 上传火焰传感器检测电压信息和报警信息到物联网平台 device.postProps(upload_data) # 每2秒钟上报一次 utime.sleep(2) if __name__ == '__main__': global fireDev alarm_on = 0 # 硬件初始化 # 初始化 ADC adcDev = ADC() adcDev.open("fire") fireDev = fire.Fire(adcDev) # 初始化LED所连接GPIO ledDev = GPIO() ledDev.open("led") alarm_control(alarm_on) # 关闭报警灯 wlan = network.WLAN(network.STA_IF) #创建WLAN对象 # 请替换物联网平台申请到的产品和设备信息,可以参考README get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_fire_detector_state() adcDev.close() ledDev.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/fire_detector/esp32/code/main.py
Python
apache-2.0
5,548
from driver import ADC class Fire(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/fire_detector/haas200/code/fire.py
Python
apache-2.0
409
# -*- encoding: utf-8 -*- 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 fire # fire火焰传感器类 adcDev = 0 # ADC通道对象 ledDev = 0 # 报警LED对象 alarm_on = 0 # 记录报警状态 # 物联网平台连接标志位 iot_connected = False # 物联网设备实例 device = None # 三元组信息 # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" def alarm_control(on): global ledDev if on == 0: ledDev.write(0) # GPIO写入0,执行灭灯操作 else: ledDev.write(1) # GPIO写入 1,执行亮灯报警动作 # 等待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): global alarm_on, device # {"alarmState":1} or {"alarmState":0} payload = ujson.loads(request['params']) # 获取dict状态字段 注意要验证键存在 否则会抛出异常 if "alarmState" in payload.keys(): print(payload) alarm_on = payload["alarmState"] if (alarm_on): print("开始报警") alarm_control(1) else: alarm_control(0) print("结束报警") # 根据云端设置的报警灯状态改变本地LED状态 # alarm_control(alarm_on) # 要将更改后的状态同步上报到云平台 prop = ujson.dumps({ 'alarmState': alarm_on, }) 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_fire_detector_state(): global device, alarm_on fireVoltage = 0 # 无限循环 while True: fireVoltage = fireDev.getVoltage() # 获取电压值 print("The fire status Voltage ",fireVoltage) # 生成上报到物联网平台的属性值字串,此处的属性标识符"fireVoltage"和"alarmState"必须和物联网平台的属性一致 # "fireVoltage" - 代表燃气传感器测量到的电压值 # "alarmState" - 代表报警灯的当前状态 upload_data = {'params': ujson.dumps({ 'fireVoltage': fireVoltage, 'alarmState': alarm_on }) } # 上传火焰传感器检测电压信息和报警信息到物联网平台 device.postProps(upload_data) # 每2秒钟上报一次 utime.sleep(2) if __name__ == '__main__': global fireDev alarm_on = 0 # 硬件初始化。。。。。。。。。。。。。。。。。。 # 初始化 ADC adcDev = ADC() adcDev.open("fire") fireDev = fire.Fire(adcDev) # 初始化LED所连接GPIO ledDev = GPIO() ledDev.open("led") alarm_control(alarm_on) # 关闭报警灯 # 请替换物联网平台申请到的产品和设备信息,可以参考README get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_fire_detector_state() adcDev.close() ledDev.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/fire_detector/haas200/code/main.py
Python
apache-2.0
5,578
# 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') #当iot云端下发属性设置时,触发'props'事件 def on_props(request): params=request['params'] params=eval(params) warn = params["warning"] onoff_data["warning"]= warn onoff_data_str=ujson.dumps(onoff_data) data1={ 'params':onoff_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["flame"]= 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) #主程序, onoff_data = {} onoff_data["warning"]= 0 onoff_data_str=ujson.dumps(onoff_data) data1={ 'params':onoff_data_str } device.postProps(data1) #火焰传感器 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/fire_detector/haas506/code/main.py
Python
apache-2.0
5,463
from driver import ADC class Fire(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/fire_detector/haaseduk1/code/fire.py
Python
apache-2.0
411
# -*- encoding: utf-8 -*- from aliyunIoT import Device # aliyunIoT组件是连接阿里云物联网平台的组件 import utime # 延时API所在组件 import ujson # json字串解析库 import fire from driver import GPIO # HaaS EDU K1 LED使用GPIO进行控制 from driver import ADC # ADC类,通过微处理器的ADC模块读取ADC通道输入电压 import netmgr as nm # netmgr是Wi-Fi网络连接的组件 adcDev = 0 # ADC通道对象 ledDev = 0 # 报警LED对象 alarm_on = 0 # 记录报警状态 # 物联网平台连接标志位 iot_connected = False # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" # 物联网设备实例 device = None def alarm_control(on): global ledDev if on == 0: ledDev.write(0) # GPIO写入0,执行灭灯操作 else: ledDev.write(1) # GPIO写入 1,执行亮灯报警动作 # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): nm.init() nm.disconnect() wifi_connected = nm.getStatus() # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) print("start to connect " , wifiSsid) nm.connect(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 on_connect(data): global iot_connected iot_connected = True # 设置props 事件接收函数(当云平台向设备下发属性时) def on_props(request): global alarm_on, device # print(request) payload = ujson.loads(request['params']) # 获取dict状态字段 注意要验证键存在 否则会抛出异常 if "alarmState" in payload.keys(): alarm_on = payload["alarmState"] if (alarm_on): print("开始报警") else: print("结束报警") # print(alarm_on) # 根据云端设置的报警灯状态改变本地LED状态 alarm_control(alarm_on) # 要将更改后的状态同步上报到云平台 prop = ujson.dumps({'alarmState': alarm_on}) # print('uploading data: ', prop) 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_fire_detector_state(): global device, alarm_on fireVoltage = 0 # 无限循环 while True: fireVoltage = fireDev.getVoltage() # 获取电压值 # print("The fire status Voltage ",fireVoltage) # 生成上报到物联网平台的属性值字串 # 此处的属性标识符"fireVoltage"和"alarmState"必须和物联网平台的属性一致 # "fireVoltage" - 代表燃气传感器测量到的电压值 # "alarmState" - 代表报警灯的当前状态 prop = ujson.dumps({ 'fireVoltage': fireVoltage, 'alarmState': alarm_on }) print("uploading data to the cloud, ", prop) upload_data = {'params': prop} # 上传火焰传感器测量结果和报警灯状态到物联网平台 device.postProps(upload_data) # 每2秒钟上报一次 utime.sleep(2) if __name__ == '__main__': global fireDev alarm_on = 0 # 硬件初始化 # 初始化 ADC adcDev = ADC() adcDev.open("fire") fireDev = fire.Fire(adcDev) # 初始化LED所连接GPIO ledDev = GPIO() ledDev.open("led_r") alarm_control(alarm_on) # 关闭报警灯 # 请替换物联网平台申请到的产品和设备信息,可以参考文章:https://blog.csdn.net/HaaSTech/article/details/114360517 get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_fire_detector_state() adcDev.close() ledDev.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/fire_detector/haaseduk1/code/main.py
Python
apache-2.0
5,330
from driver import ADC class Fire(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/fire_detector/stm32/code/fire.py
Python
apache-2.0
409
# -*- encoding: utf-8 -*- from ulinksdk.aliyunIoT import Device # iot组件是连接阿里云物联网平台的组件 import network import utime # 延时API所在组件 import ujson # json字串解析库 from driver import GPIO # LED需使用GPIO进行控制 from driver import ADC # ADC类,通过微处理器的ADC模块读取ADC通道输入电压 import fire # fire火焰传感器类 adcDev = 0 # ADC通道对象 ledDev = 0 # 报警LED对象 alarm_on = 0 # 记录报警状态 # 物联网平台连接标志位 iot_connected = False # 物联网设备实例 device = None # 三元组信息 # 三元组信息 productKey = "产品密钥" deviceName = "设备名字" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifiSsid = "请填写您的路由器名称" wifiPassword = "请填写您的路由器密码" def alarm_control(on): global ledDev if on == 0: ledDev.write(0) # GPIO写入0,执行灭灯操作 else: ledDev.write(1) # GPIO写入 1,执行亮灯报警动作 # 等待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): global alarm_on, device # {"alarmState":1} or {"alarmState":0} payload = ujson.loads(request['params']) # 获取dict状态字段 注意要验证键存在 否则会抛出异常 if "alarmState" in payload.keys(): print(payload) alarm_on = payload["alarmState"] if (alarm_on): print("开始报警") alarm_control(1) else: alarm_control(0) print("结束报警") # 根据云端设置的报警灯状态改变本地LED状态 alarm_control(alarm_on) # 要将更改后的状态同步上报到云平台 prop = ujson.dumps({ 'alarmState': alarm_on, }) 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_fire_detector_state(): global device, alarm_on fireVoltage = 0 # 无限循环 while True: fireVoltage = fireDev.getVoltage() # 获取电压值 print("The fire status Voltage ",fireVoltage) # 生成上报到物联网平台的属性值字串,此处的属性标识符"fireVoltage"和"alarmState"必须和物联网平台的属性一致 # "fireVoltage" - 代表燃气传感器测量到的电压值 # "alarmState" - 代表报警灯的当前状态 upload_data = {'params': ujson.dumps({ 'fireVoltage': fireVoltage, 'alarmState': alarm_on }) } # 上传火焰传感器检测电压信息和报警信息到物联网平台 device.postProps(upload_data) # 每2秒钟上报一次 utime.sleep(2) if __name__ == '__main__': global fireDev alarm_on = 0 # 硬件初始化。。。。。。。。。。。。。。。。。。 # 初始化 ADC adcDev = ADC() adcDev.open("fire") fireDev = fire.Fire(adcDev) # 初始化LED所连接GPIO ledDev = GPIO() ledDev.open("led") alarm_control(alarm_on) # 关闭报警灯 # 请替换物联网平台申请到的产品和设备信息,可以参考README nic = network.LAN() nic.active(1) connect_lk(productKey, deviceName, deviceSecret) upload_fire_detector_state() adcDev.close() ledDev.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/fire_detector/stm32/code/mian.py
Python
apache-2.0
5,739
# -*- 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所在组件 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类型设备对象 print("sht3x inited!") 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 get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_temperature_and_Humidity() i2cObj.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/floriculture/ESP-C3-32S-Kit/code/main.py
Python
apache-2.0
7,134
""" 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/floriculture/ESP-C3-32S-Kit/code/sht3x.py
Python
apache-2.0
4,279
# -*- 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所在组件 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类型设备对象 print("sht3x inited!") 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 get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_temperature_and_Humidity() i2cObj.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/floriculture/ESP-S3-12K-Kit/code/main.py
Python
apache-2.0
7,134
""" 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/floriculture/ESP-S3-12K-Kit/code/sht3x.py
Python
apache-2.0
4,279
# -*- 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所在组件 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类型设备对象 print("sht3x inited!") 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 get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_temperature_and_Humidity() i2cObj.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/floriculture/esp32/code/main.py
Python
apache-2.0
7,134
""" 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/floriculture/esp32/code/sht3x.py
Python
apache-2.0
4,279
# -*- 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所在组件 from driver import I2C # I2C总线驱动库 from driver import GPIO # Haas200和使用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 # 物联网设备实例 device = None i2cObj = None humitureDev = 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) # 通过温湿度传感器读取温湿度信息 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类型设备对象 print("sht3x inited!") humitureDev = sht3x.SHT3X(i2cObj) # 初始化SHT3X-DIS传感器 # 初始化 GPIO airconditioner = GPIO() humidifier = GPIO() humidifier.open('led_g') # 加湿器使用board.json中led_g节点定义的GPIO,对应Haas200外接的的绿灯 airconditioner.open('led_b') # 空调使用board.json中led_b节点定义的GPIO,对应Haas200外接的上的蓝灯 # 请替换物联网平台申请到的产品和设备信息,可以参考README.md get_wifi_status() connect_lk(productKey, deviceName, deviceSecret) upload_temperature_and_Humidity() i2cObj.close()
YifuLiu/AliOS-Things
haas_lib_bundles/python/docs/examples/floriculture/haas200/code/main.py
Python
apache-2.0
6,860
""" 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/haas200/code/sht3x.py
Python
apache-2.0
3,599