Example #1
0
    def test_sensors_temperatures_against_sysctl(self):
        num_cpus = psutil.cpu_count(True)
        for cpu in range(num_cpus):
            sensor = "dev.cpu.%s.temperature" % cpu
            # sysctl returns a string in the format 46.0C
            sysctl_result = int(float(sysctl(sensor)[:-1]))
            self.assertAlmostEqual(
                psutil.sensors_temperatures()["coretemp"][cpu].current,
                sysctl_result, delta=10)

            sensor = "dev.cpu.%s.coretemp.tjmax" % cpu
            sysctl_result = int(float(sysctl(sensor)[:-1]))
            self.assertEqual(
                psutil.sensors_temperatures()["coretemp"][cpu].high,
                sysctl_result)
Example #2
0
    def __init__(self):
        """Init sensors stats."""
        # Temperatures
        self.init_temp = False
        self.stemps = {}
        try:
            # psutil>=5.1.0, Linux-only
            self.stemps = psutil.sensors_temperatures()
        except AttributeError:
            logger.debug("Cannot grab temperatures. Platform not supported.")
        else:
            self.init_temp = True
            # Solve an issue #1203 concerning a RunTimeError warning message displayed
            # in the curses interface.
            warnings.filterwarnings("ignore")

        # Fans
        self.init_fan = False
        self.sfans = {}
        try:
            # psutil>=5.2.0, Linux-only
            self.sfans = psutil.sensors_fans()
        except AttributeError:
            logger.debug("Cannot grab fans speed. Platform not supported.")
        else:
            self.init_fan = True

        # !!! Disable Fan: High CPU consumption with psutil 5.2.0 or higher
        # Delete the two followings lines when corrected (https://github.com/giampaolo/psutil/issues/1199)
        self.init_fan = False
        logger.debug("Fan speed sensors disable (see https://github.com/giampaolo/psutil/issues/1199)")

        # Init the stats
        self.reset()
Example #3
0
    def __init__(self):
        """Init sensors stats."""
        # Temperatures
        self.init_temp = False
        self.stemps = {}
        try:
            # psutil>=5.1.0 is required
            self.stemps = psutil.sensors_temperatures()
        except AttributeError:
            logger.warning("PsUtil 5.1.0 or higher is needed to grab temperatures sensors")
        except OSError as e:
            # FreeBSD: If oid 'hw.acpi.battery' not present, Glances wont start #1055
            logger.error("Can not grab temperatures sensors ({})".format(e))
        else:
            self.init_temp = True

        # Fans
        self.init_fan = False
        self.sfans = {}
        try:
            # psutil>=5.2.0 is required
            self.sfans = psutil.sensors_fans()
        except AttributeError:
            logger.warning("PsUtil 5.2.0 or higher is needed to grab fans sensors")
        except OSError as e:
            logger.error("Can not grab fans sensors ({})".format(e))
        else:
            self.init_fan = True

        # !!! Disable Fan: High CPU consumption is PSUtil 5.2.0
        # Delete the following line when corrected
        self.init_fan = False

        # Init the stats
        self.reset()
Example #4
0
    def build_sensors_list(self, type):
        """Build the sensors list depending of the type.

        type: SENSOR_TEMP_UNIT or SENSOR_FAN_UNIT

        output: a list"""
        ret = []
        if type == SENSOR_TEMP_UNIT and self.init_temp:
            input_list = self.stemps
            self.stemps = psutil.sensors_temperatures()
        elif type == SENSOR_FAN_UNIT and self.init_fan:
            input_list = self.sfans
            self.sfans = psutil.sensors_fans()
        else:
            return ret
        for chipname, chip in iteritems(input_list):
            i = 1
            for feature in chip:
                sensors_current = {}
                # Sensor name
                if feature.label == '':
                    sensors_current['label'] = chipname + ' ' + str(i)
                else:
                    sensors_current['label'] = feature.label
                # Fan speed and unit
                sensors_current['value'] = int(feature.current)
                sensors_current['unit'] = type
                # Add sensor to the list
                ret.append(sensors_current)
                i += 1
        return ret
Example #5
0
 def test_sensors_temperatures_fahreneit(self):
     d = {'coretemp': [('label', 50.0, 60.0, 70.0)]}
     with mock.patch("psutil._psplatform.sensors_temperatures",
                     return_value=d) as m:
         temps = psutil.sensors_temperatures(
             fahrenheit=True)['coretemp'][0]
         assert m.called
         self.assertEqual(temps.current, 122.0)
         self.assertEqual(temps.high, 140.0)
         self.assertEqual(temps.critical, 158.0)
Example #6
0
 def test_sensors_temperatures(self):
     temps = psutil.sensors_temperatures()
     for name, entries in temps.items():
         self.assertIsInstance(name, str)
         for entry in entries:
             self.assertIsInstance(entry.label, str)
             if entry.current is not None:
                 self.assertGreaterEqual(entry.current, 0)
             if entry.high is not None:
                 self.assertGreaterEqual(entry.high, 0)
             if entry.critical is not None:
                 self.assertGreaterEqual(entry.critical, 0)
Example #7
0
def main():
    if not hasattr(psutil, "sensors_temperatures"):
        sys.exit("platform not supported")
    temps = psutil.sensors_temperatures()
    if not temps:
        sys.exit("can't read any temperature")
    for name, entries in temps.items():
        print(name)
        for entry in entries:
            print("    %-20s %s °C (high = %s °C, critical = %s °C)" % (
                entry.label or name, entry.current, entry.high,
                entry.critical))
        print()
Example #8
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")
Example #9
0
def fetch_temps():
    temps = []
    sensors = psutil.sensors_temperatures()
    for thing in sensors:
        for piece in sensors[thing]:
            tcurrent = piece.current
            tmax = piece.high
            tcrit = piece.critical

            if not tcurrent or (not tmax and not tcrit):
                continue
            if not tmax:
                tmax = tcrit
            elif not tcrit:
                tcrit = tmax
            temps.append((thing, tcurrent, tmax, tcrit))

    print(temps)
    return temps
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
Example #11
0
 def test_temperatures(self):
     if hasattr(psutil, "sensors_temperatures") and \
             psutil.sensors_temperatures():
         self.assert_stdout('temperatures.py')
     else:
         self.assert_syntax('temperatures.py')
Example #12
0
 def update(self):
     temps = psutil.sensors_temperatures()
     if self.unit_name in temps:
         self._temp = next(filter(lambda s: s.label==self.sub_label, temps[self.unit_name]), None).current
Example #13
0
 def update(self):
     self.temp = psutil.sensors_temperatures()
     self.set_temperatures()
Example #14
0
 def get_value(self):
     return psutil.sensors_temperatures()
Example #15
0
 def render(self) -> List[Block]:
     sensors: Dict[str, List[Any]] = psutil.sensors_temperatures()
     sensor = sensors['coretemp'][0]
     i, c = self.get_icon, self.get_color_key
     text = f'{sensor.current:.0f}°C'
     return self.simple_blocks(icon=i(sensor), text=text, color_key=c(sensor))
Example #16
0
def hardWare():
    """返回当前主机硬件信息"""
    try:
        monitor = {
            "ret": 0,
            "cpu_info": {},
            "memory": {},
            "disk": {},
            "network": {}
        }
        monitor["cpu_info"]["percent"] = psutil.cpu_percent(percpu=False)
        monitor["memory"]["total"] = psutil.virtual_memory()[0]
        monitor["memory"]["used"] = psutil.virtual_memory()[3]
        monitor["memory"]["available"] = psutil.virtual_memory()[1]
        monitor["memory"]["percent"] = psutil.virtual_memory()[2]
        monitor["disk"]["total"] = psutil.disk_usage("/")[0]
        monitor["disk"]["used"] = psutil.disk_usage("/")[1]
        monitor["disk"]["available"] = psutil.disk_usage("/")[2]
        monitor["disk"]["percent"] = psutil.disk_usage("/")[3]
        monitor["disk"]["read_conut"] = psutil.disk_io_counters()[0]
        monitor["disk"]["write_conut"] = psutil.disk_io_counters()[1]
        monitor["disk"]["read_bytes"] = psutil.disk_io_counters()[2]
        monitor["disk"]["write_bytes"] = psutil.disk_io_counters()[3]
        monitor["disk"]["read_time"] = psutil.disk_io_counters()[4]
        monitor["disk"]["write_time"] = psutil.disk_io_counters()[5]
        monitor["disk"]["busy_time"] = psutil.disk_io_counters()[8]
        monitor["network"]["bytes_sent"] = psutil.net_io_counters()[0]
        monitor["network"]["bytes_recv"] = psutil.net_io_counters()[1]
        monitor["network"]["packets_sent"] = psutil.net_io_counters()[2]
        monitor["network"]["packets_recv"] = psutil.net_io_counters()[3]
        monitor["network"]["errin"] = psutil.net_io_counters()[4]
        monitor["network"]["errout"] = psutil.net_io_counters()[5]
        monitor["cpu_info"]["temperature"] = psutil.sensors_temperatures(
        )["cpu-thermal"][0][1]
        monitor["boot_time"] = time.strftime(
            "%Y-%m-%d %X", time.localtime(psutil.boot_time()))
        monitor["users"] = len(psutil.users())
        monitor["pids"] = len(psutil.pids())
        while True:
            result = instance.read()
            temperature = result.temperature
            humidity = result.humidity
            if temperature != 0 and humidity != 0:
                break
        monitor["temperature"] = temperature
        monitor["humidity"] = humidity
        temperature_humidity_list = []
        if mongoFindOne(temperature_humidity_key):
            temperature_humidity_list = mongoFindOne(
                temperature_humidity_key)["val"][-9:]
        t_h_time_list = []
        t_list = []
        h_list = []
        for msg in temperature_humidity_list:
            a = msg["time"]
            # print a
            # print time.strftime('%H',time.localtime(a))
            t_h_time_list.append(
                time.strftime('%H', time.localtime(msg["time"])))
            t_list.append(msg["temperature"])
            h_list.append(msg["humidity"])
            # print t_h_time_list
        monitor["t_h_time_list"] = t_h_time_list
        monitor["t_list"] = t_list
        monitor["h_list"] = h_list

    except:
        monitor = {"ret": 1001, "err": "[Hardware]Get Monitor Status Failed"}
    finally:
        monitor["time"] = int(time.time())
    # print monitor
    # print '--------------------------------------------------'
    return monitor
