├── assets ├── WebInterface.PNG └── DCC-Isolator-6N137.png ├── hardware ├── optoiso-board-only │ ├── board_back.png │ ├── schematic.png │ ├── board_front.png │ ├── board_layout.png │ ├── optoiso-board-only.kicad_prl │ └── optoiso-board-only.kicad_pro └── oled-wifi-kit-32 │ ├── oled_inspector.kicad_prl │ └── oled_inspector.kicad_pro ├── .gitignore ├── .github ├── workflows │ ├── main.yml │ └── new-items.yml └── ISSUE_TEMPLATE │ ├── config.yml │ ├── 5-to_do.yml │ ├── 4-documentation_update.yml │ ├── 3-feature_request.yml │ ├── 1-support_request.yml │ └── 2-bug_report.yml ├── EventTimer.h ├── platformio.ini ├── HttpManager.h ├── StringBuilder.h ├── OledDisplay.h ├── EventTimer_default.h ├── DCCStatistics.h ├── Config.h ├── EventTimer_ESP32.h ├── OledDisplay.cpp ├── EventTimer_AtMega.h ├── DCCStatistics.cpp ├── README.md ├── HttpManager.cpp ├── LICENSE └── DCCInspector-EX.ino /assets/WebInterface.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DCC-EX/DCCInspector-EX/HEAD/assets/WebInterface.PNG -------------------------------------------------------------------------------- /assets/DCC-Isolator-6N137.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DCC-EX/DCCInspector-EX/HEAD/assets/DCC-Isolator-6N137.png -------------------------------------------------------------------------------- /hardware/optoiso-board-only/board_back.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DCC-EX/DCCInspector-EX/HEAD/hardware/optoiso-board-only/board_back.png -------------------------------------------------------------------------------- /hardware/optoiso-board-only/schematic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DCC-EX/DCCInspector-EX/HEAD/hardware/optoiso-board-only/schematic.png -------------------------------------------------------------------------------- /hardware/optoiso-board-only/board_front.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DCC-EX/DCCInspector-EX/HEAD/hardware/optoiso-board-only/board_front.png -------------------------------------------------------------------------------- /hardware/optoiso-board-only/board_layout.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DCC-EX/DCCInspector-EX/HEAD/hardware/optoiso-board-only/board_layout.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore PlatformIO and Visual Studio code files 2 | .pioenvs 3 | .piolibdeps 4 | .clang_complete 5 | .gcc-flags.json 6 | .pio 7 | .vscode 8 | .vscode/* 9 | **/hardware/*backups/ 10 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v2 12 | - name: Install Python Wheel 13 | run: pip install wheel 14 | - name: Install PlatformIO Core 15 | run: pip install -U platformio 16 | - name: Compile Command Station (AVR) 17 | run: python -m platformio run -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | # Configuration file for the template chooser 2 | # 3 | # This file needs to exist in the https://github.com/DCC-EX/.github repository in the ".github/ISSUE_TEMPLATE/" folder. 4 | 5 | blank_issues_enabled: false 6 | contact_links: 7 | - name: DCC-EX Discord server 8 | url: https://discord.gg/y2sB4Fp 9 | about: For the best support experience, join our Discord server 10 | - name: DCC-EX Contact and Support page 11 | url: https://dcc-ex.com/support/index.html 12 | about: For other support options, refer to our Contact & Support page -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/5-to_do.yml: -------------------------------------------------------------------------------- 1 | # General To Do item GitHub issue form 2 | # 3 | # This file needs to reside in the ".github/ISSUE_TEMPLATE/" folder. 4 | 5 | name: To Do 6 | description: Create a general To Do item 7 | title: "[To Do]: " 8 | labels: 9 | - To Do 10 | body: 11 | - type: markdown 12 | attributes: 13 | value: | 14 | Use this template to create an issue for a general task that needs to be done. 15 | 16 | This is handy for capturing ad-hoc items that don't necessarily require code to be written or updated. 17 | 18 | - type: textarea 19 | id: description 20 | attributes: 21 | label: Task description 22 | description: Provide the details of what needs to be done. 23 | validations: 24 | required: true -------------------------------------------------------------------------------- /EventTimer.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021 Neil McKechnie 2 | * 3 | * This Library is free software: you can redistribute it and/or modify 4 | * it under the terms of the GNU General Public License as published by 5 | * the Free Software Foundation, either version 3 of the License, or 6 | * (at your option) any later version. 7 | * 8 | * This Library is distributed in the hope that it will be useful, 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | * GNU General Public License for more details. 12 | * 13 | * You should have received a copy of the GNU General Public License 14 | * along with this software. If not, see 15 | * . 16 | */ 17 | 18 | /* 19 | * EventTimer.h 20 | * 21 | * Include file that selects one of the specific EventTimer 22 | * class definitions, depending on architecture. 23 | * 24 | */ 25 | 26 | #if defined(ARDUINO_UNO_NANO) || defined(ARDUINO_AVR_MEGA2560) 27 | #include "EventTimer_AtMega.h" 28 | #elif defined(ESP32) 29 | #include "EventTimer_ESP32.h" 30 | #else 31 | #include "EventTimer_default.h" 32 | #endif 33 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/4-documentation_update.yml: -------------------------------------------------------------------------------- 1 | # Documentation update GitHub issue form 2 | # 3 | # This file needs to reside in the ".github/ISSUE_TEMPLATE/" folder. 4 | 5 | name: Documentation Update 6 | description: Submit a request for documentation updates, or to report broken links or inaccuracies 7 | title: "[Documentation Update]: " 8 | labels: 9 | - Needs Documentation 10 | body: 11 | - type: markdown 12 | attributes: 13 | value: | 14 | Use this template to submit a request for updates to our documentation. 15 | 16 | This can be used for general documentation requests if information is missing or lacking, or to correct issues with our existing documentation such as broken links, or inaccurate information. 17 | 18 | - type: textarea 19 | id: details 20 | attributes: 21 | label: Documentation details 22 | description: Provide the details of what needs to be documented or corrected. 23 | validations: 24 | required: true 25 | 26 | - type: input 27 | id: page 28 | attributes: 29 | label: Page with issues 30 | description: If reporting broken links or inaccuracies, please provide the link to the page here. 31 | placeholder: https://dcc-ex.com/index.html -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/3-feature_request.yml: -------------------------------------------------------------------------------- 1 | # Feature Request GitHub issue form 2 | # 3 | # This file needs to reside in the ".github/ISSUE_TEMPLATE/" folder. 4 | 5 | name: Feature Request 6 | description: Suggest a new feature 7 | title: "[Feature Request]: " 8 | labels: 9 | - Enhancement 10 | body: 11 | - type: markdown 12 | attributes: 13 | value: | 14 | Use this template to suggest a new feature for EX-DCCInspector. 15 | 16 | - type: textarea 17 | id: description 18 | attributes: 19 | label: Problem/idea statement 20 | description: Please provide the problem you're trying to solve, or share the idea you have. 21 | placeholder: A clear and concise description of the problem you're trying to solve, or the idea you have. For example, I'm always frustrated when... 22 | validations: 23 | required: true 24 | 25 | - type: textarea 26 | id: alternatives 27 | attributes: 28 | label: Alternatives or workarounds 29 | description: Please provide any alternatives or workarounds you currently use. 30 | validations: 31 | required: true 32 | 33 | - type: textarea 34 | id: context 35 | attributes: 36 | label: Additional context 37 | description: Add any other context, screenshots, or files related to the feature request here. -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/1-support_request.yml: -------------------------------------------------------------------------------- 1 | # Support Request GitHub issue form 2 | # 3 | # This file needs to reside in the ".github/ISSUE_TEMPLATE/" folder. 4 | 5 | name: Support Request 6 | description: Request support or assistance 7 | title: "[Support Request]: " 8 | labels: 9 | - Support Request 10 | body: 11 | - type: markdown 12 | attributes: 13 | value: | 14 | Use this template to request support or assistance with EX-DCCInspector. 15 | 16 | For a better support experience, feel free to join our [Discord server](https://discord.gg/y2sB4Fp), as you will typically get a faster response, and will be able to communicate directly with the DCC-EX team. 17 | 18 | - type: input 19 | id: version 20 | attributes: 21 | label: Version 22 | description: Please provide the version of the software in use. 23 | validations: 24 | required: true 25 | 26 | - type: textarea 27 | id: description 28 | attributes: 29 | label: Issue description 30 | description: Please describe the issue being encountered as accurately and detailed as possible. 31 | validations: 32 | required: true 33 | 34 | - type: textarea 35 | id: hardware 36 | attributes: 37 | label: Hardware 38 | description: If appropriate, please provide details of the hardware in use. 39 | placeholder: | 40 | Arduino Nano -------------------------------------------------------------------------------- /hardware/oled-wifi-kit-32/oled_inspector.kicad_prl: -------------------------------------------------------------------------------- 1 | { 2 | "board": { 3 | "active_layer": 0, 4 | "active_layer_preset": "All Layers", 5 | "auto_track_width": true, 6 | "hidden_netclasses": [], 7 | "hidden_nets": [], 8 | "high_contrast_mode": 0, 9 | "net_color_mode": 1, 10 | "opacity": { 11 | "images": 0.6, 12 | "pads": 1.0, 13 | "tracks": 1.0, 14 | "vias": 1.0, 15 | "zones": 0.6 16 | }, 17 | "ratsnest_display_mode": 0, 18 | "selection_filter": { 19 | "dimensions": true, 20 | "footprints": true, 21 | "graphics": true, 22 | "keepouts": true, 23 | "lockedItems": true, 24 | "otherItems": true, 25 | "pads": true, 26 | "text": true, 27 | "tracks": true, 28 | "vias": true, 29 | "zones": true 30 | }, 31 | "visible_items": [ 32 | 0, 33 | 1, 34 | 2, 35 | 3, 36 | 4, 37 | 5, 38 | 8, 39 | 9, 40 | 10, 41 | 11, 42 | 12, 43 | 13, 44 | 14, 45 | 15, 46 | 16, 47 | 17, 48 | 18, 49 | 19, 50 | 20, 51 | 21, 52 | 22, 53 | 23, 54 | 24, 55 | 25, 56 | 26, 57 | 27, 58 | 28, 59 | 29, 60 | 30, 61 | 32, 62 | 33, 63 | 34, 64 | 35, 65 | 36 66 | ], 67 | "visible_layers": "fffffff_ffffffff", 68 | "zone_display_mode": 0 69 | }, 70 | "meta": { 71 | "filename": "optoiso.kicad_prl", 72 | "version": 3 73 | }, 74 | "project": { 75 | "files": [] 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /hardware/optoiso-board-only/optoiso-board-only.kicad_prl: -------------------------------------------------------------------------------- 1 | { 2 | "board": { 3 | "active_layer": 36, 4 | "active_layer_preset": "", 5 | "auto_track_width": true, 6 | "hidden_netclasses": [], 7 | "hidden_nets": [], 8 | "high_contrast_mode": 0, 9 | "net_color_mode": 1, 10 | "opacity": { 11 | "images": 0.6200000047683716, 12 | "pads": 0.7599999904632568, 13 | "tracks": 1.0, 14 | "vias": 1.0, 15 | "zones": 0.6 16 | }, 17 | "ratsnest_display_mode": 0, 18 | "selection_filter": { 19 | "dimensions": true, 20 | "footprints": true, 21 | "graphics": true, 22 | "keepouts": true, 23 | "lockedItems": true, 24 | "otherItems": true, 25 | "pads": true, 26 | "text": true, 27 | "tracks": true, 28 | "vias": true, 29 | "zones": true 30 | }, 31 | "visible_items": [ 32 | 0, 33 | 1, 34 | 2, 35 | 3, 36 | 4, 37 | 5, 38 | 8, 39 | 9, 40 | 10, 41 | 11, 42 | 12, 43 | 13, 44 | 14, 45 | 15, 46 | 16, 47 | 18, 48 | 19, 49 | 20, 50 | 21, 51 | 22, 52 | 23, 53 | 24, 54 | 25, 55 | 26, 56 | 27, 57 | 28, 58 | 29, 59 | 30, 60 | 32, 61 | 33, 62 | 34, 63 | 35, 64 | 36 65 | ], 66 | "visible_layers": "fffffff_ffffffff", 67 | "zone_display_mode": 0 68 | }, 69 | "meta": { 70 | "filename": "optoiso-board-only.kicad_prl", 71 | "version": 3 72 | }, 73 | "project": { 74 | "files": [] 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /platformio.ini: -------------------------------------------------------------------------------- 1 | ; PlatformIO Project Configuration File 2 | ; 3 | ; Build options: build flags, source filter 4 | ; Upload options: custom upload port, speed and extra flags 5 | ; Library options: dependencies, extra library storages 6 | ; Advanced options: extra scripting 7 | ; 8 | ; Please visit documentation for the other options and examples 9 | ; https://docs.platformio.org/page/projectconf.html 10 | 11 | [platformio] 12 | default_envs = 13 | esp32_heltec 14 | esp32_generic 15 | esp8266 16 | nano 17 | nanoNew 18 | uno 19 | mega 20 | src_dir = . 21 | 22 | [env] 23 | monitor_speed = 115200 24 | lib_deps = 25 | DIO2 26 | adafruit/Adafruit BusIO 27 | adafruit/Adafruit SSD1306 28 | build_flags = -Wall -Wextra 29 | 30 | [env:esp32_heltec] 31 | platform = espressif32 32 | board = heltec_wifi_kit_32_v2 33 | framework = arduino 34 | lib_deps = 35 | ${env.lib_deps} 36 | 37 | [env:esp32_generic] 38 | platform = espressif32 39 | board = nodemcu-32s 40 | framework = arduino 41 | lib_deps = 42 | ${env.lib_deps} 43 | 44 | [env:esp8266] 45 | platform = espressif8266 46 | board = heltec_wifi_kit_8 47 | framework = arduino 48 | lib_deps = 49 | ${env.lib_deps} 50 | 51 | [env:nano] 52 | platform = atmelavr 53 | framework = arduino 54 | board = nanoatmega328 55 | lib_deps = 56 | ${env.lib_deps} 57 | 58 | [env:nanoNew] 59 | # Arduino Nano with new (512-byte) bootloader 60 | platform = atmelavr 61 | framework = arduino 62 | board = nanoatmega328new 63 | board_upload.maximum_size = 32256 64 | lib_deps = 65 | ${env.lib_deps} 66 | 67 | [env:uno] 68 | platform = atmelavr 69 | framework = arduino 70 | board = uno 71 | lib_deps = 72 | ${env.lib_deps} 73 | 74 | [env:mega] 75 | platform = atmelavr 76 | framework = arduino 77 | board = megaatmega2560 78 | lib_deps = 79 | ${env.lib_deps} 80 | 81 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/2-bug_report.yml: -------------------------------------------------------------------------------- 1 | # Bug report GitHub issue form 2 | # 3 | # This file needs to reside in the ".github/ISSUE_TEMPLATE/" folder. 4 | 5 | name: Bug Report 6 | description: Submit a bug report 7 | labels: 8 | - Bug 9 | title: "Bug Report: " 10 | body: 11 | - type: markdown 12 | attributes: 13 | value: | 14 | Thanks for taking the time to submit a bug report to the DCC-EX team! 15 | 16 | In order to help us to validate the bug and ascertain what's causing it, please provide as much information as possible in this form. 17 | 18 | - type: input 19 | id: version 20 | attributes: 21 | label: EX-DCCInspector Version 22 | description: Please provide the version of EX-DCCInspector in use. 23 | validations: 24 | required: true 25 | 26 | - type: textarea 27 | id: description 28 | attributes: 29 | label: Bug description 30 | description: Please provide a clear and concise description of what the symptoms of the bug are. 31 | validations: 32 | required: true 33 | 34 | - type: textarea 35 | id: reproduction 36 | attributes: 37 | label: Steps to reproduce the bug 38 | description: Please provide the steps to reproduce the behaviour. 39 | validations: 40 | required: true 41 | 42 | - type: textarea 43 | id: expectation 44 | attributes: 45 | label: Expected behaviour 46 | description: Please provide a clear and concise description of what you expected to happen. 47 | validations: 48 | required: true 49 | 50 | - type: textarea 51 | id: screenshots 52 | attributes: 53 | label: Screenshots 54 | description: If applicable, upload any screenshots here. 55 | 56 | - type: textarea 57 | id: hardware 58 | attributes: 59 | label: Hardware in use 60 | description: Please provide details of hardware in use. 61 | placeholder: | 62 | Arduino Nano 63 | validations: 64 | required: true 65 | 66 | - type: textarea 67 | id: extra-context 68 | attributes: 69 | label: Additional context 70 | description: Please provide any other relevant information that could help us resolve this issue, for example a customised config.h file. -------------------------------------------------------------------------------- /HttpManager.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021 Neil McKechnie 2 | * 3 | * This Library is free software: you can redistribute it and/or modify 4 | * it under the terms of the GNU General Public License as published by 5 | * the Free Software Foundation, either version 3 of the License, or 6 | * (at your option) any later version. 7 | * 8 | * This Library is distributed in the hope that it will be useful, 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | * GNU General Public License for more details. 12 | * 13 | * You should have received a copy of the GNU General Public License 14 | * along with this software. If not, see 15 | * . 16 | */ 17 | 18 | /* 19 | * HttpManager class definition - include file. 20 | * 21 | * Encapsulates the WiFI and Web Server functionality of the DCC inspector program. 22 | * 23 | * HTTPMANAGER ISN'T SUPPORTED ON NANO, UNO or MEGA because of lack of memory. 24 | */ 25 | 26 | #ifndef httpmanager_h 27 | #define httpmanager_h 28 | 29 | #include "Config.h" 30 | 31 | #if defined(ESP8266) 32 | #include 33 | #include 34 | #define WebServer ESP8266WebServer 35 | #include 36 | #elif defined(ESP32) 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #endif 43 | 44 | #include "StringBuilder.h" 45 | #include "DCCStatistics.h" 46 | 47 | class HttpManagerClass { 48 | public: 49 | // Function to initialise the object, connect to WiFi and start HTTP server. 50 | bool begin(const char *ssid, const char *password, const char *dnsName); 51 | // Function to provide a buffer of dynamic data (decoded DCC packets). 52 | void setBuffer(char *buffer); 53 | // Function to write statistics, formatted as HTML, to a print stream. 54 | void writeHtmlStatistics(Statistics &stats); 55 | // Function to be called in loop() function to keep things going. 56 | void process(); 57 | // Function to get null-terminated string containing html data. 58 | void getIP(); 59 | // Function to get IP address if connected 60 | char *getHtmlString() { 61 | return sbHtml.getString(); 62 | } 63 | 64 | private: 65 | static void handleRoot(); 66 | static void processArguments(); 67 | static void handleNotFound(); 68 | static void handleData(); 69 | #if defined(ESP32) 70 | static void WiFiEvent (arduino_event_id_t event); 71 | #endif 72 | // Flag whether connected or not. 73 | bool connected = false; 74 | // Buffer for generating HTML 75 | char buffer[4000] = ""; 76 | StringBuilder sbHtml = StringBuilder(buffer, sizeof(buffer)); 77 | static char *bufferPointer; 78 | static WebServer server; 79 | } /* class HttpManagerClass */; 80 | 81 | // Singleton class instance. 82 | extern HttpManagerClass HttpManager; 83 | 84 | #endif 85 | -------------------------------------------------------------------------------- /StringBuilder.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021 Neil McKechnie 2 | * 3 | * This Library is free software: you can redistribute it and/or modify 4 | * it under the terms of the GNU General Public License as published by 5 | * the Free Software Foundation, either version 3 of the License, or 6 | * (at your option) any later version. 7 | * 8 | * This Library is distributed in the hope that it will be useful, 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | * GNU General Public License for more details. 12 | * 13 | * You should have received a copy of the GNU General Public License 14 | * along with this software. If not, see 15 | * . 16 | */ 17 | 18 | /* 19 | * StringBuilder class 20 | * 21 | * Inherits from Print class so allows all Print class methods to write to 22 | * a char[] buffer. 23 | * 24 | */ 25 | #ifndef stringbuilder_h 26 | #define stringbuilder_h 27 | 28 | #include 29 | #include 30 | 31 | class StringBuilder : public Print { 32 | public: 33 | // Constructor 34 | StringBuilder(char *buf, size_t len) : Print() { 35 | buffer = buf; 36 | buffMax = len-1; // Allow space for null terminating character. 37 | reset(); 38 | } 39 | 40 | // Reset (empty) buffer. 41 | void reset() { 42 | buffIndex = 0; 43 | overflow = false; 44 | end(); 45 | } 46 | 47 | // Pad with spaces to the nominated position. 48 | void setPos(unsigned int pos) { 49 | int n = pos - buffIndex; // Number of spaces to write 50 | for (int i=0; i. 16 | */ 17 | 18 | /* 19 | * OledDisplay class 20 | * 21 | * Handles the Oled Display output from the DCC diagnostic program. 22 | * 23 | * The output to be displayed is passed to the program as parameter 24 | * to the function update(). The string is sent to the screen (at least 25 | * as much as fits on the screen). The buffer reference is held so that, 26 | * if the user presses the button connected to BUTTONPIN, the screen is updated 27 | * starting at a later line in the buffer. In this way, the user can 28 | * scroll through the text. 29 | * If the current scroll line number is greater than the number of lines 30 | * of text when a refresh is due, then the text is displayed from the 31 | * beginning once more. 32 | * 33 | * OLED ISN'T SUPPORTED ON ARDUINO NANO AND UNO because of the lack of memory. 34 | */ 35 | 36 | #ifndef oleddisplay_h 37 | #define oleddisplay_h 38 | 39 | #include 40 | 41 | #include "Config.h" 42 | 43 | // Only compile if USE_OLED is defined. 44 | // If not, then the entire contents are ignored by the compiler. 45 | #ifdef USE_OLED 46 | 47 | #include "DCCStatistics.h" 48 | #include "StringBuilder.h" 49 | 50 | class OledDisplayClass { 51 | public: 52 | // Function called to initialise the object instance. 53 | // Connects to the OLED display and puts it into a 54 | // suitable mode. 55 | bool begin(int sdaPin, int sclPin); 56 | inline void reset() { sbOled.reset(); } 57 | 58 | // Function called to force an update of the screen, 59 | // starting with the line referenced by 'firstLine'. 60 | void refresh(); 61 | 62 | // Check the button pin input to see if the button has 63 | // been pressed. If so, increment 'firstLine' and refresh, 64 | // so that the displayed text scrolls upwards. 65 | // This function should be called regularly from the loop() function. 66 | void checkButton(); 67 | 68 | // Display specified text on the screen. 69 | void append(const char *string); 70 | 71 | // Write a summary version of the statistics data onto the screen. 72 | void writeShortStatistics(Statistics &lastStats); 73 | 74 | private: 75 | // OLED Display 76 | Adafruit_SSD1306 display = Adafruit_SSD1306(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); 77 | // Line number (starting with 0) of first line to be displayed. 78 | int firstLine = 0; 79 | 80 | const char *selectedLine(); 81 | 82 | char sbBuffer[1000]; 83 | StringBuilder sbOled = StringBuilder(sbBuffer, sizeof(sbBuffer)); 84 | 85 | } /* class OledDisplayClass */; 86 | 87 | extern OledDisplayClass OledDisplay; 88 | 89 | #endif 90 | #endif 91 | -------------------------------------------------------------------------------- /EventTimer_default.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021 Neil McKechnie 2 | * 3 | * This Library is free software: you can redistribute it and/or modify 4 | * it under the terms of the GNU General Public License as published by 5 | * the Free Software Foundation, either version 3 of the License, or 6 | * (at your option) any later version. 7 | * 8 | * This Library is distributed in the hope that it will be useful, 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | * GNU General Public License for more details. 12 | * 13 | * You should have received a copy of the GNU General Public License 14 | * along with this software. If not, see 15 | * . 16 | */ 17 | 18 | /* 19 | * EventTimer_default.h 20 | * 21 | * Timer functions for measuring elapsed time between events. In this version, 22 | * the functions use the micros() function available on all Arduino controllers 23 | * as well as ESP8266, ESP32 etc. 24 | * 25 | * This module acts as the fallback if no specific support is available e.g. 26 | * through an Input Capture Register. 27 | */ 28 | 29 | #ifndef eventtimer_default_h 30 | #define eventtimer_default_h 31 | 32 | #include 33 | 34 | #define TICKSPERMICROSEC 1 35 | 36 | // ESP platform must have IRAM_ATTR on any function called from 37 | // interrupt handlers, so that they aren't executed from flash. 38 | #if defined(ESP32) || defined(ESP8266) || defined(ESP_PLATFORM) 39 | #define INTERRUPT_SAFE IRAM_ATTR 40 | #else 41 | #define INTERRUPT_SAFE 42 | #endif 43 | 44 | // Predeclare event handler function for later... 45 | void eventHandler(); 46 | 47 | /* 48 | * User event handler is sent the time since the last valid event. 49 | * If the user event handler decides that this event isn't valid 50 | * (e.g. time since last one is too short) then it should return 51 | * false to reject the event. If the event is valid, then it 52 | * should return true to accept it. 53 | */ 54 | typedef bool EventHandler(unsigned long eventSpacing); 55 | 56 | class EventTimerClass { 57 | public: 58 | 59 | // Initialise the object instance, validating that the input pin is 60 | // correct and noting the reference to the user handler for future use. 61 | bool begin(int pin, EventHandler userHandler) { 62 | this->pin = pin; 63 | int interruptNumber = digitalPinToInterrupt(pin); 64 | if (interruptNumber < 0) { 65 | Serial.print("ERROR: Pin "); Serial.print(pin); Serial.println(" has no interrupt support"); 66 | return false; 67 | } 68 | this->callUserHandler = userHandler; 69 | attachInterrupt(interruptNumber, eventHandler, CHANGE); 70 | return true; 71 | }; 72 | 73 | // Utility function to give number of ticks since the last event. Useful 74 | // for determining how much time has elapsed within the interrupt handler since 75 | // the interrupt was triggered. 76 | inline unsigned long INTERRUPT_SAFE elapsedTicksSinceLastEvent() { 77 | return micros() - thisEventTicks; 78 | }; 79 | 80 | // Function called from the interrupt handler to calculate the gap between interrupts, 81 | // and to invoke the user program's handler. The user's handler is passed the 82 | // number of ticks elapsed since the last valid interrupt. It returns true/false to 83 | // indicate if this interrupt is deemed to be 'valid' or not. 84 | void INTERRUPT_SAFE processInterrupt(unsigned long thisEventTicks) { 85 | this->thisEventTicks = thisEventTicks; 86 | unsigned long eventSpacing = thisEventTicks - lastValidEventTicks; 87 | bool accepted = callUserHandler(eventSpacing); 88 | if (accepted) { 89 | lastValidEventTicks = thisEventTicks; 90 | } 91 | }; 92 | 93 | // Utility function to return the number of timer ticks per microsecond. 94 | // With millis() as a counter, this is always 1. 95 | inline unsigned int ticksPerMicrosec() { 96 | return TICKSPERMICROSEC; 97 | }; 98 | 99 | // Utility function to inform whether input capture is in use or not. For this 100 | // version, it always returns false. 101 | inline bool inputCaptureMode() { return false; }; 102 | 103 | private: 104 | EventHandler *callUserHandler = 0; 105 | unsigned long lastValidEventTicks = 0; 106 | unsigned long thisEventTicks = 0; 107 | int pin = -1; 108 | } /* class EventTimerClass */; 109 | 110 | // Declare singleton class instance 111 | EventTimerClass EventTimer; 112 | 113 | // Interrupt handler for digital input change event. 114 | void INTERRUPT_SAFE eventHandler() { 115 | EventTimer.processInterrupt(micros()); 116 | } 117 | 118 | #endif 119 | -------------------------------------------------------------------------------- /DCCStatistics.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021 Neil McKechnie 2 | * 3 | * This Library is free software: you can redistribute it and/or modify 4 | * it under the terms of the GNU General Public License as published by 5 | * the Free Software Foundation, either version 3 of the License, or 6 | * (at your option) any later version. 7 | * 8 | * This Library is distributed in the hope that it will be useful, 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | * GNU General Public License for more details. 12 | * 13 | * You should have received a copy of the GNU General Public License 14 | * along with this software. If not, see 15 | * . 16 | */ 17 | 18 | /* 19 | * Class definition to encapsulate the statistics recorded by the 20 | * program. It has functions which are called to update the statistics 21 | * of each type of event (new interrupt, packet received, packet errors 22 | * etc.). 23 | * It also has functions to format and write the statistics to an output 24 | * stream inheriting from class Print. 25 | */ 26 | 27 | #ifndef dccstats_h 28 | #define dccstats_h 29 | 30 | #include 31 | #include "Config.h" 32 | 33 | #if defined(ESP32) || defined(ESP8266) || defined(ESP_PLATFORM) 34 | #define INTERRUPT_SAFE IRAM_ATTR 35 | #else 36 | #define INTERRUPT_SAFE 37 | #endif 38 | 39 | // Range of bit lengths (us) for recording count by bit length. 40 | const int minBitLength = 45; // microseconds (58 - 20% - 1) 41 | const int maxBitLength = 141; // microseconds (116 + 20% + 1) 42 | 43 | // Statistics structure. Sizes of counts are chosen to be large enough not to overflow 44 | typedef struct { 45 | unsigned int refreshTime; 46 | unsigned long count=0, count0=0, count1=0; 47 | unsigned int packetCount=0, checksumError=0, countLongPackets=0, countLostPackets=0; 48 | unsigned int outOfSpecRejectionCount = 0; 49 | unsigned int max1=0, min1=65535, max0=0, min0=65535; 50 | unsigned long total1=0, total0=0, totalInterruptTime=0; 51 | unsigned int maxInterruptTime=0, minInterruptTime=65535; 52 | unsigned int max1BitDelta=0, max0BitDelta=0; 53 | unsigned long glitchCount=0, spareLoopCount=0, innerSpareLoopCount=0; 54 | unsigned long rcn5msFailCount=0, idleCount=0; 55 | unsigned int countByLength[2][maxBitLength-minBitLength+1]; 56 | } Statistics; 57 | 58 | class DCCStatisticsClass { 59 | public: 60 | 61 | // Update statistics to reflect the received digital input transition. Altbit 62 | // is zero if the transition is the end of the first half-bit and one if it is the 63 | // end of the second half of a DCC bit; Bitvalue is the value 64 | // of the DCC bit; and interruptInterval is the microsecond time between 65 | // successive interrupts (the length of the half-bit in DCC terms). 66 | void INTERRUPT_SAFE recordHalfBit(byte altbit, byte bitValue, unsigned int interruptInterval, unsigned int delta); 67 | inline void INTERRUPT_SAFE recordLostPacket() { 68 | activeStats.countLostPackets++; 69 | } 70 | inline void INTERRUPT_SAFE recordLongPacket() { 71 | activeStats.countLongPackets++; 72 | } 73 | inline void INTERRUPT_SAFE recordPacket() { 74 | activeStats.packetCount++; 75 | } 76 | inline void INTERRUPT_SAFE recordChecksumError() { 77 | activeStats.checksumError++; 78 | } 79 | inline void INTERRUPT_SAFE recordOutOfSpecRejection() { 80 | activeStats.outOfSpecRejectionCount++; 81 | } 82 | inline void INTERRUPT_SAFE recordrcn5msFailure() { 83 | activeStats.rcn5msFailCount++; 84 | } 85 | inline void INTERRUPT_SAFE recordIdlePacket() { 86 | activeStats.idleCount++; 87 | } 88 | inline void INTERRUPT_SAFE recordInterruptHandlerTime(unsigned int interruptDuration) { 89 | if (interruptDuration > activeStats.maxInterruptTime) activeStats.maxInterruptTime = interruptDuration; 90 | if (interruptDuration < activeStats.minInterruptTime) activeStats.minInterruptTime = interruptDuration; 91 | activeStats.totalInterruptTime += interruptDuration; 92 | } 93 | inline void INTERRUPT_SAFE recordGlitch() { 94 | activeStats.glitchCount++; 95 | } 96 | 97 | inline void updateLoopCount() { 98 | activeStats.spareLoopCount++; 99 | } 100 | inline bool faultPresent() { 101 | if (activeStats.glitchCount > 0 || activeStats.checksumError > 0 || 102 | activeStats.countLongPackets > 0 || activeStats.countLostPackets > 0 103 | || activeStats.outOfSpecRejectionCount > 0 104 | || activeStats.rcn5msFailCount > 0) 105 | return true; 106 | else 107 | return false; 108 | } 109 | void writeFullStatistics(Statistics &stats, bool showCpuStats, bool showBitLengths); 110 | void writeShortStatistics(Print &output); 111 | 112 | // Return a copy of the current set of statistics accumulated. 113 | Statistics getAndClearStats(); 114 | 115 | inline unsigned int getRefreshTime() { return refreshTime; } 116 | inline void setRefreshTime(unsigned int value) { refreshTime = value; } 117 | 118 | private: 119 | unsigned long maxSpareLoopCountPerSec = 0; // baseline for CPU load calculation 120 | unsigned int refreshTime = 4; 121 | volatile Statistics activeStats; // Statistics currently being updated 122 | }; 123 | 124 | extern DCCStatisticsClass DCCStatistics; 125 | 126 | #endif 127 | -------------------------------------------------------------------------------- /Config.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021 Neil McKechnie 2 | * 3 | * This Library is free software: you can redistribute it and/or modify 4 | * it under the terms of the GNU General Public License as published by 5 | * the Free Software Foundation, either version 3 of the License, or 6 | * (at your option) any later version. 7 | * 8 | * This Library is distributed in the hope that it will be useful, 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | * GNU General Public License for more details. 12 | * 13 | * You should have received a copy of the GNU General Public License 14 | * along with this software. If not, see 15 | * . 16 | */ 17 | 18 | #ifndef config_h 19 | #define config_h 20 | 21 | // The following logic should work for all supported platforms, hopefully. 22 | #if defined(ARDUINO_heltec_wifi_kit_32) || defined(ARDUINO_WIFI_KIT_32) 23 | #define ARDUINO_HELTEC_WIFI_KIT_32 24 | #endif 25 | 26 | #if defined(ESP_PLATFORM) 27 | #if !defined(ESP32) 28 | #define ESP32 29 | #endif 30 | #elif defined(ESP8266) 31 | // nothing needs done here. 32 | #elif defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_NANO) 33 | #define ARDUINO_UNO_NANO 34 | #elif defined(ARDUINO_AVR_MEGA2560) 35 | #define ARDUINO_MEGA 36 | #else 37 | #error "Platform not recognised" 38 | #endif 39 | 40 | // Uncomment the "#define USE_DIO2" to use the 'Fast digital i/o library' DIO2 41 | // in place of the normal digitalRead() and digitalWrite(). 42 | // Reduces CPU load by about 17%. Only applicable to Arduino Uno/Mega/Nano. 43 | #define USE_DIO2 44 | 45 | // Uncomment the "#define USETIMER" to perform the timing using the ATmega328's 46 | // and ESP32's Input Capture mode which captures the time through hardware instead 47 | // of software. This enables a higher accuracy and consistency, and because we can capture the 48 | // Timer counter register (TCNTn) at the time of the digital change, it is immune to 49 | // timing errors caused by other interrupts. 50 | // Works on Arduino Uno (Timer1/pin D8) 51 | // Arduino Nano (Timer1/pin D8) 52 | // Arduino Mega (Timer4/pin D49) 53 | // If we don't use this, then the selected input pin must support change interrupt 54 | // (defaults to pin D2 on Uno, Nano and Mega, GPIO2 on ESP8266 and GPIO5 on ESP32. 55 | #define USETIMER 56 | 57 | // Input pin definitions. Defaults: 58 | // Nano (USETIMER): 8 59 | // Uno (USETIMER): 8 60 | // Mega (USETIMER): 49 61 | // Nano/Uno/Mega, Non-USETIMER: 2 62 | // ESP32: 5 63 | // ESP8266: 2 64 | // Other: 2 65 | #if defined(USETIMER) 66 | #if defined(ARDUINO_UNO_NANO) 67 | #define INPUTPIN 8 68 | #elif defined(ARDUINO_MEGA) 69 | #define INPUTPIN 49 70 | #elif defined(ESP32) 71 | #define INPUTPIN 5 72 | #else 73 | // Assume timer not supported, use default pin 74 | #undef USETIMER 75 | #define INPUTPIN 2 76 | #endif 77 | #else 78 | #if defined(ESP32) 79 | #define INPUTPIN 5 80 | #else 81 | #define INPUTPIN 2 82 | #endif 83 | #endif 84 | 85 | // Uncomment following lines to enable OLED output on pins SDA_OLED and SCL_OLED. 86 | // (ESP or Mega only). 87 | #define USE_OLED 88 | 89 | #if defined(ESP8266) // Heltec Kit 8 has pins 4/15 for I2C. 90 | #define SDA_OLED 4 91 | #define SCL_OLED 5 92 | #define OLED_RESET 16 93 | #define OLED_I2CADDRESS 0x3C 94 | #define SCREEN_WIDTH 128 95 | #define SCREEN_HEIGHT 32 96 | #elif defined(ARDUINO_HELTEC_WIFI_KIT_32) // Heltec Kit 32 has pins 4/15 predefined for I2C. 97 | // #define SDA_OLED 4 98 | // #define SCL_OLED 15 99 | #define OLED_RESET 16 100 | #define OLED_I2CADDRESS 0x3C 101 | #define SCREEN_WIDTH 128 102 | #define SCREEN_HEIGHT 64 103 | #else // Other boards - edit as appropriate. 104 | #define SDA_OLED 4 105 | #define SCL_OLED 5 106 | #define OLED_RESET 16 107 | #define OLED_I2CADDRESS 0x3D 108 | #define SCREEN_WIDTH 128 109 | #define SCREEN_HEIGHT 64 110 | #endif 111 | // Button for selecting new page on OLED. The button action is carried out 112 | // when the pin goes from 1 to 0 (pull-up is enabled). 113 | #define BUTTONPIN 0 114 | 115 | // LED pin definitions - uncomment and assign as required. 116 | //#define LEDPIN_ACTIVE 13 // Shows interrupts being received, ie DCC active 117 | //#define LEDPIN_LOCOSPEED 3 // Driven from loco speed packet for loco 3 118 | //#define LEDPIN_DECODING 7 // lights when a packet with valid checksum is received 119 | //#define LEDPIN_FAULT 6 // Lights when a checksum error or glitch is encountered. 120 | 121 | // Uncomment the following line to enable HTTP Server (ESP32 or ESP8266 only). 122 | #define USE_HTTPSERVER 123 | 124 | // SSID and password can be configured here. However, the server will, by preference, 125 | // connect using the same credentials as last time; if that fails it will try WPS; 126 | // only if that fails too, will it use the credentials below. 127 | #define WIFI_SSID "" 128 | #define WIFI_PASSWORD "" 129 | 130 | // Name used by mDNS to register the device. On some browsers it can be accessed 131 | // through this name with a ".local" suffix (e.g. http://DccInspector.local/). 132 | #define DNSNAME "DccInspector" 133 | 134 | // OLED isn't supported on Uno or Nano 135 | #if defined(ARDUINO_UNO_NANO) 136 | #if defined(USE_OLED) 137 | #undef USE_OLED 138 | #endif 139 | #endif 140 | 141 | // HTTP Server isn't supported on Uno or Nano or Mega 142 | #if defined(ARDUINO_UNO_NANO) | defined(ARDUINO_MEGA) 143 | #if defined(USE_HTTPSERVER) 144 | #undef USE_HTTPSERVER 145 | #endif 146 | #endif 147 | 148 | #define SERIAL_SPEED 115200 149 | 150 | #if defined(ESP32) || defined(ESP8266) || defined(ESP_PLATFORM) 151 | #define INTERRUPT_SAFE IRAM_ATTR 152 | #else 153 | #define INTERRUPT_SAFE 154 | #endif 155 | 156 | #endif 157 | -------------------------------------------------------------------------------- /EventTimer_ESP32.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021 Neil McKechnie 2 | * 3 | * This Library is free software: you can redistribute it and/or modify 4 | * it under the terms of the GNU General Public License as published by 5 | * the Free Software Foundation, either version 3 of the License, or 6 | * (at your option) any later version. 7 | * 8 | * This Library is distributed in the hope that it will be useful, 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | * GNU General Public License for more details. 12 | * 13 | * You should have received a copy of the GNU General Public License 14 | * along with this software. If not, see 15 | * . 16 | */ 17 | 18 | /* 19 | * EventTimer_ESP32.h 20 | * 21 | * Timer functions for measuring elapsed time between events. On the ESP32 platform, 22 | * the functions use the os-provided input capture support functions. 23 | */ 24 | 25 | #ifndef eventtimer_default_h 26 | #define eventtimer_default_h 27 | 28 | #include 29 | #include "driver/mcpwm.h" 30 | #include "soc/mcpwm_struct.h" 31 | #include "soc/mcpwm_reg.h" 32 | 33 | #define TICKSPERMICROSEC 80 34 | 35 | /* 36 | * User event handler is sent the time since the last valid event. 37 | * If the user event handler decides that this event isn't valid 38 | * (e.g. time since last one is too short) then it should return 39 | * false to reject the event. If the event is valid, then it 40 | * should return true to accept it. 41 | * For the ESP32 (and ESP8266) this must be declared IRAM_ATTR. 42 | */ 43 | typedef bool EventHandler(unsigned long eventInterval); 44 | 45 | static bool IRAM_ATTR captureCallbackFunction(mcpwm_unit_t mcpwm, mcpwm_capture_channel_id_t cap_channel, const cap_event_data_t *edata, void *user_data); 46 | 47 | class EventTimerClass { 48 | public: 49 | 50 | // Initialise the object instance, validating that the input pin is 51 | // correct and noting the reference to the user handler for future use. 52 | bool begin(int pin, EventHandler userHandler) { 53 | this->pin = pin; 54 | this->callUserHandler = userHandler; 55 | 56 | // In the version of the ESP32 SDK included with the Arduino platform, there doesn't seem to be a way 57 | // of capturing on both edges; only on positive edge or negative edge. Therefore, we're 58 | // setting up two separate captures, one on each edge. 59 | // When the input pin changes state, the current value of the timer is captured and then the interrupt 60 | // is scheduled. The interrupt response code is responsible for retrieving the captured value. 61 | mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM_CAP_0, INPUTPIN); 62 | mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM_CAP_1, INPUTPIN); 63 | mcpwm_capture_config_t cap_conf; 64 | cap_conf.capture_cb = captureCallbackFunction; 65 | cap_conf.user_data = NULL; 66 | cap_conf.cap_prescale = 1; //no prescale, i.e. 800,000,000 counts equals one second. 67 | cap_conf.cap_edge = MCPWM_POS_EDGE; 68 | mcpwm_capture_enable_channel(MCPWM_UNIT_0, MCPWM_SELECT_CAP0, &cap_conf); 69 | //capture signal on positive edge 70 | cap_conf.cap_edge = MCPWM_NEG_EDGE; 71 | mcpwm_capture_enable_channel(MCPWM_UNIT_0, MCPWM_SELECT_CAP1, &cap_conf); 72 | //capture signal on negative edge 73 | MCPWM0.int_ena.cap0_int_ena = 1; // Enable interrupt on CAP0 signal 74 | MCPWM0.int_ena.cap1_int_ena = 1; // Enable interrupt on CAP1 signal 75 | //mcpwm_isr_register(MCPWM_UNIT_0, isr_handler, NULL, ESP_INTR_FLAG_IRAM, NULL); // Set ISR Handler 76 | return true; 77 | }; 78 | 79 | // Utility function to give number of ticks since the last event. Useful 80 | // for determining how much time has elapsed within the interrupt handler since 81 | // the interrupt was triggered. 82 | // I couldn't find a way of retrieving the current ICP timer value, only the captured one. 83 | // Until I can find one, here's a work-around that uses the micros() function. It's not 84 | // used for timing events, so isn't particularly critical. 85 | inline unsigned long IRAM_ATTR elapsedTicksSinceLastEvent() { 86 | return (micros() - thisEventMicros) * TICKSPERMICROSEC; 87 | }; 88 | 89 | // Function called from the interrupt handler to calculate the gap between interrupts, 90 | // and to invoke the user program's handler. The user's handler is passed the 91 | // number of ticks elapsed since the last valid interrupt. It returns true/false to 92 | // indicate if this interrupt is deemed to be 'valid' or not. 93 | void IRAM_ATTR processInterrupt(mcpwm_capture_channel_id_t cap_channel) { 94 | // Get current micros() value to support elapsedTicksSinceLastEvent(). 95 | thisEventMicros = micros(); 96 | 97 | unsigned long thisEventTicks = mcpwm_capture_signal_get_value(MCPWM_UNIT_0, cap_channel); //get capture signal counter value 98 | unsigned long eventInterval = thisEventTicks - lastValidEventTicks; 99 | bool accepted = callUserHandler(eventInterval); 100 | if (accepted) { 101 | lastValidEventTicks = thisEventTicks; 102 | } 103 | }; 104 | 105 | // Utility function to return the number of timer ticks per microsecond. 106 | // On the ESP32, this is normally 80 but can be adjusted through a prescaler. 107 | inline unsigned int ticksPerMicrosec() { 108 | return TICKSPERMICROSEC; 109 | }; 110 | 111 | // Utility function to inform whether input capture is in use or not. For this 112 | // version, it always returns true. 113 | inline bool inputCaptureMode() { return true; }; 114 | 115 | private: 116 | EventHandler *callUserHandler = 0; 117 | unsigned long lastValidEventTicks = 0; 118 | unsigned long thisEventMicros = 0; 119 | int pin = -1; 120 | } /* class EventTimerClass */; 121 | 122 | EventTimerClass EventTimer; 123 | 124 | static bool IRAM_ATTR captureCallbackFunction(mcpwm_unit_t mcpwm, mcpwm_capture_channel_id_t cap_channel, const cap_event_data_t *edata, void *user_data) { 125 | EventTimer.processInterrupt(cap_channel); 126 | return false; 127 | } 128 | 129 | #endif 130 | -------------------------------------------------------------------------------- /OledDisplay.cpp: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021 Neil McKechnie 2 | * 3 | * This Library is free software: you can redistribute it and/or modify 4 | * it under the terms of the GNU General Public License as published by 5 | * the Free Software Foundation, either version 3 of the License, or 6 | * (at your option) any later version. 7 | * 8 | * This Library is distributed in the hope that it will be useful, 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | * GNU General Public License for more details. 12 | * 13 | * You should have received a copy of the GNU General Public License 14 | * along with this software. If not, see 15 | * . 16 | */ 17 | 18 | /* 19 | * Class to encapsulate the handling of the OLED display in the 20 | * DCC Diagnostic program. It also handles the button which 21 | * is used for scrolling the display. 22 | */ 23 | 24 | #include "OledDisplay.h" 25 | 26 | #include "Config.h" 27 | 28 | #ifdef USE_OLED 29 | 30 | // Function called to initialise the object instance. 31 | // Connects to the OLED display and puts it into a 32 | // suitable mode. 33 | bool OledDisplayClass::begin(int sdaPin, int sclPin) { 34 | Serial.print("OLED SDA/SCL="); 35 | Serial.print(sdaPin); 36 | Serial.print("/"); 37 | Serial.println(sclPin); 38 | #if defined(ESP32) || defined(ESP8266) 39 | Wire.begin(sdaPin, sclPin); 40 | #endif 41 | if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_I2CADDRESS)) { 42 | Serial.println("Can't connect to OLED display!"); 43 | return false; 44 | } 45 | display.clearDisplay(); 46 | display.display(); 47 | display.setTextSize(1); 48 | display.setTextColor(SSD1306_WHITE); 49 | display.setTextWrap(false); 50 | //display.setRotation(2); 51 | 52 | // Initialise the button pin. 53 | #ifdef BUTTONPIN 54 | pinMode(BUTTONPIN, INPUT_PULLUP); 55 | #endif 56 | 57 | Serial.println("OLED initialised"); 58 | return true; 59 | } 60 | 61 | // Function called to force an update of the screen, 62 | // starting with the line referenced by 'firstLine'. 63 | void OledDisplayClass::refresh() { 64 | // locate nominated line 65 | display.clearDisplay(); 66 | display.setCursor(0,0); 67 | display.print(selectedLine()); 68 | display.display(); 69 | } 70 | 71 | // Check the button pin input to see if the button has 72 | // been pressed. If so, increment 'firstLine' and refresh, 73 | // so that the displayed text scrolls upwards. 74 | // This function should be called regularly from the loop() function. 75 | void OledDisplayClass::checkButton() { 76 | #ifdef BUTTONPIN 77 | static int lastButtonState = 0; 78 | int buttonState = digitalRead(BUTTONPIN); 79 | if (buttonState == 0 && lastButtonState == 1) { 80 | // Button pressed. Move a few lines down. 81 | firstLine += 4; 82 | refresh(); 83 | } 84 | lastButtonState = buttonState; 85 | #endif 86 | } 87 | 88 | // Display specified text on the screen. 89 | void OledDisplayClass::append(const char *string) { 90 | sbOled.println(string); 91 | sbOled.end(); 92 | refresh(); 93 | } 94 | 95 | //======================================================================= 96 | // WriteShortStatistics sends a short summary to a print stream for writing 97 | // to the OLED display. 98 | 99 | void OledDisplayClass::writeShortStatistics(Statistics &lastStats) { 100 | 101 | sbOled.reset(); 102 | if (lastStats.count > 0) { 103 | sbOled.print(F("Bits/")); 104 | sbOled.print(lastStats.refreshTime); 105 | sbOled.print(F(" sec: ")); 106 | sbOled.println(lastStats.count/2); 107 | 108 | sbOled.println(F("Lengths (us)")); 109 | 110 | sbOled.print(F(" 0:")); 111 | if (lastStats.count0 > 0) { 112 | sbOled.print((double)lastStats.total0/lastStats.count0, 1); 113 | sbOled.print(F(" (")); 114 | sbOled.print(lastStats.min0); 115 | sbOled.print('-'); 116 | sbOled.print(lastStats.max0); 117 | sbOled.println(')'); 118 | } else 119 | sbOled.println(F("N/A")); 120 | 121 | sbOled.print(F(" 1:")); 122 | if (lastStats.count1 > 0) { 123 | sbOled.print((double)lastStats.total1/lastStats.count1, 1); 124 | sbOled.print(F(" (")); 125 | sbOled.print(lastStats.min1); 126 | sbOled.print('-'); 127 | sbOled.print(lastStats.max1); 128 | sbOled.println(')'); 129 | } else 130 | sbOled.println(F("N/A")); 131 | 132 | sbOled.print(F("Deltas: 0:<")); 133 | sbOled.print(lastStats.max0BitDelta); 134 | sbOled.print(F(" 1:<")); 135 | sbOled.println(lastStats.max1BitDelta); 136 | 137 | sbOled.print(F("Glitches: ")); 138 | sbOled.println(lastStats.glitchCount); 139 | 140 | sbOled.print(F("Frames: ")); 141 | sbOled.println(lastStats.packetCount); 142 | 143 | sbOled.print(F("CksumErr: ")); 144 | sbOled.println(lastStats.checksumError); 145 | 146 | sbOled.print(F("NMRA Reject: ")); 147 | sbOled.println(lastStats.outOfSpecRejectionCount); 148 | 149 | sbOled.print(F("RCN 5ms Fails: ")); 150 | sbOled.println(lastStats.rcn5msFailCount); 151 | sbOled.println(F("--")); 152 | 153 | } else { 154 | sbOled.print(F("Bits/")); 155 | sbOled.print(lastStats.refreshTime); 156 | sbOled.println(F(" sec: 0\n" 157 | " 0: 0 1: 0\n" 158 | "Lengths (us)\n" 159 | " 0: N/A\n" 160 | " 1: N/A\n" 161 | "Deltas: N/A\n" 162 | "Frames: 0\n" 163 | "CksumErr: 0\n" 164 | "NMRA Reject: 0\n" 165 | "--")); 166 | } 167 | sbOled.end(); 168 | } 169 | 170 | // Locate pointer to first character of line 'firstLine' in buffer 'sbBuffer'. 171 | // If line doesn't exist, then go back to the beginning of the buffer. 172 | const char *OledDisplayClass::selectedLine() { 173 | if (firstLine > 0) { 174 | int thisLineNo = 0; 175 | for (const char *cptr=sbBuffer; *cptr != 0; cptr++) { 176 | if (*cptr == '\n') { 177 | if (++thisLineNo == firstLine) { 178 | cptr++; // Move to start of next line following newline 179 | if (*cptr == '\0') 180 | break; // Gone off end... 181 | else 182 | return cptr; // line valid. 183 | } 184 | } 185 | } 186 | } 187 | // If we get here then there aren't enough lines, so go back to start. 188 | firstLine = 0; 189 | return sbBuffer; 190 | } 191 | 192 | 193 | // Singleton instance of class 194 | OledDisplayClass OledDisplay; 195 | 196 | #endif -------------------------------------------------------------------------------- /EventTimer_AtMega.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021 Neil McKechnie 2 | * 3 | * This Library is free software: you can redistribute it and/or modify 4 | * it under the terms of the GNU General Public License as published by 5 | * the Free Software Foundation, either version 3 of the License, or 6 | * (at your option) any later version. 7 | * 8 | * This Library is distributed in the hope that it will be useful, 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | * GNU General Public License for more details. 12 | * 13 | * You should have received a copy of the GNU General Public License 14 | * along with this software. If not, see 15 | * . 16 | */ 17 | 18 | /* 19 | * EventTimer_AtMega.h 20 | * 21 | * Timer functions for measuring elapsed time between events. On the 22 | * AtMega328 and AtMega2560 controllers, the functions use the Input Capture 23 | * capability of the microcontroller to capture the timer value very precisely 24 | * using hardware. 25 | * 26 | * Since the Timer counter is limited to 16 bits, it will overflow if the interval exceeds 27 | * about 32milliseconds. To avoid this, we check micros() to determine if pulse 28 | * length is too long and, in that case, calculate the ticks from micros(). 29 | * 30 | */ 31 | 32 | #ifndef eventtimer_default_h 33 | #define eventtimer_default_h 34 | 35 | #include 36 | #include "Config.h" 37 | 38 | #define GPIO_PREFER_SPEED 39 | #include 40 | 41 | #define TICKSPERMICROSEC 2 // 2 (0.5us) or 16 (62.5ns) 42 | 43 | #if defined(ARDUINO_UNO_NANO) 44 | #define ICP_INPUTPIN 8 45 | #define TCNTn TCNT1 // TimerN Counter Register 46 | #define ICRn ICR1 // TimerN Input Change Register 47 | #define TCCRnA TCCR1A // TimerN configuration register 48 | #define TCCRnB TCCR1B // TimerN configuration register 49 | #define TIMSKn TIMSK1 // TimerN interrupt register 50 | #define ICIEn ICIE1 // Interrupt mask 51 | #define ICESn ICES1 // Mask 52 | #define CAPTURE_INTERRUPT TIMER1_CAPT_vect // ISR vector 53 | #elif defined (ARDUINO_MEGA) 54 | #define ICP_INPUTPIN 49 55 | #define TCNTn TCNT4 // TimerN Counter Register 56 | #define ICRn ICR4 // TimerN Input Change Register 57 | #define TCCRnA TCCR4A // TimerN configuration register 58 | #define TCCRnB TCCR4B // TimerN configuration register 59 | #define TIMSKn TIMSK4 // TimerN interrupt register 60 | #define ICIEn ICIE4 // Interrupt mask 61 | #define ICESn ICES4 // Mask 62 | #define CAPTURE_INTERRUPT TIMER4_CAPT_vect // ISR vector 63 | #else 64 | #error "Architecture not supported by EventTimer library." 65 | #endif 66 | 67 | /* 68 | * User event handler is sent the time since the last valid event. 69 | * If the user event handler decides that this event isn't valid 70 | * (e.g. time since last one is too short) then it should return 71 | * false to reject the event. If the event is valid, then it 72 | * should return true to accept it. 73 | */ 74 | typedef bool EventHandler(unsigned long eventInterval); 75 | 76 | class EventTimerClass { 77 | public: 78 | 79 | // Initialise the object instance, validating that the input pin is 80 | // correct and noting the reference to the user handler for future use. 81 | bool begin(int pin, EventHandler userHandler) { 82 | if (pin != ICP_INPUTPIN) { 83 | Serial.print(F("ERROR: pin=")); 84 | Serial.print(pin); 85 | Serial.print(F(", ICP=")); 86 | Serial.println(ICP_INPUTPIN); 87 | return false; 88 | } 89 | 90 | this->pin = pin; 91 | this->callUserHandler = userHandler; 92 | 93 | // Set up input capture. 94 | // Configure Timer to increment TCNTn on a 2MHz clock, 95 | // (every 0.5us), or 16MHz (every 62.5ns), no interrupt. 96 | // Use Input Capture Pin ICP to capture time of input change 97 | // and interrupt the CPU. 98 | TCCRnA = 0; 99 | #if TICKSPERMICROSEC==2 100 | TCCRnB = (1 << CS11); // Prescaler CLK/8 101 | #elif TICKSPERMICROSEC==16 102 | TCCRnB = (1 << CS10); // Prescaler CLK/1 103 | #else 104 | #error "TICKSPERMICROSEC" not 2 or 16. 105 | #endif 106 | TIMSKn = (1 << ICIEn); // Input capture interrupt enable 107 | 108 | return true; 109 | }; 110 | 111 | // Utility function to give number of ticks since the last event. Useful 112 | // for determining how much time has elapsed within the interrupt handler since 113 | // the interrupt was triggered. 114 | inline unsigned long elapsedTicksSinceLastEvent() { 115 | return (unsigned int)(TCNTn - thisEventTicks); 116 | }; 117 | 118 | // Function called from the interrupt handler to calculate the gap between interrupts, 119 | // and to invoke the user program's handler. The user's handler is passed the 120 | // number of ticks elapsed since the last valid interrupt. It returns true/false to 121 | // indicate if this interrupt is deemed to be 'valid' or not. 122 | void processInterrupt() { 123 | // Time-critical bits. 124 | unsigned long thisEventMicros = micros(); 125 | thisEventTicks = ICRn; 126 | byte diginState = digitalRead2(this->pin); 127 | 128 | // Set up input capture for next edge. 129 | if (diginState) 130 | TCCRnB &= ~(1 << ICESn); // Capture next falling edge on input 131 | else 132 | TCCRnB |= (1 << ICESn); // Capture next rising edge on input 133 | 134 | // Initially estimate time ticks using micros() values. 135 | unsigned long eventSpacing = (thisEventMicros - lastValidEventMicros) * TICKSPERMICROSEC; 136 | if (eventSpacing < 60000L) { 137 | // Estimated time is well within range of timer count, so calculate ticks from ICRn 138 | eventSpacing = thisEventTicks - lastValidEventTicks; 139 | } 140 | // Call user handler. 141 | bool accepted = callUserHandler(eventSpacing); 142 | if (accepted) { 143 | lastValidEventTicks = thisEventTicks; 144 | lastValidEventMicros = thisEventMicros; 145 | } 146 | }; 147 | 148 | // Utility function to return the number of timer ticks per microsecond. 149 | // On the AtMega, this is 2 or 16, depending on the timer pre-scaler setting. 150 | inline unsigned int ticksPerMicrosec() { 151 | return TICKSPERMICROSEC; 152 | }; 153 | 154 | // Utility function to inform whether input capture is in use or not. For this 155 | // version, it always returns true. 156 | inline bool inputCaptureMode() { return true; }; 157 | 158 | private: 159 | EventHandler *callUserHandler = 0; 160 | unsigned int lastValidEventTicks = 0; 161 | unsigned long lastValidEventMicros = 0; 162 | unsigned int thisEventTicks = 0; 163 | int pin = -1; 164 | 165 | } /* class EventTimerClass */; 166 | 167 | // Declare singleton class instance. 168 | EventTimerClass EventTimer; 169 | 170 | // Interrupt handler for input capture event 171 | ISR(CAPTURE_INTERRUPT) { 172 | EventTimer.processInterrupt(); 173 | } 174 | 175 | #endif 176 | -------------------------------------------------------------------------------- /.github/workflows/new-items.yml: -------------------------------------------------------------------------------- 1 | # This workflow is to be used for all repositories to integrate with the DCC++ EX Beta Project. 2 | # It will add all issues and pull requests for a repository to the project, and put in the correct status. 3 | # 4 | # Ensure "REPO_LABEL" is updated with the correct label for the repo stream of work. 5 | name: Add Issue or Pull Request to Project 6 | 7 | env: 8 | REPO_LABEL: ${{ secrets.PROJECT_STREAM_LABEL }} 9 | PROJECT_NUMBER: 7 10 | ORG: DCC-EX 11 | 12 | on: 13 | issues: 14 | types: 15 | - opened 16 | pull_request_target: 17 | types: 18 | - ready_for_review 19 | - opened 20 | - review_requested 21 | 22 | jobs: 23 | add_to_project: 24 | runs-on: ubuntu-latest 25 | steps: 26 | - name: Add labels 27 | uses: andymckay/labeler@master 28 | with: 29 | add-labels: ${{ env.REPO_LABEL }} 30 | 31 | - name: Generate token 32 | id: generate_token 33 | uses: tibdex/github-app-token@36464acb844fc53b9b8b2401da68844f6b05ebb0 34 | with: 35 | app_id: ${{ secrets.PROJECT_APP_ID }} 36 | private_key: ${{ secrets. PROJECT_APP_KEY }} 37 | 38 | - name: Get project data 39 | env: 40 | GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }} 41 | run: | 42 | gh api graphql -f query=' 43 | query($org: String!, $number: Int!) { 44 | organization(login: $org){ 45 | projectV2(number: $number) { 46 | id 47 | fields(first:20) { 48 | nodes { 49 | ... on ProjectV2Field { 50 | id 51 | name 52 | } 53 | ... on ProjectV2SingleSelectField { 54 | id 55 | name 56 | options { 57 | id 58 | name 59 | } 60 | } 61 | } 62 | } 63 | } 64 | } 65 | }' -f org=$ORG -F number=$PROJECT_NUMBER > project_data.json 66 | 67 | echo 'PROJECT_ID='$(jq '.data.organization.projectV2.id' project_data.json) >> $GITHUB_ENV 68 | echo 'STATUS_FIELD_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Status") | .id' project_data.json) >> $GITHUB_ENV 69 | echo 'BACKLOG_OPTION_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Status") |.options[] | select(.name=="Backlog") |.id' project_data.json) >> $GITHUB_ENV 70 | echo 'TO_DO_OPTION_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Status") |.options[] | select(.name=="To Do") |.id' project_data.json) >> $GITHUB_ENV 71 | echo 'NEEDS_REVIEW_OPTION_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Status") |.options[] | select(.name=="Needs Review") |.id' project_data.json) >> $GITHUB_ENV 72 | echo 'IN_PROGRESS_OPTION_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Status") |.options[] | select(.name=="In Progress") |.id' project_data.json) >> $GITHUB_ENV 73 | 74 | - name: Add issue to project 75 | env: 76 | GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }} 77 | ITEM_ID: ${{ github.event.issue.node_id }} 78 | if: github.event_name == 'issues' 79 | run: | 80 | project_item_id="$( gh api graphql -f query=' 81 | mutation($project:ID!, $item:ID!) { 82 | addProjectV2ItemById(input: {projectId: $project, contentId: $item}) { 83 | item { 84 | id 85 | } 86 | } 87 | }' -f project=$PROJECT_ID -f item=$ITEM_ID --jq '.data.addProjectV2ItemById.item.id')" 88 | echo 'PROJECT_ITEM_ID='$project_item_id >> $GITHUB_ENV 89 | 90 | - name: Add PR to project 91 | env: 92 | GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }} 93 | ITEM_ID: ${{ github.event.pull_request.node_id }} 94 | if: github.event_name == 'pull_request' 95 | run: | 96 | project_item_id="$( gh api graphql -f query=' 97 | mutation($project:ID!, $item:ID!) { 98 | addProjectV2ItemById(input: {projectId: $project, contentId: $item}) { 99 | item { 100 | id 101 | } 102 | } 103 | }' -f project=$PROJECT_ID -f item=$ITEM_ID --jq '.data.addProjectV2ItemById.item.id')" 104 | echo 'PROJECT_ITEM_ID='$project_item_id >> $GITHUB_ENV 105 | 106 | - name: Set status - To Do 107 | env: 108 | GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }} 109 | if: github.event_name == 'issues' && (contains(github.event.*.labels.*.name, 'Bug') || contains(github.event.*.labels.*.name, 'Support Request')) 110 | run: | 111 | gh api graphql -f query=' 112 | mutation( 113 | $project: ID! 114 | $item: ID! 115 | $status_field: ID! 116 | $status_value: String! 117 | ){ 118 | set_status: updateProjectV2ItemFieldValue(input: { 119 | projectId: $project 120 | itemId: $item 121 | fieldId: $status_field 122 | value: { 123 | singleSelectOptionId: $status_value 124 | } 125 | }) { 126 | projectV2Item { 127 | id 128 | } 129 | } 130 | }' -f project=$PROJECT_ID -f item=$PROJECT_ITEM_ID -f status_field=$STATUS_FIELD_ID -f status_value=${{ env.TO_DO_OPTION_ID }} --silent 131 | 132 | - name: Set status - Review 133 | env: 134 | GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }} 135 | if: github.event_name == 'issues' && (contains(github.event.*.labels.*.name, 'Unit Tested') || contains(github.event.*.labels.*.name, 'Regression Tested') || contains(github.event.*.labels.*.name, 'Needs Review')) || github.event_name == 'pull_request' 136 | run: | 137 | gh api graphql -f query=' 138 | mutation( 139 | $project: ID! 140 | $item: ID! 141 | $status_field: ID! 142 | $status_value: String! 143 | ){ 144 | set_status: updateProjectV2ItemFieldValue(input: { 145 | projectId: $project 146 | itemId: $item 147 | fieldId: $status_field 148 | value: { 149 | singleSelectOptionId: $status_value 150 | } 151 | }) { 152 | projectV2Item { 153 | id 154 | } 155 | } 156 | }' -f project=$PROJECT_ID -f item=$PROJECT_ITEM_ID -f status_field=$STATUS_FIELD_ID -f status_value=${{ env.NEEDS_REVIEW_OPTION_ID }} --silent 157 | -------------------------------------------------------------------------------- /DCCStatistics.cpp: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021 Neil McKechnie 2 | * 3 | * This Library is free software: you can redistribute it and/or modify 4 | * it under the terms of the GNU General Public License as published by 5 | * the Free Software Foundation, either version 3 of the License, or 6 | * (at your option) any later version. 7 | * 8 | * This Library is distributed in the hope that it will be useful, 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | * GNU General Public License for more details. 12 | * 13 | * You should have received a copy of the GNU General Public License 14 | * along with this software. If not, see 15 | * . 16 | */ 17 | 18 | // Module containing singleton instance of DCCStatistics class. 19 | 20 | #include "DCCStatistics.h" 21 | 22 | // Update statistics to reflect the received digital input transition. Altbit 23 | // is zero if the transition is the end of the first half-bit and one if it is 24 | // the end of the second half of a DCC bit; Bitvalue is the value of the DCC 25 | // bit; and interruptInterval is the microsecond time between successive 26 | // interrupts (the length of the half-bit in DCC terms). 27 | void INTERRUPT_SAFE DCCStatisticsClass::recordHalfBit( 28 | byte altbit, byte bitValue, unsigned int interruptInterval, 29 | unsigned int delta) { 30 | activeStats.count++; 31 | if (bitValue == 0) { 32 | activeStats.count0++; 33 | if (interruptInterval > activeStats.max0) 34 | activeStats.max0 = interruptInterval; 35 | if (interruptInterval < activeStats.min0) 36 | activeStats.min0 = interruptInterval; 37 | activeStats.total0 += interruptInterval; 38 | if (altbit && (delta > activeStats.max0BitDelta)) 39 | activeStats.max0BitDelta = delta; 40 | } else { 41 | activeStats.count1++; 42 | if (interruptInterval > activeStats.max1) 43 | activeStats.max1 = interruptInterval; 44 | if (interruptInterval < activeStats.min1) 45 | activeStats.min1 = interruptInterval; 46 | activeStats.total1 += interruptInterval; 47 | if (altbit & (delta > activeStats.max1BitDelta)) 48 | activeStats.max1BitDelta = delta; 49 | } 50 | if (interruptInterval < minBitLength) 51 | interruptInterval = minBitLength; 52 | else if (interruptInterval > maxBitLength) 53 | interruptInterval = maxBitLength; 54 | activeStats.countByLength[altbit][interruptInterval - minBitLength]++; 55 | } 56 | 57 | //======================================================================= 58 | // WriteFullStatistics writes the statistics to Serial stream. 59 | // 60 | void DCCStatisticsClass::writeFullStatistics(Statistics &stats, 61 | bool showCpuStats, 62 | bool showBitLengths) { 63 | Serial.print(F("Bit Count/")); 64 | Serial.print(refreshTime); 65 | Serial.print(F(" sec=")); 66 | // These counts are for half-bits, so divide by two. 67 | Serial.print(stats.count / 2); 68 | Serial.print(F(" (Zeros=")); 69 | Serial.print(stats.count0 / 2); 70 | Serial.print(F(", Ones=")); 71 | Serial.print(stats.count1 / 2); 72 | Serial.print(F("), Glitches=")); 73 | Serial.println(stats.glitchCount); 74 | 75 | Serial.print(F("Valid Packets=")); 76 | Serial.print(stats.packetCount); 77 | Serial.print(F(", Idles=")); 78 | Serial.print(stats.idleCount); 79 | Serial.print(F(", NMRA out of spec=")); 80 | Serial.print(stats.outOfSpecRejectionCount); 81 | Serial.print(F(", RCN 5ms errors=")); 82 | Serial.print(stats.rcn5msFailCount); 83 | Serial.print(F(", Checksum Errors=")); 84 | Serial.print(stats.checksumError); 85 | Serial.print(F(", Lost pkts=")); 86 | Serial.print(stats.countLostPackets); 87 | Serial.print(F(", Long pkts=")); 88 | Serial.println(stats.countLongPackets); 89 | 90 | Serial.print(F("0 half-bit length (us): ")); 91 | if (stats.min0 <= stats.max0) { 92 | Serial.print((float)stats.total0 / stats.count0, 1); 93 | Serial.print(F(" (")); 94 | Serial.print(stats.min0); 95 | Serial.print(F("-")); 96 | Serial.print(stats.max0); 97 | Serial.print(F(")")); 98 | Serial.print(F(" delta < ")); 99 | Serial.print(stats.max0BitDelta); 100 | } else 101 | Serial.print(F("")); 102 | Serial.println(); 103 | Serial.print(F("1 half-bit length (us): ")); 104 | if (stats.min1 <= stats.max1) { 105 | Serial.print((float)stats.total1 / stats.count1, 1); 106 | Serial.print(F(" (")); 107 | Serial.print(stats.min1); 108 | Serial.print(F("-")); 109 | Serial.print(stats.max1); 110 | Serial.print(F(")")); 111 | Serial.print(F(" delta < ")); 112 | Serial.print(stats.max1BitDelta); 113 | } else 114 | Serial.print(F("")); 115 | Serial.println(); 116 | 117 | if (showCpuStats) { 118 | Serial.print(F("IRC Duration (us): ")); 119 | if (stats.minInterruptTime <= stats.maxInterruptTime) { 120 | Serial.print((float)stats.totalInterruptTime / stats.count, 1); 121 | Serial.print(F(" (")); 122 | Serial.print(stats.minInterruptTime); 123 | Serial.print(F("-")); 124 | Serial.print(stats.maxInterruptTime); 125 | Serial.print(F(")")); 126 | } else 127 | Serial.print(F("")); 128 | 129 | // Calculate and display cpu load 130 | unsigned long spareLoopCountPerSec = stats.spareLoopCount / refreshTime; 131 | Serial.print(F(", CPU load: ")); 132 | Serial.print( 133 | 100.0f * (1.0f - (float)spareLoopCountPerSec / maxSpareLoopCountPerSec), 134 | 1); 135 | Serial.print(F("%")); 136 | Serial.println(); 137 | } 138 | 139 | if (showBitLengths) { 140 | Serial.println(F("------ Half-bit count by length (us) -------")); 141 | for (int i = minBitLength; i <= maxBitLength; i++) { 142 | unsigned long c0 = stats.countByLength[0][i - minBitLength]; 143 | unsigned long c1 = stats.countByLength[1][i - minBitLength]; 144 | if (c0 > 0 || c1 > 0) { 145 | if (i == minBitLength) 146 | Serial.print(F("<=")); 147 | else if (i == maxBitLength) 148 | Serial.print(F(">=")); 149 | Serial.print(i); 150 | Serial.print('\t'); 151 | Serial.print(c0); 152 | Serial.print('\t'); 153 | Serial.println(c1); 154 | } 155 | } 156 | Serial.println(F("--------------------------------------------")); 157 | } 158 | } 159 | 160 | // Return a copy of the current set of statistics accumulated. We could inhibit 161 | // interrupts while accessing the activeStats data, but the effect on the 162 | // interrupt code may be more significant than the effect on the resulting 163 | // counters. 164 | Statistics DCCStatisticsClass::getAndClearStats() { 165 | Statistics stats; 166 | memcpy(&stats, (void *)&activeStats, sizeof(activeStats)); 167 | memset((void *)&activeStats, 0, sizeof(activeStats)); 168 | activeStats.minInterruptTime = activeStats.min0 = activeStats.min1 = 65535; 169 | 170 | // Sample spare loop count and adjust max accordingly, for CPU load calcs. 171 | if (maxSpareLoopCountPerSec < stats.spareLoopCount / refreshTime) 172 | maxSpareLoopCountPerSec = stats.spareLoopCount / refreshTime; 173 | stats.refreshTime = refreshTime; 174 | return stats; 175 | } 176 | 177 | // Declare singleton class instance 178 | DCCStatisticsClass DCCStatistics; 179 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DccInspector-EX 2 | 3 | ## Summary 4 | 5 | Diagnostic/sniffer program for DCC analysis, based on an Arduino or ESP32 target. 6 | The bit structure and packet structure are analysed and reported, and packets are decoded 7 | and displayed in binary and also in a textual form. 8 | 9 | On Arduino, the program produces output to the Serial port. 10 | 11 | On ESP32, it supports HTTP output via WiFi, and will display a reduced set of information 12 | on an OLED display. A button can be configured to allow the screen to be scrolled to display 13 | more information. Development boards such as the Heltec Kit 32 include OLED and a button and 14 | can be used directly. The ESP32 will go into deep sleep mode (to preserve battery when used stand-alone) if no input 15 | DCC signal is detected for two minutes, it resumes when reset. 16 | 17 | ## Hardware Interface 18 | 19 | The device may be directly connected to a DCC controller of the same I/O voltage and earth, e.g. in a 20 | DCC++ or DCC++ EX system. If it is used to monitor DCC signals, which are 21 | normally bipolar 12-18V signals, an optocoupler circuit will be required. 22 | 23 | Various circuits are discussed on the internet, but if you use a 6N137 optocoupler I 24 | would recommend a 1nF capacitor across the optocoupler input to stabilise the DCC input signal. 25 | Without this the opto-isolator may experience ringing, causing fleeting interrupts on the input 26 | (recorded as 'glitches' in the diagnostics). 27 | 28 | I use a pull-up resistor of 470 ohms (labelled R3 below) on the output pin 6, connected to 5V; 29 | a larger resistor (even the Arduino's internal pull-up) will generally still work but may slow 30 | down the optocoupler. Using the internal pull-up (~25Kohm), the rise-time on the signal is some microseconds 31 | in length, compared to around 200ns with a 470 (or 330) ohm pull-up. This may be acceptable in a decoder where the 32 | timing requirements may be relaxed, but a faster response is preferred for a diagnostic tool. 33 | 34 | No connection is necessary to pin 7, although some versions of the circuit show a pull-up resistor here. 35 | 36 | ![Recommended Optocoupler Circuit](assets/DCC-Isolator-6N137.png "Recommended Optocoupler Circuit") 37 | 38 | Strictly, the 6N137 isn't rated for the 3.3V supply used on an ESP8266 or ESP32. 39 | I've had good results running with the circuit shown above with a 3.3V supply (replacing R3 with 330 ohm), 40 | but if you want to do things properly, the VCC terminal of the 6N137 should be 41 | connected to +5V, or the optocoupler should be replaced with a 3.3V tolerant optocoupler. In either case, 42 | R3 should be connected to +3.3V to avoid putting too high a voltage on the ESP's input pin. 43 | 44 | The default input pin used by the sketch depends on the target used. For Arduino Uno and Nano, pin 8; 45 | for Mega, pin 49. For the ESP8266/ESP32 it's GPIO2 (labelled D4 on the 8266 NodeMCU). 46 | 47 | ## Target Platforms 48 | 49 | The diagnostic program supports the Arduino Uno, Nano, Mega and ESP32 particularly. 50 | 51 | On Arduino, measurements are performed at an accuracy of 1/2 or 1/16th microsecond using Timer1 input 52 | capture mode, and calculation results are rounded to 1 microsecond. 53 | 54 | For increased compatibility with other microcontrollers, it is possible to use the micros() function for timing. 55 | However, on an Arduino Uno/Nano/Mega this introduces up to 3us error in the micros() result, plus up to 56 | 6.5us uncertainty in the scheduling of the interrupt which samples the micros() value; consequently, the 57 | measured pulse length will, approximately once every millisecond, be off by up to 10us, and the rest of 58 | the time be up to 3us out. This mode of operation is not recommended. 59 | 60 | The sketch also supports the ESP8266 and ESP32. 61 | On the ESP8266, the timing is performed using the micros() function. Consequently, 62 | some inaccuracies due to interrupts are still present, of the order of 4us either way. 63 | 64 | The ESP32 runs in input capture mode, which works very well and potentially can support a 65 | measurement accuracy of around 4ns. The sketch uses the default 12.5ns timer resolution and rounds 66 | the results to 1us accuracy. 67 | 68 | ## WiFi and Web Browser 69 | 70 | On ESP8266 and ESP32, an HTTP server is provided which allows the output to be viewed from 71 | a standard browser. The first time the device starts, it will attempt to get WiFi credentials from the 72 | router using WPS protocol. Press the WPS button on the router before resetting the device, and 73 | the device should connect to the router. When the device is reset or started in future, it will 74 | connect using the same credentials by preference. 75 | 76 | ![Example of output in web browser](assets/WebInterface.PNG "Example of web output") 77 | 78 | ## Serial USB Output 79 | 80 | The sketch produces output to the Serial stream, by default 81 | once every 4 seconds. The output statistics includes bit counts, 82 | bit lengths, checksum errors, packets too long, and 83 | time spent within the interrupt code. Fleeting input state changes 84 | (<= 3us) are optionally filtered and counted. A break-down of pulse counts by 85 | length can also be produced, to monitor the consistency of the DCC signal. 86 | The bit stream is validated against the specifications in NMRA S-9.1 (2020) for bit length 87 | and delta. The validation can be selected through the serial monitor to be strict=0 (no validation), strict=1 88 | (NMRA Decoder compliance level) or strict=2 (NMRA Controller compliance level). 89 | The number of packets rejected due to non-compliance is recorded and displayed. 90 | 91 | In between statistics output, received DCC packets are decoded and 92 | printed; duplicate throttle packets and idle packets are however not printed more than once per period. 93 | 94 | Press '?' in the serial monitor to see help of the commands available. The 95 | breakdown of pulse lengths is not displayed by default, press 'B' to enabled it. 96 | Likewise, the CPU statistics are not displayed by default, press 'C' to enable them. 97 | 98 | ## Example Output On Serial USB 99 | 100 | ### Example Uno Monitoring DCC++ EX 3.0.10 (5V, 6N137 Optocoupler, Main Track, Strict NMRA): 101 | All DCC packets are within the NMRA specification 102 | and the pulse lengths are always within 1us of the target lengths of 116us and 58us. 103 | 104 | This demonstrates the improvements in pulse quality which were introduced in DCC++EX in 105 | version 3.0.5 when running on an ATmega2560 board with standard motor pins, compared to the pulse lengths 106 | measured for the DCC++EX version 3.0.4 below. It is achieved by using the Arduino's 107 | hardware PWM capabilities to generate the pulse transitions; this is accurate to one clock cycle, 108 | i.e. 1/16th of a microsecond, although the measurement accuracy is reduced slightly by the optocoupler circuit. 109 | 110 | ``` 111 | - 112 | Bit Count/4 sec=25621 (Zeros=9134, Ones=16486), Glitches=0 113 | Valid Packets=446, NMRA out of spec=0, Checksum Errors=0, Lost pkts=0, Long pkts=0 114 | 0 half-bit length (us): 115.9 (115-116) delta < 1 115 | 1 half-bit length (us): 57.9 (57-58) delta < 1 116 | ------ Half-bit count by length (us) ------- 117 | 57 3218 0 118 | 58 13270 16490 119 | 115 2444 150 120 | 116 6690 8984 121 | -------------------------------------------- 122 | -- 123 | Loc 3 Rev128 25 00000011 00111111 00011010 124 | Loc 7979 Fwd128 122 11011111 00101011 00111111 11111011 125 | - 126 | ``` 127 | 128 | ### Example ESP32 Monitoring DCC++ EX 3.0.4 (5V, 6N137 Optocoupler, Main Track, Strict NMRA) 129 | When the DCC signal is generated within interrupt handling code within the Command Station, the accuracy of 130 | the signal cannot be maintained to such a high accuracy. Below, we can see that the pulse length varies over a range of around 14us. 131 | This would mean that some packets are outside of the NMRA specification and may be ignored by the loco decoder. 132 | The analyser reports 81 packets as out of spec and 351 in-spec, i.e. around 20% are out of spec. This is not 133 | normally a problem on a DCC layout as each packet is transmitted at least three times. If one packet doesn't get 134 | through, the probability is that one of the retransmissions will! 135 | 136 | The half-bit counts are turned off here, but CPU monitoring within the analyser is turned on. 137 | 138 | ``` 139 | - 140 | Bit Count/4 sec=24865 (Zeros=10167, Ones=14697), Glitches=0 141 | Valid Packets=351, NMRA out of spec=81, Checksum Errors=0, Lost pkts=0, Long pkts=0 142 | 0 half-bit length (us): 115.9 (109-122) delta < 14 143 | 1 half-bit length (us): 57.5 (51-64) delta < 14 144 | IRC Duration (us): 2.2 (1-10), CPU load: 27.5% 145 | -- 146 | Loc 7552 Fwd128 33 11011101 10000000 00111111 10100010 147 | Loc 3 Fwd128 25 00000011 00111111 10011010 148 | - 149 | ``` 150 | 151 | ### Example Uno Monitoring DCC++ Classic (5V direct connection, Main Track, Strict NMRA): 152 | The original DCC++ Classic also uses the hardware PWM capabilities of the Arduino to generate the 153 | DCC pulse transitions. This is capable of accuracy to within one clock cycle, as demonstrated in 154 | the results below. 155 | 156 | ``` 157 | - 158 | Bit Count/4 sec=27573 (Zeros=9881, Ones=17692), Glitches=0 159 | Valid Packets=411, NMRA out of spec=0, Checksum Errors=0, Lost pkts=0, Long pkts=0 160 | 0 half-bit length (us): 100.0 (100-100) delta < 1 161 | 1 half-bit length (us): 58.0 (58-58) delta < 1 162 | IRC Duration (us): 29.8 (27-39), CPU load: 54.6% 163 | ------ Half-bit count by length (us) ------- 164 | 58 17692 17692 165 | 100 9882 9882 166 | -------------------------------------------- 167 | -- 168 | Loc 7801 Fwd128 55 11011110 01111001 00111111 10111000 169 | Loc 2323 Fwd128 5 11001001 00010011 00111111 10000110 170 | - 171 | ``` 172 | 173 | 174 | ## Command Summary 175 | 176 | Keyboard commands that can be sent via Serial Monitor: 177 | 178 | ``` 179 | 1 = 1s refresh time 180 | 2 = 2s 181 | 3 = 4s (default) 182 | 4 = 8s 183 | 5 = 16s 184 | 6 = 4 DCC packet buffer 185 | 7 = 8 186 | 8 = 16 187 | 9 = 32 (default) 188 | 0 = 64 189 | a = show accessory packets toggle 190 | l = show locomotive packets toggle 191 | d = show diagnostics toggle 192 | h = show heartbeat toggle 193 | b = show half-bit counts by length 194 | c = show cpu/irc usage in sniffer 195 | f = input filter toggle 196 | s = set NMRA compliance strictness (0=none,1=decoder,2=controller) 197 | ? = help (show this information) 198 | ``` 199 | -------------------------------------------------------------------------------- /hardware/oled-wifi-kit-32/oled_inspector.kicad_pro: -------------------------------------------------------------------------------- 1 | { 2 | "board": { 3 | "3dviewports": [], 4 | "design_settings": { 5 | "defaults": { 6 | "board_outline_line_width": 0.049999999999999996, 7 | "copper_line_width": 0.19999999999999998, 8 | "copper_text_italic": false, 9 | "copper_text_size_h": 1.5, 10 | "copper_text_size_v": 1.5, 11 | "copper_text_thickness": 0.3, 12 | "copper_text_upright": false, 13 | "courtyard_line_width": 0.049999999999999996, 14 | "dimension_precision": 4, 15 | "dimension_units": 3, 16 | "dimensions": { 17 | "arrow_length": 1270000, 18 | "extension_offset": 500000, 19 | "keep_text_aligned": true, 20 | "suppress_zeroes": false, 21 | "text_position": 0, 22 | "units_format": 1 23 | }, 24 | "fab_line_width": 0.09999999999999999, 25 | "fab_text_italic": false, 26 | "fab_text_size_h": 1.0, 27 | "fab_text_size_v": 1.0, 28 | "fab_text_thickness": 0.15, 29 | "fab_text_upright": false, 30 | "other_line_width": 0.09999999999999999, 31 | "other_text_italic": false, 32 | "other_text_size_h": 1.0, 33 | "other_text_size_v": 1.0, 34 | "other_text_thickness": 0.15, 35 | "other_text_upright": false, 36 | "pads": { 37 | "drill": 0.762, 38 | "height": 1.524, 39 | "width": 1.524 40 | }, 41 | "silk_line_width": 0.12, 42 | "silk_text_italic": false, 43 | "silk_text_size_h": 1.0, 44 | "silk_text_size_v": 1.0, 45 | "silk_text_thickness": 0.15, 46 | "silk_text_upright": false, 47 | "zones": { 48 | "45_degree_only": false, 49 | "min_clearance": 0.508 50 | } 51 | }, 52 | "diff_pair_dimensions": [], 53 | "drc_exclusions": [], 54 | "meta": { 55 | "filename": "board_design_settings.json", 56 | "version": 2 57 | }, 58 | "rule_severities": { 59 | "annular_width": "error", 60 | "clearance": "error", 61 | "copper_edge_clearance": "error", 62 | "courtyards_overlap": "error", 63 | "diff_pair_gap_out_of_range": "error", 64 | "diff_pair_uncoupled_length_too_long": "error", 65 | "drill_out_of_range": "error", 66 | "duplicate_footprints": "warning", 67 | "extra_footprint": "warning", 68 | "footprint_type_mismatch": "error", 69 | "hole_clearance": "error", 70 | "hole_near_hole": "error", 71 | "invalid_outline": "error", 72 | "item_on_disabled_layer": "error", 73 | "items_not_allowed": "error", 74 | "length_out_of_range": "error", 75 | "malformed_courtyard": "error", 76 | "microvia_drill_out_of_range": "error", 77 | "missing_courtyard": "ignore", 78 | "missing_footprint": "warning", 79 | "net_conflict": "warning", 80 | "npth_inside_courtyard": "ignore", 81 | "padstack": "error", 82 | "pth_inside_courtyard": "ignore", 83 | "shorting_items": "error", 84 | "silk_over_copper": "error", 85 | "silk_overlap": "error", 86 | "skew_out_of_range": "error", 87 | "through_hole_pad_without_hole": "error", 88 | "too_many_vias": "error", 89 | "track_dangling": "warning", 90 | "track_width": "error", 91 | "tracks_crossing": "error", 92 | "unconnected_items": "error", 93 | "unresolved_variable": "error", 94 | "via_dangling": "warning", 95 | "zone_has_empty_net": "error", 96 | "zones_intersect": "error" 97 | }, 98 | "rules": { 99 | "allow_blind_buried_vias": false, 100 | "allow_microvias": false, 101 | "max_error": 0.005, 102 | "min_clearance": 0.0, 103 | "min_copper_edge_clearance": 0.049999999999999996, 104 | "min_hole_clearance": 0.0, 105 | "min_hole_to_hole": 0.25, 106 | "min_microvia_diameter": 0.19999999999999998, 107 | "min_microvia_drill": 0.09999999999999999, 108 | "min_silk_clearance": 0.0, 109 | "min_through_hole_diameter": 0.3, 110 | "min_track_width": 0.19999999999999998, 111 | "min_via_annular_width": 0.049999999999999996, 112 | "min_via_diameter": 0.39999999999999997, 113 | "use_height_for_length_calcs": true 114 | }, 115 | "track_widths": [], 116 | "via_dimensions": [], 117 | "zones_allow_external_fillets": false, 118 | "zones_use_no_outline": true 119 | }, 120 | "layer_presets": [], 121 | "viewports": [] 122 | }, 123 | "boards": [], 124 | "cvpcb": { 125 | "equivalence_files": [] 126 | }, 127 | "erc": { 128 | "erc_exclusions": [], 129 | "meta": { 130 | "version": 0 131 | }, 132 | "pin_map": [ 133 | [ 134 | 0, 135 | 0, 136 | 0, 137 | 0, 138 | 0, 139 | 0, 140 | 1, 141 | 0, 142 | 0, 143 | 0, 144 | 0, 145 | 2 146 | ], 147 | [ 148 | 0, 149 | 2, 150 | 0, 151 | 1, 152 | 0, 153 | 0, 154 | 1, 155 | 0, 156 | 2, 157 | 2, 158 | 2, 159 | 2 160 | ], 161 | [ 162 | 0, 163 | 0, 164 | 0, 165 | 0, 166 | 0, 167 | 0, 168 | 1, 169 | 0, 170 | 1, 171 | 0, 172 | 1, 173 | 2 174 | ], 175 | [ 176 | 0, 177 | 1, 178 | 0, 179 | 0, 180 | 0, 181 | 0, 182 | 1, 183 | 1, 184 | 2, 185 | 1, 186 | 1, 187 | 2 188 | ], 189 | [ 190 | 0, 191 | 0, 192 | 0, 193 | 0, 194 | 0, 195 | 0, 196 | 1, 197 | 0, 198 | 0, 199 | 0, 200 | 0, 201 | 2 202 | ], 203 | [ 204 | 0, 205 | 0, 206 | 0, 207 | 0, 208 | 0, 209 | 0, 210 | 0, 211 | 0, 212 | 0, 213 | 0, 214 | 0, 215 | 2 216 | ], 217 | [ 218 | 1, 219 | 1, 220 | 1, 221 | 1, 222 | 1, 223 | 0, 224 | 1, 225 | 1, 226 | 1, 227 | 1, 228 | 1, 229 | 2 230 | ], 231 | [ 232 | 0, 233 | 0, 234 | 0, 235 | 1, 236 | 0, 237 | 0, 238 | 1, 239 | 0, 240 | 0, 241 | 0, 242 | 0, 243 | 2 244 | ], 245 | [ 246 | 0, 247 | 2, 248 | 1, 249 | 2, 250 | 0, 251 | 0, 252 | 1, 253 | 0, 254 | 2, 255 | 2, 256 | 2, 257 | 2 258 | ], 259 | [ 260 | 0, 261 | 2, 262 | 0, 263 | 1, 264 | 0, 265 | 0, 266 | 1, 267 | 0, 268 | 2, 269 | 0, 270 | 0, 271 | 2 272 | ], 273 | [ 274 | 0, 275 | 2, 276 | 1, 277 | 1, 278 | 0, 279 | 0, 280 | 1, 281 | 0, 282 | 2, 283 | 0, 284 | 0, 285 | 2 286 | ], 287 | [ 288 | 2, 289 | 2, 290 | 2, 291 | 2, 292 | 2, 293 | 2, 294 | 2, 295 | 2, 296 | 2, 297 | 2, 298 | 2, 299 | 2 300 | ] 301 | ], 302 | "rule_severities": { 303 | "bus_definition_conflict": "error", 304 | "bus_entry_needed": "error", 305 | "bus_to_bus_conflict": "error", 306 | "bus_to_net_conflict": "error", 307 | "conflicting_netclasses": "error", 308 | "different_unit_footprint": "error", 309 | "different_unit_net": "error", 310 | "duplicate_reference": "error", 311 | "duplicate_sheet_names": "error", 312 | "endpoint_off_grid": "warning", 313 | "extra_units": "error", 314 | "global_label_dangling": "warning", 315 | "hier_label_mismatch": "error", 316 | "label_dangling": "error", 317 | "lib_symbol_issues": "warning", 318 | "missing_bidi_pin": "warning", 319 | "missing_input_pin": "warning", 320 | "missing_power_pin": "error", 321 | "missing_unit": "warning", 322 | "multiple_net_names": "warning", 323 | "net_not_bus_member": "warning", 324 | "no_connect_connected": "warning", 325 | "no_connect_dangling": "warning", 326 | "pin_not_connected": "error", 327 | "pin_not_driven": "error", 328 | "pin_to_pin": "warning", 329 | "power_pin_not_driven": "error", 330 | "similar_labels": "warning", 331 | "simulation_model_issue": "error", 332 | "unannotated": "error", 333 | "unit_value_mismatch": "error", 334 | "unresolved_variable": "error", 335 | "wire_dangling": "error" 336 | } 337 | }, 338 | "libraries": { 339 | "pinned_footprint_libs": [], 340 | "pinned_symbol_libs": [] 341 | }, 342 | "meta": { 343 | "filename": "optoiso.kicad_pro", 344 | "version": 1 345 | }, 346 | "net_settings": { 347 | "classes": [ 348 | { 349 | "bus_width": 12, 350 | "clearance": 0.2, 351 | "diff_pair_gap": 0.25, 352 | "diff_pair_via_gap": 0.25, 353 | "diff_pair_width": 0.2, 354 | "line_style": 0, 355 | "microvia_diameter": 0.3, 356 | "microvia_drill": 0.1, 357 | "name": "Default", 358 | "pcb_color": "rgba(0, 0, 0, 0.000)", 359 | "schematic_color": "rgba(0, 0, 0, 0.000)", 360 | "track_width": 0.25, 361 | "via_diameter": 0.8, 362 | "via_drill": 0.4, 363 | "wire_width": 6 364 | } 365 | ], 366 | "meta": { 367 | "version": 3 368 | }, 369 | "net_colors": null, 370 | "netclass_assignments": null, 371 | "netclass_patterns": [] 372 | }, 373 | "pcbnew": { 374 | "last_paths": { 375 | "gencad": "", 376 | "idf": "", 377 | "netlist": "", 378 | "specctra_dsn": "", 379 | "step": "", 380 | "vrml": "" 381 | }, 382 | "page_layout_descr_file": "" 383 | }, 384 | "schematic": { 385 | "annotate_start_num": 0, 386 | "drawing": { 387 | "dashed_lines_dash_length_ratio": 12.0, 388 | "dashed_lines_gap_length_ratio": 3.0, 389 | "default_bus_thickness": 12.0, 390 | "default_junction_size": 40.0, 391 | "default_line_thickness": 6.0, 392 | "default_text_size": 50.0, 393 | "default_wire_thickness": 6.0, 394 | "field_names": [], 395 | "intersheets_ref_own_page": false, 396 | "intersheets_ref_prefix": "", 397 | "intersheets_ref_short": false, 398 | "intersheets_ref_show": false, 399 | "intersheets_ref_suffix": "", 400 | "junction_size_choice": 3, 401 | "label_size_ratio": 0.3, 402 | "pin_symbol_size": 25.0, 403 | "text_offset_ratio": 0.3 404 | }, 405 | "legacy_lib_dir": "", 406 | "legacy_lib_list": [], 407 | "meta": { 408 | "version": 1 409 | }, 410 | "net_format_name": "Pcbnew", 411 | "ngspice": { 412 | "fix_include_paths": true, 413 | "fix_passive_vals": false, 414 | "meta": { 415 | "version": 0 416 | }, 417 | "model_mode": 0, 418 | "workbook_filename": "" 419 | }, 420 | "page_layout_descr_file": "", 421 | "plot_directory": "", 422 | "spice_adjust_passive_values": false, 423 | "spice_current_sheet_as_root": false, 424 | "spice_external_command": "spice \"%I\"", 425 | "spice_model_current_sheet_as_root": true, 426 | "spice_save_all_currents": false, 427 | "spice_save_all_voltages": false, 428 | "subpart_first_id": 65, 429 | "subpart_id_separator": 0 430 | }, 431 | "sheets": [ 432 | [ 433 | "cfb1c39d-2ad4-40f1-924d-81e5ad4d08e4", 434 | "" 435 | ] 436 | ], 437 | "text_variables": {} 438 | } 439 | -------------------------------------------------------------------------------- /hardware/optoiso-board-only/optoiso-board-only.kicad_pro: -------------------------------------------------------------------------------- 1 | { 2 | "board": { 3 | "3dviewports": [], 4 | "design_settings": { 5 | "defaults": { 6 | "board_outline_line_width": 0.09999999999999999, 7 | "copper_line_width": 0.19999999999999998, 8 | "copper_text_italic": false, 9 | "copper_text_size_h": 1.5, 10 | "copper_text_size_v": 1.5, 11 | "copper_text_thickness": 0.3, 12 | "copper_text_upright": false, 13 | "courtyard_line_width": 0.049999999999999996, 14 | "dimension_precision": 4, 15 | "dimension_units": 3, 16 | "dimensions": { 17 | "arrow_length": 1270000, 18 | "extension_offset": 500000, 19 | "keep_text_aligned": true, 20 | "suppress_zeroes": false, 21 | "text_position": 0, 22 | "units_format": 1 23 | }, 24 | "fab_line_width": 0.09999999999999999, 25 | "fab_text_italic": false, 26 | "fab_text_size_h": 1.0, 27 | "fab_text_size_v": 1.0, 28 | "fab_text_thickness": 0.15, 29 | "fab_text_upright": false, 30 | "other_line_width": 0.15, 31 | "other_text_italic": false, 32 | "other_text_size_h": 1.0, 33 | "other_text_size_v": 1.0, 34 | "other_text_thickness": 0.15, 35 | "other_text_upright": false, 36 | "pads": { 37 | "drill": 0.762, 38 | "height": 1.524, 39 | "width": 1.524 40 | }, 41 | "silk_line_width": 0.15, 42 | "silk_text_italic": false, 43 | "silk_text_size_h": 1.0, 44 | "silk_text_size_v": 1.0, 45 | "silk_text_thickness": 0.15, 46 | "silk_text_upright": false, 47 | "zones": { 48 | "min_clearance": 0.5 49 | } 50 | }, 51 | "diff_pair_dimensions": [], 52 | "drc_exclusions": [], 53 | "meta": { 54 | "version": 2 55 | }, 56 | "rule_severities": { 57 | "annular_width": "error", 58 | "clearance": "error", 59 | "connection_width": "warning", 60 | "copper_edge_clearance": "error", 61 | "copper_sliver": "warning", 62 | "courtyards_overlap": "error", 63 | "diff_pair_gap_out_of_range": "error", 64 | "diff_pair_uncoupled_length_too_long": "error", 65 | "drill_out_of_range": "error", 66 | "duplicate_footprints": "warning", 67 | "extra_footprint": "warning", 68 | "footprint": "error", 69 | "footprint_type_mismatch": "ignore", 70 | "hole_clearance": "error", 71 | "hole_near_hole": "error", 72 | "invalid_outline": "error", 73 | "isolated_copper": "warning", 74 | "item_on_disabled_layer": "error", 75 | "items_not_allowed": "error", 76 | "length_out_of_range": "error", 77 | "lib_footprint_issues": "warning", 78 | "lib_footprint_mismatch": "warning", 79 | "malformed_courtyard": "error", 80 | "microvia_drill_out_of_range": "error", 81 | "missing_courtyard": "ignore", 82 | "missing_footprint": "warning", 83 | "net_conflict": "warning", 84 | "npth_inside_courtyard": "ignore", 85 | "padstack": "warning", 86 | "pth_inside_courtyard": "ignore", 87 | "shorting_items": "error", 88 | "silk_edge_clearance": "warning", 89 | "silk_over_copper": "warning", 90 | "silk_overlap": "warning", 91 | "skew_out_of_range": "error", 92 | "solder_mask_bridge": "error", 93 | "starved_thermal": "error", 94 | "text_height": "warning", 95 | "text_thickness": "warning", 96 | "through_hole_pad_without_hole": "error", 97 | "too_many_vias": "error", 98 | "track_dangling": "warning", 99 | "track_width": "error", 100 | "tracks_crossing": "error", 101 | "unconnected_items": "error", 102 | "unresolved_variable": "error", 103 | "via_dangling": "warning", 104 | "zones_intersect": "error" 105 | }, 106 | "rules": { 107 | "max_error": 0.005, 108 | "min_clearance": 0.0, 109 | "min_connection": 0.0, 110 | "min_copper_edge_clearance": 0.0, 111 | "min_hole_clearance": 0.25, 112 | "min_hole_to_hole": 0.25, 113 | "min_microvia_diameter": 0.19999999999999998, 114 | "min_microvia_drill": 0.09999999999999999, 115 | "min_resolved_spokes": 2, 116 | "min_silk_clearance": 0.0, 117 | "min_text_height": 0.7999999999999999, 118 | "min_text_thickness": 0.08, 119 | "min_through_hole_diameter": 0.3, 120 | "min_track_width": 0.0, 121 | "min_via_annular_width": 0.09999999999999999, 122 | "min_via_diameter": 0.5, 123 | "solder_mask_clearance": 0.0, 124 | "solder_mask_min_width": 0.0, 125 | "solder_mask_to_copper_clearance": 0.0, 126 | "use_height_for_length_calcs": true 127 | }, 128 | "teardrop_options": [ 129 | { 130 | "td_allow_use_two_tracks": true, 131 | "td_curve_segcount": 5, 132 | "td_on_pad_in_zone": false, 133 | "td_onpadsmd": true, 134 | "td_onroundshapesonly": false, 135 | "td_ontrackend": false, 136 | "td_onviapad": true 137 | } 138 | ], 139 | "teardrop_parameters": [ 140 | { 141 | "td_curve_segcount": 0, 142 | "td_height_ratio": 1.0, 143 | "td_length_ratio": 0.5, 144 | "td_maxheight": 2.0, 145 | "td_maxlen": 1.0, 146 | "td_target_name": "td_round_shape", 147 | "td_width_to_size_filter_ratio": 0.9 148 | }, 149 | { 150 | "td_curve_segcount": 0, 151 | "td_height_ratio": 1.0, 152 | "td_length_ratio": 0.5, 153 | "td_maxheight": 2.0, 154 | "td_maxlen": 1.0, 155 | "td_target_name": "td_rect_shape", 156 | "td_width_to_size_filter_ratio": 0.9 157 | }, 158 | { 159 | "td_curve_segcount": 0, 160 | "td_height_ratio": 1.0, 161 | "td_length_ratio": 0.5, 162 | "td_maxheight": 2.0, 163 | "td_maxlen": 1.0, 164 | "td_target_name": "td_track_end", 165 | "td_width_to_size_filter_ratio": 0.9 166 | } 167 | ], 168 | "track_widths": [], 169 | "via_dimensions": [], 170 | "zones_allow_external_fillets": false 171 | }, 172 | "layer_presets": [], 173 | "viewports": [] 174 | }, 175 | "boards": [], 176 | "cvpcb": { 177 | "equivalence_files": [] 178 | }, 179 | "erc": { 180 | "erc_exclusions": [], 181 | "meta": { 182 | "version": 0 183 | }, 184 | "pin_map": [ 185 | [ 186 | 0, 187 | 0, 188 | 0, 189 | 0, 190 | 0, 191 | 0, 192 | 1, 193 | 0, 194 | 0, 195 | 0, 196 | 0, 197 | 2 198 | ], 199 | [ 200 | 0, 201 | 2, 202 | 0, 203 | 1, 204 | 0, 205 | 0, 206 | 1, 207 | 0, 208 | 2, 209 | 2, 210 | 2, 211 | 2 212 | ], 213 | [ 214 | 0, 215 | 0, 216 | 0, 217 | 0, 218 | 0, 219 | 0, 220 | 1, 221 | 0, 222 | 1, 223 | 0, 224 | 1, 225 | 2 226 | ], 227 | [ 228 | 0, 229 | 1, 230 | 0, 231 | 0, 232 | 0, 233 | 0, 234 | 1, 235 | 1, 236 | 2, 237 | 1, 238 | 1, 239 | 2 240 | ], 241 | [ 242 | 0, 243 | 0, 244 | 0, 245 | 0, 246 | 0, 247 | 0, 248 | 1, 249 | 0, 250 | 0, 251 | 0, 252 | 0, 253 | 2 254 | ], 255 | [ 256 | 0, 257 | 0, 258 | 0, 259 | 0, 260 | 0, 261 | 0, 262 | 0, 263 | 0, 264 | 0, 265 | 0, 266 | 0, 267 | 2 268 | ], 269 | [ 270 | 1, 271 | 1, 272 | 1, 273 | 1, 274 | 1, 275 | 0, 276 | 1, 277 | 1, 278 | 1, 279 | 1, 280 | 1, 281 | 2 282 | ], 283 | [ 284 | 0, 285 | 0, 286 | 0, 287 | 1, 288 | 0, 289 | 0, 290 | 1, 291 | 0, 292 | 0, 293 | 0, 294 | 0, 295 | 2 296 | ], 297 | [ 298 | 0, 299 | 2, 300 | 1, 301 | 2, 302 | 0, 303 | 0, 304 | 1, 305 | 0, 306 | 2, 307 | 2, 308 | 2, 309 | 2 310 | ], 311 | [ 312 | 0, 313 | 2, 314 | 0, 315 | 1, 316 | 0, 317 | 0, 318 | 1, 319 | 0, 320 | 2, 321 | 0, 322 | 0, 323 | 2 324 | ], 325 | [ 326 | 0, 327 | 2, 328 | 1, 329 | 1, 330 | 0, 331 | 0, 332 | 1, 333 | 0, 334 | 2, 335 | 0, 336 | 0, 337 | 2 338 | ], 339 | [ 340 | 2, 341 | 2, 342 | 2, 343 | 2, 344 | 2, 345 | 2, 346 | 2, 347 | 2, 348 | 2, 349 | 2, 350 | 2, 351 | 2 352 | ] 353 | ], 354 | "rule_severities": { 355 | "bus_definition_conflict": "error", 356 | "bus_entry_needed": "error", 357 | "bus_to_bus_conflict": "error", 358 | "bus_to_net_conflict": "error", 359 | "conflicting_netclasses": "error", 360 | "different_unit_footprint": "error", 361 | "different_unit_net": "error", 362 | "duplicate_reference": "error", 363 | "duplicate_sheet_names": "error", 364 | "endpoint_off_grid": "warning", 365 | "extra_units": "error", 366 | "global_label_dangling": "warning", 367 | "hier_label_mismatch": "error", 368 | "label_dangling": "error", 369 | "lib_symbol_issues": "warning", 370 | "missing_bidi_pin": "warning", 371 | "missing_input_pin": "warning", 372 | "missing_power_pin": "error", 373 | "missing_unit": "warning", 374 | "multiple_net_names": "warning", 375 | "net_not_bus_member": "warning", 376 | "no_connect_connected": "warning", 377 | "no_connect_dangling": "warning", 378 | "pin_not_connected": "error", 379 | "pin_not_driven": "error", 380 | "pin_to_pin": "warning", 381 | "power_pin_not_driven": "error", 382 | "similar_labels": "warning", 383 | "simulation_model_issue": "error", 384 | "unannotated": "error", 385 | "unit_value_mismatch": "error", 386 | "unresolved_variable": "error", 387 | "wire_dangling": "error" 388 | } 389 | }, 390 | "libraries": { 391 | "pinned_footprint_libs": [], 392 | "pinned_symbol_libs": [] 393 | }, 394 | "meta": { 395 | "filename": "optoiso-board-only.kicad_pro", 396 | "version": 1 397 | }, 398 | "net_settings": { 399 | "classes": [ 400 | { 401 | "bus_width": 12, 402 | "clearance": 0.2, 403 | "diff_pair_gap": 0.25, 404 | "diff_pair_via_gap": 0.25, 405 | "diff_pair_width": 0.2, 406 | "line_style": 0, 407 | "microvia_diameter": 0.3, 408 | "microvia_drill": 0.1, 409 | "name": "Default", 410 | "pcb_color": "rgba(0, 0, 0, 0.000)", 411 | "schematic_color": "rgba(0, 0, 0, 0.000)", 412 | "track_width": 0.25, 413 | "via_diameter": 0.8, 414 | "via_drill": 0.4, 415 | "wire_width": 6 416 | } 417 | ], 418 | "meta": { 419 | "version": 3 420 | }, 421 | "net_colors": null, 422 | "netclass_assignments": null, 423 | "netclass_patterns": [] 424 | }, 425 | "pcbnew": { 426 | "last_paths": { 427 | "gencad": "", 428 | "idf": "", 429 | "netlist": "", 430 | "specctra_dsn": "", 431 | "step": "", 432 | "vrml": "" 433 | }, 434 | "page_layout_descr_file": "" 435 | }, 436 | "schematic": { 437 | "annotate_start_num": 0, 438 | "drawing": { 439 | "dashed_lines_dash_length_ratio": 12.0, 440 | "dashed_lines_gap_length_ratio": 3.0, 441 | "default_line_thickness": 6.0, 442 | "default_text_size": 50.0, 443 | "field_names": [], 444 | "intersheets_ref_own_page": false, 445 | "intersheets_ref_prefix": "", 446 | "intersheets_ref_short": false, 447 | "intersheets_ref_show": false, 448 | "intersheets_ref_suffix": "", 449 | "junction_size_choice": 3, 450 | "label_size_ratio": 0.375, 451 | "pin_symbol_size": 25.0, 452 | "text_offset_ratio": 0.15 453 | }, 454 | "legacy_lib_dir": "", 455 | "legacy_lib_list": [], 456 | "meta": { 457 | "version": 1 458 | }, 459 | "net_format_name": "", 460 | "ngspice": { 461 | "fix_include_paths": true, 462 | "fix_passive_vals": false, 463 | "meta": { 464 | "version": 0 465 | }, 466 | "model_mode": 0, 467 | "workbook_filename": "" 468 | }, 469 | "page_layout_descr_file": "", 470 | "plot_directory": "", 471 | "spice_adjust_passive_values": false, 472 | "spice_current_sheet_as_root": false, 473 | "spice_external_command": "spice \"%I\"", 474 | "spice_model_current_sheet_as_root": true, 475 | "spice_save_all_currents": false, 476 | "spice_save_all_voltages": false, 477 | "subpart_first_id": 65, 478 | "subpart_id_separator": 0 479 | }, 480 | "sheets": [ 481 | [ 482 | "82133f54-2b33-41ec-84f2-8dae5f884f71", 483 | "" 484 | ] 485 | ], 486 | "text_variables": {} 487 | } 488 | -------------------------------------------------------------------------------- /HttpManager.cpp: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021 Neil McKechnie 2 | * 3 | * This Library is free software: you can redistribute it and/or modify 4 | * it under the terms of the GNU General Public License as published by 5 | * the Free Software Foundation, either version 3 of the License, or 6 | * (at your option) any later version. 7 | * 8 | * This Library is distributed in the hope that it will be useful, 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | * GNU General Public License for more details. 12 | * 13 | * You should have received a copy of the GNU General Public License 14 | * along with this software. If not, see 15 | * . 16 | */ 17 | 18 | /* 19 | * HttpManager class definition - methods and static data. 20 | * 21 | * Encapsulates the WiFI and Web Server functionality of the DCC inspector program. 22 | * 23 | */ 24 | 25 | #include 26 | extern byte strictMode; 27 | extern bool filterInput; 28 | 29 | #include "Config.h" 30 | 31 | #ifdef USE_HTTPSERVER 32 | 33 | #include "HttpManager.h" 34 | 35 | #include "OledDisplay.h" 36 | #include "DCCStatistics.h" 37 | 38 | #if defined(ESP32) 39 | #define PLATFORM "ESP32" 40 | #elif defined(ESP8266) 41 | #define PLATFORM "ESP8266" 42 | #endif 43 | 44 | // Buffer pointer reference. This is the buffer of dynamic text sent to the web server client. 45 | char *HttpManagerClass::bufferPointer = 0; 46 | 47 | // Web server object. 48 | WebServer HttpManagerClass::server; 49 | 50 | // Function to handle request for the root web page (http://server/). 51 | // It sends a static web page that includes an updating IFRAME where the dynamic data 52 | // will be displayed. 53 | void HttpManagerClass::handleRoot() { 54 | #if defined(LED_BUILTIN) 55 | digitalWrite(LED_BUILTIN, 1); 56 | #endif 57 | processArguments(); 58 | int refreshTime = DCCStatistics.getRefreshTime(); 59 | String temp = 60 | "\r\n" 61 | "\r\n" 67 | "\r\n" 68 | "DCC Diagnostics - Bit analysis\r\n" 69 | "\r\n" 72 | "\r\n" 73 | "\r\n" 74 | "

