Exemplo n.º 1
0
def webServerStart(port):
    global kill_received

    webServer = WebServer(port)
    while not kill_received:
        time.sleep(1)
    webServer.shutdown()
Exemplo n.º 2
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
Exemplo n.º 3
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
Exemplo n.º 4
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')
            }
        })
Exemplo n.º 5
0
        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
Exemplo n.º 6
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
Exemplo n.º 7
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()]
Exemplo n.º 8
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)
Exemplo n.º 9
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()
Exemplo n.º 10
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)
Exemplo n.º 11
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()
Exemplo n.º 12
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()
Exemplo n.º 13
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.")
  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()
Exemplo n.º 15
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()
Exemplo n.º 16
0
import gc, core
from webserver import WebServer
gc.collect()
core.do_connect()
ws = WebServer()
ws.start()
Exemplo n.º 17
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)
Exemplo n.º 18
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:
# -*- 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()
Exemplo n.º 20
0
 def do_activate(self):
     self.server = WebServer(self.object, os.path.dirname(os.path.realpath(__file__)))
     self.server.start()
Exemplo n.º 21
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()
Exemplo n.º 22
0
from timeit import default_timer as timer
from pydispatch import dispatcher
from webserver import WebServer
import subprocess
import time
import random
import math

Web_Server = WebServer()  # Webserver running on BBB for an HTML interface

try:
    import Adafruit_BBIO.GPIO as GPIO
    import Adafruit_BBIO.PWM as PWM
except:
    print "Could not import GPIO library!"

# Hardware Pin defines
# ---------------------------------------
Solenoid1_Pin = "P9_23"
Solenoid2_Pin = "P9_24"

StepperPin0 = "P9_11"
StepperPin1 = "P9_13"
StepperPin2 = "P9_15"
StepperPin3 = "P9_27"
pin_list = [StepperPin0, StepperPin1, StepperPin2, StepperPin3]

# all leds are setup on pwm pins, although not necessary since not all need to fade
LED_Brain_Activity_Pin = "P9_14"
LED_Eye1_Pin = "P9_21"
LED_Eye2_Pin = "P8_13"
Exemplo n.º 23
0
from webserver import WebServer
from camera import Camera
from controller import Controller

if __name__ == '__main__':
    print('Starting camera')
    camera = None
    print('Starting controller')
    controller = Controller(camera=camera, offset=7)
    print('Starting Web Server')
    server = WebServer(camera=camera, controller=controller, log_output=True)
Exemplo n.º 24
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.")
Exemplo n.º 25
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)
    def recv(self, message, ref):
        action = message.get('action', None)

        if action == 'config':
            if self.manager.isrunning:
                self.debug("Reconfiguration process: Shutting down Manager",
                           color='cyan')
                self.manager.shutdown()

            # Initialize manager
            self.debug("Starting up manager", color='blue')
            self.manager.attach(
                WebServer(uuid.uuid4(), 'Local Webserver', self.__commit))
            watchdog_uuid = uuid.uuid4()
            self.manager.attach(Watchdog(watchdog_uuid, 'Watchdog', self))
            self.manager.set_watchdog(watchdog_uuid)

            # Get commit ID
            commit = message.get('commit', None)
            if commit:
                if self.__force_version:
                    self.debug("Using static version: {}".format(
                        self.__force_version),
                               color="cyan")
                else:
                    # Set new commit
                    self.debug("Setting COMMIT to: {}".format(commit),
                               color="cyan")
                    with open("commit.dat", "w") as F:
                        F.write(commit)

                    # Pull changes
                    cmd = "git show --format='%H' --no-patch"  # Long HASH
                    status, output = getstatusoutput(cmd)
                    if status:
                        lastcommit = output
                    else:
                        lastcommit = None

                    if commit != lastcommit:
                        status, output = getstatusoutput("git fetch origin")
                        if status:
                            self.error(
                                "Couldn't fetch changes from REPOSITORY, I won't try any MERGE!"
                            )
                        else:
                            if commit == 'LATEST':
                                extraarg = ''
                            else:
                                extraarg = ' ' + commit
                            status, output = getstatusoutput(
                                "git merge{}".format(extraarg))
                            if status:
                                self.error("Couldn't merge changes!")

            else:
                # Delete commit.dat
                self.warning("This client is not linked to GITHUB")
                if os.path.exists("commit.dat"):
                    os.unlink("commit.dat")

            # Configure hardware
            self.debug("Setting configuration", color='blue')

            error = False
            for hw in message.get('hardware', []):
                # Get details
                uuidtxt = hw.get('uuid', None)
                kind = hw.get('kind', '')
                config = hw.get('config', {})

                if uuidtxt is not None:
                    uid = uuid.UUID(uuidtxt)
                    if not self.manager.exists_worker(uid):
                        self.debug("    > Configuring ",
                                   color='yellow',
                                   tail=False)
                        self.debug(str(uid),
                                   color='purple',
                                   head=False,
                                   tail=False)
                        self.debug(" as ",
                                   color='yellow',
                                   head=False,
                                   tail=False)
                        if kind in self.AVAILABLE_HARDWARE:
                            self.debug(kind, color='white', head=False)
                            try:
                                self.manager.attach(
                                    self.AVAILABLE_HARDWARE.get(kind)(uid,
                                                                      config))
                            except HardwareError as e:
                                self.send_error(
                                    "Device {} as {} is wrong configured: {}".
                                    format(uid, kind, e), ref, uid)
                                error = True
                        else:
                            self.debug(
                                "{}??? - Not setting it up!".format(kind),
                                color='red',
                                head=False)
                else:
                    self.error(
                        "    > I found a hardware configuration without UUID, I will not set it up!"
                    )

            # Make sure all tasks in manager are running
            self.manager.run(self)

            # If some error during startup
            if error:
                self.error(
                    "I have detected some error, I will try to reconfigure system when next message arrives!"
                )
            else:
                # No error happened, we are ready to go
                self.debug("Everything is set up and ready to work",
                           color='green')
                self.__fully_configured = True

        elif action == 'reset':
            self.warning("Got Reset request from Server")
            self.close(reason='Reset requested from Server')
        elif action == 'msg':
            msg = message.get('message', None)
            uid = message.get('uuid', None)
            if msg and uid:
                error = self.manager.recv(msg, ref, uid)
                if error:
                    self.send_error(error, ref)
            elif msg:
                self.send_error("No destination added to your message", ref)
            elif uuid:
                self.send_error("Got message for '{}' with no content", ref)
            else:
                self.send_error(
                    "Missing message and destination for your message", ref)
        elif action == 'error':
            self.error("Got an error from server: {}".format(
                message.get('error', 'No error')))
        elif action == 'ping':
            subref = message.get('ref', '-')
            self.debug("Sending PONG {} (ref:{})".format(subref, ref))
            self.send({'action': 'pong'}, ref)
        elif action != 'config':
            self.send_error("Unknown action '{}'".format(action), ref)

        if action != 'config' and not self.__fully_configured:
            self.debug("Reconfigure system", color='yellow')
            self.send({'action': 'get_config'}, ref)
