def submit(self):
     new_password = self.ids['new_password'].text
     old_password = self.ids['old_password'].text
     confirm = self.ids['confirm'].text
     password = firebase.get('/users/' +
                             self.manager.get_screen('profile').user +
                             '/password')
     if old_password == password:
         if len(new_password) > 7:
             if new_password == confirm:
                 firebase.put(
                     '/', '/users/' +
                     self.manager.get_screen('profile').user + '/password',
                     new_password)
                 self.ids['new_password'].text = ""
                 self.ids['old_password'].text = ""
                 self.ids['confirm'].text = ""
                 self.ids['status'].text = "Password updated!"
             else:
                 self.ids['status'].text = "New password mismatched!"
         else:
             self.ids['status'].text = "New password too short!"
             print len(new_password)
     else:
         self.ids['status'].text = "Incorrect password!"
 def sign_me_up(self):
     entered_username = self.ids['username'].text.strip()
     entered_email = self.ids['email'].text.strip()
     entered_password = self.ids['password'].text.strip()
     confirm_password = self.ids['password_confirm'].text.strip()
     if " " in entered_username or "	" in entered_username:
         self.ids['status'].text = 'Username invalid! Cannot have spaces'
     elif entered_username in firebase.get('/users'):
         self.ids['status'].text = 'Username Taken!'
     elif self.email_availability(entered_email) == False:
         self.ids['status'].text = 'Email has already been signed up!'
     elif len(entered_password) < 7:
         self.ids['status'].text = "Password too short!"
     elif entered_password != confirm_password:
         self.ids['status'].text = 'Password mismatched!'
     else:
         user = {
             'dispensers': ['None'],
             'email': entered_email,
             'password': entered_password,
             'pic_url': 'http://i.imgur.com/VMtRJHG.jpg',
             'badges': ['None']
         }
         firebase.put('/', '/users/' + entered_username, user)
         self.ids['sign_up'].clear_widgets()
         self.ids['sign_up'].add_widget(Label(text="Sign Up Successful!"))
         self.ids['sign_up'].add_widget(
             Label(text="Start contributing to a better world for cats!"))
         self.ids['sign_up'].add_widget(
             Button(text='Go to your profile',
                    color=(0, 0, 0, 1),
                    background_normal='./assets/buttons/long_button.png',
                    background_down='./assets/buttons/long_button_down.png',
                    on_press=self.transfer_data))
Пример #3
0
def delUsers(studentid=None):  #deletes users
    if studentid == None:  #if no user inpit, deletes all users
        firebase.put('/Accounts/', '', None)
    elif type(studentid) is not list:  #converts input to list if not list
        studentid = [studentid]
    for student in studentid:  #deletes all users in list
        firebase.put('/Accounts/', str(student), None)
Пример #4
0
def firebase_edit_user(userid,name,password,email):
    url = URL_ROOT + "/users/%s" %(userid)
    dict_user = {}
    dict_user["name"] = name
    dict_user["password"] = password
    dict_user["email"] = email

    firebase.put(url,dict_user)
    print "edit_user with userid:%s,username:%s, password:%s, email:%s" %(userid,name,password,email)
Пример #5
0
def firebase_delete_device(userid, devicename):
    url = URL_ROOT + "/devices/%s" %(userid)

    dict_devices = firebase_get_device_dict(userid)
    print "delete_device(before)dict_devices:%s, devicename:%s " %( dict_devices, devicename)
    result = dict_devices.pop(devicename, None)
    print "delete_device(after) dict_devices:%s, devicename:%s " %( dict_devices, devicename)
    firebase.put(url,dict_devices)
    print "deleted_device with userid:%s,devicename:%s, result:%s" %(userid,devicename,result)
Пример #6
0
def firebase_edit_user(userid, name, password, email):
    url = URL_ROOT + "/users/%s" % (userid)
    dict_user = {}
    dict_user["name"] = name
    dict_user["password"] = password
    dict_user["email"] = email

    firebase.put(url, dict_user)
    print "edit_user with userid:%s,username:%s, password:%s, email:%s" % (
        userid, name, password, email)
Пример #7
0
def firebase_delete_user(userid):
    url = URL_ROOT + "/users/%s" % userid
   # print "firebase_delete_user, url:", url
    dict_users = firebase_get_users_dict()
    result = dict_users.pop(userid, None)
   # print "--------------------- delete_user(after) userid:%s,\n dict_users:%s" %( userid, dict_users)
    firebase.put(URL_ROOT + "/users",dict_users)
        #2nd way but not stable
    #firebase.put(url,None)
    print "firebase_delete_user: done"
Пример #8
0
def firebase_delete_user(userid):
    url = URL_ROOT + "/users/%s" % userid
    # print "firebase_delete_user, url:", url
    dict_users = firebase_get_users_dict()
    result = dict_users.pop(userid, None)
    # print "--------------------- delete_user(after) userid:%s,\n dict_users:%s" %( userid, dict_users)
    firebase.put(URL_ROOT + "/users", dict_users)
    #2nd way but not stable
    #firebase.put(url,None)
    print "firebase_delete_user: done"
