def otazkaNETblika(): log.debug("Blika NET (sim registrovana)?") #vyprazdni queue if ZP.netBlika_queue.full(): ZP.netBlika_queue.get() try: serialPort.write(b'AT+CREG?\r\n') q_get = ZP.netBlika_queue.get(timeout=7) if q_get == 1: #cakam na odpoved, do 10 sekund log.debug("Net blika - home network") return True elif q_get == 5: #cakam na odpoved, do 10 sekund log.debug("Net blika - roaming network") return True elif q_get == 2: #cakam na odpoved, do 10 sekund log.error("Net neblika - hlada siet ...") return 2 elif q_get == 3: #cakam na odpoved, do 10 sekund log.error("Net neblika - registracia zamietnuta") return False elif q_get == 4: #cakam na odpoved, do 10 sekund log.error("Net neblika - neznamy problem") return False else: log.error("serialRead nevratil co bolo ocakavane.") return False except: log.error("serialRead neodpovedal nacas!") return False
def cistyCipshut(): try: #funguje len ak bezi thread serialRead() #CIPSHT: #najprv vymaz queue if queueVypni.full(): queueVypni.get() serialPort.write(prikazyNaVypni[1]) try: if queueVypni.get(timeout=4) == 'cipshutOK': log.info("AT+CIPSHUT > SHUT OK.") return 0 else: log.error( "postup nebol dodrzany alebo sa vyskytla chyba, restartuj internet" ) return 1 except: log.error("Nepodarilo sa.") return 1 except queue.Empty: log.exception("serialRead neodpovedal nacas!") except: log.exception("EXCEPTION!")
def zacniBlikat(verzieBlikania): #zaregistruj sa na siet #verzieBlikania su True/False/2 if verzieBlikania == True: return 0 elif verzieBlikania == 2: log.debug("Zda sa, ze siet sa pripaja, cakam par sekund.") time.sleep(7) #pockaj par sekund a snad uz to bude ok return 0 elif verzieBlikania == False: log.error("Nepodarilo sa pripojit na operator <=> NET neblika pomaly.") return 1
def pripojAdapter(): #len pri zapnuti RPI global serialPort try: #v pripade ze subor /dev/ttyUSB* chyba, restaruj USB porty resp. RPI adapterFile = os.popen('ls /dev/ttyUSB*').readlines()[0][:-1] serialPort = serial.Serial(adapterFile, 115200) log.debug("Pripojil som adapter.") ZP.event_cakajNaPripojenie.set() # time.sleep(2) return 0 except: serialPort = None log.exception("EXCEPTION!") log.error("Adapter sa nepodarilo pripojit!") return 1
def posliSpravu(response): #this function, in order to work properly, has to follow prijmiSpravu() function in serial logic for pocetZlyhani in range(3): try: #initiate sending: serialPort.write(prikazyPosliSpravu[0]) #cakaj na ODOSIELANIE: if queueSocket.get(timeout=10) == 'cipsendOK': serialPort.write(bytes(response, 'utf-8') + b'\x1a\r\n') else: log.error("Serial neprijal spravu na odoslanie.") return 1 #AdapterManager o tom upozorni ale tento pripad zatial ignorujeme. #cakaj na SEND OK: if queueSocket.get(timeout=10) == 'sendOK': log.info("Sprava odoslana.")\ #serialPort.write(prikazyPosliSpravu[1]) #ignoruj, socket sa zatvara automaticky else: log.critical( "Serial odpoved na odoslanie spravy je necakana. SERVER neodpoveda?!" ) return 1 #AdapterManager o tom upozorni ale tento pripad zatial ignorujeme. #cakaj na closed: if queueSocket.get(timeout=10) == 'closed': log.debug("Socket closed.") cistyCipshut() else: log.warning("Socket closed didn't work but I ignore it.") #ak nenastal problem, return 0: return 0 #message was sent at this point except queue.Empty: if pocetZlyhani >= 2: #only when we tried 3 times, restart adapter ZP.adapterJob_prioDeq.put( 'pwrKeyAdapter', delete=False ) #keep other jobs pending as we are just fixing something return 1 #AdapterManager o tom upozorni ale tento pripad zatial ignorujeme. log.exception( "Spravu sa asi nepodarilo odoslat - serial neodpoveda. Pokus " + str(pocetZlyhani) + "/3. Potom restartujem.")
def otazkaSignalOk(): log.debug("Signal ok?") if queueSignal.full(): queueSignal.get() try: serialPort.write(b'AT+CSQ\r') q_get = queueSignal.get(timeout=5) specialne.ulozSiluSignalu(q_get) if type(q_get) is int: if q_get in [0, 99]: log.error("Ziaden signal!") return False elif q_get in [1, 2, 3, 4]: log.debug("Slaby signal: " + str(q_get)) return True else: log.debug("Sila signalu dostacujuca: " + str(q_get)) return True else: log.error("Serial vratil chybu!") return False except: log.error("serialRead neodpovedal nacas!") return False
def vypniInternet(): try: #funguje len ak bezi thread serialRead() #VYPNI INTERNET: #najprv vymaz queue if queueVypni.full(): queueVypni.get() log.info("Vypinam internet...") serialPort.write(prikazyNaVypni[0]) try: if queueVypni.get(timeout=3) == 'cipcloseOK': log.debug("cipclose OK") serialPort.write(prikazyNaVypni[1]) #cipshut else: log.error( "A postup nebol dodrzany alebo sa vyskytla chyba, restartuj internet" ) return 1 except: log.error("Nepodarilo sa.") return 1 try: if queueVypni.get(timeout=5) == 'cipshutOK': log.info("AT+CIPSHUT > SHUT OK.") return 0 else: log.error( "postup nebol dodrzany alebo sa vyskytla chyba, restartuj internet" ) return 1 except: log.error("Nepodarilo sa.") return 1 except queue.Empty: log.exception("serialRead neodpovedal nacas!") except: log.exception("EXCEPTION!")
def prijmiSpravu(): global prijataSpravaOsekana for pocetZlyhani in range( 3 ): #normally there is just one loop because there a return statement appears. try: prijataSpravaOsekana = 1 #prepare to return 1 in case serialRead didn't read any better value for the message if queueSocket.full(): queueSocket.get() log.debug("Prijmam spravu...") #initiate connection serialPort.reset_input_buffer() serialPort.write(prikazyPrijmiSpravu[0]) q_get = queueSocket.get( timeout=10 ) #raises queue.Empty when serialRead doesnt reply and we run another loop of this function if q_get == 'cipstartOKspravaPrijata': prijataSprava = prijataSpravaOsekana return prijataSprava elif q_get == 'alreadyConnect': ZP.troubleMonitor.alreadyConnect_addCount() log.error("Already connected.") return 1 #this return will make manager redo 'posta' work but only if above count is not exceeded. elif q_get == 'serverUnreachable': ZP.troubleMonitor.serverUnreachable_addCount() log.error("Server unreachable.") return 2 #this return will make manager redo 'posta' work but only if above count is not exceeded. else: log.error("Vyskytla sa neznama chyba, restartujem internet!") return 1 #this can be repeating infinitelly as long as serialRead doesnt get fixed. I expect this to not happen. except queue.Empty: if pocetZlyhani >= 2: #only when we tried 3 times, restart adapter ZP.adapterJob_prioDeq.put( 'pwrKeyAdapter', delete=False ) #keep other jobs pending as we are just fixing something return 1 #this can be repeating infinitelly as long as serialRead doesnt get fixed. I expect this to not happen. log.exception( "Spravu sa asi nepodarilo PRIJAT - serial neodpoveda. Pokus " + str(pocetZlyhani) + "/3. Potom restartujem.")
def zapniInternet(): global internetByMalBytPripraveny try: #funguje len ak bezi thread serialRead() #ZAPNI INTERNET if queueZapni.full(): queueZapni.get() log.info("Zapinam internet...") serialPort.write(prikazyNaZapni[0]) if queueZapni.get(timeout=5) == 'csttOK': serialPort.write(prikazyNaZapni[1]) else: log.error( "postup nebol dodrzany alebo sa vyskytla chyba, restartuj internet" ) return 1 if queueZapni.get(timeout=5) == 'ciicrOK': serialPort.write(prikazyNaZapni[2]) else: log.error( "postup nebol dodrzany alebo sa vyskytla chyba, restartuj internet" ) return 1 if queueZapni.get(timeout=5) == 'cifsrOK': log.info("Internet zapnuty!") internetByMalBytPripraveny = True return 0 else: log.error( "postup nebol dodrzany alebo sa vyskytla chyba, restartuj internet" ) return 1 except queue.Empty: log.exception("serialRead neodpovedal nacas!") except: log.exception("EXCEPTION!")
def read(): novyRiadok = b'' CastSpravy = None serverUnreachable_count = 0 while True: try: ZP.event_cakajNaPripojenie.wait() predoslyRiadok = novyRiadok novyRiadok = worker.serialPort.readline() logSerial.debug('line: ' + str(novyRiadok)) #SIGNAL OK? najdi = re.search(r'b\'\+CSQ: (\d+),', str(novyRiadok)) if najdi != None: try: signal = int(najdi.group(1)) except: worker.queueSignal.put("CHYBA") log.error("SerialRead nacital neznamu hodnotu signalu: " + str(najdi.group(1))) else: if signal < 100: worker.queueSignal.put(signal) if b'+CSQ: 15,0' in novyRiadok: worker.queueSignal.put() #NET BLIKA? if b'AT+CREG?' in predoslyRiadok: if b'+CREG: 0,1' in novyRiadok: #registered, home network ZP.netBlika_queue.put(1) elif b'+CREG: 0,2' in novyRiadok or b'+CREG: 0,0' in novyRiadok: #Not registered, but MT is currently searching a new operator to register to ZP.netBlika_queue.put(2) elif b'+CREG: 0,3' in novyRiadok: #registration denied ZP.netBlika_queue.put(3) elif b'+CREG: 0,4' in novyRiadok: #unknown ZP.netBlika_queue.put(4) elif b'+CREG: 0,5' in novyRiadok: #registered, roaming ZP.netBlika_queue.put(5) else: log.error("CHYBA: cgreg odpoved:" + str(novyRiadok)) #ODPOVEDA? if b'AT\r' in predoslyRiadok and b'OK\r' in novyRiadok: ZP.adapterOdpoveda_queue.put(1) #VYPNI internet: #CIPCLOSE if b'AT+CIPCLOSE' in predoslyRiadok: #-2 pretoze serial sam prida dva znaky do vystupu if (b'OK' in novyRiadok or b'ERROR' in novyRiadok): logSerial.debug("cipclose OK") worker.queueVypni.put('cipcloseOK') else: log.error("CHYBA: cipclose odpoved:" + str(novyRiadok)) worker.queueVypni.put('chyba') #CIPSHUT if b'AT+CIPSHUT' in predoslyRiadok: #-2 pretoze serial sam prida dva znaky do vystupu if (b'SHUT OK' in novyRiadok): logSerial.debug("cipshut OK") worker.queueVypni.put('cipshutOK') else: log.error("CHYBA: cipshut odpoved:" + str(novyRiadok)) worker.queueVypni.put('chyba') #PDP DEACT problem #tento problem podla mna nastava ked nevypnem poriadne internet pred vypnutim RPI. #to by sa nemalo stavat ak do toho nekafrem pri debugovani #nie celkom slusny pokus o vyriesenie problemu s +pdp deact po cipshut prikaze # if (b'+PDP: DEACT' in novyRiadok): # print ("PDP FOUND") # worker.queueVypni.put('pdpDeactProblem') #CIPSTATUS: if (b'STATE:' in novyRiadok): if (b'STATE: IP INITIAL' in novyRiadok): worker.queueZapni.put('IP INITIAL') elif (b'STATE: IP STATUS' in novyRiadok): worker.queueZapni.put('IP STATUS') # elif (b'STATE: TCP CLOSED' in novyRiadok): # worker.queueZapni.put('TCP CLOSED') else: log.error("CHYBA: CIPSTATUS odpoved:" + str(novyRiadok)) worker.queueZapni.put('chyba') #ZAPNI internet: #CSTT if worker.prikazyNaZapni[ 0] in predoslyRiadok: #-2 pretoze serial sam prida dva znaky do vystupu if (b'OK' in novyRiadok): worker.queueZapni.put('csttOK') else: log.error("CHYBA: CSTT odpoved:" + str(novyRiadok)) worker.queueZapni.put('chyba') #CIICR if worker.prikazyNaZapni[ 1] in predoslyRiadok: #-2 pretoze serial sam prida dva znaky do vystupu if (b'OK' in novyRiadok): worker.queueZapni.put('ciicrOK') else: log.error("CHYBA: CIICR odpoved:" + str(novyRiadok)) worker.queueZapni.put('chyba') #CIFSR if worker.prikazyNaZapni[ 2] in predoslyRiadok: #-2 pretoze serial sam prida dva znaky do vystupu if re.search(r'b\'\d+.\d+.\d+.\d+', str(novyRiadok)) != None: worker.queueZapni.put('cifsrOK') else: log.warning("CHYBA: CIFSR odpoved:" + str(novyRiadok)) worker.queueZapni.put('chyba') #SOCKET: if b'ALREADY CONNECT' in novyRiadok: worker.queueSocket.put('alreadyConnect') if b'CONNECT FAIL' in novyRiadok: worker.queueSocket.put('serverUnreachable') if b'CONNECT OK' in predoslyRiadok and b'STATE:' not in predoslyRiadok: #reset counters since connection was successful ZP.troubleMonitor.alreadyConnect_resetCount() ZP.troubleMonitor.serverUnreachable_resetCount() dlzSpravy_code = novyRiadok[:2] #2byte dlzSpravy_int = ZP.CODE.index(dlzSpravy_code.decode()) if dlzSpravy_int == 0: #server nema ziadnu spravu od androidu, poslal default: b'\x00\x00\x00\x00' worker.prijataSpravaOsekana = '00' else: #nacitaj prijatu spravud worker.prijataSpravaOsekana = novyRiadok.decode()[:-2] log.debug("prijataSprava " + str(worker.prijataSpravaOsekana)) worker.queueSocket.put('cipstartOKspravaPrijata') #CIPSEND, ak dostanes cerstvu poziadavnku na odosielanie tak len pockaj chvilu a daj zelenu: if worker.prikazyPosliSpravu[0] in novyRiadok: time.sleep(0.3) worker.queueSocket.put('cipsendOK') if b'SEND OK' in novyRiadok: worker.queueSocket.put( 'sendOK' ) #put sendOK just now so that Socket() reads message just now if b'CLOSED' in novyRiadok and b'TCP CLOSED' not in novyRiadok and b'CLOSE OK' not in novyRiadok and b'STATE:' not in novyRiadok: #TCP CLOSED is when connection fails. we dont want to mistaken it for successful communication (CLOSED) worker.queueSocket.put('closed') time.sleep(0.01) except AttributeError: log.error("SerialRead hlasi nepripojeny adapter! (ser == None)") ZP.event_cakajNaPripojenie.clear() except serial.serialutil.SerialException: log.error( "SerialRead hlasi nepripojeny adapter! (SerialException)") ZP.event_cakajNaPripojenie.clear() except: if datetime.datetime.now().microsecond % 999000 == 0: log.exception("serialRead problem!") else: pass
def otazkaPripravenyNaSpojenie(): global internetByMalBytPripraveny #otazka: AT+CIPSTATUS #odpoved: STATE: TCP CLOSED je status po uspesnej komunikacii (odoslanej sprave) #odpoved: STATE: CONNECT OK je status po cerstom cipstart pripojeni (po prijati spravy) na server pred odoslanim spravy #odpoved: STATE: IP INITIAL je pred spustenim internetu (=cerstvy adapter pred AT+CSTT>AT+CIICR>AT+CIFSR procedurou) # je aj po CIPSHUT ale po procedure AT+CSTT>AT+CIICR>AT+CIFSR #odpoved: STATE: IP STATUS je zapnuty internet (cifsr odpoved je IPcka) = pripraveny na AT+CIPSTART komunikaciu so serverom #odpoved: STATE: IP START je ked je cstt o2internet ale ciicr este nie je nic #odpoved: STATE: IP GPRSACT je ked je ciicr OK (po cstt) ale cisfr este nie je nic # cipshut je recommended pred cipstart stale ak status nie je IP STATUS / IP INITIAL #vyprazdni queue log.debug("Zapnuty internet?") if queueZapni.full(): queueZapni.get() try: serialPort.write(b'AT+CIPSTATUS\r') q_get = queueZapni.get(timeout=5) if q_get == "IP STATUS": log.debug( "Internet zapnuty. status: IP STATUS (pripraveny na komunikaciu CIPSTART)" ) return True if q_get == "IP INITIAL": log.debug("status: IP INITIAL") # log.debug("INTERNET PRIPRAVENY VARIABLE: " + str(internetByMalBytPripraveny)) if internetByMalBytPripraveny == True: #ak si uz zapinal internet (stane sa pri spusteni RPI) tak vrat true a ani sa nepytaj na cifsr nech nezatazujeme adapter pri kazdej sprave return True #ak by to bol problem (co by standardne nemal) tak ten sa vyriesi nejak sam v druhom pokuse serialPort.write(b'AT+CIFSR\r') if queueZapni.get( timeout=5 ) == "cifsrOK": #ak nevrati cifsrOK, tak sa dostaneme dole restartujeme internet log.debug("Internet zapnuty. AT+CIFSR vratil IP") return True # if q_get == "TCP CLOSED": # log.debug("Internet zapnuty. status: TCP CLOSED (predosla komuniakcia prebehla uspesne).\ # Riskujem lebo v manualy nie je explicitne uvedene, ze tento status je ok na nasledny CIPSTART.") # return True #return false vo vsetkych pripadoch okrem IP STATUS a IP INITIAL + CIFSR OK. Pretoze aj ked je mozno internet pripojeny, #nie sme v spravnom stave (ako je uvedene v manuale) vypniInternet( ) #toto je poistka pre PDP DEACT problem. v inych pripadoch by stacilo raz. #vypniInternet je lepsie ako priamo volat CIPSHUT lebo skript v druhom pripade necaka na odpoved a prepisuje adapter halabala. return False #teraz ocakavam, ze volajuca funkcia zavola AT+CIPSHUT + zapniInternet() #STARE: # try: # serialPort.write(b'AT+CIFSR\r') # if queueZapni.get(timeout = 5) == "cifsrOK": # log.debug("Internet zapnuty") # return True # else: # log.warning("Internet nie je zapnuty.") # return False except: log.error("serialRead neodpovedal nacas!") return False
def praca(): #spusti serial reader v predstihu: threading.Thread(target=reader.read, name='serialRead', daemon=True).start() pocet_pokusov = 3 while True: try: q_get = ZP.adapterJob_prioDeq.get() log.info("pracujem na: '" + str(q_get) + "', zbytok Q:" + str(ZP.adapterJob_prioDeq.deqList)) if q_get == 'pripojAdapter': worker.pripojAdapter() assistant.zarucOdpAPripojenie() elif q_get == 'restartujInternet': worker.restartujInternet() elif q_get == 'telefonuj': #ak sa nepodari ani pripravit telefonovanie tak ho urcite vloz naspat do queue if assistant.pripravTelefonovanie() == 0: #telefonuj: #a v pripade, ze sa nepodari tak vloz telefonovanie naspat do queue if worker.telefonuj() == 1: ZP.adapterJob_prioDeq.put('telefonuj') else: ZP.adapterJob_prioDeq.put('telefonuj') elif q_get == 'posta': ZP.AdapterNeodosielaSpravu = False assistant.pripravOdosielanie() prijataSprava = worker.prijmiSpravu() #neosekana #if no new instructions were received, just reply with current KonfigD if prijataSprava == 1: log.error( "Sprava neodoslana (server prestal reagovat alebo AlreadyConnect error). Restartujem internet !" ) if (ZP.troubleMonitor.alreadyConnect_tryAgain ): #try again if required. log.error( "Novy pokus cislo" + str(ZP.troubleMonitor.alreadyConnect_count) + "/" + str(ZP.troubleMonitor.alreadyConnect_MAXcount)) #restartuj internet kedze alreadyConnect sa len tak nevyriesi.. ZP.adapterJob_prioDeq.put( 'restartujInternet', delete=False ) #do not delete other jobs - keep them pending as we are just fixing something if specialne.MessageNotInAdapterQueue(): ZP.adapterJob_prioDeq.put("posta") else: log.error( "Pocet pokusov vyprsal. Pravdepodobne nie je server vobec dostupny. Nastavujem informovanie na minimalne 3 min." ) #load the property, it will be used at the beginning of the next main run ZP.troubleMonitor.konfigD_modifiedProperties = ZP.troubleMonitor.alreadyConnect_konfigD ZP.troubleMonitor.alreadyConnect_tryAgain = True #(reset) opakuj pokusy pri dalsich korespondenciach elif prijataSprava == 2: log.error("Sprava neodoslana (server unreachable) !") if (ZP.troubleMonitor.serverUnreachable_tryAgain ): #try again if required. log.error( "Novy pokus cislo" + str(ZP.troubleMonitor.serverUnreachable_count) + "/" + str(ZP.troubleMonitor.serverUnreachable_MAXcount)) if specialne.MessageNotInAdapterQueue(): ZP.adapterJob_prioDeq.put("posta") else: log.error("Pocet pokusov vyprsal, vzdavam to!") ZP.troubleMonitor.serverUnreachable_tryAgain = True #opakuj pokusy pri dalsich korespondenciach elif prijataSprava == None: log.critical( "Socket vratil prijatu spravu NONE, skontroluj co to je za problem." ) else: if len( prijataSprava ) < 6: #no new instructions is something like this b'\x00\x00\r\n' log.debug("Neprisla sprava.") prijataSprava = None #neviem uz preco... odpoved = korespondencia.sformulujOdpoved(ZP.konfigD) #if new instructions were received, reply with updated konfigD(dummy for this moment) first. else: log.debug("Prijata sprava zpracovana: " + str(prijataSprava)) prijataSprava_obj = korespondencia.Rozbal( prijataSprava) #ak prisla sprava, zapis konfigy do txt a z toho txt nacitaj premenne. Nenacitavaj premenne znova v kazdom While loope ale len ak prisla sprava. #nacitaj ZP.konfigD a odpocetD (ak neprisla sprava tak nastavenia su 1.defaultne alebo 2.relax mod) print("ZP.konfigD PRED:", ZP.konfigD) konfigD_dummy = specialne.aktualizujKonfigDSpravou( prijataSprava_obj) print("konfigD_dummy", konfigD_dummy) print("ZP.konfigD PO:", ZP.konfigD) with ZP.prijataSprava_dequelock: ZP.prijataSprava_deque.append( (prijataSprava_obj, konfigD_dummy)) #loguj data z prijatej spravy log.info("Prijata sprava!: "+ " " + str(prijataSprava_obj.intervalMerTep) + " " + str(prijataSprava_obj.intervalMerGps) + " " + str(prijataSprava_obj.intervalInfTep) \ + " " + str(prijataSprava_obj.intervalInfGps) + " " + str(prijataSprava_obj.tolerLow) + " " + str(prijataSprava_obj.tolerHigh) + " " + str(prijataSprava_obj.onOffAlarmPark) + " " + str(prijataSprava_obj.aktBoxy)) odpoved = korespondencia.sformulujOdpoved( konfigD_dummy) if worker.posliSpravu(odpoved) == 1: log.critical( 'Nepodarilo sa odoslat spravu. Necakana chyba!') else: pass #odosle spravu ZP.AdapterNeodosielaSpravu = True elif q_get == 'pripravOdosielanie': assistant.pripravOdosielanie() elif q_get == 'pripravTelefonovanie': assistant.pripravTelefonovanie() elif q_get == 'vypniInternet': #nie je treba sa ani pytat, proste to skus worker.vypniInternet() elif q_get == 'pwrKeyAdapter': worker.pwrKeyAdapter() worker.pripojAdapter() except: pocet_pokusov -= 1 if pocet_pokusov == 0: log.exception( "AdapterManager zlyhal vela krat, restartujem ho!") ZP.adapterJob_prioDeq.put( 'pwrKeyAdapter', delete=False ) #keep other jobs pending as we are just fixing something pocet_pokusov = 3 else: log.exception("Adapter zlyhal, restartujem po dalsich " + str(pocet_pokusov) + " zlyhaniach.")