def computerInformation():
    try:
        print "System CPU times", 30 * "-", "\n"
        print psutil.cpu_times()
    except:
        print ""
    try:
        print "Number of logical CPUs in the system", 30 * "-", "\n"
        print psutil.cpu_count()
    except:
        print ""
    try:
        print "Number of usable CPUs", 30 * "-", "\n"
        print len(psutil.Process().cpu_affinity())
    except:
        print ""
    try:
        print "CPU statistics", 30 * "-", "\n"
        print psutil.cpu_stats()
    except:
        print ""
    try:
        print "CPU frequency", 30 * "-", "\n"
        print psutil.cpu_freq()
    except:
        print ""
    try:
        print "Statistics about system memory", 30 * "-", "\n"
        print psutil.virtual_memory()
    except:
        print ""
    try:
        print "System swap memory statistics", 30 * "-", "\n"
        print psutil.swap_memory()
    except:
        print ""
    try:
        print "Mounted disk partitions", 30 * "-", "\n"
        print psutil.disk_partitions()
    except:
        print ""
    try:
        print "Disk usage statistics", 30 * "-", "\n"
        print psutil.disk_usage('/')
    except:
        print ""
    try:
        print "System-wide disk I/O statistics", 30 * "-", "\n"
        print psutil.disk_io_counters()
    except:
        print ""
    try:
        print "System-wide network I/O statistics", 30 * "-", "\n"
        print psutil.net_io_counters()
    except:
        print ""
    try:
        print "System-wide socket connections", 30 * "-", "\n"
        print psutil.net_connections()
    except:
        print ""
    try:
        print "The addresses associated to each NIC", 30 * "-", "\n"
        print psutil.net_if_addrs()
    except:
        print ""
    try:
        print "Information about each NIC", 30 * "-", "\n"
        print psutil.net_if_stats()
    except:
        print ""
    try:
        print "Hardware temperatures", 30 * "-", "\n"
        print psutil.sensors_temperatures()
    except:
        print ""
    try:
        print "Hardware fans speed", 30 * "-", "\n"
        print psutil.sensors_fans()
    except:
        print ""
    try:
        print "Battery status information", 30 * "-", "\n"
        battery = psutil.sensors_battery()
        print battery
        print("charge = %s%%, time left = %s" %
              (battery.percent, secs2hours(battery.secsleft)))
    except:
        print ""
    try:
        print "System boot time", 30 * "-", "\n"
        print psutil.boot_time()
    except:
        print ""
    try:
        print "Users currently connected on the system", 30 * "-", "\n"
        print psutil.users()
    except:
        print ""
    try:
        print "Current running PIDs", 30 * "-", "\n"
        print psutil.pids()
    except:
        print ""
Example #18
0
def main():
    fahrenheit = False
    names = False
    testing = False
    time_start = None
    components = "gStfM"
    separator = "  "
    home = os.getenv("HOME")
    draw_icons = False

    pcpu, avg, speed, freqs, temp, fans, b_time, memory, swap, disks_usage, which, ul, dl, xfer_start, xfer_finish, \
        path_to_icon, glyph, c_name= None, None, None, None, None, None, None, None, None, None, None, None, None, None, \
        None, None, None, None

    for i in range(1, len(sys.argv)):
        if sys.argv[i] == "-h" or sys.argv[i] == "--help":
            print_help()
            exit(0)

        if sys.argv[i] == "-F":
            fahrenheit = True

        if sys.argv[i] == "-N":
            names = True

        if sys.argv[i] == "-T":
            testing = True

        if sys.argv[i].startswith("-C"):
            components = sys.argv[i][2::]

        if sys.argv[i].startswith("-S"):
            try:
                # if number given
                spacing = int(sys.argv[i][2::])
                separator = " " * spacing
            except ValueError:
                # string given
                separator = sys.argv[i][2::]

        if sys.argv[i].startswith("-W"):
            try:
                which = int(sys.argv[i][2::])
            except ValueError:
                pass

        if sys.argv[i].upper() == "-ALL":
            components = "gpaQStfMcWDUk"
            names = True
            testing = True

        if sys.argv[i].startswith("-I"):
            draw_icons = True
            # We can only have one icon per executor, so let's strip components to the first one
            components = sys.argv[i][2]
            # exception for UL/DL speed; to assign an icon to it we need to calculate speeds first
            if components != "k":
                path_to_icon = icon_path(home, components)

        if sys.argv[i].startswith("-M"):
            # We can only have a custom name for a single component
            components = components[0]
            names = True
            c_name = sys.argv[i][2::]

    if testing:
        time_start = int(round(time.time() * 1000))

    output = ""

    # Prepare ONLY requested data, ONLY once
    if "g" or "p" in components:
        try:
            pcpu = psutil.cpu_percent(interval=1, percpu=True)
        except:
            pass

    if "a" in components:
        try:
            avg = str(psutil.cpu_percent(interval=1))
            if len(avg) < 4:
                avg = " " + avg
        except:
            pass

    if "s" or "S" in components:
        try:
            speed = psutil.cpu_freq(False)
        except:
            pass

    if "q" or "Q" in components:
        try:
            freqs = psutil.cpu_freq(True)
            if len(freqs) == 0:
                freqs = None
        except:
            pass

    if "t" in components:
        try:
            temp = psutil.sensors_temperatures(fahrenheit)
        except:
            pass

    if "f" in components:
        try:
            fans = psutil.sensors_fans()
        except:
            pass

    if "m" or "M" or "z" or "Z" in components:
        try:
            memory = psutil.virtual_memory()
        except:
            pass

    if "w" or "W" or "x" in components:
        try:
            swap = psutil.swap_memory()
        except:
            pass

    if "k" in components:
        try:
            xfer_start = psutil.net_io_counters()
            time.sleep(1)
            xfer_finish = psutil.net_io_counters()
            ul = (xfer_finish[0] - xfer_start[0]) / 1024
            dl = (xfer_finish[1] - xfer_start[1]) / 1024
            # We've not selected an icon previously. Now we have enough data.
            if draw_icons:
                path_to_icon = net_icon(home, ul, dl)
            else:
                glyph = net_glyph(home, ul, dl)
        except:
            pass

    drives = []
    # Find drive names, mountpoints
    if "d" or "D" or "n" or "N" in components:
        try:
            d = psutil.disk_partitions()
            # This will store name, mountpoint
            for entry in d:
                n = entry[0].split("/")
                name = n[len(n) - 1]
                # name, mountpoint
                drive = name, entry[1]
                drives.append(drive)
        except:
            pass

    if "d" or "D" in components:
        try:
            disks_usage = []
            for drive in drives:
                # Search drives by path
                data = psutil.disk_usage(drive[1])
                # Store name, used, total, percent
                essential = drive[0].upper(), data[1], data[0], data[3]
                disks_usage.append(essential)
        except:
            pass

    if "n" in components or "N" in components:
        try:
            disks_usage = []
            for drive in drives:
                # Search drives by path
                data = psutil.disk_usage(drive[1])
                # Store mountpoint, used, total, percent
                essential = drive[1], data[1], data[0], data[3]
                disks_usage.append(essential)
        except:
            pass

    if "u" or "U" in components:
        try:
            b_time = psutil.boot_time()
        except:
            pass

    # Build output component after component
    output += separator

    for char in components:
        if char == "g" and pcpu is not None:
            if c_name:
                output += c_name
            output += graph_per_cpu(pcpu) + separator

        if char == "p" and pcpu is not None:
            if names:
                output += c_name if c_name else "CPU: "
            output += per_cpu(pcpu) + separator

        if char == "a" and avg is not None:
            if names:
                output += c_name if c_name else ""
            output += avg + "%" + separator

        if char == "q" and freqs is not None:
            if names:
                output += c_name if c_name else ""
            output += freq_per_cpu(freqs)[0][:-1] + "GHz" + separator

        if char == "Q" and freqs is not None:
            if names:
                output += c_name if c_name else ""
            result = freq_per_cpu(freqs)
            output += result[0][:-1] + "/" + str(result[1]) + "GHz" + separator

        if char == "s" and speed is not None:
            if names:
                output += c_name if c_name else ""
            output += str(round(speed[0] / 1000, 1)) + "GHz" + separator

        if char == "S" and speed is not None:
            if names:
                output += c_name if c_name else ""
            output += str(round(speed[0] / 1000, 1)) + "/" + str(
                round(speed[2] / 1000, 1)) + "GHz" + separator

        if char == "t" and temp is not None and len(temp) > 0:
            if names:
                output += c_name if c_name else ""
            output += str(temp["coretemp"][0][1]).split(".")[0]
            output += "℉" if fahrenheit else "℃"
            output += separator

        if char == "f" and fans is not None and len(fans) > 0:
            if names:
                output += c_name if c_name else " "
            fan0 = next(iter(fans.values()))
            output += str(fan0[0][1]) + "/m" + separator

        if char == 'm' and memory is not None:
            if names:
                output += c_name if c_name else " "
            output += str(round(
                (memory[0] - memory[1]) / 1073741824, 1)) + "GB" + separator

        if char == 'M' and memory is not None:
            if names:
                output += c_name if c_name else " "
            output += str(round((memory[3]) / 1073741824, 1)) + "/" + str(
                round(memory[0] / 1073741824, 1)) + "GB" + separator

        if char == 'c' and memory is not None:
            if names:
                output += c_name if c_name else " "
            output += str(memory[2]) + "%" + separator

        if char == 'C' and memory is not None:
            if names:
                output += c_name if c_name else " "
            output += str(100 - memory[2]) + "%" + separator

        if char == 'u' and b_time is not None:
            up_time = int(time.time()) - b_time
            m, s = divmod(up_time, 60)
            h, m = divmod(m, 60)
            if names:
                output += c_name if c_name else " "
            output += "%d:%02d" % (h, m) + separator

        if char == 'U' and b_time is not None:
            up_time = int(time.time()) - b_time
            m, s = divmod(up_time, 60)
            h, m = divmod(m, 60)
            if names:
                output += c_name if c_name else " "
            output += "%d:%02d:%02d" % (h, m, s) + separator

        if char == "w" and swap is not None:
            if names:
                output += c_name if c_name else "SWAP: "
            output += str(round(swap[1] / 1073741824, 1)) + "GB" + separator

        if char == "W" and swap is not None:
            if names:
                output += c_name if c_name else "SWAP: "
            output += str(round(swap[1] / 1073741824, 1)) + "/"
            output += str(round(swap[0] / 1073741824, 1)) + "GB" + separator

        if char == "x" and swap is not None:
            if names:
                output += c_name if c_name else "SWAP: "
            output += str(swap[3]) + "%" + separator

        if char == "d" or char == "n" and disks_usage is not None:
            if which is not None:
                try:
                    entry = disks_usage[which]
                    output += entry[0] + ": "
                    output += str(entry[3]) + "%" + separator
                except IndexError:
                    pass
            else:
                for entry in disks_usage:
                    output += entry[0] + ": "
                    output += str(entry[3]) + "%" + separator

        if char == "D" or char == "N" and disks_usage is not None:
            if c_name:
                output += c_name
            if which is not None:
                try:
                    entry = disks_usage[which]
                    output += entry[0] + ":"
                    output += str(round(entry[1] / 1073741824, 1)) + "/"
                    output += str(round(entry[2] / 1073741824,
                                        1)) + "GB" + separator
                except IndexError:
                    pass
            else:
                for entry in disks_usage:
                    output += entry[0] + ":"
                    output += str(round(entry[1] / 1073741824, 1)) + "/"
                    output += str(round(entry[2] / 1073741824,
                                        1)) + "GB" + separator

        if char == "k":
            if names and xfer_start is not None and xfer_finish is not None:
                output += c_name if c_name else glyph
            output += '%08.2f' % (
                (xfer_finish[0] - xfer_start[0]) / 1024) + '/' + '%08.2f' % (
                    (xfer_finish[1] - xfer_start[1]) /
                    1024) + ' kB/s' + separator

    if testing:
        output += "[" + str(
            int((round(time.time() * 1000)) - time_start) /
            1000) + "s]" + separator

    # remove leading and trailing separator
    l = len(separator)
    if l > 0:
        output = output[l:-l]

    if draw_icons:
        print(path_to_icon)

    print(output)
