├── .gitignore ├── src ├── mqtt_config.h ├── build.sh ├── analogDecoder.h ├── mqtt.h ├── digitalDecoder.h ├── analogDecoder.cpp ├── mqtt.cpp ├── main.cpp └── digitalDecoder.cpp ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | src/honeywell 3 | -------------------------------------------------------------------------------- /src/mqtt_config.h: -------------------------------------------------------------------------------- 1 | #define MQTT_USERNAME "" 2 | #define MQTT_PASSWORD "" 3 | #define MQTT_HOST "127.0.0.1" 4 | #define MQTT_PORT 1883 5 | -------------------------------------------------------------------------------- /src/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | g++ -o honeywell -fdiagnostics-color --std=c++11 mqtt.cpp digitalDecoder.cpp analogDecoder.cpp main.cpp -lrtlsdr -lmosquittopp 3 | -------------------------------------------------------------------------------- /src/analogDecoder.h: -------------------------------------------------------------------------------- 1 | #ifndef __ANALOG_DECODER_H__ 2 | #define __ANALOG_DECODER_H__ 3 | 4 | #include 5 | 6 | class AnalogDecoder 7 | { 8 | public: 9 | AnalogDecoder() = default; 10 | 11 | void handleMagnitude(float value); 12 | void setCallback(std::function cb) {m_cb = cb;}; 13 | 14 | private: 15 | std::function m_cb; 16 | 17 | int m_discardedSamples = 0; 18 | float m_ookMax = 0.0; 19 | float m_val = 0.0; 20 | }; 21 | 22 | #endif 23 | -------------------------------------------------------------------------------- /src/mqtt.h: -------------------------------------------------------------------------------- 1 | #ifndef __MQTT_H__ 2 | #define __MQTT_H__ 3 | 4 | #include 5 | #include 6 | 7 | class Mqtt : public mosqpp::mosquittopp 8 | { 9 | private: 10 | const char *host; 11 | const char *id; 12 | int port; 13 | int keepalive; 14 | const char *will_message; 15 | const char *will_topic; 16 | 17 | void on_connect(int rc); 18 | void on_disconnect(int rc); 19 | void on_publish(int mid); 20 | 21 | public: 22 | Mqtt(const char *id, const char *host, int port, const char *username, const char *password, const char *will_topic, const char *will_message); 23 | ~Mqtt(); 24 | bool send(const char * _topic, const char * _message); 25 | bool set_will(const char * _topic, const char * _message); 26 | }; 27 | 28 | #endif 29 | -------------------------------------------------------------------------------- /src/digitalDecoder.h: -------------------------------------------------------------------------------- 1 | #ifndef __DIGITAL_DECODER_H__ 2 | #define __DIGITAL_DECODER_H__ 3 | 4 | #include "mqtt.h" 5 | 6 | #include 7 | #include 8 | 9 | class DigitalDecoder 10 | { 11 | public: 12 | DigitalDecoder(Mqtt &mqtt_init) : mqtt(mqtt_init) {} 13 | 14 | void handleData(char data); 15 | void setRxGood(bool state); 16 | 17 | 18 | private: 19 | 20 | void writeDeviceState(); 21 | void sendDeviceState(); 22 | void updateDeviceState(uint32_t serial, uint8_t state); 23 | void handlePayload(uint64_t payload); 24 | void handleBit(bool value); 25 | void decodeBit(bool value); 26 | void checkForTimeouts(); 27 | 28 | unsigned int samplesSinceEdge = 0; 29 | bool lastSample = false; 30 | bool rxGood = false; 31 | uint64_t lastRxGoodUpdateTime = 0; 32 | Mqtt &mqtt; 33 | uint32_t packetCount = 0; 34 | uint32_t errorCount = 0; 35 | 36 | struct deviceState_t 37 | { 38 | uint64_t lastUpdateTime; 39 | uint64_t lastAlarmTime; 40 | 41 | uint8_t lastRawState; 42 | 43 | bool tamper; 44 | bool alarm; 45 | bool batteryLow; 46 | bool timeout; 47 | 48 | uint8_t minAlarmStateSeen; 49 | }; 50 | 51 | std::map deviceStateMap; 52 | }; 53 | 54 | #endif 55 | -------------------------------------------------------------------------------- /src/analogDecoder.cpp: -------------------------------------------------------------------------------- 1 | #include "analogDecoder.h" 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #define HW_RATIO 17 8 | 9 | #define MIN_OOK_THRESHOLD 0.25f 10 | #define OOK_THRESHOLD_RATIO 0.75f 11 | #define OOK_DECAY_PER_SAMPLE 0.0001f 12 | 13 | #define FILTER_ALPHA 0.7 14 | 15 | 16 | void AnalogDecoder::handleMagnitude(float val) 17 | { 18 | // 19 | // Smooth 20 | // 21 | m_val = (FILTER_ALPHA)*m_val + (1.0 - FILTER_ALPHA)*val; 22 | val = m_val; 23 | 24 | // 25 | // 1 of N 26 | // 27 | if(m_discardedSamples < (HW_RATIO-1)) 28 | { 29 | m_discardedSamples++; 30 | return; 31 | } 32 | 33 | m_discardedSamples = 0; 34 | 35 | // 36 | // Saturate 37 | // 38 | val = std::min(val, 1.0f); 39 | 40 | // 41 | // Threshold 42 | // 43 | m_ookMax -= OOK_DECAY_PER_SAMPLE; 44 | m_ookMax = std::max(m_ookMax, val); 45 | m_ookMax = std::max(m_ookMax, MIN_OOK_THRESHOLD/OOK_THRESHOLD_RATIO); 46 | 47 | // 48 | // Send to digital stage 49 | // 50 | int digital; 51 | if(m_cb) 52 | { 53 | if(val > m_ookMax*OOK_THRESHOLD_RATIO) 54 | { 55 | digital = 1; 56 | m_cb(1); 57 | } 58 | else 59 | { 60 | digital = 0; 61 | m_cb(0); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/mqtt.cpp: -------------------------------------------------------------------------------- 1 | #include "mqtt.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | Mqtt::Mqtt(const char * _id, const char * _host, int _port, const char * _username, const char * _password, const char * _will_topic, const char * _will_message) : mosquittopp(_id) 9 | { 10 | int version = MQTT_PROTOCOL_V311; 11 | mosqpp::lib_init(); 12 | this->keepalive = 30; 13 | this->id = _id; 14 | this->port = _port; 15 | this->host = _host; 16 | this->will_topic = _will_topic; 17 | this->will_message = _will_message; 18 | // Set version to 3.1.1 19 | opts_set(MOSQ_OPT_PROTOCOL_VERSION, &version); 20 | // Set username and password if non-null 21 | if (strlen(_username) > 0 && strlen(_password) > 0) { 22 | username_pw_set(_username, _password); 23 | } 24 | // Set last will and testament (LWT) message 25 | if (will_topic != NULL && will_message != NULL) { 26 | int rc = set_will(will_topic, will_message); 27 | if ( rc ) { 28 | std::cout <<">> Mqtt - set LWT message to: " << will_message << std::endl; 29 | } else { 30 | std::cout <<">> Mqtt - Failed to set LWT message!" << std::endl; 31 | } 32 | } 33 | // non blocking connection to broker request; 34 | connect_async(host, port, keepalive); 35 | // Start thread managing connection / publish / subscribekeepalive); 36 | loop_start(); 37 | }; 38 | 39 | Mqtt::~Mqtt() { 40 | loop_stop(); 41 | mosqpp::lib_cleanup(); 42 | } 43 | 44 | bool Mqtt::set_will(const char * _topic, const char * _message) 45 | { 46 | int ret = will_set(_topic, strlen(_message), _message, 1, true); 47 | return ( ret == MOSQ_ERR_SUCCESS ); 48 | } 49 | 50 | void Mqtt::on_disconnect(int rc) { 51 | std::cout << ">> Mqtt - disconnected(" << rc << ")" << std::endl; 52 | } 53 | 54 | void Mqtt::on_connect(int rc) 55 | { 56 | if ( rc == 0 ) { 57 | std::cout << ">> Mqtt - connected" << std::endl; 58 | } else { 59 | std::cout << ">> Mqtt - failed to connect: (" << rc << ")" << std::endl; 60 | } 61 | } 62 | 63 | void Mqtt::on_publish(int mid) 64 | { 65 | std::cout << ">> Mqtt - Message (" << mid << ") published " << std::endl; 66 | } 67 | 68 | bool Mqtt::send(const char * _topic, const char * _message) 69 | { 70 | // Send - depending on QoS, mosquitto lib managed re-submission this the thread 71 | // 72 | // * NULL : Message Id (int *) this allow to latter get status of each message 73 | // * topic : topic to be used 74 | // * length of the message 75 | // * message 76 | // * qos (0,1,2) 77 | // * retain (boolean) - indicates if message is retained on broker or not 78 | // Should return MOSQ_ERR_SUCCESS 79 | int ret = publish(NULL, _topic, strlen(_message), _message, 1, true); 80 | return ( ret == MOSQ_ERR_SUCCESS ); 81 | } 82 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HoneywellSecurityMQTT 2 | 3 | This project is based on jhaines0's HoneywellSecurity project but instead of being intended for integration with SmartThings, it is designed to report status via MQTT. This allows it to easily be used with other systems such as Home Assistant. 4 | 5 | 6 | ## Features 7 | - Decodes data from sensors based on Honeywell's 345MHz system. This includes rebrands such as 2GIG, Vivint, etc. 8 | - Requires no per-sensor configuration 9 | - Decodes sensor status such as tamper and low battery 10 | - Reports alarm and sensor status to an MQTT broker 11 | - Watchdog with reporting in case of receiver failure 12 | - Checks for sensors failing to report in 13 | 14 | 15 | ## Requirements 16 | - RTL-SDR USB adapter; commonly available on Amazon 17 | - rtlsdr library 18 | - mosquittopp library 19 | - gcc 20 | 21 | ## Installation 22 | ### Dependencies 23 | On a Debian-based system, something like this should work: 24 | ``` 25 | sudo apt-get install build-essential librtlsdr-dev rtl-sdr libmosquittopp-dev 26 | ``` 27 | 28 | To avoid having to run as root, you can add the following rule to a file in `/etc/udev/rules.d`: 29 | ``` 30 | SUBSYSTEMS=="usb", ATTRS{idVendor}=="0bda", ATTRS{idProduct}=="2838", MODE:="0660", GROUP:="audio" 31 | ``` 32 | 33 | Then add the desired user to the `audio` group. 34 | If you plugged in the RTL-SDR before installing rtl-sdr, you probably will need to do something like `sudo rmmod rtl2832 dvb_usb_rtl28xxu` then remove and reinstall the adapter. 35 | 36 | ### Configuration 37 | Modify `mqtt_config.h` to specify the host, port, username, and password of your MQTT broker. If `""` is used for the username or password, then an anonymous login is attempted. 38 | 39 | ### Building 40 | ``` 41 | cd src 42 | ./build.sh 43 | ``` 44 | 45 | ### Running 46 | `./honeywell` 47 | 48 | ### Home Assistant example 49 | ```yaml 50 | 51 | sensor: 52 | - platform: mqtt 53 | name: Front Door Status 54 | state_topic: "/security/sensors345/732804/status" 55 | binary_sensor: 56 | - platform: mqtt 57 | name: Front Door 58 | state_topic: "/security/sensors345/732804/alarm" 59 | payload_on: "ALARM" 60 | payload_off: "OK" 61 | device_class: opening 62 | - platform: mqtt 63 | name: 345MHz RX Fault 64 | state_topic: "/security/sensors345/rx_status" 65 | payload_on: "FAILED" 66 | payload_off: "OK" 67 | device_class: safety 68 | 69 | ``` 70 | 71 | ## Notes 72 | - The alarm loop bit will vary depending on sensor type and installation. To handle this without requiring manual configuration HoneywellSecurityMQTT will need to receive at least one non-triggered packet from each sensor. This can be accomplished by letting it run for at least ~90 minutes to allow pulse checks to arrive from each sensor. This does mean that if the first packet received is due to an event (e.g. open door), it will not be detected. Subsequent detections will work, however. A future improvement is to save the learned devices and their behavior so that future executions of the program will not require this learning period. 73 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | #include "digitalDecoder.h" 2 | #include "analogDecoder.h" 3 | #include "mqtt.h" 4 | #include "mqtt_config.h" 5 | 6 | #include 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | 15 | // Init MQTT, including will in case of disconnection 16 | // TODO: Will doesn't seem to be working with HA as expected 17 | Mqtt mqtt = Mqtt("sensors345", MQTT_HOST, MQTT_PORT, MQTT_USERNAME, MQTT_PASSWORD, "/security/sensors345/rx_status", "FAILED"); 18 | DigitalDecoder dDecoder(mqtt); 19 | AnalogDecoder aDecoder; 20 | 21 | float magLut[0x10000]; 22 | 23 | void alarmHandler(int signal) 24 | { 25 | dDecoder.setRxGood(false); 26 | } 27 | 28 | int main() 29 | { 30 | // 31 | // Open the device 32 | // 33 | if(rtlsdr_get_device_count() < 1) 34 | { 35 | std::cout << "Could not find any devices" << std::endl; 36 | return -1; 37 | } 38 | 39 | rtlsdr_dev_t *dev = nullptr; 40 | 41 | if(rtlsdr_open(&dev, 0) < 0) 42 | { 43 | std::cout << "Failed to open device" << std::endl; 44 | return -1; 45 | } 46 | 47 | // 48 | // Set the frequency 49 | // 50 | if(rtlsdr_set_center_freq(dev, 345000000) < 0) 51 | { 52 | std::cout << "Failed to set frequency" << std::endl; 53 | return -1; 54 | } 55 | 56 | std::cout << "Successfully set the frequency to " << rtlsdr_get_center_freq(dev) << std::endl; 57 | 58 | // 59 | // Set the gain 60 | // 61 | if(rtlsdr_set_tuner_gain_mode(dev, 1) < 0) 62 | { 63 | std::cout << "Failed to set gain mode" << std::endl; 64 | return -1; 65 | } 66 | 67 | if(rtlsdr_set_tuner_gain(dev, 350) < 0) 68 | { 69 | std::cout << "Failed to set gain" << std::endl; 70 | return -1; 71 | } 72 | 73 | std::cout << "Successfully set gain to " << rtlsdr_get_tuner_gain(dev) << std::endl; 74 | 75 | // 76 | // Set the sample rate 77 | // 78 | if(rtlsdr_set_sample_rate(dev, 1000000) < 0) 79 | { 80 | std::cout << "Failed to set sample rate" << std::endl; 81 | return -1; 82 | } 83 | 84 | std::cout << "Successfully set the sample rate to " << rtlsdr_get_sample_rate(dev) << std::endl; 85 | 86 | // 87 | // Prepare for streaming 88 | // 89 | rtlsdr_reset_buffer(dev); 90 | 91 | for(uint32_t ii = 0; ii < 0x10000; ++ii) 92 | { 93 | uint8_t real_i = ii & 0xFF; 94 | uint8_t imag_i = ii >> 8; 95 | 96 | float real = (((float)real_i) - 127.4) * (1.0f/128.0f); 97 | float imag = (((float)imag_i) - 127.4) * (1.0f/128.0f); 98 | 99 | float mag = std::sqrt(real*real + imag*imag); 100 | magLut[ii] = mag; 101 | } 102 | 103 | // 104 | // Common Receive 105 | // 106 | 107 | aDecoder.setCallback([&](char data){dDecoder.handleData(data);}); 108 | 109 | // 110 | // Async Receive 111 | // 112 | 113 | typedef void(*rtlsdr_read_async_cb_t)(unsigned char *buf, uint32_t len, void *ctx); 114 | 115 | auto cb = [](unsigned char *buf, uint32_t len, void *ctx) 116 | { 117 | AnalogDecoder *adec = (AnalogDecoder *)ctx; 118 | 119 | int n_samples = len/2; 120 | for(int i = 0; i < n_samples; ++i) 121 | { 122 | float mag = magLut[*((uint16_t*)(buf + i*2))]; 123 | adec->handleMagnitude(mag); 124 | } 125 | }; 126 | 127 | // Setup watchdog to check for a common-mode failure (e.g. antenna disconnection) 128 | std::signal(SIGALRM, alarmHandler); 129 | 130 | // Initialize RX state to good 131 | dDecoder.setRxGood(true); 132 | const int err = rtlsdr_read_async(dev, cb, &aDecoder, 0, 0); 133 | std::cout << "Read Async returned " << err << std::endl; 134 | 135 | /* 136 | // 137 | // Synchronous Receive 138 | // 139 | static const size_t BUF_SIZE = 1024*256; 140 | uint8_t buffer[BUF_SIZE]; 141 | 142 | while(true) 143 | { 144 | int n_read = 0; 145 | if(rtlsdr_read_sync(dev, buffer, BUF_SIZE, &n_read) < 0) 146 | { 147 | std::cout << "Failed to read from device" << std::endl; 148 | return -1; 149 | } 150 | 151 | int n_samples = n_read/2; 152 | for(int i = 0; i < n_samples; ++i) 153 | { 154 | float mag = magLut[*((uint16_t*)(buffer + i*2))]; 155 | aDecoder.handleMagnitude(mag); 156 | } 157 | } 158 | */ 159 | // 160 | // Shut down 161 | // 162 | rtlsdr_close(dev); 163 | return 0; 164 | } 165 | 166 | 167 | 168 | 169 | -------------------------------------------------------------------------------- /src/digitalDecoder.cpp: -------------------------------------------------------------------------------- 1 | #include "digitalDecoder.h" 2 | #include "mqtt.h" 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | 16 | // Pulse checks seem to be about 60-70 minutes apart 17 | #define RX_TIMEOUT_MIN (90) 18 | 19 | // Give each sensor 3 intervals before we flag a problem 20 | #define SENSOR_TIMEOUT_MIN (90*5) 21 | 22 | #define SYNC_MASK 0xFFFF000000000000ul 23 | #define SYNC_PATTERN 0xFFFE000000000000ul 24 | 25 | // Don't send these messages more than once per minute unless there is a state change 26 | #define RX_GOOD_MIN_SEC (60) 27 | #define UPDATE_MIN_SEC (60) 28 | 29 | static const char BASE_TOPIC[] = "/security/sensors345/"; 30 | 31 | void DigitalDecoder::setRxGood(bool state) 32 | { 33 | std::string topic(BASE_TOPIC); 34 | timeval now; 35 | 36 | topic += "rx_status"; 37 | 38 | gettimeofday(&now, nullptr); 39 | 40 | if (rxGood != state || (now.tv_sec - lastRxGoodUpdateTime) > RX_GOOD_MIN_SEC) 41 | { 42 | mqtt.send(topic.c_str(), state ? "OK" : "FAILED"); 43 | } 44 | 45 | // Reset watchdog either way 46 | alarm(RX_TIMEOUT_MIN*60); 47 | 48 | rxGood = state; 49 | lastRxGoodUpdateTime = now.tv_sec; 50 | } 51 | 52 | void DigitalDecoder::updateDeviceState(uint32_t serial, uint8_t state) 53 | { 54 | deviceState_t ds; 55 | uint8_t alarmState; 56 | std::ostringstream alarmTopic; 57 | std::ostringstream statusTopic; 58 | alarmTopic << BASE_TOPIC << serial << "/alarm"; 59 | statusTopic << BASE_TOPIC << serial << "/status"; 60 | 61 | // Extract prior info 62 | if(deviceStateMap.count(serial)) 63 | { 64 | ds = deviceStateMap[serial]; 65 | } 66 | else 67 | { 68 | ds.minAlarmStateSeen = 0xFF; 69 | ds.lastUpdateTime = 0; 70 | ds.lastAlarmTime = 0; 71 | } 72 | 73 | // Update minimum/OK state if needed 74 | // Look only at the non-tamper loop bits 75 | alarmState = (state & 0xB0); 76 | if(alarmState < ds.minAlarmStateSeen) ds.minAlarmStateSeen = alarmState; 77 | 78 | // Decode alarm bits 79 | // We just alarm on any active loop that has been previously observed as inactive 80 | // This hopefully avoids having to use per-sensor configuration 81 | ds.alarm = (alarmState > ds.minAlarmStateSeen); 82 | 83 | // Decode tamper bit 84 | ds.tamper = (state & 0x40); 85 | 86 | // Decode battery low bit 87 | ds.batteryLow = (state & 0x08); 88 | 89 | // Timestamp 90 | timeval now; 91 | gettimeofday(&now, nullptr); 92 | ds.timeout = false; 93 | 94 | if(ds.alarm) ds.lastAlarmTime = now.tv_sec; 95 | 96 | // Put the answer back in the map 97 | deviceStateMap[serial] = ds; 98 | 99 | // Send the notification if something changed or enough time has passed 100 | if(state != ds.lastRawState || (now.tv_sec - ds.lastUpdateTime) > UPDATE_MIN_SEC) 101 | { 102 | std::ostringstream status; 103 | 104 | // Send alarm state 105 | mqtt.send(alarmTopic.str().c_str(), ds.alarm ? "ALARM" : "OK"); 106 | 107 | // Build and send combined fault status 108 | if (!ds.tamper && !ds.batteryLow) 109 | { 110 | status << "OK"; 111 | } else { 112 | 113 | if (ds.tamper) 114 | { 115 | status << "TAMPER "; 116 | } 117 | 118 | if (ds.batteryLow) 119 | { 120 | status << "LOWBATT"; 121 | } 122 | } 123 | mqtt.send(statusTopic.str().c_str(), status.str().c_str()); 124 | 125 | deviceStateMap[serial].lastUpdateTime = now.tv_sec; 126 | deviceStateMap[serial].lastRawState = state; 127 | 128 | checkForTimeouts(); 129 | 130 | for(const auto &dd : deviceStateMap) 131 | { 132 | printf("%sDevice %7u: %s %s %s %s\n",dd.first==serial ? "*" : " ", dd.first, dd.second.alarm ? "ALARM" : "OK", dd.second.tamper ? "TAMPER" : "", dd.second.batteryLow ? "LOWBATT" : "", dd.second.timeout ? "TIMEOUT" : ""); 133 | } 134 | std::cout << std::endl; 135 | 136 | } 137 | 138 | } 139 | 140 | /* Checks all devices for last time updated */ 141 | void DigitalDecoder::checkForTimeouts() 142 | { 143 | timeval now; 144 | std::ostringstream status; 145 | 146 | status << "TIMEOUT"; 147 | gettimeofday(&now, nullptr); 148 | 149 | for(const auto &dd : deviceStateMap) 150 | { 151 | if ((now.tv_sec - dd.second.lastUpdateTime) > SENSOR_TIMEOUT_MIN*60) 152 | { 153 | if (false == dd.second.timeout) 154 | { 155 | std::ostringstream statusTopic; 156 | 157 | deviceStateMap[dd.first].timeout = true; 158 | statusTopic << BASE_TOPIC << dd.first << "/status"; 159 | mqtt.send(statusTopic.str().c_str(), status.str().c_str()); 160 | } 161 | } 162 | } 163 | } 164 | 165 | void DigitalDecoder::handlePayload(uint64_t payload) 166 | { 167 | uint64_t sof = (payload & 0xF00000000000) >> 44; 168 | uint64_t ser = (payload & 0x0FFFFF000000) >> 24; 169 | uint64_t typ = (payload & 0x000000FF0000) >> 16; 170 | uint64_t crc = (payload & 0x00000000FFFF) >> 0; 171 | 172 | // 173 | // Check CRC 174 | // 175 | uint64_t polynomial; 176 | if (sof == 0x2 || sof == 0xA) { 177 | // 2GIG brand 178 | polynomial = 0x18050; 179 | } else { 180 | // sof == 0x8 181 | polynomial = 0x18005; 182 | } 183 | uint64_t sum = payload & (~SYNC_MASK); 184 | uint64_t current_divisor = polynomial << 31; 185 | 186 | while(current_divisor >= polynomial) 187 | { 188 | #ifdef __arm__ 189 | if(__builtin_clzll(sum) == __builtin_clzll(current_divisor)) 190 | #else 191 | if(__builtin_clzl(sum) == __builtin_clzl(current_divisor)) 192 | #endif 193 | { 194 | sum ^= current_divisor; 195 | } 196 | current_divisor >>= 1; 197 | } 198 | 199 | const bool valid = (sum == 0); 200 | 201 | // 202 | // Print Packet 203 | // 204 | #ifdef __arm__ 205 | if(valid) 206 | printf("Valid Payload: %llX (Serial %llu, Status %llX)", payload, ser, typ); 207 | else 208 | printf("Invalid Payload: %llX", payload); 209 | #else 210 | if(valid) 211 | printf("Valid Payload: %lX (Serial %lu, Status %lX)", payload, ser, typ); 212 | else 213 | printf("Invalid Payload: %lX", payload); 214 | #endif 215 | std::cout << std::endl; 216 | 217 | packetCount++; 218 | if(!valid) 219 | { 220 | errorCount++; 221 | printf("%u/%u packets failed CRC", errorCount, packetCount); 222 | std::cout << std::endl; 223 | } 224 | 225 | // 226 | // Tell the world 227 | // 228 | if(valid) 229 | { 230 | // We received a valid packet so the receiver must be working 231 | setRxGood(true); 232 | // Update the device 233 | updateDeviceState(ser, typ); 234 | } 235 | } 236 | 237 | 238 | 239 | void DigitalDecoder::handleBit(bool value) 240 | { 241 | static uint64_t payload = 0; 242 | 243 | payload <<= 1; 244 | payload |= (value ? 1 : 0); 245 | 246 | //#ifdef __arm__ 247 | // printf("Got bit: %d, payload is now %llX\n", value?1:0, payload); 248 | //#else 249 | // printf("Got bit: %d, payload is now %lX\n", value?1:0, payload); 250 | //#endif 251 | 252 | if((payload & SYNC_MASK) == SYNC_PATTERN) 253 | { 254 | handlePayload(payload); 255 | payload = 0; 256 | } 257 | } 258 | 259 | void DigitalDecoder::decodeBit(bool value) 260 | { 261 | enum ManchesterState 262 | { 263 | LOW_PHASE_A, 264 | LOW_PHASE_B, 265 | HIGH_PHASE_A, 266 | HIGH_PHASE_B 267 | }; 268 | 269 | static ManchesterState state = LOW_PHASE_A; 270 | 271 | switch(state) 272 | { 273 | case LOW_PHASE_A: 274 | { 275 | state = value ? HIGH_PHASE_B : LOW_PHASE_A; 276 | break; 277 | } 278 | case LOW_PHASE_B: 279 | { 280 | handleBit(false); 281 | state = value ? HIGH_PHASE_A : LOW_PHASE_A; 282 | break; 283 | } 284 | case HIGH_PHASE_A: 285 | { 286 | state = value ? HIGH_PHASE_A : LOW_PHASE_B; 287 | break; 288 | } 289 | case HIGH_PHASE_B: 290 | { 291 | handleBit(true); 292 | state = value ? HIGH_PHASE_A : LOW_PHASE_A; 293 | break; 294 | } 295 | } 296 | } 297 | 298 | void DigitalDecoder::handleData(char data) 299 | { 300 | static const int samplesPerBit = 8; 301 | 302 | 303 | if(data != 0 && data != 1) return; 304 | 305 | const bool thisSample = (data == 1); 306 | 307 | if(thisSample == lastSample) 308 | { 309 | samplesSinceEdge++; 310 | 311 | //if(samplesSinceEdge < 100) 312 | //{ 313 | // printf("At %d for %u\n", thisSample?1:0, samplesSinceEdge); 314 | //} 315 | 316 | if((samplesSinceEdge % samplesPerBit) == (samplesPerBit/2)) 317 | { 318 | // This Sample is a new bit 319 | decodeBit(thisSample); 320 | } 321 | } 322 | else 323 | { 324 | samplesSinceEdge = 1; 325 | } 326 | lastSample = thisSample; 327 | } 328 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------