Esempio n. 1
0
def main():
    try:
        logging.info(">> Collecting data")
        data = Data()

        logging.info(">> Writing data to CSV")
        writeToCSV(data)

        logging.info(">> Sending data to Thinger.io")
        sendDataToThingerIO(data)

        logging.info(">> Checking battery state")
        if data.BatteryLevel < 20:
            logging.warning(
                f"Battery critical: {data.BatteryLevel}% - Shutdown initiated."
            )
            shutdown()
        else:
            logging.info(f"Battery state: {data.BatteryLevel}%")

    except IOError as e:
        logging.error(e)

    except KeyboardInterrupt:
        logging.info("Script closed by user")
        exit()
Esempio n. 2
0
def main():
    print "Starting main()\n"
    u.setup()
    u.calibrate(
    )  # You only need to include this command if you want the tophats to sense better at the cost of speed.
    a.get_gas_valve()
    print "Finished main\n"
    u.shutdown(86)
Esempio n. 3
0
def main():
    print "Starting main()\n"
    u.setup()
    u.calibrate()
    a.get_crates()
    a.put_crates_in_correct_zone()
    a.get_botguy()
    a.put_botguy_on_side()
    u.shutdown()
Esempio n. 4
0
def my_signal_handler(signum, frame):
    global upd_pid
    if verbose: print time.asctime(),'signal handler caught signal', signum
    if os.getpid()!=upd_pid:
        if verbose: print time.asctime(),'sending TERM signal to update_load process (',upd_pid,')'
        os.kill(upd_pid,signal.SIGTERM)
        if verbose: print time.asctime(),'sending shutdown message to scheduler and exit'
        shutdown(server_host,server_port,scheduler_host,scheduler_port)
    sys.exit(0)
Esempio n. 5
0
def my_signal_handler(signum, frame):
    global upd_pid
    if verbose: print time.asctime(),'signal handler caught signal', signum
    if os.getpid()!=upd_pid:
        if verbose: print time.asctime(),'sending TERM signal to update_load process (',upd_pid,')'
        os.kill(upd_pid,signal.SIGTERM)
        if verbose: print time.asctime(),'sending shutdown message to scheduler and exit'
        shutdown(server_host,server_port,scheduler_host,scheduler_port)
    sys.exit(0)
Esempio n. 6
0
def main():
    print "Starting main()\n"
    u.setup()
    u.calibrate()
    a.get_ambulance()
    a.get_blocks()
    a.deliver_ambulance_and_blocks()
    #a.get_firefighters()
    #a.deliver_firefighters()
    u.shutdown()
Esempio n. 7
0
def main():
    print "Starting main()\n"
    u.setup()
    u.calibrate(
    )  # You only need to include this command if you want the cliffs to sense better at the cost of speed.
    a.get_left_coupler()
    a.go_to_magnets()
    u.reset_roomba()
    a.do_magnets()
    a.deliver_left_coupler()
    print "Finished main\n"
    u.shutdown()
Esempio n. 8
0
def enter_polling_loop(url, timeout):
    while True:
        try:
            r = requests.get(url)
            if r.text.rstrip() == "hard_shutdown":
                utils.shutdown()
            elif r.text.rstrip() == "no_change":
                print "no change"
            else:
                print "Unhandled %s" % r.text
        except requests.exceptions.ConnectionError:
            print "connection failed to %s" % url
        sleep(timeout)
    def listen_from_client(self):
        """

        :return:
        """
        print("Listening....")
        while True:
            (client_socket, client_address
             ) = self.serverSocket.accept()  # Establish the connection
            # d = threading.Thread(name=self._getClientName(client_address),
            #                      target=self.listen(client_socket, client_address),
            #                      args=(client_socket, client_address))
            # d.setDaemon(True)
            # d.start()
            self.listen(client_socket, client_address)
        shutdown(self.serverSocket, 0, 0)
def main():
    info = {"parkspot_id": "", "token": ""}

    # Load Parkspot ID and Token
    infoPath = Path(settings.infoFile)
    if infoPath.is_file():
        info = (pickle.load(open(settings.infoFile, "rb")))

    tokenAvailable = True
    if (info['token'] == ""):
        tokenAvailable = False

    networkAvailable = hasNetwork()

    if networkAvailable is False or tokenAvailable is False:
        setupParkspot(info)

    api = ParkspotApi(info)

    # Create a new parkspot if we did not create one yet
    if info["parkspot_id"] == "":
        if api.createParkspot() is False:
            print("Could not create Parkspot. Resetting")
            reset()
        pickle.dump(info, open(settings.infoFile, "w+b"))

    # Tell the backend our IP
    if api.updateLocalIp() is False:
        print("Could update IP. Resetting")
        shutdown()

    # Initialize the camera and the model
    print("Starting model")
    cam = Camera(usePiCamera=False, resolution=(1280, 720))
    model = CNN(cam, 'cnn/model/complexCNN.h5', api)

    # Create the parkspot grpc service
    service = ParkspotService(cam, model, api)

    # Run model
    while True:
        model.detect()
        time.sleep(5)

    # When everything is done, release everything
    cv2.destroyAllWindows()
    service.stop()
