forked from IBM-Cloud/python-iot-raspberry-pi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
75 lines (60 loc) · 2.15 KB
/
server.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
from flask import Flask,redirect
from flask import render_template
from flask import request
import os, json
import time
import ibmiotf.application
from twilio.rest import TwilioRestClient
vcap = json.loads(os.getenv("VCAP_SERVICES"))
twilioAccount = vcap["user-provided"][0]["credentials"]["accountSID"]
twilioToken = vcap["user-provided"][0]["credentials"]["authToken"]
twilioClient = TwilioRestClient(twilioAccount, twilioToken)
client = None
phoneNumberTo = ""
textMessage = "Button Pushed"
phoneNumberFrom = os.getenv("PHONE_NUMBER_FROM")
deviceId = os.getenv("DEVICE_ID")
def myCommandCallback(cmd):
global phoneNumberTo
global textMessage
buttonPushed = cmd.payload["d"]["buttonPushed"]
message = twilioClient.messages.create(to=phoneNumberTo, from_=phoneNumberFrom, body=textMessage)
print buttonPushed
try:
options = {
"org": vcap["iotf-service"][0]["credentials"]["org"],
"id": vcap["iotf-service"][0]["credentials"]["iotCredentialsIdentifier"],
"auth-method": "apikey",
"auth-key": vcap["iotf-service"][0]["credentials"]["apiKey"],
"auth-token": vcap["iotf-service"][0]["credentials"]["apiToken"]
}
client = ibmiotf.application.Client(options)
client.connect()
client.deviceEventCallback = myCommandCallback
client.subscribeToDeviceEvents(event="input")
except ibmiotf.ConnectionException as e:
print e
app = Flask(__name__)
if os.getenv("VCAP_APP_PORT"):
port = int(os.getenv("VCAP_APP_PORT"))
else:
port = 8080
@app.route('/')
def hello():
return render_template('index.html')
@app.route('/light/<command>', methods=['GET', 'POST'])
def light_route(command):
print command
myData = {'command' : command}
client.publishEvent("raspberrypi", deviceId, "light", "json", myData)
return redirect("/", code=302)
@app.route('/phoneNumber', methods=['POST'])
def phone_number_route():
global phoneNumberTo
global textMessage
phoneNumber = request.form['phoneNumber']
textMessage = request.form['message']
phoneNumberTo = "+1" + phoneNumber
return redirect("/", code=302)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=port)