Beispiel #1
0
 def build(self):
     # self.ws = WebServer("http://192.168.43.150:5000", 1)
     self.screen_manager = ScreenManager()
     if 'MANTENCIONES_VERBOSE' in os.environ:
         verbose=1
     else:
         verbose=0
     if 'DEVELOPMENT_SERVER' in os.environ:
         domain_url='http://192.168.43.150:5000'
         # domain_url='http://192.168.1.39:5000'
     else:
         domain_url='http://kheitmann.webfactional.com'
     self.ws = WebServer(domain_url, verbose)
     self.informe_actual = ""
     self.store = JsonStore('base_de_datos.json')
     if self.store.exists('session'):
         session = self.store.get('session')
         if session['auth_token'] is None:
             print("No hay login")
             self.screen_manager.add_widget(Login(name="login"))
             self.screen_manager.add_widget(Grupos(name="grupos"))
         else:
             print("Si hay login")
             self.ws.set_auth_token(session['auth_token'])
             self.screen_manager.add_widget(Grupos(name="grupos"))
             self.screen_manager.add_widget(Login(name="login"))
     else:
         print("no hay")
         self.store.put('session', auth_token=None)
         self.screen_manager.add_widget(Login(name="login"))
         self.screen_manager.add_widget(Grupos(name="grupos"))
     agregar_screens(self.screen_manager)
     return self.screen_manager
        def build(self):
            self.screen_manager = ScreenManager()
            import os
            if 'MANTENCIONES_VERBOSE' in os.environ:
                verbose=1
            else:
                verbose=0
            if 'DEVELOPMENT_SERVER' in os.environ:
                # domain_url='http://192.168.43.150:5000'
                domain_url='http://192.168.1.39:5000'
            else:
                domain_url='http://kheitmann.webfactional.com'
            from webserver import WebServer
            from kivy.storage.jsonstore import JsonStore
            self.ws = WebServer(domain_url, verbose)
            self.store = JsonStore('base_de_datos.json')

            if self.store.exists('session'):
                session = self.store.get('session')
                if session['auth_token'] is None:
                    print("AUTH TOKEN ES NONE")
                    return None
                else:
                    self.ws.set_auth_token(session['auth_token'])
            else:
                print("NO HAY BASE DE DATOS")
                return None

            self.screen_manager.add_widget(Grupo(name='grupo'))
            self.screen_manager.add_widget(Informe(name='informe'))

            return self.screen_manager
Beispiel #3
0
    def __init__(self):
        # init config reader
        self._config = ConfigMonitor()
        # start debugger
        log.debug(self._config.getVar('logging','dir'))

        # init serverpush
        self._push = Serverpush(self._config.getVar('cluster','host'))

        # basic informations
        info = BasicInformations()

        # register on server
        if self._config.getVar('cluster','id')!='':
            print(self._config.getVar('cluster','id'))
        else:
            log.info("reciving new id")
            response = self._push.push('register',json.dumps(info.getInfo()))

            print(response)


        # start webserver
        s = WebServer(self._config.getVar("webserver","host"),self._config.getVar("webserver","port"))
        s.start()
        pass
Beispiel #4
0
    def __init__(self):
        """Initie les caractéristiques du socket.

        Auteur : Nathan

        """
        self.host = input("Host ? (si vide sera localshost)\n : ")
        if self.host == "":
            self.host = "localhost"
        self.port = 9876
        self.max_size = 2048
        self.client = None

        self.encours = True
        self.attente = False
        self.etat = "None"

        i = input("Voulez vous que ce soit un client websocket ?\n(par défaut = non)\n : ")
        if i.lower() in ["o", "oui", "y", "yes"]:
            self.ws = True
            from webserver import WebServer
            self.webserver = WebServer(self)
        else:
            self.ws = False

        self.genres = ["homme", "femme", "agenre", "androgyne", "bigender",
                       "non-binaire", "autre"]
        self.debug = False
Beispiel #5
0
 def __init__(self, test_mode: bool) -> None:
     super().__init__()
     self.test_mode = test_mode
     handlers = [(r'/socket', RocketSocket, dict(server=self))]
     self.webserver = WebServer(port=8080, handlers=handlers)
     self.source: Inputs = InputTest() if test_mode else InputSerial()
     self.recorders: List[Recorder] = [LogRecorder(), CSVRecorder()]
def webServerStart(port):
    global kill_received

    webServer = WebServer(port)
    while not kill_received:
        time.sleep(1)
    webServer.shutdown()
Beispiel #7
0
def main():
    with open(helper.relative_path('..', 'conf', 'logging_conf.yaml')) as f:
        logging.config.dictConfig(yaml.load(f))

    logger = logging.getLogger('debug')

    loop = asyncio.get_event_loop()
    loop.set_debug(True)

    for sig in (signal.SIGINT, signal.SIGTERM):
        loop.add_signal_handler(sig, loop.stop)

    game = Game(loop, 2, 4, logger=logger)
    colorView = ColorBlendingView(loop, game)
    shelf = IKEAShelf(loop, colorView, logger=logger)

    # consoleView = ConsoleStateView(loop, game, in_place=True)
    
    #     shape = random.choice(list(Shape))
    #     x = random.randrange(self.field.width - len(shape.value))
    #     y = 0
    #     brick = Brick(shape, random.choice(colors), x, y)
    #     brick.gravity_affected = True
    #     self.place_brick(brick)

    server = WebServer(loop=loop, logger=logger)
    server.game = game

    try:
        with server:
            shelf.demo_cycle()
            loop.run_forever()
    finally:
        loop.close()
	def __init__(self, args):
		self.args = args

		self.bus = Bus.Bus(args.serial_device, BAUDRATE, debug=args.bus_debug)
		self.bus.drain()
	
		self.sound = SoundManager({"beep":"beep_short.wav", "beep_end": "beep_end.wav", "error": "error.wav", "defused": "bomb_defused.wav", "explosion": "explosion_02.wav"})

		# check for mastercontrol module
		if not args.ignore_master_control:
			control_description = self.bus.check_for_module(Bus.CONTROL_MODULE)
			if control_description is None:
				raise Exception("no mastercontrol module found!")
			self.bus.init_module(Bus.CONTROL_MODULE, True, "1000A", control_description["num_random"])

		# check other modules
		self.modules = check_existing_modules(self.bus)
		for m in args.disable:
			try:
				self.modules.pop(m)
			except KeyError:
				print("disable module {} which was not enumerated. typo?".format(m))

		if args.mode == "gui":
			self.server = Server("", self.modules)
	
		if args.mode == "webgui":
			self.server = WebServer(("0.0.0.0", 8080), module_descriptions=self.modules)
Beispiel #9
0
    def addWorker(self, color, radius, script, interval, title):
        if (title == "auto"):
            title = str(self.id)
            self.id += 1

        newws = WebServer(color, radius, self, script, interval, title)
        newws.start()
        self.threadList.append(newws)
Beispiel #10
0
	def addWorker(self,color,radius,script,interval,title):
		if(title=="auto"):
			title = str(self.id)
			self.id += 1
			
		newws = WebServer(color,radius,self,script,interval,title)
		newws.start()
		self.threadList.append(newws)
Beispiel #11
0
def main():
    relay_controller = RelayController(vendor_id=VENDOR_ID,
                                       product_id=PRODUCT_ID,
                                       activation_time=ACTIVATION_TIME)
    web_server = WebServer(host=HOST,
                           port=PORT,
                           relay_controller=relay_controller)
    web_server.start()
