def get_batteries(self):
        """
        Retrieve batteries from csv and create battery objects.
        """

        if self.advanced == True:
            random_batteries = get_random_batteries(self.district)
            labels, clusters = get_clusters(self.district, random_batteries)
            clusters = clusters.tolist()
            for battery_id, battery in enumerate(random_batteries, 1):
                cluster = random.choice(clusters)
                clusters.remove(cluster)
                x = cluster[0]
                y = cluster[1]
                capacity = battery[1]["capacity"]
                cost = battery[1]["price"]
                b = Battery(battery_id, x, y, capacity, cost)
                self.batteries.append(b)
        else:
            f = open(f'data/district{self.district_nr}_batteries.csv')
            batteries_data = csv.reader(f)
            next(batteries_data)

            for battery_id, row in enumerate(batteries_data, 1):
                x, y = eval(row[0])[0], eval(row[0])[1]
                capacity = eval(row[1])
                battery = Battery(battery_id, x, y, capacity)

                self.batteries.append(battery)
示例#2
0
class ElectricCar(Car):
    def __init__(self, name, price, model_year):
        super().__init__(name, price, model_year)
        self.battery = Battery("li", 5)

    def car_capacity(self):
        self.battery.get_running_capacity()
示例#3
0
class CheckBattery:
    def __init__(self, start, end):
        self.start = start
        self.end = end
        self.battery = Battery()
        self.notification = None

    def check(self):
        capacity = self.battery.get_capacity()
        if self.battery.is_charging():
            if capacity >= self.end:
                os.system("espeak 'Please unplug!'")
                message = "Charged to {}%. Please unplug!".format(self.end)
                self.notify(message)
        else:
            if capacity <= self.start:
                os.system("espeak 'Please plug in!'")
                message = "Battery level {}%. Please plug in!".format(
                    self.start)
                self.notify(message)

    def notify(self, message):
        if not self.notification == message:
            os.system('notify-send "BATTERY WARNING" "{}"'.format(message))
            self.notification = message
示例#4
0
    def __init__(self, uss, comm, q):
        """
        コンストラクタです。
        """
        self.logger = logging.getLogger(__name__)

        self.pipe_uss = uss
        self.pipe_comm = comm
        self.uss = []
        self.req = {}
        self.q = q

        sleep(1)  # 先に起動すると困る
        PeriodicTask.__init__(self)

        self.cmds = []

        self.recv()
        self.batt = Battery(self.req["btA"], self.req["btB"])
        self.movement = Run()

        self.ms = []
        for pin in IO.PIN:
            self.ms.append(IO(pin, IO.IN, True))
        self.ms = tuple(self.ms)
示例#5
0
    def innitialize(self):
        self.batteries = []

        # innitialize batteries
        for i, house in enumerate(self.houses):
            battery = Battery(i, house.x, house.y, 1508)
            battery.costs = 5000  # Later via Battery()?
            self.batteries.append(battery)
示例#6
0
class ElectricCar(Car):
    def __init__(self, make, model, year, battery_size):
        super().__init__(make, model, year)
        #self.battery_size = 70
        self.battery = Battery(battery_size)

    def describe_battery(self):
        #print("This car has a " + str(self.battery_size) + "-kWh battery.")
        self.battery.describe_battery()

    def fill_gas_tank(self, gas_tank):
        print("This car doesn't need a gas tank!")
示例#7
0
    def __init__(self, width=1920, height=1080):
        # Create Screen with the provided resolution
        self.width = width  #1920
        self.height = height  #1080
        self.screen = Screen(width, height)
        self.logo = self.screen.load_image("logo.png")
        #self.logo = self.screen.scale(self.logo, 500,100)

        #self.screen.set_fps(10)
        # NOTE: Remove comment on next line to add Full screen
        #self.screen.set_full_screen()

        size = self.screen.get_size()
        self.border = 10
        b = self.border  # Just to make the next line more readable

        self.battery = Battery(self.screen,
                               x=20,
                               y=self.height - 355,
                               width=140,
                               height=300)

        # Creates a wyndow with a margin to make it pritty <3
        self.window = Window(self.screen, b + 180, b + 130,
                             size[0] - (b * 2 + 270), size[1] - (b * 2 + 180))
        self.window.set_all_colors((100, 100, 100))
        self.window.set_border_color((200, 200, 200))
        self.window.set_border_width(10)
        self.chart_og = Chart()
        self.chart_og.set_width(8)
        self.chart_og.set_color((255, 150, 0))
        self.chart_og.add_point([1, 0])
        self.chart_og.add_point([2, 0])
        self.window.add_chart(self.chart_og)

        self.chart_optimised = Chart()
        self.chart_optimised.set_width(8)
        self.chart_optimised.set_color((0, 150, 255))
        self.chart_optimised.add_point([1, 0])
        self.chart_optimised.add_point([2, 0])
        self.window.add_chart(self.chart_optimised)
        # Next we add a function that converts the X values to
        # something the window class can work with, simple numbers
        # the window class does not know how to handle dates
        # so they need to be converted to intigers. These X values
        # are still used as labels in the x axis so format them
        # wisely.
        # NOTE: Remove comment on the fallowing line to add convertion function
        #self.chart.set_conv_funct(self.convert)

        self.data = Value(self.screen, 22, 150)
