Ejemplo n.º 1
0
 def test_sensors_battery_against_sysctl(self):
     self.assertEqual(psutil.sensors_battery().percent,
                      sysctl("hw.acpi.battery.life"))
     self.assertEqual(psutil.sensors_battery().power_plugged,
                      sysctl("hw.acpi.acline") == 1)
     secsleft = psutil.sensors_battery().secsleft
     if secsleft < 0:
         self.assertEqual(sysctl("hw.acpi.battery.time"), -1)
     else:
         self.assertEqual(secsleft, sysctl("hw.acpi.battery.time") * 60)
Ejemplo n.º 2
0
 def test_percent(self):
     w = wmi.WMI()
     battery_wmi = w.query('select * from Win32_Battery')[0]
     battery_psutil = psutil.sensors_battery()
     self.assertAlmostEqual(
         battery_psutil.percent, battery_wmi.EstimatedChargeRemaining,
         delta=1)
Ejemplo n.º 3
0
 def test_power_plugged(self):
     w = wmi.WMI()
     battery_wmi = w.query('select * from Win32_Battery')[0]
     battery_psutil = psutil.sensors_battery()
     # Status codes:
     # https://msdn.microsoft.com/en-us/library/aa394074(v=vs.85).aspx
     self.assertEqual(battery_psutil.power_plugged,
                      battery_wmi.BatteryStatus == 2)
Ejemplo n.º 4
0
 def test_sensors_battery(self):
     out = sh("pmset -g batt")
     percent = re.search("(\d+)%", out).group(1)
     drawing_from = re.search("Now drawing from '([^']+)'", out).group(1)
     power_plugged = drawing_from == "AC Power"
     psutil_result = psutil.sensors_battery()
     self.assertEqual(psutil_result.power_plugged, power_plugged)
     self.assertEqual(psutil_result.percent, int(percent))
Ejemplo n.º 5
0
 def test_sensors_battery_no_battery(self):
     # If no battery is present one of these calls is supposed
     # to fail, see:
     # https://github.com/giampaolo/psutil/issues/1074
     with self.assertRaises(RuntimeError):
         sysctl("hw.acpi.battery.life")
         sysctl("hw.acpi.battery.time")
         sysctl("hw.acpi.acline")
     self.assertIsNone(psutil.sensors_battery())
Ejemplo n.º 6
0
 def test_sensors_battery(self):
     ret = psutil.sensors_battery()
     self.assertGreaterEqual(ret.percent, 0)
     self.assertLessEqual(ret.percent, 100)
     if ret.secsleft not in (psutil.POWER_TIME_UNKNOWN,
                             psutil.POWER_TIME_UNLIMITED):
         self.assertGreaterEqual(ret.secsleft, 0)
     else:
         if ret.secsleft == psutil.POWER_TIME_UNLIMITED:
             self.assertTrue(ret.power_plugged)
     self.assertIsInstance(ret.power_plugged, bool)
Ejemplo n.º 7
0
 def get_status(self):
     info = psutil.sensors_battery()
     status = {
         'type': 'battery',
         'battery_power': not info.power_plugged,
         'battery_charge': info.percent / 100.,
     }
     if status['battery_power']:
         secs = info.secsleft
         if secs >= 0:
             status['remaining_minutes'] = secs / 60.
     return status
Ejemplo n.º 8
0
def main():
    if not hasattr(psutil, "sensors_battery"):
        return sys.exit("platform not supported")
    batt = psutil.sensors_battery()
    if batt is None:
        return sys.exit("no battery is installed")

    print("charge:     %s%%" % round(batt.percent, 2))
    if batt.power_plugged:
        print("status:     %s" % (
            "charging" if batt.percent < 100 else "fully charged"))
        print("plugged in: yes")
    else:
        print("left:       %s" % secs2hours(batt.secsleft))
        print("status:     %s" % "discharging")
        print("plugged in: no")
Ejemplo n.º 9
0
def main():
    if hasattr(psutil, "sensors_temperatures"):
        temps = psutil.sensors_temperatures()
    else:
        temps = {}
    if hasattr(psutil, "sensors_fans"):
        fans = psutil.sensors_fans()
    else:
        fans = {}
    if hasattr(psutil, "sensors_battery"):
        battery = psutil.sensors_battery()
    else:
        battery = None

    if not any((temps, fans, battery)):
        print("can't read any temperature, fans or battery info")
        return

    names = set(list(temps.keys()) + list(fans.keys()))
    for name in names:
        print(name)
        # Temperatures.
        if name in temps:
            print("    Temperatures:")
            for entry in temps[name]:
                print("        %-20s %s°C (high=%s°C, critical=%s°C)" % (
                    entry.label or name, entry.current, entry.high,
                    entry.critical))
        # Fans.
        if name in fans:
            print("    Fans:")
            for entry in fans[name]:
                print("        %-20s %s RPM" % (
                    entry.label or name, entry.current))

    # Battery.
    if battery:
        print("Battery:")
        print("    charge:     %s%%" % round(battery.percent, 2))
        if battery.power_plugged:
            print("    status:     %s" % (
                "charging" if battery.percent < 100 else "fully charged"))
            print("    plugged in: yes")
        else:
            print("    left:       %s" % secs2hours(battery.secsleft))
            print("    status:     %s" % "discharging")
            print("    plugged in: no")
