Ejemplo n.º 1
0
 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()
Ejemplo n.º 2
0
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)
Ejemplo n.º 3
0
 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
                                     }
                                   }
Ejemplo n.º 4
0
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)
Ejemplo n.º 5
0
Archivo: main.py Proyecto: G-ram/portal
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."
Ejemplo n.º 6
0
 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
Ejemplo n.º 7
0
 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)
Ejemplo n.º 8
0
    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
Ejemplo n.º 9
0
    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)
Ejemplo n.º 10
0
    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
Ejemplo n.º 11
0
    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
Ejemplo n.º 12
0
    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)
Ejemplo n.º 13
0
    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
Ejemplo n.º 14
0
    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
Ejemplo n.º 15
0
    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))
Ejemplo n.º 16
0
 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
Ejemplo n.º 17
0
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))
Ejemplo n.º 18
0
 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
Ejemplo n.º 19
0
 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]
Ejemplo n.º 20
0
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')
Ejemplo n.º 21
0
 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)         
Ejemplo n.º 22
0
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
Ejemplo n.º 23
0
    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
Ejemplo n.º 25
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)
Ejemplo n.º 26
0
 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)
Ejemplo n.º 27
0
 def __init__(self, sensor=None):
     self._low_pressure_threshold = 17
     self._high_pressure_threshold = 21
     self._sensor = sensor or Sensor()
     self._is_alarm_on = False
Ejemplo n.º 28
0
# 가상의 센서 4개 운영 
# 값은 센서마다 범위를 주고, 랜덤하게
#  
# 온도 센서 5초 간격으로 측정값 발행(iot/user1/temp)
# 습도 센서 7초 간격으로 측정값 발행(iot/user1/humi)
# 조도 센서 10초 간격으로 측정값 발행(iot/user1/illu)
# 미세먼지 센서 12초 간격으로 측정값 발행(iot/user1/dust)

from sensor import Sensor


sensors = [
    Sensor(5, (3, 10), 'iot/user1/temp'),
    Sensor(7, (20, 60), 'iot/user1/humi'),
    Sensor(10, (20, 80), 'iot/user1/illu'),
    Sensor(12, (0, 1), 'iot/user1/dust'),
]

for sensor in sensors:
    sensor.start() 
Ejemplo n.º 29
0
user = "******"
password = "******"
# auth = {'username': user, 'password': password}
host = "45.143.137.138"
port = 1883

payload_available = "Online"
payload_not_available = "Offline"

device_topics = ['mqtt/test_client/room1/device1/bin_sensor1/command',
                 'mqtt/test_client/room1/device1/bin_sensor1/state',
                 'mqtt/test_client/room1/device1/LWT']
hass_topics = []

# client, device name, sensor name, sensor type
sensors = [Sensor('test_client', 'device1', 'bin_sensor1', 'switch')]


def calc_topic(topic: str):
    if topic[:17].__eq__('mqtt/ytd61h9zk4jb'):
        return 'homeassistant' + topic[17:]
    elif topic[:13].__eq__('homeassistant'):
        return 'mqtt/ytd61h9zk4jb' + topic[13:]
    else:
        print('invalid topic??')
        return "error/"


# subscriber -----------------------------------------

def on_connect(client, userdata, flags, rc):
Ejemplo n.º 30
0
from sensor_utils import TimeBuffer

from config import Config

from sensor import Sensor

t = TimeBuffer()

t.load('../data/2019-11-22_readings.csv')

c = Config('sensor_config.json')

s = Sensor(c)

t.play(s.process_sample)
Ejemplo n.º 31
0
    # --- PID FILE EXISTS ---
    if os.path.isfile('smart4l.lock'):
        # TODO check if python process run with this pid
        Message.wrn("PID file  already exists")
        os.remove("smart4l.lock")
    open("smart4l.lock", "w+").write(str(os.getpid()))
    # --- === ---

    app = Smart4l()

    app.persistent = Persistent(app)
    app.httpApi = FlaskAPI(app.persistent)
    app.socket = Smart4lServeur(app.update_measure)

    app.add_service(
        Service(Sensor(DHT11(), "DHT11", app.update_measure), 1,
                "Temperature"))
    app.add_service(Service(app.persistent, 20, "DB"))
    app.add_service(Service(app.httpApi, "API Http"))

    app.reload()

    try:
        # Infinite loop for keyboard interuption
        while True:
            continue
    except KeyboardInterrupt:
        app.stop()
        os.remove("smart4l.lock")
else:
    Message.err(f"{__name__} : must be run as a script\n")
