Skip to content

Commit e47ba72

Browse files
committed
Add API to get brightness, animate, sleep statuses
Signed-off-by: Daniel Schaefer <[email protected]>
1 parent eccd056 commit e47ba72

File tree

3 files changed

+116
-28
lines changed

3 files changed

+116
-28
lines changed

control.py

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
]
2929
DRAW_PATTERNS = ['off', 'on', 'foo']
3030
GREYSCALE_DEPTH = 32
31+
RESPONSE_SIZE = 32
3132
WIDTH = 9
3233
HEIGHT = 34
3334

@@ -42,10 +43,16 @@ def main():
4243
action="store_true")
4344
parser.add_argument('--sleep', help='Simulate the host going to sleep or waking up',
4445
action=argparse.BooleanOptionalAction)
46+
parser.add_argument('--is-sleeping', help='Check current sleep state',
47+
action='store_true')
4548
parser.add_argument("--brightness", help="Adjust the brightness. Value 0-255",
4649
type=int)
50+
parser.add_argument("--get-brightness", help="Get current brightness",
51+
action="store_true")
4752
parser.add_argument('--animate', action=argparse.BooleanOptionalAction,
4853
help='Start/stop vertical scrolling')
54+
parser.add_argument('--get-animate', action='store_true',
55+
help='Check if currently animating')
4956
parser.add_argument("--pattern", help='Display a pattern',
5057
type=str, choices=PATTERNS)
5158
parser.add_argument("--image", help="Display a PNG or GIF image in black and white only)",
@@ -88,11 +95,19 @@ def main():
8895
elif args.sleep is not None:
8996
command = FWK_MAGIC + [0x03, args.sleep]
9097
send_command(command)
98+
elif args.is_sleeping:
99+
command = FWK_MAGIC + [0x03]
100+
res = send_command(command, with_response=True)
101+
sleeping = bool(res[0])
102+
print(f"Currently sleeping: {sleeping}")
91103
elif args.brightness is not None:
92104
if args.brightness > 255 or args.brightness < 0:
93105
print("Brightness must be 0-255")
94106
sys.exit(1)
95107
brightness(args.brightness)
108+
elif args.get_brightness:
109+
br = get_brightness()
110+
print(f"Current brightness: {br}")
96111
elif args.percentage is not None:
97112
if args.percentage > 100 or args.percentage < 0:
98113
print("Percentage must be 0-100")
@@ -102,6 +117,9 @@ def main():
102117
pattern(args.pattern)
103118
elif args.animate is not None:
104119
animate(args.animate)
120+
elif args.get_animate:
121+
animating = get_animate()
122+
print(f"Currently animating: {animating}")
105123
elif args.panic:
106124
command = FWK_MAGIC + [0x05, 0x00]
107125
send_command(command)
@@ -154,13 +172,29 @@ def brightness(b: int):
154172
send_command(command)
155173

156174

175+
def get_brightness():
176+
"""Adjust the brightness scaling of the entire screen.
177+
"""
178+
command = FWK_MAGIC + [0x00]
179+
res = send_command(command, with_response=True)
180+
return int(res[0])
181+
182+
157183
def animate(b: bool):
158184
"""Tell the firmware to start/stop animation.
159185
Scrolls the currently saved grid vertically down."""
160186
command = FWK_MAGIC + [0x04, b]
161187
send_command(command)
162188

163189

190+
def get_animate():
191+
"""Tell the firmware to start/stop animation.
192+
Scrolls the currently saved grid vertically down."""
193+
command = FWK_MAGIC + [0x04]
194+
res = send_command(command, with_response=True)
195+
return bool(res[0])
196+
197+
164198
def image_bl(image_file):
165199
"""Display an image in black and white
166200
Confirmed working with PNG and GIF.
@@ -600,14 +634,19 @@ def clock():
600634
time.sleep(1)
601635

602636

603-
def send_command(command):
637+
def send_command(command, with_response=False):
604638
"""Send a command to the device.
605639
Opens new serial connection every time"""
606640
# print(f"Sending command: {command}")
607641
global SERIAL_DEV
608642
with serial.Serial(SERIAL_DEV, 115200) as s:
609643
s.write(command)
610644

645+
if with_response:
646+
res = s.read(RESPONSE_SIZE)
647+
#print(f"Received: {res}")
648+
return res
649+
611650

612651
def send_serial(s, command):
613652
"""Send serial command by using existing serial connection"""

src/bin/ledmatrix.rs

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -265,21 +265,32 @@ fn main() -> ! {
265265
// Do nothing
266266
}
267267
Ok(count) => {
268-
if let Some(command) = parse_command(count, &buf) {
269-
if let Command::Sleep(go_sleeping) = command {
268+
match (parse_command(count, &buf), &state.sleeping) {
269+
(Some(Command::Sleep(go_sleeping)), _) => {
270270
handle_sleep(
271271
go_sleeping,
272272
&mut state,
273273
&mut matrix,
274274
&mut delay,
275275
&mut led_enable,
276276
);
277-
} else if let SleepState::Awake = state.sleeping {
277+
}
278+
(Some(c @ Command::BootloaderReset), _)
279+
| (Some(c @ Command::IsSleeping), _) => {
280+
if let Some(response) = handle_command(&c, &mut state, &mut matrix) {
281+
let _ = serial.write(&response);
282+
};
283+
}
284+
(Some(command), SleepState::Awake) => {
278285
// While sleeping no command is handled, except waking up
279-
handle_command(&command, &mut state, &mut matrix);
286+
if let Some(response) =
287+
handle_command(&command, &mut state, &mut matrix)
288+
{
289+
let _ = serial.write(&response);
290+
};
291+
fill_grid_pixels(&state.grid, &mut matrix);
280292
}
281-
282-
fill_grid_pixels(&state.grid, &mut matrix);
293+
_ => {}
283294
}
284295
}
285296
}

src/control.rs

Lines changed: 59 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,10 @@ pub enum PatternVals {
4444

4545
// TODO: Reduce size for modules that don't require other commands
4646
pub enum Command {
47+
/// Get current brightness scaling
48+
GetBrightness,
4749
/// Set brightness scaling
48-
Brightness(u8),
50+
SetBrightness(u8),
4951
/// Display pre-programmed pattern
5052
Pattern(PatternVals),
5153
/// Reset into bootloader
@@ -54,8 +56,10 @@ pub enum Command {
5456
Percentage(u8),
5557
/// Go to sleepe or wake up
5658
Sleep(bool),
59+
IsSleeping,
5760
/// Start/stop animation (vertical scrolling)
58-
Animate(bool),
61+
SetAnimate(bool),
62+
GetAnimate,
5963
/// Panic. Just to test what happens
6064
Panic,
6165
/// Draw black/white on the grid
@@ -74,17 +78,21 @@ pub fn parse_command(count: usize, buf: &[u8]) -> Option<Command> {
7478
}
7579

7680
// Parse the generic commands common to all modules
77-
if count >= 4 && buf[0] == 0x32 && buf[1] == 0xAC {
81+
if count >= 3 && buf[0] == 0x32 && buf[1] == 0xAC {
7882
let command = buf[2];
79-
let arg = buf[3];
83+
let arg = if count <= 3 { None } else { Some(buf[3]) };
8084

8185
//let mut text: String<64> = String::new();
8286
//writeln!(&mut text, "Command: {command}, arg: {arg}").unwrap();
8387
//let _ = serial.write(text.as_bytes());
8488

8589
match command {
8690
0x02 => Some(Command::BootloaderReset),
87-
0x03 => Some(Command::Sleep(arg == 1)),
91+
0x03 => Some(if let Some(go_to_sleep) = arg {
92+
Command::Sleep(go_to_sleep == 1)
93+
} else {
94+
Command::IsSleeping
95+
}),
8896
0x05 => Some(Command::Panic),
8997
_ => None, //Some(Command::Unknown),
9098
}
@@ -95,30 +103,39 @@ pub fn parse_command(count: usize, buf: &[u8]) -> Option<Command> {
95103

96104
#[cfg(feature = "ledmatrix")]
97105
pub fn parse_module_command(count: usize, buf: &[u8]) -> Option<Command> {
98-
if count >= 4 && buf[0] == 0x32 && buf[1] == 0xAC {
106+
if count >= 3 && buf[0] == 0x32 && buf[1] == 0xAC {
99107
let command = buf[2];
100-
let arg = buf[3];
108+
let arg = if count <= 3 { None } else { Some(buf[3]) };
101109

102110
match command {
103-
0x00 => Some(Command::Brightness(arg)),
111+
0x00 => Some(if let Some(brightness) = arg {
112+
Command::SetBrightness(brightness)
113+
} else {
114+
Command::GetBrightness
115+
}),
104116
0x01 => match arg {
105-
0x00 => {
117+
Some(0x00) => {
106118
if count >= 5 {
107119
Some(Command::Percentage(buf[4]))
108120
} else {
109121
None
110122
}
111123
}
112-
0x01 => Some(Command::Pattern(PatternVals::Gradient)),
113-
0x02 => Some(Command::Pattern(PatternVals::DoubleGradient)),
114-
0x03 => Some(Command::Pattern(PatternVals::DisplayLotus)),
115-
0x04 => Some(Command::Pattern(PatternVals::ZigZag)),
116-
0x05 => Some(Command::Pattern(PatternVals::FullBrightness)),
117-
0x06 => Some(Command::Pattern(PatternVals::DisplayPanic)),
118-
0x07 => Some(Command::Pattern(PatternVals::DisplayLotus2)),
119-
_ => None,
124+
Some(0x01) => Some(Command::Pattern(PatternVals::Gradient)),
125+
Some(0x02) => Some(Command::Pattern(PatternVals::DoubleGradient)),
126+
Some(0x03) => Some(Command::Pattern(PatternVals::DisplayLotus)),
127+
Some(0x04) => Some(Command::Pattern(PatternVals::ZigZag)),
128+
Some(0x05) => Some(Command::Pattern(PatternVals::FullBrightness)),
129+
Some(0x06) => Some(Command::Pattern(PatternVals::DisplayPanic)),
130+
Some(0x07) => Some(Command::Pattern(PatternVals::DisplayLotus2)),
131+
Some(_) => None,
132+
None => None,
120133
},
121-
0x04 => Some(Command::Animate(arg == 1)),
134+
0x04 => Some(if let Some(run_animation) = arg {
135+
Command::SetAnimate(run_animation == 1)
136+
} else {
137+
Command::GetAnimate
138+
}),
122139
0x06 => {
123140
if count >= 3 + DRAW_BYTES {
124141
let mut bytes = [0; DRAW_BYTES];
@@ -194,9 +211,14 @@ pub fn handle_generic_command(command: &Command) {
194211
}
195212

196213
#[cfg(feature = "ledmatrix")]
197-
pub fn handle_command(command: &Command, state: &mut State, matrix: &mut Foo) {
214+
pub fn handle_command(command: &Command, state: &mut State, matrix: &mut Foo) -> Option<[u8; 32]> {
198215
match command {
199-
Command::Brightness(br) => {
216+
Command::GetBrightness => {
217+
let mut response: [u8; 32] = [0; 32];
218+
response[0] = state.brightness;
219+
return Some(response);
220+
}
221+
Command::SetBrightness(br) => {
200222
//let _ = serial.write("Brightness".as_bytes());
201223
state.brightness = *br;
202224
matrix
@@ -226,7 +248,12 @@ pub fn handle_command(command: &Command, state: &mut State, matrix: &mut Foo) {
226248
_ => {}
227249
}
228250
}
229-
Command::Animate(a) => state.animate = *a,
251+
Command::SetAnimate(a) => state.animate = *a,
252+
Command::GetAnimate => {
253+
let mut response: [u8; 32] = [0; 32];
254+
response[0] = state.animate as u8;
255+
return Some(response);
256+
}
230257
Command::Draw(vals) => state.grid = draw(vals),
231258
Command::StageGreyCol(col, vals) => {
232259
draw_grey_col(&mut state.col_buffer, *col, vals);
@@ -237,8 +264,19 @@ pub fn handle_command(command: &Command, state: &mut State, matrix: &mut Foo) {
237264
// Zero the old staging buffer, just for good measure.
238265
state.col_buffer = percentage(0);
239266
}
267+
// TODO: Move to handle_generic_command
268+
Command::IsSleeping => {
269+
let mut response: [u8; 32] = [0; 32];
270+
response[0] = match state.sleeping {
271+
SleepState::Sleeping(_) => 1,
272+
SleepState::Awake => 0,
273+
};
274+
return Some(response);
275+
}
276+
// TODO: Make it return something
240277
_ => handle_generic_command(command),
241278
}
279+
None
242280
}
243281

244282
#[cfg(feature = "b1display")]

0 commit comments

Comments
 (0)