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

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

singleton manager

File size: 25.9 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 gcs_watchdog->SafeStop();
144 connection_lost = true;
145}
146
147FrameworkManager_impl::~FrameworkManager_impl() {
148 // Printf("destruction FrameworkManager_impl\n");
149 int status;
150 char errorMsg[256];
151
152 SafeStop();
153 Join();
154
155 if (rcv_buf != NULL)
156 free(rcv_buf);
157
158 if (logger_defined == true) {
159 continuer = false;
160 (void)pthread_join(log_th, NULL);
161
162 status = DeletePipe(&cmd_pipe);
163 if (status != 0) {
164 Err("Error deleting pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
165 }
166 status = DeletePipe(&data_pipe);
167 if (status != 0) {
168 Err("Error deleting pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
169 }
170
171#ifdef __XENO__
172 status = rt_heap_delete(&log_heap);
173 if (status != 0) {
174 Err("rt_heap_delete error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
175 }
176#endif
177
178 logs.clear();
179 }
180
181 if (file_doc != NULL)
182 xmlFreeDoc(file_doc);
183
184 if (ui_defined)
185 delete top_layout;
186
187 if (com != NULL) {
188 delete com;
189 status = UDT::close(com_sock);
190 if (status != 0)
191 Printf("Error udt::close %s", UDT::getlasterror().getErrorMessage());
192
193 status = UDT::close(file_sock);
194 if (status != 0)
195 Printf("Error udt::close %s", UDT::getlasterror().getErrorMessage());
196
197 SleepMS(200); // a revoir, sinon UDT::cleanup bloque en RT
198 UDT::cleanup();
199 }
200
201 // Printf("destruction FrameworkManager_impl ok\n");
202}
203
204void FrameworkManager_impl::SetupConnection(string address, uint16_t port,Time watchdogTimeout,
205 size_t rcv_buf_size) {
206 if (com != NULL) {
207 Err("SetupConnection should be called only one time\n");
208 return;
209 }
210
211 UDT::startup();
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(address, port);
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 // file managment
228 bool blocking = true;
229 UDT::setsockopt(file_sock, 0, UDT_SNDSYN, &blocking, sizeof(bool));
230 UDT::setsockopt(file_sock, 0, UDT_RCVSYN, &blocking, sizeof(bool));
231
232 int timeout = 100; // ms
233 UDT::setsockopt(com_sock, 0, UDT_RCVTIMEO, &timeout, sizeof(int));
234
235 Start();
236
237 // watchdog for connection with ground station
238 connection_lost = false;
239 gcs_watchdog = new Watchdog(
240 this, std::bind(&FrameworkManager_impl::ConnectionLost, this),
241 (Time)1000000000);
242 gcs_watchdog->Start();
243}
244
245void FrameworkManager_impl::SetupUserInterface(string xml_file) {
246 ui_defined = true;
247 this->xml_file = xml_file;
248
249 // top_layout=new Layout(NULL,XML_ROOT_ELEMENT,XML_ROOT_TYPE);
250 top_layout = new Layout(NULL, self->ObjectName(), XML_ROOT_TYPE);
251
252 // xml setup of the main widget
253 if (xml_file != "") {
254 xmlNodePtr *file_node = &(((Widget *)(top_layout))->pimpl_->file_node);
255 file_doc = xmlParseFile(xml_file.c_str());
256 if (file_doc == NULL) {
257 self->Warn("XML document not parsed successfully. Creating a new one.\n");
258 file_doc = xmlNewDoc((xmlChar *)"1.0");
259 *file_node = xmlNewNode(NULL, (xmlChar *)XML_ROOT_TYPE);
260 xmlSetProp(*file_node, (xmlChar *)"name",
261 (xmlChar *)ObjectName().c_str());
262 xmlDocSetRootElement(file_doc, *file_node);
263 // PrintXml();
264 } else {
265 *file_node = xmlDocGetRootElement(file_doc);
266 if (xmlStrcmp((*file_node)->name, (xmlChar *)XML_ROOT_TYPE)) {
267 self->Warn("%s, no match found in xml file\n", XML_ROOT_TYPE);
268 *file_node = xmlNewNode(NULL, (xmlChar *)XML_ROOT_TYPE);
269 xmlSetProp(*file_node, (xmlChar *)"name",
270 (xmlChar *)ObjectName().c_str());
271 xmlDocSetRootElement(file_doc, *file_node);
272 }
273 }
274 } else {
275 self->Err("xml file not defined\n");
276 }
277
278 // gui
279 tabwidget =
280 new TabWidget(top_layout->At(0, 0), XML_MAIN_TABWIDGET, TabWidget::North);
281 save_button =
282 new PushButton(top_layout->At(1, 0),
283 "save config on target (" + self->ObjectName() + ")");
284 // load_button=new PushButton(top_layout->At(1,1),"load config on target (" +
285 // self->ObjectName() + ")");
286}
287
288// in case of RT, this thread switches to secondary mode when calling
289// com->Receive
290// it switches back to RT in ProcessXML when mutex are locked
291void FrameworkManager_impl::Run(void) {
292 while (!ToBeStopped()) {
293 ssize_t bytesRead;
294
295 bytesRead = com->Receive(rcv_buf, rcv_buf_size);
296
297 if (bytesRead == (ssize_t)rcv_buf_size)
298 Err("FrameworkManager max receive size, augmenter le buffer size!\n");
299
300 if (bytesRead > 0) {
301 // printf("recu %ld, trame %x\n",bytesRead,(uint8_t)rcv_buf[0]);
302 // rcv_buf[bytesRead-1]=0;//pour affichage
303 // printf("%s\n",rcv_buf);
304
305 switch ((uint8_t)rcv_buf[0]) {
306 case XML_HEADER: {
307 xmlDoc *doc;
308 rcv_buf[bytesRead] = 0;
309 //Printf("%s\n",rcv_buf);
310 doc = xmlReadMemory(rcv_buf, (int)bytesRead, "include.xml",
311 "ISO-8859-1", 0);
312 xmlNode *cur_node = NULL;
313
314 for (cur_node = xmlDocGetRootElement(doc); cur_node;
315 cur_node = cur_node->next) {
316 if (cur_node->type == XML_ELEMENT_NODE) {
317 if (!xmlStrcmp(cur_node->name, (xmlChar *)XML_ROOT_TYPE)) {
318#ifdef __XENO__
319 WarnUponSwitches(
320 true); // ProcessXML should not switch to secondary mode
321#endif
322 top_layout->Widget::pimpl_->ProcessXML(cur_node->children);
323#ifdef __XENO__
324 WarnUponSwitches(false); // other parts of this thread can switch
325 // to secondary mode
326#endif
327 break;
328 }
329 }
330 }
331
332 xmlFreeDoc(doc);
333
334 if (save_button->Clicked())
335 SaveXml();
336
337 SaveXmlChange(rcv_buf);
338
339 break;
340 }
341 case WATCHDOG_HEADER: {
342 gcs_watchdog->Touch();
343 break;
344 }
345 default:
346 Err("unknown id: %x\n", (uint8_t)rcv_buf[0]);
347 break;
348 }
349 } else {
350 if (com->ConnectionLost())
351 SleepMS(10); // avoid infinite loop in this case
352 }
353 }
354}
355
356void FrameworkManager_impl::SaveXml(void) {
357 if (ui_defined)
358 xmlSaveFormatFile(xml_file.c_str(), file_doc, 1);
359}
360
361void FrameworkManager_impl::SaveXmlChange(char *buf) {
362 if (is_logging == true) {
363 FILE *xml_change;
364 char filename[256];
365 Time time = GetTime();
366
367 sprintf(filename, "%s/changes_at_%lld.xml", log_path.c_str(), time);
368
369 xml_change = fopen(filename, "a");
370 fprintf(xml_change, "%s", buf);
371 fclose(xml_change);
372
373 sprintf(filename, "changes_at_%lld.xml", time);
374 xml_changes.push_back(filename);
375 }
376}
377
378void FrameworkManager_impl::SendFile(string path, string name) {
379 char *buf, *more_buf;
380 int size;
381 filebuf *pbuf;
382 ssize_t nb_write;
383 string filename = path + "/" + name;
384
385 // open the file
386 fstream ifs(filename.c_str(), ios::in | ios::binary);
387 ifs.seekg(0, ios::end);
388 size = ifs.tellg();
389 ifs.seekg(0, ios::beg);
390 pbuf = ifs.rdbuf();
391
392 if (size <= 0) {
393 Err("error opening file %s\n", filename.c_str());
394 return;
395 }
396
397 buf = (char *)malloc(sizeof(uint8_t) + sizeof(int) + name.size());
398 if (buf == NULL) {
399 Err("malloc error, not sending file\n");
400 return;
401 }
402
403 if (IsBigEndian()) {
404 buf[0] = FILE_INFO_BIG_ENDIAN;
405 } else {
406 buf[0] = FILE_INFO_LITTLE_ENDIAN;
407 }
408
409 memcpy(buf + 1, &size, sizeof(int));
410 memcpy(buf + 1 + sizeof(int), name.c_str(), name.size());
411 Printf("sending %s, size: %i\n", filename.c_str(), size);
412 // send file information
413 UDT::sendmsg(file_sock, buf, sizeof(uint8_t) + sizeof(int) + name.size(), -1,
414 true);
415
416 more_buf = (char *)realloc((void *)buf, size);
417 if (more_buf == NULL) {
418 Err("realloc error, not sending file\n");
419 free(buf);
420 return;
421 } else {
422 buf = more_buf;
423 }
424
425 pbuf->sgetn(buf, size);
426 // send the file
427 nb_write = UDT::sendmsg(file_sock, buf, size, -1, true);
428
429 if (nb_write < 0) {
430 Err("UDT::sendmsg error (%s)\n", UDT::getlasterror().getErrorMessage());
431 } else if (nb_write != size) {
432 Err("UDT::sendmsg error, sent %ld/%i\n", nb_write, size);
433 }
434
435 ifs.close();
436 free(buf);
437}
438
439void FrameworkManager_impl::FinishSending() {
440 char rm_cmd[256];
441
442 // send orignal xml
443 SendFile(log_path, "setup.xml");
444 sprintf(rm_cmd, "rm %s/setup.xml", log_path.c_str());
445 system(rm_cmd);
446
447 // send xml changes
448 for (size_t i = 0; i < xml_changes.size(); i++) {
449 // Printf("%s\n",xml_changes.at(i).c_str());
450 SendFile(log_path, xml_changes.at(i).c_str());
451 sprintf(rm_cmd, "rm %s/%s", log_path.c_str(), xml_changes.at(i).c_str());
452 system(rm_cmd);
453 }
454 xml_changes.clear();
455
456 // end notify
457 char buf = END;
458 int nb_write = UDT::sendmsg(file_sock, &buf, 1, -1, true);
459
460 if (nb_write < 0) {
461 Err("UDT::sendmsg error (%s)\n", UDT::getlasterror().getErrorMessage());
462 } else if (nb_write != 1) {
463 Err("UDT::sendmsg error, sent %i/%i\n", nb_write, 1);
464 }
465
466 //wait end ACK
467 int nb_read = UDT::recvmsg(file_sock,&buf,1);
468 if(nb_read<0) {
469 Err("UDT::recvmsg error (%s)\n",UDT::getlasterror().getErrorMessage());
470 } else if (nb_read != 1) {
471 Err("UDT::recvmsg error, sent %i/%i\n",nb_read,1);
472 }
473}
474
475UDTSOCKET FrameworkManager_impl::GetSocket(string address, uint16_t port) {
476 while (1) {
477 UDTSOCKET new_fd;
478 new_fd = UDT::socket(AF_INET, SOCK_DGRAM, 0);
479 if (new_fd == UDT::INVALID_SOCK) {
480 Err("socket error: %s\n", UDT::getlasterror().getErrorMessage());
481 return 0;
482 }
483
484 sockaddr_in serv_addr;
485 serv_addr.sin_family = AF_INET;
486 serv_addr.sin_port = htons(short(port));
487
488 if (inet_pton(AF_INET, address.c_str(), &serv_addr.sin_addr) <= 0) {
489 Err("incorrect network address\n");
490 return 0;
491 }
492
493 memset(&(serv_addr.sin_zero), '\0', 8);
494
495 if (UDT::ERROR ==
496 UDT::connect(new_fd, (sockaddr *)&serv_addr, sizeof(serv_addr))) {
497 // Printf("connect error: %s
498 // %i\n",UDT::getlasterror().getErrorMessage(),UDT::getlasterror().getErrorCode());
499 UDT::close(new_fd);
500 if (UDT::getlasterror().getErrorCode() != 1001 &&
501 UDT::getlasterror().getErrorCode() != 1002) {
502 Err("connect error: %s\n", UDT::getlasterror().getErrorMessage());
503 return 0;
504 }
505 } else {
506 // printf("connected to
507 // %s:%i\n",inet_ntoa(serv_addr.sin_addr),serv_addr.sin_port);
508 return new_fd;
509 }
510 }
511}
512
513#ifdef __XENO__
514int FrameworkManager_impl::CreatePipe(RT_PIPE *fd, string name) {
515 name = self->ObjectName() + "-" + name;
516 // xenomai limitation
517 if (name.size() > 31)
518 self->Err("rt_pipe_create error (%s is too long)\n", name.c_str());
519// start log writter
520#ifdef RT_PIPE_SIZE
521 return rt_pipe_create(fd, name.c_str(), P_MINOR_AUTO, RT_PIPE_SIZE);
522#else
523 return rt_pipe_create(fd, name.c_str(), P_MINOR_AUTO, 0);
524#endif
525}
526#else
527int FrameworkManager_impl::CreatePipe(int (*fd)[2], string name) {
528 // if(pipe2(fd[0],O_NONBLOCK) == -1)
529 if (pipe(fd[0]) == -1) {
530 return errno;
531 } else {
532 int attr = fcntl((*fd)[0], F_GETFL, 0);
533 if (attr == -1) {
534 return errno;
535 }
536 if (fcntl((*fd)[0], F_SETFL, attr | O_NONBLOCK) == -1) {
537 return errno;
538 }
539 attr = fcntl((*fd)[1], F_GETFL, 0);
540 if (attr == -1) {
541 return errno;
542 }
543 if (fcntl((*fd)[1], F_SETFL, attr | O_NONBLOCK) == -1) {
544 return errno;
545 }
546
547 return 0;
548 }
549}
550#endif
551
552#ifdef __XENO__
553int FrameworkManager_impl::DeletePipe(RT_PIPE *fd) {
554 return rt_pipe_delete(fd);
555}
556#else
557int FrameworkManager_impl::DeletePipe(int (*fd)[2]) {
558 int status1 = close((*fd)[0]);
559 int status2 = close((*fd)[1]);
560 if (status1 == 0 && status2 == 0)
561 return 0;
562 if (status1 != 0)
563 return status1;
564 if (status2 != 0)
565 return status2;
566}
567#endif
568
569void FrameworkManager_impl::SetupLogger(string log_path) {
570 char errorMsg[256];
571
572 if (logger_defined == true) {
573 Warn("SetupLogger() was already called.\n");
574 return;
575 }
576
577 this->log_path = log_path;
578
579 int status = CreatePipe(&cmd_pipe, "log_cmd");
580 if (status != 0) {
581 Err("Error creating pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
582 return;
583 }
584
585 status = CreatePipe(&data_pipe, "log_data");
586 if (status != 0) {
587 Err("Error creating pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
588 return;
589 }
590
591#ifdef __XENO__
592 string tmp_name;
593 tmp_name = self->ObjectName() + "-log_heap";
594 status = rt_heap_create(&log_heap, tmp_name.c_str(), LOG_HEAP, H_FIFO);
595 if (status != 0) {
596 Err("rt_heap_create error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
597 return;
598 }
599#endif //__XENO__
600
601 continuer = true;
602
603#ifdef NRT_STACK_SIZE
604 // Initialize thread creation attributes
605 pthread_attr_t attr;
606 if (pthread_attr_init(&attr) != 0) {
607 Err("pthread_attr_init error\n");
608 return;
609 }
610
611 if (pthread_attr_setstacksize(&attr, NRT_STACK_SIZE) != 0) {
612 Err("pthread_attr_setstacksize error\n");
613 return;
614 }
615
616 if (pthread_create(&log_th, &attr, write_log_user, (void *)this) < 0)
617#else
618 if (pthread_create(&log_th, NULL, write_log_user, (void *)this) < 0)
619#endif
620 {
621 Err("pthread_create error\n");
622 return;
623 }
624#ifdef NRT_STACK_SIZE
625 if (pthread_attr_destroy(&attr) != 0) {
626 Err("pthread_attr_destroy error\n");
627 return;
628 }
629#endif
630
631 logger_defined = true;
632}
633
634void FrameworkManager_impl::AddDeviceToLog(IODevice *device) {
635 if (logger_defined == false) {
636 Warn("SetupLogger() was not called, not adding to log\n");
637 return;
638 }
639
640 if (is_logging == false) {
641 if (!device->pimpl_->IsSetToBeLogged()) {
642 device->pimpl_->SetToBeLogged();
643 log_desc_t tmp;
644 tmp.device = device;
645 logs.push_back(tmp);
646 } else {
647 Warn("not adding it twice\n");
648 }
649 } else {
650 Err("impossible while logging\n");
651 }
652}
653
654bool FrameworkManager_impl::IsDeviceLogged(const IODevice *device) const {
655 return device->pimpl_->IsSetToBeLogged();
656}
657
658void FrameworkManager_impl::StartLog(void) {
659 if (logger_defined == false) {
660 Err("SetupLogger() was not called, not starting log\n");
661 return;
662 }
663
664 ssize_t written;
665 size_t nb_err = 0;
666
667 if (logs.size() == 0) {
668 Warn("Not starting log: nothing to log!\n");
669 return;
670 }
671
672 if (is_logging == false) {
673 for (size_t i = 0; i < logs.size(); i++) {
674
675 logs.at(i).running = true;
676 logs.at(i).dbtFile = NULL;
677 logs.at(i).size = logs.at(i).device->pimpl_->LogSize();
678#ifdef __XENO__
679 written =
680 rt_pipe_write(&cmd_pipe, &logs.at(i), sizeof(log_desc_t), P_NORMAL);
681#else
682 written = write(cmd_pipe[1], &logs.at(i), sizeof(log_desc_t));
683#endif
684
685 if (written < 0) {
686 char errorMsg[256];
687 Err("write pipe error (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
688 nb_err++;
689 logs.at(i).running = false;
690 } else if (written != sizeof(log_desc_t)) {
691 Err("write pipe error %ld/%ld\n", written, sizeof(log_desc_t));
692 nb_err++;
693 logs.at(i).running = false;
694 }
695 }
696
697 if (nb_err != logs.size())
698 is_logging = true;
699 } else {
700 Warn("Already logging\n");
701 }
702}
703
704void FrameworkManager_impl::StopLog(void) {
705 ssize_t written;
706
707 if (is_logging == true) {
708 for (size_t i = 0; i < logs.size(); i++) {
709 logs.at(i).running = false;
710 }
711// send only one running false condition, user thread will stop and send all
712#ifdef __XENO__
713 written =
714 rt_pipe_write(&cmd_pipe, &logs.at(0), sizeof(log_desc_t), P_NORMAL);
715#else
716 written = write(cmd_pipe[1], &logs.at(0), sizeof(log_desc_t));
717#endif
718
719 if (written < 0) {
720 char errorMsg[256];
721 Err("write pipe error (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
722 return;
723 } else if (written != sizeof(log_desc_t)) {
724 Err("write pipe error %ld/%ld\n", written, sizeof(log_desc_t));
725 return;
726 }
727
728 is_logging = false;
729 } else {
730 Warn("Not logging\n");
731 }
732}
733
734char *FrameworkManager_impl::GetBuffer(size_t sz) {
735// Printf("alloc %i\n",sz);
736#ifdef __XENO__
737 void *ptr;
738 int status = rt_heap_alloc(&log_heap, sz, TM_NONBLOCK, &ptr);
739 if (status != 0) {
740 char errorMsg[256];
741 Err("rt_heap_alloc error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
742 ptr = NULL;
743 }
744 return (char *)ptr;
745#else
746 return (char *)malloc(sz);
747#endif
748}
749
750void FrameworkManager_impl::ReleaseBuffer(char *buf) {
751#ifdef __XENO__
752 int status = rt_heap_free(&log_heap, buf);
753
754 if (status != 0) {
755 char errorMsg[256];
756 Err("rt_heap_free error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
757 }
758#else
759 free(buf);
760#endif
761}
762
763void FrameworkManager_impl::WriteLog(const char *buf, size_t size) {
764 ssize_t written;
765
766#ifdef __XENO__
767 written = rt_pipe_write(&data_pipe, buf, size, P_NORMAL);
768#else
769 written = write(data_pipe[1], buf, size);
770#endif
771
772 if (written < 0) {
773 char errorMsg[256];
774 Err("error write pipe (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
775 } else if (written != (ssize_t)size) {
776 Err("error write pipe %ld/%ld\n", written, size);
777 }
778}
779
780void *FrameworkManager_impl::write_log_user(void *arg) {
781 int cmd_pipe = -1;
782 int data_pipe = -1;
783 string filename;
784 fd_set set;
785 struct timeval timeout;
786 FrameworkManager_impl *caller = (FrameworkManager_impl *)arg;
787 int rv;
788
789 vector<log_desc_t> logs;
790
791#ifdef __XENO__
792 char errorMsg[256];
793 filename = NRT_PIPE_PATH + caller->self->ObjectName() + "-log_cmd";
794 while (cmd_pipe < 0) {
795 cmd_pipe = open(filename.c_str(), O_RDWR);
796 if (cmd_pipe < 0 && errno != ENOENT)
797 caller->self->Err("open rt_pipe error: %s %s\n", filename.c_str(), strerror_r(errno, errorMsg, sizeof(errorMsg)));
798 usleep(1000);
799 }
800 filename = NRT_PIPE_PATH + caller->self->ObjectName() + "-log_data";
801 while (data_pipe < 0) {
802 data_pipe = open(filename.c_str(), O_RDWR);
803 if (data_pipe < 0 && errno != ENOENT)
804 caller->self->Err("open rt_pipe error: %s %s\n", filename.c_str(), strerror_r(errno, errorMsg, sizeof(errorMsg)));
805 usleep(1000);
806 }
807#else
808 cmd_pipe = caller->cmd_pipe[0];
809 data_pipe = caller->data_pipe[0];
810#endif
811
812 while (caller->continuer == true) {
813 FD_ZERO(&set);
814 FD_SET(cmd_pipe, &set);
815 FD_SET(data_pipe, &set);
816
817 timeout.tv_sec = 0;
818 timeout.tv_usec = SELECT_TIMEOUT_MS * 1000;
819 rv = select(FD_SETSIZE, &set, NULL, NULL, &timeout);
820
821 if (rv == -1) {
822 caller->Err("select error\n"); // an error accured
823 } else if (rv == 0) {
824 // printf("timeout write_log_user %s\n",caller->ObjectName().c_str()); //
825 // a timeout occured
826 } else {
827 if (FD_ISSET(cmd_pipe, &set)) {
828 log_desc_t tmp;
829 read(cmd_pipe, &tmp, sizeof(log_desc_t));
830
831 if (tmp.running == true) // start logging
832 {
833 filename = caller->log_path + "/" + caller->FileName(tmp.device) + ".dbt";
834 printf("Creating log file %s (log size %i)\n", filename.c_str(), (int)tmp.size);
835 tmp.dbtFile = inithdFile((char *)filename.c_str(), UAV, tmp.size);
836 logs.push_back(tmp);
837
838 if (logs.size() == 1) {
839 filename = caller->log_path + "/setup.xml";
840 xmlSaveFile(filename.c_str(), caller->file_doc);
841 }
842 } else // stop logging
843 {
844 //disable watchdog temporarly
845 //this is necessary because GCS is no longer sending the heartbeat when receiving files...
846 //TODO: add a thread in GCS for receiving file
847 //but be careful that with a xbee modem for exemple, sending files can saturate communication and
848 //avoid the heartbeat to be received... so disabling watchdog is not a so bad option...
849 if(caller->gcs_watchdog!=NULL) {
850 caller->gcs_watchdog->SafeStop();
851 caller->gcs_watchdog->Join();
852 }
853 for (size_t i = 0; i < logs.size(); i++) {
854 if (logs.at(i).dbtFile != NULL) {
855 close_hdfile(logs.at(i).dbtFile);
856
857 filename = caller->FileName(logs.at(i).device) + ".dbt";
858 caller->SendFile(caller->log_path, filename);
859
860 fstream txt_file;
861 filename = caller->FileName(logs.at(i).device) + ".txt";
862 txt_file.open((caller->log_path + "/" + filename).c_str(),
863 fstream::out);
864 txt_file << "1: time (us)\n2: time (ns)\n";
865 int index = 3;
866 logs.at(i).device->pimpl_->WriteLogsDescriptors(txt_file, &index);
867 txt_file.close();
868
869 caller->SendFile(caller->log_path, filename);
870 }
871 }
872 // a revoir celui ci est le xml enregistré et pas forcement l'actuel
873 // if(caller->xml_file!="") caller->SendFile(caller->xml_file);
874 caller->FinishSending();
875
876 logs.clear();
877 //enable watchdog again
878 if(caller->gcs_watchdog!=NULL) {
879 caller->gcs_watchdog->Start();
880 }
881 }
882 }
883
884 if (FD_ISSET(data_pipe, &set)) {
885 log_header_t header;
886 read(data_pipe, &header, sizeof(log_header_t));
887
888 for (size_t i = 0; i < logs.size(); i++) {
889 if (logs.at(i).device == header.device) {
890 char *buf = (char *)malloc(header.size);
891 read(data_pipe, buf, header.size);
892 // printf("%s \n",header.device->ObjectName().c_str());
893 // for(int i=0;i<header.size;i++) printf("%x ",buf[i]);
894 // printf("\n");
895 if (logs.at(i).size == header.size) {
896 if (logs.at(i).dbtFile != NULL) {
897 write_hdfile(
898 logs.at(i).dbtFile, buf, (road_time_t)(header.time / 1000),
899 (road_timerange_t)(header.time % 1000), header.size);
900 } else {
901 printf("err\n");
902 }
903 } else {
904 caller->self->Err("%s log size is not correct %i/%i\n",
905 header.device->ObjectName().c_str(),
906 header.size, logs.at(i).size);
907 }
908 free(buf);
909 }
910 }
911 }
912 }
913 }
914
915#ifdef __XENO__
916 close(cmd_pipe);
917 close(data_pipe);
918#endif
919
920 pthread_exit(0);
921}
922
923string FrameworkManager_impl::FileName(IODevice *device) {
924 return getFrameworkManager()->ObjectName() + "_" + device->ObjectName();
925}
926
927void FrameworkManager_impl::PrintXml(void) const {
928 xmlChar *xmlbuff;
929 int buffersize;
930 xmlDocDumpFormatMemory(file_doc, &xmlbuff, &buffersize, 1);
931 Printf("xml:\n%s\n", xmlbuff);
932 xmlFree(xmlbuff);
933}
Note: See TracBrowser for help on using the repository browser.