Exemple #1
0
def main():
    monitors = Monitor(LOCKFILE)
    mt = MyThread(60, monitors.skynet)
    try:
        parse_command_line()
        #Objects.database.allow_sync = False
        app = Application()
        [i.setFormatter(LogFormatters()) for i in logging.getLogger().handlers]
        # 脚本
        mt.start()
        app.listen(options.port)
        tornado.ioloop.IOLoop.current().start()
    except Exception as e:
        print(e)
    finally:
        mt.cancel()
        monitors.close()
        print('清理结束')
Exemple #2
0
class Main(object):
    def __init__(self):
        self.monitor = None

        try:
            # instanciates the config
            self.config = Config()

            # exists baboon when receiving a sigint signal
            signal.signal(signal.SIGINT, self.sigint_handler)

            # Initialize the scm class to use
            scm_classes = Diffman.__subclasses__()
            for cls in scm_classes:
                tmp_inst = cls()
                if tmp_inst.scm_name == self.config.scm:
                    self.diffman = tmp_inst

            # TODO verify self.diffman

            self.mediator = Mediator(self.diffman)

            self.transport = Transport(self.mediator)
            self.transport.open()

            self.monitor = Monitor(self.transport, self.diffman)
            self.monitor.watch()

            # TODO this won't work on windows...
            signal.pause()

        except BaboonException, err:
            sys.stderr.write("%s\n" % err)
            # Try to close the transport properly. If the transport is
            # not correctly started, the close() method has no effect.
            self.transport.close()

            # Same thing for the monitor
            if self.monitor:
                self.monitor.close()

            # Exits with a fail return code
            sys.exit(1)
Exemple #3
0
        memory = []
        while (not data[5]):
            add_data(data)
            data = ard.get_data()
            counter += 1
            memory.append(data)
        while (data[5]):  #handle a continuous press
            data = ard.get_data()
        solar = create_array(len(memory), 0)
        dm.solar = solar
        dm.load = memory

        ogload, optimized, soc = dm.demand_shave()
        while (not data[4]):  #freeze code while play button is not pressed
            data = ard.get_data()

        while (data[4]):  # Wait for the play button press
            data = ard.get_data()
        #once the play button is depressed it will play back with optimzation
        sim.clear()
        mon.clear_charts()
        resimulate(ogload, optimized, soc)

        while (not data[5]):  # wait for the stop button press
            data = ard.get_data()

    counter += 1

ard.close()
mon.close()
class RemoteStartAPI:
    app = Flask(__name__)

    def __init__(self):
        self.__starter = Starter()
        self.__monitor = Monitor()

        self.__register_url_rules()

    def __register_url_rules(self):
        self.app.add_url_rule("/", "hello", self.root)
        self.app.add_url_rule("/ignition_on", "ignition_on", self.ignition_on)
        self.app.add_url_rule("/ignition_off", "ignition_off", self.ignition_off)
        self.app.add_url_rule("/doors_open", "doors_open", self.doors_open)
        self.app.add_url_rule("/doors_close", "doors_close", self.doors_close)
        self.app.add_url_rule("/neutral_gear", "neutral_gear", self.neutral_gear)
        self.app.add_url_rule("/engine_start", "engine_start", self.engine_start)
        self.app.add_url_rule("/speed", "speed", self.speed)
        self.app.add_url_rule("/rpm", "rpm", self.rpm)

    @staticmethod
    def root():
        return "Rzabol says hello."

    @staticmethod
    def run_with_connection_error_check(f, *args, **kwargs):
        try:
            return f(*args, **kwargs), 200
        except ConnectionError as e:
            return {"Error": str(e)}, 500

    def ignition_on(self):
        return self.run_with_connection_error_check(self.__starter.ignition_on)

    def ignition_off(self):
        return self.run_with_connection_error_check(self.__starter.ignition_off)

    def doors_open(self):
        return self.run_with_connection_error_check(self.__starter.doors_open)

    def doors_close(self):
        return self.run_with_connection_error_check(self.__starter.doors_close)

    def neutral_gear(self):
        try:
            neutral = self.__starter.is_on_neutral_gear()
            return {"Neutral": bool(neutral)}
        except ConnectionError as e:
            return {"Error": str(e)}, 500

    def engine_start(self):
        time = request.args.get("time", None)
        try:
            if time is not None:
                self.__starter.engine_start(time)
            else:
                self.__starter.engine_start()
        except ConnectionError as e:
            return {"Error": str(e)}, 500
        except OnGearError:
            return {"Error": "Car is on gear!"}, 409
        else:
            return

    def speed(self):
        return {"speed": self.__monitor.get_speed()}

    def rpm(self):
        return {"rpm": self.__monitor.get_rpm()}

    def run(self):
        self.app.run()

    def __del__(self):
        self.__monitor.close()
        self.__starter.close_conn()
