def sensorInit(
    sensorArray,
    spoof=0
):  #spoof determines whether sensors are fed real or fake data (demonstartion purposes)
    """Initializes all sensors to be used."""
    sensorArray.append(
        s.Sensor("Oxygen", "mg/l", spoof, lambda x: x, "red", 6.67))
    sensorArray.append(
        s.Sensor("Nitrogen", "mg/l", spoof, lambda x: x, "blue", 29.67))
Beispiel #2
0
    def __init__(self):
        self.consumers = []
        s = sensor.Sensor()
        hc = consumer.HttpConsumer(5 * 60)
        hc.plugto(s)

        fa = analyzer.FrequencyAnalyzer("HTTP_URL_FREQUENCY_10S", "hostname",
                                        30)
        fa.plugto(hc)

        fa2 = analyzer.FrequencyAnalyzer("HTTP_URL_FREQUENCY_2M", "hostname",
                                         30)
        fa2.plugto(hc)

        self.ids = ids.IDS()
        self.ids.plugto("HTTP_URL_FREQUENCY_10S")
        self.ids.plugto("HTTP_URL_FREQUENCY_2M")
        self.ids.plug(self)

        self.terminal = terminaloutput.TerminalOutput()
        self.terminal.addsection(
            terminaloutput.screensection("ALERT", "IDS Alerts", 10))
        self.terminal.addsection(
            terminaloutput.screensection("NOTIFICATION", "IDS Notifications",
                                         20))
        self.terminal.start()

        self.consumers.append(hc)
Beispiel #3
0
    def discover_sensors(self):
        """
            Tries to discover any sensor that is connected to Gilberto :
                 * List all connected ports
                 * Check if it's a new port
                 * Add if yes

        """

        # Browse devices
        for device in serial.tools.list_ports.comports():
            log.debug(device.product)
            if device.device not in self.sensors.keys():
                # Check if the device is an arduino uno
                if device.product in self.authorized_products:
                    log.debug('Arduino detected: ' + str(device.device))
                    try:
                        # Add as new arduino device
                        cur_device = sensor.Sensor(device.device)
                        # Waiting for the first message
                        cur_device.wait_helo()
                        # Waiting for the device uid
                        cur_device.uid = cur_device.uid().decode('utf-8')
                        # Create a new device manager
                        if cur_device.uid in self.authorized_uids:
                            log.debug('Recognized sensor')
                            self.sensors[cur_device.port] = cur_device
                            self.rmanagers[cur_device.port] = RaspManager(
                                self.central_address, self.central_port,
                                cur_device, cur_device.uid, self.websocket)
                            self.rmanagers[cur_device.port].device.state()
                        else:
                            log.warn('Unauthorized sensor connected')
                    except:
                        log.warn('could not connect to' + str(device.device))
Beispiel #4
0
    def on_start(self):
        if self.monitor_running:
            return

        # Disable widgets
        self.portbox.setDisabled(True)
        self.toolbar_buttons['select_path'].setDisabled(True)
        self.toolbar_buttons['rescan'].setDisabled(True)

        # ...disable action rescan
        self.menus['file'].children()[1].setDisabled(True)

        # Set selectable port to sensor
        port = self.portbox.currentText()
        self.serobj = serobj = serial.Serial(port, timeout=0.1)
        self.sensor = sensor.Sensor(serobj)

        # Run recieve data to single thread
        self.t = threading.Thread(target=self.sensor.run, daemon=False)
        self.t.start()

        # Run timer
        self.timer_recieve = self.startTimer(self.TIMEOUT,
                                             timerType=QtCore.Qt.PreciseTimer)

        self.status.showMessage("Running")
        self.monitor_running = True