import time
import serial
import psutil

ser = serial.Serial('/dev/ttyACM0')
ser.baudrate = 9600
ser.flushInput()

cpu = 0
ram = 0
temp = 0

while (1):
    cpu = psutil.cpu_percent()
    ram = psutil.virtual_memory().percent
    temp = psutil.sensors_temperatures()["acpitz"][0][1]
    string_to_send = str(int(cpu)) + "," + str(int(ram)) + "," + str(
        int(temp)) + "\n"
    print(string_to_send)
    ser.write(bytes(string_to_send, encoding='utf8'))
    time.sleep(3)
Example #20
0
# CPU percentage per cpu
    try:
        cpu_percent = psutil.cpu_percent(interval=None, percpu=True)
    except:
        cpu_percent = "\033[1mNO DATA RECEIVED\033[0m"

# CPU frequency
    try:
        cpu_frequency = psutil.cpu_freq()
    except:
        cpu_frequency = "\033[1mNO DATA RECEIVED\033[0m"

# CPU temperarature
    try:
        cpu_temp = psutil.sensors_temperatures()
    except:
        cpu_temp = "\033[1mNO DATA RECEIVED\033[0m"

# MEMORY information
    try:
        memory = psutil.virtual_memory()
    except:
        memory = "\033[1mNO DATA RECEIVED\033[0m"

# CPU fan
    try:
        cpu_fan = psutil.sensors_fans()
    except:
        cpu_fan = "\033[1mNO DATA RECEIVED\033[0m"
Example #21
0
def getCPUTemp():            
    return str(psutil.sensors_temperatures()['cpu-thermal'][0][1])
Example #22
0
def temp():
    return jsonify({'sensors_temperatures':psutil.sensors_temperatures(fahrenheit=False)})
Example #23
0
    #DATA E HORA
    data_e_hora_atuais = datetime.now()
    fuso_horario = timezone('America/Sao_Paulo')
    data_e_hora_sao_paulo = data_e_hora_atuais.astimezone(fuso_horario)
    data = data_e_hora_sao_paulo.strftime('%Y-%m-%d')
    hora = data_e_hora_sao_paulo.strftime('%H:%M:%S')

    #RETORNA UM FLOAT QUE REPRESENTA A UTILIZAÇÃO ATUAL DA CPU DE TODO O SISTEMA COMO UMA PORCENTAGEM
    cpu_percent = psutil.cpu_percent(interval=0.1, percpu=False)

    #RETORNA A FREQUÊNCIA DA CPU, INCLUINDO A FREQUÊNCIA ATUAL EXPRESSA EM MHZ
    cpu_mhz = psutil.cpu_freq(percpu=False)[0]

    #RETORNA A TEMPERATURA MAIS ALTA ENTRE OS NÚCLEOS DA CPU
    temps = psutil.sensors_temperatures(fahrenheit=False)
    name = list(temps.keys())
    cpu_temp = temps[name[0]][0][1]

    #RETORNA ESTATÍSTICAS SOBRE O USO DE MEMÓRIA DO SISTEMA, INCLUINDO O CAMPO PERCENTUAL
    memory_percent = psutil.virtual_memory()[2]

    #RETORNA ESTATÍSTICAS DE USO DE DISCO INCLUINDO A PORCENTAGEM DE USO
    disk_percent = psutil.disk_usage('/')[3]

    #RETORNA AS INFORMAÇÕES DE STATUS DA BATERIA, INCLUINDO A PORCENTAGEM
    battery_percent = psutil.sensors_battery()[0]

    #EXECUÇÃO DAS CONSULTAS SQL EM PYTHON
    sql_zero = "INSERT INTO datahora (data, hora) VALUES (%s, %s)"
    sql_datahora = (data, hora)