def FirebaseSendData(predict_set):
    ## Add data to firebase
    epoch_time_now = calendar.timegm(time.gmtime())
    for i, val in predict_set.items():
        conv_val = np.asscalar(val)
        respond = firebase.put("/car-park-snapshots/swu/park0/p" + str(i),
                               "val", conv_val)
        history_respond = firebase.put(
            "/car-park-snapshots-history/swu/park0/p" + str(i) + "/" +
            str(epoch_time_now), "val", conv_val)
Пример #10
0
def firebase_turn_off_all(userid):
    #get all the devices from the user, and set it to 0
    list_devices = firebase_get_device_list(userid)
    if len(list_devices) == 0:
        print "no device to update off all"
    else:
        dict_devices_off = get_dict_with_value(list_devices,0)
        print "dict_device_off" , dict_devices_off
        url = URL_ROOT + "/devices/%s" % userid
        firebase.put(url,dict_devices_off)
        print "turn_off_all, URL :%s" % url
Пример #11
0
def firebase_turn_on_all(userid):
    #get all the devices from the user, and set it to 0
    list_devices = firebase_get_device_list(userid)
    if len(list_devices) == 0:
        print "no device to update on_all"
    else:
        dict_devices_on = get_dict_with_value(list_devices, 1)
        print "dict_device_on ", dict_devices_on
        url = URL_ROOT + "/devices/%s" % userid
        firebase.put(url, dict_devices_on)
        print "turn_on_all, URL :%s" % url
Пример #12
0
def firebase_delete_device(userid, devicename):
    url = URL_ROOT + "/devices/%s" % (userid)

    dict_devices = firebase_get_device_dict(userid)
    print "delete_device(before)dict_devices:%s, devicename:%s " % (
        dict_devices, devicename)
    result = dict_devices.pop(devicename, None)
    print "delete_device(after) dict_devices:%s, devicename:%s " % (
        dict_devices, devicename)
    firebase.put(url, dict_devices)
    print "deleted_device with userid:%s,devicename:%s, result:%s" % (
        userid, devicename, result)
Пример #13
0
 def book2(self, value):
     if self.clr2 == 0:
         self.clr2 = 2
         self.cr2b.disabled = True
         firebase.put('/', 'clr2', self.clr2)
     elif self.clr2 == 1:
         self.cr2b.disabled = True
     elif self.clr2 == 2:
         self.cr1b.disabled = True
     else:
         self.cr2b.disabled = False
         self.clr2 = 0
Пример #14
0
 def book1(self, value):
     if self.clr1 == 0:
         self.clr1 = 2
         self.cr1b.disabled = True
         self.cr1b.text = "Cannot Book \n Room Already Booked"
         firebase.put('/', 'clr1', self.clr1)
     elif self.clr1 == 1:
         self.cr1b.disabled = True
     elif self.clr1 == 2:
         self.cr1b.disabled = True
     else:
         self.cr1b.disabled = False
         self.clr1 = 0
Пример #15
0
def launch_request():
    session_attributes = {}

    firebase.put(url, {'action': True})

    card_title = 'Welcome to Fish Feeder'
    speech_output = 'Hey there fishy fishy, time for your feed'
    reprompt_text = 'Hey there fishy fishy, time for your feed'
    should_end_session = True
    return build_response(session_attributes,
                          build_speechlet_response(card_title,
                                                   speech_output, reprompt_text,
                                                   should_end_session))
	def submit(self, instance):
		queries = firebase.get('/queries')
		user = self.manager.get_screen('profile').user
		the_time = time.ctime()
		text = self.query.text
		the_query = {'who': user, "time": the_time, "query": text}
		queries.append(the_query)
		firebase.put('/', '/queries', queries)
		self.ids['box'].clear_widgets()
		self.ids['form'].clear_widgets()
		self.ids['form'].add_widget(Button(text='<< Back',color=(0,0,0,1), background_normal='./assets/buttons/long_button.png', background_down='./assets/buttons/long_button_down.png', on_press=self.back))
		self.ids['form'].add_widget(BoxLayout())
		self.ids['form'].add_widget(BoxLayout())
		self.ids['form'].add_widget(Label(text="Thanks! We'll get back to you asap", color=(0,0,0,1)))
	def place_order(self, instance):
		user = self.manager.get_screen('profile').user
		cred_number = self.cred_number.text
		ccv = self.ccv.text
		name = self.the_name.text
		hp = self.hp_no.text
		orders = firebase.get('/orders')
		the_order = {'user': user, 'creditcard': cred_number, 'ccv': ccv, 'name': name, 'phone': hp}
		orders.append(the_order)
		firebase.put('/', '/orders', orders)
		self.ids['order'].clear_widgets()
		self.ids['order'].add_widget(BoxLayout())
		self.ids['order'].add_widget(Label(text="Thanks for purchasing our product!", color=(0,0,0,1)))
		self.ids['order'].add_widget(Label(text="Please find your receipt in your email", color=(0,0,0,1)))
	def submit(self):
		new_password = self.ids['new_password'].text
		old_password = self.ids['old_password'].text
		confirm = self.ids['confirm'].text
		password = firebase.get('/users/'+self.manager.get_screen('profile').user+'/password')
		if old_password == password:
			if len(new_password) > 7:
				if new_password == confirm:
					firebase.put('/', '/users/'+self.manager.get_screen('profile').user+'/password', new_password)
					self.ids['new_password'].text = ""
					self.ids['old_password'].text = ""
					self.ids['confirm'].text = ""
					self.ids['status'].text = "Password updated!"
				else:
					self.ids['status'].text = "New password mismatched!"
			else:
				self.ids['status'].text = "New password too short!"
				print len(new_password)
		else:
			self.ids['status'].text = "Incorrect password!"
