Skip to content

Instantly share code, notes, and snippets.

@cwyark
Created June 12, 2017 07:28
Show Gist options
  • Save cwyark/bf8f61f2eee997f224c8b3ad6763d805 to your computer and use it in GitHub Desktop.
Save cwyark/bf8f61f2eee997f224c8b3ad6763d805 to your computer and use it in GitHub Desktop.
import sys, gc
import umachine as machine
import uterminal
from umachine import SPI, Pin, I2C
sys.path.append("/flash/lib")
#debug_uart = machine.UART(2, tx="PA_4", rx="PA_0", baudrate=115200)
#debug_uart.init()
#uterminal.register(debug_uart)
try:
from sdcard import SDCard
import sht2x, ds1338, logging
except ImportError as e:
print("Can not import module, cause:{}".format(e))
f = open(sys_log_filename, "a")
f.write(e)
f.close()
exit(0)
syslog_flash_filename = "/flash/logging.txt"
syslog_sd_filename = "/sd/logging.txt"
sensorlog_sd_filename = "/sd/data.txt"
hw_logger = logging.getLogger("hardware")
sys_logger = logging.getLogger("system")
i2c_sda_pin = "PD_4"
i2c_scl_pin = "PD_5"
spi_miso_pin = "PC_3"
spi_mosi_pin = "PC_2"
spi_sck_pin = "PC_1"
spi_cs_pin = "PB_4"
spi = SPI(0, miso=spi_miso_pin, mosi=spi_mosi_pin, sck=spi_sck_pin)
cs = Pin(spi_cs_pin, Pin.OUT)
i2c = I2C(0, sda=i2c_sda_pin, scl=i2c_scl_pin)
sht20_drv = sht2x.SHT20Drv(i2c)
ds1338_drv = ds1338.DS1338Drv(i2c)
def msg_datetime_processed(msg):
now = ds1338_drv.getCurrentTime()
return "[{year}/{month}/{day} {hour}:{minute}:{second}] {msg}".format(year=now[6] + 6, month=now[5],
day=now[4], hour=now[2], minute=now[1], second=now[0], msg=msg)
def info(logger, msg):
logger.info(msg_datetime_processed(msg))
def flash_logging(msg):
msg += "\\r\\n"
f = open(syslog_flash_filename, "a")
f.write(msg_datetime_processed(msg))
f.close()
def sd_logging(msg):
msg += "\\r\\n"
f = open(syslog_sd_filename, "a")
f.write(msg_datetime_processed(msg))
f.close()
try:
info(hw_logger, "Checking SD card is valid or not.")
sd = SDCard(spi, cs)
info(hw_logger, "Check SD card success, now mounting SD card to vfs.")
sdvfs = uos.VfsFat(sd)
uos.mount(sdvfs, '/sd')
info(hw_logger, "SD card mount success")
except OSError as e:
info(hw_logger, "SD card initialize failed, cause = {}".format(e))
flash_logging("SD card initialize failed, cause = {}".format(e))
sd_logging("Wake from low power sleep and start to record")
info(sys_logger, "Append '/sd' to system path")
sys.path.append("/sd")
config_sleep_interval = 10 # default sleep interval is 10 seconds
config_debug = False
config_cvs_format = "{year},{month},{day},{hour},{minute},{second},{temperature},{humidity}\\r\\n"
config_wdt_interval = 60
try:
from config import *
except ImportError as e:
info(sys_logger, "Import config.py from '/sd' failed, skiping and run as default environment")
sd_logging("Import config.py from '/sd' failed, skiping and run as default environment")
info(sys_logger, "Low power sleeping interval is %d seconds" % config_sleep_interval)
info(sys_logger, "Debug mode is %d" % config_debug)
info(sys_logger, "csv format is %s" % config_cvs_format)
wdt = umachine.WDT()
info(sys_logger, "Starting watch dog timer, count down = %d seconds" % config_wdt_interval)
wdt.start(config_wdt_interval * 1000)
try:
current_temp = sht20_drv.readTemp()[0]
info(hw_logger, "Measured temperature is {}".format(current_temp))
except Exception as e:
info(hw_logger, "Measure temperature failed, cause: {}".format(e))
sd_logging("Measure temperature failed, cause: {}".format(e))
current_temp = 0
try:
current_humi = sht20_drv.readHumi()[0]
info(hw_logger, "Measured humidity is {}".format(current_humi))
except Exception as e:
info(hw_logger, "Measure humidity failed, cause: {}".format(e))
sd_logging("Measure humidity failed, cause: {}".format(e))
current_humi = 0
info(sys_logger, "Writing sensor informations in csv format to file:{}".format(sensorlog_sd_filename))
def sd_sensor_logging():
now = ds1338_drv.getCurrentTime()
with open(sensorlog_sd_filename, "a") as f:
csv = config_cvs_format.format(year=now[6]+6, month=now[5], day=now[4], hour=now[2],
minute=now[1], second=now[0], temperature=current_temp, humidity=current_humi)
length = len(csv)
ret = f.write(csv)
if ret != length:
raise OSError("write data is not equal to length, exception")
info(sys_logger, "Start to log sensor data to SD card ....")
try:
sd_sensor_logging();
except Exception as e:
info(sys_logger, "Recording failed!!!!!!!!")
flash_logging(str(e))
info(sys_logger, "End of log sensor data to SD card ....")
info(sys_logger, "Low power sleeping for %d seconds ...." % config_sleep_interval)
sd_logging("End of record and going to sleep mode");
machine.deepsleep(config_sleep_interval * 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment