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
#[allow(unused_imports)]

use tokio::process::{Command,Child};
use tokio::time::{Duration,delay_for};
use tokio::{select,join};
use std::process::Stdio;
use thiserror::Error;
use apigpio::Connection;
use apigpio::Level::*;
use arrayvec::ArrayVec;
use std::os::unix::process::ExitStatusExt;
use futures_util::FutureExt;
use futures_util::future::{BoxFuture,Shared};

use libc::SIGTERM;

use anyhow::anyhow;
use picollar::ledpins;
use picollar::config::{self,Config,NO_MORE};

const POLL_PIGPIOD : Duration = Duration::from_millis(50);

const WAIT_BEFORE_SYNC : Duration = Duration::from_millis(750);

#[derive(Debug)]
enum CrashKind {
  ManagerFailed,
  StartupIoError,
  StartupPigpiodFailed,
  LatePigpiodFailed,
}

use CrashKind::*;

impl CrashKind {
  pub fn cadence(self) -> [u16;2] {
    match self {
      StartupIoError       => [ 300,1200],
      StartupPigpiodFailed => [ 100,1000],
      LatePigpiodFailed    => [ 100, 100],
      ManagerFailed        => [1200, 300],
    }
  }
}

impl CrashError {
  fn new(kind : CrashKind, e : anyhow::Error, what : &'static str) -> Self {
    CrashError(
      kind,
      <anyhow::Error>::context(e.into(), what),
    )
  }
}

#[derive(Debug)]
struct CrashError (CrashKind, anyhow::Error);

#[derive(Error,Debug)]
enum MainLoopError {
  #[error("main loop crashed {0:?}")]
  MainLoopCrash (CrashError),
  #[error("pigpio comms failed at runtime {0:?}")]
  PigpioRuntimeComms (apigpio::Error),
}

use MainLoopError::*;

enum CannotSucceed { }

impl From<apigpio::Error> for MainLoopError {
  fn from(e : apigpio::Error) -> Self { PigpioRuntimeComms(e) }
}

impl From<MainLoopError> for CrashError {
  fn from(e : MainLoopError) -> CrashError {
    match e {
      MainLoopCrash (ce) => ce,
      PigpioRuntimeComms(e) => CrashError::new(
        LatePigpiodFailed,
        e.into(),
        "pigpiod runtime comms failure"
      ),
    }
  }
}

async fn mainloop(pi : &Connection, cfg : &Config)
                  -> std::result::Result<CannotSucceed,MainLoopError>
{
  loop {
    ledpins::setled(pi,[H,L,L]).await?;

    let mgr_emap = |e : std::io::Error| MainLoopCrash(CrashError::new(
      StartupIoError,
      e.into(),
      "manager startup failure",
    ));

    let mut manager = cfg.command_simple("manager","manager",&NO_MORE)
      .expect("manager command onfiguration");

    let status = manager
      .spawn()
      .map_err(mgr_emap)?
      .await
      .map_err(mgr_emap)?
      ;
    if !(status.success() || status.signal() == Some(SIGTERM)) {
      Err(MainLoopCrash(CrashError(
        ManagerFailed,
        anyhow!("manager terminated {:?}", status)
      )))?;
    }

    eprintln!("supervisor: manager finished {:?}", status);
    pi.wave_tx_stop().await?;
    pi.wave_clear().await?;
    pi.set_pull_up_down(ledpins::XMIT,Some(L)).await?;
    pi.set_mode(ledpins::XMIT,apigpio::GpioMode::Input).await?;
  }
}

async fn pigpiod_connect() -> Result<Connection,CrashError> {
  let pi = loop {
    eprintln!("supervisor: connecting...");
    match Connection::new().await {
      Ok(pi) => break <Result<_,CrashError>>::Ok(pi),
      Err(apigpio::Error::DaemonConnectionFailed(_))
        => delay_for(POLL_PIGPIOD).await,
      Err(e) => Err(CrashError::new(
        StartupPigpiodFailed,
        e.into(),
        "failed to connect to pigpiod"
      ))?,
    }
  }?;
  eprintln!("supervisor: connected...");
  Ok(pi)
}

struct PigpiodStarted (Child);

#[derive(Copy,Clone)]
struct PigpiodFailed();

type PigpiodFailedFuture<'a> = Shared<BoxFuture<'a, PigpiodFailed>>;

async fn pigpiod_spawn(cfg : &Config) -> Result<PigpiodStarted,CrashError> {
  eprintln!("supervisor: starting pigpiod...");

  let child= cfg.command_general("pigpiod", &["pigpiod"], &["-l","-g"])
    .expect("pigpiod command")
    .stdin(Stdio::null())
    .spawn()
    .map_err(|e| CrashError::new(
      StartupIoError,
      e.into(),
      "pigpiod startup"
    ))?;

  eprintln!("supervisor: pigpiod spawned");
  Ok(PigpiodStarted(child))
}

async fn pigpiod_collect(started : PigpiodStarted) -> PigpiodFailed {
  let status = started.0.await;
  eprintln!("SUPERVISOR: CRASHING: PIGPIOD TERMINATED: {:?}", status);
  PigpiodFailed()
}

async fn pigpiod_startup<'a>(cfg : &Config)
        -> Result<(Connection, PigpiodFailedFuture<'a>), CrashError> {
  let pigpiod : PigpiodStarted = pigpiod_spawn(cfg).await?;

  let pff : PigpiodFailedFuture
    = pigpiod_collect(pigpiod).boxed().shared();
  
  let pi = select!{
    pi = pigpiod_connect() => pi?,

    PigpiodFailed() = pff.clone() => {
      return Err(CrashError(
        StartupPigpiodFailed,
        anyhow!("pigpiod failed during our startup"),
      ));
    },
  };

  Ok((pi, pff))
}
  
async fn operate<'a>(pff : &mut PigpiodFailedFuture<'a>,
                     cfg : &Config)
                     -> Result<CannotSucceed, CrashError> {
  let (pi, npff) = pigpiod_startup(cfg).await?;
  *pff = npff;

  select!{
    r = mainloop(&pi, &cfg) => Ok(r?),

    PigpiodFailed() = pff.clone() => {
      return Err(CrashError(
        LatePigpiodFailed,
        anyhow!("pigpiod failed during operation"),
      ));
    },
  }
}

async fn crashed_flash_led(pins : &mut [rppal::gpio::OutputPin],
                           kind : CrashKind) -> CannotSucceed {
  let cadence = kind.cadence();
  pins[0].set_low();
  pins[1].set_low();
  pins[2].set_low();
  let mut i = 0;
  match join!{ async {
    let _x : CannotSucceed = loop {
      pins[0].toggle();
      delay_for(Duration::from_millis(cadence[i].into())).await;
      i = 1-i;
    }; #[allow(unreachable_code)] _x
  }, async {
    delay_for(WAIT_BEFORE_SYNC).await;
    extern "C" { fn sync(); }
    match tokio::task::spawn_blocking(|| unsafe { sync(); }).await {
      Err(e) => eprintln!("supervisor: sync failed: {:?}", e),
      Ok(()) => eprintln!("supervisor: disks synced"),
    }
  }} {
    (x, ()) => match x { }
  }
}
  
#[tokio::main]
async fn main(){
  let cfg = config::read().expect("read config");

  let direct_gpio = rppal::gpio::Gpio::new().expect("rpal open");
  let direct_xmit = direct_gpio.get(ledpins::XMIT as u8)
    .expect("get xmit pin");

  let mut pff : PigpiodFailedFuture = futures_util::future::pending()
    .boxed().shared();

  let r = operate(&mut pff, &cfg).await;

  let CrashError(kind, info) = match r {
    Err(e) => e,
    Ok(x) => match x { },
  };

  direct_xmit
    .into_input_pulldown()
    .set_reset_on_drop(false);

  eprintln!("SUPERVISOR: CRASHED: {:?} {:?}", kind, info);

  let mut pins : ArrayVec<[rppal::gpio::OutputPin;3]>
    = ledpins::RGB.iter().map(|p| {
    let mut p = direct_gpio
      .get(*p as u8).expect("get led pin")
      .into_output();
    p.set_reset_on_drop(false);
    p
  }).collect();

  select!{
    _ = crashed_flash_led(&mut pins, kind) => {},
    PigpiodFailed() = pff.clone() => { },
  };

  crashed_flash_led(&mut pins, LatePigpiodFailed).await;
}