 /*
- * The Space Probe firmware is a very thin stub program, which speaks a
- * simple serial command/response protocol.
+ * The Space Probe firmware is a very thin stub program, implementing a simple web API
  *
- * All numbers <X> are transmitted as 4-digit decimal integers, regardless of scale.
- *
- * Commands:
- *
- * Cmd: L<R>,<G>,<B>,<O>,<F>\n
- * Rsp: OK\n
- *
- * Set LEDs R,G,B levels (0-255) with blink cylce <O>ms On then <F>ms off.
- *
- * ****
- *
- * Cmd: B<N>
- * Rsp: OK\n
- *
- * Beep for N milliseconds
- *
- * *****
- *
- * Cmd: D<N>\n
- * Rsp: OK\n
- *
- * Set dial gauge PWM output to <N> (0-255)
- *
- * *****
- *
- * Cmd: K\n
- * Rsp: <N>\n
- *
- * Read back knob position <N> (0-1023)
- *
- * *****
- *
- * Cmd: P\n
- * Rsp: OK\n
- *
- * Ping! Check the probe is still there. If the probe doesn't see any command (including ping)
- * for 5 seconds it'll start blinking the red LED quickly until it sees a response.
- */
+ * See the help_handler method below for the help text (also available if you GET HTTP address /)
+ * */
 
 #include <Ethernet.h>
 #include <Flash.h>


  if (last_ms > ms) { // millis() has wrapped! uptime ftw!
    last_cmd_ms = 0;
    stop_beep_ms = 0;
  }
  last_ms = ms;
  bool lost = ( last_cmd_ms + CMD_TIMEOUT_MS ) < ms; // have we lost our link?

  analogWrite(GREEN_PIN, blink_on ? (lost ? 0 : green) : 0);
  analogWrite(BLUE_PIN, blink_on ? (lost ? 0 : blue) : 0);

  digitalWrite(SPEAKER_PIN, ( ms < stop_buzz_ms )
                        && ( (micros() & BUZZ_US) < BUZZ_US/2) );
}

static void handler_response_common(TinyWebServer& web_server) {
  web_server.send_error_code(200);
  web_server.end_headers();
  last_cmd_ms = millis();
}

boolean alive_handler(TinyWebServer& web_server){
  handler_response_common(web_server);
  web_server << F("OK");
  return true;
}

boolean knob_handler(TinyWebServer& web_server)
{
  handler_response_common(web_server);
  web_server << knob_pos;
  return true;
}

boolean set_leds_handler(TinyWebServer& web_server)
{
  char buf[40];

  Client& client = web_server.get_client();
  client.setTimeout(500);
  client.readBytesUntil('\n',buf,40);

  int r = sscanf(buf, "%04d,%04d,%04d,%04d,%04d", &red, &green, &blue, &on_duty, &off_duty);
  if(r != 5) {
    web_server.send_error_code(500);
    web_server.end_headers();
    web_server << F("Invalid LED string");
  }
  else {
    handler_response_common(web_server);
    web_server << F("OK");
  }
  return true;
}