示例#8
0
def check_events(color, events, units, screen, flags, cprof):
    """ watch keyboard/mouse for events

    When close window button is pressed, exit the game. Other functionality
    may come later.
    """
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.unicode == "q":
                color = "blue"
            if event.unicode == "e":
                color = "green"
            if event.unicode == "z":
                if color == "blue":
                    units.append(
                        Company(screen, 0, *pygame.mouse.get_pos(), 2, 2,
                                color, flags, 500))
                if color == "green":
                    units.append(
                        Company(screen, 0, *pygame.mouse.get_pos(), 2, 2,
                                color, flags, 500, False))
            if event.unicode == "x":
                if color == "blue":
                    units.append(
                        Battery(screen, 0, *pygame.mouse.get_pos(), 3, color,
                                flags, 12))
                if color == "green":
                    units.append(
                        Battery(screen, 0, *pygame.mouse.get_pos(), 3, color,
                                flags, 12, False))
            if event.unicode == "c":
                if color == "blue":
                    units.append(
                        Squadron(screen, 0, *pygame.mouse.get_pos(), 2, 2,
                                 color, flags, 120))
                if color == "green":
                    units.append(
                        Squadron(screen, 0, *pygame.mouse.get_pos(), 2, 2,
                                 color, flags, 120, False))
            if event.unicode == "f":
                units = []
                flags = []
            if event.unicode == "g":
                cprof.print_stats('tottime')
    for event in events:
        units = event.check(units)
        if event.triggered:
            events.remove(event)
    return color, units
示例#9
0
    def test_charge(self):
        bat = Battery(3.0, cells=4)

        # Can't charge a battery if voltage under battery's current voltage
        bat.charge(volts=14.0, amps=3, seconds=60)
        self.assertEqual(bat.charge_state, 1.5)
        self.assertEqual(bat.voltage, 14.4)

        # Can charge battery if voltage over battery's current voltage
        bat.charge(volts=16.6, amps=3, seconds=60)
        # Basic properties haven't changed:
        self.assertEqual(bat.capacity, 3.0)
        self.assertEqual(bat.cells, 4)
        self.assertEqual(bat.minimum_voltage, 3.0)
        self.assertEqual(bat.maximum_voltage, 4.2)
        # Charge state has changed
        self.assertEqual(bat.charge_state, 1.55)
        # Voltage has risen slightly
        self.assertGreater(bat.voltage, 14.4)

        # At this stage we can push a battery beyond the charge voltage if we
        # give a long enough duration, but we can't go over the battery's
        # capacity.
        bat.charge(volts=16.6, amps=3, seconds=3600)  # Should be well over
        # But capacity is limited to
        self.assertEqual(bat.charge_state, bat.capacity)
        # And voltage is maxed out
        self.assertEqual(bat.voltage, 16.8)
示例#10
0
def system(data, horizon):
    pv_model = PV(area=4)
    HP_model = HP(efficiency=0.9)
    battery = Battery(charge_efficiency=0.95, bat_capacity=15, discharging_rate=1.5, charging_rate=2,horizon=optimization_horizon)
    ED_model = ED()
    TD_model = TD()
    pv = pv_model.get_PV_data('data-openideas.csv', 'solar', horizon, data)
    HP = HP_model.get_td_data('data-openideas.csv', 'out_QradD', 'out_QradN', 35, horizon, data)
    ed = ED_model.get_ED_data('linear data.csv', horizon, data)
    battery.do_action(data, compute_energy_cost=False)
    TD = TD_model.get_TD_data('data-openideas.csv', 'out_QradD', 'out_QradN', horizon, data)



    return data
示例#11
0
    def load_batteries(self, filename):
        ''' Load batteries file to python '''
        with open(filename, "r") as f:
            content = f.readlines()

            innitial_batteries = []
            self.batteries = []

            # loop through and replace all the "bad" characters with nothing. After that split values
            for i in content:
                i = i.replace("\t", " ")
                i = i.replace(",", "")
                i = i.replace("[", "")
                i = i.replace("]", "")

                i = i.strip('\n')
                innitial_batteries.append(i.split())

            # load batteries into list (id, x, y, max_amp)
            for i, battery in enumerate(innitial_batteries[1:]):
                self.batteries.append(
                    Battery(i, int(battery[0]), int(battery[1]),
                            float(battery[2])))

            return self.batteries
示例#12
0
    def load_batteries():
        """
        Parses through text file and saves batteries as battery.Battery
        objects. Returns instances in dict to __init__
        """
        # find specific directory with the data
        subpath = f"Huizen&Batterijen\wijk{INPUT}_batterijen.txt"
        path = str(Path.cwd()).replace("scripts", subpath)

        with open(path) as batteries_text:

            # read text file per line
            data_batteries = batteries_text.readlines()

            # delete headers
            data_batteries.pop(0)

            batteries = {}

            # Library color list toevoegen
            COLOUR_LIST = ["m", "g", "c", "y", "b",
                           "grey", "maroon", "yellow", "orange",
                           "fuchsia", "lime", "peru"]

            # for every batterie isolate coordinates and capacity
            for id, battery in enumerate(data_batteries):
                coordinates = battery.split("\t", 1)[0]
                cap = battery.split("\t", 1)[1].strip()
                x = re.sub("\D", "", coordinates.split(",", 1)[0])
                y = re.sub("\D", "", coordinates.split(",", 1)[1])
                colour = COLOUR_LIST[id]
                batteries[id] = Battery(cap, x, y, colour)

        # return dict to INIT
        return batteries
示例#13
0
    def __init__(self, debug=False):
        self.cfg = None
        self.rtc = RTC()
        self.debug = debug
        self.battery = Battery()

        # use this pin for debug
        self.wifi_pin = Pin("GP24", mode=Pin.IN, pull=Pin.PULL_UP)

        # Empty WDT object
        self.wdt = None

        if not debug:
            if not self.wifi_pin():
                self.wdt = WDT(timeout=20000)
            self.sd = None
        else:
            from machine import SD
            try:
                self.sd = SD()
                mount(self.sd, '/sd')
                self.logfile = open("/sd/display.log", "a")
            except OSError:
                self.sd = None
                self.logfile = None

        self.epd = EPD()

        self.log("Time left on the alarm: %dms" % self.rtc.alarm_left())

        # Don't flash when we're awake outside of debug
        heartbeat(self.debug)
