-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.cpp
427 lines (380 loc) · 10.2 KB
/
utils.cpp
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
#include <stdio.h>
#ifdef ESP_PLATFORM
// am ESP32 geht das std::stoi sonst ned: - muss vorm utils.h includet sein
#define _GLIBCXX_USE_C99 1
#endif
//#include <stdexcept>
//#include <sstream>
#include <iostream>
#include <memory>
#include <stdarg.h>
#include <cctype>
#include <algorithm>
#include <string.h>
#include "Thread.h"
#include "utils.h"
#ifdef HAVE_EXECINFO
// fürs backtrace:
#include <execinfo.h>
// fürs demangle:
#include <cxxabi.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
// dirname
#include <libgen.h>
// intptr_t
#include <inttypes.h>
#ifdef ESP_PLATFORM
// fürs Serial
#include <Arduino.h>
#include "config.h"
#endif
#ifdef SYSLOG_SERVER
#include <Syslog.h>
#include <WiFiUdp.h>
#if not defined SYSLOG_PORT
#define SYSLOG_PORT 514
#endif
WiFiUDP udpClient;
Syslog syslog(udpClient, SYSLOG_PROTO_IETF);
#endif
#define TAG "utils"
namespace utils {
utils::Log log;
};
const std::string NOT_SET="__NOT_SET";
Config config;
Config::Config() {
}
void Config::init(const std::string &confFilename) {
std::string data=readFile(confFilename);
std::istringstream f(data);
std::string line;
while (std::getline(f, line)) {
std::string key, value;
size_t komma=line.find_first_of('=');
if(komma != std::string::npos) {
key=line.substr(0,komma);
value=line.substr(komma+1);
key=utils::trim(key);
value=utils::trim(value);
} else {
key=line;
value="";
}
this->data.insert( std::pair<std::string, std::string>(key, value) );
}
}
const std::string Config::get(const std::string key) {
try {
std::multimap<std::string, std::string>::const_iterator it = this->data.find(key);
if(it == this->end()) { // raspi 20161004 macht keine exception wenn nicht gefunden
return NOT_SET;
}
return it->second;
} catch(std::out_of_range &e) {
throw std::out_of_range("key " + key + " not found");
}
}
int utils::stoi(const std::string &in) {
if(in == NOT_SET) {
throw std::runtime_error("NOT SET");
}
#if __cplusplus > 199711L
size_t end=0;
int ret=std::stoi(in, &end, 0);
if(end != in.length()) {
#else
char *endp=NULL;
int ret=::strtol(in.c_str(), &endp, 0);
if(endp != NULL) {
#endif
throw std::runtime_error("error converting number");
}
return ret;
}
bool utils::startsWith(const std::string &str, const std::string &with) {
return str.find(with) == 0;
}
bool utils::startsWith(const std::string &str, const char *with) {
return str.find(with) == 0;
}
bool utils::endsWith(const std::string &str, const char *with) {
return str.rfind(with) == str.length()-strlen(with);
}
/**
* tut spaces am ende weg
*/
void strtrim(char *s)
{
char *pos=s+strlen(s);
while(pos > s) {
pos--;
if(isspace(*pos)) {
*pos='\0';
} else
break;
}
}
#ifdef HAVE_EXECINFO
void utils::dumpBacktrace() {
void *array[10];
size_t size;
// get void*'s for all entries on the stack
size = backtrace(array, 10);
// print out all the frames to stderr das kamma mit addr2line noch anschaun dann:
//fprintf(stderr, "Error: %s size=%zd\n", what.c_str(), size);
backtrace_symbols_fd(array, size, STDERR_FILENO);
/*
messages = backtrace_symbols(array, size);
// skip first stack frame (points here)
for (i = 1; i < size && messages != NULL; ++i) {
fprintf(stderr, "[bt]: (%d) %s\n", i, messages[i]);
}
free(messages);
*/
// http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes
char ** messages = backtrace_symbols(array, size);
// skip first stack frame (points here)
for (size_t i = 1; i < size && messages != NULL; ++i) {
char *mangled_name = 0, *offset_begin = 0, *offset_end = 0;
// find parantheses and +address offset surrounding mangled name
for (char *p = messages[i]; *p; ++p) {
if (*p == '(') {
mangled_name = p;
} else if (*p == '+') {
offset_begin = p;
} else if (*p == ')') {
offset_end = p;
break;
}
}
// if the line could be processed, attempt to demangle the symbol
if (mangled_name && offset_begin && offset_end && mangled_name < offset_begin) {
*mangled_name++ = '\0';
*offset_begin++ = '\0';
*offset_end++ = '\0';
int status;
char * real_name = abi::__cxa_demangle(mangled_name, 0, 0, &status);
// if demangling is successful, output the demangled function name
if (status == 0) {
std::cerr << "[bt]: (" << i << ") " << messages[i] << " : "
<< real_name << "+" << offset_begin << offset_end
<< std::endl;
}
// otherwise, output the mangled function name
else {
std::cerr << "[bt]: (" << i << ") " << messages[i] << " : "
<< mangled_name << "+" << offset_begin << offset_end
<< std::endl;
}
free(real_name);
}
// otherwise, print the whole line
else {
std::cerr << "[bt]: (" << i << ") " << messages[i] << std::endl;
}
}
std::cerr << std::endl;
free(messages);
}
#endif
#undef runtime_error
std::RuntimeExceptionWithBacktrace::RuntimeExceptionWithBacktrace(const std::string &what) throw()
: std::runtime_error(what)
{
printf("Error: %s\n", what.c_str());
utils::dumpBacktrace();
}
std::RuntimeExceptionWithBacktrace::~RuntimeExceptionWithBacktrace() throw ()
{
}
/**
* liest eine komplette Datei, wenn nicht gefunden dann relativ zum bin dir
* @param filename - das was eingelesen wird, kopie(!!)
*/
#if not defined ESP_PLATFORM
std::string readFile(const std::string &filename)
{
std::string ret;
const char *cf=filename.c_str();
std::string filename2;
struct stat buf;
if(stat(cf, &buf) != 0) {
char execpath[MAXPATHLEN];
if(readlink("/proc/self/exe", execpath, sizeof(execpath)) <= 0) {
printf("error reading /proc/self/exe\n");
abort();
}
char *linkpath=dirname(execpath);
filename2 = std::string(linkpath) + '/' + filename ;
cf=filename2.c_str();
if(stat(cf, &buf) != 0) {
throw std::runtime_error(utils::format("error stat file %s",cf));
}
}
ret.resize(buf.st_size,'\0');
FILE *f=fopen(cf,"r");
if(!f) {
throw std::runtime_error(utils::format("error reading file %s",filename.c_str()));
} else {
const char *data=ret.data(); // mutig ...
fread((void*)data,1,buf.st_size,f);
fclose(f);
DEBUGF("reading %s %lu bytes",filename.c_str(),buf.st_size);
}
return ret;
}
void writeFile(const std::string &filename, const std::string &data) {
FILE *f=fopen(filename.c_str(),"w");
if(!f) {
throw std::runtime_error(utils::format("error writing file %s",filename.c_str()));
} else {
fwrite((void*)data.data(),1,data.size(),f);
fclose(f);
DEBUGF("written @%s %zd bytes\n",filename.c_str(),data.size());
}
}
#endif
/* is template im utils.h
std::string utils::format(const char *fmt, ...) {
size_t size = 0;
va_list ap;
char *buf=NULL;
va_start(ap, fmt);
size=vasprintf(&buf, fmt, ap );
va_end(ap);
if(buf==NULL) {
DEBUGF("format failed: fmt:%s",fmt);
return std::string("format failed");
}
printf("format result size:%zu string:%s\n", size, buf);
std::string ret=std::string( buf, size ); // We don't want the '\0' inside
free(buf);
return ret;
}
*/
/**
* das muss am ende der Datei sein!!!
* @throws exception bei einem fehler / wenn size nicht gelesen werden konnte
*/
#undef read
ssize_t myRead(int so, void *data, size_t size) {
int read=0;
// printf("myRead: %zd\n",size);
while(read < (int) size) {
// printf("read: %zd\n",size-read);
int rc=::read(so,((char *) data)+read,size-read);
// printf("rc: %d\n",rc);
if(rc < 0) {
throw std::runtime_error("error reading data");
} else if(rc == 0) { // stream is blocking -> sollt nie vorkommen
throw std::runtime_error("nothing to read");
}
read+=rc;
}
return read;
}
bool utils::isDir(const char *filename) {
struct stat buffer;
if(stat(filename, &buffer) != 0) {
return false;
}
if(S_ISDIR(buffer.st_mode)) {
return true;
} else {
return false;
}
}
ThreadSpecific threadSpecificClientID;
ThreadSpecific threadSpecificMessageID;
void utils::setThreadClientID(int clientID) {
intptr_t tmp = clientID;
threadSpecificClientID.set((void*) tmp);
}
void utils::setThreadMessageID(int messageID) {
intptr_t tmp = messageID;
threadSpecificMessageID.set((void*) tmp);
}
int utils::getThreadClientID() {
intptr_t tmp = (intptr_t) (threadSpecificClientID.get() );
return (int) tmp;
}
int utils::getThreadMessageID() {
intptr_t tmp = (intptr_t) (threadSpecificMessageID.get() );
return (int) tmp;
}
// c++11 magick
std::string utils::trim(const std::string &s)
{
// BOOST_NO_CXX11_AUTO_DECLARATIONS
#if __cplusplus > 199711L
auto wsfront=std::find_if_not(s.begin(),s.end(),[](int c){return std::isspace(c);});
auto wsback=std::find_if_not(s.rbegin(),s.rend(),[](int c){return std::isspace(c);}).base();
return (wsback<=wsfront ? std::string() : std::string(wsfront,wsback));
#else
size_t endpos = s.find_last_not_of(" \t");
size_t startpos = s.find_first_not_of(" \t");
std::string ret=s;
if( std::string::npos != endpos ) {
ret = s.substr( 0, endpos+1 );
ret = ret.substr( startpos );
}
return ret;
#endif
}
void utils::Log::init(bool softAP) {
setlinebuf(stdout);
setlinebuf(stderr);
#ifdef SYSLOG_SERVER
DEBUGF("~~~~~~~~~~~~~~~ init syslog server @%s:%d", SYSLOG_SERVER, SYSLOG_PORT);
udpClient.stop();
if(softAP) {
NOTICEF("disabling syslog server @%s:%d - softAP ", SYSLOG_SERVER, SYSLOG_PORT);
syslog.server(NULL, SYSLOG_PORT);
} else {
NOTICEF("enabling syslog server @%s:%d", SYSLOG_SERVER, SYSLOG_PORT);
syslog.server(SYSLOG_SERVER, SYSLOG_PORT);
syslog.deviceHostname(LOK_NAME);
syslog.appName("btcontrol");
syslog.defaultPriority(LOG_KERN);
}
#endif
}
void utils::Log::printf(int level, const char *file, int line, const char *fmt, ...) {
#ifdef ESP_PLATFORM
// Serial.printf("%d: ", utils::getThreadClientID());
Serial.printf("%s:%d ", file, line);
va_list args;
va_start(args, fmt);
char *data=NULL;
vasprintf(&data, fmt, args);
Serial.print(data);
#ifdef SYSLOG_SERVER
int l=LOG_DEBUG;
if(level == LEVEL_NOTICE)
l=LOG_NOTICE;
else if(level == LEVEL_ERROR)
l=LOG_ERR;
if(!syslog.log(l, data)) {
// Serial.println("Error sending data to syslog server!");
}
#endif
free(data);
va_end(args);
#else
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
#endif
}
#if ! defined(ESP_PLATFORM) && ! defined(HAVE_RASPI_WIRINGPI)
unsigned long millis() {
struct timespec ts;
clock_gettime(CLOCK_BOOTTIME, &ts);
return ts.tv_sec*1000 + ts.tv_nsec / 1000000;
}
#endif