Beispiel #5
0
 def sensorsRead(self):
     """Считать датчики из файла."""
     if os.path.exists(self.pathSensors):
         try:
             fileList = os.listdir(self.pathSensors)
             self.sensors.clear()
             self.groups.clear()
             for fileName in fileList:
                 with open('{}/{}'.format(self.pathSensors, fileName),
                           'r',
                           encoding="utf-8") as file:
                     for line in file:
                         line = line.replace('\n', '')
                         line = line.replace(' = ', '=')
                         temp = line.split('=')
                         if len(temp) > 1:
                             name = temp[1]
                         else:
                             name = 'No name'
                         ss = sensor.Sensor(temp[0], file, name)
                         self.sensors[temp[0]] = ss
                         if fileName in self.groups:
                             self.groups[fileName].add(ss)
                         else:
                             self.groups[fileName] = {ss}
                     file.close()
         except Exception:
             self.logged.emit(
                 '{} Sensors not readed from "{}"!'.format(
                     datetime.now().strftime('%H:%M:%S'), self.pathSensors),
                 'lsf')
     else:
         os.makedirs(self.pathSensors, 0o777, True)
Beispiel #6
0
def calibratePairs(theQuery):
    """Generator object to calibrate readings and return in JSON
    friendly format

    :param theQuery: SQLA query object containing readings
    """

    #Dictionary to hold all sensor paramters
    session = meta.Session()
    sensorParams = {}

    for reading in theQuery:
        theSensor = sensorParams.get((reading.nodeId, reading.typeId), None)
        LOG.debug("Original Reading {0} Sensor is {1}".format(
            reading, theSensor))
        if not theSensor:
            theSensor = session.query(sensor.Sensor)
            theSensor = theSensor.filter_by(
                nodeId=reading.nodeId, sensorTypeId=reading.typeId).first()
            if theSensor is None:
                theSensor = sensor.Sensor(calibrationSlope=1.0,
                                          calibrationOffset=0.0)
            sensorParams[(reading.nodeId, reading.typeId)] = theSensor

        theTime = time.mktime(reading.time.timetuple()) * 1000.0
        #theTime = reading.time.isoformat()
        theValue = (theSensor.calibrationSlope * reading.value)
        theValue += theSensor.calibrationOffset
        #theValue = reading.value

        yield (theTime, theValue)
Beispiel #7
0
    def __init__(self,
                 x,
                 y,
                 orient=180,
                 max_steer=0,
                 max_speed=5,
                 max_accel=5.0):
        self.pos = Vector2(x, y)
        self.vel = Vector2(0.0, 0.0)
        self.accel = Vector2(0.0, 0.0)
        self.engine_force = 0.0
        self.steer_angle = 0.0
        self.orient = orient
        self.brake_b = 0
        self.gear = 1  #0:park, 1:drive, 2:reverse
        self.prev_pos = Vector2(0, 0)
        self.pos_buf = Vector2(0, 0)
        self.terrain = 0
        self.drag = C_DRAG_ROAD
        self.RR = 30 * self.drag
        self.ang_vel = 0

        # Sensors
        self.front_sensor = sensor.Sensor(x, y)

        # Threshold Constants
        self.max_steer = max_steer
        self.max_speed = max_speed
Beispiel #8
0
def calibrateReadings(theQuery):
    """Generator object to calibate all readings,
    hopefully this gathers all calibration based readings into one
    area

    :param theQuery: SQLA query object containing Reading values"""

    #Dictionary to hold all sensor paramters
    session = meta.Session()
    sensorParams = {}

    for reading in theQuery:

        theSensor = sensorParams.get((reading.nodeId, reading.typeId), None)
        LOG.debug("Orig Reading {0} Sensor is {1}".format(reading, theSensor))
        if not theSensor:
            theSensor = session.query(sensor.Sensor).filter_by(
                nodeId=reading.nodeId, sensorTypeId=reading.typeId).first()
            if theSensor is None:
                theSensor = sensor.Sensor(calibrationSlope=1.0,
                                          calibrationOffset=0.0)
            sensorParams[(reading.nodeId, reading.typeId)] = theSensor

        #Then add the offset etc
        cReading = Reading(
            time=reading.time,
            nodeId=reading.nodeId,
            typeId=reading.typeId,
            locationId=reading.locationId,
            value=theSensor.calibrationOffset +
            (theSensor.calibrationSlope * reading.value),
        )

        yield cReading
