Example #1
0
def start(args):
    """
    Create all required interfaces and start the application.
    """

    args = vars(args)
    log.debug('Command line arguments: %s' % args)
    init(**args)

    if args.get('create_user'):
        db.users.insert({
            'username': args.get('create_user'),
            'hash': sha.sha(getpass.getpass()).hexdigest()
        })
        return

    log.info('Starting alfred {0}'.format(__version__))
    signal.signal(signal.SIGINT, signalHandler)

    # Starting all the stuffs
    manager.start()
    # persistence.start()
    ruleHandler.loadRules(os.path.join(os.path.dirname(__file__), 'rules'))
    ruleHandler.start()

    # Sends heartbeats
    sys.startTime = time.asctime()
    signal.signal(signal.SIGALRM, heartbeat)
    heartbeat(signal.SIGALRM, None)

    # Let's have an interface :)
    webserver.start(args.get('client_path'))
Example #2
0
def start(args):
    """
    Create all required interfaces and start the application.
    """

    args = vars(args)
    log.debug('Command line arguments: %s' % args)
    init(**args)

    if args.get('create_user'):
        db.users.insert({'username': args.get(
            'create_user'), 'hash': sha.sha(getpass.getpass()).hexdigest()})
        return

    log.info('Starting alfred {0}'.format(__version__))
    signal.signal(signal.SIGINT, signalHandler)

    # Starting all the stuffs
    manager.start()
    # persistence.start()
    ruleHandler.loadRules(os.path.join(os.path.dirname(__file__), 'rules'))
    ruleHandler.start()

    # Sends heartbeats
    sys.startTime = time.asctime()
    signal.signal(signal.SIGALRM, heartbeat)
    heartbeat(signal.SIGALRM, None)

    # Let's have an interface :)
    webserver.start(args.get('client_path'))
Example #3
0
def main():
    logger.info('Starting rpi-car-server')

    try:
        ext.load_extensions()
        webserver.start()
        return 1
    except KeyboardInterrupt:
        pass
    except Exception as ex:
        logger.exception(ex)
        raise
def main():
    """
    Main function of the application.
    """
    # Initialize the event manager.
    event_manager = events.EventManager()
    AppState.get_state().set_event_manager(event_manager)

    # Initialize and register the application heartbeat.
    heart_beat = HeartBeat()
    event_manager.register_listener(heart_beat)

    # Initialize and register the world.
    #experiment_ = experiment.experiment.Experiment.load_experiment("20161126T003019.p")
    experiment_ = experiment.basic.BasicVisionExperiment()
    AppState.get_state().set_experiment(experiment_)
    world = experiment_.get_world()
    event_manager.register_listener(world)
    AppState.get_state().set_world(world)

    # Initialize pygame.
    surface = init()

    # Initialize and register the view.
    main_view = view.View(surface)
    event_manager.register_listener(main_view)

    # Initialize the website trace history view.
    trace_view = agentevents.AgentEvents()
    event_manager.register_listener(trace_view)

    # Initialize and register the controller.
    main_controller = controller.Controller()
    event_manager.register_listener(main_controller)

    # Add the experiment controller to the controller
    main_controller.set_experiment_controller(
        lambda e, coords: experiment_.controller(
            e, main_view.window_coords_to_world_coords(coords)))

    # Start the webserver.
    webserver.trace_view = trace_view
    webserver.start()

    # Start the heartbeat.
    heart_beat.run()
Example #5
0
	def start(self, args):
		logger = Logger()
		backend = OutputElasticSearch(args.es_server, args.index)
		parsers = ParserPlugins()
		
		indexer = Indexer(logger, backend, parsers)
		indexer.ignore_extensions(self.ignore_extensions)
		
		if args.check_removed:
			indexer.check_removed()

		if args.index_dir:
			indexer.directory(args.index_dir)

		if args.truncate:
			backend.truncate()

		if args.webserver:
			import webserver
			webserver.start(backend)
Example #6
0
def deploy():
    """
    Deploy the web application to remote server(s)
    """
    require('environment', provided_by=('staging', 'production'))
    ## TODO: early initialization steps go here  
    if env.get('initial_deploy'):
        code.copy_website_skeleton()
        solr.make_common_skeleton()

    with settings(warn_only=True):
        webserver.stop()

    code.update()
    venv.update_requirements()
    db.update()
    solr.update_app()
    solr.update_index()
    static.collect_files()
    webserver.clear_logs()

    webserver.start()
