forked from wmbusmeters/wmbusmeters
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serial.cc
351 lines (292 loc) · 9.01 KB
/
serial.cc
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
/*
Copyright (C) 2017-2018 Fredrik Öhrström
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 3 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, see <http://www.gnu.org/licenses/>.
*/
#include"util.h"
#include"serial.h"
#include <algorithm>
#include <fcntl.h>
#include <functional>
#include <memory.h>
#include <pthread.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
static int openSerialTTY(const char *tty, int baud_rate);
struct SerialDeviceTTY;
struct SerialCommunicationManagerImp : public SerialCommunicationManager {
SerialCommunicationManagerImp(time_t exit_after_seconds);
SerialDevice *createSerialDeviceTTY(string dev, int baud_rate);
void listenTo(SerialDevice *sd, function<void()> cb);
void stop();
void waitForStop();
bool isRunning();
void opened(SerialDeviceTTY *sd);
void closed(SerialDeviceTTY *sd);
private:
void *eventLoop();
static void *startLoop(void *);
bool running_;
pthread_t thread_;
int max_fd_;
vector<SerialDevice*> devices_;
time_t start_time_;
time_t exit_after_seconds_;
};
struct SerialDeviceImp : public SerialDevice {
private:
function<void()> on_data_;
friend struct SerialCommunicationManagerImp;
};
struct SerialDeviceTTY : public SerialDeviceImp {
SerialDeviceTTY(string device, int baud_rate, SerialCommunicationManagerImp *manager);
bool open(bool fail_if_not_ok);
void close();
bool send(vector<uchar> &data);
int receive(vector<uchar> *data);
int fd() { return fd_; }
SerialCommunicationManager *manager() { return manager_; }
private:
string device_;
int baud_rate_;
int fd_;
pthread_mutex_t write_lock_ = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t read_lock_ = PTHREAD_MUTEX_INITIALIZER;
SerialCommunicationManagerImp *manager_;
};
SerialDeviceTTY::SerialDeviceTTY(string device, int baud_rate,
SerialCommunicationManagerImp *manager) {
device_ = device;
baud_rate_ = baud_rate;
manager_ = manager;
}
bool SerialDeviceTTY::open(bool fail_if_not_ok)
{
bool ok = checkCharacterDeviceExists(device_.c_str(), fail_if_not_ok);
if (!ok) return false;
fd_ = openSerialTTY(device_.c_str(), baud_rate_);
if (fd_ == -1) {
if (fail_if_not_ok) {
error("Could not open %s with %d baud N81\n", device_.c_str(), baud_rate_);
} else {
return false;
}
}
manager_->opened(this);
verbose("(serial) opened %s\n", device_.c_str());
return true;
}
void SerialDeviceTTY::close()
{
::flock(fd_, LOCK_UN);
::close(fd_);
fd_ = -1;
manager_->closed(this);
verbose("(serial) closed %s\n", device_.c_str());
}
bool SerialDeviceTTY::send(vector<uchar> &data)
{
if (data.size() == 0) return true;
pthread_mutex_lock(&write_lock_);
bool rc = true;
int n = data.size();
int written = 0;
while (true) {
int nw = write(fd_, &data[written], n-written);
if (nw > 0) written += nw;
if (nw < 0) {
if (errno==EINTR) continue;
rc = false;
goto end;
}
if (written == n) break;
}
if (isDebugEnabled()) {
string msg = bin2hex(data);
debug("(serial %s) sent \"%s\"\n", device_.c_str(), msg.c_str());
}
end:
pthread_mutex_unlock(&write_lock_);
return rc;
}
int SerialDeviceTTY::receive(vector<uchar> *data)
{
pthread_mutex_lock(&read_lock_);
data->clear();
int available = 0;
int num_read = 0;
ioctl(fd_, FIONREAD, &available);
if (!available) goto end;
data->resize(available);
while (true) {
int nr = read(fd_, &((*data)[num_read]), available-num_read);
if (nr > 0) num_read += nr;
if (nr < 0) {
if (errno==EINTR) continue;
goto end;
}
if (num_read == available) break;
}
if (isDebugEnabled()) {
string msg = bin2hex(*data);
debug("(serial %s) received \"%s\"\n", device_.c_str(), msg.c_str());
}
end:
pthread_mutex_unlock(&read_lock_);
return num_read;
}
SerialCommunicationManagerImp::SerialCommunicationManagerImp(time_t exit_after_seconds)
{
running_ = true;
max_fd_ = 0;
pthread_create(&thread_, NULL, startLoop, this);
//running_ = (rc == 0);
start_time_ = time(NULL);
exit_after_seconds_ = exit_after_seconds;
}
void *SerialCommunicationManagerImp::startLoop(void *a) {
auto t = (SerialCommunicationManagerImp*)a;
return t->eventLoop();
}
SerialDevice *SerialCommunicationManagerImp::createSerialDeviceTTY(string device, int baud_rate) {
SerialDevice *sd = new SerialDeviceTTY(device, baud_rate, this);
return sd;
}
void SerialCommunicationManagerImp::listenTo(SerialDevice *sd, function<void()> cb) {
SerialDeviceImp *si = dynamic_cast<SerialDeviceImp*>(sd);
si->on_data_ = cb;
}
void SerialCommunicationManagerImp::stop()
{
running_ = false;
}
void SerialCommunicationManagerImp::waitForStop()
{
while (running_) { usleep(1000*1000);}
pthread_kill(thread_, SIGUSR1);
pthread_join(thread_, NULL);
for (SerialDevice *d : devices_) {
d->close();
}
}
bool SerialCommunicationManagerImp::isRunning()
{
return running_;
}
void SerialCommunicationManagerImp::opened(SerialDeviceTTY *sd) {
max_fd_ = max(sd->fd(), max_fd_);
devices_.push_back(sd);
pthread_kill(thread_, SIGUSR1);
}
void SerialCommunicationManagerImp::closed(SerialDeviceTTY *sd) {
auto p = find(devices_.begin(), devices_.end(), sd);
if (p != devices_.end()) {
devices_.erase(p);
}
max_fd_ = 0;
for (SerialDevice *d : devices_) {
if (d->fd() > max_fd_) {
max_fd_ = d->fd();
}
}
}
void *SerialCommunicationManagerImp::eventLoop() {
fd_set readfds;
while (running_) {
FD_ZERO(&readfds);
for (SerialDevice *d : devices_) {
FD_SET(d->fd(), &readfds);
}
struct timeval timeout { 3600, 0 };
if (exit_after_seconds_ > 0) {
time_t curr = time(NULL);
time_t diff = curr-start_time_;
if (diff > exit_after_seconds_) {
verbose("(serial) exit after %ld seconds\n", diff);
stop();
break;
}
timeout.tv_sec = exit_after_seconds_ - diff;
}
int activity = select(max_fd_+1 , &readfds , NULL , NULL, &timeout);
if (!running_) break;
if (activity < 0 && errno!=EINTR) {
warning("(serial) internal error after select! errno=%s\n", strerror(errno));
}
if (activity > 0) {
for (SerialDevice *d : devices_) {
if (FD_ISSET(d->fd(), &readfds)) {
SerialDeviceImp *si = dynamic_cast<SerialDeviceImp*>(d);
if (si->on_data_) si->on_data_();
}
}
}
}
verbose("(serial) event loop stopped!\n");
return NULL;
}
SerialCommunicationManager *createSerialCommunicationManager(time_t exit_after_seconds)
{
return new SerialCommunicationManagerImp(exit_after_seconds);
}
static int openSerialTTY(const char *tty, int baud_rate)
{
int rc = 0;
speed_t speed = 0;
struct termios tios;
int fd = open(tty, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
usleep(1000*1000);
fd = open(tty, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) goto err;
}
rc = flock(fd, LOCK_EX | LOCK_NB);
if (rc == -1) {
// It is already locked by another wmbusmeter process.
warning("Device %s is already in use and locked.\n", tty);
goto err;
}
switch (baud_rate) {
case 9600: speed = B9600; break;
case 19200: speed = B19200; break;
case 38400: speed = B38400; break;
case 57600: speed = B57600; break;
case 115200: speed = B115200;break;
default:
goto err;
}
memset(&tios, 0, sizeof(tios));
rc = cfsetispeed(&tios, speed);
if (rc < 0) goto err;
rc = cfsetospeed(&tios, speed);
if (rc < 0) goto err;
tios.c_cflag |= (CREAD | CLOCAL);
tios.c_cflag &= ~CSIZE;
tios.c_cflag |= CS8;
tios.c_cflag &=~ CSTOPB;
tios.c_cflag &=~ PARENB;
tios.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
tios.c_iflag &= ~INPCK;
tios.c_iflag &= ~(IXON | IXOFF | IXANY);
tios.c_oflag &=~ OPOST;
tios.c_cc[VMIN] = 0;
tios.c_cc[VTIME] = 0;
rc = tcsetattr(fd, TCSANOW, &tios);
if (rc < 0) goto err;
return fd;
err:
if (fd != -1) close(fd);
return -1;
}