Пример #1
0
    def __init__(self, motor_pin=None, servo_pin=None, servo_left=1000, servo_mid=1500, servo_right=2000, motor_reverse=False):
        assert motor_pin is not None, "motor_pin is not defined"
        assert servo_pin is not None, "servo_pin is not defined"

        if servo_left < servo_right:
            assert servo_left < servo_mid < servo_right, "servo_mid is not in between servo_left and servo_right"
        else:
            assert servo_left > servo_mid > servo_right, "servo_mid is not in between servo_left and servo_right"

        # setup motor
        self.motor = PWM(motor_pin)
        self.motor.period = 20000000

        if motor_reverse:
            self.MOTOR_REVERSE = True
            self.MOTOR_BRAKE = 1500
            self.MOTOR_MIN = 1000
            self.MOTOR_MAX = 2000
        
        else:
            self.MOTOR_REVERSE = False
            self.MOTOR_MIN = self.MOTOR_BRAKE = 1000
            self.MOTOR_MAX = 2000

        # setup servo
        self.servo = PWM(servo_pin)
        self.servo.period = 20000000
        
        self.SERVO_MID = servo_mid
        self.SERVO_MIN = servo_left
        self.SERVO_MAX = servo_right
Пример #2
0
 def __init__(self, hub):
     self.update_on = ('light', 'brightness')
     self.pwm = PWM(GPIO, pwm=BRIGHTNESS)
     if hub.light:
         self.pwm.on()
     else:
         self.pwm.off()
Пример #3
0
 def __init__(self):
     self.duty_scale = (self.duty_max - self.duty_min) / 100
     self.pwm = PWM(0)
     self.pwm.export()
     self.pwm.inversed = False
     self.pwm.period = 20000000
     self.pwm.duty_cycle = 2000000
     self.pwm.enable = True
Пример #4
0
 def __init__(self, pads):
     _r = Signal()
     _g = Signal()
     _b = Signal()
     self.submodules.r = PWM(_r)
     self.submodules.g = PWM(_g)
     self.submodules.b = PWM(_b)
     self.comb += [pads.r.eq(~_r), pads.g.eq(~_g), pads.b.eq(~_b)]
Пример #5
0
class Controls:
    def __init__(self):
        self.motor = PWM(0)
        self.servo = PWM(1)

        self.motor.export()
        self.servo.export()

        self.motor.period = 20000000
        self.servo.period = 20000000

        self.motor.enable = True
        self.servo.enable = True

        self.neutral()

    def move(self, speed):
        """
        0 <= speed <= 1
        where 0 is stopped
              1 is full speed
        """
        speed = interpolate_01(STOP_DUTY, FASTEST_DUTY, speed)
        self.motor.duty_cycle = int(speed)

    def turn(self, angle):
        """
        -1 <= angle <= +1
        where -1 is left
               0 is center
              +1 is right
        """
        # -angle because LEFT_DUTY > RIGHT_DUTY but want -1 to mean LEFT
        angle = interpolate_pm1(LEFT_DUTY, RIGHT_DUTY, -angle)
        self.servo.duty_cycle = int(angle)

    def neutral(self):
        self.move(STOP)
        self.turn(CENTER)

    def test(self):
        self.neutral()

        self.turn(LEFT)
        time.sleep(.5)

        self.turn(RIGHT)
        time.sleep(.5)

        self.turn(CENTER)
        time.sleep(.5)

        self.move(.15)
        time.sleep(1)

        self.move(STOP)
Пример #6
0
def serve():
    """ Entry point for the CLI.

    Bootstrap a new database first if necessary, then start the webserver.
    """
    args = parse_args()
    _init_logging(verbose=args.verbose, log_file=args.log_file)
    app = create_app(args.config_file)
    with app.app_context():
        pwm = PWM()
        pwm.bootstrap(app.config['SQLALCHEMY_DATABASE_URI'])
    app.run(debug=args.debug, host=args.host, port=args.port)
Пример #7
0
def serve():
    """ Entry point for the CLI.

    Bootstrap a new database first if necessary, then start the webserver.
    """
    args = parse_args()
    _init_logging(verbose=args.verbose, log_file=args.log_file)
    app = create_app(args.config_file)
    with app.app_context():
        pwm = PWM()
        pwm.bootstrap(app.config['SQLALCHEMY_DATABASE_URI'])
    app.run(debug=args.debug, host=args.host, port=args.port)
Пример #8
0
 def setUp(self):
     self.tmp_db = tempfile.NamedTemporaryFile(delete=False)
     self.tmp_db.close()
     db = sa.create_engine('sqlite:///%s' % self.tmp_db.name)
     Base.metadata.create_all(db)
     DBSession = sessionmaker(bind=db)
     self.session = DBSession()
     self.session.add(Domain(name='example.com', salt=b'NaCl'))
     self.session.add(Domain(name='otherexample.com', salt=b'supersalty'))
     self.session.add(Domain(name='facebook.com', salt=b'notsomuch'))
     self.session.commit()
     self.pwm = PWM()
     self.pwm.bootstrap(self.tmp_db.name)
Пример #9
0
    def __init__(self):
        self.motor = PWM(0)
        self.servo = PWM(1)

        self.motor.export()
        self.servo.export()

        self.motor.period = 20000000
        self.servo.period = 20000000

        self.motor.enable = True
        self.servo.enable = True

        self.neutral()
Пример #10
0
    def __init__(self,pwm=None,uart=None,uart_divisor=None,**kwargs):
        log.info("start build")
        log.info(str(*kwargs))
        super().__init__(**kwargs)

        #test = Testing()
        #self.add(test)

        for i in range(4):
            temp = TimerPeripheral(32,name="timer_"+str(i))
            self.add(temp)

        borker = BorkPeripheral()
        self.add(borker)

        blinky = LedPeripheral(Signal(2))
        self.add(blinky)
        
        counter = CounterPeripheral(10)
        self.add(counter)

        spi_interface = SPI()
        self.add(spi_interface)

        if uart is not None:
            serial1 = AsyncSerialPeripheral(divisor=uart_divisor)
            self.add(serial1)

        if pwm is not None:
            pwm = PWM(pwm)
            self.add(pwm)
Пример #11
0
    def elaborate(self, platform):
        m = Module()

        m.submodules.nco = self.nco = nco = NCO_LUT(output_width= self.pwm_resolution, 
            sin_input_width=self.resolution, signed_output=False)
        m.submodules.pwm = self.pwm = pwm = PWM(resolution = self.pwm_resolution)
        m.submodules.pdm = self.pdm = pdm = PDM(resolution = self.pwm_resolution)
    
        if(platform != None):
            platform.add_resources([
                Resource("pwm", 0,
                    Pins("2", conn=("gpio", 0), dir ="o" ), 
                    Attrs(IOSTANDARD="LVCMOS33")
                    ),
            ])
            self.pwm_o = platform.request("pwm")
            dpad = platform.request("dpad")

        m.d.comb += [
            nco.phi_inc_i.eq(self.phi_inc),
            pwm.input_value_i.eq(nco.sine_wave_o),
            pwm.write_enable_i.eq(0),
            pdm.input.eq(nco.sine_wave_o),
            pdm.write_en.eq(1),
            #self.pwm_o.o.eq(pwm.pwm_o),
            self.pwm_o.o.eq( Mux(dpad.c.i, pwm.pwm_o, pdm.pdm_out) ),
        ]

        


        return m
