This example presents field data from sensor BME280 connecting to cloud, mbed Device Connector.

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers app.py Source File

app.py

00001 import mbed_connector_api             # mbed Device Connector library
00002 import pybars                         # use to fill in handlebar templates
00003 from   flask          import Flask    # framework for hosting webpages
00004 from   flask_socketio import SocketIO
00005 from   flask_socketio import emit
00006 from   flask_socketio import send
00007 from   flask_socketio import join_room
00008 from   flask_socketio import leave_room
00009 from   base64         import standard_b64decode as b64decode
00010 import os
00011 
00012 app = Flask(__name__)
00013 socketio = SocketIO(app,async_mode='threading')
00014 
00015 if 'ACCESS_KEY' in os.environ.keys():
00016     token = os.environ['ACCESS_KEY'] # get access key from environment variable
00017 else:
00018     token = "ChangeMe" # replace with your API token
00019 
00020 connector = mbed_connector_api.connector(token)
00021 
00022 @app.route('/')
00023 def index():
00024     # get list of endpoints, for each endpoint get resources
00025     epList = connector.getEndpoints().result
00026     for index in range(len(epList)):
00027         print "Endpoint Found: ",epList[index]['name']
00028         print "epList[index]", epList[index]
00029         print "end", index
00030         e_h = connector.getResourceValue(epList[index]['name'],"/3304/0/5700")
00031         e_t = connector.getResourceValue(epList[index]['name'],"/3303/0/5700")
00032         e_p = connector.getResourceValue(epList[index]['name'],"/3323/0/5700")
00033         while not e_p.isDone() or not e_t.isDone or not e_h.isDone :
00034             None
00035         epList[index]['humidity_value'] = e_h.result
00036         epList[index]['tempereture_value'] = e_t.result
00037         epList[index]['pressure_value'] = e_p.result
00038     
00039     print "Endpoint List :",epList
00040     # fill out html using handlebar template
00041     handlebarJSON = {'endpoints':epList}
00042     comp = pybars.Compiler()
00043     tmp_src = open("./views/index.hbs",'r').read()
00044     source = unicode(tmp_src, "utf-8")
00045     template = comp.compile(source)
00046     return "".join(template(handlebarJSON))
00047 
00048 @socketio.on('connect')
00049 def connect():
00050     print('Connect')
00051     join_room('room')
00052 
00053 @socketio.on('disconnect')
00054 def disconnect():
00055     print('Disconnect')
00056     leave_room('room')
00057 
00058 @socketio.on('subscribe_to_presses')
00059 def subscribeToPresses(data):
00060     print('subscribe_to_presses: ',data)
00061     # Subscribe to all changes of resources
00062     e_h = connector.putResourceSubscription(data['endpointName'],'/3304/0/5700')
00063     e_t = connector.putResourceSubscription(data['endpointName'],'/3303/0/5700')
00064     e_p = connector.putResourceSubscription(data['endpointName'],'/3323/0/5700')
00065     while not e_h.isDone() or not e_t.isDone() or not e_p.isDone():
00066         None
00067     if e_h.error:
00068         print("Error e_h 21: ",e_h.error.errType, e_h.error.error, e.raw_data)
00069     elif e_t.error:
00070         print("Error e_t 21: ",e_t.error.errType, e_t.error.error, e_t.raw_data)
00071     elif e_p.error:
00072         print("Error e_p 21: ",e_p.error.errType, e_p.error.error, e_p.raw_data)
00073     else:
00074         print("Subscribed Successfully!")
00075         emit('subscribed-to-presses')
00076 
00077 @socketio.on('unsubscribe_to_presses')
00078 def unsubscribeToPresses(data):
00079     print('unsubscribe_to_presses: ',data)
00080     e_h = connector.deleteResourceSubscription(data['endpointName'],'/3304/0/5700')
00081     e_t = connector.deleteResourceSubscription(data['endpointName'],'/3303/0/5700')
00082     e_p = connector.deleteResourceSubscription(data['endpointName'],'/3323/0/5700')
00083     while not e_h.isDone() or not e_t.isDone() or not e_p.isDone():
00084         None
00085     if e_h.error:
00086         print("Error e_h 22: ",e_h.error.errType, e_h.error.error, e.raw_data)
00087     elif e_t.error:
00088         print("Error e_t 22: ",e_t.error.errType, e_t.error.error, e_t.raw_data)
00089     elif e_p.error:
00090         print("Error e_p 22: ",e_p.error.errType, e_p.error.error, e_p.raw_data)
00091     else:
00092         print("Unsubscribed Successfully!")
00093     emit('unsubscribed-to-presses',{"endpointName":data['endpointName'],"value":'True'})
00094 
00095 @socketio.on('get_presses')
00096 def getPresses(data):
00097     # Read data from GET resources
00098     e_h = connector.getResourceValue(data['endpointName'],"/3304/0/5700")
00099     e_t = connector.getResourceValue(data['endpointName'],"/3303/0/5700")
00100     e_p = connector.getResourceValue(data['endpointName'],"/3323/0/5700")
00101     while not e_p.isDone() or not e_t.isDone or not e_h.isDone :
00102         None
00103     if e_h.error :
00104         print("Error e_h: ",e_h.error.errType, e_h.error.error, e_h.raw_data)
00105     elif e_t.error :
00106         print("Error e_t: ",e_t.error.errType, e_t.error.error, e_t.raw_data)
00107     elif e_p.error :
00108         print("Error e_p: ",e_p.error.errType, e_p.error.error, e_p.raw_data)
00109     else:
00110         dataT_to_emit = {"endpointName":'multiple_data', "value":"e_t="+e_t.result+";e_h="+e_h.result+";e_p="+e_p.result}
00111         emit('SetTemp', dataT_to_emit)
00112 
00113 
00114 # 'notifications' are routed here, handle subscriptions and update webpage
00115 def notificationHandler(data):
00116     global socketio
00117     print "\r\nNotification Data Received : %s" %data['notifications']
00118     notifications = data['notifications']
00119     tmp=""
00120     for thing in notifications:
00121         if  thing["path"]=="/3304/0/5700":
00122             tmp +="e_h="+b64decode(thing["payload"])+";"
00123         elif thing["path"]=="/3303/0/5700":
00124             tmp +="e_t="+b64decode(thing["payload"])+";"
00125         elif thing["path"]=="/3323/0/5700":
00126             tmp +="e_p="+b64decode(thing["payload"])+";"
00127     
00128     stuff = {"endpointName":thing["ep"],"value":tmp+"end"}
00129     print ("990 Emitting :",stuff)
00130     socketio.emit('SetTemp',stuff)
00131 
00132 if __name__ == "__main__":
00133     # remove all subscriptions, start fresh
00134     connector.deleteAllSubscriptions()
00135     # start long polling connector.mbed.com
00136     connector.startLongPolling()
00137     # send 'notifications' to the notificationHandler FN
00138     connector.setHandler('notifications', notificationHandler)
00139     socketio.run(app,host='0.0.0.0', port=8080)