def update(self): self.all_sprites.update(self.tela) self.camera.update(self.jogador) if pygame.time.get_ticks() - self.ultimo_hit > 3000: self.imunidade=False if self.imunidade==False: hitou=pygame.sprite.spritecollide(self.jogador,self.inimigos,False,colidiu_func) for hit in hitou: som_dano.play() hit.velocidade=vector(0,0) self.jogador.vidas=self.jogador.vidas-1 self.ultimo_hit=pygame.time.get_ticks() self.imunidade=True if self.jogador.vidas<= 0: som_morte.play() highscore[NOME] = self.score firebase.patch('/Estoque',highscore) self.score = 0 self.gameover=True pygame.mixer.music.load("GameOver.mp3") pygame.mixer.music.play(-1) hitou=pygame.sprite.groupcollide(self.inimigos,self.tiros,False,True) for hit in hitou: hit.vida=hit.vida-dano_tiro hit.velocidade=vector(0,0)
def send_alarm(src): config = { "apiKey": "AAAAXDKjDeY:APA91bHLONjob43L-tynyMAicqee38C9yuAo6rZFdlc25zmCmmnqyrcyG7NIugNLECKIU2q4QpyNPTzN0NsJHTm8SyiuzJOxzL5JPmHwIoJO7LrYDboUJU0-115EXKWpK8vLVJor1-Pi", "authDomain": "homeattender.firebaseapp.com", "databaseURL": "https://homeattender.firebaseio.com/", "storageBucket": "homeattender.appspot.com" } #base firebase setup firebase = firebase.FirebaseApplication('https://homeattender.firebaseio.com/', None) push_service = FCMNotification(api_key=config["apiKey"]) registration_id = "cp5OKaH4C_Y:APA91bEtcHMcJINecS8SpGYMckeO_Jj9HYwyrQXs4jGBObxgrT8yGCYmdh0JHVE4VP0Q0MmlGxH-OOC6ixT9pFNkqfivOke-nTXanJnhbyVkVBK28bT7KMhSH_Mun3SuWRj14xH58e0V3ZAJLpsFFds8BwFjbyXbnQ" #picture pyrebase setup to send from rasp to phone pyrebase = pyrebase.initialize_app(config) storage = pyrebase.storage() #PUSH file_sorce = sprintf(image_name, "/home/pi/lip/LeotonModule/fire_%.4d.jpg", src); picture_name = "fire{}.png".format(time.strftime("%Y%m%d-%H%M%S")) storage.child(picture_name).put(src) time="" msg = "Fire detected!".time firebase.patch('/FireAlarm', {'Info': msg, 'PicName': picture_name}) #NOTIFICATION message_title = "FIRE" message_body = "FIRE HAS BEEN DETECTED" firebase.patch('/', {'Alert': 'off'}) push_service.notify_single_device(registration_id=self.registration_id, message_title=message_title, message_body=message_body) return '0'
def setPompaAirNyala(): print "pompa nyala" firebase.patch('/sensor/relay', {"status": True}) GPIO.setup(GPIO_RELAY, GPIO.OUT) # GPIO Assign mode GPIO.setup(GPIO_RELAY1, GPIO.OUT) # GPIO Assign mode GPIO.output(GPIO_RELAY, GPIO.LOW) # nyala GPIO.output(GPIO_RELAY1, GPIO.LOW) # nyala
def GameOver(self): self.tela.fill((0,0,0)) self.text=fonte_titulo.render("Game Over", 1, (250,0,0)) self.tela.blit(self.text,(80,100)) self.text_1=fonte_texto.render("O seu SCORE foi de {0}".format(self.placar), 1, (250,250,250)) self.tela.blit(self.text_1,(150,250)) self.text_2=fonte_texto.render("Para voltar ao menu aperte M", 1, (250,250,250)) self.tela.blit(self.text_2,(150,300)) self.text_3=fonte_texto.render("Para jogar novamente aperte R", 1, (250,250,250)) self.tela.blit(self.text_3,(150,330)) key = pygame.key.get_pressed() if key[pygame.K_m]: menu.menu() if key[pygame.K_r]: jogo = loopPrincipal() jogo.dar_load() jogo.roda() firebase.patch('/Estoque',highscore) #Função chamada pelo menu para iniciar o jogo #def start(): #jogo = loopPrincipal() #while True: # jogo.dar_load() # jogo.roda() #-------------------------------------------------------------------------------------------------------------------- #firebase.patch('/Estoque',highscore) #colocar quando morrer
def answerStickAdd(**param): event = param['event'] tokens = param['tokens'] alias = tokens[0] packageId = tokens[1] stickerId = tokens[2] newStickerInfo = {'packageId': packageId, 'stickerId': stickerId} # 기존 스티커 리스트를 가져와서 aliasInfo = firebase.get('/customSticker', alias) # 이전에 저장된 값이 없다면 리스트로 만들어 초기화 if aliasInfo is None: stickerList = [newStickerInfo] aliasInfo = {"list": stickerList} else: stickerList = aliasInfo.get('list') if not validateStickAdd(stickerList, newStickerInfo, event): return # 현재 없는 새로운 스티커라면 등록 stickerList.append(newStickerInfo) aliasInfo = {"list": stickerList} # save custom sticker in firebase. use patch and add last slash to remove unique number firebase.patch('/customSticker/' + alias + '/', aliasInfo) printTextMessage(event, 'Stiker ' + alias + 'Juga disimpan dalam !!!')
def process_product(command): คำสั่ง = command if คำสั่ง == "": ชื่อสินค้า = input("กรุณาระบุชื่อสินค้า ") ราคาสินค้า = int(input("กรุณาระบุราคาสินค้า ")) จำนวนที่เหลืออยู่ของสินค้า = int(input("กรุณาระบุจำนวนที่เหลืออยู่ของสินค้า ")) # จำนวนที่ขายไปแล้วของสินค้า = int(input("กรุณาระบุจำนวนที่ขายไปแล้วของสินค้า ")) สินค้า = { "ชื่อ":ชื่อสินค้า, "ราคา":ราคาสินค้า, "จำนวนที่เหลืออยู่":จำนวนที่เหลืออยู่ของสินค้า, # "จำนวนที่ขายไปแล้ว":จำนวนที่ขายไปแล้วของสินค้า } #save to firebase firebase.patch(DATABASE_PRODUCT+"/"+ชื่อสินค้า,สินค้า) return สินค้า elif คำสั่ง.lower().strip(" ") == "all": all_products = firebase.get(DATABASE_PRODUCT,None) print(all_products) return True # None == False else: print("ท่านได้ออกจากคำสั่งเรียบร้อย ขอขอบพระคุณที่ใช้บริการ") return False
def update_relay(): result = firebase.get('/sensor/relay', 'status') result1 = firebase.get('/sensor/dht', 'temp') print result1 if result == True: GPIO_RELAY = 18 GPIO.setup(GPIO_RELAY, GPIO.OUT) # GPIO Assign mode GPIO.output(GPIO_RELAY, GPIO.LOW) # out GPIO.output(GPIO_RELAY, GPIO.LOW) print('Relay Nyala') # print('result1') if result == False: GPIO_RELAY = 18 GPIO.setup(GPIO_RELAY, GPIO.OUT) # GPIO Assign mode GPIO.output(GPIO_RELAY, GPIO.HIGH) # out GPIO.output(GPIO_RELAY, GPIO.HIGH) print('Relay Mati') if result1 < 30: GPIO_RELAY = 18 GPIO.setup(GPIO_RELAY, GPIO.OUT) # GPIO Assign mode GPIO.output(GPIO_RELAY, GPIO.HIGH) # out GPIO.output(GPIO_RELAY, GPIO.HIGH) firebase.patch('/sensor/relay', {"status": False}) print('Suhu Normal') if result1 > 29: print('Suhu Panas kipas blower menyala!!') GPIO_RELAY = 18 GPIO.setup(GPIO_RELAY, GPIO.OUT) # GPIO Assign mode GPIO.output(GPIO_RELAY, GPIO.LOW) # out GPIO.output(GPIO_RELAY, GPIO.LOW) firebase.patch('/sensor/relay', {"status": True})
def main(): url = 'http://data.ntpc.gov.tw/od/data/api/28AB4122-60E1-4065-98E5-ABCCB69AACA6?$format=json' response = requests.get(url) response.encoding = 'UTF-8' items = response.json() # STG firebase.delete(stgTable, None) print('count = ' + str(len(items))) for item in items: addr = item['location'] g = geocoder.google(addr) if g.ok: data = {'lineid': item['lineid'], 'car': item['car'], 'address': addr, 'time': item['time'], 'lat': g.lat, 'lng': g.lng} result = firebase.post(stgTable, data) else: print(g.json) time.sleep(0.5) # Copy to PROD print('Copy to PROD') firebase.delete('/PROD', None) stgResults = firebase.get(stgTable, None) firebase.patch('/PROD', stgResults) print('Done')
def servoControl(): LAP=1 while True: ciclo=0 start=firebase.get('Remote/STAR_STOP',None) while (start=="1"): start=firebase.get('Remote/STAR_STOP',None) Direction= firebase.get('Remote/IZQ_DER',None) print(Direction) Sequence= firebase.get('Remote/MAN_AUT',None) print('Secuencia: '+ Sequence) if (Sequence== '1'): if(LAP==1): for posicion in range(1,11,1): if (Sequence=='1'and start=='1'): Sequence= firebase.get('Remote/MAN_AUT',None) start=firebase.get('Remote/STAR_STOP',None) print('SecuenciaP: '+ Sequence) ciclo=posicion SerCam.ChangeDutyCycle(ciclo) print('posicion:'+str(ciclo)) #Enviamos un pulso del 4.5% para girar el servo hacia la izquierda sleep(3) #pausa de medio segundo if(posicion==10): LAP=2 else: posicion=20 #Detenemos el servo elif(LAP==2): for posicion in range(11,0,-1): if (Sequence=='1'and start=='1'): Sequence= firebase.get('Remote/MAN_AUT',None) start=firebase.get('Remote/STAR_STOP',None) print('Secuenciavuelta: '+ Sequence) ciclo=posicion SerCam.ChangeDutyCycle(ciclo) print('posicion:'+str(ciclo)) #Enviamos un pulso del 4.5% para girar el servo hacia la izquierda sleep(3) #pausa de medio segundo if(posicion==10): LAP=1 else: posicion=20 elif (Sequence=='0'): SerCam.ChangeDutyCycle(0) if(Direction=='0'): ciclo=ciclo+1 if (ciclo>10): ciclo=10 SerCam.ChangeDutyCycle(ciclo) dato={'IZQ_DER': '2'} firebase.patch('Remote',dato) Direction='2' elif(Direction =='1') : ciclo=ciclo-1 if(ciclo<0): ciclo=0 SerCam.ChangeDutyCycle(ciclo) dato={'IZQ_DER': '2'} firebase.patch('Remote',dato) Direction='2'
def upDownControl(): while True: i=0 ciclo_2=0 SerCam_2.ChangeDutyCycle(0) start=firebase.get('Remote/STAR_STOP',None) while (start=="1"): start=firebase.get('Remote/STAR_STOP',None) UpDown= firebase.get('Remote/UP_DOW',None) if(UpDown=='1'): ciclo_2=ciclo_2 + 1 if (ciclo_2>4): ciclo_2=4 SerCam_2.ChangeDutyCycle(ciclo_2) print("Up_DOWN:"+str(ciclo_2)) dato_2={'UP_DOW': '2'} firebase.patch('Remote',dato_2) UpDown='2' elif(UpDown=='0') : ciclo_2=ciclo_2 - 1 if(ciclo_2<0): ciclo_2=0 SerCam_2.ChangeDutyCycle(ciclo_2) print("Up_DOWN:"+str(ciclo_2)) dato_2={'UP_DOW': '2'} firebase.patch('Remote',dato_2) UpDown='2'
def check_MBTI(): init() mbti = firebase.get('/User/' + Uid + '/MBTI', None) input_mbti = req['action']['detailParams']['mbti']['value'] if 'mbti_1' not in context_list: input_mbti = mbti + input_mbti firebase.patch('/User/' + Uid, {'MBTI': input_mbti}) if 'mbti_4' in context_list: mbti = firebase.get('/User/' + Uid + '/MBTI', None) comment = makeSimpleText( user + '님의 ' + firebase.get('/UI/mbti/' + mbti + '/description', None)) career = makeSimpleText('추천직업으로는 ' + firebase.get('/UI/mbti/' + mbti + '/career', None) + '가 있어요') qes = makeSimpleText("성격유형별 대표직업을 확인했습니다. 그중 마음에 드는 직업을 선택하셨나요??") reply = firebase.get("/UI/result_branch/reply", None) del reply[2] return SendReply([comment, career, qes], reply) return SendMessage([makeSimpleText('')])
def getDateTime(service, user_id, msg_id, alert): try: message = service.users().messages().get( userId=user_id, id=msg_id, format='minimal').execute() # Splits the content of the message to the needed components and assigns it to a TUalert object temp = message['snippet'].split('Date:')[1].split('at') alert.date = temp[0] alert.time = temp[1].split('Subject:')[0] # Data struct that we pass into the database (Need to find a better way to handle this) data = { 'Date': alert.date, 'Time': alert.time, 'Crime': alert.crime, 'AlertType': alert.alert, 'Location': alert.location, 'Id': alert.id, 'Description': alert.description, 'Longitude': alert.long, 'Latitude': alert.lat } # Puts the TUalert into the database firebase.patch('Alerts/' + str(alert.id) + '/', data) return alert except errors.HttpError, error: print('An error occurred: %s' % error)
def cadastro(): error = None print(request.form) if request.method == 'POST': username = request.form['username1'] senha = request.form['password1'] novo_login = { username: { 'id': len(logins), 'senha': senha, }, } erroo = False if username in arquivo_firebase['login']: error = 'Este nome de usuário já existe.' erroo = True if len(senha) < 5: error = 'A sua senha deve ter no mínimo 5 caracteres' erroo = True if not erroo: logins.append(novo_login) print(logins) arquivo_firebase['login'] = logins firebase.patch('https://projetofinal-dessoft.firebaseio.com/', arquivo_firebase) redirect(url_for('mensagem')) return render_template('cadastro.html', error=error)
def update_firebase(): data1 = arduino.readline() print "Sensor Nutrisi TDS:", data1 sleep(0) data2 = arduino.readline() print "Sensor PH", data2 sleep(0) data3 = arduino.readline() print "Sensor Cahaya PhotoDioda:", data3 sleep(0) humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) print "Suhu :", temperature sleep(0) print "Kelembapan:", humidity sleep(3) # regex data dari readline nilaiTds = re.findall(r',?([^,]+)(?:,|\r\n)', data1) nilaiPH = re.findall(r',?([^,]+)(?:,|\r\n)', data2) nilaiCahaya = re.findall(r',?([^,]+)(?:,|\r\n)', data3) # convert ke int dan float nilai1 = float(nilaiTds[0]) nilai2 = float(nilaiPH[0]) nilai3 = float(nilaiCahaya[0]) data = { "tds/value": nilai1, "ph/value": nilai2, "photoDioda/value/": nilai3, "dht/humidity": humidity, "dht/temp": temperature } firebase.patch('/sensor/', data)
def answerStickerRemoveCarousel(**param): event = param['event'] tokens = param['tokens'] alias = tokens[0] packageId = tokens[1] stickerId = tokens[2] newStickerInfo = {'packageId': packageId, 'stickerId': stickerId} # 기존 스티커 리스트를 가져와서 aliasInfo = firebase.get('/customSticker', alias) stickerList = aliasInfo.get('list') targetIdx = hasStickerInfo(aliasInfo, newStickerInfo) # targetIdx 가 -1 이면 리턴(삭제할 대상이 없음) if targetIdx == -1: printTextMessage(event, 'Aku dibersihkan eoptto!') return stickerList.pop(targetIdx) aliasInfo = {"list": stickerList} # save custom sticker in firebase. use patch and add last slash to remove unique number firebase.patch('/customSticker/' + alias + '/', aliasInfo) printTextMessage(event, 'Stiker ' + alias + 'Geo di jyeotto..')
def updateo(request): global x global a global id global dictimes dictimes = [] a[0] = request.GET['id1'] if (firebase.get('/' + str(request.GET['id1']), 'id') != None): if (firebase.get('/' + str(request.GET['id1']), 'pass') == request.GET['pass1']): x = int(request.GET['slot']) reg_id = request.GET['id1'] s = "/" + str(reg_id) id = s print(s, "is id here") firebase.patch(s, {'slot': x}) tb = firebase.delete(s, 'table') else: messages.error( request, "the paswords or username do not match or no such user") return redirect('update1') for i in range(0, x): con = 'slote' + str(i) dictimes.append(con) return render(request, 'filluptime.html', {'times': dictimes}) else: messages.error( request, "the paswords or username do not match or no such user") return redirect('update1')
def pushToFirebase(): currentDate, currentTime = printDateTime() firebase.post('/Motion_LivingRoom', { 'date': currentDate, 'status': 'active', 'time': currentTime }) firebase.patch('/Motion_Status', {'status': 'active'})
def change_attribute(subject, key, value): """ Reach out to Firebase and change a generic attribute. This function is pretty straightforward, it simple swaps out some firebase attributes, used quite often. """ firebase.patch('/users/' + subject + '/', data={key: value})
def job_calculate(): init() sum = 0 number = req['action']['detailParams'] for n in number.keys(): sum += json.loads(number[n]['value'])['amount'] job = firebase.get('/User/' + Uid + '/cal_job', None) next_job = "" for i in range(0, 3): if job[i]["score"] == -1: firebase.patch('/User/' + Uid + "/cal_job/" + str(i), {"score": sum}) if 'calculate_3' not in context_list: next_job = job[i + 1]['name'] break if 'calculate_3' in context_list: # 3번째 직업 점수 매겼을 경우 result = firebase.get('/User/' + Uid + '/cal_job', None) max = 0 rec_job = "" job_code = "" for i in range(0, 3): if result[i]['score'] > max: max = result[i]['score'] rec_job = result[i]['name'] job_code = result[i]['code'] firebase.patch('/User/' + Uid + '/rec_job', { 'name': rec_job, 'code': job_code }) comment = [] comment.append( makeSimpleText("3가지 직업중 '" + rec_job + "' 직업을 가장 선호하시는군요. 잘 결정하셨네요^^ " + user + "님은 잘하실 수 있을 겁니다.\n\n이 직업의 간단한 정보를 안내해 드릴게요")) comment.append(makeSimpleText(callAPI(job_code, False))) detail = firebase.get('/UI/career_result/detail_information', None) comment.append(detail) reply = firebase.get('/UI/career_result/next_button', None) return SendReply(comment, [reply]) comment = [] comment.append(makeSimpleText("다음으로 " + next_job + "에 대한 점수를 매겨주세요.")) comment.append( makeSimpleText(firebase.get('/UI/interest_result/calculate_job', None))) return SendMessage(comment)
def updateTemperature(temp): wares = firebase.get("/warehouse", None) global temperatureUpdateTimer if(temperatureUpdateTimer <= 0 and wares is not None): #Update when timer reaches 0 for item in wares: if(wares[item]['row'] == 1): #Update all items in row 1 firebase.patch("/warehouse/"+item,{'temperature':temp}) temperatureUpdateTimer = 5 #Time between temperature updates temperatureUpdateTimer = temperatureUpdateTimer-1
def fir_data(): if GPIO.input(18): print("Door is open") status = 'open' if GPIO.input(18) == False: print("Door is closed") status = 'closed' data = {"open": status} firebase.patch('smart-security-e2179', data)
def setPompaMati(): print "pompa mati" firebase.patch('/sensor/relay', {"status": False}) GPIO_RELAY = 18 GPIO_RELAY1 = 19 GPIO.setup(GPIO_RELAY, GPIO.OUT) # GPIO Assign mode GPIO.setup(GPIO_RELAY1, GPIO.OUT) # GPIO Assign mode GPIO.output(GPIO_RELAY, GPIO.HIGH) # nyala GPIO.output(GPIO_RELAY1, GPIO.HIGH) # nyala
def setRelaySpringkler(nyala): firebase.patch('/control/relaySpringkler', {"manual": True}) GPIO.setup(PIN_SPRINGKLER, GPIO.OUT) # GPIO Assign mode if nyala: GPIO.output(PIN_SPRINGKLER, GPIO.LOW) # nyala print("Springkler Hidup") else: GPIO.output(PIN_SPRINGKLER, GPIO.HIGH) # mati print("Springkler Mati")
def setRelay(nyala): firebase.patch('/sensor/relay', {"isLoading": False}) GPIO.setup(GPIO_RELAY, GPIO.OUT) # GPIO Assign mode if nyala: GPIO.output(GPIO_RELAY, GPIO.LOW) # nyala print("relay hidup") firebase.patch('/sensor/relay', {"status": True}) else: GPIO.output(GPIO_RELAY, GPIO.HIGH) # mati
def aggiornaFirebase(ultimoPrenotato, analogico, dataOdierna): print('inizio aggiorna') urlUpdate = urlDB + '/' + dataOdierna #ultimoNumeroPrenotato = ultimoNumeroPrenotato+1 print(ultimoPrenotato) resultUltimo = firebase.patch(urlUpdate, data={'ultimoNumeroPrenotato': str(ultimoPrenotato + 1)}) resultAnalogico = firebase.patch(urlUpdate, data={'analogico':str(int(analogico) + 1)}) print (resultUltimo) print(resultAnalogico)
def done(request): global reg_id print(reg_id) global dictimep global temslots global a1 global dictimes global id s = str(id) + '/table' k = s mon = [] tue = [] wed = [] thu = [] fri = [] sat = [] sun = [] for i in a1: s = s + '/' + str(i) print(s) for j in temslots: firebase.patch( s, {j: request.GET[i + '+' + dictimep[temslots.index(j)]]}) s = k reg_id = '/' + str(reg_id) print(reg_id) dic = firebase.get(reg_id, 'table') print(dic) print(temslots) for i in dic.get('mon').values(): mon.append(i) for i in dic.get('tue').values(): tue.append(i) for i in dic.get('wed').values(): wed.append(i) for i in dic.get('thu').values(): thu.append(i) for i in dic.get('fri').values(): fri.append(i) for i in dic.get('sat').values(): sat.append(i) for i in dic.get('sun').values(): sun.append(i) print(wed) return render( request, 'tab.html', { 'mon': mon, 'tue': tue, 'wed': wed, 'thu': thu, 'fri': fri, 'sat': sat, 'sun': sun, 'a1': a1, 'tem': temslots })
def setRelayAir(nyala): firebase.patch('/sensor/relay2', {"manual": True}) GPIO.setup(PIN_AIR, GPIO.OUT) # GPIO Assign mode if nyala: GPIO.output(PIN_AIR, GPIO.LOW) # nyala print("air hidup") else: GPIO.output(PIN_AIR, GPIO.HIGH) # mati print("air mati")
def try_decode(bit_string, roundId): if bit_string in morse_code_lookup.keys(): data = firebase.get('/morse', roundId) s = morse_code_lookup[bit_string] data['input'] = data['input'].encode("utf-8") data['input'] += s firebase.patch('/morse/' + roundId, {'input':data['input']}) data = firebase.get('/morse', roundId) sys.stdout.write(morse_code_lookup[bit_string]) sys.stdout.flush()
def callback(): agent = str(request.form['CallSid']) event = request.form['StatusCallbackEvent'] firebase.patch("/" + str(agent), data={ 'ConferenceSid': request.form['ConferenceSid'], 'StatusCallbackEvent': request.form['StatusCallbackEvent'] }) return '200'
def setRelayPompaB(nyala): PIN_POMPAB = 25 GPIO.setup(PIN_POMPAB, GPIO.OUT) # GPIO Assign mode if nyala: firebase.patch('/sensor/relay1', {"isLoading":False}) GPIO.output(PIN_POMPAB, GPIO.LOW) # nyala print("Pompa B Nyala") else: firebase.patch('/sensor/relay1', {"isLoading":False}) GPIO.output(PIN_POMPAB, GPIO.HIGH) # mati print("Pompa B Mati")
def handle_key(): """Handle key press from a user.""" # Get the digit pressed by the user digit_pressed = request.values.get('Digits', None) if digit_pressed == "1": resp = twilio.twiml.Response() from firebase import firebase firebase = firebase.FirebaseApplication( 'https://smart911.firebaseio.com', None) result1 = firebase.get('/operators', None) for operator in result1: if result1[operator.encode('ascii')]['online'] == True: resp.dial("+" + str(result1[operator.encode('ascii')]['number'])) id = firebase.get('cases/AutoID/value', None) #update case id result2 = firebase.patch( "/operators/" + operator.encode('ascii') + '/case/', {'value': id}) from_number = request.values.get('From', None) new_case = { "EMT": { "location": "", "text": "" }, "id": id, "user": { "imageURL": "", "location": "much location", "phone": from_number } } result3 = firebase.post('/cases', new_case) #increment AutoID by 1 for next case result = firebase.patch('/cases/AutoID', {'value': id + 1}) return str(resp) # If the dial fails: resp.say("Sorry, no operator is available") return redirect("/") # If the caller pressed anything but 1, redirect them to the homepage. else: return redirect("/")
def aggiornaFirebase(ultimoPrenotato, analogico, dataOdierna): print('inizio aggiorna') urlUpdate = urlDB + '/' + dataOdierna #ultimoNumeroPrenotato = ultimoNumeroPrenotato+1 print(ultimoPrenotato) resultUltimo = firebase.patch( urlUpdate, data={'ultimoNumeroPrenotato': str(ultimoPrenotato + 1)}) resultAnalogico = firebase.patch( urlUpdate, data={'analogico': str(int(analogico) + 1)}) print(resultUltimo) print(resultAnalogico)
def check_water(): fitbit_water = "%s%s/foods/log/water/date/today.json" % ( FITIBIT_API, FITBIT_DEV_USER_AC) response = requests.get(fitbit_water, headers={"Authorization": AUTH}) print(response.text) # {"summary":{"water":500},"water":[{"amount":500,"logId":5435932865}]} res_dict = json.loads(response.text) water_ml = res_dict["summary"]["water"] firebase_value = firebase.get("/fitbit/water_ml", None) print("water firebase value: %s" % firebase_value) if firebase_value is None or water_ml > firebase_value: firebase.patch(FIREBASE_URL + '/fitbit', {'water_ml': water_ml})
def main(): from firebase import firebase firebase = firebase.FirebaseApplication('https://libtech-app.firebaseio.com/', None) args = argsFetch() logger = loggerFetch(args.get('log_level')) logger.info('args: %s', str(args)) if args['write']: d={} d=[] d.append({'make':'nd','model':'readyToEat','price':95}) d.append({'make':'sahaja','model':'vegetable','price':55}) d.append({'make':'tvs','model':'fruit','price':195}) with open('first.json', 'w') as outfile: json.dump(d, outfile) if args['populate']: jsonName="districts.json" json_data=open(jsonName,encoding='utf-8-sig').read() d = json.loads(json_data) myDict={} for key,values in d.items(): code=key name=values['name'] parentCode=values['stateCode'] logger.info(key) dictKey="%s_%s_%s" % (code,name,parentCode) myDict[dictKey] = {'name': name, 'code': code, 'parentCode': parentCode, 'slug': dictKey } logger.info(dictKey) result = firebase.patch('https://libtech-app.firebaseio.com/medicines/', myDict) logger.info("...END PROCESSING") exit(0)
def WriteParameters_sync(Parameters): '''Write parameters to file''' for r in Relays: Parameters[r] = G.GetState(r) Parameters['LastWritten'] = time.time() qP.put(Parameters) try: r = firebase.patch('/Parameters', Parameters, params=Params) except: logger.info('Error writing parameters to Firebase') return Parameters
def newDroplet(gh_id=None, int_id=None): if gh_id: firebase.patch('/projects/%s/%s/' % (gh_id, int_id), data={'state': 'Creating droplet'}) project = firebase.get('/projects/%s/%s' % (gh_id, int_id), name=None, params=None) num = random.randint(1111111,9999999) images = {'flask':6219398,'sinatra':6219719,'php':6222492} newdrop = doPost('/droplets', {'name':'%s%s.dep10y.me' % (project['type'],num), 'region':'nyc3', 'image': images[project['type']], 'ssh_keys':[325148], 'size':'512mb'}) if gh_id: firebase.patch('/projects/%s/%s/' % (gh_id, int_id), data={'state': 'Waiting for creation to finish', 'droplet_id':newdrop['droplet']['id']}) time.sleep(30) if gh_id: firebase.patch('/projects/%s/%s/' % (gh_id, int_id), data={'state': 'Setting DNS'}) createdDrop = doGet('/droplets/%s' % newdrop['droplet']['id']) newsets = getRecords() domainset = doNCPost(dict({'Command':'namecheap.domains.dns.setHosts','SLD':'dep10y','TLD':'me','HostName1':'%s%s' % (project['type'],num),'TTL1':'1200','RecordType1':'A','Address1':createdDrop['droplet']['networks']['v4'][0]['ip_address']}.items()+newsets.items())) if gh_id: firebase.patch('/projects/%s/%s/' % (gh_id, int_id), data={'state': 'Running at %s' % createdDrop['droplet']['name']}) return createdDrop
def change_attribute(subject, key, value): try: firebase.patch('/users/' + str(subject), data={key: value}) except Exception as e: print str(e)
def update(zone,firebase): url="ITESM/Zone"+str(zone.getName()) #update busy and update total with zone.getBusy and zone.getTotal firebase.patch(url,{"Busy":zone.getBusy()}) firebase.patch(url,{"Total":zone.getTotal()})
def main(): from firebase import firebase firebase = firebase.FirebaseApplication('https://libtech-app.firebaseio.com/', None) regex=re.compile(r'<input+.*?"\s*/>+',re.DOTALL) args = argsFetch() finyear='17' fullfinyear=getFullFinYear(finyear) logger = loggerFetch(args.get('log_level')) logger.info('args: %s', str(args)) logger.info("BEGIN PROCESSING...") db = dbInitialize(db=nregaDB, charset="utf8") # The rest is updated automatically in the function cur=db.cursor() db.autocommit(True) #Query to set up Database to read Hindi Characters blockCode='005' fullBlockCode='0515005' panchayatCodes="(panchayatCode = '%s' or panchayatCode='%s')" % ('029','034') districtName="muzaffarpur" query="SET NAMES utf8" cur.execute(query) result = firebase.delete('https://libtech-app.firebaseio.com', None) query="select blockName,panchayatName from panchayats where rawDistrictName='%s' and blockCode='%s' and %s " %(districtName,blockCode,panchayatCodes) cur.execute(query) results=cur.fetchall() for row in results: [blockName,panchayatName]=row result = firebase.post('https://libtech-app.firebaseio.com/geo/%s'%(blockName.upper()), {'panchayatName': panchayatName.upper()}) query="select DISTINCT(jobcard),blockName,panchayatName from workDetails where fullBlockCode='%s' and finyear='17' and %s" %(fullBlockCode,panchayatCodes) cur.execute(query) results=cur.fetchall() for row in results: [jobcard1,blockName,panchayatName]=row jobcard=jobcard1.replace("/","_") logger.info(jobcard) result = firebase.post('https://libtech-app.firebaseio.com/jobcard/%s/%s/'%(blockName.upper(),panchayatName.upper()), {'jobcard': jobcard}) # print(result) query="select panchayatName, jobcard, name, musterNo, workName, totalWage, wagelistNo, ftoNo, musterStatus, bankNamePostOffice, date_format(dateTo, '%d-%M-%Y') as dateTo, DATE_FORMAT(firstSignatoryDate, '%d-%M-%Y') as firstSignatoryDate, DATE_FORMAT(secondSignatoryDate, '%d-%M-%Y') as secondSignatoryDate, DATE_FORMAT(transactionDate, '%d-%M-%Y') as transactionDate, DATE_FORMAT(bankProcessedDate, '%d-%M-%Y') as bankProcessedDate, DATE_FORMAT(paymentDate, '%d-%M-%Y') as paymentDate, DATE_FORMAT(creditedDate, '%d-%M-%Y') as creditedDate, ftoMatchStatus, rejectionReason, @varMaxDate:=greatest(COALESCE(dateTo, '1900-01-01 00:00:00'), COALESCE(firstSignatoryDate, '1900-01-01 00:00:00'), COALESCE(secondSignatoryDate, '1900-01-01 00:00:00'), COALESCE(transactionDate, '1900-01-01 00:00:00'), COALESCE(bankProcessedDate, '1900-01-01 00:00:00'), COALESCE(paymentDate, '1900-01-01 00:00:00'), COALESCE(creditedDate, '1900-01-01 00:00:00')) as maxDate, CASE @varMaxDate WHEN dateTo THEN 'dateTo' WHEN firstSignatoryDate THEN 'firstSignatoryDate' WHEN secondSignatoryDate THEN 'secondSignatoryDate' WHEN transactionDate THEN 'transactionDate' WHEN bankProcessedDate THEN 'bankProcessedDate' WHEN paymentDate THEN 'paymentDate' WHEN creditedDate THEN 'creditedDate' END AS maxDateColName from workDetails where fullBlockCode='0515005' and finyear='17' and (panchayatCode='029' or panchayatCode='034') order by dateTo " cur.execute(query) results=cur.fetchall() for row in results: panchayatName = row[0].upper() jobcard = row[1] jobcard = jobcard.replace('/', '_') name = row[2] musterNo = row[3] workName = row[4] totalWage = row[5] wagelistNo = row[6] ftoNo = row[7] musterStatus = row[8] bankNameOrPOName = row[9] dateTo = row[10] firstSignatoryDate = row[11] secondSignatoryDate = row[12] transactionDate = row[13] bankProcessedDate = row[14] paymentDate = row[15] creditedDate = row[16] ftoStatus = row[17] rejectionReason = row[18] maxDate = row[19] maxDateColName = row[20] try: currentStatusOfNode = firebase.get('/data/%s/%s/%s'%(panchayatName, jobcard, dateTo), None) currentNoTransactionsForDate = len(currentStatusOfNode) - 1 newTransactionNo = currentNoTransactionsForDate + 1 except: newTransactionNo = 1 result = firebase.patch('https://libtech-app.firebaseio.com/data/%s/%s/%s/%s'%(panchayatName, jobcard, dateTo, newTransactionNo), {'jobcard': jobcard, 'name': name, 'musterNo': musterNo, 'workName': workName, 'totalWage': totalWage, 'wagelistNo': wagelistNo, 'ftoNo': ftoNo, 'musterStatus': musterStatus, 'bankNameOrPOName': bankNameOrPOName, 'dateTo': dateTo, 'firstSignatoryDate': firstSignatoryDate, 'secondSignatoryDate': secondSignatoryDate, 'transactionDate': transactionDate, 'bankProcessedDate': bankProcessedDate, 'paymentDate': paymentDate, 'creditedDate': creditedDate, 'ftoStatus': ftoStatus, 'rejectionReason': rejectionReason, 'maxDate': maxDate, 'maxDateColName': maxDateColName}) #print(result) dbFinalize(db) # Make sure you put this if there are other exit paths or errors logger.info("...END PROCESSING") exit(0)
def update(threadName,firebase,count): firebase.patch('/ITESM/ZoneB', {'Busy':count})
os.system('clear') print print ' GPS reading' print '----------------------------------------' print 'latitude ' , gpsd.fix.latitude print 'longitude ' , gpsd.fix.longitude print 'time utc ' , gpsd.utc,' + ', gpsd.fix.time print 'altitude (m)' , gpsd.fix.altitude print 'eps ' , gpsd.fix.eps print 'epx ' , gpsd.fix.epx print 'epv ' , gpsd.fix.epv print 'ept ' , gpsd.fix.ept print 'speed (m/s) ' , gpsd.fix.speed print 'climb ' , gpsd.fix.climb print 'track ' , gpsd.fix.track print 'mode ' , gpsd.fix.mode print print 'sats ' , gpsd.satellites result = firebase.patch('trainSystem/vehicles/35',{ 'lat' : gpsd.fix.latitude, 'lon' : gpsd.fix.longitude }) print result time.sleep(3) #set to whatever except (KeyboardInterrupt, SystemExit): #when you press ctrl+c print "\nKilling Thread..." gpsp.running = False gpsp.join() # wait for the thread to finish what it's doing print "Done.\nExiting."
from firebase import firebase firebase = firebase.FirebaseApplication("https://glaring-torch-8449.firebaseio.com/", authentication=None) result = firebase.get("/courses", None) print result # def newUser(response): # print "a new user was created", response # firebase.get_async('/users', None, callback=newUser) users = firebase.get("/users", None) print users path = "/users/" for u in users: url = path + u firebase.patch(url, {"courses": result}) print u
# post = # post = firebase.patch('/experiment2', test) while True: get = firebase.get('/spacegame/hangout2', None) for player in get.keys(): if player == 'target': pass else: get[player]['xpos'] += get[player]['xspeed'] get[player]['ypos'] += get[player]['yspeed'] # print "player ....... " , player # print player # print get[player]['xpos'] # print "player : ", get[player] # print '/spacegame/hangout2/'+player+'/xpos' firebase.patch('/spacegame/hangout2/'+player, get[player]) firebase.patch('/spacegame/hangout2/'+player, get[player]) if get[player]['thrust'] == True: if get[player]['rotate'] == 0 : get[player]['xspeed'] += -5 elif get[player]['rotate'] == 45 : get[player]['xspeed'] += -5 get[player]['yspeed'] += -5 elif get[player]['rotate'] == 90 : get[player]['yspeed'] += -5 elif get[player]['rotate'] == 135 : get[player]['xspeed'] += +5
import serial import pynmea2 from firebase import firebase firebase = firebase.FirebaseApplication('https://boiling-fire-7865.firebaseio.com') serialStream = serial.Serial("/dev/ttyAMA0", 9600, timeout=0.5) while True: sentence = serialStream.readline() if sentence.find('GGA') > 0: data = pynmea2.parse(sentence) print "{time} : {lat},{lon} ".format(time=data.timestamp,lat=data.latitude,lon=data.longitude) result = firebase.patch('trainSystem/vehicles/36',{ 'lat' : data.latitude, 'lon' : data.longitude, 'timestamp' : {'.sv': 'timestamp'} }) print result
def callback(): agent = str(request.form['CallSid']) event = request.form['StatusCallbackEvent'] firebase.patch("/"+str(agent), data={'ConferenceSid': request.form['ConferenceSid'], 'StatusCallbackEvent': request.form['StatusCallbackEvent']}) return '200'
def patch_object(url, data): result = firebase.patch(url, data=data) return result
from firebase import firebase firebase = firebase.FirebaseApplication('https://hekate.firebaseio.com', None) # results = firebase.get("hekate", None) firebase.patch("User1", {"ping": "168.168.1.1"}) # firebase.delete("Commands", 'cmd') # firebase.delete("Commands", 'Ping') def shownewentry(results): print(results) # firebase.on("child_added", shownewentry(snapshot))
from firebase import firebase import json as simplejson firebase = firebase.FirebaseApplication('https://blistering-fire-6119.firebaseio.com',None) result = firebase.get('/users',None) print result location_1 = 'Avaliable' location_2 = 'Not avaliable' name = {'Morningside_dr':location_1, "123st":location_2} #data = json.dumps(name) #URL = 'https://blistering-fire-6119.firebaseio.com/users' #print firebase.get(URL) a = firebase.patch('/status',name) #post = firebase_.post('/users',name) #print post
import os from azure.servicebus import ServiceBusService, Message, Topic, Rule, DEFAULT_RULE_NAME from firebase import firebase import json ns_key = os.environ.get('NS_KEY') firebase = firebase.FirebaseApplication('https://logbasedev.firebaseio.com/', None) bus_service = ServiceBusService( service_namespace='onroad-ns', shared_access_key_name='RootManageSharedAccessKey', shared_access_key_value=ns_key) while True: msg = bus_service.receive_subscription_message('onroad-topic', 'locations', peek_lock=False) if msg.body: for event in json.loads(msg.body): new_location = {'latitude':event['lat'], 'longitude':event['long'], 'locationtime':event['time']}; #TODO: Remove device hardcoding firebase.patch('/account/simplelogin:2/livecars/0', new_location)