Пример #12
0
    def elaborate(self, platform):
        self.platform = platform
        m = Module()

        pll600 = self.__elab_build_pll600(m)

        m.submodules.nco = self.nco = nco \
            = DomainRenamer({"sync": "clk600"})(NCO_LUT(output_width= self.pwm_resolution, sin_input_width=self.resolution))
        m.submodules.pwm = self.pwm = pwm \
            = DomainRenamer({"sync": "clk600"})(PWM(resolution = self.pwm_resolution))
    
    
        platform.add_resources([
            Resource("pwm", 0,
                Pins("1", conn=("gpio", 0), dir ="o" ), 
                Attrs(io_standard="3.0-V PCI")
                ),
        ])
        
        self.pwm_o = platform.request("pwm")

        m.d.comb += [
            nco.phi_inc_i.eq(self.phi_inc),
            pwm.input_value_i.eq(nco.sine_wave_o),
            pwm.write_enable_i.eq(0),
            self.pwm_o.o.eq(pwm.pwm_o),
        ]
       

        return m
Пример #13
0
    def __init__(self, platform, **kwargs):
        sys_clk_freq = int(100e6)
        # SoC init (No CPU, we controlling the SoC with UART)
        SoCCore.__init__(self, platform, sys_clk_freq,
            cpu_type=None,
            csr_data_width=32,
            with_uart=False,
            with_timer=False,
            ident="My first System On Chip", ident_version=True,
        )

        # Clock Reset Generation
        self.submodules.crg = CRG(platform.request("clk100"))

        # No CPU, use Serial to control Wishbone bus
        self.add_cpu_or_bridge(UARTWishboneBridge(platform.request("serial"), sys_clk_freq, baudrate=115200))
        self.add_wb_master(self.cpu_or_bridge.wishbone)

        # FPGA identification
        self.submodules.dna = dna.DNA()

        led1 = platform.request("user_led")

        self.submodules.led  = PWM()

        self.comb+=led1.eq(self.led.pwm_out)
Пример #14
0
    def __init__(self):
        self._speed = 0
        self._direction = 0
        self._enabled = False

        self._enabledOutput = DigitalOutputDevice(self._enabledPin)
        self._speedPwm = PWM(0)  # pin 12
        self._directionPwm = PWM(1)  # pin 13

        self._speedPwm.export()
        self._directionPwm.export()

        time.sleep(1)  # wait till pwms are exported

        self._speedPwm.period = 20_000_000
        self._directionPwm.period = 20_000_000
