Esempio n. 1
0
 def _start(self):
     try:
         logger.info("Starting HTTP server on port {}".format(self.http_port))
         self.httpd = TCPServer(("", self.http_port), CustomRequestHandler)
         self.httpd.serve_forever()
     except Exception as e:
         logger.exception(e)
Esempio n. 2
0
        def _start(self):
            logger.info("Using Joystick : {}".format(self.joystick.get_name()))

            while self.keep_running:
                mainthread_dispatch(
                    lambda: self._process_events(pygame.event.get()))
                sleep(0.01)
Esempio n. 3
0
def find_devices_and_import():

    global setup_complete, _motor_provider_class, _servo_provider_class
    if setup_complete:
        return
    devices = i2c_scan()            # TODO: add config option to specify i2c bus
    logger.info("i2c devices detected: {}".format(devices))

    PICONZERO_I2C_DEVICE_ID = 0x22
    PIMORONI_PANTILT_HAT_I2C_DEVICE_ID = 0x15
    PIMORONI_EXPLORER_PHAT_DEVICE_ID = 0x48        # THis is actually the on-board ADS


    from .motor import Default as Motor
    from .servo import Default as Servo

    if PICONZERO_I2C_DEVICE_ID in devices:
        from .motor.piconzero import PiconzeroMotor as Motor
        from .servo.piconzero import PiconzeroServo as Servo
    else:
        if PIMORONI_PANTILT_HAT_I2C_DEVICE_ID in devices:
            from .servo.pimoroniservo import PimoroniPanTiltServo as Servo

        if PIMORONI_EXPLORER_PHAT_DEVICE_ID in devices:
            from .motor.pimoroni import PimoroniExplorerHatMotor as Motor

    _motor_provider_class = Motor
    _servo_provider_class = Servo
    setup_complete = True
Esempio n. 4
0
 def stop(self):
     logger.info("Stopping WebSocket server")
     try:
         if self.ws:
             self.ws.stop()
             self.ws = None
     except:
         logger.exception("Failed to stop WebSocket")
Esempio n. 5
0
 def set_angle(self, angle):
     msg = "Set Angle {}".format(angle)
     logger.debug(msg)
     if angle == self.last_angle or angle is None:
         return
     self.last_angle = angle
     logger.info(msg)
     pz.setOutput(self.servo_id, angle)
Esempio n. 6
0
 def set_angle(self, angle):
     msg = "DefaultServoProvider({}).set_angle({})".format(
         self._servo_id, angle)
     logger.debug(msg)
     if angle == self.last_angle:
         return
     logger.info(msg)
     self.last_angle = angle
Esempio n. 7
0
 def start(self):
     resource_path = os.path.join(os.path.split(__file__)[0], "resources")
     www_dir = resource_path + "/www"
     os.chdir(www_dir)
     logger.info("WWW dir: {}".format(www_dir))
     self.http_thread = threading.Thread(target=self._start, name = 'HTTPServer')
     self.http_thread.daemon = False # allow clean shutdown
     self.http_thread.start()
Esempio n. 8
0
    def __init__(self, servo_id):
        if servo_id not in range(0, 6):
            raise ValueError("Servo id must be between 0 and 5")

        self.last_angle = None
        self.servo_id = servo_id
        pz.init()
        pz.setOutputConfig(self.servo_id, 2)  # Set output mode to Servo
        logger.info("Servo {} created".format(self.servo_id))
Esempio n. 9
0
 def set_speed(self, speed):
     msg = "set_speed({}, {})".format(self.motor_id, speed)
     logger.debug(msg)
     if speed == self._last_speed or speed is None:
         return
     self._last_speed = speed
     logger.info(msg)
     # TODO: scale -100..100 to -128..127
     speed = constrain(speed, -128, 127)
     pz.setMotor(self.motor_id, speed)
Esempio n. 10
0
    def _start(self):
        try:
            logger.info("Starting WebSocket server on port {}".format(self.ws_port))
            self.ws = SimpleWebSocketServer('', self.ws_port, self.ws_class)
            try:
                self.ws.serveforever()
            except Exception:
                logger.exception("Failed to close WebSocket")

        except Exception as e:
            logger.exception("Failed to create WebSocket")
Esempio n. 11
0
 def set_angle(self, angle):
     msg = "Set Angle {}".format(angle)
     logger.debug(msg)
     if angle == self.last_angle or angle is None:
         return
     logger.info(msg)
     self.last_angle = angle
     angle -= 90
     try:
         self.set_servo_angle(angle)
     except IOError as e:
         logger.exception("cant set angle")
Esempio n. 12
0
        def __init__(self, joystick_id=0):
            self.controller_state = {}
            self.keep_running = True
            self.mapping = {}
            self._listener = None

            devices = list_devices()
            if not len(devices) > 0:
                logger.info("No input devices found")
                return
            logger.info("Found input devices: {}".format(devices))

            device_path = devices[
                0]  # Just joysticks on the first controller, for now
            logger.info("Using device: {}".format(device_path))
            self.input_device = InputDevice(device_path)
            self.thread = threading.Thread(target=self._start,
                                           name="InputController" +
                                           str(joystick_id))
            self.thread.daemon = True
            self.thread.start()

            vpid = "{}:{}".format(self.input_device.info.vendor,
                                  self.input_device.info.product)
            logger.info("Device USB VPID: {}".format(vpid))
            if vpid in VENDOR_PRODUCT_MAPPINGS:
                self.mapping = VENDOR_PRODUCT_MAPPINGS[vpid]
            else:
                logger.warning(
                    "Input device USB VPID not found for '{}', using default".
                    format(vpid))
                self.mapping = VENDOR_PRODUCT_MAPPINGS["DEFAULT"]