Ejemplo n.º 10
0
    def test_percent(self):
        w = wmi.WMI()
        battery_psutil = psutil.sensors_battery()
        if battery_psutil is None:
            with self.assertRaises(IndexError):
                w.query('select * from Win32_Battery')[0]
        else:
            battery_wmi = w.query('select * from Win32_Battery')[0]
            if battery_psutil is None:
                self.assertNot(battery_wmi.EstimatedChargeRemaining)
                return

            self.assertAlmostEqual(
                battery_psutil.percent, battery_wmi.EstimatedChargeRemaining,
                delta=1)
            self.assertEqual(
                battery_psutil.power_plugged, battery_wmi.BatteryStatus == 1)
Ejemplo n.º 11
0
    def test_sensors_battery(self):
        def secs2hours(secs):
            m, s = divmod(secs, 60)
            h, m = divmod(m, 60)
            return "%d:%02d" % (h, m)

        out = sh("acpiconf -i 0")
        fields = dict([(x.split('\t')[0], x.split('\t')[-1])
                       for x in out.split("\n")])
        metrics = psutil.sensors_battery()
        percent = int(fields['Remaining capacity:'].replace('%', ''))
        remaining_time = fields['Remaining time:']
        self.assertEqual(metrics.percent, percent)
        if remaining_time == 'unknown':
            self.assertEqual(metrics.secsleft, psutil.POWER_TIME_UNLIMITED)
        else:
            self.assertEqual(secs2hours(metrics.secsleft), remaining_time)
Ejemplo n.º 12
0
def sensors_battery():
    result = "no battery is installed"
    if not hasattr(psutil, "sensors_battery"):
        return result
    batt = psutil.sensors_battery()
    if batt is None:
        return result
    result = "charge:     %s%%" % round(batt.percent, 2)
    if batt.power_plugged:
        va ="status:     %s" % (
            "charging" if batt.percent < 100 else "fully charged")
        vb ="plugged in: yes"
        return result + "\n" + va + "\n" + vb 
    else:
        va = "left:       %s" % secs2hours(batt.secsleft)
        vb = "status:     %s" % "discharging"
        vc = "plugged in: no"
        return result + "\n" + va + "\n" + vb + "\n" + vc
Ejemplo n.º 13
0
def getStatusBytes():
    global statusCacheTime, statusCache
    if time.time()< (statusCacheTime+10):
        return statusCache
    statusCacheTime = time.time()
    bstat = 0
    nstat = 255
    temp = 0
    try:
        import psutil
        battery = psutil.sensors_battery()
        bstat = int((battery.percent/100)*63)
        if battery.power_plugged:
            bstat +=128
        else:
            bstat+=0
        temp = 0
        x = psutil.sensors_temperatures()
        for i in x:
            for j in x[i]:
                if temp< j.current:
                    temp = j.current
    except:
        print(traceback.format_exc())
    
    #Linux only
    #TODO: This assumes that if there's wifi,
    #That's what's being used, otherwise we get unknown.
    #This inaccurate data is better than nothing I think.
    try:

        ##This reports WiFi signal level on
        p = subprocess.check_output("iwconfig", stderr=os.devnull)
        sig = int(re.search(b"Signal level=(.*?)dBm",p).group(1).decode("utf8"))
        sig=min(sig, -20)
        sig=max(sig,-120)
        nstat= sig+120
    except:
       pass

    statusCache = struct.pack("<BBb",int(bstat),nstat, max(min(int(temp), 127), -127))
    return statusCache
Ejemplo n.º 14
0
def refresh():
    global last
    disk = bytes2human(disk_usage('/').free)
    ip = gethostbyname(gethostname())
    try:
        ssid = check_output("iwgetid -r", shell=True).strip().decode("utf-8")
        ssid = "(%s)" % ssid
    except Exception:
        ssid = "None"
    battery = sensors_battery()
    percent = int(battery.percent) if battery else 0
    status = ["Discharging", "Charging"]
    status = status[battery.power_plugged] if battery else "Unknown"
    if percent in (15, 10, 5) and status == 'Discharging' and percent != last:
        run(["notify-send", "Battery Low!"])
        last = percent
    date = datetime.now().strftime('%h %d %A %H:%M')
    format = "Space: %s | Internet: %s %s | Battery: %s%% %s | Date: %s"
    format = " %s " % format
    write(format % (disk, ip, ssid, percent, status, date))
Ejemplo n.º 15
0
def cpu():
    usage = str(psutil.cpu_percent())
    speak('CPU is at ' + usage)
    battery = psutil.sensors_battery()
    speak('Battery is at ')
    speak(battery.percentage)
Ejemplo n.º 16
0
 def sensors_battery(self):
     return psutil.sensors_battery()
net = model_zoo.get_model('ssd_512_resnet50_v1_voc', pretrained=True)

#im_fname = utils.download('https://github.com/dmlc/web-data/blob/master/' +
#                          'gluoncv/detection/street_small.jpg?raw=true',
#                          path='street_small.jpg')

x, img = data.transforms.presets.ssd.load_test(filename, short=512)

end = time.time()
row = { }
row['imgname'] = filename
row['host'] = os.uname()[1]
row['shape'] = str(x.shape)
row['end'] = '{0}'.format( str(end ))
row['te'] = '{0}'.format(str(end-start))
row['battery'] = psutil.sensors_battery()[0]
row['systemtime'] = datetime.datetime.now().strftime('%m/%d/%Y %H:%M:%S')
row['cpu'] = psutil.cpu_percent(interval=1)
usage = psutil.disk_usage("/")
row['diskusage'] = "{:.1f} MB".format(float(usage.free) / 1024 / 1024)
row['memory'] = psutil.virtual_memory().percent
row['id'] = str(uuid)
json_string = json.dumps(row)
# print(json_string)

