Exemplo n.º 1
0
def publisher(**kwargs):
    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(10)
    pub = geckopy.Publisher()

    if platform.system() == 'Linux':
        args = {
            'src': 0,
            'usePiCamera': True,
            'resolution': (
                640,
                480,
            ),
            'framerate': 10
        }
    else:
        args = {'src': 0, 'usePiCamera': False}

    cam = VideoStream(**args).start()
    time.sleep(1)

    # camera check
    img = cam.read()
    print(img.shape)
    cv2.imwrite('test.png', img)

    while not geckopy.is_shutdown():
        img = cam.read()
        # img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        msg = Image(img.shape, img.tobytes())
        pub.pub('camera', msg)
        rate.sleep()

    cam.stop()
Exemplo n.º 2
0
def imu_publisher(**kwargs):
    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(10)

    p = geckopy.Publisher()

    test = kwargs.get('test', False)

    imu = IMU_hw()

    while not geckopy.is_shutdown():
        if test:  # fake readings
            msg = IMU(
                Vector(1, 2, 3),
                Vector(1, 2, 3),
                Vector(1, 2, 3),
            )

        else:
            a, m, g = imu.get()
            geckopy.log('{:.1f} {:.1f} {:.1f}'.format(*a))
            msg = IMU(Vector(*a), Vector(*m), Vector(*g))

        p.pub('imu', msg)

        msg = Vector(0, 0, 1)
        p.pub('unit_accel', msg)

        # sleep
        rate.sleep()
Exemplo n.º 3
0
def imu_publisher(**kwargs):
    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(10)
    p = geckopy.Publisher()

    if platform.system() == 'Linux':
        isLinux = True
        imu = IMU_hw()
    else:
        isLinux = False
        imu = None

    while not geckopy.is_shutdown():
        if isLinux:
            a, m, g = imu.get()
            # geckopy.log('{:.1f} {:.1f} {:.1f}'.format(*a))
            msg = IMU(Vector(*a), Vector(*m), Vector(*g))
        else:  # fake readings
            msg = IMU(
                Vector(1, 2, 3),
                Vector(1, 2, 3),
                Vector(1, 2, 3),
            )

        p.pub('imu', msg)

        # msg = Vector(0,0,1)
        # p.pub('unit_accel', msg)

        # sleep
        rate.sleep()
Exemplo n.º 4
0
def movement(**kwargs):
    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(1)

    path = [
        (1.0,0,0,),
        (1.0,0,0,),
        (1.0,0,0,),
        (1.0,0,0,),
        (1.0,0,0,),
        (1.0,0,0,),
    ]

    p = geckopy.Publisher()
    i = 0
    cmd = itertools.cycle(path)
    while not geckopy.is_shutdown():
        msg = next(cmd)
        p.pub('cmd', msg)  # topic msg
        geckopy.log(msg)

        # geckopy.log('[{}] published: {}'.format(i, msg))
        # i = (i + 1) % len(path)
        rate.sleep()
    print('pub bye ...')
Exemplo n.º 5
0
def publisher(**kwargs):
    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(10)  # 10 Hz

    # p = geckopy.Publisher(['camera'])

    p = geckopy.pubBinderTCP(kwargs.get('key'), kwargs.get('topic'))
    if p is None:
        raise Exception("publisher is None")

    # determine if we should use picamera or standard usb camera
    # if platform.system() == 'Linux':
    #     picam = True
    # else:
    #     picam = False
    #
    # camera = VideoStream(usePiCamera=picam)
    # camera.start()

    while not geckopy.is_shutdown():
        img = camera.read()
        # img = cv2.resize(img, (320, 240))
        # img = cv2.resize(img, (640, 480))
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        msg = image2msg(img)
        p.publish('camera', msg)
        rate.sleep()

    print('pub bye ...')
