예제 #1
0
def main():
    class FrameCollector(object):
        def __init__(self):
            self.frame = None

        def __call__(self, x):
            self.frame = x

    collector = FrameCollector()

    loop = echolib.IOLoop()
    client = echolib.Client()
    loop.add_handler(client)

    sub = FrameSubscriber(client, "camera", collector)

    try:
        while loop.wait(10):
            if collector.frame is not None:
                display(collector.frame)
                collector.frame = None

    except KeyboardInterrupt:
        pass

    sys.exit(1)
예제 #2
0
    def __init__(self, bounds=None):
        self.loop = echolib.IOLoop()
        self.client = echolib.Client(
            name=os.environ.get("APPLICATION_NAME", ""))
        self.loop.add_handler(self.client)
        self.bounds = bounds
        self.camera = Camera(self, "camera0")
        self.manipulator = Manipulator(self, "manipulator0")
        self.markers_pub = MarkersPublisher(self.client, "markers")

        while not (self.camera.is_ready() and self.manipulator.is_ready()):
            self.wait(100)
예제 #3
0
def start_app(app):

    from manus.apps import AppCommandType, AppCommandPublisher, AppCommand
    loop = echolib.IOLoop()
    client = echolib.Client(name="appstart")
    loop.add_handler(client)

    control = AppCommandPublisher(client, "apps.control")
    loop.wait(100)
    message = AppCommand()
    message.type = AppCommandType.EXECUTE
    message.arguments.append(app)
    control.send(message)
    loop.wait(100)
예제 #4
0
    def __init__(self, stdscreen):
        self.screen = stdscreen
        curses.curs_set(0)
        self.screen.clear()
        loop = echolib.IOLoop()
        client = echolib.Client(loop, "/tmp/echo.sock")

        state = ManipulatorStateSubscriber(client, "manipulator0.state",
                                           self.on_state)
        commands = TrajectorySubscriber(client, "manipulator0.trajectory",
                                        self.on_trajectory)

        while loop.wait(30):
            pass
예제 #5
0
    def __init__(self):
        self.active_application = None
        self.applications = {}
        self.loop = echolib.IOLoop()

        self.client = echolib.Client(name="apps")
        self.loop.add_handler(self.client)

        self.control = AppCommandSubscriber(self.client, "apps.control",
                                            lambda x: self.control_callback(x))
        self.announce = AppEventPublisher(self.client, "apps.announce")
        self.listing = AppListingPublisher(self.client, "apps.list")
        self.output = AppStreamDataPublisher(self.client, "apps.output")
        self.input = AppStreamDataSubscriber(self.client, "apps.input",
                                             lambda x: self.input_callback(x))
예제 #6
0
def main():
    def message(message):
        reader = echolib.MessageReader(message)
        name = reader.readString()
        message = reader.readString()
        print(name + ": " + message)

    def write(client, pub, name):
        while client.isConnected():
            try:
                message = input()
                writer = echolib.MessageWriter()
                writer.writeString(name)
                writer.writeString(message)
                pub.send(writer)
            except EOFError:
                break

    loop = echolib.IOLoop()

    client = echolib.Client()
    loop.add_handler(client)

    name = input("Please enter your name:")

    sub = echolib.Subscriber(client, "chat", "string pair", message)

    pub = echolib.Publisher(client, "chat", "string pair")

    thread = threading.Thread(target=write, args=(
        client,
        pub,
        name,
    ))
    thread.start()

    try:
        while loop.wait(10) and thread.is_alive():
            # We have to give the write thread some space
            time.sleep(0.001)
    except KeyboardInterrupt:
        pass

    sys.exit(1)
예제 #7
0
파일: camera.py 프로젝트: vicoslab/echolib
def main():

    loop = echolib.IOLoop()
    client = echolib.Client()
    loop.add_handler(client)

    output = FramePublisher(client, "camera")
    #count = echolib.SubscriptionWatcher(client, "camera")

    camera = cv2.VideoCapture(0)

    if not camera.isOpened():  
        print("Camera not available")
        camera = DummyCamera()

    try:
        while loop.wait(100):
            _, image = camera.read()
            output.send(Frame(image=image))

    except Exception as e:
        traceback.print_exception(e)
예제 #8
0
        batch = ConfigBatch()
        for key, value in self.store.items():
            batch.entries.append(ConfigEntry(key, value))
        self._notify.send(batch)