Пример #19
0
def register():
    form = RegisterForm()
    if request.method == 'POST' and form.validate():
        user_data = {
            'foods': form.foods.data,
            'email': form.email.data,
            # We store a hash of the password instead of the actual password so
            # that if our database is compromised, no one can read the
            # passwords.
            'password': generate_password_hash(form.password.data)
        }
        email = form.email.data
        ref = '/users/' + email + '.json'

        if firebase.get(ref):
            flash('Email already registered.', 'danger')
            return redirect(url_for('index'))

        firebase.put(ref, user_data)
        return redirect(url_for('index'))
    return render_template('register.html', form=form)
 def submit(self, instance):
     queries = firebase.get('/queries')
     user = self.manager.get_screen('profile').user
     the_time = time.ctime()
     text = self.query.text
     the_query = {'who': user, "time": the_time, "query": text}
     queries.append(the_query)
     firebase.put('/', '/queries', queries)
     self.ids['box'].clear_widgets()
     self.ids['form'].clear_widgets()
     self.ids['form'].add_widget(
         Button(text='<< Back',
                color=(0, 0, 0, 1),
                background_normal='./assets/buttons/long_button.png',
                background_down='./assets/buttons/long_button_down.png',
                on_press=self.back))
     self.ids['form'].add_widget(BoxLayout())
     self.ids['form'].add_widget(BoxLayout())
     self.ids['form'].add_widget(
         Label(text="Thanks! We'll get back to you asap",
               color=(0, 0, 0, 1)))
Пример #21
0
def intent_request(intent_request):
    intent = intent_request['intent']
    intent_name = intent['name']

    if intent_name == 'FeedNow':

        session_attributes = {}

        firebase.put(url, {'action': True})

        card_title = 'Welcome to Fish Feeder'
        speech_output = 'Hey there fishy fishy, time for your feed'
        reprompt_text = 'Hey there fishy fishy, time for your feed'
        should_end_session = True
        return build_response(session_attributes,
                            build_speechlet_response(card_title,
                                                    speech_output, reprompt_text,
                                                    should_end_session))

    # HELP INTENT
    if intent_name == 'AMAZON.HelpIntent':
        card_title = \
            'Try saying like - Alexa, tell Fish Feeder to feed my fish'
        speech_output = \
            'Try saying like - Alexa, tell Fish Feeder to feed my fish'

        should_end_session = False
        reprompt_text = 'Try saying like - Alexa, tell Fish Feeder to feed my fish'
        return build_response({}, build_speechlet_response(card_title,
                                                           speech_output, reprompt_text,
                                                           should_end_session))

    # CANCEL AND STOP INTENTS
    if intent_name == 'AMAZON.CancelIntent' or intent_name \
            == 'AMAZON.StopIntent':
        card_title = 'Session Ended'
        speech_output = 'Thank you for using fish feeder. Good bye!'
        return build_response({}, build_speechlet_response(card_title,
                                                           speech_output, None, True))
	def sign_me_up(self):
		entered_username = self.ids['username'].text.strip()
		entered_email = self.ids['email'].text.strip()
		entered_password = self.ids['password'].text.strip()
		confirm_password = self.ids['password_confirm'].text.strip()
		if " " in entered_username or "	" in entered_username:
			self.ids['status'].text = 'Username invalid! Cannot have spaces'
		elif entered_username in firebase.get('/users'):
			self.ids['status'].text = 'Username Taken!'
		elif self.email_availability(entered_email) == False:
			self.ids['status'].text = 'Email has already been signed up!'
		elif len(entered_password) < 7:
			self.ids['status'].text = "Password too short!"
		elif entered_password != confirm_password:
			self.ids['status'].text = 'Password mismatched!'
		else:
			user = {'dispensers': ['None'], 'email': entered_email, 'password': entered_password, 'pic_url': 'http://i.imgur.com/VMtRJHG.jpg', 'badges': ['None']}
			firebase.put('/', '/users/'+entered_username, user)
			self.ids['sign_up'].clear_widgets()
			self.ids['sign_up'].add_widget(Label(text="Sign Up Successful!"))
			self.ids['sign_up'].add_widget(Label(text="Start contributing to a better world for cats!"))
			self.ids['sign_up'].add_widget(Button(text='Go to your profile', color=(0,0,0,1), background_normal='./assets/buttons/long_button.png', background_down='./assets/buttons/long_button_down.png', on_press=self.transfer_data))