Exemple #5
0
class Forex:
    def __init__(self, dir):
        self.dir = dir
        self.config = json.load(open('{}/config.json'.format(dir)))
        self.sample_batch_size = 32
        self.episodes = 10000
        self.time_steps = 30
        self.features = 8
        self.input_shape = (30, 4)
        self.monitor = Monitor(dir)
        self.env = BTgymEnv(
            filename=self.config['data'],
            episode_duration={
                'days': 1,
                'hours': 0,
                'minutes': 0
            },
            strategy=MyStrategy,
            start_00=True,
            start_cash=self.config['capital'],
            broker_commission=self.config['commission'],
            fixed_stake=self.config['stake'],
            #drawdown_call=50,
            state_shape={
                'raw_state':
                spaces.Box(low=1, high=2, shape=self.input_shape),
                'indicator_states':
                spaces.Box(low=-1, high=10, shape=self.input_shape)
            },
            port=5006,
            data_port=4804,
            verbose=0,
        )
        self.state_size = self.env.observation_space.shape['raw_state'][
            0] + self.env.observation_space.shape['indicator_states'][0]
        self.action_size = self.env.action_space.n
        self.agent = Agent(self.state_size, self.action_size, dir)
        print("Engine:{}".format(self.env.engine.broker.getcash()))

    def run(self):
        #path = dict([(0, 2),(54, 3),(72, 2),(83, 3),(84, 1),(125, 3),(126, 2),(156, 3),(157, 1),(171, 3),(179, 1),(188, 3),(189, 2),(204, 3),(205, 1),(295, 3),(307, 2),(316, 3),(363, 2),(390, 3),(391, 1),(476, 3),(477, 2),(484, 3),(485, 1),(574, 3)])
        try:
            episodes = 0
            for index_episode in range(self.config['episodes'] -
                                       self.config['trained_episodes']):
                state = self.env.reset()
                # state = np.reshape(state['raw_state'], [4, self.state_size])
                state = self.getFullState(state)
                #print("State:{}".format(state))
                state = np.reshape(state, (1, self.time_steps, 8))
                #print("Re State:{}".format(state))
                # np.concatenate((state['raw_state'],state['indicator_states']),axis=1)
                done = False
                index = 0
                final_cash = 0
                message = ""

                count = 0
                negativeReward = 0
                positiveReward = 0
                mapper = {
                    0: 0,
                    1: 0,
                    2: 0,
                    3: 0,
                }
                while not done:
                    # self.env.render()
                    action = self.agent.act(state)
                    next_state, reward, done, info = self.env.step(action)
                    mapper[action] += 1
                    if reward > 0:
                        positiveReward += reward
                    else:
                        negativeReward += reward
                    # next_state = np.reshape(next_state, [1, self.state_size])
                    # next_state = np.array(next_state['raw_state'])
                    # print("Shape1 :{} Shape2 :{}".format(next_state['raw_state'].shape,next_state['indicator_states'].shape))

                    final_cash = info[0]['broker_cash']
                    message = info[0]['broker_message']
                    next_state = self.getFullState(next_state)
                    next_state = np.reshape(next_state,
                                            (1, self.time_steps, 8))
                    #print("Action:{} Reward:{} Done:{}".format(action, reward,done))
                    self.agent.remember(state, action, reward, next_state,
                                        done)
                    state = next_state
                    index += 1
                    self.config['steps'] += info[0]['step']
                    self.monitor.logstep({
                        "reward":
                        reward,
                        "drawdown":
                        info[0]['drawdown'],
                        'broker_value':
                        info[0]['broker_value'],
                        "steps":
                        self.config['steps']
                    })
                    if self.config['steps'] % 100 == 0:
                        self.monitor.logimage(
                            feed_dict={
                                'human': self.env.render('human')[None, :],
                            },
                            global_step=self.config['steps'],
                        )
                    # print('action: {},reward: {},info: {}\n'.format(action, reward, info))
                episodes += 1
                episode_stat = self.env.get_stat()
                self.monitor.logepisode({
                    "reward":
                    reward,
                    "cpu_time_sec":
                    episode_stat['runtime'].total_seconds(),
                    "global_step":
                    self.config['trained_episodes'] + episodes,
                    'broker_value':
                    info[0]['broker_value'],
                    "episode":
                    self.env.render('episode')[None, :]
                })
                if "CLOSE, END OF DATA" == message:
                    print("\x1b[6;30;42m{}\t{} {} \t{} {}\t\t{}\x1b[0m".format(
                        time.strftime("%H:%M:%S"), index + 1, positiveReward,
                        int(final_cash), mapper, message))
                else:
                    if positiveReward > 0:
                        print("{}\t{} {} \t{} {}\t\t{}".format(
                            time.strftime("%H:%M:%S"), index + 1,
                            positiveReward, int(final_cash), mapper, message))
                    #print("{} {} \t{} {}\t\t{}".format(index + 1,positiveReward,int(final_cash),mapper,message))
                self.agent.replay(self.sample_batch_size)
        finally:
            self.config['trained_episodes'] += episodes
            self.agent.save_model()
            self.monitor.close()
            with open('{}/config.json'.format(self.dir), 'w') as outfile:
                json.dump(self.config, outfile)

    def getFullState(self, state):
        return np.concatenate((state['raw_state'], state['indicator_states']),
                              axis=1)

    def testInitial(self):
        with open("log.txt", "a") as myfile:
            env = BTgymEnv(
                filename='./btgym/examples/data/DAT_ASCII_EURUSD_M1_2016.csv',
                start_cash=100,
                broker_commission=0.0001,
                leverage=10.0,
                fixed_stake=10)

            done = False

            o = env.reset()

            while not done:
                action = env.action_space.sample()
                obs, reward, done, info = env.step(action)
                myfile.write('action: {},reward: {},info: {}\n'.format(
                    action, reward, info))

        env.close()

    def test(self):
        state = self.env.reset()
        # state = np.reshape(state['raw_state'], [4, self.state_size])
        state = self.getFullState(state)
        state = np.reshape(state, (1, self.time_steps, 8))
        done = False
        index = 0
        final_cash = 0
        message = ""
        while not done:
            #self.env.render()
            action = self.agent.act(state)
            next_state, reward, done, info = self.env.step(action)
            final_cash = info[0]['broker_cash']
            message = info[0]['broker_message']
            # next_state = np.reshape(next_state, [1, self.state_size])
            # next_state = np.array(next_state['raw_state'])
            # print("Shape1 :{} Shape2 :{}".format(next_state['raw_state'].shape,next_state['indicator_states'].shape))
            next_state = self.getFullState(next_state)
            next_state = np.reshape(next_state, (1, self.time_steps, 8))
            state = next_state
            index += 1
        print("\x1b[6;30;42m{}\t{} \t{} \t\t{}\x1b[0m".format(
            time.strftime("%H:%M:%S"), index + 1, final_cash, message))
