/
mercury-mon.c
352 lines (302 loc) · 12.1 KB
/
mercury-mon.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
/*
* Mercury power meter monitoring application. The application is designed
* to stay active and regularly poll data from the power meter.
*
* Installation as a service on RPi:
*
* 1. Create service file
* $ sudo nano /etc/systemd/system/mercury-mon.service
*
* Description=mercury-mon
*
* Wants=network.target
* After=syslog.target network-online.target
*
* [Service]
* Type=simple
* ExecStart=/home/den/Shden/mercury236/mercury-mon /dev/ttyUSB0 16500 20
* Restart=on-failure
* RestartSec=10
* KillMode=process
*
* [Install]
* WantedBy=multi-user.target
*
* 2. Reload services:
* $ sudo systemctl daemon-reload
*
* 3. Enable the service:
* $ sudo systemctl enable mercury-mon
*
* 4. Start the service:
* $ sudo systemctl start
*
* 5. Check the status of service:
* $ systemctl status mercury-mon
*/
#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/select.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <semaphore.h>
#include <syslog.h>
#include <fcntl.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
#include "mercury236.h"
#define BSZ 255
#define OPT_DEBUG "--debug"
#define OPT_HELP "--help"
int debugPrint = 0;
typedef enum
{
EXIT_OK = 0,
EXIT_FAIL = -1
} ExitCode;
// -- Command line usage help
void printUsage()
{
printf("Usage: mercury-mon [RS485] [MaxPower] [LogFactor] [PollTime]\n\r\n\r");
printf(" RS485\t\taddress of RS485 dongle (e.g. /dev/ttyUSB0), required.\n\r");
printf(" MaxPower\tpower (Watt) allowed, if this value exceeded, monitor calls script to deactivate some consumers.");
printf(" LogFactor\twrite to log 1 of LogFactor power measurments to log file.\n\r");
printf(" PollTime\tpower meter poll time cycle (seconds).\n\r");
printf(" %s\tto print extra debug info.\n\r", OPT_DEBUG);
printf("\n\r");
printf(" %s\tprints this screen.\n\r", OPT_HELP);
printf("\n\r");
printf("Press Ctrl+C to exit.\n\r");
}
int terminateMonitorNow = 0;
// -- Signal Handler for SIGINT
void sigint_handler(int sig_num)
{
printf("\nTerminating monitor by Ctrl+C...\n");
terminateMonitorNow = 1;
}
// -- All checks for current power go here
void handleConsumptionUpdate(float currentPower, float maxPower)
{
if (currentPower > maxPower)
{
syslog(LOG_NOTICE, "Maximum power exceeded (%8.2fW).\n\r", currentPower);
FILE* f = fopen("/home/den/Shden/appliances/mainHeater", "w");
if (NULL != f)
{
fputc('0', f);
fclose(f);
syslog(LOG_NOTICE, "Main heater turned off.\n\r");
}
}
}
// Usage: mercury-mon [RS485] [MaxPower] [LogFactor] [options]
int main(int argc, const char** args)
{
openlog(NULL, LOG_PID, LOG_DAEMON);
// must have RS485 address (1st required param)
if (argc < 2)
{
syslog(LOG_NOTICE, "Error: no RS485 device specified.\n\r");
printUsage();
closelog();
exit(EXIT_FAIL);
}
// must have max power (2nd requred param)
if (argc < 3)
{
syslog(LOG_NOTICE, "Error: no max power specified.\n\r");
printUsage();
closelog();
exit(EXIT_FAIL);
}
// must have log factor (3rd requried param)
if (argc < 4)
{
syslog(LOG_NOTICE, "Error: no log factor provided.\n\r");
printUsage();
closelog();
exit(EXIT_FAIL);
}
// must have poll time (4th requred param)
if (argc < 5)
{
syslog(LOG_NOTICE, "Error: no poll time provided.\n\r");
printUsage();
closelog();
exit(EXIT_FAIL);
}
// Ctrl+C handler
signal(SIGINT, sigint_handler);
// get RS485 device specification
char dev[BSZ];
strncpy(dev, args[1], BSZ);
// get maximum allowed power
int maxPower = strtol(args[2], NULL, 10);
if (maxPower < 100 || maxPower > 30000)
{
syslog(LOG_NOTICE, "Error: maximum power (%d) is out of the range (100..30000).\n\r", maxPower);
closelog();
exit(EXIT_FAIL);
}
// get log factor
int logFactor = strtol(args[3], NULL, 10);
if (logFactor < 1 || logFactor > 100)
{
syslog(LOG_NOTICE, "Error: log factor (%d) is out of the range (1..100).\n\r", logFactor);
closelog();
exit(EXIT_FAIL);
}
// get poll time
int pollTime = strtol(args[4], NULL, 10);
if (pollTime < 1 || pollTime > 600)
{
syslog(LOG_NOTICE, "Error: poll time (%d) is out of the range (1..600).\n\r", pollTime);
closelog();
exit(EXIT_FAIL);
}
// get command line options
for (int i=5; i<argc; i++)
{
if (!strcmp(OPT_DEBUG, args[i]))
debugPrint = 1;
// else if (!strcmp(OPT_TEST_RUN, args[i]))
// dryRun = 1;
// else if (!strcmp(OPT_HUMAN, args[i]))
// format = OF_HUMAN;
// else if (!strcmp(OPT_CSV, args[i]))
// format = OF_CSV;
// else if (!strcmp(OPT_JSON, args[i]))
// format = OF_JSON;
// else if (!strcmp(OPT_HEADER, args[i]))
// header = 1;
else if (!strcmp(OPT_HELP, args[i]))
{
printUsage();
closelog();
exit(EXIT_OK);
}
else
{
syslog(LOG_NOTICE, "Error: %s option is not recognised\n\r", args[i]);
printUsage();
closelog();
exit(EXIT_FAIL);
}
}
OutputBlock o;
bzero(&o, sizeof(OutputBlock));
// semaphore code to lock the shared mem
int prevMask = umask(0000);
sem_t* semptr = sem_open(
MERCURY_SEMAPHORE, /* name */
O_CREAT, /* create the semaphore */
MERCURY_ACCESS_PERM, /* protection perms */
1); /* initial value */
umask(prevMask);
if (SEM_FAILED == semptr)
{
syslog(LOG_NOTICE, "Semaphore open error.");
closelog();
exit(EXIT_FAIL);
}
// Open RS485 dongle
// O_RDWR Read/Write access to serial port
// O_NOCTTY - No terminal will control the process
// O_NDELAY - Non blocking open
int RS485 = open(dev, O_RDWR | O_NOCTTY | O_NDELAY);
if (RS485 < 0)
{
syslog(LOG_NOTICE, "Cannot open %s terminal channel.\n\r", dev);
closelog();
exit(EXIT_FAIL);
}
fcntl(RS485, F_SETFL, 0);
struct termios serialPortSettings;
bzero(&serialPortSettings, sizeof(serialPortSettings));
cfsetispeed(&serialPortSettings, BAUDRATE);
cfsetospeed(&serialPortSettings, BAUDRATE);
serialPortSettings.c_cflag &= PARENB; /* Disables the Parity Enable bit(PARENB),So No Parity */
serialPortSettings.c_cflag &= ~CSTOPB; /* CSTOPB = 2 Stop bits,here it is cleared so 1 Stop bit */
serialPortSettings.c_cflag &= ~CSIZE; /* Clears the mask for setting the data size */
serialPortSettings.c_cflag |= CS8; /* Set the data bits = 8 */
serialPortSettings.c_cflag |= CREAD | CLOCAL; /* Enable receiver,Ignore Modem Control lines */
serialPortSettings.c_iflag &= ~(IXON | IXOFF | IXANY); /* Disable XON/XOFF flow control both i/p and o/p */
serialPortSettings.c_iflag &= ~(ICANON | ECHO | ECHOE | ISIG); /* Non Cannonical mode */
serialPortSettings.c_oflag &= ~OPOST; /* No Output Processing */
tcflush(RS485, TCIOFLUSH);
tcsetattr(RS485, TCSANOW, &serialPortSettings);
int exitCode = 0;
int resCheckChannel = CHECK_CHANNEL_FAILURE;
if (!sem_wait(semptr))
{
resCheckChannel = checkChannel(RS485);
sem_post(semptr);
}
int loopCount = 0;
switch(resCheckChannel)
{
case OK:
do
{
loopCount++;
int loopStatus = OK;
/* wait until semaphore != 0 */
if (!sem_wait(semptr))
{
loopStatus =
initConnection(RS485) +
// getU(RS485, &o.U) + // Get voltage by phases
// getI(RS485, &o.I) + // Get current by phases
// getCosF(RS485, &o.C) + // Get power cos(f) by phases
// getF(RS485, &o.f) + // Get grid frequency
// getA(RS485, &o.A) + // Get phase angles
// getP(RS485, &o.P) + // Get active power consumption by phases
// Only poll for power consumption
getS(RS485, &o.S) + // Get reactive power consumption by phases
// // Get power counter from reset, for yesterday and today
// getW(RS485, &o.PR, PP_RESET, 0, 0) + // total from reset
// getW(RS485, &o.PRT[0], PP_RESET, 0, 0+1) + // day tariff from reset
// getW(RS485, &o.PRT[1], PP_RESET, 0, 1+1) + // night tariff from reset
// getW(RS485, &o.PY, PP_YESTERDAY, 0, 0) +
// getW(RS485, &o.PT, PP_TODAY, 0, 0) +
closeConnection(RS485);
// increment semaphore to let other processes go
sem_post(semptr);
}
if (loopCount >= logFactor)
{
loopCount = 0;
syslog(LOG_NOTICE, (OK == loopStatus)
? "Current power consumption: %8.2fW\n\r"
: "One or more errors occurred during data collection.\n\r", o.S.sum);
}
// run all checks for the obtained power value
handleConsumptionUpdate(o.S.sum, maxPower);
usleep(pollTime * 1000 * 1000); // 5 sec
} while (!terminateMonitorNow);
printf("Monitor terminated successfully.\n\r");
exitCode = EXIT_OK;
break;
case CHECK_CHANNEL_FAILURE:
syslog(LOG_NOTICE, "Power meter channel time out.\n\r");
exitCode = EXIT_FAIL;
break;
default:
syslog(LOG_NOTICE, "Power meter communication channel test failed.\n\r");
exitCode = EXIT_FAIL;
break;
}
// Clean up
// munmap(outputBlockPtr, sizeof(OutputBlock)); /* unmap the storage */
close(RS485);
sem_close(semptr);
closelog();
exit(exitCode);
}