lib.rs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. use wasm_bindgen::prelude::*;
  2. use sccd::controller;
  3. use sccd::statechart;
  4. // Traits
  5. use sccd::statechart::SC;
  6. use sccd::statechart::Scheduler;
  7. #[wasm_bindgen]
  8. extern "C" {
  9. #[wasm_bindgen(js_namespace = console)]
  10. fn log(s: &str);
  11. }
  12. #[wasm_bindgen(module = "/outputhandler.js")]
  13. extern "C" {
  14. pub type OutputHandler;
  15. #[wasm_bindgen(method)]
  16. fn handle_output(this: &OutputHandler, e: digitalwatch::OutEvent);
  17. }
  18. #[wasm_bindgen]
  19. extern {
  20. fn alert(s: &str);
  21. }
  22. #[wasm_bindgen]
  23. #[derive(Default)]
  24. pub struct Handle {
  25. controller: controller::Controller<digitalwatch::InEvent>,
  26. statechart: digitalwatch::Statechart<controller::Controller<digitalwatch::InEvent>>,
  27. }
  28. #[wasm_bindgen]
  29. pub fn setup(out: &OutputHandler) -> Handle {
  30. let mut handle = Handle::default();
  31. handle.statechart.init(&mut handle.controller, &mut |e|{ out.handle_output(e) });
  32. handle
  33. }
  34. #[wasm_bindgen]
  35. pub fn add_event(h: &mut Handle, delay: statechart::Timestamp, i: digitalwatch::InEvent) {
  36. h.controller.set_timeout(delay, i);
  37. }
  38. // Wasm_bindgen cannot yet create bindings for enums with values (such as controller::Until) or tuples, so we translate it to a simple struct
  39. #[wasm_bindgen]
  40. pub struct RunUntilResult {
  41. pub simtime: statechart::Timestamp,
  42. pub next_wakeup_eternity: bool,
  43. pub next_wakeup: statechart::Timestamp,
  44. }
  45. impl RunUntilResult {
  46. fn new(simtime: statechart::Timestamp, next_wakeup: controller::Until) -> Self {
  47. match next_wakeup {
  48. controller::Until::Timestamp(t) => Self{
  49. simtime,
  50. next_wakeup_eternity: false,
  51. next_wakeup: t,
  52. },
  53. controller::Until::Eternity => Self{
  54. simtime,
  55. next_wakeup_eternity: true,
  56. next_wakeup: 0,
  57. },
  58. }
  59. }
  60. }
  61. #[wasm_bindgen]
  62. pub fn run_until(h: &mut Handle, t: statechart::Timestamp, out: &OutputHandler) -> RunUntilResult {
  63. let (simtime, next_wakeup) = h.controller.run_until(&mut h.statechart, controller::Until::Timestamp(t), &mut |e|{ out.handle_output(e) });
  64. RunUntilResult::new(simtime, next_wakeup)
  65. }