Ejemplo n.º 32
0
class ControllerTests(unittest.TestCase):
    """
    Unit tests for the Controller class, declaring pump, address, etc. outside
    an __init__ method because I had some difficulty implementing __init__ while
    inhereting from unittest.Testcase
    """

    address = '127.0.0.1'
    port = '8000'
    my_pump = Pump(address, port)
    my_sensor = Sensor(address, port)
    my_decider = Decider(10, 1)
    my_controller = Controller(my_sensor, my_pump, my_decider)

    def test_first_controller(self):
        '''Testing ability to correctly query sensor for height of tank'''

        logger.info("Starting first controller test")
        try:

            logger.info("Done with first controller test")
            assert (isinstance(self.my_sensor.measure(), float))

        except Exception as exception:
            logger.critical(exception)

    def test_second_controller(self):
        '''Tests the ability to query the pump for its current state'''

        logger.info("Starting second controller test")
        try:

            logger.info("Done with second controller test")
            assert (self.my_pump.get_state() in [1, -1, 0])

        except Exception as exception:
            logger.critical(exception)

    def test_third_controller(selft):
        '''Tests the ability to query the decider for the next appropriate state
        given a set of starting conditions. Note, this will only test one set of starting
        conditions. Exhaustive testing of the deciders logic is performed in DeciderTests'''

        try:

            logger.info("Done with third controller test")

            self.my_decider.decide(500, self.my_decider.target_height,
                                   self.my_controller.actions)
        except Exception as exception:
            logger.critical(exception)

    def test_fourth_controller(self):
        '''Tests the ability to set the pump to a new state'''
        try:
            logger.info("Starting fourth controller test")
            self.my_pump.set_state(0)
            assert (self.my_pump.get_state() == 0)

        except Exception as exception:
            logger.critical(exception)

    pass
Ejemplo n.º 33
0
""" Control the mouse with foot.

This is a simple controller that uses the sensor data to move the cursor. It
does not have anything to do with the machine learning system. Since we already
had the hardware, we took the extra time to implement this as well.

The values are adjusted to provide a more natural feel.

"""

from sensor import Sensor
from pymouse import PyMouse
from os.path import isfile

s = Sensor()
m = PyMouse()

# init sensor
while not s.get_single_sample():
    pass

m.move(10000, 10000)
x, y = m.position()
m.move(x / 2, y / 2)

X_THRESHOLD = 2.
Y_THRESHOLD = 3.


def convert(raw_value, threshold):
    PARAM = 1.5
