-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.py
95 lines (72 loc) · 2.72 KB
/
app.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
from flask import Flask, jsonify, render_template, request
from wakeonlan import send_magic_packet
from ping3 import ping
from configparser import ConfigParser
app = Flask(__name__)
config = ConfigParser()
# helper function
def reverse_mac(mac):
"""Reverses a MAC address and formats it with hyphens between each pair of characters."""
mac = mac.replace(':', '').replace('-', '')
mac_pairs = [mac[i:i+2] for i in range(0, len(mac), 2)]
reversed_mac = '-'.join(reversed(mac_pairs))
return reversed_mac.upper()
# Index route
@app.route('/')
def index():
config.read('config.ini')
DEFAULT_HOST = config['DEFAULTS']['DEFAULT_HOST']
DEFAULT_MAC = config['DEFAULTS']['DEFAULT_MAC']
DEFAULT_DESTINATION = config['DEFAULTS']['DEFAULT_DESTINATION']
return render_template('index.jinja',
app=app,
default_host=DEFAULT_HOST,
default_mac=DEFAULT_MAC,
default_destination=DEFAULT_DESTINATION)
# Saving route
@app.route('/save', methods=['POST'])
def save():
DEFAULT_HOST = request.form['hostIP']
DEFAULT_MAC = request.form['mac-address']
DEFAULT_DESTINATION = request.form['destination']
config['DEFAULTS'] = {
'DEFAULT_HOST': DEFAULT_HOST,
'DEFAULT_MAC': DEFAULT_MAC,
'DEFAULT_DESTINATION': DEFAULT_DESTINATION
}
with open('config.ini', 'w') as configfile:
config.write(configfile)
# Note that flask will still have cached the .ini file,
# so future gets to '/' will be reading from memory until the container restarts.
# Return a simple JSON response with a 200 status code
return jsonify({'message': 'Config saved successfully'}), 200
# API endpoints
@app.route('/api/wol/<mac>', methods=['GET'])
def wol(mac):
try:
send_magic_packet(mac)
return jsonify({'result': True})
except Exception as e:
return jsonify({'result': False, 'error': str(e)})
@app.route('/api/sol/<mac>', methods=['GET'])
def sol(mac):
try:
cam = reverse_mac(mac)
send_magic_packet(cam)
return jsonify({'result': True})
except Exception as e:
return jsonify({'result': False, 'error': str(e)})
@app.route('/api/state/ip/<ip>', methods=['GET'])
def state(ip):
try:
response_time = ping(ip, timeout=2)
if response_time is False:
return jsonify({'status': 'unknown'})
if response_time is not None:
return jsonify({'status': 'awake'})
else:
return jsonify({'status': 'asleep'})
except ping.PingError as e:
return jsonify({'status': 'unknown', 'error': str(e)})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=9008)