Esempio n. 13
0
def i2c_scan(bus_num=1):
    global HAVE_SMBUS
    if not HAVE_SMBUS:
        return []
    bus = smbus.SMBus(bus_num)  # 1 indicates /dev/i2c-1
    devices = []
    for device in range(128):
        try:
            bus.read_byte(device)
            logger.info("Found i2c device at addr: {}".format(hex(device)))
            devices.append(device)
        except Exception:  # exception if read_byte fails
            pass

    return devices
Esempio n. 14
0
def main():
    logger.info('Initializing camera')
    with picamera.PiCamera() as camera:
        config = get_config()
        w = config.getint('camera', 'width', fallback=640)
        h = config.getint('camera', 'height', fallback=480)
        camera.resolution = (w, h)
        camera.framerate = config.getint('camera', 'framerate', fallback=24)
        camera.rotation = config.getint('camera', 'rotation', fallback=0)
        camera.hflip = config.getboolean('camera', 'hflip', fallback=False)
        camera.vflip = config.getboolean('camera', 'vflip', fallback=False)
        camera.led = config.getboolean('camera', 'led', fallback=False)
        sleep(1)  # camera warm-up tim
        logger.info('Initializing websockets server on port %d' % WS_PORT)
        websocket_server = make_server(
            '',
            WS_PORT,
            server_class=WSGIServer,
            handler_class=HTTP11WebSocketWSGIRequestHandler,
            app=WebSocketWSGIApplication(handler_cls=StreamingWebSocket))
        websocket_server.initialize_websockets_manager()
        websocket_thread = Thread(target=websocket_server.serve_forever)
        #logger.info('Initializing HTTP server on port %d' % HTTP_PORT)
        #http_server = StreamingHttpServer()
        #http_thread = Thread(target=http_server.serve_forever)
        logger.debug('Initializing broadcast thread')
        output = BroadcastOutput(camera)
        broadcast_thread = BroadcastThread(output.converter, websocket_server)
        logger.info('Starting recording')
        camera.start_recording(output, 'yuv')
        try:
            logger.debug('Starting websockets thread')
            websocket_thread.start()
            #logger.info('Starting HTTP server thread')
            #http_thread.start()
            logger.debug('Starting broadcast thread')
            broadcast_thread.start()
            while True:
                camera.wait_recording(1)
        except KeyboardInterrupt:
            pass
        finally:
            logger.info('Stopping recording')
            camera.stop_recording()
            logger.debug('Waiting for broadcast thread to finish')
            broadcast_thread.join()
            logger.debug('Shutting down HTTP server')
            #http_server.shutdown()
            logger.debug('Shutting down websockets server')
            websocket_server.shutdown()
            logger.debug('Waiting for HTTP server thread to finish')
            #http_thread.join()
            logger.debug('Waiting for websockets thread to finish')
            websocket_thread.join()
Esempio n. 15
0
HAVE_BLUEDOT = False

# ---------------------------------------------------------------------------------------------------------

# TODO: other joypads
# TODO: test the PyGame impl. on Windows
# TODO: shared common behaviour refactor

# ---------------------------------------------------------------------------------------------------------
# Look for Event support first (Linux) then PyGame (Linux, Windows, Mac, other)
try:
    from evdev import InputDevice, categorize, AbsEvent, KeyEvent, list_devices
    from evdev.ecodes import KEY, SYN, REL, ABS
    HAVE_EVENT = True
except ImportError:
    logger.info("Optional EventDev library not found")
    HAVE_EVENT = False

try:
    import pygame
    from pygame.locals import *
    HAVE_PYGAME = True
except ImportError:
    logger.info("Optional PyGame library not found")
    HAVE_PYGAME = False

try:
    from bluedot import BlueDot
    HAVE_BLUEDOT = True
except ImportError:
    logger.info("Optional BlueDot library not found")
Esempio n. 16
0
#!/usr/bin/python3

from picraftzero.log import logger
# TODO: check config for 'service' entry for user script and tun that instead
from picraftzero.config import get_config

config = get_config()
script_file = config.get('service', 'script', fallback=None)

if script_file:
    logger.info("Running user script: {}".format(script_file))
    with open(script_file) as f:
        code = compile(f.read(), script_file, 'exec')
        exec(code)
        # user script is expected to exit with an error code or 0, so shouldnt reach here
        exit(1)

# see the `pantilt.py` example for more info.

from picraftzero import Wheelbase, PanTilt, Joystick, steering_mixer, scaled_pair, start, filter_messages, MessageReceiver, join_values
joystick_right = Joystick(0)
joystick_left = Joystick(1)
messages = MessageReceiver(port=8001)

wheelbase = Wheelbase(left=1, right=0)
pan_tilt = PanTilt(pan=0, tilt=1)

wheelbase.source = steering_mixer(joystick_right.values)
pan_tilt.source = join_values(
    filter_messages(messages.values, type='PANTILT', id=0),
    scaled_pair(joystick_left.values, 180, 0, -100, 100))
Esempio n. 17
0
 def stop(self):
     logger.info("Stopping HTTP server")
     #self.httpd.server_close()
     if self.httpd:
         self.httpd.shutdown()
Esempio n. 18
0
 def _start(self):
     try:
         logger.info("Starting PiStreaming CameraServer server")
         pistreaming_server.main()
     except Exception as e:
         logger.exception(e)
Esempio n. 19
0
 def start(self):
     logger.info("Using mock CameraServer server")
Esempio n. 20
0
 def stop(self):
     logger.info("Stopping Camera server")