Ejemplo n.º 34
0
def select_image():

    path = tkinter.filedialog.askopenfilename()
    if len(path) > 0:
        image = ImageTk.PhotoImage(Image.open(path))
        # process_image(path)
        obj = Intencive(path)
        ob2 = Sensor(obj)
        mat = Matrix(ob2)
        a, b, c, w, h, log1, lat1 = ob2.overall(path)

        m = mat.intensive_matrix(a, w, h)
        dist_mat = mat.distance_mat(b)
        pos_m = mat.pos_mat()
        neg_m = mat.neg_mat(c)

        mat.set_mat_maul(dist_mat, pos_m)
        mat.set_mat_maul2(neg_m)
        mat.set_mat_mul3(m)
        # mat.calculate_inverse_matrix()

        # print('inverse matreix======',mat.ainv)
        cord = Newcoordinate(mat)

        m1 = cord.pixel_to_world(0, 0, mat.mat_mul3)
        m2 = cord.pixel_to_world(w, 0, mat.mat_mul3)
        m3 = cord.pixel_to_world(w, h, mat.mat_mul3)
        m4 = cord.pixel_to_world(0, h, mat.mat_mul3)
        m5 = cord.pixel_to_world(w / 2, h / 2, mat.mat_mul3)

        print('m1==', m1)
        print('m2==', m2)
        print('m3==', m3)
        print('m4==', m4)
        print('m5==', m5)

        d1 = cord.eq_distance(m1, m2)
        print(d1)
        d2 = cord.eq_distance(m2, m3)
        print(d2)
        d3 = cord.eq_distance(m3, m4)
        print(d3)
        d4 = cord.eq_distance(m4, m1)
        print(d4)
        d5 = cord.eq_distance(m1, m3)
        print(d5)
        d6 = cord.eq_distance(m2, m4)
        print(d6)
        d7 = cord.eq_distance(m2, m5)
        print(d7)
        d8 = cord.eq_distance(m1, m5)
        print(d8)
        d9 = cord.eq_distance(m3, m5)
        print(d9)
        d10 = cord.eq_distance(m4, m5)
        print(d10)

        # km = cord.div()
        dis_km_25 = cord.div(d7)
        print('distance of m2,m5 in km', dis_km_25)
        dis_km_15 = cord.div(d8)
        print('distance of m1,m5 in km', dis_km_15)
        dis_km_35 = cord.div(d9)
        print('distance of m3,m5 in km', dis_km_35)
        dis_km_45 = cord.div(d10)
        print('distance of m4,m5 in km', dis_km_45)
        # ang = cord.angle_calculation()

        value_of_angle1 = cord.angle_calculation(m5, m1)
        print('angle value for m5,m1  ===>', value_of_angle1)
        value_of_angle2 = cord.angle_calculation(m5, m2)
        print('angle value for m5,m2  ===>', value_of_angle2)
        value_of_angle3 = cord.angle_calculation(m5, m3)
        print('angle value for m5,m3  ===>', value_of_angle3)
        value_of_angle4 = cord.angle_calculation(m5, m4)
        print('angle value for m5,m4  ===>', value_of_angle4)

        new_cod_val = cord.coordinate_angle(value_of_angle1, dis_km_15, lat1,
                                            log1, Radius)
        print(new_cod_val)

        new_cod_val = cord.coordinate_angle(value_of_angle2, dis_km_25, lat1,
                                            log1, Radius)
        print(new_cod_val)
        #
        new_cod_val = cord.coordinate_angle(value_of_angle3, dis_km_35, lat1,
                                            log1, Radius)
        print(new_cod_val)

        new_cod_val = cord.coordinate_angle(value_of_angle4, dis_km_45, lat1,
                                            log1, Radius)
        print(new_cod_val)

        def every_pixel_cord(x, y):
            world_cord = cord.pixel_to_world(x, y, mat.mat_mul3)
            print('x value=-==', x)
            print('y value is ===', y)
            # print('world coordinate', wc)
            dist_to_center = cord.eq_distance(m5, world_cord)
            # print(di)
            dist_km = cord.div(dist_to_center)
            # print('division', dv)
            angle = cord.angle_calculation(m5, world_cord)
            # print('angle',angle)
            latitude, longitude = cord.coordinate_angle(
                angle, dist_km, lat1, log1, Radius)
            print('latitude,longitude', latitude, longitude)
            return (latitude, longitude)

        frame = Frame(root, bd=2, relief=SUNKEN)

        frame.grid_rowconfigure(0, weight=1)
        frame.grid_columnconfigure(0, weight=1)

        xscrollbar = Scrollbar(frame, orient=HORIZONTAL)
        xscrollbar.grid(row=1, column=0, sticky=E + W)

        yscrollbar = Scrollbar(frame)
        yscrollbar.grid(row=0, column=1, sticky=N + S)

        canvas = Canvas(frame,
                        bd=0,
                        xscrollcommand=xscrollbar.set,
                        yscrollcommand=yscrollbar.set,
                        width=800,
                        height=500)
        canvas.grid(row=0, column=0, sticky=N + S + E + W)

        canvas.create_image(0, 0, image=image, anchor="nw")
        canvas.config(scrollregion=canvas.bbox(ALL))

        xscrollbar.config(command=canvas.xview)
        yscrollbar.config(command=canvas.yview)

        def printcoords(event):
            x = event.x
            y = event.y
            latitude, longitude = every_pixel_cord(x, y)
            fields = ('X', 'Y', 'latitude', 'longitude')
            root1 = Tk()
            input_val = [("X", x), ("Y", y), ("latitude", latitude),
                         ("longitude", longitude)]
            ents = makeform(root1, input_val)
            b3 = Button(root1,
                        text='Quit',
                        command=(lambda e=root1: destroy_root(e)))
            b3.pack(side=LEFT, padx=5, pady=5)

            root1.mainloop()

        canvas.bind("<Button 1>", printcoords)

        frame.pack()
        root.mainloop()
Ejemplo n.º 35
0
import wave
import os
import sys
import time
#from light import Light
from sensor import Sensor

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 10  # 最多60秒
WAVE_OUTPUT_FILENAME = "./assets/usersay.wav"  # 文件名

#led = Light(18)
mysensor = Sensor(17)


def wait_sound():

    no_sound_time_begin = time.time()
    sound_time_begin = 0

    while True:  # 等待有效声音

        if mysensor.hear_sound():  # 听到声音

            if sound_time_begin == 0:  # 第一次听到声音
                sound_time_begin = time.time()

            else:
Ejemplo n.º 36
0
from service import Service
from smart4l_socket import Smart4lClient




# execute only if run as a script
if __name__ == "__main__":

    app = Smart4l()

    socket = Smart4lClient()
    app.add_service(
    	Service(
    		Sensor(
    			DHT11(), "DHT11 RPI2", socket.send_message
    			)
    		, timeout=1, name="Temperature RPI2")
    	)
    

    app.reload()

    try:
        # Infinite loop for keyboard interuption
        while True:
            continue
    except KeyboardInterrupt:
        app.stop()
else:
    Message.err(f"{__name__} : must be run as a script\n")