Exemplo n.º 27
0
import argparse
import config

from webserver import WebServer
from handler import Handler
from config_reader import ConfigReader

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='server')
    parser.add_argument('-r', type=str, help='root directory')
    parser.add_argument('-c', type=int, help='CPU count')
    parser.add_argument('-H', type=int, help='host')
    parser.add_argument('-p', type=str, help='port')

    args = vars(parser.parse_args())
    config_file = ConfigReader(config.config_path)

    cpu_count = args['c'] or config_file.cpu_limit or config.CPU_COUNT
    root_dir = args['r'] or config_file.document_root or config.ROOT_DIR
    host = args['H'] or config_file.host or config.HOST
    port = args['p'] or config_file.listen or config.PORT
    address = (config.HOST, config.PORT)

    handler = Handler(root_dir)
    server = WebServer(cpu_count, address, config.LISTENERS, config.BUFFER,
                       handler)
    server.start()
Exemplo n.º 28
0
                            cwd=os.path.join(current_dir, 'frontend'),
                            shell=True).wait()
    if code != 0:
        print('An error occurred while building!')
        quit(code)

    if os.path.join(current_dir, 'frontend', 'dist') != webserver_static_path:
        shutil.rmtree(webserver_static_path)
        shutil.copytree(os.path.join(current_dir, 'frontend', 'dist'),
                        webserver_static_path)

web = WebServer(
    oauth2_client_id=global_settings['APPLICATION_ID'],
    oauth2_client_secret=global_settings['APPLICATION_SECRET'],
    oauth2_redirect_uri=global_settings['OAUTH2_REDIRECT_URI'],
    webserver_secret=global_settings['WEBSERVER_SECRET'],
    discord_bot=bot,
    static_path=webserver_static_path,
    debug=global_settings['WEBSERVER_DEBUG'],
)

app = web.app

if __name__ == '__main__':
    kwargs = {}
    try:
        port_index = sys.argv[1:].index('--port')
        kwargs['port'] = sys.argv[1:][port_index + 1]
    except ValueError:
        pass
    try:
Exemplo n.º 29
0
def create_server(host='127.0.0.1', port=5000):
    return WebServer((host, port), handlers)
Exemplo n.º 30
0
import util
from webserver import WebServer
from mqttclient import MqttClient
from state import State

try:
    import usocket as socket
except ModuleNotFoundError:
    import socket

state = State()
# Configuration
state.save_value(key='id', value=1)
state.save_value(key='type', value='temperature')

webserver = WebServer()
#webserver.start()
webThread = _thread.start_new_thread(webserver.start, ())

type = state.get_value('type')
if type == 'temperature':
    sensor = sensor.TemperatureSensor()
elif type == 'power':
    sensor = sensor.PowerSensor()
elif type == 'ambient':
    sensor = sensor.AmbientSensor()

webserver.router.set_sensor(sensor)

mqttClient = MqttClient(sensor=sensor)