forked from gianfrdp/SDM120C
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sdm120c.c
1875 lines (1665 loc) · 68.2 KB
/
sdm120c.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
#ifdef __cplusplus
extern "C" {
#endif
/*
* sdm120c: ModBus RTU client to read EASTRON SDM120C smart mini power meter registers
*
* Copyright (C) 2015 Gianfranco Di Prinzio <gianfrdp@inwind.it>
*
* Locking code partially from aurora by Curtronis.
* Some code by TheDrake too. :)
*
* This program 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 2 of the License, or
* (at your option) any later version.
*
* This program 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 this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Enable checks for inter-lock problems debug
#define CHECKFORGHOSTAPPEND 0
#define CHECKFORCLEARLOCKRACE 0
#include <sys/types.h>
#include <sys/file.h>
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <ctype.h>
#include <getopt.h>
#include <syslog.h>
#if CHECKFORCLEARLOCKRACE
#include <glob.h>
#endif
#include <modbus-version.h>
#include <modbus.h>
#define DEFAULT_RATE 2400
#define MODEL_120 1
#define MODEL_220 2
// Read
#define VOLTAGE 0x0000
#define CURRENT 0x0006
#define POWER 0x000C
#define APOWER 0x0012
#define RAPOWER 0x0018
#define PFACTOR 0x001E
#define PANGLE 0x0024
#define FREQUENCY 0x0046
#define IAENERGY 0x0048
#define EAENERGY 0x004A
#define IRAENERGY 0x004C
#define ERAENERGY 0x004E
#define TAENERGY 0x0156
#define TRENERGY 0x0158
// Write
#define NPARSTOP 0x0012
#define DEVICE_ID 0x0014
#define BAUD_RATE 0x001C
#define TIME_DISP_220 0xF500
#define TIME_DISP 0xF900
#define PULSE_OUT 0xF910
#define TOT_MODE 0xF920
#define BR1200 5
#define BR2400 0
#define BR4800 1
#define BR9600 2
#define MAX_RETRIES 100
#define E_PARITY 'E'
#define O_PARITY 'O'
#define N_PARITY 'N'
#define RESTART_TRUE 1
#define RESTART_FALSE 0
#define DEBUG_STDERR 1
#define DEBUG_SYSLOG 2
int debug_mask = 0; //DEBUG_STDERR | DEBUG_SYSLOG; // Default, let pass all
int debug_flag = 0;
int trace_flag = 0;
int metern_flag = 0;
const char *version = "1.3.5.6";
char *programName;
const char *ttyLCKloc = "/var/lock/LCK.."; /* location and prefix of serial port lock file */
#define CMDLINESIZE 128 /* should be enough for debug */
char cmdline[CMDLINESIZE]="";
long unsigned int PID;
long unsigned int PPID;
char *PARENTCOMMAND = NULL;
static int yLockWait = 0; /* Seconds to wait to lock serial port */
static time_t command_delay = -1; // = 30; /* MilliSeconds to wait before sending a command */
static time_t settle_time = -1; // us to wait line to settle before starting chat
char *devLCKfile = NULL;
char *devLCKfileNew = NULL;
void usage(char* program) {
printf("sdm120c %s: ModBus RTU client to read EASTRON SDM120C smart mini power meter registers\n",version);
printf("Copyright (C) 2015 Gianfranco Di Prinzio <gianfrdp@inwind.it>\n");
printf("Complied with libmodbus %s\n\n", LIBMODBUS_VERSION_STRING);
printf("Usage: %s [-a address] [-d n] [-x] [-p] [-v] [-c] [-e] [-i] [-t] [-f] [-g] [-T] [[-m]|[-q]] [-b baud_rate] [-P parity] [-S bit] [-z num_retries] [-j seconds] [-w seconds] [-1 | -2] device\n", program);
printf(" %s [-a address] [-d n] [-x] [-b baud_rate] [-P parity] [-S bit] [-1 | -2] [-z num_retries] [-j seconds] [-w seconds] -s new_address device\n", program);
printf(" %s [-a address] [-d n] [-x] [-b baud_rate] [-P parity] [-S bit] [-1 | -2] [-z num_retries] [-j seconds] [-w seconds] -r baud_rate device \n", program);
printf(" %s [-a address] [-d n] [-x] [-b baud_rate] [-P parity] [-S bit] [-1 | -2] [-z num_retries] [-j seconds] [-w seconds] -N parity device \n", program);
printf(" %s [-a address] [-d n] [-x] [-b baud_rate] [-P parity] [-S bit] [-1 | -2] [-z num_retries] [-j seconds] [-w seconds] -R new_time device \n", program);
printf(" %s [-a address] [-d n] [-x] [-b baud_rate] [-P parity] [-S bit] [-1 | -2] [-z num_retries] [-j seconds] [-w seconds] -M new_mmode device \n", program);
printf(" %s [-a address] [-d n] [-x] [-b baud_rate] [-P parity] [-S bit] [-1 | -2] [-z num_retries] [-j seconds] [-w seconds] -O new_pulse device\n\n", program);
printf("Required:\n");
printf("\tdevice\t\tSerial device (i.e. /dev/ttyUSB0)\n");
printf("Connection parameters:\n");
printf("\t-a address \tMeter number (1-247). Default: 1\n");
printf("\t-b baud_rate \tUse baud_rate serial port speed (1200, 2400, 4800, 9600)\n");
printf("\t\t\tDefault: 2400\n");
printf("\t-P parity \tUse parity (E, N, O)\n");
printf("\t-S bit \t\tUse stop bits (1, 2). Default: 1\n");
printf("\t-1 \t\tModel: SDM120C (default)\n");
printf("\t-2 \t\tModel: SDM220\n");
printf("Reading parameters (no parameter = retrieves all values):\n");
printf("\t-p \t\tGet power (W)\n");
printf("\t-v \t\tGet voltage (V)\n");
printf("\t-c \t\tGet current (A)\n");
printf("\t-l \t\tGet apparent power (VA)\n");
printf("\t-n \t\tGet reactive power (VAR)\n");
printf("\t-f \t\tGet frequency (Hz)\n");
printf("\t-o \t\tGet phase angle (Degree)\n");
printf("\t-g \t\tGet power factor\n");
printf("\t-i \t\tGet imported energy (Wh)\n");
printf("\t-e \t\tGet exported energy (Wh)\n");
printf("\t-t \t\tGet total energy (Wh)\n");
printf("\t-A \t\tGet imported reactive energy (VARh)\n");
printf("\t-B \t\tGet exported reactive energy (VARh)\n");
printf("\t-C \t\tGet total reactive energy (VARh)\n");
printf("\t-T \t\tGet Time for rotating display values (0=no rotation)\n");
printf("\t-m \t\tOutput values in IEC 62056 format ID(VALUE*UNIT)\n");
printf("\t-q \t\tOutput values in compact mode\n");
printf("Writing new settings parameters:\n");
printf("\t-s new_address \tSet new meter number (1-247)\n");
printf("\t-r baud_rate \tSet baud_rate meter speed (1200, 2400, 4800, 9600)\n");
printf("\t-N parity \tSet parity and stop bits (0-3)\n");
printf("\t\t\t0: N1, 1: E1, 2: O1, 3: N2\n");
printf("\t-R new_time \tSet rotation time for displaying values (0=no rotation)\n");
printf("\t\t\tSDM120: (0-30s)\n");
printf("\t\t\tSDM220: (m-m-s-m) Demand interval, Slide time, Scroll time, Backlight time\n");
printf("\t-M new_mmode \tSet total energy measurement mode (1-3)\n");
printf("\t\t\t1: Total=Import, 2: Total=Import+Export, 3: Total=Import-Export\n");
printf("\t-O new_pulse \tSet Pulse 1 output (0-3)\n");
printf("\t\t\t0: 0.001kWh/imp(default), 1: 0.01kWh/imp, 2: 0.1kWh/imp, 3: 1kWh/imp\n");
printf("Fine tuning & debug parameters:\n");
printf("\t-z num_retries\tTry to read max num_retries times on bus before exiting\n");
printf("\t\t\twith error. Default: 1 (no retry)\n");
printf("\t-j 1/10 secs\tResponse timeout. Default: 2=0.2s\n");
printf("\t-D 1/1000 secs\tDelay before sending commands. Default: 0ms\n");
printf("\t-w seconds\tTime to wait to lock serial port (1-30s). Default: 0s\n");
printf("\t-W 1/1000 secs\tTime to wait for 485 line to settle. Default: 0ms\n");
printf("\t-y 1/1000 secs\tSet timeout between every bytes (1-500). Default: disabled\n");
printf("\t-d debug_level\tDebug (0=disable, 1=debug, 2=errors to syslog, 3=both)\n");
printf("\t\t\tDefault: 0\n");
printf("\t-x \t\tTrace (libmodbus debug on)\n");
}
/*--------------------------------------------------------------------------
tv_diff
----------------------------------------------------------------------------*/
static long inline tv_diff(struct timeval const * const t1, struct timeval const * const t2)
{
struct timeval res;
timersub(t1, t2, &res);
return res.tv_sec*1000000 + res.tv_usec;
}
/*--------------------------------------------------------------------------
rnd_usleep
----------------------------------------------------------------------------*/
static long inline rnd_usleep(const useconds_t usecs)
{
long unsigned rnd10 = 10.0*rand()/(RAND_MAX+1.0) + 1;
if (usleep(usecs*rnd10) == 0)
return usecs*rnd10;
else
return -1;
}
/*--------------------------------------------------------------------------
getCurTime
----------------------------------------------------------------------------*/
char* getCurTime()
{
time_t curTimeValue;
struct tm *ltime;
static struct timeval _t;
static struct timezone tz;
static char CurTime[100];
time(&curTimeValue);
ltime = (struct tm *) localtime(&curTimeValue);
gettimeofday(&_t, &tz);
sprintf(CurTime, "%04d%02d%02d-%02d:%02d:%02d.%06d", ltime->tm_year + 1900, ltime->tm_mon + 1, ltime->tm_mday, ltime->tm_hour, ltime->tm_min, ltime->tm_sec, (int)_t.tv_usec);
return CurTime;
}
/*--------------------------------------------------------------------------
getCmdLine
----------------------------------------------------------------------------*/
void getCmdLine()
{
int fd = open("/proc/self/cmdline", O_RDONLY);
int nbytesread = read(fd, cmdline, CMDLINESIZE);
char *p;
if (nbytesread>0) {
for (p=cmdline; p < cmdline+nbytesread; p++) if (*p=='\0') *p=' ';
cmdline[nbytesread-1]='\0';
} else
cmdline[0]='\0';
close(fd);
}
/*--------------------------------------------------------------------------
log_message
----------------------------------------------------------------------------*/
void log_message(const int log, const char* format, ...) {
va_list args;
char buffer[1024];
static int bCmdlineSyslogged = 0;
if (log) {
va_start(args, format);
vsnprintf(buffer, 1024, format, args);
va_end(args);
}
if (log & debug_mask & DEBUG_STDERR) {
fprintf(stderr, "%s: %s(%lu) ", getCurTime(), programName, PID);
fprintf(stderr, "%s", buffer);
fprintf(stderr, "\n");
}
if (log & debug_mask & DEBUG_SYSLOG) {
openlog("sdm120c", LOG_PID|LOG_CONS, LOG_USER);
if (!bCmdlineSyslogged) {
char versionbuffer[strlen(programName)+strlen(version)+3];
snprintf(versionbuffer, strlen(programName)+strlen(version)+3, "%s v%s", programName, version);
syslog(LOG_INFO, "%s", versionbuffer);
char parent[80];
snprintf(parent, sizeof(parent), "parent: %s(%lu)", PARENTCOMMAND, PPID);
syslog(LOG_INFO, "%s", parent);
syslog(LOG_INFO, "%s", cmdline);
bCmdlineSyslogged++;
}
syslog(LOG_INFO, buffer);
closelog();
}
}
/*--------------------------------------------------------------------------
getMemPtr
----------------------------------------------------------------------------*/
void *getMemPtr(size_t mSize)
{
void *ptr;
ptr = calloc(sizeof(char),mSize);
if (!ptr) {
log_message(debug_flag | LOG_SYSLOG, "malloc failed");
exit(2);
}
//cptr = (char *)ptr;
//for (i = 0; i < mSize; i++) cptr[i] = '\0';
return ptr;
}
/*--------------------------------------------------------------------------
ClrSerLock
Clear Serial Port lock.
----------------------------------------------------------------------------*/
int ClrSerLock(long unsigned int LckPID) {
FILE *fdserlck, *fdserlcknew;
long unsigned int PID;
int bWrite, bRead;
int errno_save = 0;
int fLen = 0;
int cmdLen = 0;
int curChar = 0;
char *COMMAND = NULL;
errno = 0;
log_message(debug_flag, "devLCKfile: <%s>", devLCKfile);
log_message(debug_flag, "devLCKfileNew: <%s> ", devLCKfileNew);
log_message(debug_flag, "Clearing Serial Port Lock (%lu)...", LckPID);
fdserlck = fopen(devLCKfile, "r");
if (fdserlck == NULL) {
log_message(debug_flag | DEBUG_SYSLOG, "Problem opening serial device lock file to clear PID %lu: %s for read.",LckPID,devLCKfile);
return(0);
}
log_message(debug_flag, "Acquiring exclusive lock on %s...",devLCKfile);
flock(fileno(fdserlck), LOCK_EX); // Will wait to acquire lock then continue
log_message(debug_flag, "Exclusive lock on %s acquired (%d) %s...",devLCKfile, errno, strerror(errno));
#if CHECKFORCLEARLOCKRACE
// Check for potential conflicts
glob_t globbuf;
int iGlob, fGlob = TRUE;
log_message(debug_flag, "GlobCheck - Check to avoid simultaneous PID clearing");
for (iGlob=5; iGlob>0 && fGlob; iGlob--) {
fGlob = FALSE;
if (glob("/var/lock/LCK..ttyUSB0.*", GLOB_NOSORT, NULL, &globbuf) != GLOB_NOMATCH) {
log_message(debug_flag | DEBUG_SYSLOG, "GlobCheck (%u), some other process is clearing lock too!!! (%s)",iGlob, globbuf.gl_pathv[0]);
fGlob=TRUE;
log_message(debug_flag, "Sleeping %ldus", rnd_usleep(500000));
}
globfree(&globbuf);
}
#endif
fdserlcknew = fopen(devLCKfileNew, "a");
if (fdserlcknew == NULL) {
log_message(debug_flag | DEBUG_SYSLOG, "Problem opening new serial device lock file to clear PID %lu: %s for write.",LckPID,devLCKfileNew);
fclose(fdserlck);
return(0);
}
// Find cmdLen max len in file
curChar = 0;
while (curChar != EOF) {
fLen = 0;
while ((curChar = fgetc(fdserlck)) != EOF && curChar != '\n' && curChar != ' ') fLen++;
if (curChar == ' ') {
fLen = 0;
while ((curChar = fgetc(fdserlck)) != EOF && curChar != '\n') fLen++;
if (fLen > cmdLen) cmdLen = fLen;
}
}
rewind(fdserlck);
log_message(debug_flag, "cmdLen=%i", cmdLen);
COMMAND = getMemPtr(cmdLen+1);
log_message(debug_flag, "cmdLen=%i COMMAND %s", cmdLen, (COMMAND==NULL ? "is null" : "is not null"));
COMMAND[0] = '\0'; PID = 0;
errno = 0;
bRead = fscanf(fdserlck, "%lu%*[ ]%[^\n]\n", &PID, COMMAND);
errno_save = errno;
log_message(debug_flag, "errno=%i, bRead=%i LckPID=%lu PID=%lu COMMAND='%s'", errno_save, bRead, LckPID, PID, COMMAND);
while (bRead != EOF && bRead > 0) {
if (PID != LckPID) {
errno = 0;
if (COMMAND[0] != '\0') {
bWrite = fprintf(fdserlcknew, "%lu %s\n", PID, COMMAND);
errno_save = errno;
} else {
bWrite = fprintf(fdserlcknew, "%lu\n", PID);
errno_save = errno;
}
log_message(debug_flag, "errno=%i, bWrite=%i PID=%lu", errno, bWrite, PID);
if (bWrite < 0 || errno_save != 0) {
log_message(debug_flag | DEBUG_SYSLOG, "Problem clearing serial device lock, can't write lock file: %s. %s",devLCKfile,strerror(errno_save));
log_message(debug_flag | DEBUG_SYSLOG, "(%u) %s",errno_save,strerror(errno_save));
fclose(fdserlcknew);
return(0);
}
}
errno=0; PID=0; COMMAND[0] = '\0';
bRead = fscanf(fdserlck, "%lu%*[ ]%[^\n]\n", &PID, COMMAND);
errno_save = errno;
log_message(debug_flag, "errno=%i, bRead=%i LckPID=%lu PID=%lu COMMAND='%s'", errno_save, bRead, LckPID, PID, COMMAND);
}
fflush(fdserlcknew);
errno = 0;
if (rename(devLCKfileNew,devLCKfile)) {
log_message(debug_flag | DEBUG_SYSLOG, "Problem clearing serial device lock, can't update lock file: %s.",devLCKfile);
log_message(debug_flag | DEBUG_SYSLOG, "(%d) %s", errno, strerror(errno));
}
#if CHECKFORGHOSTAPPEND
log_message(debug_flag, "Clearing Serial Port Lock almost done...");
log_message(debug_flag, "Sleeping %luus", rnd_usleep(10000));
// Check for latest appends (ghost appends)
int iGhost=10;
bRead = fscanf(fdserlck, "%lu%*[ ]%*[^\n]\n", &PID);
while (iGhost > 0) {
if (bRead > 0) {
log_message(debug_flag | DEBUG_SYSLOG, "Found ghost append (%d): %s. %lu",iGhost,devLCKfile,PID);
errno = 0;
bWrite = fprintf(fdserlcknew, "%lu\n", PID);
errno_save = errno;
if (bWrite < 0 || errno_save != 0) {
log_message(debug_flag | DEBUG_SYSLOG, "Problem clearing serial device lock, can't write lock file: %s. %s",devLCKfile,strerror (errno_save));
log_message(debug_flag | DEBUG_SYSLOG, "(%u) %s", errno_save, strerror(errno_save));
fclose(fdserlcknew);
return(0);
}
}
fflush(fdserlcknew);
log_message(debug_flag, "Sleeping %ldus", rnd_usleep(10000));
iGhost--; PID=0;
bRead = fscanf(fdserlck, "%lu%*[ ]%*[^\n]\n", &PID);
}
#endif
fclose(fdserlck);
fclose(fdserlcknew);
free(COMMAND);
log_message(debug_flag, "Clearing Serial Port Lock done");
return -1;
}
/*--------------------------------------------------------------------------
AddSerLock
Queue Serial Port lock intent.
----------------------------------------------------------------------------*/
void AddSerLock(const char *szttyDevice, const char *devLCKfile, const long unsigned int PID, char *COMMAND, const int debug_flag) {
FILE *fdserlck;
int bWrite;
int errno_save = 0;
log_message(debug_flag, "Attempting to get lock on Serial Port %s...",szttyDevice);
do {
fdserlck = fopen((const char *)devLCKfile, "a");
if (fdserlck == NULL) {
log_message(DEBUG_STDERR | DEBUG_SYSLOG, "Problem locking serial device, can't open lock file: %s for write.",devLCKfile);
log_message(DEBUG_STDERR | DEBUG_SYSLOG, "Check owner and execution permission for '%s', they shoud be root '-rws--x--x'.",programName);
exit(2);
}
log_message(debug_flag, "Acquiring shared lock on %s...",devLCKfile);
errno = 0;
if (flock(fileno(fdserlck), LOCK_SH | LOCK_NB) == 0) break; // Lock Acquired
errno_save=errno;
if (errno_save == EWOULDBLOCK) {
log_message(debug_flag, "Would block %s, retry (%d) %s...", devLCKfile, errno_save, strerror(errno_save));
rnd_usleep(25000);
fclose(fdserlck);
} else {
log_message(DEBUG_STDERR | DEBUG_SYSLOG, "Problem locking serial device, can't open lock file: %s for write. (%d) %s", devLCKfile, errno_save, strerror(errno_save));
exit(2);
}
} while (errno_save == EWOULDBLOCK);
log_message(debug_flag, "Shared lock on %s acquired...",devLCKfile);
errno=0;
bWrite = fprintf(fdserlck, "%lu %s\n", PID, COMMAND);
errno_save = errno;
fflush(fdserlck);
fclose(fdserlck); // Will release lock
//fdserlck = NULL;
if (bWrite < 0 || errno_save != 0) {
log_message(debug_flag | DEBUG_SYSLOG, "Problem locking serial device, can't write lock file: %s.", devLCKfile);
log_message(debug_flag | DEBUG_SYSLOG, "(%u) %s", devLCKfile, errno_save, strerror(errno_save));
exit(2);
}
}
void exit_error(modbus_t *ctx)
{
/*
// Wait for line settle
log_message(debug_flag, "Sleeping %dms for line settle...", settle_time);
usleep(1000 * settle_time);
log_message(debug_flag, "Flushed %d bytes", modbus_flush(ctx));
*/
modbus_close(ctx);
modbus_free(ctx);
ClrSerLock(PID);
free(devLCKfile);
free(devLCKfileNew);
if (!metern_flag) {
printf("NOK\n");
log_message(debug_flag | DEBUG_SYSLOG, "NOK");
}
free(PARENTCOMMAND);
exit(EXIT_FAILURE);
}
inline int bcd2int(int val)
{
return((((val & 0xf0) >> 4) * 10) + (val & 0xf));
}
int int2bcd(int val)
{
return(((val / 10) << 4) + (val % 10));
}
int bcd2num(const uint16_t *src, int len)
{
int n = 0;
int m = 1;
int i = 0;
int shift = 0;
int digit = 0;
int j = 0;
for (i = 0; i < len; i++) {
for (j = 0; j < 4; j++) {
digit = ((src[len-1-i]>>shift) & 0x0F) * m;
n += digit;
m *= 10;
shift += 4;
}
}
return n;
}
#if 0
// unused
int getMeasureBCD(modbus_t *ctx, int address, int retries, int nb) {
uint16_t tab_reg[nb * sizeof(uint16_t)];
int rc;
int i;
int j = 0;
int exit_loop = 0;
while (j < retries && exit_loop == 0) {
j++;
if (command_delay) {
log_message(debug_flag, "Sleeping command delay: %ldus", command_delay);
usleep(command_delay);
}
log_message(debug_flag, "%d/%d. Register Address %d [%04X]", j, retries, 30000+address+1, address);
rc = modbus_read_input_registers(ctx, address, nb, tab_reg); // will wait response_timeout for a reply
if (rc == -1) {
log_message(debug_flag | ( j==retries ? DEBUG_SYSLOG : 0), "%s: ERROR (%d) %s, %d/%d, Address %d [%04X]", errno, modbus_strerror(errno), j, retries, 30000+address+1, address);
/* libmodbus already flushes
log_message(debug_flag, "Flushed %d bytes", modbus_flush(ctx));
*/
if (command_delay) {
log_message(debug_flag, "Sleeping command delay: %ldus", command_delay);
usleep(command_delay);
}
} else {
exit_loop = 1;
}
}
if (rc == -1) {
exit_error(ctx);
}
if (debug_flag) {
for (i=0; i < rc; i++) {
log_message(debug_flag, "reg[%d/%d]=%d (0x%X)", i, (rc-1), tab_reg[i], tab_reg[i]);
}
}
int value = bcd2num(&tab_reg[0], rc);
return value;
}
#endif
float getMeasureFloat(modbus_t *ctx, int address, int retries, int nb) {
uint16_t tab_reg[nb * sizeof(uint16_t)];
int rc = -1;
int i;
int j = 0;
int exit_loop = 0;
int errno_save=0;
struct timeval tvStart, tvStop;
while (j < retries && exit_loop == 0) {
j++;
if (command_delay) {
log_message(debug_flag, "Sleeping command delay: %ldus", command_delay);
usleep(command_delay);
}
log_message(debug_flag, "%d/%d. Register Address %d [%04X]", j, retries, 30000+address+1, address);
gettimeofday(&tvStart, NULL);
rc = modbus_read_input_registers(ctx, address, nb, tab_reg);
errno_save = errno;
gettimeofday(&tvStop, NULL);
if (rc == -1) {
if (trace_flag) fprintf(stderr, "%s: ERROR (%d) %s, %d/%d\n", programName, errno_save, modbus_strerror(errno_save), j, retries);
log_message(debug_flag | ( j==retries ? DEBUG_SYSLOG : 0), "ERROR (%d) %s, %d/%d, Address %d [%04X]", errno_save, modbus_strerror(errno_save), j, retries, 30000+address+1, address);
log_message(debug_flag | ( j==retries ? DEBUG_SYSLOG : 0), "Response timeout gave up after %ldus", tv_diff(&tvStop, &tvStart));
/* libmodbus already flushes
log_message(debug_flag, "Flushing modbus buffer");
log_message(debug_flag, "Flushed %d bytes", modbus_flush(ctx));
*/
if (command_delay) {
log_message(debug_flag, "Sleeping command delay: %ldus", command_delay);
usleep(command_delay);
}
} else {
log_message(debug_flag, "Read time: %ldus", tv_diff(&tvStop, &tvStart));
exit_loop = 1;
}
}
if (rc == -1) {
exit_error(ctx);
}
if (debug_flag) {
for (i=0; i < rc; i++) {
log_message(debug_flag, "reg[%d/%d]=%d (0x%X)", i, (rc-1), tab_reg[i], tab_reg[i]);
}
}
// swap LSB and MSB
uint16_t tmp1 = tab_reg[0];
uint16_t tmp2 = tab_reg[1];
tab_reg[0] = tmp2;
tab_reg[1] = tmp1;
float value = modbus_get_float(&tab_reg[0]);
return value;
}
int getConfigBCD(modbus_t *ctx, int address, int retries, int nb) {
uint16_t tab_reg[nb * sizeof(uint16_t)];
int rc = -1;
int i;
int j = 0;
int exit_loop = 0;
while (j < retries && exit_loop == 0) {
j++;
if (command_delay) {
log_message(debug_flag, "Sleeping command delay: %ldus", command_delay);
usleep(command_delay);
}
log_message(debug_flag, "%d/%d. Register Address %d [%04X]", j, retries, 400000+address+1, address);
rc = modbus_read_registers(ctx, address, nb, tab_reg);
if (rc == -1) {
log_message(debug_flag | ( j==retries ? DEBUG_SYSLOG : 0), "ERROR (%d) %s, %d/%d, Address %d [%04X]", errno, modbus_strerror(errno), j, retries, 30000+address+1, address);
/* libmodbus already flushes
log_message(debug_flag, "Flushing modbus buffer");
log_message(debug_flag, "Flushed %d bytes", modbus_flush(ctx));
*/
if (command_delay) {
log_message(debug_flag, "Sleeping command delay: %ldus", command_delay);
usleep(command_delay);
}
} else {
exit_loop = 1;
}
}
if (rc == -1) {
exit_error(ctx);
}
if (debug_flag) {
for (i=0; i < rc; i++) {
log_message(debug_flag, "reg[%d/%d]=%d (0x%X)", i, (rc-1), tab_reg[i], tab_reg[i]);
}
}
int value = bcd2num(&tab_reg[0], rc);
return value;
}
void changeConfigHex(modbus_t *ctx, int address, int new_value, int restart)
{
uint16_t tab_reg[1];
tab_reg[0] = new_value;
if (command_delay) {
log_message(debug_flag, "Sleeping command delay: %ldus", command_delay);
usleep(command_delay);
}
int n = modbus_write_registers(ctx, address, 1, tab_reg);
if (n != -1) {
printf("New value %d for address 0x%X\n", new_value, address);
if (restart == RESTART_TRUE) printf("You have to restart the meter for apply changes\n");
} else {
log_message(DEBUG_STDERR | DEBUG_SYSLOG, "error 1: (%d) %s, %d, %d", errno, modbus_strerror(errno), n);
if (errno == EMBXILFUN) // Illegal function
log_message(DEBUG_STDERR | DEBUG_SYSLOG, "Tip: is the meter in set mode?");
exit_error(ctx);
}
}
void changeConfigFloat(modbus_t *ctx, int address, int new_value, int restart, int nb)
{
uint16_t tab_reg[nb * sizeof(uint16_t)];
modbus_set_float((float) new_value, &tab_reg[0]);
// swap LSB and MSB
uint16_t tmp1 = tab_reg[0];
uint16_t tmp2 = tab_reg[1];
tab_reg[0] = tmp2;
tab_reg[1] = tmp1;
if (command_delay) {
log_message(debug_flag, "Sleeping command delay: %ldus", command_delay);
usleep(command_delay);
}
int n = modbus_write_registers(ctx, address, nb, tab_reg);
if (n != -1) {
printf("New value %d for address 0x%X\n", new_value, address);
if (restart == RESTART_TRUE) printf("You have to restart the meter for apply changes\n");
} else {
log_message(DEBUG_STDERR | DEBUG_SYSLOG, "error 2: (%d) %s, %d, %d", errno, modbus_strerror(errno), n);
if (errno == EMBXILFUN) // Illegal function
log_message(DEBUG_STDERR | DEBUG_SYSLOG, "Tip: is the meter in set mode?");
exit_error(ctx);
}
}
void changeConfigBCD(modbus_t *ctx, int address, int new_value, int restart, int nb)
{
uint16_t tab_reg[nb * sizeof(uint16_t)];
uint16_t u_new_value = int2bcd(new_value);
tab_reg[0] = u_new_value;
if (command_delay) {
log_message(debug_flag, "Sleeping command delay: %ldus", command_delay);
usleep(command_delay);
}
int n = modbus_write_registers(ctx, address, nb, tab_reg);
if (n != -1) {
printf("New value %d for address 0x%X\n", u_new_value, address);
if (restart == RESTART_TRUE) printf("You have to restart the meter for apply changes\n");
} else {
log_message(DEBUG_STDERR | DEBUG_SYSLOG, "error 3: (%d) %s, %d, %d", errno, modbus_strerror(errno), n);
if (errno == EMBXILFUN) // Illegal function
log_message(DEBUG_STDERR | DEBUG_SYSLOG, "Tip: is the meter in set mode?");
exit_error(ctx);
}
}
/*--------------------------------------------------------------------------
getIntLen
----------------------------------------------------------------------------*/
int getIntLen(long value){
long l=!value;
while(value) { l++; value/=10; }
return l;
}
/*--------------------------------------------------------------------------
getPIDcmd
----------------------------------------------------------------------------*/
void *getPIDcmd(long unsigned int PID)
{
int fdcmd;
char *COMMAND = NULL;
size_t cmdLen = 0;
size_t length;
char buffer[1024];
char cmdFilename[getIntLen(PID)+14+1];
// Generate the name of the cmdline file for the process
*cmdFilename = '\0';
snprintf(cmdFilename,sizeof(cmdFilename),"/proc/%lu/cmdline",PID);
// Read the contents of the file
if ((fdcmd = open(cmdFilename, O_RDONLY)) < 0) return NULL;
if ((length = read(fdcmd, buffer, sizeof(buffer))) <= 0) {
close(fdcmd); return NULL;
}
close(fdcmd);
// read does not NUL-terminate the buffer, so do it here
buffer[length] = '\0';
// Get 1st string (command)
cmdLen=strlen(buffer)+1;
if((COMMAND = getMemPtr(cmdLen)) != NULL ) {
strncpy(COMMAND, buffer, cmdLen);
COMMAND[cmdLen-1] = '\0';
}
return COMMAND;
}
/*--------------------------------------------------------------------------
lockSer
----------------------------------------------------------------------------*/
void lockSer(const char *szttyDevice, const long unsigned int PID, int debug_flag)
{
char *pos;
FILE *fdserlck = NULL;
char *COMMAND = NULL;
long unsigned int LckPID;
struct timeval tLockStart, tLockNow;
int bRead;
int errno_save = 0;
int fLen = 0;
int curChar = 0;
char *LckCOMMAND = NULL;
char *LckPIDcommand = NULL;
pos = strrchr(szttyDevice, '/');
if (pos > 0) {
pos++;
devLCKfile = getMemPtr(strlen(ttyLCKloc)+(strlen(szttyDevice)-(pos-szttyDevice))+1);
devLCKfile[0] = '\0';
strcpy(devLCKfile,ttyLCKloc);
strcat(devLCKfile, pos);
devLCKfile[strlen(devLCKfile)] = '\0';
devLCKfileNew = getMemPtr(strlen(devLCKfile)+getIntLen(PID)+2); /* dot & terminator */
devLCKfileNew[0] = '\0';
strcpy(devLCKfileNew,devLCKfile);
sprintf(devLCKfileNew,"%s.%lu",devLCKfile,PID);
devLCKfileNew[strlen(devLCKfileNew)] = '\0';
} else {
devLCKfile = NULL;
}
log_message(debug_flag, "szttyDevice: %s",szttyDevice);
log_message(debug_flag, "devLCKfile: <%s>",devLCKfile);
log_message(debug_flag, "devLCKfileNew: <%s>",devLCKfileNew);
log_message(debug_flag, "PID: %lu", PID);
COMMAND = getPIDcmd(PID);
AddSerLock(szttyDevice, devLCKfile, PID, COMMAND, debug_flag);
LckPID = 0;
long unsigned int oldLckPID = 0;
int staleLockRetries = 0;
int const staleLockRetriesMax = 2;
long unsigned int clrStaleTargetPID = 0;
int missingPidRetries = 0;
int const missingPidRetriesMax = 2;
gettimeofday(&tLockStart, NULL);
tLockNow=tLockStart;
if (debug_flag) log_message(debug_flag, "Checking for lock");
while(LckPID != PID && tv_diff(&tLockNow, &tLockStart) <= yLockWait*1000000L) {
do {
fdserlck = fopen(devLCKfile, "r");
if (fdserlck == NULL) {
log_message(debug_flag | DEBUG_SYSLOG, "Problem locking serial device, can't open lock file: %s for read.",devLCKfile);
exit(2);
}
//log_message(debug_flag, "Acquiring shared lock on %s...",devLCKfile);
errno = 0;
if (flock(fileno(fdserlck), LOCK_SH | LOCK_NB) == 0) break; // Lock Acquired
errno_save=errno;
if (errno_save == EWOULDBLOCK) {
log_message(debug_flag, "Would block %s, retry (%d) %s...", devLCKfile, errno_save, strerror(errno_save));
rnd_usleep(25000);
fclose(fdserlck);
} else {
log_message(DEBUG_STDERR | DEBUG_SYSLOG, "Problem locking serial device, can't open lock file: %s for read. (%d) %s", devLCKfile, errno_save, strerror(errno_save));
exit(2);
}
} while (errno_save == EWOULDBLOCK);
//log_message(debug_flag, "Shared lock on %s acquired...",devLCKfile);
fLen = 0;
while ((curChar = fgetc(fdserlck)) != EOF && curChar != '\n' && curChar != ' ') fLen++;
fLen = 0;
if (curChar == ' ') while ((curChar = fgetc(fdserlck)) != EOF && curChar != '\n') fLen++;
rewind(fdserlck);
//if (LckPID != oldLckPID) log_message(debug_flag, "fLen=%i", fLen);
LckCOMMAND = getMemPtr(fLen+1);
//if (LckPID != oldLckPID) log_message(debug_flag, "fLen=%i LckCOMMAND %s", fLen, (LckCOMMAND==NULL ? "is null" : "is not null"));
LckCOMMAND[0] = '\0';
LckPID=0;
errno = 0;
bRead = fscanf(fdserlck, "%lu%*[ ]%[^\n]\n", &LckPID, LckCOMMAND);
errno_save = errno;
fclose(fdserlck);
if (LckPID != oldLckPID) {
log_message(debug_flag | (bRead==EOF || errno_save != 0 ? DEBUG_SYSLOG : 0), "errno=%i, bRead=%i PID=%lu LckPID=%lu", errno_save, bRead, PID, LckPID);
log_message(debug_flag, "Checking process %lu (%s) for lock", LckPID, LckCOMMAND);
//oldLckPID = LckPID;
}
if (bRead == EOF || LckPID == 0 || errno_save != 0) {
log_message(debug_flag | DEBUG_SYSLOG, "Problem locking serial device, can't read PID from lock file: %s.",devLCKfile);
log_message(debug_flag | DEBUG_SYSLOG, "errno=%i, bRead=%i PID=%lu LckPID=%lu", errno_save, bRead, PID, LckPID);
if (errno_save != 0) {
// Real error
log_message(debug_flag | DEBUG_SYSLOG, "(%u) %s", errno_save, strerror(errno_save));
free(LckCOMMAND); free(LckPIDcommand); free(COMMAND);
exit(2);
} else {
if (missingPidRetries < missingPidRetriesMax) {
missingPidRetries++;
log_message(debug_flag, "%s miss process self PID from lock file?",devLCKfile);
} else if (missingPidRetries >= missingPidRetriesMax) {
// Self PID missing... (Should never happen)
log_message(debug_flag | DEBUG_SYSLOG, "%s miss process self PID from lock file, amending.",devLCKfile);
AddSerLock(szttyDevice, devLCKfile, PID, COMMAND, debug_flag);
//LckPID=0;
missingPidRetries = 0;
}
}
oldLckPID = LckPID;
} else { //fread OK
// We got a pid from lockfile, let's clear missing pid status
missingPidRetries = 0;
LckPIDcommand = getPIDcmd(LckPID);
if (LckPID != oldLckPID) {
log_message(debug_flag, "PID: %lu COMMAND: \"%s\" LckPID: %lu LckCOMMAND: \"%s\" LckPIDcommand \"%s\"%s", PID, COMMAND
, LckPID, LckCOMMAND, LckPIDcommand
, LckPID == PID ? " = me" : "");
oldLckPID = LckPID;
}
// PID - this process
// LckPID - PID from lock file
// COMMAND - this process
// LckCOMMAND - process command from lock file
// LckPIDcommand - process command of process using PID from lock file
if ((PID != LckPID && LckPIDcommand == NULL) || (LckCOMMAND[0]!='\0' && strcmp(LckPIDcommand,LckCOMMAND) != 0) || strcmp(LckPIDcommand,"") == 0) {
// Is it a stale lock pid?
if (staleLockRetries < staleLockRetriesMax) {
staleLockRetries++;
clrStaleTargetPID = LckPID;
log_message(debug_flag | (staleLockRetries > 1 ? DEBUG_SYSLOG : 0), "Stale pid lock(%d)? PID=%lu, LckPID=%lu, LckCOMMAND='%s', LckPIDCommand='%s'", staleLockRetries, PID, LckPID, LckCOMMAND, LckPIDcommand);
} else if (LckPID == clrStaleTargetPID && staleLockRetries >= staleLockRetriesMax) {
log_message(debug_flag | DEBUG_SYSLOG, "Clearing stale serial port lock. (%lu)", LckPID);
ClrSerLock(LckPID);
staleLockRetries = 0;
clrStaleTargetPID = 0;
}
} else {
// Pid lock have a process running, let's reset stale pid retries
staleLockRetries = 0;
clrStaleTargetPID = 0;
}
}
if (yLockWait > 0 && LckPID != PID) {
rnd_usleep(25000);
//log_message(debug_flag, "Sleeping %luus", rnd_usleep(25000));
}
// Cleanup and loop
if (LckCOMMAND != NULL) {
free(LckCOMMAND);
LckCOMMAND = NULL;
}
if (LckPIDcommand != NULL) {
free(LckPIDcommand);
LckPIDcommand = NULL;