Ejemplo n.º 37
0
class DeciderTests(unittest.TestCase):
    """
    Unit tests for the Decider class
    """

    # DONE: write a test or tests for each of the behaviors defined for
    #       Decider.decide

    def setUp(self):
        self.decider = Decider(100, .05)
        self.sensor = Sensor('127.0.0.1', 8001)
        self.pump = Pump('127.0.0.1', 8000)
        self.controller = Controller(self.sensor, self.pump, self.decider)

        self.actions = {
            'PUMP_IN': Pump.PUMP_IN,
            'PUMP_OFF': Pump.PUMP_OFF,
            'PUMP_OUT': Pump.PUMP_OUT
        }

    def test_decider(self):
        """
        Test Decider module logic
        """

        # Pump OFF, level low
        self.assertEqual(
            self.decider.decide(50, self.actions['PUMP_OFF'], self.actions),
            self.actions['PUMP_IN'])
        # Pump OFF, level high
        self.assertEqual(
            self.decider.decide(150, self.actions['PUMP_OFF'], self.actions),
            self.actions['PUMP_OUT'])
        # Pump OFF, level within margin
        self.assertEqual(
            self.decider.decide(100, self.actions['PUMP_OFF'], self.actions),
            self.actions['PUMP_OFF'])
        self.assertEqual(
            self.decider.decide(102, self.actions['PUMP_OFF'], self.actions),
            self.actions['PUMP_OFF'])
        self.assertEqual(
            self.decider.decide(98, self.actions['PUMP_OFF'], self.actions),
            self.actions['PUMP_OFF'])

        # Pump IN, level above target
        self.assertEqual(
            self.decider.decide(150, self.actions['PUMP_IN'], self.actions),
            self.actions['PUMP_OFF'])
        # Pump IN, level below target
        self.assertEqual(
            self.decider.decide(50, self.actions['PUMP_IN'], self.actions),
            self.actions['PUMP_IN'])

        # Pump OUT, level below target
        self.assertEqual(
            self.decider.decide(50, self.actions['PUMP_OUT'], self.actions),
            self.actions['PUMP_OFF'])
        # Pump OUT, level above target
        self.assertEqual(
            self.decider.decide(150, self.actions['PUMP_OUT'], self.actions),
            self.actions['PUMP_OUT'])

        # Test bad input to decider actions
        self.assertIsNone(self.decider.decide(100, 100, self.actions))

        # MOCKs for pump, sensor and decider modules
        self.pump.get_state = MagicMock(return_value=Pump.PUMP_OFF)
        self.sensor.measure = MagicMock(return_value=50)
        self.decider.decide = MagicMock(return_value=1)

        self.decider.decide(self.sensor.measure(), self.pump.get_state(),
                            self.actions)

        # Confirm that decide was called with 50, PUMP_OFF, and actions dict
        self.decider.decide.assert_called_with(
            50, Pump.PUMP_OFF, {
                'PUMP_IN': Pump.PUMP_IN,
                'PUMP_OUT': Pump.PUMP_OUT,
                'PUMP_OFF': Pump.PUMP_OFF
            })
Ejemplo n.º 38
0
 def __init__( self, m2mContainerId,  streamName ):
     Sensor.__init__(self, streamName)
     self.data = {}
     self.m2mContainerId = m2mContainerId
     self.stream_def["title"] = streamName
     self.stream_def["properties"]={"value":{"type":"boolean"}}
import controller_design
from sensor import Sensor
from filterpy import common
import bike_parameters

# Set debuggin print options to fit entire matrices
np.set_printoptions(suppress=True, linewidth=200)

# Parameters for the simulation
dt = 1 / 10  # sampling time for the sensor
velocity = 10  # velocity of the bike
r_var = 1e-3
q_var = 1

# Create the sensors
roll_gyro_sensor = Sensor(r_var)
steer_gyro_sensor = Sensor(r_var)
sensors = [roll_gyro_sensor, steer_gyro_sensor]

# Create the bike model
# C = np.array([[1, 0, 0, 0],
# 			  [0, 1, 0, 0]])
C = np.array([[0, 0, 1, 0], [0, 0, 0, 1]])
D = np.zeros(2)
bike = BikeModel(params.M, params.C_1, params.K_0, params.K_2)
bike.set_velocity(velocity)
# bike.update_C(C)

# Create controller
Q_c = np.eye(4)
R_c = np.eye(1) * 0.001
Ejemplo n.º 40
0
 def setUp(self):
     self.pump = Pump('127.0.0.1', 8010)
     self.decider = Decider(100, 0.05)
     self.sensor = Sensor('127.0.0.1', '8011')
     self.controller = Controller(self.sensor, self.pump, self.decider)
     self.actions = self.controller.actions
