Skip to content

Commit

Permalink
Added initial configuration options
Browse files Browse the repository at this point in the history
  • Loading branch information
SamuelDudley committed Feb 27, 2017
1 parent 8b4c512 commit 3c9cf8c
Show file tree
Hide file tree
Showing 7 changed files with 100 additions and 17 deletions.
26 changes: 17 additions & 9 deletions __init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,17 @@

import webbrowser # open url's in browser window

from app.config import SERVER_INTERFACE, SERVER_PORT, MODULE_DEBUG, APP_DEBUG

class ServerProtocol(WebSocketServerProtocol):

def onConnect(self, request):
print("Client connecting: {0}".format(request.peer))
if APP_DEBUG:
print("Client connecting: {0}".format(request.peer))

def onOpen(self):
print("WebSocket connection open")
if APP_DEBUG:
print("WebSocket connection open")
self.id = uuid.uuid4()
self.factory.data[self.id]=self
payload = {'new_connection':self.id}
Expand All @@ -45,8 +49,12 @@ def onMessage(self, payload, isBinary):
self.factory.message_queue.put(payload)

def onClose(self, wasClean, code, reason):
print("WebSocket connection closed: {0}".format(reason))
del self.factory.data[self.id]
if APP_DEBUG:
print("WebSocket connection closed: {0}".format(reason))
try:
del self.factory.data[self.id]
except Exception as e:
print("An error occurred when attempting to close a websocket: {}".format(e))


class CesiumModule(mp_module.MPModule):
Expand All @@ -68,7 +76,7 @@ def __init__(self, mpstate):

self.cesium_settings = mp_settings.MPSettings(
[ ('openbrowser', bool, False),
('debug', bool, True)])
('debug', bool, MODULE_DEBUG)])

self.aircraft = {'lat':None, 'lon':None, 'alt_wgs84':None,
'roll':None, 'pitch':None, 'yaw':None}
Expand All @@ -88,7 +96,7 @@ def run_server(self):
# log.startLogging(sys.stdout)

# create a Twisted Web resource for our WebSocket server
self.factory = WebSocketServerFactory(u"ws://0.0.0.0:5000")
self.factory = WebSocketServerFactory(u"ws://"+SERVER_INTERFACE+":"+SERVER_PORT)
self.factory.protocol = ServerProtocol
self.factory.setProtocolOptions(maxConnections=100)
self.factory.data = {}
Expand All @@ -104,12 +112,12 @@ def run_server(self):

# create a Twisted Web Site and run everything
site = Site(rootResource)
reactor.listenTCP(5000, site, interface='0.0.0.0')
reactor.listenTCP(int(SERVER_PORT), site, interface=SERVER_INTERFACE)
self.server_thread = threading.Thread(target=reactor.run, args=(False,))
self.server_thread.daemon = True
self.server_thread.start()

self.mpstate.console.writeln('MAVCesium display loaded at http://127.0.0.1:5000/', fg='white', bg='blue')
self.mpstate.console.writeln('MAVCesium display loaded at http://'+SERVER_INTERFACE+":"+SERVER_PORT+'/', fg='white', bg='blue')

def stop_server(self):
if self.server_thread is not None:
Expand All @@ -119,7 +127,7 @@ def stop_server(self):

