/* * ESP32-H2 + CC1101 POCSAG pager receiver * Native ESP-IDF; no third-party libraries. * * Hardware: * CC1101: SCLK=GPIO4, MOSI=GPIO5, MISO=GPIO0, CSN=GPIO1, GDO0=GPIO3 * SPI SSD1306 128x64: SCLK=GPIO4, MOSI=GPIO5, CS=GPIO13, * DC=GPIO14, RESET=GPIO12 * * Assumptions: * - CC1101 module has a 26 MHz crystal. * - RF centre frequency is set with RF_FREQ_HZ below. * - OLED is a 7-pin SPI SSD1306 (not I2C, not SH1106). * * This is an experimental receiver. It does not guarantee reception * under weak/noisy signals. Validate RF frequency, deviation, polarity, * and timing against a known-good POCSAG transmitter. */ #include #include #include #include #include #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_err.h" #include "esp_log.h" #include "esp_attr.h" #include "driver/gpio.h" #include "driver/spi_master.h" #include "driver/gptimer.h" #include "led_strip.h" /* ---------------------------- Pins/config ---------------------------- */ #define SPI_HOST_USED SPI2_HOST #define PIN_SPI_SCLK GPIO_NUM_4 #define PIN_SPI_MOSI GPIO_NUM_5 #define PIN_SPI_MISO GPIO_NUM_0 #define PIN_CC1101_CS GPIO_NUM_1 #define PIN_CC1101_GDO0 GPIO_NUM_3 #define PIN_OLED_CS GPIO_NUM_10 #define PIN_OLED_DC GPIO_NUM_11 #define PIN_OLED_RESET GPIO_NUM_12 #define PIN_BUTTON_BOOT GPIO_NUM_9 #define PIN_STATUS_LED GPIO_NUM_13 #define PIN_NEOPIXEL GPIO_NUM_8 /* Change this one value to tune the receiver. Rebuild and flash afterwards. */ #define RF_FREQ_HZ 435000000UL #define CC1101_XTAL_HZ 26000000UL #define MY_RIC 1234567UL #define OLED_IDLE_OFF_MS 60000U #define OWN_PAGE_ALERT_MS 3000U #define SAMPLE_TIMER_HZ 1000000UL #define SAMPLE_PERIOD_TICKS 26UL #define SAMPLE_RATE_HZ (SAMPLE_TIMER_HZ / SAMPLE_PERIOD_TICKS) #define SAMPLE_BUF_SIZE 16384U #define SAMPLE_BUF_MASK (SAMPLE_BUF_SIZE - 1U) #define SPI_TRANSFER_CHUNK 64U #define HISTORY_COUNT 8 #define MESSAGE_SIZE 160 static const char *TAG = "pager"; /* ---------------------------- SPI devices ---------------------------- */ static spi_device_handle_t cc_dev; static spi_device_handle_t oled_dev; static gptimer_handle_t sample_timer; static led_strip_handle_t neopixel; static unsigned display_baud; static bool oled_is_on = true; static TickType_t ui_last_activity; static esp_err_t spi_tx(spi_device_handle_t dev, const uint8_t *data, size_t len) { spi_transaction_t t = { .length = len * 8, .tx_buffer = data, }; return spi_device_polling_transmit(dev, &t); } static esp_err_t spi_txrx(spi_device_handle_t dev, const uint8_t *tx, uint8_t *rx, size_t len) { spi_transaction_t t = { .length = len * 8, .tx_buffer = tx, .rx_buffer = rx, }; return spi_device_polling_transmit(dev, &t); } static void setup_spi(void) { spi_bus_config_t bus = { .mosi_io_num = PIN_SPI_MOSI, .miso_io_num = PIN_SPI_MISO, .sclk_io_num = PIN_SPI_SCLK, .quadwp_io_num = -1, .quadhd_io_num = -1, .max_transfer_sz = SPI_TRANSFER_CHUNK, }; ESP_ERROR_CHECK(spi_bus_initialize(SPI_HOST_USED, &bus, SPI_DMA_DISABLED)); spi_device_interface_config_t cc_cfg = { .clock_speed_hz = 1000000, .mode = 0, .spics_io_num = PIN_CC1101_CS, .queue_size = 1, }; ESP_ERROR_CHECK(spi_bus_add_device(SPI_HOST_USED, &cc_cfg, &cc_dev)); spi_device_interface_config_t oled_cfg = { .clock_speed_hz = 4000000, .mode = 0, .spics_io_num = PIN_OLED_CS, .queue_size = 1, }; ESP_ERROR_CHECK(spi_bus_add_device(SPI_HOST_USED, &oled_cfg, &oled_dev)); } /* ------------------------------- CC1101 ------------------------------- */ static void cc_write(uint8_t reg, uint8_t val) { uint8_t b[2] = { reg, val }; ESP_ERROR_CHECK(spi_tx(cc_dev, b, sizeof(b))); } static uint8_t cc_read_status(uint8_t reg) { uint8_t tx[2] = { (uint8_t)(reg | 0xC0), 0 }; uint8_t rx[2] = { 0 }; ESP_ERROR_CHECK(spi_txrx(cc_dev, tx, rx, sizeof(tx))); return rx[1]; } static void cc_strobe(uint8_t cmd) { ESP_ERROR_CHECK(spi_tx(cc_dev, &cmd, 1)); } /* CC1101 frequency word: FREQ = RF * 2^16 / crystal frequency. */ static uint32_t cc1101_set_frequency(uint32_t frequency_hz) { uint64_t numerator = ((uint64_t)frequency_hz << 16) + (CC1101_XTAL_HZ / 2U); uint32_t word = (uint32_t)(numerator / CC1101_XTAL_HZ); cc_write(0x0D, (uint8_t)(word >> 16)); cc_write(0x0E, (uint8_t)(word >> 8)); cc_write(0x0F, (uint8_t)word); return (uint32_t)(((uint64_t)word * CC1101_XTAL_HZ + 32768U) >> 16); } static void cc1101_init(void) { ESP_LOGI(TAG, "Resetting CC1101"); cc_strobe(0x30); /* SRES */ vTaskDelay(pdMS_TO_TICKS(10)); /* * Async serial output on GDO0. Packet engine is bypassed. * MDMCFG4/3 select a wide receiver bandwidth and a 1200-baud * modem rate; software validates the POCSAG preamble rate. */ const uint8_t regs[][2] = { {0x00, 0x0D}, /* IOCFG2 */ {0x01, 0x2E}, /* IOCFG1 */ {0x02, 0x0D}, /* IOCFG0: async data */ {0x06, 0xFF}, /* PKTLEN */ {0x07, 0x04}, /* PKTCTRL1 */ {0x08, 0x32}, /* PKTCTRL0: async serial */ {0x0B, 0x06}, /* FSCTRL1 */ {0x0C, 0x00}, /* FSCTRL0 */ {0x10, 0xB5}, /* MDMCFG4: 1200 baud, wide channel BW */ {0x11, 0x83}, /* MDMCFG3 */ {0x12, 0x00}, /* MDMCFG2: 2-FSK */ {0x13, 0x22}, /* MDMCFG1 */ {0x14, 0xF8}, /* MDMCFG0 */ {0x15, 0x14}, /* DEVIATN */ {0x18, 0x18}, /* MCSM0 */ {0x19, 0x16}, /* FOCCFG */ {0x1A, 0x6C}, /* BSCFG */ {0x1B, 0x43}, /* AGCCTRL2 */ {0x1C, 0x40}, /* AGCCTRL1 */ {0x1D, 0x91}, /* AGCCTRL0 */ }; for (size_t i = 0; i < sizeof(regs) / sizeof(regs[0]); i++) cc_write(regs[i][0], regs[i][1]); uint32_t actual_hz = cc1101_set_frequency(RF_FREQ_HZ); ESP_LOGI(TAG, "RF target=%lu Hz, actual=%lu Hz, crystal=%lu Hz", (unsigned long)RF_FREQ_HZ, (unsigned long)actual_hz, (unsigned long)CC1101_XTAL_HZ); cc_strobe(0x33); /* SCAL */ vTaskDelay(pdMS_TO_TICKS(5)); cc_strobe(0x3A); /* SFRX */ cc_strobe(0x34); /* SRX */ ESP_LOGI(TAG, "CC1101 PARTNUM=0x%02X VERSION=0x%02X", cc_read_status(0x30), cc_read_status(0x31)); } /* ------------------------------ SSD1306 ------------------------------ */ static uint8_t fb[1024]; /* Small 5x7 font for uppercase letters, digits and common punctuation. * Lowercase input is converted to uppercase on display. */ static const uint8_t font[][5] = { {0,0,0,0,0}, /* space */ {0,0,0x5F,0,0}, /* ! */ {0x03,0x00,0x03,0x00,0}, /* " */ {0x14,0x7F,0x14,0x7F,0x14}, /* # */ {0x24,0x2A,0x7F,0x2A,0x12}, /* $ */ {0x23,0x13,0x08,0x64,0x62}, /* % */ {0x36,0x49,0x55,0x22,0x50}, /* & */ {0x05,0x03,0,0,0}, /* ' */ {0x1C,0x22,0x41,0,0}, /* ( */ {0x41,0x22,0x1C,0,0}, /* ) */ {0x14,0x08,0x3E,0x08,0x14}, /* * */ {0x08,0x08,0x3E,0x08,0x08}, /* + */ {0x50,0x30,0,0,0}, /* , */ {0x08,0x08,0x08,0x08,0x08}, /* - */ {0x60,0x60,0,0,0}, /* . */ {0x20,0x10,0x08,0x04,0x02}, /* / */ {0x3E,0x51,0x49,0x45,0x3E}, /* 0 */ {0x00,0x42,0x7F,0x40,0x00}, /* 1 */ {0x42,0x61,0x51,0x49,0x46}, /* 2 */ {0x21,0x41,0x45,0x4B,0x31}, /* 3 */ {0x18,0x14,0x12,0x7F,0x10}, /* 4 */ {0x27,0x45,0x45,0x45,0x39}, /* 5 */ {0x3C,0x4A,0x49,0x49,0x30}, /* 6 */ {0x01,0x71,0x09,0x05,0x03}, /* 7 */ {0x36,0x49,0x49,0x49,0x36}, /* 8 */ {0x06,0x49,0x49,0x29,0x1E}, /* 9 */ {0x7E,0x11,0x11,0x11,0x7E}, /* A */ {0x7F,0x49,0x49,0x49,0x36}, /* B */ {0x3E,0x41,0x41,0x41,0x22}, /* C */ {0x7F,0x41,0x41,0x22,0x1C}, /* D */ {0x7F,0x49,0x49,0x49,0x41}, /* E */ {0x7F,0x09,0x09,0x09,0x01}, /* F */ {0x3E,0x41,0x49,0x49,0x7A}, /* G */ {0x7F,0x08,0x08,0x08,0x7F}, /* H */ {0x00,0x41,0x7F,0x41,0x00}, /* I */ {0x20,0x40,0x41,0x3F,0x01}, /* J */ {0x7F,0x08,0x14,0x22,0x41}, /* K */ {0x7F,0x40,0x40,0x40,0x40}, /* L */ {0x7F,0x02,0x0C,0x02,0x7F}, /* M */ {0x7F,0x04,0x08,0x10,0x7F}, /* N */ {0x3E,0x41,0x41,0x41,0x3E}, /* O */ {0x7F,0x09,0x09,0x09,0x06}, /* P */ {0x3E,0x41,0x51,0x21,0x5E}, /* Q */ {0x7F,0x09,0x19,0x29,0x46}, /* R */ {0x46,0x49,0x49,0x49,0x31}, /* S */ {0x01,0x01,0x7F,0x01,0x01}, /* T */ {0x3F,0x40,0x40,0x40,0x3F}, /* U */ {0x1F,0x20,0x40,0x20,0x1F}, /* V */ {0x3F,0x40,0x38,0x40,0x3F}, /* W */ {0x63,0x14,0x08,0x14,0x63}, /* X */ {0x07,0x08,0x70,0x08,0x07}, /* Y */ {0x61,0x51,0x49,0x45,0x43}, /* Z */ {0x7F,0x41,0x41,0,0}, /* [ */ {0x02,0x04,0x08,0x10,0x20}, /* backslash */ {0,0x41,0x41,0x7F,0}, /* ] */ {0x04,0x02,0x01,0x02,0x04}, /* ^ */ {0x40,0x40,0x40,0x40,0x40}, /* _ */ {0x01,0x02,0x04,0,0}, /* ` */ {0x20,0x54,0x54,0x54,0x78}, /* a */ {0x7F,0x48,0x44,0x44,0x38}, /* b */ {0x38,0x44,0x44,0x44,0x20}, /* c */ {0x38,0x44,0x44,0x48,0x7F}, /* d */ {0x38,0x54,0x54,0x54,0x18}, /* e */ {0x08,0x7E,0x09,0x01,0x02}, /* f */ {0x0C,0x52,0x52,0x52,0x3E}, /* g */ {0x7F,0x08,0x04,0x04,0x78}, /* h */ {0,0x44,0x7D,0x40,0}, /* i */ {0x20,0x40,0x44,0x3D,0}, /* j */ {0x7F,0x10,0x28,0x44,0}, /* k */ {0,0x41,0x7F,0x40,0}, /* l */ {0x7C,0x04,0x18,0x04,0x78}, /* m */ {0x7C,0x08,0x04,0x04,0x78}, /* n */ {0x38,0x44,0x44,0x44,0x38}, /* o */ {0x7C,0x14,0x14,0x14,0x08}, /* p */ {0x08,0x14,0x14,0x18,0x7C}, /* q */ {0x7C,0x08,0x04,0x04,0x08}, /* r */ {0x48,0x54,0x54,0x54,0x20}, /* s */ {0x04,0x3F,0x44,0x40,0x20}, /* t */ {0x3C,0x40,0x40,0x20,0x7C}, /* u */ {0x1C,0x20,0x40,0x20,0x1C}, /* v */ {0x3C,0x40,0x30,0x40,0x3C}, /* w */ {0x44,0x28,0x10,0x28,0x44}, /* x */ {0x0C,0x50,0x50,0x50,0x3C}, /* y */ {0x44,0x64,0x54,0x4C,0x44}, /* z */ }; static void oled_cmd(uint8_t cmd) { gpio_set_level(PIN_OLED_DC, 0); ESP_ERROR_CHECK(spi_tx(oled_dev, &cmd, 1)); } static void oled_power_on(void) { if (!oled_is_on) { oled_cmd(0xAF); oled_is_on = true; } } static void oled_power_off(void) { if (oled_is_on) { oled_cmd(0xAE); oled_is_on = false; } } static void oled_data(const uint8_t *data, size_t len) { gpio_set_level(PIN_OLED_DC, 1); while (len > 0) { size_t chunk = len > SPI_TRANSFER_CHUNK ? SPI_TRANSFER_CHUNK : len; ESP_ERROR_CHECK(spi_tx(oled_dev, data, chunk)); data += chunk; len -= chunk; } } static void oled_init(void) { gpio_config_t out = { .pin_bit_mask = (1ULL << PIN_OLED_DC) | (1ULL << PIN_OLED_RESET), .mode = GPIO_MODE_OUTPUT, }; ESP_ERROR_CHECK(gpio_config(&out)); gpio_set_level(PIN_OLED_RESET, 0); vTaskDelay(pdMS_TO_TICKS(30)); gpio_set_level(PIN_OLED_RESET, 1); vTaskDelay(pdMS_TO_TICKS(30)); const uint8_t init_seq[] = { 0xAE, 0xD5, 0x80, 0xA8, 0x3F, 0xD3, 0x00, 0x40, 0x8D, 0x14, 0x20, 0x00, 0xA1, 0xC8, 0xDA, 0x12, 0x81, 0x7F, 0xD9, 0xF1, 0xDB, 0x40, 0xA4, 0xA6, 0xAF }; for (size_t i = 0; i < sizeof(init_seq); i++) oled_cmd(init_seq[i]); memset(fb, 0, sizeof(fb)); } static void oled_flush(void) { oled_cmd(0x21); oled_cmd(0); oled_cmd(127); oled_cmd(0x22); oled_cmd(0); oled_cmd(7); oled_data(fb, sizeof(fb)); } static void oled_clear(void) { memset(fb, 0, sizeof(fb)); } static void oled_pixel(int x, int y) { if (x < 0 || x >= 128 || y < 0 || y >= 64) return; fb[(y / 8) * 128 + x] |= (uint8_t)(1U << (y & 7)); } static void oled_char(int x, int y, char c) { if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); unsigned idx; if (c == ' ') idx = 0; else if (c >= '!' && c <= '/') idx = (unsigned)(c - ' '); else if (c >= '0' && c <= '9') idx = 16U + (unsigned)(c - '0'); else if (c >= 'A' && c <= 'Z') idx = 26U + (unsigned)(c - 'A'); else if (c >= '[' && c <= '`') idx = 52U + (unsigned)(c - '['); else idx = 0; if (idx >= sizeof(font) / sizeof(font[0])) idx = 0; for (int col = 0; col < 5; col++) { uint8_t bits = font[idx][col]; for (int row = 0; row < 7; row++) if (bits & (1U << row)) oled_pixel(x + col, y + row); } } static void oled_text(int x, int y, const char *s) { while (*s && x <= 122) { oled_char(x, y, *s++); x += 6; } } /* -------------------------- Message history -------------------------- */ typedef struct { uint32_t ric; unsigned baud; unsigned function; char text[MESSAGE_SIZE]; } pager_message_t; static pager_message_t history[HISTORY_COUNT]; static unsigned history_count = 0; static unsigned history_head = 0; static unsigned history_cursor; static bool monitor_mode; static unsigned ui_screen; static unsigned menu_cursor; static bool live_page; static unsigned text_page; static void ui_render(void); static void ui_note_activity(void); static void history_add(uint32_t ric, unsigned baud, unsigned function, const char *text) { if (!text || !text[0]) return; if (!monitor_mode && ric != MY_RIC) return; pager_message_t *m = &history[history_head]; m->ric = ric; m->baud = baud; m->function = function; strlcpy(m->text, text, sizeof(m->text)); history_head = (history_head + 1) % HISTORY_COUNT; if (history_count < HISTORY_COUNT) history_count++; history_cursor = 0; ui_note_activity(); ESP_LOGI(TAG, "PAGER RIC=%lu function=%u baud=%u: %s", (unsigned long)ric, function, baud, text); ui_render(); } /* ------------------------------- BCH --------------------------------- */ #define POCSAG_SYNC 0x7CD215D8UL #define POCSAG_IDLE 0x7A89C197UL #define BCH_POLY 0x769U static uint32_t syndrome_errors[1024]; static uint16_t bch_syndrome(uint32_t value) { for (int bit = 30; bit >= 10; bit--) { if (value & (1UL << bit)) value ^= (uint32_t)BCH_POLY << (bit - 10); } return (uint16_t)(value & 0x3FF); } static void bch_init(void) { memset(syndrome_errors, 0, sizeof(syndrome_errors)); for (int i = 0; i < 31; i++) { uint32_t e = 1UL << i; syndrome_errors[bch_syndrome(e)] = e; } for (int i = 0; i < 31; i++) { for (int j = i + 1; j < 31; j++) { uint32_t e = (1UL << i) | (1UL << j); syndrome_errors[bch_syndrome(e)] = e; } } } static bool bch_correct(uint32_t *word, unsigned *ncorrected) { uint32_t upper31 = *word >> 1; uint16_t syn = bch_syndrome(upper31); uint32_t error = syndrome_errors[syn]; if (syn && !error) return false; upper31 ^= error; unsigned parity = 0; for (int i = 1; i < 32; i++) parity ^= (upper31 >> (i - 1)) & 1U; unsigned parity_error = ((*word & 1U) != parity); unsigned error_count = (unsigned)__builtin_popcount(error); if (error_count + parity_error > 2U) return false; uint32_t rebuilt = (upper31 << 1) | parity; *word = rebuilt; *ncorrected = error_count + parity_error; return true; } /* ---------------------------- POCSAG decode --------------------------- */ typedef enum { RATE_UNKNOWN = 0, RATE_512 = 512, RATE_1200 = 1200, RATE_2400 = 2400 } baud_t; static baud_t current_baud = RATE_UNKNOWN; static uint32_t bit_period_q16; static uint32_t phase_q16; static uint32_t edge_samples; static unsigned hit512, hit1200, hit2400; static uint8_t last_sample; static uint32_t observed_edges; static uint32_t edge_period_sum; static uint32_t edge_period_min = UINT32_MAX; static uint32_t edge_period_max; static unsigned edge_period_count; static uint32_t sync_shift; static unsigned sync_bits; static bool batch_locked; static bool invert_bits; static uint32_t codeword_shift; static unsigned codeword_bits; static unsigned batch_word_index; static uint32_t current_ric; static unsigned current_function; static bool message_active; static char message[MESSAGE_SIZE]; static size_t message_len; static uint32_t alpha_acc; static unsigned alpha_nbits; static unsigned numeric_nibble_count; static const char numeric_chars[16] = { '0','1','2','3','4','5','6','7', '8','9','U',' ','-','[',']','?' }; enum { UI_LIVE, UI_HISTORY, UI_MENU }; static TickType_t button_debounce_at; static TickType_t button_pressed_at; static TickType_t page_alert_until; static TickType_t alert_toggle_at; static int button_last_level = 1; static bool button_down; static bool alert_led_on; static bool alert_output_state; static bool alert_output_initialized; static unsigned menu_return_screen; static pager_message_t *history_at_age(unsigned age) { if (age >= history_count) return NULL; unsigned index = (history_head + HISTORY_COUNT - 1U - age) % HISTORY_COUNT; return &history[index]; } static void ui_note_activity(void) { ui_last_activity = xTaskGetTickCount(); oled_power_on(); } static unsigned text_page_count(size_t length) { return length ? (unsigned)((length + 83U) / 84U) : 1U; } static void oled_draw_text_page(int y, const char *text, unsigned page) { size_t offset = (size_t)page * 84U; size_t length = strlen(text); if (offset >= length) return; text += offset; for (unsigned row = 0; row < 4U && *text; row++) { char line[22]; size_t count = strnlen(text, 21U); memcpy(line, text, count); line[count] = '\0'; oled_text(0, y + (int)row * 8, line); text += count; } } static void ui_draw_live(void) { char line[24]; oled_text(0, 0, monitor_mode ? "POCSAG MONITOR" : "MY PAGER"); snprintf(line, sizeof(line), "RIC %lu", (unsigned long)MY_RIC); oled_text(0, 9, line); if (live_page && message_active) { unsigned pages = text_page_count(message_len); if (text_page >= pages) text_page = 0; snprintf(line, sizeof(line), "RX %lu F%u %u/%u", (unsigned long)current_ric, current_function, text_page + 1U, pages); oled_text(0, 18, line); oled_draw_text_page(27, message, text_page); return; } pager_message_t *latest = history_at_age(0); if (latest) { snprintf(line, sizeof(line), "LAST %lu F%u", (unsigned long)latest->ric, latest->function); oled_text(0, 20, line); unsigned pages = text_page_count(strlen(latest->text)); if (text_page >= pages) text_page = 0; snprintf(line, sizeof(line), "PAGE %u/%u", text_page + 1U, pages); oled_text(78, 20, line); oled_draw_text_page(31, latest->text, text_page); } else { oled_text(0, 25, display_baud ? "WAITING FOR PAGE" : "WAITING FOR RF"); } } static void ui_draw_history(void) { char line[24]; pager_message_t *entry = history_at_age(history_cursor); oled_text(0, 0, "MESSAGE HISTORY"); if (!entry) { oled_text(0, 18, "NO SAVED PAGES"); oled_text(0, 52, "HOLD FOR MENU"); return; } snprintf(line, sizeof(line), "%u/%u RIC %lu", history_cursor + 1U, history_count, (unsigned long)entry->ric); oled_text(0, 10, line); snprintf(line, sizeof(line), "F%u %u BAUD", entry->function, entry->baud); oled_text(0, 19, line); unsigned pages = text_page_count(strlen(entry->text)); if (text_page >= pages) text_page = 0; snprintf(line, sizeof(line), "PAGE %u/%u", text_page + 1U, pages); oled_text(78, 19, line); oled_draw_text_page(30, entry->text, text_page); } static void ui_draw_menu(void) { static const uint8_t cursor_rows[7] = { 0x01, 0x02, 0x04, 0x08, 0x04, 0x02, 0x01 }; const char *items[] = { monitor_mode ? "FILTER: ALL RIC" : "FILTER: MY RIC", "LIVE DISPLAY", "MESSAGE HISTORY", "RETURN" }; oled_text(0, 0, "PAGER MENU"); for (unsigned i = 0; i < 4; i++) { int y = 11 + (int)i * 10; if (i == menu_cursor) { for (int row = 0; row < 7; row++) { for (int col = 0; col < 5; col++) { if (cursor_rows[row] & (1U << col)) oled_pixel(col, y + row); } } } oled_text(8, y, items[i]); } oled_text(0, 55, "TAP NEXT, HOLD SELECT"); } static void ui_render(void) { if (!oled_is_on) oled_power_on(); oled_clear(); if (ui_screen == UI_MENU) ui_draw_menu(); else if (ui_screen == UI_HISTORY) ui_draw_history(); else ui_draw_live(); oled_flush(); } static void oled_draw_history(void) { ui_render(); } static void ui_short_press(void) { ui_note_activity(); if (ui_screen == UI_MENU) { menu_cursor = (menu_cursor + 1U) % 4U; } else if (ui_screen == UI_LIVE) { if (live_page && message_active && text_page + 1U < text_page_count(message_len)) { text_page++; } else { ui_screen = UI_HISTORY; history_cursor = 0; text_page = 0; } } else if (history_count) { pager_message_t *entry = history_at_age(history_cursor); if (entry && text_page + 1U < text_page_count(strlen(entry->text))) { text_page++; } else { history_cursor = (history_cursor + 1U) % history_count; text_page = 0; } } else { ui_screen = UI_LIVE; } ui_render(); } static void ui_long_press(void) { ui_note_activity(); if (ui_screen != UI_MENU) { menu_return_screen = ui_screen; ui_screen = UI_MENU; menu_cursor = 0; ui_render(); return; } switch (menu_cursor) { case 0: monitor_mode = !monitor_mode; history_count = 0; history_head = 0; history_cursor = 0; text_page = 0; break; case 1: ui_screen = UI_LIVE; break; case 2: ui_screen = UI_HISTORY; history_cursor = 0; text_page = 0; break; default: ui_screen = menu_return_screen; break; } ui_render(); } static void ui_poll_button(void) { TickType_t now = xTaskGetTickCount(); int level = gpio_get_level(PIN_BUTTON_BOOT); if (level != button_last_level) { button_last_level = level; button_debounce_at = now; return; } if (now - button_debounce_at < pdMS_TO_TICKS(30)) return; if (level == 0 && !button_down) { button_down = true; button_pressed_at = now; } else if (level != 0 && button_down) { button_down = false; if (now - button_pressed_at >= pdMS_TO_TICKS(700)) ui_long_press(); else ui_short_press(); } } static void ui_idle_power_down(void) { if (oled_is_on && xTaskGetTickCount() - ui_last_activity >= pdMS_TO_TICKS(OLED_IDLE_OFF_MS)) oled_power_off(); } static void ui_start_own_page_alert(void) { TickType_t now = xTaskGetTickCount(); page_alert_until = now + pdMS_TO_TICKS(OWN_PAGE_ALERT_MS); alert_toggle_at = now; alert_led_on = false; } static void ui_update_alert(void) { TickType_t now = xTaskGetTickCount(); if ((int32_t)(now - page_alert_until) >= 0) { alert_led_on = false; } else if ((int32_t)(now - alert_toggle_at) >= 0) { alert_led_on = !alert_led_on; alert_toggle_at = now + pdMS_TO_TICKS(150); } bool changed = !alert_output_initialized || alert_led_on != alert_output_state; if (changed) { gpio_set_level(PIN_STATUS_LED, alert_led_on ? 1 : 0); if (alert_led_on) ESP_ERROR_CHECK(led_strip_set_pixel(neopixel, 0, 255, 24, 0)); else ESP_ERROR_CHECK(led_strip_clear(neopixel)); ESP_ERROR_CHECK(led_strip_refresh(neopixel)); alert_output_state = alert_led_on; alert_output_initialized = true; } } static void ui_hardware_init(void) { gpio_config_t button_cfg = { .pin_bit_mask = 1ULL << PIN_BUTTON_BOOT, .mode = GPIO_MODE_INPUT, .pull_up_en = GPIO_PULLUP_ENABLE, .pull_down_en = GPIO_PULLDOWN_DISABLE, .intr_type = GPIO_INTR_DISABLE, }; ESP_ERROR_CHECK(gpio_config(&button_cfg)); gpio_config_t led_cfg = { .pin_bit_mask = 1ULL << PIN_STATUS_LED, .mode = GPIO_MODE_OUTPUT, }; ESP_ERROR_CHECK(gpio_config(&led_cfg)); gpio_set_level(PIN_STATUS_LED, 0); led_strip_config_t strip_cfg = { .strip_gpio_num = PIN_NEOPIXEL, .max_leds = 1, .led_model = LED_MODEL_WS2812, .color_component_format = LED_STRIP_COLOR_COMPONENT_FMT_GRB, .flags.invert_out = false, }; led_strip_rmt_config_t rmt_cfg = { .clk_src = RMT_CLK_SRC_DEFAULT, .resolution_hz = 10000000, .mem_block_symbols = 64, .flags.with_dma = false, }; ESP_ERROR_CHECK(led_strip_new_rmt_device(&strip_cfg, &rmt_cfg, &neopixel)); ESP_ERROR_CHECK(led_strip_clear(neopixel)); ESP_ERROR_CHECK(led_strip_refresh(neopixel)); button_last_level = gpio_get_level(PIN_BUTTON_BOOT); button_debounce_at = xTaskGetTickCount(); ui_last_activity = button_debounce_at; } static void message_finish(void) { if (message_active && message_len) { message[message_len] = '\0'; history_add(current_ric, (unsigned)current_baud, current_function, message); oled_draw_history(); } message_active = false; current_ric = 0; current_function = 0; message_len = 0; memset(message, 0, sizeof(message)); alpha_acc = 0; alpha_nbits = 0; numeric_nibble_count = 0; live_page = false; text_page = 0; ui_render(); } static void message_abort(void) { message_active = false; current_ric = 0; current_function = 0; message_len = 0; memset(message, 0, sizeof(message)); alpha_acc = 0; alpha_nbits = 0; numeric_nibble_count = 0; live_page = false; } static void append_message_char(char c) { if (message_len < MESSAGE_SIZE - 1) message[message_len++] = c; } static void decode_numeric(uint32_t payload) { for (int shift = 16; shift >= 0; shift -= 4) { unsigned nibble = (payload >> shift) & 0xF; char c = numeric_chars[nibble]; /* POCSAG numeric filler/padding. */ if (nibble == 0xF) continue; append_message_char(c); numeric_nibble_count++; } } static void decode_alpha(uint32_t payload) { /* Codewords arrive MSB first, but each 7-bit ASCII character is transmitted least-significant bit first. Keep the character accumulator across codeword boundaries. */ for (int bit = 19; bit >= 0; bit--) { unsigned incoming = (payload >> bit) & 1U; alpha_acc |= incoming << alpha_nbits; alpha_nbits++; if (alpha_nbits == 7U) { unsigned ch = alpha_acc & 0x7FU; alpha_acc = 0; alpha_nbits = 0; if (ch == 0x0DU || ch == 0x0AU) append_message_char(' '); else if (ch >= 0x20U && ch <= 0x7EU) append_message_char((char)ch); } } } static void decode_codeword(uint32_t raw, unsigned slot) { if (raw == POCSAG_IDLE) { message_finish(); return; } unsigned fixed = 0; if (!bch_correct(&raw, &fixed)) { ESP_LOGW(TAG, "BCH failure, raw=%08lX", (unsigned long)raw); message_abort(); batch_locked = false; sync_bits = 0; sync_shift = 0; codeword_bits = 0; codeword_shift = 0; return; } if (fixed) ESP_LOGD(TAG, "Corrected %u bit(s)", fixed); if (raw == POCSAG_IDLE) { message_finish(); return; } unsigned is_message = (raw >> 31) & 1U; uint32_t payload = (raw >> 11) & 0xFFFFFU; if (!is_message) { message_finish(); unsigned address = payload >> 2; current_function = payload & 3U; unsigned frame = (slot / 2U) & 7U; current_ric = (address << 3) | frame; /* * POCSAG function bits: * 00 / 01: numeric format * 10 / 11: alphanumeric format * * A tone-only page is represented by an address with * no subsequent message codewords, not by function 00. */ message_active = true; message_len = 0; alpha_acc = 0; alpha_nbits = 0; numeric_nibble_count = 0; live_page = monitor_mode || current_ric == MY_RIC; text_page = 0; if (current_ric == MY_RIC) ui_start_own_page_alert(); if (live_page) { ui_screen = UI_LIVE; ui_note_activity(); } if (monitor_mode || current_ric == MY_RIC) { ESP_LOGI(TAG, "Address RIC=%lu function=%u", (unsigned long)current_ric, current_function); } if (live_page) ui_render(); } else if (message_active) { if (current_function <= 1) decode_numeric(payload); else decode_alpha(payload); if (live_page && ui_screen == UI_LIVE) { ui_note_activity(); ui_render(); } } } static void process_bit(uint8_t bit) { if (invert_bits) bit ^= 1U; if (!batch_locked) { sync_shift = (sync_shift << 1) | bit; if (sync_bits < 32) sync_bits++; if (sync_bits == 32) { if (sync_shift == POCSAG_SYNC) { batch_locked = true; batch_word_index = 0; codeword_bits = 0; codeword_shift = 0; ESP_LOGI(TAG, "POCSAG sync"); } else if (sync_shift == ~POCSAG_SYNC) { invert_bits = true; batch_locked = true; batch_word_index = 0; codeword_bits = 0; codeword_shift = 0; ESP_LOGI(TAG, "POCSAG sync (inverted)"); } } return; } codeword_shift = (codeword_shift << 1) | bit; codeword_bits++; if (codeword_bits == 32) { decode_codeword(codeword_shift, batch_word_index); batch_word_index++; codeword_bits = 0; codeword_shift = 0; if (batch_word_index == 16) { batch_locked = false; sync_bits = 0; sync_shift = 0; } } } static void set_detected_baud(baud_t rate) { if (current_baud != RATE_UNKNOWN) return; current_baud = rate; bit_period_q16 = (uint32_t)(((uint64_t)SAMPLE_RATE_HZ << 16) / (unsigned)rate); phase_q16 = bit_period_q16 / 2U; sync_shift = 0; sync_bits = 0; batch_locked = false; display_baud = (unsigned)rate; ESP_LOGI(TAG, "Detected baud: %u", (unsigned)rate); oled_draw_history(); } static void process_sample(uint8_t sample) { if (current_baud == RATE_UNKNOWN) { edge_samples++; if (sample != last_sample) { observed_edges++; if (edge_samples <= 200) { edge_period_sum += edge_samples; edge_period_count++; if (edge_samples < edge_period_min) edge_period_min = edge_samples; if (edge_samples > edge_period_max) edge_period_max = edge_samples; } if (edge_samples >= 69 && edge_samples <= 81) { hit512++; hit1200 = hit2400 = 0; } else if (edge_samples >= 28 && edge_samples <= 36) { hit1200++; hit512 = hit2400 = 0; } else if (edge_samples >= 13 && edge_samples <= 19) { hit2400++; hit512 = hit1200 = 0; } else { hit512 = hit1200 = hit2400 = 0; } edge_samples = 0; last_sample = sample; if (hit512 >= 12) set_detected_baud(RATE_512); else if (hit1200 >= 12) set_detected_baud(RATE_1200); else if (hit2400 >= 12) set_detected_baud(RATE_2400); } return; } phase_q16 += 65536U; if (phase_q16 >= bit_period_q16) { phase_q16 -= bit_period_q16; process_bit(sample); } } /* ------------------------------ GPTimer ------------------------------- */ static uint8_t sample_buf[SAMPLE_BUF_SIZE]; static volatile uint32_t sample_wr; static volatile uint32_t sample_rd; static volatile uint32_t sample_drops; static bool IRAM_ATTR sample_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *ctx) { (void)timer; (void)edata; (void)ctx; uint32_t wr = sample_wr; uint32_t rd = sample_rd; if ((uint32_t)(wr - rd) < SAMPLE_BUF_SIZE) { sample_buf[wr & SAMPLE_BUF_MASK] = gpio_get_level(PIN_CC1101_GDO0) ? 1 : 0; sample_wr = wr + 1; } else { sample_drops++; } return false; } static void start_sampler(void) { gptimer_config_t cfg = { .clk_src = GPTIMER_CLK_SRC_DEFAULT, .direction = GPTIMER_COUNT_UP, .resolution_hz = SAMPLE_TIMER_HZ, }; ESP_ERROR_CHECK(gptimer_new_timer(&cfg, &sample_timer)); gptimer_event_callbacks_t cbs = { .on_alarm = sample_alarm_cb, }; ESP_ERROR_CHECK(gptimer_register_event_callbacks(sample_timer, &cbs, NULL)); gptimer_alarm_config_t alarm = { .alarm_count = SAMPLE_PERIOD_TICKS, .reload_count = 0, .flags.auto_reload_on_alarm = true, }; ESP_ERROR_CHECK(gptimer_set_alarm_action(sample_timer, &alarm)); ESP_ERROR_CHECK(gptimer_enable(sample_timer)); ESP_ERROR_CHECK(gptimer_start(sample_timer)); ESP_LOGI(TAG, "Sample rate nominally %lu Hz", (unsigned long)SAMPLE_RATE_HZ); } /* -------------------------------- main -------------------------------- */ void app_main(void) { ESP_LOGI(TAG, "ESP32-H2 POCSAG pager receiver"); gpio_config_t gdo_cfg = { .pin_bit_mask = 1ULL << PIN_CC1101_GDO0, .mode = GPIO_MODE_INPUT, .pull_up_en = GPIO_PULLUP_DISABLE, .pull_down_en = GPIO_PULLDOWN_DISABLE, .intr_type = GPIO_INTR_DISABLE, }; ESP_ERROR_CHECK(gpio_config(&gdo_cfg)); gpio_config_t oled_cs_cfg = { .pin_bit_mask = 1ULL << PIN_OLED_CS, .mode = GPIO_MODE_OUTPUT, }; ESP_ERROR_CHECK(gpio_config(&oled_cs_cfg)); gpio_set_level(PIN_OLED_CS, 1); setup_spi(); oled_init(); ui_hardware_init(); ui_screen = UI_LIVE; ui_render(); bch_init(); cc1101_init(); ui_render(); start_sampler(); TickType_t last_status = xTaskGetTickCount(); while (1) { while (sample_rd != sample_wr) { uint32_t rd = sample_rd; uint8_t s = sample_buf[rd & SAMPLE_BUF_MASK]; sample_rd = rd + 1; process_sample(s); } ui_poll_button(); ui_update_alert(); ui_idle_power_down(); if (xTaskGetTickCount() - last_status >= pdMS_TO_TICKS(5000)) { last_status = xTaskGetTickCount(); unsigned edge_period_avg = edge_period_count ? edge_period_sum / edge_period_count : 0; ESP_LOGI(TAG, "baud=%u samples=%lu dropped=%lu history=%u " "GDO_edges=%lu period_samples=%lu..%lu avg=%u", (unsigned)current_baud, (unsigned long)sample_wr, (unsigned long)sample_drops, history_count, (unsigned long)observed_edges, (unsigned long)(edge_period_count ? edge_period_min : 0), (unsigned long)edge_period_max, edge_period_avg); observed_edges = 0; edge_period_sum = 0; edge_period_min = UINT32_MAX; edge_period_max = 0; edge_period_count = 0; } vTaskDelay(1); } }