Пример #23
0
def update_firebase():

    fire_count=fire_count+1 
    lat = vehicle.location.global_relative_frame.lat
    lon = vehicle.location.global_relative_frame.lon
    firebase.put('/drone1/obj'+str(fire_count),"lat",lat)
    firebase.put('/drone1/obj'+str(fire_count),"lng",lon)
    firebase.put('/',"count1",fire_count)   
Пример #24
0
def register():
    form = RegisterForm()
    if request.method == 'POST' and form.validate():
        user_data = {
            'names': [name.strip() for name in form.names.data.split(",")],
            'location': form.location.data,
            'languages': form.languages.data,
            'email': form.email.data,
            # We store a hash of the password instead of the actual password so
            # that if our database is compromised, no one can read the
            # passwords.
            'password': generate_password_hash(form.password.data)
        }
        teamname = form.teamname.data
        ref = '/users/' + teamname + '.json'

        if firebase.get(ref):
            flash('Team name already registered.', 'danger')
            return redirect(url_for('index'))

        firebase.put(ref, user_data)
        return redirect(url_for('index'))
    return render_template('register.html', form=form)
 def place_order(self, instance):
     user = self.manager.get_screen('profile').user
     cred_number = self.cred_number.text
     ccv = self.ccv.text
     name = self.the_name.text
     hp = self.hp_no.text
     orders = firebase.get('/orders')
     the_order = {
         'user': user,
         'creditcard': cred_number,
         'ccv': ccv,
         'name': name,
         'phone': hp
     }
     orders.append(the_order)
     firebase.put('/', '/orders', orders)
     self.ids['order'].clear_widgets()
     self.ids['order'].add_widget(BoxLayout())
     self.ids['order'].add_widget(
         Label(text="Thanks for purchasing our product!",
               color=(0, 0, 0, 1)))
     self.ids['order'].add_widget(
         Label(text="Please find your receipt in your email",
               color=(0, 0, 0, 1)))
Пример #26
0
def post_water_reading(waterlevel):
  #current time and date
  #time_hhmmss = time.strftime('%H:%M:%S')
  hour = time.strftime('%H')
  date_mmddyyyy = time.strftime('%d/%m/%Y')
    
  #current location name
  WLS_loc = 'Tumana'
  water_level =waterlevel
    
  #insert record
  data = {'name':WLS_loc,'date':date_mmddyyyy,'time':hour,'water_level':water_level}
  res = firebase.put(firebase_url+'/current_level/'+WLS_loc,water_level)
 # result = firebase.push(firebase_url+'/location.json',data)#requests.post(firebase_url +'/location.json', data=json.dumps(data))
  print ('')
  print ('')
  return
Пример #27
0
def changestatus(workstationnumber,value):
    labstatus = firebase.get('/py_lab')
    if labstatus['Work_Station_%s'%workstationnumber]['status'] == value: return firebase.put('/','py_lab/Work_Station_%s'%workstationnumber,labstatus['Work_Station_%s'%workstationnumber])
    else:
        firebase.put('/','py_lab/Work_Station_%s/status'%workstationnumber,'Checking Vacancy\nTimer: ')
        s = watchlist[workstationnumber-1] #workstation1 is sw1, workstation2 is sw2, etc
        if s.status == True: pass
        if s.status == False: s.start()
        while s.getElapsedTime() <= 60.0:
            firebase.put('/','py_lab/Work_Station_%s/timer'%workstationnumber,str(timeformatter(float(s.getElapsedTime()))))
            if s.getElapsedTime() > 60.0:
                s.stop()
                s.reset()
                firebase.put('/','py_lab/Work_Station_%s',{'status':value, 'timer':0})
                break
        pass
Пример #28
0
 def monitorPlayers(callbackMethod):
     playerSubscription = firebase.subscriber(
         GameStateDatabase.url + '/player', callbackMethod)
     playerSubscription.start()
     print("subscription started")
     firebase.put(GameStateDatabase.url + '/player', 1)
     print("player set to 1")
     firebase.put(GameStateDatabase.url + '/player', 3)
     print("player set to 3")
     firebase.put(GameStateDatabase.url + '/player', 2)
     print("player set to 2")
     #playerSubscription.stop()
     #print("subscription stopped")
