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

Last change on this file since 118 was 118, checked in by Sanahuja Guillaume, 7 years ago

aded semaphore
resolved bug for rt_printf before thread is started

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