Exemplo n.º 6
0
def pcv(**kwargs):
    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(10)

    p = geckopy.Publisher()

    camera = WebcamVideoStream(src=0).start()

    while not geckopy.is_shutdown():
        img = camera.read()

        if img is not None:
            # geckopy.log(img.shape)
            # img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            img = cv2.resize(img, (640,480))
            msg = find_ball(img)
            # msg = Image(img.shape, img.tobytes(), img.dtype)
            if msg:
                # p.pub('images_color', msg)  # topic msg
                p.pub('target', msg)
                geckopy.log(msg)
            # p.pub(topic, {'a': 5})
            # geckopy.log(img.shape)
        else:
            geckopy.log("*** couldn't read image ***")

        # sleep
        rate.sleep()

    camera.stop()
    print('cv bye ...')
Exemplo n.º 7
0
def lidar_publisher(**kwargs):
    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(1)

    geckopy.log(kwargs)

    p = geckopy.Publisher()

    test = kwargs.get('test', False)
    # MAP_SIZE_PIXELS         = 500
    # MAP_SIZE_METERS         = 10

    if platform.system() == 'Linux':
        port = '/dev/serial/by-id/usb-Silicon_Labs_CP2102_USB_to_UART_Bridge_Controller_0001-if00-port0'
    else:
        port = "/dev/tty.SLAB_USBtoUART"

    # Connect to Lidar unit
    lidar = LDS01()
    lidar.open(port)
    lidar.run(True)

    # Create an RMHC SLAM object with a laser model and optional robot model
    # slam = RMHC_SLAM(LDS01_Model(), MAP_SIZE_PIXELS, MAP_SIZE_METERS)

    # Set up a SLAM display
    # display = SlamShow(MAP_SIZE_PIXELS, MAP_SIZE_METERS*1000/MAP_SIZE_PIXELS, 'SLAM')

    # Initialize empty map
    # mapbytes = bytearray(MAP_SIZE_PIXELS * MAP_SIZE_PIXELS)

    while not geckopy.is_shutdown():
        # Update SLAM with current Lidar scan
        pts = lidar.read()
        # need to reverse the order for it to plot correctly
        pts = list(reversed(pts))
        msg = Lidar(pts)
        p.pub('scan', msg)

        # slam.update(pts)

        # Get current robot position
        # x, y, theta = slam.getpos()

        # Get current map bytes as grayscale
        # slam.getmap(mapbytes)

        # display.displayMap(mapbytes)
        # display.setPose(x, y, theta)
        # display.refresh()

        # p.pub('avoid', msg)
        # geckopy.log(msg)

        # sleep
        rate.sleep()

    # all done
    lidar.close()
Exemplo n.º 8
0
def publisher(**kwargs):
    geckopy.init_node()
    rate = geckopy.Rate(10)

    tcp = kwargs["useTcp"]
    key = kwargs["key"]

    if tcp:
        p = pubBinderTCP(key, 'twist_kb')
    else:
        p = pubBinderUDS(key, 'twist_kb', fname=kwargs["udsfile"])

    if p is None:
        return

    ang = [0, 0, 0]
    lin = [0, 0, 0]

    while not geckopy.is_shutdown():

        # have to do some fancy stuff to avoid sending \n all the time
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            key = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

        if key not in ['a', 'd', 'w', 'x', 's', 'q']:
            continue

        print('>>>', key)

        if key == 'a':
            ang[2] += 0.1
            ang[2] = limit_max(ang[2])
        elif key == 'd':
            ang[2] -= 0.1
            ang[2] = limit_min(ang[2])
        elif key == 'w':
            lin[0] += 0.1
            lin[0] = limit_max(lin[0])
        elif key == 'x':
            lin[0] -= 0.1
            lin[0] = limit_min(lin[0])
        elif key == 's':  # stop - all 0's
            ang = [0, 0, 0]
            lin = [0, 0, 0]
        elif key == 'q':
            break

        twist = twist_t(vec_t(*lin), vec_t(*ang))
        p.publish(twist)  # topic msg
        rate.sleep()
