-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
63 lines (50 loc) · 2.66 KB
/
main.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
import json
import requests
import datetime
import time
import subprocess
from requests.exceptions import RequestException
from parse_rest.connection import register
from parse_rest.datatypes import Object
from parse_rest.datatypes import ACL
from HeadCount import HeadCount
# from xml.etree import ElementTree
import config
# Parse initialization
register(config.APPLICATION_ID, config.REST_API_KEY, master_key=config.MASTER_KEY)
ip = config.router['ip']
try:
# Router login
payload = config.router
loginReq = requests.post('http://%s/cgi-bin/login' % ip, data=payload)
# Router Wi-Fi devices request
headers = {'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
formdata = '<xmlrequest version="1.0.1"><command inst="cfgmgr-0"><key>begin_transaction</key><value>wireless-0</value></command><command inst="cfgmgr-0"><key>begin_transaction</key><value>wireless-1</value></command><query inst="wireless-0"><key>ap0_sta_list</key><value/></query><query inst="wireless-0"><key>ap1_sta_list</key><value/></query><query inst="wireless-0"><key>ap2_sta_list</key><value/></query><query inst="wireless-0"><key>ap3_sta_list</key><value/></query><query inst="wireless-1"><key>ap0_sta_list</key><value/></query><query inst="wireless-1"><key>ap1_sta_list</key><value/></query><query inst="wireless-1"><key>ap2_sta_list</key><value/></query><query inst="wireless-1"><key>ap3_sta_list</key><value/></query><command inst="cfgmgr-0"><key>commit</key><value>wireless-0</value></command><command inst="cfgmgr-0"><key>commit</key><value>wireless-1</value></command><command inst="cfgmgr-0"><key>end_transaction</key><value>wireless-0</value></command><command inst="cfgmgr-0"><key>end_transaction</key><value>wireless-1</value></command></xmlrequest>'
r = requests.post('http://%s/cgi-bin/webapp' % ip, data=formdata, cookies=loginReq.cookies)
# XML Parse
# tree = ElementTree.fromstring(r.content)
count = r.text.count(".mac")
if count > 0:
message = "Open! %d device(s) connected." % count
else:
message = "Closed!"
except RequestException:
count = -1
message = "Status Unknown!"
lastHeadCount = HeadCount.Query.all().order_by('-updatedAt').limit(1)
if lastHeadCount[0].count != count:
headCount = HeadCount()
headCount.ACL = ACL()
headCount.count = count
headCount.save()
else:
headCount = lastHeadCount[0]
state = {
'state': {
'open': None if count < 0 else count > 0,
'lastchange': int(time.mktime(headCount.updatedAt.timetuple())),
'headcount': count,
'message': message
}
}
print json.dumps(state, indent=4)