Exemplo n.º 1
0
def check_N(N, backend):
    with Display():
        ls = []
        try:
            for i in range(N):
                cmd = [
                    sys.executable,
                    __file__.rsplit(".", 1)[0] + ".py",
                    str(i),
                    backend,
                    "--debug",
                ]
                p = EasyProcess(cmd)
                p.start()
                ls += [p]

            sleep(3)

            good_count = 0
            rc_ls = []
            for p in ls:
                p.wait()
                if p.return_code == 0:
                    good_count += 1
                rc_ls += [p.return_code]
        finally:
            for p in ls:
                p.stop()
        print(rc_ls)
        print(good_count)
        assert good_count == N
Exemplo n.º 2
0
    def start(self):
        '''
        start display

        :rtype: self
        '''
        if self.use_xauth:
            self._setup_xauth()
        EasyProcess.start(self)

        # https://github.com/ponty/PyVirtualDisplay/issues/2
        # https://github.com/ponty/PyVirtualDisplay/issues/14
        self.old_display_var = os.environ.get('DISPLAY', None)

        self.redirect_display(True)

        # wait until X server is active
        start_time = time.time()
        if self.check_startup:
            rp = self._check_startup_fd
            display_check = None
            rlist, wlist, xlist = select.select((rp,), (), (), X_START_TIMEOUT)
            if rlist:
                display_check = os.read(rp, 10).rstrip()
            else:
                msg = 'No display number returned by X server'
                raise XStartTimeoutError(msg)
            dnbs = str(self.display)
            if bytes != str:
                dnbs = bytes(dnbs, 'ascii')
            if display_check != dnbs:
                msg = 'Display number "%s" not returned by X server' + str(display_check)
                raise XStartTimeoutError(msg % self.display)

        d = self.new_display_var
        ok = False
        while True:
            try:
                exit_code = EasyProcess('xdpyinfo').call().return_code
            except EasyProcessError:
                log.warn('xdpyinfo was not found, X start can not be checked! Please install xdpyinfo!')
                time.sleep(X_START_WAIT)    # old method
                ok = True
                break

            if exit_code != 0:
                pass
            else:
                log.info('Successfully started X with display "%s".', d)
                ok = True
                break

            if time.time() - start_time >= X_START_TIMEOUT:
                break
            time.sleep(X_START_TIME_STEP)
        if not ok:
            msg = 'Failed to start X on display "%s" (xdpyinfo check failed).'
            raise XStartTimeoutError(msg % d)
        return self
Exemplo n.º 3
0
def test_deadlock():
    d = Display(visible=VISIBLE, size=(600, 400))
    d.start()
    
    p = EasyProcess([python, '-c', 'import Image;Image.new("RGB",(99, 99)).show()'])
    p.start()
    p.sleep(1)
    # hangs with pipes
    p.stop()
    
    d.stop()
Exemplo n.º 4
0
 def display(self, zipfilename='', block=True):
     fig = plt.figure()
     self.create(fig, zipfilename)
     if block:
         plt.show()
     else:
         p = EasyProcess([
             sys.executable, '-m', 'elme.start.plot', self.project.name,
             '--plot', self.name, '--zipfilename', zipfilename
         ])
         p.start()
Exemplo n.º 5
0
def test_deadlock():
    d = Display(visible=VISIBLE, size=(600, 400))
    d.start()

    p = EasyProcess(
        [python, '-c', 'import Image;Image.new("RGB",(99, 99)).show()'])
    p.start()
    p.sleep(1)
    # hangs with pipes
    p.stop()

    d.stop()
Exemplo n.º 6
0
 def display(self, zipfilename='', block=True):
     fig = plt.figure()
     self.create(fig, zipfilename)
     if block:
         plt.show()
     else:
         p = EasyProcess([sys.executable,
                          '-m', 'elme.start.plot',
                          self.project.name,
                          '--plot', self.name,
                          '--zipfilename', zipfilename
                          ])
         p.start()
Exemplo n.º 7
0
def test_deadlock():
    # skip these tests for Windows/Mac
    if not sys.platform.startswith("linux"):
        return
    d = Display(visible=VISIBLE, size=(600, 400))
    d.start()

    p = EasyProcess(
        [python, "-c", 'import Image;Image.new("RGB",(99, 99)).show()'])
    p.start()
    p.sleep(1)
    # hangs with pipes
    p.stop()

    d.stop()
Exemplo n.º 8
0
    def start(self):
        '''
        start display

        :rtype: self
        '''
        EasyProcess.start(self)

        # https://github.com/ponty/PyVirtualDisplay/issues/2
        # https://github.com/ponty/PyVirtualDisplay/issues/14
        self.old_display_var = os.environ.get('DISPLAY', None)

        self.redirect_display(True)
        # wait until X server is active
        # TODO: better method
        time.sleep(0.1)
        return self
Exemplo n.º 9
0
    def start(self):
        '''
        start display

        :rtype: self
        '''
        EasyProcess.start(self)

        # https://github.com/ponty/PyVirtualDisplay/issues/2
        self.old_display_var = os.environ[
            'DISPLAY'] if 'DISPLAY' in os.environ else ':0'

        self.redirect_display(True)
        # wait until X server is active
        # TODO: better method
        time.sleep(0.1)
        return self
def service(request, service_mock):
    port = random.randint(30000, 40000)
    p = EasyProcess('python3.4 src/service.py {}'
        'http://localhost:{}/tests/html1'            
        .format(port, service_mock.port))

    def turn_off():
        print("DOWN")
        p.stop()
        print("STDOUT: " + p.stdout)
        print("STDERROR: " + p.stderr)
        print("CODE: " + str(p.return_code))

    request.addfinalizer(turn_off)
    p.start()
    time.sleep(0.5)
    p.port = port
    return p
Exemplo n.º 11
0
    def start(self):
        '''
        start display
        
        :rtype: self
        '''
        self.display = self.search_for_display()
        EasyProcess.__init__(self, self._cmd)
        EasyProcess.start(self)

        # https://github.com/ponty/PyVirtualDisplay/issues/2
        self.old_display_var = os.environ[
            'DISPLAY'] if 'DISPLAY' in os.environ else ':0'

        self.redirect_display(True)
        # wait until X server is active
        # TODO: better method
        time.sleep(0.1)
        return self
Exemplo n.º 12
0
    def start(self):
        """
        start display

        :rtype: self
        """
        if self.use_xauth:
            self._setup_xauth()
        EasyProcess.start(self)

        # https://github.com/ponty/PyVirtualDisplay/issues/2
        # https://github.com/ponty/PyVirtualDisplay/issues/14
        self.old_display_var = os.environ.get("DISPLAY", None)

        self.redirect_display(True)
        # wait until X server is active
        # TODO: better method
        time.sleep(0.1)
        return self
Exemplo n.º 13
0
    def start(self):
        '''
        start display

        :rtype: self
        '''
        if self.use_xauth:
            self._setup_xauth()
        EasyProcess.start(self)

        # https://github.com/ponty/PyVirtualDisplay/issues/2
        # https://github.com/ponty/PyVirtualDisplay/issues/14
        self.old_display_var = os.environ.get('DISPLAY', None)

        self.redirect_display(True)

        # wait until X server is active
        start_time = time.time()
        ok = False
        d = self.new_display_var
        while time.time() - start_time < X_START_TIMEOUT:
            try:
                exit_code = EasyProcess('xdpyinfo').call().return_code
            except EasyProcessError:
                log.warn('xdpyinfo was not found, X start can not be checked! Please install xdpyinfo!')
                time.sleep(X_START_WAIT)    # old method
                ok = True
                break

            if exit_code != 0:
                pass
            else:
                log.info('Successfully started X with display "%s".', d)
                ok = True
                break

            time.sleep(X_START_TIME_STEP)
        if not ok:
            msg = 'Failed to start X on display "%s" (xdpyinfo check failed).'
            raise XStartTimeoutError(msg % d)
        return self
