-
Notifications
You must be signed in to change notification settings - Fork 32
/
LocoNet.cpp
2046 lines (1727 loc) · 55.2 KB
/
LocoNet.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
/****************************************************************************
* Copyright (C) 2009..2013 Alex Shepherd
* Copyright (C) 2020 Damian Philipp
*
* Portions Copyright (C) Digitrax Inc.
* Portions Copyright (C) Uhlenbrock Elektronik GmbH
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*****************************************************************************
*
* IMPORTANT:
*
* Some of the message formats used in this code are Copyright Digitrax, Inc.
* and are used with permission as part of the MRRwA (previously EmbeddedLocoNet) project.
* That permission does not extend to uses in other software products. If you wish
* to use this code, algorithm or these message formats outside of
* MRRwA, please contact Digitrax Inc, for specific permission.
*
* Note: The sale any LocoNet device hardware (including bare PCB's) that
* uses this or any other LocoNet software, requires testing and certification
* by Digitrax Inc. and will be subject to a licensing agreement.
*
* Please contact Digitrax Inc. for details.
*
*****************************************************************************
*
* IMPORTANT:
*
* Some of the message formats used in this code are Copyright Uhlenbrock Elektronik GmbH
* and are used with permission as part of the MRRwA (previously EmbeddedLocoNet) project.
* That permission does not extend to uses in other software products. If you wish
* to use this code, algorithm or these message formats outside of
* MRRwA, please contact Copyright Uhlenbrock Elektronik GmbH, for specific permission.
*
*****************************************************************************
* DESCRIPTION
* This module provides functions that manage the sending and receiving of LocoNet packets.
*
* As bytes are received from the LocoNet, they are stored in a circular
* buffer and after a valid packet has been received it can be read out.
*
* When packets are sent successfully, they are also appended to the Receive
* circular buffer so they can be handled like they had been received from
* another device.
*
* Statistics are maintained for both the send and receiving of packets.
*
* Any invalid packets that are received are discarded and the stats are
* updated approproately.
*
*****************************************************************************/
// Uncomment to enable SV Processing Debug Print statements
// #define DEBUG_SV
#include "LocoNet.h"
#include "ln_sw_uart.h"
#include "ln_config.h"
#include "utils.h"
#if defined(ESP8266)
# include <EEPROM.h>
# define E2END 0x1FF // Simulate 512 byte EEPROM
uint8_t eeprom_read_byte(const uint8_t* offset) {
return EEPROM.read((int)offset);
}
void eeprom_write_byte(const uint8_t* offset, uint8_t value) {
EEPROM.write((int)offset, value);
}
#elif defined(STM32F1)
# include <FreeRTOS.h>
# include <task.h>
# include <libopencm3/stm32/gpio.h>
# include <cstdint>
#else
# include <avr/eeprom.h>
# include <avr/wdt.h>
#endif
const char* LoconetStatusStrings[] = {
"CD Backoff",
"Prio Backoff",
"Network Busy",
"Done",
"Collision",
"Unknown Error",
"Retry Error"
};
LocoNetClass::LocoNetClass()
{
}
void LocoNetClass::init(void)
{
#ifdef ESP8266
init(D7); // By default use pin D7 as the Tx pin to be compatible with the previous library default
#else
init(6); // By default use pin 6 as the Tx pin to be compatible with the previous library default
#endif
}
const char* LocoNetClass::getStatusStr(LN_STATUS Status)
{
if ((Status >= LN_CD_BACKOFF) && (Status <= LN_RETRY_ERROR))
return LoconetStatusStrings[Status];
return "Invalid Status";
}
void LocoNetClass::init(uint8_t txPin)
{
initLnBuf(&LnBuffer);
setTxPin(txPin);
initLocoNetHardware(&LnBuffer);
#ifdef ESP8266
// Setup EEProm emulation on EPS8266
EEPROM.begin(E2END);
#endif
}
void LocoNetClass::setTxPin(uint8_t txPin)
{
//#if defined(STM32F1) && !defined(__ARDUINO__)
{
// uint16_t bitNum = 15;
// gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, (1 << bitNum)); // LN TX
// LnPortRegisterType out = GPIOB; // TODO: This shold be configurable..
}
//#else
pinMode(txPin, OUTPUT);
#ifndef ESP8266
// Not figure out which Port bit is the Tx Bit from the Arduino pin number
LnPortRegisterType bitMask = digitalPinToBitMask(txPin);
LnPortRegisterType bitMaskTest = 0x01;
LnPortRegisterType bitNum = 0;
LnPortRegisterType port = digitalPinToPort(txPin);
LnPortAddrType out = portOutputRegister(port);
while (bitMask != bitMaskTest)
bitMaskTest = 1 << ++bitNum;
setTxPortAndPin(out, bitNum);
#else
setTxPortAndPin(nullptr, txPin);
#endif
}
// Check to see if any messages is ready to receive()?
bool LocoNetClass::available(void)
{
return lnPacketReady(&LnBuffer);
}
//Get the state of the uart, when value is 0, it is ok to send data; value list is ln_sw_uart.h
LN_UART_STATE LocoNetClass::uartState()
{
return uartLoconetState();
}
// Check the size in bytes of waiting message
uint8_t LocoNetClass::length(void)
{
if (lnPacketReady(&LnBuffer))
{
lnMsg* m = (lnMsg*)&(LnBuffer.Buf[LnBuffer.ReadIndex]);
return getLnMsgSize(m);
}
else
return 0;
}
lnMsg* LocoNetClass::receive(void)
{
return recvLnMsg(&LnBuffer);
}
/*
Send a LocoNet message, using the default priority delay.
When an attempt to send fails, this method will continue to try to re-send
the message until it is successfully sent or until the maximum retry
limit is reached.
Return value is one of:
LN_DONE - Indicates successful send of the message
LN_RETRY_ERROR - Could not successfully send the message within
LN_TX_RETRIES_MAX attempts
LN_UNKNOWN - Indicates an abnormal exit condition for the send attempt.
In this case, it is recommended to make another send
attempt.
*/
LN_STATUS LocoNetClass::send(lnMsg* pPacket)
{
return send(pPacket, LN_BACKOFF_INITIAL);
}
/*
Send a LocoNet message, using an argument for the priority delay.
When an attempt to send fails, this method will continue to try to re-send
the message until it is successfully sent or until the maximum retry
limit is reached.
Return value is one of:
LN_DONE - Indicates successful send of the message
LN_RETRY_ERROR - Could not successfully send the message within
LN_TX_RETRIES_MAX attempts
LN_UNKNOWN - Indicates an abnormal exit condition for the send attempt.
In this case, it is recommended to make another send
attempt.
*/
LN_STATUS LocoNetClass::send(lnMsg* pPacket, uint8_t ucPrioDelay)
{
unsigned char ucTry;
LN_STATUS enReturn;
unsigned char ucWaitForEnterBackoff;
for (ucTry = 0; ucTry < LN_TX_RETRIES_MAX; ucTry++)
{
// wait previous traffic and than prio delay and than try tx
ucWaitForEnterBackoff = 1; // don't want to abort do/while loop before
do // we did not see the backoff state once
{
enReturn = sendLocoNetPacketTry(pPacket, ucPrioDelay);
if (enReturn == LN_DONE) // success?
return LN_DONE;
if (enReturn == LN_PRIO_BACKOFF)
ucWaitForEnterBackoff = 0; // now entered backoff -> next state != LN_BACKOFF is worth incrementing the try counter
} while ((enReturn == LN_CD_BACKOFF) || // waiting CD backoff
(enReturn == LN_PRIO_BACKOFF) || // waiting master+prio backoff
((enReturn == LN_NETWORK_BUSY) && ucWaitForEnterBackoff)); // or within any traffic unfinished
// failed -> next try going to higher prio = smaller prio delay
if (ucPrioDelay > LN_BACKOFF_MIN)
ucPrioDelay--;
}
LnBuffer.Stats.TxErrors++;
return LN_RETRY_ERROR;
}
/*
Create a four-byte LocoNet message from the three method parameters plus a
computed checksum, and send that message to LocoNet using a default priority
delay.
When an attempt to send fails, this method will continue to try to re-send
the message until it is successfully sent or until the maximum retry
limit is reached.
Return value is one of:
LN_DONE - Indicates successful send of the message
LN_RETRY_ERROR - Could not successfully send the message within
LN_TX_RETRIES_MAX attempts
LN_UNKNOWN - Indicates an abnormal exit condition for the send attempt.
In this case, it is recommended to make another send
attempt.
*/
LN_STATUS LocoNetClass::send(uint8_t OpCode, uint8_t Data1, uint8_t Data2)
{
lnMsg SendPacket;
SendPacket.data[0] = OpCode;
SendPacket.data[1] = Data1;
SendPacket.data[2] = Data2;
return send(&SendPacket);
}
/*
Create a four-byte LocoNet message from the three method parameters plus a
computed checksum, and send that message to LocoNet using a parameter for the
priority delay.
This method will make exactly one attempt to send the LocoNet message which
may or may not succeed. Code which uses this method must check the return
status value to determine if the send should be re-tried. Such code must also
implement a retry limit counter.
Return value is one of:
LN_DONE - Indicates successful send of the message.
LN_CD_BACKOFF - Indicates that the message cannot be sent at this time
because the LocoNet state machine is in the "Carrier Detect
Backoff" phase. This should not count against the "retry"
count.
LN_PRIO_BACKOFF - Indicates that the message cannot be sent at this time
because the LocoNet state machine is in the "Priority
Backoff" phase. This should not count against the "retry"
count.
LN_NETWORK_BUSY - Indicates that the message cannot be sent at this time
because some other LocoNet agent is currently sending
a message. This should not count against the "retry"
count.
LN_COLLISSION - Indicates that an attempt was made to send the message
but that the message was corrupted by some other LocoNet
agent's LocoNe traffic. The retry counter should be
decremented and another send should be attempted if the
retry limit has not been reached.
LN_UNKNOWN - Indicates an abnormal exit condition for the send attempt.
In this case, it is recommended to decrement the retry
counter and make another send attempt if the retry limit
has not been reached.
*/
LN_STATUS LocoNetClass::send(uint8_t OpCode, uint8_t Data1, uint8_t Data2, uint8_t PrioDelay)
{
lnMsg SendPacket;
SendPacket.data[0] = OpCode;
SendPacket.data[1] = Data1;
SendPacket.data[2] = Data2;
return sendLocoNetPacketTry(&SendPacket, PrioDelay);
}
/* send a LONG_ACK (LACK) message to Loconet as a response to an OPC_PEER_XFER
message, using the method parameter as the error code in the LONG_ACK message.
When an attempt to send fails, this method will continue to try to re-send
the message until it is successfully sent or until the maximum retry
limit is reached.
Return value is one of:
LN_DONE - Indicates successful send of the message.
LN_RETRY_ERROR - Indicates that the method could not successfully send the
message within LN_TX_RETRIES_MAX attempts.
LN_UNKNOWN - Indicates an abnormal exit condition for the send attempt.
In this case, it is recommended to make another send
attempt.
*/
LN_STATUS LocoNetClass::sendLongAck(uint8_t ucCode)
{
lnMsg SendPacket;
SendPacket.data[0] = OPC_LONG_ACK;
SendPacket.data[1] = OPC_PEER_XFER - 0x80;
SendPacket.data[2] = ucCode;
return send(&SendPacket);
}
LnBufStats* LocoNetClass::getStats(void)
{
return &LnBuffer.Stats;
}
LN_STATUS LocoNetClass::reportPower(uint8_t State)
{
lnMsg SendPacket;
if (State)
SendPacket.data[0] = OPC_GPON;
else
SendPacket.data[0] = OPC_GPOFF;
return send(&SendPacket);
}
uint8_t LocoNetClass::processSwitchSensorMessage(lnMsg* LnPacket)
{
uint16_t Address;
uint8_t Direction;
uint8_t Output;
uint8_t ConsumedFlag = 1;
Address = (LnPacket->srq.sw1 | ((LnPacket->srq.sw2 & 0x0F) << 7));
if (LnPacket->sr.command != OPC_INPUT_REP)
Address++;
switch (LnPacket->sr.command)
{
case OPC_INPUT_REP:
Address <<= 1;
Address += (LnPacket->ir.in2 & OPC_INPUT_REP_SW) ? 2 : 1;
if (notifySensor)
notifySensor(Address, LnPacket->ir.in2 & OPC_INPUT_REP_HI);
break;
case OPC_GPON:
if (notifyPower)
notifyPower(1);
break;
case OPC_GPOFF:
if (notifyPower)
notifyPower(0);
break;
case OPC_SW_REQ:
if (notifySwitchRequest)
notifySwitchRequest(Address, LnPacket->srq.sw2 & OPC_SW_REQ_OUT, LnPacket->srq.sw2 & OPC_SW_REQ_DIR);
break;
case OPC_SW_REP:
if (LnPacket->srp.sn2 & OPC_SW_REP_INPUTS)
{
if (notifySwitchReport)
notifySwitchReport(Address, LnPacket->srp.sn2 & OPC_SW_REP_HI, LnPacket->srp.sn2 & OPC_SW_REP_SW);
}
else
{
if (notifySwitchOutputsReport)
notifySwitchOutputsReport(Address, LnPacket->srp.sn2 & OPC_SW_REP_CLOSED, LnPacket->srp.sn2 & OPC_SW_REP_THROWN);
}
break;
case OPC_SW_STATE:
Direction = LnPacket->srq.sw2 & OPC_SW_REQ_DIR;
Output = LnPacket->srq.sw2 & OPC_SW_REQ_OUT;
if (notifySwitchState)
notifySwitchState(Address, Output, Direction);
break;
case OPC_SW_ACK:
break;
case OPC_MULTI_SENSE:
switch (LnPacket->data[1] & OPC_MULTI_SENSE_MSG)
{
case OPC_MULTI_SENSE_DEVICE_INFO:
// This is a PM42 power event.
/* Working on porting this */
if (notifyMultiSensePower)
{
uint8_t pCMD;
pCMD = (LnPacket->msdi.arg3 & 0xF0);
if ((pCMD == 0x30) || (pCMD == 0x10))
{
// Autoreverse & Circuitbreaker
uint8_t cm1 = LnPacket->msdi.arg3;
uint8_t cm2 = LnPacket->msdi.arg4;
uint8_t Mode; // 0 = AutoReversing 1 = CircuitBreaker
uint8_t boardID = ((LnPacket->msdi.arg2 + 1) + ((LnPacket->msdi.arg1 & 0x1) == 1) ? 128 : 0);
// Report 4 Sub-Districts for a PM4x
uint8_t d = 1;
for (uint8_t i = 1; i < 5; i++)
{
if ((cm1 & d) != 0)
{
Mode = 0;
}
else {
Mode = 1;
}
Direction = cm2 & d;
d = d * 2;
notifyMultiSensePower(boardID, i, Mode, Direction); // BoardID, Subdistrict, Mode, Direction
}
}
else if (pCMD == 0x70) {
// Programming
}
else if (pCMD == 0x00) {
// Device type report
}
}
break;
case OPC_MULTI_SENSE_ABSENT:
case OPC_MULTI_SENSE_PRESENT:
// Transponding Event
if (notifyMultiSenseTransponder)
{
uint16_t Locoaddr;
uint8_t Present;
char Zone;
Address = LnPacket->mstr.zone + ((LnPacket->mstr.type & 0x1F) << 7);
Present = (LnPacket->mstr.type & 0x20) != 0 ? true : false;
Address++;
if (LnPacket->mstr.adr1 == 0x7D)
Locoaddr = LnPacket->mstr.adr2;
else
Locoaddr = (LnPacket->mstr.adr1 * 128) + LnPacket->mstr.adr2;
if ((LnPacket->mstr.zone & 0x0F) == 0x00) Zone = 'A';
else if ((LnPacket->mstr.zone & 0x0F) == 0x02) Zone = 'B';
else if ((LnPacket->mstr.zone & 0x0F) == 0x04) Zone = 'C';
else if ((LnPacket->mstr.zone & 0x0F) == 0x06) Zone = 'D';
else if ((LnPacket->mstr.zone & 0x0F) == 0x08) Zone = 'E';
else if ((LnPacket->mstr.zone & 0x0F) == 0x0A) Zone = 'F';
else if ((LnPacket->mstr.zone & 0x0F) == 0x0C) Zone = 'G';
else if ((LnPacket->mstr.zone & 0x0F) == 0x0E) Zone = 'H';
else Zone = LnPacket->mstr.zone & 0x0F;
notifyMultiSenseTransponder(Address, Zone, Locoaddr, Present);
break;
}
}
break;
case OPC_LONG_ACK:
if (LnPacket->lack.opcode == (OPC_SW_STATE & 0x7F))
{
Direction = LnPacket->lack.ack1 & 0x01;
if (notifyLongAck)
notifyLongAck(LnPacket->data[1], LnPacket->data[2]);
}
else
ConsumedFlag = 0;
break;
default:
ConsumedFlag = 0;
}
return ConsumedFlag;
}
LN_STATUS LocoNetClass::requestSwitch(uint16_t Address, uint8_t Output, uint8_t Direction)
{
uint8_t AddrH = (--Address >> 7) & 0x0F;
uint8_t AddrL = Address & 0x7F;
if (Output)
AddrH |= OPC_SW_REQ_OUT;
if (Direction)
AddrH |= OPC_SW_REQ_DIR;
return send(OPC_SW_REQ, AddrL, AddrH);
}
LN_STATUS LocoNetClass::reportSwitch(uint16_t Address)
{
Address -= 1;
return send(OPC_SW_STATE, (Address & 0x7F), ((Address >> 7) & 0x0F));
}
LN_STATUS LocoNetClass::reportSensor(uint16_t Address, uint8_t State)
{
uint8_t AddrH = ((--Address >> 8) & 0x0F) | OPC_INPUT_REP_CB;
uint8_t AddrL = (Address >> 1) & 0x7F;
if (Address % 2)
AddrH |= OPC_INPUT_REP_SW;
if (State)
AddrH |= OPC_INPUT_REP_HI;
return send(OPC_INPUT_REP, AddrL, AddrH);
}
LocoNetClass LocoNet = LocoNetClass();
// LocoNet Throttle Support
// To make it easier to handle the Speed steps 0 = Stop, 1 = Em Stop and 2 -127
// normal speed steps we will swap speed steps 0 and 1 so that the normal
// range for speed steps is Stop = 1 2-127 is normal as before and now 0 = EmStop
static uint8_t SwapSpeedZeroAndEmStop(uint8_t Speed)
{
if (Speed == 0)
return 1;
if (Speed == 1)
return 0;
return Speed;
}
void LocoNetThrottleClass::updateAddress(uint16_t Address, uint8_t ForceNotify)
{
if (ForceNotify || myAddress != Address)
{
myAddress = Address;
if (notifyThrottleAddress)
notifyThrottleAddress(myUserData, myState, Address, mySlot);
}
}
void LocoNetThrottleClass::updateSpeed(uint8_t Speed, uint8_t ForceNotify)
{
if (ForceNotify || mySpeed != Speed)
{
mySpeed = Speed;
if (notifyThrottleSpeed)
notifyThrottleSpeed(myUserData, myState, SwapSpeedZeroAndEmStop(Speed));
}
}
void LocoNetThrottleClass::updateState(TH_STATE State, uint8_t ForceNotify)
{
TH_STATE PrevState;
if (ForceNotify || myState != State)
{
PrevState = myState;
myState = State;
if (notifyThrottleState)
notifyThrottleState(myUserData, PrevState, State);
}
}
void LocoNetThrottleClass::updateStatus1(uint8_t Status, uint8_t ForceNotify)
{
register uint8_t Mask; // Temporary uint8_t Variable for bitwise AND to force
// the compiler to only do 8 bit operations not 16
if (ForceNotify || myStatus1 != Status)
{
myStatus1 = Status;
if (notifyThrottleSlotStatus)
notifyThrottleSlotStatus(myUserData, Status);
Mask = LOCO_IN_USE;
updateState(((Status & Mask) == Mask) ? TH_ST_IN_USE : TH_ST_FREE, ForceNotify);
}
}
void LocoNetThrottleClass::updateDirectionAndFunctions(uint8_t DirFunc0to4, uint8_t ForceNotify)
{
uint8_t Diffs;
uint8_t Function;
uint8_t Mask;
if (ForceNotify || myDirFunc0to4 != DirFunc0to4)
{
Diffs = myDirFunc0to4 ^ DirFunc0to4;
myDirFunc0to4 = DirFunc0to4;
// Check Functions 1-4
for (Function = 1, Mask = 1; Function <= 4; Function++)
{
if (notifyThrottleFunction && (ForceNotify || Diffs & Mask))
notifyThrottleFunction(myUserData, Function, DirFunc0to4 & Mask);
Mask <<= 1;
}
// Check Functions 0
if (notifyThrottleFunction && (ForceNotify || Diffs & DIRF_F0))
notifyThrottleFunction(myUserData, 0, DirFunc0to4 & (uint8_t)DIRF_F0);
// Check Direction
if (notifyThrottleDirection && (ForceNotify || Diffs & DIRF_DIR))
notifyThrottleDirection(myUserData, myState, DirFunc0to4 & (uint8_t)DIRF_DIR);
}
}
void LocoNetThrottleClass::updateFunctions5to8(uint8_t Func5to8, uint8_t ForceNotify)
{
uint8_t Diffs;
uint8_t Function;
uint8_t Mask;
if (ForceNotify || myFunc5to8 != Func5to8)
{
Diffs = myFunc5to8 ^ Func5to8;
myFunc5to8 = Func5to8;
// Check Functions 5-8
for (Function = 5, Mask = 1; Function <= 8; Function++)
{
if (notifyThrottleFunction && (ForceNotify || Diffs & Mask))
notifyThrottleFunction(myUserData, Function, Func5to8 & Mask);
Mask <<= 1;
}
}
}
void LocoNetThrottleClass::updateSpeedSteps(TH_SPEED_STEPS SpeedSteps, uint8_t ForceNotify)
{
if (ForceNotify || ((myStatus1 & 0x07) != SpeedSteps))
{
myStatus1 = (myStatus1 & 0xF8) | SpeedSteps;
if (notifyThrottleSpeedSteps)
notifyThrottleSpeedSteps(myUserData, SpeedSteps);
}
}
#define SLOT_REFRESH_TICKS 600 // 600 * 100ms = 60 seconds between speed refresh
void LocoNetThrottleClass::process100msActions(void)
{
if (myState == TH_ST_IN_USE)
{
myTicksSinceLastAction++;
bool isDeferredSpeedChanged = myDeferredSpeed > LN_DEFERRED_SPEED_NOOP;
if (isDeferredSpeedChanged || (myTicksSinceLastAction > SLOT_REFRESH_TICKS))
{
LocoNet.send(OPC_LOCO_SPD, mySlot, (isDeferredSpeedChanged) ? myDeferredSpeed : mySpeed);
myDeferredSpeed = LN_DEFERRED_SPEED_NOOP;
myTicksSinceLastAction = 0;
}
}
}
void LocoNetThrottleClass::init(uint8_t UserData, uint8_t Options, uint16_t ThrottleId)
{
myState = TH_ST_FREE;
myThrottleId = ThrottleId;
myDeferredSpeed = LN_DEFERRED_SPEED_NOOP;
myUserData = UserData;
myOptions = Options;
}
void LocoNetThrottleClass::processMessage(lnMsg* LnPacket)
{
uint8_t Data2;
uint16_t SlotAddress;
// Update our copy of slot information if applicable
if (LnPacket->sd.command == OPC_SL_RD_DATA)
{
SlotAddress = (uint16_t)((LnPacket->sd.adr2 << 7) + LnPacket->sd.adr);
if (mySlot == LnPacket->sd.slot)
{
// Make sure that the slot address matches even though we have the right slot number
// as it is possible that another throttle got in before us and took our slot.
if (myAddress == SlotAddress)
{
if ((myState == TH_ST_SLOT_RESUME) && (myThrottleId != (uint16_t)((LnPacket->sd.id2 << 7) + LnPacket->sd.id1)))
{
updateState(TH_ST_FREE, 1);
if (notifyThrottleError)
notifyThrottleError(myUserData, TH_ER_NO_LOCO);
}
else
{
updateState(TH_ST_IN_USE, 1);
updateAddress(SlotAddress, 1);
updateSpeed(LnPacket->sd.spd, 1);
updateDirectionAndFunctions(LnPacket->sd.dirf, 1);
updateFunctions5to8(LnPacket->sd.snd, 1);
updateSpeedSteps(mySpeedSteps, 1);
// We need to force a State update to cause a display refresh once all data is known
updateState(TH_ST_IN_USE, 1);
// Now Write our own Speed Steps and Throttle Id to the slot and write it back to the command station
LnPacket->sd.command = OPC_WR_SL_DATA;
LnPacket->sd.stat = (LnPacket->sd.stat & 0xf8) | mySpeedSteps;
updateStatus1(LnPacket->sd.stat, 1);
LnPacket->sd.id1 = (uint8_t)(myThrottleId & 0x7F);
LnPacket->sd.id2 = (uint8_t)(myThrottleId >> 7);
LocoNet.send(LnPacket);
}
}
// Ok another throttle did a NULL MOVE with the same slot before we did
// so we have to try again
else if (myState == TH_ST_SLOT_MOVE)
{
updateState(TH_ST_SELECT, 1);
LocoNet.send(OPC_LOCO_ADR, (uint8_t)(myAddress >> 7), (uint8_t)(myAddress & 0x7F));
}
}
// Slot data is not for one of our slots so check if we have requested a new addres
else
{
if (myAddress == SlotAddress)
{
if ((myState == TH_ST_SELECT) || (myState == TH_ST_DISPATCH))
{
if ((LnPacket->sd.stat & STAT1_SL_CONUP) == 0 &&
(LnPacket->sd.stat & LOCO_IN_USE) != LOCO_IN_USE)
{
if (myState == TH_ST_SELECT)
{
updateState(TH_ST_SLOT_MOVE, 1);
mySlot = LnPacket->sd.slot;
Data2 = LnPacket->sd.slot;
}
else
{
updateState(TH_ST_FREE, 1);
Data2 = 0;
}
LocoNet.send(OPC_MOVE_SLOTS, LnPacket->sd.slot, Data2);
}
else
{
if (notifyThrottleError)
notifyThrottleError(myUserData, TH_ER_SLOT_IN_USE);
updateState(TH_ST_FREE, 1);
}
}
else if (myState == TH_ST_SLOT_STEAL)
{
// Make Sure the Slot is actually IN_USE already as we are not going to do an SLOT_MOVE etc
if ((LnPacket->sd.stat & STAT1_SL_CONUP) == 0 &&
(LnPacket->sd.stat & LOCO_IN_USE) == LOCO_IN_USE)
{
mySlot = LnPacket->sd.slot;
updateState(TH_ST_IN_USE, 1);
updateAddress(SlotAddress, 1);
updateSpeed(LnPacket->sd.spd, 1);
updateDirectionAndFunctions(LnPacket->sd.dirf, 1);
updateFunctions5to8(LnPacket->sd.snd, 1);
updateStatus1(LnPacket->sd.stat, 1);
// We need to force a State update to cause a display refresh once all data is known
updateState(TH_ST_IN_USE, 1);
}
else
{
if (notifyThrottleError)
notifyThrottleError(myUserData, TH_ER_NO_LOCO);
updateState(TH_ST_FREE, 1);
}
}
else if (myState == TH_ST_SLOT_FORCE_FREE)
{
LocoNet.send(OPC_SLOT_STAT1, LnPacket->sd.slot, (uint8_t)(myStatus1 & ~(STAT1_SL_BUSY | STAT1_SL_ACTIVE)));
mySlot = 0xFF;
updateState(TH_ST_FREE, 1);
}
}
if (myState == TH_ST_ACQUIRE)
{
mySlot = LnPacket->sd.slot;
updateState(TH_ST_IN_USE, 1);
updateAddress(SlotAddress, 1);
updateSpeed(LnPacket->sd.spd, 1);
updateDirectionAndFunctions(LnPacket->sd.dirf, 1);
updateStatus1(LnPacket->sd.stat, 1);
}
}
}
else if (((LnPacket->sd.command >= OPC_LOCO_SPD) && (LnPacket->sd.command <= OPC_LOCO_SND)) ||
(LnPacket->sd.command == OPC_SLOT_STAT1))
{
if (mySlot == LnPacket->ld.slot)
{
if (LnPacket->ld.command == OPC_LOCO_SPD)
updateSpeed(LnPacket->ld.data, 0);
else if (LnPacket->ld.command == OPC_LOCO_DIRF)
updateDirectionAndFunctions(LnPacket->ld.data, 0);
else if (LnPacket->ld.command == OPC_LOCO_SND)
updateFunctions5to8(LnPacket->ld.data, 0);
else if (LnPacket->ld.command == OPC_SLOT_STAT1)
updateStatus1(LnPacket->ld.data, 0);
}
}
else if (LnPacket->lack.command == OPC_LONG_ACK)
{
if ((myState >= TH_ST_ACQUIRE) && (myState <= TH_ST_SLOT_MOVE))
{
if (LnPacket->lack.opcode == (OPC_MOVE_SLOTS & 0x7F))
if (notifyThrottleError)
notifyThrottleError(myUserData, TH_ER_NO_LOCO);
if (LnPacket->lack.opcode == (OPC_LOCO_ADR & 0x7F))
if (notifyThrottleError)
notifyThrottleError(myUserData, TH_ER_NO_SLOTS);
updateState(TH_ST_FREE, 1);
}
}
}
uint16_t LocoNetThrottleClass::getAddress(void)
{
return myAddress;
}
TH_ERROR LocoNetThrottleClass::stealAddress(uint16_t Address)
{
if (myState <= TH_ST_RELEASE)
{
updateAddress(Address, 1);
updateState(TH_ST_SLOT_STEAL, 1);
LocoNet.send(OPC_LOCO_ADR, (uint8_t)(Address >> 7), (uint8_t)(Address & 0x7F));
return TH_ER_OK;
}
if (notifyThrottleError)
notifyThrottleError(myUserData, TH_ER_BUSY);
return TH_ER_BUSY;
}
TH_ERROR LocoNetThrottleClass::setAddress(uint16_t Address)
{
if (myState <= TH_ST_RELEASE)
{
updateAddress(Address, 1);
updateState(TH_ST_SELECT, 1);
LocoNet.send(OPC_LOCO_ADR, (uint8_t)(Address >> 7), (uint8_t)(Address & 0x7F));
return TH_ER_OK;
}
if (notifyThrottleError)
notifyThrottleError(myUserData, TH_ER_BUSY);
return TH_ER_BUSY;
}
TH_ERROR LocoNetThrottleClass::resumeAddress(uint16_t Address, uint8_t LastSlot)
{
if (myState <= TH_ST_RELEASE)
{
mySlot = LastSlot;
updateAddress(Address, 1);
updateState(TH_ST_SLOT_RESUME, 1);
LocoNet.send(OPC_RQ_SL_DATA, LastSlot, 0);
return TH_ER_OK;
}
if (notifyThrottleError)
notifyThrottleError(myUserData, TH_ER_BUSY);
return TH_ER_BUSY;
}
TH_ERROR LocoNetThrottleClass::freeAddressForce(uint16_t Address)
{
if (myState <= TH_ST_RELEASE)
{
updateAddress(Address, 1);
updateState(TH_ST_SLOT_FORCE_FREE, 1);
LocoNet.send(OPC_LOCO_ADR, (uint8_t)(Address >> 7), (uint8_t)(Address & 0x7F));
return TH_ER_OK;
}
if (notifyThrottleError)
notifyThrottleError(myUserData, TH_ER_BUSY);
return TH_ER_BUSY;
}
TH_ERROR LocoNetThrottleClass::dispatchAddress(void)
{
if (myState == TH_ST_IN_USE)
{
updateState(TH_ST_FREE, 1);
LocoNet.send(OPC_MOVE_SLOTS, mySlot, 0);
return TH_ER_OK;
}
if (notifyThrottleError)
notifyThrottleError(myUserData, TH_ER_NOT_SELECTED);
return TH_ER_NOT_SELECTED;
}
TH_ERROR LocoNetThrottleClass::dispatchAddress(uint16_t Address)
{
if (myState <= TH_ST_RELEASE)
{
updateAddress(Address, 1);
updateState(TH_ST_DISPATCH, 1);
LocoNet.send(OPC_LOCO_ADR, (uint8_t)(Address >> 7), (uint8_t)(Address & 0x7F));
return TH_ER_OK;
}
if (notifyThrottleError)
notifyThrottleError(myUserData, TH_ER_BUSY);
return TH_ER_BUSY;
}
TH_ERROR LocoNetThrottleClass::acquireAddress(void)