if __name__ == '__main__':

    if len(sys.argv) > 1:
        storefile = sys.argv[1]
    else:
        storefile = None

    loop = echolib.IOLoop()
    client = echolib.Client(name="config")
    loop.add_handler(client)

    manager = ConfigManager(client)

    if storefile is not None and os.path.isfile(storefile):
        manager.read_config(storefile)

    def shutdown_handler(signum, frame):
        if storefile is not None:
            manager.write_config(storefile)
        sys.exit(0)

    signal.signal(signal.SIGTERM, shutdown_handler)

    try:
예제 #9
0
import echolib, random
from manipulator_msgs import ManipulatorDescriptionSubscriber, ManipulatorStateSubscriber, PlanSegment, JointCommand, Plan, PlanPublisher

description = None

def description_callback(obj):
	global description
	description = obj

def description_state(obj):
	pass

loop = echolib.IOLoop()

client = echolib.Client(loop, "/tmp/echo.sock")

a = ManipulatorDescriptionSubscriber(client, "manipulator0.description", description_callback)
b = ManipulatorStateSubscriber(client, "manipulator0.state", description_state)

move = PlanPublisher(client, "manipulator0.plan")

while loop.wait(1000):
	plan = Plan()
	plan.segments.append(PlanSegment())
	for j in description.joints:
		c = JointCommand()
		c.speed = 4.0
		c.goal = random.uniform(j.dh_min, j.dh_max)
		print c.goal
		plan.segments[0].joints.append(c)
예제 #10
0
    channel_in  = sys.argv[1]
    channel_out = sys.argv[2]

    counter = 0

    def __callback(message):
        
        global counter
        counter += 1

        print("Msg %d: %s " % (counter, echolib.MessageReader(message).readString()))
        

    loop   = echolib.IOLoop()
    client = echolib.Client()
    loop.add_handler(client)


    subscriber = echolib.Subscriber(client, channel_in, u"string", __callback)
    publisher  = echolib.Publisher(client, channel_out, u"string") 

    t = time()

    while loop.wait(100):
    
        writer = echolib.MessageWriter()
        writer.writeString("Hello there")

        print("Send")
예제 #11
0
from .network import NetworkHandler
from .hardware import HardwareHandler