Beispiel #12
0
    def setup(self):
        self.logger.info("--------------------------------------")
        self.logger.info("   Balloon Mission Computer V4.01     ")
        self.logger.info("--------------------------------------")
        self.logger.debug("setup")
        # setup
        with open('data/config.json') as fin:
            self.config = json.load(fin)
        self.images_dir = self.config["directories"][
            "images"] if "directories" in self.config and "images" in self.config[
                "directories"] else "./images"
        self.tmp_dir = self.config["directories"][
            "tmp"] if "directories" in self.config and "tmp" in self.config[
                "directories"] else "./tmp"

        if not os.path.exists(self.tmp_dir):
            os.makedirs(self.tmp_dir)
        if not os.path.exists(self.images_dir):
            os.makedirs(self.images_dir)

        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)  # Broadcom pin-numbering scheme
        GPIO.setup(self.config['pins']['BUZZER'], GPIO.OUT)
        GPIO.setup(self.config['pins']['LED1'], GPIO.OUT)
        GPIO.setup(self.config['pins']['LED2'], GPIO.OUT)
        GPIO.output(self.config['pins']['LED1'], GPIO.HIGH)

        self.aprs = APRS(self.config['callsign'], self.config['ssid'],
                         "idoroseman.com")
        self.modem = AFSK()
        self.gps = Ublox()
        self.gps.start()
        self.radio = Dorji(self.config['pins'])
        self.radio.init()
        self.radio_q = queue.Queue()
        self.radio_thread = threading.Thread(target=self.radio_worker)
        self.radio_thread.start()
        self.timers = Timers(self.config['timers'])
        self.sensors = Sensors()
        self.cam = Camera()
        self.ssdv = SSDV(self.config['callsign'], self.config['ssid'])
        self.sstv = SSTV()
        self.webserver = WebServer()
        self.radio_queue(self.config['frequencies']['APRS'],
                         'data/boatswain_whistle.wav')

        for item in ["APRS", "APRS-META", "Imaging", 'Capture']:
            self.timers.handle({item: self.config['timers'][item] > 0}, [])
        self.timers.handle({"Buzzer": False}, [])

        self.ledState = 1
        self.imaging_counter = 1
        self.state = "init"
        self.min_alt = sys.maxsize
        self.max_alt = 0
        self.prev_alt = 0
        self.send_bulltin()
        GPIO.output(self.config['pins']['LED1'], GPIO.LOW)
Beispiel #13
0
class MantencionesApp(App):
    def __init__(self, **kwargs):
        super(MantencionesApp, self).__init__(**kwargs)

        Window.bind(on_keyboard=self.Android_back_click)

    def set_informe_actual(self, _informe_actual):
        self.informe_actual = _informe_actual

    def get_informe_actual(self):
        return self.informe_actual

    def build(self):
        # self.ws = WebServer("http://192.168.43.150:5000", 1)
        self.screen_manager = ScreenManager()
        if 'MANTENCIONES_VERBOSE' in os.environ:
            verbose=1
        else:
            verbose=0
        if 'DEVELOPMENT_SERVER' in os.environ:
            domain_url='http://192.168.43.150:5000'
            # domain_url='http://192.168.1.39:5000'
        else:
            domain_url='http://kheitmann.webfactional.com'
        self.ws = WebServer(domain_url, verbose)
        self.informe_actual = ""
        self.store = JsonStore('base_de_datos.json')
        if self.store.exists('session'):
            session = self.store.get('session')
            if session['auth_token'] is None:
                print("No hay login")
                self.screen_manager.add_widget(Login(name="login"))
                self.screen_manager.add_widget(Grupos(name="grupos"))
            else:
                print("Si hay login")
                self.ws.set_auth_token(session['auth_token'])
                self.screen_manager.add_widget(Grupos(name="grupos"))
                self.screen_manager.add_widget(Login(name="login"))
        else:
            print("no hay")
            self.store.put('session', auth_token=None)
            self.screen_manager.add_widget(Login(name="login"))
            self.screen_manager.add_widget(Grupos(name="grupos"))
        agregar_screens(self.screen_manager)
        return self.screen_manager

    def Android_back_click(self,window,key,*largs):
        # Codigo del boton back de android
        if key == 27:
            print("BACK!")
            # self.manager.transition = SlideTransition(direction="right")
            # self.manager.current = 'grupo'
            return True
class Doorman:
  """Main Doorman App for the Raspberry Pi."""

  def __init__(self):
    """Begin the app."""

    web_dir = os.path.join(os.path.dirname(__file__), 'html')
    os.chdir(web_dir)
    print('CWD:', web_dir)

    self.totp = TOTP('supersecretkey32') # Key unique to each user.

    self.fr = FaceRecognition()
    self.fr.set_request_unlock(request_unlock)

    self.server = WebServer(port=8080, ws_port=8081)
    self.server.set_begin_registration(self.begin_registration)
    self.server.set_verify_code(self.verify_code)

    self.requestedUnlock = False

    print('Hello world!')

    self.fr.start_recognition()

  def request_unlock(self):
    """Send request to client to unlock the computer."""
    self.server.request_unlock()
    self.requestedUnlock = True
    time.sleep(30)
    if self.requestedUnlock:
      self.request_lock()
      self.requestedUnlock = False

  def request_lock(self):
    """Send request to client to lock the computer."""
    self.server.request_lock()

  def begin_registration(self):
    """Handler for web request to register new user."""

    print('Registration beginning!')
    # TODO: Replace this with the registration process.

  def verify_code(self, code):
    """
    Handler for web request to verify the given code.

    :param code: The code to verify from the user.
    :return: True if verified successfully, False if invalid.
    """

    is_valid = self.totp.verify_totp(code)

    self.requestedUnlock = False

    if not is_valid:
      request_lock()

    return is_valid
Beispiel #15
0
class TeleMotePlugin(GObject.Object, Peas.Activatable):
    __gtype_name__ = 'TeleMotePlugin'

    object = GObject.property(type=GObject.Object)

    def __init__(self):
        GObject.Object.__init__(self)

    def do_activate(self):
        self.server = WebServer(self.object, os.path.dirname(os.path.realpath(__file__)))
        self.server.start()

    def do_deactivate(self):
        self.server.stop()
Beispiel #16
0
class Server(NetworkServer):
    def __init__(self, test_mode: bool) -> None:
        super().__init__()
        self.test_mode = test_mode
        handlers = [(r'/socket', RocketSocket, dict(server=self))]
        self.webserver = WebServer(port=8080, handlers=handlers)
        self.source: Inputs = InputTest() if test_mode else InputSerial()
        self.recorders: List[Recorder] = [LogRecorder(), CSVRecorder()]

    def on_message(self, data: str) -> None:
        try:
            action = json.loads(data)
            if action.get('action') == 'recorder':
                for recorder in [
                        recorder for recorder in self.recorders
                        if recorder.name() == action.get('recorder')
                ]:
                    recorder.set_enabled(action.get('value', False))
        except Exception as error:
            logging.error(f'Error found {error}')

    def __recorders_to_dict(self) -> Dict[str, bool]:
        result: Dict[str, bool] = {}
        for recorder in self.recorders:
            result[recorder.name()] = recorder.enabled
        return result

    async def run_main(self) -> None:
        rocket_data = RocketData()
        for data in self.source.get_data():
            try:
                rocket_data.update(datastream=data)
                rocket_data.recorders = self.__recorders_to_dict()
                for recorder in (recorder for recorder in self.recorders
                                 if recorder.enabled):
                    recorder.new_data(rocket_data)
                for socket in self.sockets:
                    try:
                        socket.write_message(rocket_data.to_json())
                    except WebSocketClosedError as error:
                        logging.error(f'Connection closed {error}')
                        self.remove_socket(socket)
            except Exception as error:
                logging.error('Could not parse ' + str(error))
            await asyncio.sleep(0.001)

    def run(self) -> None:
        self.webserver.run(callback=self.run_main)
Beispiel #17
0
 def createWebServer(self):
     server = WebServer(self)
     self.m_servers.append(server)
     # :TODO:
     # page.applySettings(self.m_defaultPageSettings)
     # page.libraryPath = os.path.dirname(os.path.abspath(self.m_scriptFile)
     return server
Beispiel #18
0
def main():
    print(open("banner").read())
    print("")

    gyro = GyroMon()
    user = UserMon()
    serial_send = SerialSend(user, gyro)
    gyro.start()
    #user.start()
    serial_send.start()

    raw_input("Press any key to start sending real data\n")

    serial_send.start_real()
    dirname = os.getcwd()
    cherrypy.log.screen = None
    cherrypy.quickstart(
        WebServer(user, gyro, serial_send), '/', {
            'global': {
                'server.socket_host': '0.0.0.0',
                'server.socket_port': 8080
            },
            '/remote.html': {
                'tools.staticfile.on':
                True,
                'tools.staticfile.filename':
                os.path.join(dirname, 'remote/remote.html')
            }
        })
