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.Battery()
def testBatteryEstimator_AttachIdealBattery_EnergyChecksPass(self): idealBattery = battery.Battery(capacity=9300, chargingLossPercent=0, dischargingLossPercent=0, maxChargingPower=5000, maxDischargingPower=7000) batteryEstimator = batteryestimator.BatteryEstimator(idealBattery) newEnergy = batteryEstimator.accumulateFeedInEnergy( self.testData, self.energyTypes) oldSums = [sum(x) for x in zip(*self.testData.values())] newSums = [sum(x) for x in zip(*newEnergy.values())] self.assertEqual(oldSums[self.energyTypes.index('Production')], newSums[self.energyTypes.index('Production')]) self.assertEqual(oldSums[self.energyTypes.index('Consumption')], newSums[self.energyTypes.index('Consumption')]) self.assertGreater(newSums[self.energyTypes.index('SelfConsumption')], oldSums[self.energyTypes.index('SelfConsumption')]) self.assertEqual( newSums[self.energyTypes.index('Production')] + newSums[self.energyTypes.index('Purchased')], newSums[self.energyTypes.index('Consumption')] + newSums[self.energyTypes.index('FeedIn')] + newSums[self.energyTypes.index('Accumulated')])
def testBatteryEstimator_UseRealBattery_PurchasedEnergyDecreasesWithBattery( self): realBattery = battery.Battery(capacity=9300, chargingLossPercent=1, dischargingLossPercent=1, maxChargingPower=5000, maxDischargingPower=7000) batteryEstimator = batteryestimator.BatteryEstimator(realBattery) oct30energyData = {} for key in self.testData.keys(): if key >= datetime.datetime( year=2019, month=10, day=29, hour=0, minute=0, second=0 ) and key < datetime.datetime( year=2019, month=10, day=30, hour=0, minute=0, second=0): oct30energyData[key] = self.testData[key] accumulatedEnergy = batteryEstimator.accumulateFeedInEnergy( oct30energyData, self.energyTypes) oldSums = [sum(x) for x in zip(*oct30energyData.values())] newSums = [sum(x) for x in zip(*accumulatedEnergy.values())] self.assertGreater(oldSums[self.energyTypes.index('Purchased')], newSums[self.energyTypes.index('Purchased')])
def init(): win = Dock() top = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) mid = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, valign=Gtk.Align.CENTER) bot = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, valign=Gtk.Align.END) bigbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) bigbox.set_homogeneous(True) bigbox.add(EBox(top, name="topbox")) bigbox.add(EBox(mid, name="midbox")) bigbox.add(EBox(bot, name="botbox")) win.add(bigbox) mid.add(bspwm.DesktopView()) bot.add(Clock('%I\n%M\n%S')) bot.add(battery.Battery()) bot.add(PowerButton()) async def tray(): await asyncio.sleep(0.2) await asyncio.create_subprocess_exec("stalonetray", "-c", "/dev/null", "--vertical", "--slot-size", "30", "--window-strut", "left", "--transparent", "--grow-gravity", "N", "--sticky") asyncio.ensure_future(tray()) win.show_all() win.connect('delete-event', lambda *args: asyncio.get_event_loop().stop()) return win
def __init__(self, make, model, year): """ Inicializa os atributos da classe-pai. Em seguida, inicializa os atributos específicos de um carro elétrico. """ super().__init__(make, model, year) self.battery = battery.Battery() # Atenção para a notação de ponto nas linhas 5 e 14.
def testBattery_dischargingIdealBattery_ChargedBatteryReturnsZero(self): testBattery = battery.Battery(capacity=1000, chargingLossPercent=0, dischargingLossPercent=0, maxChargingPower=10000, maxDischargingPower=10000) testBattery.energy = 100 # Wh dischargedEnergy = -10 # Wh returnedEnergy = testBattery.chargeDischargeBattery(dischargedEnergy) expectedReturnedEnergy = 0 self.assertEqual(expectedReturnedEnergy, returnedEnergy)
def __init__(self, d=None): self.min_loop_duration = 12 #ms self.d = d if d else display.Display() self.b = backlight.Backlight() self.k = keyboard.Keyboard() self.l = looper.Looper(self.b, self.d) self.p = polyphony.Polyphony(self.k, self.d, self.l) self.l.p = self.p self.bat = battery.Battery(self.d) self.last_t = time.ticks_ms() self.last_t_disp = 0 self.longest_loop = 0
def testBattery_chargingIdealBattery_OverloadedEnergyReturned(self): testBattery = battery.Battery(capacity=1000, chargingLossPercent=0, dischargingLossPercent=0, maxChargingPower=10000, maxDischargingPower=10000) chargeEnergy = 1000 # Wh overloadedEnergy = 100 returnedEnergy = testBattery.chargeDischargeBattery(chargeEnergy + overloadedEnergy) self.assertEqual(overloadedEnergy, returnedEnergy) self.assertEqual(chargeEnergy, testBattery.energy)
def testBattery_dischargeRealEmptyBattery_dischargingEnergyReturned(self): testBattery = battery.Battery(capacity=1000, chargingLossPercent=1, dischargingLossPercent=1, maxChargingPower=1000, maxDischargingPower=1000) dischargedEnergy = -10 # Wh testBatteryInitialEnergy = 0 testBattery.energy = testBatteryInitialEnergy returnedEnergy = testBattery.chargeDischargeBattery(dischargedEnergy) self.assertEqual(dischargedEnergy, returnedEnergy)
def testBattery_chargingIdealBattery_chargedEnergyStored(self): testBattery = battery.Battery(capacity=1000, chargingLossPercent=0, dischargingLossPercent=0, maxChargingPower=1000, maxDischargingPower=1000) chargeEnergy = 100 # Wh returnedEnergy = testBattery.chargeDischargeBattery(chargeEnergy) expectedReturnedEnergy = 0 self.assertEqual(expectedReturnedEnergy, returnedEnergy) self.assertEqual(chargeEnergy, testBattery.energy)
def testBattery_chargingRealBatteryWithTooHighPower_OverChargingEnergyReturned( self): testBattery = battery.Battery(capacity=1000, chargingLossPercent=0, dischargingLossPercent=0, maxChargingPower=100, maxDischargingPower=100) chargeEnergy = 100 # Wh returnedEnergy = testBattery.chargeDischargeBattery(chargeEnergy) self.assertEqual(chargeEnergy - returnedEnergy, testBattery.energy) expectedReturnedEnergy = chargeEnergy - testBattery.maxChargingPower / 4 self.assertEqual(expectedReturnedEnergy, returnedEnergy)
def testBattery_chargingIdealBatteryChargeWithZeroEnergy_NothingHappens( self): testBattery = battery.Battery(capacity=1000, chargingLossPercent=0, dischargingLossPercent=0, maxChargingPower=10000, maxDischargingPower=10000) chargedEnergy = 0 # Wh oldBatteryEnergy = testBattery.energy returnedEnergy = testBattery.chargeDischargeBattery(chargedEnergy) expectedReturnedEnergy = 0 self.assertEqual(expectedReturnedEnergy, returnedEnergy) self.assertEqual(oldBatteryEnergy, testBattery.energy)
def testBattery_chargingRealBattery_ChargingEnergyLossHappens(self): testBattery = battery.Battery(capacity=1000, chargingLossPercent=5, dischargingLossPercent=5, maxChargingPower=10000, maxDischargingPower=10000) chargeEnergy = 100 # Wh returnedEnergy = testBattery.chargeDischargeBattery(chargeEnergy) expectedBatteryEnergy = chargeEnergy * ( 100 - testBattery.chargingLossPercent) / 100 self.assertEqual(expectedBatteryEnergy, testBattery.energy) expectedReturnedEnergy = 0 self.assertEqual(expectedReturnedEnergy, returnedEnergy)
def __init__(self, communication_object): """ @param communication_object: Communication object used for communicating with the brick @type communication_object: communication.Communication """ self.subscription = None self._opened_ports = {} self.hostname = "" self.mute = False # blocks sound messages self.closed = False self._message_handler = asynchronous.MessageHandler( communication_object) self.battery = battery.Battery() self.refresh_battery()
def __init__(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if os.path.exists('config.json'): with open('config.json', 'r') as config: self.config = json.loads(config.read()) print('Settings fetch from \'config.json\'.') else: self.config = self.get_config_from_main_frame() self.battery = battery.Battery(50) self.watch_and_alert(5) self.listen_thread = threading.Thread( target=self.listen_for_energy_change) self.listen_thread.start()
def testBattery_dischargingRealBattery_DischargingEnergyLossHappens(self): testBattery = battery.Battery(capacity=1000, chargingLossPercent=5, dischargingLossPercent=5, maxChargingPower=10000, maxDischargingPower=10000) dischargedEnergy = -100 # Wh testBatteryInitialEnergy = 1000 testBattery.energy = testBatteryInitialEnergy returnedEnergy = testBattery.chargeDischargeBattery(dischargedEnergy) expectedBatteryEnergy = testBatteryInitialEnergy + dischargedEnergy * ( 100 + testBattery.chargingLossPercent) / 100 self.assertEqual(expectedBatteryEnergy, testBattery.energy) expectedReturnedEnergy = 0 self.assertEqual(expectedReturnedEnergy, returnedEnergy)
def testBattery_dischargingRealBatteryWithTooHighPower_OverDischargingEnergyReturned( self): testBattery = battery.Battery(capacity=1000, chargingLossPercent=0, dischargingLossPercent=0, maxChargingPower=100, maxDischargingPower=100) dischargedEnergy = -100 # Wh testBatteryInitialEnergy = 1000 testBattery.energy = testBatteryInitialEnergy returnedEnergy = testBattery.chargeDischargeBattery(dischargedEnergy) self.assertEqual( testBatteryInitialEnergy + dischargedEnergy - returnedEnergy, testBattery.energy) expectedReturnedEnergy = dischargedEnergy + testBattery.maxDischargingPower / 4 self.assertEqual(expectedReturnedEnergy, returnedEnergy)
def __init__(self): self.battery = battery.Battery() self.battery.new_params = None self.battery.register_callback(self.battery_update_callback) self.battery.update() self.indicator = appindicator.Indicator.new(APPINDICATOR_ID, self.get_icon(), CATEGORY) self.indicator.set_status(appindicator.IndicatorStatus.ACTIVE) self.indicator.set_menu(self.build_menu()) self.window = None self.log_update_period = timedelta(minutes=5) self.log_last_update = datetime.now() - self.log_update_period self.update_battery() self.update_chart() sec = 1000 gobject.timeout_add(1 * sec, self.update_battery) gobject.timeout_add(1 * sec, self.update_log) gobject.timeout_add(30 * sec, self.update_chart)
def create_battery(): brand = input("What is the brand of the battery? : ") capacity = input("What is the capacity of the battery? : ") voltage = input("What is the voltage of the battery? : ") return battery.Battery(brand, capacity, voltage)
def __init__(self, make, model, year): super().__init__(make, model,year) # defined properties for subclasses self.battery = battery.Battery()
padding=-1, foreground=dk_grey, background=grey), widget.TaskList(borderwidth=1, background=grey, border=cyan, urgent_border=red), widget.TextBox(text="\u25e4 ", fontsize=42, padding=-8, foreground=grey), widget.TextBox(text="\u2328", foreground=cyan), widget.KeyboardLayout(configured_keyboards=["us dvorak", "us"], foreground=cyan, update_interval=5), tempsensor.TempSensor(font="fontawesome"), networkmonitor.NetworkMonitor(font="fontawesome"), volume.Volume(font="fontawesome"), widget.Clock(format='%m-%d-%Y %a %H:%M:%S'), ] if os.path.exists('/sys/class/power_supply/BAT0'): widgets1.insert(-1, battery.Battery()) screens = [ Screen(top=bar.Bar(widgets1, size=23)), Screen(top=bar.Bar(widgets2, size=23)) ] follow_mouse_focus = True cursor_warp = False floating_layout = layout.Floating() auto_fullscreen = True
equivalent CO2 (eCO2) and Total Volatile Organic Compound (TVOC) and displays the values on a 2.9in Waveshare e-Paper display. """ import machine import esp32 import utime import ccs811 import bme280 import screen import battery import baseline import config _i2c = machine.I2C(scl=config.scl, sda=config.sda, freq=100000) _rtc = machine.RTC() _bat = battery.Battery(config.battery) _baseline = baseline.Baseline() def run(): """Main entry point to execute this program.""" try: bme = bme280.BME280(i2c=_i2c, mode=bme280.BME280_OSAMPLE_4) scr = screen.Screen(config) if _delete_ccs811_baseline_requested(): _baseline.delete() if _is_first_run(): # 20 runs (minutes), p9 of datasheet _set_runs_to_condition(20)
def main(): print("Welcome to the BPS Simulator") print( "Type 'start' to start BeVolt. Otherwise, you can specify the types of data to simulate." ) print(">>", end="") if input() == 'start': # Initial capacity is (2500*14)/(2950*14)=0.847 i.e. 84.7% charged init_capacity_mah = 2500 * config.num_batt_cells_parallel_per_module # Amperes current draw of the electrical system ampere_draw = 30 # Create state of the battery BeVolt = battery.Battery(ampere_draw, config.total_batt_pack_capacity_mah, init_capacity_mah) PLL.PLL_Init() SPI.init(battery=BeVolt) else: BeVolt = None configure() SPI.init(state=state, mode=mode) try: launch_bevolt() except Exception as e: print(repr(e)) logging.basicConfig(filename='debug.log', level=logging.DEBUG) global stdscr global CANbox stdscr = curses.initscr() curses.start_color() curses.noecho() curses.cbreak() #box is for CAN messages CANbox = curses.newwin(7, 21, 12, 80) CANbox.immedok(True) CANbox.box() CANbox.refresh() #Start background thread for timer timerThread = Timer.timer_Thread timerThread.start() spiThread = SPI.spi_thread spiThread.start() while True: try: # Generate all values generate(BeVolt) # Display all values display(BeVolt) time.sleep(1) # one second delay except KeyboardInterrupt: curses.endwin() if BeVolt is not None: print( "\n\rWould you like to change \n\r1. 'wires'\n\r2. 'quit'\n\r3. 'PLL'\n\r4. send a CAN message ('CAN')\n\r5. 'EEPROM'" ) else: print( "\n\rWould you like to change\n\r1. 'config'\n\r2. 'quit'\n\r3. 'PLL'\n\r4. send a CAN message ('CAN')\n\r5. 'EEPROM'" ) print(">>", end="") choice = input() if (choice == 'wires' or choice == '1') and BeVolt is not None: change_wires(BeVolt) stdscr = curses.initscr() curses.start_color() elif (choice == 'config' or choice == '1') and BeVolt is None: configure() stdscr = curses.initscr() elif choice == 'quit' or choice == '2': break elif choice == 'PLL' or choice == '3': print( "Enter the frequency you would like to change the clock to in Hz." ) frequency = int(input()) PLL.Change_Frequency(frequency) elif choice == 'CAN' or choice == '4': print( "Enter the CAN ID for the system you wish to simulate. Leave out '0x'." ) id = input() while (CAN.Invalid_CAN_ID(id) == True): print("Invalid CAN ID. Try again.") id = input() print( "Enter up to 8 bytes of the CAN message that you would like to send, and separate each byte by a ','. Leave out '0x'." ) message = input().split(',') CAN.Send_Message(id, message, len(message)) elif choice == 'EEPROM' or choice == '5': returnErrorCodes = 0 print( "Enter 'all' for all data or 'read' to enter specific address to read." ) print(">>", end="") choiceEEPROM1 = input() print( "Enter 'raw' to read the raw hex values or 'msg' for the translated error messages.", end="\n") print("If invalid response is given, default is raw data.") print(">>", end="") choiceEEPROM2 = input() if choiceEEPROM2 == 'raw': returnErrorCodes = 0 elif choiceEEPROM2 == 'msg': returnErrorCodes = 1 else: print("Invalid entry...", end="\n") print("Defaulted to raw data.") if choiceEEPROM1 == 'all': print(I2C.EEPROM_Dump(returnErrorCodes)) print("Enter to continue simulator:") print(">>", end="") choice = input() elif choiceEEPROM1 == 'read': print( "Enter address to start reading faults from (in hex format)." ) print(">>", end="") EEPROMstartAddress = input() print( "Enter address to stop reading faults from (in hex format)." ) print(">>", end="") EEPROMendAddress = input() EEPROMstartAddress = int(EEPROMstartAddress, 16) EEPROMendAddress = int(EEPROMendAddress, 16) if EEPROMstartAddress >= 0 and EEPROMstartAddress <= maxEEPROMAddress and EEPROMendAddress >= 0 and EEPROMendAddress <= maxEEPROMAddress: print( I2C.I2C_Read(EEPROMstartAddress, EEPROMendAddress, returnErrorCodes)) print("Enter to continue simulator:") choiceEEPROM = input() else: print("Invalid address...", end="\n") print("Enter to continue simulator:") choiceEEPROM = input() else: print("Invalid entry given for 1st choice (all/read)...", end="\n") print("Enter to continue simulator:") choiceEEPROM = input() else: print("That is not a valid option. Continuing simulation...") stdscr = curses.initscr() curses.start_color() except Exception as e: curses.echo() curses.nocbreak() curses.endwin() print("ERROR:", end=" ") print(repr(e), end="\r\n") exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, fname, exc_tb.tb_lineno) print( "If addwstr() returned ERR, make your terminal window bigger.") print("\n\rContinue? (Y/n): ", end="") cont = input() if (cont.lower() == "n" or cont.lower() == "no"): break print("Continuing...") main() curses.echo() curses.nocbreak() curses.endwin() Timer.terminate(True)
row.append(temperature_values[i][1]) row.append(DCC[i]) values.append(row) row = [] return values # TEST UNIT_TEST = 0 if __name__ == "__main__": if UNIT_TEST: # Test SPI functions import battery BeVolt = battery.Battery( 30, config.total_batt_pack_capacity_mah, 2500 * config.num_batt_cells_parallel_per_module) module_values = read() for i, module in enumerate(module_values): print("| {0} | {1:.4f}V | {2:.3f}°C | {3:.3f}°C |".format( 'X' if module[0] else ' ', module[1] / 10000, module[2] / 1000, module[3] / 1000)) # Test LTC6811 instantiation for ic in range(4): batt_modules = [] lim = 8 # Last ic in chain only monitors 7 battery modules if ic == 3: lim = 7
def main(): print("Welcome to the BPS Simulator") print("Type 'start' to start BeVolt. Otherwise, you can specify the types of data to simulate.") print(">>", end="") if input() == 'start': # Initial capacity is (2500*14)/(2950*14)=0.847 i.e. 84.7% charged init_capacity_mah = 2500 * config.num_batt_cells_parallel_per_module # Amperes current draw of the electrical system ampere_draw = 30 # Create state of the battery BeVolt = battery.Battery(ampere_draw, config.total_batt_pack_capacity_mah, init_capacity_mah) PLL.PLL_Init() else: BeVolt = None configure() try: launch_bevolt() except Exception as e: print(repr(e)) global stdscr global CANbox stdscr = curses.initscr() curses.start_color() curses.noecho() curses.cbreak() #box is for CAN messages CANbox = curses.newwin(7, 21, 12, 78) CANbox.immedok(True) CANbox.box() CANbox.refresh() #Start background thread for timer timerThread = Timer.timer_Thread timerThread.start() while True: try: # Generate all values generate(BeVolt) # Display all values display(BeVolt) time.sleep(1) # one second delay except KeyboardInterrupt: curses.endwin() if BeVolt is not None: print("\n\rWould you like to change 'wires', 'quit', or 'PLL'?") print(">>", end="") choice = input() if choice == 'wires': change_wires(BeVolt) stdscr = curses.initscr() curses.start_color() elif choice == 'quit': break elif choice == 'PLL': print("Enter the frequency you would like to change the clock to in Hz.") frequency = int(input()) PLL.Change_Frequency(frequency) else: print("That is not a valid option. Continuing simulation...") stdscr = curses.initscr() curses.start_color() else: print("\n\rWould you like to change 'config', 'quit', or send a CAN message ('CAN')?") choice = input() if choice == 'config': configure() stdscr = curses.initscr() elif choice == 'quit': break elif choice == 'CAN': print("Enter the CAN ID for the system you wish to simulate. Leave out '0x'.") id = input() while(CAN.Invalid_CAN_ID(id) == True): print("Invalid CAN ID. Try again.") id = input() print("Enter up to 8 bytes of the CAN message that you would like to send, and separate each byte by a ','. Leave out '0x'.") message = input().split(',') CAN.Send_Message(id, message, len(message)) else: print("That is not a valid option. Continuing simulation...") stdscr = curses.initscr() curses.start_color() except Exception as e: curses.echo() curses.nocbreak() curses.endwin() print("ERROR:", end=" ") print(repr(e), end="\r\n") print("If addwstr() returned ERR, make your terminal window bigger.") print("\n\rContinue? (Y/n): ", end="") cont = input() if(cont.lower() == "n" or cont.lower() == "no"): break print("Continuing...") main() curses.echo() curses.nocbreak() curses.endwin() Timer.terminate(True)
import asyncio import can import battery import driver import simulator can0 = can.Bus('vcan0', bustype='socketcan') bat = battery.Battery(capacity=10, cells=30) driver = driver.ChargerDriver(can0) driver.volts = 120 driver.amps = 10 driver.start() sim = simulator.ElconCharger(can0, bat)