示例#14
0
    def load_batteries(self):
        cwd = os.getcwd()
        cwd = os.path.dirname(cwd)
        path = os.path.join(*[cwd, "data", f"{INPUT_BATTERIES}"])
        sys.path.append(path)
        with open(path) as batteries_text:

            # read text file per line
            data_batteries = batteries_text.readlines()

            # delete headers
            data_batteries.pop(0)

            batteries = {}

            # for every batterie isolate coordinates and capacity
            for id, battery in enumerate(data_batteries):
                coordinates = battery.split("\t", 1)[0]
                cap = battery.split("\t", 1)[1]
                cap = cap.strip()
                x = coordinates.split(",", 1)[0]
                y = coordinates.split(",", 1)[1]
                x = re.sub("\D", "", x)
                y = re.sub("\D", "", y)
                # colour = self.colour_list[id]
                colour = COLOUR_LIST[id]
                batteries[id] = Battery(cap, x, y, colour)

        # return dict to INIT
        return batteries
示例#15
0
 def __init__(self):
     super(Pod, self).__init__()
     capsule = self.add('capsule', PassengerCapsule(), promotes=['n_rows', 'row_len'])
     tube = self.add('tube', TubeStructural(), promotes=['tube_P', 'tube_T', 'tube_r', 'tube_area', 'fill_area'])
     inlet = self.add('inlet', InletGeom(), promotes=['hub_to_tip', 'tube_area', 'bypass_area', 'cross_section', 'area_frontal'])
     battery = self.add('battery', Battery(), promotes=['time_mission', 'energy', 'cross_section'])
     aero = self.add('aero', Aero(), promotes=['rho', 'gross_thrust', 'net_force', 'coef_drag', 'velocity_capsule', 'area_frontal'])
示例#16
0
 def __init__(self, make, model, year, odometer):
     """Initialize attributes to describe a car."""
     self.make = make
     self.model = model
     self.year = year
     self.odometer = odometer
     self.battery = Battery(0.5)
示例#17
0
    def load_batteries(self, filename):
        """"
        Load batteries from filename.
        returns a dictionary of "id" : Battery objects
        """
        battery_data = []
        with open(filename, "r") as file:
            for line in file:
                line = line.strip('\n')
                battery_data.append(line.split(','))

        batteries = {}
        id_nr = 0
        for battery in battery_data:
            id = id_nr
            battery.insert(0, id)
            x = int(battery[1])
            y = int(battery[2])
            capacity = float(battery[3])
            id_nr += 1
            #initialize a house object and put it in a dict with id as key
            battery = Battery(id, x, y, capacity)
            batteries[id] = battery

        return batteries
示例#18
0
文件: app.py 项目: artluix/PyHWMon
    def __init__(self):
        Gtk.Window.__init__(self)

        self.host = Host()
        self.cpu = CPU()
        self.gpu_integrated = GPU_Integrated()
        self.gpu_discrete = GPU_Discrete()
        self.ssd = SSD()
        self.bat = Battery()

        self.notebook = Gtk.Notebook()
        self.add(self.notebook)

        self.page_1 = Gtk.Box()
        self.__fill_page_1()
        self.notebook.append_page(self.page_1, Gtk.Label('Hardware Monitor'))


        self.page_2 = Gtk.Box()
        self.__fill_page_2()
        self.notebook.append_page(self.page_2, Gtk.Label('Hardware Info'))


        self.page_3 = Gtk.Box()
        self.__fill_page_3()
        self.notebook.append_page(self.page_3, Gtk.Label('About'))
示例#19
0
    def load_batteries(self):
        """
        Parses through text file and saves batteries as battery.Battery
        objects. Returns instances in dict to __init__
        """

        with open(batt_file) as batteries_text:

            # read text file per line
            data_batteries = batteries_text.readlines()

            # delete headers
            data_batteries.pop(0)

            batteries = {}

            # Library color list toevoegen
            COLOUR_LIST = [
                "m", "g", "c", "y", "b", "grey", "maroon", "yellow", "orange",
                "fuchsia", "lime", "peru"
            ]

            # for every batterie isolate coordinates and capacity
            for id, battery in enumerate(data_batteries):
                coordinates = battery.split("\t", 1)[0]
                cap = battery.split("\t", 1)[1].strip()
                x = re.sub("\D", "", coordinates.split(",", 1)[0])
                y = re.sub("\D", "", coordinates.split(",", 1)[1])
                colour = COLOUR_LIST[id]
                batteries[id] = Battery(cap, x, y, colour)

        # return dict to INIT
        return batteries
示例#20
0
	def __init__(self, make, model, year):
		"""
		Initialize attributes of the parent class.
		Then initialize attributes specific to an electric car.
		"""
		super().__init__(make, model, year)
		self.battery = Battery()
    def load_batteries(self):
        global diax
        global diay

        # reading the battery file
        batteryfile = open("data/wijk1_batterijen.txt", "r")
        list_batteries = []

        # making battery instances and adding to list
        counter = 0
        for line in batteryfile:
            if counter != 0:
                check = line.split()
                x_value = check[0].strip('[').strip(',')
                y_value = check[1].strip(']')
                capacity = check[2]
                list_batteries.append(Battery(x_value, y_value, capacity))
            counter = 1
        battery_change = list_batteries[0]

        battery_change.set_xval(diay)
        battery_change.set_yval(diax)
        dia += 1

        return list_batteries