Ejemplo n.º 41
0
    y_target = 0
    z_target = 10
    roll_target = 0
    pitch_target = 30
    yaw_target = 0
    # yaw_target = np.arctan(y_target / x_target) * 180 / np.pi
    print(f"yaw_target: {yaw_target}")
    rot_outputs = np.array([[roll_target, pitch_target, yaw_target]]).T * np.pi / 180
    lin_outputs = np.array([[x_target, y_target, z_target]]).T
    lin_targets = np.array([[x_target, y_target, z_target]]).T
    rot_targets = np.array([[roll_target, pitch_target, yaw_target]]).T * np.pi / 180
    # Initialize Drone Hardware
    dh = DataHandler(
        parentfolder="results", visualize=visualize, n_servers=n_servers, port=port
    )
    sensors = [Sensor(delta_t, initial_pos[i, 0], initial_vel[i, 0]) for i in range(3)]
    sensors.extend(
        [
            Sensor(delta_t, initial_angle[i, 0], initial_angle_vel[i, 0])
            for i in range(3)
        ]
    )

    rot_pids = [
        PID(
            kp=0.7,
            ki=0.1,
            kd=0.1,
            timeStep=delta_t,
            setValue=roll_target * np.pi / 180,
            integralRange=2,
Ejemplo n.º 42
0
 def __init__(self, source, metric_prefix, output):
     Sensor.__init__(self, source, metric_prefix, output)
Ejemplo n.º 43
0
class DeciderTests(unittest.TestCase):
    """
    Unit tests for the Decider class, declaring pre-requisite test objects
    outside __init__ class because I ahd difficulting using __init__
    with unittest.Testcase
    """

    # TODO: write a test or tests for each of the behaviors defined for
    #       Decider.decide

    my_pump = Pump(address, port)
    my_sensor = Sensor(address, port)
    my_decider = Decider(10, 1)
    my_controller = Controller(my_sensor, my_pump, my_decider)
    address = '127.0.0.1'
    port = '8000'

    def test_first_decider(self):
        '''Behavior Test: If the pump is off and the height is below the margin region, then the
             pump should be turned to PUMP_IN.'''

        logger.info("running first decider test")

        try:
            assert (self.my_decider.decide(5, 0,
                                           self.my_controller.actions) == 1)
        except Exception as exception:
            logger.critical(exception)

    def test_second_decider(self):
        '''Behavior Test: If the pump is off and the height is above the margin region, then the
             pump should be turned to PUMP_OUT.'''

        logger.info("running second decider test")
        try:
            assert (self.my_decider.decide(12, 0,
                                           self.my_controller.actions) == -1)
        except Exception as exception:
            logger.critical(exception)

    def test_third_decider(self):
        '''Behavior Test: If the pump is off and the height is within the margin region or on
             the exact boundary of the margin region, then the pump shall remain at
             PUMP_OFF.'''

        logger.info("running third decider test")

        try:
            assert ((self.my_decider.decide(
                self.my_decider.target_height + self.my_decider.margin, 0,
                self.my_controller.actions)) == 0)
            assert ((self.my_decider.decide(
                self.my_decider.target_height - self.my_decider.margin, 0,
                self.my_controller.actions)) == 0)
        except Exception as exception:
            logger.critical(exception)

    def test_fourth_decider(self):
        '''Behavior Test: If the pump is performing PUMP_IN and the height is above the target
             height, then the pump shall be turned to PUMP_OFF, otherwise the pump
             shall remain at PUMP_IN.'''

        logger.info("running fourth decider test")
        try:
            assert ((self.my_decider.decide(self.my_decider.target_height + 1,
                                            1,
                                            self.my_controller.actions)) == 0)
        except Exception as exception:
            logger.critical(exception)

    def test_fifth_decider(self):
        '''Behavior Test: If the pump is performing PUMP_OUT and the height is below the target
             height, then the pump shall be turned to PUMP_OFF, otherwise, the pump
             shall remain at PUMP_OUT.'''

        logger.info("running fifth decider test")
        try:
            assert (self.my_decider.decide(self.my_decider.target_height - 1,
                                           -1,
                                           self.my_controller.actions) == 0)
        except Exception as exception:
            logger.critical(exception)
Ejemplo n.º 44
0
class Controller:
    '''Driver class for controlling tour guide's hybrid paradigm'''
    def __init__(self):

        # Initialize ROS node
        rospy.init_node("Controller")
        self.name = "Controller object"
        self.rate = rospy.Rate(10)  # allow node to 'spin' at 10hz

        rospy.on_shutdown(self.shutdown)  # calls this function when Ctrl+C

        self.motion = Motion()
        self.sensor = Sensor()
        self.localizer = Localizer()

        self.visited_highlights = []

        # Boolean for reached goal
        self.goalReached = False

    def start(self):
        rospy.loginfo("Starting Tour Guide..")
        begin = 'q'

        # Note: the Motion, Sensor, and Localizer classes
        # seem to take a second to fully initialize so we give
        # this Controller a second to fully initialize as well
        rospy.sleep(1)

        # TODO: here, could we determine if the guide will be
        #       1) casually walking around,
        #       2) begin P2P mode, or
        #       3) begin tour mode?

        # TODO: for now, it will be 'casually walking around'
        # TODO: Chris -  I was thinking we should just take out 'idle_mode'
        # for demo purposes. As soon as the program starts, we can ask the user
        # if they would like a P2P or a regular tour
        # then go from there
        # self.idle_mode()

        # TODO: Chris -  I think it will also be easier if we just have the robot
        # start the tour at its initial position which is at the West Entrance
        rospy.loginfo("Would you like a P2P tour or a regular tour?")
        rospy.loginfo("Press a key:")
        rospy.loginfo("'1': Point To Point")
        rospy.loginfo("'2': Regular Tour")
        begin = input()

        if (begin == 1):
            self.point_to_point_mode()
        elif (begin == 2):
            self.tour_guide_mode()

    def idle_mode(self):
        '''Make Turtlebot move around aimlessly
           and avoid nearby obstacles
        '''
        rospy.loginfo("Initalizing Idle mode.")

        while not rospy.is_shutdown():

            if self.sensor.is_obstacle_detected():
                # Rotate Turtlebot accordingly to avoid obstacles
                self.sensor.avoid_obstacle()
            else:
                # If no obstacles detected, no need to rotate
                self.motion.halt_rotation()

            self.motion.move_forward()

    def tour_guide_mode(self):
        ''' Robot will decide its path/highlights depending on its location'''
        rospy.loginfo("Initializing Tour Guide mode.")

        print(self.localizer.position)

        west_entrance = Locations.WestEntrance
        east_entrance = Locations.EastEntrance

        # TODO: just start at nearest entrance and go down the list
        if self.get_nearest_entrance(west_entrance,
                                     east_entrance) == west_entrance:
            self.localizer.moveToGoal(Locations.WestEntrance)
            self.localizer.moveToGoal(Locations.Atrium)
            self.localizer.moveToGoal(Locations.CSOffice)
            self.localizer.moveToGoal(Locations.ElectronicsLab)
            self.localizer.moveToGoal(Locations.ComputerLab)
            self.localizer.moveToGoal(Locations.EastEntrance)
        else:
            self.localizer.moveToGoal(Locations.EastEntrance)
            self.localizer.moveToGoal(Locations.ComputerLab)
            self.localizer.moveToGoal(Locations.ElectronicsLab)
            self.localizer.moveToGoal(Locations.Atrium)
            self.localizer.moveToGoal(Locations.CSOffice)
            self.localizer.moveToGoal(Locations.WestEntrance)
        '''
        # Go to that highlight
        self.moveToGoal(nearest_highlight)

        # Add to "highlights visited"
        visited_highlights.append(nearest_highlight)

        # Keep going until all highlights are visited
        while len(visited_highlights) <= 6:

            # Calculate next highlight
            nearest_highlight = self.get_nearest_highlight()

            # Go to that highlight
            self.moveToGoal(nearest_highlight)

            # Add to "highlights visited"
            visited_highlights.append(nearest_highlight)

        '''
        print(
            "...And that's all! Thank you for participating in the Devon Tour!"
        )

    def get_nearest_entrance(self, west_entrance, east_entrance):
        west_entrance_distance = self.distance(west_entrance)
        east_entrance_distance = self.distance(east_entrance)

        print("distance to west entrance = " + str(west_entrance_distance))
        print("distance to east entrance = " + str(east_entrance_distance))

        if west_entrance_distance < east_entrance_distance:
            return west_entrance
        else:
            return east_entrance

    def distance(self, coordinates):
        distance = math.sqrt((self.localizer.position.x - coordinates.x)**2 +
                             (self.localizer.position.y - coordinates.y)**2)

        return distance

    def point_to_point_mode(self):
        ''' User chooses which highlights to go to'''
        choice = self.choose()

        # Depending on which highlight the user chooses, the robot will
        # move to the goal
        if (choice == 1):
            self.goalReached = self.localizer.moveToGoal(Locations.CSOffice)
            print(
                "We've reached the CS Office, where the CS department mainly" +
                " resides")
        elif (choice == 2):
            self.goalReached = self.localizer.moveToGoal(Locations.Atrium)
            print(
                "Welcome to the Atrium! This area is used for get-togethers," +
                "studying, welcome parties, and more!")
        elif (choice == 3):
            self.goalReached = self.localizer.moveToGoal(
                Locations.EastEntrance)
            print("This is the east entrance")
        elif (choice == 4):
            self.goalReached = self.localizer.moveToGoal(
                Locations.WestEntrance)
            print("This is the west entrance")
        elif (choice == 5):
            self.goalReached = self.localizer.moveToGoal(Locations.ComputerLab)
            print(
                "Inside this room here is the CS Computer Lab, where any CS" +
                " student can come in and use the machines or for TA's office"
                + " hours")
        elif (choice == 6):
            self.goalReached = self.moveToGoal(Locations.ElectronicsLab)
            print("In this room is the Electronics Lab.")

        # if choice isn't q and the robot reached its goal
        if (choice != 'q'):
            if (self.goalReached):
                rospy.loginfo("Reached highlight!")
            # If it fails to reach the goal
            else:
                rospy.loginfo("Couldn't reach the highlight, try again")

        # Loop to keep going until user quits the tour
        while choice != 'q':
            choice = self.choose()
            if (choice == 1):
                self.goalReached = self.localizer.moveToGoal(
                    Locations.CSOffice)
                print(
                    "We've reached the CS Office, where the CS department mainly"
                    + " resides")
            elif (choice == 2):
                self.goalReached = self.localizer.moveToGoal(Locations.Atrium)
                print(
                    "Welcome to the Atrium! This area is used for get-togethers,"
                    + "studying, welcome parties, and more!")
            elif (choice == 3):
                self.goalReached = self.localizer.moveToGoal(
                    Locations.EastEntrance)
                print("This is the east entrance")
            elif (choice == 4):
                self.goalReached = self.localizer.moveToGoal(
                    Locations.WestEntrance)
                print("This is the west entrance")
            elif (choice == 5):
                self.goalReached = self.localizer.moveToGoal(
                    Locations.ComputerLab)
                print(
                    "Inside this room here is the CS Computer Lab, where any CS"
                    +
                    " student can come in and use the machines or for TA's office"
                    + " hours")
            elif (choice == 6):
                self.goalReached = self.localizer.moveToGoal(
                    Locations.ElectronicsLab)
                print("In this room is the Electronics Lab.")

    def choose(self):
        ''' User chooses where they would like to start the tour'''
        tour = 'q'
        rospy.loginfo("Initializing P2P Guide mode.")
        rospy.loginfo("Press a key to go to the highlights:")
        rospy.loginfo("'1': CS/ECE Office")
        rospy.loginfo("'2': Atrium")
        rospy.loginfo("'3': East Entrance")
        rospy.loginfo("'4': West Entrance")
        rospy.loginfo("'5': Computer Lab")
        rospy.loginfo("'6': Electronics Lab")
        rospy.loginfo("'q': Quit")

        tour = input()
        return tour

    def shutdown(self):
        '''Shutdown function that's called when user
           inputs Ctrl + C
        '''
        rospy.loginfo("Stopping Turtlebot")
        self.motion.halt()
        rospy.sleep(1)  # ensures Turtlebot received the command before

    def avoid_obstacle(self):
        '''Checks where a nearby obstacle is and
           rotates accordingly
        '''
        left_laser = self.sensor.get_left_laser_value()
        mid_laser = self.sensor.get_mid_laser_value()
        right_laser = self.sensor.get_right_laser_value()

        # Check if obstacle in front is 1 ft away
        if mid_laser <= Distance.FOOT:
            self.motion.rotate_180()
        # Check if obstacle is 2 ft to the left
        elif left_laser < 2 * Distance.FOOT:
            self.motion.rotate_right()
        # Check if obstacle is 2 ft to the right
        elif right_laser < 2 * Distance.FOOT:
            self.motion.rotate_left()
Ejemplo n.º 45
0
 def setUp(self):
     sensor = Sensor(address="0.0.0.0", port=514)
     pump = Pump(address="0.0.0.0", port=514)
     decider = Decider(target_height=100, margin=.10)
     self.controller = Controller(sensor=sensor, pump=pump, decider=decider)
Ejemplo n.º 46
0
 def setUp(self):
     self.decider = Decider(200, .06)
     self.sensor = Sensor('127.0.0.1', 8011)
     self.pump = Pump('127.0.0.1', 8010)
     self.controller = Controller(self.sensor, self.pump, self.decider)
Ejemplo n.º 47
0
r22 = p2.line(x2, y22, color="navy", line_width=2)
ds12 = r12.data_source
ds22 = r22.data_source

channel = 0
speed = 500000
dt = 0.001

w.wiringPiSPISetup(channel, speed)
# only the first 5 bits are relevant the rest we don't care about
# Channel 0 01101XXX XXXXXXXX
# Channel 1 01111XXX XXXXXXXX
channel0_select = 'hE'
channel1_select = 'xE'

sensor1 = Sensor(channel0_select, 'Sensor 1')
sensor2 = Sensor(channel1_select, 'Sensor 2')

t0 = time.time()


@linear()
def update(step):
    global x1, x2, y1, y2
    global t0

    s1 = sensor1.read()
    s2 = sensor2.read()

    x1.append(step)
    x2.append(step)
Ejemplo n.º 48
0
 def __init__(self):
     self._low_pressure_threshold = 17
     self._high_pressure_threshold = 21
     self._sensor = Sensor()
     self._is_alarm_on = False
Ejemplo n.º 49
0
 def __init__(self, name):
     Sensor.__init__(self, name)
     self.update()
Ejemplo n.º 50
0
 def __init__(self, serialPath, serialBaud, logger=None):
     Sensor.__init__(self, self.name, logger)
     self.serialPath = serialPath
     self.serialBaud = serialBaud
     self.connect()
Ejemplo n.º 51
0
)
parser.add_argument(
    '--cycle',
    type=str,
    action="store",
    default="",
    help=
    "Specifiy a humidity cycle: minutes,min_humidity,max_humidity,[minutes,min,max]..."
)
args = parser.parse_args()

# Output
output = Output(args.output_pin)

# Sensor - and link it to the output
sensor = Sensor(args.sensor_pin, output)

# Graphs
graph = Graph(args.graphdir, sensor)
last_drawn = datetime.now()

# Build our simple humidity cycle if we don't have one
cycleposition = 0
if args.cycle:
    cycle = args.cycle.split(',')
else:
    cycle = [60, args.humiditymin, args.humiditymax]
cycle = [int(x) for x in cycle]

# Sanity
if len(cycle) % 3 != 0:
Ejemplo n.º 52
0
from sensor_utils import list_to_string

# loads settings from sensor.json or argv[1]
CONFIG_FILENAME = "sensor_config.json"

# Use default filename OR one given as argument
filename = CONFIG_FILENAME

print("test.py started with {} arguments: [{}]".format(
    len(sys.argv), list_to_string(sys.argv)))

if len(sys.argv) > 1:
    filename = sys.argv[1]

#config = Config(filename)

s = Sensor()

# for playback we can specify
#   sleep=0.1 for a fixed period between samples
# or
#   realtime=True which will pause the time between recorded sample timestamps.
# otherwise the playback will be as fast as possible.

t = TimeBuffer()

t.load('sensor_play.csv')

t.play(s.process_sample, realtime=True)
Ejemplo n.º 53
0
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()
Ejemplo n.º 54
0
from sensor import Sensor

mySensor = Sensor("COM3", 115200)
Ejemplo n.º 55
0
from event import Event

from bottle import route, run, template, static_file, request, response, redirect, abort, error, get, post
import bottle

from faker import Faker
from faker.providers import date_time

faker = Faker()
faker.add_provider(date_time)

user = User(1, 'admin', 'admin')
room1 = Room(1, 'Living Room')
room2 = Room(2, 'Dining Room')
room3 = Room(3, 'Bedroom')
sensor1 = Sensor(2, 'infrared', 'b')
camera1 = Camera(1)
camera1.online = True
sensor1.online = True
room1.sensors.append(sensor1)
room1.cameras.append(camera1)

user.rooms = [room1, room2, room3]

# setup an in-memory database
db = sqlite3.connect(':memory:')

with open('static/logs.txt') as f:
    logs = f.readlines()

Ejemplo n.º 56
0
from sensor import Sensor
import hashlib

s = Sensor('test_client', 'device1', 'bin_sensor1', 'switch')
s1 = s.get_hass_sensor()
s2 = s.get_dev_sensor()
print()
print(s1)
print("\n")
print(s2)
Ejemplo n.º 57
0
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}}})
Ejemplo n.º 58
0
 def __init__(self, config_file="config.ini"):
     self._read_config_file(config_file)
     self._sensors = [Sensor(d) for d in self._sensors_details]
