nvram json read write for esp32 & pyboard

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
User avatar
devnull
Posts: 473
Joined: Sat Jan 07, 2017 1:52 am
Location: Singapore / Cornwall
Contact:

nvram json read write for esp32 & pyboard

Post by devnull » Mon Jun 04, 2018 2:54 am

Based on the info gathered from here ( viewtopic.php?f=6&t=953 ) I have created a json read / write module, hopefully someone else will find it useful.


jram.py

Code: Select all

import json
from sys import platform

if platform == 'pyboard':
  
  import stm, uctypes
  
  class JRAM(object):
    BKPSRAM = 0x40024000
    def __init__(self):
      stm.mem32[stm.RCC + stm.RCC_APB1ENR] |= 0x10000000    # PWREN bit
      stm.mem32[stm.PWR + stm.PWR_CR] |= 0x100              # Set the DBP bit in the PWR power control register
      stm.mem32[stm.RCC +stm.RCC_AHB1ENR]|= 0x40000         # enable BKPSRAMEN
      stm.mem32[stm.PWR + stm.PWR_CSR] |= 0x200             # BRE backup register enable bit
    
    def __getitem__(self, idx):
      assert idx >= 0 and idx <= 0x3ff, "Index must be between 0 and 1023"
      return stm.mem32[self.BKPSRAM + idx * 4]
    
    def __setitem__(self, idx, val):
      assert idx >= 0 and idx <= 0x3ff, "Index must be between 0 and 1023"
      stm.mem32[self.BKPSRAM + idx * 4] = val
    
    def get_bytearray(self):
      return uctypes.bytearray_at(self.BKPSRAM, 4096)
  
    def clr(self):
      self.put({})
      return self.get()  
      
    def get(self):
      ba = self.get_bytearray()
      try:
        return json.loads(bytes(ba[4:4+self[0]]).decode("utf-8"))
      except:
        return self.clr()
        
    def put(self,a):
      ba = self.get_bytearray()
      z = json.dumps(a).encode('utf8')
      self[0] = len(z)
      ba[4: 4+len(z)] = z

elif platform.startswith('esp32'):
  from machine import RTC
  rtc = RTC()
  
  class JRAM():

    ## Non Volatile JSON
    def get(self):
      try:return json.loads(rtc.memory().decode('ascii'))
      except: return {}
    
    def put(self,dic):
      rtc.memory(json.dumps(dic))
  
    def clr(self):
      put({})
      return get()
    
## usage
# from jram import JRAM as nvr
# nvr().clr()
# nvr().put({'elephants': 9, 'rats': 77, 'dogs': 99, 'zoo': 100})
# nvr().get()

LisaM
Posts: 19
Joined: Tue Nov 07, 2017 6:11 pm

Re: nvram json read write for esp32 & pyboard

Post by LisaM » Thu Aug 09, 2018 4:31 pm

This doesn't work for the ESP32, the RTC memory is cleared during startup (and therefor also after a machine.reset() ).. :(

Post Reply