Пример #29
0
def checkMachines():
    """Called when periodically by main() to check washing machine states"""
    #Repeats for all 3 Washing Machines (wm)
    for i in range(3):
        #Gets state of wm
        wm = firebase.get('/washingmachine/%s/state' % (str(i + 1)))
        #If wash is ready for collection
        if wm == -2:
            #Gets Users assigned to this wm
            users = firebase.get('/washingmachine/%s/studentid' % (str(i + 1)))
            #For all assgined users
            for j in users:
                #Get their chatID and pmState
                ID = firebase.get('/Accounts/%s/chatID' % (str(j)))
                pmState = firebase.get('/Accounts/%s/pmstate' % (str(j)))
                #If pmState does not exist, add it
                if pmState == None:
                    firebase.put('/Accounts/%s/' % (str(j)), "pmstate", 1)
                    pmState = 0
                #change pmState to 0 after 15mins
                elif pmState < 90 and pmState > 0:
                    pmState += 1
                    firebase.put('/Accounts/%s/' % (str(j)), "pmstate",
                                 pmState)
                else:
                    pmState = 0
                    firebase.put('/Accounts/%s/' % (str(j)), "pmstate",
                                 pmState + 1)
                #If chatID exists and pmState = 0, pm the user
                if ID != None and pmState == 0:
                    #Prints message for our reference
                    print "Messenging user: %r" % (ID)
                    #PMs user
                    reply = "Hello! Your laundry in washing machine %r is now ready for collection!" % (
                        i + 1)
                    bot.sendMessage(ID, reply)
 if hundred == 1 and seventy5 == 1 and fifty == 1 and twenty5 == 1:
     new_percent = 100
 elif seventy5 == 1 and fifty == 1 and twenty5 == 1:
     new_percent = 75
 elif fifty == 1 and twenty5 == 1:
     new_percent = 50
 elif twenty5 == 1:
     new_percent = 25
 else:
     new_percent = 0
 #update to cloud how much food left
 if new_percent != old_percent:
     if new_percent == 100:
         fill_time = time.time()
         print fill_time
         firebase.put('/', '/dispensers/sutd/last_filled', time.ctime(fill_time))
     firebase.put('/', '/dispensers/sutd/fullness', new_percent)
     old_percent = new_percent
 #update to cloud if the food is spoilt
 if fill_time:
     if time.time()-fill_time >= 172800:
         if food_spoilt == 'False':
             food_spoilt = 'True'
             firebase.put('/', '/dispensers/sutd/spoilt', food_spoilt)
     else:
         if food_spoilt == 'True':
             food_spoilt = 'False'
             firebase.put('/', '/dispensers/sutd/food_spoilt', food_spoilt)
         
 ####################code for controlling the auto-dispensing mechanism#########################
 if breakfast in time.ctime():
Пример #31
0
sensorLocation = sensorMap.sensorMap()
        
py_lab = {}

for seat,seatInfo in sensorLocation.iteritems():

    if seat not in py_lab:
        py_lab[seat] = {}

while True:
                
    for seatNum in range(1,len(sensorLocation) + 1):
                
                currentTime = time.strftime("%H:%M:%S|%d/%m/%y")
                GPIO_num = sensorLocation['seat_%d'%seatNum]['Pressure_mat']
                
                GPIO.setmode(GPIO.BCM)
                GPIO.setup(GPIO_num, GPIO.IN, GPIO.PUD_DOWN)
                
                if GPIO.input(GPIO_num) == GPIO.HIGH:
                    print " \n SENSOR ACTIVATED * SENSOR ACTIVATED \n "
                    py_lab['seat_%d'%seatNum]['Pressure_Mat'] = True
                    py_lab['seat_%d'%seatNum]['Update_Time'] = currentTime
                else:
                    py_lab['seat_%d'%seatNum]['Pressure_Mat'] = False
                    py_lab['seat_%d'%seatNum]['Update_Time'] = currentTime
                
    print py_lab                    
    firebase.put('/','py_lab',py_lab)
Пример #32
0
 def incrementPlayer():
     currentPlayer = firebase.get(GameStateDatabase.url + '/player')
     currentPlayer += 1
     return firebase.put(GameStateDatabase.url + '/player', currentPlayer)
Пример #33
0
def firebase_turn(userid, devicename, value):
    url = URL_ROOT + "/devices/%s/%s" % (userid, devicename)
    firebase.put(url, value)
    print "turn_on, device:%s,value:%d, URL :%s" % (devicename, value, url)
	def add_the_dispenser(self, instance):
		user_dispensers = firebase.get('/users/'+self.user+'/dispensers')
		user_dispensers.append(instance.id)
		firebase.put('/', '/users/'+self.user+'/dispensers', user_dispensers)
		self.display_result()
Пример #35
0
 ]
try: #this should handle the case of writing -1 to influxdb
  client.write_points(json_body)
  try:
   currentTime = datetime.datetime.now()
   data = str(temp)+","+str(humidity)+","+str(moisture)+","+relay_status+","+str(currentTime)
   payLoad = {'deviceID':'{deviceid}', 'passwd':'{password}', 'data':data}
   r = requests.post("{server address}", data=payLoad)
   print r
  except:
   print "Data not put in server"
   pass
  try:
   URL = '{firebase-address}'
   payload = {"greenhouse":{"temperature":str(temp),"humidity":str(humidity),"moisture":str(moisture),"relay_status":relay_status,"currentTime":str(currentTime)}}
   firebase.put(URL, payload)
  except:
   print "Data not put into firebase"
   pass
 except:
  if counter == 10:
   subprocess.call(["avrdude", "-c", "gpio", "-p", "m328p"])#run avrdude
   counter  = 0
  else:
   counter = counter + 1