# MQTT
client = mqtt.Client()
client.username_pw_set("user","pass")
client.connect("server", 17769, 60)
client.publish("gluoncv", payload=json_string, qos=0, retain=True)
Ejemplo n.º 18
0
import os
import psutil
import time

listOfProcessNames = list() 
print(psutil.cpu_times())
print(psutil.sensors_battery())
print(psutil.users())
procs = list(psutil.process_iter()) #get_process_list()
    #procs = sorted(procs, key=lambda proc: proc.name)
 
   
for proc in procs:
   # p = psutil.Process(os.getpid())
    p = psutil.Process(proc.pid)

    #print(p.cpu_percent())
    #print(p.memory_info())
    #print(proc)
    pInfoDict = proc.as_dict(attrs=['pid', 'name', 'cpu_percent','username','open_files'])
    pInfoDict['vms'] = proc.memory_info().vms / (1024 * 1024)
   # Append dict of process detail in list
    listOfProcessNames.append(pInfoDict)

print (listOfProcessNames)



Ejemplo n.º 19
0
 def render(self) -> List[Block]:
     battery = psutil.sensors_battery()
     i, c = self.get_icon, self.get_color_key
     text = f'{battery.percent:.0f}%'
     return self.simple_blocks(icon=i(battery), text=text, color_key=c(battery))
Ejemplo n.º 20
0
def cpu():
    usage = str(psutil.cpu_percent())
    speak("CPU is at"+ usage)
    battery = (psutil.sensors_battery()).percent
    speak("Battery is at")
    speak(battery)
Ejemplo n.º 21
0
 def test_emulate_power_charging(self):
     with mock.patch("psutil._pswindows.cext.sensors_battery",
                     return_value=(0, 8, 0, 0)) as m:
         self.assertEqual(psutil.sensors_battery().secsleft,
                          psutil.POWER_TIME_UNLIMITED)
         assert m.called
Ejemplo n.º 22
0
 def value(self) -> Optional[bool]:
     battery = psutil.sensors_battery()
     if battery is not None:
         return battery.power_plugged
     else:
         return None
Ejemplo n.º 23
0
def battery():
    battery = psutil.sensors_battery()
    speak("Battery is at")
    speak(battery.percent)
Ejemplo n.º 24
0
def cpu():
    speak("Cpu is at {} percent usage".format(psutil.cpu_percent()))
    speak("Battery is at {}percent.".format(psutil.sensors_battery().percent))
Ejemplo n.º 25
0
net_io_counters = json.loads(json.dumps(net_io_counters_val))
net_connections_val = psutil.net_connections()
net_connections = json.loads(json.dumps(net_connections_val))
net_if_addrs_val = psutil.net_if_addrs()
net_if_addrs = json.loads(json.dumps(net_if_addrs_val))
net_if_stats_val = psutil.net_if_stats()
net_if_stats = json.loads(json.dumps(net_if_stats_val))
status['Network']['NetIoCounters'] = net_io_counters
status['Network']['NetConnections'] = net_connections
status['Network']['NetIfAddrs'] = net_if_addrs
status['Network']['NetIfStats'] = net_if_stats

#传感
#sensors_temperatures=psutil.sensors_temperatures()
#sensors_fans=psutil.sensors_fans()
sensors_battery_val = psutil.sensors_battery()
sensors_battery = json.loads(json.dumps(sensors_battery_val))
#status['Sensor']['SensorsTemperatures']=sensors_temperatures
#status['Sensor']['SensorsFans']=sensors_fans
status['Sensor']['SensorsBattery'] = sensors_battery

#系统
boot_time_val = psutil.boot_time()
boot_time = json.loads(json.dumps(boot_time_val))
users_val = psutil.users()
users = json.loads(json.dumps(users_val))
status['System']['BootTime'] = boot_time
status['System']['Users'] = users

print(status)
Ejemplo n.º 26
0
 def __init__(self):
     print(int(psutil.sensors_battery().percent), "%")
Ejemplo n.º 27
0
 def counter(t):
     self.refresh_bar()
     if (psutil.sensors_battery().power_plugged == False and str(int(self.unplugAt)) == str(int(psutil.sensors_battery().percent))):
         self.menu["Charge: "] = "Charge: " + str(psutil.sensors_battery().percent) + "%"
Ejemplo n.º 28
0
 def test_has_battery(self):
     if win32api.GetPwrCapabilities()['SystemBatteriesPresent']:
         self.assertIsNotNone(psutil.sensors_battery())
     else:
         self.assertIsNone(psutil.sensors_battery())
Ejemplo n.º 29
0
top = Checkbutton(root, text='Keep on top')
top.grid(column=1, row=2)
top.state(['!alternate'])
clock_minutes.grid(column=6, row=1)
clock_colon.grid(column=5, row=1)

root.config(bg='black')
root.resizable(False, False)

while True:
    try:
        if ram_display:
            ram.set_value(round(bytes_to_gb(virtual_memory().used), 1))
        else:
            ram.set_value(int(virtual_memory().percent))
        if hasattr(sensors_battery(), 'percent'):
            battery.set(int(sensors_battery().percent))
            if sensors_battery().power_plugged:
                if battery.get() == 100:
                    p_label.config(text=' Fully charged  ')
                else:
                    p_label.config(text='Charging ' +
                                   ('  ' * (3 - len(str(int(battery.get())))) +
                                    str(int(battery.get())) + '%'))
            else:
                p_label.config(text=f'  Battery ' +
                               ('  ' * (3 - len(str(int(battery.get())))) +
                                str(int(battery.get())) + '%  '))
        else:
            p_label.config(text='No batt present')
            battery.set('0')