Example #24
0
def main():
    t0 = time.time()

    # Initialize empty list of frames for simple_motion_detector
    last_frames = []

    # HOG face detector
    hog = dlib.get_frontal_face_detector()

    # Load gender model
    genderNet, MODEL_MEAN_VALUES, genderList = load_gender_model()

    # Key parameters
    (i_frame, see, date, small_frame_w, h_line_1, h_line_2, n_last_frames,
     delta_threshold, dilate_iterations, min_stripe_area, padding,
     face_padding, hog_threshold, temp_threshold) = key_params()

    # Counters: one for the case where a frame has more than one face, the
    # other for counting how many times the computer has slept to avoid
    # overheating
    face_in_frame, rests = 1, 0

    # Load random forest classifier (get rid of wheel detections)
    forest = load_forest()

    # Create directory for frames
    if not (os.path.isdir(cwd + 'frames_cnn_hog/' + date) or see):
        os.mkdir(cwd + 'frames_cnn_hog/' + date)

    # Create faces DataFrame and encodings array
    df_faces = pd.DataFrame(columns=[
        'date', 'frame', 'face_in_frame', 'h_face', 'RGB', 'score',
        'face_type', 'gender', 'gender_conf'
    ])
    encodings = np.zeros((0, 128))

    # Get video capture of "video_[date].avi" (verbosely)
    n_frame, total_frames, cap = get_video_capture(date, i_frame)

    while True:

        # Set frontal face boolean as False and face_in_frame as 1
        frontal_face = False
        face_in_frame = 1

        n_frame = int(cap.get(cv2.CAP_PROP_POS_FRAMES) + 1)

        # Read frame
        ret, frame = cap.read()

        # Break if not correctly read
        if not ret:
            break

        small_frame = imutils.resize(frame, width=small_frame_w)
        r = frame.shape[1] / small_frame.shape[1]

        fgmask, last_frames = simple_motion_detector(
            small_frame.copy(), n_frame, i_frame, n_last_frames, last_frames,
            delta_threshold, dilate_iterations)

        mov = check_stripe_movement(fgmask, min_stripe_area, h_line_1,
                                    h_line_2)

        if mov:
            # print('PROCESSING')

            rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            rgb_small_frame = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB)

            face_locations = face_recognition.face_locations(rgb_small_frame,
                                                             model="cnn")

            big_face_locations = [
                tuple([int(r * x) for x in face]) for face in face_locations
            ]

            face_encodings = face_recognition.face_encodings(
                rgb_frame, big_face_locations)

            for face_location, big_face_location, face_encoding in zip(
                    face_locations, big_face_locations, face_encodings):
                # print("FACE")
                top, right, bottom, left = face_location

                big_top, big_right, big_bottom, big_left = big_face_location

                rgb = rgb_frame[big_top:big_bottom,
                                big_left:big_right, :].mean(axis=0).mean(
                                    axis=0)

                forest_pred = get_forest_pred(forest, rgb)

                h_face = big_bottom - big_top

                hog_fl, scores, idx = hog_face_loc(rgb_small_frame, top, right,
                                                   bottom, left, padding, hog,
                                                   hog_threshold)

                if len(hog_fl) and forest_pred:
                    # print('FRONTAL')

                    gender, gender_conf = predict_gender(
                        frame, big_top, big_right, big_bottom, big_left,
                        face_padding, MODEL_MEAN_VALUES, genderNet, genderList)

                    draw_face_small_frame(small_frame, face_in_frame, gender,
                                          top, right, bottom, left, padding)

                    df_faces = df_faces.append(
                        {
                            'date': date,
                            'frame': n_frame,
                            'face_in_frame': face_in_frame,
                            'h_face': h_face,
                            'RGB': rgb,
                            'score': scores[0],
                            'face_type': idx[0],
                            'gender': gender,
                            'gender_conf': gender_conf
                        },
                        ignore_index=True)

                    encodings = np.concatenate(
                        (encodings, face_encoding.reshape((1, 128))))

                    frontal_face = True
                    face_in_frame += 1

        if frontal_face and not see:
            cv2.imwrite(
                cwd + 'frames_cnn_hog/' + date + '/' + str(n_frame) + '.jpg',
                small_frame)

        if see:
            key = draw_and_show(small_frame, fgmask, h_line_1, h_line_2)
            if key == ord('q'):
                break

        if ((n_frame % 10000) == 0) and not see:
            df_faces.to_csv(cwd + 'CSVs_cnn_hog/' + date + '_' + str(i_frame) +
                            '.csv')
            np.save((cwd + 'encodings_cnn_hog/' + date + '_' + str(i_frame) +
                     '.npy'), encodings)
            # print('-----------CSV and encodings saved------------')

        if (psutil.sensors_temperatures()['coretemp'][0].current >
                temp_threshold):
            # print('resting...')
            while (psutil.sensors_temperatures()['coretemp'][0].current > 68):
                time.sleep(1)
            rests += 1

    if not see:
        np.save(
            (cwd + 'encodings_cnn_hog/' + date + '_' + str(i_frame) + '.npy'),
            encodings)
        df_faces.to_csv(cwd + 'CSVs_cnn_hog/' + date + '_' + str(i_frame) +
                        '.csv')
        print('CSV and encodings saved')

    cap.release()

    if see:
        cv2.destroyAllWindows()

    print('Processed', n_frame, 'of', total_frames, 'frames')
    print('Faces data shapes:', df_faces.shape, encodings.shape)
    print('Total time:', round((time.time() - t0) / 3600, 2), 'hours')
    print('Rested ' + str(rests) + ' times')
    print('Done processing', date)

    cluster_1_door.main(date)
Example #25
0
#!/usr/bin/python3.6

import json
import psutil
import os
import re

data = {'cpu': {}}

data['cpu']['count'] = psutil.cpu_count(logical=False)
data['cpu']['countLogial'] = psutil.cpu_count(logical=True)

temperatures = psutil.sensors_temperatures()
if 'coretemp' in temperatures:
    temperatures = psutil.sensors_temperatures()['coretemp']
    data['cpu']['temperature'] = {'data': {}, 'high': temperatures[0].high, 'critical': temperatures[0].critical}
    for (key,val) in enumerate(temperatures):
        data['cpu']['temperature']['data'][key] = val.current

data['cpu']['times'] = {}
timesOutput = re.sub(r'([0-1]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]\s*(PM|AM)*\s*', '', os.popen('mpstat -P ALL').read())
timesOutput = re.sub(r'[%]', '', timesOutput)
timesOutput = re.sub(r'[ ]+', ' ', timesOutput).split('\n')
del timesOutput[:2]
timesOutput.pop()
for i, val in enumerate(timesOutput):
    timesOutput[i] = timesOutput[i].split(' ')

data['cpu']['times']['header'] = timesOutput[0] 

data['cpu']['times']['data'] = {}
Example #26
0
async def property_update(device_client, os_type, machine):
    print("[DEBUG] Update System Message")
    # get IP Address
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    ipLocal = s.getsockname()[0]
    s.close()
    ipPublic = requests.get('http://ifconfig.me/ip', timeout=1).text.strip()
    #

    global root_path
    if os_type == "Windows":
        root_path = 'C:/'
        hostname_str = platform.node()
        cpuInfo = ' '.join(
            os.popen('wmic cpu get name').read().splitlines()[2].split())
        cpuCores = psutil.cpu_count()
        biosManufacturer = ' '.join(
            os.popen('wmic bios get Manufacturer').read().splitlines()
            [2].split())
        biosVersion = ''.join(
            os.popen('wmic bios get Version').read().splitlines()[2].split())
        baseboardManufacturer = ''.join(
            os.popen('wmic baseboard get Manufacturer').read().splitlines()
            [2].split())
        baseboardSerialNumber = ''.join(
            os.popen('wmic baseboard get SerialNumber').read().splitlines()
            [2].split())
        baseboardProduct = ''.join(
            os.popen('wmic baseboard get Product').read().splitlines()
            [2].split())
        osVersion = ''.join(
            os.popen('wmic os get Version').read().splitlines()[2].split())
        osBuildNumber = ''.join(
            os.popen('wmic os get BuildNumber').read().splitlines()[2].split())

    elif os_type == "Linux":
        root_path = '/'
        hostname_str = platform.node()
        osVersion = ' '.join(
            os.popen('hostnamectl |grep "Operating System"').read().split(':')
            [1].split())
        osBuildNumber = ' '.join(
            os.popen('hostnamectl |grep "Kernel"').read().split(':')
            [1].split())
        if "x86" in machine:
            cpuInfo = ' '.join(
                os.popen('lscpu |grep "Model name"').read().split(':')
                [1].split())
            biosManufacturer = ' '.join(
                os.popen('cat /sys/class/dmi/id/bios_vendor').read().split())
            biosVersion = ' '.join(
                os.popen('cat /sys/class/dmi/id/bios_version').read().split())
            baseboardManufacturer = ' '.join(
                os.popen('cat /sys/class/dmi/id/board_vendor').read().split())
            baseboardSerialNumber = ' '.join(
                os.popen(
                    'sudo cat /sys/class/dmi/id/board_serial').read().split())
            baseboardProduct = ' '.join(
                os.popen('cat /sys/class/dmi/id/board_name').read().split())
            # Linux Only
            highTemp = psutil.sensors_temperatures()['coretemp'][0][2]
            criticalTemp = psutil.sensors_temperatures()['coretemp'][0][3]
        else:
            biosManufacturer = 'N/A'
            biosVersion = 'N/A'
            baseboardManufacturer = 'N/A'
            baseboardSerialNumber = 'N/A'
            baseboardProduct = 'N/A'
            try:
                cpuInfo = ' '.join(
                    os.popen('lscpu |grep "Model name"').read().split(':')
                    [1].split())
            except:
                cpuInfo = machine
            try:
                highTemp = psutil.sensors_temperatures()['soc-thermal'][0][2]
                criticalTemp = psutil.sensors_temperatures(
                )['soc-thermal'][0][3]
            except:
                highTemp = 0
                criticalTemp = 0

    cpuCores = psutil.cpu_count()
    cpuMaxfreq = psutil.cpu_freq().max
    logicalDISKtotal = psutil.disk_usage(root_path).total
    memTotal = psutil.virtual_memory().total

    # Print Property result
    print('============================')
    print('Property List Upodate >>>>>>')
    print("OS type : {os}".format(os=os_type))
    print("OS Version : {osV}".format(osV=osVersion))
    print("OS Build/Kernel : {osK}".format(osK=osBuildNumber))
    print("Hostname : {host}".format(host=hostname_str))
    print("CPU Info : {cpu}".format(cpu=cpuInfo))
    print("CPU Core Count : {cpus}".format(cpus=cpuCores))
    print("CPU Max Frequency : {cpuMF}".format(cpuMF=cpuMaxfreq))
    if os_type == "Linux":
        print("> CPU High Temp : {cpu_ht} Ce".format(cpu_ht=highTemp))
        print("> CPU Critical : {cpu_ct} Ce".format(cpu_ct=criticalTemp))
    print("BIOS Manufature : {biosM}".format(biosM=biosManufacturer))
    print("BIOS Version : {biosV}".format(biosV=biosVersion))
    print("Board Manufature : {boardM}".format(boardM=baseboardManufacturer))
    print("Board Product : {boardP}".format(boardP=baseboardProduct))
    print(
        "Board SerialNumber : {boardSN}".format(boardSN=baseboardSerialNumber))
    print("System DISK size : {diskSZ}".format(diskSZ=logicalDISKtotal))
    print("Memory size : {memSZ}".format(memSZ=memTotal))
    print("Local IP Address : {ip}".format(ip=ipLocal))
    print("Public IP Address : {ip}".format(ip=ipPublic))

    # For Multiple components
    if os_type == "Windows":
        properties_device_info = pnp_helper.create_reported_properties(
            windows_device_info_component_name,
            hostname=hostname_str,
            cpuInfo=cpuInfo,
            cpuCores=cpuCores,
            cpuMaxfreq=cpuMaxfreq,
            biosManufacturer=biosManufacturer,
            biosVersion=biosVersion,
            baseboardManufacturer=baseboardManufacturer,
            baseboardSerialNumber=baseboardSerialNumber,
            baseboardProduct=baseboardProduct,
            osVersion=osVersion,
            osBuildNumber=osBuildNumber,
            memTotal=memTotal,
            logicalDISKtotal=logicalDISKtotal,
            ipLocal=ipLocal,
            ipPublic=ipPublic,
        )
    elif os_type == "Linux":
        properties_device_info = pnp_helper.create_reported_properties(
            linux_device_info_component_name,
            hostname=hostname_str,
            cpuInfo=cpuInfo,
            cpuCores=cpuCores,
            cpuMaxfreq=cpuMaxfreq,
            biosManufacturer=biosManufacturer,
            biosVersion=biosVersion,
            baseboardManufacturer=baseboardManufacturer,
            baseboardSerialNumber=baseboardSerialNumber,
            baseboardProduct=baseboardProduct,
            osVersion=osVersion,
            osBuildNumber=osBuildNumber,
            memTotal=memTotal,
            logicalDISKtotal=logicalDISKtotal,
            ipLocal=ipLocal,
            ipPublic=ipPublic,
            highTemp=highTemp,
            criticalTemp=criticalTemp,
        )
    global property_updates
    property_updates = asyncio.gather(
        device_client.patch_twin_reported_properties(properties_device_info), )
