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()