forked from openalpr/openalpr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdaemon.cpp
494 lines (376 loc) · 13.4 KB
/
daemon.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
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
#include <unistd.h>
#include <sstream>
#include <execinfo.h>
#include "daemon/beanstalk.hpp"
#include "video/logging_videobuffer.h"
#include "daemon/daemonconfig.h"
#include "inc/safequeue.h"
#include "tclap/CmdLine.h"
#include "alpr.h"
#include "openalpr/cjson.h"
#include "support/tinythread.h"
#include <curl/curl.h>
#include "support/timing.h"
#include <log4cplus/logger.h>
#include <log4cplus/loggingmacros.h>
#include <log4cplus/configurator.h>
#include <log4cplus/consoleappender.h>
#include <log4cplus/fileappender.h>
using namespace alpr;
// Variables
SafeQueue<cv::Mat> framesQueue;
// Prototypes
void streamRecognitionThread(void* arg);
bool writeToQueue(std::string jsonResult);
bool uploadPost(CURL* curl, std::string url, std::string data);
void dataUploadThread(void* arg);
// Constants
const std::string ALPRD_CONFIG_FILE_NAME="alprd.conf";
const std::string OPENALPR_CONFIG_FILE_NAME="openalpr.conf";
const std::string DEFAULT_LOG_FILE_PATH="/var/log/alprd.log";
const std::string BEANSTALK_QUEUE_HOST="127.0.0.1";
const int BEANSTALK_PORT=11300;
const std::string BEANSTALK_TUBE_NAME="alprd";
struct CaptureThreadData
{
std::string company_id;
std::string stream_url;
std::string site_id;
int camera_id;
int analysis_threads;
bool clock_on;
std::string config_file;
std::string country_code;
std::string pattern;
bool output_images;
std::string output_image_folder;
int top_n;
};
struct UploadThreadData
{
std::string upload_url;
};
void segfault_handler(int sig) {
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
backtrace_symbols_fd(array, size, STDERR_FILENO);
exit(1);
}
bool daemon_active;
static log4cplus::Logger logger;
int main( int argc, const char** argv )
{
signal(SIGSEGV, segfault_handler); // install our segfault handler
daemon_active = true;
bool noDaemon = false;
bool clockOn = false;
std::string logFile;
std::string configDir;
TCLAP::CmdLine cmd("OpenAlpr Daemon", ' ', Alpr::getVersion());
TCLAP::ValueArg<std::string> configDirArg("","config","Path to the openalpr config directory that contains alprd.conf and openalpr.conf. (Default: /etc/openalpr/)",false, "/etc/openalpr/" ,"config_file");
TCLAP::ValueArg<std::string> logFileArg("l","log","Log file to write to. Default=" + DEFAULT_LOG_FILE_PATH,false, DEFAULT_LOG_FILE_PATH ,"topN");
TCLAP::SwitchArg daemonOffSwitch("f","foreground","Set this flag for debugging. Disables forking the process as a daemon and runs in the foreground. Default=off", cmd, false);
TCLAP::SwitchArg clockSwitch("","clock","Display timing information to log. Default=off", cmd, false);
try
{
cmd.add( configDirArg );
cmd.add( logFileArg );
if (cmd.parse( argc, argv ) == false)
{
// Error occurred while parsing. Exit now.
return 1;
}
// Make sure configDir ends in a slash
configDir = configDirArg.getValue();
if (hasEnding(configDir, "/") == false)
configDir = configDir + "/";
logFile = logFileArg.getValue();
noDaemon = daemonOffSwitch.getValue();
clockOn = clockSwitch.getValue();
}
catch (TCLAP::ArgException &e) // catch any exceptions
{
std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
return 1;
}
std::string openAlprConfigFile = configDir + OPENALPR_CONFIG_FILE_NAME;
std::string daemonConfigFile = configDir + ALPRD_CONFIG_FILE_NAME;
// Validate that the configuration files exist
if (fileExists(openAlprConfigFile.c_str()) == false)
{
std::cerr << "error, openalpr.conf file does not exist at: " << openAlprConfigFile << std::endl;
return 1;
}
if (fileExists(daemonConfigFile.c_str()) == false)
{
std::cerr << "error, alprd.conf file does not exist at: " << daemonConfigFile << std::endl;
return 1;
}
log4cplus::BasicConfigurator config;
config.configure();
if (noDaemon == false)
{
// Fork off into a separate daemon
daemon(0, 0);
log4cplus::SharedAppenderPtr myAppender(new log4cplus::RollingFileAppender(logFile));
myAppender->setName("alprd_appender");
// Redirect std out to log file
logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("alprd"));
logger.addAppender(myAppender);
LOG4CPLUS_INFO(logger, "Running OpenALPR daemon in daemon mode.");
}
else
{
//log4cplus::SharedAppenderPtr myAppender(new log4cplus::ConsoleAppender());
//myAppender->setName("alprd_appender");
// Redirect std out to log file
logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("alprd"));
//logger.addAppender(myAppender);
LOG4CPLUS_INFO(logger, "Running OpenALPR daemon in the foreground.");
}
LOG4CPLUS_INFO(logger, "Using: " << daemonConfigFile << " for daemon configuration");
std::string daemon_defaults_file = INSTALL_PREFIX "/share/openalpr/config/alprd.defaults.conf";
DaemonConfig daemon_config(daemonConfigFile, daemon_defaults_file);
if (daemon_config.stream_urls.size() == 0)
{
LOG4CPLUS_FATAL(logger, "No video streams defined in the configuration.");
return 1;
}
LOG4CPLUS_INFO(logger, "Using: " << daemon_config.imageFolder << " for storing valid plate images");
pid_t pid;
std::vector<tthread::thread*> threads;
for (int i = 0; i < daemon_config.stream_urls.size(); i++)
{
pid = fork();
if (pid == (pid_t) 0)
{
// This is the child process, kick off the capture data and upload threads
CaptureThreadData* tdata = new CaptureThreadData();
tdata->stream_url = daemon_config.stream_urls[i];
tdata->camera_id = i + 1;
tdata->config_file = openAlprConfigFile;
tdata->output_images = daemon_config.storePlates;
tdata->output_image_folder = daemon_config.imageFolder;
tdata->country_code = daemon_config.country;
tdata->company_id = daemon_config.company_id;
tdata->site_id = daemon_config.site_id;
tdata->analysis_threads = daemon_config.analysis_threads;
tdata->top_n = daemon_config.topn;
tdata->pattern = daemon_config.pattern;
tdata->clock_on = clockOn;
tthread::thread* thread_recognize = new tthread::thread(streamRecognitionThread, (void*) tdata);
threads.push_back(thread_recognize);
if (daemon_config.uploadData)
{
// Kick off the data upload thread
UploadThreadData* udata = new UploadThreadData();
udata->upload_url = daemon_config.upload_url;
tthread::thread* thread_upload = new tthread::thread(dataUploadThread, (void*) udata );
threads.push_back(thread_upload);
}
break;
}
// Parent process will continue and spawn more children
}
while (daemon_active)
alpr::sleep_ms(30);
for (uint16_t i = 0; i < threads.size(); i++)
delete threads[i];
return 0;
}
void processingThread(void* arg)
{
CaptureThreadData* tdata = (CaptureThreadData*) arg;
Alpr alpr(tdata->country_code, tdata->config_file);
alpr.setTopN(tdata->top_n);
alpr.setDefaultRegion(tdata->pattern);
while (daemon_active) {
// Wait for a new frame
cv::Mat frame = framesQueue.pop();
// Process new frame
timespec startTime;
getTimeMonotonic(&startTime);
std::vector<AlprRegionOfInterest> regionsOfInterest;
regionsOfInterest.push_back(AlprRegionOfInterest(0,0, frame.cols, frame.rows));
AlprResults results = alpr.recognize(frame.data, frame.elemSize(), frame.cols, frame.rows, regionsOfInterest);
timespec endTime;
getTimeMonotonic(&endTime);
double totalProcessingTime = diffclock(startTime, endTime);
if (tdata->clock_on) {
LOG4CPLUS_INFO(logger, "Camera " << tdata->camera_id << " processed frame in: " << totalProcessingTime << " ms.");
}
if (results.plates.size() > 0) {
std::stringstream uuid_ss;
uuid_ss << tdata->site_id << "-cam" << tdata->camera_id << "-" << getEpochTimeMs();
std::string uuid = uuid_ss.str();
// Save the image to disk (using the UUID)
if (tdata->output_images) {
std::stringstream ss;
ss << tdata->output_image_folder << "/" << uuid << ".jpg";
cv::imwrite(ss.str(), frame);
}
// Update the JSON content to include UUID and camera ID
std::string json = alpr.toJson(results);
cJSON *root = cJSON_Parse(json.c_str());
cJSON_AddStringToObject(root, "uuid", uuid.c_str());
cJSON_AddNumberToObject(root, "camera_id", tdata->camera_id);
cJSON_AddStringToObject(root, "site_id", tdata->site_id.c_str());
cJSON_AddNumberToObject(root, "img_width", frame.cols);
cJSON_AddNumberToObject(root, "img_height", frame.rows);
// Add the company ID to the output if configured
if (tdata->company_id.length() > 0)
cJSON_AddStringToObject(root, "company_id", tdata->company_id.c_str());
char *out;
out=cJSON_PrintUnformatted(root);
cJSON_Delete(root);
std::string response(out);
free(out);
// Push the results to the Beanstalk queue
for (int j = 0; j < results.plates.size(); j++)
{
LOG4CPLUS_DEBUG(logger, "Writing plate " << results.plates[j].bestPlate.characters << " (" << uuid << ") to queue.");
}
writeToQueue(response);
}
usleep(10000);
}
}
void streamRecognitionThread(void* arg)
{
CaptureThreadData* tdata = (CaptureThreadData*) arg;
LOG4CPLUS_INFO(logger, "country: " << tdata->country_code << " -- config file: " << tdata->config_file );
LOG4CPLUS_INFO(logger, "pattern: " << tdata->pattern);
LOG4CPLUS_INFO(logger, "Stream " << tdata->camera_id << ": " << tdata->stream_url);
/* Create processing threads */
const int num_threads = tdata->analysis_threads;
tthread::thread* threads[num_threads];
for (int i = 0; i < num_threads; i++) {
LOG4CPLUS_INFO(logger, "Spawning Thread " << i );
tthread::thread* t = new tthread::thread(processingThread, (void*) tdata);
threads[i] = t;
}
cv::Mat frame;
LoggingVideoBuffer videoBuffer(logger);
videoBuffer.connect(tdata->stream_url, 5);
LOG4CPLUS_INFO(logger, "Starting camera " << tdata->camera_id);
while (daemon_active)
{
std::vector<cv::Rect> regionsOfInterest;
int response = videoBuffer.getLatestFrame(&frame, regionsOfInterest);
if (response != -1) {
if (framesQueue.empty()) {
framesQueue.push(frame.clone());
}
}
usleep(10000);
}
videoBuffer.disconnect();
LOG4CPLUS_INFO(logger, "Video processing ended");
delete tdata;
for (int i = 0; i < num_threads; i++) {
delete threads[i];
}
}
bool writeToQueue(std::string jsonResult)
{
try
{
Beanstalk::Client client(BEANSTALK_QUEUE_HOST, BEANSTALK_PORT);
client.use(BEANSTALK_TUBE_NAME);
int id = client.put(jsonResult);
if (id <= 0)
{
LOG4CPLUS_ERROR(logger, "Failed to write data to queue");
return false;
}
LOG4CPLUS_DEBUG(logger, "put job id: " << id );
}
catch (const std::runtime_error& error)
{
LOG4CPLUS_WARN(logger, "Error connecting to Beanstalk. Result has not been saved.");
return false;
}
return true;
}
void dataUploadThread(void* arg)
{
CURL *curl;
/* In windows, this will init the winsock stuff */
curl_global_init(CURL_GLOBAL_ALL);
UploadThreadData* udata = (UploadThreadData*) arg;
while(daemon_active)
{
try
{
/* get a curl handle */
curl = curl_easy_init();
Beanstalk::Client client(BEANSTALK_QUEUE_HOST, BEANSTALK_PORT);
client.watch(BEANSTALK_TUBE_NAME);
while (daemon_active)
{
Beanstalk::Job job;
client.reserve(job);
if (job.id() > 0)
{
//LOG4CPLUS_DEBUG(logger, job.body() );
if (uploadPost(curl, udata->upload_url, job.body()))
{
client.del(job.id());
LOG4CPLUS_INFO(logger, "Job: " << job.id() << " successfully uploaded" );
// Wait 10ms
sleep_ms(10);
}
else
{
client.release(job);
LOG4CPLUS_WARN(logger, "Job: " << job.id() << " failed to upload. Will retry." );
// Wait 2 seconds
sleep_ms(2000);
}
}
}
/* always cleanup */
curl_easy_cleanup(curl);
}
catch (const std::runtime_error& error)
{
LOG4CPLUS_WARN(logger, "Error connecting to Beanstalk. Will retry." );
}
// wait 5 seconds
usleep(5000000);
}
curl_global_cleanup();
}
bool uploadPost(CURL* curl, std::string url, std::string data)
{
bool success = true;
CURLcode res;
struct curl_slist *headers=NULL; // init to NULL is important
/* Add the required headers */
headers = curl_slist_append(headers, "Accept: application/json");
headers = curl_slist_append( headers, "Content-Type: application/json");
headers = curl_slist_append( headers, "charsets: utf-8");
if(curl) {
/* Add the headers */
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
/* First set the URL that is about to receive our POST. This URL can
just as well be a https:// URL if that is what should receive the
data. */
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
/* Now specify the POST data */
//char* escaped_data = curl_easy_escape(curl, data.c_str(), data.length());
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());
//curl_free(escaped_data);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if(res != CURLE_OK)
{
success = false;
}
}
return success;
}