if __name__ == '__main__':

    if len(sys.argv) > 1:
        h = hashlib.new('sha1')
        h.update(sys.argv[1])
        print(h.hexdigest())
        sys.exit(0)

    testing = bool(os.getenv('MANUS_TESTING', False))
    secret = os.getenv('MANUS_SECRET', None)
    loop = echolib.IOLoop()

    client = echolib.Client(name="privileged")
    loop.add_handler(client)

    handlers = {
        PrivilegedCommandType.SYSTEM: SystemHandler(client),
        PrivilegedCommandType.NETWORK: NetworkHandler(client),
        PrivilegedCommandType.HARDWARE: HardwareHandler(client),
    }

    def control_callback(command):
        h = hashlib.new('sha1')
        h.update(command.secret)
        if secret and h.hexdigest() != secret:
            print("Unauthorized command")
            return
        print("Running privileged command: %s" %
예제 #12
0
def main():

    logging_level = logging.DEBUG

    logger = logging.getLogger("manus")
    logger.propagate = False

    log_storage = logging.StreamHandler()
    log_storage.setFormatter(
        logging.Formatter(fmt='%(asctime)s - %(levelname)s\t%(message)s',
                          datefmt='%Y-%m-%d %H:%M:%S'))
    logger.addHandler(log_storage)
    logger.setLevel(logging_level)

    scriptdir = os.path.dirname(
        os.path.abspath(inspect.getfile(inspect.currentframe())))

    client = echolib.Client(name="webshell")
    storage = db.DB()

    try:

        storagefile = os.getenv('MANUS_STORAGE', "/tmp/manus_storage.db")
        if os.path.exists(storagefile):
            logger.info("Opening storage database from %s" % storagefile)
            storage.open(storagefile, None, db.DB_HASH)
        else:
            logger.info("Creating storage database in %s" % storagefile)
            storage.open(storagefile, None, db.DB_HASH, db.DB_CREATE)
            defaults_storage = os.getenv('MANUS_STORAGE_DEFAULTS', None)
            if defaults_storage and os.path.exists(defaults_storage):
                for root, dirs, files in os.walk(defaults_storage):
                    for file in files:
                        if file.endswith(".json"):
                            key = os.path.splitext(file)[0]
                            with open(os.path.join(defaults_storage, file),
                                      'r') as fd:
                                data = "%s;%s" % ("text/json", fd.read())
                                storage.put(key, data)
                                logger.info("Restoring initial data from: %s" %
                                            file)

        handlers = []
        cameras = []
        manipulators = []

        try:
            camera = echocv.tornado.Camera(client, "camera0")
            handlers.append(
                (r'/api/camera/video', echocv.tornado.VideoHandler, {
                    "camera": camera
                }))
            handlers.append(
                (r'/api/camera/image', echocv.tornado.ImageHandler, {
                    "camera": camera
                }))
            handlers.append(
                (r'/api/camera/describe', CameraDescriptionHandler, {
                    "camera": camera
                }))
            handlers.append((r'/api/camera/position', CameraLocationHandler, {
                "camera": camera
            }))
            cameras.append(camera)
        except Exception as e:
            print(traceback.format_exc())

        try:
            manipulator = manus.Manipulator(client, "manipulator0")
            handlers.append(
                (r'/api/manipulator/describe', ManipulatorDescriptionHandler, {
                    "manipulator": manipulator
                }))
            handlers.append(
                (r'/api/manipulator/state', ManipulatorStateHandler, {
                    "manipulator": manipulator
                }))
            handlers.append(
                (r'/api/manipulator/joint', ManipulatorMoveJointHandler, {
                    "manipulator": manipulator
                }))
            handlers.append(
                (r'/api/manipulator/move', ManipulatorMoveHandler, {
                    "manipulator": manipulator
                }))
            handlers.append(
                (r'/api/manipulator/safe', ManipulatorMoveSafeHandler, {
                    "manipulator": manipulator
                }))
            handlers.append((r'/api/manipulator/trajectory',
                             ManipulatorTrajectoryHandler, {
                                 "manipulator": manipulator
                             }))
            manipulators.append(manipulator)
        except Exception as e:
            print(traceback.format_exc())

        #handlers.append((r'/api/markers', MarkersStorageHandler))
        apps = AppsManager(client)
        privileged = PrivilegedClient(client)
        config = ConfigManager(client)

        #handlers.append((r'/api/login', LoginHandler, {"users" : None}))
        handlers.append((r'/api/apps', AppsHandler, {"apps": apps}))
        handlers.append((r'/api/privileged', PrivilegedHandler, {
            "privileged": privileged
        }))
        handlers.append((r'/api/storage', StorageHandler, {
            "storage": storage
        }))
        handlers.append((r'/api/websocket', ApiWebSocket, {
            "cameras": cameras,
            "manipulators": manipulators,
            "apps": apps,
            "config": config
        }))
        handlers.append((r'/api/config', ConfigHandler, {"config": config}))
        handlers.append((r'/api/info', ApplicationHandler))
        handlers.append((r'/', RedirectHandler, {'url': '/index.html'}))
        handlers.append((r'/(.*)', DevelopmentStaticFileHandler, {
            'path':
            os.path.dirname(manus_webshell.static.__file__)
        }))

        def markers_callback(markers):
            data = {m.id : {"location": [m.location.x, m.location.y, m.location.z], \
                "rotation": [m.rotation.x, m.rotation.y, m.rotation.z], \
                "size": [m.size.x, m.size.y, m.size.z], \
                "color": [m.color.red, m.color.green, m.color.blue]} for m in markers.markers}
            ApiWebSocket.distribute_message({
                "channel": "markers",
                "action": "overwrite",
                "markers": data,
                "overlay": markers.owner
            })

        markers_subscriber = MarkersSubscriber(client, "markers",
                                               markers_callback)

        application = tornado.web.Application(
            handlers,
            cookie_secret=os.getenv('MANUS_COOKIE_SECRET', "manus"),
            debug=bool(os.getenv('MANUS_DEBUG', "false")))

        server = tornado.httpserver.HTTPServer(application)
        server.listen(int(os.getenv('MANUS_PORT', "8080")))

        tornado_loop = tornado.ioloop.IOLoop.instance()

        signal.signal(
            signal.SIGINT, lambda sig, frame: tornado_loop.
            add_callback_from_signal(on_shutdown))
        signal.signal(
            signal.SIGTERM, lambda sig, frame: tornado_loop.
            add_callback_from_signal(on_shutdown))

        def on_disconnect(client):
            tornado_loop.stop()

        echocv.tornado.install_client(tornado_loop, client, on_disconnect)

        logger.info("Starting %s webshell" % manus.NAME)

        def flush_database():
            # Flush every 5 seconds
            storage.sync()
            tornado_loop.add_timeout(time.time() + 5, flush_database)

        flush_database()

        try:
            tornado_loop.start()
        except KeyboardInterrupt:
            pass
        except Exception as err:
            print(traceback.format_exc())

        echocv.tornado.uninstall_client(tornado_loop, client)

        flush_database()

    except Exception as e:
        print(traceback.format_exc())

    logger.info("Stopping %s webshell" % manus.NAME)
    storage.close()