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