DCC Diagnostics

\r\n" 75 | "

Diagnostic information from " PLATFORM " server:

\r\n" 76 | "
\r\n" 77 | "\r\n" 78 | "\r\n" 83 | "
\r\n" 84 | "\r\n" 85 | "\r\n" 94 | "
\r\n" 95 | "\r\n" 96 | "" 100 | "
\r\n" 101 | "\r\n" 102 | "
\r\n" 103 | "

\r\n" 106 | "\r\n" 107 | ""; 108 | server.send(200, "text/html", temp); 109 | temp = ""; // release space held 110 | 111 | #if defined(LED_BUILTIN) 112 | digitalWrite(LED_BUILTIN, 0); 113 | #endif 114 | } 115 | 116 | // Function to handle the request for dynamic data (http://server/data). 117 | void HttpManagerClass::handleData() { 118 | #if defined(LED_BUILTIN) 119 | digitalWrite(LED_BUILTIN, 1); 120 | #endif 121 | server.send(200, "text/html", HttpManager.getHtmlString()); 122 | #if defined(LED_BUILTIN) 123 | digitalWrite(LED_BUILTIN, 0); 124 | #endif 125 | } 126 | 127 | // Function to handle any other requests. Returns "404 Not Found". 128 | void HttpManagerClass::handleNotFound() { 129 | #if defined(LED_BUILTIN) 130 | digitalWrite(LED_BUILTIN, 1); 131 | #endif 132 | String message = "File Not Found\n\n"; 133 | message += "URI: "; 134 | message += server.uri(); 135 | message += "\nMethod: "; 136 | message += (server.method() == HTTP_GET) ? "GET" : "POST"; 137 | message += "\nArguments: "; 138 | message += server.args(); 139 | message += "\n"; 140 | 141 | for (uint8_t i = 0; i < server.args(); i++) { 142 | message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; 143 | } 144 | 145 | server.send(404, "text/plain", message); 146 | #if defined(LED_BUILTIN) 147 | digitalWrite(LED_BUILTIN, 0); 148 | #endif 149 | } 150 | 151 | void HttpManagerClass::processArguments() { 152 | if (server.hasArg("r")) 153 | DCCStatistics.setRefreshTime(server.arg("r").toInt()); 154 | if (server.hasArg("s")) 155 | strictMode = server.arg("s").toInt(); 156 | if (server.hasArg("f")) 157 | filterInput = server.arg("f").toInt(); 158 | } 159 | 160 | #if defined(ESP32) 161 | void HttpManagerClass::WiFiEvent (arduino_event_id_t event) { 162 | switch (event) { 163 | case SYSTEM_EVENT_STA_WPS_ER_SUCCESS: 164 | Serial.print(F("[WPS Successful]")); 165 | esp_wifi_wps_disable (); 166 | WiFi.begin (); 167 | break; 168 | // case SYSTEM_EVENT_STA_DISCONNECTED: 169 | // Serial.print(F("[WiFi Disconnected, reconnecting]")); 170 | // WiFi.reconnect(); 171 | // break; 172 | // case SYSTEM_EVENT_STA_WPS_ER_FAILED: 173 | // Serial.println("WPS Failed, retrying"); 174 | // // esp_wifi_wps_disable(); 175 | // esp_wifi_wps_start(0); 176 | // break; 177 | // case SYSTEM_EVENT_STA_WPS_ER_TIMEOUT: 178 | // Serial.println("WPS Timed out, retrying"); 179 | // // esp_wifi_wps_disable(); 180 | // // esp_wifi_wps_enable(&config); 181 | // esp_wifi_wps_start(0); 182 | // break; 183 | default: 184 | break; 185 | } 186 | } 187 | #endif 188 | 189 | // Function to initialise the object. It connects to the WiFi access point, 190 | // registers an mDNS name (e.g. ESP.local) and sets up the web server. 191 | // By preference, it will connect using the same SSID and password as last time. 192 | // If this fails, it tries WPS. If that fails, it tries the configured SSID/Password. 193 | // If nothing works, the WiFi/HTTP capabilities are disabled. 194 | bool HttpManagerClass::begin(const char *ssid, const char *password, const char *dnsName) { 195 | // Configuration for WiFi wps mode. 196 | #if defined(ESP32) 197 | esp_wps_config_t config; 198 | memset(&config, 0, sizeof(config)); 199 | config.wps_type = WPS_TYPE_PBC; 200 | 201 | WiFi.onEvent (WiFiEvent); 202 | #endif 203 | 204 | int connectMode = 0; 205 | 206 | WiFi.mode(WIFI_STA); 207 | WiFi.setAutoReconnect(true); 208 | 209 | int waitTime = 0; 210 | while (WiFi.status() != WL_CONNECTED) { 211 | switch (connectMode++) { 212 | case 0: // Try persistent credentials 213 | WiFi.setAutoConnect(true); 214 | WiFi.begin(); 215 | Serial.println(); 216 | // Wait for connection 217 | Serial.print(F("Connecting to cached WiFi ")); 218 | #if defined(USE_OLED) 219 | OledDisplay.append("Connecting to WiFi"); 220 | #endif 221 | waitTime = 10; // 10 second timeout. 222 | break; 223 | case 1: // Try WPS 224 | Serial.println(); 225 | WiFi.disconnect(); 226 | Serial.print(F("Connecting via WPS ")); 227 | #if defined(USE_OLED) 228 | OledDisplay.append("Trying WPS"); 229 | #endif 230 | #if defined(ESP32) 231 | esp_wifi_wps_enable(&config); 232 | esp_wifi_wps_start(0); 233 | #elif defined(ESP8266) 234 | WiFi.beginWPSConfig(); 235 | #endif 236 | 237 | waitTime = 20; // 20 second timeout 238 | break; 239 | case 2: // Try nominated user/pass (if not blank) 240 | if (ssid != 0 && ssid[0] != 0) { 241 | WiFi.begin(ssid, password); 242 | Serial.println(); 243 | Serial.print(F("Connecting to \"")); 244 | Serial.print(ssid); 245 | Serial.print(F("\" ")); 246 | waitTime = 10; // 10 second timeout 247 | } else 248 | waitTime = 0; 249 | break; 250 | case 3: // Exhausted all possibilities, carry on. 251 | Serial.println(); 252 | Serial.println(F("Can't connect.")); 253 | #if defined(USE_OLED) 254 | OledDisplay.append("Can't connect"); 255 | #endif 256 | return false; 257 | } 258 | // Wait for connection for 15 seconds. 259 | while (waitTime-- > 0) { 260 | if (WiFi.status() == WL_CONNECTED) 261 | break; 262 | 263 | delay(1000); 264 | Serial.print('.'); 265 | } 266 | #if defined(ESP32) 267 | esp_wifi_wps_disable(); 268 | #endif 269 | } 270 | 271 | connected = true; 272 | 273 | Serial.println(); 274 | Serial.print(F("Connected to \"")); 275 | Serial.print(WiFi.SSID()); 276 | Serial.print(F("\", IP address: ")); 277 | Serial.println(WiFi.localIP()); 278 | #if defined(USE_OLED) 279 | OledDisplay.append("Connected!"); 280 | #endif 281 | 282 | if (MDNS.begin(dnsName)) { 283 | Serial.println(F("MDNS responder started")); 284 | } 285 | 286 | server.on("/", handleRoot); 287 | server.on("/data", handleData); 288 | server.onNotFound(handleNotFound); 289 | server.begin(); 290 | Serial.println(F("HTTP server started")); 291 | 292 | return true; 293 | } 294 | 295 | // Function to set the pointer to dynamic data to be sent to the 296 | // web client on request. 297 | void HttpManagerClass::setBuffer(char *bp) { 298 | bufferPointer = bp; 299 | } 300 | 301 | // Function to be called from the loop() function to do all the 302 | // regular processing related to the class. 303 | void HttpManagerClass::process() { 304 | if (connected) 305 | server.handleClient(); 306 | } 307 | 308 | // Function to display the IP Address of the server if connected 309 | void HttpManagerClass::getIP() { 310 | if (connected){ 311 | Serial.print(F("IP address: ")); 312 | Serial.println(WiFi.localIP()); 313 | } 314 | else { 315 | Serial.println("Not Connected!"); 316 | } 317 | } 318 | 319 | //======================================================================= 320 | // WriteHtmlStatistics writes the last set of statistics to a print stream. 321 | void HttpManagerClass::writeHtmlStatistics(Statistics &lastStats) 322 | { 323 | const char *rowStart = ""; 324 | const char *cellDiv = ""; 325 | const char *rowEnd = ""; 326 | sbHtml.reset(); 327 | sbHtml.print(F( 328 | "" 329 | "" 330 | "" 335 | "" 336 | "")); 337 | sbHtml.print(F("

Signal Attributes

")); 338 | sbHtml.print(F("

Sampled over a ")); 339 | sbHtml.print(lastStats.refreshTime); 340 | sbHtml.print(F("-second period

")); 341 | sbHtml.print(F("")); 342 | sbHtml.print(rowStart); 343 | sbHtml.print(cellDiv); 344 | sbHtml.print(F("Total")); 345 | sbHtml.print(cellDiv); 346 | sbHtml.print(F("0 bit")); 347 | sbHtml.print(cellDiv); 348 | sbHtml.print(F("1 bit")); 349 | sbHtml.print(rowEnd); 350 | 351 | sbHtml.print(rowStart); 352 | sbHtml.print(F("DCC Bit Count")); 353 | sbHtml.print(cellDiv); 354 | sbHtml.print(lastStats.count/2); 355 | sbHtml.print(cellDiv); 356 | sbHtml.print(lastStats.count0/2); 357 | sbHtml.print(cellDiv); 358 | sbHtml.print(lastStats.count1/2); 359 | sbHtml.print(rowEnd); 360 | 361 | sbHtml.print(rowStart); 362 | sbHtml.print(F("Average Length (µs)")); 363 | sbHtml.print(cellDiv); 364 | sbHtml.print(cellDiv); 365 | if (lastStats.count0 > 0) 366 | sbHtml.print((float)lastStats.total0/lastStats.count0, 1); 367 | else 368 | sbHtml.print(F("N/A")); 369 | sbHtml.print(cellDiv); 370 | if (lastStats.count1 > 0) 371 | sbHtml.print((float)lastStats.total1/lastStats.count1, 1); 372 | else 373 | sbHtml.print(F("N/A")); 374 | sbHtml.print(rowEnd); 375 | 376 | sbHtml.print(rowStart); 377 | sbHtml.print(F("Min-Max (µs)")); 378 | sbHtml.print(cellDiv); 379 | sbHtml.print(cellDiv); 380 | if (lastStats.count0 > 0) { 381 | sbHtml.print(lastStats.min0); 382 | sbHtml.print('-'); 383 | sbHtml.print(lastStats.max0); 384 | } else 385 | sbHtml.print(F("N/A")); 386 | sbHtml.print(cellDiv); 387 | if (lastStats.count1 > 0) { 388 | sbHtml.print(lastStats.min1); 389 | sbHtml.print('-'); 390 | sbHtml.print(lastStats.max1); 391 | } else 392 | sbHtml.print(F("N/A")); 393 | sbHtml.print(rowEnd); 394 | 395 | sbHtml.print(rowStart); 396 | sbHtml.print(F("Max delta (µs)")); 397 | sbHtml.print(cellDiv); 398 | sbHtml.print(cellDiv); 399 | if (lastStats.count0 > 0) { 400 | sbHtml.print(F("<")); 401 | sbHtml.print(lastStats.max0BitDelta); 402 | } else 403 | sbHtml.print(F("N/A")); 404 | sbHtml.print(cellDiv); 405 | if (lastStats.count1 > 0) { 406 | sbHtml.print(F("<")); 407 | sbHtml.print(lastStats.max1BitDelta); 408 | } else 409 | sbHtml.print(F("N/A")); 410 | sbHtml.print(rowEnd); 411 | 412 | sbHtml.print(rowStart); 413 | sbHtml.print(F("Glitches")); 414 | sbHtml.print(cellDiv); 415 | sbHtml.print(lastStats.glitchCount); 416 | sbHtml.print(rowEnd); 417 | 418 | sbHtml.print(rowStart); 419 | sbHtml.print(F("Valid Packets Received")); 420 | sbHtml.print(cellDiv); 421 | sbHtml.print(lastStats.packetCount); 422 | sbHtml.print(rowEnd); 423 | 424 | sbHtml.print(rowStart); 425 | sbHtml.print(F("Idle Packets Received")); 426 | sbHtml.print(cellDiv); 427 | sbHtml.print(lastStats.packetCount); 428 | sbHtml.print(rowEnd); 429 | 430 | sbHtml.print(rowStart); 431 | sbHtml.print(F("NMRA out of spec packets")); 432 | sbHtml.print(cellDiv); 433 | sbHtml.print(lastStats.outOfSpecRejectionCount); 434 | sbHtml.print(rowEnd); 435 | 436 | sbHtml.print(rowStart); 437 | sbHtml.print(F("RCN 5ms errors")); 438 | sbHtml.print(cellDiv); 439 | sbHtml.print(lastStats.rcn5msFailCount); 440 | sbHtml.print(rowEnd); 441 | 442 | sbHtml.print(rowStart); 443 | sbHtml.print(F("Checksum errors")); 444 | sbHtml.print(cellDiv); 445 | sbHtml.print(lastStats.checksumError); 446 | sbHtml.print(rowEnd); 447 | 448 | sbHtml.print(rowStart); 449 | sbHtml.print(F("Long packets")); 450 | sbHtml.print(cellDiv); 451 | sbHtml.print(lastStats.countLongPackets); 452 | sbHtml.print(rowEnd); 453 | 454 | sbHtml.print(F("
")); 455 | 456 | sbHtml.print(F("

