1 // generic.cxx -- generic protocal 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>
38 #include <Main/globals.hxx>
39 #include <Main/fg_props.hxx>
40 #include <Main/fg_os.hxx>
41 #include <Main/util.hxx>
42 #include "generic.hxx"
46 FGGeneric::FGGeneric(vector<string> tokens) : exitOnError(false)
49 if (tokens[1] == "socket") {
51 } else if (tokens[1] == "file") {
57 if (configToken >= tokens.size()) {
58 SG_LOG(SG_GENERAL, SG_ALERT,
59 "Not enough tokens passed for generic protocol");
63 string config = tokens[ configToken ];
64 file_name = config+".xml";
65 direction = tokens[2];
67 if (direction != "in" && direction != "out") {
68 SG_LOG(SG_GENERAL, 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;
183 // add the footer to the packet ("line")
184 switch (binary_footer_type) {
186 binary_footer_value = length;
194 if (binary_footer_type != FOOTER_NONE) {
195 int32_t intValue = binary_footer_value;
196 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
197 intValue = sg_bswap_32(binary_footer_value);
199 memcpy(&buf[length], &intValue, sizeof(int32_t));
200 length += sizeof(int32_t);
206 bool FGGeneric::gen_message_ascii() {
207 string generic_sentence;
212 for (unsigned int i = 0; i < _out_message.size(); i++) {
215 generic_sentence += var_separator;
218 switch (_out_message[i].type) {
220 val = _out_message[i].offset +
221 _out_message[i].prop->getIntValue() * _out_message[i].factor;
222 snprintf(tmp, 255, _out_message[i].format.c_str(), (int)val);
226 snprintf(tmp, 255, _out_message[i].format.c_str(),
227 _out_message[i].prop->getBoolValue());
231 val = _out_message[i].offset +
232 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
233 snprintf(tmp, 255, _out_message[i].format.c_str(), (float)val);
237 val = _out_message[i].offset +
238 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
239 snprintf(tmp, 255, _out_message[i].format.c_str(), (float)val);
243 val = _out_message[i].offset +
244 _out_message[i].prop->getDoubleValue() * _out_message[i].factor;
245 snprintf(tmp, 255, _out_message[i].format.c_str(), (double)val);
248 default: // SG_STRING
249 snprintf(tmp, 255, _out_message[i].format.c_str(),
250 _out_message[i].prop->getStringValue());
253 generic_sentence += tmp;
256 /* After each lot of variables has been added, put the line separator
259 generic_sentence += line_separator;
261 length = generic_sentence.length();
262 strncpy( buf, generic_sentence.c_str(), length );
267 bool FGGeneric::gen_message() {
269 return gen_message_binary();
271 return gen_message_ascii();
275 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;
292 val = _in_message[i].offset + (double)tmp32 * _in_message[i].factor;
294 _in_message[i].prop->setIntValue((int)val);
295 p1 += sizeof(int32_t);
299 _in_message[i].prop->setBoolValue( p1[0] != 0 );
304 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
305 tmp32 = sg_bswap_32(*(int32_t *)p1);
307 tmp32 = *(int32_t *)p1;
310 val = _in_message[i].offset +
311 ((double)tmp32 / 65536.0f) * _in_message[i].factor;
313 _in_message[i].prop->setFloatValue(val);
314 p1 += sizeof(int32_t);
319 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
320 tmpun32.intVal = sg_bswap_32(*(uint32_t *)p1);
322 tmpun32.floatVal = *(float *)p1;
325 val = _in_message[i].offset +
326 tmpun32.floatVal * _in_message[i].factor;
328 _in_message[i].prop->setFloatValue(val);
329 p1 += sizeof(int32_t);
334 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
335 tmpun64.longVal = sg_bswap_64(*(uint64_t *)p1);
337 tmpun64.doubleVal = *(double *)p1;
340 val = _in_message[i].offset +
341 tmpun64.doubleVal * _in_message[i].factor;
343 _in_message[i].prop->setDoubleValue(val);
344 p1 += sizeof(int64_t);
347 default: // SG_STRING
348 SG_LOG( SG_IO, SG_ALERT, "Generic protocol: "
349 "Ignoring unsupported binary input chunk type.");
356 bool FGGeneric::parse_message_ascii(int length) {
360 int chunks = _in_message.size();
361 int line_separator_size = line_separator.size();
363 if (length < line_separator_size ||
364 line_separator.compare(buf + length - line_separator_size) != 0) {
366 SG_LOG(SG_IO, SG_WARN,
367 "Input line does not end with expected line separator." );
369 buf[length - line_separator_size] = 0;
372 while ((++i < chunks) && p1) {
373 p2 = strstr(p1, var_separator.c_str());
376 p2 += var_separator.length();
379 switch (_in_message[i].type) {
381 val = _in_message[i].offset + atoi(p1) * _in_message[i].factor;
382 _in_message[i].prop->setIntValue((int)val);
386 _in_message[i].prop->setBoolValue( atof(p1) != 0.0 );
391 val = _in_message[i].offset + strtod(p1, 0) * _in_message[i].factor;
392 _in_message[i].prop->setFloatValue((float)val);
396 val = _in_message[i].offset + strtod(p1, 0) * _in_message[i].factor;
397 _in_message[i].prop->setDoubleValue(val);
400 default: // SG_STRING
401 _in_message[i].prop->setStringValue(p1);
410 bool FGGeneric::parse_message(int length) {
412 return parse_message_binary(length);
414 return parse_message_ascii(length);
419 // open hailing frequencies
420 bool FGGeneric::open() {
421 if ( is_enabled() ) {
422 SG_LOG( SG_IO, SG_ALERT, "This shouldn't happen, but the channel "
423 << "is already in use, ignoring" );
427 SGIOChannel *io = get_io_channel();
429 if ( ! io->open( get_direction() ) ) {
430 SG_LOG( SG_IO, SG_ALERT, "Error opening channel communication layer." );
436 if ( get_direction() == SG_IO_OUT && ! preamble.empty() ) {
437 if ( ! io->write( preamble.c_str(), preamble.size() ) ) {
438 SG_LOG( SG_IO, SG_WARN, "Error writing preamble." );
447 // process work for this port
448 bool FGGeneric::process() {
449 SGIOChannel *io = get_io_channel();
451 if ( get_direction() == SG_IO_OUT ) {
453 if ( ! io->write( buf, length ) ) {
454 SG_LOG( SG_IO, SG_WARN, "Error writing data." );
457 } else if ( get_direction() == SG_IO_IN ) {
458 if ( io->get_type() == sgFileType ) {
460 length = io->readline( buf, FG_MAX_MSG_SIZE );
462 parse_message( length );
464 SG_LOG( SG_IO, SG_ALERT, "Error reading data." );
468 length = io->read( buf, binary_record_length );
469 if ( length == binary_record_length ) {
470 parse_message( length );
472 SG_LOG( SG_IO, SG_ALERT,
473 "Generic protocol: Received binary "
474 "record of unexpected size, expected: "
475 << binary_record_length << " but received: "
481 while ((length = io->readline( buf, FG_MAX_MSG_SIZE )) > 0 ) {
482 parse_message( length );
485 while ((length = io->read( buf, binary_record_length ))
486 == binary_record_length ) {
487 parse_message( length );
491 SG_LOG( SG_IO, SG_ALERT,
492 "Generic protocol: Received binary "
493 "record of unexpected size, expected: "
494 << binary_record_length << " but received: "
504 return true; // should not get there, but please the compiler
511 bool FGGeneric::close() {
512 SGIOChannel *io = get_io_channel();
514 if ( get_direction() == SG_IO_OUT && ! postamble.empty() ) {
515 if ( ! io->write( postamble.c_str(), postamble.size() ) ) {
516 SG_LOG( SG_IO, SG_ALERT, "Error writing postamble." );
521 set_enabled( false );
523 if ( ! io->close() ) {
534 SGPath path( globals->get_fg_root() );
535 path.append("Protocol");
536 path.append(file_name.c_str());
538 SG_LOG(SG_GENERAL, SG_INFO, "Reading communication protocol from "
543 readProperties(path.str(), &root);
544 } catch (const sg_exception &) {
545 SG_LOG(SG_GENERAL, SG_ALERT,
546 "Unable to load the protocol configuration file");
550 if (direction == "out") {
551 SGPropertyNode *output = root.getNode("generic/output");
553 _out_message.clear();
554 read_config(output, _out_message);
556 } else if (direction == "in") {
557 SGPropertyNode *input = root.getNode("generic/input");
560 read_config(input, _in_message);
561 if (!binary_mode && (line_separator.size() == 0 ||
562 *line_separator.rbegin() != '\n')) {
564 SG_LOG(SG_IO, SG_WARN,
565 "Warning: Appending newline to line separator in generic input.");
566 line_separator.push_back('\n');
574 FGGeneric::read_config(SGPropertyNode *root, vector<_serial_prot> &msg)
576 binary_mode = root->getBoolValue("binary_mode");
579 /* These variables specified in the $FG_ROOT/data/Protocol/xxx.xml
580 * file for each format
582 * var_sep_string = the string/charachter to place between variables
583 * line_sep_string = the string/charachter to place at the end of each
586 preamble = fgUnescape(root->getStringValue("preamble"));
587 postamble = fgUnescape(root->getStringValue("postamble"));
588 var_sep_string = fgUnescape(root->getStringValue("var_separator"));
589 line_sep_string = fgUnescape(root->getStringValue("line_separator"));
591 if ( var_sep_string == "newline" ) {
592 var_separator = '\n';
593 } else if ( var_sep_string == "tab" ) {
594 var_separator = '\t';
595 } else if ( var_sep_string == "space" ) {
597 } else if ( var_sep_string == "formfeed" ) {
598 var_separator = '\f';
599 } else if ( var_sep_string == "carriagereturn" ) {
600 var_sep_string = '\r';
601 } else if ( var_sep_string == "verticaltab" ) {
602 var_separator = '\v';
604 var_separator = var_sep_string;
607 if ( line_sep_string == "newline" ) {
608 line_separator = '\n';
609 } else if ( line_sep_string == "tab" ) {
610 line_separator = '\t';
611 } else if ( line_sep_string == "space" ) {
612 line_separator = ' ';
613 } else if ( line_sep_string == "formfeed" ) {
614 line_separator = '\f';
615 } else if ( line_sep_string == "carriagereturn" ) {
616 line_separator = '\r';
617 } else if ( line_sep_string == "verticaltab" ) {
618 line_separator = '\v';
620 line_separator = line_sep_string;
623 // default values: no footer and record_length = sizeof(representation)
624 binary_footer_type = FOOTER_NONE;
625 binary_record_length = -1;
627 // default choice is network byte order (big endian)
628 if (sgIsLittleEndian()) {
629 binary_byte_order = BYTE_ORDER_NEEDS_CONVERSION;
631 binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
634 if ( root->hasValue("binary_footer") ) {
635 string footer_type = root->getStringValue("binary_footer");
636 if ( footer_type == "length" ) {
637 binary_footer_type = FOOTER_LENGTH;
638 } else if ( footer_type.substr(0, 5) == "magic" ) {
639 binary_footer_type = FOOTER_MAGIC;
640 binary_footer_value = strtol(footer_type.substr(6,
641 footer_type.length() - 6).c_str(), (char**)0, 0);
642 } else if ( footer_type != "none" ) {
643 SG_LOG(SG_IO, SG_ALERT,
644 "generic protocol: Unknown generic binary protocol "
645 "footer '" << footer_type << "', using no footer.");
649 if ( root->hasValue("record_length") ) {
650 binary_record_length = root->getIntValue("record_length");
653 if ( root->hasValue("byte_order") ) {
654 string byte_order = root->getStringValue("byte_order");
655 if (byte_order == "network" ) {
656 if ( sgIsLittleEndian() ) {
657 binary_byte_order = BYTE_ORDER_NEEDS_CONVERSION;
659 binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
661 } else if ( byte_order == "host" ) {
662 binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
664 SG_LOG(SG_IO, SG_ALERT,
665 "generic protocol: Undefined generic binary protocol"
666 "byte order, using HOST byte order.");
671 int record_length = 0; // Only used for binary protocols.
672 vector<SGPropertyNode_ptr> chunks = root->getChildren("chunk");
673 for (unsigned int i = 0; i < chunks.size(); i++) {
677 // chunk.name = chunks[i]->getStringValue("name");
678 chunk.format = fgUnescape(chunks[i]->getStringValue("format", "%d"));
679 chunk.offset = chunks[i]->getDoubleValue("offset");
680 chunk.factor = chunks[i]->getDoubleValue("factor", 1.0);
682 string node = chunks[i]->getStringValue("node", "/null");
683 chunk.prop = fgGetNode(node.c_str(), true);
685 string type = chunks[i]->getStringValue("type");
687 // Note: officially the type is called 'bool' but for backward
688 // compatibility 'boolean' will also be supported.
689 if (type == "bool" || type == "boolean") {
690 chunk.type = FG_BOOL;
692 } else if (type == "float") {
693 chunk.type = FG_FLOAT;
694 record_length += sizeof(int32_t);
695 } else if (type == "double") {
696 chunk.type = FG_DOUBLE;
697 record_length += sizeof(int64_t);
698 } else if (type == "fixed") {
699 chunk.type = FG_FIXED;
700 record_length += sizeof(int32_t);
701 } else if (type == "string")
702 chunk.type = FG_STRING;
705 record_length += sizeof(int32_t);
707 msg.push_back(chunk);
712 if (binary_record_length == -1) {
713 binary_record_length = record_length;
714 } else if (binary_record_length < record_length) {
715 SG_LOG(SG_IO, SG_ALERT,
716 "generic protocol: Requested binary record length shorter than "
717 " requested record representation.");
718 binary_record_length = record_length;