def pystream_single(args, unk): iparser = instalparser.makeInstalParser() iparser.instal_input = open(args.input_files[0], "r") if args.output_file: iparser.instal_output = open(args.output_file, "w") iparser.mode = "default" idocument = "" idocument = idocument + iparser.instal_input.read(-1) iparser.instal_parse(idocument) if args.domain_file: iparser.print_domain(args.domain_file) iparser.instal_print_all() iparser.instal_input.close() if args.output_file: iparser.instal_output.close() ##### start of multi-shot solving cycle if args.output_file and args.fact_file: institution = ["externals.lp", "time.lp", args.output_file] initial_state = open(args.fact_file, "r").readlines() print(initial_state) sensor = Sensor(iparser, dummy, initial_state, institution, args) # print("initially:") # for i in initial_state: # print(i.name(),i.args()) # print("events from:",args.event_file) # with open(args.event_file,'r') as events: # for e in events: for event in fileinput.input(unk): sensor.solve(event)
def __init__( self ): self.streamID = "Environment" # Specify the STREAM-ID as it's specified in your stream definition on the SeaaS platform Sensor.__init__(self, self.streamID) # Copy/Paste from web portal # Call API to get LATEST stream information ..... self.sensorValue[self.streamID] = {} #Override if it exists self.hasCCINdefinition = True self.stream_def["title"] = self.streamID self.stream_def["properties"] = { self.streamID: { "type": "object", "properties": { "temperature": { "type": "integer" }, "humidity": { "type": "integer" }, "airpressure": { "type": "integer" } }, "additionalProperties": False } }
def __init__(self, sensorNode): """\brief Initializes the class \param sensorNode (\c SensorNode) A SensorNode object containing information to instantiate the class with """ Sensor.__init__(self, sensorNode) self.__ipAddress = sensorNode.getInterfaces("infrastructure")[0].getIP()
def main(argv): config_file = None try: opts, args = getopt.getopt(argv,"hc:",["cfgfile="]) except getopt.GetoptError: print 'repository.py -c <cfgfile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'repository.py -c <cfgfile>' sys.exit() elif opt in ("-c", "--cfgfile"): config_file = arg if config_file is None: print 'repository.py -c <cfgfile>' sys.exit(2) repository = Repository(config_file) sensor = Sensor('ground', config_file) readings = sensor.get_readings() if readings is not None: s=json.dumps(readings, sort_keys=True, indent=4, separators=(',', ': ')) print s repository.save_readings(readings)
def main(): global sensor sensor = Sensor() try: sensor.connect() except: print("Error connecting to sensor") raise return #cv.namedWindow("Threshold", cv.WINDOW_AUTOSIZE); cv.namedWindow("Contours", cv.WINDOW_AUTOSIZE); nfunc = np.vectorize(normalize) images = get_next_image() baseline_frame = images[-1] baseline = baseline_frame['image'] width = baseline_frame['cols'] height = baseline_frame['rows'] while 1: images = get_next_image(); frame = images[-1] pixels = np.array(frame['image']) pixels_zeroed = np.subtract(baseline, pixels); min = np.amin(pixels_zeroed) max = np.amax(pixels_zeroed) pixels_normalized = nfunc(pixels_zeroed, min, max) large = sp.ndimage.zoom(pixels_normalized, 10, order=1) large = large.astype(np.uint8); large = cv.medianBlur(large,7) #large = cv.GaussianBlur(large,(7,7),0) #stuff, blobs = cv.threshold(large,150,255,cv.THRESH_BINARY) stuff, blobs = cv.threshold(large,160,255,cv.THRESH_BINARY+cv.THRESH_OTSU) contours, hierarchy = cv.findContours(blobs, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) out = np.zeros((height*10,width*10,3), np.uint8) cv.drawContours(out,contours,-1,(255,255,0),3) regions_found = len(contours) contours = np.vstack(contours).squeeze() rect = cv.minAreaRect(contours) box = cv.cv.BoxPoints(rect) box = np.int0(box) cv.drawContours(out,[box],0,(0,255,255),2) #cv.imshow("Threshold", blobs); cv.imshow("Contours", out) cv.waitKey(1) x = rect[0][0] y = rect[0][1] angle = rect[2]; if(regions_found < 10): send(x, y, angle) time.sleep(0.4) sensor.close() print "Done. Everything cleaned up."
def __init__(self): Sensor.__init__(self) self.have_serial = False try: self.ser = serial.Serial(port=self.PORT, baudrate=115200, timeout=1) self.have_serial = True except: pass
def __init__(self, dataset, datadir='.'): """ Initialization. :param dataset: Filename. :param datadir: Directory of the file default '.' """ self.scans, width = self.load_data(datadir, dataset) Sensor.__init__(self, width, self.scan_rate_hz, self.viewangle, self.distance_no_detection_mm, self.detectionMargin, self.offsetMillimeters)
def __init__(self): """@todo: to be defined1. """ Sensor.__init__(self) self.have_sensor = False try: self.i2c = Adafruit_I2C(self.I2C_ADDRESS) self.have_sensor = True except: pass
def __init__(self, log=True): self.log = log if (log): self.out = open('log', 'w') self.reader = Reader() self.width = self.reader.getWidth() self.height = self.reader.getHeight() self.row = self.height / 2 # row to read Sensor.__init__(self, self.width, self.scan_rate_hz, self.viewangle, self.distance_no_detection_mm, self.detectionMargin, self.offsetMillimeters)
def __init__(self, name, sensor_id, port, baud, time_source, data_handlers): '''Save properties for opening serial port later.''' Sensor.__init__(self, 'green_seeker', name, sensor_id, time_source, data_handlers) self.port = port self.baud = baud self.read_timeout = 2 self.stop_reading = False # If true then sensor will stop reading data. self.connection = None self.max_closing_time = self.read_timeout + 1
def __init__(self, name, sensor_id, time_source, position_source, data_handlers): '''Constructor.''' Sensor.__init__(self, 'position', name, sensor_id, time_source, data_handlers) self.position_source = position_source self.stop_passing = False # If true then sensor will passing data to handlers. self.is_open = False # internally flag to keep track of whether or not sensor is open. self.last_utc_time = 0 # last position timestamp that was passed onto data handlers. self.max_closing_time = 3 # seconds
def __init__(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connection = socket.socket() self.width = 0 self.scan_rate_hz = 0 self.viewangle = 0 self.distance_no_detection_mm = 0 self.detection_margin = 0 self.offset_millimeters = 0 self.initialize() Sensor.__init__(self, self.width, self.scan_rate_hz, self.viewangle, self.distance_no_detection_mm, self.detection_margin, self.offset_millimeters)
def info(inData): from user import User from sensor import Sensor from station import Station pureData=Auth.select(inData) userInfo={} sensorInfo={} stationInfo={} #print(pureData) for tmp in pureData['data']: t=tmp['sensorId'] if(not(t in sensorInfo)): curSensor=Sensor.select({'id': t}) sensorInfo[t]=curSensor tmp['sensorName']=sensorInfo[t]['data'][0]['name'] t=sensorInfo[t]['data'][0]['stationId'] if(not(t in stationInfo)): curStation=Station.select({id: t}) stationInfo[t]=curStation tmp['stationName']=stationInfo[t]['data'][0]['name'] t=tmp['userId'] if(not(t in userInfo)): curUser=User.select({'id':t}) userInfo[t]=curUser tmp['userName']=userInfo[t]['data'][0]['username'] return pureData
def delete_station2(inData): ''' :param inData: :return:{ 2:'there is no id in inData', 3:'there is no such id' } ''' ret=0 if(not inData.has_key('id')): ret=2 return ret query=session.query(Station) tmpStation=query.filter(Station.id==inData['id']).first() if(tmpStation==None): ret=3 return ret else: from sensor import Sensor tmpAllSensor=Sensor.select({'stationId': tmpStation.id}) for tmpSensor in tmpAllSensor['pureData']: tmpSensor.stationId=0 session.delete(tmpStation) session.commit() ret=1 return ret
def load_sensors(self): if "sensors" not in config: print("can not find the sensors segment in setting.cfg") return all_sensors = config["sensors"] for sensor_id in all_sensors: if sensor_id not in self.__sensors__: sensor_object = all_sensors[sensor_id] if "kind" in sensor_object: sensor_object_kind = sensor_object["kind"] if sensor_object_kind in self.__models__: new_sensor = SensorLogic.copy_with_info(self.__models__[sensor_object_kind], sensor_id, sensor_object["name"]) self.__sensors__[sensor_id] = new_sensor else: new_sensor = Sensor(sensor_object_kind, sensor_id, sensor_object["name"]) if sensor_object["type"] is "action": on_action = SAction("on") off_action = SAction("off") new_sensor.add_action(on_action) new_sensor.add_action(off_action) else: value_property = SProperty("value", 0, None, 0) new_sensor.add_property(value_property) self.__sensors__[sensor_id] = new_sensor else: print("{0:s} sensor in setting.cfg lost kind property".format(sensor_id))
def sample(self): s = Sensor.sample(self) # Exceeded the max value...probably out of range. if s > self.maxVal: ret = Sensor.UNKNOWN else: ret = s * self.rangeInMeters / self.maxVal return ret
def run_sensor(player): sensor = Sensor() last_reading = sensor.get_light_sensor_reading() current_reading = sensor.get_light_sensor_reading() start_time = datetime.now() while True: reading = sensor.get_light_sensor_reading() print reading, last_reading, current_reading last_reading = current_reading current_reading = reading if current_reading - last_reading > 100: player.play() start_time = datetime.now() if (datetime.now() - start_time).seconds > 30 and player.is_playing(): player.stop() yield From(asyncio.sleep(0.1))
def delStation(inData): ''' :param: inData :return: {1:'success', 2:'failed', 3:'permission denied', 4:'param wrong'} ''' from user import User from sensor import Sensor if(('UserId' in inData) and ('StationId' in inData)): updateUserLevel = session.query(User.level).filter(User.id == inData['UserId'], User.valid == 1).first() if(updateUserLevel == None or int(updateUserLevel[0] != 0)): return 3 else: session.query(Station).filter(Station.id == inData['StationId'], Station.valid == 1).update({'valid':0, 'time':datetime.now()}) delSensorId = session.query(Sensor.id).filter(Sensor.stationId == inData['StationId'], Sensor.valid == 1).all() for sensorId in delSensorId: Sensor.delSensor({'UserId':inData['UserId'], 'SensorId':int(sensorId[0])}) session.commit() return 1 else: return 4
def algoritmoReducao(self, colunas, numTotEpocas, numAmostrasCiclo): sensor = Sensor(self.ARQUIVO) for var in colunas: saida = [] erroAc = [] medidas = [] variavel = sensor.obterLeitura(var, 0, numTotEpocas-1) if(self.remOutlier): variavel = Estatistica.removeOutliers(variavel) numIter = int(ceil(float(numTotEpocas)/numAmostrasCiclo)) erro = 0 limSup = limInf = 0 i = 1 while(i <= numIter): limInf = (i-1)*numAmostrasCiclo limSup = i*numAmostrasCiclo-1 if(limSup >= numTotEpocas): limSup = (numTotEpocas%numAmostrasCiclo)+limInf-1 medidas = variavel[limInf:limSup+1] informacoes = Estatistica.regSimples(range(limInf+1, limSup+2), medidas, True) saida = saida.__add__(informacoes[2]) erro = informacoes[4] erroAc.append(erro) i += 1 residuo = Estatistica.erroResidual(variavel, saida); DIC = {'variavel': VARIAVEL[var%len(VARIAVEL)], 'media': Estatistica.media(erroAc), 'minimo': Estatistica.minimo(erroAc), 'maximo': Estatistica.maximo(erroAc), 'eqm': sum(erroAc), 'pkt-gerados': numIter, 'mecanismo': 'Regressao'} Log.registraLog(ARQUIVO_SAIDA, FORMAT, DIC) if(self.plot): Estatistica.plotar((range(1, numTotEpocas+1), range(1, numTotEpocas+1)), (variavel, saida), "Filtro Medio", "Epoca", VARIAVEL[var%len(VARIAVEL)], ["Valores Reais", "Valores Preditos"]) return [numIter, saida, variavel, residuo]
class Slice(Thread): def __init__(self, local=False, interval=INTERVAL): Thread.__init__(self) self.done = None self.interval = interval self.local = local self.sensor = Sensor() def run(self): self.done = Event() while not self.done.wait(self.interval): info = self.sensor.read() if info: if self.local: print info else: self.send(info) else: print('The sensor could not be read') def send(self, info): # search for the server service service_matches = bt.find_service(uuid=UUID) if not service_matches: print('The server could not be found') first_match = service_matches[0] port = first_match['port'] name = first_match['name'] host = first_match['host'] print('Attempting to connect to \'%s\' on %s' % (name, host)) # Create the client socket sock = bt.BluetoothSocket(bt.RFCOMM) sock.connect((host, port)) print('The connection has been accepted by the server') sock.send(str(info)) print('The information has been sent') sock.close() print('The client socket has been closed') def stop(self): try: self.done.set() except AttributeError: print('The client cannot be stopped. It is not running') else: print('The client has been stopped')
def algoritmoReducao(self, colunas, numTotEpocas, numAmostrasCiclo): sensor = Sensor(self.ARQUIVO) for var in colunas: saida = [] erroAc = 0 medidas = [] variavel = sensor.obterLeitura(var, 0, numTotEpocas-1) numIter = int(ceil(float(numTotEpocas)/numAmostrasCiclo)) erro = 0 coefGerados = 1 limSup = limInf = 0 i = 1 while(i <= numIter): limSup = i*numAmostrasCiclo-1 if(limSup >= numTotEpocas): limSup = (numTotEpocas%numAmostrasCiclo)+limInf-1 medidas = variavel[limInf:limSup+1] informacoes = Estatistica.regSimples(range(limInf+1, limSup+2), medidas, (True)) erro = informacoes[3] if(erro <= self.limiar or (limInf == limSup-numAmostrasCiclo+1)): saida[limInf:limSup+1] = informacoes[limInf:limSup+1] print len(saida) erroAc.append(sum(erro)) if(erro > self.limiar): limInf = i*numAmostrasCiclo coefGerados += 1 i += 1 else: limInf = (i-1)*numAmostrasCiclo coefGerados += 1 DIC = {'variavel': VARIAVEL[var%len(VARIAVEL)], 'media': Estatistica.media(erroAc), 'minimo': Estatistica.minimo(erroAc), 'maximo': Estatistica.maximo(erroAc), 'Erro-Acumulativo': sum(erroAc), 'pkt-gerados': coefGerados} Log.registraLog('cumulativo', FORMAT, DIC)
class Alarm(object): def __init__(self): self._low_pressure_threshold = 17 self._high_pressure_threshold = 21 self._sensor = Sensor() self._is_alarm_on = False def check(self): psi_pressure_value = self._sensor.sample_pressure() if psi_pressure_value < self._low_pressure_threshold or self._high_pressure_threshold < psi_pressure_value: self._is_alarm_on = True @property def is_alarm_on(self): return self._is_alarm_on
def info(inData): from user import User from sensor import Sensor from station import Station from auth import Auth allEqpData=Eqp.select(inData) userInfo={} sensorInfo={} stationInfo={} authInfo={} #print(allEqpData) for tmp in allEqpData['data']: t=tmp['number'] tmpAllSensor=Sensor.select({'number': t}) if(len(tmpAllSensor['data'])==0): tmp['sensorName']='not find' tmp['stationName']='not find' tmp['username']='******' else: curSensor=tmpAllSensor['pureData'][0] tmp['sensorName']=curSensor.name tmpAllStation=Station.select({'id': curSensor.stationId}) if(len(tmpAllStation['data'])==0): tmp['stationName']='not find' else: curStation=tmpAllStation['pureData'][0] tmp['stationName']=curStation.name tmp['userName']=curStation.supervisor tmpAllAuth=Auth.select({'sensorId': curSensor.id}) # if(len(tmpAllAuth['data'])==0): # tmp['username']='******' # else: # tmpAllUser=User.select({'id': tmpAllAuth['pureData'][0].userId}) # if(len(tmpAllUser['data'])==0): # tmp['username']='******' # else: # tmp['username']=tmpAllUser['data'][0]['username'] return allEqpData
class Alarm(object): def __init__(self): self._low_pressure_threshold = 17 self._high_pressure_threshold = 21 self._sensor = Sensor() self._is_alarm_on = False self._alarm_count = 0 def check(self): psi_pressure_value = self._sensor.pop_next_pressure_psi_value() if psi_pressure_value < self._low_pressure_threshold or self._high_pressure_threshold < psi_pressure_value: self._is_alarm_on = True self._alarm_count += 1 @property def is_alarm_on(self): return self._is_alarm_on
def __init__(self, sensor_server="172.17.5.180", sensor_port=5555, sensor_sample_rate=100000, sensor_tx_freq=1000, gantry_server="172.17.5.100", gantry_port=5007, store_filename="data.log"): self.robot = Gantry(host=gantry_server,port=gantry_port) self.sensor = Sensor(server=sensor_server, port=sensor_port, sample_rate=sensor_sample_rate, tx_freq=sensor_tx_freq) self.transmitter = siggen self.transmitter.setFrequency(sensor_tx_freq) self.transmitter.setVoltage(-2,2) self.transmitter.turnOn() self._tx_freq = sensor_tx_freq self.store = DataStorage(store_filename) self.pos = Pos(0,0)
def __init__(self,instal_texts,domain_texts,fact_text,options=""): #instal_texts is a list of strings ipath = [] for i in instal_texts: ipath.append(self.temporary_text_file(i)) dpath = [] for d in domain_texts: dpath.append(self.temporary_text_file(d)) fpath = self.temporary_text_file(fact_text) opath = mkdtemp() #-o needs to be a directory if >1 input file and a .lp file otherwise. This is a hack but it crashes otherwise. if len(instal_texts) > 1: opath_end = "/" else: opath_end = "/tmp.lp" #Construct argument list using temp files argparser = instalargparse.buildargparser() topass = ['-o',opath+opath_end,'-f',fpath,options] topass += ['-i'] + ipath topass += ['-d'] + dpath (args,unk) = argparser.parse_known_args(topass) # assumes input files are .ial not .lp args.ial_files = args.input_files args.lp_files = [] model_files = instal_compile(args) initial_state = instal_state_facts(args) domain_facts = instal_domain_facts(args) self.sensor = Sensor(dummy,initial_state,model_files,domain_facts,args) # Clean up files. for i in ipath: os.remove(i) for d in dpath: os.remove(d) os.remove(fpath) shutil.rmtree(opath)
def __init__(self, serialPath, serialBaud, logger=None): Sensor.__init__(self, self.name, logger) self.serialPath = serialPath self.serialBaud = serialBaud self.connect()
parser.add_argument("-q", "--qos", help="MQTT QoS", type=int, default=1) parser.add_argument("-o", "--topic2", help="Additional MQTT topic") parser.add_argument("-t", "--topic", help="MQTT topic", required=True) # specific parser.add_argument("-s", "--topic_key", help="MQTT topic key", required=True) parser.add_argument("-w", "--wait", help="time between readings", type=float, default=0.5) parser.add_argument("-i", "--pin", help="gpio pin (BCM)", type=int, required=True) parser.add_argument("-y", "--high_value", help="high value", default=Sensor.HIGH) parser.add_argument("-z", "--low_value", help="low value", default=Sensor.LOW) parser.add_argument("-g", "--log_level", help="logging level", type=int, default=logging.INFO) args = parser.parse_args() # logging setup logger = set_logger(level=args.log_level) sensor = Sensor(args.pin) sensor.start() last_state = None status = None while True: current_state = sensor.reading() if current_state != last_state: last_state = current_state # reset state value if current_state == Sensor.LOW: status = args.low_value else: status = args.high_value logger.debug("sensor-monitor: changed %s %s" % (args.topic_key, str(status))) # publish MqttClient.publish(args, args.topic, {'state': {'reported': {args.topic_key: status}}})
def __init__(self): self._low_pressure_threshold = 17 self._high_pressure_threshold = 21 self._sensor = Sensor() self._is_alarm_on = False
class Echidna(object): def __init__(self, sensor_server="172.17.5.180", sensor_port=5555, sensor_sample_rate=100000, sensor_tx_freq=1000, gantry_server="172.17.5.100", gantry_port=5007, store_filename="data.log"): self.robot = Gantry(host=gantry_server,port=gantry_port) self.sensor = Sensor(server=sensor_server, port=sensor_port, sample_rate=sensor_sample_rate, tx_freq=sensor_tx_freq) self.transmitter = siggen self.transmitter.setFrequency(sensor_tx_freq) self.transmitter.setVoltage(-2,2) self.transmitter.turnOn() self._tx_freq = sensor_tx_freq self.store = DataStorage(store_filename) self.pos = Pos(0,0) def setStore(self,fname): if self.store.db.isopen: self.store.close() self.store = DataStorage(fname) def setTxFreq(self,freq): self._tx_freq = freq self.transmitter.setFrequency(freq) self.sensor.tx_freq = freq def stepOverTank(self,fname="tank"): self.pos = self.discretizeTank() x_size = self.pos.shape[0] y_size = self.pos.shape[1] for x in range(x_size): for y in range(y_size): p = self.pos[x,y] logger.info("Moving to (%f, %f)" % (p[0],p[1])) self.robot.moveAndWait(p[0],p[1], 60) d = self.sensor.getSample(100) fig, samp = self.plotRadar(5) fig.savefig(fname + "-x%3.2f-y%3.2f(x%d,y%d).tiff" % (p[0],p[1],x,y)) plt.close(fig) d.setPos(p, (x,y)) self.store.save(d) def stepOverPos(self,pos,fname="target"): self.count = 0 self.pos = pos x_size = self.pos.shape[0] y_size = self.pos.shape[1] for x in range(x_size): for y in range(y_size): p = self.pos[x,y] logger.info("Moving to (%f, %f)" % (p[0],p[1])) self.robot.move(p[0],p[1], 70) #d = self.sensor.getSample(25) fig, d = self.plotRadar() d.setPos(p) self.store.save(d) fig.savefig("%d-" % self.count + fname + "-x%3.2f-y%3.2f.tiff" % (p[0],p[1])) plt.close(fig) while(self.robot.busy()): time.sleep(0.5) self.count = self.count + 1 def freqSweep(self,start,stop,step=1, nsamps=100): self.count = 0 range = np.arange(start,stop,step) samples = [] for freq in range: logger.info("%d | Sampling frequency: %f" % (self.count,freq)) self.setTxFreq(freq) d = self.sensor.getSample(nsamps) d.setPos(self.pos.astuple()) self.store.save(d) self.count = self.count + 1 samples.append(d) return samples def discretizeTank(self, width=23.5, length=23.5, steps=50.0): x_steps = np.round(np.arange(0,width,width/steps),2) y_steps = np.round(np.arange(0,length,length/steps),2) pos = np.zeros((x_steps.size,y_steps.size, 2)) for i in range(x_steps.size): for j in range(y_steps.size): pos[i][j][0] = x_steps[i] pos[i][j][1] = y_steps[j] return pos def learn_baseline(self, samples=250): self.sample_baseline = self.sensor.getSample(samples) def getDiffSignal(self, samples=10, baseline_samples=250): if not hasattr(self,"sample_baseline"): self.learn_baseline(baseline_samples) sample = self.sensor.getSample(samples) data = sample.getMeanPower() return (data - self.sample_baseline.getMeanPower()), sample def plotRadar(self, samples=15, baseline_samples=250): fig = plt.figure() ax = fig.add_axes([0.1,0.1,0.8,0.8], polar=True) lines = ax.get_lines() ax.set_rmax(0.1) y, samp = self.getDiffSignal(samples, baseline_samples) for val in y: sys.stdout.write("%3.6f,"% val) sys.stdout.write("\n") x = np.arange(y.size)/np.float(y.size)*np.pi*2.0 data = zip(x,y) lines = ax.get_lines() for vec in data: ax.set_rmax(0.15) ax.plot([vec[0],vec[0]],[0,vec[1]],linewidth=3.0) ax.set_rmax(0.1) plt.show() return fig, samp def __del__(self): self.store.close()