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"
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 |
--------------------------------------------------------------------------------