示例#22
0
文件: cli.py 项目: hugoahosta/vizex
def cli(arg, save, path, every,
        details, exclude, header, style,
        text, graph, mark) -> None:
    """
    ** Displays Disk Usage in the terminal, graphically. **

    Customize visuals by setting colors and attributes.

    COLORS: light_red, red, dark_red, dark_blue, blue,
        cyan, yellow, green, pink, white, black, purple,
        neon, grey, beige, orange, magenta, peach.

    ATTRIBUTES: bold, dim, underlined, blink, reverse.
    """


    options: Options = Options()
    if mark:
        options.symbol = mark
    if header:
        options.header_color = header
    if text:
        options.text_color = text
    if graph:
        options.graph_color = graph
    if style:
        options.header_style = style

    exclude_list = list(exclude)

    if arg == 'battery':
        try:
            battery = Battery()
            battery.print_charts()
        except:
            print('Battery not found!')
    elif arg == 'cpu':
        cpus = CPUFreq()
        cpus.display_separately()
    else:
        # renderer = None
        renderer = DiskUsage(
            path=path, exclude=exclude_list, details=details, every=every
        )
        if save:
            renderer.save_data(save)
        renderer.print_charts(options)
示例#23
0
    def __init__(self):
        self.b = Battery(constants.battery_capacity,constants.battery_max_charge,constants.battery_max_discharge,constants.nbatt,constants.nbatt_c,constants.nbatt_d,\
            constants.battery_cost, constants.life_time, constants.round_trip)
        self.g = GasTurbine(constants.gas_turbine_max, constants.microgas_turbine_om_cost, constants.fual_cost, constants.co2_coe, constants.co2_cost, \
            constants.so2_coe, constants.so2_cost, constants.no_coe, constants.no_cost)
        self.l = Load(constants.shortage_cost)
        self.p = PV(constants.pv_max, constants.pv_om_cost)
        self.w = WindTurbine(constants.wind_turbine_max,
                             constants.wind_turbine_om_cost)
        self.m = MEMS(self.b, self.g, self.l, self.p, self.w)
        self.bm = BaseMEMS(self.b, self.g, self.l, self.p, self.w)

        self.l.set_forecast(constants.load_important_forecast,
                            constants.load_transferable_forecast)
        self.p.set_forecast([ir / 0.2 * 1000 for ir in constants.pv_forecast])
        self.w.set_forecast(
            [0.2 * wind_speed**3 for wind_speed in constants.wind_forecast])
示例#24
0
 def __init__(self, make, model, year):
     """
     初始化父类的属性
     经过测试:父类有多少个参数, super这里就必须传入多少个
     默认参数不用
     """
     super().__init__(make, model, year)
     self.battery = Battery()  # 将实例用作属性
示例#25
0
    def __init__(self, make, model, year):
        super().__init__(make, model, year)
        # Python 2.7
        # super(ElectricCar, self).__init__(make, model, year)

        # 将实例用作属性
        self.battery_size = 70
        # 将实例用作属性:提取类
        self.battery = Battery()
示例#26
0
    def __init__(self, num_households, possible_providers):
        self.num_households = num_households
        self.num_appliances = 5

        # House type (0 if house is occupied all day)
        self.household_type = np.zeros(self.num_households)
        self.household_type[int(self.num_households /
                                2):self.num_households] = 1

        # Constants matrix
        self.a = np.ones((self.num_households, self.num_appliances))
        self.b = np.ones((self.num_households, self.num_appliances))
        self.c = np.ones((self.num_households, self.num_appliances))

        self.battery = Battery(self.num_households)
        self.demand = Demand(self.num_households, self.num_appliances)

        # Arrays with energy prices
        self.price = np.zeros(
            (Constants.max_num_iterations, Constants.num_producers,
             Constants.day_hours.size))

        # Logical array with houses consuming of each producer
        self.customers = np.zeros(
            (Constants.num_producers, self.num_households,
             Constants.day_hours.size), 'int')
        self.adjacency_matrix = np.zeros(
            (Constants.num_producers + self.num_households,
             Constants.num_producers + self.num_households,
             Constants.day_hours.size), 'int')
        self.possible_providers = possible_providers

        # Money each house spends in energy by hour
        self.expenditures = np.zeros(
            (self.num_households, Constants.day_hours.size))

        air = AirConditioner(self.num_households)
        washer = Washer()
        phev = Phev()
        light = Lightning()
        ent = Entertainment()

        self.appliances = np.array((air, phev, washer, light, ent))
示例#27
0
 def dictToBattery(client):
     eMin = client["eMin"]
     eMax = client["eMax"]
     pMin = client["pMin"]
     pMax = client["pMax"]
     tEnd = client["tEnd"]
     e = client["e"]
     p = client["p"]
     CID = client["CID"]
     return Battery(eMin, eMax, pMin, pMax, tEnd, e, p, CID)
示例#28
0
    def __init__(
            self,
            app_name: str,
            low_battery_summary: str,
            high_battery_summary: str,
            low_battery_message: str,
            high_battery_message: str,
            low_battery_icon: str,
            high_battery_icon: str
    ):
        self._app_name = app_name
        self._low_battery_summary = low_battery_summary
        self._high_battery_summary = high_battery_summary
        self._low_battery_message = low_battery_message
        self._high_battery_message = high_battery_message
        self._low_battery_icon = low_battery_icon
        self._high_battery_icon = high_battery_icon

        self._battery = Battery()
示例#29
0
    def distance(self):
        """
        Calculates a route between battery and house
        according to the manhatten distance
        """
        coordinates_h = House.get_coord()
        coordinates_b = Battery.get_coord()
        length = abs(coordinates_h[0] - coordinates_b[0]) + abs(coordinates_h[1] - coordinates_b[1])

        return length
示例#30
0
 def __init__(self, duration=24, day=1, loadRow=0):
     self.PV = PV()
     self.Battery = Battery()
     self.totalPrices = totalPrices
     self.totalPvGen = totalPvGen
     self.totalLoad = totalLoad
     self.totalAverageLoad = totalLoad.mean(axis=1)
     self.__timeDuration = duration
     self.__day = day
     self.loadRow = loadRow