Ejemplo n.º 30
0
def getBat():
	try:
		d = psutil.sensors_battery()
		return dict(perc=d.percent, plug=d.power_plugged)
	except:
		pass
Ejemplo n.º 31
0
# --- support

HAS_CPU_AFFINITY = hasattr(psutil.Process, "cpu_affinity")
HAS_CPU_FREQ = hasattr(psutil, "cpu_freq")
HAS_CONNECTIONS_UNIX = POSIX and not SUNOS
HAS_ENVIRON = hasattr(psutil.Process, "environ")
HAS_PROC_IO_COUNTERS = hasattr(psutil.Process, "io_counters")
HAS_IONICE = hasattr(psutil.Process, "ionice")
HAS_MEMORY_FULL_INFO = 'uss' in psutil.Process().memory_full_info()._fields
HAS_MEMORY_MAPS = hasattr(psutil.Process, "memory_maps")
HAS_NUM_CTX_SWITCHES = hasattr(psutil.Process, "num_ctx_switches")
HAS_PROC_CPU_NUM = hasattr(psutil.Process, "cpu_num")
HAS_RLIMIT = hasattr(psutil.Process, "rlimit")
HAS_SENSORS_BATTERY = hasattr(psutil, "sensors_battery")
HAS_BATTERY = HAS_SENSORS_BATTERY and psutil.sensors_battery()
HAS_SENSORS_FANS = hasattr(psutil, "sensors_fans")
HAS_SENSORS_TEMPERATURES = hasattr(psutil, "sensors_temperatures")

# --- misc

PYTHON = os.path.realpath(sys.executable)
DEVNULL = open(os.devnull, 'r+')
VALID_PROC_STATUSES = [getattr(psutil, x) for x in dir(psutil)
                       if x.startswith('STATUS_')]
AF_UNIX = getattr(socket, "AF_UNIX", object())
SOCK_SEQPACKET = getattr(socket, "SOCK_SEQPACKET", object())

_subprocesses_started = set()
_pids_started = set()
_testfiles_created = set()
Ejemplo n.º 32
0
def battery_usage():
    usage = psutil.sensors_battery()
    speak("Battery is at")
    speak(usage.percent)
    speak("percent")
    return None
Ejemplo n.º 33
0
def getBatteryStatus():
    myBattery = psutil.sensors_battery()
    batteryStatus = math.floor(myBattery.percent)
    speak("The actual battery status is {} percent !".format(
        (str(batteryStatus))))
Ejemplo n.º 34
0
def msg(percent):
    notification.notify(title="Warning",
                        message=f"Battery is at a low level ({percent:.2f}%)",
                        timeout=50)


def popup():
    result = subprocess.call(
        [f"python prompt.py 'Battery dying soon - {percent:.2f}%'"],
        shell=True)
    print("popup shown")


notification.notify(title="Alert", message="Batmon started", timeout=50)

while 1:
    battery = psutil.sensors_battery()

    if not battery.power_plugged:
        if 7 < battery.percent < 15:
            msg(battery.percent)
            sleep(60)
        elif battery.percent <= 7:
            popup()
            sleep(30)
        else:
            sleep(15)
    else:
        sleep(120)
Ejemplo n.º 35
0
HERE = os.path.abspath(os.path.dirname(__file__))
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
SCRIPTS_DIR = os.path.join(ROOT_DIR, 'scripts')

# --- support

HAS_CPU_AFFINITY = hasattr(psutil.Process, "cpu_affinity")
HAS_CPU_FREQ = hasattr(psutil, "cpu_freq")
HAS_ENVIRON = hasattr(psutil.Process, "environ")
HAS_PROC_IO_COUNTERS = hasattr(psutil.Process, "io_counters")
HAS_IONICE = hasattr(psutil.Process, "ionice")
HAS_MEMORY_MAPS = hasattr(psutil.Process, "memory_maps")
HAS_PROC_CPU_NUM = hasattr(psutil.Process, "cpu_num")
HAS_RLIMIT = hasattr(psutil.Process, "rlimit")
HAS_SENSORS_BATTERY = hasattr(psutil, "sensors_battery")
HAS_BATTERY = HAS_SENSORS_BATTERY and psutil.sensors_battery()
HAS_SENSORS_FANS = hasattr(psutil, "sensors_fans")
HAS_SENSORS_TEMPERATURES = hasattr(psutil, "sensors_temperatures")

# --- misc

PYTHON = os.path.realpath(sys.executable)
DEVNULL = open(os.devnull, 'r+')
VALID_PROC_STATUSES = [getattr(psutil, x) for x in dir(psutil)
                       if x.startswith('STATUS_')]
GET_PIP_URL = "https://bootstrap.pypa.io/get-pip.py"
AF_UNIX = getattr(socket, "AF_UNIX", object())
SOCK_SEQPACKET = getattr(socket, "SOCK_SEQPACKET", object())

TEST_DEPS = []
if sys.version_info[:2] == (2, 6):
Ejemplo n.º 36
0
def cpu():
    usage = str(psutil.cpu_percent())
    speak("the cpu is at " + usage)
    battery = psutil.sensors_battery()
    speak("the battery is at")
    speak(battery.percent)
