summaryrefslogtreecommitdiffstats
path: root/martin/door/src/hcs200.h
blob: 95aa18b17f893d34f691a6719b370548b2d8194c (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#pragma once

#include <functional>
#include <Print.h>

class HCS200_Keycode
{
  public:
    /** Bit masks to determine which button was pressed on the keyfob.
     * NOTE: the bit position does not match the button number
     */
    enum ButtonMask
      : unsigned char
    {
        BM_S3 = 0x1,
        BM_S0 = 0x2,
        BM_S1 = 0x4,
        BM_S2 = 0x8
    };

    void print(Print &stream);
    void send(std::function<void(int)> setOutput);

  private:
    void send(bool value, std::function<void(int)> setOutput);

  public:
    uint32_t encrypted;
    uint32_t serial;
    unsigned char buttons;
    bool lowbat;
};

class HCS200
{
  public:
    enum RxState
    {
      RS_NOSYNC = 0,      // Receiver is inactive
      RS_PREAMBLE_START,
      RS_PREAMBLE_LOW,
      RS_PREAMBLE_HIGH,
      RS_PREAMBLE_HEADER,
      RS_DATA,            // DATA is being received
      RS_COMPLETED        // Receive complete
    };

    void on_isr(uint8_t value);
    void reset();
    bool decode(struct HCS200_Keycode &out);
    void print_state(Print &stream);

  public:
    int classify(unsigned pulse);

    /** The state of the code word received, this is 'volatile' since it is
     * accessed from both the main loop and the interrupt service routine.
     */
    volatile char rx_state = RS_NOSYNC;

    /** Time stamp when the previous interrupt was triggered (when the input pin
     * transitioned either from 0 to 1 or from 1 to 0.  This is the value of
     * micros() function.
     */
    unsigned long last_timestamp = 0;

    /** The duration of the last pulse width (the time between a transition of the
     * input pin)
     */
    unsigned last_pulse_width = 0;

    /** Number of changes during preamble
     */
    char preamble_count = 0;

    /** Number of bits received already.
     */
    char rx_bit_count = 0;

    /** Duration of the transmitter clock -- this is determined when the preamble
     * is received, as the preamble has all the pulse widths the same length.
     *
     * The remotes I tested transmit at 2400 bauds, so the tx_clock is always
     * about 420 micro seconds, however, this code attempts to determine it
     * dynamically and should adapt to transmitters of different speeds.
     */
    unsigned tx_clock = 0;

    /** Number of bits we expect to receive.  The HCS200 data sheet specifies that
     * 66 bits are transmited.
     */
    const unsigned short MAX_BITS = 66;

    /** Buffer where we store the received bits. HCS sends only 66
     */
    uint32_t rx_buf[3];
};