示例#31
0
文件: pod.py 项目: wind1239/Hyperloop
    def configure(self):

        #Add Components
        capsule = self.add('capsule', PassengerCapsule())
        tube = self.add('tube', TubeStructural())
        inlet = self.add('inlet', InletGeom())
        battery = self.add('battery', Battery())
        aero = self.add('aero', Aero())

        #Boundary Input Connections
        #Pod -> Capsule
        self.connect('n_rows', 'capsule.n_rows')
        self.connect('length_row', 'capsule.length_row')
        #Pod->Tube
        self.connect('radius_tube_inner', 'tube.radius_inner')
        self.connect('Ps_tube', 'tube.Ps_tube')
        #Pod->Inlet
        self.connect('area_inlet_in', 'inlet.area_in')
        self.connect('area_inlet_out', 'inlet.area_out')
        self.connect('hub_to_tip', 'inlet.hub_to_tip')
        #Pod -> Battery
        self.connect('time_mission', 'battery.time_mission')
        self.connect('energy', 'battery.energy')
        #Pod -> Aero
        self.connect('coef_drag', 'aero.coef_drag')
        self.connect('rho_air', 'aero.rho')
        self.connect('speed_max', 'aero.velocity_capsule')
        self.connect('F_net', 'aero.gross_thrust')

        #Inter Component Connections
        #Capsule -> Inlet
        self.connect('capsule.area_cross_section',
                     'inlet.area_passenger_capsule')
        #Capsule -> Battery
        self.connect('capsule.area_cross_section',
                     'battery.area_cross_section')
        #Inlet -> Aero
        self.connect('inlet.area_frontal', 'aero.area_capsule')

        #Boundary Output Connections
        #Capsule -> Pod
        self.connect('capsule.area_cross_section', 'area_cross_section')
        #Tube->Pod
        self.connect('tube.radius_outer', 'radius_tube_outer')
        #Inlet->Pod
        self.connect('inlet.radius_back_outer', 'radius_inlet_back_outer')
        self.connect('inlet.area_bypass', 'area_compressor_bypass')
        #Aero -> Pod
        self.connect(
            'aero.net_force',
            'net_force')  #not currently used, eventually passed to mission

        #Declare Solver Workflow
        self.driver.workflow.add(
            ['capsule', 'tube', 'inlet', 'battery', 'aero'])
def initPopulationGenerator(populationNumbers, timeIntervals):

    workerBattery = Battery()

    for i in range(populationNumbers):

        matrix = generateMatrix(timeIntervals)
        randomizeInputMatrix(matrix, battery)
        simulate(matrix, battery)

        spawn_queue.put([matrix[6, -1], 0, matrix.copy()])
示例#33
0
 def test_value(self):
     b= Battery()
     b.battery_raw = MagicMock(side_effect=[3500,3800,5000])
     self.assertEqual(b.value(), 0)
     self.assertEqual(b.value(), 100)
