-
Notifications
You must be signed in to change notification settings - Fork 15
/
zabbuino.ino
1924 lines (1711 loc) · 66.9 KB
/
zabbuino.ino
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
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Use proper release Arduino IDE to avoid compilation errors , please.
v1.6.11 and above is good
*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
PROGRAMM FEATURES SECTION
Please, refer to the "cfg_basic.h" file for enabling or disabling Zabbuino's features and refer to the "src/cfg_tune.h" to deep tuning.
if connected sensors seems not work - first check setting in port_protect[], port_mode[], port_pullup[] arrays in I/O PORTS
SETTING SECTION of "src/cfg_tune.h" file
*/
#include "src/dispatcher.h"
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
STARTUP SECTION
*/
void setup() {
#ifdef SERIAL_USE
DEBUG_PORT.begin(constSerialMonitorSpeed);
#endif // SERIAL_USE
SPI.begin();
__DMLL( DEBUG_PORT.print(FSH_P(constZbxAgentVersion)); DEBUG_PORT.println(FSH_P(STRING_wakes_up)); )
sysMetrics.sysVCCMin = sysMetrics.sysVCCMax = getADCVoltage(ANALOG_CHAN_VBG);
sysMetrics.sysRamFree = sysMetrics.sysRamFreeMin = getRamFree();
pinMode(constStateLedPin, OUTPUT);
#ifdef ADVANCED_BLINKING
// blink on start
blinkMore(6, 50, 500);
#endif
}
/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
GENERAL SECTION
*/
void loop() {
uint8_t result = 0x00, needNetworkRelaunch = true, errorCode = ERROR_NONE;
char incomingData;
//uint16_t blinkType = constBlinkNope;
uint32_t processStartTime, processEndTime, prevPHYCheckTime, prevNetActivityTime, prevSysMetricGatherTime, clientConnectTime, netDebugPrintTime;
request_t request;
request.type = PACKET_TYPE_NONE;
request.payloadByte = request.data;
NetworkClient netClient;
NetworkServer netServer(constZbxAgentTcpPort);
__USER_FUNCTION( uint32_t prevUserFuncCall = 0x00; )
// 0. Init some libs to make system screen works if it enabled
#ifdef TWI_USE
SoftTWI.begin();
#endif
#ifdef FEATURE_SYSTEM_RTC_ENABLE
__DMLM( DEBUG_PORT.print(FSH_P(STRING_Init_system_RTC)); DEBUG_PORT.print(FSH_P(STRING_3xDot_Space)); )
if (RESULT_IS_FAIL == initRTC(&SoftTWI)) {
// sysMetrics.sysStartTimestamp already inited by 0x00 with memset() on start
__DMLM( DEBUG_PORT.println(FSH_P(STRING_fail)); )
} else {
__DMLM( DEBUG_PORT.println(FSH_P(STRING_ok)); )
// Get current timestamp from system RTC and store it into sysMetrics structure.
// On RTC failure - do not use it
if (RESULT_IS_FAIL == getUnixTime(&SoftTWI, (uint32_t*) &sysMetrics.sysStartTimestamp)) {
sysMetrics.sysStartTimestamp = 0x00;
}
}
#endif
// Run user function
__USER_FUNCTION( initStageUserFunction(request.payloadByte); )
// System load procedure
// 1. Factory reset block
#ifdef FEATURE_EEPROM_ENABLE
// factoryReset() return false on EEPROM saving fail or not executed
factoryReset(sysConfig);
#endif // FEATURE_EEPROM_ENABLE
// 2. Load configuration from EEPROM
//
#ifdef FEATURE_EEPROM_ENABLE
__DMLL( DEBUG_PORT.print(FSH_P(STRING_Config)); DEBUG_PORT.print(FSH_P(STRING_loading)); DEBUG_PORT.print(FSH_P(STRING_3xDot_Space)); )
if (!loadConfigFromEEPROM(sysConfig)) {
__DMLL( DEBUG_PORT.println(FSH_P(STRING_fail)); )
// bad CRC detected, use default values for this run
setConfigDefaults(sysConfig);
if (!saveConfigToEEPROM(sysConfig)) {
__DMLM( DEBUG_PORT.print(FSH_P(STRING_Config)); DEBUG_PORT.println(FSH_P(STRING_saving_error)); )
__DMLL( DEBUG_PORT.println(FSH_P(STRING_Use_default_settings)); )
// what to do on saving error?
}
} else {
__DMLL( DEBUG_PORT.println(FSH_P(STRING_ok)); )
}
#else // FEATURE_EEPROM_ENABLE
__DMLM( DEBUG_PORT.println(FSH_P(STRING_EEPROM_disabled)); )
__DMLL( DEBUG_PORT.println(FSH_P(STRING_Use_default_settings)); )
// Use hardcoded values if EEPROM feature disabled
setConfigDefaults(sysConfig);
#endif // FEATURE_EEPROM_ENABLE
// 3. Forcing the system parameters in accordance with the user's compilation options & hardware set
//
#ifdef FEATURE_PASSWORD_PROTECTION_FORCE
sysConfig.useProtection = true;
#endif
#ifdef FEATURE_NET_DHCP_FORCE
sysConfig.useDHCP = true;
#endif // FEATURE_NET_DHCP_FORCE
#if defined(FEATURE_SYSTEM_RTC_ENABLE)
set_zone(sysConfig.tzOffset);
#endif
// 4. Network initialization and starting
//
#if defined FEATURE_ETHERNET_SHIELD_RESET_BUG_FIX
// Let's have a some delay from the system start if Ethernet Shield turns on unstable
processStartTime = millis();
if (processStartTime < constEthernetShieldInitDelay) {
delay(constEthernetShieldInitDelay - processStartTime);
}
#endif
// Call user function
__USER_FUNCTION( netPrepareStageUserFunction(request.payloadByte); )
// init() just make preset of Network object internal data. Real starting maken on relaunch()
Network::init(sysConfig.macAddress, sysConfig.ipAddress, sysConfig.ipAddress, sysConfig.ipGateway, sysConfig.ipNetmask, sysConfig.useDHCP);
//netServer.begin();
__DMLL(
//DEBUG_PORT.println(F("Wait for network warming up... "));
#if defined(FEATURE_SYSTEM_RTC_ENABLE)
DEBUG_PORT.print(F("Timezone: ")); DEBUG_PORT.println(sysConfig.tzOffset, DEC);
#endif
DEBUG_PORT.print(FSH_P(STRING_Password)); DEBUG_PORT.println(sysConfig.password, DEC);
)
// 5. Other system parts initialization
//
// I/O ports initialization. Refer to "I/O PORTS SETTING SECTION" in src/cfg_tune.h
if (RESULT_IS_FAIL == initPortMode()) {
__DMLM( DEBUG_PORT.println(FSH_P(STRING_IO_ports_presets_is_wrong)); )
}
// Prepare external interrupts info structure and so
#ifdef INTERRUPT_USE
initExtInt();
#endif
// Watchdog activation
__WATCHDOG( wdt_enable(constWtdTimeout); )
#ifdef GATHER_METRIC_USING_TIMER_INTERRUPT
// need to analyze return code?
initTimerOne(constSysMetricGatherPeriod);
#endif
#ifdef ADVANCED_BLINKING
// blink on init end
blinkMore(2, 1000, 1000);
#endif
// Correcting timestamps
prevSysMetricGatherTime = prevPHYCheckTime = 0x00;
prevNetActivityTime = netDebugPrintTime = clientConnectTime = millis();
// 6. Enter to infinitive loop to serve incoming requests
//
// if no exist while() here - netProblemTime must be global or static - its will be 0 every loop() and time-related cases will be processeed abnormally
// ...and while save some cpu ticks because do not call everytime from "hidden main()" subroutine, and do not init var, and so.
//*****************************************************************************************************************************************************
// Call user function
__USER_FUNCTION( preLoopStageUserFunction(request.payloadByte); )
parseRequest(CHAR_NULL, REINIT_ANALYZER, request);
while (true) {
// reset watchdog every loop
__WATCHDOG( wdt_reset(); )
// Gather internal metrics periodically
if ((millis() - prevSysMetricGatherTime) > constSysMetricGatherPeriod) {
// When FEATURE_SYSINFO_ENABLE is disabled, compiler can be omit gatherSystemMetrics() sub (due find no operators inside) and trow exception
#ifndef GATHER_METRIC_USING_TIMER_INTERRUPT
gatherSystemMetrics();
#endif
correctVCCMetrics(getADCVoltage(ANALOG_CHAN_VBG));
prevSysMetricGatherTime = millis();
// update millis() rollovers to measure uptime if no RTC onboard
millisRollover();
}
// Turn off state led if no errors occured in the current loop.
// Otherwise - make LED blinked or just turn on
if (ERROR_NONE == errorCode) {
digitalWrite(constStateLedPin, LOW);
sysMetrics.sysAlarmRisedTime = 0x00;
} else {
if (sysMetrics.sysAlarmRisedTime) {
sysMetrics.sysAlarmRisedTime = millis();
}
// Call user function
__USER_FUNCTION( alarmStageUserFunction(request.payloadByte, errorCode); )
#ifdef ON_ALARM_STATE_BLINK
digitalWrite(constStateLedPin, millis() % blinkSettings[errorCode].allTime < blinkSettings[errorCode].onTime);
#else
digitalWrite(constStateLedPin, HIGH);
#endif
} // if (ERROR_NONE == errorCode) ... else
if (needNetworkRelaunch) {
needNetworkRelaunch = false;
// Network module lost address (was resetted) or was not init (first time run)
// Relaunch will reset hardware and re-init its registers
sysMetrics.netPHYReinits++;
__DMLL( DEBUG_PORT.print(FSH_P(STRING_Network_module_reset_No)); DEBUG_PORT.println(sysMetrics.netPHYReinits); )
// relaunch() returns code that can be used as status led blink type
errorCode = Network::relaunch();
if (ERROR_NONE == errorCode) {
netServer.begin();
// relaunch() returns true if DHCP is OK or Static IP used
__DMLL( Network::printNetworkInfo(); )
}
}
// tick() subroutine is very important for UIPEthernet, and must be called often (every ~250ms). If ENC28J60 driver not used - this subroutine do nothing
Network::tick();
if ((millis() - prevPHYCheckTime) > constPHYCheckInterval) {
//phyCheckInterval = constPHYCheckInterval;
// do not forget SPI.begin() or system is hangs up
if ((millis() - netDebugPrintTime) > consNetDebugPrintInterval) {
//__DMLL( Network::printPHYState(); )
netDebugPrintTime = millis();
}
// Network hardware is ok?
if (Network::isPhyOk()) {
// Network hardware settings is the same that MCU needs?
if (!Network::isPhyConfigured()) {
// Need relaunch on next loop in hardware settings error detected
needNetworkRelaunch = true;
} else { // if (!Network::isPhyConfigured())
// PHY is works properly
result = Network::maintain();
// Renew procedure finished with success
switch (result) {
case DHCP_CHECK_NONE:
case DHCP_CHECK_RENEW_OK:
case DHCP_CHECK_REBIND_OK:
// No alarm blink need, network activity registred
errorCode = ERROR_NONE;
break;
default:
// Got some errors - blink with "DHCP problem message"
//blinkType = constBlinkDhcpProblem;
errorCode = ERROR_DHCP;
__DMLM( DEBUG_PORT.println(FSH_P(STRING_DHCP_renew_problem_occured)); )
} // switch (result)
} // if (!Network::isPhyConfigured())
} else { // if (Network::isPhyOk())
// PHY is disconnected or rise any error flag
needNetworkRelaunch = true;
// Right errorCode will be taken on relaunch()
} // if (Network::isPhyOk())
prevPHYCheckTime = millis();
}
// No DHCP problem found, but no data recieved or network activity for a long time
if (ERROR_NONE == errorCode && (constNetIdleTimeout <= (millis() - prevNetActivityTime))) {
errorCode = ERROR_NO_NET_ACTIVITY;
}
//*********************************************
#ifdef FEATURE_SERIAL_LISTEN_TOO
// !!! Need to drop slow serial connection too
// Network connections will processed if no data in Serial buffer exist
if (DEBUG_PORT.available() <= 0) {
#endif
if (!netClient) {
// accept() returns client with "Connected but not send data" state and system must have more stability on this
#if defined(NETWORK_ETH_WIZNET)
netClient = netServer.accept();
#else
netClient = netServer.available();
#endif
if (!netClient) {
// Call "loop stage" user function screen every constRenewSystemDisplayInterval only if no connection exist, because that function can modify cBuffer content
// and recieved data can be corrupted
__USER_FUNCTION(
if (constUserFunctionCallInterval <= (uint32_t) (millis() - prevUserFuncCall)) {
loopStageUserFunction(request.payloadByte);
prevUserFuncCall = millis();
}
)
// Jump to new round of main loop
continue;
}
// reinit analyzer because previous session can be dropped or losted
parseRequest(CHAR_NULL, REINIT_ANALYZER, request);
clientConnectTime = millis();
// ToDo: add remoteIp() output
__DMLH( DEBUG_PORT.print(FSH_P(STRING_New)); DEBUG_PORT.print(FSH_P(STRING_client_No)); DEBUG_PORT.println(netClient); )
}
// Client will be dropped if its connection so slow. Then round must be restarted.
if (constNetSessionTimeout <= (uint32_t) (millis() - clientConnectTime)) {
__DMLH( DEBUG_PORT.print(FSH_P(STRING_Drop)); DEBUG_PORT.print(FSH_P(STRING_client_No)); DEBUG_PORT.println(netClient); )
netClient.stop();
// Jump to new round of main loop
continue;
}
// Network data can be splitted to a number frames and ethClient.available() can return 0 on first frame processing. Need to ignore it.
if (!netClient.available()) {
continue;
}
incomingData = netClient.read();
#ifdef FEATURE_SERIAL_LISTEN_TOO
} else {
// If in Serial buffer is exist just read it
incomingData = DEBUG_PORT.read();
}
#endif
result = parseRequest(incomingData, NO_REINIT_ANALYZER, request);
// result is true if analyzeStream() do not finished and need more data
// result is false if EOL or trailing char detected or there no room in buffer or max number or args parsed...
if (true == result) {
continue;
}
// ethClient.connected() returns true even client is disconnected, but leave the data in the buffer.
// Data can be readed, command will executed, but why get answer? If no recipient - why need to load MCU?
// Will be better do nothing if client is disconnected while analyzing is finished
// But checking must be disable for commands which coming in from the DEBUG_PORT. Otherwise commands will be never executed if no active network client exist.
#ifndef FEATURE_SERIAL_LISTEN_TOO
if (!netClient.connected()) {
continue;
}
#endif
// Fire up State led, than will be turned off on next loop
digitalWrite(constStateLedPin, HIGH);
processStartTime = millis();
__DMLM( uint32_t ramBefore = getRamFree(); )
//__DMLL( DEBUG_PORT.print(cBuffer); DEBUG_PORT.print(FSH_P(STRING_right_arrow)); ) // zbxd\1 is broke this output
sysMetrics.sysCmdLast = executeCommand(netClient, sysConfig, request);
#ifdef FEATURE_REMOTE_COMMANDS_ENABLE
// When system.run[] command is recieved, need to run another command, which taken from option #0 by cmdIdx() sub
if (RESULT_IS_NEW_COMMAND == sysMetrics.sysCmdLast) {
uint16_t k = 0x00;
parseRequest(CHAR_NULL, REINIT_ANALYZER, request);
// simulate command recieving to properly string parsing
// option #0 is moved early to the buffer in the executeCommand()
while (parseRequest(request.payloadByte[k], NO_REINIT_ANALYZER, request)) {
k++;
}
__DMLL( DEBUG_PORT.print(request.command); DEBUG_PORT.print(FSH_P(STRING_right_arrow)); )
sysMetrics.sysCmdLast = executeCommand(netClient, sysConfig, request);
}
#endif
processEndTime = millis();
// use processEndTime as processDurationTime
processEndTime = processEndTime - processStartTime ;
__DMLM( DEBUG_PORT.print(F("Spended: ")); DEBUG_PORT.print(processEndTime);
DEBUG_PORT.print(F(" ms, ")); DEBUG_PORT.print((ramBefore - getRamFree()));
DEBUG_PORT.println(F(" memory bytes"));
)
// Correct internal runtime metrics if need
if (sysMetrics.sysCmdTimeMax < processEndTime) {
sysMetrics.sysCmdTimeMax = processEndTime;
sysMetrics.sysCmdTimeMaxN = sysMetrics.sysCmdLast;
}
// Wait some time to finishing answer send, close connection, and restart network activity control cycle
//delay(constNetStabilizationDelay);
// Actually Ethernet lib's flush() do nothing, but UIPEthernet flush() free ENC28J60 memory blocks where incoming (?) data stored
netClient.flush();
netClient.stop();
#ifdef FEATURE_SERIAL_LISTEN_TOO
// Flush the incoming Serial buffer by reading because Serial object have no clear procedure.
flushStreamRXBuffer(&Serial, 1000UL, false);
parseRequest(CHAR_NULL, REINIT_ANALYZER, request);
#endif
sysMetrics.sysCmdLastExecTime = prevPHYCheckTime = prevNetActivityTime = millis();
//blinkType = constBlinkNope;
errorCode = ERROR_NONE;
} // while(true)
}
/* ****************************************************************************************************************************
**************************************************************************************************************************** */
static int16_t executeCommand(Stream& _netClient, netconfig_t& _sysConfig, request_t& _request) {
int8_t rc;
uint8_t accessGranted = false;
uint16_t i;
uint8_t cmdIdx;
// duration option in the tone[] command is ulong
//int32_t argv[constArgC];
// Zabbix use 64-bit numbers, but we can use only int32_t range. Error can be occurs on ltoa() call with value > long_int_max
int32_t value = 0x00;
uint32_t payloadLength;
cmdIdx = arraySize(commands);
__DMLD( DEBUG_PORT.print(F("Request type: ")); )
// Is need to returns Error if packet's data size is big or not equal to length taken from header?
switch (_request.type) {
case PACKET_TYPE_PLAIN: {
// Create fake command CMD_ZBX_NOPE to return ZBX_NOTSUPPORTED
// _request.command point to start of allowed data's space which used as output buffer
_request.command = (char*) _request.data;
_request.dataFreeSize = sizeof(_request.data);
__DMLD( DEBUG_PORT.println(FSH_P(STRING_Plain_text)); )
break;
}
case PACKET_TYPE_ZABBIX: {
_request.command = (char*) &_request.data[ZBX_HEADER_LENGTH];
_request.dataFreeSize = sizeof(_request.data) - ZBX_HEADER_LENGTH;
__DMLD( DEBUG_PORT.println(FSH_P(STRING_Zabbix)); )
break;
}
case PACKET_TYPE_NONE:
default: {
*_request.command = CHAR_NULL;
__DMLD( DEBUG_PORT.println(F("None")); )
break;
}
}
__DMLL(DEBUG_PORT.print(F("Request cmd: '")); DEBUG_PORT.print(_request.command); DEBUG_PORT.println('\''); )
// Search specified command index in the list of implemented functions
rc = 0x01;
while (cmdIdx && (0x00 != rc)) {
cmdIdx--;
PGM_P cmdName = pgm_read_word(&(commands[cmdIdx].name));
rc = strcmp_P(_request.command, cmdName);
__DMLD( DEBUG_PORT.print(F("#")); DEBUG_PORT.print(FSH_P(STRING_HEX_Prefix)); DEBUG_PORT.print(cmdIdx , HEX); DEBUG_PORT.print(FSH_P(STRING_right_arrow)); DEBUG_PORT.println(FSH_P(cmdName)); )
}
cmdIdx = pgm_read_byte(&(commands[cmdIdx].idx));
// If no suitable command found - do nothing, jump to the finish where show result ZBX_NOTSUPPORTED
if (0x00 >= cmdIdx) {
rc = ZBX_NOTSUPPORTED;
goto finish;
}
rc = RESULT_IS_FAIL;
sysMetrics.sysCmdCount++;
__DMLM( DEBUG_PORT.print(FSH_P(STRING_Execute_command_No)); DEBUG_PORT.print(cmdIdx, HEX); DEBUG_PORT.print(FSH_P(STRING_right_arrow)); DEBUG_PORT.println(_request.command); )
// ***************************************************************************************************************
// If command have no options - it must be run immedately
switch (cmdIdx) {
// case CMD_ZBX_NOPE:
// break;
case CMD_ZBX_AGENT_PING: {
//
// agent.ping
//
rc = RESULT_IS_OK;
goto finish;
}
case CMD_ZBX_AGENT_HOSTNAME: {
//
// agent.hostname
//
strcpy(_request.payloadChar, _sysConfig.hostname);
rc = RESULT_IS_BUFFERED;
goto finish;
}
case CMD_ZBX_AGENT_VERSION: {
//
// agent.version
//
strcpy_P(_request.payloadChar, constZbxAgentVersion);
rc = RESULT_IS_BUFFERED;
goto finish;
}
case CMD_SYSTEM_UPTIME: {
//
// system.uptime
//
// Returns uptime in seconds
value = ((uint32_t) millisRollover() * UINT32_MAX + millis()) / 1000UL;
#ifdef FEATURE_SYSTEM_RTC_ENABLE
// Just rewrite millises uptime by another, which taken from system RTC
if (0x00 != sysMetrics.sysStartTimestamp) {
SoftTWI.reconfigure(constSystemRtcSDAPin, constSystemRtcSCLPin);
if (getUnixTime(&SoftTWI, (uint32_t*) &value)) {
value = value - sysMetrics.sysStartTimestamp;
}
}
#endif
rc = RESULT_IS_UNSIGNED_VALUE;
goto finish;
}
#ifdef FEATURE_SYSINFO_ENABLE
case CMD_SYSTEM_HW_CHASSIS: {
//
// system.hw.chassis
//
strcpy_P(_request.payloadChar, PSTR(BOARD));
rc = RESULT_IS_BUFFERED;
goto finish;
}
case CMD_NET_PHY_NAME: {
//
// net.phy.name
//
strcpy_P(_request.payloadChar, PSTR(PHY_MODULE_NAME));
rc = RESULT_IS_BUFFERED;
goto finish;
}
case CMD_NET_PHY_REINITS: {
//
// net.phy.reinits
//
value = sysMetrics.netPHYReinits;
rc = RESULT_IS_UNSIGNED_VALUE;
goto finish;
}
case CMD_SYS_CMD_TIMEMAX_N: {
//
// sys.cmd.timemax.n
//
// ???? may be use rc = RESULT_IS_HEX ?
ultoa(sysMetrics.sysCmdTimeMaxN, _request.payloadChar, 16);
rc = RESULT_IS_BUFFERED;
goto finish;
}
case CMD_SYS_RAM_FREE: {
//
// sys.ram.free
//
// That metric must be collected periodically to avoid returns always same data
value = sysMetrics.sysRamFree;
rc = RESULT_IS_UNSIGNED_VALUE;
goto finish;
}
case CMD_SYS_RAM_FREEMIN: {
//
// sys.ram.freemin
//
// Without ATOMIC_BLOCK block using sysMetrics[IDX_METRIC_SYS_RAM_FREEMIN] variable can be changed in interrupt on reading
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
value = sysMetrics.sysRamFreeMin;
}
rc = RESULT_IS_UNSIGNED_VALUE;
goto finish;
}
#endif
case CMD_SYS_VCC: {
//
// sys.vcc
//
// Take VCC
value = getADCVoltage(ANALOG_CHAN_VBG);
// VCC may be bigger than max or smaller than min.
// To avoid wrong results and graphs in monitoring system - correct min/max metrics
correctVCCMetrics(value);
rc = RESULT_IS_UNSIGNED_VALUE;
goto finish;
}
case CMD_SYS_VCCMIN: {
//
// sys.vccMin
//
//value = sysMetrics[IDX_METRIC_SYS_VCCMIN];
value = sysMetrics.sysVCCMin;
rc = RESULT_IS_UNSIGNED_VALUE;
goto finish;
}
case CMD_SYS_VCCMAX: {
//
// sys.vccMax
//
value = sysMetrics.sysVCCMax;
rc = RESULT_IS_UNSIGNED_VALUE;
goto finish;
}
#ifdef FEATURE_SYSTEM_RTC_ENABLE
case CMD_SYSTEM_LOCALTIME: {
//
// system.localtime
// Zabbix wants UTC as localtime
//
// If "system.localtime" returns fail - try to use "set.localtime" first. May be battery or vcc voltage is low.
// System do not kickstart RTC if any problem detected to avoid taking random time and unexpected behaviour
//
if (RESULT_IS_OK == getUnixTime(&SoftTWI, (uint32_t*) &value)) {
rc = RESULT_IS_UNSIGNED_VALUE;
}
goto finish;
}
#endif // FEATURE_SYSTEM_RTC_ENABLE
} // switch (cmdIdx) part #1
// ***************************************************************************************************************
// Command with options take more time
// batch convert args to number values
i = arraySize(_request.argv);
while (i) {
i--;
_request.argv[i] = strtol(_request.args[i], NULL, 0);
__DMLH(
DEBUG_PORT.print(F("argv[")); DEBUG_PORT.print(i); DEBUG_PORT.print(F("] => \""));
if (_request.args[i]) {
DEBUG_PORT.print(_request.args[i]);
} else {
DEBUG_PORT.print(F("<null>"));
}
DEBUG_PORT.print(F("\" => ")); DEBUG_PORT.println(_request.argv[i]);
)
}
// Check rights for password protected action
accessGranted = (!_sysConfig.useProtection || (uint32_t) _request.argv[0x00] == _sysConfig.password);
switch (cmdIdx) {
#ifdef FEATURE_USER_FUNCTION_PROCESSING
case CMD_USER_RUN: {
//
// user.run[option#0, option#1, option#2, option#3, option#4, option#5]
// user.run[0xA0,14]
//
rc = executeCommandUserFunction(_request.payloadByte, _request.args, _request.argv, &value);
goto finish;
}
#endif // FEATURE_USER_FUNCTION_PROCESSING
#ifdef FEATURE_REMOTE_COMMANDS_ENABLE
case CMD_SYSTEM_RUN: {
//
// system.run["newCommand"]
//
if (!_request.args[0x00]) {
goto finish;
}
char *ptrOption, *ptrPayload;
ptrOption = _request.args[0x00];
ptrPayload = _request.payloadChar;
while (*ptrOption) {
*ptrPayload = *ptrOption;
ptrPayload++; ptrOption++;
}
*ptrPayload = '\n';
// immediately return RESULT_IS_NEW_COMMAND to re-run executeCommand() with new command
return RESULT_IS_NEW_COMMAND;
goto finish;
}
#endif // FEATURE_REMOTE_COMMANDS_ENABLE
#ifdef FEATURE_ARDUINO_BASIC_ENABLE
case CMD_ARDUINO_ANALOGWRITE: {
//
// analogWrite[pin, value]
//
if (! isSafePin(_request.argv[0x00])) {
goto finish;
}
analogWrite(_request.argv[0x00], _request.argv[0x01]);
rc = RESULT_IS_OK;
goto finish;
}
case CMD_ARDUINO_ANALOGREAD: {
//
// analogRead[pin, analogReferenceSource, mapToLow, mapToHigh]
//
#ifdef FEATURE_AREF_ENABLE
// change source of the reference voltage if its given
if (_request.args[0x00]) {
analogReference(_request.argv[0x00]);
delayMicroseconds(2000);
}
#endif
if (! isSafePin(_request.argv[0x00])) {
goto finish;
}
value = analogRead(_request.argv[0x00]);
if (_request.args[0x02] && _request.args[0x03]) {
value = map(value, constAnalogReadMappingLowValue, constAnalogReadMappingHighValue, _request.argv[0x02], _request.argv[0x03]);
}
rc = RESULT_IS_UNSIGNED_VALUE;
goto finish;
}
case CMD_ARDUINO_DELAY: {
//
// delay[time]
//
if (!_request.args[0x00]) {
goto finish;
}
delay(_request.argv[0x00]);
rc = RESULT_IS_OK;
goto finish;
}
case CMD_ARDUINO_DIGITALWRITE: {
//
// digitalWrite[pin, value, testPin, testValue]
//
if (! isSafePin(_request.argv[0x00])) {
goto finish;
}
// turn on or turn off logic on pin
pinMode(_request.argv[0x00], OUTPUT);
digitalWrite(_request.argv[0x00], !!_request.argv[0x01]);
rc = RESULT_IS_OK;
goto finish;
}
case CMD_ARDUINO_DIGITALREAD: {
//
// digitalRead[pin, internal_pullup]
//
if (! isSafePin(_request.argv[0x00])) {
goto finish;
}
pinMode(_request.argv[0x00], (_request.argv[0x01]) ? INPUT_PULLUP : INPUT);
value = digitalRead(_request.argv[0x00]);
rc = RESULT_IS_UNSIGNED_VALUE;
goto finish;
}
#endif // FEATURE_ARDUINO_BASIC_ENABLE
#ifdef FEATURE_AREF_ENABLE
case CMD_ARDUINO_ANALOGREFERENCE: {
//
// analogReference[source]
//
if (_request.args[0x00]) {
analogReference(_request.argv[0x00]);
delayMicroseconds(2000);
}
rc = RESULT_IS_OK;
goto finish;
}
#endif
#ifdef FEATURE_TONE_ENABLE
case CMD_ARDUINO_TONE: {
//
// tone[pin, frequency, duration]
//
if (! isSafePin(_request.argv[0x00])) {
goto finish;
}
// duration is given?
if (_request.args[0x02]) {
tone(_request.argv[0x00], _request.argv[0x01], _request.argv[0x02]);
} else {
tone(_request.argv[0x00], _request.argv[0x01]);
}
rc = RESULT_IS_OK;
goto finish;
}
case CMD_ARDUINO_NOTONE: {
//
// noTone[pin]
//
if (! isSafePin(_request.argv[0x00])) {
goto finish;
}
noTone(_request.argv[0x00]);
rc = RESULT_IS_OK;
goto finish;
}
#endif
#ifdef FEATURE_RANDOM_ENABLE
case CMD_ARDUINO_RANDOMSEED: {
//
// randomSeed[value]
//
randomSeed(_request.args[0x00] ? ((uint32_t) _request.argv[0x00]) : millis());
rc = RESULT_IS_OK;
goto finish;
}
case CMD_ARDUINO_RANDOM: {
//
// random[min, max]
//
// !! random return long
value = (_request.args[0x00] && _request.args[0x01]) ? random((uint32_t) _request.argv[0x00], (uint32_t)_request.argv[0x01]) : random( _request.args[0x00] ? (uint32_t) _request.argv[0x00] : millis());
rc = RESULT_IS_UNSIGNED_VALUE;
goto finish;
}
#endif // FEATURE_RANDOM_ENABLE
#ifdef FEATURE_EEPROM_ENABLE
case CMD_SET_HOSTNAME: {
//
// set.hostname[password, hostname]
//
// _request.args[0x01] is not NULL if argument #2 given
if (!accessGranted || !_request.args[0x01]) {
goto finish;
}
strncpy(_sysConfig.hostname, _request.args[0x01], constAgentHostnameMaxLength);
// strncpy() can do not copy trailing \0
_sysConfig.hostname[constAgentHostnameMaxLength] = CHAR_NULL;
rc = RESULT_IS_UNSTORED_IN_EEPROM;
goto finish;
}
case CMD_SET_PASSWORD: {
//
// set.password[oldPassword, newPassword]
//
if (!accessGranted || !_request.args[0x01]) {
goto finish;
}
// take new password from argument #2
_sysConfig.password = _request.argv[0x01];
rc = RESULT_IS_UNSTORED_IN_EEPROM;
goto finish;
}
case CMD_SET_SYSPROTECT: {
//
// set.sysprotect[password, protection]
//
if (!accessGranted || !_request.args[0x01]) {
goto finish;
}
_sysConfig.useProtection = (1 == _request.argv[0x01]) ? true : false;
rc = RESULT_IS_UNSTORED_IN_EEPROM;
goto finish;
}
case CMD_SET_NETWORK: {
//
// set.network[password, useDHCP, macAddress, ipAddress, ipNetmask, ipGateway]
//
if (!accessGranted) {
goto finish;
}
uint8_t success = true;
netconfig_t newConfig;
memcpy((uint8_t*) &newConfig, (uint8_t*) &_sysConfig, sizeof(newConfig));
// useDHCP flag coming from argument#1 and must be numeric (boolean) - 1 or 0,
// argv[0x00] data contain in payload[_argOffset[0x01]] placed from _argOffset[0x00]
newConfig.useDHCP = !!_request.argv[0x01];
// ip, netmask and gateway have one size - 4 byte
// take 6 bytes from second argument of command and use as new MAC-address
// if convertation is failed (sub return -1) variable must be falsed too via logic & operator
success = (success) ? (sizeof(newConfig.macAddress) == hstoba((uint8_t *) &newConfig.macAddress, _request.args[0x02])) : false;
// If string to which point optarg[0x03] can be converted to valid NetworkAddress - just do it.
// Otherwize (string can not be converted) _sysConfig.ipAddress will stay untouched;
success = (success) ? (strToNetworkAddress((char*) _request.args[0x03], newConfig.ipAddress)) : false;
success = (success) ? (strToNetworkAddress((char*) _request.args[0x04], newConfig.ipNetmask)) : false;
success = (success) ? (strToNetworkAddress((char*) _request.args[0x05], newConfig.ipGateway)) : false;
// if any convert operation failed - just do not return "need to eeprom write" return code
if (success) {
rc = (saveConfigToEEPROM(newConfig)) ? RESULT_IS_OK : DEVICE_ERROR_EEPROM_CORRUPTED;
}
goto finish;
}
#endif // FEATURE_EEPROM_ENABLE
#ifdef FEATURE_SYSTEM_RTC_ENABLE
case CMD_SET_LOCALTIME: {
//
// set.localtime[password, unixTimestamp, tzOffset]
// set.localtime must take unixTimestamp as UTC, because system.localtime command returns UTC too
//
if (!accessGranted) {
goto finish;
}
uint8_t success = true;
#ifdef FEATURE_EEPROM_ENABLE
// tzOffset is defined?
if (_request.args[0x02]) {
_sysConfig.tzOffset = (int16_t) _request.argv[0x02];
// Save config to EEPROM
success = saveConfigToEEPROM(_sysConfig);
if (success) {
set_zone(_sysConfig.tzOffset);
rc = RESULT_IS_OK;
}
}
#endif // FEATURE_EEPROM_ENABLE
// unixTimestamp option is given?
if (_request.args[0x01] && success) {
// tzOffset is defined and stored sucesfully
if (setUnixTime(&SoftTWI, _request.argv[0x01])) {
rc = RESULT_IS_OK;
}
}
goto finish;
}
#endif // FEATURE_SYSTEM_RTC_ENABLE
case CMD_SYS_PORTWRITE: {
//
// portWrite[port, value]
//
// 'a' used because tolower() used to args saving while parsing
// PortA have index 1, not 0; PortB is 2, PortC is 3...
uint8_t portNo = *_request.args[0x00] - 'a' + 0x01;
rc = writeToPort(portNo, _request.argv[0x01]);
goto finish;
}
#ifdef FEATURE_SHIFTOUT_ENABLE
case CMD_SYS_SHIFTOUT: {
//
// shiftOut[dataPin, clockPin, latchPin, bitOrder, compressionType, data]
//
uint8_t latchUsed = isSafePin(_request.argv[0x02]);
if (isSafePin(_request.argv[0x00]) && isSafePin(_request.argv[0x01])) {
if (latchUsed) {
pinMode(_request.argv[0x02], OUTPUT);
digitalWrite(_request.argv[0x02], LOW);
}
rc = shiftOutAdvanced(_request.argv[0x00], _request.argv[0x01], _request.argv[0x03], _request.argv[0x04], (uint8_t*)_request.args[0x05]);
if (latchUsed) {
digitalWrite(_request.argv[0x02], HIGH);
}
}
goto finish;
}
#endif
#ifdef FEATURE_WS2812_ENABLE
case CMD_WS2812_SENDRAW:
//
// WS2812.sendRaw[dataPin, compressionType, data]
// !!! need to increase ARGS_PART_SIZE, because every encoded LED color take _six_ HEX-chars => 10 leds stripe take 302 (2+50*6) byte of incoming buffer only
//
// Tested on ATmega328@16 and 8 pcs WS2812 5050 RGB LED bar
if (isSafePin(_request.argv[0x00])) {
// 4-th param equal 0x00 mean that buffer not contain raw color bytes and must be prepared (converted from "0xABCDEF.." string)
rc = WS2812Out(_request.argv[0x00], _request.argv[0x01], (uint8_t*) _request.args[0x02], 0x00);
}
goto finish;
#endif // FEATURE_WS2812_ENABLE
case CMD_SYS_REBOOT:
//
// reboot[password]
//
if (accessGranted) {
rc = RESULT_IS_SYSTEM_REBOOT_ACTION;
}
goto finish;