Exemplo n.º 9
0
def main():

    if True:
        sp = GeckoSimpleProcess()
        sp.start(func=core, name='geckocore', kwargs={})

    print("<<< Starting Roomba >>>")
    port = "/dev/serial/by-id/usb-FTDI_FT231X_USB_UART_DA01NX3Z-if00-port0"
    bot = Create2(port)
    bot.start()
    bot.full()

    geckopy.init_node()
    rate = geckopy.Rate(10)  # loop rate

    # s = geckopy.subBinderUDS(key, 'cmd', "/tmp/cmd")
    s = geckopy.subBinderTCP(key, 'cmd')
    if s is None:
        raise Exception("subscriber is None")

    # p = geckopy.pubBinderUDS(key,'create2',"/tmp/create")
    p = geckopy.pubBinderTCP(key, 'create2')
    if p is None:
        raise Exception("publisher is None")

    print("<<< Starting Loop >>>")
    try:
        bot.drive_direct(200, 200)
        while not geckopy.is_shutdown():
            sensors = bot.get_sensors()  # returns all data
            batt = 100 * sensors.battery_charge / sensors.battery_capacity
            # print(">> batter: {:.1f}".format(batt))
            bot.digit_led_ascii("{:4}".format(int(batt)))
            # bot.digit_led_ascii("80")
            # print(">> ir:", sensors.light_bumper)
            # print(">> ir:", end=" ")
            # for i in range(6):
            #     print("{:.1f}".format(sensors[35 + i]), end=" ")
            # print(" ")
            # msg = sensors
            # p.publish(msg)

            msg = s.recv_nb()
            if msg:
                print(msg)

            rate.sleep()
    except KeyboardInterrupt:
        print("bye ...")

    bot.drive_stop()
    # time.sleep(1)
    # bot.close()
    print("<<< Exiting >>>")
Exemplo n.º 10
0
def publisher(**kwargs):
    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(1)

    p = geckopy.Publisher(['data'])

    while not geckopy.is_shutdown():
        msg = {'a': 1}
        p.pub('data', msg)
        rate.sleep()

    print('pub bye ...')
Exemplo n.º 11
0
def sub(**kwargs):
    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(2)

    s = geckopy.subConnectTCP("local", "bob2")
    if (s == None):
        print("ERROR setting up subscriber")
        return
    cnt = 0
    while not geckopy.is_shutdown():
        data = s.recv_nb()
        print("sub:", data)
        print('-' * 40)
        rate.sleep()
Exemplo n.º 12
0
def publisher(**kwargs):
    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(2)

    topic = kwargs.get('topic')
    p = geckopy.pubBinderTCP(kwargs.get('key'), topic)
    start = time.time()
    cnt = 0
    while not geckopy.is_shutdown():
        msg = cnt
        p.publish(msg)  # topic msg

        geckopy.logdebug('{}[{}] published msg'.format(topic, cnt))
        cnt += 1
        rate.sleep()
    print('pub bye ...')
Exemplo n.º 13
0
def imu_pub():
    geckopy.init_node()
    rate = geckopy.Rate(2)

    p = geckopy.pubBinderTCP(KEY, "imu")

    if p is None:
        raise Exception("publisher is None")

    imu = NXP_IMU()

    while not geckopy.is_shutdown():
        msg = imu.get()
        p.publish(msg)  # topic msg
        rate.sleep()
    print('imu pub bye ...')
Exemplo n.º 14
0
def publisher(**kwargs):
    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(2)

    topic = kwargs.get('topic')
    p = geckopy.Publisher(topic)
    start = time.time()
    cnt = 0
    while not geckopy.is_shutdown():
        msg = {'time': time.time() - start}
        p.pub(topic, msg)  # topic msg

        geckopy.logdebug('[{}] published msg'.format(cnt))
        cnt += 1
        rate.sleep()
    print('pub bye ...')