Пример #15
0
	def __init__(self, pin , pin_pwm , pin_pwmR):
		self.avance = 0 
		self.pin = pin
		self.pin_pwmR = pin_pwmR
		self.cuenta = 0
		self.index = 0 
		self.velocidad = 0
		self.tiempo_anterior = time.time()
		self.tiempo_actual = 0
		self.pin_pwm = pin_pwm
		GPIO.setmode(GPIO.BOARD)
		GPIO.setup(self.pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
		GPIO.add_event_detect(self.pin, GPIO.FALLING, callback=self.interrupcion, bouncetime=5)
		GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
		self.pwm_llanta = PWM(self.pin_pwm)
		self.pwm_llantar = PWM(self.pin_pwmR)
		self.pid_vel  = PID()
Пример #16
0
class Interrupt(object):
	"""Clase elaborada por Luis Borbolla para interrupcion por hardware en raspberry pi """
	def __init__(self, pin , pin_pwm , pin_pwmR):
		self.avance = 0 
		self.pin = pin
		self.pin_pwmR = pin_pwmR
		self.cuenta = 0
		self.index = 0 
		self.velocidad = 0
		self.tiempo_anterior = time.time()
		self.tiempo_actual = 0
		self.pin_pwm = pin_pwm
		GPIO.setmode(GPIO.BOARD)
		GPIO.setup(self.pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
		GPIO.add_event_detect(self.pin, GPIO.FALLING, callback=self.interrupcion, bouncetime=5)
		GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
		self.pwm_llanta = PWM(self.pin_pwm)
		self.pwm_llantar = PWM(self.pin_pwmR)
		self.pid_vel  = PID()


	def setup(self , setPoint):
		self.pwm_llanta.start()
		if setPoint >0:
		    self.pwm_llanta.set_duty(setPoint/15.0)

		else:
		    self.pwm_llantar.set_duty(setPoint/15.0)
		self.pid_vel.setPoint(setPoint)
		
	def interrupcion(self,channel):
		#print 'velocidad = %s' % self.pin
		self.cuenta += 1
		self.tiempo_actual = time.time()
		self.avance += 10		
		prom_tiempos = (self.tiempo_actual-self.tiempo_anterior)/2
		self.velocidad = 9.974556675147593/prom_tiempos   #2.5*25.4*m.pi/20 == 9.974556675147593
	    	self.tiempo_anterior = self.tiempo_actual
		error = self.pid_vel.update(self.velocidad)
  		self.pwm_llanta.update(error/15.0)


	

	def esperar_int(self):
    	
		try:
    		    print "Waiting for rising edge on port 24"
    		    GPIO.wait_for_edge(24, GPIO.RISING)
    		    print "Rising edge detected on port 24. Here endeth the third lesson."

		except KeyboardInterrupt:
    		    GPIO.cleanup()       # clean up GPIO on CTRL+C exit
		GPIO.cleanup()           # clean up GPIO on normal exit
Пример #17
0
class Motion:
    _enabledPin = 6

    def __init__(self):
        self._speed = 0
        self._direction = 0
        self._enabled = False

        self._enabledOutput = DigitalOutputDevice(self._enabledPin)
        self._speedPwm = PWM(0)  # pin 12
        self._directionPwm = PWM(1)  # pin 13

        self._speedPwm.export()
        self._directionPwm.export()

        time.sleep(1)  # wait till pwms are exported

        self._speedPwm.period = 20_000_000
        self._directionPwm.period = 20_000_000

    def enable(self):
        self._updatePwm()
        self._speedPwm.enable = True
        self._directionPwm.enable = True
        self._enabledOutput.value = 1

    def disable(self):
        self._enabledOutput.value = 0
        self._speedPwm.enable = False
        self._directionPwm.enable = False

    def set_values(self, speed=None, direction=None):
        self._speed = speed if speed is not None else self._speed
        self._direction = direction if direction is not None else self._direction
        self._updatePwm()

    def _updatePwm(self):
        self._speedPwm.duty_cycle = _translate_duty_cycle(
            self._speed, speed_offset, speed_scale)
        self._directionPwm.duty_cycle = _translate_duty_cycle(
            self._direction, direction_offset, direction_scale)
Пример #18
0
class Servo:
    duty_min = 900000
    duty_max = 2790000
    duty_range = []
    pwm = []

    def __init__(self):
        self.duty_scale = (self.duty_max - self.duty_min) / 100
        self.pwm = PWM(0)
        self.pwm.export()
        self.pwm.inversed = False
        self.pwm.period = 20000000
        self.pwm.duty_cycle = 2000000
        self.pwm.enable = True

    def set_value(self, value):
        value = numpy.clip(value, 0, 100)
        scaled = int(value * self.duty_scale) + self.duty_min
        self.pwm.duty_cycle = scaled

    def disable(self):
        self.pwm.enable = False
Пример #19
0
class Driver:

    def __init__(self):
        self.pwm = PWM()

    def move(self, angular_speed, linear_speed):
        """
        Move the robot with given speeds
        :param angular_speed: Angular speed (-100 a 100)
        :param linear_speed: Linear speed (-100 a 100)
        """

        robot_radius = 0.11
        max_speed = 1.0

        duty_cycle_0 = int(((-linear_speed - (
                    robot_radius * angular_speed)) / max_speed) * 100)
        duty_cycle_1 = int(((linear_speed - (
                    robot_radius * angular_speed)) / max_speed) * 100)

        if duty_cycle_0 > 0:
            orientation_0 = 1
        else:
            orientation_0 = -1

        if duty_cycle_1 > 0:
            orientation_1 = 1
        else:
            orientation_1 = -1

        self.pwm.setPWM(0, orientation_0, abs(duty_cycle_0))
        self.pwm.setPWM(1, orientation_1, abs(duty_cycle_1))


    def finish(self):
        self.pwm.pwmFim()
Пример #20
0
 def PWM_init(self):
     from pwm import PWM
     self._pwm0 = PWM(0)
     self._pwm1 = PWM(1)
     self._pwm2 = PWM(2)
     self._pwm3 = PWM(3)
     self._pwm4 = PWM(4)
     self._pwm5 = PWM(5)
     self._pwm6 = PWM(6)
     self._pwm7 = PWM(7)
     self.pwm_switch(self.ON)
     self._pwm0.DEBUG = 'error'
     self._pwm1.DEBUG = 'error'
     self._pwm2.DEBUG = 'error'
     self._pwm3.DEBUG = 'error'
     self._pwm4.DEBUG = 'error'
     self._pwm5.DEBUG = 'error'
     self._pwm6.DEBUG = 'error'
     self._pwm7.DEBUG = 'error'
Пример #21
0
class Light():
    def __init__(self, hub):
        self.update_on = ('light', 'brightness')
        self.pwm = PWM(GPIO, pwm=BRIGHTNESS)
        if hub.light:
            self.pwm.on()
        else:
            self.pwm.off()

    def update(self, hub, changed):
        if hub.light:
            if BATT == False or config.BATT_LOW == None or hub.battery > config.BATT_LOW:
                self.pwm.set_duty(hub.brightness)
                self.pwm.on()
        else:
            self.pwm.off()

    def stop(self, hub):
        self.pwm.off()
Пример #22
0
def calibrage():
    GPIO.setmode(
        GPIO.BOARD)  # On lit les pattes dans l'ordre classique en électronique
    GPIO.setup(35, GPIO.OUT)  # La broche 35 est configurée en sortie
    pwm_X = PWM(0)
    pwm_Y = PWM(
        1)  # il n'existe que 2 canaux pour implementer les PWMs (0 et 1)
    pwm_X.export()
    pwm_Y.export()
    pwm_X.period = 100000  # les unites sont en nanosecondes, ainsi dans cet exemple la periode vaut 100000*1ns = 100 us
    pwm_Y.period = 100000
    GPIO.output(35, GPIO.HIGH)
    for i in range(0, int(pwm_Y.period / 5)):
        pwm_Y.duty_cycle = 5 * i
        pwm_Y.enable = True

    for i in range(0, int(pwm_X.period / 5)):

        pwm_X.duty_cycle = 5 * i
        pwm_X.enable = True

    for i in range(0, int(pwm_Y.period / 5)):
        pwm_Y.duty_cycle = pwm_Y.period - 5 * i
        pwm_Y.enable = True

    for i in range(0, int(pwm_X.period / 5)):
        pwm_X.duty_cycle = pwm_X.period - 5 * i
        pwm_X.enable = True

    pwm_X.enable = False
    pwm_Y.enable = False
    stylo_haut()
    time.sleep(1)
    pwm_X.duty_cycle = int(pwm_X.period / 2)
    pwm_X.enable = True
    time.sleep(1)

    camera = picamera.PiCamera()
    camera.capture('calibrage.jpg')
    time.sleep(1)
    pwm_X.enable = False

    pwm_X.unexport()
    pwm_Y.unexport()
    GPIO.cleanup()
    return 1
Пример #23
0
def tracer_grille(grille, agrandissement, angle, origine):
    n = 4000
    calibre = 0.1
    pwm_X = PWM(0)
    pwm_Y = PWM(
        1)  # il n'existe que 2 canaux pour implementer les PWMs (0 et 1)
    pwm_X.export()
    pwm_Y.export()
    pwm_X.period = 100000  # les unites sont en nanosecondes, ainsi dans cet exemple la periode vaut 100000*1ns = 100 us
    pwm_Y.period = 100000

    GPIO.setmode(
        GPIO.BOARD)  # On lit les pattes dans l'ordre classique en électronique
    GPIO.setup(35, GPIO.OUT)  # La broche 35 est configurée en sortie

    ##La fréquence max du lever/baisser de stylo et 4Hz. Donc 250ms.

    ###    Ecriture de la grille

    for i in range(0, len(grille)):
        for j in range(0, len(grille[0])):

            if (grille[i][j] != 0):

                seq_chiffre = choix(grille[i][j], i, j, agrandissement, angle)

                x = seq_chiffre[0]
                y = seq_chiffre[1]
                haut = seq_chiffre[2]
                for k in range(0, len(x)):
                    x[k] += origine[0] * calibre
                    y[k] += origine[1] * calibre

                stylo_haut()

                for k in range(0, len(x)):
                    if (k != 0):
                        lever_stylo(haut[k], haut[k - 1])

                    pwm_X.duty_cycle = int(x[k] * pwm_X.period / 3.3)
                    pwm_Y.duty_cycle = int(y[k] * pwm_Y.period / 3.3)
                    pwm_X.enable = True
                    pwm_Y.enable = True
                stylo_haut()

#Lorsque l'on a termine avec la table tracante
    pwm_X.enable = False  # On desactive la PWM
    pwm_Y.enable = False
    pwm_X.unexport()
    pwm_Y.unexport()
    GPIO.cleanup(
    )  # A la fin du programme on remet à 0 les broches du Rasberry PI
    return (0)
Пример #24
0
import time
import matplotlib.pyplot as plt
import numpy as np

from pwm import PWM
"""### Motor initialization and configuration

Motor speed range [0 - stop, 1 - full speed]
"""

# Enable servo
# object for servo
MOTOR_BRAKE = 1000000

motor = PWM(0)
motor.period = 20000000
motor.duty_cycle = MOTOR_BRAKE
motor.enable = True

#!! Wait for 3 seconds until the motor stops beeping
"""# Upon start of device, motor speed must be set to 0 for at least 5 seconds"""

motor.duty_cycle = MOTOR_BRAKE + 120000  # Motor should run at low speed

motor.duty_cycle = MOTOR_BRAKE + 1000000  # Motor full speed

motor.duty_cycle = MOTOR_BRAKE  # stop motor
"""### Servo configuration and calibration

Servo angle range [-1 - full left, 0 - center, 1 - full right]
Пример #25
0
class Robot():
    def __init__(self):

        if RobotUtils.LIVE_TESTING:
            self.pwm = PWM()
            self.pwm.setPWMFreq(RobotUtils.FREQUENCY)
        else:
            self.pwm = None

        self.inputQueue = Queue()
        self.agendaThread = threading.Thread(group=None,
                                             target=self.updateAgendaLoop,
                                             name="agendaThread")
        self.agendaThread.start()

        self.data_file_name = RobotUtils.DATA_FILE

        self.front_left = None
        self.front_right = None
        self.back_left = None
        self.back_right = None

        self.xMovement = 50
        self.yMovement = 50

        self.forwardIncMax = 15
        self.forwardInc = 1
        self.forwardIncMin = 1

        self.backwardIncMax = 15
        self.backwardInc = 1
        self.backwardIncMin = 1

        self.movement_threshold = 3

        self.MotionPlanner = MP()

        self.stop = False
        self.autonomous = False
        self.last_command = "STAND"
        self.max_command_delay = 200  # Commands have 200 milliseconds to execute before disregarded

        # Horizantal Video Servo Data
        self.horizVidValue = 50
        self.horizVidPin = 4
        self.horizVidMinVal = 0
        self.horizVidMaxVal = 100

        # Vertical Video Servo Data
        self.vertVidValue = 50
        self.vertVidPin = 8
        self.vertVidMinVal = 0
        self.vertVidMaxVal = 100

        self.horizVidMotor = Motor(self.horizVidValue, self.horizVidPin,
                                   self.horizVidMinVal, self.horizVidMaxVal, 0,
                                   "horizantal video motor", self.pwm)
        self.vertVidMotor = Motor(self.vertVidValue, self.vertVidPin,
                                  self.vertVidMinVal, self.vertVidMaxVal, 0,
                                  "vertical video motor", self.pwm)

        self.setup()
        self.reset()
        print '\033[93m' + "Robot Created. this was printed from robot class of number: " + str(
            id(self)) + '\033[0m'
        self.updateAgenda()

    # loads json data and creates Leg objects with add_leg()
    def setup(self):
        with open(self.data_file_name) as data_file:
            data = json.load(data_file)
            constants = data["constants"]
            for i in range(len(data["legs"])):
                self.add_leg(data["legs"][i], constants)

    # reads dictuanary values from input, creates a Leg object, and adds it to leg variables
    def add_leg(self, legData, constants):

        leg_name = legData["name"]

        body_pin = legData["motors"]["body"]["pinValue"]
        body_offset = legData["motors"]["body"]["offset"]
        body_center = constants["bodyCenterValue"] + body_offset
        body_min = constants["bodyRange"]["min"]
        body_max = constants["bodyRange"]["max"]

        mid_horiz_value = legData["motors"]["middle"]["horizValue"]
        middle_pin = legData["motors"]["middle"]["pinValue"]
        middle_min = constants["middleRange"]["min"]
        middle_max = constants["middleRange"]["max"]
        middle_offset_to_center = constants["midOffsetFromHoriz"]

        leg_horiz_value = legData["motors"]["leg"]["horizValue"]
        leg_pin = legData["motors"]["leg"]["pinValue"]
        leg_min = constants["legRange"]["min"]
        leg_max = constants["legRange"]["max"]
        leg_offset_to_center = constants["legOffsetFromHoriz"]

        leg = Leg(self.pwm, leg_name, body_pin, body_min, body_max,
                  body_center, mid_horiz_value, middle_pin, middle_min,
                  middle_max, middle_offset_to_center, leg_horiz_value,
                  leg_pin, leg_min, leg_max, leg_offset_to_center)

        if leg_name == "FR":
            self.front_right = leg

        elif leg_name == "FL":
            self.front_left = leg

        elif leg_name == "BL":
            self.back_left = leg

        elif leg_name == "BR":
            self.back_right = leg

        else:
            print "ERROR: LEG CANNOT BE IDENTIFIED"

    # Called by server when a change in user data is detected
    def inputData(self, data):
        self.inputQueue.put(data)

    def processData(self, data):
        self.xMovement = float(data["data"]["xMovement"])
        self.yMovement = float(data["data"]["yMovement"])
        self.horizVidValue = float(data["data"]["horizontalVideo"])
        self.vertVidValue = float(data["data"]["verticalVideo"])
        self.stop = data["data"]["stop"]
        self.autonomous = data["data"]["autonomous"]

    def updateAgendaLoop(self):
        while True:
            try:
                data = self.inputQueue.get_nowait()
                #if math.fabs( int(data.data["timestamp"]) - int(round(time.time() * 1000))) > self.max_command_delay:
                #	print "Command Delay Exceeded, command SHOULD be ignored"

                self.processData(data)
                self.updateAgenda()
            except Empty:
                print "pass"
                pass

            time.sleep(RobotUtils.AGENDA_UPDATE_SPEED)

        print '\033[94m' + "Robot: QUEUE READING FINISHED" + '\033[0m'
        sys.exit()

    # acts as central coordinator for the robot - raeads incoming data + state of the bot and calls methods accordingly
    def updateAgenda(self):

        print "in updateAgeda()"
        # if stop is called, the bot freezes in standing pose
        if not self.stop:

            # bot is autonomous, which has not been built yet, so we stand. Or do the mamba.
            if self.autonomous:
                self.reset()
                print '\033[94m' + "Robot: AUTONOMOUS" + '\033[0m'

            # bot is teleop mode
            else:
                # update camera motors
                self.horizVidMotor.moveTo(self.horizVidValue)
                self.vertVidMotor.moveTo(self.vertVidValue)

                xMagnitude = abs(self.xMovement - 50)
                yMagnitude = abs(self.yMovement - 50)

                # filter out value fluctuation by ensuring movment commands are past a certain threshold. Movement commands must be greater than 50 +- threshold to perform a command
                if (xMagnitude > self.movement_threshold) or (
                        yMagnitude > self.movement_threshold):

                    # command to move in the x axis rank higher in importance than command to move in y axis
                    if xMagnitude > yMagnitude:

                        # if xMovement is greater than 50 than we move left
                        if self.xMovement < 50:
                            print '\033[95m' + "Robot: LEFT" + '\033[0m \n'
                            self.turn(1)
                            self.forwardInc = self.forwardIncMin

                        # turn left
                        elif self.xMovement >= 50:
                            self.turn(-1)
                            print '\033[95m' + "Robot: RIGHT" + '\033[0m \n'
                            self.forwardInc = self.forwardIncMin

                        else:
                            print "logic error. This should not ever be printed"

                    # command to move in the y axis rank higher in importance than command to move in x axis
                    else:

                        # move forward
                        if self.yMovement > 50:

                            print '\033[95m' + "Robot: FORWARD" + '\033[0m \n'
                            # perform next segment of forward walk
                            #self.walkInit()

                            # increment forward walk increment variable
                            self.forwardInc += 1

                            # test to see if forward walk incrment variable has reached maximum value and reset it to min value if it has
                            if self.forwardInc == self.forwardIncMax:
                                self.forwardInc = self.forwardIncMin

                            # reset the backward incrementer, because the backward motion has been stopped, and needs to reset
                            self.backwardInc = self.backwardIncMin

                        # move backward
                        elif self.yMovement <= 50:
                            print '\033[95m' + "Robot: BACKWARD" + '\033[0m \n'

                        else:
                            print "logic error. this should not be printed"

                else:
                    print "\033[94m", "Robot: STAND", "\033[0m"
                    if not self.last_command == "STAND":
                        self.last_command = "STAND"
                        self.reset()

        else:
            print "\033[94m", "Robot: STOP \033[0m"
            self.reset()

    # Sets quadbot to standing position
    def reset(self):
        self.front_right.reset()
        self.front_left.reset()
        self.back_right.reset()
        self.back_left.reset()

    # resets legs to default position
    def init_stand(self):

        velocity = 5
        increment_count = 100

        body_offset = 0
        middle_offset = 100
        leg_offset = 100

        print "lunge start"
        self.lunge(body_offset, middle_offset, leg_offset, body_offset,
                   middle_offset, leg_offset, body_offset, middle_offset,
                   leg_offset, body_offset, middle_offset, leg_offset,
                   increment_count, velocity)

        time.sleep(2)

        self.lunge(body_offset, -middle_offset / 4, -leg_offset / 2,
                   body_offset, -middle_offset / 4, -leg_offset / 2,
                   body_offset, -middle_offset / 4, -leg_offset / 2,
                   body_offset, -middle_offset / 4, -leg_offset / 2,
                   increment_count, velocity)

        time.sleep(2)
        self.reset()

    def testMotionPlanner(self):
        x_min = 6
        x_max = 17
        y_min = -10
        y_max = 13

        print "Beggining Tests"

        for x in xrange(x_min, x_max, 1):
            y = 0
            values = self.MotionPlanner.calcThetas(x, y)
            print "Moving to: ", values
            self.back_left.middle.moveTo(values[0])
            self.back_left.leg.moveTo(values[1])
            time.sleep(.25)

        for y in xrange(y_min, y_max, 1):
            x = 13
            values = self.MotionPlanner.calcThetas(x, y)
            print "Moving to: ", values
            self.back_left.middle.moveTo(values[0])
            self.back_left.leg.moveTo(values[1])
            time.sleep(.25)

    def setAllHoriz(self):
        self.front_right.setMidAndLegHoriz()
        self.front_left.setMidAndLegHoriz()
        self.back_right.setMidAndLegHoriz()
        self.back_left.setMidAndLegHoriz()
        time.sleep(5)

    def setMidsToMin(self):
        self.front_right.middle.moveTo(self.front_right.middle.min)
        self.front_left.middle.moveTo(self.front_left.middle.min)
        self.back_left.middle.moveTo(self.back_left.middle.min)
        self.back_right.middle.moveTo(self.back_right.middle.min)
        time.sleep(10)

    def setMidsToMax(self):
        self.front_right.middle.moveTo(self.front_right.middle.max)
        self.front_left.middle.moveTo(self.front_left.middle.max)
        self.back_left.middle.moveTo(self.back_left.middle.max)
        self.back_right.middle.moveTo(self.back_right.middle.max)

    def turn(self, direction):

        if (direction > 0):
            turnDegree = 20
        else:
            turnDegree = -20

        stepHeightMid = 60
        stepHeightLeg = 5
        velocity = 0.002
        time_delay = 0
        self.front_right.standardPivotStep(turnDegree, stepHeightMid,
                                           stepHeightLeg, velocity, time_delay)
        time.sleep(time_delay)

        self.back_left.standardPivotStep(turnDegree, stepHeightMid,
                                         stepHeightLeg, velocity, time_delay)
        time.sleep(time_delay)

        self.front_left.standardPivotStep(turnDegree, stepHeightMid,
                                          stepHeightLeg, velocity, time_delay)
        time.sleep(time_delay)

        self.back_right.standardPivotStep(turnDegree, stepHeightMid,
                                          stepHeightLeg, velocity, time_delay)
        time.sleep(time_delay)
        self.reset()

    # Move all motors at once for synchronized motion (lunging)
    def lunge(self, FRB, FRM, FRL, FLB, FLM, FLL, BLB, BLM, BLL, BRB, BRM, BRL,
              increment_count, velocity):

        increment_count = float(increment_count)
        velocity = float(velocity)

        for x in range(int(increment_count)):

            self.front_right.body.moveOffset(float(FRB) / (increment_count))
            self.front_right.middle.moveOffset(float(FRM) / increment_count)
            self.front_right.leg.moveOffset(float(FRL) / increment_count)

            self.front_left.body.moveOffset(float(FLB) / increment_count)
            self.front_left.middle.moveOffset(float(FLM) / increment_count)
            self.front_left.leg.moveOffset(float(FLL) / increment_count)

            self.back_left.body.moveOffset(float(BLB) / increment_count)
            self.back_left.middle.moveOffset(float(BLM) / increment_count)
            self.back_left.leg.moveOffset(float(BLL) / increment_count)

            self.back_right.body.moveOffset(float(BRB) / increment_count)
            self.back_right.middle.moveOffset(float(BRM) / increment_count)
            self.back_right.leg.moveOffset(float(BRL) / increment_count)

            time.sleep(velocity / increment_count)

    # Method to walk forward. broken into ___ segments, which when executed sequentially create desired gate.
    def forward(self):
        self.reset()
        print "Beggining Walk"

        # Walk Methon Inputs
        std_pvt_body_delta = 15
        # std_pvt is short for 'standard pivor step'
        std_pvt_middle_delta = 20
        std_pvt_leg_delta = 15

        leg_ext_body_delta = 25
        # leg_ext is short for 'Leg Extend'.
        leg_ext_middle_delta = 20
        leg_ext_leg_delta = 15
        leg_ext_middle_raise = 30

        lunge_intensity = 1.0
        lunge_increment_count = 30

        L1_FRB_lunge_offset = lunge_intensity * 0  # XXX_lunge_offset provides parameters for lunge method
        L1_FRM_lunge_offset = lunge_intensity * 20
        L1_FRL_lunge_offset = lunge_intensity * -28

        L1_FLB_lunge_offset = lunge_intensity * 40
        L1_FLM_lunge_offset = lunge_intensity * 0
        L1_FLL_lunge_offset = lunge_intensity * 0

        L1_BLB_lunge_offset = lunge_intensity * 20
        L1_BLM_lunge_offset = lunge_intensity * -10
        L1_BLL_lunge_offset = lunge_intensity * 28

        L1_BRB_lunge_offset = lunge_intensity * -20
        L1_BRM_lunge_offset = lunge_intensity * 0
        L1_BRL_lunge_offset = lunge_intensity * 0

        L2_FRB_lunge_offset = -L1_FLB_lunge_offset  # XXX_lunge_offset provides parameters for lunge method
        L2_FRM_lunge_offset = L1_FLM_lunge_offset
        L2_FRL_lunge_offset = L1_FLL_lunge_offset

        L2_FLB_lunge_offset = L1_FRB_lunge_offset
        L2_FLM_lunge_offset = 1.25 * L1_FRM_lunge_offset
        L2_FLL_lunge_offset = 1.25 * L1_FRL_lunge_offset

        L2_BLB_lunge_offset = -L1_BRB_lunge_offset
        L2_BLM_lunge_offset = 0
        L2_BLL_lunge_offset = 0

        L2_BRB_lunge_offset = -L1_BLB_lunge_offset
        L2_BRM_lunge_offset = L1_BLM_lunge_offset
        L2_BRL_lunge_offset = L1_BLL_lunge_offset

        velocity = .1
        # Time for motor to move to new position. small velocity -> rapid movement
        time_delay = 0
        # Time delay between motor commands in leg method calls
        segment_delay = .1
        # 3 second delay between commands for debugging purposes

        # First Segment: back right standard pivot step
        self.back_right.standardPivotStep(std_pvt_body_delta,
                                          std_pvt_middle_delta,
                                          std_pvt_leg_delta, velocity / 10,
                                          time_delay / 10)
        time.sleep(segment_delay)

        # Second Segment: front right leg extends
        self.front_right.legExtend(leg_ext_body_delta, leg_ext_middle_delta,
                                   leg_ext_leg_delta, leg_ext_middle_raise,
                                   velocity, time_delay)
        time.sleep(segment_delay)

        # Condense forward and right
        self.lunge(L1_FRB_lunge_offset, L1_FRM_lunge_offset,
                   L1_FRL_lunge_offset, L1_FLB_lunge_offset,
                   L1_FLM_lunge_offset, L1_FLL_lunge_offset,
                   L1_BLB_lunge_offset, L1_BLM_lunge_offset,
                   L1_BLL_lunge_offset, L1_BRB_lunge_offset,
                   L1_BRM_lunge_offset, L1_BRL_lunge_offset,
                   lunge_increment_count, velocity)

        time.sleep(segment_delay)

        # Back left standard pivot
        self.back_left.reset()
        self.back_left.standardPivotStep(-std_pvt_body_delta / 2,
                                         std_pvt_middle_delta,
                                         std_pvt_leg_delta, velocity,
                                         time_delay)

        time.sleep(segment_delay)

        # Front Left Leg Extend body_delta, middle_delta, leg_delta,middle_raise
        self.front_left.reset()
        self.front_left.legExtend(-leg_ext_body_delta, -leg_ext_middle_delta,
                                  leg_ext_middle_raise, leg_ext_middle_raise,
                                  velocity, time_delay)
        time.sleep(segment_delay)

        # Front left condence forward
        self.lunge(L2_FRB_lunge_offset, L2_FRM_lunge_offset,
                   L2_FRL_lunge_offset, L2_FLB_lunge_offset,
                   L2_FLM_lunge_offset, L2_FLL_lunge_offset,
                   L2_BLB_lunge_offset, L2_BLM_lunge_offset,
                   L2_BLL_lunge_offset, L2_BRB_lunge_offset,
                   L2_BRM_lunge_offset, L2_BRL_lunge_offset,
                   lunge_increment_count, velocity)

        time.sleep(segment_delay)

        # Back left reset
        self.back_right.middle.moveOffSetInT(50, velocity * segment_delay)
        self.back_right.reset()

        time.sleep(segment_delay)

    def legacy_forward(self):
        print "Starting walk"
        velocity = .01
        time_delay = 0
        step_wait = 2
        std_piv_step_body_delta = -15
        std_piv_step_middle_delta = 50
        std_piv_step_leg_delta = 5

        self.front_left.standardPivotStep(std_piv_step_body_delta,
                                          std_piv_step_middle_delta,
                                          std_piv_step_leg_delta, velocity,
                                          time_delay)
        time.sleep(step_wait)

        self.back_right.standardPivotStep(-std_piv_step_body_delta,
                                          std_piv_step_middle_delta,
                                          std_piv_step_leg_delta, velocity,
                                          time_delay)
        time.sleep(step_wait)

        leg_extend_body_delta = 20
        leg_extend_middle_delta = -5
        leg_extend_leg_delta = 28

        self.front_right.legExtend(leg_extend_body_delta,
                                   leg_extend_middle_delta,
                                   leg_extend_leg_delta, velocity, time_delay)
        time.sleep(step_wait)

        splitNum = 10
        leg_condense_FLbody_delta = 40 / splitNum
        leg_condense_BRbody_delta = -20 / splitNum
        leg_condense_FRmiddle_delta = 20 / splitNum
        leg_condense_FRleg_delta = -28 / splitNum
        leg_condense_BLbody_delta = 20 / splitNum
        leg_condense_BLmiddle_delta = -10 / splitNum
        leg_condense_BLleg_delta = 28 / splitNum

        # condense forward right
        for x in range(0, splitNum):
            self.front_left.body.moveOffset(leg_condense_FLbody_delta)
            self.back_right.body.moveOffset(leg_condense_BRbody_delta)
            self.front_right.middle.moveOffset(leg_condense_FRmiddle_delta)
            self.front_right.leg.moveOffset(leg_condense_FRleg_delta)
            self.back_left.body.moveOffset(leg_condense_BLbody_delta)
            self.back_left.middle.moveOffset(leg_condense_BLmiddle_delta)
            self.back_left.leg.moveOffset(leg_condense_BLleg_delta)

        leg_step_BLbody_delta = -30
        leg_step_BLmiddle_delta = 30
        leg_step_BLleg_delta = -28
        time.sleep(step_wait)

        # back left standard pivot step with mid offset"
        self.back_left.standardPivotStepWithMidMovement(
            leg_step_BLbody_delta, leg_step_BLmiddle_delta,
            leg_step_BLleg_delta, velocity, time_delay)

        leg_step_FRbody_delta = -40
        leg_step_FRmiddle_delta = 5
        leg_step_FRleg_delta = 28

        # front left standard pivot step with mid movement"
        self.front_left.standardPivotStepWithMidMovement(
            leg_step_FRbody_delta, leg_step_FRmiddle_delta,
            leg_step_FRleg_delta, velocity, time_delay)
        time.sleep(step_wait)

        frontRightBodySplitDiff = self.front_right.body.center_value - self.front_right.body.value
        frontRightMiddleSplitDiff = self.front_right.middle.value - self.front_right.middle.center_value
        frontRightLegSplitDiff = self.front_right.leg.value - self.front_right.leg.center_value

        frontLeftBodySplitDiff = self.front_left.body.center_value - self.front_left.body.value
        frontLeftMiddleSplitDiff = self.front_left.middle.center_value - self.front_left.middle.value
        frontLeftLegSplitDiff = self.front_left.leg.center_value - self.front_left.leg.value

        backRightBodySwing = -20 / splitNum
        backRightMiddleSwing = -10 / splitNum
        backRightLegSwing = 28 / splitNum
        backLeftBodySwing = 40 / splitNum

        # forward condence
        for x in range(0, splitNum):
            self.front_right.body.moveOffset(frontRightBodySplitDiff /
                                             splitNum)
            self.front_right.middle.moveOffset(1)
            self.front_right.leg.moveOffset(frontRightLegSplitDiff / splitNum)

            #self.front_left.body.moveOffset(frontLeftBodySplitDiff/splitNum)
            self.front_left.middle.moveOffset(frontLeftMiddleSplitDiff /
                                              splitNum)
            self.front_left.leg.moveOffset(frontLeftLegSplitDiff / splitNum)

            self.back_right.body.moveOffset(backRightBodySwing)
            self.back_right.middle.moveOffset(backRightMiddleSwing)
            self.back_right.leg.moveOffset(backRightLegSwing)
            self.back_left.body.moveOffset(backLeftBodySwing)

        time.sleep(step_wait)

        leg_step_BRbody_delta = 30
        leg_step_BRmiddle_delta = 30
        leg_step_BRleg_delta = -28

        self.back_right.standardPivotStepWithMidMovement(
            leg_step_BRbody_delta, leg_step_BRmiddle_delta,
            leg_step_BRleg_delta, velocity, time_delay)

        leg_extend_body_delta = 35
        leg_extend_middle_delta = -5
        leg_extend_leg_delta = 28

        self.front_right.legExtend(leg_extend_body_delta,
                                   leg_extend_middle_delta,
                                   leg_extend_leg_delta, velocity, time_delay)
        time.sleep(step_wait)

        RlungeFLbody = 40
        RlungeBRbody = -20
        RlungeFRmiddle = 30
        RlungeFRleg = -28
        RlungeBLmiddle = -10
        RlungeBLleg = 28

        self.lunge(0, RlungeFRmiddle, RlungeFRleg, RlungeFLbody, 0, 0, 0,
                   RlungeBLmiddle, RlungeBLleg, RlungeBRbody, 0, 0)

        leg_step_BLbody_delta = -30
        leg_step_BLmiddle_delta = 30
        leg_step_BLleg_delta = -28
        time.sleep(step_wait)

        self.back_left.standardPivotStepWithMidMovement(
            leg_step_BLbody_delta, leg_step_BLmiddle_delta,
            leg_step_BLleg_delta, velocity, time_delay)

        self.front_left.legExtend(-leg_extend_body_delta,
                                  leg_extend_middle_delta,
                                  leg_extend_leg_delta, velocity, time_delay)
        time.sleep(step_wait)

        LlungeFRbody = -40
        LlungeBLbody = 20
        LlungeFLmiddle = 30
        LlungeFLleg = -28
        LlungeBRmiddle = -10
        LlungeBRleg = 28

        self.lunge(LlungeFRbody, 0, 0, 0, LlungeFLmiddle, LlungeFLleg,
                   LlungeBLbody, 0, 0, 0, LlungeBRmiddle, LlungeBRleg)
        self.reset()
        print "Done with walk."
        time.sleep(10)
Пример #26
0
    def __init__(self):

        if RobotUtils.LIVE_TESTING:
            self.pwm = PWM()
            self.pwm.setPWMFreq(RobotUtils.FREQUENCY)
        else:
            self.pwm = None

        self.inputQueue = Queue()
        self.agendaThread = threading.Thread(group=None,
                                             target=self.updateAgendaLoop,
                                             name="agendaThread")
        self.agendaThread.start()

        self.data_file_name = RobotUtils.DATA_FILE

        self.front_left = None
        self.front_right = None
        self.back_left = None
        self.back_right = None

        self.xMovement = 50
        self.yMovement = 50

        self.forwardIncMax = 15
        self.forwardInc = 1
        self.forwardIncMin = 1

        self.backwardIncMax = 15
        self.backwardInc = 1
        self.backwardIncMin = 1

        self.movement_threshold = 3

        self.MotionPlanner = MP()

        self.stop = False
        self.autonomous = False
        self.last_command = "STAND"
        self.max_command_delay = 200  # Commands have 200 milliseconds to execute before disregarded

        # Horizantal Video Servo Data
        self.horizVidValue = 50
        self.horizVidPin = 4
        self.horizVidMinVal = 0
        self.horizVidMaxVal = 100

        # Vertical Video Servo Data
        self.vertVidValue = 50
        self.vertVidPin = 8
        self.vertVidMinVal = 0
        self.vertVidMaxVal = 100

        self.horizVidMotor = Motor(self.horizVidValue, self.horizVidPin,
                                   self.horizVidMinVal, self.horizVidMaxVal, 0,
                                   "horizantal video motor", self.pwm)
        self.vertVidMotor = Motor(self.vertVidValue, self.vertVidPin,
                                  self.vertVidMinVal, self.vertVidMaxVal, 0,
                                  "vertical video motor", self.pwm)

        self.setup()
        self.reset()
        print '\033[93m' + "Robot Created. this was printed from robot class of number: " + str(
            id(self)) + '\033[0m'
        self.updateAgenda()
Пример #27
0
 def test_not_ready(self):
     pwm = PWM()
     self.assertRaises(NotReadyException, pwm.get_domain, 'example.com')
Пример #28
0
from pwm import PWM
pwm0 = PWM(0)
pwm1 = PWM(1)
pwm0.export()
pwm1.export()
pwm0.period = 20000000
pwm1.period = 20000000
pwm0.duty_cycle = 1000000
pwm0.enable = False
pwm1.duty_cycle = 1465000
pwm1.enable = False
Пример #29
0
from pwm_server import create_app

from os import path
from pwm import PWM

dev_config = path.abspath(path.join(path.dirname(__file__), 'dev_config.py'))

app = create_app(dev_config)

with app.app_context():
    pwm = PWM()
    pwm.bootstrap(app.config['SQLALCHEMY_DATABASE_URI'])

app.run(port=8848, debug=True)
Пример #30
0
class PWMCoreTest(unittest.TestCase):

    def setUp(self):
        self.tmp_db = tempfile.NamedTemporaryFile(delete=False)
        self.tmp_db.close()
        db = sa.create_engine('sqlite:///%s' % self.tmp_db.name)
        Base.metadata.create_all(db)
        DBSession = sessionmaker(bind=db)
        self.session = DBSession()
        self.session.add(Domain(name='example.com', salt=b'NaCl'))
        self.session.add(Domain(name='otherexample.com', salt=b'supersalty'))
        self.session.add(Domain(name='facebook.com', salt=b'notsomuch'))
        self.session.commit()
        self.pwm = PWM()
        self.pwm.bootstrap(self.tmp_db.name)


    def tearDown(self):
        os.remove(self.tmp_db.name)


    def test_get_domain(self):
        # test getting existing domain
        domain = self.pwm.get_domain('example.com')
        self.assertEqual(domain.salt, b'NaCl')
        self.assertEqual(domain.name, 'example.com')

        # test nonexisting domain
        self.assertRaises(NoSuchDomainException, self.pwm.get_domain, 'neverheardofthis')


    def test_add_domain(self):
        new_domain = self.pwm.create_domain('othersite.com')
        key = new_domain.derive_key('secret')

        # should now get the same key on second attempt
        fetched_domain = self.pwm.get_domain('othersite.com')
        self.assertEqual(fetched_domain.derive_key('secret'), key)


    def test_domain_search(self):
        results = self.pwm.search('example')
        self.assertEqual(len(results), 2)
        results = self.pwm.search('bank')
        self.assertEqual(len(results), 0)


    def test_no_duplicates(self):
        # PY26: If we drop support for python 2.6, this can be rewritten to use assertRaises as a
        # context manager, which is better for readability
        self.assertRaises(DuplicateDomainException, self.pwm.create_domain, 'example.com')


    def test_modify_domain(self):
        domain = self.pwm.get_domain('example.com')
        old_key = domain.derive_key('secret')
        modified_domain = self.pwm.modify_domain('example.com', new_salt=True,
            username='******')
        self.assertNotEqual(old_key, modified_domain.derive_key('secret'))
        self.assertEqual(modified_domain.username, '*****@*****.**')


    def test_modify_nonexistent_domain(self):
        self.assertRaises(NoSuchDomainException, self.pwm.modify_domain, 'neverheardofthis')
Пример #31
0
 def __init__(self, pads):
     self.submodules.r = PWM(pads.r)
     self.submodules.g = PWM(pads.g)
     self.submodules.b = PWM(pads.b)
Пример #32
0
    # Time parameters for simulation
    tf = 1
    dt = 0.1 * tau
    N = int(tf / dt)
    t = np.linspace(0, tf, N)

    # Voltage Signal parameters
    #Step Response
    V = 3.3  #[V]
    delay = 0.2 * tf  #[s]
    # voltage = Step(0, tf, dt, V, delay).signal
    #PWM input
    freq = 100  #[Hz]
    duty = 30  #[%]
    voltage = PWM(0, tf, dt, V, freq, duty).signal

    # MTQ Data Storage
    i_data = np.zeros(N)
    m_data = np.zeros(N)
    B_data = np.zeros(N)
    m_calc = np.zeros(N)

    # Sensors
    # Electric current
    i_std = 22e-5  #[A]
    i_bias = 22e-6  #[A]
    current_sensor = CurrentSensor(i_bias, i_std)
    # Magnetometer
    B_std = 1  #[uT]
    B_bias = 1e-1  #[uT]
Пример #33
0
from pwm import PWM
pwm0 = PWM(0)
pwm0.export()
pwm0.period = 20000000
pwm0.duty_cycle = 1000000
pwm0.enable = True
pwm0.duty_cycle = 1000000
Пример #34
0
# Voltage Signal parameters
V = 3.3 #[V]
duty=50 #[%]
#PWM input              #PWM nombre que se le da a la señal  o       
f0 = 1                  #[Hz] valor inicial #CAMBIE fo=0 a fo=1 para que no me tire "RuntimeWarning: divide by zero encountered in double_scalars"
fd = 100                #[Hz]pasos 
ff = 10000              #[Hz] valor final
Nf = int((ff-f0)/fd+1)  #[number of points] numero de valores que voy a tener
freq = np.linspace(f0, ff, Nf) #[%] 
voltage = np.zeros((Nf, N)) #matriz tabla de valores dependiendo de frecuencia y tiempo)
v_rms = np.zeros(Nf)
v_med = np.zeros(Nf)


for i in range (0,Nf):
    voltage[i,:] = PWM(0, tf, dt, V, freq[i], duty).signal #[i,:], filas
    v_rms[i] = np.sqrt(np.mean(voltage[i,:]**2)) #rms root mean sqr value
    v_med[i] = np.mean(voltage[i,:])

# Sensors
# Electric current
i_std = 22e-5		#[A]
i_bias = 22e-6		#[A]
current_sensor = CurrentSensor(i_bias, i_std)
# Magnetometer
B_std = 1			#[uT]
B_bias = 1e-1		#[uT]
magnetometer = Magnetometer(B_bias, B_std)
z = 16e-3			#[m]

def generate_tomtom_png( user_info ) :
	#the tomtom result file should be available in the current working direcotry

	jobid = user_info['jobid']

	motifs = []
	for l in open( logo_summary_fn  ) :
		l = l.split()
		print l
		if l and l[0] == jobid :
			motifs = l
			break

	orientations = [ 'r' if 'rc' in m else 'f' for m in motifs ]

	if not exists( tomtom_dir ) :
		raise Exception( tomtom_dir + ' does not exists!' )
	#chdir( tomtom_dir )

	tomtom = et.parse( tomtom_result_fn )
	motifs = {}
	for motif in tomtom.iter( 'motif' ) :
		motifs[ motif.attrib['id'] ] = motif

	#debug
	#for motif in motifs :
		#print motif.tag, motif.attrib

	#target_files = tomtom.iter( 'target_file' )
	queries = tomtom.iter( 'query' )

	for query in queries :
		query_motif = query.find('motif')

		qpwm = PWM( query_motif )
		querynum = int( query_motif.attrib['id'].split('_')[1] )

		print querynum, orientations
		if orientations[querynum] == 'f' :
			qpwm.generate_png( join( tomtom_dir, '%s_f.png'%query_motif.attrib['id'] ) )
			qpwm.reverse()
			qpwm.generate_png( join( tomtom_dir, '%s_r.png'%query_motif.attrib['id'] ) )
		else :
			qpwm.generate_png( join( tomtom_dir, '%s_r.png'%query_motif.attrib['id'] ) )
			qpwm.reverse()
			qpwm.generate_png( join( tomtom_dir, '%s_r.png'%query_motif.attrib['id'] ) )

		for i, match in enumerate( query.iter( 'match' ) ) :

			#print '*'*30
			#print i,":", match.attrib
			targetid = match.attrib['target']
			offset = int(match.attrib['offset']) #target offset
			orientation = match.attrib['orientation'] #target orientation

			target_motif = motifs[targetid]
			tpwm = PWM( target_motif )
			if orientation == 'forward' :
				pass
			elif orientation == 'reverse' :
				tpwm.reverse()

			qpwm = PWM( query_motif )
			qpwm.match( tpwm, offset )

			if orientations[querynum] == 'f' :
				qpwm.generate_png( join( tomtom_dir, '%s_m_%s_f.png' % (query_motif.attrib['id'],i) ) )
				tpwm.generate_png( join( tomtom_dir, '%s_m_%s_f_t.png' % (query_motif.attrib['id'],i) ) )
				#reversed
				qpwm.reverse()
				tpwm.reverse()
				qpwm.generate_png( join( tomtom_dir, '%s_m_%s_r.png' % (query_motif.attrib['id'],i) ) )
				tpwm.generate_png( join( tomtom_dir, '%s_m_%s_r_t.png' % (query_motif.attrib['id'],i) ) )
				#print '*'*30
				#print
			else :
				qpwm.generate_png( join( tomtom_dir, '%s_m_%s_r.png' % (query_motif.attrib['id'],i) ) )
				tpwm.generate_png( join( tomtom_dir, '%s_m_%s_r_t.png' % (query_motif.attrib['id'],i) ) )
				qpwm.reverse()
				tpwm.reverse()
	
				qpwm.generate_png( join( tomtom_dir, '%s_m_%s_f.png' % (query_motif.attrib['id'],i) ) )
				tpwm.generate_png( join( tomtom_dir, '%s_m_%s_f_t.png' % (query_motif.attrib['id'],i) ) )