Example #27
0
 def get_cpu_temp(self):
     cpu_temp = 0
     t = psutil.sensors_temperatures()['coretemp']
     for c in t:
         cpu_temp = max(cpu_temp, c.current)
     return cpu_temp
Example #28
0
def sysinfo():
    """
    get system information
    """

    # processor_info
    model_name = getoutput("egrep 'model name' /proc/cpuinfo -m 1").split(":")[-1]
    print(f"Processor:{model_name}")

    # get core count
    total_cpu_count = int(getoutput("nproc --all"))
    print("Cores:", total_cpu_count)

    # get architecture
    cpu_arch = pl.machine()
    print("Architecture:", cpu_arch)

    # get driver
    driver = getoutput("cpufreqctl.auto-cpufreq --driver")
    print("Driver: " + driver)

    # get usage and freq info of cpus
    usage_per_cpu = psutil.cpu_percent(interval=1, percpu=True)
    # psutil current freq not used, gives wrong values with offline cpu's
    minmax_freq_per_cpu = psutil.cpu_freq(percpu=True)

    # max and min freqs, psutil reports wrong max/min freqs whith offline cores with percpu=False
    max_freq = max([freq.max for freq in minmax_freq_per_cpu])
    min_freq = min([freq.min for freq in minmax_freq_per_cpu])
    print("\n" + "-" * 30 + " Current CPU states " + "-" * 30 + "\n")
    print(f"CPU max frequency: {max_freq:.0f} MHz")
    print(f"CPU min frequency: {min_freq:.0f} MHz\n")

    # get coreid's and frequencies of online cpus by parsing /proc/cpuinfo
    coreid_info = getoutput("egrep 'processor|cpu MHz|core id' /proc/cpuinfo").split("\n")
    cpu_core = dict()
    freq_per_cpu = []
    for i in range(0, len(coreid_info), 3):
        freq_per_cpu.append(float(coreid_info[i + 1].split(':')[-1]))
        cpu = int(coreid_info[i].split(':')[-1])
        core = int(coreid_info[i + 2].split(':')[-1])
        cpu_core[cpu] = core

    online_cpu_count = len(cpu_core)
    offline_cpus = [str(cpu) for cpu in range(total_cpu_count) if cpu not in cpu_core]

    # temperatures
    core_temp = psutil.sensors_temperatures()
    temp_per_cpu = [float("nan")] * online_cpu_count
    try:
        if "coretemp" in core_temp:
            # list labels in 'coretemp'
            core_temp_labels = [temp.label for temp in core_temp["coretemp"]]
            for i, cpu in enumerate(cpu_core):
                # get correct index in core_temp
                core = cpu_core[cpu]
                cpu_temp_index = core_temp_labels.index(f"Core {core}")
                temp_per_cpu[i] = core_temp["coretemp"][cpu_temp_index].current
        elif "k10temp" in core_temp:
            # https://www.kernel.org/doc/Documentation/hwmon/k10temp
            temp_per_cpu = [core_temp["k10temp"][0].current] * online_cpu_count
        elif "zenpower" in core_temp:
            # https://github.com/AdnanHodzic/auto-cpufreq/issues/145#issuecomment-763294009
            temp_per_cpu = [core_temp["zenpower"][0].current] * online_cpu_count
        elif "acpitz" in core_temp:
            temp_per_cpu = [core_temp["acpitz"][0].current] * online_cpu_count
    except:
        pass

    print("\t Usage  Temperature  Frequency")
    for (cpu, usage, freq, temp) in zip(cpu_core, usage_per_cpu, freq_per_cpu, temp_per_cpu):
        print(f"CPU{cpu}:\t{usage:>5.1f}%    {temp:>3.0f} °C    {freq:>5.0f} MHz")

    if offline_cpus:
        print(f"\nDisabled CPUs: {','.join(offline_cpus)}")

    # get average temperature of all cores
    avg_cores_temp = sum(temp_per_cpu)
    global avg_all_core_temp
    avg_all_core_temp = float(avg_cores_temp/online_cpu_count)
Example #29
0
def burn(x: int = cpu_count()) -> heat_metrics:
    try:
        if x >= cpu_count():
            x = x - 1
        x * x
    except:
        raise SystemExit
    return heat_metrics(mins=float(argv[2]), cool=False)


if __name__ == '__main__':
    try:
        n_cpu = int(argv[1])
        ts = datetime.now()
        device = 'nct6796'
        T0 = sensors_temperatures().get(device)[2].current
        c = Fore.GREEN
        nc = Style.RESET_ALL
        print(ts)
        print(' {c}{}°{nc} CPUs: {c}{}{nc}'.format(T0, n_cpu, c=c, nc=nc))
        with Pool(n_cpu) as p:
            p.map(burn, range(n_cpu))

        print('\n Starting {}Cooling{nc} until {c}{}{nc}'.format(Fore.BLUE,
                                                                 T0,
                                                                 c=c,
                                                                 nc=nc))
        ts0 = datetime.now()
        heat_metrics(mins=1, cool=True, limit=T0)
        ts_d = ts0 - datetime.now()
        print('Finished Cooling in {c}{}'.format(ts_d, c=c))
Example #30
0
def GetSensorsTemperature():
    senstemp = psutil.sensors_temperatures(fahrenheit=False)
    return senstemp
Example #31
0
 def test_temperatures(self):
     if not psutil.sensors_temperatures():
         self.skipTest("no temperatures")
     self.assert_stdout('temperatures.py')
Example #32
0
 def _get_cpu_tmp_(self):
     return str(psutil.sensors_temperatures()['cpu-thermal'][0].current)
Example #33
0
    def _machine_stats(self):
        """
        :return: machine stats dictionary, all values expressed in megabytes
        """
        cpu_usage = [float(v) for v in psutil.cpu_percent(percpu=True)]
        stats = {
            "cpu_usage": sum(cpu_usage) / float(len(cpu_usage)),
        }

        bytes_per_megabyte = 1024**2

        def bytes_to_megabytes(x):
            return x / bytes_per_megabyte

        virtual_memory = psutil.virtual_memory()
        stats["memory_used_gb"] = bytes_to_megabytes(
            virtual_memory.used) / 1024
        stats["memory_free_gb"] = bytes_to_megabytes(
            virtual_memory.available) / 1024
        disk_use_percentage = psutil.disk_usage(Text(Path.home())).percent
        stats["disk_free_percent"] = 100.0 - disk_use_percentage
        with warnings.catch_warnings():
            if logging.root.level > logging.DEBUG:  # If the logging level is bigger than debug, ignore
                # psutil.sensors_temperatures warnings
                warnings.simplefilter("ignore", category=RuntimeWarning)
            sensor_stat = (psutil.sensors_temperatures() if hasattr(
                psutil, "sensors_temperatures") else {})
        if "coretemp" in sensor_stat and len(sensor_stat["coretemp"]):
            stats["cpu_temperature"] = max(
                [float(t.current) for t in sensor_stat["coretemp"]])

        # update cached measurements
        net_stats = psutil.net_io_counters()
        stats["network_tx_mbs"] = bytes_to_megabytes(net_stats.bytes_sent)
        stats["network_rx_mbs"] = bytes_to_megabytes(net_stats.bytes_recv)
        io_stats = psutil.disk_io_counters()
        stats["io_read_mbs"] = bytes_to_megabytes(io_stats.read_bytes)
        stats["io_write_mbs"] = bytes_to_megabytes(io_stats.write_bytes)

        # check if we can access the gpu statistics
        if self._gpustat:
            try:
                gpu_stat = self._gpustat.new_query()
                for i, g in enumerate(gpu_stat.gpus):
                    # only monitor the active gpu's, if none were selected, monitor everything
                    if self._active_gpus and i not in self._active_gpus:
                        continue
                    stats["gpu_%d_temperature" % i] = float(
                        g["temperature.gpu"])
                    stats["gpu_%d_utilization" % i] = float(
                        g["utilization.gpu"])
                    stats["gpu_%d_mem_usage" % i] = 100. * float(
                        g["memory.used"]) / float(g["memory.total"])
                    # already in MBs
                    stats["gpu_%d_mem_free_gb" %
                          i] = float(g["memory.total"] -
                                     g["memory.used"]) / 1024
                    stats["gpu_%d_mem_used_gb" %
                          i] = float(g["memory.used"]) / 1024
            except Exception:
                # something happened and we can't use gpu stats,
                self._gpustat_fail += 1
                if self._gpustat_fail >= 3:
                    self._task.get_logger().report_text(
                        'TRAINS Monitor: GPU monitoring failed getting GPU reading, '
                        'switching off GPU monitoring')
                    self._gpustat = None

        return stats
