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()
31 #include <simgear/debug/logstream.hxx>
32 #include <simgear/io/iochannel.hxx>
33 #include <simgear/structure/exception.hxx>
34 #include <simgear/misc/sg_path.hxx>
35 #include <simgear/misc/stdint.hxx>
36 #include <simgear/props/props.hxx>
37 #include <simgear/props/props_io.hxx>
38 #include <simgear/math/SGMath.hxx>
40 #include <Main/globals.hxx>
41 #include <Main/fg_props.hxx>
42 #include <Main/fg_os.hxx>
43 #include <Main/util.hxx>
44 #include "generic.hxx"
46 FGGeneric::FGGeneric(vector<string> tokens) : exitOnError(false), initOk(false)
49 if (tokens[1] == "socket") {
51 } else if (tokens[1] == "file") {
57 if ((configToken >= tokens.size())||(tokens[ configToken ] == "")) {
58 SG_LOG(SG_NETWORK, SG_ALERT,
59 "Not enough tokens passed for generic '" << tokens[1] << "' protocol. ");
63 string config = tokens[ configToken ];
64 file_name = config+".xml";
65 direction = tokens[2];
67 if (direction != "in" && direction != "out" && direction != "bi") {
68 SG_LOG(SG_NETWORK, SG_ALERT, "Unsuported protocol direction: "
76 FGGeneric::~FGGeneric() {
89 // generate the message
90 bool FGGeneric::gen_message_binary() {
91 string generic_sentence;
95 for (unsigned int i = 0; i < _out_message.size(); i++) {
97 switch (_out_message[i].type) {
100 val = _out_message[i].offset +
101 _out_message[i].prop->getIntValue() * _out_message[i].factor;
102 int32_t intVal = val;
103 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
104 intVal = (int32_t) sg_bswap_32((uint32_t)intVal);
106 memcpy(&buf[length], &intVal, sizeof(int32_t));
107 length += sizeof(int32_t);
112 buf[length] = (char) (_out_message[i].prop->getBoolValue() ? true : false);
118 val = _out_message[i].offset +
119 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
121 int32_t fixed = (int)(val * 65536.0f);
122 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
123 fixed = (int32_t) sg_bswap_32((uint32_t)fixed);
125 memcpy(&buf[length], &fixed, sizeof(int32_t));
126 length += sizeof(int32_t);
132 val = _out_message[i].offset +
133 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
135 tmpun32.floatVal = static_cast<float>(val);
137 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
138 tmpun32.intVal = sg_bswap_32(tmpun32.intVal);
140 memcpy(&buf[length], &tmpun32.intVal, sizeof(uint32_t));
141 length += sizeof(uint32_t);
147 val = _out_message[i].offset +
148 _out_message[i].prop->getDoubleValue() * _out_message[i].factor;
150 tmpun64.doubleVal = val;
152 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
153 tmpun64.longVal = sg_bswap_64(tmpun64.longVal);
155 memcpy(&buf[length], &tmpun64.longVal, sizeof(uint64_t));
156 length += sizeof(uint64_t);
160 default: // SG_STRING
161 const char *strdata = _out_message[i].prop->getStringValue();
162 int32_t strlength = strlen(strdata);
164 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
165 SG_LOG( SG_IO, SG_ALERT, "Generic protocol: "
166 "FG_STRING will be written in host byte order.");
168 /* Format for strings is
169 * [length as int, 4 bytes][ASCII data, length bytes]
171 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
172 strlength = sg_bswap_32(strlength);
174 memcpy(&buf[length], &strlength, sizeof(int32_t));
175 length += sizeof(int32_t);
176 strncpy(&buf[length], strdata, strlength);
178 /* FIXME padding for alignment? Something like:
179 * length += (strlength % 4 > 0 ? sizeof(int32_t) - strlength % 4 : 0;
185 // add the footer to the packet ("line")
186 switch (binary_footer_type) {
188 binary_footer_value = length;
196 if (binary_footer_type != FOOTER_NONE) {
197 int32_t intValue = binary_footer_value;
198 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
199 intValue = sg_bswap_32(binary_footer_value);
201 memcpy(&buf[length], &intValue, sizeof(int32_t));
202 length += sizeof(int32_t);
208 bool FGGeneric::gen_message_ascii() {
209 string generic_sentence;
214 for (unsigned int i = 0; i < _out_message.size(); i++) {
217 generic_sentence += var_separator;
220 switch (_out_message[i].type) {
222 val = _out_message[i].offset +
223 _out_message[i].prop->getIntValue() * _out_message[i].factor;
224 snprintf(tmp, 255, _out_message[i].format.c_str(), (int)val);
228 snprintf(tmp, 255, _out_message[i].format.c_str(),
229 _out_message[i].prop->getBoolValue());
233 val = _out_message[i].offset +
234 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
235 snprintf(tmp, 255, _out_message[i].format.c_str(), (float)val);
239 val = _out_message[i].offset +
240 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
241 snprintf(tmp, 255, _out_message[i].format.c_str(), (float)val);
245 val = _out_message[i].offset +
246 _out_message[i].prop->getDoubleValue() * _out_message[i].factor;
247 snprintf(tmp, 255, _out_message[i].format.c_str(), (double)val);
250 default: // SG_STRING
251 snprintf(tmp, 255, _out_message[i].format.c_str(),
252 _out_message[i].prop->getStringValue());
255 generic_sentence += tmp;
258 /* After each lot of variables has been added, put the line separator
261 generic_sentence += line_separator;
263 length = generic_sentence.length();
264 strncpy( buf, generic_sentence.c_str(), length );
269 bool FGGeneric::gen_message() {
271 return gen_message_binary();
273 return gen_message_ascii();
277 bool FGGeneric::parse_message_binary(int length) {
283 while ((++i < (int)_in_message.size()) && (p1 < p2)) {
285 switch (_in_message[i].type) {
287 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
288 tmp32 = sg_bswap_32(*(int32_t *)p1);
290 tmp32 = *(int32_t *)p1;
292 updateValue(_in_message[i], (int)tmp32);
293 p1 += sizeof(int32_t);
297 updateValue(_in_message[i], p1[0] != 0);
302 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
303 tmp32 = sg_bswap_32(*(int32_t *)p1);
305 tmp32 = *(int32_t *)p1;
307 updateValue(_in_message[i], (float)tmp32 / 65536.0f);
308 p1 += sizeof(int32_t);
313 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
314 tmpun32.intVal = sg_bswap_32(*(uint32_t *)p1);
316 tmpun32.floatVal = *(float *)p1;
318 updateValue(_in_message[i], tmpun32.floatVal);
319 p1 += sizeof(int32_t);
324 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
325 tmpun64.longVal = sg_bswap_64(*(uint64_t *)p1);
327 tmpun64.doubleVal = *(double *)p1;
329 updateValue(_in_message[i], tmpun64.doubleVal);
330 p1 += sizeof(int64_t);
333 default: // SG_STRING
334 SG_LOG( SG_IO, SG_ALERT, "Generic protocol: "
335 "Ignoring unsupported binary input chunk type.");
343 bool FGGeneric::parse_message_ascii(int length) {
346 int chunks = _in_message.size();
347 int line_separator_size = line_separator.size();
349 if (length < line_separator_size ||
350 line_separator.compare(buf + length - line_separator_size) != 0) {
352 SG_LOG(SG_IO, SG_WARN,
353 "Input line does not end with expected line separator." );
355 buf[length - line_separator_size] = 0;
358 size_t varsep_len = var_separator.length();
359 while ((++i < chunks) && p1) {
364 p2 = strstr(p1, var_separator.c_str());
371 switch (_in_message[i].type) {
373 updateValue(_in_message[i], atoi(p1));
377 updateValue(_in_message[i], atof(p1) != 0.0);
382 updateValue(_in_message[i], (float)strtod(p1, 0));
386 updateValue(_in_message[i], (double)strtod(p1, 0));
389 default: // SG_STRING
390 _in_message[i].prop->setStringValue(p1);
400 bool FGGeneric::parse_message_len(int length) {
402 return parse_message_binary(length);
404 return parse_message_ascii(length);
409 // open hailing frequencies
410 bool FGGeneric::open() {
411 if ( is_enabled() ) {
412 SG_LOG( SG_IO, SG_ALERT, "This shouldn't happen, but the channel "
413 << "is already in use, ignoring" );
417 SGIOChannel *io = get_io_channel();
419 if ( ! io->open( get_direction() ) ) {
420 SG_LOG( SG_IO, SG_ALERT, "Error opening channel communication layer." );
426 if ( ((get_direction() == SG_IO_OUT )||
427 (get_direction() == SG_IO_BI))
428 && ! preamble.empty() ) {
429 if ( ! io->write( preamble.c_str(), preamble.size() ) ) {
430 SG_LOG( SG_IO, SG_WARN, "Error writing preamble." );
439 // process work for this port
440 bool FGGeneric::process() {
441 SGIOChannel *io = get_io_channel();
443 if ( (get_direction() == SG_IO_OUT) ||
444 (get_direction() == SG_IO_BI) ) {
446 if ( ! io->write( buf, length ) ) {
447 SG_LOG( SG_IO, SG_WARN, "Error writing data." );
452 if (( get_direction() == SG_IO_IN ) ||
453 (get_direction() == SG_IO_BI) ) {
454 if ( io->get_type() == sgFileType ) {
456 length = io->readline( buf, FG_MAX_MSG_SIZE );
458 parse_message_len( length );
460 SG_LOG( SG_IO, SG_ALERT, "Error reading data." );
464 length = io->read( buf, binary_record_length );
465 if ( length == binary_record_length ) {
466 parse_message_len( length );
468 SG_LOG( SG_IO, SG_ALERT,
469 "Generic protocol: Received binary "
470 "record of unexpected size, expected: "
471 << binary_record_length << " but received: "
477 while ((length = io->readline( buf, FG_MAX_MSG_SIZE )) > 0 ) {
478 parse_message_len( length );
481 while ((length = io->read( buf, binary_record_length ))
482 == binary_record_length ) {
483 parse_message_len( length );
487 SG_LOG( SG_IO, SG_ALERT,
488 "Generic protocol: Received binary "
489 "record of unexpected size, expected: "
490 << binary_record_length << " but received: "
500 return true; // should not get there, but please the compiler
507 bool FGGeneric::close() {
508 SGIOChannel *io = get_io_channel();
510 if ( ((get_direction() == SG_IO_OUT)||
511 (get_direction() == SG_IO_BI))
512 && ! postamble.empty() ) {
513 if ( ! io->write( postamble.c_str(), postamble.size() ) ) {
514 SG_LOG( SG_IO, SG_ALERT, "Error writing postamble." );
519 set_enabled( false );
521 if ( ! io->close() ) {
532 SGPath path( globals->get_fg_root() );
533 path.append("Protocol");
534 path.append(file_name.c_str());
536 SG_LOG(SG_NETWORK, SG_INFO, "Reading communication protocol from "
541 readProperties(path.str(), &root);
542 } catch (const sg_exception & ex) {
543 SG_LOG(SG_NETWORK, SG_ALERT,
544 "Unable to load the protocol configuration file: " << ex.getFormattedMessage() );
548 if (direction == "out") {
549 SGPropertyNode *output = root.getNode("generic/output");
551 _out_message.clear();
552 if (!read_config(output, _out_message))
558 } else if (direction == "in") {
559 SGPropertyNode *input = root.getNode("generic/input");
562 if (!read_config(input, _in_message))
567 if (!binary_mode && (line_separator.size() == 0 ||
568 *line_separator.rbegin() != '\n')) {
570 SG_LOG(SG_IO, SG_WARN,
571 "Warning: Appending newline to line separator in generic input.");
572 line_separator.push_back('\n');
582 FGGeneric::read_config(SGPropertyNode *root, vector<_serial_prot> &msg)
584 binary_mode = root->getBoolValue("binary_mode");
587 /* These variables specified in the $FG_ROOT/data/Protocol/xxx.xml
588 * file for each format
590 * var_sep_string = the string/charachter to place between variables
591 * line_sep_string = the string/charachter to place at the end of each
594 preamble = fgUnescape(root->getStringValue("preamble"));
595 postamble = fgUnescape(root->getStringValue("postamble"));
596 var_sep_string = fgUnescape(root->getStringValue("var_separator"));
597 line_sep_string = fgUnescape(root->getStringValue("line_separator"));
599 if ( var_sep_string == "newline" ) {
600 var_separator = '\n';
601 } else if ( var_sep_string == "tab" ) {
602 var_separator = '\t';
603 } else if ( var_sep_string == "space" ) {
605 } else if ( var_sep_string == "formfeed" ) {
606 var_separator = '\f';
607 } else if ( var_sep_string == "carriagereturn" ) {
608 var_sep_string = '\r';
609 } else if ( var_sep_string == "verticaltab" ) {
610 var_separator = '\v';
612 var_separator = var_sep_string;
615 if ( line_sep_string == "newline" ) {
616 line_separator = '\n';
617 } else if ( line_sep_string == "tab" ) {
618 line_separator = '\t';
619 } else if ( line_sep_string == "space" ) {
620 line_separator = ' ';
621 } else if ( line_sep_string == "formfeed" ) {
622 line_separator = '\f';
623 } else if ( line_sep_string == "carriagereturn" ) {
624 line_separator = '\r';
625 } else if ( line_sep_string == "verticaltab" ) {
626 line_separator = '\v';
628 line_separator = line_sep_string;
631 // default values: no footer and record_length = sizeof(representation)
632 binary_footer_type = FOOTER_NONE;
633 binary_record_length = -1;
635 // default choice is network byte order (big endian)
636 if (sgIsLittleEndian()) {
637 binary_byte_order = BYTE_ORDER_NEEDS_CONVERSION;
639 binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
642 if ( root->hasValue("binary_footer") ) {
643 string footer_type = root->getStringValue("binary_footer");
644 if ( footer_type == "length" ) {
645 binary_footer_type = FOOTER_LENGTH;
646 } else if ( footer_type.substr(0, 5) == "magic" ) {
647 binary_footer_type = FOOTER_MAGIC;
648 binary_footer_value = strtol(footer_type.substr(6,
649 footer_type.length() - 6).c_str(), (char**)0, 0);
650 } else if ( footer_type != "none" ) {
651 SG_LOG(SG_IO, SG_ALERT,
652 "generic protocol: Unknown generic binary protocol "
653 "footer '" << footer_type << "', using no footer.");
657 if ( root->hasValue("record_length") ) {
658 binary_record_length = root->getIntValue("record_length");
661 if ( root->hasValue("byte_order") ) {
662 string byte_order = root->getStringValue("byte_order");
663 if (byte_order == "network" ) {
664 if ( sgIsLittleEndian() ) {
665 binary_byte_order = BYTE_ORDER_NEEDS_CONVERSION;
667 binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
669 } else if ( byte_order == "host" ) {
670 binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
672 SG_LOG(SG_IO, SG_ALERT,
673 "generic protocol: Undefined generic binary protocol"
674 "byte order, using HOST byte order.");
679 int record_length = 0; // Only used for binary protocols.
680 vector<SGPropertyNode_ptr> chunks = root->getChildren("chunk");
682 for (unsigned int i = 0; i < chunks.size(); i++) {
686 // chunk.name = chunks[i]->getStringValue("name");
687 chunk.format = fgUnescape(chunks[i]->getStringValue("format", "%d"));
688 chunk.offset = chunks[i]->getDoubleValue("offset");
689 chunk.factor = chunks[i]->getDoubleValue("factor", 1.0);
690 chunk.min = chunks[i]->getDoubleValue("min");
691 chunk.max = chunks[i]->getDoubleValue("max");
692 chunk.wrap = chunks[i]->getBoolValue("wrap");
693 chunk.rel = chunks[i]->getBoolValue("relative");
695 string node = chunks[i]->getStringValue("node", "/null");
696 chunk.prop = fgGetNode(node.c_str(), true);
698 string type = chunks[i]->getStringValue("type");
700 // Note: officially the type is called 'bool' but for backward
701 // compatibility 'boolean' will also be supported.
702 if (type == "bool" || type == "boolean") {
703 chunk.type = FG_BOOL;
705 } else if (type == "float") {
706 chunk.type = FG_FLOAT;
707 record_length += sizeof(int32_t);
708 } else if (type == "double") {
709 chunk.type = FG_DOUBLE;
710 record_length += sizeof(int64_t);
711 } else if (type == "fixed") {
712 chunk.type = FG_FIXED;
713 record_length += sizeof(int32_t);
714 } else if (type == "string")
715 chunk.type = FG_STRING;
718 record_length += sizeof(int32_t);
720 msg.push_back(chunk);
726 if ((chunks.size() > 1)&&(var_sep_string.length() == 0))
728 // ASCII protocols really need a separator when there is more than one chunk per line
729 SG_LOG(SG_IO, SG_ALERT,
730 "generic protocol: Invalid configuration. "
731 "'var_separator' must not be empty for protocols which have more than one chunk per line.");
737 if (binary_record_length == -1) {
738 binary_record_length = record_length;
739 } else if (binary_record_length < record_length) {
740 SG_LOG(SG_IO, SG_ALERT,
741 "generic protocol: Requested binary record length shorter than "
742 " requested record representation.");
743 binary_record_length = record_length;
750 void FGGeneric::updateValue(FGGeneric::_serial_prot& prot, bool val)
754 // value inverted if received true, otherwise leave unchanged
756 setValue(prot.prop, !getValue<bool>(prot.prop));
760 setValue(prot.prop, val);