Exemplo n.º 14
0
class MPPServer:
    def __init__(self, application, config):
        self.config = config
        self.config["room_alias"] = ("#" + self.config["local_room_alias"] +
                                     ":" + self.config["hs_name"])
        self.config["user_id"] = ("@" + self.config["local_user_id"] + ":" +
                                  self.config["hs_name"])

        self.disp = disp
        self.keyboard = Controller()
        self.api = application.Api()

        try:
            # when creating a room with a room alias, only local part of alias is used
            self.room_id = self.api.create_room(
                alias=self.config["local_room_alias"], is_public=True)
            logger.info("new room created: " + self.room_id)
        except exceptions.MatrixError:
            # if it already exists just get the room_id
            self.room_id = self.api.get_room_id(self.config["room_alias"])
            logger.info("using existing room: " + self.room_id)

        self._start_mgba()

    def _start_mgba(self):
        self.pkmn = EasyProcess("mgba -s 2 -b " +
                                self.config["bios_location"] + " " +
                                self.config["rom_location"])
        self.pkmn.start()
        logger.info("mgba started")

        self.ts = time.time()
        self.save_timers = [[index, time.time(), l, f]
                            for index, (l, f) in enumerate(((50, Key.f1),
                                                            (1000, Key.f2),
                                                            (10000, Key.f3),
                                                            (50000, Key.f4),
                                                            (100000, Key.f5)))]
        time.sleep(5)
        self._load()
        self.send_screenshot()

    def __del__(self):
        self.pkmn.stop()
        self.disp.stop()

    def send_screenshot(self):
        if self.ts + 2 < time.time():
            self._send()
            self.ts = time.time()

    def _send(self):
        img = self.disp.grab()
        f = BytesIO()
        try:
            img.save(f, format="JPEG", quality=50, optimize=True)
            mxc = self.api.media_upload(f.getvalue(),
                                        "image/jpeg")["content_uri"]
            file_name = str(int(self.ts)) + ".jpg"
            self.api.send_content(self.room_id, mxc, file_name, "m.image")
            logger.debug("sent screenshot to " + self.room_id)
        except AttributeError:
            self.api.send_notice(self.room_id, "Error in capturing screenshot")
            logger.error("could not capture screenshot from display")

    def _save(self):
        for i, t, l, f in self.save_timers:
            if t + l < time.time():
                with self.keyboard.pressed(Key.shift):
                    self._press_key(f)
                logger.info("saved state to " + str(f) + " after " + str(l) +
                            " seconds")
                self.save_timers[i][1] = time.time()

    def _load(self):
        self._press_key(Key.f1)
        logger.debug("loaded gamestate from f1")

    def room_handler(self, room_alias):
        # Only room created is #matrixplayspokemon
        logger.info("homeserver asked for " + room_alias)
        return room_alias == self.config["room_alias"]

    def user_handler(self, mxid):
        # Only user is as_user.mxid
        logger.info("homeserver asked for " + mxid)
        return mxid == self.config["user_id"]

    def transaction_handler(self, event_stream):
        for event in event_stream:
            if (event.id == self.room_id and event.type == "m.room.message"
                    and event.content["msgtype"] == "m.text"):
                content = event.content["body"].lower()
                if content == "a":
                    self._press_key("x")
                elif content == "b":
                    self._press_key("z")
                elif content == "l":
                    self._press_key("a")
                elif content == "r":
                    self._press_key("s")
                elif content == "up":
                    self._press_key(Key.up)
                elif content == "down":
                    self._press_key(Key.down)
                elif content == "left":
                    self._press_key(Key.left)
                elif content == "right":
                    self._press_key(Key.right)
                elif content == "start":
                    self._press_key(Key.enter)
                elif content == "select":
                    self._press_key(Key.backspace)

                elif content == "dump" and self.config["debug"]:
                    logger.debug("received dump command")
                    self._dump()
                elif content == "save" and self.config["debug"]:
                    logger.debug("received save command")
                    with self.keyboard.pressed(Key.shift):
                        self._press_key(Key.f1)
                    logger.debug("saved current gamestate to f1")
                elif content == "load" and self.config["debug"]:
                    logger.debug("received load command")
                    self._load()

            logger.debug("handled " + event.type +
                         #" from " + event.mxid +
                         " in " + event.id)
            self.send_screenshot()
            self._save()
        return True

    def _press_key(self, key):
        self.keyboard.press(key)
        # make sure the key is pressed long enought to register with mgba
        time.sleep(0.05)
        self.keyboard.release(key)
        logger.debug("pressed key: " + str(key))

    def _dump(self):
        self.pkmn.stop()
        logger.warning("mgba stdout: " + self.pkmn.stdout)
        logger.warning("mgba stderr: " + self.pkmn.stderr)
        self._start_mgba()
Exemplo n.º 15
0
formatter = logging.Formatter(
    "%(asctime)s : %(levelname)s : %(name)s : %(message)s")
handler.setFormatter(formatter)
logger = logging.getLogger()
logger.addHandler(handler)
logger.setLevel(logging.INFO)