Esempio n. 11
0
    def shutdown_count(self):
        """关机倒计时
        """
        # update displayed time
        # self.now.set(current_iso8601())
        # schedule timer to call myself after 1 second
        self.time_count -= 1
        s = "{0}秒后关机 (点击勾选框可取消关机)"
        self.txt['text'] = s.format(self.time_count)
        self.after_id = utils.win.after(1000, self.shutdown_count)

        if self.time_count <= 0:
            utils.win.after_cancel(self.after_id)
            self.txt['text'] = ""
            if self.need_shutdown:
                self.need_shutdown = False
                utils.shutdown()
Esempio n. 12
0
def main():
    print "Starting main()\n"
    u.setup()
    u.calibrate()
    a.only_first_three()
    # m.backwards(1300)
    m.turn_right()
    m.backwards(4500)
    u.sd()


    a.get_low_poms_cheeky()
    a.get_frisbee()
    a.get_mid_poms()
    a.get_high_poms_cheeky()
    a.get_farther_high_poms() 
    a.get_farther_mid_poms()
    a.get_farther_low_poms()
    print "Finished main\n"
    u.shutdown(86)
Esempio n. 13
0
def main(loop, redis):
    serv_generator, handler, app = loop.run_until_complete(init(loop))
    serv = loop.run_until_complete(serv_generator)
    loop.create_task(runner(redis))

    print('start server %s' % str(serv.sockets[0].getsockname()))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        print(' Stop server begin')
    finally:
        loop.run_until_complete(shutdown(serv, app, handler, redis))
        loop.close()
    print('Stop server end')
Esempio n. 14
0
def main():
    print(f"Running benchmarks at {time.time()}")

    if not torch.cuda.is_available():
        device = torch.device("cpu")
        batch_size = 16
    else:
        device = torch.device("cuda")
        batch_size = 1024
    print("Device", device)
    print("Batch size", batch_size)
    print("Is_cloud:", utils.is_cloud())

    workspace_folder = (CLOUD_WORKSPACE_FOLDER
                        if utils.is_cloud() else LOCAL_WORKSPACE_FOLDER)

    model_filepath = f"{workspace_folder}/checkpoints/math_112m_bs128_2-3-20_0_5375000_training_0.pth"

    # build default transformer model
    model = utils.build_transformer()
    # restore model from checkpoint
    state = checkpoints.restore_checkpoint(model_filepath, model)
    if state is None:
        print("Ending run without checkpoint")
        exit(0)

    if False:
        question = "What is 25 + 35?"
        print(model_process.predict_single(question, model, device, n_best=5))
        sys.exit(0)

    ds_path = f"{workspace_folder}/mathematics_dataset-v1.0"
    benchmark = BenchmarkDatasetManager(ds_path)

    generator = Generator(
        model,
        device,
        beam_size=5,
        max_token_seq_len=MAX_ANSWER_SZ,
        n_best=1,
    )
    results = {}
    for module, dataset in benchmark.get_datasets("interpolate").items():
        print(f"Testing {module} of length {len(dataset)} ...")
        start = time.time()
        loader = data.DataLoader(
            dataset,
            batch_size=batch_size,
            shuffle=False,
            num_workers=16,
            collate_fn=benchmark_collate_fn,
            pin_memory=False,
        )
        iterator = iter(loader)

        resps = model_process.predict_benchmark(generator, iterator, device)
        correct = 0
        for resp in resps:
            if resp["correct"] is True:
                correct += 1

        print(f"S: {(time.time() - start) * 1000}ms")
        print(
            f"Got {correct} of {len(dataset)} correct in {module} after {(time.time() - start)}s."
        )
        results[module] = correct
        with open(f"{module}.txt", "a") as f:
            f.write(f"{correct}")

    print(results)
    print("Benchmark complete")
    utils.shutdown()
Esempio n. 15
0
 def shutdown(self, kwargs):
     shutdown()
Esempio n. 16
0
        epochs=1000,  # Not relevant, will get ended before this due to max_b
        tb=tb,
        run_max_batches=run_max_batches,
        validation_data=None,
        start_epoch=start_epoch,
        start_batch=start_batch,
        total_loss=total_loss,
        n_char_total=n_char_total,
        n_char_correct=n_char_correct,
        run_batches=run_batches,
        interpolate_data=interpolate_loader,
        extrapolate_data=extrapolate_loader,
        checkpoint=save_checkpoints,
        lr=lr,
        warmup_lr=warmup_lr,
        warmup_interval=warmup_interval,
        smoothing=smoothing,
    )


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("Ending script")
    except BaseException:
        print("Catching error...")
        print(traceback.format_exc())
        utils.shutdown()
        raise
Esempio n. 17
0
#!/usr/bin/python

import config
from gpiozero import MotionSensor, Button
from utils import flash, alert, toggle, shutdown

sensor = MotionSensor(4)

try:
	while True:
		sensor.wait_for_motion()
		sensor.when_motion = alert()
			
except KeyboardInterrupt:
    shutdown()
Esempio n. 18
0
def shutdown():
    utils.shutdown()
    return redirect("/")