# if resistance>light_threshold:
#  GPIO.output(relay_led,GPIO.LOW)
# else:
#  GPIO.output(relay_led,GPIO.HIGH)
#  setRGB(255,127,0)
#      str = "Greenhouse Data Display"
    if hundred == 1 and seventy5 == 1 and fifty == 1 and twenty5 == 1:
        new_percent = 100
    elif seventy5 == 1 and fifty == 1 and twenty5 == 1:
        new_percent = 75
    elif fifty == 1 and twenty5 == 1:
        new_percent = 50
    elif twenty5 == 1:
        new_percent = 25
    else:
        new_percent = 0
    #update to cloud how much food left
    if new_percent != old_percent:
        if new_percent == 100:
            fill_time = time.time()
            print fill_time
            firebase.put('/', '/dispensers/sutd/last_filled',
                         time.ctime(fill_time))
        firebase.put('/', '/dispensers/sutd/fullness', new_percent)
        old_percent = new_percent
    #update to cloud if the food is spoilt
    if fill_time:
        if time.time() - fill_time >= 172800:
            if food_spoilt == 'False':
                food_spoilt = 'True'
                firebase.put('/', '/dispensers/sutd/spoilt', food_spoilt)
        else:
            if food_spoilt == 'True':
                food_spoilt = 'False'
                firebase.put('/', '/dispensers/sutd/food_spoilt', food_spoilt)

    ####################code for controlling the auto-dispensing mechanism#########################
    if breakfast in time.ctime():
		# check to see if the eye aspect ratio is below the blink
		# threshold, and if so, increment the blink frame counter
		if ear < EYE_AR_THRESH:
			COUNTER += 1

			# if the eyes were closed for a sufficient number of
			# then sound the alarm
			if COUNTER >= EYE_AR_CONSEC_FRAMES:
				# if the alarm is not on, turn it on
				if not ALARM_ON:
					ALARM_ON = True

					# check to see if an alarm file was supplied,
					# and if so, start a thread to have the alarm
					# sound played in the background
				result = firebase.put('https://cabdetails-2e8a0.firebaseio.com/','pupilprogress',str(0))	
				result = firebase.put('https://cabdetails-2e8a0.firebaseio.com/','DrowsinessDetected',str(0))
				t = Thread(target=sound_alarm,
				args=(r"C:\Users\SAMARTH G VASIST\Downloads\Industrial Alarm-SoundBible.com-1012301296.wav",))
				t.deamon = True
				t.start()
                
                 

				# draw an alarm on the frame
				cv2.putText(frame, "DROWSINESS ALERT!", (10, 30),
					cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)

		# otherwise, the eye aspect ratio is not below the blink
		# threshold, so reset the counter and alarm
		else:
Пример #38
0
def putData(studentid,
            weight=None,
            machineid=None,
            endtime=None,
            debt=None,
            pmstate=None):  #changes the attributes of users on firebase
    if weight != None:
        if type(weight
                ) is str:  #removes weight attribute (used for command 'clear')
            firebase.put('/Accounts/%s/' % (studentid), 'weight', None)
        else:  #puts weight list
            firebase.put('/Accounts/%s/' % (studentid), 'weight', weight)
    if machineid != None:
        if type(machineid) is str:  #removes machineid attribute
            firebase.put('/Accounts/%s/' % (studentid), 'machineid', None)
        else:  #puts machineid list
            firebase.put('/Accounts/%s/' % (studentid), 'machineid', machineid)
    if endtime != None:
        if type(endtime) is str:  #removes endtime list
            firebase.put('/Accounts/%s/' % (studentid), 'endtime', None)
        else:  #puts endtime list
            firebase.put('/Accounts/%s/' % (studentid), 'endtime', endtime)
    if debt != None:
        try:  #accumulates debt if the type is correct, else resets debt
            debt += getData(studentid, 'debt')
            firebase.put('/Accounts/%s/' % (studentid), 'debt', debt)
        except TypeError:
            firebase.put('/Accounts/%s/' % (studentid), 'debt', 0)
    if pmstate != None:
        if type(pmstate) is str:  #removes pmstate attribute
            firebase.put('/Accounts/%s/' % (studentid), 'pmstate', None)
        else:  #puts pmstate
            firebase.put('/Accounts/%s/' % (studentid), 'pmstate', pmstate)
Пример #39
0
import firebase
import time

url = "https://flickering-fire-1661.firebaseio.com/" # URL to Firebase database
token = "ZpSWTZaRaODNivf2S3Vil0a50BAPjx1ZhGsVbL2S" # unique token used for authentication

# Create a firebase object by specifying the URL of the database and its secret token.
# The firebase object has functions put and get, that allows user to put data onto 
# the database and also retrieve data from the database.
firebase = firebase.FirebaseApplication(url, token)

print "Reading from my database."
# meow = firebase.get('/sighpie') # get the value from the node age
# print meow
now = str(time.strftime('%H:%M:%S') + '|' + time.strftime('%d/%m/%Y'))
bye = 5
hi = 8
firebase.put('/stationA/', 'ldr', bye)
firebase.put('/stationA/', 'temp', hi)
firebase.put('/stationA/', 'time', now)
Пример #40
0
def createUser(studentid, password,
               phone):  #creates a user together with the required attributes
    firebase.put('/Accounts/%s/' % (studentid), 'studentid', studentid)
    firebase.put('/Accounts/%s/' % (studentid), 'password', password)
    firebase.put('/Accounts/%s/' % (studentid), 'phonenumber', phone)
    putData(studentid, debt='clear')