Example #7
0
def deploy():
    """
    Deploy the web application to remote server(s)
    """
    require('environment', provided_by=('staging', 'production'))
    ## TODO: early initialization steps go here
    if env.get('initial_deploy'):
        code.copy_website_skeleton()
        solr.make_common_skeleton()

    with settings(warn_only=True):
        webserver.stop()

    code.update()
    venv.update_requirements()
    db.update()
    solr.update_app()
    solr.update_index()
    static.collect_files()
    webserver.clear_logs()

    webserver.start()
Example #8
0
            sta.active(True)
            sta.connect(ssid, pwd)
            deadline = utime.ticks_add(utime.ticks_ms(), CONNECTION_TIME_MS)
            while utime.ticks_diff(
                    deadline, utime.ticks_ms()) > 0 and not sta.isconnected():
                pass
            status = "Successfully connected" if sta.isconnected(
            ) else "Error connecting"
            status += " to " + ssid
            print(status)
        else:
            print("Bad request parameters")
            return (400, None, None)
        template_file = "connect.phtml"
        template = read_file(template_file)
        return (200, {"Content-Type": "text/html"}, template.format(status))
    else:
        return (405, None, None)


def restart(method, path, query, body):
    if method == "POST":
        machine.reset()
    else:
        return (405, None, None)


handlers = {"/scan": scan, "/connect": connect, "/restart": restart}

webserver.start(handlers=handlers)
Example #9
0
def start_json_server():
    print("Starting jsonserver")
    webserver.start(predictions)
Example #10
0
def main():
    global ds1820

    # config
    config = configparser.ConfigParser()
    config.read('/usr/local/etc/serialmon_01.ini')
    try:
        mail_oad = config["EMAIL"]["SEND_ONCE_A_DAY"]
        mail_int = config["EMAIL"]["SEND_INTERVAL"]
        log_int = config["LOGGING"]["INTERVAL"]
        ds_val = config["LOGGING"]["DS1820"]
    except KeyError:
        mail_oad = ""
        mail_int = ""
        log_int = ""
        ds_val = ""
        log.info("main", "serialmon_01.ini not filled")
    if ds_val.upper() == "YES":
        ds1820 = 1
    if ds_val.upper() == "ONLY":
        ds1820 = 2

    # init
    readlval()
    GPIO.init()
    sensors.start()
    webserver.start(gethtmltable, relstate, relupdate, GPIO.tcp_status)
    try:
        if mail_oad != "":
            log.info("main", "email: once a day at {:s}".format(mail_oad))
            schedule.every().day.at(mail_oad).do(once_a_day, 1)
        if mail_int == "1":
            log.info("main", "email: every hour")
            schedule.every().hour.do(once_a_day, 1)
        elif mail_int != "":
            log.info("main", "email: every {:s} hours".format(mail_int))
            schedule.every(int(mail_int)).hours.do(once_a_day, 1)
        if log_int == "1":
            log.info("main", "logging: every hour")
            schedule.every().hour.do(once_a_hour)
        elif log_int != "":
            log.info("main", "logging: every {:s} hours".format(log_int))
            schedule.every(int(log_int)).hours.do(once_a_hour)
    except Exception as e:
        log.info("main", "serialmon_01.ini: " + str(e))

    # --------------------arguments---Debug or Fakeval-----
    checkarguments()

    # ---------------------running
    ser = None
    while True:
        if ser == None:
            ser = serial_init()
        else:
            if not ser.isOpen():
                ser = serial_init()
            else:
                newline = str(ser.readline(), "utf-8")
                analyze(newline)
                GPIO.usb_blink(1)
        if relstate() == 1:
            if (time.time() - reltimer()) >= 60 * 60:
                relupdate(0)
        schedule.run_pending()
Example #11
0
        # st7735.prep_rect(bitmap.w(), bitmap.h())
        # while st7735.fill_rect(bitmap.get_pixel_arrays()):
        #     continue
        #
        # bitmap.close()
        print('I am connected and will start server')

        import network
        sta_if = network.WLAN(network.STA_IF)
        ip, _, _, _ = sta_if.ifconfig()

        st7735.clear(0xffffff)
        st7735.text(1, 1, 'Starting server\nIP: ' + ip, font, 0x000000)

        import webserver
        webserver.start()

    else:
        print('I need to be connected manually')

        import os
        essid = 'chipOS'
        # password = ''.join([chr(97 + int.from_bytes(os.urandom(1), 'little') % 26) for _ in range(8)])
        password = '******'
        ip, _, _, _ = hotspot.open_ap(essid, password)

        print('\nPW: ' + password +
              '\nSorry, you need to\nconnect manually...')
        st7735.text(
            1, 1, 'WLAN: ' + essid + '\nPW:   ' + password +
            '\n\nSorry you need to\nconnect manually.\n\nIP: ' + ip, font)
