Advertisement
Guest User

Untitled

a guest
Mar 29th, 2016
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.40 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. #-*- coding: utf-8 -*-
  4. import os, time, psutil, sys
  5. from datetime import datetime as dt, timedelta
  6.  
  7. def bold(input_data, output_length):
  8.     return "__" + str(input_data)[:output_length] + "__"
  9.  
  10.  
  11. def get_info_from_file(file_path):
  12.     with open(file_path, "rt") as status_file:
  13.          charge_number = status_file.read()
  14.          status_file.close()
  15.     return charge_number
  16.    
  17. def update_last_line(file_lines, new_last_line):
  18.     file_lines[len(file_lines) - 1] = new_last_line
  19.     return file_lines
  20.  
  21. def check_log_file(file_path):
  22.     if not os.path.isfile(file_path):
  23.         new_file = open(file_path, 'w')
  24.         new_file.write("Liczenie zużycia baterii\n========================")
  25.         new_file.close()
  26.  
  27. # klasa czasu
  28. # skladaja sie na nia dwie liczby z plikow
  29. # z folderu linuxa o baterii
  30. # ma metody aktualizujaca stan baterii
  31. # i obliczajaca procent stanu baterii
  32. class battery_state:
  33.     def __init__(self):
  34.         self.battery_full = int(get_info_from_file("/sys/class/power_supply/BATC/charge_full"))
  35.         self.battery_charge = int(get_info_from_file("/sys/class/power_supply/BATC/charge_now"))
  36.         self.battery_charge_on_start = self.battery_charge
  37.         self.battery_status = get_info_from_file("/sys/class/power_supply/BATC/status")
  38.    
  39.     def get_percent_charge(self):
  40.         battery_percent_charge = self.battery_charge / self.battery_full
  41.         return int(str(battery_percent_charge * 100)[:2])
  42.        
  43.     def update_battery_charge(self):
  44.         self.battery_charge = int(get_info_from_file("/sys/class/power_supply/BATC/charge_now"))
  45.         self.battery_status = get_info_from_file("/sys/class/power_supply/BATC/status")
  46.        
  47.     def get_current_battery_discharge(self):
  48.         self.update_battery_charge()
  49.         return self.battery_charge_on_start - self.battery_charge
  50.    
  51.     def is_battery_charging(self):
  52.         self.update_battery_charge()
  53.         if not "Dischar" in self.battery_status:
  54.             result = True
  55.         else:
  56.             result = False
  57.        
  58.         return result
  59.        
  60.  
  61. class script_running_time:
  62.     def __init__(self, start_time):
  63.         self.run_time = dt.now() - start_time
  64.         self.start_time = start_time
  65.     def update(self):
  66.         self.run_time = dt.now() - self.start_time
  67.        
  68. class laptop_usage:
  69.     def __init__(self):
  70.         self.cpu_usage_sum = 0
  71.         self.ram_usage_sum = 0
  72.         self.brightness_sum = 0
  73.         self.times_added = 0
  74.         # self.brightness_added = 0
  75.         # self.cpu_times_added = 0
  76.         # self.ram_times_added = 0
  77.        
  78.     # type of data
  79.     # 1 dla CPU
  80.     # 2 dla RAM
  81.     # 3 dla JASNOŚCI
  82.     def get_average_percent(self, type_of_data):
  83.         if type_of_data == 1:  
  84.             average_percent = self.cpu_usage_sum / self.times_added
  85.         elif type_of_data == 2:
  86.             average_percent = self.ram_usage_sum / self.times_added
  87.         elif type_of_data == 3:
  88.             average_percent = self.brightness_sum / self.times_added
  89.         #print(str(self.cpu_usage_sum) + " / " + str(self.cpu_times_added) + " = " + str(average_percent)[:4])
  90.         return average_percent
  91.    
  92.     def update_usage(self):
  93.         self.times_added += 1
  94.        
  95.         self.cpu_usage_sum += psutil.cpu_percent()
  96.         self.ram_usage_sum += psutil.phymem_usage().percent
  97.         self.brightness_sum += float(os.popen("xbacklight").read())
  98.  
  99.     def discharge_time(self, script_uptime, battery_object):
  100.         # liczymy z proporcji, skoro:
  101.         # current_battery_discharge = script_uptime.total_seconds()
  102.         # battery_full = nasz_wynik
  103.         # wiec wynika z tego, ze:
  104.         # nasz_wynik = (battery_full * script_uptime.total_seconds()) / current_battery_discharge
  105.         result_seconds = battery_object.battery_full * script_uptime.total_seconds()
  106.         if battery_object.get_current_battery_discharge() > 0:
  107.            result_seconds /= battery_object.get_current_battery_discharge()
  108.         if debug:
  109.             print(str(result_seconds) + "=" +
  110.                     str(battery_object.battery_full) + "*" +
  111.                     str(script_uptime.total_seconds()) + "/" +
  112.                     str(battery_object.get_current_battery_discharge()))
  113.         return timedelta(seconds=result_seconds)
  114.    
  115. #    def add_usage(self, new_usage, is_cpu):
  116. #        if is_cpu:
  117. #            self.cpu_usage_sum += new_usage
  118. #            self.cpu_times_added += 1
  119. #        else:
  120. #            self.ram_usage_sum += new_usage
  121. #            self.ram_times_added += 1
  122.            
  123.  
  124. # poczatek dzialan
  125. my_battery_state = battery_state()
  126. script_start_time = dt.now()
  127. laptop_uptime = script_running_time(script_start_time)
  128. laptop_stats = laptop_usage()
  129. log_file_path = os.getenv("HOME") + "/login_time.md"
  130. # file_content_on_start
  131. state_of_laptop = ""
  132. last_line_of_log = ""
  133. ram_usage = psutil.phymem_usage().percent
  134. is_loading = my_battery_state.is_battery_charging()
  135. # fix dla openboxa, brak nazwy
  136. if "XDG_CURRENT_DESKTOP" in os.environ:
  137.     user_desktop = os.environ['XDG_CURRENT_DESKTOP']
  138. else:
  139.     user_desktop = "Openbox"
  140. debug = False
  141.  
  142. # jesli sie laduje to nie ma po co zapisywac
  143. if my_battery_state.is_battery_charging():
  144.     sys.exit("Battery is charging")
  145.  
  146. # sprawdzamy czy plik istnieje
  147. check_log_file(log_file_path)
  148.  
  149. # na poczatek tworzymy nowa linie
  150. # w ktorej sa zapisane informacje o stanie komputera na starcie
  151. with open(log_file_path, "a") as out_file:
  152.     start_string = "\nStart " + user_desktop + " o "
  153.     start_string += str(script_start_time.hour) + ":"
  154.     start_string += str(script_start_time.minute)
  155.     start_string += ", stan baterii wynosił "
  156.     start_string += str(my_battery_state.get_percent_charge()) + "%"
  157.     start_string += "(" + str(my_battery_state.battery_charge) + ")"
  158.     start_string += "\n".ljust(len(start_string), "-") + "\nXDDD"
  159.     out_file.write(start_string)
  160.     out_file.close()
  161.    
  162. with open(log_file_path, "rt") as out_file:
  163.     file_content_on_start = out_file.readlines()
  164.  
  165. while True:
  166.     my_battery_state.update_battery_charge()
  167.     laptop_uptime.update()
  168.     laptop_stats.update_usage()
  169.    
  170.     if my_battery_state.is_battery_charging():
  171.         sys.exit("Started battery charging. Good bye!")
  172.  
  173.  
  174.     last_line_of_log = "System działał " + bold(laptop_uptime.run_time, 10)
  175.     last_line_of_log += ", a stan baterii wynosił "
  176.     last_line_of_log += bold(my_battery_state.get_percent_charge(),15) + "%"
  177.     last_line_of_log += "(" + bold(my_battery_state.battery_charge, 15) + ")"
  178.     last_line_of_log += " przy średnim zużyciu CPU równym "
  179.     last_line_of_log += bold(laptop_stats.get_average_percent(1),4) + "%"
  180.     last_line_of_log += ", RAM równemu "
  181.     last_line_of_log += bold(laptop_stats.get_average_percent(2),4) + "%"
  182.     last_line_of_log += " ze średnią jasnością ekranu równą "
  183.     last_line_of_log += bold(laptop_stats.get_average_percent(3),4) + "%."
  184.     if laptop_stats.times_added > 8:
  185.         last_line_of_log += "Z takim zużyciem rozladowanie od 100% do 0 zajęłoby "
  186.         last_line_of_log += bold(laptop_stats.discharge_time(
  187.                                 laptop_uptime.run_time, my_battery_state),10)
  188.    
  189.     file_content = update_last_line(file_content_on_start, last_line_of_log)
  190.    
  191.     with open(log_file_path, "wt") as input_file:
  192.         input_file.writelines(file_content)
  193.         input_file.close()
  194.     time.sleep(5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement