aboutsummaryrefslogtreecommitdiffstats
path: root/nrf52/state_machine.cpp
blob: 15e38b93746ec64fea992a323ebdb4c9ace0c1bc (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
#include "state_machine.h"

#include "i2c_message.h"
#include "log.h"

#include <Arduino.h>

StateMachine::StateMachine(BLEHidAdafruit *blehid): currentState(WAIT_FOR_TYPE), blehid(blehid) {}

void StateMachine::byteReceived(uint8_t inByte) {
  dbgPrint("inByte=");
  dbgPrintln(inByte);

  switch (this->currentState) {
  case WAIT_FOR_TYPE:
    switch (inByte) {
    case KBD:
      digitalWrite(LED_BUILTIN, HIGH);
      this->msgType = KBD;
      break;

    case DBG:
      dbgPrint("T-M0: ");
      this->msgType = DBG;
      break;

    default:
      this->msgType = INVALID;
      Serial.printf("Invalid message type: %ud.\r\n", inByte);
    }

    this->currentState = WAIT_FOR_LEN;
    break;

  case WAIT_FOR_LEN:
    dbgPrintf("msg len: %u\r\n", inByte);
    this->msgLen = inByte;
    this->msgCount = 0;

    if (this->msgLen == 0) {
      this->currentState = WAIT_FOR_TYPE;
    } else {
      this->currentState = WAIT_FOR_DATA;
    }
    break;

  case WAIT_FOR_DATA:
    dbgPrintf("data: %02x\r\n", inByte);
    switch (this->msgType) {
    case KBD:
      this->message[this->msgCount++ % sizeof(this->message)] = inByte;
      break;

    case DBG:
      dbgPrint(inByte);
      break;
    }

    if (this->msgCount == this->msgLen) {
      switch (this->msgType) {
      case KBD:
        dbgPrintln("sending kbd report");
        this->blehid->keyboardReport(this->message[0], &this->message[2]);
        digitalWrite(LED_BUILTIN, LOW);
        break;

      case DBG:
        dbgPrintln();
        break;
      }
      this->currentState = WAIT_FOR_TYPE;
    }
    break;

  default:
    Serial.printf("Invalid message state: %ud.\r\n", this->currentState);
    break;
  }
}