示例#34
0
class Display(object):
    IMG_DIR = '/flash/imgs'

    def __init__(self, debug=False):
        self.cfg = None
        self.rtc = RTC()
        self.debug = debug
        self.battery = Battery()

        # use this pin for debug
        self.wifi_pin = Pin("GP24", mode=Pin.IN, pull=Pin.PULL_UP)

        # Empty WDT object
        self.wdt = None

        if not debug:
            if not self.wifi_pin():
                self.wdt = WDT(timeout=20000)
            self.sd = None
        else:
            from machine import SD
            try:
                self.sd = SD()
                mount(self.sd, '/sd')
                self.logfile = open("/sd/display.log", "a")
            except OSError:
                self.sd = None
                self.logfile = None

        self.epd = EPD()

        self.log("Time left on the alarm: %dms" % self.rtc.alarm_left())

        # Don't flash when we're awake outside of debug
        heartbeat(self.debug)

    def log(self, msg, end='\n'):
        time = "%d, %d, %d, %d, %d, %d" % self.rtc.now()[:-2]
        msg = time + ", " + msg
        if self.logfile:
            self.logfile.write(msg + end)
        print(msg, end=end)

    def feed_wdt(self):
        if self.wdt:
            self.wdt.feed()

    def connect_wifi(self):
        from network import WLAN

        if not self.cfg:
            raise ValueError("Can't initialise wifi, no config")

        self.log('Starting WLAN, attempting to connect to ' + ','.join(self.cfg.wifi.keys()))
        wlan = WLAN(0, WLAN.STA)
        wlan.ifconfig(config='dhcp')
        while not wlan.isconnected():
            nets = wlan.scan()
            for network in nets:
                if network.ssid in self.cfg.wifi.keys():
                    self.log('Connecting to ' + network.ssid)
                    self.feed_wdt() # just in case
                    wlan.connect(ssid=network.ssid, auth=(network.sec, self.cfg.wifi[network.ssid]))
                    while not wlan.isconnected():
                        idle()
                    break

            self.feed_wdt() # just in case
            sleep_ms(2000)

        self.log('Connected as %s' % wlan.ifconfig()[0])

    @staticmethod
    def reset_cause():
        import machine
        val = machine.reset_cause()
        if val == machine.POWER_ON:
            return "power"
        elif val == machine.HARD_RESET:
            return "hard"
        elif val == machine.WDT_RESET:
            return "wdt"
        elif val == machine.DEEPSLEEP_RESET:
            return "sleep"
        elif val == machine.SOFT_RESET:
            return "soft"

    def set_alarm(self, now, json_metadata):
        import json
        json_dict = json.loads(json_metadata)

        # Now we know the time too
        self.rtc = RTC(datetime=now)
        list_int = json_dict["wakeup"][:6]
        time_str = ",".join([str(x) for x in list_int])

        self.log("Setting alarm for " + time_str)
        self.rtc.alarm(time=tuple(list_int))

        if self.rtc.alarm_left() == 0:
            self.log("Alarm failed, setting for +1 hour")
            self.rtc.alarm(time=3600000)

        del json

    def display_file_image(self, file_obj):
        towrite = 15016
        max_chunk = 250
        while towrite > 0:
            c = max_chunk if towrite > max_chunk else towrite
            buff = file_obj.read(c)
            self.epd.upload_image_data(buff, delay_us=2000)
            self.feed_wdt()
            towrite -= c

        self.epd.display_update()

    def display_no_config(self):
        self.log("Displaying no config msg")
        with open(Display.IMG_DIR + '/no_config.bin', 'rb') as pic:
            self.display_file_image(pic)

    def display_low_battery(self):
        self.log("Displaying low battery msg")
        with open(Display.IMG_DIR + '/low_battery.bin', 'rb') as pic:
            self.display_file_image(pic)

    def display_cannot_connect(self):
        self.log("Displaying no server comms msg")
        with open(Display.IMG_DIR + '/no_server.bin', 'rb') as pic:
            self.display_file_image(pic)

    def display_no_wifi(self):
        self.log("Displaying no wifi msg")
        with open(Display.IMG_DIR + '/no_wifi.bin', 'rb') as pic:
            self.display_file_image(pic)

    def check_battery_level(self):
        now_batt = 200
        last_batt = self.battery.battery_raw()
        while now_batt > last_batt:
            sleep_ms(50)
            last_batt = now_batt
            self.feed_wdt()
            now_batt = self.battery.battery_raw()
            self.log("Battery value: %d (%d)" % (self.battery.value(), self.battery.battery_raw()))

        if not self.battery.safe():
            self.log("Battery voltage (%d) low! Turning off" % self.battery.battery_raw())
            self.feed_wdt()
            self.display_low_battery()
            return False
        else:
            self.log("Battery value: %d (%d)" % (self.battery.value(), self.battery.battery_raw()))
        return True

    def run_deepsleep(self):

        if not self.run():
            # RTC wasn't set, try to sleep forever
            self.rtc.alarm(time=2000000000)

        # Set the wakeup (why do it earlier?)
        rtc_i = self.rtc.irq(trigger=RTC.ALARM0, wake=DEEPSLEEP)

        self.log("Going to sleep, waking in %dms" % self.rtc.alarm_left())

        # Close files on the SD card
        if self.sd:
            self.logfile.close()
            self.logfile = None
            unmount('/sd')
            self.sd.deinit()

        # Turn the screen off
        self.epd.disable()

        if not self.wifi_pin():
            # Basically turn off
            deepsleep()
        else:
            self.log("DEBUG MODE: Staying awake")
            pass
            # Do nothing, allow network connections in

    def run(self):

        woken = self.wifi_pin()
        self.epd.enable()

        if not self.check_battery_level():
            return False

        try:
            self.epd.get_sensor_data()
        except ValueError:
            self.log("Can't communicate with display, flashing light and giving up")
            heartbeat(True)
            sleep_ms(15000)
            return True

        if self.rtc.alarm_left() > 0:
            self.log("Woken up but the timer is still running, refreshing screen only")
            self.epd.display_update()
            self.feed_wdt()
            return True

        try:
            self.cfg = Config.load(sd=self.sd)
            self.log("Loaded config")
        except (OSError, ValueError) as e:
            self.log("Failed to load config: " + str(e))
            self.display_no_config()
            try:
                self.connect_wifi()
            except:
                pass # everything

            while True:
                sleep_ms(10)
                self.feed_wdt()

        self.feed_wdt()

        self.connect_wifi()

        content = b''
        try:
            self.log("Connecting to server %s:%d" % (self.cfg.host, self.cfg.port))
            c = Connect(self.cfg.host, self.cfg.port, debug=self.debug)

            self.feed_wdt()

            cause = Display.reset_cause()
            if woken:
                cause = "user"

            self.log("Reset cause: " + cause)

            if len(self.cfg.upload_path) > 0:
                temp = self.epd.get_sensor_data() # we read this already
                c.post(self.cfg.upload_path,
                       battery=self.battery.value(),
                       reset=cause,
                       screen=temp)

            self.log("Fetching metadata from " + self.cfg.metadata_path)
            metadata = c.get_quick(self.cfg.metadata_path, max_length=1024, path_type='json')

            # This will set the time to GMT, not localtime
            self.set_alarm(c.last_fetch_time, metadata)

            self.feed_wdt()
            del metadata
            del self.battery
            self.log("Fetching image from " + self.cfg.image_path)
            self.epd.image_erase_frame_buffer()
            self.feed_wdt()

            length, socket = c.get_object(self.cfg.image_path)

            if length != 15016:
                raise ValueError("Wrong data size for image: %d" % length)

            self.feed_wdt()

        except (RuntimeError, ValueError, OSError) as e:
            self.log("Failed to get remote info: " + str(e))
            self.display_cannot_connect()
            self.rtc.alarm(time=3600000)
            return True

        sleep_ms(1000) # How do we make the write to display more reliable?
        self.feed_wdt()
        self.log("Uploading to display")
        self.display_file_image(socket)
        c.get_object_done() # close off socket

        if self.cfg.src == "sd":
            # If we've got a working config from SD instead of flash
            self.log("Transferring working config")
            Config.transfer()
            self.log("SUCCESS")

        self.log("Finished. Mem free: %d" % gc.mem_free())
        return True
示例#35
0
 def test_safe(self):
     b= Battery()
     b.battery_raw = MagicMock(side_effect=[3400,3800])
     self.assertEqual(b.safe(), False)
     self.assertEqual(b.safe(), True)
示例#36
0
文件: app.py 项目: artluix/PyHWMon
class App(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self)

        self.host = Host()
        self.cpu = CPU()
        self.gpu_integrated = GPU_Integrated()
        self.gpu_discrete = GPU_Discrete()
        self.ssd = SSD()
        self.bat = Battery()

        self.notebook = Gtk.Notebook()
        self.add(self.notebook)

        self.page_1 = Gtk.Box()
        self.__fill_page_1()
        self.notebook.append_page(self.page_1, Gtk.Label('Hardware Monitor'))


        self.page_2 = Gtk.Box()
        self.__fill_page_2()
        self.notebook.append_page(self.page_2, Gtk.Label('Hardware Info'))


        self.page_3 = Gtk.Box()
        self.__fill_page_3()
        self.notebook.append_page(self.page_3, Gtk.Label('About'))

