summaryrefslogtreecommitdiffstats
path: root/src/bin/server.rs
blob: a1ac3e26fc95bbae3ee72c35a26abe025c259b60 (plain) (blame)
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
//! Using a static IP example
//!
//! - set SSID and PASSWORD env variable
//! - set STATIC_IP and GATEWAY_IP env variable (e.g. "192.168.2.191" / "192.168.2.1")
//! - might be necessary to configure your WiFi access point accordingly
//! - uses the given static IP
//! - responds with some HTML content when connecting to port 8080
//!

//% FEATURES: esp-wifi esp-wifi/wifi esp-wifi/utils esp-hal/unstable
//% CHIPS: esp32 esp32s2 esp32s3 esp32c2 esp32c3 esp32c6

#![no_std]
#![no_main]

use core::cell::{OnceCell, RefCell};
use core::ops::Deref;
use core::str::FromStr;

use blocking_network_stack::Stack;
use critical_section::Mutex;
use dumbswitch::network_data;
use embedded_io::*;
use esp_alloc as _;
use esp_backtrace as _;
use esp_hal::delay::Delay;
use esp_hal::gpio::{Event, Input, Io, Level, Output, Pull};
use esp_hal::handler;
use esp_hal::interrupt::InterruptConfigurable;
use esp_hal::{
  clock::CpuClock,
  main,
  rng::Rng,
  time::{self, Duration},
  timer::timg::TimerGroup,
};
use esp_println::println;
use esp_wifi::{
  init,
  wifi::{
    utils::create_network_interface, AccessPointInfo, ClientConfiguration, Configuration,
    WifiError, WifiStaDevice,
  },
};
use log::{debug, error, info, trace, warn};
use smoltcp::iface::{SocketSet, SocketStorage};

pub enum OurOption<T> {
  /// No value.
  None,
  /// Some value of type `T`.
  Some(T),
}

static BUTTON: Mutex<RefCell<Option<Input>>> = Mutex::new(RefCell::new(None));
static mut LED: OurOption<RefCell<Output<'_>>> = OurOption::None;

fn set_open_led_state(val: bool) {
  #[cfg(not(feature="led-as-busy-led"))]
  {
    let v = unsafe {
      #[allow(static_mut_refs)]
      &LED
    };
    let v = match v {
      OurOption::None => {
        return;
      }
      OurOption::Some(v) => v,
    };
    let mut b = v.borrow_mut();
    b.set_level(if val { Level::High } else { Level::Low });
  }
}

// TODO: in future, add another LED for busy
fn set_busy_led_state(val: bool) {
  #[cfg(feature="led-as-busy-led")]
  {
    let v = unsafe {
      #[allow(static_mut_refs)]
      &LED
    };
    let v = match v {
      OurOption::None => {
        return;
      }
      OurOption::Some(v) => v,
    };
    let mut b = v.borrow_mut();
    b.set_level(if val { Level::High } else { Level::Low });
  }
}