# Must start display before we can use Xlib via pynput
disp = SmartDisplay(visible=False, size=(240, 160))
disp.start()
logger.info("xvfb display started")
from pynput.keyboard import Key, Controller
logger.info("pynput imported and working")
# Have to start pulse here because mgba is being a weenie
pulse = EasyProcess("pulseaudio")
pulse.start()
logger.info("pulseaudio started")

with open("config.json") as f:
    config = json.load(f)

if config["debug"]:
    logger.setLevel(logging.DEBUG)

application = server.Application(config["hs_address"], config["token"])


class MPPServer:
    def __init__(self, application, config):
        self.config = config
        self.config["room_alias"] = ("#" + self.config["local_room_alias"] +
Exemplo n.º 16
0
    def start(self):
        """
        start display

        :rtype: self
        """
        if self.use_xauth:
            self._setup_xauth()
        EasyProcess.start(self)
        time.sleep(0.01)

        # https://github.com/ponty/PyVirtualDisplay/issues/2
        # https://github.com/ponty/PyVirtualDisplay/issues/14
        self.old_display_var = os.environ.get("DISPLAY", None)

        self.redirect_display(True)

        # wait until X server is active
        start_time = time.time()
        if self.check_startup:
            rp = self._check_startup_fd
            display_check = None
            rlist, wlist, xlist = select.select((rp, ), (), (),
                                                X_START_TIMEOUT)
            if rlist:
                display_check = os.read(rp, 10).rstrip()
            else:
                msg = "No display number returned by X server"
                raise XStartTimeoutError(msg)
            dnbs = str(self.display)
            if bytes != str:
                dnbs = bytes(dnbs, "ascii")
            if display_check != dnbs:
                msg = 'Display number "%s" not returned by X server' + str(
                    display_check)
                raise XStartTimeoutError(msg % self.display)

        d = self.new_display_var
        ok = False
        while True:
            if not EasyProcess.is_alive(self):
                break

            try:
                xdpyinfo = EasyProcess("xdpyinfo")
                xdpyinfo.enable_stdout_log = False
                xdpyinfo.enable_stderr_log = False
                exit_code = xdpyinfo.call().return_code
            except EasyProcessError:
                log.warning(
                    "xdpyinfo was not found, X start can not be checked! Please install xdpyinfo!"
                )
                time.sleep(X_START_WAIT)  # old method
                ok = True
                break

            if exit_code != 0:
                pass
            else:
                log.info('Successfully started X with display "%s".', d)
                ok = True
                break

            if time.time() - start_time >= X_START_TIMEOUT:
                break
            time.sleep(X_START_TIME_STEP)
        if not EasyProcess.is_alive(self):
            log.warning("process exited early", )
            msg = "Failed to start process: %s"
            raise XStartError(msg % self)
        if not ok:
            msg = 'Failed to start X on display "%s" (xdpyinfo check failed, stderr:[%s]).'
            raise XStartTimeoutError(msg % (d, xdpyinfo.stderr))
        return self
Exemplo n.º 17
0
                "REMOTEKB_LIBSDL_PATH"] = "/usr/lib/x86_64-linux-gnu/libSDL2-2.0.so.0.8.0"

        #move into /tmp/sdl directory to have sdl image dumps there
        if not os.path.isdir("/tmp/sdl"):
            os.mkdir("/tmp/sdl")

        #requires remotekb_wrap in launch for sdlkbdsim use
        pico8_binary = 'runner_{}_{}'.format(os.uname().sysname,
                                             os.uname().machine)
        print(str(PROJECT_ROOT / "pico8" / pico8_binary))
        pico8proc = EasyProcess(
            str(PROJECT_ROOT / "pico8" / pico8_binary) + " -windowed 1" +
            " -width 128" + " -height 128" + " -frameless 1" + " -volume 0" +
            " -foreground_sleep_ms 20" + " -home /tmp",
            cwd='/tmp/sdl')
        pico8proc.start()

        process = Process(target=process_dumped_images,
                          args=(shared_image_array, ))
        process.start()

    if not args.disable_port_forwarding:
        upnp = UPNPPortForward()
        upnp.forward_port(args.port, 'TCP')
        upnp.forward_port(args.port, 'UDP')
        print("Share URL for remote play: http://{}:{}".format(
            upnp.get_external_ip(), args.port))

    app = web.Application()
    app.on_shutdown.append(on_shutdown)
    app.router.add_get("/", index)