Beispiel #9
0
def task_right_sensor():
    ''' Function which runs for Task 2, which measures the distance noise is from the robot.  '''
    global RIGHT_SENSOR
    state = GATHER
    sensor1 = sensor.Sensor(pyb.Pin.board.PA8, pyb.Pin.board.PA9)

    limit = 35000

    while True:

        if state == GATHER:
            ''' measures the distance robot is from objects based on noise, 5 sensors'''
            echo1 = sensor1.measure_distance()

            if (echo1 < limit):
                RIGHT_SENSOR = 1
                state = SEND

        elif state == SEND:
            ''' sends single to motor task to move backward'''
            echo1 = sensor1.measure_distance()
            if (echo1 > limit):
                RIGHT_SENSOR = 0
                state = GATHER

        yield (state)
def take_landmarks_handler(req):
    global incoming_landmarks, incoming_landmarks_lock
    global sensor, sensor_lock
    #rp.logwarn(req.client_name + ": " + str(req.client_pose))
    R = np.eye(3)
    p = np.array(req.client_pose.p)
    R[:, 0] = np.array(req.client_pose.x)
    R[:, 1] = np.array(req.client_pose.y)
    R[:, 2] = np.array(req.client_pose.z)
    R = uts.rotation_fix(R)
    client = sns.Sensor(pos=np.array(p), ori=np.array(R), fp=fp.EggFootprint())
    #rp.logwarn(client)
    client_landmarks = [
        lm.Landmark.from_msg(lmk_msg) for lmk_msg in req.client_landmarks
    ]
    my_new_landmarks = set()
    client_new_landmarks = set()
    success = False
    sensor_lock.acquire()
    #rp.logwarn(sensor.pos)
    for lmk in client_landmarks:
        #rp.logwarn(client.perception(lmk)-sensor.perception(lmk))
        if sensor.perception(lmk) < client.perception(lmk) - 1e-2:
            my_new_landmarks.add(lmk)
            success = True
        else:
            client_new_landmarks.add(lmk)
    sensor_lock.release()
    if success:
        incoming_landmarks_lock.acquire()
        incoming_landmarks |= my_new_landmarks
        incoming_landmarks_lock.release()
    return csv.TakeLandmarksResponse(
        success=success,
        client_new_landmarks=[lmk.to_msg() for lmk in client_new_landmarks])
Beispiel #11
0
 def __init__(self, _object, metadata=None):
     if (metadata != None):
         self.metadata = EntityAttribute(metadata)
     objectType = type(_object)
     print(objectType)
     if (objectType is float):
         self.type = "Float"
         self.value = float(_object)
     elif objectType is int:
         self.type = "Integer"
         self.value = int(_object)
     elif objectType is str:
         self.type = "String"
         self.value = str(_object)
     elif objectType is bool:
         self.type = "Boolean"
         self.value = bool(_object)
     elif objectType is list:
         self.type = "Array"
         self.value = []
         for item in _object:
             if item is SensorDataEntry or isinstance(
                     item, SensorDataEntry):
                 self.value.append(sensor.Sensor(item))
             else:
                 self.value.append(EntityAttribute(item))
     elif objectType is dict:
         for key, value in _object.iteritems():
             setattr(self, key, EntityAttribute(value))
     else:
         self.type = _object.__class__.__name__
         tempDict = {}
         for key, value in _object.__dict__.iteritems():
             tempDict[key] = EntityAttribute(value)
         self.value = tempDict
def take_landmarks_handler(req):
    global incoming_landmarks, incoming_landmarks_lock
    global sensor, sensor_lock
    client = sns.Sensor(pos=np.array(req.client_pose.position),
                        ori=np.array(req.client_pose.orientation),
                        fp=init_sns.sensors[req.client_name]._fp)
    client_landmarks = [
        lm.Landmark.from_msg(lmk_msg) for lmk_msg in req.client_landmarks
    ]
    my_new_landmarks = set()
    client_new_landmarks = set()
    success = False
    sensor_lock.acquire()
    for lmk in client_landmarks:
        if sensor.perception(lmk) < client.perception(lmk):
            my_new_landmarks.add(lmk)
            success = True
        else:
            client_new_landmarks.add(lmk)
    sensor_lock.release()
    if success:
        incoming_landmarks_lock.acquire()
        incoming_landmarks |= my_new_landmarks
        incoming_landmarks_lock.release()
    return csv.TakeLandmarksResponse(
        success=success,
        client_new_landmarks=[lmk.to_msg() for lmk in client_new_landmarks])
def init(amount,d_max,timer,RTS_enable,suspend_enable,CWmax,channel,threshold=0.8,detection_time=300*10**3,data_size=100):
    CWmin=16
    file=open(os.path.pardir+"/events/station_list_amount="+str(amount)+"_d_max="+str(d_max)+".pkl","rb")
    import pickle
    amount=pickle.load(file)
    system_AP=AP.AP([0,0],CWmin,CWmax,timer,channel,threshold,detection_time)
    STA_list=[]
    for i in range(amount): # generate sensors according to the recorded locations
        x=pickle.load(file)
        y=pickle.load(file)
        STA_list.append(sensor.Sensor(i+1,CWmin,CWmax,[x,y],RTS_enable,suspend_enable,system_AP,timer,channel,data_size))
    file.close()
    system_AP.register_associated_STAs(STA_list)
    file=open(os.path.pardir+"/events/packet_events_amount="+str(amount)+"_d_max="+str(d_max)+".pkl","rb")
    amount=pickle.load(file)
    print("there are "+str(amount)+" packet there")
    for i in range(amount): # load event from the corresponding file
        start_time=pickle.load(file)
        AID=pickle.load(file)
        assert STA_list[AID-1].AID==AID
        new_event=event.Event("packet arrival",start_time)
        new_event.register_device(STA_list[AID-1])
            # event=pickle.load(file)
        timer.register_event(new_event)
        statistics_collection.collector.register_packet_generated()
    file.close()
    system_AP.STA_list=STA_list
    print("STA amount is "+str(STA_list.__len__()))
    return(system_AP,STA_list)
 def register_sensors(self):
     print "register sensors"
     sensors = []
     for node in self.graph.nodes:
         if not node.is_entry and not node.is_exit and len(node.entries) > 0:
             sensors.append(sensor.Sensor(node))
     return sensors
Beispiel #15
0
    def __init__(self, _file_name = '', _file_object = None,
                                               _store=False, 
                                          sensor_qual='tac',
                                              wideband=True,
                                             nullshift=True,
                                             biasdrift=True):
        """
        Imu_sensor class models a 6 DOF inertial measurement unit (IMU).
        Given a data file with the true imu values, this class will load that
        and dynamically generate the modeled errors as the `measured` imu values
        are requested.  All errors are generated `on-the-fly`, removing
        any requirement to load all the data into memory.
        
        Varying time steps will be handled in two ways:
        1) the true imu values will be interpolated
        2) the errors generated will adapt to the timestep size
        
        Parameters
        ----------
          _file_name: path to file containing true imu values [string]
        _file_object: name of file object open to true imu measurements [file object]
              _store: flag specifying whether values will be stored with time stamps [True/False]
         sensor_qual: string specifying inertial sensor quality.
                  Acceptable values: 'nav' or 'navigation'
                                     'tac' or 'tactical'
                                     'con' or 'consumer'
        
        *Flags specifying what errors will be used to corrupt the imu measurement*
        
         wideband: wideband noise
        nullshift: run-to-run varying bias (constant for duration of run)
                   (note: see self._generate_null_shift_errors documentation)
        biasdrift: bias instability (modeled as first-order Markov process)

        Note: seeding is NOT currently supported
        TODO: The inertial sensor specification is really the "root PSD" and needs to 
               be converted into a STD of noise sample!  You can't use the "root PSD"
               directly!
               This should be updated in parallel with the numbers and units specifications
               of the inertial_sensors object class
        """
    
        # Checks for valid file name or object takes place in Sensor class.
        self._sensor_obj  = sensor.Sensor(file_name = _file_name, file_object = _file_object)
        self.sensor_qual = sensor_qual
        
        # Generate sensor quality dictionary
        self._sqd = inertial_qual.get_parameters(sensor_qual)
        
        # Store flag values
        self._flag_store = _store
        self._flag_wideband  = wideband
        self._flag_nullshift = nullshift
        self._flag_biasdrift = biasdrift
        
        # Initialze a state to count the number of unique time calls
        # to  get_imu() where corrputed measurements were requested.
        self._ncalls = 0
Beispiel #16
0
def initialize(configFile):
    config = configparser.ConfigParser()
    config.read(configFile)
    for section in config:
        if "sensor" in section:
            name = config[section]['name']
            type = config[section]['type']
            pin = config[section]['pin']
            sensors.append(sensor.Sensor(name, type, int(pin)))
    return config['settings']['apiToken']
Beispiel #17
0
	def read_sensor_list(self):
		with open('sensor.list') as f:
			sensor_list = f.readlines()
			sensor_list = [x.strip('\n') for x in sensor_list]
			#print("Server: following sensors read")
			#print("\t"+str(sensor_list))
			self.logData("Following sensors read from sensor.list")
			self.logData("\t" + str(sensor_list))
                        for x in sensor_list:
                                self.sensor_list.append(sensor.Sensor(x, re.search("(.*)_.*", x).group(1)))
Beispiel #18
0
def main(): 

    def readTest(filename,col):
        ''' read testcase from file, col being the number of col interested'''
        with open(filename, 'rb') as csvfile:
            spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
            time=[]
            action=[]
            spamreader.next()
            for row in spamreader:
                time.append(row[0])
                action.append(row[col])     
            return time, action    



    def interaction(temp,timel,action):
        '''react according to the testcase'''
        if action[0]!='Register':
            print "Error: register client first"
        temp.register_to_server()
        time.sleep(float(timel[1])+float(setting.start_time) - time.time())
        for index in range(1,len(timel)-1):
            temp.set_state_push(action[index])
            #calculate time remained before next point in the timeline
            waitTime = float(timel[index+1])+float(setting.start_time) - time.time()
            if waitTime>0:
                time.sleep(waitTime)

        temp.set_state_push(action[len(timel)-1])
      
    def start_sync():
        '''sync time of different process before running'''
        current_time = int(time.time())
        waitT = setting.start_time - current_time
        time.sleep(waitT)

    temp = sensor.Sensor("motion",serveradd,localadd,devNum)
    
    # create a thread to listen, deal with server pulls
    temp.leader_elect()
    temp.time_syn()
    listen_thread = temperature(temp)
    listen_thread.start()

    timel,action= readTest('test-input.csv',2)

    start_sync()
    interaction(temp,timel,action)  
    time.sleep(10)
def measure(vref, gain, duration, delay, file_name):

    # I need to also consider the first measurment at t = 0
    max_iterations = math.ceil(duration / delay) + 1
    data = np.zeros(shape=(max_iterations, 2))  # array full of 0's

    plt.ion()  # turn interactive mode on

    with sensor.Sensor(port, baudrate=9600, timeout=1) as arduino:
        arduino.set_gain(gain)
        arduino.set_ref_voltage(vref)

        print("Initialization complete! Starting measurements.")

        i = 0  # counts the number of measurments taken
        # I do this once at t = 0s
        temperature = arduino.get_temp()
        save_to_file(file_name, i * delay, temperature)
        data[i] = [i * delay, temperature]

        print(data[i])  # prints the time and temperature

        add_to_plot(data)

        i += 1
        # Then I do it every "delay" seconds
        t_prev = time.time()

        while True:
            t_now = time.time()

            if t_now - t_prev >= delay:
                t_prev = t_now

                temperature = arduino.get_temp()
                save_to_file(file_name, i * delay, temperature)

                data[i] = [i * delay, temperature]  # add row to matrix

                print(data[i])

                add_to_plot(data)

                i += 1

                if i >= max_iterations:
                    break

    plt.title("Measurment complete.")
    print("Measurments done! There were ", i, " measurements.")
Beispiel #20
0
    def setUp(self):
        data = 't	north	east	down	yaw	pitch	roll \n\
                0.0	3.57	-3.0	0	-2.0	0	0\n\
                0.5	3.57	-3.1	0	-3.0	0	0\n\
                1.0	3.57	-3.2	0	-4.0	0	0\n\
                1.5	3.57	-3.4	0	-5.0	0	0\n\
                2.0	3.57  -3.5	0	-6.0	0	0\n\
                2.5	nan	nan	nan	nan	nan	nan\n\
                3.0	3.57	-3.7	0	-8.0	0	0\n\
                3.5	3.57	-3.8	0	-9.0	0	0\n\
                4.0	3.57	-3.9	0	-10.0	0	0\n\
                4.5	3.57	-4.0	0	-9.0	0	0\n\
                5.0	3.57	-4.1	0	-8.0	0	0'

        lines = StringIO.StringIO(data)
        self.sensor = sensor.Sensor(file_object=lines)
Beispiel #21
0
    def get_sensors(self, start_dt, end_dt):
        for sensor_type in self.supported_sensors:
            if show_messages or running_cli:
                print("Retrieving {} data...".format(sensor_type))
            sensor_url = self.__get_sensor_url(self.node_id, sensor_type,
                                               start_dt, end_dt)
            url_request = urllib.request.urlopen(sensor_url, context=context)
            url_response = url_request.read().decode()

            sensor_data_json = json.loads(url_response)["data"]
            sensor_item = sensor.Sensor(sensor_type, start_dt, end_dt,
                                        sensor_data_json)
            self.sensors.append(sensor_item)

            if show_messages or running_cli:
                print("Retrieved {} data".format(sensor_type))
Beispiel #22
0
 def __init__(self, _object, metadata=None):
     objectType = type(_object)
     # Floats
     if (objectType is float):
         self.type = "Float"
         self.value = float(_object)
     # Ints
     elif objectType is int:
         self.type = "Integer"
         self.value = int(_object)
     # Strings
     elif objectType is str:
         self.type = "String"
         self.value = str(_object)
     # Booleans
     elif objectType is bool:
         self.type = "Boolean"
         self.value = bool(_object)
     # Lists/Arrays
     elif objectType is list:
         self.type = "Array"
         self.value = []
         for item in _object:
             # Sensors
             if isinstance(item, SensorDataEntry):
                 self.value.append(sensor.Sensor(item))
             # Readings
             elif isinstance(item, SensorReading):
                 self.value.append(reading.Reading(item))
             # Generic objects
             else:
                 self.value.append(EntityAttribute(item))
     # Dictionaries
     elif objectType is dict:
         for key, value in _object.iteritems():
             setattr(self, key, EntityAttribute(value))
     # Other objects
     else:
         self.type = _object.__class__.__name__
         tempDict = {}
         for key, value in _object.__dict__.iteritems():
             tempDict[key] = EntityAttribute(value)
         self.value = tempDict
     # Add metadata
     if (metadata != None):
         self.metadata = EntityAttribute(metadata)
Beispiel #23
0
    def test_sep(self):
        """ Check to handle separators other than whitespace."""
        data = 't,	north,	east,	down,	yaw,	pitch,	roll \n\
                0.0, 3.57,	-3.0,	0,	-2.0,	0,	0\n\
                0.5, 3.57,	-3.1,	0,	-3.0,	0,	0\n\
                1.0, 3.57,	-3.2,	0,	-4.0,	0,	0\n\
                1.5, 3.57,	-3.4,	0,	-5.0,	0,	0\n\
                2.0, 3.57,  -3.5,	0,	-6.0,	0,	0\n\
                2.5, nan, nan, nan, nan, nan, nan'

        lines = StringIO.StringIO(data)
        sensor_obj = sensor.Sensor(file_object=lines, sep=',')

        t1 = 1.0

        for e1, e2 in zip(sensor_obj.get(t1), [3.57, -3.2, 0, -4.0, 0, 0]):
            self.assertAlmostEqual(e1, e2, places=8)
Beispiel #24
0
def calibPandas(theQuery):
    """Generator object to calibate all readings,
    hopefully this gathers all calibration based readings into one
    area

    :param theQuery: SQLA query object containing Reading values"""

    #Dictionary to hold all sensor paramters
    session = meta.Session()
    sensorParams = {}

    for reading in theQuery:

        theSensor = sensorParams.get((reading.nodeId, reading.typeId), None)
        #LOG.debug("Original Reading {0} Sensor is {1}".format(reading,theSensor))
        if not theSensor:
            #theSensor = "FOO"
            theSensor = session.query(sensor.Sensor).filter_by(
                nodeId=reading.nodeId, sensorTypeId=reading.typeId).first()
            if theSensor is None:
                theSensor = sensor.Sensor(calibrationSlope=1.0,
                                          calibrationOffset=0.0)
            sensorParams[(reading.nodeId, reading.typeId)] = theSensor

        #Then add the offset etc
        cReading = {
            "time":
            reading.time,
            "nodeId":
            reading.nodeId,
            "typeId":
            reading.typeId,
            "locationId":
            reading.locationId,
            "locationStr":
            reading.location.room.name,
            "value":
            theSensor.calibrationOffset +
            (theSensor.calibrationSlope * reading.value),
            "location":
            "Node {0}: {1} {2}".format(reading.nodeId,
                                       reading.location.room.name,
                                       reading.sensorType.name),
        }

        yield cReading
Beispiel #25
0
    def test_scalar(self):
        """ Check for scalar data to be returned as scalar (not list)."""
        data = 't,	baroalt\n\
                0.0, 3.57\n\
                0.5, 3.57\n\
                1.0, 3.57\n\
                1.5, 3.57\n\
                2.0, 3.57\n\
                2.5, nan'

        lines = StringIO.StringIO(data)
        sensor_obj = sensor.Sensor(file_object=lines, sep=',')

        t1 = 1.0
        h = 3.57
        h_computed = sensor_obj.get(t1)
        # Check for both scalar type and for accuracy.
        self.assertTrue(isinstance(h_computed, numbers.Number))
        self.assertAlmostEqual(h, h_computed)
Beispiel #26
0
        def __init__(self, play_mode, sock):
            self.play_mode = play_mode
            self.sock = sock

            self.orientation = sensor.orientation.TOP
            self.won = False
            self.elapsed_time = 0.0
            self.last_attack = 0.0
            self.health = INITIAL_HEALTH
            self.orientation_history = zeros(HISTORY_SIZE)
            self.index = 0
            self.game_over = False
            self.quitting = False

            volume_options = [[u"Volume off", 0], [u"Volume low", 1],
                              [u"Volume med", 2], [u"Volume high", 3]]

            appuifw.app.exit_key_handler = self.quit
            appuifw.app.menu = [(u"Choose skin",
                                 tuple([(unicode(skin["skinName"].title()),
                                         self.skin_changer(skin))
                                        for skin in ui.SKINS])),
                                (u"Set volume",
                                 tuple([(option[0],
                                         self.volume_changer(option[1]))
                                        for option in volume_options])),
                                (u"Back to the fight", self.back_to_fight),
                                (u"Back to main menu", self.quit)]

            self.__timer = e32.Ao_timer()

            self.event = None
            self.eventlock = e32.Ao_lock()

            axyz.connect(self.new_accel_data)

            sensor_type = sensor.sensors()['RotSensor']
            self.rotation_sensor = sensor.Sensor(sensor_type['id'],
                                                 sensor_type['category'])
            self.rotation_sensor.set_event_filter(sensor.RotEventFilter())
            self.rotation_sensor.connect(self.new_rotation_data)

            self.tick()
Beispiel #27
0
 def __init__(self, host='127.0.0.1'):
     self.s = Server(duplex=0).boot()
     self.s.start()
     self.sensor = sensor.Sensor()
     self.base_note = 261.6
     self.pitch_low = 600
     self.pitch_high = 60
     self.vol_low = 60
     self.vol_high = 600
     self.running = True
     self.sound_file = 'synth1'
     self.octave_shift = 0
     self.host = host
     self.bpm = 140
     self.rec = ''
     self._prev_far_limit = True
     self._prev_pitch = 1
     self.repeat = 0
     self.fun_mode = False
Beispiel #28
0
    def __init__(self):
        appuifw.app.screen = "normal"
        appuifw.app.menu = [(u"Translate", self.onTranslate),
                            (u"Source language", self.onSetSource),
                            (u"Target language", self.onSetTarget),
                            (u"Access point", self.onSetAccessPoint),
                            (u"Clear", self.onClear),
                            (u"Exit", self.onExit)]
        self.lock = e32.Ao_lock()
        self.text = appuifw.Text(u"")
        self.text.font = "normal"
        self.source = "en"
        self.target = "da"
        self.uiLang = "en"
        self.sourceList = None
        self.targetList = None
        self.accessPointId = None
        self.accessPoint = None
        self.lastSensed = time.time()
        self.accelerometer = None
        self.minSensed = 0
        self.maxSensed = 0
        self.sensing = True
        self.sortedLanguageLists = {}
        
        self.restoreSettings()
        self.setTitle()
    
        appuifw.app.body = self.text
        appuifw.app.exit_key_handler = self.onExit

        # Install accelerometer sensor callback
        try:
            import sensor
            accInfo = sensor.sensors()['AccSensor']
            self.accelerometer = \
                sensor.Sensor(accInfo['id'], accInfo['category'])
            if 0: self.accelerometer.connect(self.onAccelerate)
        except:
            pass
        
        self.lock.wait()
def test_rotation_sensor():
    def rotation_callback(orientation_value):
        print 'New orientation: ', orientations[orientation_value]

    if 'RotSensor' not in sensors_supported:
        print "Rotation sensor not supported by this device"
        return

    rot_sensor_data = sensors_supported['RotSensor']
    rot_sensor = sensor.Sensor(rot_sensor_data['id'],
                               rot_sensor_data['category'])

    print 'Rotate the phone to validate orientation..(Testing for 15 seconds)'
    rot_sensor.set_event_filter(sensor.RotEventFilter())
    rot_sensor.connect(rotation_callback)

    e32.ao_sleep(15)

    rot_sensor.disconnect()
    print 'Rotation sensor test finished'
Beispiel #30
0
def main():
    """Main prog"""

    #init default sensors
    sens = sensor.Sensor()

    debug = var.debug

    done = False

    wk = stt.Stt("keyword")
    voice = tts.Tts()
    voice.say("charly fait pouet pouet")

    done = False

    #main loop
    while not done:
        #waiting someone putting the magic button or someone saying magical word
        #TODO
        if (var.keyword_ok == True):
            var.keyword_ok = False
            wk.stop()
            #someone is here
            #so we try to recognise him/her with camera and ask what to do
            #if recognise
            #speak to recognised people
            voice.say("bonjour brice")
            text = font.render("Bonjour", True, (250, 250, 250))
            wk = stt.Stt("keyword")
            #else speak to unknown

            wk.stop()

            #after delay without more restart thread
        #else:
        #sleep mode ?
        #if (debug):
        #    print("no one")

    exit()