Half-Bit Count by Length

")); 457 | sbHtml.print(F("")); 458 | sbHtml.print(rowStart); 459 | sbHtml.print(F("Length (µs)")); 460 | sbHtml.print(cellDiv); 461 | sbHtml.print(F("Count (1st Half)")); 462 | sbHtml.print(cellDiv); 463 | sbHtml.print(F("Count (2nd Half)")); 464 | sbHtml.print(rowEnd); 465 | 466 | for (int i=minBitLength; i<=maxBitLength; i++) { 467 | unsigned long c0 = lastStats.countByLength[0][i-minBitLength]; 468 | unsigned long c1 = lastStats.countByLength[1][i-minBitLength]; 469 | if (c0 > 0 || c1 > 0) { 470 | sbHtml.print(rowStart); 471 | if (i == minBitLength) sbHtml.print(F("≤")); 472 | else if (i == maxBitLength) sbHtml.print(F("≥")); 473 | sbHtml.print(i); 474 | sbHtml.print(cellDiv); 475 | sbHtml.print(c0); 476 | sbHtml.print(cellDiv); 477 | sbHtml.print(c1); 478 | sbHtml.print(rowEnd); 479 | } 480 | } 481 | sbHtml.print(F("
")); 482 | 483 | // Append the buffer of decoded packets (plain text). 484 | sbHtml.print(F("