class Interface(QObject):
	#Weather information stored for fast use. In order:
	#Summary, Min. temp, Max. temp, Temp outside, Humidity
	#Chance of rain, Wind speed, Sunrise time, Sunset time
	weather_list = {
					"Today":[-1, "***", "***", "***", "***", "***", "***", "***", "***"],
					"Monday":[-1, "***", "***", "***", "***", "***", "***", "***", "***"],
					"Tuesday":[-1, "***", "***", "***", "***", "***", "***", "***", "***"],
					"Wednesday":[-1, "***", "***", "***", "***", "***", "***", "***", "***"],
					"Thursday":[-1, "***", "***", "***", "***", "***", "***", "***", "***"],
					"Friday":[-1, "***", "***", "***", "***", "***", "***", "***", "***"],
					"Saturday":[-1, "***", "***", "***", "***", "***", "***", "***", "***"],
					"Sunday":[-1, "***", "***", "***", "***", "***", "***", "***", "***"]
					};

	command_list = {};
	scheduled_commands = [];

	@Slot(bool, result=int)
	def get_summary(self,today=True):
		if today:
			return self.weather_list["Today"][0];
		else:
			return self.weather_list[self.future_day][0];

	@Slot(bool, result=str)
	def get_minimum(self,today=True):
		if today:
			return self.weather_list["Today"][1];
		else:
			return self.weather_list[self.future_day][1];

	@Slot(bool, result=str)
	def get_maximum(self,today=True):
		if today:
			return self.weather_list["Today"][2];
		else:
			return self.weather_list[self.future_day][2];

	@Slot(bool, result=str)
	def get_temperature(self,today=True):
		if today:
			return self.weather_list["Today"][3];
		else:
			return self.weather_list[self.future_day][3];

	@Slot(bool, result=str)
	def get_humidity(self,today=True):
		if today:
			return self.weather_list["Today"][4];
		else:
			return self.weather_list[self.future_day][4];

	@Slot(bool, result=str)
	def get_rain(self,today=True):
		if today:
			return self.weather_list["Today"][5];
		else:
			return self.weather_list[self.future_day][5];

	@Slot(bool, result=str)
	def get_wind(self,today=True):
		if today:
			return self.weather_list["Today"][6];
		else:
			return self.weather_list[self.future_day][6];

	@Slot(bool, result=str)
	def get_sunrise(self,today=True):
		if today:
			return self.weather_list["Today"][7];
		else:
			return self.weather_list[self.future_day][7];

	@Slot(bool, result=str)
	def get_sunset(self,today=True):
		if today:
			return self.weather_list["Today"][8];
		else:
			return self.weather_list[self.future_day][8];

	@Slot(str)
	def set_future_day(self, day):
		self.future_day = str(day);

	@Slot()
	def update_weather(self):
		self.temp_thread.start();

	@Slot(result=bool)
	def isRetrievingTemperature(self):
		return self.temp_thread.isRunning();

	@Slot(result=str)
	def get_command_list(self):
		return json.dumps(self.command_list, sort_keys=True);

	@Slot(result=str)
	def get_scheduled_commands(self):
		adapted = {};
		i = 0;

		for command, date in self.scheduled_commands:
			adapted[str(i)] = [command, str(date.year), str(date.month), str(date.day), str(date.hour), str(date.minute)];
			i += 1;

		return json.dumps(adapted, sort_keys=True);

	@Slot(str, result=str)
	def process_command(self, command):
		#Write the serial string associated with command to the serial port
		try: 
			self.serial_port.write(self.command_list[command][0] + "\n");
			return "Success";
		except:
			print("Error writing command to port.");
			return "Error writing to port";

	def write_commands_list(self):
		com_file = open("commandWindows.yml", "w");
		com_file.write(yaml.dump(self.command_list));
		com_file.close();

	def write_scheduled_list(self):
		com_file = open("scheduledCommands.yml", "w");
		com_file.write(yaml.dump(self.scheduled_commands));
		com_file.close();

	@Slot(str, str, str, result=int)
	def add_command(self, command, serial_string, reply_string):
		command = command.title();

		if command in self.command_list:
			return 1;

		self.command_list[command] = [serial_string, reply_string];

		try:
			self.write_commands_list();
			return 0;
		except:
			return -1;

	@Slot(str, str, str, str, str, str, result=str)
	def schedule_command(self, command, year, month, day, hour, minute):
		try:
			year = int(year);
			month = int(month);
			day = int(day);
			hour = int(hour);
			minute = int(minute);
		except:
			return "Invalid date";

		date = datetime(year, month, day, hour, minute);

		if date <= datetime.now():
			return "This software does not offer time travel capabilities";

		self.scheduled_commands.append([command, date]);

		try:
			self.write_scheduled_list();
		except:
			return "Could not write to file";

		return "Sucessfully Scheduled";

	@Slot(str, str, str, str, str, str, result=str)
	def unschedule_command(self, command, year, month, day, hour, minute):
		try:
			year = int(year);
			month = int(month);
			day = int(day);
			hour = int(hour);
			minute = int(minute);
		except:
			return "Error parsing date";

		date = datetime(year, month, day, hour, minute);

		if [command, date] not in self.scheduled_commands:
			return "No such command scheduled";
		else:
			self.scheduled_commands.remove([command, date]);

			try:
				self.write_scheduled_list();
			except:
				return "Could not write to file";

	@Slot(str)
	def remove_command(self, command):
		try:
	        	self.command_list.pop(command, None);
	    	except:
	        	print("Error removing command");
		
		self.write_commands_list();

	@Slot(result=str)
	def get_email_address(self):
		return self.monitor.my_address;

	@Slot(str, str, result=int)
	def connect(self, email, passw):
		result = self.monitor.server_connect(email, passw);

		if result == 0:
			monitor_process = multiprocessing.Process(target=self.monitor.execute);
			monitor_process.daemon = True;
			monitor_process.start();

		return result;

	@Slot(str, result=str)
	def report_bug(self, bug):
		return self.monitor.bug_report(bug, True, self.monitor.my_address);

	@Slot(str, str, result=str)
	def change_connection_password(self, oldPass, newPass):
		return self.monitor.set_connection_hash(oldPass, newPass);

	@Slot(result=str)
	def get_maintenance_email(self):
		return self.monitor.maintenance_address;
	
	@Slot(result=str)
	def get_api_key(self):
		return self.weather_module.weather_key;

	@Slot(result=str)
	def get_port(self):
		return self.port;

	@Slot(result=str)
	def get_location(self):
		return self.weather_module.home_location.replace("%20", " ").title();

	@Slot(result=str)
	def get_weather_id(self):
		return self.weather_module.home_weather_id;

	@Slot(str, str, str, result=str)
	def set_account_settings(self, maintenance_email, api_key, port):
		self.monitor.maintenance_address = maintenance_email;
		self.weather_module.weather_key = api_key;
		self.port = port;

		try:
			self.serial_port = serial.Serial(port);
		except:
			print("Error opening serial port");

		try:
			self.monitor.write_config();
		except:
			return "Could not write to file";

		return "Settings Changed";

	@Slot(str, str, result=str)
	def set_local_settings(self, location, weather_id):
		self.weather_module.home_location = location.replace(" ", "%20");
		self.weather_module.home_weather_id = weather_id;

		try:
			self.monitor.write_config();
		except:
			return "Could not write to file";

		return "Settings Changed";

	@Slot(result=bool)
	def uses_metric_units(self):
		return self.weather_module.metric_units;

	@Slot(bool)
	def set_metric(self, value):
		self.weather_module.metric_units = value;

		try:
			self.monitor.write_config();
		except:
			print("Could not write to file");

	def __init__(self):
		super(Interface, self).__init__();
	
		rewrite_required = False;

		try:
			config = open("config.yml", "r");
			settings = yaml.load(config);
			config.close();
		except:
			settings = Defaults.config;
			rewrite_required = True;
		
		my_address = settings["home_email"];
		maintenance_address = settings["maintenance_email"];
		metric_units = settings["metric_units"];
		home_location = settings["location"];
		weather_key = settings["api_key"];
		weather_id = settings["weather_id"];
		self.port = settings["port"];
		connection_hash = settings["connection_password"];
		del settings;

		try:
			#Default 9600 baud rate
			self.serial_port = serial.Serial(self.port);
		except:
			print("Error opening serial port.");

		try:
			com_file = open("commandWindows.yml", "r");
			self.command_list = yaml.load(com_file);
			com_file.close();
		except:
			self.command_list = Defaults.commandWindows;
			self.write_commands_list();

		try:
			scheduled_file = open("scheduledCommands.yml", "r");
			self.scheduled_commands = yaml.load(scheduled_file);
			scheduled_file.close();
		except:
			self.scheduled_commands = Defaults.scheduledCommands;

		if self.command_list == None:
			self.command_list = {};

		if self.scheduled_commands == None:
			self.scheduled_commands = [];

		current = datetime.now();		

		for command, date in self.scheduled_commands:
			if date <= current:
				self.scheduled_commands.remove([command, date]);

		try:
			self.write_scheduled_list();
		except:
			print("Could not write to scheduled file");		

		self.weather_module = Weather(home_location, weather_key, weather_id, metric_units);
		self.temp_thread = Temp_Thread(self);
		self.serial_thread = Serial_Thread(self);
		self.future_day = self.weather_module.weekdays[(time.localtime(time.time())[6] + 1)%7];
		#self.update_weather();

		while self.temp_thread.isRunning():
			time.sleep(0.2);
		
		self.monitor = Monitor(self, self.weather_module, my_address, maintenance_address, home_location, connection_hash);

		if rewrite_required:
			self.monitor.write_config();

		self.serial_thread.start();

	@Slot()
	def close(self):
		self.temp_thread.quit();
		self.monitor.close();
		sys.exit();