1 // generic.cxx -- generic protocol class
3 // Written by Curtis Olson, started November 1999.
5 // Copyright (C) 1999 Curtis L. Olson - http://www.flightgear.org/~curt
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
27 #include <string.h> // strstr()
28 #include <stdlib.h> // strtod(), atoi()
30 #include <simgear/debug/logstream.hxx>
31 #include <simgear/io/iochannel.hxx>
32 #include <simgear/structure/exception.hxx>
33 #include <simgear/misc/sg_path.hxx>
34 #include <simgear/misc/stdint.hxx>
35 #include <simgear/props/props.hxx>
36 #include <simgear/props/props_io.hxx>
37 #include <simgear/math/SGMath.hxx>
39 #include <Main/globals.hxx>
40 #include <Main/fg_props.hxx>
41 #include <Main/fg_os.hxx>
42 #include <Main/util.hxx>
43 #include "generic.hxx"
45 FGGeneric::FGGeneric(vector<string> tokens) : exitOnError(false), initOk(false)
48 if (tokens[1] == "socket") {
50 } else if (tokens[1] == "file") {
56 if ((configToken >= tokens.size())||(tokens[ configToken ] == "")) {
57 SG_LOG(SG_NETWORK, SG_ALERT,
58 "Not enough tokens passed for generic '" << tokens[1] << "' protocol. ");
62 string config = tokens[ configToken ];
63 file_name = config+".xml";
64 direction = tokens[2];
66 if (direction != "in" && direction != "out" && direction != "bi") {
67 SG_LOG(SG_NETWORK, SG_ALERT, "Unsuported protocol direction: "
75 FGGeneric::~FGGeneric() {
88 // generate the message
89 bool FGGeneric::gen_message_binary() {
90 string generic_sentence;
94 for (unsigned int i = 0; i < _out_message.size(); i++) {
96 switch (_out_message[i].type) {
99 val = _out_message[i].offset +
100 _out_message[i].prop->getIntValue() * _out_message[i].factor;
101 int32_t intVal = val;
102 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
103 intVal = (int32_t) sg_bswap_32((uint32_t)intVal);
105 memcpy(&buf[length], &intVal, sizeof(int32_t));
106 length += sizeof(int32_t);
111 buf[length] = (char) (_out_message[i].prop->getBoolValue() ? true : false);
117 val = _out_message[i].offset +
118 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
120 int32_t fixed = (int)(val * 65536.0f);
121 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
122 fixed = (int32_t) sg_bswap_32((uint32_t)fixed);
124 memcpy(&buf[length], &fixed, sizeof(int32_t));
125 length += sizeof(int32_t);
131 val = _out_message[i].offset +
132 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
134 tmpun32.floatVal = static_cast<float>(val);
136 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
137 tmpun32.intVal = sg_bswap_32(tmpun32.intVal);
139 memcpy(&buf[length], &tmpun32.intVal, sizeof(uint32_t));
140 length += sizeof(uint32_t);
146 val = _out_message[i].offset +
147 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
149 tmpun64.doubleVal = val;
151 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
152 tmpun64.longVal = sg_bswap_64(tmpun64.longVal);
154 memcpy(&buf[length], &tmpun64.longVal, sizeof(uint64_t));
155 length += sizeof(uint64_t);
159 default: // SG_STRING
160 const char *strdata = _out_message[i].prop->getStringValue();
161 int32_t strlength = strlen(strdata);
163 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
164 SG_LOG( SG_IO, SG_ALERT, "Generic protocol: "
165 "FG_STRING will be written in host byte order.");
167 /* Format for strings is
168 * [length as int, 4 bytes][ASCII data, length bytes]
170 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
171 strlength = sg_bswap_32(strlength);
173 memcpy(&buf[length], &strlength, sizeof(int32_t));
174 length += sizeof(int32_t);
175 strncpy(&buf[length], strdata, strlength);
177 /* FIXME padding for alignment? Something like:
178 * length += (strlength % 4 > 0 ? sizeof(int32_t) - strlength % 4 : 0;
184 // add the footer to the packet ("line")
185 switch (binary_footer_type) {
187 binary_footer_value = length;
195 if (binary_footer_type != FOOTER_NONE) {
196 int32_t intValue = binary_footer_value;
197 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
198 intValue = sg_bswap_32(binary_footer_value);
200 memcpy(&buf[length], &intValue, sizeof(int32_t));
201 length += sizeof(int32_t);
207 bool FGGeneric::gen_message_ascii() {
208 string generic_sentence;
213 for (unsigned int i = 0; i < _out_message.size(); i++) {
216 generic_sentence += var_separator;
219 switch (_out_message[i].type) {
221 val = _out_message[i].offset +
222 _out_message[i].prop->getIntValue() * _out_message[i].factor;
223 snprintf(tmp, 255, _out_message[i].format.c_str(), (int)val);
227 snprintf(tmp, 255, _out_message[i].format.c_str(),
228 _out_message[i].prop->getBoolValue());
232 val = _out_message[i].offset +
233 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
234 snprintf(tmp, 255, _out_message[i].format.c_str(), (float)val);
238 val = _out_message[i].offset +
239 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
240 snprintf(tmp, 255, _out_message[i].format.c_str(), (float)val);
244 val = _out_message[i].offset +
245 _out_message[i].prop->getDoubleValue() * _out_message[i].factor;
246 snprintf(tmp, 255, _out_message[i].format.c_str(), (double)val);
249 default: // SG_STRING
250 snprintf(tmp, 255, _out_message[i].format.c_str(),
251 _out_message[i].prop->getStringValue());
254 generic_sentence += tmp;
257 /* After each lot of variables has been added, put the line separator
260 generic_sentence += line_separator;
262 length = generic_sentence.length();
263 strncpy( buf, generic_sentence.c_str(), length );
268 bool FGGeneric::gen_message() {
270 return gen_message_binary();
272 return gen_message_ascii();
276 bool FGGeneric::parse_message_binary(int length) {
282 while ((++i < (int)_in_message.size()) && (p1 < p2)) {
284 switch (_in_message[i].type) {
286 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
287 tmp32 = sg_bswap_32(*(int32_t *)p1);
289 tmp32 = *(int32_t *)p1;
291 updateValue(_in_message[i], (int)tmp32);
292 p1 += sizeof(int32_t);
296 updateValue(_in_message[i], p1[0] != 0);
301 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
302 tmp32 = sg_bswap_32(*(int32_t *)p1);
304 tmp32 = *(int32_t *)p1;
306 updateValue(_in_message[i], (float)tmp32 / 65536.0f);
307 p1 += sizeof(int32_t);
312 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
313 tmpun32.intVal = sg_bswap_32(*(uint32_t *)p1);
315 tmpun32.floatVal = *(float *)p1;
317 updateValue(_in_message[i], tmpun32.floatVal);
318 p1 += sizeof(int32_t);
323 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
324 tmpun64.longVal = sg_bswap_64(*(uint64_t *)p1);
326 tmpun64.doubleVal = *(double *)p1;
328 updateValue(_in_message[i], tmpun64.doubleVal);
329 p1 += sizeof(int64_t);
332 default: // SG_STRING
333 SG_LOG( SG_IO, SG_ALERT, "Generic protocol: "
334 "Ignoring unsupported binary input chunk type.");
342 bool FGGeneric::parse_message_ascii(int length) {
345 int chunks = _in_message.size();
346 int line_separator_size = line_separator.size();
348 if (length < line_separator_size ||
349 line_separator.compare(buf + length - line_separator_size) != 0) {
351 SG_LOG(SG_IO, SG_WARN,
352 "Input line does not end with expected line separator." );
354 buf[length - line_separator_size] = 0;
357 while ((++i < chunks) && p1) {
358 p2 = strstr(p1, var_separator.c_str());
361 p2 += var_separator.length();
364 switch (_in_message[i].type) {
366 updateValue(_in_message[i], atoi(p1));
370 updateValue(_in_message[i], atof(p1) != 0.0);
375 updateValue(_in_message[i], (float)strtod(p1, 0));
379 updateValue(_in_message[i], (double)strtod(p1, 0));
382 default: // SG_STRING
383 _in_message[i].prop->setStringValue(p1);
393 bool FGGeneric::parse_message(int length) {
395 return parse_message_binary(length);
397 return parse_message_ascii(length);
402 // open hailing frequencies
403 bool FGGeneric::open() {
404 if ( is_enabled() ) {
405 SG_LOG( SG_IO, SG_ALERT, "This shouldn't happen, but the channel "
406 << "is already in use, ignoring" );
410 SGIOChannel *io = get_io_channel();
412 if ( ! io->open( get_direction() ) ) {
413 SG_LOG( SG_IO, SG_ALERT, "Error opening channel communication layer." );
419 if ( ((get_direction() == SG_IO_OUT )||
420 (get_direction() == SG_IO_BI))
421 && ! preamble.empty() ) {
422 if ( ! io->write( preamble.c_str(), preamble.size() ) ) {
423 SG_LOG( SG_IO, SG_WARN, "Error writing preamble." );
432 // process work for this port
433 bool FGGeneric::process() {
434 SGIOChannel *io = get_io_channel();
436 if ( (get_direction() == SG_IO_OUT) ||
437 (get_direction() == SG_IO_BI) ) {
439 if ( ! io->write( buf, length ) ) {
440 SG_LOG( SG_IO, SG_WARN, "Error writing data." );
445 if (( get_direction() == SG_IO_IN ) ||
446 (get_direction() == SG_IO_BI) ) {
447 if ( io->get_type() == sgFileType ) {
449 length = io->readline( buf, FG_MAX_MSG_SIZE );
451 parse_message( length );
453 SG_LOG( SG_IO, SG_ALERT, "Error reading data." );
457 length = io->read( buf, binary_record_length );
458 if ( length == binary_record_length ) {
459 parse_message( length );
461 SG_LOG( SG_IO, SG_ALERT,
462 "Generic protocol: Received binary "
463 "record of unexpected size, expected: "
464 << binary_record_length << " but received: "
470 while ((length = io->readline( buf, FG_MAX_MSG_SIZE )) > 0 ) {
471 parse_message( length );
474 while ((length = io->read( buf, binary_record_length ))
475 == binary_record_length ) {
476 parse_message( length );
480 SG_LOG( SG_IO, SG_ALERT,
481 "Generic protocol: Received binary "
482 "record of unexpected size, expected: "
483 << binary_record_length << " but received: "
493 return true; // should not get there, but please the compiler
500 bool FGGeneric::close() {
501 SGIOChannel *io = get_io_channel();
503 if ( ((get_direction() == SG_IO_OUT)||
504 (get_direction() == SG_IO_BI))
505 && ! postamble.empty() ) {
506 if ( ! io->write( postamble.c_str(), postamble.size() ) ) {
507 SG_LOG( SG_IO, SG_ALERT, "Error writing postamble." );
512 set_enabled( false );
514 if ( ! io->close() ) {
525 SGPath path( globals->get_fg_root() );
526 path.append("Protocol");
527 path.append(file_name.c_str());
529 SG_LOG(SG_NETWORK, SG_INFO, "Reading communication protocol from "
534 readProperties(path.str(), &root);
535 } catch (const sg_exception & ex) {
536 SG_LOG(SG_NETWORK, SG_ALERT,
537 "Unable to load the protocol configuration file: " << ex.getFormattedMessage() );
541 if (direction == "out") {
542 SGPropertyNode *output = root.getNode("generic/output");
544 _out_message.clear();
545 read_config(output, _out_message);
547 } else if (direction == "in") {
548 SGPropertyNode *input = root.getNode("generic/input");
551 read_config(input, _in_message);
552 if (!binary_mode && (line_separator.size() == 0 ||
553 *line_separator.rbegin() != '\n')) {
555 SG_LOG(SG_IO, SG_WARN,
556 "Warning: Appending newline to line separator in generic input.");
557 line_separator.push_back('\n');
567 FGGeneric::read_config(SGPropertyNode *root, vector<_serial_prot> &msg)
569 binary_mode = root->getBoolValue("binary_mode");
572 /* These variables specified in the $FG_ROOT/data/Protocol/xxx.xml
573 * file for each format
575 * var_sep_string = the string/charachter to place between variables
576 * line_sep_string = the string/charachter to place at the end of each
579 preamble = fgUnescape(root->getStringValue("preamble"));
580 postamble = fgUnescape(root->getStringValue("postamble"));
581 var_sep_string = fgUnescape(root->getStringValue("var_separator"));
582 line_sep_string = fgUnescape(root->getStringValue("line_separator"));
584 if ( var_sep_string == "newline" ) {
585 var_separator = '\n';
586 } else if ( var_sep_string == "tab" ) {
587 var_separator = '\t';
588 } else if ( var_sep_string == "space" ) {
590 } else if ( var_sep_string == "formfeed" ) {
591 var_separator = '\f';
592 } else if ( var_sep_string == "carriagereturn" ) {
593 var_sep_string = '\r';
594 } else if ( var_sep_string == "verticaltab" ) {
595 var_separator = '\v';
597 var_separator = var_sep_string;
600 if ( line_sep_string == "newline" ) {
601 line_separator = '\n';
602 } else if ( line_sep_string == "tab" ) {
603 line_separator = '\t';
604 } else if ( line_sep_string == "space" ) {
605 line_separator = ' ';
606 } else if ( line_sep_string == "formfeed" ) {
607 line_separator = '\f';
608 } else if ( line_sep_string == "carriagereturn" ) {
609 line_separator = '\r';
610 } else if ( line_sep_string == "verticaltab" ) {
611 line_separator = '\v';
613 line_separator = line_sep_string;
616 // default values: no footer and record_length = sizeof(representation)
617 binary_footer_type = FOOTER_NONE;
618 binary_record_length = -1;
620 // default choice is network byte order (big endian)
621 if (sgIsLittleEndian()) {
622 binary_byte_order = BYTE_ORDER_NEEDS_CONVERSION;
624 binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
627 if ( root->hasValue("binary_footer") ) {
628 string footer_type = root->getStringValue("binary_footer");
629 if ( footer_type == "length" ) {
630 binary_footer_type = FOOTER_LENGTH;
631 } else if ( footer_type.substr(0, 5) == "magic" ) {
632 binary_footer_type = FOOTER_MAGIC;
633 binary_footer_value = strtol(footer_type.substr(6,
634 footer_type.length() - 6).c_str(), (char**)0, 0);
635 } else if ( footer_type != "none" ) {
636 SG_LOG(SG_IO, SG_ALERT,
637 "generic protocol: Unknown generic binary protocol "
638 "footer '" << footer_type << "', using no footer.");
642 if ( root->hasValue("record_length") ) {
643 binary_record_length = root->getIntValue("record_length");
646 if ( root->hasValue("byte_order") ) {
647 string byte_order = root->getStringValue("byte_order");
648 if (byte_order == "network" ) {
649 if ( sgIsLittleEndian() ) {
650 binary_byte_order = BYTE_ORDER_NEEDS_CONVERSION;
652 binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
654 } else if ( byte_order == "host" ) {
655 binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
657 SG_LOG(SG_IO, SG_ALERT,
658 "generic protocol: Undefined generic binary protocol"
659 "byte order, using HOST byte order.");
664 int record_length = 0; // Only used for binary protocols.
665 vector<SGPropertyNode_ptr> chunks = root->getChildren("chunk");
666 for (unsigned int i = 0; i < chunks.size(); i++) {
670 // chunk.name = chunks[i]->getStringValue("name");
671 chunk.format = fgUnescape(chunks[i]->getStringValue("format", "%d"));
672 chunk.offset = chunks[i]->getDoubleValue("offset");
673 chunk.factor = chunks[i]->getDoubleValue("factor", 1.0);
674 chunk.min = chunks[i]->getDoubleValue("min");
675 chunk.max = chunks[i]->getDoubleValue("max");
676 chunk.wrap = chunks[i]->getBoolValue("wrap");
677 chunk.rel = chunks[i]->getBoolValue("relative");
679 string node = chunks[i]->getStringValue("node", "/null");
680 chunk.prop = fgGetNode(node.c_str(), true);
682 string type = chunks[i]->getStringValue("type");
684 // Note: officially the type is called 'bool' but for backward
685 // compatibility 'boolean' will also be supported.
686 if (type == "bool" || type == "boolean") {
687 chunk.type = FG_BOOL;
689 } else if (type == "float") {
690 chunk.type = FG_FLOAT;
691 record_length += sizeof(int32_t);
692 } else if (type == "double") {
693 chunk.type = FG_DOUBLE;
694 record_length += sizeof(int64_t);
695 } else if (type == "fixed") {
696 chunk.type = FG_FIXED;
697 record_length += sizeof(int32_t);
698 } else if (type == "string")
699 chunk.type = FG_STRING;
702 record_length += sizeof(int32_t);
704 msg.push_back(chunk);
709 if (binary_record_length == -1) {
710 binary_record_length = record_length;
711 } else if (binary_record_length < record_length) {
712 SG_LOG(SG_IO, SG_ALERT,
713 "generic protocol: Requested binary record length shorter than "
714 " requested record representation.");
715 binary_record_length = record_length;
720 void FGGeneric::updateValue(FGGeneric::_serial_prot& prot, bool val)
724 // value inverted if received true, otherwise leave unchanged
726 setValue(prot.prop, !getValue<bool>(prot.prop));
730 setValue(prot.prop, val);