]> git.mxchange.org Git - flightgear.git/blob - src/Network/generic.cxx
Merge branch 'next' of gitorious.org:fg/flightgear into next
[flightgear.git] / src / Network / generic.cxx
1 // generic.cxx -- generic protocol class
2 //
3 // Written by Curtis Olson, started November 1999.
4 //
5 // Copyright (C) 1999  Curtis L. Olson - http://www.flightgear.org/~curt
6 //
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.
11 //
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.
16 //
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.
20 //
21 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include "config.h"
25 #endif
26
27 #include <string.h>                // strstr()
28 #include <stdlib.h>                // strtod(), atoi()
29
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>
38
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"
44
45 FGGeneric::FGGeneric(vector<string> tokens) : exitOnError(false)
46 {
47     size_t configToken;
48     if (tokens[1] == "socket") {
49         configToken = 7;
50     } else if (tokens[1] == "file") {
51         configToken = 5;
52     } else {
53         configToken = 6; 
54     }
55
56     if (configToken >= tokens.size()) {
57        SG_LOG(SG_NETWORK, SG_ALERT,
58               "Not enough tokens passed for generic protocol");
59        return;
60     }
61
62     string config = tokens[ configToken ];
63     file_name = config+".xml";
64     direction = tokens[2];
65
66     if (direction != "in" && direction != "out" && direction != "bi") {
67         SG_LOG(SG_NETWORK, SG_ALERT, "Unsuported protocol direction: "
68                << direction);
69     }
70
71     reinit();
72 }
73
74 FGGeneric::~FGGeneric() {
75 }
76
77 union u32 {
78     uint32_t intVal;
79     float floatVal;
80 };
81
82 union u64 {
83     uint64_t longVal;
84     double doubleVal;
85 };
86
87 // generate the message
88 bool FGGeneric::gen_message_binary() {
89     string generic_sentence;
90     length = 0;
91
92     double val;
93     for (unsigned int i = 0; i < _out_message.size(); i++) {
94
95         switch (_out_message[i].type) {
96         case FG_INT:
97         {
98             val = _out_message[i].offset +
99                   _out_message[i].prop->getIntValue() * _out_message[i].factor;
100             int32_t intVal = val;
101             if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
102                 intVal = (int32_t) sg_bswap_32((uint32_t)intVal);
103             }
104             memcpy(&buf[length], &intVal, sizeof(int32_t));
105             length += sizeof(int32_t);
106             break;
107         }
108
109         case FG_BOOL:
110             buf[length] = (char) (_out_message[i].prop->getBoolValue() ? true : false);
111             length += 1;
112             break;
113
114         case FG_FIXED:
115         {
116             val = _out_message[i].offset +
117                  _out_message[i].prop->getFloatValue() * _out_message[i].factor;
118
119             int32_t fixed = (int)(val * 65536.0f);
120             if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
121                 fixed = (int32_t) sg_bswap_32((uint32_t)fixed);
122             } 
123             memcpy(&buf[length], &fixed, sizeof(int32_t));
124             length += sizeof(int32_t);
125             break;
126         }
127
128         case FG_FLOAT:
129         {
130             val = _out_message[i].offset +
131                  _out_message[i].prop->getFloatValue() * _out_message[i].factor;
132             u32 tmpun32;
133             tmpun32.floatVal = static_cast<float>(val);
134
135             if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
136                 tmpun32.intVal = sg_bswap_32(tmpun32.intVal);
137             }
138             memcpy(&buf[length], &tmpun32.intVal, sizeof(uint32_t));
139             length += sizeof(uint32_t);
140             break;
141         }
142
143         case FG_DOUBLE:
144         {
145             val = _out_message[i].offset +
146                  _out_message[i].prop->getFloatValue() * _out_message[i].factor;
147             u64 tmpun64;
148             tmpun64.doubleVal = val;
149
150             if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
151                 tmpun64.longVal = sg_bswap_64(tmpun64.longVal);
152             }
153             memcpy(&buf[length], &tmpun64.longVal, sizeof(uint64_t));
154             length += sizeof(uint64_t);
155             break;
156         }
157
158         default: // SG_STRING
159             const char *strdata = _out_message[i].prop->getStringValue();
160             int32_t strlength = strlen(strdata);
161
162             if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
163                 SG_LOG( SG_IO, SG_ALERT, "Generic protocol: "
164                         "FG_STRING will be written in host byte order.");
165             }
166             /* Format for strings is 
167              * [length as int, 4 bytes][ASCII data, length bytes]
168              */
169             if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
170                 strlength = sg_bswap_32(strlength);
171             }
172             memcpy(&buf[length], &strlength, sizeof(int32_t));
173             length += sizeof(int32_t);
174             strncpy(&buf[length], strdata, strlength);
175             length += strlength; 
176             /* FIXME padding for alignment? Something like: 
177              * length += (strlength % 4 > 0 ? sizeof(int32_t) - strlength % 4 : 0;
178              */
179             break;
180         }
181     }
182
183     // add the footer to the packet ("line")
184     switch (binary_footer_type) {
185         case FOOTER_LENGTH:
186             binary_footer_value = length;
187             break;
188
189         case FOOTER_MAGIC:
190         case FOOTER_NONE:
191             break;
192     }
193
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);
198         }
199         memcpy(&buf[length], &intValue, sizeof(int32_t));
200         length += sizeof(int32_t);
201     }
202
203     return true;
204 }
205
206 bool FGGeneric::gen_message_ascii() {
207     string generic_sentence;
208     char tmp[255];
209     length = 0;
210
211     double val;
212     for (unsigned int i = 0; i < _out_message.size(); i++) {
213
214         if (i > 0) {
215             generic_sentence += var_separator;
216         }
217
218         switch (_out_message[i].type) {
219         case FG_INT:
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);
223             break;
224
225         case FG_BOOL:
226             snprintf(tmp, 255, _out_message[i].format.c_str(),
227                                _out_message[i].prop->getBoolValue());
228             break;
229
230         case FG_FIXED:
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);
234             break;
235
236         case FG_FLOAT:
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);
240             break;
241
242         case FG_DOUBLE:
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);
246             break;
247
248         default: // SG_STRING
249             snprintf(tmp, 255, _out_message[i].format.c_str(),
250                                    _out_message[i].prop->getStringValue());
251         }
252
253         generic_sentence += tmp;
254     }
255
256     /* After each lot of variables has been added, put the line separator
257      * char/string
258      */
259     generic_sentence += line_separator;
260
261     length =  generic_sentence.length();
262     strncpy( buf, generic_sentence.c_str(), length );
263
264     return true;
265 }
266
267 bool FGGeneric::gen_message() {
268     if (binary_mode) {
269         return gen_message_binary();
270     } else {
271         return gen_message_ascii();
272     }
273 }
274
275 bool FGGeneric::parse_message_binary(int length) {
276     char *p2, *p1 = buf;
277     int32_t tmp32;
278     int i = -1;
279
280     p2 = p1 + length;
281     while ((++i < (int)_in_message.size()) && (p1  < p2)) {
282
283         switch (_in_message[i].type) {
284         case FG_INT:
285             if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
286                 tmp32 = sg_bswap_32(*(int32_t *)p1);
287             } else {
288                 tmp32 = *(int32_t *)p1;
289             }
290             updateValue(_in_message[i], (int)tmp32);
291             p1 += sizeof(int32_t);
292             break;
293
294         case FG_BOOL:
295             updateValue(_in_message[i], p1[0] != 0);
296             p1 += 1;
297             break;
298
299         case FG_FIXED:
300             if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
301                 tmp32 = sg_bswap_32(*(int32_t *)p1);
302             } else {
303                 tmp32 = *(int32_t *)p1;
304             }
305             updateValue(_in_message[i], (float)tmp32 / 65536.0f);
306             p1 += sizeof(int32_t);
307             break;
308
309         case FG_FLOAT:
310             u32 tmpun32;
311             if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
312                 tmpun32.intVal = sg_bswap_32(*(uint32_t *)p1);
313             } else {
314                 tmpun32.floatVal = *(float *)p1;
315             }
316             updateValue(_in_message[i], tmpun32.floatVal);
317             p1 += sizeof(int32_t);
318             break;
319
320         case FG_DOUBLE:
321             u64 tmpun64;
322             if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
323                 tmpun64.longVal = sg_bswap_64(*(uint64_t *)p1);
324             } else {
325                 tmpun64.doubleVal = *(double *)p1;
326             }
327             updateValue(_in_message[i], tmpun64.doubleVal);
328             p1 += sizeof(int64_t);
329             break;
330
331         default: // SG_STRING
332             SG_LOG( SG_IO, SG_ALERT, "Generic protocol: "
333                     "Ignoring unsupported binary input chunk type.");
334             break;
335         }
336     }
337     
338     return true;
339 }
340
341 bool FGGeneric::parse_message_ascii(int length) {
342     char *p2, *p1 = buf;
343     int i = -1;
344     int chunks = _in_message.size();
345     int line_separator_size = line_separator.size();
346
347     if (length < line_separator_size ||
348         line_separator.compare(buf + length - line_separator_size) != 0) {
349
350         SG_LOG(SG_IO, SG_WARN,
351                "Input line does not end with expected line separator." );
352     } else {
353         buf[length - line_separator_size] = 0;
354     }
355
356     while ((++i < chunks) && p1) {
357         p2 = strstr(p1, var_separator.c_str());
358         if (p2) {
359             *p2 = 0;
360             p2 += var_separator.length();
361         }
362
363         switch (_in_message[i].type) {
364         case FG_INT:
365             updateValue(_in_message[i], atoi(p1));
366             break;
367
368         case FG_BOOL:
369             updateValue(_in_message[i], atof(p1) != 0.0);
370             break;
371
372         case FG_FIXED:
373         case FG_FLOAT:
374             updateValue(_in_message[i], (float)strtod(p1, 0));
375             break;
376
377         case FG_DOUBLE:
378             updateValue(_in_message[i], (double)strtod(p1, 0));
379             break;
380
381         default: // SG_STRING
382             _in_message[i].prop->setStringValue(p1);
383             break;
384         }
385
386         p1 = p2;
387     }
388
389     return true;
390 }
391
392 bool FGGeneric::parse_message(int length) {
393     if (binary_mode) {
394         return parse_message_binary(length);
395     } else {
396         return parse_message_ascii(length);
397     }
398 }
399
400
401 // open hailing frequencies
402 bool FGGeneric::open() {
403     if ( is_enabled() ) {
404         SG_LOG( SG_IO, SG_ALERT, "This shouldn't happen, but the channel " 
405                 << "is already in use, ignoring" );
406         return false;
407     }
408
409     SGIOChannel *io = get_io_channel();
410
411     if ( ! io->open( get_direction() ) ) {
412         SG_LOG( SG_IO, SG_ALERT, "Error opening channel communication layer." );
413         return false;
414     }
415
416     set_enabled( true );
417
418     if ( ((get_direction() == SG_IO_OUT )||
419           (get_direction() == SG_IO_BI))
420           && ! preamble.empty() ) {
421         if ( ! io->write( preamble.c_str(), preamble.size() ) ) {
422             SG_LOG( SG_IO, SG_WARN, "Error writing preamble." );
423             return false;
424         }
425     }
426
427     return true;
428 }
429
430
431 // process work for this port
432 bool FGGeneric::process() {
433     SGIOChannel *io = get_io_channel();
434
435     if ( (get_direction() == SG_IO_OUT) ||
436          (get_direction() == SG_IO_BI) ) {
437         gen_message();
438         if ( ! io->write( buf, length ) ) {
439             SG_LOG( SG_IO, SG_WARN, "Error writing data." );
440             goto error_out;
441         }
442     }
443
444     if (( get_direction() == SG_IO_IN ) ||
445         (get_direction() == SG_IO_BI) ) {
446         if ( io->get_type() == sgFileType ) {
447             if (!binary_mode) {
448                 length = io->readline( buf, FG_MAX_MSG_SIZE );
449                 if ( length > 0 ) {
450                     parse_message( length );
451                 } else {
452                     SG_LOG( SG_IO, SG_ALERT, "Error reading data." );
453                     return false;
454                 }
455             } else {
456                 length = io->read( buf, binary_record_length );
457                 if ( length == binary_record_length ) {
458                     parse_message( length );
459                 } else {
460                     SG_LOG( SG_IO, SG_ALERT,
461                             "Generic protocol: Received binary "
462                             "record of unexpected size, expected: "
463                             << binary_record_length << " but received: "
464                             << length);
465                 }
466             }
467         } else {
468             if (!binary_mode) {
469                 while ((length = io->readline( buf, FG_MAX_MSG_SIZE )) > 0 ) {
470                     parse_message( length );
471                 }
472             } else {
473                 while ((length = io->read( buf, binary_record_length )) 
474                           == binary_record_length ) {
475                     parse_message( length );
476                 }
477
478                 if ( length > 0 ) {
479                     SG_LOG( SG_IO, SG_ALERT,
480                         "Generic protocol: Received binary "
481                         "record of unexpected size, expected: "
482                         << binary_record_length << " but received: "
483                         << length);
484                 }
485             }
486         }
487     }
488     return true;
489 error_out:
490     if (exitOnError) {
491         fgOSExit(1);
492         return true; // should not get there, but please the compiler
493     } else
494         return false;
495 }
496
497
498 // close the channel
499 bool FGGeneric::close() {
500     SGIOChannel *io = get_io_channel();
501
502     if ( ((get_direction() == SG_IO_OUT)||
503           (get_direction() == SG_IO_BI))
504           && ! postamble.empty() ) {
505         if ( ! io->write( postamble.c_str(), postamble.size() ) ) {
506             SG_LOG( SG_IO, SG_ALERT, "Error writing postamble." );
507             return false;
508         }
509     }
510
511     set_enabled( false );
512
513     if ( ! io->close() ) {
514         return false;
515     }
516
517     return true;
518 }
519
520
521 void
522 FGGeneric::reinit()
523 {
524     SGPath path( globals->get_fg_root() );
525     path.append("Protocol");
526     path.append(file_name.c_str());
527
528     SG_LOG(SG_NETWORK, SG_INFO, "Reading communication protocol from "
529                                 << path.str());
530
531     SGPropertyNode root;
532     try {
533         readProperties(path.str(), &root);
534     } catch (const sg_exception & ex) {
535         SG_LOG(SG_NETWORK, SG_ALERT,
536          "Unable to load the protocol configuration file: " << ex.getFormattedMessage() );
537          return;
538     }
539
540     if (direction == "out") {
541         SGPropertyNode *output = root.getNode("generic/output");
542         if (output) {
543             _out_message.clear();
544             read_config(output, _out_message);
545         }
546     } else if (direction == "in") {
547         SGPropertyNode *input = root.getNode("generic/input");
548         if (input) {
549             _in_message.clear();
550             read_config(input, _in_message);
551             if (!binary_mode && (line_separator.size() == 0 ||
552                 *line_separator.rbegin() != '\n')) {
553
554                 SG_LOG(SG_IO, SG_WARN,
555                     "Warning: Appending newline to line separator in generic input.");
556                 line_separator.push_back('\n');
557             }
558         }
559     }
560 }
561
562
563 void
564 FGGeneric::read_config(SGPropertyNode *root, vector<_serial_prot> &msg)
565 {
566     binary_mode = root->getBoolValue("binary_mode");
567
568     if (!binary_mode) {
569         /* These variables specified in the $FG_ROOT/data/Protocol/xxx.xml
570          * file for each format
571          *
572          * var_sep_string  = the string/charachter to place between variables
573          * line_sep_string = the string/charachter to place at the end of each
574          *                   lot of variables
575          */
576         preamble = fgUnescape(root->getStringValue("preamble"));
577         postamble = fgUnescape(root->getStringValue("postamble"));
578         var_sep_string = fgUnescape(root->getStringValue("var_separator"));
579         line_sep_string = fgUnescape(root->getStringValue("line_separator"));
580
581         if ( var_sep_string == "newline" ) {
582             var_separator = '\n';
583         } else if ( var_sep_string == "tab" ) {
584             var_separator = '\t';
585         } else if ( var_sep_string == "space" ) {
586             var_separator = ' ';
587         } else if ( var_sep_string == "formfeed" ) {
588             var_separator = '\f';
589         } else if ( var_sep_string == "carriagereturn" ) {
590             var_sep_string = '\r';
591         } else if ( var_sep_string == "verticaltab" ) {
592             var_separator = '\v';
593         } else {
594             var_separator = var_sep_string;
595         }
596
597         if ( line_sep_string == "newline" ) {
598             line_separator = '\n';
599         } else if ( line_sep_string == "tab" ) {
600             line_separator = '\t';
601         } else if ( line_sep_string == "space" ) {
602             line_separator = ' ';
603         } else if ( line_sep_string == "formfeed" ) {
604             line_separator = '\f';
605         } else if ( line_sep_string == "carriagereturn" ) {
606             line_separator = '\r';
607         } else if ( line_sep_string == "verticaltab" ) {
608             line_separator = '\v';
609         } else {
610             line_separator = line_sep_string;
611         }
612     } else {
613         // default values: no footer and record_length = sizeof(representation)
614         binary_footer_type = FOOTER_NONE;
615         binary_record_length = -1;
616
617         // default choice is network byte order (big endian)
618         if (sgIsLittleEndian()) {
619            binary_byte_order = BYTE_ORDER_NEEDS_CONVERSION;
620         } else {
621            binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
622         }
623
624         if ( root->hasValue("binary_footer") ) {
625             string footer_type = root->getStringValue("binary_footer");
626             if ( footer_type == "length" ) {
627                 binary_footer_type = FOOTER_LENGTH;
628             } else if ( footer_type.substr(0, 5) == "magic" ) {
629                 binary_footer_type = FOOTER_MAGIC;
630                 binary_footer_value = strtol(footer_type.substr(6, 
631                             footer_type.length() - 6).c_str(), (char**)0, 0);
632             } else if ( footer_type != "none" ) {
633                 SG_LOG(SG_IO, SG_ALERT,
634                        "generic protocol: Unknown generic binary protocol "
635                        "footer '" << footer_type << "', using no footer.");
636             }
637         }
638
639         if ( root->hasValue("record_length") ) {
640             binary_record_length = root->getIntValue("record_length");
641         }
642
643         if ( root->hasValue("byte_order") ) {
644             string byte_order = root->getStringValue("byte_order");
645             if (byte_order == "network" ) {
646                 if ( sgIsLittleEndian() ) {
647                     binary_byte_order = BYTE_ORDER_NEEDS_CONVERSION;
648                 } else {
649                     binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
650                 }
651             } else if ( byte_order == "host" ) {
652                 binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
653             } else {
654                 SG_LOG(SG_IO, SG_ALERT,
655                        "generic protocol: Undefined generic binary protocol"
656                        "byte order, using HOST byte order.");
657             }
658         }
659     }
660
661     int record_length = 0; // Only used for binary protocols.
662     vector<SGPropertyNode_ptr> chunks = root->getChildren("chunk");
663     for (unsigned int i = 0; i < chunks.size(); i++) {
664
665         _serial_prot chunk;
666
667         // chunk.name = chunks[i]->getStringValue("name");
668         chunk.format = fgUnescape(chunks[i]->getStringValue("format", "%d"));
669         chunk.offset = chunks[i]->getDoubleValue("offset");
670         chunk.factor = chunks[i]->getDoubleValue("factor", 1.0);
671         chunk.min = chunks[i]->getDoubleValue("min");
672         chunk.max = chunks[i]->getDoubleValue("max");
673         chunk.wrap = chunks[i]->getBoolValue("wrap");
674         chunk.rel = chunks[i]->getBoolValue("relative");
675
676         string node = chunks[i]->getStringValue("node", "/null");
677         chunk.prop = fgGetNode(node.c_str(), true);
678
679         string type = chunks[i]->getStringValue("type");
680
681         // Note: officially the type is called 'bool' but for backward
682         //       compatibility 'boolean' will also be supported.
683         if (type == "bool" || type == "boolean") {
684             chunk.type = FG_BOOL;
685             record_length += 1;
686         } else if (type == "float") {
687             chunk.type = FG_FLOAT;
688             record_length += sizeof(int32_t);
689         } else if (type == "double") {
690             chunk.type = FG_DOUBLE;
691             record_length += sizeof(int64_t);
692         } else if (type == "fixed") {
693             chunk.type = FG_FIXED;
694             record_length += sizeof(int32_t);
695         } else if (type == "string")
696             chunk.type = FG_STRING;
697         else {
698             chunk.type = FG_INT;
699             record_length += sizeof(int32_t);
700         }
701         msg.push_back(chunk);
702
703     }
704
705     if( binary_mode ) {
706         if (binary_record_length == -1) {
707             binary_record_length = record_length;
708         } else if (binary_record_length < record_length) {
709             SG_LOG(SG_IO, SG_ALERT,
710                    "generic protocol: Requested binary record length shorter than "
711                    " requested record representation.");
712             binary_record_length = record_length;
713         }
714     }
715 }
716
717 void FGGeneric::updateValue(FGGeneric::_serial_prot& prot, bool val)
718 {
719   if( prot.rel )
720   {
721     // value inverted if received true, otherwise leave unchanged
722     if( val )
723       setValue(prot.prop, !getValue<bool>(prot.prop));
724   }
725   else
726   {
727     setValue(prot.prop, val);
728   }
729 }