Skip to content

Allow vpython to be used remotely on a headless Pi #111

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,12 @@ If you execute build_original_no_overload.py, and change the statement "if True:
Note that in site-packages/vpython/vpython_libraries it is glowcomm.html that is used by launchers such as idle or spyder; glowcomm.js is used with Jupyter notebook (and a modified version is used in Jupyterlab).

Placing console.log(....) statements in the GlowScript code or in the JavaScript section of glowcomm.html can be useful in debugging. You may also need to put debugging statements into site-packages/vpython/vpython.py.


## Environment options

The following options make sense for running VPython in a headless environment:

* VPYTHON_PORT -> Specify the TCP/IP port number for the HTTP server.
* VPYTHON_NOBROWSER -> Set this to disable trying to launch a browser.
The link will be printed instead.
36 changes: 25 additions & 11 deletions vpython/no_notebook.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@
import copy
import socket
import multiprocessing
import logging


import signal
from urllib.parse import unquote

from .rate_control import rate

logger = logging.getLogger(__name__)

# Redefine `Thread.run` to not show a traceback for Spyder when stopping
# the server by raising a KeyboardInterrupt or SystemExit.
Expand Down Expand Up @@ -64,7 +66,7 @@ def find_free_port():
return s.getsockname()[1]


__HTTP_PORT = find_free_port()
__HTTP_PORT = int(os.getenv("VPYTHON_PORT", find_free_port()))
__SOCKET_PORT = find_free_port()

try:
Expand Down Expand Up @@ -119,6 +121,7 @@ class serveHTTP(BaseHTTPRequestHandler):
'ico': ['image/x-icon', serverdata]}

def do_GET(self):
logger.debug("Doing get")
global httpserving
httpserving = True
html = False
Expand All @@ -135,6 +138,7 @@ def do_GET(self):
mime = self.mimes[fext]
# For example, mime[0] is image/jpg,
# mime[1] is C:\Users\Bruce\Anaconda3\lib\site-packages\vpython\vpython_data
logger.debug("Sending response")
self.send_response(200)
self.send_header('Content-type', mime[0])
self.end_headers()
Expand All @@ -153,6 +157,7 @@ def do_GET(self):
self.wfile.write(glowcomm.encode('utf-8'))

def log_message(self, format, *args): # this overrides server stderr output
logger.debug(format, *args)
return

# Requests from client to websocket server can be the following:
Expand Down Expand Up @@ -245,25 +250,34 @@ def onClose(self, wasClean, code, reason):
else:
os.kill(os.getpid(), signal.SIGINT)

logger.info("Creating server")

try:
if platform.python_implementation() == 'PyPy':
server_address = ('', 0) # let HTTPServer choose a free port
server_address = ('', int(os.getenv("VPYTHON_PORT", 0))) # let HTTPServer choose a free port
__server = HTTPServer(server_address, serveHTTP)
port = __server.server_port # get the chosen port
# Change the global variable to store the actual port used
__HTTP_PORT = port
_webbrowser.open('http://localhost:{}'.format(port)
) # or webbrowser.open_new_tab()
url = 'http://localhost:{}'.format(__HTTP_PORT)
if os.getenv("VPYTHON_NOBROWSER"):
print(url)
else:
_webbrowser.open(url) # or webbrowser.open_new_tab()
else:
__server = HTTPServer(('', __HTTP_PORT), serveHTTP)
# or webbrowser.open_new_tab()
if _browsertype == 'default': # uses default browser
_webbrowser.open('http://localhost:{}'.format(__HTTP_PORT))

url = 'http://localhost:{}'.format(__HTTP_PORT)
if os.getenv("VPYTHON_NOBROWSER"):
print(url)
else:
if _browsertype == 'default': # uses default browser
_webbrowser.open(url) # or webbrowser.open_new_tab()

except:
pass

logger.info("Server created")

if _browsertype == 'pyqt':
if platform.python_implementation() == 'PyPy':
Expand All @@ -287,15 +301,15 @@ def start_Qapp(port):
filename = filepath + '/qtbrowser.py'
os.system('python ' + filename + ' http://localhost:{}'.format(port))


logger.info("Starting serve forever loop")
# create a browser in its own process
if _browsertype == 'pyqt':
__m = multiprocessing.Process(target=start_Qapp, args=(__HTTP_PORT,))
__m.start()

__w = threading.Thread(target=__server.serve_forever)
__w.start()

logger.info("Started")

def start_websocket_server():
"""
Expand All @@ -322,13 +336,13 @@ def start_websocket_server():
__interact_loop.run_until_complete(__coro)
__interact_loop.run_forever()


logger.debug("Starting WS server")
# Put the websocket server in a separate thread running its own event loop.
# That works even if some other program (e.g. spyder) already running an
# async event loop.
__t = threading.Thread(target=start_websocket_server)
__t.start()

logger.debug("WS Started")

def stop_server():
"""Shuts down all threads and exits cleanly."""
Expand Down
10 changes: 9 additions & 1 deletion vpython/vpython_libraries/glowcomm.html
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,15 @@
"use strict";

//var sock = socket_port() // created by no_notebook.py
ws = new WebSocket("ws://localhost:"+sock)
let ws_url;
if (document.location.hostname.includes("localhost")){
ws_url = "ws://localhost:"+sock;
}
else {
ws_url = 'ws://' + document.location.hostname + ":" + sock;
}

ws = new WebSocket(ws_url);
ws.binaryType = "arraybuffer";

ws.onopen = function() {
Expand Down