Example #12
0
    else:
        return i

def pack(stuff):
    return json.dumps(stuff,separators=(',',':'))

def unpack(string):
    return convert(json.loads(string,separators=(',',':')))


directives = {"*":"command(s) for all"}

#possible commands:
#KILL, REZ, SET{key:val,key:val...}
#START{jobname}
for i in range(0,9000):
    directives[str(i)]="commands for "+str(i)


toset = {"INTERVAL":100,"JOB":"test","stuff":"otherstuff"}

directives["321"] = "SET"+pack(toset)

webResults = webserver.getQueue()
webserver.setContents(directives)

printer = stupidPrinter(webResults)
printer.start()

webserver.start()
Example #13
0
def handleInterrupt(timer):    
    global interruptCounter
    global save_flag
    interruptCounter = interruptCounter + 1
    if interruptCounter == 1:        
        timeserver = setting.get('timeserver')
        if timeserver == '':
            setting.set('timeserver', 'pool.ntp.org') 
        webrepl.stop()
        RepUpdate.new(VBat)
                    
    if interruptCounter <= 5:
        print('<= 5 sec')
        if adc.read() < 200:
            timer.deinit()
            wifi.do_nothing()
            wifi.do_sta()
            print('Push Message')
            led_blink(10, 200, 0)
            if wifi.wait_sta(15):
                try:
                    import GenSasToken
                    import AzurePublish
                    import ubinascii
                    import network
                    mac = ubinascii.hexlify(network.WLAN().config('mac'),':').decode().upper()
                    UserJson = setting.get('userjson')
                    UserJson = UserJson.strip('\n')
                    UserJson = UserJson.strip('\r')
                    UserJson = UserJson.strip('\n')
                    UserJson = UserJson.strip(' ')
                    UserJson = UserJson.lstrip('{')
                    UserJson = UserJson.rstrip('}')
                    UserJson = UserJson.strip(' ')
                    msg = '{"UniqueID": "' + mac + '"'
                    if UserJson != '':
                        msg += ',' + UserJson
                    msg += '}'
                    gc.collect()
                    token = GenSasToken.now()
                    gc.collect()
                    encoded = AzurePublish.data(msg, token)
                except:
                    encoded = 'ERROR'
            else:
                encoded = 'ERROR'
            if encoded != 'ERROR':
                try:
                    dict = ujson.loads(encoded)
                    dict = dict["desired"]
                    setting.set('FWnumberNew', dict["FWnumber"])
                    setting.set('FWurl', dict["FWurl"])
                except:
                    print('ERROR TWIN MSG')
                led_blink(1, 1023, 0)
            else:
                print('ERROR Azure TX')
                led_blink(1, 0, 1023)
            time.sleep(2)    
            led_blink(1, 0, 0)
            RepUpdate.update()
            shutdown(save_flag)
    if interruptCounter == 5:
        print('5 sec')
        led_blink(1, 200, 200)
    if interruptCounter == 10:
        print('10 sec')
        if adc.read() < 200:
            print('WEB AP ...')
            timer.deinit()
            wifi.do_nothing()
            wifi.do_ap()
            led_blink(1, 0, 200)
            time.sleep(2)
            try:
                import webserver
                webserver.start()
            except:
                print('WEB Server Crash') 
            led_blink(1, 0, 0)
            shutdown()
        else:
            led_blink(3, 200, 200)
    if interruptCounter == 15:
        print('15 sec')
        if adc.read() < 200:
            print('WEB STA ...')
            timer.deinit()
            wifi.do_nothing()
            wifi.do_sta()
            led_blink(3, 0, 200)
            if wifi.wait_sta(15):
                try:
                    import webserver
                    webserver.start()
                except:
                    print('WEB Server Crash') 
            led_blink(1, 0, 0)
            shutdown()
        else:
            led_blink(10, 0, 511)
            print('Repair Time 120 sec')
            wifi.do_nothing()
            wifi.do_ap()
            wifi.do_sta()
            wifi.wait_sta(15)
            webrepl.start()
    if interruptCounter == 120:
        timer.deinit()
        print('120 sec')
        shutdown(False)