#---------------------------------------------- PAGE 1 -------------------------------------------------------------

    def __fill_page_1(self):
        self.store_1 = Gtk.TreeStore(str, str, str, str) 
        treeview = Gtk.TreeView(self.store_1)
        treeview.set_enable_tree_lines(True)
        treeview.modify_font(Pango.FontDescription('monaco 10'))
        renderer = Gtk.CellRendererText()

        scrolled_window = Gtk.ScrolledWindow()
        scrolled_window.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
        scrolled_window.add(treeview)
        self.page_1.pack_start(scrolled_window, True, True, 0)

        columns = ('Sensor', 'Value', 'Min', 'Max')
        for i in range(len(columns)):
            column = Gtk.TreeViewColumn(columns[i], renderer, text=i)
            treeview.append_column(column)

        self.__add_nodes_to_store_1()
        treeview.expand_all()

        self.__add_threads()
        self.__set_threads_daemons()
        self.__start_threads()


    def __add_nodes_to_store_1(self):
        host_node = self.store_1.append(None, [self.host.get_name()] + [''] * 3 )

        cpu_node = self.store_1.append(host_node, [self.cpu.get_name()] + [''] * 3)

        cpu_temp_node = self.store_1.append(cpu_node, ['Temperature'] + [''] * 3)
        self.cpu_temp_value_nodes = []     
        for t_l in self.cpu.get_temp_labels():
            self.cpu_temp_value_nodes.append(self.store_1.append(cpu_temp_node, [t_l] + [''] * 3))

        cpu_freq_node = self.store_1.append(cpu_node, ['Frequency'] + [''] * 3)
        self.cpu_freq_value_nodes = []     
        for f_l in self.cpu.get_freq_labels():
            self.cpu_freq_value_nodes.append(self.store_1.append(cpu_freq_node, [f_l] + [''] * 3))

        cpu_usage_node = self.store_1.append(cpu_node, ['Usage'] + [''] * 3)
        self.cpu_usage_value_nodes = []     
        for u_l in self.cpu.get_usage_labels():
            self.cpu_usage_value_nodes.append(self.store_1.append(cpu_usage_node, [u_l] + [''] * 3))

        gpu_interated_node = self.store_1.append(host_node, [self.gpu_integrated.get_name()] + [''] * 3)
        gpu_integrated_freq_node = self.store_1.append(gpu_interated_node, ['Frequency'] + [''] * 3)
        self.gpu_integrated_freq_value_node = self.store_1.append(gpu_integrated_freq_node, \
            [self.gpu_integrated.get_freq_label()] + [''] * 3)

        gpu_discrete_node = self.store_1.append(host_node, [self.gpu_discrete.get_name()] + [''] * 3)
        gpu_discrete_temp_node = self.store_1.append(gpu_discrete_node, ['Temperature'] + [''] * 3)
        self.gpu_discrete_temp_value_node = self.store_1.append(gpu_discrete_temp_node, \
            [self.gpu_discrete.get_temp_label()] + [''] * 3)

        ssd_node = self.store_1.append(host_node, [self.ssd.get_name()] + [''] * 3)

        ssd_temp_node = self.store_1.append(ssd_node, ['Temperature'] + [''] * 3)
        self.ssd_temp_value_node = self.store_1.append(ssd_temp_node, [self.ssd.get_temp_label()] + [''] * 3)

        bat_node = self.store_1.append(host_node, [self.bat.get_name()] + [''] * 3)

        bat_voltage_node = self.store_1.append(bat_node, ['Voltage'] + [''] * 3)
        self.bat_voltage_value_node = self.store_1.append(bat_voltage_node, [self.bat.get_voltage_label()] + [''] * 3) 

        bat_charge_node = self.store_1.append(bat_node, ['Charge'] + [''] * 3)
        self.store_1.append(bat_charge_node, [self.bat.get_charge_header_label()] + self.bat.get_charge_header_row())
        self.bat_charge_value_node = self.store_1.append(bat_charge_node, [self.bat.get_charge_label()] + [''] * 3)


    def __add_threads(self):
        sensors_update_callbacks = [
                                    self.__cpu_temp_update_callback, 
                                    self.__cpu_freq_update_callback,
                                    self.__cpu_usage_update_callback, 
                                    self.__gpu_integrated_freq_update_callback, 
                                    self.__gpu_discrete_temp_update_callback, 
                                    self.__ssd_temp_update_callback, 
                                    self.__bat_voltage_update_callback, 
                                    self.__bat_charge_update_callback
                                    ]

        self.sensors_threads = []
        for c in sensors_update_callbacks:
            self.sensors_threads.append(threading.Thread(target=self.__thread_callback, args=[c]))

    def __thread_callback(self, update_func):
        while True:
            GObject.idle_add(update_func)
            time.sleep(INTERVAL)
    
    def __set_threads_daemons(self):
        for t in self.sensors_threads:
            t.daemon = True

    def __start_threads(self):
        for t in self.sensors_threads:
            t.start()



    def __cpu_temp_update_callback(self):
        cpu_temperature = self.cpu.get_temperature()
        for i, cpu_temp_row in enumerate(zip(*cpu_temperature)):
            self.store_1[self.cpu_temp_value_nodes[i]][1:] = [str(x) + ' °C' for x in cpu_temp_row]


    def __cpu_freq_update_callback(self):
        cpu_frequency = self.cpu.get_frequency()
        for i, cpu_freq_row in enumerate(zip(*cpu_frequency)):
            self.store_1[self.cpu_freq_value_nodes[i]][1:] = [str(x) + ' MHz' for x in cpu_freq_row]

    def __cpu_usage_update_callback(self):
        cpu_usage = self.cpu.get_usage()
        for i, cpu_usage_row in enumerate(zip(*cpu_usage)):
            self.store_1[self.cpu_usage_value_nodes[i]][1:] = [str(x) + ' %' for x in cpu_usage_row]


    def __gpu_integrated_freq_update_callback(self):
        gpu_freq_row = self.gpu_integrated.get_frequency()
        self.store_1[self.gpu_integrated_freq_value_node][1:] = [str(x) + ' MHz' for x in gpu_freq_row]

    def __gpu_discrete_temp_update_callback(self):
        gpu_temp_row = self.gpu_discrete.get_temperature()
        self.store_1[self.gpu_discrete_temp_value_node][1:] = [str(x) + ' °C' for x in gpu_temp_row]


    def __ssd_temp_update_callback(self):
        ssd_temp_row = self.ssd.get_temperature()
        self.store_1[self.ssd_temp_value_node][1:] = [str(x) + ' °C' for x in ssd_temp_row]


    def __bat_voltage_update_callback(self):
        bat_voltage_row = self.bat.get_voltage()
        self.store_1[self.bat_voltage_value_node][1:] = [str(x) + ' V' for x in bat_voltage_row]

    def __bat_charge_update_callback(self):
        bat_charge_row = self.bat.get_charge()
        self.store_1[self.bat_charge_value_node][1:] = [str(x) + ' mWh' for x in bat_charge_row]

