2 # -*- coding: iso-8859-15 -*-
8 def set_keepalive(sock, after_idle_sec=1, interval_sec=3, max_fails=5):
9 """Set TCP keepalive on an open socket.
11 It activates after 1 second (after_idle_sec) of idleness,
12 then sends a keepalive ping once every 3 seconds (interval_sec),
13 and closes the connection after 5 failed ping (max_fails), or 15 seconds
15 sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
16 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, after_idle_sec)
17 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval_sec)
18 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, max_fails)
19 if not hasattr(socket, "set_keepalive"):
20 socket.set_keepalive = set_keepalive
23 def __init__(self, addr = ("panda", 10002)):
24 self.pSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
25 self.pSocket.settimeout(1)
26 socket.set_keepalive(self.pSocket)
27 self.pSocket.connect(addr)
31 data = {'command': cmd}
32 num = self.pSocket.sendall(json.dumps(data))
34 msg = json.loads(self.pSocket.recv(4096))
35 if msg.has_key("return"): return msg["return"]
36 elif msg.has_key("error"): return msg["error"]
37 self.lMsgs.insert(0, msg)
40 if len(self.lMsgs) > 0:
41 return self.lMsgs.pop()
42 self.pSocket.setblocking(False)
44 return json.loads(self.pSocket.recv(4096))
48 self.pSocket.setblocking(True)
50 if __name__ == "__main__":
51 print JsonClient().write(sys.argv[1])
53 #from datetime import datetime
54 #from time import sleep
55 #pClient = JsonClient()
57 # msg = pClient.read()
59 # print "Got async", msg
60 # print datetime.now(), float(pClient.write("get distance forward lower"))