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