class NvidiaRacecar(Racecar): #set offsets for my car #after changing values, re-run setup.py i2c_address = traitlets.Integer(default_value=0x40) steering_gain = traitlets.Float(default_value=1) steering_offset = traitlets.Float(default_value=0.15) steering_channel = traitlets.Integer(default_value=0) throttle_gain = traitlets.Float(default_value=1) throttle_channel = traitlets.Integer(default_value=1) throttle_offset = traitlets.Float(default_value=0.13) def __init__(self, *args, **kwargs): super(NvidiaRacecar, self).__init__(*args, **kwargs) self.kit = ServoKit(channels=16, address=self.i2c_address) self.steering_motor = self.kit.continuous_servo[self.steering_channel] self.throttle_motor = self.kit.continuous_servo[self.throttle_channel] self.steering_motor.throttle = self.steering_offset self.throttle_motor.throttle = self.throttle_offset @traitlets.observe('steering') def _on_steering(self, change): self.steering_motor.throttle = change[ 'new'] * self.steering_gain + self.steering_offset @traitlets.observe('throttle') def _on_throttle(self, change): self.throttle_motor.throttle = change[ 'new'] * self.throttle_gain + self.throttle_offset
class videoStream(Camera): capture_fps = traitlets.Integer(default_value=30) capture_width = traitlets.Integer(default_value=640) capture_height = traitlets.Integer(default_value=480) capture_device = traitlets.Unicode(default_value='/home/horus/Notebooks/Orcamia/test/AsaltoPistolaJuguete.avi') def __init__(self, *args, **kwargs): super(videoStream, self).__init__(*args, **kwargs) try: self.cap = cv2.VideoCapture(self._gst_str(), cv2.CAP_GSTREAMER) re , image = self.cap.read() if not re: raise RuntimeError('Could not read image from camera.') except: raise RuntimeError( 'Could not initialize camera. Please see error trace.') atexit.register(self.cap.release) def _gst_str(self): return 'filesrc location={} ! avidemux ! decodebin ! videoconvert ! videoscale ! appsink'.format(self.capture_device, self.capture_width, self.capture_height) #return 'rtspsrc location={} ! decodebin ! nvvidconv ! video/x-raw, width=(int){}, height=(int){}, format=(string)BGRx ! videoconvert ! appsink'.format(self.capture_device, self.capture_width, self.capture_height) def _read(self): re, image = self.cap.read() if re: image_resized = cv2.resize(image,(int(self.width),int(self.height))) return image_resized else: raise RuntimeError('Could not read image from camera')
class CSICamera(Camera): capture_fps = traitlets.Integer(default_value=30) capture_width = traitlets.Integer(default_value=640) capture_height = traitlets.Integer(default_value=480) def __init__(self, *args, **kwargs): super(CSICamera, self).__init__(*args, **kwargs) try: self.cap = cv2.VideoCapture(self._gst_str(), cv2.CAP_GSTREAMER) re, image = self.cap.read() if not re: raise RuntimeError('Could not read image from camera.') except: raise RuntimeError( 'Could not initialize camera. Please see error trace.') atexit.register(self.cap.release) def _gst_str(self): return 'nvarguscamerasrc ! video/x-raw(memory:NVMM), width=%d, height=%d, format=(string)NV12, framerate=(fraction)%d/1 ! nvvidconv ! video/x-raw, width=(int)%d, height=(int)%d, format=(string)BGRx ! videoconvert ! appsink' % ( self.capture_width, self.capture_height, self.capture_fps, self.width, self.height) def _read(self): re, image = self.cap.read() if re: return image else: raise RuntimeError('Could not read image from camera')
class MJPEGCamera(Camera): capture_location = traitlets.Unicode(default_value="127.0.0.1:8080/stream") capture_fps = traitlets.Integer(default_value=30) capture_width = traitlets.Integer(default_value=640) capture_height = traitlets.Integer(default_value=480) def __init__(self, *args, **kwargs): super(MJPEGCamera, self).__init__(*args, **kwargs) try: self.cap = cv2.VideoCapture(self._gst_str(), cv2.CAP_GSTREAMER) re, image = self.cap.read() if not re: raise RuntimeError('Could not read image from camera.') except: raise RuntimeError( 'Could not initialize camera. Please see error trace.') atexit.register(self.cap.release) def _gst_str(self): return 'souphttpsrc location=%s do-timestamp=true is_live=true ! multipartdemux ! jpegdec ! videorate ! videoscale ! video/x-raw, width=(int)%d, height=(int)%d, framerate=(fraction)%d/1 ! videoconvert ! video/x-raw, format=BGR ! appsink' % ( "http://" + self.capture_location, self.capture_width, self.capture_height, self.capture_fps) def _read(self): re, image = self.cap.read() if re: return image else: raise RuntimeError('Could not read image from camera')
class RTSPCamera(Camera): capture_fps = traitlets.Integer(default_value=30) capture_width = traitlets.Integer(default_value=640) capture_height = traitlets.Integer(default_value=480) capture_source = traitlets.Any(default_value='rtsp://localhost:8080') def __init__(self, *args, **kwargs): super(RTSPCamera, self).__init__(*args, **kwargs) try: self.cap = cv2.VideoCapture(self._gst_str(), cv2.CAP_GSTREAMER) re , image = self.cap.read() if not re: raise RuntimeError('Could not read image from camera.') except: raise RuntimeError( 'Could not initialize camera. Please see error trace.') atexit.register(self.cap.release) def _gst_str(self): return 'rtspsrc location={} latency=0 ! rtph264depay ! h264parse ! omxh264dec ! videorate ! videoscale ! video/x-raw,framerate={}/1,width={},height={} ! videoconvert ! video/x-raw,format=(string)BGR ! queue ! appsink sync=false'.format(self.capture_source, self.capture_fps, self.capture_width, self.capture_height) def _read(self): re, image = self.cap.read() if re: image_resized = cv2.resize(image,(int(self.width),int(self.height))) return image_resized else: raise RuntimeError('Could not read image from camera')
class Camera(SingletonConfigurable): value = traitlets.Any() # config width = traitlets.Integer(default_value=224).tag(config=True) height = traitlets.Integer(default_value=224).tag(config=True) fps = traitlets.Integer(default_value=21).tag(config=True) capture_width = traitlets.Integer(default_value=3280).tag(config=True) capture_height = traitlets.Integer(default_value=2464).tag(config=True) def __init__(self, *args, **kwargs): self.value = np.empty((self.height, self.width, 3), dtype=np.uint8) super(Camera, self).__init__(*args, **kwargs) try: self.cap = cv2.VideoCapture(self._gst_str(), cv2.CAP_GSTREAMER) re, image = self.cap.read() if not re: raise RuntimeError('Could not read image from camera.') self.value = image self.start() except: self.stop() raise RuntimeError( 'Could not initialize camera. Please see error trace.') atexit.register(self.stop) def _capture_frames(self): while True: re, image = self.cap.read() if re: self.value = image else: break def _gst_str(self): return 'nvarguscamerasrc ! video/x-raw(memory:NVMM), width=%d, height=%d, format=(string)NV12, framerate=(fraction)%d/1 ! nvvidconv ! video/x-raw, width=(int)%d, height=(int)%d, format=(string)BGRx ! videoconvert ! appsink' % ( self.capture_width, self.capture_height, self.fps, self.width, self.height) def start(self): if not self.cap.isOpened(): self.cap.open(self._gst_str(), cv2.CAP_GSTREAMER) if not hasattr(self, 'thread') or not self.thread.isAlive(): self.thread = threading.Thread(target=self._capture_frames) self.thread.start() def stop(self): if hasattr(self, 'cap'): self.cap.release() if hasattr(self, 'thread'): self.thread.join() def restart(self): self.stop() self.start()
class Camera_USB(SingletonConfigurable): value = traitlets.Any() # config width = traitlets.Integer(default_value=640).tag(config=True) height = traitlets.Integer(default_value=480).tag(config=True) fps = traitlets.Integer(default_value=21).tag(config=True) capture_width = traitlets.Integer(default_value=3280).tag(config=True) capture_height = traitlets.Integer(default_value=2464).tag(config=True) def __init__(self, *args, **kwargs): self.value = np.empty((self.height, self.width, 3), dtype=np.uint8) super(Camera_USB, self).__init__(*args, **kwargs) try: self.cap = cv2.VideoCapture(0) self.cap.set(3, self.width) self.cap.set(4, self.height) re, image = self.cap.read() if not re: raise RuntimeError('Could not read image from camera.') self.value = image self.start() except: self.stop() raise RuntimeError( 'Could not initialize camera. Please see error trace.') atexit.register(self.stop) def _capture_frames(self): while True: re, image = self.cap.read() if re: self.value = image else: break def start(self): if not self.cap.isOpened(): self.cap.open(0) if not hasattr(self, 'thread') or not self.thread.isAlive(): self.thread = threading.Thread(target=self._capture_frames) self.thread.start() def stop(self): if hasattr(self, 'cap'): self.cap.release() if hasattr(self, 'thread'): self.thread.join() def restart(self): self.stop() self.start()
class Robot(SingletonConfigurable): left_motor = traitlets.Instance(Motor) right_motor = traitlets.Instance(Motor) brush_motor = traitlets.Instance(Motor) # # config i2c_bus = traitlets.Integer(default_value=1).tag(config=True) left_motor_channel = traitlets.Integer(default_value=1).tag(config=True) left_motor_alpha = traitlets.Float(default_value=1.0).tag(config=True) right_motor_channel = traitlets.Integer(default_value=2).tag(config=True) right_motor_alpha = traitlets.Float(default_value=1.0).tag(config=True) brush_motor_channel = traitlets.Integer(default_value=3).tag( config=True) # brush_motor_alpha = traitlets.Float(default_value=1.0).tag(config=True) # def __init__(self, *args, **kwargs): super(Robot, self).__init__(*args, **kwargs) self.motor_driver = Adafruit_MotorHAT(i2c_bus=self.i2c_bus) self.left_motor = Motor(self.motor_driver, channel=self.left_motor_channel, alpha=self.left_motor_alpha) self.right_motor = Motor(self.motor_driver, channel=self.right_motor_channel, alpha=self.right_motor_alpha) self.brush_motor = Motor(self.motor_driver, channel=self.brush_motor_channel, alpha=self.brush_motor_alpha) # def set_motors(self, left_speed, right_speed): self.left_motor.value = left_speed self.right_motor.value = right_speed def forward(self, speed=1.0, duration=None): self.left_motor.value = speed self.right_motor.value = speed def backward(self, speed=1.0): self.left_motor.value = -speed self.right_motor.value = -speed def left(self, speed=1.0): self.left_motor.value = -speed self.right_motor.value = speed def right(self, speed=1.0): self.left_motor.value = speed self.right_motor.value = -speed def stop(self): self.left_motor.value = 0 self.right_motor.value = 0 def brush(self, speed=1.0): self.brush_motor.value = speed
class Robot(SingletonConfigurable): pwm_driver = traitlets.Instance(PCA9685) left_motor = traitlets.Instance(Motor) right_motor = traitlets.Instance(Motor) # config left_motor_channel = traitlets.Integer(default_value=0).tag(config=True) left_motor_alpha = traitlets.Float(default_value=1.0).tag(config=True) right_motor_channel = traitlets.Integer(default_value=1).tag(config=True) right_motor_alpha = traitlets.Float(default_value=1.0).tag(config=True) def __init__(self, *args, **kwargs): super(Robot, self).__init__(*args, **kwargs) # Create a i2c bus interface, a simple PCA9685 class instance and set the pwn frequency. # You can optionally provide a finer tuned reference clock speed to improve the accuracy of the # timing pulses. This calibration will be specific to each board and its environment. See the # calibration.py example in the PCA9685 driver. # pca = PCA9685(i2c, reference_clock_speed=25630710) _i2c = busio.I2C(SCL, SDA) _pwm_driver = PCA9685(_i2c) _pwm_driver.frequency = 50 self.left_motor = Motor(_pwm_driver, channel=self.left_motor_channel, alpha=self.left_motor_alpha, beta=0.05) self.right_motor = Motor(_pwm_driver, channel=self.right_motor_channel, alpha=self.right_motor_alpha, beta=0.05) def set_motors(self, left_speed, right_speed): self.left_motor.value = left_speed self.right_motor.value = right_speed def forward(self, speed=1.0, duration=None): self.left_motor.value = speed self.right_motor.value = -speed def backward(self, speed=1.0): self.left_motor.value = -speed self.right_motor.value = speed def left(self, speed=1.0): self.left_motor.value = -speed self.right_motor.value = -speed def right(self, speed=1.0): self.left_motor.value = speed self.right_motor.value = speed def stop(self): self.left_motor.value = 0.0 self.right_motor.value = 0.0
class CropCells(Preprocessor): """A preprocessor to crop the notebook cells from <start> to <end>""" start = traits.Integer(0, help="first cell of notebook to be converted").tag(config=True) end = traits.Integer(-1, help="last cell of notebook to be converted").tag(config=True) def preprocess(self, nb, resources): logging.info('preprocessing notebook: cropping cells {0} to {1}'.format(self.start, self.end)) nb.cells = nb.cells[self.start:self.end] return nb, resources
class JetbotRacecar(Racecar): steering_gain = traitlets.Float(default_value=-0.65) steering_offset = traitlets.Float(default_value=0) throttle_gain = traitlets.Float(default_value=0.8) i2c_bus = traitlets.Integer(default_value=1).tag(config=True) left_motor_channel = traitlets.Integer(default_value=1).tag(config=True) right_motor_channel = traitlets.Integer(default_value=2).tag(config=True) def __init__(self, *args, **kwargs): super(JetbotRacecar, self).__init__(*args, **kwargs) self.motor_driver = Adafruit_MotorHAT(i2c_bus=self.i2c_bus) self.left_motor = DcMotor(self.motor_driver, channel=self.left_motor_channel) self.right_motor = DcMotor(self.motor_driver, channel=self.right_motor_channel) def _move_car(self): """Moves car with 2 wheels (left, right)""" value_y = self.steering * self.steering_gain + self.steering_offset value_x = self.throttle * self.throttle_gain # convert steering and throttle to left/right thrust values theta = np.arctan2(value_y, value_x) radial_x = abs(value_x) * np.cos(theta) radial_y = abs(value_y) * np.sin(theta) radius = np.sqrt(pow(radial_x, 2) + pow(radial_y, 2)) * 100. theta_radial_degrees = degrees(np.arctan2(radial_y, radial_x)) left_thrust, right_thrust = throttle_angle_to_thrust( radius, theta_radial_degrees) # set motors values self.left_motor.value = float(left_thrust / 100.) self.right_motor.value = float(right_thrust / 100.) @traitlets.observe('steering') def _on_steering(self, change): self._move_car() @traitlets.observe('throttle') def _on_throttle(self, change): self._move_car() @traitlets.observe('throttle_gain') def _on_throttle_gain(self, change): self._move_car() @traitlets.observe('steering_gain') def _on_steering_gain(self, change): self._move_car() @traitlets.observe('steering_offset') def _on_steering_offset(self, change): self._move_car()
class ProgressCircularNoAnimation(v.VuetifyTemplate): """v-progress-circular that avoids animations""" parts = traitlets.List(traitlets.Unicode()).tag(sync=True) width = traitlets.Integer().tag(sync=True) size = traitlets.Integer().tag(sync=True) value = traitlets.Float().tag(sync=True) color = traitlets.Unicode('{: 14,d}').tag(sync=True) text = traitlets.Unicode('{: 14,d}').tag(sync=True) hidden = traitlets.Bool(False).tag(sync=True) template = traitlets.Unicode(''' <v-progress-circular v-if="!hidden" :key="value" :size="size" :width="width" :value="value" :color="color">{{ text }}</v-progress-circular> <v-progress-circular v-else style="visibility: hidden" :key="value" :size="size" :width="width" :value="value" :color="color">{{ text }}</v-progress-circular> ''').tag(sync=True)
class Camera(traitlets.HasTraits): value = traitlets.Any() width = traitlets.Integer(default_value=224) height = traitlets.Integer(default_value=224) format = traitlets.Unicode(default_value='bgr8') running = traitlets.Bool(default_value=False) def __init__(self, *args, **kwargs): super(Camera, self).__init__(*args, **kwargs) if self.format == 'bgr8': self.value = np.empty((self.height, self.width, 3), dtype=np.uint8) self._running = False def _read(self): """Blocking call to read frame from camera""" raise NotImplementedError def read(self): if self._running: raise RuntimeError('Cannot read directly while camera is running') self.value = self._read() return self.value def _capture_frames(self): while True: if not self._running: break self.value = self._read() @traitlets.observe('running') def _on_running(self, change): if change['new'] and not change['old']: # transition from not running -> running self._running = True self.thread = threading.Thread(target=self._capture_frames) self.thread.start() elif change['old'] and not change['new']: # transition from running -> not running self._running = False self.thread.join() def start_recording(self): raise RuntimeError('Not implemented exception') def stop_recording(self): # global video_recording # video_recording = False raise RuntimeError('Not implemented exception') def capture_as_rgb_array_bottom_half(self): return crop_bottom_half(self.read())
class Robot(SingletonConfigurable): left_motor = traitlets.Instance(Motor) right_motor = traitlets.Instance(Motor) # config left_motor_channel = traitlets.Integer(default_value=1).tag(config=True) left_motor_alpha = traitlets.Float(default_value=1.0).tag(config=True) right_motor_channel = traitlets.Integer(default_value=2).tag(config=True) right_motor_alpha = traitlets.Float(default_value=1.0).tag(config=True) def __init__(self, *args, **kwargs): super(Robot, self).__init__(*args, **kwargs) self.motor_driver = None # for compatibility with jetbot self.left_motor = Motor(self.motor_driver, channel=self.left_motor_channel, alpha=self.left_motor_alpha) self.right_motor = Motor(self.motor_driver, channel=self.right_motor_channel, alpha=self.right_motor_alpha) def set_motors(self, left_speed, right_speed): self.left_motor.value = left_speed self.right_motor.value = right_speed def forward(self, speed=1.0): self.left_motor.value = speed self.right_motor.value = speed def backward(self, speed=1.0): self.left_motor.value = -speed self.right_motor.value = -speed def left(self, speed=1.0): self.left_motor.value = -speed self.right_motor.value = speed def right(self, speed=1.0): self.left_motor.value = speed self.right_motor.value = -speed def stop(self): self.left_motor.value = 0 self.right_motor.value = 0 def free(self): self.left_motor.release() self.right_motor.release()
class Robot(SingletonConfigurable): left_motor = traitlets.Instance(Motor) right_motor = traitlets.Instance(Motor) # config #i2c_bus = traitlets.Integer(default_value=1).tag(config=True) left_motor_channel = traitlets.Integer(default_value=1).tag(config=True) left_motor_alpha = traitlets.Float(default_value=1.0).tag(config=True) right_motor_channel = traitlets.Integer(default_value=2).tag(config=True) right_motor_alpha = traitlets.Float(default_value=1.0).tag(config=True) def __init__(self, *args, **kwargs): super(Robot, self).__init__(*args, **kwargs) self.motor_driver = qwiic_scmd.QwiicScmd() self.left_motor = Motor(self.motor_driver, channel=self.left_motor_channel, alpha=self.left_motor_alpha) self.right_motor = Motor(self.motor_driver, channel=self.right_motor_channel, alpha=self.right_motor_alpha) self.motor_driver.enable() def set_motors(self, left_speed, right_speed): self.left_motor.value = left_speed self.right_motor.value = right_speed self.motor_driver.enable() # Set Motor Controls: .set_drive( motor number, direction, speed) # Motor Number: A = 0, B = 1 # Direction: FWD = 0, BACK = 1 # Speed: (-255) - 255 (neg. values reverse direction of motor) def forward(self, speed=1.0, duration=None): self.set_motors(speed, speed) def backward(self, speed=1.0): self.set_motors(-speed, -speed) def left(self, speed=1.0): self.set_motors(-speed, speed) def right(self, speed=1.0): self.set_motors(speed, -speed) def stop(self): self.motor_driver.disable()
class Camera(SingletonConfigurable): value = traitlets.Any() # config width = traitlets.Float(default_value=224.0).tag(config=True) height = traitlets.Float(default_value=224.0).tag(config=True) fps = traitlets.Float(default_value=2.0).tag(config=True) capture_width = traitlets.Integer(default_value=3280).tag(config=True) capture_height = traitlets.Integer(default_value=2464).tag(config=True) is_usb = traitlets.Bool(default_value=False).tag(config=True) brightness = traitlets.Float(default_value=10.0).tag(config=True) device = traitlets.Integer(default_value=0).tag(config=True) def __init__(self, *args, **kwargs): super(Camera, self).__init__(*args, **kwargs)
class Trace(nowidget.Trait): collector = traitlets.Any() trace = traitlets.Any() traces = traitlets.List() max_dict_size = traitlets.Integer(1000) def log(self, trace): self.traces.append(trace) def flush(self): self.flushed = True def __enter__(self): self.trace = monkeytype.tracing.trace_calls( self, self.max_dict_size, lambda c: c.co_filename.startswith( '<ipython-input-') ) self.toggle(True) self.trace.__enter__() def __exit__(self, type=None, object=None, traceback=None): self.toggle(False) self.trace.__exit__(type, object, traceback) def stub(self, line=None, cell=None): # if line is None: return {k: v.render() for k, v in monkeytype.stubs.build_module_stubs_from_traces( self.traces, self.max_dict_size).items()} on = __enter__ off = __exit__
class NvidiaRacecar(Racecar): i2c_address1 = traitlets.Integer(default_value=0x40) i2c_address2 = traitlets.Integer(default_value=0x60) steering_gain = traitlets.Float(default_value=-0.65) steering_offset = traitlets.Float(default_value=0) steering_channel = traitlets.Integer(default_value=0) throttle_gain = traitlets.Float(default_value=0.8) def __init__(self, *args, **kwargs): super(NvidiaRacecar, self).__init__(*args, **kwargs) self.kit = ServoKit(channels=16, address=self.i2c_address1) self.motor = ServoKit(channels=16, address=self.i2c_address2) self.motor._pca.frequency = 1600 self.steering_motor = self.kit.continuous_servo[self.steering_channel] @traitlets.observe('steering') def _on_steering(self, change): self.steering_motor.throttle = change[ 'new'] * self.steering_gain + self.steering_offset @traitlets.observe('throttle') def _on_throttle(self, change): if change['new'] > 0: self.motor._pca.channels[0].duty_cycle = int( 0xFFFF * (change['new'] * self.throttle_gain)) self.motor._pca.channels[1].duty_cycle = 0xFFFF self.motor._pca.channels[2].duty_cycle = 0 self.motor._pca.channels[3].duty_cycle = 0 self.motor._pca.channels[4].duty_cycle = int( 0xFFFF * (change['new'] * self.throttle_gain)) self.motor._pca.channels[7].duty_cycle = int( 0xFFFF * (change['new'] * self.throttle_gain)) self.motor._pca.channels[6].duty_cycle = 0xFFFF self.motor._pca.channels[5].duty_cycle = 0 else: self.motor._pca.channels[0].duty_cycle = int( -0xFFFF * (change['new'] * self.throttle_gain)) self.motor._pca.channels[1].duty_cycle = 0 self.motor._pca.channels[2].duty_cycle = 0xFFFF self.motor._pca.channels[3].duty_cycle = int( -0xFFFF * (change['new'] * self.throttle_gain)) self.motor._pca.channels[4].duty_cycle = 0 self.motor._pca.channels[7].duty_cycle = int( -0xFFFF * (change['new'] * self.throttle_gain)) self.motor._pca.channels[6].duty_cycle = 0 self.motor._pca.channels[5].duty_cycle = 0xFFFF
class NvidiaRacecar(Racecar): i2c_address = traitlets.Integer(default_value=0x40) steering_gain = traitlets.Float(default_value=-0.65) steering_offset = traitlets.Float(default_value=0) steering_channel = traitlets.Integer(default_value=0) throttle_gain = traitlets.Float(default_value=0.8) # The two channels control the two motors correspondingly. throttle_channel = traitlets.Integer(default_value=1) throttle_channel_1 = traitlets.Integer(default_value=2) def __init__(self, *args, **kwargs): super(NvidiaRacecar, self).__init__(*args, **kwargs) self.kit = ServoKit(channels=16, address=self.i2c_address) self.steering_motor = self.kit.continuous_servo[self.steering_channel] self.throttle_motor = self.kit.continuous_servo[self.throttle_channel] self.throttle_motor_1 = self.kit.continuous_servo[ self.throttle_channel_1] # Set up the direction control pins for the two motors. Here, PIN 16 and PIN 18 are utilized to control two motors. GPIO.setup( 'SPI2_CS1', GPIO.OUT, initial=GPIO.HIGH ) # This sets up the motor which needs to run reversely. PIN16 GPIO.setup('SPI2_CS0', GPIO.OUT, initial=GPIO.LOW) # PIN18 @traitlets.observe('steering') def _on_steering(self, change): self.steering_motor.throttle = change[ 'new'] * self.steering_gain + self.steering_offset @traitlets.observe('throttle') def _on_throttle(self, change): self.throttle_motor.throttle = change['new'] * self.throttle_gain self.throttle_motor_1.throttle = change['new'] * self.throttle_gain # Moving forward: 1; moving backward: 2 @traitlets.observe('direction') def _on_direction(self, change): if change['new'] == 1: GPIO.output('SPI2_CS1', GPIO.HIGH) GPIO.output('SPI2_CS0', GPIO.LOW) if change['new'] == -1: GPIO.output('SPI2_CS1', GPIO.LOW) GPIO.output('SPI2_CS0', GPIO.HIGH) if change['new'] == 0: self.throttle_moter._pwm_out.duty_cycle = 0 self.throttle_moter_1._pwm_out.duty_cycle = 0
class Robot(SingletonConfigurable): left_motor = traitlets.Instance(Motor) right_motor = traitlets.Instance(Motor) # config i2c_bus = traitlets.Integer(default_value=1).tag(config=True) left_motor_channel = traitlets.Integer(default_value=0).tag(config=True) left_motor_alpha = traitlets.Float(default_value=1.0).tag(config=True) right_motor_channel = traitlets.Integer(default_value=1).tag(config=True) right_motor_alpha = traitlets.Float(default_value=1.0).tag(config=True) def __init__(self, *args, **kwargs): super(Robot, self).__init__(*args, **kwargs) self.motor_driver = Device(0x40, self.i2c_bus) self.left_motor = Motor(self.motor_driver, channel=self.left_motor_channel, alpha=self.left_motor_alpha) self.right_motor = Motor(self.motor_driver, channel=self.right_motor_channel, alpha=self.right_motor_alpha) self.motor_driver.set_pwm_frequency(50) def set_motors(self, left_speed, right_speed): self.left_motor.value = left_speed self.right_motor.value = right_speed def forward(self, speed=1.0, duration=None): self.left_motor.value = -speed self.right_motor.value = speed def backward(self, speed=1.0): self.left_motor.value = speed self.right_motor.value = -speed def left(self, speed=1.0): self.left_motor.value = -speed self.right_motor.value = -speed def right(self, speed=1.0): self.left_motor.value = speed self.right_motor.value = speed def stop(self): self.left_motor.value = 0 self.right_motor.value = 0
class Robot(SingletonConfigurable): left_motor = traitlets.Instance(Motor) right_motor = traitlets.Instance(Motor) # config left_motor_channel = traitlets.Integer( default_value=MotorDriver.MOTOR_A).tag(config=True) left_motor_alpha = traitlets.Float(default_value=1.0).tag(config=True) right_motor_channel = traitlets.Integer( default_value=MotorDriver.MOTOR_B).tag(config=True) right_motor_alpha = traitlets.Float(default_value=1.0).tag(config=True) def __init__(self, *args, i2c_bus=1, driver_board='dfrobot', **kwargs): super(Robot, self).__init__(*args, **kwargs) self.motor_driver = MotorDriver(busnum=i2c_bus, board=driver_board) self.left_motor = Motor(self.motor_driver, channel=self.left_motor_channel, alpha=self.left_motor_alpha) self.right_motor = Motor(self.motor_driver, channel=self.right_motor_channel, alpha=self.right_motor_alpha) def set_motors(self, left_speed, right_speed): self.left_motor.value = left_speed self.right_motor.value = right_speed def forward(self, speed=1.0, duration=None): self.left_motor.value = speed self.right_motor.value = speed def backward(self, speed=1.0): self.left_motor.value = -speed self.right_motor.value = -speed def left(self, speed=1.0): self.left_motor.value = -speed self.right_motor.value = speed def right(self, speed=1.0): self.left_motor.value = speed self.right_motor.value = -speed def stop(self): self.left_motor.value = 0 self.right_motor.value = 0
class BlackExporter(nbconvert.exporters.python.PythonExporter): width = traitlets.Integer(default_value=100) def from_notebook_node(self, nb, resources=None, **kw): nb, resources = super().from_notebook_node(nb, resources=resources, **kw) return black.format_str(nb, self.width), resources
class Robot(SingletonConfigurable): left_motor = traitlets.Instance(Motor) right_motor = traitlets.Instance(Motor) # config left_motor_channel = traitlets.Integer(default_value=1).tag(config=True) left_motor_alpha = traitlets.Float(default_value=1.0).tag(config=True) right_motor_channel = traitlets.Integer(default_value=2).tag(config=True) right_motor_alpha = traitlets.Float(default_value=1.0).tag(config=True) def __init__(self, *args, **kwargs): super(Robot, self).__init__(*args, **kwargs) self.motor_driver = MegaRover_MotorDriver() self.right_motor = Motor(self.motor_driver, channel=self.right_motor_channel, alpha=self.right_motor_alpha) self.left_motor = Motor(self.motor_driver, channel=self.left_motor_channel, alpha=self.left_motor_alpha) def set_motors(self, left_speed, right_speed): self.left_motor._write_value(left_speed) self.right_motor._write_value(right_speed) def forward(self, speed=1.0, duration=None): self.left_motor._write_value(speed) self.right_motor._write_value(speed) def backward(self, speed=1.0): self.left_motor._write_value(-speed) self.right_motor._write_value(-speed) def left(self, speed=1.0): self.left_motor._write_value(-speed) self.right_motor._write_value(speed) def right(self, speed=1.0): self.left_motor._write_value(speed) self.right_motor._write_value(-speed) def stop(self): self.left_motor._write_value(0) self.right_motor._write_value(0)
class PassGen(traitlets.HasTraits): """ Class to represent state of password generator and handle generation of password. """ password_length = traitlets.Integer() include_numbers = traitlets.Bool() special_character_groups = traitlets.Enum(SPECIAL_GROUPS, default_value=SPECIAL_GROUPS[0]) password = traitlets.Unicode("password") def __init__(self): super(PassGen, self).__init__(description='Password model') pass # The observe decorator is used to indicate that the function being # decorated should be called if any of the traits listed as arguments # change. The decorated function must have an argument named change; # in this example the change variable isn't used because we want to update # the generated password no matter what the change was. @traitlets.observe('password_length', 'include_numbers', 'special_character_groups') def generate_password(self, change): """ Generate a password of the desired length including the user's chosen set of special characters and, if desired, including some numerals. """ # Generate an initial password composed only of letters. new_pass = [] for _ in range(self.password_length): new_pass.append(random.choice(string.ascii_letters)) # Generate a list of indices for choosing which characters in the # initial password to replace, then shuffle it. We'll pop # elements off the list as we need them. order_for_replacements = list(range(self.password_length)) random.shuffle(order_for_replacements) # Replace some of the letters with special characters n_special = random.randint(1, 3) for _ in range(n_special): loc = order_for_replacements.pop(0) new_pass[loc] = random.choice(self.special_character_groups) if self.include_numbers: # Number of digits to include. n_digits = random.randint(1, 3) for _ in range(n_digits): loc = order_for_replacements.pop(0) new_pass[loc] = random.choice(string.digits) self.password = ''.join(new_pass)
class PlaySlider(widgets.HBox): """ A combined Play / IntSlider widget. """ max = traitlets.Integer(100) min = traitlets.Integer(0) value = traitlets.Integer(0) step = traitlets.Integer(1) interval = traitlets.Integer(500) def __init__(self, *args, min=0, max=100, value=100, step=1, interval=500, label="Value", continuous_update=True, **kwargs): # initialise the hbox widget super().__init__([ widgets.Label(label + ": "), widgets.Play(min=min, max=max, value=value, interval=interval), widgets.IntSlider( min=min, max=max, value=value, step=step, continuous_update=continuous_update, ), ]) for trait in ("min", "max", "value", "step"): # first the two control elements: widgets.link((self.children[1], trait), (self.children[2], trait)) # then link the latter with self: widgets.link((self.children[2], trait), (self, trait)) widgets.link((self.children[1], "interval"), (self, "interval"))
class RealCar(Car): i2c_address = traitlets.Integer(default_value=0x40) steering_gain = traitlets.Float(default_value=-0.65) steering_offset = traitlets.Float(default_value=0.08) steering_channel = traitlets.Integer(default_value=0) throttle_gain = traitlets.Float(default_value=0.25) throttle_channel = traitlets.Integer(default_value=1) max_real_throttle_fwd = traitlets.Float(default_value=0.15) max_real_throttle_bwd = traitlets.Float(default_value=-0.25) status = 0 target = 0 timer = None def __init__(self, *args, **kwargs): super(RealCar, self).__init__(*args, **kwargs) self.kit = ServoKit(channels=16, address=self.i2c_address) self.kit._pca.frequency = 60 self.steering_motor = self.kit.continuous_servo[self.steering_channel] self.throttle_motor = self.kit.continuous_servo[self.throttle_channel] self.steering_motor.throttle = 0 self.throttle_motor.throttle = 0 @traitlets.observe('steering') def _on_steering(self, change): self.steering_motor.throttle = change[ 'new'] * self.steering_gain + self.steering_offset print('realcar steering:', self.steering_motor.throttle) @traitlets.observe('throttle') def _on_throttle(self, change): value = change['new'] * self.throttle_gain self.throttle_motor.throttle = self._clip_real_throttle(value) print('realcar throttle:', self.throttle_motor.throttle) def _clip_real_throttle(self, value): if value > self.max_real_throttle_fwd: return self.max_real_throttle_fwd elif value < self.max_real_throttle_bwd: return self.max_real_throttle_bwd else: return value
class USBCamera(Camera): capture_fps = traitlets.Integer(default_value=30) capture_width = traitlets.Integer(default_value=640) capture_height = traitlets.Integer(default_value=480) capture_device = traitlets.Integer(default_value=0) def __init__(self, *args, **kwargs): super(USBCamera, self).__init__(*args, **kwargs) try: self.cap = cv2.VideoCapture(self._gst_str(), cv2.CAP_GSTREAMER) re, image = self.cap.read() if not re: raise RuntimeError('Could not read image from camera.') except: raise RuntimeError( 'Could not initialize camera. Please see error trace.') atexit.register(self.cap.release) def _gst_str(self): return 'v4l2src device=/dev/video{} ! video/x-raw, width=(int){}, height=(int){}, framerate=(fraction){}/1 ! videoconvert ! video/x-raw, format=(string)BGR ! appsink'.format( self.capture_device, self.capture_width, self.capture_height, self.capture_fps) def _read(self): re, image = self.cap.read() if re: image_resized = cv2.resize(image, (int(self.width), int(self.height))) return image_resized else: raise RuntimeError('Could not read image from camera') def close(self): self.cap.release()
class _InfoSnackbar(ipyvuetify.VuetifyTemplate): color = traitlets.Unicode("primary").tag(sync=True, allow_null=True) message = traitlets.Unicode("").tag(sync=True, allow_null=False) timeout = traitlets.Integer(5000).tag(sync=True, allow_null=True) active = traitlets.Bool(True).tag(sync=True, allow_null=True) multi_line = traitlets.Bool(True).tag(sync=True, allow_null=True) template = traitlets.Unicode( """ <template> <v-snackbar v-model="active" centered=true :color="color" elevation=0 :multi-line="multi_line" :timeout="timeout" > {{message}} <v-btn color="white" text @click="active = false" > Close </v-btn> </v-snackbar> </template> """ ).tag(sync=True) def __init__( self, snackbar=False, message=None, multi_line=True, color="primary", timeout=6000, active=True, *args, **kwargs ): super().__init__(*args, **kwargs) self.color = color self.timeout = timeout self.active = active self.message = message self.multi_line = multi_line
class AIRacecar(Racecar): i2c_address = traitlets.Integer(default_value=0x40) steering_gain = traitlets.Float(default_value=-0.65) steering_offset = traitlets.Float(default_value=0) steering_channel = traitlets.Integer(default_value=0) throttle_gain = traitlets.Float(default_value=0.8) throttle_channel = traitlets.Integer(default_value=1) def __init__(self, *args, **kwargs): super(AIRacecar, self).__init__(*args, **kwargs) self.kit = ServoKit(channels=16, address=self.i2c_address) self.steering_motor = self.kit.continuous_servo[self.steering_channel] self.throttle_motor = self.kit.continuous_servo[self.throttle_channel] @traitlets.observe('steering') def _on_steering(self, change): self.steering_motor.throttle = change[ 'new'] * self.steering_gain + self.steering_offset @traitlets.observe('throttle') def _on_throttle(self, change): self.throttle_motor.throttle = change['new'] * self.throttle_gain
class RTSPCamera(Camera): capture_fps = traitlets.Integer(default_value=15) capture_width = traitlets.Integer(default_value=640) capture_height = traitlets.Integer(default_value=480) capture_device = traitlets.Unicode( default_value='rtsp://Your_IP_Cam_Address') def __init__(self, *args, **kwargs): super(RTSPCamera, self).__init__(*args, **kwargs) try: self.cap = cv2.VideoCapture(self.capture_device, cv2.CAP_FFMPEG) re, image = self.cap.read() if not re: raise RuntimeError( 'Could not read image from camera, phase 1.') except: raise RuntimeError( 'Could not initialize camera. Please see error trace, phase 2.' ) atexit.register(self.cap.release) def _gst_str(self): return (self.capture_device, self.capture_width, self.capture_height) def _read(self): re, image = self.cap.read() if re: image_resized = cv2.resize(image, (int(self.width), int(self.height))) return image_resized else: raise RuntimeError('Could not read image from camera, phase 3')