#[main]
fn main() -> ! {
  esp_println::logger::init_logger_from_env();
  let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max());
  let peripherals = esp_hal::init(config);

  let delay = Delay::new();

  esp_alloc::heap_allocator!(72 * 1024);

  info!("Preparing GPIO");

  let mut io = Io::new(peripherals.IO_MUX);

  // Set GPIO1 as an output, and set its state low initially.
  let led = RefCell::new(Output::new(peripherals.GPIO1, Level::Low));
  let led = unsafe {
    LED = OurOption::Some(led);
    #[allow(static_mut_refs)]
    match &LED {
      OurOption::None => panic!(),
      OurOption::Some(v) => v,
    }
  };

  // Set GPIO4 as an input
  let mut button = Input::new(peripherals.GPIO3, Pull::Down);

  info!("Waiting 500ms pre-init");
  delay.delay_millis(500);

  led.borrow_mut().set_low();

  let timg0 = TimerGroup::new(peripherals.TIMG0);

  let mut rng = Rng::new(peripherals.RNG);

  let init = init(timg0.timer0, rng.clone(), peripherals.RADIO_CLK).unwrap();

  let mut wifi = peripherals.WIFI;
  let (iface, device, mut controller) =
    create_network_interface(&init, &mut wifi, WifiStaDevice).unwrap();

  let mut socket_set_entries: [SocketStorage; 3] = Default::default();
  let socket_set = SocketSet::new(&mut socket_set_entries[..]);

  let now = || time::now().duration_since_epoch().to_millis();
  let mut stack = Stack::new(iface, device, socket_set, now, rng.random());

  let client_config = Configuration::Client(ClientConfiguration {
    ssid: network_data::SSID.try_into().unwrap(),
    password: network_data::PASSWORD.try_into().unwrap(),
    ..Default::default()
  });
  let res = controller.set_configuration(&client_config);
  debug!("wifi_set_configuration returned {:?}", res);

  controller.start().unwrap();
  debug!("is wifi started: {:?}", controller.is_started());

  info!("Start Wifi Scan");
  let res: Result<(heapless::Vec<AccessPointInfo, 30>, usize), WifiError> = controller.scan_n();
  if let Ok((res, _count)) = res {
    for ap in res {
      debug!("AP Info: {:?}", ap);
    }
  }

  debug!("{:?}", controller.capabilities());
  debug!("wifi_connect {:?}", controller.connect());

  // wait to get connected
  info!("Wait to get connected");
  loop {
    match controller.is_connected() {
      Ok(true) => break,
      Ok(false) => {
        set_busy_led_state(true);
        delay.delay_millis(10);
        set_busy_led_state(false);
        delay.delay_millis(500);
      }
      Err(err) => {
        error!("Failed to connect to wifi: {:?}", err);
        let mut high = false;
        loop {
          delay.delay_millis(1000);
          high = !high;
          if high {
            led.borrow_mut().set_high();
          } else {
            led.borrow_mut().set_low();
          }
        }
      }
    }
  }
  debug!("{:?}", controller.is_connected());

  info!("Setting static IP {}", network_data::STATIC_IP);

  stack
    .set_iface_configuration(&blocking_network_stack::ipv4::Configuration::Client(
      blocking_network_stack::ipv4::ClientConfiguration::Fixed(
        blocking_network_stack::ipv4::ClientSettings {
          ip: blocking_network_stack::ipv4::Ipv4Addr::from(parse_ip(network_data::STATIC_IP)),
          subnet: blocking_network_stack::ipv4::Subnet {
            gateway: blocking_network_stack::ipv4::Ipv4Addr::from(parse_ip(
              network_data::GATEWAY_IP,
            )),
            mask: blocking_network_stack::ipv4::Mask(24),
          },
          dns: None,
          secondary_dns: None,
        },
      ),
    ))
    .unwrap();

  for i in 0..4 {
    delay.delay_millis(100);
    if i % 2 == 0 {
      led.borrow_mut().set_high();
    } else {
      led.borrow_mut().set_low();
    }
  }

  info!(
    "Start busy loop on main. Point your browser to http://{}:8080/",
    network_data::STATIC_IP
  );

  let mut rx_buffer = [0u8; 1536];
  let mut tx_buffer = [0u8; 1536];
  let mut socket = stack.get_socket(&mut rx_buffer, &mut tx_buffer);

  socket.listen(8080).unwrap();

  // fn update_open(is_open: bool, button: &Input<'_>, led: &mut Output<'_>, delay: &Delay) -> bool {
  //   let mut is_open = if is_open { true } else { false };
  //   if button.is_low() {
  //     is_open = !is_open;

  //     if is_open {
  //       led.set_high();
  //     } else {
  //       led.set_low();
  //     }
  //     while button.is_low() {
  //       trace!("waiting for unpress btn");
  //       delay.delay_millis(10);
  //     }
  //   }
  //   is_open
  // }

  loop {
    socket.work();

    if !socket.is_open() {
      socket.listen(8080).unwrap();
    }

    set_busy_led_state(true);
    if socket.is_connected() {
      let is_open = button.is_high();
      unsafe {
        set_open_led_state(is_open);
      }

      let r = socket.write_all((if is_open { b"HTTP/1.0 200 OK\r\n\
\r\n\
1" } else { b"HTTP/1.0 200 OK\r\n\
\r\n\
0" }));
      if !r.is_ok() {
        error!("{:#?}", r.unwrap_err());
        continue;
      };

      let r = socket.flush();
      if !r.is_ok() {
        error!("{:#?}",r.unwrap_err());
        continue;
      };
      socket.work();
      // }

      socket.close();
    }
    set_busy_led_state(false);
    // TODO: what
    let deadline = time::now() + Duration::millis(100);
    while time::now() < deadline && !socket.is_connected() {
      socket.work();
    }

    let is_open = button.is_high();
    set_open_led_state(is_open);
  }
}

fn parse_ip(ip: &str) -> [u8; 4] {
  let mut result = [0u8; 4];
  for (idx, octet) in ip.split(".").into_iter().enumerate() {
    result[idx] = u8::from_str_radix(octet, 10).unwrap();
  }
  result
}