Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- import serial
- import json
- import requests
- import serial
- from ControllerState import ControllerState
- Test = serial.Serial("COM3",9600,timeout=0.2)
- BASE_PROGFERT = 1600 + 8192
- BASE_PROGRIEGO = 0 + 8192
- BASE_CONFIGINYECTORES = 1960 + 8192
- DIRTY_ADD = 4234
- URL_SERVER = 'http://emiliozelione2018.pythonanywhere.com/'
- USERNAME = "Prueba1"
- PASSWORD = "goldfinger"
- TIME_UPDATE = 2
- FILEPATH_SAVE = "controller.bin"
- def fetchJson():
- response = requests.get(
- URL_SERVER + 'requests?all&username=' + USERNAME +
- '&password=' +
- PASSWORD)
- dataJson = response.json()
- return(dataJson)
- def fetchLastUpdate():
- response = requests.get(
- URL_SERVER +
- 'requests?updated_when&username=' +
- USERNAME +
- '&password=' +
- PASSWORD)
- dataJson = response.json()
- return(dataJson['update'])
- def checkLogin():
- response = requests.get(
- URL_SERVER +
- 'login?username=' +
- USERNAME +
- '&password=' +
- PASSWORD)
- dataJson = response.json()
- return(dataJson['ok'])
- def readDirty():
- print(readRegisters(DIRTY_ADD,1))
- def readRegisters(Add,nRegs):
- byteList=[]
- AddH = int(Add/256)
- AddL = Add % 256
- Encabezado = [1, 3, AddH, AddL, 0, nRegs] # Son 1Registros
- # Tengo la lista en bytes, Aplicar los CRC
- byteList = Encabezado + byteList
- listaCRC = Calcular_CRC(byteList)
- byteList = byteList+listaCRC # Le agrega los bytes de CRC
- incoming = []
- Total_in = nRegs*2+5
- while(len(incoming)<(Total_in)):
- Test.write(byteList)
- Test.flush()
- incoming = Test.read(Total_in)
- BytesIn = BytesToInteger(incoming)
- print("Bytes Leidos "+str(BytesIn))
- CRC_in = BytesIn[(Total_in-2):Total_in]
- print("CRC_in " +str(CRC_in))
- del BytesIn[-2:] # borra los 2 ultimos elementos
- listaCRC = Calcular_CRC(BytesIn)
- print("Lista CRC " +str(listaCRC))
- if(listaCRC==CRC_in):
- del BytesIn[0:3] # borra del 0 al 3 no inclusive
- return BytesIn
- else:
- return None
- def readFromcontrollerConfigIny(ci):
- FertProg =cs.allFertilization[pf]
- print("Prog Fertilizacion " +str(pf))
- Add = BASE_PROGFERT + (pf-1)*18
- byteList=[]
- byteList=readRegisters(Add,9)
- print(byteList)
- def readFromcontrollerPFert(pf):
- FertProg =cs.allFertilization[pf]
- print("Prog Fertilizacion " +str(pf))
- Add = BASE_PROGFERT + (pf-1)*18
- byteList=[]
- byteList=readRegisters(Add,9)
- print(byteList)
- i = 0
- Val = [0]*10
- while(i < 8):
- Val[i] = (byteList[2*i]*256+byteList[2*i+1])
- i = i+1
- Val[8] = byteList[16]/10
- Val[9] = byteList[17]/10
- print("La lista Val " + str(Val))
- def readFromcontrollerPRiego(pr):
- ProgRiego = cs.allIrrigation[pr]
- print("Prog Riego " +str(pr))
- Add = BASE_PROGRIEGO + (pr-1)*32
- listaA = readRegisters(Add,8)
- print(listaA)
- ProgRiego.water_total_1=listaA[0]
- ProgRiego.water_total_2=listaA[1]
- ProgRiego.water_before_1=listaA[2]
- ProgRiego.water_before_2=listaA[3]
- ProgRiego.water_after_1=listaA[4]
- ProgRiego.water_after_2=listaA[5]
- ProgRiego.time_between_1=listaA[6]
- ProgRiego.time_between_2=listaA[7]
- ProgRiego.time_start_1=listaA[8]
- ProgRiego.time_start_2=listaA[9]
- ProgRiego.units=listaA[10]
- ProgRiego.fertilization_program=listaA[11]
- ProgRiego.kicks=listaA[12]
- ProgRiego.condition_program=listaA[13]
- Add = BASE_PROGRIEGO + (pr-1)*32 +16
- listaB = readRegisters(Add,8)
- print(listaB)
- del listaB[0:5] # borra del 0 al 5 no inclusive
- ProgRiego.valves= DecoValves(listaB)
- print(ProgRiego.valves)
- def DecoValves(ListaValves):
- CantValv = 0
- CadValv = ""
- i = 0
- while(i < 9): # Registros
- j = 0
- while(j < 8): # bits
- peso = ListaValves[i] & (2**j)
- valv = (i*8)+j+1
- if(peso != 0):
- if(CantValv == 0):
- CadValv = str(valv)
- else:
- CadValv = CadValv + ',' + str(valv)
- CantValv = CantValv+1
- j = j+1
- i = i+1
- return(CadValv)
- def writeRegisters(Add,nRegs,byteList):
- AddH = int(Add/256)
- AddL = Add % 256
- Encabezado = [1, 16, AddH, AddL, 0,nRegs,nRegs*2]
- byteList = Encabezado + byteList
- listaCRC = Calcular_CRC(byteList)
- byteList = byteList+listaCRC
- # Le agrega los bytes de CRC
- incoming = []
- Total_in = 8
- # Cuando Escribis Recibis 8 Bytes Fijos
- while(len(incoming)<(Total_in)):
- Test.write(byteList)
- Test.flush()
- incoming = Test.read(Total_in)
- BytesIn = BytesToInteger(incoming)
- print(BytesIn)
- CRC_in = BytesIn[(Total_in-2):Total_in]
- print(CRC_in)
- del BytesIn[-2:] # borra los 2 ultimos elementos
- listaCRC = Calcular_CRC(BytesIn)
- print(listaCRC)
- print(" incoming : "+str(len(incoming)))
- if(listaCRC==CRC_in):
- return True
- else:
- return False
- def writeTocontrollerConfigIny(iny):
- byteList = []
- Inyector = cs.allInyection[iny]
- CaudMaxVenturi = Inyector.flow
- TON = Inyector.time_on
- mlPulse = Inyector.litres_pulse
- MaxDesvio = Inyector.max_deviation
- Simular = Inyector.simulator
- print(Inyector)
- byteList.insert(0,int(iny))
- byteList.insert(1,int(CaudMaxVenturi/256))
- byteList.insert(2,int(CaudMaxVenturi % 256))
- byteList.insert(3,int(TON))
- byteList.insert(4,int(mlPulse/256))
- byteList.insert(5,int(mlPulse % 256))
- byteList.insert(6,int(Simular))
- byteList.insert(7,int(MaxDesvio))
- Add = BASE_CONFIGINYECTORES+(iny-1)*8
- print("Config Iny :"+str(iny))
- print(byteList)
- print(writeRegisters(Add,4,byteList))
- def writeTocontrollerPRiego(pr):
- byteList = []
- ProgRiego = cs.allIrrigation[pr]
- lista_Valv = ProgRiego.valves.split(',')
- print(type(lista_Valv[0]))
- print("Lista Valvulas " + str(lista_Valv))
- RegistrosValvulas = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
- i = 0
- for elem in lista_Valv:
- bit = (int(elem)-1) % 8
- indice = int((int(elem)-1)/8)
- RegistrosValvulas[indice] = RegistrosValvulas[indice] | (2**bit)
- i = i+1
- i = 0
- byteList.insert(0,ProgRiego.water_total_1)
- byteList.insert(1,ProgRiego.water_total_2)
- byteList.insert(2,ProgRiego.water_before_1)
- byteList.insert(3,ProgRiego.water_before_2,)
- byteList.insert(4,ProgRiego.water_after_1)
- byteList.insert(5,ProgRiego.water_after_2)
- byteList.insert(6,ProgRiego.time_between_1)
- byteList.insert(7,ProgRiego.time_between_2)
- byteList.insert(8,ProgRiego.time_start_1)
- byteList.insert(9,ProgRiego.time_start_2)
- byteList.insert(10,ProgRiego.units)
- byteList.insert(11,ProgRiego.fertilization_program)
- byteList.insert(12,ProgRiego.kicks)
- byteList.insert(13,ProgRiego.condition_program)
- byteList.insert(14, 0) # Domingo
- byteList.insert(15, 0) # Lunes
- Add = BASE_PROGRIEGO + (pr-1)*32
- print(writeRegisters(Add,8,byteList))
- byteList = []
- byteList.insert(0, 0) # Martes
- byteList.insert(1, 0) # Miercoles
- byteList.insert(2, 0) # Jueves
- byteList.insert(3, 0) # Viernes
- byteList.insert(4, 0) # Sabado
- i = 0
- while(i < 10):
- byteList.append(RegistrosValvulas[i])
- i = i+1
- byteList.append(0) # Campo Reservado
- Add = BASE_PROGRIEGO+(pr-1)*32+16
- print(writeRegisters(Add,8,byteList))
- def sendServer():
- return None
- def writeTocontrollerPFert(pf):
- FertProg = cs.allFertilization[pf]
- print("Programa de Ferti "+str(pf))
- newList = []
- byteList = []
- newList.append(int(FertProg.values_1))
- newList.append(int(FertProg.values_2))
- newList.append(int(FertProg.values_3))
- newList.append(int(FertProg.values_4))
- newList.append(int(FertProg.values_5))
- newList.append(int(FertProg.values_6))
- newList.append(int(FertProg.values_7))
- newList.append(int(FertProg.values_8))
- EC = FertProg.ec *10
- pH = FertProg.ph *10
- newList.append(int(EC)*256+int(pH))
- print("newlist "+str(newList))
- i = 0
- for elem in newList:
- byteList.append(int(newList[i]/256))
- byteList.append(newList[i] % 256)
- i = i+1
- Add = BASE_PROGFERT+(pf-1)*18
- print("Direccion " +str(Add))
- print("byteList :"+str(byteList))
- print(writeRegisters(Add,9,byteList))
- def Calcular_CRC(listCRC):
- i = 0
- rot = 0
- result = 0xFFFF
- while(i < len(listCRC)):
- result = result ^ listCRC[i]
- while(rot < 8):
- if(result & 0x0001) == 1:
- result = result >> 1
- result = result ^ 0xA001
- else:
- result = result >> 1
- rot = rot + 1
- rot = 0
- i = i+1
- CRCH = int(result/256)
- CRCL = result % 256
- listCRC = [CRCL, CRCH]
- return(listCRC)
- def BytesToInteger(stream):
- bytes_in = []
- a = 0
- for b in stream:
- bytes_in.append(int(hex(stream[a]), 16))
- a = a+1
- return(bytes_in)
- correctLogin = False
- cs = ControllerState.load_from_file(FILEPATH_SAVE)
- if cs == None:
- cs = ControllerState()
- # c.save_to_file(FILEPATH_SAVE)
- # cs = ControllerState.load_from_file(FILEPATH_SAVE)
- # physicalController = serial.Serial("COM3", 9600)
- while(True):
- if correctLogin == False:
- correctLogin = checkLogin()
- print("login ok")
- else:
- # TODO check el flag del controlador, y si hay que actualizar algo, actualizar.
- #readDirty()
- #if dirtyFlag():
- #getModifiedDataToController(cs)
- #sendServer()
- lastUpdate = fetchLastUpdate()
- if cs.last_update != int(lastUpdate):
- data = fetchJson()
- cs.load_from_json(data)
- # sincronizar con controlasdor
- for key in cs.allIrrigation:
- #writeTocontrollerPRiego(key)
- readFromcontrollerPRiego(key)
- #for key in cs.allInyection:
- # writeTocontrollerConfigIny(key)
- #for key in cs.allFertilization:
- #readFromcontrollerPFert(key)
- # writeTocontrollerPFert(key)
- print("updated")
- time.sleep(TIME_UPDATE)
- if correctLogin:
- cs.save_to_file(FILEPATH_SAVE)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement