Exemple #1
0
class GestureOnlyEnvironment(Environment):
    """
    A subclass of Environment that does not interface with the display,
    but rather takes advantage of the basic handlers defined for the
    gesture-control interface.
    """

    activeHandlers = [
        # PrintOctothorpeHandler,
        LuxControlHandler,
        # MacOSMouseControlHandler,
    ]

    def startUp(self):
        if YAPI.RegisterHub('usb', YRefParam()) != YAPI.SUCCESS:
            sys.exit('Connection error: connection through USB failed')

        self.tiltSensorRight = Sensor()

        # bootstrap handlers
        for h in self.activeHandlers:
            self.tiltSensorRight.attachHandler(h())
        self.tiltSensorRight.startWatching()

        # start display update loop
        def loop():
            threading.Timer(.10, loop).start()

            # no-op here

        loop()
Exemple #2
0
def read_sensors(n, time_start, wait_time):

    # Valve Definition and Classes
    vent_valve = Valve('Vent Valve', 'P8_12', 0, 'Solenoid', 0, 0)

    # Pressure Sensor Definition and Classes
    pressure_cold_flow = Sensor('pressure_cold_flow', 'pressure', 'P9_12',
                                'P9_14', 'P9_16', '000', '000', '000')

    pressure_list = []
    pressure_time_list = []

    for i in range(100):
        pressure, time_pres = pressure_cold_flow.read_sensor()
        pressure_list.append(pressure)
        pressure_time_list.append(time_pres + wait_time * n)

    current_time = 'Time Update: {} seconds'.format(time.time() - time_start)
    print(current_time)
    saved_data_combined = [pressure_list, pressure_time_list]
    export_data = zip_longest(*saved_data_combined, fillvalue='')

    with open('leak_data.csv', 'a', encoding="ISO-8859-1",
              newline='') as myfile:
        wr = csv.writer(myfile)
        wr.writerows(export_data)
    myfile.close()
Exemple #3
0
    def __init__(self, robot, sensingShape, requests, obstacles):
        '''Constructor'''
        Sensor.__init__(self, robot, sensingShape)

        self.requests = requests
        self.obstacles = obstacles
        self.all_requests = requests

        def world_reply_handler(channel, data):
            msg = world_msg_t.decode(data)
            print('World reply from cozmo:', list(msg.cubes),
                  list(msg.cube_light))
            # update requests position
            [
                r.region.translate(np.asarray(p[:2]) - r.region.center)
                for r, p in it.izip(self.all_requests, msg.cube_pose)
            ]
            # select visible and active requests (lights on and in camera view)
            self.requests = [
                r for idx, r in enumerate(self.all_requests)
                if msg.cubes[idx] and msg.cube_light[idx] > 0
            ]
            self.obstacles = []  #TODO:

        self.lc = lcm.LCM()
        self.lc.subscribe('WORLD', world_reply_handler)

        self.poll_msg = poll_msg_t()
        self.cube_msg = cube_msg_t()
Exemple #4
0
def collect_data(id):
    msg_counter = 0
    try:
        sensors = Sensor()
        while True:
            sensor_response = sensors.read_sensors()
            send_message(id, sensor_response)
            msg_counter += 1
            sleep(2)
    except KeyboardInterrupt:
        print "messages sent: {}".format(msg_counter)
        connection.close()
Exemple #5
0
    def startUp(self):
        if YAPI.RegisterHub('usb', YRefParam()) != YAPI.SUCCESS:
            sys.exit('Connection error: connection through USB failed')

        self.tiltSensorRight = Sensor()

        # bootstrap handlers
        for h in self.activeHandlers:
            self.tiltSensorRight.attachHandler(h())
        self.tiltSensorRight.startWatching()

        # start display update loop
        def loop():
            threading.Timer(.10, loop).start()

            # no-op here

        loop()
Exemple #6
0
 def build_sensor_from_url(self, url, admins):
     sensor = Sensor.from_url(url, admins)
     if sensor.type == "camera":
         sensor.on_changed = self.event_camera
     elif sensor.type == "notify":
         sensor.on_changed = self.event_notify
     else:
         sensor.on_changed = self.event_sensor
     return sensor
Exemple #7
0
def get_current_bearing():
    while True:
        time.sleep(1)
        try:
            # p.moveLeft("1200")
            s = p.sendMessage("GET,ALIM")
            if ("None" not in s):
                robot_bearing = float(s.split(',')[0].split('(')[1])
                print("robot current bearing: ", robot_bearing)
                return robot_bearing
        except:
            print("data not found")
Exemple #8
0
    def __init__(self):
        # #############################################################################
        # ######                                                                 ######
        # ###                            Initialization                             ###
        # ######                                                                 ######
        # #############################################################################

        # Position                                   [m]
        # Velocity                                   [m/s]
        # Orientation: Euler angles: Z - Y - X body axis - yaw, pitch, roll
        # Orientation: mt.Quaternion - Note: make sures this is the propor representation of zero rotation
        # Angular velocity in vehicle frame [p, q, r][rad/s] p*b1 + q*b2 + r*b3
        self.state = State()
        self.stateTarget = State()
        self.sensor = Sensor()

        self.t = 0

        self.controller = None
        self.path = None

        # #############################################################################
        # ######                                                                 ######
        # ###                          Physical Constants                           ###
        # ######                                                                 ######
        # #############################################################################

        # RPM to force constant (F = k_f * omega^2)  [N/rpm^2]
        self.k_f = 6.11 * 10**-8
        # RPM to moment constant (F = k_m * omega^2) [Nm/rpm^2]
        self.k_m = 1.5 * 10**-9
        # Quad arm length                   [m]
        self.armLength = 0.086
        # Max thrust per motor              [N]
        self.maxThrust = 0.883
        # Max thrust per motor              [N]
        self.minThrust = 0
        # Total mass                        [kg]
        self.mass = 0.18
        # Moment of inertia                 [kg m^2]
        # self.i = np.array([[0.2500, 0, 0.0026],
        #                    [0,      0.2320, 0],
        #                    [0.0026, 0, 0.3738]])*0.001
        self.i = np.diag([0.25, 0.25, 0.37]) * 0.001
        self.iInv = np.linalg.inv(self.i)
        # matrix mapping the thrust vector to moments
        gamma = self.k_m / self.k_f
        self.m1 = np.array([[0,               self.armLength, 0,             -self.armLength],
                            [-self.armLength, 0,              self.armLength, 0             ],
                            [gamma,          -gamma,          gamma,         -gamma         ]])

        self.params = Params(self.mass, -Quad.g[2], self.i)
Exemple #9
0
    def __init__(self, jsonfile, logfile, sipcallfile, optsUpdateUI=None):
        """ Init for the Worker class """

        print("{0}------------ INIT FOR DOOR SENSOR CLASS! ----------------{1}"
              .format(bcolors.HEADER, bcolors.ENDC))
        # Global Variables
        self.jsonfile = jsonfile
        self.logfile = logfile
        self.sipcallfile = sipcallfile
        self.settings = self.ReadSettings()
        self.limit = 10
        self.logtypes = 'all'

        # Stop execution on exit
        self.kill_now = False

        # Init Alarm
        self.mynotify = Notify(self.settings)
        self.mynotify.setupUpdateUI(optsUpdateUI)
        self.mynotify.setupSendStateMQTT()
        mylogs = Logs(self.logfile)
        self.getSensorsLog = mylogs.getSensorsLog
        self.writeLog("system", "Alarm Booted")
        mylogs.startTrimThread()

        # Event Listeners
        self.sensors = Sensor()
        self.sensors.on_alert(self.sensorAlert)
        self.sensors.on_alert_stop(self.sensorStopAlert)
        self.sensors.on_error(self.sensorError)
        self.sensors.on_error_stop(self.sensorStopError)
        self.sensors.add_sensors(self.settings)

        # Init MQTT Messages
        self.mynotify.on_disarm_mqtt(self.deactivateAlarm)
        self.mynotify.on_arm_mqtt(self.activateAlarm)
        self.mynotify.on_sensor_set_alert(self.sensorAlert)
        self.mynotify.on_sensor_set_stopalert(self.sensorStopAlert)
        self.mynotify.sendStateMQTT()
Exemple #10
0
    def startUp(self):
        if YAPI.RegisterHub('usb', YRefParam()) != YAPI.SUCCESS:
            sys.exit('Connection error: connection through USB failed')

        self.tiltSensorRight = Sensor()
        self.display = Display()

        # bootstrap handlers
        for h in self.activeHandlers:
            self.tiltSensorRight.attachHandler(h())
        self.tiltSensorRight.startWatching()

        # start display update loop
        def loop():
            threading.Timer(.10, loop).start()

            self.display.updateStatus()

            # for debugging, show data in the message row for now
            self.display.updateMessage('P:{} R:{}'.format(
                str(pitch), str(roll)))

        loop()