Example #14
0
 def run(self):
     webserver.start()
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Virustotal Results Page</title>
<link rel="icon"
      type="image/png"
      href="http://localhost:%s/favicon.png">
</head>
<body>
<center>
<h4>Hash analysis results from Virustotal.com</h4>
""" % args.port

cont_end = """
</center>
</body>
</html>
 """
contents = "%s %s %s" % (cont_start, htmltable, cont_end)
html_gen.str_to_file(contents, filename='index.html')
# ====================================================

# ================= RUN WEB SERVER ===================
msg1 = """
To see the results please open browser and navigate to
    http://localhost:%s\n\r""" % args.port
print(msg1)

# second command line argument is web server port# (integer):
webserver.start(port=args.port)
# ====================================================
Example #16
0
import wifimgr
import lights
import webserver
import display
import time

try:
    import usocket as socket
except:
    import socket
display.print("", "  Lights demo", "")
lights.demo()
display.print("  Wifi connect", "", "")
wlan = wifimgr.get_connection()
if wlan is None:
    print("Could not initialize the network connection.")
    while True:
        pass  # you shall not pass :D
print(wlan.ifconfig())

print('starting web server')
display.print("         Start", "     Web server", "")

webserver.start(wlan.ifconfig()[0])
Example #17
0
def main():
    webserver.start()
Example #18
0
def run_experiment(experiment_, render = True, interactive = True, console_output = True, save_logs = True):
    """
    Run an experiment until it halts. Simulates the world defined 
    by the experiment and handles control events.
    
    :param experiment_: An object of type Experiment.
    :param render: A boolean indicating whether the simulation is
                   to be rendered to the screen.
    :param interactive: A boolean indicating whether interactive
                        is to be enabled. If interactive mode is
                        on, rendering should be on as well.
    :param console_output: A boolean indicating whether simulation
                           output is to be displayed in the console.
    :param save_logs: A boolean indicating whether simulation output
                      is to be saved in a log file.
    """

    if interactive:
        assert render, "render must be true if interactive mode is set"

    # Reset the app state
    AppState.get_state().reset()

    # Initialize the event manager.
    event_manager = events.EventManager()
    AppState.get_state().set_event_manager(event_manager)

    # Initialize and register the application heartbeat.
    heart_beat = HeartBeat()
    event_manager.register_listener(heart_beat)

    # Initialize and register the world.
    AppState.get_state().set_experiment(experiment_)
    world = experiment_.get_world()
    event_manager.register_listener(world)
    AppState.get_state().set_world(world)

    # Initialize pygame.
    surface = init()

    if render:
        # Initialize and register the view.
        main_view = view.View(surface)
        event_manager.register_listener(main_view)

    # Initialize the website trace history view.
    trace_view = agentevents.AgentEvents()
    event_manager.register_listener(trace_view)

    # Initialize and register the controller.
    main_controller = controller.Controller()
    event_manager.register_listener(main_controller)

    if interactive:
        # Add the experiment controller to the controller
        main_controller.set_experiment_controller(lambda e, coords: experiment_.controller(e, main_view.window_coords_to_world_coords(coords)))

    if console_output:
        # Enable console logger
        AppState.get_state().enable_console_logger()

    if save_logs:
        # Store experiment logs
        if not os.path.isdir(settings.RESULTS_DIR):
            os.makedirs(settings.RESULTS_DIR)
        file_path = os.path.join(settings.RESULTS_DIR, "%s - %s.log" % (strftime("%Y%m%dT%H%M%S"), experiment_.__class__.__name__))
        AppState.get_state().enable_file_logger(file_path)

    # Start the webserver.
    webserver.register({'traces': trace_view})
    webserver.start()

    # Start the heartbeat.
    heart_beat.run(slow = render, halt_fun = experiment_.halt, metrics_fun = experiment_.calculate_metrics)

    if len(heart_beat.metrics) > 0:
        # Store experiment results
        if not os.path.isdir(settings.RESULTS_DIR):
            os.makedirs(settings.RESULTS_DIR)

        file_path = os.path.join(settings.RESULTS_DIR, "%s - %s.json" % (strftime("%Y%m%dT%H%M%S"), experiment_.__class__.__name__))
        with open(file_path, 'w') as f:
            json.dump(heart_beat.metrics, f, indent=4, sort_keys=True)