def decode_object(o): import Sensors import pandas as pd if '__Channel__' in o: a = Sensors.Channel(o['__Channel__']['project'], o['__Channel__']['location'], o['__Channel__']['equipment'], o['__Channel__']['parameter'], o['__Channel__']['unit'], o['__Channel__']['raw_data']) a.__dict__.update(o['__Channel__']) return a elif '__Sensor__' in o: a = Sensors.Sensor(o['__Sensor__']['project'], o['__Sensor__']['location'], o['__Sensor__']['equipment'], o['__Sensor__']['frame']) a.__dict__.update(o['__Sensor__']) return a elif '__DataFrame__' in o: a = pd.read_json(o['__DataFrame__'], orient='split') return (a) elif '__Timestamp__' in o: return pd.to_datetime(o['__Timestamp__']) else: return o
def initHardware(): pSens0 = Sensors.DPressureSens(0, P_mplx_id) IMUsens0 = Sensors.MPU_9150(0, mplx_id_0) IMUsens1 = Sensors.MPU_9150(0, mplx_id_1) pActuator = Actuators.Valve(0, pValve0) dActuator = Actuators.DiscreteValve(0, dValve0) stopButton = Sensors.Button(sButton) return pSens0, IMUsens0, IMUsens1, pActuator, dActuator, stopButton
def preprocessMuscle(entity): for i in range(0,len(entity.muscles)): if entity.muscles[i].mesh == None: entity.muscles[i].mesh = Graphics.VBO_cylinder(6,2) Graphics.buildVBO(entity.muscles[i]) P1 = entity.muscles[i].Aworld P2 = entity.muscles[i].Bworld P3 = entity.muscles[i].Cworld if P1 == [] or P2 == [] or P3 == []: continue """ set muscle model matrix """ Ux = Definitions.vector4D((0, 1, 0, 0)) Vx = Definitions.vector4D((0, P1[0][0]-P2[0][0], P1[0][1]-P2[0][1], P1[0][2]-P2[0][2])) scale = math.sqrt(Vx.x*Vx.x + Vx.y*Vx.y + Vx.z*Vx.z) center = Definitions.vector4D((0, 0.5*(P1[0][0]+P2[0][0]), 0.5*(P1[0][1]+P2[0][1]), 0.5*(P1[0][2]+P2[0][2]))) Wx = Definitions.vector4D.AngleAxisBetween2Vec(Ux,Vx) Definitions.modelMatrix.push() Definitions.modelMatrix.set(Definitions.I) Definitions.modelMatrix.translate(center.x, center.y, center.z) Definitions.modelMatrix.rotate(Wx.o, Wx.x, Wx.y, Wx.z) """ readjust facing direction """ uy = np.dot(np.array([0, 1, 0, 0]), Definitions.modelMatrix.peek()) # Note : not same as Ux because here it's [x,y,z,o] and in vector4D it's [o,x,y,z] vy = np.array([0.5*(P1[0][0]+P2[0][0])-P3[0][0], 0.5*(P1[0][1]+P2[0][1])-P3[0][1], 0.5*(P1[0][2]+P2[0][2])-P3[0][2], 0]) Uy = Definitions.vector4D((0, uy[0], uy[1], uy[2])) Vy = Definitions.vector4D((0, vy[0], vy[1], vy[2])) Wy = Definitions.vector4D.AngleAxisBetween2Vec(Uy,Vy) if Definitions.vector4D.VecDot(Vx,Wy) < 0: Wy.o = -Wy.o Definitions.modelMatrix.rotate(Wy.o, 1, 0, 0) Definitions.modelMatrix.scale(scale,0.03,0.03) entity.muscles[i].modelMatrix = Definitions.modelMatrix.peek() if entity.muscles[i].id == Definitions.lookingAtID: Definitions.lookingAt = np.dot(np.array([[0, 0, 0, 1]]), entity.muscles[i].modelMatrix) for sensor in Sensors.virtuSens + Sensors.zoiSens: if sensor.attach == entity.muscles[i].tag: sensor.h = 0.6 if sensor.type == 'Eye': sensor.h = 0.4 if ID.idCategory(sensor.id) == ID.ZOI: sensor.h = 0.55 Sensors.preprocessSensor(sensor, scale, 0.03, 0.03) Definitions.modelMatrix.pop()
def setMode(newMode): """ Sets up robot for specified mode. """ global mode, mazeState #Stop hardware rc.stopAll() disarmShooter() #This also restores led matrices to eye_open pattern #Update global mode mode = newMode #Update display for active mode if mode == Mode.menu: Sensors.stopAll() showMenu(MenuLevel.top) else: #Initialise screen and hardware for all operating modes setModeBackground() if mode == Mode.manual: initDriving() elif mode == Mode.sensorsTest: Sensors.startAll() elif mode == Mode.wallFollowing: ad.targetWallDistance = 0 #Reset ad.initialisePID() Sensors.startAll() initDriving() elif mode == Mode.hubbleChallenge: #Initialise pixy ad.initialisePID() Sensors.startAll() initDriving() mazeState = 0
def ControlTurbidity(): TUR_level = Sensors.ReadChannel(Sensors.Turbidity_channel) TUR_volts = Sensors.ConvertVolts(TUR_level, 2) print TUR_level if TUR_level >= Out_TurB1 and TUR_level < Out_TurB2: print "Sensor is out off water" elif TUR_level >= CLO_TurB1 and TUR_level < CLO_TurB2: print "WAter is dirty" ChangeTankWAter() elif TUR_level >= C_TurB1: print "WAter is clear" else: print "Opague object detected between the sensor"
def __init__(self): self.flow_near = None self.flow_out = None self.cl = CommandList() self.config() self.notify = [] self.notify.append(noti.MockObject(self.cfg)) self.notify.append(noti.TelegramChannel(self.cfg)) self.sensors = [] self.sensors.append(sen.Flow()) self.sensors.append(sen.NFC())
def __init__(self): self.imageProcessing = ImageProcessing.ImageProcessing() self.robotMovement = RobotMovement.RobotMovement() self.Sensors = Sensors.Sensors() self.wiiRemote = WiiRemote.WiiRemote() self.running = True self.mainloop()
class Packet(): # define state header = Header() ads = ADS() comms = COMMS() eps = EPS() imu = IMU() sensors = Sensors() # define functions def __init__(self): pass def decode(self, data): # validate header if not self.header.check(data): print "Packet validation failed!" print "Aborting packet decoding" sys.exit(1) msg = "" # decode ads data msg = msg + self.ads.decode(data[0:20]) # decode comms data msg = msg + self.comms.decode(data[10:30]) # decode eps data msg = msg + self.eps.decode(data[20:40]) # decode sensors data msg = msg + self.sensors.decode(data[30:50]) return msg
def loadZOI(entity, fileName): Sensors.zoiSens = [] if fileName == "": Limbs.setLimbsShow(Avatar.virtuMan, Events.SHOW) Muscles.setMusclesShow(Avatar.virtuMan, Events.SHOW) return Limbs.setLimbsShow(Avatar.virtuMan, Events.FADE) Muscles.setMusclesShow(Avatar.virtuMan, Events.HIDE) file = open(pathAvatars + entity.tag + '/' + pathTemplates + Sensors.selectedTemplate + '/' + pathZoi + fileName + extension, 'r') color = (0.5,0.5,0.5,1) type = Sensors.selectedTemplate while True: line = file.readline() # read sensor data if line == "": break name, parent, x, t, s = line.split(';') Sensors.zoiSens = Sensors.zoiSens + [Sensors.sensors(parent, type, (float(x),float(t),float(s)), color)] Sensors.zoiSens[len(Sensors.zoiSens)-1].tag = name Limbs.showLimb(Avatar.virtuMan, parent) Muscles.showMuscle(Avatar.virtuMan, parent) file.close()
def __init__(self): self.root = tk.Tk() ## self.root.grid_columnconfigure(3, weight=3) self.var = tk.StringVar() #self.varH = tk.StringVar() #label = tk.Label(self.root, text="Sensors:") value = tk.Label(self.root, textvariable=self.var, width=30) #humidity = tk.Label(self.root, textvariable=self.varH, width=20) #label.grid(row=0, column=0) value.grid(row=0, column=0) #humidity.grid(row=0, column=2) #, sticky="w" ledButton = tk.Button(self.root, text='Switch Blue', command=self.test, bg='bisque2', height=1, width=24) ledButton.grid(row=4, sticky=tk.NSEW) # create a queue for communication self.queue = queue.Queue() # create some sensors self.sensor = sns.THSensor(self.queue) self.sensor.setName("SensorT&H") # start polling the queue self.poll_queue()
def smokeData(ser=ser): temp = Sensors.ReadDHT11(ser) print(temp) data = [time() * 1000, float(temp[2]), float(temp[3])] response = make_response(json.dumps(data)) response.content_type = 'application/json' return response
def monitor(): """ Periodically adds sensor data to database. """ s = Session() while True: temp, hum = Sensors.getTempHum() moi = Sensors.getSoilMoisture() e = Enviro(temp, hum, moi) s.add(e) s.commit() print "Count is now %d" % s.query(Enviro).count() while (s.query(Enviro).count() > 288): s.delete(s.query(Enviro).order_by(Enviro.sdate).first()) s.commit() time.sleep(300)
def main(fire_fighter_id, sensor_id): """ The main the function :return: """ heat_sensor = Sensors.HeatSensor() while True: if heat_sensor.device_exists(): raw_data = heat_sensor.read_temp_raw() temp = heat_sensor.calculate_temperature(raw_data)[1] time_stamp = datetime.datetime.now() headers = { 'Content-type': 'application/json', 'Accept': 'text/plain' } print temp data_dict = { "sensor": sensor_id, "firefighter": fire_fighter_id, "measurement_object": 1, "value": temp, "timestamp": str(time_stamp) } response = requests.post("http://192.168.1.1:5001/api/reading", data=json.dumps(data_dict), headers=headers) print response time.sleep(1)
def Main(): running = True objectDetected = False gapDetected = False turns_left = 0 turns_right = 0 while running: move.both_forward() while objectDetected == False & gapDetected == False: if sense.read_bottom() > 0.75: gapDetected = True if sense.read_front() < 0.3 & sense.read_back() > 0.01: objectDetected = True if objectDetected == True: if turns_right > turns_left: move.right_forward() move.left_backward() time.sleep(2) move.all_stop() else: move.left_forward() move.right_backward() time.sleep(2) # move.all_stop() objectDetected = False if gapDetected == True: if turns_right > turns_left: move.right_forward() move.left_backward() time.sleep(2) move.all_stop() else: move.left_forward() move.right_backward() time.sleep(2) # move.all_stop() gapDetected = False
def tur(): level = 0 for x in range(0, 10): tur = Sensors.ReadChannel(Sensors.Turbidity_channel) level = level + tur level = level / 10 print(tur) return jsonify(tur=int(level))
def TankEmpty(): while True: Actuators.Pump1_On() print "pump 1 on" result1 = Sensors.read_AquaWaterLevel() if result1 >= (AquariumHeigth - 3): print "Tank is empty" Actuators.Pump1_Off() break
def level(): # level = 0 #for x in range(0,10): val = Sensors.read_AquaWaterLevel() # level = level + val #level = level/10 return jsonify(level=int(val))
def TankFill(): while True: Actuators.Pump2_On() print "pump 2 on" result2 = Sensors.read_AquaWaterLevel() if result2 == OptimumWaterLevel: print "Tank is full" Actuators.Pump2_Off() break
def data(ser=ser): temp = Sensors.ReadDHT11( ser) #dht.readtemperature(True) # Printing resultant string #temp =[1,50] print(temp[0]) print(temp[1]) data = [time() * 1000, float(temp[0]), float(temp[1])] response = make_response(json.dumps(data)) response.content_type = 'application/json' return response
def __init__(self, link_uri): """ Initialize crazyflie using passed in link""" self.s1 = threading.Semaphore(1) self._cf = Crazyflie() self.t = Sensors.logs(self) # the three function calls below setup threads for connection monitoring self._cf.disconnected.add_callback( self._disconnected ) #first monitor thread checking for disconnections self._cf.connection_failed.add_callback( self._connection_failed ) #second monitor thread for checking for back connection to crazyflie self._cf.connection_lost.add_callback( self._connection_lost ) # third monitor thread checking for lost connection print("Connecting to %s" % link_uri) self._cf.open_link( link_uri) #connects to crazyflie and downloads TOC/Params self.is_connected = True # Control Parm self.g = 10. # gravitational acc. [m/s^ 2] self.m = 0.044 # mass [kg] self.pi = 3.14 self.num_state = 6 self.num_action = 3 self.hover_thrust = 36850.0 self.thrust2input = 115000 # Logged states - , # log.position, log.velocity and log.attitude are all in the body frame of reference self.position = [0.0, 0.0, 0.0] # [m] in the global frame of reference self.velocity = [0.0, 0.0, 0.0] # [m/s] in the global frame of reference self.attitude = [0.0, 0.0, 0.0] # [rad] Attitude (p,r,y) with inverted roll (r) # References self.position_reference = [0.00, 0.00, 0.00] # [m] in the global frame # Increments self.position_increments = [0.1, 0.1, 0.1, 0.02] # [m] # Limits self.thrust_limit = (0, 63000) self.roll_limit = (-30, 30) self.pitch_limit = (-30, 30) # Controller settings self.isEnabled = True self.rate = 50 # Hz self.period = 1.0 / float(self.rate)
def robotInit(self): """ This function is called upon program startup and should be used for any initialization code. """ self.table = NetworkTables.getTable("SmartDashboard") self.robot_drive = wpilib.drive.DifferentialDrive( wpilib.Spark(0), wpilib.Spark(1)) self.stick = wpilib.Joystick(0) self.elevatorMotor = wpilib.VictorSP(5) self.intakeMotor = wpilib.VictorSP(2) self.intakeMotorLeft = wpilib.VictorSP(3) self.intakeMotorRight = wpilib.VictorSP(4) self.climbMotor = wpilib.VictorSP(6) self.ahrs = AHRS.create_i2c(0) #self.gearSpeed = .5 #self.lights = wpilib.Relay(1) #self.lightToggle = False #self.lightToggleBool = True #self.togglev = 0 self.robot_drive.setSafetyEnabled(False) wpilib.CameraServer.launch() self.xb = wpilib.Joystick(1) self.Compressor = wpilib.Compressor(0) self.Compressor.setClosedLoopControl(True) self.enabled = self.Compressor.enabled() self.PSV = self.Compressor.getPressureSwitchValue() self.LeftSolenoid = wpilib.DoubleSolenoid(0, 1) self.RightSolenoid = wpilib.DoubleSolenoid(2, 3) self.Compressor.start() self.wheel = wpilib.Encoder(0, 1) self.wheel2 = wpilib.Encoder(2, 3, True) self.encoder = Sensors.Encode(self.wheel, self.wheel2) #wpilib.CameraServer.launch() self.ultrasonic = wpilib.AnalogInput(0) self.autoSchedule = Auto.Auto(self, ) self.intakeToggle = False self.intakePos = False self.openSwitch = wpilib.DigitalInput(9) self.closedSwitch = wpilib.DigitalInput(8) self.speed = 0.6 self.leftSpeed = 0.7 self.rightSpeed = 0.7 self.speedToggle = False
def ControlW_Temperature(): W_temp = Sensors.read_temp() print "Water Temperature :", W_temp if W_temp > Maximum_T: Actuators.CoolerFan_On() print "Cooler fan is On" elif W_temp < Minumum_T: print "Heater is On" Actuators.CoolerFan_Off() elif W_temp >= Minumum_T and W_temp < Maximum_T: print "Water Temperature is Optimum" Actuators.CoolerFan_Off()
def control_sensors(): print "Choose an option: " print "1. Read Measurement" print "2. Return" input_option = input() input_option = verify_input(input_option) if input_option == 1: print "Enter a time frame in seconds" input_magnitude = input() input_magnitude = verify_input(input_magnitude) for x in range(0 , input_magnitude): print "Front Sensor: %fm" % sense.read_front() print "Back Sensor: %fm" % sense.read_back() print "Bottom Sensor: %fm" % sense.read_bottom() move.time.sleep(1) if input_option == 2: return
def loadSensors(): Sensors.virtuSens = [] for file in sensorFileName: if file[1] == True: print("load sensor group : {}".format(file[0])) file = open(pathSensors + file[0], 'r') while True: line = file.readline() # read sensor data if line == "": break parent, type, x, t, s = line.split(' ') Sensors.virtuSens = Sensors.virtuSens + [Sensors.sensors(parent, type, (float(x),float(t),float(s)))] file.close()
def loadGroup(entity, fileName): Sensors.virtuSens = [] Sensors.selectedSens = 0 if fileName == "": return file = open(pathAvatars + entity.tag + '/' + pathGroups + fileName + extension, 'r') while True: line = file.readline() # read sensor data if line == "": break name, parent, type, x, t, s = line.split(';') Sensors.virtuSens = Sensors.virtuSens + [Sensors.sensors(parent, type, (float(x),float(t),float(s)))] Sensors.virtuSens[len(Sensors.virtuSens)-1].tag = name file.close()
def loadZOI(zoiFileName): Sensors.zoiSens = [] if zoiFileName[0] == "": return print("load zoi : {}".format(zoiFileName[0])) file = open(pathZoi + zoiFileName[0] + '.txt', 'r') color = (0.5,0.5,0.5,1) type = zoiFileName[0] while True: line = file.readline() # read sensor data if line == "": break parent, x, t, s = line.split(' ') Sensors.zoiSens = Sensors.zoiSens + [Sensors.sensors(parent, type, (float(x),float(t),float(s)), color)] Sensors.zoiSens[len(Sensors.zoiSens)-1].tag = 'Zoi' file.close()
def updateTemplate(entity): global templateFileName templateFileName = os.listdir(pathAvatars + entity.tag + '/' + pathTemplates) Sensors.sensorGraphics = [] for template in templateFileName: file = open(pathAvatars + entity.tag + '/' + pathTemplates + template + '/' + 'Template' + extension, 'r') line = file.readline() if line == "": continue r, g, b, a, shape, scale = line.split(';') newTemplate = Sensors.templates() newTemplate.type = template newTemplate.color = [int(r),int(g),int(b),int(a)] newTemplate.shape = int(shape) newTemplate.scale = float(scale) newTemplate.mesh = Graphics.VBO_create(newTemplate.shape) Graphics.buildVBO(newTemplate) Sensors.sensorGraphics = Sensors.sensorGraphics + [newTemplate] file.close()
def renameTemplate(entity, oldName, newName): try: os.rename(pathAvatars + entity.tag + '/' + pathTemplates + oldName, pathAvatars + entity.tag + '/' + pathTemplates + newName) # change sensor name in group files to match with new template name for fileName in groupFileName: # read file file = open(pathAvatars + entity.tag + '/' + pathGroups + fileName + extension, 'r') fileData = [] while True: line = file.readline() # read sensor data if line == "": break tag, parent, type, x, t, s = line.split(';') if type == oldName: type = newName fileData = fileData + [Sensors.sensors(parent, type, (float(x),float(t),float(s)))] fileData[len(fileData)-1].tag = tag file.close() # rewrite file file = open(pathAvatars + entity.tag + '/' + pathGroups + fileName + extension, 'w') for sensor in fileData: file.write(sensor.tag) file.write(";") file.write(sensor.attach) file.write(";") file.write(sensor.type) file.write(";") file.write(str(sensor.x)) file.write(";") file.write(str(sensor.t)) file.write(";") file.write(str(sensor.s)) file.write("\n") file.close() for sensorData in Sensors.sensorGraphics: if sensorData.type == oldName: sensorData.type = newName break except: pass
def ControlWaterLevel(): result = Sensors.read_AquaWaterLevel() print "Distance: ", result, "cm" if result >= OptimumWaterLevel and result < HalfWaterLevel: print "Water level is in Optimum Level " Actuators.Pump1_Off() Actuators.Pump2_Off() elif result >= HalfWaterLevel and result < AquariumHeigth: print "Water level very low. Pump 2 is on to fill the tank" Actuators.Pump2_On() #Actuators.Pump1_Off() elif result < OptimumWaterLevel: print "Water level too high. Pump 1 is on to reduce the tank" #Actuators.Pump1_On() #Actuators.Pump2_Off() elif result > AquariumHeigth: print "out of range" Actuators.Pump1_Off() Actuators.Pump2_Off() else: print "something wrong"
def __init__(self): self.controls = Controls() self.sensors = Sensors() self.brains = AI()
def generateSamples_simple(folderSample, workingDirectory, trainShape, pathWd, featuresPath, samplesOptions, pathConf, dataField): bindingPython = Config(file(pathConf)).GlobChain.bindingPython dataField = Config(file(pathConf)).chain.dataField outputPath = Config(file(pathConf)).chain.outputPath userFeatPath = Config(file(pathConf)).chain.userFeatPath if userFeatPath == "None": userFeatPath = None tmpFolder = outputPath + "/TMPFOLDER" if not os.path.exists(tmpFolder): os.mkdir(tmpFolder) # Sensors S2 = Sensors.Sentinel_2("", Opath(tmpFolder), pathConf, "") L8 = Sensors.Landsat8("", Opath(tmpFolder), pathConf, "") L5 = Sensors.Landsat5("", Opath(tmpFolder), pathConf, "") # shutil.rmtree(tmpFolder, ignore_errors=True) SensorsList = [S2, L8, L5] stats = workingDirectory + "/" + trainShape.split("/")[-1].replace( ".shp", "_stats.xml") tile = trainShape.split("/")[-1].split("_")[0] stack = fu.getFeatStackName(pathConf) feat = featuresPath + "/" + tile + "/Final/" + stack if bindingPython == "True": feat = fu.FileSearch_AND(featuresPath + "/" + tile + "/tmp/", True, "ST_MASK")[0] os.environ["ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS"] = "1" cmd = "otbcli_PolygonClassStatistics -in " + feat + " -vec " + trainShape + " -out " + stats + " -field " + dataField print cmd os.system(cmd) verifPolyStats(stats) sampleSelection = workingDirectory + "/" + trainShape.split( "/")[-1].replace(".shp", "_SampleSel.sqlite") cmd = "otbcli_SampleSelection -out " + sampleSelection + " " + samplesOptions + " -field " + dataField + " -in " + feat + " -vec " + trainShape + " -instats " + stats print cmd os.system(cmd) # if pathWd:shutil.copy(sampleSelection,folderSample) os.environ["ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS"] = "5" samples = workingDirectory + "/" + trainShape.split("/")[-1].replace( ".shp", "_Samples.sqlite") if bindingPython == "True": sampleExtr = otb.Registry.CreateApplication("SampleExtraction") sampleExtr.SetParameterString("vec", sampleSelection) sampleExtr.SetParameterString("field", dataField) sampleExtr.SetParameterString("out", samples) AllRefl = sorted( fu.FileSearch_AND(featuresPath + "/" + tile + "/tmp/", True, "REFL.tif")) AllMask = sorted( fu.FileSearch_AND(featuresPath + "/" + tile + "/tmp/", True, "MASK.tif")) datesInterp = sorted( fu.FileSearch_AND(featuresPath + "/" + tile + "/tmp/", True, "DatesInterp")) realDates = sorted( fu.FileSearch_AND(featuresPath + "/" + tile + "/tmp/", True, "imagesDate")) print AllRefl print AllMask print datesInterp print realDates # gapFill + feat features = [] concatSensors = otb.Registry.CreateApplication("ConcatenateImages") for refl, mask, datesInterp, realDates in zip(AllRefl, AllMask, datesInterp, realDates): gapFill = otb.Registry.CreateApplication( "ImageTimeSeriesGapFilling") nbDate = fu.getNbDateInTile(realDates) nbReflBands = fu.getRasterNbands(refl) comp = int(nbReflBands) / int(nbDate) print datesInterp if not isinstance(comp, int): raise Exception("unvalid component by date (not integer) : " + comp) gapFill.SetParameterString("in", refl) gapFill.SetParameterString("mask", mask) gapFill.SetParameterString("comp", str(comp)) gapFill.SetParameterString("it", "linear") gapFill.SetParameterString("id", realDates) gapFill.SetParameterString("od", datesInterp) gapFill.Execute() # gapFill.SetParameterString("out","/ptmp/vincenta/tmp/TestGapFill.tif") # gapFill.ExecuteAndWriteOutput() # pause = raw_input("Pause1") # featExtr = otb.Registry.CreateApplication("iota2FeatureExtraction") # featExtr.SetParameterInputImage("in",gapFill.GetParameterOutputImage("out")) # featExtr.SetParameterString("comp",str(comp)) # for currentSensor in SensorsList: # if currentSensor.name in refl: # red = str(currentSensor.bands["BANDS"]["red"]) # nir = str(currentSensor.bands["BANDS"]["NIR"]) # swir = str(currentSensor.bands["BANDS"]["SWIR"]) # featExtr.SetParameterString("red",red) # featExtr.SetParameterString("nir",nir) # featExtr.SetParameterString("swir",swir) # featExtr.SetParameterString("ram","256") # featExtr.Execute() # features.append(featExtr) concatSensors.AddImageToParameterInputImageList( "il", gapFill.GetParameterOutputImage("out")) features.append(gapFill) # sensors Concatenation + sampleExtraction sampleExtr = otb.Registry.CreateApplication("SampleExtraction") sampleExtr.SetParameterString("ram", "1024") sampleExtr.SetParameterString("vec", sampleSelection) sampleExtr.SetParameterString("field", dataField) sampleExtr.SetParameterString("out", samples) if len(AllRefl) > 1: concatSensors.Execute() allFeatures = concatSensors.GetParameterOutputImage("out") else: allFeatures = features[0].GetParameterOutputImage("out") if userFeatPath: print "Add user features" userFeat_arbo = Config(file(pathConf)).userFeat.arbo userFeat_pattern = (Config( file(pathConf)).userFeat.patterns).split(",") concatFeatures = otb.Registry.CreateApplication( "ConcatenateImages") userFeatures = fu.getUserFeatInTile(userFeatPath, tile, userFeat_arbo, userFeat_pattern) concatFeatures.SetParameterStringList("il", userFeatures) concatFeatures.Execute() concatAllFeatures = otb.Registry.CreateApplication( "ConcatenateImages") concatAllFeatures.AddImageToParameterInputImageList( "il", allFeatures) concatAllFeatures.AddImageToParameterInputImageList( "il", concatFeatures.GetParameterOutputImage("out")) concatAllFeatures.Execute() allFeatures = concatAllFeatures.GetParameterOutputImage("out") sampleExtr.SetParameterInputImage("in", allFeatures) sampleExtr.ExecuteAndWriteOutput() # cmd = "otbcli_SampleExtraction -field "+dataField+" -out "+samples+" -vec "+sampleSelection+" -in /ptmp/vincenta/tmp/TestGapFill.tif" # print cmd # pause = raw_input("Pause") # os.system(cmd) else: cmd = "otbcli_SampleExtraction -field " + dataField + " -out " + samples + " -vec " + sampleSelection + " -in " + feat print cmd os.system(cmd) if pathWd: shutil.copy( samples, folderSample + "/" + trainShape.split("/")[-1].replace(".shp", "_Samples.sqlite")) os.remove(sampleSelection) os.remove(stats)
def get_sensors(self): cursor = self.connection.cursor() cursor.execute('SELECT * from sensors') sensors = [Sensors.sensor_create(sensor_type, id, config) for id, sensor_type, config in cursor] cursor.close() return sensors
def __init__(self, link_uri): """ Initialize crazyflie using passed in link""" #trim variables that will be updated during flight for stabilization self.roll_trim = 2 self.pitch_trim = -1 #-------------- PID stuff -------------------# self.avg_state = [0,0,0] self.last_state = [0,0,0] self.num_readings = 0 self.state_sum = [0,0,0] self.kproportional = .1 #----------------- END PID --------------------# #----------------- Flight Vars ----------------# self.next_roll = 0 self.next_pitch = 0 self.next_thrust = 0 self.gyro_threash = 15 self.take_off_thrust_step = 500 self.kill_threash = 10000 self.take_off_thrust = 38000 self.hover_alt_step = 3 self.thrust_step = 500 self.hover_thrust_step = 250 self.is_hovering = False self.min_thrust = 0 self.is_flying = False #---------------- End Flight Vars --------------# #---------------- Copter State Vars ----------------# #self.altitude = [0,0] #[base/initial, current] #self.current_altitude = 0 self.curr_thrust = 10000 #10000 is the base thrust to get the props moving self.max_thrust = 60000 #max thrust we ever want to give it self._cf = Crazyflie() #class declaration is in ..\lib\cflib\crazyflie\__init__.py self.t = Sensors.logs(self) #the three function calls below setup threads for connection monitoring self._cf.disconnected.add_callback(self._disconnected) #first monitor thread checking for disconnections self._cf.connection_failed.add_callback(self._connection_failed) #second monitor thread for checking for back connection to crazyflie self._cf.connection_lost.add_callback(self._connection_lost) # third monitor thread checking for lost connection print "Connecting to %s" % link_uri self._cf.open_link(link_uri) #connects to crazyflie and downloads TOC/Params self.is_connected = True