]> defiant.homedns.org Git - arm_ros_conn.git/blob - scripts/json_client.py
-added arm_ros_conn
[arm_ros_conn.git] / scripts / json_client.py
1 #!/usr/bin/env python
2 # -*- coding: iso-8859-15 -*-
3
4 import sys
5 import socket
6 import json
7
8 def set_keepalive(sock, after_idle_sec=1, interval_sec=3, max_fails=5):
9         """Set TCP keepalive on an open socket.
10
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
14         """
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
21
22 class JsonClient:
23         def __init__(self, addr = ("arm", 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)
28                 self.lMsgs = []
29
30         def write(self, cmd):
31                 data = {'command': cmd}
32                 num = self.pSocket.sendall(json.dumps(data))
33                 while True:
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)
38
39         def read(self):
40                 if len(self.lMsgs) > 0:
41                         return self.lMsgs.pop()
42                 self.pSocket.setblocking(False)
43                 try:
44                         return json.loads(self.pSocket.recv(4096))
45                 except socket.error:
46                         pass
47                 finally:
48                         self.pSocket.setblocking(True)
49
50 if __name__ == "__main__":
51         print JsonClient().write(sys.argv[1])
52
53         #from datetime import datetime
54         #from time import sleep
55         #pClient = JsonClient()
56         #while True:
57         #       msg = pClient.read()
58         #       if msg:
59         #               print "Got async", msg
60         #       print datetime.now(), float(pClient.write("get distance forward lower"))
61         #       sleep(0.1)