def open_display_in_browser(self):
if self.web_server_thread.isAlive():
url = 'http://127.0.0.1:5000/'
url = 'http://'+SERVER_INTERFACE+":"+SERVER_PORT+'/'
try:
browser_controller = webbrowser.get('google-chrome')
browser_controller.open_new_tab(url)
Expand Down
10 changes: 4 additions & 6 deletions app/cesium_web_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
Jan 2016
'''


from config import SERVER_INTERFACE, SERVER_PORT, FLASK_SECRET_KEY, WEBSOCKET, BING_API_KEY

import os, sys, json, uuid

Expand All @@ -26,14 +26,12 @@
APP_TEMPLATES = os.path.join(APP_ROOT, 'templates')

app = Flask(__name__, root_path=APP_ROOT, template_folder=APP_TEMPLATES, static_folder=APP_STATIC)
app.secret_key = str(uuid.uuid4())
app.secret_key = FLASK_SECRET_KEY

with open(os.path.join(APP_ROOT, 'api_keys.txt', )) as fid:
api_keys = json.load(fid)

@app.route('/')
def index():
return render_template('index.html', bing_api_key=api_keys['bing'])
return render_template('index.html', bing_api_key=BING_API_KEY, websocket=WEBSOCKET)

@app.route('/context/', methods=['POST'])
def get_current_context():
Expand All @@ -49,7 +47,7 @@ def start_server(debug = False):
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)

app.run(host='0.0.0.0',port=5000)
app.run(host=SERVER_INTERFACE ,port=SERVER_PORT)

if __name__ == '__main__':
start_server()
Expand Down
63 changes: 63 additions & 0 deletions app/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
""" configuration variables """

import configparser
import os
import uuid

def parse_bool(OPTION):
if OPTION == '0':
OPTION = False
else:
OPTION = True
return OPTION


_conf = configparser.ConfigParser()
_conf_file_paths = []

if 'HOME' in os.environ:
_conf_file_path = os.path.join(os.environ['HOME'], ".mavcesium.ini")
_conf_file_paths.append(_conf_file_path)
if 'LOCALAPPDATA' in os.environ:
_conf_file_path = os.path.join(os.environ['LOCALAPPDATA'], "MAVProxy", "mavcesium.ini")
_conf_file_paths.append(_conf_file_path)

try: # try to use pkg_resources to allow for zipped python eggs
import pkg_resources
_cur_dir = pkg_resources.resource_filename('MAVProxy.modules.mavproxy_cesium','app')
except: # otherwise fall back to the standard file system
_cur_dir = os.path.dirname(os.path.abspath(__file__))

_conf_file_paths.append(os.path.join(_cur_dir, 'mavcesium_default.ini'))

for _conf_file_path in _conf_file_paths:
if os.path.exists(_conf_file_path):
try:
# load the config
_conf.read_file(open(_conf_file_path))

SERVER_INTERFACE = _conf.get('general', 'server_interface')
SERVER_PORT = _conf.get('general', 'server_port')
WEBSOCKET = "ws://"+SERVER_INTERFACE+":"+SERVER_PORT+"/ws"

BING_API_KEY = _conf.get('api_keys', 'bing')

FLASK_SECRET_KEY = _conf.get('general', 'flask_secret_key')
if FLASK_SECRET_KEY == '':
FLASK_SECRET_KEY = str(uuid.uuid4())

APP_DEBUG = parse_bool(_conf.get('debug', 'app_debug'))
MODULE_DEBUG = parse_bool(_conf.get('debug', 'module_debug'))


if MODULE_DEBUG:
print ('Using config file at {}'.format( _conf_file_path ))
break # use first working config

except Exception as e:
print ('Failed to use config file at {} : {}'.format( _conf_file_path, e ))



# TODO: check for pass / fail and action

12 changes: 12 additions & 0 deletions app/mavcesium_default.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[general]
# web site url = eg. 'http://' + domain_name
server_interface = 0.0.0.0
server_port = 5000
flask_secret_key = ''

[api_keys]
bing = Auw42O7s-dxnXl0f0HdmOoIAD3bvbPjFOVKDN9nNKrf1uroCCBxetdPowaQF4XaG

[debug]
app_debug = 1
module_debug = 1
2 changes: 1 addition & 1 deletion app/static/DST/js/websocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ function check_websocket(){
};

function open_websocket() {
socket = new WebSocket("ws://127.0.0.1:5000/ws");
socket = new WebSocket(websocket);
socket.binaryType = "arraybuffer";
socket.onopen = function() {
console.log("WebSocket connected!");
Expand Down
3 changes: 2 additions & 1 deletion app/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
<script src="/static/Build/Cesium/Cesium.js"></script>
<script>
var bing_api_key = '{{ bing_api_key }}';
var websocket = '{{ websocket }}';
</script>
<style>
@import url(/static/Build/Cesium/Widgets/widgets.css);
Expand Down Expand Up @@ -66,10 +67,10 @@
<script src="/static/DST/js/third_party/lobipanel.js"></script>
<script src="/static/DST/js/cesium_setup.js"></script>
<script src="/static/DST/js/core.js"></script>
<script src="/static/DST/js/websocket.js"></script>
<script src="/static/DST/js/wp.js"></script>
<script src="/static/DST/js/context_menu.js"></script>
<script src="/static/DST/js/settings.js"></script>
<script src="/static/DST/js/hud.js"></script>
<script src="/static/DST/js/websocket.js"></script>
</body>
</html>
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
Flask>=0.11.1
autobahn[twisted]
configparser

0 comments on commit 3c9cf8c

Please sign in to comment.