Exemplo n.º 15
0
def pub(**kwargs):
    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(2)

    p = geckopy.pubBinderTCP("local", "bob2")
    if (p == None):
        print("ERROR setting up publisher")
        return
    cnt = 0
    v = vec_t(1, 2, 3)
    m = imu_st(v, v, v)
    while not geckopy.is_shutdown():
        # m = imu_st(v,v,v)
        p.publish(m)
        print("sent")
        rate.sleep()
        cnt += 1
Exemplo n.º 16
0
def camera_pub():
    geckopy.init_node()
    rate = geckopy.Rate(2)

    p = geckopy.pubBinderTCP(KEY, "camera")

    if p is None:
        raise Exception("publisher is None")

    cam = PiCamera()
    while not geckopy.is_shutdown():
        # img = cam.read()
        img = True
        if img:
            msg = "hi"
            p.publish(msg)
        rate.sleep()
    print('camera pub bye ...')
Exemplo n.º 17
0
def subscriber(**kwargs):
    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(2)
    logger = geckopy.getLogger(__name__)

    s = geckopy.subConnectTCP(kwargs.get('key'), kwargs.get('topic'))
    if s is None:
        logger.error("subscriber is None")
        return

    while not geckopy.is_shutdown():
        ss = s.recv_nb()
        if ss:
            msg = protobufUnpack(ss, Vector)
            logger.info("sub: {}".format(msg))
        chew_up_cpu(.1)
        rate.sleep()

    print('sub bye ...')
Exemplo n.º 18
0
def publisher(**kwargs):
    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(2)

    p = geckopy.pubBinderTCP(kwargs.get('key'), kwargs.get('topic'))
    if p is None:
        print("** publisher is None")
        return

    start = time.time()
    cnt = 0
    while not geckopy.is_shutdown():
        msg = {'time': time.time() - start}
        p.publish(msg)  # topic msg

        geckopy.logdebug('[{}] published msg'.format(cnt))
        cnt += 1
        rate.sleep()
    print('pub bye ...')
Exemplo n.º 19
0
def publish(**kwargs):
    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(1)

    key = kwargs.get('key')
    topic = kwargs.get('topic')

    p = geckopy.pubBinderTCP(key, topic)
    datumn = time.time()
    while not geckopy.is_shutdown():
        msg = {
            'time': time.time() - datumn,
            'double': 3.14,
            'int': 5,
            'array': [1, 2, 3, 4, 5]
        }
        p.publish(msg)
        rate.sleep()

    print('pub bye ...')
Exemplo n.º 20
0
def subscribe2(**kwargs):
    geckopy.init_node(**kwargs)

    key = kwargs.get('key')
    topic = kwargs.get('topic')
    print(">>", kwargs)
    print(">> Sub: {} {}".format(key, topic))
    s = geckopy.subConnectTCP(key, topic)

    while not geckopy.is_shutdown():
        m = s.recv_nb()
        # if 'img' in m:
        #     im = m['img']
        #     im = np.frombuffer(im, dtype=m['dtype'])
        #     im = im.reshape(m['shape'])
        #     geckopy.loginfo('image: {}x{}'.format(*im.shape[:2]))
        # else:
        if m:
            geckopy.logwarn('msg: {}'.format(m))
            chew_up_cpu(.2)
Exemplo n.º 21
0
def subscriber(**kwargs):
    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(2)

    topic = kwargs.get('topic')
    # c = Callback(topic)
    s = geckopy.subConnectTCP(kwargs.get('key'), kwargs.get('topic'))
    if s is None:
        print("subscriber is None")
        # global threads_alive
        # threads_alive -= 1
        return

    while not geckopy.is_shutdown():
        msg = s.recv_nb()
        if msg:
            geckopy.loginfo("{}: {}".format(topic, msg))
        chew_up_cpu(.1)
        rate.sleep()

    print('sub bye ...')
