-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpersistent_ram.py
More file actions
55 lines (46 loc) · 1.87 KB
/
persistent_ram.py
File metadata and controls
55 lines (46 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""
PersistentRam
provides convenient access to the alarm.sleep_memory.
The PersistentRam stores the current state of the program (I, U, W, or T) and
the current weather data from the last time the network was accessed.
Memory map:
Location Content
0 state - either a 'I', 'U', 'W' or 'T'
1:5 length - the length of the JSON string that holds the weather data
5: the data
"""
import alarm
import struct
import json
class PersistentRam:
@property
def state(self):
# states are 'I' for initialize and 'U' for update, W for weather, T for time
if chr(alarm.sleep_memory[0]) in ['I', 'U', 'W', 'T']:
return chr(alarm.sleep_memory[0])
else:
alarm.sleep_memory[0] = ord('I')
return 'I'
@state.setter
def state(self, value):
if value not in ['I', 'U', 'W', 'T']:
raise ValueError('State value must be "I", "U", "W" or "T"')
alarm.sleep_memory[0] = ord(value)
@property
def weather_data(self):
# returns the weather data as a dict
# retrieve the length of the weather data string
# retrieve the weather data string, convert to a dict and return
wd_len = struct.unpack('I', alarm.sleep_memory[1:5])[0]
wd_str = alarm.sleep_memory[5:5+wd_len].decode()
return json.loads(wd_str)
@weather_data.setter
def weather_data(self, wd_json):
# Convert the JSON dict to a string
# save the length of the string and the string of weather data
wd_str = json.dumps(wd_json)
wd_len = len(wd_str)
if wd_len > len(alarm.sleep_memory) - 5:
raise ValueError('Length of weather data exceeds available size')
alarm.sleep_memory[1:5] = struct.pack('I', wd_len) # used to convert bytes <-> unsigned int
alarm.sleep_memory[5:wd_len+5] = bytearray(wd_str.encode('ascii'))