-
Notifications
You must be signed in to change notification settings - Fork 0
/
Modbus.c
1379 lines (1114 loc) · 36 KB
/
Modbus.c
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
/*
* Modbus.c
* Modbus RTU Master and Slave library for STM32 CUBE with FreeRTOS
* Created on: May 5, 2020
* Author: Alejandro Mera
* Adapted from https://github.com/smarmengol/Modbus-Master-Slave-for-Arduino
*/
#include "FreeRTOS.h"
#include "cmsis_os.h"
#include "task.h"
#include "queue.h"
#include "main.h"
//#include "Modbus.h"
#include "timers.h"
#include "semphr.h"
#define bitRead(value, bit) (((value) >> (bit)) & 0x01)
#define bitSet(value, bit) ((value) |= (1UL << (bit)))
#define bitClear(value, bit) ((value) &= ~(1UL << (bit)))
#define bitWrite(value, bit, bitvalue) ((bitvalue) ? bitSet(value, bit) : bitClear(value, bit))
#define lowByte(w) ((w) & 0xff)
#define highByte(w) ((w) >> 8)
modbusHandler_t *mHandlers[MAX_M_HANDLERS];
///Queue Modbus telegrams for master
const osMessageQueueAttr_t QueueTelegram_attributes = {
.name = "QueueModbusTelegram"
};
const osThreadAttr_t myTaskModbusA_attributes = {
.name = "TaskModbusSlave",
.priority = (osPriority_t) osPriorityNormal,
.stack_size = 128 * 4
};
//Task Modbus Master
//osThreadId_t myTaskModbusAHandle;
const osThreadAttr_t myTaskModbusB_attributes = {
.name = "TaskModbusMaster",
.priority = (osPriority_t) osPriorityNormal,
.stack_size = 128 * 4
};
//Semaphore to access the Modbus Data
const osSemaphoreAttr_t ModBusSphr_attributes = {
.name = "ModBusSphr"
};
uint8_t numberHandlers = 0;
static void sendTxBuffer(modbusHandler_t *modH);
static int16_t getRxBuffer(modbusHandler_t *modH);
static uint8_t validateAnswer(modbusHandler_t *modH);
static void buildException( uint8_t u8exception, modbusHandler_t *modH );
static uint8_t validateRequest(modbusHandler_t * modH);
static uint16_t word(uint8_t H, uint8_t l);
static void get_FC1(modbusHandler_t *modH);
static void get_FC3(modbusHandler_t *modH);
static int8_t process_FC1(modbusHandler_t *modH, uint8_t Database );
static int8_t process_FC3(modbusHandler_t *modH, uint8_t Database );
static int8_t process_FC5( modbusHandler_t *modH);
static int8_t process_FC6(modbusHandler_t *modH);
static int8_t process_FC15(modbusHandler_t *modH);
static int8_t process_FC16(modbusHandler_t *modH);
static void vTimerCallbackT35(TimerHandle_t *pxTimer);
static void vTimerCallbackTimeout(TimerHandle_t *pxTimer);
//static int16_t getRxBuffer(modbusHandler_t *modH);
static int8_t SendQuery(modbusHandler_t *modH , modbus_t telegram);
/* Ring Buffer functions */
// This function must be called only after disabling USART RX interrupt or inside of the RX interrupt
void RingAdd(modbusRingBuffer_t *xRingBuffer, uint8_t u8Val)
{
xRingBuffer->uxBuffer[xRingBuffer->u8end] = u8Val;
xRingBuffer->u8end = (xRingBuffer->u8end + 1) % MAX_BUFFER;
if (xRingBuffer->u8available == MAX_BUFFER)
{
xRingBuffer->overflow = true;
xRingBuffer->u8start = (xRingBuffer->u8start + 1) % MAX_BUFFER;
}
else
{
xRingBuffer->overflow = false;
xRingBuffer->u8available++;
}
}
// This function must be called only after disabling USART RX interrupt
uint8_t RingGetAllBytes(modbusRingBuffer_t *xRingBuffer, uint8_t *buffer)
{
return RingGetNBytes(xRingBuffer, buffer, xRingBuffer->u8available);
}
// This function must be called only after disabling USART RX interrupt
uint8_t RingGetNBytes(modbusRingBuffer_t *xRingBuffer, uint8_t *buffer, uint8_t uNumber)
{
uint8_t uCounter;
if(xRingBuffer->u8available == 0 || uNumber == 0 ) return 0;
if(uNumber > MAX_BUFFER) return 0;
for(uCounter = 0; uCounter < uNumber && uCounter< xRingBuffer->u8available ; uCounter++)
{
buffer[uCounter] = xRingBuffer->uxBuffer[xRingBuffer->u8start];
xRingBuffer->u8start = (xRingBuffer->u8start + 1) % MAX_BUFFER;
}
xRingBuffer->u8available = xRingBuffer->u8available - uCounter;
xRingBuffer->overflow = false;
RingClear(xRingBuffer);
return uCounter;
}
uint8_t RingCountBytes(modbusRingBuffer_t *xRingBuffer)
{
return xRingBuffer->u8available;
}
void RingClear(modbusRingBuffer_t *xRingBuffer)
{
xRingBuffer->u8start = 0;
xRingBuffer->u8end = 0;
xRingBuffer->u8available = 0;
xRingBuffer->overflow = false;
}
/* End of Ring Buffer functions */
const unsigned char fctsupported[] =
{
MB_FC_READ_COILS,
MB_FC_READ_DISCRETE_INPUT,
MB_FC_READ_REGISTERS,
MB_FC_READ_INPUT_REGISTER,
MB_FC_WRITE_COIL,
MB_FC_WRITE_REGISTER,
MB_FC_WRITE_MULTIPLE_COILS,
MB_FC_WRITE_MULTIPLE_REGISTERS
};
/**
* @brief
* Initialization for a Master/Slave.
* this function will check the configuration parameters
* of the modbus handler
*
* @param modH modbus handler
*/
void ModbusInit(modbusHandler_t * modH)
{
if (numberHandlers < MAX_M_HANDLERS)
{
//Initialize the ring buffer
RingClear(&modH->xBufferRX);
if(modH->uModbusType == MB_SLAVE)
{
//Create Modbus task slave
modH->myTaskModbusAHandle = osThreadNew(StartTaskModbusSlave, modH, &myTaskModbusA_attributes);
}
else if (modH->uModbusType == MB_MASTER)
{
//Create Modbus task Master and Queue for telegrams
modH->myTaskModbusAHandle = osThreadNew(StartTaskModbusMaster, modH, &myTaskModbusB_attributes);
modH->xTimerTimeout=xTimerCreate("xTimerTimeout", // Just a text name, not used by the kernel.
modH->u16timeOut , // The timer period in ticks.
pdFALSE, // The timers will auto-reload themselves when they expire.
( void * )modH->xTimerTimeout, // Assign each timer a unique id equal to its array index.
(TimerCallbackFunction_t) vTimerCallbackTimeout // Each timer calls the same callback when it expires.
);
if(modH->xTimerTimeout == NULL)
{
while(1); //error creating timer, check heap and stack size
}
modH->QueueTelegramHandle = osMessageQueueNew (MAX_TELEGRAMS, sizeof(modbus_t), &QueueTelegram_attributes);
if(modH->QueueTelegramHandle == NULL)
{
while(1); //error creating queue for telegrams, check heap and stack size
}
}
else
{
while(1); //Error Modbus type not supported choose a valid Type
}
if (modH->myTaskModbusAHandle == NULL)
{
while(1); //Error creating Modbus task, check heap and stack size
}
modH->xTimerT35 = xTimerCreate("TimerT35", // Just a text name, not used by the kernel.
T35 , // The timer period in ticks.
pdFALSE, // The timers will auto-reload themselves when they expire.
( void * )modH->xTimerT35, // Assign each timer a unique id equal to its array index.
(TimerCallbackFunction_t) vTimerCallbackT35 // Each timer calls the same callback when it expires.
);
if (modH->xTimerT35 == NULL)
{
while(1); //Error creating the timer, check heap and stack size
}
modH->ModBusSphrHandle = osSemaphoreNew(1, 1, &ModBusSphr_attributes);
if(modH->ModBusSphrHandle == NULL)
{
while(1); //Error creating the semaphore, check heap and stack size
}
mHandlers[numberHandlers] = modH;
numberHandlers++;
}
else
{
while(1); //error no more Modbus handlers supported
}
}
/**
* @brief
* Start object.
*
* Call this AFTER calling begin() on the serial port, typically within setup().
*
* (If you call this function, then you should NOT call any of
* ModbusRtu's own begin() functions.)
*
* @ingroup setup
*/
void ModbusStart(modbusHandler_t * modH)
{
if(modH->xTypeHW != USART_HW && modH->xTypeHW != USART_HW_DMA )
{
while(1); //ERROR select the type of hardware
}
if (modH->xTypeHW == USART_HW_DMA && ENABLE_USART_DMA == 0 )
{
while(1); //ERROR To use USART_HW_DMA you need to enable it in the ModbusConfig.h file
}
if (modH->xTypeHW == USART_HW || modH->xTypeHW == USART_HW_DMA )
{
if (modH->EN_Port != NULL )
{
// return RS485 transceiver to transmit mode
HAL_GPIO_WritePin(modH->EN_Port, modH->EN_Pin, GPIO_PIN_RESET);
}
if (modH->uModbusType == MB_SLAVE && modH->u16regsHR == NULL )
{
while(1); //ERROR define the DATA pointer shared through Modbus
}
//check that port is initialized
while (HAL_UART_GetState(modH->port) != HAL_UART_STATE_READY)
{
}
#if ENABLE_USART_DMA ==1
if( modH->xTypeHW == USART_HW_DMA )
{
if(HAL_UARTEx_ReceiveToIdle_DMA(modH->port, modH->xBufferRX.uxBuffer, MAX_BUFFER ) != HAL_OK)
{
while(1)
{
//error in your initialization code
}
}
__HAL_DMA_DISABLE_IT(modH->port->hdmarx, DMA_IT_HT); // we don't need half-transfer interrupt
}
else{
// Receive data from serial port for Modbus using interrupt
if(HAL_UART_Receive_IT(modH->port, &modH->dataRX, 1) != HAL_OK)
{
while(1)
{
//error in your initialization code
}
}
}
#else
// Receive data from serial port for Modbus using interrupt
if(HAL_UART_Receive_IT(modH->port, &modH->dataRX, 1) != HAL_OK)
{
while(1)
{
//error in your initialization code
}
}
#endif
if(modH->u8id !=0 && modH->uModbusType == MB_MASTER )
{
while(1)
{
//error Master ID must be zero
}
}
if(modH->u8id ==0 && modH->uModbusType == MB_SLAVE )
{
while(1)
{
//error Master ID must be zero
}
}
}
modH->u8lastRec = modH->u8BufferSize = 0;
modH->u16InCnt = modH->u16OutCnt = modH->u16errCnt = 0;
}
void vTimerCallbackT35(TimerHandle_t *pxTimer)
{
//Notify that a stream has just arrived
int i;
//TimerHandle_t aux;
for(i = 0; i < numberHandlers; i++)
{
if( (TimerHandle_t *)mHandlers[i]->xTimerT35 == pxTimer ){
if(mHandlers[i]->uModbusType == MB_MASTER)
{
xTimerStop(mHandlers[i]->xTimerTimeout,0);
}
xTaskNotify(mHandlers[i]->myTaskModbusAHandle, 0, eSetValueWithOverwrite);
}
}
}
void vTimerCallbackTimeout(TimerHandle_t *pxTimer)
{
//Notify that a stream has just arrived
int i;
//TimerHandle_t aux;
for(i = 0; i < numberHandlers; i++)
{
if( (TimerHandle_t *)mHandlers[i]->xTimerTimeout == pxTimer ){
xTaskNotify(mHandlers[i]->myTaskModbusAHandle, ERR_TIME_OUT, eSetValueWithOverwrite);
}
}
}
void StartTaskModbusSlave(void *argument)
{
modbusHandler_t *modH = (modbusHandler_t *)argument;
//uint32_t notification;
for(;;)
{
modH->i8lastError = 0;
if(modH->xTypeHW == USART_HW || modH->xTypeHW == USART_HW_DMA)
{
ulTaskNotifyTake(pdTRUE, portMAX_DELAY); /* Block until a Modbus Frame arrives */
if (getRxBuffer(modH) == ERR_BUFF_OVERFLOW)
{
modH->i8lastError = ERR_BUFF_OVERFLOW;
modH->u16errCnt++;
continue;
}
}
if (modH->u8BufferSize < 7)
{
//The size of the frame is invalid
modH->i8lastError = ERR_BAD_SIZE;
modH->u16errCnt++;
continue;
}
// check slave id
if ( modH->u8Buffer[ID] != modH->u8id)
{
continue;
}
// validate message: CRC, FCT, address and size
uint8_t u8exception = validateRequest(modH);
if (u8exception > 0)
{
if (u8exception != ERR_TIME_OUT)
{
buildException( u8exception, modH);
sendTxBuffer(modH);
}
modH->i8lastError = u8exception;
//return u8exception
continue;
}
modH->i8lastError = 0;
xSemaphoreTake(modH->ModBusSphrHandle , portMAX_DELAY); //before processing the message get the semaphore
// process message
switch(modH->u8Buffer[ FUNC ] )
{
case MB_FC_READ_COILS:
modH->i8state = process_FC1(modH,DB_COILS);
break;
case MB_FC_READ_DISCRETE_INPUT:
modH->i8state = process_FC1(modH,DB_INPUT_COILS);
break;
case MB_FC_READ_REGISTERS:
modH->i8state = process_FC3(modH,DB_HOLDING_REGISTER);
break;
case MB_FC_READ_INPUT_REGISTER:
modH->i8state = process_FC3(modH,DB_INPUT_REGISTERS);
break;
case MB_FC_WRITE_COIL:
modH->i8state = process_FC5(modH);
break;
case MB_FC_WRITE_REGISTER :
modH->i8state = process_FC6(modH);
break;
case MB_FC_WRITE_MULTIPLE_COILS:
modH->i8state = process_FC15(modH);
break;
case MB_FC_WRITE_MULTIPLE_REGISTERS :
modH->i8state = process_FC16(modH);
break;
default:
break;
}
xSemaphoreGive(modH->ModBusSphrHandle); //Release the semaphore
continue;
}
}
void ModbusQuery(modbusHandler_t * modH, modbus_t telegram )
{
//Add the telegram to the TX tail Queue of Modbus
if (modH->uModbusType == MB_MASTER)
{
telegram.u32CurrentTask = (uint32_t *) osThreadGetId();
xQueueSendToBack(modH->QueueTelegramHandle, &telegram, 0);
}
else{
while(1);// error a slave cannot send queries as a master
}
}
void ModbusQueryInject(modbusHandler_t * modH, modbus_t telegram )
{
//Add the telegram to the TX head Queue of Modbus
xQueueReset(modH->QueueTelegramHandle);
telegram.u32CurrentTask = (uint32_t *) osThreadGetId();
xQueueSendToFront(modH->QueueTelegramHandle, &telegram, 0);
}
/**
* @brief
* *** Only Modbus Master ***
* Generate a query to an slave with a modbus_t telegram structure
* The Master must be in COM_IDLE mode. After it, its state would be COM_WAITING.
* This method has to be called only in loop() section.
*
* @see modbus_t
* @param modH modbus handler
* @param modbus_t modbus telegram structure (id, fct, ...)
* @ingroup loop
*/
int8_t SendQuery(modbusHandler_t *modH , modbus_t telegram )
{
uint8_t u8regsno, u8bytesno;
uint8_t error = 0;
xSemaphoreTake(modH->ModBusSphrHandle , portMAX_DELAY); //before processing the message get the semaphore
if (modH->u8id!=0) error = ERR_NOT_MASTER;
if (modH->i8state != COM_IDLE) error = ERR_POLLING ;
if ((telegram.u8id==0) || (telegram.u8id>247)) error = ERR_BAD_SLAVE_ID;
if(error)
{
modH->i8lastError = error;
xSemaphoreGive(modH->ModBusSphrHandle);
return error;
}
if (telegram.u8fct == MB_FC_READ_COILS || telegram.u8fct == MB_FC_READ_DISCRETE_INPUT ||
telegram.u8fct == MB_FC_WRITE_COIL || telegram.u8fct == MB_FC_WRITE_MULTIPLE_COILS)
{
modH->u16regsCoils = telegram.u16reg;
}
else if (telegram.u8fct == MB_FC_READ_REGISTERS || telegram.u8fct == MB_FC_READ_INPUT_REGISTER ||
telegram.u8fct == MB_FC_WRITE_REGISTER || telegram.u8fct == MB_FC_WRITE_MULTIPLE_REGISTERS)
{
modH->u16regsHR = telegram.u16reg;
}
// telegram header
modH->u8Buffer[ ID ] = telegram.u8id;
modH->u8Buffer[ FUNC ] = telegram.u8fct;
modH->u8Buffer[ ADD_HI ] = highByte(telegram.u16RegAdd );
modH->u8Buffer[ ADD_LO ] = lowByte( telegram.u16RegAdd );
switch( telegram.u8fct )
{
case MB_FC_READ_COILS:
case MB_FC_READ_DISCRETE_INPUT:
case MB_FC_READ_REGISTERS:
case MB_FC_READ_INPUT_REGISTER:
modH->u8Buffer[ NB_HI ] = highByte(telegram.u16CoilsNo );
modH->u8Buffer[ NB_LO ] = lowByte( telegram.u16CoilsNo );
modH->u8BufferSize = 6;
break;
case MB_FC_WRITE_COIL:
modH->u8Buffer[ NB_HI ] = (( telegram.u16reg[0]> 0) ? 0xff : 0);
modH->u8Buffer[ NB_LO ] = 0;
modH->u8BufferSize = 6;
break;
case MB_FC_WRITE_REGISTER:
modH->u8Buffer[ NB_HI ] = highByte( telegram.u16reg[0]);
modH->u8Buffer[ NB_LO ] = lowByte( telegram.u16reg[0]);
modH->u8BufferSize = 6;
break;
case MB_FC_WRITE_MULTIPLE_COILS: // TODO: implement "sending coils"
u8regsno = telegram.u16CoilsNo / 16;
u8bytesno = u8regsno * 2;
if ((telegram.u16CoilsNo % 16) != 0)
{
u8bytesno++;
u8regsno++;
}
modH->u8Buffer[ NB_HI ] = highByte(telegram.u16CoilsNo );
modH->u8Buffer[ NB_LO ] = lowByte( telegram.u16CoilsNo );
modH->u8Buffer[ BYTE_CNT ] = u8bytesno;
modH->u8BufferSize = 7;
for (uint16_t i = 0; i < u8bytesno; i++)
{
if(i%2)
{
modH->u8Buffer[ modH->u8BufferSize ] = lowByte( telegram.u16reg[ i/2 ] );
}
else
{
modH->u8Buffer[ modH->u8BufferSize ] = highByte( telegram.u16reg[ i/2 ] );
}
modH->u8BufferSize++;
}
break;
case MB_FC_WRITE_MULTIPLE_REGISTERS:
modH->u8Buffer[ NB_HI ] = highByte(telegram.u16CoilsNo );
modH->u8Buffer[ NB_LO ] = lowByte( telegram.u16CoilsNo );
modH->u8Buffer[ BYTE_CNT ] = (uint8_t) ( telegram.u16CoilsNo * 2 );
modH->u8BufferSize = 7;
for (uint16_t i=0; i< telegram.u16CoilsNo; i++)
{
modH->u8Buffer[ modH->u8BufferSize ] = highByte( telegram.u16reg[ i ] );
modH->u8BufferSize++;
modH->u8Buffer[ modH->u8BufferSize ] = lowByte( telegram.u16reg[ i ] );
modH->u8BufferSize++;
}
break;
}
sendTxBuffer(modH);
xSemaphoreGive(modH->ModBusSphrHandle);
modH->i8state = COM_WAITING;
modH->i8lastError = 0;
return 0;
}
void StartTaskModbusMaster(void *argument)
{
modbusHandler_t *modH = (modbusHandler_t *)argument;
uint32_t ulNotificationValue;
modbus_t telegram;
for(;;)
{
/*Wait indefinitely for a telegram to send */
xQueueReceive(modH->QueueTelegramHandle, &telegram, portMAX_DELAY);
// This is the case for implementations with only USART support
SendQuery(modH, telegram);
/* Block indefinitely until a Modbus Frame arrives or query timeouts*/
ulNotificationValue = ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
// notify the task the request timeout
modH->i8lastError = 0;
if(ulNotificationValue)
{
modH->i8state = COM_IDLE;
modH->i8lastError = ERR_TIME_OUT;
modH->u16errCnt++;
xTaskNotify((TaskHandle_t)telegram.u32CurrentTask, modH->i8lastError, eSetValueWithOverwrite);
continue;
}
getRxBuffer(modH);
if ( modH->u8BufferSize < 6){
modH->i8state = COM_IDLE;
modH->i8lastError = ERR_BAD_SIZE;
modH->u16errCnt++;
xTaskNotify((TaskHandle_t)telegram.u32CurrentTask, modH->i8lastError, eSetValueWithOverwrite);
continue;
}
xTimerStop(modH->xTimerTimeout,0); // cancel timeout timer
// validate message: id, CRC, FCT, exception
int8_t u8exception = validateAnswer(modH);
if (u8exception != 0)
{
modH->i8state = COM_IDLE;
modH->i8lastError = u8exception;
xTaskNotify((TaskHandle_t)telegram.u32CurrentTask, modH->i8lastError, eSetValueWithOverwrite);
continue;
}
modH->i8lastError = u8exception;
xSemaphoreTake(modH->ModBusSphrHandle , portMAX_DELAY); //before processing the message get the semaphore
// process answer
switch( modH->u8Buffer[ FUNC ] )
{
case MB_FC_READ_COILS:
case MB_FC_READ_DISCRETE_INPUT:
//call get_FC1 to transfer the incoming message to u16regs buffer
get_FC1(modH);
break;
case MB_FC_READ_INPUT_REGISTER:
case MB_FC_READ_REGISTERS :
// call get_FC3 to transfer the incoming message to u16regs buffer
get_FC3(modH);
break;
case MB_FC_WRITE_COIL:
case MB_FC_WRITE_REGISTER :
case MB_FC_WRITE_MULTIPLE_COILS:
case MB_FC_WRITE_MULTIPLE_REGISTERS :
// nothing to do
break;
default:
break;
}
modH->i8state = COM_IDLE;
if (modH->i8lastError ==0) // no error the error_OK, we need to use a different value than 0 to detect the timeout
{
xSemaphoreGive(modH->ModBusSphrHandle); //Release the semaphore
xTaskNotify((TaskHandle_t)telegram.u32CurrentTask, ERR_OK_QUERY, eSetValueWithOverwrite);
}
continue;
}
}
/**
* This method processes functions 1 & 2 (for master)
* This method puts the slave answer into master data buffer
*
* @ingroup register
*/
void get_FC1(modbusHandler_t *modH)
{
uint8_t u8byte, i;
u8byte = 3;
for (i=0; i< modH->u8Buffer[2]; i++) {
if(i%2)
{
modH->u16regsCoils[i/2]= word(modH->u8Buffer[i+u8byte], lowByte(modH->u16regsCoils[i/2]));
}
else
{
modH->u16regsCoils[i/2]= word(highByte(modH->u16regsCoils[i/2]), modH->u8Buffer[i+u8byte]);
}
}
}
/**
* This method processes functions 3 & 4 (for master)
* This method puts the slave answer into master data buffer
*
* @ingroup register
*/
void get_FC3(modbusHandler_t *modH)
{
uint8_t u8byte, i;
u8byte = 3;
for (i=0; i< modH->u8Buffer[ 2 ] /2; i++)
{
modH->u16regsHR[ i ] = word(modH->u8Buffer[ u8byte ], modH->u8Buffer[ u8byte +1 ]);
u8byte += 2;
}
}
/**
* @brief
* This method validates master incoming messages
*
* @return 0 if OK, EXCEPTION if anything fails
* @ingroup buffer
*/
uint8_t validateAnswer(modbusHandler_t *modH)
{
// check message crc vs calculated crc
uint16_t u16MsgCRC =
((modH->u8Buffer[modH->u8BufferSize - 2] << 8)
| modH->u8Buffer[modH->u8BufferSize - 1]); // combine the crc Low & High bytes
if ( calcCRC(modH->u8Buffer, modH->u8BufferSize-2) != u16MsgCRC )
{
modH->u16errCnt ++;
return ERR_BAD_CRC;
}
// check exception
if ((modH->u8Buffer[ FUNC ] & 0x80) != 0)
{
modH->u16errCnt ++;
return ERR_EXCEPTION;
}
// check fct code
bool isSupported = false;
for (uint8_t i = 0; i< sizeof( fctsupported ); i++)
{
if (fctsupported[i] == modH->u8Buffer[FUNC])
{
isSupported = 1;
break;
}
}
if (!isSupported)
{
modH->u16errCnt ++;
return EXC_FUNC_CODE;
}
return 0; // OK, no exception code thrown
}
/**
* @brief
* This method moves Serial buffer data to the Modbus u8Buffer.
*
* @return buffer size if OK, ERR_BUFF_OVERFLOW if u8BufferSize >= MAX_BUFFER
* @ingroup buffer
*/
int16_t getRxBuffer(modbusHandler_t *modH)
{
int16_t i16result;
if(modH->xTypeHW == USART_HW)
{
HAL_UART_AbortReceive_IT(modH->port); // disable interrupts to avoid race conditions on serial port
}
if (modH->xBufferRX.overflow)
{
RingClear(&modH->xBufferRX); // clean up the overflowed buffer
i16result = ERR_BUFF_OVERFLOW;
}
else
{
modH->u8BufferSize = RingGetAllBytes(&modH->xBufferRX, modH->u8Buffer);
modH->u16InCnt++;
i16result = modH->u8BufferSize;
}
if(modH->xTypeHW == USART_HW)
{
HAL_UART_Receive_IT(modH->port, &modH->dataRX, 1);
}
return i16result;
}
/**
* @brief
* This method validates slave incoming messages
*
* @return 0 if OK, EXCEPTION if anything fails
* @ingroup modH Modbus handler
*/
uint8_t validateRequest(modbusHandler_t *modH)
{
// check message crc vs calculated crc
uint16_t u16MsgCRC;
u16MsgCRC= ((modH->u8Buffer[modH->u8BufferSize - 2] << 8)
| modH->u8Buffer[modH->u8BufferSize - 1]); // combine the crc Low & High bytes
if ( calcCRC( modH->u8Buffer, modH->u8BufferSize-2 ) != u16MsgCRC )
{
modH->u16errCnt ++;
return ERR_BAD_CRC;
}
// check fct code
bool isSupported = false;
for (uint8_t i = 0; i< sizeof( fctsupported ); i++)
{
if (fctsupported[i] == modH->u8Buffer[FUNC])
{
isSupported = 1;
break;
}
}
if (!isSupported)
{
modH->u16errCnt ++;
return EXC_FUNC_CODE;
}
// check start address & nb range
uint16_t u16AdRegs = 0;
uint16_t u16NRegs = 0;
//uint8_t u8regs;
switch ( modH->u8Buffer[ FUNC ] )
{
case MB_FC_READ_COILS:
case MB_FC_READ_DISCRETE_INPUT:
case MB_FC_WRITE_MULTIPLE_COILS:
u16AdRegs = word( modH->u8Buffer[ ADD_HI ], modH->u8Buffer[ ADD_LO ]) / 16;
u16NRegs = word( modH->u8Buffer[ NB_HI ], modH->u8Buffer[ NB_LO ]) /16;
if(word( modH->u8Buffer[ NB_HI ], modH->u8Buffer[ NB_LO ]) % 16) u16NRegs++; // check for incomplete words
// verify address range
if((u16AdRegs + u16NRegs) > modH->u16regCoils_size) return EXC_ADDR_RANGE;
//verify answer frame size in bytes
u16NRegs = word( modH->u8Buffer[ NB_HI ], modH->u8Buffer[ NB_LO ]) / 8;
if(word( modH->u8Buffer[ NB_HI ], modH->u8Buffer[ NB_LO ]) % 8) u16NRegs++;
u16NRegs = u16NRegs + 5; // adding the header and CRC ( Slave address + Function code + number of data bytes to follow + 2-byte CRC )
if(u16NRegs > 256) return EXC_REGS_QUANT;
break;
case MB_FC_WRITE_COIL:
u16AdRegs = word( modH->u8Buffer[ ADD_HI ], modH->u8Buffer[ ADD_LO ]) / 16;
if(word( modH->u8Buffer[ ADD_HI ], modH->u8Buffer[ ADD_LO ]) % 16) u16AdRegs++; // check for incomplete words
if (u16AdRegs > modH->u16regCoils_size) return EXC_ADDR_RANGE;
break;
case MB_FC_WRITE_REGISTER :
u16AdRegs = word( modH->u8Buffer[ ADD_HI ], modH->u8Buffer[ ADD_LO ]);
if (u16AdRegs > modH-> u16regHR_size) return EXC_ADDR_RANGE;
break;
case MB_FC_READ_REGISTERS :
case MB_FC_READ_INPUT_REGISTER :
case MB_FC_WRITE_MULTIPLE_REGISTERS :
u16AdRegs = word( modH->u8Buffer[ ADD_HI ], modH->u8Buffer[ ADD_LO ]);
u16NRegs = word( modH->u8Buffer[ NB_HI ], modH->u8Buffer[ NB_LO ]);
if (( u16AdRegs + u16NRegs ) > modH->u16regHR_size) return EXC_ADDR_RANGE;
//verify answer frame size in bytes
u16NRegs = u16NRegs*2 + 5; // adding the header and CRC
if ( u16NRegs > 256 ) return EXC_REGS_QUANT;
break;
}
return 0; // OK, no exception code thrown
}
/**
* @brief
* This method creates a word from 2 bytes
*
* @return uint16_t (word)
* @ingroup H Most significant byte
* @ingroup L Less significant byte
*/
uint16_t word(uint8_t H, uint8_t L)
{
bytesFields W;
W.u8[0] = L;
W.u8[1] = H;
return W.u16[0];
}
/**
* @brief
* This method calculates CRC
*
* @return uint16_t calculated CRC value for the message
* @ingroup Buffer
* @ingroup u8length
*/
uint16_t calcCRC(uint8_t *Buffer, uint8_t u8length)
{
unsigned int temp, temp2, flag;
temp = 0xFFFF;
for (unsigned char i = 0; i < u8length; i++)
{
temp = temp ^ Buffer[i];
for (unsigned char j = 1; j <= 8; j++)
{
flag = temp & 0x0001;
temp >>=1;
if (flag)
temp ^= 0xA001;
}
}
// Reverse byte order.