Debian Codegraph @

scripts/python/FlightGear.py

raw symbols SCIP
1 from telnetlib import Telnet
2 import sys
3 import socket
4 import re
5 import time
6
7 __all__ = ["FlightGear"]
8
9 CRLF = '\r\n'
10
11 class FGTelnet(Telnet):
12 def __init__(self,host,port):
13 Telnet.__init__(self,host,port)
14 self.prompt = [re.compile('/[^>]*> '.encode('utf-8'))]
15 self.timeout = 5
16 #Telnet.set_debuglevel(self,2)
17
18 def help(self):
19 return
20
21 def ls(self,dir=None):
22 """
23 Returns a list of properties.
24 """
25 if dir is None:
26 self._putcmd('ls')
27 else:
28 self._putcmd('ls %s' % dir )
29 return self._getresp()
30
31 def ls2(self, dir_):
32 self._putcmd(f'ls2 {dir_}')
33 return self._getresp()
34
35 def dump(self):
36 """Dump current state as XML."""
37 self._putcmd('dump')
38 return self._getresp()
39
40 def cd(self, dir):
41 """Change directory."""
42 self._putcmd('cd ' + dir)
43 self._getresp()
44 return
45
46 def pwd(self):
47 """Display current path."""
48 self._putcmd('pwd')
49 return self._getresp()
50
51 def get(self,var):
52 """Retrieve the value of a parameter."""
53 self._putcmd('get %s' % var )
54 return self._getresp()
55
56 def set(self,var,value):
57 """Set variable to a new value"""
58 self._putcmd('set %s %s' % (var,value))
59 self._getresp() # Discard response
60
61 def quit(self):
62 """Terminate connection"""
63 self._putcmd('quit')
64 self.close()
65 return
66
67 # Internal: send one command to FlightGear
68 def _putcmd(self,cmd):
69 cmd = cmd + CRLF
70 Telnet.write(self, cmd.encode('utf-8'))
71 return
72
73 def _getresp(self):
74 # Telnet.expect() can return short result, so we call it in a loop.
75 response = b''
76 while 1:
77 _i, _match, data = Telnet.expect(self, self.prompt, self.timeout)
78 response += data
79 if _i == 0:
80 break # We have the prompt that marks the end of the data.
81 assert _i == -1, f'i={i}'
82 # Remove the terminating prompt.
83 # Everything preceding it is the response.
84 return response.decode('utf-8').split('\n')[:-1]
85
86 class LsItem:
87 def __init__(self, num_children, name, index, type_, value_text):
88 self.num_children = num_children
89 self.name = name
90 self.index = index
91 self.type_ = type_
92 self.value_text = value_text
93 # Convert to correct type; type_ is originally from
94 # flightgear/src/Network/props.cxx:getValueTypeString().
95 #
96 if type_ in ('unknown', 'unspecified', 'none'):
97 value = value_text
98 elif type_ == 'bool':
99 value = (value_text == 'true')
100 elif type_ in ('int', 'long'):
101 value = int(value_text)
102 elif type_ in ('float', 'double'):
103 self.value = float(value_text)
104 elif type_ == 'string':
105 self.value = value_text
106 else:
107 assert 0, f'Unrecognised type: {type_}'
108
109 def __str__(self):
110 return f'num_children={self.num_children} name={self.name}[{self.index}] type={self.type_}: {self.value!r}'
111
112 class FlightGear:
113 """FlightGear interface class.
114
115 An instance of this class represents a connection to a FlightGear telnet
116 server.
117
118 Properties are accessed using a dictionary style interface:
119 For example:
120
121 # Connect to flightgear telnet server.
122 fg = FlightGear('myhost', 5500)
123 # parking brake on
124 fg['/controls/gear/brake-parking'] = 1
125 # Get current heading
126 heading = fg['/orientation/heading-deg']
127
128 Other non-property related methods
129 """
130
131 def __init__( self, host = 'localhost', port = 5500 ):
132 try:
133 self.telnet = FGTelnet(host,port)
134 except socket.error as msg:
135 self.telnet = None
136 raise msg
137
138 def __del__(self):
139 # Ensure telnet connection is closed cleanly.
140 self.quit()
141
142 def __getitem__(self,key):
143 """Get a FlightGear property value.
144 Where possible the value is converted to the equivalent Python type.
145 """
146 s = self.telnet.get(key)[0]
147 match = re.compile( r'[^=]*=\s*\'([^\']*)\'\s*([^\r]*)\r').match( s )
148 if not match:
149 return None
150 value,type = match.groups()
151 #value = match.group(1)
152 #type = match.group(2)
153 if value == '':
154 return None
155
156 if type == '(double)':
157 return float(value)
158 elif type == '(int)':
159 return int(value)
160 elif type == '(bool)':
161 if value == 'true':
162 return 1
163 else:
164 return 0
165 else:
166 return value
167
168 def __setitem__(self, key, value):
169 """Set a FlightGear property value."""
170 if value is True:
171 # Flightgear props doesn't treat string 'True' as true - see
172 # SGPropertyNode::setStringValue().
173 value = 'true'
174 self.telnet.set( key, value )
175
176 def ls(self, dir_):
177 '''
178 Returns list of LsItem's.
179 '''
180 lines = self.telnet.ls2(dir_)
181 ret = []
182 for line in lines:
183 if line.endswith('\r'):
184 line = line[:-1]
185 #print(f'line={line!r}')
186 try:
187 num_children, name, index, type_, value = line.split(' ', 4)
188 except Exception as e:
189 print(f'*** dir_={dir_!r} len(lines)={len(lines)}. failed to read items from line={line!r}. lines is: {lines!r}')
190 raise
191 index = int(index)
192 num_children = int(num_children)
193 item = LsItem(num_children, name, index, type_, value)
194 #print(f'item={item}')
195 ret.append( item)
196 return ret
197
198 def quit(self):
199 """Close the telnet connection to FlightGear."""
200 if self.telnet:
201 self.telnet.quit()
202 self.telnet = None
203
204 def view_next(self):
205 """Move to next view."""
206 self.telnet.set( "/command/view/next", "true")
207
208 def view_prev(self):
209 """Move to next view."""
210 self.telnet.set( "/command/view/prev", "true")
211