Пример #41
0

def drawScreens(frame):
	#print screens
	for idx, screen in enumerate(screens):
		if idx > 0:
			rect = (tuple(screen[0]), tuple(screen[1]), screen[2])
			box = np.int0(boxPoints(rect))
			fillConvexPoly(frame, box, colors[idx % len(colors)])


if __name__ == "__main__":
	root = firebase.firebaseURL(APP_NAME)
	firebase.patch(root, {u'FRAME_WIDTH': FRAME_WIDTH , u'FRAME_HEIGHT': FRAME_HEIGHT, u'RELOAD': -1, u'valid': "no"})
	_screens = firebase.firebaseURL(APP_NAME + "/screens")
	firebase.put(_screens, {u'0': 'none'})

	capture = VideoCapture();
	capture.open(0);
	#set height and width of capture frame
	capture.set(4,FRAME_WIDTH);
	capture.set(5,FRAME_HEIGHT);
	#start an infinite loop where webcam feed is copied to cameraFeed matrix
	#all of our operations will be performed within this loop
	firstFrame = None
	while True:
		if COUNTER == 0:
			thread.start_new_thread(syncScreens, ())	
		#store image to matrix
		rval, frame = capture.read()
		if not rval:
	def update(self):
		user = self.manager.get_screen('profile').user
		email = self.ids['input'].text
		firebase.put('/', '/users/'+user+'/email', email)
		self.manager.get_screen('profile').ids['email'].text = email
		self.ids['status'].text = "Successfully update your email!"
Пример #43
0
def initMachines(
        number):  #creates the specified number of machines on firebase
    for machine in range(number + 1)[1:]:
        putState(machine, door=0, state=0, studentid='clear', weight='clear')
        firebase.put('/washingmachine/%d/' % (machine), 'id', machine)
	def update(self):
		user = self.manager.get_screen('profile').user
		pic_url = self.ids['input'].text
		firebase.put('/', '/users/'+user+'/pic_url', pic_url)
		self.manager.get_screen('profile').ids['pic'].source = pic_url
		self.ids['status'].text = "Successfully update profile picture!"
Пример #45
0
def clearMachines():  #removes all machines from firebase
    for machine in firebase.get('/washingmachine/')[1:]:
        firebase.put('/washingmachine/', str(machine['id']), None)
	def delete_dispenser(self, dispenser_number, instance):
		self.dispensers.remove(self.dispensers[dispenser_number])
		firebase.put('/', '/users/'+self.user+'/dispensers', self.dispensers)
		self.ids['dispensers_manager'].clear_widgets()
		self.generate_screen()
Пример #47
0
def putState(
        machine,
        door=None,
        state=None,
        weight=None,
        studentid=None):  #changes the attributes of the machines on firebase
    if door != None:
        if door == 0:  #0 is the command that door is closed
            firebase.put('/washingmachine/%d/' % (machine), 'door', door)
        elif door == 1:  #1 is the command that door is opened and puts time of openning
            firebase.put('/washingmachine/%d/' % (machine), 'door', time())
    if state != None:
        firebase.put('/washingmachine/%d/' % (machine), 'state', state)
    if weight != None:
        try:  #accumulates weight if the type is correct, else clears all the weight
            weight += getState(machine, 'weight')
            firebase.put('/washingmachine/%d/' % (machine), 'weight', weight)
        except TypeError:
            firebase.put('/washingmachine/%d/' % (machine), 'weight', 0.0)
    if studentid != None:
        if studentid == 'clear':  #clears the list of studentids
            firebase.put('/washingmachine/%d/' % (machine), 'studentid', None)
        else:  #puts studentid list
            firebase.put('/washingmachine/%d/' % (machine), 'studentid',
                         studentid)
Пример #48
0
def firebase_turn(userid,devicename,value):
    url = URL_ROOT + "/devices/%s/%s" %(userid,devicename)
    firebase.put(url,value)
    print "turn_on, device:%s,value:%d, URL :%s" % (devicename,value,url)
