示例#1
0
    def run(self):
        "Start the server"

        # Just redirects every message logged to the application status object
        # in order to make it available through the web interface
        self.logger.addHandler(PushHandler(self.status.push_log))

        if self.work_queue.use_dfs:
            self.info("Starting Distributed Filesystem")
            self.work_queue.fs.start()

        self.info("Server started on http://%s:%d" % self.addrinfo)
        self.hb_thread.start()
        Server.run(self)
示例#2
0
def application(interface):

    mac = config.get_config('mac')
    server = config.get_config('address')
    place = config.get_config('place')
    chipid = config.get_config('chipid')

    # Temperature sensor device
    import ds18b20 as sensor
    # Now add some configuration params
    for pin in [12, 0, 2]:
        sensor.sensor = sensor.TempSensor(pin=pin,
                                          place=place,
                                          server=server,
                                          chipid=chipid,
                                          mac=mac)
        if sensor.sensor.present:
            print('Found sensor @', pin)
            break

    from register import Register
    rurl = config.get_config('register')
    auth = config.get_config('authorization')
    register = Register(rurl, auth)

    # http Server
    from httpserver import Server
    server = Server(title=place)  # construct server object
    server.activate(8805)  # server activate with port

    # now we introduce the sleep concept
    sleep = config.get_config('sleep')
    try:
        sleep = int(sleep) / 10
    except:
        sleep = 0

    startime = time.time()
    while True:

        # activate and run for a while if returns True we go to sleep
        server.wait_connections(interface)

        T = sensor.sensor.status()
        display.display(T['temp'])

        delta = abs(time.time() - startime)
        if sleep and delta > sleep:
            register.http_post(T)
            from gotosleep import gotosleep
            gotosleep(int(sleep))
        elif delta > 300:
            register.http_post(T)
            startime = time.time()
示例#3
0
def application():

    # Temperature sensor device
    from ds18b20 import sensor, TempSensor
    sensor = TempSensor()

    from register import register, Register
    rurl = config.get_config('register')
    auth = config.get_config('authorization')
    if rurl:
        register = Register(rurl, auth)

    # Pir device
    from pir import pir, PirDevice
    pir = PirDevice()

    # Relaye device
    from relay import relay, Relay
    pin = config.get_config('relay-pin')
    try:
        p = int(pin)
    except:
        p = 14
    relay = Relay(p)

    # The range application
    from ranges import ranges, Ranges
    ranges = Ranges()
    r = config.get_config('ranges')
    if r:
        ranges.set(r)

    # The control
    from control import control, Control
    timeout = config.get_config('timeout')
    if not timeout: timeout = 20
    control = Control(timeout)

    # Http Server
    from httpserver import Server
    server = Server()  # construct server object
    server.activate(8805)  # server activate with

    try:
        server.wait_connections(interface, 0)  # activate and run for a while
        control.loop()
    except KeyboardInterrupt:
        pass
    except Exception as e:
        sys.print_exception(e)
        print(e)
示例#4
0
def main():

    # Enable automatic garbage collector
    gc.enable()

    config.read_config()

    # Get defaults
    ssid = config.get_config('ssid')
    pwd = config.get_config('pwd')

    # Connect to Network and save if
    sta_if = do_connect(ssid, pwd)

    chipid = hexlify(machine.unique_id())
    config.set_config('chipid', chipid)

    # Turn on Access Point only if AP PWD is present
    apssid = 'YoT-%s' % bytes.decode(chipid)
    appwd = config.get_config('appwd')
    do_accesspoint(apssid, appwd)

    # To have time to press ^c
    time.sleep(2)

    # Update config with new values
    # Get Network Parameters
    if sta_if != None:
        (address, mask, gateway, dns) = sta_if.ifconfig()
        config.set_config('address', address)
        config.set_config('mask', mask)
        config.set_config('gateway', gateway)
        config.set_config('dns', dns)
        config.set_config('mac', hexlify(sta_if.config('mac'), ':'))

    # Ok now we save configuration!
    config.set_time()
    config.save_config()

    # Registering
    register_url = config.get_config('register')
    authorization = config.get_config('authorization')
    if register_url != '' and authorization != '':
        from register import register
        # When it starts send a register just to know we're alive
        tim = machine.Timer(-1)
        print('register init 5min')
        tim.init(period=300000,
                 mode=machine.Timer.PERIODIC,
                 callback=lambda t: register(register_url, authorization))

    # Free some memory
    ssid = pwd = None
    apssid = appwd = None
    address = mask = gateway = dns = None
    gc.collect()

    # Launch Server
    from httpserver import Server
    s = Server(8805)  # construct server object
    s.activate()  # server activate with
    try:
        s.wait_connections()  # activate and run
    except KeyboardInterrupt:
        pass
    except Exception:
        machine.reset()
        pass
示例#5
0
    def __init__(self, fconf, handler):
        """
        Initialize a MasterServer instance
        @param fconf the path to the configuration file
        @param handler the handler object in charge of managing HTTP requests
        """
        Logger.__init__(self, "Manager")

        conf = json.load(open(fconf))

        # Jinja2 initialization.
        tmpl_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                 'templates')
        self.env = Environment(loader=FileSystemLoader(tmpl_path))
        self.status = ApplicationStatus()

        # This is a dictionary structure in the form
        # reduce_dict["group-name"] = [
        #   [ file list by unique integers, size in byte
        #   ] => Reduce-0
        #   [
        #   ] => Reduce-1
        # ]
        self.reduce_mark = set()
        self.reduce_dict = defaultdict(list)
        self.dead_reduce_dict = defaultdict(list)

        # This is a dictionary nick => Handler instance
        self.masters = {}
        self.last_id = -1
        self.pending_works = defaultdict(list) # nick => [work, ...]

        self.ping_max = int(conf["ping-max"])
        self.ping_interval = int(conf["ping-interval"])
        self.num_reducer = int(conf["num-reducer"])

        # This will just keep track of the name of the files
        self.reduce_files = []
        self.results_printed = False

        for _ in range(self.num_reducer):
            self.reduce_files.append("N/A")

        # Load the input module and assing the generator to the work_queue
        module = load_module(conf["input-module"])
        cls = getattr(module, "Input", None)

        # Some code for the DFS
        generator = cls(fconf).input()
        self.use_dfs = use_dfs = conf['dfs-enabled']

        if use_dfs:
            dfsconf = conf['dfs-conf']
            dfsconf['host'] = dfsconf['master']

            self.path = conf['output-prefix']
        else:
            dfsconf = None

            self.path = os.path.join(
                os.path.join(conf['datadir'], conf['output-prefix'])
            )

        self.work_queue = WorkQueue(self.logger, generator, use_dfs, dfsconf)

        # Lock to synchronize access to the timestamps dictionary
        self.lock = Lock()
        self.timestamps = {} # nick => (send_ts:enum, ts:float)

        # Ping thread
        self.hb_thread = Thread(target=self.hearthbeat)

        # Event to mark the end of the server
        self.finished = Event()

        self.addrinfo = (conf['master-host'], conf['master-port'])
        Server.__init__(self, self.addrinfo[0], self.addrinfo[1], handler)