Example #34
0
 def test_sensors_temperatures(self):
     # Duplicate of test_system.py. Keep it anyway.
     for name, units in psutil.sensors_temperatures().items():
         self.assertIsInstance(name, str)
         for unit in units:
             self.assertIsInstance(unit.label, str)
Example #35
0
 def test_sensors_temperatures(self):
     # Duplicate of test_system.py. Keep it anyway.
     for name, units in psutil.sensors_temperatures().items():
         self.assertIsInstance(name, str)
         for unit in units:
             self.assertIsInstance(unit.label, str)
Example #36
0
#!/usr/bin/python3
import psutil
import socket
import time

TARGET_IP="192.168.28.53"
TARGET_PORT=1234

while True:
  temperature = 0.0
  time.sleep(0.5)
  temperature += psutil.sensors_temperatures()["coretemp"][0].current
  time.sleep(0.5)
  temperature += psutil.sensors_temperatures()["coretemp"][0].current
  time.sleep(0.5)
  temperature += psutil.sensors_temperatures()["coretemp"][0].current
  time.sleep(0.5)
  temperature += psutil.sensors_temperatures()["coretemp"][0].current
  time.sleep(0.5)
  temperature += psutil.sensors_temperatures()["coretemp"][0].current
  temperature /= 5.0

  cores = psutil.cpu_percent(percpu=True)

  out = str(temperature) + "," + ",".join(map(str, sorted(cores, reverse=True)))
  socket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto(out.encode("utf-8"), (TARGET_IP, TARGET_PORT))
Example #37
0
def run():
    db = Database()
    _time = int(time.time())
    cpu_usage = psutil.cpu_percent()
    disk_space = psutil.disk_usage('/var/lib/docker')
    disk_usage = psutil.disk_io_counters(perdisk=False)
    network_usage = psutil.net_io_counters(pernic=True)
    temperatures = psutil.sensors_temperatures()

    def get_average(items):
        items = [item.current for item in items]
        return sum(items) / len(items)

    db.insert_hardware(
        _time, {
            "component": "ram",
            "hw_id": None,
            "utilisation": psutil.virtual_memory().percent,
            "temperature": None,
            "power_consumption": None,
        })

    db.insert_hardware(
        _time, {
            "component": "disk_space",
            "hw_id": None,
            "utilisation": disk_space.free,
            "temperature": None,
            "power_consumption": None,
        })
    '''
    db.insert_hardware(_time, {
        "component": "disk_usage",
        "hw_id": None,
        "utilisation": disk_usage.read_count,
        "temperature": None,
        "power_consumption": None,
    })

    for item in network_usage:
        db.insert_hardware(_time, {
            "component": "network",
            "hw_id": item,
            "utilisation": network_usage[item].bytes_recv,
            "temperature": None,
            "power_consumption": None,
        })
    '''

    db.insert_hardware(
        _time,
        {
            "component": "cpu",
            "hw_id": None,
            "utilisation": psutil.cpu_percent(),
            "temperature": None,  #get_average(temperatures['coretemp']),
            "power_consumption": None,
        })

    for gpu in GPUtil.getGPUs():
        db.insert_hardware(
            _time, {
                "component": "gpu",
                "hw_id": gpu.id,
                "utilisation": gpu.load * 100,
                "temperature": gpu.temperature,
                "power_consumption": float(exec("gpu_power", args=(gpu.id))),
            })
Example #38
0
 def test_temperatures(self):
     if hasattr(psutil, "sensors_temperatures") and \
             psutil.sensors_temperatures():
         self.assert_stdout('temperatures.py')
     else:
         self.assert_syntax('temperatures.py')
Example #39
0
def main():

    ####################
    # MEASUREMENTS
    ####################

    # Number of CPUs
    num_total_cpu = psutil.cpu_count(
    )  # Total CPU count (physical and virtual)
    num_physical_cpu = psutil.cpu_count(logical=False)  # Physical CPU count
    min_cpu_freq = psutil.cpu_freq().min  # Minimum operating frequency
    max_cpu_freq = psutil.cpu_freq().max  # Maximum operating frequency

    # Overall motion controller CPU percent usage

    # Ignore first value. See documentation on usage
    psutil.cpu_percent()
    psutil.cpu_percent(percpu=True)

    total_cpu_percent = list()  # Total CPU usage
    per_cpu_percent = list()  # Per CPU usage

    # Real time CPU frequency
    total_cpu_freq = list()  # Real time CPU frequency
    per_cpu_freq = list()  # Real time per CPU frequency

    per_cpu_temp = list()  # CPU temperature

    total_context_switches = 0  # Total number of context switches

    # Resource heavy processes for monitoring
    planning_cpu_affinity = [
        p.cpu_affinity() for p in psutil.process_iter()
        if 'mujin_plannings' in p.as_dict(attrs=['pid', 'name'])['name']
    ]
    rbridges_cpu_affinity = [
        p.cpu_affinity() for p in psutil.process_iter()
        if 'mujin_robotbridges_start' in p.as_dict(
            attrs=['pid', 'name'])['name']
    ]

    ######################
    # INFRASTRUCTURE SETUP
    ######################

    parser = argparse.ArgumentParser(
        description='Script for collecting motion controller data')
    parser.add_argument(
        '-mpt',
        '--motion_controller_port',
        action='store',
        type=int,
        dest='motionServerPort',
        default=24000,
        help='Motion controller data collection server port. Default is 7777')
    parser.add_argument('-vip',
                        '--vision_controller_server',
                        action='store',
                        type=str,
                        dest='visionServerIp',
                        required=True,
                        help='Vision controller IP address')
    parser.add_argument(
        '-vpt',
        '--',
        action='store',
        type=int,
        dest='visionServerPort',
        default=24001,
        help='Vision controller data collection server port. Default is 7777')
    parser.add_argument('-sec',
                        '--seconds',
                        action='store',
                        type=int,
                        dest='samplingRate',
                        default=5,
                        help='Sample frequency: Number of seconds per sample')
    options = parser.parse_args()

    ConfigureLogging()

    # Create server to listen for start event (for collecting motion controller data)
    log.warn(
        'Starting motion controller server and connecting to vision controller server...'
    )
    visionControllerClient = SyncTestWithControllerClient(
        options.visionServerIp, options.visionServerPort
    )  # Create vision controller client to sync tests
    motionControllerServer = SyncTestWithControllerServer(
        options.motionServerPort, visionControllerClient)
    motionControllerServer.Start(
    )  # Spin off thread to listen for start and stop events from motion controller
    log.warn('Created motion controller server!')

    # Wait for start data collection event
    log.warn('Motion server listening for start collection event!')
    while motionControllerServer.ShouldRun() is not True:
        continue
    log.warn(
        'Motion server received start data collection event and successfully synced with vision controller. Starting data collection on motion controller!'
    )

    #########################
    # DATA COLLECTION
    #########################

    # Start measuring context switches
    contextSwitchesStart = psutil.cpu_stats().ctx_switches

    # Waits for controller to set 'isRunningOrderCycle' to False (production cycles finished running)
    lastSample = time.time()
    sampleInterval = options.samplingRate

    while motionControllerServer.ShouldRun() is not False:
        timeLapsed = time.time() - lastSample
        if timeLapsed > sampleInterval:
            total_cpu_percent.append(psutil.cpu_percent())
            per_cpu_percent.append(psutil.cpu_percent(percpu=True))
            total_cpu_freq.append(psutil.cpu_freq().current)
            per_cpu_freq.append(
                [cpuFreq.current for cpuFreq in psutil.cpu_freq(percpu=True)])
            per_cpu_temp.append([
                cpuTemp.current
                for cpuTemp in psutil.sensors_temperatures()['coretemp'][1:(
                    num_total_cpu + 1)]
            ])
            lastSample = time.time()
        else:
            continue

    # Stop measuring context switches
    total_context_switches = psutil.cpu_stats(
    ).ctx_switches - contextSwitchesStart

    log.warn(
        'Stopped data collection on motion controller and requesting vision controller server to stop data collection'
    )

    # Stop motion controller data colelction server
    log.warn('Stopping motion controller server...')
    motionControllerServer.Stop()
    log.warn('Stopped motion controller server!')

    ###################################
    # COLLECT DATA FROM ORDER CYCLE LOG
    ###################################

    # Collect data from /var/log/mujin/ordercycles/ordercycles.log
    logFile = '/var/log/mujin/ordercycles/ordercycles.log'
    orderCycleLogEntry = cpuTestUtilities.ParseRotatedLog(
        logFile,
        logparserfn=lambda cursor, line: (cursor, ujson.loads(line)),
        limit=1)[0][1]

    total_time = float(orderCycleLogEntry['cycleElapsedProcessingTime'])
    num_cycles = len(orderCycleLogEntry['cycleStatistics']['executed'])
    detection_times = [
        cycle['objectDetectionTime']
        for cycle in orderCycleLogEntry['visionStatistics']['detectionHistory']
    ]
    planning_times = [
        cycle['totalPlanningComputationTime']
        for cycle in orderCycleLogEntry['cycleStatistics']['executed']
    ]
    trajectory_times = [
        cycle['trajtotalduration']
        for cycle in orderCycleLogEntry['cycleStatistics']['executed']
    ]

    #####################################
    # WRITE DATA TO FILES AND SAVE GRAPHS
    #####################################

    log.warn('Writing motion controller data...')

    # Data
    kwargs = \
    { \
        'num_total_cpu': num_total_cpu, \
        'num_physical_cpu': num_physical_cpu, \
        'min_cpu_freq': min_cpu_freq, \
        'max_cpu_freq': max_cpu_freq, \
        'total_time': total_time, \
        'num_cycles': num_cycles, \
        'detection_times': detection_times, \
        'planning_times': planning_times, \
        'trajectory_times': trajectory_times, \
        'total_cpu_percent': total_cpu_percent, \
        'per_cpu_percent': per_cpu_percent, \
        'total_cpu_freq': total_cpu_freq, \
        'per_cpu_freq': per_cpu_freq, \
        'per_cpu_temp': per_cpu_temp, \
        'total_context_switches': total_context_switches, \
        'planning_cpu_affinity': planning_cpu_affinity, \
        'rbridges_cpu_affinity': rbridges_cpu_affinity \
    }

    # Write to output file
    WriteDataSaveGraphData(**kwargs)

    log.warn('Finished writing motion controller data!')
