-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
68 lines (61 loc) · 2.4 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
from requests.exceptions import HTTPError
from flask import Flask, jsonify
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
import TbApi
from dotenv import load_dotenv
import os
import base64
import auto_mail_handeler
import socket
load_dotenv('.env')
email = os.environ.get("tb_email_login")
password = base64.b64decode(os.environ.get("tb_email_login_password")).decode("utf-8")
app = Flask(__name__)
limiter = Limiter(
app,
key_func=get_remote_address,
default_limits=["200 per day", "50 per hour"])
tbapi_url = "https://demo.thingsboard.io:443"
tbapi = TbApi.TbApi(tbapi_url, email, password)
@app.route("/deviceName/<string:deviceName>")
@limiter.limit("3 per minute")
def newDevice(deviceName):
try:
auto_mail_handeler.setTimeVerification()
auto_mail_handeler.send_email_notification("Device "+deviceName+" wants to connect to your server.\nSend an email with subject 'accept "+deviceName+"' to add device.\nYou have 8 minutes to sent appruval")
auto_mail_handeler.mailLookUp()
message = auto_mail_handeler.message
print(message)#debugging
verification_str = str("accept "+deviceName)
print(verification_str)#debugging
if message == False:
return jsonify({"error": "No new mail"})
else:
if message == verification_str:
try:
tbapi.add_device(device_name=deviceName, device_type=None, shared_attributes=None, server_attributes=None)
except:
return jsonify({"error": "Device already exists"}),400
token = tbapi.get_device_token(tbapi.get_devices_by_name(deviceName))
return jsonify({ "token": token }), 200
else:
return jsonify({"error": "Device denied"}), 469
except HTTPError as error:
response = error.response.json()
return jsonify({ "error": response["message"] }), 400
if __name__ == '__main__':
def get_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(0)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP
print("Server started on:",get_ip())
app.run(debug=True,host = get_ip(), port=5000)