from options import RecorderOptions
from visualizer import SensorVisualizer
from sensor import Sensor
from filter import Filter
from recorder import Recorder
from classifier import ClassifierBinary

parser = RecorderOptions()
opt = parser.parse()

raw_input("Enter to start")
sensor = Sensor(opt.n, opt.port, opt.freq)
filter = Filter(opt.n, opt.n)
visualizer = SensorVisualizer(repr=opt.repr)
recorder = Recorder(opt)
classifier = ClassifierBinary(opt.threshold, opt.index, opt.nStep)

print("action: {}".format(opt.action))


def main():
    lastSignal = False
    moveCount = 0
    stopCount = 0
    while True:
        data = sensor.read()
        data = filter.update(data)
        signal = classifier(data)
        if signal:
            moveCount += 1
            print('move', moveCount)
Ejemplo n.º 60
0
class ControllerTests(unittest.TestCase):
    """
    Unit tests for the Controller class
    """
    def setUp(self):
        """
        Sets up controller.
        """
        self.sensor = Sensor("127.0.0.1", "8000")
        self.pump = Pump("127.0.0.1", "8000")
        self.decider = Decider(100, .05)
        self.controller = Controller(self.sensor, self.pump, self.decider)

    def test_tick(self):
        """
        Test if decider.decide and pump.set_state are called with the correct
        parameters after controller.tick()
        """
        self.sensor.measure = MagicMock(return_value=100)
        self.pump.get_state = MagicMock(return_value=self.pump.PUMP_OFF)
        self.decider.decide = MagicMock(return_value=self.pump.PUMP_IN)
        self.pump.set_state = MagicMock(return_value=True)

        self.controller.tick()

        self.sensor.measure.assert_called_with()
        self.pump.get_state.assert_called_with()
        self.decider.decide.assert_called_with(100, self.pump.PUMP_OFF,
                                               self.controller.actions)
        self.pump.set_state.assert_called_with(self.pump.PUMP_IN)

    def test_raise_url_controller(self):
        """
        Test controller.tick raises the sensor.measure URLError
        """
        with self.assertRaises(URLError):
            self.controller.tick()

    def test_raise_url_sensor(self):
        """
        Test sensor.measure raises URLError
        """
        with self.assertRaises(URLError):
            self.sensor.measure()

    def test_raise_url_pump_get(self):
        """
        Test pump.get_state raises URLError
        """
        self.sensor.measure = MagicMock(return_value=100)
        with self.assertRaises(URLError):
            self.pump.get_state()

    def test_raise_url_pump_set(self):
        """
        Test pump.set_state raises URLError
        """
        self.sensor.measure = MagicMock(return_value=100)
        self.pump.get_state = MagicMock(return_value=self.pump.PUMP_OFF)
        with self.assertRaises(URLError):
            self.pump.set_state(self.pump.PUMP_OFF)