Ejemplo n.º 37
0
import psutil

bat = psutil.sensors_battery()[0]

print bat
Ejemplo n.º 38
0
 def get_battery(self):
     bat = psutil.sensors_battery()
     if bat:
         return bat._asdict()
     return dict()
Ejemplo n.º 39
0
from glances.logger import logger
from glances.plugins.glances_plugin import GlancesPlugin

# Batinfo library (optional; Linux-only)
batinfo_tag = True
try:
    import batinfo
except ImportError:
    logger.debug("batpercent plugin - Batinfo library not found. Trying fallback to PsUtil.")
    batinfo_tag = False

# PsUtil library 5.2.0 or higher (optional; Linux-only)
psutil_tag = True
try:
    psutil.sensors_battery()
except AttributeError:
    logger.debug("batpercent plugin - PsUtil 5.2.0 or higher is needed to grab battery stats.")
    psutil_tag = False


class Plugin(GlancesPlugin):

    """Glances battery capacity plugin.

    stats is a list
    """

    def __init__(self, args=None):
        """Init the plugin."""
        super(Plugin, self).__init__(args=args)
Ejemplo n.º 40
0
 def test_has_battery(self):
     if win32api.GetPwrCapabilities()['SystemBatteriesPresent']:
         self.assertIsNotNone(psutil.sensors_battery())
     else:
         self.assertIsNone(psutil.sensors_battery())
Ejemplo n.º 41
0
def ac_connected():
    return psutil.sensors_battery().power_plugged
client.connect()

# # Send Data
# for x in range(2, 30, 3):
#     myData={'name' : 'foo', 'cpu' : x, 'mem' : 50}
#     client.publishEvent(eventId="status", msgFormat="json", data=myData, qos=2, onPublish=None)


# Connect and send datapoint(s) into the cloud
# deviceCli.connect()
# for x in range(0, 1000):
while True:
    temp = random.uniform(18,37)
    cpu_percent= psutil.cpu_percent();
    memory= dict(psutil.virtual_memory()._asdict())
    battery = dict(psutil.sensors_battery()._asdict())
    time = datetime.datetime.now()
    computer_state = {"cpu": cpu_percent, "memory": memory, "battery":battery}
    # data = {"simpledev": "ok", "x": temp}

    def myOnPublishCallback():
        print("Confirmed event %s received by IoTF\n" % time)

    # success = client.publishEvent("test", "json", data, qos=0, onPublish=myOnPublishCallback)
    # if not success:
    #     print("Not connected to IoTF")
        
    success1 = client.publishEvent("compute_status", "json", computer_state, qos=0, onPublish=myOnPublishCallback)
    if not success1:
        print("Not connected to IoTF")
import time    
Ejemplo n.º 43
0
 def __init__(self) -> None:
     """ Create a new Battery Object """
     self._battery = psutil.sensors_battery()
     if not self._battery:
         raise Exception("Battery information currently unavailable")
Ejemplo n.º 44
0
def battery():
    return psutil.sensors_battery().percent  # in percentage
Ejemplo n.º 45
0
 def _updateBatteryState(self):
     """Updates the battery state
     """
     battery = psutil.sensors_battery()
     self.plugged = battery.power_plugged
     self.percent = battery.percent
Ejemplo n.º 46
0
 def test_emulate_secs_left_unknown(self):
     with mock.patch("psutil._pswindows.cext.sensors_battery",
                     return_value=(0, 0, 0, -1)) as m:
         self.assertEqual(psutil.sensors_battery().secsleft,
                          psutil.POWER_TIME_UNKNOWN)
         assert m.called
Ejemplo n.º 47
0
 def test_emulate_no_battery(self):
     with mock.patch("psutil._pswindows.cext.sensors_battery",
                     return_value=(0, 128, 0, 0)) as m:
         self.assertIsNone(psutil.sensors_battery())
         assert m.called
Ejemplo n.º 48
0
 def test_sensors_battery(self):
     self.execute(psutil.sensors_battery())
Ejemplo n.º 49
0
 def test_emulate_secs_left_unknown(self):
     with mock.patch("psutil._pswindows.cext.sensors_battery",
                     return_value=(0, 0, 0, -1)) as m:
         self.assertEqual(psutil.sensors_battery().secsleft,
                          psutil.POWER_TIME_UNKNOWN)
         assert m.called