Example #40
0
async def view_log(websocket, path):
    global config
    global dmrids
    logging.info('Connected, remote={}, path={}'.format(websocket.remote_address, path))

    try:
        try:
            parse_result = urlparse(path)
        except Exception:
            raise ValueError('Fail to parse URL', format(path))

        path = os.path.abspath(parse_result.path)
        now = datetime.datetime.now(datetime.timezone.utc)
        year = str(now.year)
        month = str(now.month)
        if len(month) == 1:
            month = "0" + month
        day = str(now.day)
        if len(day) == 1:
            day = "0" + day
        
        file_path = ""
        if path == "/MMDVM":
            if config['DEFAULT']['Filerotate'] == "True":
                file_path = config['MMDVMHost']['Logdir']+config['MMDVMHost']['Prefix']+"-"+year+"-"+month+"-"+day+".log"
            else:
                file_path = config['MMDVMHost']['Logdir']+config['MMDVMHost']['Prefix']+".log"
        elif path == "/DAPNET":
            if config['DEFAULT']['Filerotate'] == "True":
                file_path = config['DAPNETGateway']['Logdir']+config['DAPNETGateway']['Prefix']+"-"+year+"-"+month+"-"+day+".log"
            else:
                file_path = config['DAPNETGateway']['Logdir']+config['DAPNETGateway']['Prefix']+".log"

        if path == "/MMDVM" or path == "/DAPNET":
            logging.info(file_path)
            if not os.path.isfile(file_path):
                raise ValueError('File not found', format(file_path))

            with open(file_path, newline = '\n', encoding="utf8", errors='ignore') as f:
                content = ''.join(deque(f, int(config['DEFAULT']['MaxLines'])))
                content = conv.convert(content, full=False)
                lines = content.split("\n")
                for line in lines:
                    if line.find("received") > 0 or line.find("network watchdog") > 0:
                        if line.find("from ") > 0 and line.find("to ") > 0:
                            source = line[line.index("from ") + 5:line.index("to ")].strip()
                            if source in dmrids:
                                line = line.replace(source, dmrids[source])
                            if source in callsigns:
                                newval = source + "$" + callsigns[source] + "$"
                                line = line.replace(source, newval)
                        if line.find("to ") > 0:
                            if line.find("at ") > 0 and line.find("late entry") < 0:
                                target = line[line.index("to ") + 3:line.rindex("at ")]
                                if target in dmrids:
                                    line = line.replace(target, dmrids[target])
                                if target in callsigns:
                                    newval = target + "$" + callsigns[target] + "$"
                                    line = line.replace(target, newval)
                            else:
                                target = line[line.index("to") + 3:]
                                if target.find(",") > 0:
                                    target = target[0:target.index(",")]
                                if target in dmrids:
                                    line = line.replace(target, dmrids[target])
                                if target in callsigns:
                                    newval = target + "$" + callsigns[target] + "$"
                                    line = line.replace(target, newval)
                    await websocket.send(line)

                while True:
                    content = f.read()
                    if content:
                        content = conv.convert(content, full=False)
                        lines = content.split("\n")
                        for line in lines:
                            if line.find("received") > 0 or line.find("network watchdog") > 0 or line.find("transmission lost") > 0:
                                if line.find("from ") > 0 and line.find("to ") > 0:
                                    source = line[line.index("from ") + 5:line.index("to ")].strip()
                                    if source in dmrids:
                                        line = line.replace(source, dmrids[source])
                                    if source in callsigns:
                                        newval = source + "$" + callsigns[source] + "$"
                                        line = line.replace(source, newval)
                                if line.find("to ") > 0:
                                    if line.find("at ") > 0 and line.find("late entry") < 0:
                                        target = line[line.index("to ") + 3:line.rindex("at ")]
                                        if target in dmrids:
                                            line = line.replace(target, dmrids[target])
                                        if target in callsigns:
                                            newval = target + "$" + callsigns[target] + "$"
                                            line = line.replace(target, newval)
                                    else:
                                        target = line[line.index("to") + 3:]
                                        if target.find(",") > 0:
                                            target = target[0:target.index(",")]
                                        if target in dmrids:
                                            line = line.replace(target, dmrids[target])
                                        if target in callsigns:
                                            newval = target + "$" + callsigns[target] + "$"
                                            line = line.replace(target, newval)
                            await websocket.send(line)
                    else:
                        await asyncio.sleep(0.2)
        
        if path == "/SYSINFO":
            mmdvmhost_version = str(subprocess.Popen(config['MMDVMHost']['MMDVM_bin'] + " -v", shell=True, stdout=subprocess.PIPE).stdout.read().decode("utf-8"))
            mmdvmhost_ctime = time.ctime(os.path.getmtime(config['MMDVMHost']['MMDVM_bin']))
            mmdvmhost_buildtime = datetime.datetime.strptime(mmdvmhost_ctime, "%a %b %d %H:%M:%S %Y")
            mmdvm_version = getMMDVMVersion()
            callsign = mmdvmhost_config['General']['Callsign']
            dmrid = mmdvmhost_config['General']['Id']
            txqrg = mmdvmhost_config['Info']['TXFrequency']
            rxqrg = mmdvmhost_config['Info']['RXFrequency']
            await websocket.send("HOSTINFO: mmdvmhost_version:" + mmdvmhost_version + " mmdvmhost_ctime:" + mmdvmhost_ctime + " mmdvm_version:" + mmdvm_version + " callsign:" + callsign + " dmrid:" + dmrid + " txqrg:" + txqrg + " rxqrg:" + rxqrg)
            await asyncio.sleep(1)
            while True:
                cpu_temp = ""
                temps = psutil.sensors_temperatures()
                if not temps:
                    cpu_temp = "N/A"
                for name, entries in temps.items():
                    for entry in entries:
                        if entry.label or name == "cpu_thermal":
                            cpu_temp = str(entry.current)
                cpufrqs = psutil.cpu_freq()
                cpufrq = "N/A"
                if cpufrqs:
                    cpufrq = str(cpufrqs.current)
                cpu_usage = str(psutil.cpu_percent())
                cpu_load = os.getloadavg();
                cpu_load1 = str(cpu_load[0])
                cpu_load5 = str(cpu_load[1])
                cpu_load15 = str(cpu_load[2])
                
                ram = psutil.virtual_memory()
                ram_total = str(ram.total / 2**20)
                ram_used = str(ram.used / 2**20)
                ram_free = str(ram.free / 2**20)
                ram_percent_used = str(ram.percent)
                
                disk = psutil.disk_usage('/')
                disk_total = str(disk.total / 2**30)
                disk_used = str(disk.used / 2**30)
                disk_free = str(disk.free / 2**30)
                disk_percent_used = str(disk.percent)
                
                await websocket.send("SYSINFO: cputemp:" + cpu_temp + " cpufrg:" + cpufrq + " cpuusage:" + cpu_usage + " cpu_load1:" + cpu_load1 + " cpu_load5:" + cpu_load5 + " cpu_load15:" + cpu_load15 + " ram_total:" + ram_total + " ram_used:" + ram_used + " ram_free:" + ram_free + " ram_percent_used:" + ram_percent_used + " disk_total:" + disk_total + " disk_used:" + disk_used + " disk_free:" + disk_free + " disk_percent_used:" + disk_percent_used)
                await asyncio.sleep(10)

        if path == "/SERVICES":
            services_items = [x for x in config.items('ServiceMonitoring') if x[0] not in config.defaults()]
            while True:
                for key, value in services_items:
                    logging.info('key: ' + key + " = " + value)
                    if checkIfProcessRunning(value):
                        logging.info('process ' + value + " is running")
                        await websocket.send("SERVICESMONITOR: " + value + ":running")
                    else:
                        logging.info('process ' + value + " is stopped")
                        await websocket.send("SERVICESMONITOR: " + value + ":stopped")
                await asyncio.sleep(30)

    except ValueError as e:
        try:
            await websocket.send('Logtailer-Errormessage: ValueError: {}'.format(e))
            await websocket.close()
        except Exception:
            pass

        log_close(websocket, path, e)

    except Exception as e:
        try:
            await websocket.send('Logtailer-Errormessage: Error: {}'.format(e))
            await websocket.close()
        except Exception:
            pass
        log_close(websocket, path, e)

    else:
        log_close(websocket, path)