Beispiel #19
0
 def start(self):
     log.startLogging(sys.stdout)
     self.weather = WeatherLogger(self.config.settings)
     self.display = DisplayManager(self.config.settings)
     self.sensors = SensorMonitor(self.config.settings)
     self.server = WebServer(self.config.settings)
     lc = LoopingCall(self.process_event)
     lc.start(0.25)
     reactor.run()
Beispiel #20
0
    def __init__(self,
                 token_path=None,
                 client_creds=None,
                 scope=None,
                 **kwargs):
        """
        Initialize Oauth object.
        The client (the app that is requesting access to the user (user=resource owner) resources on behalf of user.

        Optional args:
		token_path	-	the path to where the user's access/refresh tokens will be stored.
        - client_creds  -   this is a convenience that allows the caller to pass a dict that contains the client_id and client_secret as, or as a string that is the path to a file that contains the client credentials in json format.
        EG:
            # pass a dict:
            oauth = Oauth('/home/user/.user.creds', client_creds=creds_dict)
            or
            # pass a str that's a path to a json file:
            oauth = Oauth('/home/user/.user.creds', client_creds='/home/Downloads/creds_dict')

        The client credentials will then be handled by this module.
        

        TODO:
        - chmod 600 token_path
        - define ONE oauth2.0 server in __init__(), because as far as I can tell, there is only one oauth server...
        """
        if token_path:
            self.token_path = token_path
        else:
            self.token_path = os.path.expanduser(
                '~/.contacts_address_resolution')
        self.webserver = WebServer()
        # Test if a path to the json file that contains the client_id and secret has been passed to init, else, the client params should be passed as key:value pairs to kwargs, which will then be returned as a dict. kwargs.keys() will be tested to ensure that the right values have been passed or an exception will be raised.
        if client_creds:
            if isinstance(client_creds, dict):
                self.client_creds = ClientCredentials(scope=scope,
                                                      **client_creds)
            if isinstance(client_creds, str):
                self.client_creds = ClientCredentials(scope=scope,
                                                      client_file=client_creds)
        elif 'client_id' in kwargs and 'client_secret' in kwargs:
            self.client_creds = ClientCredentials(scope=scope, **kwargs)
        else:
            raise Exception("The client id and secret need to be provided.")
Beispiel #21
0
    def setUp(self):
        self.w = Wallet()

        self.blocks = BlockStorage()
        self.driver = ContractDriver()

        self.ws = WebServer(wallet=self.w,
                            contracting_client=ContractingClient(),
                            blocks=self.blocks,
                            driver=n)
        self.ws.client.flush()
        self.ws.blocks.drop_collections()
  def __init__(self):
    """Begin the app."""

    web_dir = os.path.join(os.path.dirname(__file__), 'html')
    os.chdir(web_dir)
    print('CWD:', web_dir)

    self.totp = TOTP('supersecretkey32') # Key unique to each user.

    self.fr = FaceRecognition()
    self.fr.set_request_unlock(request_unlock)

    self.server = WebServer(port=8080, ws_port=8081)
    self.server.set_begin_registration(self.begin_registration)
    self.server.set_verify_code(self.verify_code)

    self.requestedUnlock = False

    print('Hello world!')

    self.fr.start_recognition()
Beispiel #23
0
def init():
    WLAN(mode=WLAN.AP, ssid='Panel Meter Clock', auth=(None))

    # setup the PWM channels
    App.pwmHours = PWM(0, frequency=5000)
    App.pwmMinutes = PWM(1, frequency=5000)
    App.pwmSeconds = PWM(2, frequency=5000)
    App.pwmChHours = App.pwmHours.channel(0,
                                          pin=HOURS_PANEL_METER_PIN,
                                          duty_cycle=0)
    App.pwmChMinutes = App.pwmMinutes.channel(1,
                                              pin=MINUTES_PANEL_METER_PIN,
                                              duty_cycle=0)
    App.pwmChSeconds = App.pwmSeconds.channel(2,
                                              pin=SECONDS_PANEL_METER_PIN,
                                              duty_cycle=0)

    # push button callback (active HIGH)
    App.pushButton = Pin(PUSH_BUTTON_PIN, Pin.IN)
    set_pin_callback(App.pushButton, push_button_callback)

    # rotary encoder callback
    App.encoderASignal = Pin(ROTARY_ENCODER_A_SIGNAL_PIN,
                             Pin.IN,
                             pull=Pin.PULL_UP)
    set_pin_callback(App.encoderASignal, encoder_a_callback)
    App.encoderBSignal = Pin(ROTARY_ENCODER_B_SIGNAL_PIN,
                             Pin.IN,
                             pull=Pin.PULL_UP)
    set_pin_callback(App.encoderBSignal, encoder_b_callback)

    # initialize the Real Time Clock to the date/time this project was started
    App.rtc.init((2017, 11, 24, 3, 22, 0, 0, 0))

    # create and start the webServer
    App.webServer = WebServer(80, 'index.htm', webserver_request_callback,
                              True)
    App.webServer.start()
Beispiel #24
0
 def do_activate(self):
     self.server = WebServer(self.object, os.path.dirname(os.path.realpath(__file__)))
     self.server.start()
Beispiel #25
0
class BalloonMissionComputer():
    # ---------------------------------------------------------------------------
    def __init__(self):
        if not os.path.exists('tmp/'):
            os.makedirs('tmp/')
        logging.basicConfig(
            format='%(asctime)s %(levelname)s %(name)s: %(message)s',
            level=logging.DEBUG,
            datefmt='%Y-%m-%d %H:%M:%S')
        self.logger = logging.getLogger(__name__)
        hdlr = logging.FileHandler('tmp/program.log')
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S')
        hdlr.setFormatter(formatter)
        self.logger.addHandler(hdlr)

    #---------------------------------------------------------------------------
    def handle_log(self, msg):
        self.webserver.log(msg)

    #---------------------------------------------------------------------------
    def calc_status_bits(self, gpsdata, sensordata):
        bits = [
            True, False, sensordata['cam2'] == "ok",
            sensordata['cam1'] == "ok", gpsdata['status'] == "fix",
            gpsdata['status'] == "lost", gpsdata['status'] == "comm error",
            gpsdata['status'] == "i2c error"
        ]
        return ''.join(['1' if val else '0' for val in bits])

    status_names = [
        'gps i2c err', "gps comm err", "gps no fix", "gps ok", "cam1 ok",
        "cam2 ok"
    ]

    # ---------------------------------------------------------------------------
    def calc_balloon_state(self, gpsdata):
        current_alt = float(gpsdata['alt'])
        if self.state == "init" and current_alt > 0:
            self.state = "ground"
            self.send_bulltin()
        if self.state == "ground" and current_alt > self.min_alt + 2000:
            self.state = "ascent"
            self.send_bulltin()
        if self.state == "ascent" and current_alt < self.max_alt - 2000:
            self.state = "descent"
            self.send_bulltin()
        if self.state == "descent" and current_alt < 2000:
            self.state = "landed"
            self.send_bulltin()
            self.timers.set_state('BUZZER', True)

        if current_alt > self.max_alt:
            self.max_alt = current_alt
        if current_alt > 0 and current_alt < self.min_alt:
            self.min_alt = current_alt
        self.prev_alt = current_alt

    # ---------------------------------------------------------------------------
    def update_system_datetime(self, gpsdata):
        if gpsdata['status'] != "fix":
            return
        if 'date' not in gpsdata:
            return
        now = datetime.datetime.now()
        gpstime = datetime.datetime.strptime(
            gpsdata['date'] + " " + gpsdata['fixTimeStr'], "%d%m%y %H:%M:%S")
        diff = int(abs((now - gpstime).total_seconds() / 60))
        if diff > 100:
            self.logger.info("system time %s" % now)
            self.logger.info("gps time %s" % gpstime)
            self.logger.info("updating")
            #           os.system('date -s %s' % gpstime.isoformat())
            proc = subprocess.Popen(
                ["date", "-s %s" % gpstime.isoformat()],
                stdout=subprocess.PIPE,
                shell=True)
            (out, err) = proc.communicate()
            self.logger.info("program output:" % out)
            self.logger.info("program error:" % err)
            #todo: verify we have premissions

    # ---------------------------------------------------------------------------
    def send_bulltin(self):
        try:
            self.logger.info("state changed to %s" % self.state)
            frame = self.aprs.create_message_msg(
                "BLN1BALON", "changed state to %s" % self.state)
            self.modem.encode(frame)
            self.modem.saveToFile(os.path.join(self.tmp_dir, 'aprs.wav'))
            self.radio_queue(self.config['frequencies']['APRS'],
                             os.path.join(self.tmp_dir, 'aprs.wav'))
        except:
            pass

    # ---------------------------------------------------------------------------
    def capture_image(self, archive=True):
        #        self.logger.debug("capture start")
        self.cam.capture()
        if archive:
            self.cam.archive()