Exemple #11
0
 def initDevice(self, comport, id):
     # Toevoegen van een nieuw device
     sleep(1)
     try:
         ser = Serial(comport, 19200, timeout=2)
         sleep(2)
         # Zolang er fout optreed stuur command "_INIT"
         while True:
             ser.write(b"_INIT\n")
             device_type = ser.readline().decode("UTF-8").strip('\n')
             if device_type != "_ERR":
                 break
         if device_type == "_MTR":
             # Device is een aansturing
             # Stuur command "_CONN" zolang er fout optreed
             while True:
                 ser.write(b"_CONN\n")
                 device_type = ser.readline().decode("UTF-8").strip('\n')
                 if device_type != "_ERR":
                     break
             # Maak nieuw aansturing (MotorControl) aan
             a = MotorControl(ser, id)
             self.motorControls.append(a)
         elif device_type == "_TEMP" or device_type == "_LGHT":
             # Maak nieuwe sensor aan
             sensor = Sensor(ser, device_type, id, self.sensors)
             if (self.loggedin):
                 self.sensorsWithoutGraph.append(sensor)
             self.sensors.append(sensor)
             ser.write(b"_CONN\n")
         else:
             # Als device type onbekend is,
             # voeg toe aan onbekende COM-porten
             self.other_com_ports.append(comport)
     except SerialException as E:
         print(E)
         # Als er een fout optreed,
         # voeg toe aan onbekende COM-porten
         self.other_com_ports.append(comport)
Exemple #12
0
 def __init__(self):
     self.lmotor = Motor(4, 0x09, 1)
     self.rmotor = Motor(4, 0x09, 2)
     self.camera = Camera()
     self.sensor = Sensor()
Exemple #13
0
class Quad(object):
    # Gravity
    g = np.array([0, 0, -9.81])
    # Integration step
    dt = 0.0001

    def __init__(self):
        # #############################################################################
        # ######                                                                 ######
        # ###                            Initialization                             ###
        # ######                                                                 ######
        # #############################################################################

        # Position                                   [m]
        # Velocity                                   [m/s]
        # Orientation: Euler angles: Z - Y - X body axis - yaw, pitch, roll
        # Orientation: mt.Quaternion - Note: make sures this is the propor representation of zero rotation
        # Angular velocity in vehicle frame [p, q, r][rad/s] p*b1 + q*b2 + r*b3
        self.state = State()
        self.stateTarget = State()
        self.sensor = Sensor()

        self.t = 0

        self.controller = None
        self.path = None

        # #############################################################################
        # ######                                                                 ######
        # ###                          Physical Constants                           ###
        # ######                                                                 ######
        # #############################################################################

        # RPM to force constant (F = k_f * omega^2)  [N/rpm^2]
        self.k_f = 6.11 * 10**-8
        # RPM to moment constant (F = k_m * omega^2) [Nm/rpm^2]
        self.k_m = 1.5 * 10**-9
        # Quad arm length                   [m]
        self.armLength = 0.086
        # Max thrust per motor              [N]
        self.maxThrust = 0.883
        # Max thrust per motor              [N]
        self.minThrust = 0
        # Total mass                        [kg]
        self.mass = 0.18
        # Moment of inertia                 [kg m^2]
        # self.i = np.array([[0.2500, 0, 0.0026],
        #                    [0,      0.2320, 0],
        #                    [0.0026, 0, 0.3738]])*0.001
        self.i = np.diag([0.25, 0.25, 0.37]) * 0.001
        self.iInv = np.linalg.inv(self.i)
        # matrix mapping the thrust vector to moments
        gamma = self.k_m / self.k_f
        self.m1 = np.array([[0,               self.armLength, 0,             -self.armLength],
                            [-self.armLength, 0,              self.armLength, 0             ],
                            [gamma,          -gamma,          gamma,         -gamma         ]])

        self.params = Params(self.mass, -Quad.g[2], self.i)

    def stateDerivative(self, state, t):
        # Get desired state
        self.pathAtT(t, self.stateTarget)
        # Control input - linear thrust and moments
        u1, u2 = self.controller.control(self.stateTarget, state, self.params)
        thrusts, momentB = limitInput(u1, u2, self.armLength, self.minThrust, self.maxThrust)
        # Angular acceleration
        dOmega = self.iInv.dot(momentB - np.cross(state.ome, self.i.dot(state.ome)))
        # Quaternion derivative
        dQua = 0.5 * state.qua * mt.Quaternion(0, *state.ome)
        # Linear acceleration
        acc = Quad.g + state.qua.rotateVector(np.array([0, 0, thrusts])) / self.mass
        # Linear velocity
        vel = state.vel
        dstate = State(p=vel, v=acc, a=np.zeros(3), o=dOmega, q=dQua)
        return dstate

    def dynUpdate(self):
        self.state = eulerIntegrate(self.stateDerivative, self.state, self.t, Quad.dt)
        # self.state = rungeKutta(self.stateDerivative, self.state, self.t, Quad.dt)
        self.state.qua.normalize()
        self.t += Quad.dt

    def getMeasurements(self):
        return self.sensor.measurements(self)
Exemple #14
0
class Ball(object):
    def __init__(self, game, res):
        self.ball_image = res.image_dict[const.BALL_IMAGE]
        center_image(self.ball_image)
        self.width = self.ball_image.width
        self.height = self.ball_image.height
    
        self.game = game
        self.res = res
        x = y = 200
        self.sprite = Sprite(self.ball_image, x = x, y = y)
        self.x = x
        self.y = y

        # State Machine

        self.state = "Stopped"

        # Sensors

        self.sensor_bottom = Sensor(self.res)
        self.sensor_top = Sensor(self.res)
        self.sensor_left = Sensor(self.res)
        self.sensor_right = Sensor(self.res)
        self.sensor_ground = Sensor(self.res)
        self.sensor_ground.red = 0.5
        self.sensor_ground.alpha = 0.5
        self.sensor_left_ground = TinySensor(self.res)
        self.sensor_middle_ground = TinySensor(self.res)
        self.sensor_right_ground = TinySensor(self.res)
        self.sensors = [self.sensor_bottom,
                        self.sensor_top,
                        self.sensor_left,
                        self.sensor_right,
                        self.sensor_ground,
                        self.sensor_left_ground,
                        self.sensor_middle_ground,
                        self.sensor_right_ground]

        # Values according to the Sonic Physics Guide
        
        self.acc = 0.046875 * const.SCALE
        self.frc = 0.046875 * const.SCALE
        self.rfrc = 0.0234375 * const.SCALE
        self.dec = 0.5 * const.SCALE
        self.max = 6.0 * const.SCALE

        self.rol = 1.03125 * const.SCALE

        self.slp = 0.125 * const.SCALE
        self.ruslp = 0.078125 * const.SCALE
        self.rdslp = 0.3125 * const.SCALE

        self.air = 0.09375 * const.SCALE
        self.grv = 0.21875 * const.SCALE
        self.maxg = 16.0 * const.SCALE

        self.drg = 0.96875

        self.jmp = 6.5 * const.SCALE
        self.jmpweak = 4.0 * const.SCALE

        # Flags

        self.flagGround = False
        self.flagAllowJump = False
        self.flagAllowHorizMovement = True
        self.flagAllowVertMovement = True
        self.flagJumpNextFrame = False
        self.flagFellOffWallOrCeiling = False

        # Trig

        self.angle = 0.0
        self.gangle = 0.0
        self.rangle = 0.0

        # Movement (dh = horizontal, dv = vertical.)
        # These can be rotated using angle and gangle above.

        self.dh = 0.0
        self.dv = 0.0
        
        self.keyUp = False
        self.keyDown = False
        self.keyLeft = False
        self.keyRight = False
        self.keyJump = False

        # Control lock timers
        self.hlock = 0

    def play_sound(self, string):
        self.res.sound_dict[string].play()

    def release_jump(self):
        self.dv = min(self.dv, self.jmpweak)
    
    def set_position(self, x = None, y = None):
        x = x or self.x
        y = y or self.y
        self.x = x
        self.y = y
        self.sprite.x = int(x)
        self.sprite.y = int(y)
        self.update_sensors()

    def handle_physics(self):
        # See if rolling
        if (abs(self.dh) >= self.rol):
            if (self.keyDown and self.flagGround and self.state != "Rolling"):
                self.state = "Rolling"
                self.play_sound('spin.wav')
                print "Rolling!"
        
        # Slope factor
        if self.state != "Rolling":
            if self.flagGround:
                self.dh -= self.slp * sin(self.rangle)
        else:
            if cmp(self.dh,0) == cmp(sin(self.rangle),0):
                self.dh -= self.ruslp * sin(self.rangle)
            elif cmp(self.dh,0) == -cmp(sin(self.rangle),0) or self.dh == 0:
                self.dh -= self.rdslp * sin(self.rangle)

        # Falling off walls and ceilings
        if 45 < self.rangle < 315 and abs(self.dh) < 2.5 * const.SCALE:
            self.set_gravity(self.gangle)
            self.flagFellOffWallOrCeiling = True

        if self.state == "Rolling" and self.dh == 0 and not self.keyDown:
            self.state = "Stopped"
            print "Stopped!"
        
        # Speed input and management
        if self.flagAllowHorizMovement:
            if self.keyLeft:
                if self.dh > 0 and self.flagGround:
                    # Decelerate
                    self.dh -= self.dec
                    if -self.dec < self.dh < 0:
                        self.dh = -self.dec
                elif self.dh > -self.max and self.state != "Rolling":
                    # Accelerate
                    if self.flagGround:
                        self.dh = max(self.dh - self.acc, -self.max)
                    else:
                        self.dh = max(self.dh - self.air, -self.max)
            elif self.keyRight:
                if self.dh < 0 and self.flagGround:
                    # Decelerate
                    self.dh += self.dec
                    if 0 < self.dh < self.dec:
                        self.dh = self.dec
                elif self.dh < self.max and self.state != "Rolling":
                    # Accelerate
                    if self.flagGround:
                        self.dh = min(self.dh + self.acc, self.max)
                    else:
                        self.dh = min(self.dh + self.air, self.max)
            elif not self.keyLeft and not self.keyRight and self.flagGround:
                if self.state == "Rolling":
                    self.dh -= min(abs(self.dh), self.rfrc) * cmp(self.dh,0)
                else:
                    self.dh -= min(abs(self.dh), self.frc) * cmp(self.dh,0)

        #Air Drag
        if 0 < self.dv < 4*const.SCALE and abs(self.dh) >= 0.125:
            self.dh *= self.drg

        #Jumping
        if self.flagJumpNextFrame:
            self.play_sound('jump.wav')
            self.dv = self.jmp
            self.set_gravity(self.gangle)
            self.state = "Jumping"
            self.flagGround = False
            self.flagAllowJump = False
            self.flagJumpNextFrame = False
        if self.keyJump and self.flagGround and self.flagAllowJump:
            self.flagJumpNextFrame = True

    def calculate_state(self):
        if self.flagGround:
            if self.state != "Rolling":
                if self.dh == 0:
                    self.state = "Stopped"
                elif 0 < abs(self.dh) < self.max:
                    self.state = "Walking"
                elif abs(self.dh) >= self.max:
                    self.state = "Running"
        else:
            if self.state != "Jumping":
                self.state = "Falling"

    def set_gravity(self, gangle):
        _ = rotate_basis(self.dh, self.dv, self.angle, gangle)
        self.dh = _[0]
        self.dv = _[1]
        self.angle = self.gangle = gangle

    def update_sensors(self):
        self.sensor_top.x = int(self.x) - sin(self.angle) * (
            self.height/2.0 - self.sensor_bottom.height/2.0)
        self.sensor_top.y = int(self.y) + cos(self.angle) * (
            self.height/2.0 - self.sensor_bottom.height/2.0)

        self.sensor_bottom.x = int(self.x) + sin(self.angle) * (
            self.height/2.0 - self.sensor_top.height/2.0)
        self.sensor_bottom.y = int(self.y) - cos(self.angle) * (
            self.height/2.0 - self.sensor_top.height/2.0)

        self.sensor_left.x = int(self.x) - cos(self.angle) * (
            self.width/2.0 - self.sensor_left.width/2.0)
        self.sensor_left.y = int(self.y) - sin(self.angle) * (
            self.width/2.0 - self.sensor_left.width/2.0)

        self.sensor_right.x = int(self.x) + cos(self.angle) * (
            self.width/2.0 - self.sensor_left.width/2.0)
        self.sensor_right.y = int(self.y) + sin(self.angle) * (
            self.width/2.0 - self.sensor_left.width/2.0)

        self.sensor_ground.x = int(self.x) + sin(self.angle) * (
            self.height/2.0 + self.sensor_ground.height/2.0)
        self.sensor_ground.y = int(self.y) - cos(self.angle) * (
            self.height/2.0 + self.sensor_ground.height/2.0)

    def calculate_rangle(self):
        self.rangle = (self.angle - self.gangle)

    def calculate_angle(self, colliding_line):
        if colliding_line is None:
            return self.gangle
        
        x1, y1, x2, y2 = colliding_line
        return direction(x2, y2, x1, y1)

    def perform_speed_movement(self, dt):
        leftcollided = False
        rightcollided = False
        for i in range(0, int(const.FAILSAFE_AMOUNT)):
            self.x += cos(self.angle) * self.dh/const.FAILSAFE_AMOUNT * dt
            self.y += sin(self.angle) * self.dh/const.FAILSAFE_AMOUNT * dt
            self.update_sensors()
            for platform in self.game.platforms:
                colliding_line = None
                '''
                if self.sensor_bottom.collide(platform):
                    # first, try see if it's a small slope
                    for _ in xrange(const.SLOPE_TEST):
                        self.y += 1
                        self.update_sensors()
                        if not self.sensor_bottom.collide(platform):
                            break
                '''
                if (self.sensor_left.collide(platform) or 
                self.sensor_right.collide(platform)):
                    self.update_sensors()
                    while self.sensor_left.collide(platform):
                        colliding_line = self.sensor_left.collide(platform)[1]
                        leftcollided = True
                        self.x += cos(self.angle)
                        self.y += sin(self.angle)
                        self.update_sensors()
                    while self.sensor_right.collide(platform):
                        colliding_line = self.sensor_right.collide(platform)[1]
                        rightcollided = True
                        self.x -= cos(self.angle)
                        self.y -= sin(self.angle)
                        self.update_sensors()

                while self.sensor_bottom.collide(platform):
                    colliding_line = self.sensor_bottom.collide(platform)[1]
                    self.y += cos(self.angle)
                    self.x -= sin(self.angle)
                    self.update_sensors()
            if leftcollided:
                if not self.flagGround:
                    self.catch_left_wall(colliding_line)
                else:
                    self.dh = 0
                break
            elif rightcollided:
                if not self.flagGround:
                    self.catch_right_wall(colliding_line)
                else:
                    self.dh = 0
                break
            elif colliding_line is not None:
                self.angle = self.calculate_angle(colliding_line)
        self.sprite.x = int(self.x)
        self.sprite.y = int(self.y)

    def perform_gravity_movement(self, dt):
        self.dv = max(self.dv - self.grv, -self.maxg)
        collided = False
        colliding_line = None
        
        y_speed = cos(self.angle)
        x_speed = sin(self.angle)
        
        # Failsafe movement
        for i in range(0, int(const.FAILSAFE_AMOUNT)):
            self.y += y_speed * (self.dv/const.FAILSAFE_AMOUNT) * dt
            self.x -= x_speed * (self.dv/const.FAILSAFE_AMOUNT) * dt
            self.update_sensors()
            for platform in self.game.platforms:
                while self.sensor_bottom.collide(platform):
                    if self.dv < 0:
                        collided = True
                        colliding_line = self.sensor_bottom.collide(platform)[1]
                    self.y += y_speed
                    self.x -= x_speed
                    self.update_sensors()
                while self.sensor_top.collide(platform):
                    if self.dv > 0:
                        collided = True
                        colliding_line = self.sensor_top.collide(platform)[1]
                    self.y -= y_speed
                    self.x += x_speed
                    self.update_sensors()
            if collided:
                if self.dv < 0:
                    self.flagGround = True
                    if self.flagFellOffWallOrCeiling:
                        self.set_hlock(30)
                        self.flagFellOffWallOrCeiling = False
                    self.angle = self.calculate_angle(colliding_line)
                    self.perform_landing_movement(colliding_line)
                elif self.dv > 0:
                    self.catch_ceiling(colliding_line)
                self.dv = 0
                break
        self.sprite.x = self.x = int(self.x)
        self.sprite.y = self.y = int(self.y)

    def perform_landing_movement(self, colliding_line):
        rangle = (self.calculate_angle(colliding_line) - self.gangle)
        if 0 <= rangle < 22.5 or 337.5 < rangle < 360:
            "Nothing extra happens!"
        elif 22.5 <= rangle < 45 or 315 < rangle <= 337.5:
            if abs(self.dh) > abs(self.dv):
                "Nothing extra happens!"
            else:
                self.dh = -self.dv * 0.5 * cmp(cos(rangle),1)
        elif 45 <= rangle < 90 or 270 < rangle <= 315:
            if abs(self.dh) > abs(self.dv):
                "Nothing extra happens!"
            else:
                self.dh = -self.dv * cmp(cos(rangle),1)

    def catch_ceiling(self, colliding_line):
        rangle = (self.calculate_angle(colliding_line) - self.gangle) % 360
        if 135 <= rangle <= 225:
            "Nothing extra happens!"
        if 90 <= rangle < 135 or 225 < rangle <= 270:
            self.flagGround = True
            self.angle = rangle
            self.calculate_rangle()

    def catch_left_wall(self, colliding_line):
        rangle = (self.calculate_angle(colliding_line) - self.gangle) % 360
        if 90 < rangle < 135:
            self.flagGround = True
            self.angle = rangle
            self.calculate_rangle()
        else:
            self.dh = 0

    def catch_right_wall(self, colliding_line):
        rangle = (self.calculate_angle(colliding_line) - self.gangle)
        if 225 < rangle < 270:
            self.flagGround = True
            self.angle = rangle
            self.calculate_rangle()
        else:
            self.dh = 0

    def perform_ground_test(self):
        for platform in self.game.platforms:
            collision = self.sensor_ground.collide(platform)
            if collision is not None:
                angle = self.calculate_angle(collision[1])
                if angle != self.angle and angle != 90:
                    return False
                return True
        self.flagGround = False
        self.set_gravity(self.gangle)
        return False

    def update(self, dt):
        self.update_lock_timers(dt)
        if self.flagGround:
            if not self.keyJump:
                self.flagAllowJump = True
        else:
            # I'd like to have the sensors be invisible when not on the ground.
            '''
            self.sensor_left_ground.visible = False
            self.sensor_middle_ground.visible = False
            self.sensor_right_ground.visible = False
            '''
        self.handle_physics()
        self.perform_speed_movement(dt)
        if not self.flagGround or not self.perform_ground_test():
            self.perform_gravity_movement(dt)
        self.calculate_state()
        self.calculate_rangle()

    def update_lock_timers(self, dt):
        if self.hlock > 0:
            self.hlock = max(self.hlock - 60 * dt, 0)
        if self.hlock == 0:
            self.flagAllowHorizMovement = True

    def set_hlock(self, frames):
        self.hlock = frames
        self.flagAllowHorizMovement = False
    
    def draw(self):
        self.sprite.render()

    def key_press(self, message):
        if message == 'up':
            self.keyUp = True
        elif message == 'down':
            self.keyDown = True
        elif message == 'left':
            self.keyLeft = True
        elif message == 'right':
            self.keyRight = True
        elif message == 'jump':
            self.keyJump = True
        elif message == 'reset':
            self.set_position(100,96)
            self.dv = 0
            self.dh = 0
            self.set_gravity(0.0)
        elif message == 'gdown':
            self.set_gravity(0.0)
        elif message == 'gright':
            self.set_gravity(90.0)
        elif message == 'gup':
            self.set_gravity(180.0)
        elif message == 'gleft':
            self.set_gravity(270.0)
        elif message == 'hlock':
            self.set_hlock(30)

    def key_release(self, message):
        if message == 'up':
            self.keyUp = False
        elif message == 'down':
            self.keyDown = False
        elif message == 'left':
            self.keyLeft = False
        elif message == 'right':
            self.keyRight = False
        elif message == 'jump':
            self.keyJump = False
            self.release_jump()