Example #41
0
async def handle_input(data, reader: asyncio.StreamReader,
                       writer: asyncio.StreamWriter):
    format = data.get("type", None)
    if format is None:
        # if the client won't tell us what they're sending why should we even bother
        log.warning(
            f"server: Broken client sent data without a type. Dropping")
        raise TypeError("Invalid packet (no type given)")

    if format == "ping":
        # Send back a double with ping time in ms
        writer.write(struct.pack(">d", client.latency * 1000))
        await writer.drain()
        return

    if format == "status":

        # Send back a whole dict of information
        response = {
            "time": time.time(),
            "active": client.active,
            "uptime": time.perf_counter() - client.first_execution,
            "latency": client.latency * 1000,
            "servers": len(client.guilds),
            "msg_count": client.message_count,
            "cmd_count": client.command_count,
            "cache_len": len(client._connection._messages),
            "pid": os.getpid(),
            "hostname": socket.gethostname(),
            "cpu_temp":
            psutil.sensors_temperatures()['cpu-thermal'][0].current,
        }

        response = json.dumps(response).encode()
        length = len(response)
        response = struct.pack(">L", length) + response
        writer.write(response)
        await writer.drain()
        return

    if format == "msg_send":

        target_id = data.get("id", None)
        message = data.get("msg", "")
        if target_id is None:
            raise ValueError("No target provided")
        if message == "":
            raise ValueError("No message provided")

        target: discord.User = client.get_user(target_id)
        if target is None:
            target: discord.TextChannel = client.get_channel(target_id)
            if target is None:
                raise LookupError("Unknown recipient")
            assert isinstance(target, discord.TextChannel)
        else:
            assert isinstance(target, discord.User)

        try:
            msg = await target.send(message)
        except discord.Forbidden as exc:
            response = {
                "success": False,
                "error": "Invalid Permissions",
                "description": f"Forbidden: {str(exc)}"
            }
        except discord.HTTPException as exc:
            response = {
                "success": False,
                "error": "Message Send Failure",
                "description": f"HTTPException: {str(exc)}"
            }
        except Exception as exc:
            response = {
                "success": False,
                "error": "Unknown error",
                "description": str(exc)
            }
        else:
            response = {
                "success": True,
                "time": str(msg.created_at),
                "guild": msg.guild.name,
                "channel": msg.channel.name,
            }
        response = json.dumps(response).encode()
        response = struct.pack(">L", len(response)) + response
        writer.write(response)
        await writer.drain()
        return

    if format == "enable":
        client.active = True
        writer.write(struct.pack(">L?", 1, True))
        await writer.drain()
        return

    if format == "disable":
        client.active = False
        writer.write(struct.pack(">L?", 1, True))
        await writer.drain()
Example #42
0
    async def stats(self, ctx):
        _(
            """Show some stats about the bot, ranging from hard- and software statistics, over performance to ingame stats."""
        )
        async with self.bot.pool.acquire() as conn:
            characters = await conn.fetchval("SELECT COUNT(*) FROM profile;")
            items = await conn.fetchval("SELECT COUNT(*) FROM allitems;")
            pg_version = conn.get_server_version()
        temps = psutil.sensors_temperatures()
        temps = temps[list(temps.keys())[0]]
        cpu_temp = statistics.mean(x.current for x in temps)
        pg_version = f"{pg_version.major}.{pg_version.micro} {pg_version.releaselevel}"
        d0 = self.bot.user.created_at
        d1 = datetime.datetime.now()
        delta = d1 - d0
        myhours = delta.days * 1.5
        sysinfo = distro.linux_distribution()
        if self.bot.owner_ids:
            owner = nice_join(
                [str(await self.bot.get_user_global(u)) for u in self.bot.owner_ids]
            )
        else:
            owner = str(await self.bot.get_user_global(self.bot.owner_id))
        guild_count = sum(
            await self.bot.cogs["Sharding"].handler("guild_count", self.bot.shard_count)
        )
        meminfo = psutil.virtual_memory()
        cpu_freq = psutil.cpu_freq()
        cpu_name = await get_cpu_name()
        compiler = re.search(r".*\[(.*)\]", sys.version)[1]

        embed = discord.Embed(
            title=_("IdleRPG Statistics"),
            colour=0xb8bbff,
            url=self.bot.BASE_URL,
            description=_(
                "Official Support Server Invite: https://support.idlerpg.xyz"
            ),
        )
        embed.set_thumbnail(url=self.bot.user.avatar_url)
        embed.set_footer(
            text=f"IdleRPG {self.bot.version} | By {owner}",
            icon_url=self.bot.user.avatar_url,
        )
        embed.add_field(
            name=_("Hosting Statistics"),
            value=_(
                """\
CPU: **{cpu_name}**
CPU Usage: **{cpu}%**, **{cores}** cores/**{threads}** threads @ **{freq}** GHz
RAM Usage: **{ram}%** (Total: **{total_ram}**)
CPU Temperature: **{cpu_temp}°C**
Python Version **{python}** <:python:445247273065250817>
discord.py Version **{dpy}**
Compiler: **{compiler}**
Operating System: **{osname} {osversion}**
Kernel Version: **{kernel}**
PostgreSQL Version: **{pg_version}**
Redis Version: **{redis_version}**"""
            ).format(
                cpu_name=cpu_name,
                cpu=psutil.cpu_percent(),
                cores=psutil.cpu_count(logical=False),
                threads=psutil.cpu_count(),
                cpu_temp=round(cpu_temp, 2),
                freq=cpu_freq.max / 1000
                if cpu_freq.max
                else round(cpu_freq.current / 1000, 2),
                ram=meminfo.percent,
                total_ram=humanize.naturalsize(meminfo.total),
                python=platform.python_version(),
                dpy=pkg.get_distribution("discord.py").version,
                compiler=compiler,
                osname=sysinfo[0].title(),
                osversion=sysinfo[1],
                kernel=os.uname().release if os.name == "posix" else "NT",
                pg_version=pg_version,
                redis_version=self.bot.redis_version,
            ),
            inline=False,
        )
        embed.add_field(
            name=_("Bot Statistics"),
            value=_(
                """\
Code lines written: **{lines}**
Shards: **{shards}**
Servers: **{guild_count}**
Characters: **{characters}**
Items: **{items}**
Average hours of work: **{hours}**"""
            ).format(
                lines=self.bot.linecount,
                shards=self.bot.shard_count,
                guild_count=guild_count,
                characters=characters,
                items=items,
                hours=myhours,
            ),
            inline=False,
        )
        await ctx.send(embed=embed)
Example #43
0
                        (int(0*scale),int(90*scale)),
                        font,
                        scale / font_scale,
                        (0,255,0),
                        int(1*scale))

            loads = psutil.getloadavg()
            cv2.putText(images[2][2],
                        f'LOAD  = {loads}',
                        (int(0*scale),int(120*scale)),
                        font,
                        scale / font_scale,
                        (0,255,0),
                        int(1*scale))

            temps = psutil.sensors_temperatures()
            package_temp = temps['coretemp'][0].current
            package_limit = temps['coretemp'][0].high
            cv2.putText(images[2][2],
                        f'CPU T = {package_temp:.1f} C',
                        (int(0*scale),int(150*scale)),
                        font,
                        scale / font_scale,
                        (0,255,0) if package_temp < package_limit else (0,255,255),
                        int(1*scale))

            gpu_percs = pynvml.nvmlDeviceGetUtilizationRates(gpuObj)
            gpu_mem   = pynvml.nvmlDeviceGetMemoryInfo(gpuObj)
            cv2.putText(images[2][2],
                        f'GPU % = Time : {gpu_percs.gpu}  Mem : {100*gpu_mem.used/gpu_mem.total:.0f}',
                        (int(0*scale),int(180*scale)),
Example #44
0
import requests
import psutil
id = 45

temp = psutil.sensors_temperatures()['coretemp'][0][1]
count = psutil.cpu_count()

url = 'http://localhost:8000/storedata'

import time
t = time.time()

while True:
    if time.time() - t > 5:
        temp = psutil.sensors_temperatures()['coretemp'][0][1]
        myobj = {'data': str(id) + ',' + str(count) + ',' + str(temp)}
        x = requests.post(url, json=myobj)
        print(myobj['data'])
        t = time.time()