#        self.logger.debug("capture end")

# ---------------------------------------------------------------------------

    def prep_image(self, id, gpsdata, sensordata):
        self.logger.debug("image manutulation start")
        self.cam.select(id)
        self.cam.resize((320, 256))
        self.cam.overlay(self.config['callsign'], gpsdata, sensordata)
        self.cam.saveToFile(os.path.join(self.tmp_dir, "image.jpg"))
        self.logger.debug("image manipulation end")

    # ---------------------------------------------------------------------------
    def process_ssdv(self):
        self.logger.debug("process ssdv start")
        self.logger.debug("jpg->ssdv")
        self.ssdv.convert('tmp/image.jpg', 'tmp/image.ssdv')
        self.logger.debug("ssdv->aprs")
        packets = self.ssdv.prepare(os.path.join(self.tmp_dir, "image.ssdv"))
        self.logger.debug("aprs->wav")
        self.ssdv.encode(packets, 'tmp/ssdv.wav')
        self.timers.trigger("PLAY-SSDV")
        self.logger.debug("process ssdv end")

    # ---------------------------------------------------------------------------
    def process_sstv(self):
        self.logger.debug("process sstv start")
        self.sstv.image = self.cam.image
        self.sstv.process()
        self.sstv.saveToFile(os.path.join(self.tmp_dir, 'sstv.wav'))
        self.timers.trigger("PLAY-SSTV")
        self.logger.debug("process sstv end")

    # ---------------------------------------------------------------------------
    def gps_reset(self):
        self.logger.warning("reset gps")
        GPIO.setup(self.config['pins']['GPS_RST'], GPIO.OUT)
        GPIO.output(self.config['pins']['GPS_RST'], GPIO.LOW)
        time.sleep(1)
        GPIO.output(self.config['pins']['GPS_RST'], GPIO.HIGH)

    # ---------------------------------------------------------------------------
    def setup(self):
        self.logger.info("--------------------------------------")
        self.logger.info("   Balloon Mission Computer V4.01     ")
        self.logger.info("--------------------------------------")
        self.logger.debug("setup")

        # setup files and directories
        with open('data/config.json') as fin:
            self.config = json.load(fin)
        self.images_dir = self.config["directories"][
            "images"] if "directories" in self.config and "images" in self.config[
                "directories"] else "./images"
        self.tmp_dir = self.config["directories"][
            "tmp"] if "directories" in self.config and "tmp" in self.config[
                "directories"] else "./tmp"

        if not os.path.exists(self.tmp_dir):
            os.makedirs(self.tmp_dir)
        if not os.path.exists(self.images_dir):
            os.makedirs(self.images_dir)

        # setup gpio
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)  # Broadcom pin-numbering scheme
        GPIO.setup(self.config['pins']['BUZZER'], GPIO.OUT)
        GPIO.setup(self.config['pins']['LED1'], GPIO.OUT)
        GPIO.setup(self.config['pins']['LED2'], GPIO.OUT)
        GPIO.output(self.config['pins']['LED1'], GPIO.HIGH)

        # modules
        self.aprs = APRS(self.config['callsign'], self.config['ssid'],
                         "idoroseman.com")
        self.modem = AFSK()
        try:
            self.gps = Ublox()
            self.gps.start()
        except:
            pass
        self.radio = Dorji(self.config['pins'])
        self.radio.init()
        self.radio_q = queue.Queue()
        self.radio_thread = threading.Thread(target=self.radio_worker)
        self.radio_thread.start()
        self.timers = Timers(self.config['timers'])
        self.sensors = Sensors()
        self.cam = Camera()
        self.ssdv = SSDV(self.config['callsign'], self.config['ssid'])
        self.sstv = SSTV()
        self.webserver = WebServer()
        self.radio_queue(self.config['frequencies']['APRS'],
                         'data/boatswain_whistle.wav')

        self.syslog = logging.getLogger()
        kh = MyLogHandler()
        kh._listeners.append(self.handle_log)
        kh.setLevel(logging.DEBUG)
        formatter2 = logging.Formatter('%(levelname)s: %(name)s - %(message)s')
        kh.setFormatter(formatter2)
        self.syslog.addHandler(kh)

        # timers
        for item in ["APRS", "APRS-META", "Imaging", 'Capture']:
            self.timers.set_state(item, self.config['timers'][item] > 0)
        self.timers.set_state("Buzzer", False)

        # lets go
        self.ledState = 1
        self.imaging_counter = 1
        self.state = "init"
        self.min_alt = sys.maxsize
        self.max_alt = 0
        self.prev_alt = 0
        self.send_bulltin()
        GPIO.output(self.config['pins']['LED1'], GPIO.LOW)

    # ---------------------------------------------------------------------------
    def run(self):
        self.logger.debug("run")
        telemetry = {}
        telemCoef = {
            'SatCount': 1,
            'outside_temp': 10,
            'inside_temp': 10,
            'barometer': 1,
            'battery': 100
        }
        exitFlag = False
        self.prev_gps_status = ""
        while not exitFlag:
            try:
                # blink
                self.ledState = 1 - self.ledState
                GPIO.output(self.config['pins']['LED1'], GPIO.HIGH)
                watchdog = Watchdog(60)

                # gps
                self.gps.loop()
                gpsdata = self.gps.get_data()
                self.calc_balloon_state(gpsdata)
                if gpsdata['status'] == "fix" and gpsdata['alt'] > 0:
                    self.sensors.calibrate_alt(gpsdata['alt'])
                if gpsdata['status'] != "fix":
                    gpsdata['alt'] = self.sensors.read_pressure()

                # sensors
                sensordata = self.sensors.get_data()
                sensordata.update(self.cam.status)
                status_bits = self.calc_status_bits(gpsdata, sensordata)
                telemetry[
                    'Satellites'] = gpsdata['SatCount'] * telemCoef['SatCount']
                telemetry['outside_temp'] = sensordata[
                    'outside_temp'] * telemCoef['outside_temp']
                telemetry['inside_temp'] = sensordata[
                    'inside_temp'] * telemCoef['inside_temp']
                telemetry['barometer'] = sensordata['barometer'] * telemCoef[
                    'barometer']
                telemetry[
                    'battery'] = sensordata['battery'] * telemCoef['battery']

                if gpsdata['status'] != self.prev_gps_status:
                    frame = self.aprs.create_telem_data_msg(
                        telemetry, status_bits, gpsdata['alt'])
                    self.modem.encode(frame)
                    self.modem.saveToFile(
                        os.path.join(self.tmp_dir, 'aprs.wav'))
                    self.radio_queue(self.config['frequencies']['APRS'],
                                     os.path.join(self.tmp_dir, 'aprs.wav'))
                    self.prev_gps_status = gpsdata['status']

                # UI
                self.webserver.update(gpsdata, sensordata, self.state)
                self.update_system_datetime(gpsdata)

                if self.timers.expired("APRS"):
                    if gpsdata['status'] == "fix":
                        self.logger.debug("sending location")
                        frame = self.aprs.create_location_msg(
                            gpsdata, telemetry, status_bits)
                    else:
                        self.logger.debug("sending only telemetry")
                        frame = self.aprs.create_telem_data_msg(
                            telemetry, status_bits, gpsdata['alt'])
                    self.modem.encode(frame)
                    self.modem.saveToFile(
                        os.path.join(self.tmp_dir, 'aprs.wav'))
                    self.radio_queue(self.config['frequencies']['APRS'],
                                     os.path.join(self.tmp_dir, 'aprs.wav'))
                    with open(os.path.join(self.tmp_dir, "flight.log"),
                              'a+') as f:
                        merged = dict()
                        merged.update(gpsdata)
                        merged.update(sensordata)
                        merged['datatime'] = datetime.datetime.now().isoformat(
                        )
                        f.write(json.dumps(merged, indent=2))
                        f.write(',\n')

                if self.timers.expired("APRS-META"):
                    frame = self.aprs.create_telem_name_msg(
                        telemetry, self.status_names)
                    self.modem.encode(frame)
                    self.modem.saveToFile(
                        os.path.join(self.tmp_dir, 'aprs.wav'))
                    self.radio_queue(self.config['frequencies']['APRS'],
                                     os.path.join(self.tmp_dir, 'aprs.wav'))

                    frame = self.aprs.create_telem_eqns_msg(telemCoef)
                    self.modem.encode(frame)
                    self.modem.saveToFile(
                        os.path.join(self.tmp_dir, 'coef.wav'))
                    self.radio_queue(self.config['frequencies']['APRS'],
                                     os.path.join(self.tmp_dir, 'coef.wav'))

                if self.timers.expired("Capture"):
                    self.capture_image()

                if self.timers.expired("Snapshot"):
                    self.imaging_counter += 1
                    cam_select = self.imaging_counter % CAMERAS
                    self.capture_image(archive=False)
                    self.prep_image(cam_select, gpsdata, sensordata)
                    self.webserver.snapshot()

                if self.timers.expired("Imaging"):
                    self.imaging_counter += 1
                    cam_select = self.imaging_counter % CAMERAS
                    cam_system = self.imaging_counter % (CAMERAS + 1)
                    self.logger.info("imageing trigger")
                    self.logger.debug("cam %s system %s" %
                                      (cam_select, cam_system))
                    self.capture_image(archive=False)
                    self.prep_image(cam_select, gpsdata, sensordata)
                    self.webserver.snapshot()
                    if cam_system == 0:
                        self.logger.info("->sstv")
                        _thread.start_new_thread(self.process_sstv, ())
                    else:
                        self.logger.info("->ssdv")
                        _thread.start_new_thread(self.process_ssdv, ())

                if self.timers.expired("PLAY-SSDV"):
                    self.logger.debug("sending ssdv")
                    self.radio_queue(self.config['frequencies']['APRS'],
                                     os.path.join("data", 'starting_ssdv.wav'))
                    self.radio_queue(self.config['frequencies']['APRS'],
                                     os.path.join("data", 'habhub.wav'))
                    self.radio_queue(self.config['frequencies']['APRS'],
                                     os.path.join(self.tmp_dir, 'ssdv.wav'))

                if self.timers.expired("PLAY-SSTV"):
                    self.logger.debug("sending sstv")
                    self.radio_queue(
                        self.config['frequencies']['APRS'],
                        os.path.join("data", 'switching_to_sstv.wav'))
                    self.radio_queue(self.config['frequencies']['SSTV'],
                                     os.path.join("data", 'starting_sstv.wav'))
                    self.radio_queue(self.config['frequencies']['SSTV'],
                                     os.path.join(self.tmp_dir, 'sstv.wav'))

                if self.timers.expired("Buzzer"):
                    for i in range(3):
                        GPIO.output(self.config['pins']['BUZZER'], GPIO.HIGH)
                        time.sleep(0.5)
                        GPIO.output(self.config['pins']['BUZZER'], GPIO.LOW)
                        time.sleep(0.5)

                GPIO.output(self.config['pins']['LED1'], GPIO.LOW)
                watchdog.stop()
                time.sleep(1)

            except Watchdog:
                self.logger.error("task timedout!")
            except KeyboardInterrupt:  # If CTRL+C is pressed, exit cleanly
                exitFlag = True
                self.gps.stop()
                break
            except Exception as x:
                self.logger.exception(x)
        self.logger.info("Done.")

    # ---------------------------------------------------------------------------
    def radio_queue(self, freq, filename):
        self.radio_q.put({'freq': freq, 'filename': filename})

    # ---------------------------------------------------------------------------
    def radio_worker(self):
        while True:
            item = self.radio_q.get()
            self.radio.play(item['freq'], item['filename'])
            self.radio_q.task_done()
