source: flair-src/trunk/lib/FlairCore/src/FrameworkManager_impl.cpp@ 241

Last change on this file since 241 was 234, checked in by Sanahuja Guillaume, 6 years ago

create file oscket only when necessary

File size: 27.0 KB
Line 
1// %flair:license{
2// This file is part of the Flair framework distributed under the
3// CECILL-C License, Version 1.0.
4// %flair:license}
5// created: 2011/08/31
6// filename: FrameworkManager.cpp
7//
8// author: Guillaume Sanahuja
9// Copyright Heudiasyc UMR UTC/CNRS 7253
10//
11// version: $Id: $
12//
13// purpose: Classe de base de la librairie
14//
15//
16/*********************************************************************/
17
18#include "FrameworkManager_impl.h"
19#include "FrameworkManager.h"
20#include "Widget_impl.h"
21#include <unistd.h>
22#include "IODevice.h"
23#include "IODevice_impl.h"
24#include "TabWidget.h"
25#include "Layout.h"
26#include "PushButton.h"
27#include "communication.h"
28#include "config.h"
29#include "Watchdog.h"
30#include <errno.h>
31#include <string.h>
32#include <arpa/inet.h>
33#include <sys/mman.h>
34#include <execinfo.h>
35#include <signal.h>
36#include <fcntl.h>
37#ifdef __XENO__
38#include <native/task.h>
39#include <rtdk.h>
40#endif
41
42using namespace std;
43using namespace flair::core;
44using namespace flair::gui;
45
46ui_com *FrameworkManager_impl::com = NULL;
47FrameworkManager_impl *FrameworkManager_impl::_this = NULL;
48
49namespace {
50#ifdef __XENO__
51
52#ifdef SIGDEBUG
53static const char *reason_str[] = {
54 "undefined", "received signal", "invoked syscall", "triggered fault",
55 "affected by priority inversion", "missing mlockall", "runaway thread",
56};
57
58void warn_upon_switch(int sig, siginfo_t *si, void *context) {
59 unsigned int reason = si->si_value.sival_int;
60 void *bt[32];
61 int nentries;
62#ifdef SIGDEBUG_WATCHDOG
63 printf("\nSIGDEBUG received, reason %d: %s\n", reason,
64 reason <= SIGDEBUG_WATCHDOG ? reason_str[reason] : "<unknown>");
65#endif
66 // Dump a backtrace of the frame which caused the switch to secondary mode:
67 nentries = backtrace(bt, sizeof(bt) / sizeof(bt[0]));
68 backtrace_symbols_fd(bt, nentries, fileno(stdout));
69}
70#else // SIGDEBUG
71void warn_upon_switch(int sig __attribute__((unused))) {
72 void *bt[32];
73 int nentries;
74
75 /* Dump a backtrace of the frame which caused the switch to
76 secondary mode: */
77 nentries = backtrace(bt, sizeof(bt) / sizeof(bt[0]));
78 backtrace_symbols_fd(bt, nentries, fileno(stdout));
79}
80#endif // SIGDEBUG
81#endif //__XENO__
82void seg_fault(int sig __attribute__((unused))) {
83 void *bt[32];
84 int nentries;
85
86 printf("Segmentation fault:\n");
87 /* Dump a backtrace of the frame which caused the segfault: */
88 nentries = backtrace(bt, sizeof(bt) / sizeof(bt[0]));
89 backtrace_symbols_fd(bt, nentries, fileno(stdout));
90
91 exit(1);
92}
93}
94
95FrameworkManager_impl::FrameworkManager_impl(FrameworkManager *self,
96 string name)
97 : Thread(self, "FrameworkManager", FRAMEWORK_TASK_PRIORITY) {
98 this->self = self;
99 is_logging = false;
100 logger_defined = false;
101 disable_errors = false;
102 ui_defined = false;
103 rcv_buf = NULL;
104 gcs_watchdog = NULL;
105 _this = this;
106 tabwidget=NULL;
107
108 // Avoids memory swapping for this program
109 mlockall(MCL_CURRENT | MCL_FUTURE);
110
111 // catch segfault
112 signal(SIGSEGV, seg_fault);
113
114// catch primary->secondary switch
115#ifdef __XENO__
116#ifdef SIGDEBUG
117 struct sigaction sa;
118 sigemptyset(&sa.sa_mask);
119 sa.sa_sigaction = warn_upon_switch;
120 sa.sa_flags = SA_SIGINFO;
121 sigaction(SIGDEBUG, &sa, NULL);
122#else //SIGDEBUG
123 signal(SIGXCPU, warn_upon_switch);
124#endif //SIGDEBUG
125 string task_name = "Framework_" + name;
126
127 // Perform auto-init of rt_print buffers if the task doesn't do so
128 rt_print_auto_init(1);
129 // Initialise the rt_print buffer for this task explicitly
130 rt_print_init(512, task_name.c_str());
131
132 int status = rt_task_shadow(NULL, task_name.c_str(), 10, 0);
133 if (status != 0) {
134 char errorMsg[256];
135 self->Err("rt_task_shadow error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
136 }
137
138#endif //__XENO__
139}
140
141void FrameworkManager_impl::ConnectionLost(void) {
142 Err("connection lost\n");
143 if(gcs_watchdog!=NULL) gcs_watchdog->SafeStop();
144 connection_lost = true;
145}
146
147FrameworkManager_impl::~FrameworkManager_impl() {
148 // Printf("destruction FrameworkManager_impl\n");
149 int status;
150
151 SafeStop();
152 Join();
153
154 if (rcv_buf != NULL)
155 free(rcv_buf);
156
157 if (logger_defined == true) {
158 continuer = false;
159 (void)pthread_join(log_th, NULL);
160
161 status = DeletePipe(&cmd_pipe);
162 if (status != 0) {
163 char errorMsg[256];
164 Err("Error deleting pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
165 }
166 status = DeletePipe(&data_pipe);
167 if (status != 0) {
168 char errorMsg[256];
169 Err("Error deleting pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
170 }
171
172#ifdef __XENO__
173 status = rt_heap_delete(&log_heap);
174 if (status != 0) {
175 char errorMsg[256];
176 Err("rt_heap_delete error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
177 }
178#endif
179
180 logs.clear();
181 }
182
183 if (file_doc != NULL)
184 xmlFreeDoc(file_doc);
185
186 if (ui_defined)
187 delete top_layout;
188
189 if (com != NULL) {
190 delete com;
191 status = UDT::close(com_sock);
192 if (status != 0)
193 Printf("Error udt::close %s", UDT::getlasterror().getErrorMessage());
194
195 SleepMS(200); // a revoir, sinon UDT::cleanup bloque en RT
196 UDT::cleanup();
197 }
198
199 // Printf("destruction FrameworkManager_impl ok\n");
200}
201
202void FrameworkManager_impl::SetupConnection(string address, uint16_t port,Time watchdogTimeout,
203 size_t rcv_buf_size) {
204 if (com != NULL) {
205 Err("SetupConnection should be called only one time\n");
206 return;
207 }
208 this->address=address;
209 this->port=port;
210
211 UDT::startup(1024*256,1024*256,1024*256);
212 this->rcv_buf_size = rcv_buf_size;
213
214 // socket file_socket, doit être créé en premier, cf station sol
215 Printf("Connecting to %s:%i\n", address.c_str(), port);
216 //file_sock = GetSocket(address, port);
217 com_sock = GetSocket();
218
219 // receive buffer allocation
220 rcv_buf = (char *)malloc(rcv_buf_size);
221 if (rcv_buf == NULL) {
222 Err("receive buffer malloc error\n");
223 }
224
225 com = new ui_com(this, com_sock);
226
227 Start();
228
229 // watchdog for connection with ground station
230 connection_lost = false;
231 gcs_watchdog = new Watchdog(this, std::bind(&FrameworkManager_impl::ConnectionLost, this),watchdogTimeout);
232 gcs_watchdog->Start();
233}
234
235void FrameworkManager_impl::SetupUserInterface(string xml_file) {
236 ui_defined = true;
237 this->xml_file = xml_file;
238
239 // top_layout=new Layout(NULL,XML_ROOT_ELEMENT,XML_ROOT_TYPE);
240 top_layout = new Layout(NULL, self->ObjectName(), XML_ROOT_TYPE);
241
242 // xml setup of the main widget
243 if (xml_file != "") {
244 xmlNodePtr *file_node = &(((Widget *)(top_layout))->pimpl_->file_node);
245 file_doc = xmlParseFile(xml_file.c_str());
246 if (file_doc == NULL) {
247 self->Warn("XML document not parsed successfully. Creating a new one.\n");
248 file_doc = xmlNewDoc((xmlChar *)"1.0");
249 *file_node = xmlNewNode(NULL, (xmlChar *)XML_ROOT_TYPE);
250 xmlSetProp(*file_node, (xmlChar *)"name",
251 (xmlChar *)ObjectName().c_str());
252 xmlDocSetRootElement(file_doc, *file_node);
253 // PrintXml();
254 } else {
255 *file_node = xmlDocGetRootElement(file_doc);
256 if (xmlStrcmp((*file_node)->name, (xmlChar *)XML_ROOT_TYPE)) {
257 self->Warn("%s, no match found in xml file\n", XML_ROOT_TYPE);
258 *file_node = xmlNewNode(NULL, (xmlChar *)XML_ROOT_TYPE);
259 xmlSetProp(*file_node, (xmlChar *)"name",
260 (xmlChar *)ObjectName().c_str());
261 xmlDocSetRootElement(file_doc, *file_node);
262 }
263 }
264 } else {
265 self->Err("xml file not defined\n");
266 }
267
268 // gui
269 tabwidget =
270 new TabWidget(top_layout->At(0, 0), XML_MAIN_TABWIDGET, TabWidget::North);
271 save_button =
272 new PushButton(top_layout->At(1, 0),
273 "save config on target (" + self->ObjectName() + ")");
274 // load_button=new PushButton(top_layout->At(1,1),"load config on target (" +
275 // self->ObjectName() + ")");
276}
277
278// in case of RT, this thread switches to secondary mode when calling
279// com->Receive
280// it switches back to RT in ProcessXML when mutex are locked
281void FrameworkManager_impl::Run(void) {
282 while (!ToBeStopped()) {
283 ssize_t bytesRead;
284 bytesRead = com->Receive(rcv_buf, rcv_buf_size);
285 com->CheckConnection();
286//printf("%i\n",bytesRead);
287 if (bytesRead == (ssize_t)rcv_buf_size)
288 Err("FrameworkManager max receive size, augmenter le buffer size!\n");
289
290 if (bytesRead > 0) {
291 //printf("recu %ld, trame %x %lld\n",bytesRead,(uint8_t)rcv_buf[0],GetTime()/(1000000));
292 //rcv_buf[bytesRead-1]=0;//pour affichage
293 //printf("%s\n",rcv_buf);
294
295 switch ((uint8_t)rcv_buf[0]) {
296 case XML_HEADER: {
297 xmlDoc *doc;
298 rcv_buf[bytesRead] = 0;
299 //Printf("%s\n",rcv_buf);
300 doc = xmlReadMemory(rcv_buf, (int)bytesRead, "include.xml",
301 "ISO-8859-1", 0);
302 xmlNode *cur_node = NULL;
303
304 for (cur_node = xmlDocGetRootElement(doc); cur_node;
305 cur_node = cur_node->next) {
306 if (cur_node->type == XML_ELEMENT_NODE) {
307 if (!xmlStrcmp(cur_node->name, (xmlChar *)XML_ROOT_TYPE)) {
308#ifdef __XENO__
309 WarnUponSwitches(
310 true); // ProcessXML should not switch to secondary mode
311#endif
312 top_layout->Widget::pimpl_->ProcessXML(cur_node->children);
313#ifdef __XENO__
314 WarnUponSwitches(false); // other parts of this thread can switch
315 // to secondary mode
316#endif
317 break;
318 }
319 }
320 }
321
322 xmlFreeDoc(doc);
323
324 if (save_button->Clicked())
325 SaveXml();
326
327 SaveXmlChange(rcv_buf);
328
329 break;
330 }
331 case WATCHDOG_HEADER: {
332 if(gcs_watchdog!=NULL) gcs_watchdog->Touch();
333 break;
334 }
335 default:
336 Err("unknown id: %x\n", (uint8_t)rcv_buf[0]);
337 break;
338 }
339 } else {
340 if (com->ConnectionLost())
341 SleepMS(10); // avoid infinite loop in this case
342 }
343 }
344}
345
346void FrameworkManager_impl::SaveXml(void) {
347 if (ui_defined)
348 xmlSaveFormatFile(xml_file.c_str(), file_doc, 1);
349}
350
351void FrameworkManager_impl::SaveXmlChange(char *buf) {
352 if (is_logging == true) {
353 FILE *xml_change;
354 char filename[256];
355 Time time = GetTime();
356
357 sprintf(filename, "%s/changes_at_%lld.xml", log_path.c_str(), time);
358
359 xml_change = fopen(filename, "a");
360 fprintf(xml_change, "%s", buf);
361 fclose(xml_change);
362
363 sprintf(filename, "changes_at_%lld.xml", time);
364 xml_changes.push_back(filename);
365 }
366}
367
368void FrameworkManager_impl::SendFile(UDTSOCKET socket,string path, string name) {
369 char *buf, *more_buf;
370 int size;
371 filebuf *pbuf;
372 ssize_t nb_write;
373 string filename = path + "/" + name;
374
375 // open the file
376 fstream ifs(filename.c_str(), ios::in | ios::binary);
377 ifs.seekg(0, ios::end);
378 size = ifs.tellg();
379 ifs.seekg(0, ios::beg);
380 pbuf = ifs.rdbuf();
381
382 if (size <= 0) {
383 Err("error opening file %s\n", filename.c_str());
384 return;
385 }
386
387 buf = (char *)malloc(sizeof(uint8_t) + sizeof(int) + name.size());
388 if (buf == NULL) {
389 Err("malloc error, not sending file\n");
390 return;
391 }
392
393 if (IsBigEndian()) {
394 buf[0] = FILE_INFO_BIG_ENDIAN;
395 } else {
396 buf[0] = FILE_INFO_LITTLE_ENDIAN;
397 }
398
399 memcpy(buf + 1, &size, sizeof(int));
400 memcpy(buf + 1 + sizeof(int), name.c_str(), name.size());
401 Printf("sending %s, size: %i\n", filename.c_str(), size);
402 // send file information
403 UDT::sendmsg(socket, buf, sizeof(uint8_t) + sizeof(int) + name.size(), -1,true);
404
405 more_buf = (char *)realloc((void *)buf, size);
406 if (more_buf == NULL) {
407 Err("realloc error, not sending file\n");
408 free(buf);
409 return;
410 } else {
411 buf = more_buf;
412 }
413
414 pbuf->sgetn(buf, size);
415 // send the file
416 nb_write = UDT::sendmsg(socket, buf, size, -1, true);
417
418 if (nb_write < 0) {
419 Err("UDT::sendmsg error (%s)\n", UDT::getlasterror().getErrorMessage());
420 } else if (nb_write != size) {
421 Err("UDT::sendmsg error, sent %ld/%i\n", nb_write, size);
422 }
423
424 ifs.close();
425 free(buf);
426}
427
428void FrameworkManager_impl::FinishSending(UDTSOCKET socket) {
429 char rm_cmd[256];
430
431 // send orignal xml
432 SendFile(socket,log_path, "setup.xml");
433 sprintf(rm_cmd, "rm %s/setup.xml", log_path.c_str());
434 system(rm_cmd);
435
436 // send xml changes
437 for (size_t i = 0; i < xml_changes.size(); i++) {
438 // Printf("%s\n",xml_changes.at(i).c_str());
439 SendFile(socket,log_path, xml_changes.at(i).c_str());
440 sprintf(rm_cmd, "rm %s/%s", log_path.c_str(), xml_changes.at(i).c_str());
441 system(rm_cmd);
442 }
443 xml_changes.clear();
444
445 // end notify
446 char buf = END_SENDING_FILES;
447 int nb_write = UDT::sendmsg(socket, &buf, 1, -1, true);
448
449 if (nb_write < 0) {
450 Err("UDT::sendmsg error (%s)\n", UDT::getlasterror().getErrorMessage());
451 } else if (nb_write != 1) {
452 Err("UDT::sendmsg error, sent %i/%i\n", nb_write, 1);
453 }
454
455 //wait end ACK
456 int nb_read = UDT::recvmsg(socket,&buf,1);
457 if(nb_read<0) {
458 Err("UDT::recvmsg error (%s)\n",UDT::getlasterror().getErrorMessage());
459 } else if (nb_read != 1) {
460 Err("UDT::recvmsg error, sent %i/%i\n",nb_read,1);
461 }
462}
463
464UDTSOCKET FrameworkManager_impl::GetSocket(void) {
465 while (1) {
466 UDTSOCKET new_fd;
467 new_fd = UDT::socket(AF_INET, SOCK_DGRAM, 0);
468 if (new_fd == UDT::INVALID_SOCK) {
469 Err("socket error: %s\n", UDT::getlasterror().getErrorMessage());
470 return 0;
471 }
472
473 sockaddr_in serv_addr;
474 serv_addr.sin_family = AF_INET;
475 serv_addr.sin_port = htons(short(port));
476
477 if (inet_pton(AF_INET, address.c_str(), &serv_addr.sin_addr) <= 0) {
478 Err("incorrect network address\n");
479 return 0;
480 }
481
482 memset(&(serv_addr.sin_zero), '\0', 8);
483
484 if (UDT::ERROR ==
485 UDT::connect(new_fd, (sockaddr *)&serv_addr, sizeof(serv_addr))) {
486 // Printf("connect error: %s
487 // %i\n",UDT::getlasterror().getErrorMessage(),UDT::getlasterror().getErrorCode());
488 UDT::close(new_fd);
489 if (UDT::getlasterror().getErrorCode() != 1001 &&
490 UDT::getlasterror().getErrorCode() != 1002) {
491 Err("connect error: %s\n", UDT::getlasterror().getErrorMessage());
492 return 0;
493 }
494 } else {
495 // printf("connected to
496 // %s:%i\n",inet_ntoa(serv_addr.sin_addr),serv_addr.sin_port);
497 return new_fd;
498 }
499 }
500}
501
502#ifdef __XENO__
503int FrameworkManager_impl::CreatePipe(RT_PIPE *fd, string name) {
504 name = self->ObjectName() + "-" + name;
505 // xenomai limitation
506 if (name.size() > 31)
507 self->Err("rt_pipe_create error (%s is too long)\n", name.c_str());
508// start log writter
509#ifdef RT_PIPE_SIZE
510 return rt_pipe_create(fd, name.c_str(), P_MINOR_AUTO, RT_PIPE_SIZE);
511#else
512 return rt_pipe_create(fd, name.c_str(), P_MINOR_AUTO, 0);
513#endif
514}
515#else
516int FrameworkManager_impl::CreatePipe(int (*fd)[2], string name) {
517 // if(pipe2(fd[0],O_NONBLOCK) == -1)
518 if (pipe(fd[0]) == -1) {
519 return errno;
520 } else {
521 int attr = fcntl((*fd)[0], F_GETFL, 0);
522 if (attr == -1) {
523 return errno;
524 }
525 if (fcntl((*fd)[0], F_SETFL, attr | O_NONBLOCK) == -1) {
526 return errno;
527 }
528 attr = fcntl((*fd)[1], F_GETFL, 0);
529 if (attr == -1) {
530 return errno;
531 }
532 if (fcntl((*fd)[1], F_SETFL, attr | O_NONBLOCK) == -1) {
533 return errno;
534 }
535
536 return 0;
537 }
538}
539#endif
540
541#ifdef __XENO__
542int FrameworkManager_impl::DeletePipe(RT_PIPE *fd) {
543 return rt_pipe_delete(fd);
544}
545#else
546int FrameworkManager_impl::DeletePipe(int (*fd)[2]) {
547 int status1 = close((*fd)[0]);
548 int status2 = close((*fd)[1]);
549 if (status1 == 0 && status2 == 0)
550 return 0;
551 if (status1 != 0)
552 return status1;
553 if (status2 != 0)
554 return status2;
555}
556#endif
557
558void FrameworkManager_impl::SetupLogger(string log_path,uint32_t stackSize) {
559
560 if (logger_defined == true) {
561 Warn("SetupLogger() was already called.\n");
562 return;
563 }
564
565 this->log_path = log_path;
566
567 int status = CreatePipe(&cmd_pipe, "log_cmd");
568 if (status != 0) {
569 char errorMsg[256];
570 Err("Error creating pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
571 return;
572 }
573
574 status = CreatePipe(&data_pipe, "log_data");
575 if (status != 0) {
576 char errorMsg[256];
577 Err("Error creating pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
578 return;
579 }
580
581#ifdef __XENO__
582 string tmp_name;
583 tmp_name = self->ObjectName() + "-log_heap";
584 status = rt_heap_create(&log_heap, tmp_name.c_str(), RT_LOG_HEAP, H_FIFO);
585 if (status != 0) {
586 char errorMsg[256];
587 Err("rt_heap_create error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
588 return;
589 }
590#endif //__XENO__
591
592 continuer = true;
593
594 // Initialize thread creation attributes
595 pthread_attr_t attr;
596 status=pthread_attr_init(&attr);
597 if (status != 0) {
598 char errorMsg[256];
599 Err("pthread_attr_init error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
600 return;
601 }
602
603 status=pthread_attr_setstacksize(&attr, stackSize);
604 if (status != 0) {
605 char errorMsg[256];
606 Err("pthread_attr_setstacksize error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
607 return;
608 }
609
610 status=pthread_create(&log_th, &attr, write_log_user, (void *)this);
611 if (status < 0) {
612 char errorMsg[256];
613 Err("pthread_create error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
614 return;
615 }
616
617 status=pthread_attr_destroy(&attr);
618 if (status != 0) {
619 char errorMsg[256];
620 Err("pthread_attr_destroy error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
621 return;
622 }
623
624 logger_defined = true;
625}
626
627void FrameworkManager_impl::AddDeviceToLog(IODevice *device) {
628 if (logger_defined == false) {
629 Warn("SetupLogger() was not called, not adding to log\n");
630 return;
631 }
632
633 if (is_logging == false) {
634 if (!device->pimpl_->IsSetToBeLogged()) {
635 device->pimpl_->SetToBeLogged();
636 log_desc_t tmp;
637 tmp.device = device;
638 logs.push_back(tmp);
639 } else {
640 Warn("not adding it twice\n");
641 }
642 } else {
643 Err("impossible while logging\n");
644 }
645}
646
647bool FrameworkManager_impl::IsDeviceLogged(const IODevice *device) const {
648 return device->pimpl_->IsSetToBeLogged();
649}
650
651void FrameworkManager_impl::StartLog(void) {
652 if (logger_defined == false) {
653 Err("SetupLogger() was not called, not starting log\n");
654 return;
655 }
656
657 ssize_t written;
658 size_t nb_err = 0;
659
660 if (logs.size() == 0) {
661 Warn("Not starting log: nothing to log!\n");
662 return;
663 }
664
665 if (is_logging == false) {
666 for (size_t i = 0; i < logs.size(); i++) {
667
668 logs.at(i).running = true;
669 logs.at(i).dbtFile = NULL;
670 logs.at(i).size = logs.at(i).device->pimpl_->LogSize();
671#ifdef __XENO__
672 written =
673 rt_pipe_write(&cmd_pipe, &logs.at(i), sizeof(log_desc_t), P_NORMAL);
674#else
675 written = write(cmd_pipe[1], &logs.at(i), sizeof(log_desc_t));
676#endif
677
678 if (written < 0) {
679 char errorMsg[256];
680 Err("write pipe error (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
681 nb_err++;
682 logs.at(i).running = false;
683 } else if (written != sizeof(log_desc_t)) {
684 Err("write pipe error %ld/%ld\n", written, sizeof(log_desc_t));
685 nb_err++;
686 logs.at(i).running = false;
687 }
688 }
689
690 if (nb_err != logs.size())
691 is_logging = true;
692 } else {
693 Warn("Already logging\n");
694 }
695}
696
697void FrameworkManager_impl::StopLog(void) {
698 ssize_t written;
699
700 if (is_logging == true) {
701 for (size_t i = 0; i < logs.size(); i++) {
702 logs.at(i).running = false;
703 }
704// send only one running false condition, user thread will stop and send all
705#ifdef __XENO__
706 written =
707 rt_pipe_write(&cmd_pipe, &logs.at(0), sizeof(log_desc_t), P_NORMAL);
708#else
709 written = write(cmd_pipe[1], &logs.at(0), sizeof(log_desc_t));
710#endif
711
712 if (written < 0) {
713 char errorMsg[256];
714 Err("write pipe error (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
715 return;
716 } else if (written != sizeof(log_desc_t)) {
717 Err("write pipe error %ld/%ld\n", written, sizeof(log_desc_t));
718 return;
719 }
720
721 is_logging = false;
722 } else {
723 Warn("Not logging\n");
724 }
725}
726
727char *FrameworkManager_impl::GetBuffer(size_t sz) {
728// Printf("alloc %i\n",sz);
729#ifdef __XENO__
730 void *ptr;
731 int status = rt_heap_alloc(&log_heap, sz, TM_NONBLOCK, &ptr);
732 if (status != 0) {
733 char errorMsg[256];
734 Err("rt_heap_alloc error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
735 ptr = NULL;
736 }
737 return (char *)ptr;
738#else
739 return (char *)malloc(sz);
740#endif
741}
742
743void FrameworkManager_impl::ReleaseBuffer(char *buf) {
744#ifdef __XENO__
745 int status = rt_heap_free(&log_heap, buf);
746
747 if (status != 0) {
748 char errorMsg[256];
749 Err("rt_heap_free error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
750 }
751#else
752 free(buf);
753#endif
754}
755
756void FrameworkManager_impl::WriteLog(const char *buf, size_t size) {
757 ssize_t written;
758
759#ifdef __XENO__
760 written = rt_pipe_write(&data_pipe, buf, size, P_NORMAL);
761#else
762 written = write(data_pipe[1], buf, size);
763#endif
764
765 if (written < 0) {
766 char errorMsg[256];
767 Err("error write pipe (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
768 } else if (written != (ssize_t)size) {
769 Err("error write pipe %ld/%ld\n", written, size);
770 }
771}
772
773void *FrameworkManager_impl::write_log_user(void *arg) {
774 int cmd_pipe = -1;
775 int data_pipe = -1;
776 fd_set set;
777 struct timeval timeout;
778 FrameworkManager_impl *caller = (FrameworkManager_impl *)arg;
779 int rv;
780
781 vector<log_desc_t> logs;
782
783#ifdef __XENO__
784 while (cmd_pipe < 0) {
785 string filename = NRT_PIPE_PATH + caller->self->ObjectName() + "-log_cmd";
786 cmd_pipe = open(filename.c_str(), O_RDWR);
787 if (cmd_pipe < 0 && errno != ENOENT) {
788 char errorMsg[256];
789 caller->self->Err("open rt_pipe error: %s %s\n", filename.c_str(), strerror_r(errno, errorMsg, sizeof(errorMsg)));
790 }
791 usleep(1000);
792 }
793 while (data_pipe < 0) {
794 string filename = NRT_PIPE_PATH + caller->self->ObjectName() + "-log_data";
795 data_pipe = open(filename.c_str(), O_RDWR);
796 if (data_pipe < 0 && errno != ENOENT) {
797 char errorMsg[256];
798 caller->self->Err("open rt_pipe error: %s %s\n", filename.c_str(), strerror_r(errno, errorMsg, sizeof(errorMsg)));
799 }
800 usleep(1000);
801 }
802#else
803 cmd_pipe = caller->cmd_pipe[0];
804 data_pipe = caller->data_pipe[0];
805#endif
806
807 while (caller->continuer == true) {
808 FD_ZERO(&set);
809 FD_SET(cmd_pipe, &set);
810 FD_SET(data_pipe, &set);
811
812 timeout.tv_sec = 0;
813 timeout.tv_usec = SELECT_TIMEOUT_MS * 1000;
814 rv = select(FD_SETSIZE, &set, NULL, NULL, &timeout);
815
816 if (rv == -1) {
817 caller->Err("select error\n"); // an error accured
818 } else if (rv == 0) {
819 // printf("timeout write_log_user %s\n",caller->ObjectName().c_str()); //
820 // a timeout occured
821 } else {
822 if (FD_ISSET(cmd_pipe, &set)) {
823 log_desc_t tmp;
824 read(cmd_pipe, &tmp, sizeof(log_desc_t));
825
826 if (tmp.running == true) {// start logging
827 string filename = caller->log_path + "/" + caller->FileName(tmp.device) + ".dbt";
828 printf("Creating log file %s (log size %i)\n", filename.c_str(), (int)tmp.size);
829 tmp.dbtFile = inithdFile((char *)filename.c_str(), UAV, tmp.size);
830 logs.push_back(tmp);
831
832 if (logs.size() == 1) {
833 filename = caller->log_path + "/setup.xml";
834 xmlSaveFile(filename.c_str(), caller->file_doc);
835 }
836 } else {// stop logging
837 //disable watchdog temporarly
838 //this is necessary because GCS is no longer sending the heartbeat when receiving files...
839 //TODO: add a thread in GCS for receiving file
840 //but be careful that with a xbee modem for exemple, sending files can saturate communication and
841 //avoid the heartbeat to be received... so disabling watchdog is not a so bad option...
842 if(caller->gcs_watchdog!=NULL) {
843 caller->gcs_watchdog->SafeStop();
844 caller->gcs_watchdog->Join();
845 }
846 //create a socket for files
847 UDTSOCKET file_sock = caller->GetSocket();
848 char data=START_SENDING_FILES;
849 ssize_t nb_write = UDT::sendmsg(file_sock, &data, 1, -1, true);
850 if (nb_write < 0) {
851 caller->Err("UDT::sendmsg error (%s)\n", UDT::getlasterror().getErrorMessage());
852 if (UDT::getlasterror().getErrorCode() == CUDTException::ECONNLOST ||
853 UDT::getlasterror().getErrorCode() == CUDTException::EINVSOCK) {
854 }
855 } else if (nb_write != 1) {
856 caller->Err("%s, code %i (%ld/%ld)\n", UDT::getlasterror().getErrorMessage(),
857 UDT::getlasterror().getErrorCode(), nb_write, 1);
858 }
859 for (size_t i = 0; i < logs.size(); i++) {
860 if (logs.at(i).dbtFile != NULL) {
861 close_hdfile(logs.at(i).dbtFile);
862
863 string filename = caller->FileName(logs.at(i).device) + ".dbt";
864 caller->SendFile(file_sock,caller->log_path, filename);
865
866 fstream txt_file;
867 filename = caller->FileName(logs.at(i).device) + ".txt";
868 txt_file.open((caller->log_path + "/" + filename).c_str(),
869 fstream::out);
870 txt_file << "1: time (us)\n2: time (ns)\n";
871 int index = 3;
872 logs.at(i).device->pimpl_->WriteLogsDescriptors(txt_file, &index);
873 txt_file.close();
874
875 caller->SendFile(file_sock,caller->log_path, filename);
876 }
877 }
878 // a revoir celui ci est le xml enregistré et pas forcement l'actuel
879 // if(caller->xml_file!="") caller->SendFile(caller->xml_file);
880 caller->FinishSending(file_sock);
881
882 int status = UDT::close(file_sock);
883 if (status != 0)
884 caller->Err("Error udt::close %s", UDT::getlasterror().getErrorMessage());
885
886 logs.clear();
887 //enable watchdog again
888 if(caller->gcs_watchdog!=NULL) {
889 caller->gcs_watchdog->Start();
890 }
891 }
892 }
893
894 if (FD_ISSET(data_pipe, &set)) {
895 log_header_t header;
896 read(data_pipe, &header, sizeof(log_header_t));
897
898 for (size_t i = 0; i < logs.size(); i++) {
899 if (logs.at(i).device == header.device) {
900 char *buf = (char *)malloc(header.size);
901 read(data_pipe, buf, header.size);
902 // printf("%s \n",header.device->ObjectName().c_str());
903 // for(int i=0;i<header.size;i++) printf("%x ",buf[i]);
904 // printf("\n");
905 if (logs.at(i).size == header.size) {
906 if (logs.at(i).dbtFile != NULL) {
907 write_hdfile(
908 logs.at(i).dbtFile, buf, (road_time_t)(header.time / 1000),
909 (road_timerange_t)(header.time % 1000), header.size);
910 } else {
911 printf("err\n");
912 }
913 } else {
914 caller->self->Err("%s log size is not correct %i/%i\n",
915 header.device->ObjectName().c_str(),
916 header.size, logs.at(i).size);
917 }
918 free(buf);
919 }
920 }
921 }
922 }
923 }
924
925#ifdef __XENO__
926 close(cmd_pipe);
927 close(data_pipe);
928#endif
929
930 pthread_exit(0);
931}
932
933string FrameworkManager_impl::FileName(IODevice *device) {
934 return getFrameworkManager()->ObjectName() + "_" + device->ObjectName();
935}
936
937void FrameworkManager_impl::PrintXml(void) const {
938 xmlChar *xmlbuff;
939 int buffersize;
940 xmlDocDumpFormatMemory(file_doc, &xmlbuff, &buffersize, 1);
941 Printf("xml:\n%s\n", xmlbuff);
942 xmlFree(xmlbuff);
943}
Note: See TracBrowser for help on using the repository browser.