Exemplo n.º 22
0
def publisher(**kwargs):
    geckopy.init_node(**kwargs)

    topic = kwargs.get('topic')
    msg = kwargs.get('msg')
    hertz = kwargs.get('rate', 10)

    p = geckopy.Publisher([topic])

    rate = geckopy.Rate(hertz)

    cnt = 0
    start = time.time()
    while not geckopy.is_shutdown():
        p.pub(topic, msg)  # topic msg
        if cnt % hertz == 0:
            print(">> {}[{:.1f}]: published {} msgs".format(
                topic,
                time.time() - start, hertz))
        cnt += 1
        rate.sleep()
Exemplo n.º 23
0
def matrix_sub():
    geckopy.init_node()
    rate = geckopy.Rate(10)

    # s = geckopy.subConnectTCP(
    #     KEY,
    #     "test"
    # )
    #
    # if s is None:
    #     raise Exception("subscriber is None")

    m = MatrixArray([0x70, 0x71, 0x72, 0x73], brightness=0)

    while not geckopy.is_shutdown():
        # msg = s.recv_nb()
        # if msg:
        #     geckopy.loginfo("{}: {}".format(msg))
        m.random()
        rate.sleep()

    print('sub bye ...')
Exemplo n.º 24
0
def matrix(**kwargs):
    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(1)
    test = kwargs.get('test', False)
    matrix = LEDDisplay()

    s = geckopy.Subscriber(['led'], got_msg)
    i = 0

    while not geckopy.is_shutdown():
        # if s has message, call function
        # else update led
        geckopy.log('x')

        # matrix.setRandom()
        matrix.update()
        # matrix.set(1,1,127)
        # matrix.clear()
        # matrix.display.set_pixel(i//8,i%8, 1)
        # matrix.write()
        # i = (i+1)%64

        rate.sleep()
Exemplo n.º 25
0
    def loop(self, **kwargs):
        geckopy.init_node(**kwargs)
        rate = geckopy.Rate(2)

        sr = geckopy.subConnectTCP(kwargs.get('key'), 'ryan')
        ss = geckopy.subConnectTCP(kwargs.get('key'), 'scott')
        p = geckopy.pubBinderTCP(kwargs.get('key'), 'ans')

        start = time.time()
        while not geckopy.is_shutdown():
            m = sr.recv_nb()
            if m:
                self.r = m

            m = ss.recv_nb()
            if m:
                self.s = m

            msg = {'ans': self.s + self.r}
            p.publish(msg)  # topic msg

            geckopy.logdebug('ans msg: {}'.format(msg))
            rate.sleep()
        print('pub bye ...')
Exemplo n.º 26
0
def keypad_proc(**kwargs):
    """
    This process handles the main keypad interface and sets the run state
    Also, MIGHT, do ultrasound and battery
    Keypad (https://www.adafruit.com/product/419)
    Pi pins (BCM)
    L  connector    R
    -----------------
    11 9 10 25 13 6 5
    """
    if platform.system() != 'Linux':
        gecko.logerror("{}: can only run on Linux".format(__FILE__))

    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(5)

    gecko.loginfo("Starting: keypad")

    kp = Keypad()

    current_state = 1

    pub = geckopy.Publisher()

    while no geckopy.is_shutdown():
        rate.sleep()

        # get keypad input
        key = kp.getKey()

        # if R2 has not fallen over, then check input
        if True:
            if key in [1, 2, 3]:
                if current_state != key:
                    current_state = key
                    pub.pub('state', current_state)

            elif key in [4, 5, 6]:
                # ns.emotion = key
                if key == 4:
                    c = random.choice(["900", "help me", "religion", "moon", "smell"])
                elif key == 5:
                    # FIXME: make mp3
                    c = random.choice(["900", "help me", "religion", "moon", "smell"])
                msg = Audio(c, None)
                pub.pub('audio', msg)

            elif key == 7:
                pub.pub('servo', Servo('wave'))

            elif key == 8:
                geckopy.loginfo("<<< got turn-off key press >>>")
                current_state = 0
                break

            elif key == "#":
                # FIXME: not sure the right way to do this cleanly
                geckopy.loginfo("Shutting down")
                # shutdown = True  # shutdown linux
                current_state = 0
                break

            elif key == "*":
                geckopy.loginfo("Rebooting now")
                current_state = 0
                # ns.reboot = True      # reboot linux
                break

        # exiting
        current_state = 0
        pub.pub('state', current_state)
        time.sleep(1)