Beispiel #26
0
    def setup(self):
        self.logger.info("--------------------------------------")
        self.logger.info("   Balloon Mission Computer V4.01     ")
        self.logger.info("--------------------------------------")
        self.logger.debug("setup")

        # setup files and directories
        with open('data/config.json') as fin:
            self.config = json.load(fin)
        self.images_dir = self.config["directories"][
            "images"] if "directories" in self.config and "images" in self.config[
                "directories"] else "./images"
        self.tmp_dir = self.config["directories"][
            "tmp"] if "directories" in self.config and "tmp" in self.config[
                "directories"] else "./tmp"

        if not os.path.exists(self.tmp_dir):
            os.makedirs(self.tmp_dir)
        if not os.path.exists(self.images_dir):
            os.makedirs(self.images_dir)

        # setup gpio
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)  # Broadcom pin-numbering scheme
        GPIO.setup(self.config['pins']['BUZZER'], GPIO.OUT)
        GPIO.setup(self.config['pins']['LED1'], GPIO.OUT)
        GPIO.setup(self.config['pins']['LED2'], GPIO.OUT)
        GPIO.output(self.config['pins']['LED1'], GPIO.HIGH)

        # modules
        self.aprs = APRS(self.config['callsign'], self.config['ssid'],
                         "idoroseman.com")
        self.modem = AFSK()
        try:
            self.gps = Ublox()
            self.gps.start()
        except:
            pass
        self.radio = Dorji(self.config['pins'])
        self.radio.init()
        self.radio_q = queue.Queue()
        self.radio_thread = threading.Thread(target=self.radio_worker)
        self.radio_thread.start()
        self.timers = Timers(self.config['timers'])
        self.sensors = Sensors()
        self.cam = Camera()
        self.ssdv = SSDV(self.config['callsign'], self.config['ssid'])
        self.sstv = SSTV()
        self.webserver = WebServer()
        self.radio_queue(self.config['frequencies']['APRS'],
                         'data/boatswain_whistle.wav')

        self.syslog = logging.getLogger()
        kh = MyLogHandler()
        kh._listeners.append(self.handle_log)
        kh.setLevel(logging.DEBUG)
        formatter2 = logging.Formatter('%(levelname)s: %(name)s - %(message)s')
        kh.setFormatter(formatter2)
        self.syslog.addHandler(kh)

        # timers
        for item in ["APRS", "APRS-META", "Imaging", 'Capture']:
            self.timers.set_state(item, self.config['timers'][item] > 0)
        self.timers.set_state("Buzzer", False)

        # lets go
        self.ledState = 1
        self.imaging_counter = 1
        self.state = "init"
        self.min_alt = sys.maxsize
        self.max_alt = 0
        self.prev_alt = 0
        self.send_bulltin()
        GPIO.output(self.config['pins']['LED1'], GPIO.LOW)
Beispiel #27
0
# Module name : main.py
# created by alvifsandanamahardika at 6/10/21
import signal
import sys

from webserver import WebServer


def shutdownServer(sig, unused):
    """
    Shutdown server from a SIGINT received signal
    :param sig: integer
    """
    server.shutdown()
    sys.exit(1)


if __name__ == '__main__':
    signal.signal(signal.SIGINT, shutdownServer)
    server = WebServer(8000)
    server.start()
    print("Press Ctrl+C to shut down server.")