Exemple #15
0
 def __init__(self, id, macAddr, name='RFduino'):
     Sensor.__init__(self, id, macAddr, name)
     self.last_seq = 0
Exemple #16
0
def read_sensors(n, time_start, wait_time):

    # Valve Definition and Classes
    vent_valve = Valve('Vent Valve', 'P8_12', 0, 'Solenoid', 0, 0)
    actuator_prop = Valve('Actuator Propellant Valve', 'P8_4', 'P8_4', 'prop',
                          4, 10)
    actuator_solenoid = Valve('Actuator Solenoid Valve', 'P8_4', 0, 'solenoid',
                              0, 0)

    # Pressure Sensor Definition and Classes
    pressure_cold_flow = Sensor('pressure_cold_flow', 'pressure', 'P9_16',
                                'P9_16', 'P9_16', '000', '001', '010')
    pressure0 = Sensor('pressure_cold_flow', 'pressure', 'P9_16', 'P9_16',
                       'P9_16', '000', '000', '000')
    pressure2 = Sensor('pressure_cold_flow', 'pressure', 'P9_16', 'P9_16',
                       'P9_16', '010', '010', '010')
    pressure4 = Sensor('pressure_cold_flow', 'pressure', 'P9_16', 'P9_16',
                       'P9_16', '100', '100', '100')

    maximum_pressure = 640
    nominal_pressure = 500

    pressure_list = []
    pressure_time_list = []
    pressure0_list = []
    pressure2_list = []
    pressure4_list = []

    for i in range(1000):
        global counter
        pressure, time_pres = pressure_cold_flow.read_sensor()
        pres0, time_pres0 = pressure0.read_sensor()
        pres2, time_pres2 = pressure2.read_sensor()
        pres4, time_pres4 = pressure4.read_sensor()

        pressure_list.append(pressure)
        pressure_time_list.append(time_pres + wait_time * n)
        pressure0_list.append(pres0)
        pressure2_list.append(pres2)
        pressure4_list.append(pres4)

        if pressure >= maximum_pressure:
            counter = counter + 1
        else:
            counter = 0

        if counter >= 3:
            time_relief = time.process_time()
            actuator_solenoid.open()
            actuator_prop.partial_open()
            print('Pressure Exceeded Maximum: Opening Relief Valve')
            print(time_relief)
            while True:
                pres_relief = pressure_cold_flow.read_sensor()
                if pres_relief[0] < nominal_pressure:
                    time_relief_end = time.process_time()
                    print('Closing Relief Valve')
                    actuator_solenoid.close()
                    actuator_prop.close()
                    print(time_relief_end)
                    break

    current_time = 'Time Update: {} seconds'.format(time.time() - time_start)
    print(current_time)
    saved_data_combined = [pressure_list, pressure_time_list]
    export_data = zip_longest(*saved_data_combined, fillvalue='')

    with open('leak_data.csv', 'a', encoding="ISO-8859-1",
              newline='') as myfile:
        wr = csv.writer(myfile)
        wr.writerows(export_data)
    myfile.close()

    for z in range(21):
        pres_temp = pressure_cold_flow.read_sensor()
        print(pres_temp[0])
Exemple #17
0
from sensors import Sensor
from valve import Valve
import front_end

percentage = 100

# Valve Definition and Classes
lox_main = Valve('LOX Propellant Valve', 'P8_13', 'P8_13', 'Prop', 4,
                 percentage)
lox_vent = Valve('LOX Vent Valve', 'P8_12', 0, 'Solenoid', 0, 0)
met_vent = Valve('Methane Vent Valve', 'P8_12', 0, 'Solenoid', 0, 0)
p_valve = Valve('Pressurant Valve', 'P8_12', 0, 'Solenoid', 0, 0)

# Pressure Sensor Definition and Classes
pressure_cold_flow = Sensor('pressure_cold_flow', 'pressure', 'P9_12', 'P9_14',
                            'P9_16', '000', '000', '000')

# Temperature Sensor Definition and Classes
temperature_fill_line = Sensor('temperature_fill_line', 'temperature', 'P9_12',
                               'P9_14', 'P9_16', '000', '000', '000')
temperature_empty_line = Sensor('temperature_empty_line', 'temperature',
                                'P9_12', 'P9_14', 'P9_16', '000', '000', '000')