#---------------------------------------------- PAGE 2 -------------------------------------------------------------

    def __fill_page_2(self):
        self.store_2 = Gtk.TreeStore(str)
        treeview = Gtk.TreeView(self.store_2)
        treeview.set_enable_tree_lines(True)
        treeview.modify_font(Pango.FontDescription('monaco 10'))
        renderer = Gtk.CellRendererText()

        scrolled_window = Gtk.ScrolledWindow()
        scrolled_window.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
        scrolled_window.add(treeview)
        self.page_2.pack_start(scrolled_window, True, True, 0)

        column = Gtk.TreeViewColumn('List Hardware', renderer, text=0)
        treeview.append_column(column)

        self.dimms = self.__read_dimms()

        data = self.__read_lshw()
        self.__parse_json_to_store_2(data)


    def __read_dimms(self):
        path = 'sysfs/decode_dimms'
        with open(path, 'r') as f:
            s = f.read()
        return s.split('\n\n\n')[1:3]


    def __parse_dimm(self, dimm, parent_node, i):
        dimm_blks = dimm.split('\n\n')
        dimm_header = dimm_blks[0].split('\n')
        dimm_header[0], dimm_header[1] = dimm_header[1], dimm_header[0]
        dimm_blks[0] = dimm_header[1]

        dimm_name = dimm_header[0][48:-1] + str(i)
        dimm_from_name = dimm_header[1].split(':')[0]
        dimm_from_path = dimm_header[1].split(':')[1].lstrip(' ')

        name_node = self.store_2.append(parent_node, [dimm_name])
        k_node = self.store_2.append(name_node, [dimm_from_name])
        self.store_2.append(k_node, [dimm_from_path])

        for blk in dimm_blks[1:]:
            blk_l = blk.split('\n')
            blk_name = blk_l[0].split('===')[1][1:-1]
            blk_name_node = self.store_2.append(name_node, [blk_name])
            for s in blk_l[1:]:
                k = s[0:48].rstrip(' ')
                v = s[48:]
                k_node = self.store_2.append(blk_name_node, [k])
                self.store_2.append(k_node, [v])


    def __read_lshw(self):
        path = 'sysfs/lshw'
        with open(path, 'r') as f:
            data_str = f.read()
        return json.loads(data_str)


    def __parse_json_to_store_2(self, d, parent_node=None):
        if type(d) is dict:
            if 'id' in d:
                if re.match('bank:[0-9]', d['id']):
                    n = int(d['id'][-1])
                    if n in (0, 2):
                        n >>= 1
                        self.__parse_dimm(self.dimms[n], parent_node, n)
                else:
                    parent_node = self.store_2.append(parent_node, [str(d['id'])])
                    del(d['id'])
                    for k in d:
                        if k not in ('capabilities', 'configuration', 'children'):
                            key_node = self.store_2.append(parent_node, [str(k)])
                            if type(d[k]) is not list:
                                value_node = self.store_2.append(key_node, [str(d[k])])
                            else:
                                for v in d[k]:
                                    value_node = self.store_2.append(key_node, [str(v)])
                        elif k in ('configuration', 'capabilities'):
                            key_node = self.store_2.append(parent_node, [str(k)])
                            value_dict = d[k]
                            for k_dict in value_dict:
                                key_l_node = self.store_2.append(key_node, [str(k_dict)])
                                self.store_2.append(key_l_node, [str(value_dict[k_dict])])

                if 'children' in d:
                    for list_dict in d['children']:
                        self.__parse_json_to_store_2(list_dict, parent_node)

#---------------------------------------------- PAGE 3 -------------------------------------------------------------

    def __fill_page_3(self):
        textview = Gtk.TextView()
        textview.modify_font(Pango.FontDescription('Droid Sans 14'))
        textview.set_editable(False)
        textview.set_cursor_visible(False)
        textview.set_justification(Gtk.Justification.CENTER)
        textbuffer = textview.get_buffer()
        s = '\n\n\n\n\n\n\n\n\nThis program is brought to you by\nArtluix - Daineko Stanislau\nSt. of BSUIR of FKSiS\nof chair of Informatics\n\nBig thanks and credits to devs of:\ndecode-dimms\n lshw\n hdparm\n hddtemp'
        textbuffer.set_text(s)
        self.page_3.pack_start(textview, True, True, 0)