aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib.rs
blob: 5bcd1acffc44351abd6f8dfac74b4e352f96fa1a (plain)
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
#![no_std]
#![no_main]
#![allow(async_fn_in_trait)]

extern crate alloc;

use arrayvec::{ArrayString, ArrayVec};
use defmt::{info, Debug2Format};

use core::{convert::Infallible, fmt::Write, str::FromStr};
use embassy_sync::{
    blocking_mutex::raw::CriticalSectionRawMutex, mutex::Mutex, pubsub::PubSubChannel,
};
use embassy_time::Timer;
use embedded_graphics::{
    draw_target::DrawTarget,
    geometry::OriginDimensions,
    mono_font::{ascii::FONT_4X6, MonoTextStyle},
    pixelcolor::Gray4,
    prelude::*,
    primitives::{Circle, PrimitiveStyle, Rectangle},
    text::{Alignment, Text},
};
use embedded_hal::digital::StatefulOutputPin;
use lora_phy::{mod_traits::RadioKind, DelayNs, LoRa};
use meshcore::{
    crypto::{PrivateKey, PublicKey, SharedSecret},
    packet::Packet,
    packet_content::PacketContent,
    text::ClearText,
};

pub static MESSAGE_CH: PubSubChannel<CriticalSectionRawMutex, ClearText, 3, 2, 1> =
    PubSubChannel::new();

pub async fn led_task(
    led_pin: &Mutex<CriticalSectionRawMutex, impl StatefulOutputPin<Error = Infallible>>,
) {
    let mut subscriber = MESSAGE_CH.subscriber().unwrap();

    loop {
        let _ = subscriber.next_message().await;
        info!("led: got message");

        let mut led = led_pin.lock().await;
        for _ in 0..3 {
            led.set_low().unwrap();
            Timer::after_millis(50).await;
            led.set_high().unwrap();
            Timer::after_millis(50).await;
        }
    }
}

fn cstr(bytes: &[u8]) -> &str {
    let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());
    core::str::from_utf8(&bytes[..end]).unwrap_or("")
}

pub async fn display_task<D>(display: &mut D, mut finish: impl AsyncFnMut(&mut D))
where
    D: DrawTarget<Color = Gray4> + OriginDimensions,
    <D as DrawTarget>::Error: core::fmt::Debug,
{
    let radius: u16 = 10;
    let mut pos = Point::new(30, 30);
    let mut vel = Point::new(-2, 1);

    let pp = Point::new(radius.into(), radius.into());
    let bounds = Rectangle::with_corners(Point::new(0, 0), -(pp - display.size()));

    let mut lines = ArrayVec::<ArrayString<128>, 8>::new();
    let mut subscriber = MESSAGE_CH.subscriber().unwrap();

    loop {
        // update ball
        pos += vel;

        let bottom_right = bounds.bottom_right().unwrap();

        if pos.x < bounds.top_left.x || pos.x > bottom_right.x {
            vel.x = -vel.x;
        }
        if pos.y < bounds.top_left.y || pos.y > bottom_right.y {
            vel.y = -vel.y;
        }

        pos.x = pos.x.clamp(bounds.top_left.x, bottom_right.x);
        pos.y = pos.y.clamp(bounds.top_left.y, bottom_right.y);

        // update chat
        if let Some(msg) = subscriber.try_next_message_pure() {
            info!("display: got message");
            if lines.is_full() {
                lines.remove(0);
            }

            let mut str: ArrayString<128> = ArrayString::new();
            write!(&mut str, "{}: {}", cstr(&msg.sender), cstr(&msg.message)).unwrap();
            lines.push(str);
        }

        display.clear(Gray4::BLACK).unwrap();
        Circle::new(pos, radius.into())
            .into_styled(PrimitiveStyle::with_stroke(Gray4::new(4), 3))
            .draw(display)
            .unwrap();

        for (i, line) in lines.iter().enumerate() {
            Text::with_alignment(
                line,
                Point::new(4, 4 + 8 * (i as i32)),
                MonoTextStyle::new(&FONT_4X6, Gray4::WHITE),
                Alignment::Left,
            )
            .draw(display)
            .unwrap();
        }

        finish(display).await;

        Timer::after_millis(10).await;
    }
}

fn hex16(hexstr: &'static str) -> [u8; 16] {
    let mut buf = [0u8; 16];
    hex::decode_to_slice(hexstr, &mut buf).expect("invalid hex secret");
    buf
}

pub async fn radio_task(lora: &mut LoRa<impl RadioKind, impl DelayNs>) {
    use lora_phy::mod_params::*;

    let keystore = meshcore::no_std_identity::StaticKeystoreInput {
        identities:
            [PrivateKey::from_str( "5884BEECFA94A15B596C8FE51832B857EB018B37F3E85671971977F5A6139374B9C3ECD2415258A9C233D4CA9332C7BF06EB269B786EA71813DE17DFFF480177", ) .unwrap()]
            .into_iter()
            .collect(),
        contacts: [].into_iter().collect(),
        groups: [
            SharedSecret::new_from_group_secret(&hex16("8b3387e9c5cdea6ac9e5edbaa115cd72")),
         SharedSecret::new_from_group_secret(&hex16("4c97bfe431abe20672259d9b6969dcec")),
    ]
        .into_iter()
        .collect(),
    }
    .compile();

    let pk: PublicKey = (&keystore.identities[0].private_key).into();
    info!("public key: {:?}", Debug2Format(&pk));

    let publisher = MESSAGE_CH.publisher().unwrap();
    let mut buffer: [u8; 256] = [0; 256];

    let mdltn_params = lora
        .create_modulation_params(
            SpreadingFactor::_8,
            Bandwidth::_62KHz,
            CodingRate::_4_8,
            869_618_000,
        )
        .unwrap();

    let rx_params = lora
        .create_rx_packet_params(16, false, buffer.len() as u8, true, false, &mdltn_params)
        .unwrap();

    lora.prepare_for_rx(RxMode::Continuous, &mdltn_params, &rx_params)
        .await
        .unwrap();

    loop {
        info!("waiting for message");
        let res = lora.rx(&rx_params, &mut buffer).await.unwrap();
        let message = &buffer[0..res.0.into()];

        let packet = Packet::try_from(message).unwrap();
        info!("packet {:?}", Debug2Format(&packet));

        match packet.content {
            PacketContent::Advert(msg) => {
                info!("got advert from {}", &msg.name);
            }
            PacketContent::GroupText(mut msg) => {
                msg.decrypt(&keystore).unwrap();
                if let Some(text) = msg.cleartext {
                    unsafe {
                        info!(
                            "decrypted group message from {}: {}",
                            alloc::str::from_utf8_unchecked(&text.sender),
                            alloc::str::from_utf8_unchecked(&text.message),
                        );
                    }
                    publisher.publish(text).await;
                } else {
                    info!("failed to decrypt group message");
                }
            }
            PacketContent::Text(mut msg) => {
                msg.decrypt(&keystore).unwrap();
                if let Some(text) = msg.cleartext {
                    unsafe {
                        info!(
                            "decrypted p2p message from {}: {}",
                            alloc::str::from_utf8_unchecked(&text.sender),
                            alloc::str::from_utf8_unchecked(&text.message),
                        );
                    }
                    publisher.publish(text).await;
                } else {
                    info!("failed to decrypt p2p message");
                }
            }
            content => {
                info!("content: {:?}", Debug2Format(&content));
            }
        }
    }
}