def others(tokens, message, unstopped_tokens, chat): # Funtion defention of Others, passed arguements are the tokenized message and original message or user input

    global callme

    ### WIKIPEDIA SEARCH ####
    
    if "tell" in unstopped_tokens and "about" in unstopped_tokens:
        wiki(unstopped_tokens, message)

    elif "tell" in unstopped_tokens and "more" in unstopped_tokens:
        wiki(unstopped_tokens, message)

    elif "change" in tokens and "date" in tokens:
        set_date()

    elif "date" in tokens:
        datenow(tokens)

    elif "time" in tokens:
        timenow(tokens)

    elif "my" in unstopped_tokens and "username" in unstopped_tokens or "my" in unstopped_tokens and "user" in unstopped_tokens and "name" in unstopped_tokens:
        if "change" in tokens:
            socli(chat, unstopped_tokens)
        username = getpass.getuser()
        print("\nHazel : Your username on this system is ",username)

    elif "look" in unstopped_tokens and "for" in unstopped_tokens:
        wiki(unstopped_tokens, message)

    elif "battery" in tokens and "status" in tokens or "battery" in tokens and "charge" in tokens or "battery" in tokens and "status" in tokens:
        battery = psutil.sensors_battery()
        plugged = battery.power_plugged
        percent = str(battery.percent)
        if plugged==False: plugged="Not Plugged In"
        else: plugged="Plugged In"
        print("\nHazel : Your battery percentage is ", percent + "% | " + plugged)

    elif "ram" in unstopped_tokens and "usage" in unstopped_tokens or "ram" in tokens and "available" in tokens or "ram" in unstopped_tokens and "used" in unstopped_tokens:
        print("\033[1;34;1m")
        mem=str(os.popen('free -t -m').readlines())
        T_ind=mem.index('T')
        mem_G=mem[T_ind+14:-4]
        S1_ind=mem_G.index(' ')
        mem_T=mem_G[0:S1_ind]
        mem_G1=mem_G[S1_ind+8:]
        S2_ind=mem_G1.index(' ')
        mem_U=mem_G1[0:S2_ind]
        mem_F=mem_G1[S2_ind+8:]
        print('Total Memory = ' + mem_T + ' MB')    
        print('Free Memory = ' + mem_F + ' MB')

    elif "list" in unstopped_tokens and "browsers" in unstopped_tokens or "list" in unstopped_tokens and "browser" in unstopped_tokens or "show" in unstopped_tokens and "browser" in unstopped_tokens:
        print("\033[1;34;1m")
        a = os.popen("pacaur -Qqs web browser").read().split("\n")[:20] # Search and index first 20 results
        for i, j in enumerate(a): # display the indexed file
            d[i] = j.split("\n")[0]
            print(d[i])

    elif "list" in unstopped_tokens and "image" in unstopped_tokens or "list" in unstopped_tokens and "image" in unstopped_tokens or "show" in unstopped_tokens and "image" in unstopped_tokens:
        print("\033[1;34;1m")
        a = os.popen("pacaur -Qqs image viewer").read().split("\n")[:20] # Search and index first 20 results
        for i, j in enumerate(a): # display the indexed file
            d[i] = j.split("\n")[0]
            print(d[i])

    elif "partitions" in unstopped_tokens and "system" in unstopped_tokens or "harddisk" in unstopped_tokens and "partitions" in unstopped_tokens or "hdd" in unstopped_tokens and "partitions" in unstopped_tokens:
        print("\033[1;34;1m")
        print("\n")
        os.system("lsblk -f")

    elif "internet" in tokens and "speed" in tokens:
        speedtest()

    elif "new" in unstopped_tokens and "mail" in tokens or "new" in unstopped_tokens and "email" in tokens or "new" in unstopped_tokens and "e-mail" in tokens:
        print("\033[1;34;1m")
        confirm = input("Do you wish to send a new email? ")
        if confirm == 'y' or confirm == 'yes' or confirm == 'ya' or confirm == 'yeah' or confirm == 'yep':
            mail()

    elif "kernel" in unstopped_tokens and "version" in unstopped_tokens or "which" in unstopped_tokens and "kernel" in unstopped_tokens:
        print("\033[1;34;1m")
        os.system("uname -r")  

    elif "my" in unstopped_tokens and "name" in unstopped_tokens:
        if callme == "there" or not callme:
            callme = boss()
        else:
            print("\033[1;34;1m")
            print("\nHazel : Come on, ",callme, "stop testing our relationship! I know who you are.")

    elif "memory" in unstopped_tokens and "usage" in tokens or"memory" in tokens and "available" in tokens or "storage" in tokens and "space" in tokens or "harddisk" in tokens and "space" in tokens and "left" in tokens:
        meminfo()

    elif "Which" in tokens and "os" in tokens and "i" in tokens or "Which" in tokens and "operating system" in tokens and "i" in tokens:
        platform.linux_distribution()

    elif "my" in unstopped_tokens and "os" in tokens or "os" in tokens and "using" in tokens or "operating system" in tokens and "using" in tokens:
        platform.linux_distribution()

    elif "existing" in tokens and "users" in tokens or "list" in tokens and "users" in tokens:
        list_users(tokens)

    elif "new" in tokens and "user" in tokens or "new" in tokens and "account" in tokens:
        adduser(tokens)

    elif "change" in tokens and "password" in tokens:
        chpasswd(tokens)

    elif "remove" in tokens and "user" in tokens or "remove" in tokens and "account" in tokens or "delete" in tokens and "user" in tokens or "delete" in tokens and "account" in tokens:
        deltuser(tokens)

    elif "send" in unstopped_tokens and "mail" in tokens or "send" in unstopped_tokens and "email" in tokens or "send" in unstopped_tokens and "e-mail" in tokens:
        print("\033[1;34;1m")
        confirm = input("Do you wish to send a new email? ")
        if confirm == 'y' or confirm == 'yes' or confirm == 'ya' or confirm == 'yeah' or confirm == 'yep':
            mail()

    elif "how" in unstopped_tokens and "to" in unstopped_tokens:
        socli(chat, unstopped_tokens)

    elif "how" in unstopped_tokens and "can" in unstopped_tokens and "i" in unstopped_tokens:
        socli(chat, unstopped_tokens)

    elif "how" in unstopped_tokens and "will" in unstopped_tokens and "i" in unstopped_tokens:
        socli(chat, unstopped_tokens)

    elif "my" in unstopped_tokens and "ip" in tokens or "my" in unstopped_tokens and "network" in tokens and "address" in tokens or "system" in tokens and "ip" in tokens:
        try:
            print("\033[1;34;1m")
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            print("\nHazel : Your current IP address is", s.getsockname()[0])
            s.close()
        except Exception as e:
            print("\033[1;34;1m")
            print("no connection")
            s.close()

    elif "where" in unstopped_tokens and "is" in unstopped_tokens:
        wiki(unstopped_tokens, message)

    elif "get" in unstopped_tokens and "details" in unstopped_tokens:
        wiki(unstopped_tokens, message)

    elif "tell" in unstopped_tokens and "me" in unstopped_tokens and "about" in unstopped_tokens:
        wiki(unstopped_tokens, message)

    elif "get" in unstopped_tokens and "information" in unstopped_tokens:
        wiki(unstopped_tokens, message)
 
    elif "what" in unstopped_tokens and "is" in unstopped_tokens and "my" not in unstopped_tokens:
        socli(chat, unstopped_tokens)

    elif "call" in unstopped_tokens and "me" in unstopped_tokens:
        if callme == 'there' or not callme:
            callme = boss()
        else:
            print(callme)

    elif "internet" in tokens and "active" in tokens or "internet" in tokens and "connected" in tokens or "available" in tokens:
        is_connected()

    elif "who" in unstopped_tokens and "is" in unstopped_tokens or "who" in unstopped_tokens and "was" in unstopped_tokens:
        wiki(unstopped_tokens, message)


    ### GOOGLE SEARCH ###

    elif "google" in tokens: # googler api search to display top 10 results from google with link, links open in default browser 
        cmd = "googler"
        print("To quit the search results, type q")
        os.system(cmd + " " + message) # perform command in shell


    ### Close the application, ctrl+c or ctrl+z wont work ###

    elif "close" in tokens or "q" in tokens or 'quit' in tokens or 'exit' in tokens:
        exit(0)

    ### OPEN FILE MANAGER ###
    ### CURRENTLY SUPPORTS OPENING TEXT FILES OR PROGRAMMING FILES ###

    elif "create" in tokens:
        openfiles()



    #### IF USER INTENDS TO DO NONE OF THE ABOVE ACTIONS, RUN THE hazel_chatter.py FILE TO GET NORMAL CHAT OUTPUTS ###
    ### DEEP LEARNING MODEL NOT IMPLEMENTED YET. CURRENTLY WORKS WITH A TEXT DATABASE TO RETRIEVE AN NLP OUTPUT, THIS IS RECURSIVE CHAT AND NOT GENERATIVE AS IN DEEP LEARNING ###

    else:
        chatter(chat) # Function call to hazel_chatter.py, passed the original user input as asrguement
