-
Notifications
You must be signed in to change notification settings - Fork 0
/
t2m.py
101 lines (78 loc) · 2.06 KB
/
t2m.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#! /usr/bin/env python
# Requires python 2.7
import sys
import socket
import datetime
import json
import logging
import os
if os.path.exists('/vagrant'):
logfilename = '/vagrant/.t2m.log'
else:
logfilename = '/tmp/.t2m.log'
logging.basicConfig(
filename=logfilename,
level=logging.DEBUG)
BUFSIZE = 1024
DEBUG = True
def main():
if len(sys.argv) < 2:
usage()
server()
try:
server()
except Exception, e:
logging.critical("server() exited with exception %s" % str(e))
def usage():
sys.stdout = sys.stderr
print('Usage: %s listen_ip udp_port' % sys.argv[0])
sys.exit(2)
def debug(msg):
if DEBUG: logging.debug(msg)
def s_to_datetime(dts):
try:
dtobj = datetime.datetime.strptime(dts, "%d/%m/%Y %H:%M")
return dtobj
except ValueError:
return False
def parse_data(data):
"""
Quick n dirty data parsing.
string -> datetime, string
"""
dtobj = None
msg = None
if ']' in data:
try:
dts, msg = data.split(']')
dts = dts.strip('[')
if msg and msg[0] == ' ':
msg = msg[1:]
dtobj = s_to_datetime(dts)
except ValueError:
pass
return dtobj, msg
def server():
if len(sys.argv) > 2:
host = sys.argv[1]
port = eval(sys.argv[2])
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
debug('udp server ready on %s:%s' % (host,port))
while 1:
data, addr = s.recvfrom(BUFSIZE)
debug('server received %r from %r' % (data, addr))
dt, msg = parse_data(data)
if dt and msg:
#send data back
datadict = {
"timestamp": int( (dt - datetime.datetime(1970,1,1)).total_seconds() ),
"message": msg
}
jsondata = json.dumps(datadict)
debug(jsondata)
print(jsondata)
s.sendto(jsondata, addr)
else:
debug('invalid message received.')
if __name__ == '__main__': main()