Exemplo n.º 27
0
def slam_publisher(**kwargs):
    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(10)

    geckopy.log(kwargs)

    p = geckopy.Publisher()

    test = kwargs.get('test', False)
    # MAP_SIZE_PIXELS         = 500
    # MAP_SIZE_METERS         = 10

    if platform.system() == 'Linux':
        port = '/dev/serial/by-id/usb-Silicon_Labs_CP2102_USB_to_UART_Bridge_Controller_0001-if00-port0'
    else:
        port = "/dev/tty.SLAB_USBtoUART"

    # Connect to Lidar unit
    lidar = LDS01()
    lidar.open(port)
    lidar.run(True)

    # Create an RMHC SLAM object with a laser model and optional robot model
    # slam = RMHC_SLAM(LDS01_Model(), MAP_SIZE_PIXELS, MAP_SIZE_METERS)

    # Set up a SLAM display
    # display = SlamShow(MAP_SIZE_PIXELS, MAP_SIZE_METERS*1000/MAP_SIZE_PIXELS, 'SLAM')

    # Initialize empty map
    # mapbytes = bytearray(MAP_SIZE_PIXELS * MAP_SIZE_PIXELS)

    while not geckopy.is_shutdown():
        # Update SLAM with current Lidar scan
        pts = lidar.read()
        # need to reverse the order for it to plot correctly
        pts = list(reversed(pts))

        # kludge until i fix the driver
        scan = []
        for i, p in enumerate(pts):
            scan.append((
                i,
                p,
            ))

        msg = Lidar(scan)

        if test:
            print("[LIDAR]=================")
            print("  points: {}".format(len(msg.scan)))
            print("  pt[0]: {}".format(msg.scan[0]))
            print("  timestamp: {}".format(msg.timestamp))

            obs = range_filter(scan, 200)
            print("[Obstacles]=============")
            print("  number: {}".format(len(obs)))
            print("  obs: {}".format(obs))
        else:
            p.pub('scan', msg)

        # slam.update(pts)

        # Get current robot position
        # x, y, theta = slam.getpos()

        # Get current map bytes as grayscale
        # slam.getmap(mapbytes)

        # display.displayMap(mapbytes)
        # display.setPose(x, y, theta)
        # display.refresh()

        # p.pub('avoid', msg)
        # geckopy.log(msg)

        # sleep
        rate.sleep()

    # all done
    lidar.close()
Exemplo n.º 28
0
#!/usr/bin/env python3

from pygecko.multiprocessing import geckopy
from pygecko.messages import lidar_st
from the_collector import BagIt
from the_collector import Pickle

if __name__ == '__main__':
    bag = BagIt(Pickle)
    geckopy.init_node()
    rate = geckopy.Rate(10)

    s = geckopy.subConnectTCP('dalek', 'lidar')

    if s is None:
        raise Exception("subscriber is None")

    # try:
    while not geckopy.is_shutdown():
        msg = s.recv_nb()
        if msg:
            # geckopy.loginfo("{}".format(msg))
            print('.', end='', flush=True)
            bag.push('lidar', msg)
        rate.sleep()

    # except KeyboardInterrupt:
    bag.write('lidar')

    print('sub bye ...')