Ejemplo n.º 51
0
 def test_battery(self):
     if hasattr(psutil, "sensors_battery") and \
             psutil.sensors_battery() is not None:
         self.assert_stdout('battery.py')
     else:
         self.assert_syntax('battery.py')
Ejemplo n.º 52
0
 def _get_battery_status():
     return psutil.sensors_battery()
Ejemplo n.º 53
0
 def test_emulate_no_battery(self):
     with mock.patch("psutil._pswindows.cext.sensors_battery",
                     return_value=(0, 128, 0, 0)) as m:
         self.assertIsNone(psutil.sensors_battery())
         assert m.called
Ejemplo n.º 54
0
def process(query):
    # By this you can get wiki serach results even without opening real wikipedia
    if 'wikipedia' in query:
        speak("Searching wikipedia.....")
        query = query.replace('wikipedia', '')
        result = wikipedia.summary(query, sentences=2)
        # You can increase or decrease the value of sentences parameter.
        # Sentences parameter defines how many lines of results you want.
        print(result)
        speak("According to search..")
        speak(result) # Your AI assistant, Joy will read the search result for you

    # Website opening through webbrowser module
    elif 'open youtube' in query:
        speak("Opening youtube....")
        webbrowser.get("windows-default").open('youtube.com')

    # You can also tell specifically what you actually search on youtube. ex: search youtube wasim akram
    elif 'search youtube' in query:
        red_words_yt = ['in', 'youtube', 'on', 'find', 'search youtube', 'search']#we'll not include this word into search bar
        query = query.split()
        green_word_yt = [word for word in query if word.lower() not in red_words_yt] # We'll only include what you serched
        search_key = ''.join(green_word_yt)
        speak("Opening in youtube")
        webbrowser.get("windows-default").open("https://www.youtube.com/results?search_query= "+search_key)

    elif 'news' in query:
        speak("Opening newspaper")
        webbrowser.get("windows-default").open('https://www.prothomalo.com/')
    # command example: search google shakib al hasan(Say anything but include
    # search google before the item you want to search for)
    elif 'search google' in query:
        red_word_gle = ['search', 'google', 'in', 'find', 'search google']
        query = query.split()
        green_word_gle = [word for word in query if word.lower() not in red_word_gle]
        search_key_gle = ''.join(green_word_gle)
        speak("Searching google")
        webbrowser.get("windows-default").open("https://google.com/search?q= "+ search_key_gle)

    elif 'open google' in query:
        speak("opening google ")
        webbrowser.get("windows-default").open('https://www.google.com')

    # Application openning/clossing from your machine

    elif 'file' in query:
        speak("Opening file explorer..")
        file_explorer = "C:\\Users\\JSP-NogorIT\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\System Tools\\File Explorer.lnk"
        os.startfile(file_explorer)
    elif 'open chrome' in query:
        speak("Opening google chrome..")
        chrome_path = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
        os.startfile(chrome_path)

    elif 'close chrome' in query:
        speak("closing Chrome browser")
       # os.system("Taskkill /IM chrome.exe /F")
        os.system("TASKKILL /F /IM chrome.exe")
    # Microsoft Office openning/clossing
    elif 'open word' in query or "microsoft word" in query:
        speak("Opening Microsoft word")
        word_path = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Word.lnk"
        os.startfile(word_path)
    elif 'close word' in query:
        speak("closing Microsoft word")
        os.system("TASKKILL /IM WINWORD.EXE")
    elif 'open powerpoint' in query or "power point" in query:
        speak("Opening Microsoft Powerpoint")
        ppt_path = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\PowerPoint.lnk"
        os.startfile(ppt_path)
    elif 'close powerpoint' in query or 'close power point' in query:
        speak("closing Microsoft Powerpoint")
        os.system("TASKKILL /IM POWERPNT.EXE")
    elif 'open excel' in query or 'microsoft excel' in query:
        speak("Opening Microsoft excel")
        xl_path = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Excel.lnk"
        os.startfile(xl_path)
    elif 'close excel' in query or 'close xl' in query:
        speak("closing Microsoft Excel")
        os.system("TASKKILL /IM EXCEL.EXE")
    # send email query
    elif 'send email' in query or 'send an email'in query or 'email' in query:
        try:
            speak('Sure, What should I say?')
            email_body = takeCommand()
            speak('Got it. Please write the receiver email address ')
            # to = input("Enter the receiver email: ")
            to = pyautogui_functions.email_taking_prompt()
            send_email(to, email_body)
            speak("Succesfully send your mail.")
        except Exception:
            speak('Sorry, I failed to sent the email...Try again please.')
    # Play music
    elif 'play music' in query or 'gana' in query or 'gun' in query:
        speak("Playing Music for you")
        music_path = "C:\\Users\\JSP-NogorIT\\Music"
        music = os.listdir(music_path)
        os.startfile(os.path.join(music_path, music[random.randint(0,118)]))
    #FAQ
    # Time
    elif 'time' in query or 'somoy' in query:
        time()
    # Date
    elif 'what is the date' in query or 'tarikh' in query or "today's date" in query:
        date()
    elif 'coronavirus' in query or 'corona' in query or 'corona virus' in query:
        webbrowser.get("windows-default").open("http://covid19tracker.gov.bd/")
    # Want to who is Joy? He is ready for his introduction...
    elif 'introduce yourself' in query or 'tell me about yourself' in query or 'who are you' in query:
        introduction = ''' I am Joy, your personal AI assistant.
                               I am created by,  Maruf Islam
                               I am ready to make your life easier.
                               Tell me what you want to do?
                               '''
        speak(introduction)
    elif 'thank you' in query:
        speak("Its my pleasure. What else you need")
    # Its time to leave? He will say goodbye to you in a nice way.
    elif 'quit' in query or 'exit' in query or 'goodbye' in query or 'bye' in query or 'sleep' in query or 'stop' in query:
        speak("Goodbye...It was a great time with you.")
        quit()

    #---------------------------------------------------------------------------------------------
    # UPDATE from ver 2.0
    # WolframAlpha integration.
    # Find wolf_alpha.py in this repository for the methods we used
    elif 'calculate' in query or 'solve' in query :
        speak("Give me sometime to calculate..")
        wolf_alpha.math_solver(query)
    elif 'weather' in query or 'forecast' in query:
        speak('Generating.. weather information')
        wolf_alpha.weather(query)
    elif 'what' in query or 'who' in query:
        speak("Let me find it out:")
        wolf_alpha.search(query)
    # Screen capture/shot
    elif 'screenshot' in query or 'screen shot' in query or 'snap' in query or 'snapshot' in query:
        speak("Taking screenshot")
        pyautogui_functions.take_scrnshot()
        speak("Successfully taken. Find it in the selected folder")
    # Jokes. Yeah 'Joy' isn't that much boring'
    elif 'jokes' in query or 'joke' in query or 'fun' in query:
        speak("Ok buddy.. let me remember.")
        jokes = pyjokes.get_joke()
        print(jokes)
        speak('Yeah got it, listen, '+jokes)
    # CPU & Battery info
    elif 'cpu' in query or 'cpu info' in query:
        cpu_usage = str(psutil.cpu_percent())
        speak("Your cpu usage is,"+ cpu_usage)
    # Battery info for laptop
    elif 'battery' in query or 'charge' in query:
        battery = psutil.sensors_battery()
        speak("Your remaining power is" + battery.percent)
    # Basic control
    elif 'sign out' in query or 'logout' in query or 'signout' in query:
        speak("Signing out..")
        os.system('shutdown -l')
    elif 'restart' in query:
        speak("Restarting your machine")
        os.system('shutdown /r /t l')
    elif 'shutdown' in query or 'power off' in query or 'shutting down' in query:
        speak('Shutting down')
        os.system('shutdown /s /t l')
Ejemplo n.º 55
0
 def test_emulate_power_charging(self):
     with mock.patch("psutil._pswindows.cext.sensors_battery",
                     return_value=(0, 8, 0, 0)) as m:
         self.assertEqual(psutil.sensors_battery().secsleft,
                          psutil.POWER_TIME_UNLIMITED)
         assert m.called
Ejemplo n.º 56
0
def battery():
    battery = psutil.sensors_battery()
    speak("battery is at ")
    percent = str(battery.percent)
    speak(percent + " percent")