print(
    "Before Test Start: Verify Electronic Connections and Follow Safety Procedures\n"
)
print("------------------------------------------")
print("\nProject Daedalus: Powerhead Hardware/Software Test\n")
print("""\

                   ._ o o
Exemple #18
0
 def test_reading(self):
     temperatureSensor = Sensor("temperature")
     reading = temperatureSensor.getReading()
     self.assertTrue(reading['value'] >= 0 and reading['value'] <= 100)
Exemple #19
0
class Worker():

    """ This class runs on the background using GPIO Events Changes.
    It uses a json file to store the settings and a log file to store the logs.
    When a sensor changes state after the alarm is activated it can enable
    the Serene, send Mail, call through VoIP.
    Also there is the updateUI method wich it has to be overridden in
    the main application.
    """

    def __init__(self, jsonfile, logfile, sipcallfile, optsUpdateUI=None):
        """ Init for the Worker class """

        print("{0}------------ INIT FOR DOOR SENSOR CLASS! ----------------{1}"
              .format(bcolors.HEADER, bcolors.ENDC))
        # Global Variables
        self.jsonfile = jsonfile
        self.logfile = logfile
        self.sipcallfile = sipcallfile
        self.settings = self.ReadSettings()
        self.limit = 10
        self.logtypes = 'all'

        # Stop execution on exit
        self.kill_now = False

        # Init Alarm
        self.mynotify = Notify(self.settings)
        self.mynotify.setupUpdateUI(optsUpdateUI)
        self.mynotify.setupSendStateMQTT()
        mylogs = Logs(self.logfile)
        self.getSensorsLog = mylogs.getSensorsLog
        self.writeLog("system", "Alarm Booted")
        mylogs.startTrimThread()

        # Event Listeners
        self.sensors = Sensor()
        self.sensors.on_alert(self.sensorAlert)
        self.sensors.on_alert_stop(self.sensorStopAlert)
        self.sensors.on_error(self.sensorError)
        self.sensors.on_error_stop(self.sensorStopError)
        self.sensors.add_sensors(self.settings)

        # Init MQTT Messages
        self.mynotify.on_disarm_mqtt(self.deactivateAlarm)
        self.mynotify.on_arm_mqtt(self.activateAlarm)
        self.mynotify.on_sensor_set_alert(self.sensorAlert)
        self.mynotify.on_sensor_set_stopalert(self.sensorStopAlert)
        self.mynotify.sendStateMQTT()


    def sensorAlert(self, sensorUUID):
        """ On Sensor Alert, write logs and check for intruder """

        name = self.settings['sensors'][sensorUUID]['name']
        print("{0}-> Alert Sensor: {2}{1}".format(
            bcolors.OKGREEN, bcolors.ENDC, name))
        self.settings['sensors'][sensorUUID]['alert'] = True
        self.settings['sensors'][sensorUUID]['online'] = True
        self.writeNewSettingsToFile(self.settings)
        stateTopic = self.settings['mqtt']['state_topic'] + '/sensor/' + name
        self.mynotify.sendSensorMQTT(stateTopic, 'on')
        self.mynotify.updateUI('settingsChanged', self.getSensorsArmed())
        self.writeLog("sensor,start," + sensorUUID, name)
        self.checkIntruderAlert()

    def sensorStopAlert(self, sensorUUID):
        """ On Sensor Alert Stop, write logs """

        name = self.settings['sensors'][sensorUUID]['name']
        print("{0}<- Stop Alert Sensor: {2}{1}".format(
            bcolors.OKGREEN, bcolors.ENDC, name))
        self.settings['sensors'][sensorUUID]['alert'] = False
        self.settings['sensors'][sensorUUID]['online'] = True
        self.writeNewSettingsToFile(self.settings)
        stateTopic = self.settings['mqtt']['state_topic'] + '/sensor/' + name
        self.mynotify.sendSensorMQTT(stateTopic, 'off')
        self.mynotify.updateUI('settingsChanged', self.getSensorsArmed())
        self.writeLog("sensor,stop," + sensorUUID, name)

    def sensorError(self, sensorUUID):
        """ On Sensor Error, write logs """

        name = self.settings['sensors'][sensorUUID]['name']
        print("{0}!- Error Sensor: {2}{1}".format(
            bcolors.FAIL, bcolors.ENDC, name))
        # print("Error Sensor", sensorUUID)
        name = self.settings['sensors'][sensorUUID]['name']
        self.settings['sensors'][sensorUUID]['alert'] = True
        self.settings['sensors'][sensorUUID]['online'] = False
        self.writeNewSettingsToFile(self.settings)
        self.writeLog("error", "Lost connection to: " + name)
        self.mynotify.updateUI('settingsChanged', self.getSensorsArmed())

    def sensorStopError(self, sensorUUID):
        """ On Sensor Stop Error, write logs """

        name = self.settings['sensors'][sensorUUID]['name']
        print("{0}-- Error Stop Sensor: {2}{1}".format(
            bcolors.FAIL, bcolors.ENDC, name))
        name = self.settings['sensors'][sensorUUID]['name']
        self.settings['sensors'][sensorUUID]['online'] = True
        self.writeNewSettingsToFile(self.settings)
        self.writeLog("error", "Restored connection to: " + name)
        self.mynotify.updateUI('settingsChanged', self.getSensorsArmed())

    def checkIntruderAlert(self):
        """ Checks if the alarm is armed and if it finds an active
            sensor then it calls the intruderAlert method """

        if (self.settings['settings']['alarmArmed'] is True):
            for sensor, sensorvalue in self.settings['sensors'].items():
                if (sensorvalue['alert'] is True and
                        sensorvalue['enabled'] is True and
                        self.settings['settings']['alarmTriggered'] is False):
                    self.settings['settings']['alarmTriggered'] = True
                    threadIntruderAlert = threading.Thread(
                        target=self.intruderAlert)
                    threadIntruderAlert.daemon = True
                    threadIntruderAlert.start()

    def ReadSettings(self):
        """ Reads the json settings file and returns it """

        with open(self.jsonfile) as data_file:
            settings = json.load(data_file)
        return settings

    def writeNewSettingsToFile(self, settings):
        """ Write the new settings to the json file """
        self.mynotify.updateSettings(settings)
        with open(self.jsonfile, 'w') as outfile:
            json.dump(settings, outfile, sort_keys=True,
                      indent=4, separators=(',', ': '))


    def writeLog(self, logType, message):
        """ Write log events into a file and send the last to UI.
            It also uses the timezone from json file to get the local time.
        """
        try:
            mytimezone = pytz.timezone(self.settings['settings']['timezone'])
        except Exception:
            mytimezone = pytz.utc

        myTimeLog = datetime.now(tz=mytimezone).strftime("%Y-%m-%d %H:%M:%S")
        logmsg = '({0}) [{1}] {2}\n'.format(logType, myTimeLog, message)
        with open(self.logfile, "a") as myfile:
            myfile.write(logmsg)
        self.mynotify.updateUI('sensorsLog', self.getSensorsLog(
            self.limit, selectTypes=self.logtypes))

    def intruderAlert(self):
        """ This method is called when an intruder is detected. It calls
            all the methods whith the actions that we want to do.
            Sends MQTT message, enables serene, Send mail, Call Voip.
        """
        self.writeLog("alarm", "Intruder Alert")
        self.enableSerene()
        self.mynotify.sendStateMQTT()
        self.mynotify.updateUI('alarmStatus', self.getTriggeredStatus())
        threadSendMail = threading.Thread(target=self.sendMail)
        threadSendMail.daemon = True
        threadSendMail.start()
        threadCallVoip = threading.Thread(target=self.callVoip)
        threadCallVoip.daemon = True
        threadCallVoip.start()

    def callVoip(self):
        """ This method uses a prebuild application in C to connect to the SIP provider
            and call all the numbers in the json settings file.
        """

        sip_domain = str(self.settings['voip']['domain'])
        sip_user = str(self.settings['voip']['username'])
        sip_password = str(self.settings['voip']['password'])
        sip_repeat = str(self.settings['voip']['timesOfRepeat'])
        if self.settings['voip']['enable'] is True:
            for phone_number in self.settings['voip']['numbersToCall']:
                phone_number = str(phone_number)
                if self.settings['settings']['alarmTriggered'] is True:
                    self.writeLog("alarm", "Calling " + phone_number)
                    cmd = (self.sipcallfile, '-sd', sip_domain,
                           '-su', sip_user, '-sp', sip_password,
                           '-pn', phone_number, '-s', '1', '-mr', sip_repeat)
                    print("{0}Voip command: {2}{1}".format(
                        bcolors.FADE, bcolors.ENDC, " ".join(cmd)))
                    proc = subprocess.Popen(cmd, stderr=subprocess.PIPE)
                    for line in proc.stderr:
                        sys.stderr.write(line)
                    proc.wait()
                    self.writeLog("alarm", "Call to " +
                                  phone_number + " endend")
                    print("{0}Call Ended{1}".format(
                        bcolors.FADE, bcolors.ENDC))

    def sendMail(self):
        """ This method sends an email to all recipients
            in the json settings file. """

        if self.settings['mail']['enable'] is True:
            mail_user = self.settings['mail']['username']
            mail_pwd = self.settings['mail']['password']
            smtp_server = self.settings['mail']['smtpServer']
            smtp_port = int(self.settings['mail']['smtpPort'])

            bodyMsg = self.settings['mail']['messageBody']
            LogsTriggered = self.getSensorsLog(
                fromText='Alarm activated')['log']
            LogsTriggered.reverse()
            for logTriggered in LogsTriggered:
                bodyMsg += '<br>' + logTriggered
            msg = MIMEText(bodyMsg, 'html')
            sender = mail_user
            recipients = self.settings['mail']['recipients']
            msg['Subject'] = self.settings['mail']['messageSubject']
            msg['From'] = sender
            msg['To'] = ", ".join(recipients)

            smtpserver = smtplib.SMTP(smtp_server, smtp_port)
            smtpserver.ehlo()
            smtpserver.starttls()
            smtpserver.login(mail_user, mail_pwd)
            smtpserver.sendmail(sender, recipients, msg.as_string())
            smtpserver.close()

            self.writeLog("alarm", "Mail sent to: " + ", ".join(recipients))

    def enableSerene(self):
        """ This method enables the output pin for the serene """

        if self.settings['serene']['enable'] is True:
            self.writeLog("alarm", "Serene started")
            serenePin = int(self.settings['serene']['pin'])
            outputGPIO().enableOutputPin(serenePin)

    def stopSerene(self):
        """ This method disables the output pin for the serene """

        if self.settings['serene']['enable'] is True:
            serenePin = self.settings['serene']['pin']
            outputGPIO().disableOutputPin(serenePin)

    def activateAlarm(self, zones=None):
        """ Activates the alarm """

        if zones is not None:
            if type(zones) == str:
                zones = [zones]
            self.setSensorsZone(zones)

        self.writeLog("user_action", "Alarm activated")
        self.settings['settings']['alarmArmed'] = True
        self.mynotify.sendStateMQTT()
        self.mynotify.updateUI('settingsChanged', self.getSensorsArmed())
        self.writeNewSettingsToFile(self.settings)

    def deactivateAlarm(self):
        """ Deactivates the alarm """

        self.writeLog("user_action", "Alarm deactivated")
        self.settings['settings']['alarmTriggered'] = False
        self.settings['settings']['alarmArmed'] = False
        self.stopSerene()
        self.mynotify.sendStateMQTT()
        self.mynotify.updateUI('settingsChanged', self.getSensorsArmed())
        self.writeNewSettingsToFile(self.settings)

    def getSensorsArmed(self):
        """ Returns the sensors and alarm status
            as a json to use it to the UI """

        sensorsArmed = {}
        sensors = self.settings['sensors']
        orderedSensors = OrderedDict(
            sorted(sensors.items(), key=lambda k_v: k_v[1]['name']))
        sensorsArmed['sensors'] = orderedSensors
        sensorsArmed['triggered'] = self.settings['settings']['alarmTriggered']
        sensorsArmed['alarmArmed'] = self.settings['settings']['alarmArmed']
        return sensorsArmed

    def getTriggeredStatus(self):
        """ Returns the status of the alert for the UI """

        return {"alert": self.settings['settings']['alarmTriggered']}

    def setLogFilters(self, limit, logtypes):
        """ Sets the global filters for the getSensorsLog method """

        self.limit = limit
        self.logtypes = logtypes

    def getSereneSettings(self):
        """ Gets the Serene Settings """
        return self.settings['serene']

    def getMailSettings(self):
        return self.settings['mail']

    def getVoipSettings(self):
        """ Gets the Voip Settings """
        return self.settings['voip']

    def getTimezoneSettings(self):
        """ Get the Timezone Settings """
        return self.settings['settings']['timezone']

    def getMQTTSettings(self):
        """ Gets the MQTT Settings """
        return self.settings['mqtt']

    def setSereneSettings(self, message):
        """ set Serene Settings """
        if self.settings['serene'] != message:
            self.settings['serene'] = message
            self.writeLog("user_action", "Settings for Serene changed")
            self.writeNewSettingsToFile(self.settings)

    def setMailSettings(self, message):
        """ Set Mail Settings """
        if self.settings['mail'] != message:
            self.settings['mail'] = message
            self.writeLog("user_action", "Settings for Mail changed")
            self.writeNewSettingsToFile(self.settings)

    def setVoipSettings(self, message):
        """ Set Voip Settings """
        if self.settings['voip'] != message:
            self.settings['voip'] = message
            self.writeLog("user_action", "Settings for VoIP changed")
            self.writeNewSettingsToFile(self.settings)

    def setTimezoneSettings(self, message):
        """ Set the Timezone """
        if self.settings['settings']['timezone'] != message:
            self.settings['settings']['timezone'] = message
            self.writeLog("user_action", "Settings for UI changed")
            self.writeNewSettingsToFile(self.settings)

    def setMQTTSettings(self, message):
        """ Set MQTT Settings """
        if self.settings['mqtt'] != message:
            self.settings['mqtt'] = message
            self.writeLog("user_action", "Settings for MQTT changed")
            self.writeNewSettingsToFile(self.settings)
            self.mynotify.setupSendStateMQTT()

    def setSensorState(self, sensorUUID, state):
        """ Activate or Deactivate a sensor """
        self.settings['sensors'][sensorUUID]['enabled'] = state
        self.writeNewSettingsToFile(self.settings)

        logState = "Deactivated"
        if state is True:
            logState = "Activated"
        logSensorName = self.settings['sensors'][sensorUUID]['name']
        self.writeLog("user_action", "{0} sensor: {1}".format(
            logState, logSensorName))
        self.writeNewSettingsToFile(self.settings)

    def setSensorsZone(self, zones):
        for sensor, sensorvalue in self.settings['sensors'].items():
            sensorZones = sensorvalue.get('zones', [])
            sensorZones = [item.lower() for item in sensorZones]
            if not set(sensorZones).isdisjoint(zones):
                sensorvalue['enabled'] = True
            else:
                sensorvalue['enabled'] = False
        self.mynotify.updateUI('settingsChanged', self.getSensorsArmed())
        self.writeNewSettingsToFile(self.settings)

    def addSensor(self, sensorValues):
        """ Add a new sensor """
        print("{0}New Sensor: {2}{1}".format(
            bcolors.WARNING, bcolors.ENDC, sensorValues))
        key = next(iter(sensorValues))
        sensorValues[key]['enabled'] = True
        sensorValues[key]['online'] = False
        sensorValues[key]['alert'] = True
        if 'undefined' in sensorValues:
            sensorUUID = str(uuid.uuid4())
            sensorValues[sensorUUID] = sensorValues.pop('undefined')
        else:
            self.sensors.del_sensor(key)
        self.settings['sensors'].update(sensorValues)
        self.writeNewSettingsToFile(self.settings)
        self.sensors.add_sensors(self.settings)
        self.mynotify.setupSendStateMQTT()

    def delSensor(self, sensorUUID):
        """ Delete a sensor """
        self.sensors.del_sensor(sensorUUID)
        del self.settings['sensors'][sensorUUID]
        self.writeNewSettingsToFile(self.settings)
Exemple #20
0
def leak_test():
    global input_flag
    global counter

    # Valve Definition and Classes
    actuator_prop = Valve('Actuator Propellant Valve', 'P8_4', 'P8_4', 'prop',
                          4, 20)
    actuator_solenoid = Valve('Actuator Solenoid Valve', 'P8_4', 0, 'solenoid',
                              0, 0)
    fill_valve = Valve('Fill Valve', 'P8_8', 0, 'solenoid', 0, 0)
    vent_valve = Valve('Vent Valve', 'P8_45', 0, 'solenoid', 0, 0)

    actuator_solenoid.open()
    actuator_prop.partial_open()
    time.sleep(2)

    # Pressure Sensor Definition and Classes
    pressureall = Sensor('pressure_cold_flow', 'pressure', 'P9_16', 'P9_16',
                         'P9_16', '000', '010', '100')
    pressure0 = Sensor('pressure_cold_flow', 'pressure', 'P9_16', 'P9_16',
                       'P9_16', '000', '000', '000')
    pressure2 = Sensor('pressure_cold_flow', 'pressure', 'P9_16', 'P9_16',
                       'P9_16', '010', '010', '010')
    pressure4 = Sensor('pressure_cold_flow', 'pressure', 'P9_16', 'P9_16',
                       'P9_16', '100', '100', '100')

    print('Welcome to the Team Daedalus: Leak Test')
    input('Please Press Enter to Confirm Start')
    print('Starting System Check')
    print()
    input("\nVerification Complete, Press Enter to Continue:\n")

    print()
    print('Closing All Valves')
    actuator_solenoid.close()
    actuator_prop.close()
    fill_valve.close()
    vent_valve.close()

    print(actuator_prop.get_state())
    print(actuator_solenoid.get_state())
    print(fill_valve.get_state())
    print(vent_valve.get_state())

    input('Press Enter to Open filling valve')
    print('Opening Fill Valve: Begin Filling Procedure')
    input('Press Enter to begin filling and Enter again to end filling')
    fill_valve.open()

    print(fill_valve.get_state())
    print(vent_valve.get_state())

    print('Press Enter When Desired Pressure is Met')
    time.sleep(3)
    i = threading.Thread(target=get_input)
    i.start()

    maximum_pressure = 10000
    nominal_pressure = 500

    while input_flag == 1:
        a = pressure0.read_sensor()
        b = pressure2.read_sensor()
        c = pressure4.read_sensor()
        e = pressureall.read_sensor()
        d = [e[0], a[0], b[0], c[0]]

        if e[0] >= maximum_pressure:
            counter = counter + 1
        else:
            counter = 0

        if counter >= 3:
            time_relief = time.process_time()
            vent_valve.open()
            print('Pressure Exceeded Maximum: Opening Relief Valve')
            print(time_relief)
            while True:
                pres_relief = pressureall.read_sensor()
                if pres_relief[0] < nominal_pressure:
                    time_relief_end = time.process_time()
                    print('Closing Relief Valve')
                    vent_valve.close()
                    print(time_relief_end)
                    break

        print(d)
        time.sleep(.2)
    fill_valve.close()
    vent_valve.close()
    print(fill_valve.get_state())
    print(vent_valve.get_state())

    input('Press Enter to Open Actuator at 10%')
    actuator_solenoid.open()
    actuator_prop.partial_open()

    input('Press Enter to Open Vent Valve')
    vent_valve.open()

    input('Enter all Other Valves')
    vent_valve.close()
    time.sleep(1)
    fill_valve.open()
    actuator_solenoid.open()
    actuator_prop.open()

    actuator_prop.get_state()
    actuator_solenoid.get_state()
    fill_valve.get_state()
    vent_valve.get_state()
    input('Press Enter to End and Close all valves')
    vent_valve.close()
    fill_valve.close()
    actuator_solenoid.close()
    actuator_prop.close()
Exemple #21
0
 def try_bricklet(self, uid, device_identifier, position):
     if device_identifier == 26:
         for x in ["relay_a", "relay_b"]:
             s = Sensor(self.controller, x, uid)
             self.relays[s.uid] = s
Exemple #22
0
    def __init__(self, game, res):
        self.ball_image = res.image_dict[const.BALL_IMAGE]
        center_image(self.ball_image)
        self.width = self.ball_image.width
        self.height = self.ball_image.height
    
        self.game = game
        self.res = res
        x = y = 200
        self.sprite = Sprite(self.ball_image, x = x, y = y)
        self.x = x
        self.y = y

        # State Machine

        self.state = "Stopped"

        # Sensors

        self.sensor_bottom = Sensor(self.res)
        self.sensor_top = Sensor(self.res)
        self.sensor_left = Sensor(self.res)
        self.sensor_right = Sensor(self.res)
        self.sensor_ground = Sensor(self.res)
        self.sensor_ground.red = 0.5
        self.sensor_ground.alpha = 0.5
        self.sensor_left_ground = TinySensor(self.res)
        self.sensor_middle_ground = TinySensor(self.res)
        self.sensor_right_ground = TinySensor(self.res)
        self.sensors = [self.sensor_bottom,
                        self.sensor_top,
                        self.sensor_left,
                        self.sensor_right,
                        self.sensor_ground,
                        self.sensor_left_ground,
                        self.sensor_middle_ground,
                        self.sensor_right_ground]

        # Values according to the Sonic Physics Guide
        
        self.acc = 0.046875 * const.SCALE
        self.frc = 0.046875 * const.SCALE
        self.rfrc = 0.0234375 * const.SCALE
        self.dec = 0.5 * const.SCALE
        self.max = 6.0 * const.SCALE

        self.rol = 1.03125 * const.SCALE

        self.slp = 0.125 * const.SCALE
        self.ruslp = 0.078125 * const.SCALE
        self.rdslp = 0.3125 * const.SCALE

        self.air = 0.09375 * const.SCALE
        self.grv = 0.21875 * const.SCALE
        self.maxg = 16.0 * const.SCALE

        self.drg = 0.96875

        self.jmp = 6.5 * const.SCALE
        self.jmpweak = 4.0 * const.SCALE

        # Flags

        self.flagGround = False
        self.flagAllowJump = False
        self.flagAllowHorizMovement = True
        self.flagAllowVertMovement = True
        self.flagJumpNextFrame = False
        self.flagFellOffWallOrCeiling = False

        # Trig

        self.angle = 0.0
        self.gangle = 0.0
        self.rangle = 0.0

        # Movement (dh = horizontal, dv = vertical.)
        # These can be rotated using angle and gangle above.

        self.dh = 0.0
        self.dv = 0.0
        
        self.keyUp = False
        self.keyDown = False
        self.keyLeft = False
        self.keyRight = False
        self.keyJump = False

        # Control lock timers
        self.hlock = 0
Exemple #23
0
from sensors import Sensor
from sensors import Sensors
from wheels import Wheel
from wheels import MockWheel
from wheels import Wheels
import RPi.GPIO as GPIO
from runtime import Runtime
from processor import Processor

GPIO.setmode(GPIO.BOARD)

sensor1 = Sensor(11, 13)
sensor3 = Sensor(15, 16)
sensor5 = Sensor(18, 19)
sensor6 = Sensor(21, 22)
sensor8 = Sensor(23, 24)
sensor10 = Sensor(26, 29)

leftMotor = Wheel(5, 3, 7, 7)
rightMotor = Wheel(8, 10, 12, 1)
# rightMotor = MockWheel("rightWheel")

zrobot_runtime = Runtime(
    Sensors([sensor1, sensor3, sensor5, sensor6, sensor8, sensor10]),
    Processor(), Wheels(leftMotor, rightMotor))
zrobot_runtime.start()
Exemple #24
0
def leak_test():
    global input_flag, counter
    time_duration = 36000

    # Data Frames for Saving
    pressure_list = ["Pressure"]
    pressure_time_list = ["time"]
    pressure0_list = ["Pressure0"]
    pressure2_list = ["Pressure2"]
    pressure4_list = ["Pressure4"]

    # Valve Definition and Classes
    actuator_prop = Valve('Actuator Propellant Valve', 'P8_4', 'P8_4', 'prop',
                          4, 20)
    actuator_solenoid = Valve('Actuator Solenoid Valve', 'P8_4', 0, 'solenoid',
                              0, 0)
    fill_valve = Valve('Fill Valve', 'P8_8', 0, 'solenoid', 0, 0)
    vent_valve = Valve('Vent Valve', 'P8_45', 0, 'solenoid', 0, 0)

    actuator_solenoid.open()
    actuator_prop.open()
    fill_valve.open()

    # Pressure Sensor Definition and Classes
    pressure_cold_flow = Sensor('pressure_cold_flow', 'pressure', 'P9_16',
                                'P9_16', 'P9_16', '000', '010', '100')
    pressure0 = Sensor('pressure_cold_flow', 'pressure', 'P9_16', 'P9_16',
                       'P9_16', '000', '000', '000')
    pressure2 = Sensor('pressure_cold_flow', 'pressure', 'P9_16', 'P9_16',
                       'P9_16', '010', '010', '010')
    pressure4 = Sensor('pressure_cold_flow', 'pressure', 'P9_16', 'P9_16',
                       'P9_16', '100', '100', '100')

    saved_data_combined = [
        pressure_list, pressure_time_list, pressure0_list, pressure2_list,
        pressure4_list
    ]
    export_data = zip_longest(*saved_data_combined, fillvalue='')
    with open('leak_data.csv', 'w', encoding="ISO-8859-1",
              newline='') as myfile:
        wr = csv.writer(myfile)
        wr.writerows(export_data)
    myfile.close()

    print('Welcome to the Team Daedalus: Leak Test')
    input('Please Press Enter to Confirm Start')
    print('Starting System Check')
    print()
    print("\nVerifying Sensor and Valve Connections\n")
    while not pressure_cold_flow.verify_connection():
        input("\nPress Enter to Start Verification Again:")
    print("\nAll Sensors are Functional\n")
    while not actuator_prop.verify_connection_valve and actuator_solenoid.verify_connection_valve and \
            fill_valve.verify_connection_valve and vent_valve.verify_connection_valve:
        input("\nPress Enter to Start Verification Again:")
    print("\nAll Valves are Functional\n")
    input("\nVerification Complete, Press Enter to Continue:\n")

    print()
    print('Closing All Valves')
    actuator_solenoid.close()
    actuator_prop.close()
    fill_valve.close()
    vent_valve.close()

    print(actuator_prop.get_state())
    print(actuator_solenoid.get_state())
    print(fill_valve.get_state())
    print(vent_valve.get_state())

    input('Press Enter to Open filling valve')
    print('Opening Fill Valve: Begin Filling Procedure')
    input('Press Enter to begin filling and Enter again to end filling')
    fill_valve.open()

    print(fill_valve.get_state())
    print(vent_valve.get_state())

    print('Press Enter When Desired Pressure is Met')
    time.sleep(3)
    i = threading.Thread(target=get_input)
    i.start()
    maximum_pressure = 640
    nominal_pressure = 500

    while input_flag == 1:
        a = pressure0.read_sensor()
        b = pressure2.read_sensor()
        c = pressure4.read_sensor()
        e = pressure_cold_flow.read_sensor()
        d = [e[0], a[0], b[0], c[0]]

        if e[0] >= maximum_pressure:
            counter = counter + 1
        else:
            counter = 0

        if counter >= 3:
            time_relief = time.process_time()
            actuator_prop_relief = Valve('Actuator Propellant Valve', 'P8_4',
                                         'P8_4', 'prop', 4, 10)
            actuator_solenoid.open()
            actuator_prop_relief.partial_open()
            print('Pressure Exceeded Maximum: Opening Relief Valve')
            print(time_relief)
            while True:
                pres_relief = pressure_cold_flow.read_sensor()
                if pres_relief[0] < nominal_pressure:
                    time_relief_end = time.process_time()
                    print('Closing Relief Valve')
                    actuator_solenoid.close()
                    actuator_prop_relief.close()
                    print(time_relief_end)
                    break
        print(d)
        time.sleep(.2)
    fill_valve.close()
    vent_valve.close()
    print(fill_valve.get_state())
    print(vent_valve.get_state())
    final_pressure = pressure_cold_flow.read_sensor()

    print("Filling Completed: Current Pressure is...")
    print(final_pressure[0])
    input("Press Enter to Begin Leak Test")
    print('Beginning Leak Test')

    input_flag = 1
    time_start = time.time()
    wait_time = 300
    n = 0

    while time.time() - time_start < time_duration:
        read_sensors(n, time_start, wait_time)
        time.sleep(wait_time)
        n = n + 1

    print('done')
    print(time.time() - time_start)
    input('Press Enter to Open Actuator at 20%')
    actuator_solenoid.open()
    actuator_prop.partial_open()

    input('Press Enter to Open All Valves')
    fill_valve.open()
    actuator_solenoid.open()
    actuator_prop.open()

    actuator_prop.get_state()
    actuator_solenoid.get_state()
    fill_valve.get_state()
    vent_valve.get_state()
Exemple #25
0
class Environment(object):
    """
    Represents the virtual environment -- the 'OS'
    behind Tal, which manages all other running apps and services,
    and centrally monitors and dispatches updates to Tals
    peripherals.
    """

    ENABLED_APPS = [
        ReaderApp,
        TracerApp,
    ]
    ENABLED_SERVICES = [
        NetworkService,
    ]
    activeHandlers = [
        LuxControlHandler,
    ]
    activeSession = None
    runningServices = []

    message = ''
    tiltSensorRight = None
    tiltSensorLeft = None  # for now
    display = None

    def __init__(self):
        self.beforeStartUp()
        self.startUp()
        self.afterStartUp()

    def beforeStartUp(self):
        self.message = 'Starting up ...'

    def startUp(self):
        if YAPI.RegisterHub('usb', YRefParam()) != YAPI.SUCCESS:
            sys.exit('Connection error: connection through USB failed')

        self.tiltSensorRight = Sensor()
        self.display = Display()

        # bootstrap handlers
        for h in self.activeHandlers:
            self.tiltSensorRight.attachHandler(h())
        self.tiltSensorRight.startWatching()

        # start display update loop
        def loop():
            threading.Timer(.10, loop).start()

            self.display.updateStatus()

            # for debugging, show data in the message row for now
            self.display.updateMessage('P:{} R:{}'.format(
                str(pitch), str(roll)))

        loop()

    def afterStartUp(self):
        self.message = 'Idle'

    def beforeStartApp(self, app):
        if app not in self.ENABLED_APPS:
            return False
        self.message = 'Starting {}...'.format(app.name)

    def startApp(self, app):
        if app in self.ENABLED_APPS:
            self.activeSession = app(environment=self)
        else:
            return False

    def afterStartApp(self, app):
        self.message = 'Running {}'.format(app.name)

    def beforeCloseApp(self, app):
        if not self.activeSession:
            return False
        self.activeSession.beforeClose()

    def closeApp(self, app):
        if not self.activeSession:
            return False
        self.activeSession = None

    def afterCloseApp(self, app):
        return

    def registerHandler(self, handlerInstance):
        self.activeHandlers.append(handlerInstance)

    def unregisterHandler(self, handlerInstance):
        self.activeHandlers.remove(handlerInstance)
Exemple #26
0
def insulation_test():

    # Data Frames for Saving
    pressure_list = ["Pressure"]
    pressure_time_list = ["time"]

    # Valve Definition and Classes
    actuator_prop = Valve('Actuator Propellant Valve', 'P8_13', 'P8_13',
                          'Prop', 4, 10)
    actuator_solenoid = Valve('Actuator Solenoid Valve', 'P8_12', 0,
                              'Solenoid', 0, 0)
    fill_valve = Valve('Fill Valve', 'P8_12', 0, 'Solenoid', 0, 0)
    vent_valve = Valve('Vent Valve', 'P8_12', 0, 'Solenoid', 0, 0)

    # Pressure Sensor Definition and Classes
    pressure_cold_flow = Sensor('pressure_cold_flow', 'pressure', 'P9_12',
                                'P9_14', 'P9_16', '000', '000', '000')

    # Temperature Sensor Definition and Classes
    temperature_fill_line = Sensor('temperature_fill_line', 'temperature',
                                   'P9_12', 'P9_14', 'P9_16', '000', '000',
                                   '000')
    temperature_empty_line = Sensor('temperature_empty_line', 'temperature',
                                    'P9_12', 'P9_14', 'P9_16', '000', '000',
                                    '000')

    saved_data_combined = [pressure_list, pressure_time_list]
    export_data = zip_longest(*saved_data_combined, fillvalue='')
    with open('insulation_data.csv', 'w', encoding="ISO-8859-1",
              newline='') as myfile:
        wr = csv.writer(myfile)
        wr.writerows(export_data)
    myfile.close()

    print('Welcome to the Team Daedalus: Insulation Test')
    input('Please Press Enter to Confirm Start')
    print('Starting System Check')
    print()
    print("\nVerifying Sensor and Valve Connections\n")
    while not pressure_cold_flow.verify_connection() and temperature_fill_line.verify_connection() \
            and temperature_empty_line.verify_connection():
        input("\nPress Enter to Start Verification Again:")
    print("\nAll Sensors are Functional\n")
    while not actuator_prop.verify_connection_valve and actuator_solenoid.verify_connection_valve and \
            fill_valve.verify_connection_valve and vent_valve.verify_connection_valve:
        input("\nPress Enter to Start Verification Again:")
    print("\nAll Valves are Functional\n")
    input("\nVerification Complete, Press Enter to Continue:\n")

    print()
    print('Closing All Valves')
    actuator_prop.close()
    actuator_solenoid.close()
    fill_valve.close()
    vent_valve.close()

    print(actuator_prop.get_state())
    print(actuator_solenoid.get_state())
    print(fill_valve.get_state())
    print(vent_valve.get_state())

    input('Press Enter to Open filling valve')
    print('Opening Fill Valve: Begin Filling Procedure')
    input('Press Enter to begin filling and Enter again to end filling')

    vent_valve.open()
    print(vent_valve.get_state())

    print('Press Enter When Desired Tank Ullage is Met')
    time.sleep(3)
    i = threading.Thread(target=get_input)
    i.start()

    while input_flag == 1:
        temp_fill = temperature_fill_line.read_sensor()
        temp_empty = temperature_empty_line.read_sensor()
        pressure = pressure_cold_flow.read_sensor()
        print(temp_fill[0], temp_empty[0], pressure[0])
        time.sleep(.1)
    vent_valve.close()
    print(vent_valve.get_state())
    final_pressure = pressure_cold_flow.read_sensor()

    print("Filling Completed: Current Pressure is...")
    print(final_pressure[0])
    input("Press Enter to Begin Leak Test")
    print('Beginning Leak Test')

    time_start = time.time()
    wait_time = 1
    n = 0

    k = threading.Thread(target=test_end_input)
    k.start()

    while test_flag == 1:
        read_sensors(n, time_start, wait_time)
        time.sleep(wait_time)
        n = n + 1

    print('done')
    print(time.time() - time_start)
    input('Press Enter to Open Valves and Depressurize Tank')
    actuator_prop.open()
    actuator_solenoid.open()
    fill_valve.open()
    vent_valve.open()

    actuator_prop.get_state()
    actuator_solenoid.get_state()
    fill_valve.get_state()
    vent_valve.get_state()
Exemple #27
0
def getRules(filename):
    threading.Timer(5.0, getRules, [filename]).start()
    return RuleList(filename)

try:
    ruleList = getRules(ruleFilename).rl
    if ruleList is not None:
        for rule in ruleList:
            print rule.sensor

    rad = SensorRadio()
    while(True):
        buff = rad.listen()
        print buff
        if buff is not None:
            newsensor = Sensor(buff[0], buff[1], buff[3])
            if any(oldsensor.idx == newsensor.idx for oldsensor in sensors):
                for oldsensor in sensors:
                    if oldsensor.idx == newsensor.idx:
                        oldsensor.value = newsensor.value
                        print 'Already in list. Update the values'
                        time.sleep(1)
            else:
                sensors.append(newsensor)
        listToJson(sensors)
        time.sleep(1)

except KeyboardInterrupt:
    print 'Got interrupt from keyboard'
    GPIO.cleanup()
Exemple #28
0
"""
Some example usage of the Sensor class
"""

from sensors import Sensor

temperatureSensor = Sensor("temperature")
reading = temperatureSensor.getReading()
reading2 = temperatureSensor.getReading()
reading3 = temperatureSensor.getReading()
print(reading)
print(reading['value'])
print(reading2['value'])
print(reading3['value'])
Exemple #29
0
 def try_bricklet(self, uid, device_identifier, position):
     if device_identifier == 26:
         s = Sensor(self.controller, "dualrelay", uid)
         for instance in ["0", "1"]:
             self.relays[s.uid + instance] = s
Exemple #30
0
    def test_bad_sensorType(self):
        with self.assertRaises(Exception) as context:
            Sensor("bad value")

        self.assertEqual('sensorType must be in {"temperature", "humidity"}',
                         str(context.exception))
    pS.on()

    sta_if = WLAN(STA_IF)
    while not sta_if.isconnected():
        pass
    pS.off()

    s = socket.socket()  # Create socket
    #ad = socket.getaddrinfo('000.000.000.000', 4444)[0][-1]  # Change your IP and Port here
    s.connect(ad)
    ss = wrap_socket(s)  # Wrap as a ssl socket
    #ss.write("aPASSWORD".encode())  # Set your password here
    ss.write("tu".encode())
    pS.on()
    irSender = Sender()
    sens = Sensor(ss, irSender)
    while True:
        data = ss.read(1).decode()  # Read one byte
        pS.off()
        if data is "q":
            ss.write("q".encode())
            utime.sleep(0.4)
            break
        elif (ord(data) >= 97 and ord(data) <= 122) or ord(data) == 10:
            irSender.got_data(data)
        sleep(0.1)
        pS.on()
    ss.close()
    s.close()
except Exception as e:
    print("Fehler", e)
 def __init__(self, id, macAddr):
     Sensor.__init__(self, id, macAddr, 'CC2650 SensorTag')
Exemple #33
0
pressure_list = ["Pressure"]
pressure_time_list = ["time"]
temperature_fill_list = ["Temperature Fill"]
temperature_fill_time_list = ["time"]
temperature_empty_list = ["Temperature Empty"]
temperature_empty_time_list = ["time"]
official_time_list = ["Official Time"]

# # Valve Definition and Classes
actuator_prop = Valve('Actuator Propellant Valve', 'P8_4', 'P8_4', 'prop', 4, 20)
actuator_solenoid = Valve('Actuator Solenoid Valve', 'P8_4', 0, 'solenoid', 0, 0)
fill_valve = Valve('Fill Valve', 'P8_8', 0, 'solenoid', 0, 0)
vent_valve = Valve('Vent Valve', 'P8_45', 0, 'solenoid', 0, 0)

# Pressure Sensor Definition and Classes
pressure_cold_flow = Sensor('pressure_cold_flow', 'pressure', 'P9_16', 'P9_16',
                            'P9_16', '000', '010', '100')

# Temperature Sensor Definition and Classes
temperature_fill_line = Sensor('temperature_fill_line', 'temperature', 'P9_12',
                               'P9_12', 'P9_12', '000', '000', '000')
temperature_empty_line = Sensor('temperature_empty_line', 'temperature',
                                'P9_14', 'P9_14', 'P9_16', '000', '000', '000')

# Relief Valve Counter: Will always start at zero
counter = 0

# Valve States and Tracking Global Variables
filling_trigger = False

data = [dict(x=[0], y=[0], type='scattergl', mode='lines+markers')]
layout_pressure = dict(title=dict(text='Live Pressure'),