Move to Meh, create Harrogate user on first start, initial binary notifications

This commit is contained in:
Philip Trauner 2017-03-03 20:25:29 +01:00
parent 868505126e
commit a8ebee04c1

View file

@ -1,10 +1,8 @@
from Highway import Route, Pipe, Client from Highway import Route, Pipe, Client
from Meh import Config, Option, ExceptionInConfigError
import Logging import Logging
import Config
import Utils import Utils
import behem0th
import socket import socket
import time import time
import os import os
@ -12,29 +10,30 @@ import sys
import subprocess import subprocess
from random import randint from random import randint
from _thread import start_new_thread from _thread import start_new_thread
from ctypes import cdll
import threading import threading
import json
from behem0th import Client as SyncClient
from behem0th import EventHandler
CHANNEL = 2 CHANNEL = 2
IS_WALLABY = Utils.is_wallaby() IS_WALLABY = Utils.is_wallaby()
PATH = "/home/root/Documents/KISS/bin/" if IS_WALLABY else (sys.argv[1] if len(sys.argv) > 1 else None)
PATH = os.path.abspath(PATH)
if PATH[-1] != "/":
PATH = PATH + "/"
USERS_LOCATION = "/home/root/Documents/KISS/users.json"
LIB_WALLABY = "/usr/lib/libwallaby.so" LIB_WALLABY = "/usr/lib/libwallaby.so"
WALLABY_PROGRAMS = "/root/Documents/KISS/bin/"
if not PATH:
Logging.error("No path specified. (Necessary on simulated Wallaby controllers.)")
exit(1)
if not IS_WALLABY: if not IS_WALLABY:
Logging.warning("Binaries that were created for Wallaby Controllers will not run on a simulated Wallaby.") Logging.warning("Binaries that were created for Wallaby Controllers will not run on a simulated Wallaby.")
def get_users():
if IS_WALLABY:
return list(json.loads(open(USERS_LOCATION, "r").read()).keys())
return ["Default User"]
class SensorReadout: class SensorReadout:
ANALOG = 1 ANALOG = 1
DIGITAL = 2 DIGITAL = 2
@ -42,7 +41,7 @@ class SensorReadout:
MODES = tuple(NAMED_MODES.keys()) MODES = tuple(NAMED_MODES.keys())
def __init__(self, handler, poll_rate=0.5): def __init__(self, handler, poll_rate=0.2):
self.poll_rate = poll_rate self.poll_rate = poll_rate
self.handler = handler self.handler = handler
self.peer_lock = threading.Lock() self.peer_lock = threading.Lock()
@ -161,6 +160,7 @@ class Identify(Pipe):
Logging.success("I was identified!") Logging.success("I was identified!")
class ListPrograms(Pipe): class ListPrograms(Pipe):
def run(self, data, peer, handler): def run(self, data, peer, handler):
programs = [] programs = []
@ -180,7 +180,7 @@ class StopPrograms(Pipe):
def run(self, data, peer, handler): def run(self, data, peer, handler):
if handler.debug: if handler.debug:
Logging.info("Stopping all botball programs.") Logging.info("Stopping all botball programs.")
if subprocess.call(["killall", "botball_user_program"], if subprocess.call(["killall", "botball_user_program"],
stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT): stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT):
handler.pipe(self.__class__.NO_PROGRAMS_RUNNING, "stop_programs", peer) handler.pipe(self.__class__.NO_PROGRAMS_RUNNING, "stop_programs", peer)
@ -198,7 +198,7 @@ class RunProgram(Pipe):
data = data + "/" data = data + "/"
path = "%s%s/botball_user_program" % (PATH, data) path = "%s%s/botball_user_program" % (PATH, data)
if os.path.isfile(path): if os.path.isfile(path):
program = subprocess.Popen(self.command + [path], program = subprocess.Popen(self.command + [path],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
start_new_thread(self.stream_stdout, (program, peer, handler)) start_new_thread(self.stream_stdout, (program, peer, handler))
else: else:
@ -254,6 +254,20 @@ class Sensor(Pipe):
self.sensor_readout = SensorReadout(handler) self.sensor_readout = SensorReadout(handler)
class BinaryReceived(Pipe, EventHandler):
def on_modified(self, event):
print(event)
def on_created(self, event):
print(event)
def start(self, handler):
self.handler = handler
class Shutdown(Pipe): class Shutdown(Pipe):
def run(self, data, peer, handler): def run(self, data, peer, handler):
try: try:
@ -310,44 +324,66 @@ class Handler(Client):
def setup(self, routes, debug=False): def setup(self, routes, debug=False):
super().setup(routes, debug=debug) super().setup(routes, debug=debug)
def peer_unavaliable(self, peer): def peer_unavaliable(self, peer):
if self.debug: if self.debug:
Logging.info("Unsubscribing '%s' from all sensor updates." % peer) Logging.info("Unsubscribing '%s' from all sensor updates." % peer)
self.routes["sensor"].sensor_readout.unsubscribe_all(peer) self.routes["sensor"].sensor_readout.unsubscribe_all(peer)
if IS_WALLABY:
if not "fl0w" in get_users():
json.loads(open(USERS_LOCATION, "r").read())["fl0w"] = {"mode" : "Advanced"}
try:
os.mkdir(FL0W_USER_PATH)
except FileExistsError:
pass
PATH = FL0W_USER_PATH + "bin/"
else:
if len(sys.argv) == 2:
if os.path.exists(sys.argv[1]):
PATH = os.path.abspath(sys.argv[1])
else:
Logging.error("Location has to be provided in dev-env.")
exit(1)
if PATH[-1] != "/":
PATH = PATH + "/"
CONFIG_PATH = "wallaby.cfg" CONFIG_PATH = "wallaby.cfg"
config = Config.Config() config = Config()
config.add(Config.Option("server_address", "ws://127.0.0.1:3077")) config.add(Option("server_address", "ws://127.0.0.1:3077"))
config.add(Config.Option("debug", False, validator=lambda x: True if True or False else False)) config.add(Option("debug", True, validator=lambda x: True if True or False else False))
config.add(Config.Option("output_unbuffer", "stdbuf")) config.add(Option("output_unbuffer", "stdbuf"))
config.add(Config.Option("identify_sound", "Wallaby/identify.wav", config.add(Option("identify_sound", "Wallaby/identify.wav",
validator=lambda x: os.path.isfile(x))) validator=lambda sound: os.path.isfile(sound)))
try:
config = config.read_from_file(CONFIG_PATH)
except FileNotFoundError:
config.write_to_file(CONFIG_PATH)
config = config.read_from_file(CONFIG_PATH)
try: try:
sync_client = behem0th.Client(path=PATH, verbose_log=True) config = config.load(CONFIG_PATH)
except (IOError, ExceptionInConfigError):
config.dump(CONFIG_PATH)
config = config.load(CONFIG_PATH)
try:
ws = Handler(config.server_address) ws = Handler(config.server_address)
# setup has to be called before the connection is established # setup has to be called before the connection is established
ws.setup({"subscribe" : Subscribe(), "hostname" : Hostname(), ws.setup({"subscribe" : Subscribe(), "hostname" : Hostname(),
"processes" : Processes(), "sensor" : Sensor(), "processes" : Processes(), "sensor" : Sensor(),
"identify" : Identify(), "list_programs" : ListPrograms(), "identify" : Identify(), "list_programs" : ListPrograms(),
"whoami" : WhoAmI(), "run_program" : RunProgram(config.output_unbuffer), "whoami" : WhoAmI(), "run_program" : RunProgram(config.output_unbuffer),
"stop_programs" : StopPrograms(), "shutdown" : Shutdown(), "stop_programs" : StopPrograms(), "shutdown" : Shutdown(),
"reboot" : Reboot()}, "reboot" : Reboot(), "binary_received" : BinaryReceived()},
debug=config.debug) debug=config.debug)
ws.connect() ws.connect()
sync_client = SyncClient(path=PATH, verbose_log=config.debug,
event_handler=ws.routes["binary_received"])
sync_client.connect(Utils.get_ip_from_url(config.server_address)) sync_client.connect(Utils.get_ip_from_url(config.server_address))
ws.run_forever() ws.run_forever()
except KeyboardInterrupt: except KeyboardInterrupt:
ws.close() ws.close()
sync_client.close() #sync_client.close()