-
Notifications
You must be signed in to change notification settings - Fork 45
/
device_gateway.py
executable file
·43 lines (39 loc) · 1.3 KB
/
device_gateway.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env python
from gevent.server import StreamServer
import config
import sys
import time
from models import GPSDevice
from logger import logger
def handle(sock, (clientip, clientport)):
logger.info('New connection from %s:%s' % (clientip, clientport))
device = None
while True:
data = sock.recv(config.DEVICE_GATEWAY_RECV_SIZE)
if not data:
break
logger.info('%s > %s' % (clientip, data[:256]))
if not device:
try:
device = GPSDevice.get_by_data(data, ipaddr=clientip)
except Exception, e:
logger.warning(e.message[:256])
time.sleep(10)
sock.close()
return
device.sent(data)
resp = device.pop_response()
while resp:
sock.send(resp)
logger.info('%s < %s' % (clientip, resp[:256]))
resp = device.pop_response()
if __name__ == '__main__':
server = StreamServer(
(config.DEVICE_GATEWAY_HOST_LISTEN, config.DEVICE_GATEWAY_PORT_LISTEN),
handle,
spawn=config.DEVICE_GATEWAY_MAX_CONNECTIONS
)
msg = 'Device Gateway listening on %s:%s' % (config.DEVICE_GATEWAY_HOST_LISTEN, config.DEVICE_GATEWAY_PORT_LISTEN)
print msg
logger.info(msg)
server.serve_forever()