-
Notifications
You must be signed in to change notification settings - Fork 0
/
dccengine.cpp
1553 lines (1334 loc) · 43.6 KB
/
dccengine.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
This file is part of wavedcc,
Copyright (C) 2021 Glenn Butcher.
wavedcc is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
wavedcc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with wavedcc. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef USE_PIGPIOD_IF
#include <pigpiod_if2.h>
#else
#include <pigpio.h>
#endif
//#include "pigpio_errors.h"
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
#include <sys/time.h>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <deque>
#include <thread>
#include <mutex>
#include <algorithm>
#include "dccpacket.h"
#include "DatagramSocket.h"
#include "ina219.h"
#define MILLISEC_INTERVAL 500.0 //.01 second interval between voltage/current updates; this is in addition to the apx 1.4ms needed to read voltage,current
bool logging = false;
DatagramSocket *slog;
/*
long timestamp()
{
struct timeval tv;
gettimeofday(&tv, NULL);
//return tv.tv_usec / 1000000 + tv.tv_sec;
return tv.tv_sec * 1000000 + tv.tv_usec;
}
*/
uint64_t timestamp() {
struct timeval tv;
gettimeofday(&tv,NULL);
return tv.tv_sec*(uint64_t)1000000+tv.tv_usec;
}
void loginit()
{
slog = new DatagramSocket(9035, (char *) "127.0.0.1", true, true);
}
void logclose()
{
if (slog) slog->~DatagramSocket();
}
void log(std::string msg)
{
char m[256];
struct timeval tv;
gettimeofday(&tv, NULL);
int n = snprintf ( m, sizeof(m), "%ld_%06ld: %s", tv.tv_sec, tv.tv_usec, msg.c_str() );
if ((n >0) & (n<256) && (slog) ) slog->send(m, n);
}
void logcurrent(float current, float voltage)
{
char m[256];
struct timeval tv;
gettimeofday(&tv, NULL);
int n = snprintf ( m, sizeof(m), "%ld_%06ld: current=%04.2f,voltage=%04.2f", tv.tv_sec, tv.tv_usec, current, voltage );
if ((n >0) & (n<256) && (slog)) slog->send(m, n);
}
void pigpio_err(int error)
{
err_rec r = pigpioError(error);
std::cout << r.name << " " << r.description << std::endl;
exit(1);
}
void set_thread_name(std::thread* thread, const char* threadName)
{
auto handle = thread->native_handle();
pthread_setname_np(handle,threadName);
}
class CommandQueue
{
public:
void addCommand(DCCPacket p)
{
m.lock();
cq.push_front(p);
m.unlock();
}
DCCPacket getCommand()
{
m.lock();
DCCPacket p = cq.back();
cq.pop_back();
m.unlock();
return p;
}
bool empty()
{
if (cq.size() > 0) return false;
return true;
}
private:
std::deque<DCCPacket> cq;
std::mutex m;
};
struct roster_item {
unsigned address;
unsigned speed;
unsigned direction;
unsigned headlight;
unsigned fgroup1, fgroup2, fgroup3;
long tstamp; // uptime calculation
int uptime; // uptime accumulator
};
class Roster
{
public:
Roster()
{
next = rr.begin();
//fgroup1 = 128;
//fgroup2 = 176;
//fgroup3 = 160;
}
roster_item get(unsigned address)
{
if (rr.find(address) == rr.end()) rr[address] = roster_item{ address, 0, 0, 0, 128, 176, 160, 0, 0};
return rr[address];
}
void set(unsigned address, roster_item r)
{
m.lock();
rr[address] = r;
m.unlock();
}
void setGroup(unsigned address, unsigned group, unsigned val)
{
m.lock();
if (group == 1) rr[address].fgroup1 = val;
else if (group == 2) rr[address].fgroup2 = val;
else if (group == 3) rr[address].fgroup3 = val;
m.unlock();
}
void update(unsigned address, unsigned speed, unsigned direction, unsigned headlight)
{
long tstamp = timestamp();
m.lock();
if (rr.find(address) == rr.end()) rr[address] = roster_item{ address, 0, 0, 0, 128, 176, 160, tstamp, 0};
if (rr[address].speed == 0 & speed > 0) { // starting up, just record the timestamp
rr[address].tstamp = tstamp;
}
else if (rr[address].speed > 0 & speed > 0) { // in motion, update uptime and timestamp
rr[address].uptime += tstamp - rr[address].tstamp;
rr[address].tstamp = tstamp;
}
else if (rr[address].speed > 0 & speed == 0) { // stopping, just update the uptime
rr[address].uptime += tstamp - rr[address].tstamp;
}
rr[address].speed = speed;
rr[address].direction = direction;
rr[address].headlight = headlight;
m.unlock();
}
roster_item getNext()
{
if (rr.size() == 0) return roster_item{ 0, 0, 0, 0, 128, 176, 160};
roster_item i;
m.lock();
i = next->second;
if (++next == rr.end()) next = rr.begin();
m.unlock();
return i;
}
bool forget(unsigned address)
{
int result;
m.lock();
result = rr.erase(address);
if (++next == rr.end()) next = rr.begin();
m.unlock();
if (result == 1) return true;
return false;
}
void forgetall()
{
m.lock();
rr.clear();
next = rr.begin();
m.unlock();
}
std::string list()
{
std::stringstream l;
l << "roster: " << std::endl;
for (std::map<unsigned, roster_item>::iterator it = rr.begin(); it != rr.end(); ++it)
l << it->first << ": " << (it->second).speed << " " << (it->second).direction << std::endl;
if (rr.size() == 0)
l << "No entries." << std::endl;
return l.str();
}
std::string uptimes()
{
std::stringstream l;
l << "uptimes (sec): " << std::endl;
for (std::map<unsigned, roster_item>::iterator it = rr.begin(); it != rr.end(); ++it)
//l << it->first << ": " << (it->second).uptime << std::endl;
l << it->first << ":" << ((it->second).uptime / 1000000) << std::endl;
if (rr.size() == 0)
l << "No entries." << std::endl;
return l.str();
}
void writeAndResetUptimes(std::string filename)
{
std::ofstream uptimefile;
uptimefile.open(filename);
for (std::map<unsigned, roster_item>::iterator it = rr.begin(); it != rr.end(); ++it) {
uptimefile << it->first << ":" << ((it->second).uptime / 1000000) << std::endl;
it->second.uptime = 0;
}
uptimefile.close();
}
private:
std::map<unsigned, roster_item> rr;
std::mutex m;
// unsigned next;
std::map<unsigned, roster_item>::iterator next;
};
//used for command line, configuration file parsing:
std::vector<std::string> split(std::string s, std::string delim)
{
std::vector<std::string> v;
if (s.find(delim) == std::string::npos) {
v.push_back(s);
return v;
}
size_t pos=0;
size_t start;
while (pos < s.length()) {
start = pos;
pos = s.find(delim,pos);
if (pos == std::string::npos) {
v.push_back(s.substr(start,s.length()-start));
return v;
}
v.push_back(s.substr(start, pos-start));
pos += delim.length();
}
return v;
}
inline bool fileExists (const std::string& name)
{
struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}
std::map<std::string, std::string> getConfig(std::string filename)
{
std::map<std::string, std::string> config;
std::ifstream infile(filename.c_str());
std::string line;
while (std::getline(infile, line)) {
if (line[0] == '#') continue; //the whole line is a comment
std::vector<std::string> c = split(line, "#");
if (c[0].find("=") == std::string::npos) continue; //there's no name=value pair
std::vector<std::string> nv = split(c[0], "=");
if (nv.size() == 2) config[nv[0]] = nv[1];
}
infile.close();
return config;
}
//global declaration of the queue to be used between the command processor and the
//dccRun thread:
CommandQueue commandqueue;
//global declaration of the roster used to refresh speed/dir packets
Roster roster;
//flag to control runDCC()
bool running = false;
//flag to control runDCCCurrent()
bool currenting = false;
//flag to control programming:
bool programming = false;
//flag to control speed step mode:
bool steps28 = true;
//current and voltage variables, populated by runDCCCurrent:
float voltage;
float current;
//millisecond value to sleep the runDCCCurrent thread:
float millisec;
std::mutex vc; //use this to guard voltage/current/highwater access
INA219 ina; //The class for interface with the INA219 through I2C
//GPIO ports to use for DCC output, set in the first part of main()
int MAIN1, MAIN2, MAINENABLE;
int PROG1, PROG2, PROGENABLE;
//variables to control CV reading behavior:
int sample_count = 10; //number of samples from the tail of the current measurment vector to use in determining quiescent current
float ack_limit = 60.0; //milliamps over quiescent to determine an ack, per S-9.2.3 60ma. Changeable with 'acklimit' property in wavedcc.conf
int ack_min = 5; // number of current measurements > quiescent + ack_limit to count in determining an ack, per S-9.2.5, 6ms +/- 1ms, so count >=5. Changeable with 'ackmin' property in wavedcc.conf
//overload threshold in milliamps:
float overload_threshold = 3000.0;
bool overload_trip = false;
//for runDCC() engine and runDCCCurrent() current monitoring threads:
std::thread *t = NULL;
std::thread *c = NULL;
//file path in which to store uptime files:
std::string uptimefilepath = "./";
//boolean to be set by the property 'uptimelogging':
bool uptimelogging = false;
#ifdef USE_PIGPIOD_IF
//pigpiod_id hold the identifier returned at initialization, needed by all pigpiod function calls
int pigpio_id;
#endif
//Thsi routine is to be run as a thread. It should be started shortly after initialization and
//left to run for the duration of the execution. It basically just loops forever, sampling the
//voltage and current every 1ms and posting it to global variables. There is also a "high-water
//mark" variable, where the maximum current read to-date is posted; this variable can be zeroed
//out for CV reading/verifying.
//
void runDCCCurrent()
{
char buf[256];
struct timeval tv1, tv2;
int dutycycle;
int overload_count = 0;
while (currenting) {
gettimeofday(&tv1, NULL);
vc.lock();
voltage = ina.get_voltage();
current = ina.get_current();
vc.unlock();
if (!overload_trip) {
if (current > overload_threshold) {
overload_count++;
if (overload_count >=3) {
#ifdef USE_PIGPIOD_IF
gpio_write(pigpio_id, MAINENABLE, 0);
gpio_write(pigpio_id, PROGENABLE, 0);
#else
gpioWrite(MAINENABLE, 0);
gpioWrite(PROGENABLE, 0);
#endif
overload_trip = true;
programming = false;
running = false;
char m[256];
int n = snprintf(m, 256, "CURRENT OVERLOAD: %04.2f", current);
if (logging) log(m);
}
}
else overload_count = 0;
}
//if (logging) logcurrent(current, voltage);
gettimeofday(&tv2, NULL);
dutycycle = ((tv2.tv_sec - tv1.tv_sec) * 1000000) + (tv2.tv_usec - tv1.tv_usec);
snprintf ( buf, 256, "current=%04.2f,voltage=%04.2f,duty_cycle=%dus", current, voltage, dutycycle );
if (logging) log(buf);
if (millisec > 2) // use the duty cycle to calculate a proper interval
usleep((int) ((1000 * millisec) - dutycycle));
else // just sleep the millisec interval above the duty cycle,
//usleep((int) (1000 * millisec));
usleep((int) (1000 * 2));
}
}
//uses the example specified at http://abyz.me.uk/rpi/pigpio/cif.html#gpioWaveCreatePad.
//
//This routine is to be run as a thread. It basically starts the DCC pulse train
//with an idle packet and retrieves either a command packet from the commandqueue or an idle packet
//if no command is available, and starts the run loop.
//
//In the loop, the retrieved packet gets queued up in the wave pulse train, then busy-waits
//until the current pulse train is done and then deletes it.
//
//the routine has no termination logic; this has to be provided externally as thread
//control
//
void runDCC()
{
struct timespec d;
d.tv_sec = 0;
d.tv_nsec = 1000000; //yields 4-5 iterations in direct, 5-6 iterations in pigpiod
int wid, nextWid;
DCCPacket commandPacket(MAIN1, MAIN2);
std::string packet;
DCCPacket idlePacket = DCCPacket::makeBaselineIdlePacket(MAIN1, MAIN2);
#ifdef USE_PIGPIOD_IF
wave_add_generic(pigpio_id, idlePacket.getPulseTrain().size(), idlePacket.getPulseTrain().data());
wid = wave_create_and_pad(pigpio_id, 50);
wave_send_using_mode(pigpio_id, wid, PI_WAVE_MODE_ONE_SHOT);
#else
gpioWaveAddGeneric(idlePacket.getPulseTrain().size(), idlePacket.getPulseTrain().data());
wid = gpioWaveCreatePad(50, 50, 0);
gpioWaveTxSend(wid, PI_WAVE_MODE_ONE_SHOT);
#endif
if (!commandqueue.empty()) {
commandPacket = commandqueue.getCommand();
}
else {
roster_item i = roster.getNext();
if (i.address != 0)
commandPacket = DCCPacket::makeBaselineSpeedDirPacket(MAIN1, MAIN2, i.address, i.direction, i.speed, i.headlight);
else
commandPacket = idlePacket;
}
while (running) {
#ifdef USE_PIGPIOD_IF
wave_add_generic(pigpio_id, commandPacket.getPulseTrain().size(), commandPacket.getPulseTrain().data());
nextWid = wave_create_and_pad(pigpio_id, 50);
wave_send_using_mode(pigpio_id, nextWid, PI_WAVE_MODE_ONE_SHOT_SYNC);
int i = 0;
while (wave_tx_at(pigpio_id) == wid) { nanosleep(&d, &d); i++; }
//printf("iterations: %d\n", i);
wave_delete(pigpio_id, wid);
#else
gpioWaveAddGeneric(commandPacket.getPulseTrain().size(), commandPacket.getPulseTrain().data());
nextWid = gpioWaveCreatePad(50, 50, 0);
gpioWaveTxSend(nextWid, PI_WAVE_MODE_ONE_SHOT_SYNC);
int i = 0;
while (gpioWaveTxAt() == wid) { nanosleep(&d, &d); i++; }
//printf("iterations: %d\n", i);
gpioWaveDelete(wid);
#endif
wid = nextWid;
// get nextWaveChunk (for this routine, just reuse nextIdlePacket...)
if (!commandqueue.empty()) {
commandPacket = commandqueue.getCommand();
}
else {
roster_item i = roster.getNext();
if (i.address != 0)
commandPacket = DCCPacket::makeBaselineSpeedDirPacket(MAIN1, MAIN2, i.address, i.direction, i.speed, i.headlight);
else
commandPacket = idlePacket;
}
}
#ifdef USE_PIGPIOD_IF
wave_tx_stop(pigpio_id);
wave_clear(pigpio_id);
#else
gpioWaveTxStop();
gpioWaveClear();
#endif
}
void signal_handler(int signum) {
std::cout << std::endl << "exiting (signal " << signum << ")..." << std::endl;
#ifdef USE_PIGPIOD_IF
gpio_write(pigpio_id, MAINENABLE, 0);
gpio_write(pigpio_id, PROGENABLE, 0);
#else
gpioWrite(MAINENABLE, 0);
gpioWrite(PROGENABLE, 0);
#endif
if (logging) logclose();
logging=false;
currenting = false;
running = false;
if (c && c->joinable()) {
c->join();
c->~thread();
c = NULL;
}
if (t && t->joinable()) {
t->join();
t->~thread();
t = NULL;
}
ina.deconfigure();
#ifdef USE_PIGPIOD_IF
pigpio_stop(pigpio_id);
#else
gpioTerminate();
#endif
exit(1);
}
//uptimefilepath
//uptimelogging
std::string dccInit()
{
MAIN1=17;
MAIN2=27;
MAINENABLE=22;
//temporary, for testing:
PROG1=17;
PROG2=27;
PROGENABLE=22;
//read configuration from wavedcc.conf
std::map<std::string, std::string> config;
std::string home(std::getenv("HOME"));
home += "/.wavedcc/wavedcc.conf";
if (fileExists("wavedcc.conf")) {
config = getConfig("wavedcc.conf");
std::cout << "Configuration from ./wavedcc.conf" << std::endl;
}
else if (fileExists(home)) {
getConfig(home);
std::cout << "Configuration from " << home << std::endl;
}
else std::cout << "No configuration file found." << std::endl;
//for configuration debug:
//for(std::map<std::string, std::string>::iterator it = config.begin(); it!= config.end(); ++it)
// std::cout << it->first << " = " << it->second << std::endl;
if (config.find("main1") != config.end()) MAIN1 = atoi(config["main1"].c_str());
if (config.find("main2") != config.end()) MAIN2 = atoi(config["main2"].c_str());
if (config.find("mainenable") != config.end()) MAINENABLE = atoi(config["mainenable"].c_str());
if (config.find("prog1") != config.end()) MAIN1 = atoi(config["prog1"].c_str());
if (config.find("prog2") != config.end()) MAIN2 = atoi(config["prog2"].c_str());
if (config.find("progenable") != config.end()) MAINENABLE = atoi(config["progenable"].c_str());
if (config.find("logging") != config.end()) {
if (config["logging"] == "1") {
loginit();
logging = true;
}
}
if (config.find("uptimelogging") != config.end())
if (config["uptimelogging"] == "1")
uptimelogging = true;
if (config.find("uptimefilepath") != config.end())
uptimefilepath = config["uptimefilepath"];
if (config.find("samplecount") != config.end()) sample_count = atoi(config["samplecount"].c_str());
if (config.find("acklimit") != config.end()) ack_limit = atof(config["acklimit"].c_str());
if (config.find("ackmin") != config.end()) ack_min = atoi(config["ackmin"].c_str());
if (config.find("overloadthreshold") != config.end()) overload_threshold = atof(config["overloadthreshold"].c_str());
#ifdef USE_PIGPIOD_IF
std::string host = "localhost";
std::string port = "8888";
if (config.find("host") != config.end()) host = config["host"];
if (config.find("port") != config.end()) host = config["port"];
pigpio_id = pigpio_start((char *) host.c_str(), (char *) port.c_str());
if (pigpio_id < 0) pigpio_err(pigpio_id);
set_mode(pigpio_id, MAIN1, PI_OUTPUT);
set_mode(pigpio_id, MAIN2, PI_OUTPUT);
set_mode(pigpio_id, MAINENABLE, PI_OUTPUT);
set_mode(pigpio_id, PROG1, PI_OUTPUT);
set_mode(pigpio_id, PROG2, PI_OUTPUT);
set_mode(pigpio_id, PROGENABLE, PI_OUTPUT);
gpio_write(pigpio_id, MAINENABLE, 0);
gpio_write(pigpio_id, PROGENABLE, 0);
wave_clear(pigpio_id);
std::string wavelet_mode = "remote (" + host + ")";
signal(SIGINT, signal_handler);
ina.configure(pigpio_id);
//ina.configure((const char *) host.c_str(), (const char *) port.c_str());
#else
int result;
result = gpioInitialise();
if (result < 0) pigpio_err(result);
gpioSetMode(MAIN1, PI_OUTPUT);
gpioSetMode(MAIN2, PI_OUTPUT);
gpioSetMode(MAINENABLE, PI_OUTPUT);
gpioSetMode(PROG1, PI_OUTPUT);
gpioSetMode(PROG2, PI_OUTPUT);
gpioSetMode(PROGENABLE, PI_OUTPUT);
gpioWrite(MAINENABLE, 0);
gpioWrite(PROGENABLE, 0);
gpioWaveClear();
std::string wavelet_mode = "native";
gpioSetSignalFunc(SIGINT, signal_handler);
ina.configure();
#endif
millisec = MILLISEC_INTERVAL; //no need to lock before thread start
currenting = true;
c = new std::thread(&runDCCCurrent);
set_thread_name(c, "current");
std::stringstream resultstr;
resultstr << "outgpios: " << MAIN1 << "|" << MAIN2 << std::endl << "mode: " << wavelet_mode << std::endl;
return resultstr.str();
}
//depends on the prior creation of rwave by the caller...
bool verifyBit(char rwave, float quiescent, unsigned cv, unsigned char bitpos, unsigned char val)
{
char msg[256];
std::vector<float> currents;
DCCPacket p = DCCPacket::makeServiceModeDirectVerifyBitPacket(PROG1, PROG2, cv, bitpos, val);
#ifdef USE_PIGPIOD_IF
wave_add_generic(pigpio_id, p.getPulseTrain().size(), p.getPulseTrain().data());
char pwave = wave_create(pigpio_id);
#else
gpioWaveAddGeneric(p.getPulseTrain().size(), p.getPulseTrain().data());
char pwave = gpioWaveCreate();
#endif
std::vector<char> pchain = {
//S-9.2.3: 3 resets:
rwave, rwave, rwave,
//S-9.2.3: 5 writes:
pwave, pwave, pwave, pwave, pwave,
//S-9.2.3: 1 or more resets to cover ack period, if present:
rwave, rwave, rwave, rwave, rwave, rwave
};
float max_current = 0.0;
int pwrcount = 0;
snprintf(msg, 256, "Verify CV%d bit %d = %d", cv, bitpos, val);
if (logging) log(msg);
#ifdef USE_PIGPIOD_IF
gpio_write(pigpio_id, PROGENABLE, 1);
wave_chain(pigpio_id, pchain.data(), pchain.size());
while (wave_tx_busy(pigpio_id)) { currents.push_back(current); usleep(1000); }
gpio_write(pigpio_id, PROGENABLE, 0);
#else
gpioWrite(PROGENABLE, 1);
gpioWaveChain(pchain.data(), pchain.size());
while (gpioWaveTxBusy()) { currents.push_back(current); usleep(1000); }
gpioWrite(PROGENABLE, 0);
#endif
float maxack = 0.0;
//count back from the end of sampling sample_count samples, find current measurements > quiescent + 60ma
for (int i=currents.size()-sample_count; i<currents.size(); i++) {
if (currents[i] > quiescent + ack_limit) {
pwrcount++; //S-9.2.3 60.0ma
maxack = currents[i];
}
}
//count back from the end of sampling sample_count samples, find current measurements > quiescent + 60ma
//for (int i=0; i<currents.size(); i++) {
// if (currents[i] > quiescent + ack_limit) {
// pwrcount++; //S-9.2.3 60.0ma
// maxack = currents[i];
// }
//}
if (pwrcount >= ack_min) { //S-9.2.3 6ms +/- 1ms
snprintf(msg, 256, "CV%d found %d in bit position %d (max=%04.2f, pc=%d)", cv, val, bitpos, maxack, pwrcount);
if (logging) log(msg);
val = 0;
return true;
}
snprintf(msg, 256, "CV%d did not find %d in bit position %d (max=%04.2f, pc=%d)", cv, val, bitpos, maxack, pwrcount);
if (logging) log(msg);
return false;
}
//depends on the prior creation of rwave by the caller...
bool verifyByte(char rwave, float quiescent, unsigned cv, unsigned char val)
{
char msg[256];
std::vector<float> currents;
DCCPacket p = DCCPacket::makeServiceModeDirectVerifyBytePacket(PROG1, PROG2, cv, val);
#ifdef USE_PIGPIOD_IF
wave_add_generic(pigpio_id, p.getPulseTrain().size(), p.getPulseTrain().data());
char pwave = wave_create(pigpio_id);
#else
gpioWaveAddGeneric(p.getPulseTrain().size(), p.getPulseTrain().data());
char pwave = gpioWaveCreate();
#endif
std::vector<char> pchain = {
//S-9.2.3: 3 resets:
rwave, rwave, rwave,
//S-9.2.3: 5 writes:
pwave, pwave, pwave, pwave, pwave,
//S-9.2.3: 1 or more resets to cover ack period, if present:
rwave, rwave, rwave, rwave, rwave, rwave
};
float max_current = 0.0;
int pwrcount = 0;
snprintf(msg, 256, "Verify CV%d value %d", cv, val);
if (logging) log(msg);
#ifdef USE_PIGPIOD_IF
gpio_write(pigpio_id, PROGENABLE, 1);
wave_chain(pigpio_id, pchain.data(), pchain.size());
while (wave_tx_busy(pigpio_id)) { currents.push_back(current); usleep(1000); }
gpio_write(pigpio_id, PROGENABLE, 0);
#else
gpioWrite(PROGENABLE, 1);
gpioWaveChain(pchain.data(), pchain.size());
while (gpioWaveTxBusy()) { currents.push_back(current); usleep(1000); }
gpioWrite(PROGENABLE, 0);
#endif
float maxack = 0.0;
//count back from the end of sampling sample_count samples, find current measurements > quiescent + 60ma
for (int i=currents.size()-sample_count; i<currents.size(); i++) {
if (currents[i] > quiescent + ack_limit) {
pwrcount++; //S-9.2.3 60.0ma
maxack = currents[i];
}
}
//count back from the end of sampling sample_count samples, find current measurements > quiescent + 60ma
//for (int i=0; i<currents.size(); i++) {
// if (currents[i] > quiescent + ack_limit) {
// pwrcount++; //S-9.2.3 60.0ma
// maxack = currents[i];
// }
//}
if (pwrcount >= ack_min) { //S-9.2.3 6ms +/- 1ms
snprintf(msg, 256, "CV%d = %d (max=%04.2f, pc=%d)", cv, val, maxack, pwrcount);
if (logging) log(msg);
val = 0;
return true;
}
snprintf(msg, 256, "CV%d != %d (max=%04.2f, pc=%d)", cv, val, maxack, pwrcount);
if (logging) log(msg);
return false;
}
//global, used to run a single engine with adr/+/-:
//int address=0, speed=0, direction=1;
bool headlight=true;
std::string dccCommand(std::string cmd)
{
cmd.erase(cmd.find_last_not_of(" \n\r\t")+1);
cmd.erase(std::remove(cmd.begin(), cmd.end(), '<'), cmd.end());
cmd.erase(std::remove(cmd.begin(), cmd.end(), '>'), cmd.end());
std::vector<std::string> cmdstring = split(cmd, " ");
std::stringstream response;
//<1{ MAIN|PROG]> - turn on all|main|prog track(s), returns <p1[ MAIN|PROG]>
if (cmdstring[0] == "1") {
if (cmdstring.size() >= 2) {
if (cmdstring[1] == "MAIN") {
if (programming) {
response << "<Error: programming mode active.>";
}
else {
if (t == NULL) {
#ifdef USE_PIGPIOD_IF
wave_clear(pigpio_id);
#else
gpioWaveClear();
#endif
running = true;
vc.lock();
millisec = 1;
vc.unlock();
usleep(1000*MILLISEC_INTERVAL); //insure current monitoring before enabling power
t = new std::thread(&runDCC);
set_thread_name(t, "pulsetrain");
#ifdef USE_PIGPIOD_IF
gpio_write(pigpio_id, PROGENABLE, 0);
gpio_write(pigpio_id, MAINENABLE, 1);
#else
gpioWrite(PROGENABLE, 0);
gpioWrite(MAINENABLE, 1);
#endif
response << "<p1 MAIN>";
}
else response << "<Error: DCC pulsetrain already started.";
}
}
else if (cmdstring[1] == "PROG") {
if (running) {
response << "<Error: run mode active";
}
else {
programming = true;
#ifdef USE_PIGPIOD_IF
wave_clear(pigpio_id);
gpio_write(pigpio_id, MAINENABLE, 0);
#else
gpioWaveClear();
gpioWrite(MAINENABLE, 0);
#endif
response << "<p1 PROG>";
}
}
else response << "<Error: invalid mode.>";
}
else if (cmdstring.size() == 1) { // <1> just enables MAIN
if (programming) {
response << "<Error: programming mode active.>";
}
else {
if (t == NULL) {
#ifdef USE_PIGPIOD_IF
wave_clear(pigpio_id);
#else
gpioWaveClear();
#endif
running = true;
vc.lock();
millisec = 1;
vc.unlock();
usleep(1000*MILLISEC_INTERVAL);
t = new std::thread(&runDCC);
set_thread_name(t, "pulsetrain");
vc.lock();
vc.unlock();
#ifdef USE_PIGPIOD_IF
gpio_write(pigpio_id, PROGENABLE, 0);
gpio_write(pigpio_id, MAINENABLE, 1);
#else
gpioWrite(PROGENABLE, 0);
gpioWrite(MAINENABLE, 1);
#endif
response << "<p1 MAIN>";
}
else response << "<Error: DCC pulsetrain already started.";
}
}
else response << "<Error: wavedcc only supports one mode at a time.>";
}
//<0[ MAIN|PROG]> - turn off all|main|prog track(s), returns <p0[ MAIN|PROG]>
else if (cmdstring[0] == "0") {
if (cmdstring.size() >= 2) {
if (cmdstring[1] == "MAIN") {
if (programming) {
response << "<Error: programming mode active.>";
}
else {
running = false;
#ifdef USE_PIGPIOD_IF
gpio_write(pigpio_id, MAINENABLE, 0);
#else
gpioWrite(MAINENABLE, 0);
#endif
if (t && t->joinable()) {
t->join();
t->~thread();
t = NULL;
}
vc.lock();
millisec = MILLISEC_INTERVAL;
vc.unlock();
response << "<p0 MAIN>\n";
if (uptimelogging) {
char fname[256];
time_t rawtime;
struct tm *ftime;
time( &rawtime );
ftime = localtime( &rawtime );
strftime(fname,256,"%Y-%m-%d_%H:%M:%S.txt", ftime);
roster.writeAndResetUptimes(uptimefilepath+std::string(fname));
}
}
}
else if (cmdstring[1] == "PROG") {
if (running) {
response << "<Error: run mode active";
}
else {
programming = false;
#ifdef USE_PIGPIOD_IF
gpio_write(pigpio_id, PROGENABLE, 0);
#else
gpioWrite(PROGENABLE, 0);
#endif
response << "<p0 PROG>\n";
}
}
else response << "<Error: invalid mode.>";
}
else { // turn off both/either
if (running) {
running = false;
#ifdef USE_PIGPIOD_IF
gpio_write(pigpio_id, MAINENABLE, 0);
#else
gpioWrite(MAINENABLE, 0);
#endif
if (t && t->joinable()) {
t->join();
t->~thread();
t = NULL;
}
response << "<p0>\n";
if (uptimelogging) {
char fname[256];
time_t rawtime;
struct tm *ftime;
time( &rawtime );
ftime = localtime( &rawtime );
strftime(fname,256,"%Y-%m-%d_%H:%M:%S.txt", ftime);
roster.writeAndResetUptimes(uptimefilepath+std::string(fname));
}
}
else if (programming) {
programming = false;
#ifdef USE_PIGPIOD_IF
gpio_write(pigpio_id, PROGENABLE, 0);