1 from telnetlib import Telnet
5 from string import split, join
8 __all__ = ["FlightGear"]
12 class FGTelnet(Telnet):
13 def __init__(self,host,port):
14 Telnet.__init__(self,host,port)
16 self.prompt.append( re.compile('/[^>]*> ') )
18 #Telnet.set_debuglevel(self,2)
23 def ls(self,dir=None):
25 Returns a list of properties.
30 self._putcmd('ls %s' % dir )
31 return self._getresp()
34 """Dump current state as XML."""
36 return self._getresp()
39 """Change directory."""
40 self._putcmd('cd ' + dir)
45 """Display current path."""
47 return self._getresp()
50 """Retrieve the value of a parameter."""
51 self._putcmd('get %s' % var )
52 return self._getresp()
54 def set(self,var,value):
55 """Set variable to a new value"""
56 self._putcmd('set %s %s' % (var,value))
57 self._getresp() # Discard response
60 """Terminate connection"""
65 # Internal: send one command to FlightGear
66 def _putcmd(self,cmd):
68 Telnet.write(self, cmd)
71 # Internal: get a response from FlightGear
73 (i,match,resp) = Telnet.expect(self, self.prompt, self.timeout)
74 # Remove the terminating prompt.
75 # Everything preceding it is the response.
76 return split(resp, '\n')[:-1]
79 """FlightGear interface class.
81 An instance of this class represents a connection to a FlightGear telnet
84 Properties are accessed using a dictionary style interface:
87 # Connect to flightgear telnet server.
88 fg = FlightGear('myhost', 5500)
90 fg['/controls/parking-brake'] = 1
92 heading = fg['/orientation/heading-deg']
94 Other non-property related methods
97 def __init__( self, host = 'localhost', port = 5500 ):
99 self.telnet = FGTelnet(host,port)
100 except socket.error, msg:
102 raise socket.error, msg
105 # Ensure telnet connection is closed cleanly.
108 def __getitem__(self,key):
109 """Get a FlightGear property value.
110 Where possible the value is converted to the equivalent Python type.
112 s = self.telnet.get(key)[0]
113 (name,x,value,type) = s.split()
117 value = value[1:-1] # strip quote characters
118 #print "name=%s,value=%s,type=%s" % (name,value,type)
119 if type == '(double)':
121 elif type == '(int)':
123 elif type == '(bool)':
131 def __setitem__(self, key, value):
132 """Set a FlightGear property value.
134 self.telnet.set( key, value )
137 """Close the telnet connection to FlightGear.
146 self.telnet._putcmd('view next')
147 self.telnet._getresp()
152 self.telnet._putcmd('view prev')
153 self.telnet._getresp()
155 def wait_for_prop_eq(self, prop, value, interval = 0.5):
156 while self.__getitem__(prop) != value: