Reduction of memory use and fragmentation

Add onbaord LED as "read-only flash" indicator
This commit is contained in:
Pierrick C 2018-08-03 19:59:34 +02:00
parent 2a1aae6da8
commit f07f998771

View File

@ -44,7 +44,7 @@ neopixel_max_value =const(70) #max value instead of brightness to spare some
####################### #######################
import board, microcontroller import microcontroller
import gc, os import gc, os
# import micropython # import micropython
import time, rtc import time, rtc
@ -63,59 +63,57 @@ import neopixel
class Data: class Data:
"""Class for handling data""" """Class for handling data"""
def __init__(self): def __init__(self):
self.data = {'SYS': {'time': {'val': "2000/01/01_00:00:00", 'unit': '' }, self.data = {'SYS': {'time': "2000/01/01_00:00:00",
'vbat': {'val': int(), 'unit': 'V' }, 'vbat': int(),
'CPUtemp': {'val': float(), 'unit': '°C' }}, 'cput': float()},
'BME280': {'temp': { 'val': float(), 'unit': '°C' }, 'BME': {'temp': float(),
'hum': { 'val': int(), 'unit': '%' }, 'hum': int(),
'press': { 'val': float(), 'unit': 'hPa' }}, 'press': float()},
'GPS': {'timestamp': {'val': "2000/01/01_00:00:00", 'unit': ''}, 'GPS': {'time': "2000/01/01_00:00:00",
'lat': {'val': float(), 'unit': 'deg'}, 'lat': float(),
'lon': {'val': float(), 'unit': 'deg'}, 'lon': float(),
'alt': {'val': float(), 'unit': 'm'}, 'alt': float(),
'qual': {'val': int(), 'unit': ''}} 'qual': int()}
} }
def update(self): def update(self):
"""Read the data from various sensors and update the data dict variable""" """Read the data from various sensors and update the data dict variable"""
#Data from Feather board #Data from Feather board
self.data['SYS']['time']['val'] = datetime_format.format(*clock.datetime[0:6]) self.data['SYS']['time'] = datetime_format.format(*clock.datetime[0:6])
self.data['SYS']['vbat']['val'] = round(measure_vbat(), 3) self.data['SYS']['vbat'] = round(measure_vbat(), 3)
self.data['SYS']['CPUtemp']['val'] = round(microcontroller.cpu.temperature, 2) self.data['SYS']['cput'] = round(microcontroller.cpu.temperature, 2)
#Data from BME280 #Data from BME280
self.data['BME280']['temp']['val'] = round(bme280.temperature, 1) self.data['BME']['temp'] = round(bme280.temperature, 1)
self.data['BME280']['hum']['val'] = int(bme280.humidity) self.data['BME']['hum'] = int(bme280.humidity)
self.data['BME280']['press']['val'] = round(bme280.pressure, 2) self.data['BME']['press'] = round(bme280.pressure, 2)
if gps_enable: if gps_enable:
if gps.has_fix: if gps.has_fix:
self.data['GPS']['timestamp']['val'] = datetime_format.format(gps.timestamp_utc.tm_year, self.data['GPS']['time'] = datetime_format.format(gps.timestamp_utc.tm_year,
gps.timestamp_utc.tm_mon, gps.timestamp_utc.tm_mon,
gps.timestamp_utc.tm_mday, gps.timestamp_utc.tm_mday,
gps.timestamp_utc.tm_hour, gps.timestamp_utc.tm_hour,
gps.timestamp_utc.tm_min, gps.timestamp_utc.tm_min,
gps.timestamp_utc.tm_sec) gps.timestamp_utc.tm_sec)
self.data['GPS']['lat']['val'] = gps.latitude self.data['GPS']['lat'] = gps.latitude
self.data['GPS']['lon']['val'] = gps.longitude self.data['GPS']['lon'] = gps.longitude
self.data['GPS']['alt']['val'] = gps.altitude_m self.data['GPS']['alt'] = gps.altitude_m
self.data['GPS']['qual']['val'] = gps.fix_quality self.data['GPS']['qual'] = gps.fix_quality
else: else:
self.data['GPS']['lat']['val'] = None self.data['GPS']['lat'] = None
self.data['GPS']['lon']['val'] = None self.data['GPS']['lon'] = None
self.data['GPS']['alt']['val'] = None self.data['GPS']['alt'] = None
else: else:
self.data['GPS'] = None self.data['GPS'] = None
def show(self): def show(self):
"""Serialize data to json-formatted string for visualization on """Serialize data for visualization on serial console"""
serial console
"""
for source in self.data.keys(): for source in self.data.keys():
print(source + ": ") print(source + ": ")
if not self.data[source] == None: if not self.data[source] == None:
for d in self.data[source].items(): for d in self.data[source].items():
print("\t{0}: {val} {unit}".format(d[0], **d[1])) print("\t{0}: {1}".format(d[0], d[1]))
def json(self): def json(self):
"""Serialize data to json-formatted string""" """Serialize data to json-formatted string"""
@ -124,31 +122,27 @@ class Data:
output = "".join((output, "'", source, "': \n")) output = "".join((output, "'", source, "': \n"))
if not self.data[source] == None: if not self.data[source] == None:
for d in self.data[source].items(): for d in self.data[source].items():
output = "".join((output, "{", output = "".join((output, " {'{}': '{}'}}\n".format(d[0], d[1])))
"'{}': ".format(d[0]),
"{",
"'val': {val},'unit': {unit}".format(**d[1]),
"}}\n"))
output = output + "}, \n" output = output + "}, \n"
output = output + "}" output = output + "}"
return output return output
def atmo2rgb(self): def atmo2rgb(self):
"""Congreen atmospheric data from BME280 sensor into NeoPixel color """Convert atmospheric data from BME280 sensor into NeoPixel color
* RED => temperature : max = 35degC, min =10degC (range 25°C) * RED => temperature : max = 35degC, min =10degC (range 25°C)
* BLUE => humidity : max= 100%, mini=0% * BLUE => humidity : max= 100%, mini=0%
* GREEN => pression : mini=960hPa, maxi = 1030hPa (range 70hPa) * GREEN => pression : mini=960hPa, maxi = 1030hPa (range 70hPa)
""" """
red = int((self.data['BME280']['temp']['val']-10)*neopixel_max_value/25) red = int((self.data['BME']['temp']-10)*neopixel_max_value/25)
if red > neopixel_max_value: if red > neopixel_max_value:
red = neopixel_max_value red = neopixel_max_value
if red < 0: if red < 0:
red = 0 red = 0
blue = int(self.data['BME280']['hum']['val']*neopixel_max_value/100) blue = int(self.data['BME']['hum']*neopixel_max_value/100)
green = int((self.data['BME280']['press']['val']-960)*neopixel_max_value/70) green = int((self.data['BME']['press']-960)*neopixel_max_value/70)
if green > neopixel_max_value: if green > neopixel_max_value:
green = neopixel_max_value green = neopixel_max_value
if green < 0: if green < 0:
@ -163,14 +157,14 @@ class Data:
"""Save the current data as csv file on SPI flash""" """Save the current data as csv file on SPI flash"""
try: try:
with open("data/data.csv", "a") as csv_file: with open("data/data.csv", "a") as csv_file:
csv_file.write("{};{};{};{}\n".format(self.data['SYS']['time']['val'], csv_file.write("{};{};{};{}\n".format(self.data['SYS']['time'],
self.data['BME280']['temp']['val'], self.data['BME']['temp'],
self.data['BME280']['hum']['val'], self.data['BME']['hum'],
self.data['BME280']['press']['val'])) self.data['BME']['press']))
except OSError as e: except OSError as e:
print("Err. {} : R-O FS".format(e)) print("Err {}: readonly".format(e))
backup_data = False #to avoid trying again till next reset backup_data = False #to avoid trying again till next reset
led13.value = True
############# #############
# Functions # # Functions #
@ -229,22 +223,27 @@ clock = rtc.RTC()
#clock.datetime = time.struct_time((2018, 7, 29, 15, 31, 30, 0, 0, 0)) #clock.datetime = time.struct_time((2018, 7, 29, 15, 31, 30, 0, 0, 0))
# BME280 sensors (I2C) # BME280 sensors (I2C)
i2c = I2C(board.SCL, board.SDA) i2c = I2C(microcontroller.pin.PA23, microcontroller.pin.PA22)
# i2c addresses for BME280 breakout : # i2c addresses for BME280 breakout :
# 0x77 = adafruit breakout board # 0x77 = adafruit breakout board
# 0x76 = tiny chinese board # 0x76 = tiny chinese board
bme280 = Adafruit_BME280_I2C(i2c, address=0x76) bme280 = Adafruit_BME280_I2C(i2c, address=0x76)
# Battery voltage # Battery voltage
vbat = AnalogIn(board.D9, ) vbat = AnalogIn(microcontroller.pin.PA07)
gps_en_pin = DigitalInOut(board.A5) gps_en_pin = DigitalInOut(microcontroller.pin.PB02)
gps_en_pin.direction = Direction.OUTPUT gps_en_pin.direction = Direction.OUTPUT
led13 = DigitalInOut(microcontroller.pin.PA17)
led13.direction = Direction.OUTPUT
led13.value = False
# GPS on FeatherWing board # GPS on FeatherWing board
gps_en_pin.value = not gps_enable gps_en_pin.value = not gps_enable
if gps_enable: if gps_enable:
gps_uart = UART(board.TX, board.RX, baudrate=9600, timeout=3000) gps_uart = UART(microcontroller.pin.PA10, microcontroller.pin.PA11,
baudrate=9600, timeout=3000)
gps = GPS(gps_uart) gps = GPS(gps_uart)
# Turn on the basic GGA and RMC info # Turn on the basic GGA and RMC info
gps.send_command('PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0') gps.send_command('PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0')
@ -252,10 +251,10 @@ if gps_enable:
# Integrated Neopixel # Integrated Neopixel
if data_to_neopixel: if data_to_neopixel:
pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=1) pixel = neopixel.NeoPixel(microcontroller.pin.PA06, 1, brightness=1)
else: else:
#if neopixel is disable : turn off the LED #if neopixel is disable : turn off the LED
pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=1) pixel = neopixel.NeoPixel(microcontroller.pin.PA06, 1, brightness=1)
pixel[0] = (0,0,0) pixel[0] = (0,0,0)
pixel = None pixel = None