Пример #49
0
def uploadwrite(state, sonars, theta, temp, ldr):
    fin = open('C:\Users\HanWei\Dropbox\SUTDNotes\SUTDTerm3\\2D\DW2DShenanigans.txt', 'a')
    now = time.strftime('%H:%M:%S') + '|' + time.strftime('%d/%m/%Y')
    othernow = time.strftime('<%H:%M:%S>') + '||' + time.strftime('<%d/%m/%Y>' + '||')
    if state[3][0] == 'A':
        fin.write(othernow + 'Expose Plates at A\n')
        firebase.put('/stationA/', 'ldr', ldr)
        firebase.put('/stationA/', 'temp', temp)
        firebase.put('/stationA/', 'time', now)
    elif state[3][0] == 'B':
        fin.write(othernow + 'Expose Plates at B\n')
        firebase.put('/stationB/', 'ldr', ldr)
        firebase.put('/stationB/', 'temp', temp)
        firebase.put('/stationB/', 'time', now)
    elif state[3][0] == 'C':
        fin.write(othernow + 'Expose Plates at C\n')
        firebase.put('/stationC/', 'ldr', ldr)
        firebase.put('/stationC/', 'temp', temp)
        firebase.put('/stationC/', 'time', now)
    elif state[3][0] == 'D':
        fin.write(othernow + 'Expose Plates at D\n')
        firebase.put('/stationD/', 'ldr', ldr)
        firebase.put('/stationD/', 'temp', temp)
        firebase.put('/stationD/', 'time', now)
    elif state[3][0] == 'X':
        if len(state[3][0]) == 1:
            fin.write(othernow + 'Finished, and arrived at X\n')
        elif len(state[3][0]) != 1:
            fin.write(othernow + 'Collect Plates at X\n')
        firebase.put('/station/', 'ldr', ldr)
        firebase.put('/stationA/', 'temp', temp)
        firebase.put('/stationA/', 'time', now)
    else:
        print 'Not a station'
    global checked
    checked = True
    fin.close()
    return state, io.Action(fvel=0, rvel=0)
Пример #50
0
import json
import firebase
class Flag:
	def __init__(self):
		self.birthday=''
	def flag(*data, *a)
		firebase=firebase.FirebaseApplication('https://ramprasadhsample.firebaseio.com/', None)
		json_data=data['birthdate']
		for email in a['email']
	result=firebase.put('/flag', json_data, {email['email']:'Sent'})
	print result
Пример #51
0
def uploadwrite(state, sonars, temp, ldr):  # Writes the time that the station was reached, ldr reading, and
    # temperature reading into file, and uploads it onto firebase
    global checked
    fin = open('C:\Users\HanWei\Dropbox\SUTDNotes\SUTDTerm3\\2D\DW2DShenanigans.txt', 'a+')  # Opens file for appending
    now = datetime.now().strftime('%H:%M:%S') + '|' + datetime.now().strftime('%d/%m/%Y')  # Str format of time for
    # firebase upload
    othernow = datetime.now().strftime('<%H:%M:%S>') + '||' + datetime.now().strftime('<%d/%m/%Y>' + '||')  # Str format
    #  of time for file write
    if state[3][0] == 'A':
        fin.write(othernow + 'Expose Plates at A\n')
        firebase.put('/stationA/', 'ldr', ldr)
        firebase.put('/stationA/', 'temp', temp)
        firebase.put('/stationA/', 'time', now)
    elif state[3][0] == 'B':
        fin.write(othernow + 'Expose Plates at B\n')
        firebase.put('/stationB/', 'ldr', ldr)
        firebase.put('/stationB/', 'temp', temp)
        firebase.put('/stationB/', 'time', now)
    elif state[3][0] == 'C':
        fin.write(othernow + 'Expose Plates at C\n')
        firebase.put('/stationC/', 'ldr', ldr)
        firebase.put('/stationC/', 'temp', temp)
        firebase.put('/stationC/', 'time', now)
    elif state[3][0] == 'D':
        fin.write(othernow + 'Expose Plates at D\n')
        firebase.put('/stationD/', 'ldr', ldr)
        firebase.put('/stationD/', 'temp', temp)
        firebase.put('/stationD/', 'time', now)
    elif state[3][0] == 'X':
        if len(state[3][0]) == 1:
            fin.write(othernow + 'Finished, and arrived at X\n')
        elif len(state[3][0]) != 1:
            fin.write(othernow + 'Collect Plates at X\n')
        firebase.put('/station/', 'ldr', ldr)
        firebase.put('/stationA/', 'temp', temp)
        firebase.put('/stationA/', 'time', now)
    else:  # Should never enter this state
        print 'Not a station'
    checked = True  # Sets checked flag to true so ebot can continue moving
    fin.close()  # Closes the file
    return state, io.Action(fvel=0, rvel=0)  # Don't move while you do everything in this function
Пример #52
0
def start():
    success = False

    print "Welcome!"

    while success == False:

        test = raw_input("1 to login\n2 to signup\n")

        if test == "1":
            account_fetched = False

            while account_fetched == False:

                username = raw_input("Input username: "******"Input password: "******"password matches"

                            leaderboard_moves = firebase.get(
                                '/leaderboard/top10_moves', None)
                            print leaderboard_moves

                            leaderboard_times = firebase.get(
                                '/leaderboard/top10_times', None)
                            print leaderboard_times

                            password_matched = True
                            account_fetched = True
                            success = True
                        else:
                            print "Password incorrect, try again."
                else:
                    print "Incorrect username, try again."

        elif test == "2":
            account_created = False

            while account_created == False:

                username = raw_input("Input a unique username: "******"Username does not exist"
                    email = raw_input("Input email: ")
                    password = raw_input("Input password: "******"Username exists, try again\n"

            success = True
        else:
            print "error"
Пример #53
0
def uploadToFirebase(motion):
    firebase.put('/','py_lab/station_1',motion)