Beispiel #28
0
import gc, core
from webserver import WebServer
gc.collect()
core.do_connect()
ws = WebServer()
ws.start()
Beispiel #29
0
    "server-network",
    resource_group_name=resource_group.name,
    location=resource_group.location,
    address_spaces=["10.0.0.0/16"],
    subnets=[
        network.VirtualNetworkSubnetArgs(name="default",
                                         address_prefix="10.0.1.0/24")
    ],
    opts=ResourceOptions(parent=resource_group),
)

subnet = network.Subnet(
    "server-subnet",
    resource_group_name=resource_group.name,
    virtual_network_name=net.name,
    address_prefixes=["10.0.2.0/24"],
    opts=ResourceOptions(parent=net),
)

web_server = WebServer(
    "server",
    WebServerArgs(
        resource_group=resource_group,
        subnet=subnet,
        username=username,
        password=password,
    ),
)

pulumi.export("public_ip", web_server.public_ip_addr)
Beispiel #30
0
    logger.setLevel(logging.DEBUG)
    formatter = '%(asctime)s %(module)s(%(lineno)s):%(funcName)s [%(levelname)s]: %(message)s'
    streamhandler = logging.StreamHandler()
    streamhandler.setFormatter(logging.Formatter(formatter, datefmt='%H:%M:%S'))
    streamhandler.setLevel(logging.DEBUG)
    logger.addHandler(streamhandler)
    logger.debug('Session start')

    mpqueue = MPQueue()  # queue for multiprocessing
    threadqueue = ThreadQueue()  # queue for threading
    aqueue = MPQueue()  # for archiver

    ws = WSServer(port=Constants.wsport)
    ws.start()

    wd = WebServer(name='Flask')
    wd.start()

    serialReceiver: Dict[str, dict] = {
        'sGPS': {
            'port': '/dev/ttyACM0',
            'baud': 9600,
        },
        'sAIS': {
            'port': '/dev/ttyUSB0',
            'baud': 38400,
        },
    }
    for k, v in serialReceiver.items():
        receiver = Receiver(port=v['port'], baud=v['baud'], mailpost=mpqueue, name=k)
        if receiver.ready:
Beispiel #31
0
webbox_dir = os.path.expanduser('~'+os.sep+".webbox")
setup = WebBoxSetup()
setup.setup(webbox_dir, "webbox.json.default", kbname) # directory, default config, kbname


# load configuration into 'config' variable
webbox_config = webbox_dir + os.sep + "webbox.json"
conf_fh = open(webbox_config, "r")
config = json.loads(conf_fh.read())
conf_fh.close()

# add the webbox path to the config (at runtime only)
config['webbox']['webbox_dir'] = webbox_dir

# add additional binary paths to the PATH
for bindir in config['server']['bindirs']:
    os.environ['PATH'] = os.path.join(os.path.dirname(__file__), bindir) + ":" + os.environ['PATH']

# show debug messages in log file
log_handler = logging.FileHandler(config['server']['log'], "a")
log_handler.setLevel(logging.DEBUG)
logger = logging.getLogger() # root logger
logger.addHandler(log_handler)
logger.debug("Logger initialised")
logger.setLevel(logging.DEBUG)

wb = WebBox(config['webbox'])
server = WebServer(config['server'], os.path.dirname(__file__), wb)
server.run()

Beispiel #32
0
    config_AP_PASSWORD = '******'
    config_AP_CHANNEL = 7
    config_AP_ON_TIME_SEC = 600
    config_FTP_USER = '******'
    config_FTP_PASSWORD = '******'
    config_WEB_USER = '******'
    config_WEB_PASSWORD = '******'
    config_ERROR = True

if config_AP_ON_TIME_SEC < 120:
    config_AP_ON_TIME_SEC = 120

_ftp = Server()
_ftp.deinit()

_web = WebServer(config_WEB_USER, config_WEB_PASSWORD)

if not config_ERROR and (len(config.MB_TCP_IP) > 0):
    _wdt = machine.WDT(timeout=20000)
    _status_ap_enabled_once = False
    _status_mb_got_request = False

    _modbus = ModbusTCP()
    print('ModbusTCP created')
    _modbus_process = _modbus_tcp_process

    pycom.heartbeat(False)
    pycom.rgbled(0x00ff00)

    #_modbus_process()
def main():
    ws = WebServer()
    ws.run()
class Gamemaster():
	def __init__(self, args):
		self.args = args

		self.bus = Bus.Bus(args.serial_device, BAUDRATE, debug=args.bus_debug)
		self.bus.drain()
	
		self.sound = SoundManager({"beep":"beep_short.wav", "beep_end": "beep_end.wav", "error": "error.wav", "defused": "bomb_defused.wav", "explosion": "explosion_02.wav"})

		# check for mastercontrol module
		if not args.ignore_master_control:
			control_description = self.bus.check_for_module(Bus.CONTROL_MODULE)
			if control_description is None:
				raise Exception("no mastercontrol module found!")
			self.bus.init_module(Bus.CONTROL_MODULE, True, "1000A", control_description["num_random"])

		# check other modules
		self.modules = check_existing_modules(self.bus)
		for m in args.disable:
			try:
				self.modules.pop(m)
			except KeyError:
				print("disable module {} which was not enumerated. typo?".format(m))

		if args.mode == "gui":
			self.server = Server("", self.modules)
	
		if args.mode == "webgui":
			self.server = WebServer(("0.0.0.0", 8080), module_descriptions=self.modules)
	
	def get_game_info(self):
		if self.args.mode == "standalone":
			print("waiting 5s for game start...")
			time.sleep(5)
			return self.get_game_info_standalone()

		elif self.args.mode in ("gui", "webgui"):
			# wait for "start" command
			while(True):
				if self.server._CheckForMessage():
					msg = self.server._PopMessage()
					if "start" in msg:
						d=msg["start"]
						return (d["seconds"], d["maxerrors"], d["serial"], d["modules"])
				else:
					print("waiting for start command...")
					time.sleep(0.5)
		else:
			raise NotImplementedError()

	def get_game_info_standalone(self):
		serial_number = str(self.args.difficulty) + str(random.randrange(0, 99)).zfill(2) + chr(0x41+random.randrange(0, 26))
		used_modules = random.sample(self.modules, self.args.num_modules)

		module_states = {m: {"enabled":m in used_modules, "random":[random.randrange(0,256) for i in range(self.modules[m]["num_random"])]} for m in self.modules}

		return (self.args.time, self.args.max_errors, serial_number, module_states)

	def should_abort(self):
		if self.args.mode in ("gui", "webgui"):
			if self.server._CheckForMessage():
				msg = self.server._PopMessage()
				if "abort" in msg:
					return True
			return False
		else:
			return False

	def explode(self):
		self.sound["explosion"].play()
		print("BOOOM!")
		self.cleanup_after_game()

	def win(self):
		self.sound["defused"].play()
		print("BOMB HAS BEEN DEFUSED!")
		self.cleanup_after_game()
	
	def cleanup_after_game(self):
		if self.args.mode == "standalone":
			print("game over, shutting down")
			sys.exit(0)

	def start_game(self):
		game_info = self.get_game_info()
		print(game_info)
		seconds, max_errors, serial_number, module_states = game_info
		# init all normal modules
		for m, state in module_states.iteritems():
			self.bus.init_module(m, state["enabled"], serial_number, state["random"])

		# wait for start switch on control panel
		"""
		if not args.ignore_control_module:
			bus.start_game(Bus.CONTROL_MODULE)
			while(True):
				continue_waiting, _ = bus.poll_status(Bus.CONTROL_MODULE)
				if not continue_waiting:
					break
		"""

		num_active_modules = sum(state["enabled"] for state in module_states.values())

		
		for m in module_states:
			self.bus.start_game(m)
		explosion_time = time.time() + seconds
		beeptimes = make_beep_times(seconds)
		next_beep_index = 0

		last_time_left = seconds
		last_num_lifes = max_errors

		while True:
			state = {"modules": {}}

			num_lifes = max_errors
			defused = 0
			for m in module_states:
				success, module_failures = self.bus.poll_status(m)
				state["modules"][m] = {"state": success, "failures": module_failures}
				if success in [0,1]:
					num_lifes -= module_failures
					if success:
						print("defused module. success = {}".format(success))
						defused += 1
				else:
					if self.args.mode == "standalone":
						raise Exception("state error in module {}: {} ({})".format(m, parse_errorcode_from_cpp("../../modules/libraries/BUMMSlave/BUMMSlave.cpp", success), module_failures))

			time_left = int(explosion_time - time.time())

			# SOUNDS
			# make countdown sounds
			if ( explosion_time - time.time() ) < self.sound["beep_end"].get_length():
				self.sound["beep_end"].play()
			elif ( explosion_time - time.time() ) < beeptimes[next_beep_index]:
				next_beep_index += 1
				self.sound["beep"].play()

			if last_num_lifes != num_lifes and num_lifes >= 0:
				self.sound["error"].play()


			# BROADCAST STATE

			state["seconds"] = time_left
			state["lifes"] = num_lifes if num_lifes >= 0 else 0

			if last_time_left != time_left or last_num_lifes != num_lifes:
				print(time_left)
				self.bus.broadcast_status(time_left, num_lifes)
				last_time_left = time_left
				last_num_lifes = num_lifes

				if self.args.mode in ("gui", "webgui"):
					self.server.send_game_update(state)

			# GAME END CONDITIONS
			# countdown over?
			if time_left <= 0:
				print("no time left")
				if self.args.mode in ("gui", "webgui"):
					self.server.send_game_end(reason=1)
				self.bus.end_game(1)
				time.sleep(1)
				self.explode()
				break

			# too many failures?
			if num_lifes < 0:
				print("too many failures!")
				if self.args.mode in ("gui", "webgui"):
					self.server.send_game_end(reason=2)
				self.bus.end_game(2)
				self.explode()
				break

			# defused?
			if defused == num_active_modules:
				if self.args.mode in ("gui", "webgui"):
					self.server.send_game_end(reason=0)
				self.bus.end_game(0)
				self.win()
				break

			if self.should_abort():
				if self.args.mode in ("gui", "webgui"):
					self.server.send_game_end(reason=3)
				self.bus.end_game(3)
				self.cleanup_after_game()
				break