Decoded DCC Packets

")); 485 | sbHtml.println(F("
"));
486 |   sbHtml.println(bufferPointer);
487 |   sbHtml.println(F("
")); 488 | sbHtml.println(F("")); 489 | } 490 | 491 | 492 | // Declare singleton class instance. 493 | HttpManagerClass HttpManager; 494 | 495 | #endif 496 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /DCCInspector-EX.ino: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021 Neil McKechnie 2 | * Parts based on DCC_Sniffer, Ruud Boer, October 2015 3 | * 4 | * This Library is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * This Library is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this software. If not, see 16 | * . 17 | */ 18 | 19 | /////////////////////////////////////////////////////// 20 | // 21 | // Add buttons to web page for modifying options: NMcK Apr 2021 22 | // Regroup functions into separate classes: NMcK Jan 2021 23 | // Move configuration items to Config.h: NMcK Jan 2021 24 | // Add OLED, and web server support on ESP32: NMcK Jan 2021 25 | // Add capture for ESP32; refactor timers: NMcK Jan 2021 26 | // Improve accuracy of timing and time calculations: NMcK Jan 2021 27 | // Add support for compilation for ESP8266 and ESP32: NMcK Jan 2021 28 | // Use ICR for pulse measurements, and display pulse length histogram: NMcK Dec 2020 29 | // Add CPU load figures for the controller: NMcK December 2020 30 | // Count, and optionally filter, edge noise from input: NMcK December 2020 31 | // Display half-bit lengths rather than bit lengths: NMcK December 2020 32 | // Improved comments; moved some strings to flash: NMcK November 2020 33 | // Moved frame construction into interrupt code: NMcK July 2020 34 | // Removed use of AVR timer interrupts: NMcK June 2020 35 | // DCC packet analyze: Ruud Boer, October 2015 36 | // 37 | // The DCC signal is detected on Arduino digital pin 8 (ICP1 on Uno/Nano), 38 | // or pin 49 (ICP4 on Mega), or pin GPIO2 on ESP8266/ESP32. This causes an interrupt, 39 | // and in the interrupt response code the time between interrupts is measured. 40 | // 41 | // Use an opto-isolator between the track signal (~30V p-p) and the 42 | // digital input (0 to 5V or 0 to 3.3V) to prevent burn-out. 43 | // 44 | // Written originally for Uno but also tested on Mega and Nano, 45 | // should work on other architectures if simple options chosen (no USETIMER and 46 | // no USE_DIO2). 47 | // 48 | // Also tested on ESP8266 (NodeMCU and Heltec Kit 8) and ESP32 (Heltec Kit 32). Both of these 49 | // support OLED display and HTTP server on WiFi. See Config.h for configuration options. 50 | // It will decode bits on the input pin which is GPIO2 for ESP8266 (labelled D4 on the NodeMCU) or 51 | // GPIO5 on the ESP32. 52 | // 53 | // The faster clock speeds on the ESP8266/ESP32 mean that interrupt jitter is less, but there is 54 | // still around +/- 4us evident on the ESP8266. Also, the ESP8266 and ESP32, micros() does 55 | // actually give a resolution of 1 microsecond (as opposed to 4us on the Arduino). The ESP32 56 | // gives the best performance and functionality, with its input capture capability alongside the 57 | // OLED/Wifi. 58 | // 59 | // The use of ICPn on the Arduino and ESP32 enables accurate timing to within 1us. The millis() 60 | // function in the Arduino is no better than 10.5us or so accurate (6.5us interrupt jitter caused by the 61 | // Arduino Timer0 interrupts, and 4us timer resolution) which is inadequate for diagnostic purposes. 62 | // 63 | // The selected digital input must have interrupt support, either via 64 | // the level change interrupt (e.g. Arduino pin 2 or 3) or, preferably, input capture interrupt 65 | // (e.g. pin 8 on Arduino Uno, pin 49 on Mega). The ESP8266 does not have input capture functionality 66 | // but any pin may be used for level change interrupt. 67 | // 68 | // The bit decoding is done by measuring the time between successive 69 | // interrupts using the 'micros()' function so should be pretty portable. 70 | // Optionally, it will use a faster 16-bit timer for higher resolution. This is 71 | // the default mode for Uno, Nano and Mega (USETIMER option). 72 | // 73 | // The counter SpareLoopCount is used to see how heavily loaded the processor is. 74 | // With DCC interrupts off, it measures the count. When the interrupts are attached 75 | // it sees how much the count drops. The percent load due to the interrupts is 76 | // the percentage difference between the two figures. 77 | // For example (my measurements on an Uno): 78 | // DCC off, SpareLoopCount=1043042 (over 4 secs) 79 | // DCC on, SpareLoopCount=768830 (over 4 secs) 80 | // CPU Load = (1043042-766830)/1043042*100 = 26% 81 | // 82 | // Loco address 3's speed command is optionally mapped onto a PWM output pin, allowing an 83 | // LED to be used to confirm that a controller is able to send recognisable 84 | // DCC commands. 85 | // 86 | // When outputting decoded DCC packets, duplicate loco speed packets and idle packets encountered 87 | // within a time period will not be logged (as they are sent continuously). However, all 88 | // accessory and loco function packets are displayed, even if repeated. 89 | // 90 | // Set the Serial Monitor Baud Rate to 115200 !! 91 | // 92 | // Keyboard commands that can be sent via Serial Monitor: 93 | // 1 = 1s refresh time 94 | // 2 = 2s 95 | // 3 = 4s (default) 96 | // 4 = 8s 97 | // 5 = 16s 98 | // 6 = 4 DCC packet buffer 99 | // 7 = 8 100 | // 8 = 16 101 | // 9 = 32 (default) 102 | // 0 = 64 103 | // a = show accessory packets toggle 104 | // l = show locomotive packets toggle 105 | // d = show diagnostics toggle 106 | // h = show heartbeat toggle 107 | // b = show half-bit counts by length toggle 108 | // c = show cpu/irc usage in sniffer toggle 109 | // f = input filter toggle 110 | // s = set NMRA compliance strictness (0=none,1=decoder,2=controller) 111 | // i = Display IP Address 112 | // ? = help (show this information) 113 | // 114 | //////////////////////////////////////////////////////// 115 | #include 116 | 117 | // Configurable parameter items now in separate include file. 118 | #include "Config.h" 119 | 120 | //////////////////////////////////////////////////////// 121 | 122 | #if defined(USE_DIO2) && (defined(ARDUINO_UNO_NANO) || defined(ARDUINO_MEGA)) 123 | #define GPIO_PREFER_SPEED 124 | #include 125 | #define digitalWrite(pin, state) digitalWrite2(pin, state) 126 | #define digitalRead(pin) digitalRead2(pin) 127 | #endif 128 | 129 | #ifdef USETIMER 130 | #include "EventTimer.h" 131 | #else 132 | #include "EventTimer_default.h" 133 | #endif 134 | 135 | // Add web server if required. 136 | #if defined(USE_HTTPSERVER) 137 | #include "HttpManager.h" 138 | #endif 139 | 140 | // Include OLED if required. 141 | #if defined(USE_OLED) 142 | #include "OledDisplay.h" 143 | #endif 144 | 145 | #include "StringBuilder.h" 146 | 147 | // Statistics structures and functions. 148 | #include "DCCStatistics.h" 149 | 150 | const int nPackets = 16; // Number of packet buffers 151 | const int pktLength = 8; // Max length+1 in bytes of DCC packet 152 | 153 | // Variables shared by interrupt routine and main loop 154 | volatile byte dccPacket[nPackets][pktLength]; // buffer to hold packets 155 | volatile byte packetsPending = 0; // Count of unprocessed packets 156 | volatile byte activePacket = 157 | 0; // indicate which buffer is currently being filled 158 | volatile bool filterInput = 159 | true; // conditions input to remove transient changes 160 | volatile byte strictMode = 161 | 1; // rejects frames containing out-of-spec bit lengths 162 | 163 | // Variables used by main loop 164 | byte packetHashListSize = 32; // DCC packets checksum buffer size 165 | bool showLoc = true; 166 | bool showAcc = true; 167 | bool showHeartBeat = true; 168 | bool showDiagnostics = true; 169 | bool showBitLengths = false; 170 | bool showCpuStats = false; 171 | 172 | byte inputPacket = 0; // Index of next packet to be analysed in dccPacket array 173 | byte pktByteCount = 0; 174 | int packetHashListCounter = 0; 175 | unsigned int packetHashList[64]; 176 | bool calibrated = false; 177 | unsigned long lastRefresh = 0; 178 | unsigned int inactivityCount = 0; 179 | 180 | // Buffers for decoded packets, used by HTTP and OLED output. 181 | #if defined(USE_HTTPSERVER) 182 | char packetBuffer[5000] = ""; 183 | #elif defined(USE_OLED) 184 | char packetBuffer[400] = ""; 185 | #else 186 | char packetBuffer[1] = ""; 187 | #endif 188 | StringBuilder sbPacketDecode(packetBuffer, sizeof(packetBuffer)); 189 | 190 | // Pre-declare capture function 191 | bool INTERRUPT_SAFE capture(unsigned long halfBitLengthTicks); 192 | 193 | //======================================================================= 194 | // Perform the setup functions for the application. 195 | 196 | void setup() { 197 | Serial.begin(SERIAL_SPEED); 198 | Serial.println(F("---")); 199 | Serial.println(F("DCC Packet Analyze initialising")); 200 | 201 | #ifdef LEDPIN_ACTIVE 202 | pinMode(LEDPIN_ACTIVE, OUTPUT); 203 | #endif 204 | #ifdef LEDPIN_DECODING 205 | pinMode(LEDPIN_DECODING, OUTPUT); 206 | #endif 207 | #ifdef LEDPIN_DECODING 208 | pinMode(LEDPIN_DECODING, OUTPUT); 209 | #endif 210 | #ifdef LEDPIN_FAULT 211 | pinMode(LEDPIN_FAULT, OUTPUT); 212 | #endif 213 | 214 | // Enable pullup in case there's no external pullup resistor. 215 | // External resistor is preferred as it can be lower, so 216 | // improve the switching speed of the Optocoupler. 217 | pinMode(INPUTPIN, INPUT_PULLUP); 218 | Serial.print("INPUTPIN="); 219 | Serial.println(INPUTPIN); 220 | 221 | if (!EventTimer.inputCaptureMode()) { 222 | // Output health warning... 223 | Serial.println( 224 | F("\r\n** WARNING Measurements will occasionally be out up to ~10us " 225 | "either way **")); 226 | Serial.println( 227 | F("** because of inaccuracies in the micros() function. " 228 | " **")); 229 | } 230 | 231 | #if defined(USE_OLED) 232 | // Start OLED display (if required). 233 | OledDisplay.begin(SDA_OLED, SCL_OLED); 234 | #if defined(ARDUINO_HELTEC_WIFI_KIT_32) 235 | // Read battery voltage from pin GPIO37 236 | // The battery measurement is enabled via pin GPIO21 237 | digitalWrite(21, 0); 238 | analogSetWidth(12); // 12 bits = 0-4095 239 | analogSetPinAttenuation(37, ADC_11db); 240 | adcAttachPin(37); 241 | 242 | uint32_t batValue = analogRead(37); 243 | // An input value of around 2600 is obtained for a 244 | // a measured battery voltage of 4100mV. 245 | uint16_t batMV = batValue * 41 / 26; 246 | if (batMV < 3400) OledDisplay.append("Battery Low"); 247 | digitalWrite(21, 1); // Disable battery monitor 248 | 249 | #endif 250 | OledDisplay.append("Initialising.."); 251 | #endif 252 | 253 | // Start WiFi and HTTP server (if required). 254 | #if defined(USE_HTTPSERVER) 255 | HttpManager.begin(WIFI_SSID, WIFI_PASSWORD, DNSNAME); 256 | #endif 257 | 258 | // Set time for first output of statistics during calibration 259 | lastRefresh = millis(); 260 | DCCStatistics.setRefreshTime(1); // Finish calibrating after 1 second 261 | 262 | Serial.print(F("Calibrating... ")); 263 | } 264 | 265 | //======================================================================= 266 | // Main program loop. 267 | 268 | void loop() { 269 | bool somethingDone = false; 270 | 271 | // The first bit runs one second after setup, and completes the 272 | // initialisation. 273 | if (!calibrated && millis() >= lastRefresh + 1000) { 274 | // Calibration cycle done, record the details. 275 | Serial.println(F("done.")); 276 | calibrated = true; 277 | 278 | // Read (and discard) stats, then clear them. 279 | DCCStatistics.getAndClearStats(); 280 | clearHashList(); 281 | 282 | // Start recording data from DCC. 283 | if (!EventTimer.begin(INPUTPIN, capture)) { 284 | Serial.println(F("Unable to start EventTimer, check configured pin")); 285 | while (1) 286 | ; 287 | } 288 | 289 | DCCStatistics.setRefreshTime(4); 290 | Serial.print(F("Updates every ")); 291 | Serial.print(DCCStatistics.getRefreshTime()); 292 | Serial.println(F(" seconds")); 293 | Serial.println(F("---")); 294 | 295 | lastRefresh = millis(); 296 | 297 | } else if (millis() >= 298 | lastRefresh + 299 | (unsigned long)DCCStatistics.getRefreshTime() * 1000) { 300 | // The next part runs once every 'refresh time' seconds. It primarily 301 | // captures, resets and 302 | // outputs the statistics. 303 | 304 | if (showHeartBeat) Serial.println('-'); 305 | 306 | // Snapshot and clear statistics 307 | Statistics stats = DCCStatistics.getAndClearStats(); 308 | clearHashList(); 309 | 310 | // Print DCC Statistics to the serial USB output. 311 | if (showDiagnostics) { 312 | DCCStatistics.writeFullStatistics(stats, showCpuStats, showBitLengths); 313 | Serial.println("--"); 314 | } 315 | 316 | // Output short version of DCC statistics to a buffer 317 | // for use by OLED 318 | #if defined(USE_OLED) 319 | OledDisplay.writeShortStatistics(stats); 320 | OledDisplay.append(sbPacketDecode.getString()); // Append decoded packets 321 | // Update OLED 322 | OledDisplay.refresh(); 323 | #endif 324 | 325 | // Output full stats for HTTPServer to use 326 | #if defined(USE_HTTPSERVER) 327 | HttpManager.setBuffer(sbPacketDecode.getString()); 328 | HttpManager.writeHtmlStatistics(stats); 329 | #endif 330 | 331 | sbPacketDecode.reset(); // Empty decoded packet list. 332 | 333 | #if defined(ESP32) 334 | // Check if time to go to sleep on ESP32 335 | inactivityCount += DCCStatistics.getRefreshTime(); 336 | if (inactivityCount > 120) { 337 | // Go to sleep after 2 minutes of inactivity. 338 | #if defined(USE_OLED) 339 | OledDisplay.reset(); 340 | OledDisplay.append("Going to sleep.."); 341 | #endif 342 | Serial.println(F("*** Inactivity detected -- going to sleep ***")); 343 | delay(5000); 344 | #if defined(ARDUINO_HELTEC_WIFI_KIT_32) 345 | // Turn off WiFi 346 | WiFi.disconnect(true); 347 | // Turn off Vext power to screen on Heltec Kit 32 V2 348 | pinMode(21, OUTPUT); 349 | digitalWrite(21, 1); 350 | #endif 351 | esp_deep_sleep_start(); 352 | } 353 | #endif 354 | 355 | lastRefresh = millis(); 356 | somethingDone = true; 357 | } 358 | 359 | // Check for DCC packets - if found, analyse and display them 360 | if (processDCC(Serial)) { 361 | somethingDone = true; 362 | inactivityCount = 0; 363 | } 364 | 365 | // Check for commands received over the USB serial connection. 366 | if (processCommands()) { 367 | somethingDone = true; 368 | inactivityCount = 0; 369 | } 370 | 371 | #if defined(USE_OLED) 372 | OledDisplay.checkButton(); 373 | #endif 374 | 375 | // Increment CPU loop counter. This is done if nothing else was. 376 | // If the counter never gets incremented, it means that the 377 | // CPU is fully loaded doing other things and has no spare time. 378 | if (!somethingDone) DCCStatistics.updateLoopCount(); 379 | 380 | #if defined(USE_HTTPSERVER) 381 | HttpManager.process(); 382 | #endif 383 | 384 | UpdateLED(); 385 | } 386 | 387 | //======================================================================= 388 | // Function invoked (from interrupt handler) on change of state of INPUTPIN. 389 | // It measures the time between successive changes (half-cycle of DCC 390 | // signal). Depending on the value, it decodes 0 or a 1 for alternate 391 | // half-cycles. A 0 half-bit is nominally 100us per half-cycle (NMRA says 392 | // 90-10000us) and a 1 half-bit is nominally 58us (52-64us). We treat a 393 | // half-bit duration < 80us as a '1' half-bit, and a duration >= 80us as a '0' 394 | // half-bit. Prologue and framing bits are detected and stripped, and data 395 | // bytes are then stored in the packet queue for processing by the main loop. 396 | // 397 | bool INTERRUPT_SAFE capture(unsigned long halfBitLengthTicks) { 398 | static byte preambleOneCount = 0; 399 | static boolean preambleFound = false; 400 | static int newByte = 401 | 0; // Accumulator for input bits until complete byte found. 402 | static int inputBitCount = 0; // Number of bits read in current newByte. 403 | static int inputByteNumber = 404 | 0; // Number of bytes read into active dccPacket buffer so far 405 | static byte interruptCount = 0; 406 | static byte previousBitValue = 0, previousDiginState = 0; 407 | static unsigned int previousHalfBitLengthTicks = 0; 408 | static byte altbit = 0; // 0 for first half-bit and 1 for second. 409 | byte bitValue; 410 | 411 | // The most critical parts are done first - read state of digital input. 412 | byte diginState = digitalRead(INPUTPIN); 413 | 414 | // Set a high bound on the half bit length 415 | if (halfBitLengthTicks > 1200 * TICKSPERMICROSEC) 416 | halfBitLengthTicks = 1200 * TICKSPERMICROSEC; // microseconds. 417 | 418 | // Calculate time between interrupts in microseconds. 419 | unsigned int interruptInterval = halfBitLengthTicks / TICKSPERMICROSEC; 420 | 421 | // Precondition input? 422 | if (filterInput) { 423 | // Check that the digital input has actually changed since last interrupt, 424 | // and that the gap between interrupts is realistic. 425 | if (interruptCount > 0 && 426 | (diginState == previousDiginState || interruptInterval <= 3)) { 427 | // No change in digital, or it was fleeting. Ignore. 428 | DCCStatistics.recordGlitch(); 429 | return false; // reject interrupt 430 | } 431 | } 432 | 433 | // If we get here, the interrupt looks valid, i.e. the digital input really 434 | // did change its state more than 3us after its last change. Calculate 435 | // difference between current bit half and preceding one, rounding up to next 436 | // microsecond. This will only be recorded on alternate half-bits, i.e. where 437 | // the previous and current half-bit make a complete bit. 438 | long deltaTicks = halfBitLengthTicks - previousHalfBitLengthTicks; 439 | if (deltaTicks < 0) deltaTicks = -deltaTicks; 440 | unsigned int delta = (deltaTicks + TICKSPERMICROSEC - 1) / TICKSPERMICROSEC; 441 | 442 | // Check length of half-bit 443 | if (interruptInterval < 80) 444 | bitValue = 1; 445 | else 446 | bitValue = 0; 447 | 448 | // Record input state and timer values ready for next interrupt 449 | previousDiginState = diginState; 450 | previousHalfBitLengthTicks = halfBitLengthTicks; 451 | 452 | // If first or second interrupt, then exit as the previous state is 453 | // incomplete. 454 | if (interruptCount < 2) { 455 | interruptCount++; 456 | previousBitValue = bitValue; 457 | return true; 458 | } 459 | 460 | #ifdef LEDPIN_ACTIVE 461 | digitalWrite(LEDPIN_ACTIVE, 1); 462 | #endif 463 | 464 | // Check if we're on the first or second half of the bit. 465 | if (bitValue != previousBitValue) { 466 | // First half of new bit received 467 | altbit = false; 468 | } else { 469 | // Toggle for alternate half-bits 470 | altbit = !altbit; 471 | } 472 | previousBitValue = bitValue; 473 | 474 | // Update statistics 475 | DCCStatistics.recordHalfBit(altbit, bitValue, interruptInterval, delta); 476 | 477 | // Store interrupt interval for use on next interrupt. 478 | previousHalfBitLengthTicks = halfBitLengthTicks; 479 | 480 | // If this is the second half-bit then we've got a whole bit!! 481 | if (altbit) { 482 | bool rejectBit = false; 483 | if (strictMode == 2) { 484 | // Validate bit lengths against NMRA spec for controllers 485 | if (bitValue == 0) { 486 | if (interruptInterval < 95 || interruptInterval > 9900) { 487 | rejectBit = true; 488 | } 489 | } else { 490 | if (interruptInterval < 55 || interruptInterval > 61 || delta > 3) { 491 | rejectBit = true; 492 | } 493 | } 494 | } else if (strictMode == 1) { 495 | // Validate bit lengths against NMRA spec for decoders. 496 | if (bitValue == 0) { 497 | if (interruptInterval < 90 || interruptInterval > 10000) { 498 | rejectBit = true; 499 | } 500 | } else { 501 | if (interruptInterval < 52 || interruptInterval > 64 || delta > 6) { 502 | rejectBit = true; 503 | } 504 | } 505 | } 506 | // Record error only if we're in a packet (preamble has been read). 507 | if (rejectBit && preambleFound) { 508 | DCCStatistics.recordOutOfSpecRejection(); 509 | // Search for next packet 510 | preambleFound = 0; 511 | preambleOneCount = 0; 512 | } 513 | 514 | // Now we've got a bit, process it. The message comprises the following: 515 | // Preamble: 10 or more '1' bits followed by a '0' start bit. 516 | // Groups of 9 bits each containing data byte of 8 bits, followed by a 517 | // '0' bit (if message not yet finished), or a '1' bit (if the byte is 518 | // the last byte of the message, i.e. the checksum). 519 | // 520 | if (!preambleFound) { 521 | if (bitValue == 1) { 522 | // Reading preamble perhaps... 523 | preambleOneCount++; 524 | } else if (preambleOneCount < 10) { // and bitValue==0) 525 | // Preamble not yet found, but zero bit encountered. Restart preable 526 | // count. 527 | preambleOneCount = 0; 528 | } else { // preambleOneCount >= 10 and bitValue==0 529 | // Start bit found at end of preamble, so prepare to process data. 530 | preambleFound = true; 531 | newByte = 0; 532 | inputBitCount = 0; 533 | inputByteNumber = 0; 534 | } 535 | } else { // Preamble previously found, so this is a message bit 536 | if (packetsPending == nPackets) { 537 | // Previous DCC packets haven't been processed by the main loop, 538 | // so there is no buffer for the incoming message. 539 | // Discard incoming message and scan for another preamble. 540 | preambleFound = false; 541 | preambleOneCount = 0; 542 | 543 | // Record this event in a counter. 544 | DCCStatistics.recordLostPacket(); 545 | 546 | } else { 547 | // Preamble read, packet buffer available, so message bit can be stored! 548 | if (inputBitCount == 8) { // Byte previously completed, so this bit is 549 | // the interbyte marker 550 | if (bitValue == 0) { // Interbyte marker is zero, so prepare for next 551 | // byte of data 552 | inputBitCount = 0; 553 | } else { // one-bit found, marks end of packet 554 | // End of packet found 555 | dccPacket[activePacket][0] = 556 | inputByteNumber; // save number of bytes 557 | packetsPending++; // flag that packet is ready for processing 558 | if (++activePacket >= nPackets) 559 | activePacket = 0; // move to next packet buffer 560 | preambleFound = false; // scan for another preamble 561 | preambleOneCount = 562 | 1; // allow the current bit to be counted in the preamble. 563 | } 564 | } else { // Reading packet data at this point. 565 | // Append received bit to the current new byte. 566 | newByte = (newByte << 1) | bitValue; 567 | if (++inputBitCount == 8) { // Completed byte, save byte (if room) 568 | if (inputByteNumber < pktLength - 1) 569 | dccPacket[activePacket][++inputByteNumber] = newByte; 570 | else { // packet has filled buffer so no more bits can be stored! 571 | packetsPending++; // flag that packet is ready for processing 572 | if (++activePacket >= nPackets) 573 | activePacket = 0; // move to next packet buffer 574 | preambleFound = false; // scan for another preamble 575 | preambleOneCount = 0; 576 | // Record this event in a counter. 577 | DCCStatistics.recordLongPacket(); 578 | } 579 | newByte = 0; 580 | } 581 | } 582 | } 583 | } 584 | } 585 | 586 | #ifdef LEDPIN_ACTIVE 587 | // Turn out ACTIVE LED. 588 | digitalWrite(LEDPIN_ACTIVE, 0); 589 | #endif 590 | 591 | // Calculate time taken in interrupt code between the measured time of event 592 | // to POINTB. 593 | 594 | unsigned int interruptDuration = 595 | EventTimer.elapsedTicksSinceLastEvent() / TICKSPERMICROSEC; // POINTB 596 | 597 | // Assume that there are about 25 cycles of instructions in this function that 598 | // are not measured, and that the prologue in dispatching the function (saving 599 | // registers etc) is around 51 cycles and the epilogue (restoring registers 600 | // etc) is around 35 cycles. This adds a further (51+25+35)/16MHz=6.9us to 601 | // the calculation. See 602 | // https://billgrundmann.wordpress.com/2009/03/02/the-overhead-of-arduino-interrupts/. 603 | // However, if the Input Capture mode is used, then this will be much smaller. 604 | // So ignore it. 605 | // interruptDuration += 7; 606 | 607 | // Record result 608 | DCCStatistics.recordInterruptHandlerTime(interruptDuration); 609 | 610 | return true; // Accept interrupt. 611 | } 612 | 613 | //======================================================================= 614 | // Connect the scan routine to the interrupt. It will execute on 615 | // all changes (0->1 and 1->0). 616 | 617 | void beginBitDetection() { EventTimer.begin(INPUTPIN, capture); } 618 | 619 | //======================================================================= 620 | // PrintPacketBits prints the raw DCC packet contents to the 621 | // nominated Print stream (e.g. Serial). 622 | 623 | void printPacketBits(Print &output, int index) { 624 | output.print(' '); 625 | for (byte i = 1; i < dccPacket[index][0]; i++) { 626 | output.print(' '); 627 | byte b = dccPacket[index][i]; 628 | for (int bit = 0; bit < 8; bit++) { 629 | output.print(b & 0x80 ? '1' : '0'); 630 | b <<= 1; 631 | } 632 | } 633 | } 634 | 635 | //======================================================================= 636 | // ClearDCCData clears the contents of the packetHashList array and resets 637 | // the statistics. 638 | // The packetHashList array normally contains the checksums of received 639 | // DCC packets, and is used to suppress the decoding of repeated packets. 640 | 641 | void clearHashList() { 642 | for (byte n = 0; n < packetHashListSize; n++) packetHashList[n] = 0; 643 | packetHashListCounter = 0; 644 | } 645 | 646 | //======================================================================= 647 | // UpdateLED is called in the main loop to set/reset the LED fault indication 648 | // in the event of a fault being detected within the sample period. 649 | 650 | void UpdateLED() { 651 | #ifdef LEDPIN_FAULT 652 | static bool ledLit = false; 653 | if (DCCStatistics.faultPresent()) { 654 | if (!ledLit) { 655 | digitalWrite(LEDPIN_FAULT, 1); 656 | ledLit = true; 657 | } 658 | } else { 659 | if (ledLit) { 660 | digitalWrite(LEDPIN_FAULT, 0); 661 | ledLit = false; 662 | } 663 | } 664 | #endif 665 | } 666 | 667 | //======================================================================= 668 | // Validate received packet and pass to decoder. 669 | // Return false if nothing done. 670 | 671 | bool processDCC(Print &output) { 672 | byte isDifferentPacket = 0; 673 | 674 | if (!packetsPending) { 675 | return false; 676 | } 677 | 678 | pktByteCount = dccPacket[inputPacket][0]; 679 | // Check packet isn't empty 680 | if (pktByteCount > 0) { 681 | // Calculate and verify checksum 682 | byte checksum = 0; 683 | for (byte n = 1; n <= pktByteCount; n++) 684 | checksum ^= dccPacket[inputPacket][n]; 685 | if (checksum) { // Result should be zero, if not it's an error! 686 | DCCStatistics.recordChecksumError(); 687 | } else { 688 | // There is a new packet with a correct checksum 689 | #ifdef LEDPIN_DECODING 690 | digitalWrite(LEDPIN_DECODING, 1); 691 | #endif 692 | static unsigned int lastLocoPacket=0; 693 | if (dccPacket[inputPacket][1] == 0B11111111) { 694 | DCCStatistics.recordIdlePacket(); 695 | lastLocoPacket=0; 696 | } 697 | else { 698 | // check for repeated loco packet without intervening idle or other packet 699 | unsigned int loco=0; 700 | if ((dccPacket[inputPacket][1] & 0x80) == 0x00 ) loco=dccPacket[inputPacket][1]; // short loco address 701 | else if ((dccPacket[inputPacket][1] & 0xc0) == 0xC0 ) 702 | loco=((dccPacket[inputPacket][1] & 0x3F) <<8) | dccPacket[inputPacket][2]; // long loco address 703 | if (loco && (loco==lastLocoPacket)) DCCStatistics.recordrcn5msFailure(); 704 | lastLocoPacket=loco; 705 | } 706 | 707 | // Hooray - we've got a packet to decode, with no errors! 708 | DCCStatistics.recordPacket(); 709 | 710 | 711 | // Generate a cyclic hash based on the packet contents for checking if 712 | // we've seen a similar packet before. 713 | isDifferentPacket = true; 714 | unsigned int hash = 715 | dccPacket[inputPacket][pktByteCount]; // calculate checksum 716 | for (byte n = 1; n < pktByteCount; n++) 717 | hash = ((hash << 5) | (hash >> 11)) ^ dccPacket[inputPacket][n]; 718 | 719 | // Check if packet's checksum is already in the list. 720 | for (byte n = 0; n < packetHashListSize; n++) { 721 | if (hash == packetHashList[n]) isDifferentPacket = false; 722 | } 723 | 724 | if (isDifferentPacket) { 725 | packetHashList[packetHashListCounter++] = 726 | hash; // add new packet's hash to the list 727 | if (packetHashListCounter >= packetHashListSize) 728 | packetHashListCounter = 0; 729 | 730 | DecodePacket(output, inputPacket, isDifferentPacket); 731 | } 732 | 733 | // Optional test led whose brightness depends on loco speed setting. 734 | #ifdef LEDPIN_LOCOSPEED 735 | // Output to LED 736 | if (dccPacket[inputPacket][1] == 0B00000011 && 737 | dccPacket[inputPacket][2] == 0B00111111) { 738 | analogWrite(LEDPIN_LOCOSPEED, 739 | map(dccPacket[inputPacket][3] & 0B01111111, 0, 127, 0, 255)); 740 | } 741 | #endif 742 | 743 | #ifdef LEDPIN_DECODING 744 | digitalWrite(LEDPIN_DECODING, 0); 745 | #endif 746 | } 747 | } 748 | packetsPending--; // Free packet buffer. 749 | if (++inputPacket >= nPackets) inputPacket = 0; 750 | 751 | return true; 752 | } 753 | 754 | //======================================================================= 755 | // Read data from the dccPacket structure and decode into 756 | // textual representation. Send results out over the USB serial 757 | // connection. 758 | 759 | void DecodePacket(Print &output, int inputPacket, bool isDifferentPacket) { 760 | byte instrByte1; 761 | byte decoderType; // 0=Loc, 1=Acc 762 | unsigned int decoderAddress; 763 | byte speed; 764 | bool outputDecodedData = false; 765 | 766 | char tempBuffer[100]; 767 | StringBuilder sbTemp(tempBuffer, sizeof(tempBuffer)); 768 | 769 | // First determine the decoder type and address. 770 | if (dccPacket[inputPacket][1] == 0B11111111) { // Idle packet 771 | if (isDifferentPacket) { 772 | sbTemp.print(F("Idle ")); 773 | outputDecodedData = true; 774 | } 775 | decoderType = 255; 776 | } else if (!bitRead(dccPacket[inputPacket][1], 777 | 7)) { // bit7=0 -> Loc Decoder Short Address 778 | decoderAddress = dccPacket[inputPacket][1]; 779 | instrByte1 = dccPacket[inputPacket][2]; 780 | decoderType = 0; 781 | } else { 782 | if (bitRead(dccPacket[inputPacket][1], 783 | 6)) { // bit7=1 AND bit6=1 -> Loc Decoder Long Address 784 | decoderAddress = 256 * (dccPacket[inputPacket][1] & 0B00111111) + 785 | dccPacket[inputPacket][2]; 786 | instrByte1 = dccPacket[inputPacket][3]; 787 | decoderType = 0; 788 | } else { // bit7=1 AND bit6=0 -> Accessory Decoder 789 | decoderAddress = dccPacket[inputPacket][1] & 0B00111111; 790 | instrByte1 = dccPacket[inputPacket][2]; 791 | decoderType = 1; 792 | } 793 | } 794 | 795 | // Handle decoder type 0 and 1 separately. 796 | if (decoderType == 1) { // Accessory Basic 797 | if (showAcc) { 798 | if (instrByte1 & 0B10000000) { // Basic Accessory 799 | decoderAddress = (((~instrByte1) & 0B01110000) << 2) + decoderAddress; 800 | byte port = (instrByte1 & 0B00000110) >> 1; 801 | sbTemp.print(F("Acc ")); 802 | sbTemp.print((decoderAddress - 1) * 4 + port + 1); 803 | sbTemp.print(' '); 804 | sbTemp.print(decoderAddress); 805 | sbTemp.print(F(":")); 806 | sbTemp.print(port); 807 | sbTemp.print(' '); 808 | sbTemp.print(bitRead(instrByte1, 3)); 809 | if (bitRead(instrByte1, 0)) 810 | sbTemp.print(F(" On")); 811 | else 812 | sbTemp.print(F(" Off")); 813 | } else { // Accessory Extended NMRA spec is not clear about address and 814 | // instruction format !!! 815 | sbTemp.print(F("Acc Ext ")); 816 | decoderAddress = (decoderAddress << 5) + 817 | ((instrByte1 & 0B01110000) >> 2) + 818 | ((instrByte1 & 0B00000110) >> 1); 819 | sbTemp.print(decoderAddress); 820 | sbTemp.print(F(" Asp ")); 821 | sbTemp.print(dccPacket[inputPacket][3], BIN); 822 | } 823 | outputDecodedData = true; 824 | } 825 | } else if (decoderType == 0) { // Loco / Multi Function Decoder 826 | if (showLoc && isDifferentPacket) { 827 | sbTemp.print(F("Loc ")); 828 | sbTemp.print(decoderAddress); 829 | byte instructionType = instrByte1 >> 5; 830 | byte value; 831 | switch (instructionType) { 832 | case 0: 833 | sbTemp.print(F(" Control")); 834 | break; 835 | 836 | case 1: // Advanced Operations 837 | if (instrByte1 == 0B00111111) { // 128 speed steps 838 | if (bitRead(dccPacket[inputPacket][pktByteCount - 1], 7)) 839 | sbTemp.print(F(" Fwd128 ")); 840 | else 841 | sbTemp.print(F(" Rev128 ")); 842 | byte speed = dccPacket[inputPacket][pktByteCount - 1] & 0B01111111; 843 | if (!speed) 844 | sbTemp.print(F("Stop")); 845 | else if (speed == 1) 846 | sbTemp.print(F("Estop")); 847 | else 848 | sbTemp.print(speed - 1); 849 | } else if (instrByte1 == 0B00111110) { // Speed Restriction 850 | if (bitRead(dccPacket[inputPacket][pktByteCount - 1], 7)) 851 | sbTemp.print(F(" On ")); 852 | else 853 | sbTemp.print(F(" Off ")); 854 | sbTemp.print(dccPacket[inputPacket][pktByteCount - 1] & 0B01111111); 855 | } 856 | break; 857 | 858 | case 2: // Reverse speed step 859 | speed = ((instrByte1 & 0B00001111) << 1) - 3 + bitRead(instrByte1, 4); 860 | if (speed == 253 || speed == 254) 861 | sbTemp.print(F(" Stop")); 862 | else if (speed == 255 || speed == 0) 863 | sbTemp.print(F(" EStop")); 864 | else { 865 | sbTemp.print(F(" Rev28 ")); 866 | sbTemp.print(speed); 867 | } 868 | break; 869 | 870 | case 3: // Forward speed step 871 | speed = ((instrByte1 & 0B00001111) << 1) - 3 + bitRead(instrByte1, 4); 872 | if (speed == 253 || speed == 254) 873 | sbTemp.print(F(" Stop")); 874 | else if (speed == 255 || speed == 0) 875 | sbTemp.print(F(" EStop")); 876 | else { 877 | sbTemp.print(F(" Fwd28 ")); 878 | sbTemp.print(speed); 879 | } 880 | break; 881 | 882 | case 4: // Loc Function L-4-3-2-1 883 | sbTemp.print(F(" L F4-F1 ")); 884 | sbTemp.print(instrByte1 & 0B00011111, BIN); 885 | break; 886 | 887 | case 5: // Loc Function 8-7-6-5 888 | if (bitRead(instrByte1, 4)) { 889 | sbTemp.print(F(" F8-F5 ")); 890 | sbTemp.print(instrByte1 & 0B00001111, BIN); 891 | } else { // Loc Function 12-11-10-9 892 | sbTemp.print(F(" F12-F9 ")); 893 | sbTemp.print(instrByte1 & 0B00001111, BIN); 894 | } 895 | break; 896 | 897 | case 6: // Future Expansions 898 | switch (instrByte1 & 0B00011111) { 899 | case 0: // Binary State Control Instruction long form 900 | sbTemp.print(F(" BinSLong ")); 901 | sbTemp.print( 902 | 128 * ((uint16_t)dccPacket[inputPacket][pktByteCount - 1]) + 903 | (dccPacket[inputPacket][pktByteCount - 2] & 127)); 904 | if bitRead (dccPacket[inputPacket][pktByteCount - 2], 7) 905 | sbTemp.print(F(" On")); 906 | else 907 | sbTemp.print(F(" Off")); 908 | break; 909 | case 0B00011101: // Binary State Control 910 | sbTemp.print(F(" BinShort ")); 911 | sbTemp.print(dccPacket[inputPacket][pktByteCount - 1] & 912 | 0B01111111); 913 | if bitRead (dccPacket[inputPacket][pktByteCount - 1], 7) 914 | sbTemp.print(F(" On")); 915 | else 916 | sbTemp.print(F(" Off")); 917 | break; 918 | case 0B00011110: // F13-F20 Function Control 919 | sbTemp.print(F(" F20-F13 ")); 920 | sbTemp.print(dccPacket[inputPacket][pktByteCount - 1], BIN); 921 | break; 922 | case 0B00011111: // F21-F28 Function Control 923 | sbTemp.print(F(" F28-F21 ")); 924 | sbTemp.print(dccPacket[inputPacket][pktByteCount - 1], BIN); 925 | break; 926 | case 0B00011000: // F29-F36 Function Control 927 | sbTemp.print(F(" F36-F29 ")); 928 | sbTemp.print(dccPacket[inputPacket][pktByteCount - 1], BIN); 929 | break; 930 | case 0B00011001: // F37-F44 Function Control 931 | sbTemp.print(F(" F44-F37 ")); 932 | sbTemp.print(dccPacket[inputPacket][pktByteCount - 1], BIN); 933 | break; 934 | case 0B00011010: // F45-F52 Function Control 935 | sbTemp.print(F(" F52-F45 ")); 936 | sbTemp.print(dccPacket[inputPacket][pktByteCount - 1], BIN); 937 | break; 938 | case 0B00011011: // F53-F60 Function Control 939 | sbTemp.print(F(" F60-F53 ")); 940 | sbTemp.print(dccPacket[inputPacket][pktByteCount - 1], BIN); 941 | break; 942 | case 0B00011100: // F61-F68 Function Control 943 | sbTemp.print(F(" F68-F61 ")); 944 | sbTemp.print(dccPacket[inputPacket][pktByteCount - 1], BIN); 945 | break; 946 | default: 947 | sbTemp.print(F(" Unknown")); 948 | break; 949 | } 950 | break; 951 | 952 | case 7: 953 | sbTemp.print(F(" CV ")); 954 | value = dccPacket[inputPacket][pktByteCount - 1]; 955 | if (instrByte1 & 0B00010000) { // CV Short Form 956 | byte cvType = instrByte1 & 0B00001111; 957 | switch (cvType) { 958 | case 0B00000010: 959 | sbTemp.print(F("23 ")); 960 | sbTemp.print(value); 961 | break; 962 | case 0B00000011: 963 | sbTemp.print(F("24 ")); 964 | sbTemp.print(value); 965 | break; 966 | case 0B00001001: 967 | sbTemp.print(F("Lock ")); 968 | sbTemp.print(value); 969 | break; 970 | default: 971 | sbTemp.print(F("Unknown")); 972 | sbTemp.print(' '); 973 | sbTemp.print(value); 974 | break; 975 | } 976 | } else { // CV Long Form 977 | int cvAddress = 256 * (instrByte1 & 0B00000011) + 978 | dccPacket[inputPacket][pktByteCount - 2] + 1; 979 | sbTemp.print(cvAddress); 980 | sbTemp.print(' '); 981 | switch (instrByte1 & 0B00001100) { 982 | case 0B00000100: // Verify Byte 983 | sbTemp.print(F("Verify ")); 984 | sbTemp.print(value); 985 | break; 986 | case 0B00001100: // Write Byte 987 | sbTemp.print(F("Write ")); 988 | sbTemp.print(value); 989 | break; 990 | case 0B00001000: // Bit Write 991 | sbTemp.print(F("Bit ")); 992 | if (value & 0B00010000) 993 | sbTemp.print(F("Vrfy ")); 994 | else 995 | sbTemp.print(F("Wrt ")); 996 | sbTemp.print(value & 0B00000111); 997 | sbTemp.print(' '); 998 | sbTemp.print((value & 0B00001000) >> 3); 999 | break; 1000 | default: 1001 | sbTemp.print(F("Unknown")); 1002 | break; 1003 | } 1004 | } 1005 | break; 1006 | 1007 | default: 1008 | sbTemp.print(F(" Unknown")); 1009 | break; 1010 | } 1011 | outputDecodedData = true; 1012 | } 1013 | } 1014 | 1015 | if (outputDecodedData) { 1016 | // If not using HTTP, append decoded packet to packet buffer 1017 | // as-is (without binary dump). It's all that fits on OLED. 1018 | #if !defined(USE_HTTPSERVER) 1019 | sbPacketDecode.println(sbTemp.getString()); 1020 | sbPacketDecode.end(); 1021 | #endif 1022 | 1023 | // Append binary dump for Serial and HTTP 1024 | sbTemp.setPos(21); 1025 | sbTemp.print(' '); 1026 | printPacketBits(sbTemp, inputPacket); 1027 | sbTemp.end(); // terminate string in buffer. 1028 | 1029 | // Get reference to buffer containing results. 1030 | char *decodedPacket = sbTemp.getString(); 1031 | 1032 | #if defined(USE_HTTPSERVER) 1033 | // Append decoded packet data and binary dump to string buffer. 1034 | sbPacketDecode.println(decodedPacket); 1035 | sbPacketDecode.end(); 1036 | #endif 1037 | 1038 | // Also print to USB serial, and dump packet in hex. 1039 | output.println(decodedPacket); 1040 | } 1041 | } 1042 | 1043 | //======================================================================= 1044 | // Process commands sent over the USB serial connection. 1045 | // Return false if nothing done. 1046 | 1047 | bool processCommands() { 1048 | if (Serial.available()) { 1049 | switch (Serial.read()) { 1050 | case 49: 1051 | Serial.println(F("Refresh Time = 1s")); 1052 | DCCStatistics.setRefreshTime(1); 1053 | break; 1054 | case 50: 1055 | Serial.println(F("Refresh Time = 2s")); 1056 | DCCStatistics.setRefreshTime(2); 1057 | break; 1058 | case 51: 1059 | Serial.println(F("Refresh Time = 4s")); 1060 | DCCStatistics.setRefreshTime(4); 1061 | break; 1062 | case 52: 1063 | Serial.println(F("Refresh Time = 8s")); 1064 | DCCStatistics.setRefreshTime(8); 1065 | break; 1066 | case 53: 1067 | Serial.println(F("Refresh Time = 16s")); 1068 | DCCStatistics.setRefreshTime(16); 1069 | break; 1070 | case 54: 1071 | Serial.println(F("Buffer Size = 4")); 1072 | packetHashListSize = 2; 1073 | break; 1074 | case 55: 1075 | Serial.println(F("Buffer Size = 8")); 1076 | packetHashListSize = 8; 1077 | break; 1078 | case 56: 1079 | Serial.println(F("Buffer Size = 16")); 1080 | packetHashListSize = 16; 1081 | break; 1082 | case 57: 1083 | Serial.println(F("Buffer Size = 32")); 1084 | packetHashListSize = 32; 1085 | break; 1086 | case 48: 1087 | Serial.println(F("Buffer Size = 64")); 1088 | packetHashListSize = 64; 1089 | break; 1090 | case 'a': 1091 | case 'A': 1092 | showAcc = !showAcc; 1093 | Serial.print(F("show accessory packets = ")); 1094 | Serial.println(showAcc); 1095 | break; 1096 | case 'l': 1097 | case 'L': 1098 | showLoc = !showLoc; 1099 | Serial.print(F("show loco packets = ")); 1100 | Serial.println(showLoc); 1101 | break; 1102 | case 'h': 1103 | case 'H': 1104 | showHeartBeat = !showHeartBeat; 1105 | Serial.print(F("show heartbeat = ")); 1106 | Serial.println(showHeartBeat); 1107 | break; 1108 | case 'd': 1109 | case 'D': 1110 | showDiagnostics = !showDiagnostics; 1111 | Serial.print(F("show diagnostics = ")); 1112 | Serial.println(showDiagnostics); 1113 | break; 1114 | case 'f': 1115 | case 'F': 1116 | filterInput = !filterInput; 1117 | Serial.print(F("filter input = ")); 1118 | Serial.println(filterInput); 1119 | break; 1120 | case 's': 1121 | case 'S': 1122 | strictMode = (strictMode + 1) % 3; 1123 | Serial.print(F("NMRA validation level = ")); 1124 | Serial.println(strictMode); 1125 | break; 1126 | case 'b': 1127 | case 'B': 1128 | showBitLengths = !showBitLengths; 1129 | Serial.print(F("show bit lengths = ")); 1130 | Serial.println(showBitLengths); 1131 | break; 1132 | case 'c': 1133 | case 'C': 1134 | showCpuStats = !showCpuStats; 1135 | Serial.print(F("show Cpu stats = ")); 1136 | Serial.println(showCpuStats); 1137 | break; 1138 | case 'i': 1139 | #if defined(USE_HTTPSERVER) 1140 | case 'I': 1141 | HttpManager.getIP(); 1142 | break; 1143 | #endif 1144 | case '?': 1145 | Serial.println(); 1146 | Serial.println( 1147 | F("Keyboard commands that can be sent via Serial Monitor:")); 1148 | Serial.println(F("1 = 1s refresh time")); 1149 | Serial.println(F("2 = 2s")); 1150 | Serial.println(F("3 = 4s (default)")); 1151 | Serial.println(F("4 = 8s")); 1152 | Serial.println(F("5 = 16s")); 1153 | Serial.println(F("6 = 4 DCC packet buffer")); 1154 | Serial.println(F("7 = 8")); 1155 | Serial.println(F("8 = 16")); 1156 | Serial.println(F("9 = 32 (default)")); 1157 | Serial.println(F("0 = 64")); 1158 | Serial.println(F("a = show accessory packets toggle")); 1159 | Serial.println(F("l = show locomotive packets toggle")); 1160 | Serial.println(F("d = show diagnostics toggle")); 1161 | Serial.println(F("h = show heartbeat toggle")); 1162 | Serial.println(F("b = show half-bit counts by length toggle")); 1163 | Serial.println(F("c = show cpu/irc usage in sniffer")); 1164 | Serial.println(F("f = input filter toggle")); 1165 | Serial.println( 1166 | F("s = set NMRA compliance strictness " 1167 | "(0=none,1=decoder,2=controller)")); 1168 | #if defined(USE_HTTPSERVER) 1169 | Serial.println(F("i = show IP Address if connected")); 1170 | #endif 1171 | Serial.println(F("? = help (show this information)")); 1172 | Serial.print(F("ShowLoco ")); 1173 | Serial.print(showLoc); 1174 | Serial.print(F(" / ShowAcc ")); 1175 | Serial.print(showAcc); 1176 | Serial.print(F(" / RefreshTime ")); 1177 | Serial.print(DCCStatistics.getRefreshTime()); 1178 | Serial.print(F("s / BufferSize ")); 1179 | Serial.print(packetHashListSize); 1180 | Serial.print(F(" / Filter ")); 1181 | Serial.print(filterInput); 1182 | Serial.print(F(" / Strict Bit Validation ")); 1183 | Serial.println(strictMode); 1184 | Serial.println(); 1185 | break; 1186 | } 1187 | return true; 1188 | } else 1189 | return false; 1190 | } 1191 | --------------------------------------------------------------------------------