Beispiel #35
0
class Client:
    """Classe principale du client.

    Attributes:
        host(str): IP de la machine à laquelle se connecter.
        port(int): Port utilisé par le socket
        max_size(int): Taille maximale d'un message en bits
        client(socket): socket.socket

    """

    def __init__(self):
        """Initie les caractéristiques du socket.

        Auteur : Nathan

        """
        self.host = input("Host ? (si vide sera localshost)\n : ")
        if self.host == "":
            self.host = "localhost"
        self.port = 9876
        self.max_size = 2048
        self.client = None

        self.encours = True
        self.attente = False
        self.etat = "None"

        i = input("Voulez vous que ce soit un client websocket ?\n(par défaut = non)\n : ")
        if i.lower() in ["o", "oui", "y", "yes"]:
            self.ws = True
            from webserver import WebServer
            self.webserver = WebServer(self)
        else:
            self.ws = False

        self.genres = ["homme", "femme", "agenre", "androgyne", "bigender",
                       "non-binaire", "autre"]
        self.debug = False

    def debut(self):
        """Demande si l'on veut s'inscrire ou se connecter.

        Auteur : Nathan

        """
        print("Voulez vous :\n  1) Vous inscrire ?\n  2) Vous connecter ?")
        r = input(": ")
        while not (r in ["1", "2"]):
            r = input(": ")
        if r == "1":
            self.inscription()
        else:
            self.connexion()

    def attente_serv(self, aff=True, aff_rec=False):
        """Attends la réception d'un message.

        Quand le message a été reçu, on peut continuer le thread actuel

        Auteur : Nathan

        """
        self.attente = True
        if aff:
            print("\nEn attente du serveur ...\n")
        while self.attente:
            pass
        if aff_rec:
            print("Serveur recu...")

    def connexion(self):
        """Demande les informations pour se connecter.

        Auteur : Nathan

        """
        print("\nConnection :\n")
        # pseudo
        pseudo = input("pseudo : ")
        while test_pseudo(pseudo):
            pseudo = input("pseudo : ")
        # password
        password = input("mot de passe : ")
        while test_password(password):
            password = input("mot de passe : ")
        self.send(json.dumps({"type": "connection", "pseudo": pseudo,
                              "password": password}))
        # on attend la réponse du serveur
        self.attente_serv()
        if self.etat == "connecté":
            # print("Connecté")
            self.interface()
        elif self.etat == "creation_perso":
            data_perso = self.creation_perso()
            self.send(json.dumps(data_perso))
            self.interface()
        else:
            self.debut()

    def inscription(self):
        """Demande les informations pour s'inscrire.

        Auteur : Nathan

        """
        print("\nInscription :\n")
        # email
        email = input("email : ")
        while test_email(email):
            email = input("email : ")
        # pseudo
        pseudo = input("pseudo : ")
        while test_pseudo(pseudo):
            pseudo = input("pseudo : ")
        # password
        password = input("mot de passe : ")
        while test_password(password):
            password = input("mot de passe : ")
        password_confirm = input("mot de passe (confirmation) : ")
        if password_confirm != password:
            print("ERREUR /!\\ Les mots de passes sont différents !")
            self.debut()
        else:
            # on peut envoyer les infos
            self.send(json.dumps({"type": "inscription", "pseudo": pseudo,
                                  "password": password, "email": email}))
            # on attend la réponse du serveur
            self.attente_serv()
            if self.etat == "connecté":
                # on recevra un autre
                self.attente_serv()
                if self.etat == "creation_perso":
                    data_perso = self.creation_perso()
                    self.send(json.dumps(data_perso))
                    self.interface()
                else:
                    print("erreur inconnue ...")
                    self.debut()
            else:
                self.debut()

    def send(self, message, important=False):
        """Permet d'envoyer un message.

        Args:
            message(str): Le message à envoyer au serveur

        Auteur : Nathan

        """
        message = message.encode(encoding="utf-8")
        size = sys.getsizeof(message)
        if size > self.max_size:
            if important:
                raise UserWarning(f"ERREUR : Le message est trop long ! "
                                  "{str(size)} / {str(self.max_size)} bytes")
            print(f"""ERREUR : Le message est trop long ! {str(size)} bytes/
                    {str(self.max_size)} bytes""")
        else:
            self.client.send(message)

    def start(self):
        """Démarre la connexion au serveur.

        Connexion avec le protocole TCP/IP, utilisation d'un thread pour la
        fonction `handle()` afin de ne pas encombrer le thread principal.

        Auteur : Nathan

        """
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client.connect((self.host, self.port))
        _thread.start_new_thread(self.handle, ())

    def handle(self):
        """Gère les messages reçus.

        Auteur : Nathan

        """
        self.on_connect()
        while True:
            try:
                msg = self.client.recv(self.max_size)
                msg = msg.decode(encoding="utf-8")
                if self.debug:
                    print("recu : ", msg)
                #
                if len(msg) == 0:
                    raise UserWarning("message vide")
                if not self.ws:
                    self.on_message(msg)
                else:
                    loop = asyncio.new_event_loop()
                    asyncio.set_event_loop(loop)
                    loop.run_until_complete(self.webserver.on_message(msg))
            except Exception as e:
                print(e)
                self.on_close()
                return

    def on_connect(self):
        """Réaction si la connexion est acceptée."""
        pass

    def on_message(self, mess):
        """Réaction si un message est reçu.

        Args:
            mess(str): Le message reçu

        Auteur : Nathan

        """
        if is_json(mess):
            data = json.loads(mess)
            while type(data) == str:
                if is_json(data):
                    data = json.loads(data)
                else:
                    return
            if type(data) != dict:
                return
            #
            if data["type"] == "connection successed":
                print("Connection acceptée")
                self.etat = "connecté"
                self.attente = False
            #
            elif data["type"] == "connection successed but creation perso":
                print("Connection acceptée, mais il faut créer un nouveau perso")
                self.etat = "creation_perso"
                self.attente = False
            #
            elif data["type"] == "inscription successed":
                print("Inscription acceptée")
                self.etat = "connecté"
                self.attente = False
            #
            elif data["type"] == "connection failed":
                print("Connection refusée\nerreur : " + data["value"])
                self.attente = False
            #
            elif data["type"] == "inscription failed":
                print("Inscription refusée\nerreur : " + data["value"])
                self.attente = False
            #
            elif data["type"] == "creation perso":
                # print("creation perso")
                self.etat = "creation_perso"
                self.attente = False
            #
            elif data["type"] == "genres":
                self.genres = json.loads(data["genres"])
            #
            elif data["type"] == "close":
                self.on_close()
            #
            elif data["type"] == "mort":
                txt = """Vous êtes mort.
Tout votre équipement a été posé la ou vous êtes mort
Le perso est mort, et sera supprimé
Votre compte ne sera pas supprimé, vous pouvez toujours vous y connecter,
Vous devrez d'ailleur à la prochaine connection recréer un perso.

Le client va se fermer, si vous voulez continuer a jouer a ce formidable jeu,
Et bien, bah, relancez le client...

                """
                input(txt)
                self.encours = False
                exit()
            #
            elif data["type"] == "message":
                print("\n" + str(data["value"]) + "\n")

    def on_close(self):
        """Réaction en cas de fermeture/problème.

        Auteur : Nathan

        """
        self.encours = False
        print("connection fermée")
        input("appuyer pour fermer le client du jeu...")
        exit()

    def test_nom(self, nom):
        """Teste si un nom est dans le bon format

        Auteur : Léa

        """
        if len(nom) < 2:
            return "Le nom doit avoir au minimum 2 lettres !"
        elif len(nom) > 20:
            return "Le nom doit avoir au maximum 20 lettres !"

    def creation_perso(self):
        """Demande les informations pour créer un personnage.

        Auteur : Léa

        """
        data_perso = {"type": "perso_cree", "nom": None, "race": None,
                      "classe": None, "genre": None}

        lst_classes = {
            "guerrier": "Un guerrier sait se battre au corps à corps, il est fort et il porte facilement tout type d'armure",
            "archer": "Un archer sait se battre à distance, et est plutôt agile",
            "prêtre": "Un prêtre excelle dans les sorts de soutiens, mais n'est pas très bon en attaque",
            "mage noir": "Un mage noir excelle dans la sorcellerie maudite, il peut invoquer des créatures ou contrôler des cadavres",
            "mage guerrier": "Un mage guerrier est équilibré dans les combats aux corps à corps et la maîtrise des sorts de combat",
            "assassin": "Un assassin est habile et précis, il rate peu et esquive beaucoup, mais n'est pas très fort physiquement",
            "voleur": "Un voleur est habile et esquive beaucoup, il peut voler des PNJ et des ennemis",
            "paladin": "Un paladin est un guerrier qui connaît des sorts de soutien, il peut à la fois se battre et soigner ses alliés",
            "barbare": "Un barbare est un guerrier qui a vécu loin de la société civilisé, il se bat avec son instinct animal, et peut même devenir un berseker",
            "tank": "Un tank est un guerrier spécialisé dans la défense, il défend ses alliés et encaisse les gros dégats à leurs place, mais en contrepartie il ne fait pas beaucoup de dégâts en attaque."
        }
        lst_races = {
            "humain": "Les humains sont la race la plus présente sur la planète, ils sont équilibrés",
            "drakonien": "Les drakôniens sont des créatures mi-homme mi-dragon, ils ont une peau solide, et ont des facilités pour lancer des sorts de feu. Ils ont une apparence humaine en tant normal (même s'ils ont un bien meilleur physique que les humains ordinaires), mais ont une forme plus draconienne lors des combats",
            "elfe": "Les elfes sont les habitants de la forêt, ils ressemblent aux humains, mais ont des oreilles pointues, une peau plus verte pâle, et ont une bien meilleure longévité que les humains. Faible contre le feu, ils ont néanmoins une bonne habilité",
            "elfe noir": "Les elfes noirs sont des elfes qui sont tombés du côté obscur, ils ont une connaissance des sortilèges maudits, n'ont pas de faiblesses contre le feu comme les autres elfes, mais sont vulnérables face aux sortilèges bénis",
            "demi-elfe": "Les demi-elfes sont des enfants d'homme et d'elfe. Pourquoi pas demi-humain à ce moment ? C'est comme ça.",
            "orc": "Les orcs ne sont pas très intelligents, ni habiles. Par contre, ils sont forts et résistants.",
            "nain": "Les nains sont forts et résistants, mais peu habiles. Leurs terrains de prédilection sont grottes et les montagnes.",
            "fée": "Les fées sont des créatures magiques plutôt faibles physiquement, mais qui ont beaucoup d'affinité avec la magie. Normal pour des créatures magique en fait, j'imagine..."
        }
        lst_genres = self.genres
        print("Création du personnage : \n")
        # nom
        print("Quel est le nom de votre personnage ?\n")
        nom = input("nom : ")
        erreur = self.test_nom(nom)
        while erreur:
            print("ERREUR /!\\ : " + erreur)
            nom = input("nom : ")
        data_perso["nom"] = nom

        # On affiche les races
        print("\n\nRaces Disponibles : \n")
        for n, d in lst_races.items():
            print(f"  - {n} : {d}\n")
        # race
        print("\nQuel est la race de votre personnage ?\n")
        race = input("race : ")
        while race.lower() not in lst_races.keys():
            print("ERREUR /!\\ : La race n'est pas dans la liste !")
            race = input("race : ")
        data_perso["race"] = race

        # On affiche les classes
        print("\n\nClasses Disponibles : ")
        for n, d in lst_classes.items():
            print(f"  - {n} : {d}\n")
        # classe
        print("\nQuel est la classe de votre personnage ?\n")
        classe = input("classe : ")
        while classe.lower() not in lst_classes.keys():
            print("ERREUR /!\\ : La classe n'est pas dans la liste !")
            classe = input("classe : ")
        data_perso["classe"] = classe

        # On affiche les genres :
        print("\nGenres : ")
        for g in lst_genres + ["autre"]:
            print(f"  - {g}")
        # genre
        print("Quel est le genre de votre personnage ?")
        genre = input("genre : ")
        data_perso["genre"] = genre
        return data_perso

    def interface(self):
        """Permet à l'utilisateur d'écrire et d'envoyer des messages.

        Auteur : Nathan

        """
        while self.encours:
            txt = input("")
            # si le jeu a été quitté pendant l'input
            if not self.encours:
                return
            t = txt.split(" ")
            if len(t) >= 1:
                if txt.startswith("/cheat "):
                    a = " ".join(t[1:])
                    dict_ = {"type": "cheat_code", "commande": a}
                    self.send(json.dumps(dict_))
                else:
                    c = t[0]
                    a = " ".join(t[1:])
                    dict_ = {"type": "commande", "commande": c, "arguments": a}
                    self.send(json.dumps(dict_))

    def main(self):
        """Fonction principale du client.

        Auteur : Nathan

        """
        self.start()

        if not self.ws:
            self.debut()
        else:
            self.webserver.main()
# -*- coding: utf-8 -*-
from time import sleep

from webserver import WebServer


class mydataclass(object):
    def __init__(self):
        self.param1 = 0
        self.param2 = 0


#MAIN LOOP
try:
    mydata = mydataclass()
    myWebServer = WebServer(mydata)
    myWebServer.start()

    cycling = True
    while cycling:
        #In the mail loop , do something, for example  increment param2
        #and do some verificationon param1
        mydata.param2 += 1
        sleep(1)
        if mydata.param1 < 0:
            print 'param1 is negative...'
        if mydata.param1 == 5:
            #parameter param1 is incremented by the user on the browser
            cycling = False

    myWebServer.stop()
Beispiel #37
0
def create_server(host='127.0.0.1', port=5000):
    return WebServer((host, port), handlers)
Beispiel #38
0
def main():
    wb = WebServer()
    wb.run()