Beispiel #1
0
async def pi(ctx, *, args):
    member = ctx.message.author
    channel = bot.get_channel(IDs.get("bot-testing"))
    if (isAdmin(member)):
        await ctx.channel.send("Informationen skickas i #bot-testing")
        if args == "temp":
            cpu = CPUTemperature()
            cpu_temp = round(cpu.temperature)
            await channel.send(f"Temp: {cpu_temp}°C")
        elif args == "load":
            load = LoadAverage()
            load_avg = round(load.load_average * 100)
            await channel.send(f"Load: {load_avg}%")
        elif args == "disk":
            disk = DiskUsage()
            disk_usage = round(disk.usage)
            await channel.send(f"Disk: {disk_usage}%")
        elif args == "all":
            cpu = CPUTemperature()
            cpu_temp = round(cpu.temperature)
            load = LoadAverage()
            load_avg = round(load.load_average * 100)
            disk = DiskUsage()
            disk_usage = round(disk.usage)
            await channel.send(
                f"Temp: {cpu_temp}°C \nLoad: {load_avg}% \nDisk: {disk_usage}%"
            )
        else:
            await channel.send(
                f"Jag förstår inte argumentet: {args} \n Jag kan följande: [temp, load, disk, all]"
            )
    else:
        await ctx.channel.send(
            "Endast individer av exceptionell rank har tillgång till denna funktion!"
        )
def send_msg(domains_being_blocked, dns_queries_today, ads_percentage_today, ads_blocked_today):
   json_body = [
       {
           "measurement": "pihole." + HOSTNAME.replace(".", "_"),
           "tags": {
              "host": HOSTNAME
           },
           "fields": {
              "domains_being_blocked": int(domains_being_blocked),
              "dns_queries_today": int(dns_queries_today),
              "ads_percentage_today": float(ads_percentage_today),
              "ads_blocked_today": int(ads_blocked_today),
              "uptime": int(uptime.uptime()),
              "temp": float(CPUTemperature().temperature),
              "load_average": float(LoadAverage().load_average),
              "disk_usage": float(DiskUsage().usage)
           }
       }
    ]
   # InfluxDB host, InfluxDB port, Username, Password, database
   client = InfluxDBClient(INFLUXDB_SERVER, INFLUXDB_PORT, INFLUXDB_USERNAME, INFLUXDB_PASSWORD, INFLUXDB_DATABASE) 

   # Uncomment to create the database (expected to exist prior to feeding it data)
   # client.create_database(INFLUXDB_DATABASE) 

   client.write_points(json_body)
   print(json_body)
    def start(self):
        """Getting the bus"""

        log.info('Initializing sensor GPIOZero')

        # Initialize the hardware driver.
        try:

            # Vanilla MicroPython 1.11 and Pycom MicroPython 1.9.4
            if platform_info.vendor in [
                    platform_info.MICROPYTHON.Vanilla,
                    platform_info.MICROPYTHON.Pycom
            ]:
                raise NotImplementedError('No GPIOZero on MicroPython')

            # CPython SerialBus EPSolar
            elif platform_info.vendor == platform_info.MICROPYTHON.RaspberryPi:
                from gpiozero import CPUTemperature, LoadAverage, DiskUsage
                self.cputemp = CPUTemperature(min_temp=50, max_temp=90)
                self.loadaverage = LoadAverage(min_load_average=0,
                                               max_load_average=2)
                self.diskusage = DiskUsage()

            else:
                raise NotImplementedError(
                    'GPIOZero driver not implemented on this platform')

            return True

        except Exception as ex:
            log.exc(ex, 'GPIOZero hardware driver failed')
Beispiel #4
0
    def __init__(self, mqtt):
        self.mqtt = mqtt
        self.cpu = CPUTemperature()
        self.disk = DiskUsage()
        self.load = LoadAverage()

        self.cpuTemperature = self.cpu.temperature
        self.diskUsage = self.disk.usage
Beispiel #5
0
def ReadDiskThread(Freq,CSVPath,ClientID,client):
  DoRead = True
  while DoRead :
    try:
      Value = round( DiskUsage().value,2)
#    logging.info("Disk Loop: %s", Value)
      Channel = 'DiskAvg'
      Save2CSV (CSVPath, ClientID, Channel, Value)
      Save2Cayenne (client, Channel, Value, 1)
      time.sleep(Freq)
    except :
      Message = "Exception reading Disk Usage"
      CSV_Message = Message
      DoRead = ProcessError(CSVPath, ClientID, '', CSV_Message, Message)
Beispiel #6
0
async def pi(ctx, *, args):
    member = ctx.message.author
    if(isAdmin(member)):
        if "temp" in args:
            cpu = CPUTemperature()
            cpu_temp = round(cpu.temperature)
            await ctx.channel.send(f"Temp: {cpu_temp}°C")
        if "load" in args:
            load = LoadAverage()
            load_avg = round(load.load_average*100)
            await ctx.channel.send(f"Load: {load_avg}%")
        if "disk" in args:
            disk = DiskUsage()
            disk_usage = round(disk.usage)
            await ctx.channel.send(f"Disk: {disk_usage}%")
        if "all" in args:
            cpu = CPUTemperature()
            load = LoadAverage()
            load_avg = round(load.load_average*100)
            disk = DiskUsage()
            disk_usage = round(disk.usage)
            await ctx.channel.send(f"Temp: {cpu.temperature}°C")
            await ctx.channel.send(f"Load: {load_avg}%")
            await ctx.channel.send(f"Disk: {disk_usage}%")
Beispiel #7
0
def sysstat(bot, update):
    """ Print system status"""
    cpu = CPUTemperature()
    txt = 'CPU temperature is ' + str(cpu.temperature)
    bot.send_message(chat_id=update.message.chat_id, text=txt)

    la = LoadAverage(min_load_average=0, max_load_average=2)
    txt = 'Load average is ' + str(la.value)
    bot.send_message(chat_id=update.message.chat_id, text=txt)

    disk = DiskUsage()
    txt = 'Current disk usage: {}%'.format(disk.usage)
    bot.send_message(chat_id=update.message.chat_id, text=txt)

    #pihole stats

    txt = 'Domains in blocklists: ' + str(pihole.domain_count)
    bot.send_message(chat_id=update.message.chat_id, text=txt)

    txt = 'Percent of blocked queries: ' + str(pihole.ads_percentage)
    bot.send_message(chat_id=update.message.chat_id, text=txt)
Beispiel #8
0
    screenDisplay()


# main
mylcd.lcd_clear()
if __name__ == '__main__':
    try:
        while True:
            print("-----")

            # get data
            cpuTempPrev = cpuTempCurr
            cpuTempCurr = cpu.temperature
            cpuUsagePrev = cpuUsageCurr
            cpuUsageCurr = psutil.cpu_percent()
            disk = DiskUsage()
            ram = psutil.virtual_memory()[2]

            # data stored to generate the CPU's barchart
            lstUsage.append(cpuUsageCurr)

            # display the screens
            showMainInfo()
            showCPUInfo(cpuTempCurr, cpuTempPrev, cpuUsageCurr, cpuUsagePrev)
            showCPUChart(cpuUsageCurr)
            showRAMUsageMini(ram)
            showDiskUsageMini(disk.usage)

            # loop / CPU's barchart reset everything 16 steps (LCD screen size)
            if i > 15:
                i = 0
    start_http_server(8000)

    # Connect to I2C sensors
    i2c = busio.I2C(board.SCL, board.SDA)
    sht31dSensor = adafruit_sht31d.SHT31D(i2c)  #Humidity / Temperature Sensor
    tsl12591Sensor = adafruit_tsl2591.TSL2591(i2c)  #Light Sensor

    # Define guages
    humidity = Gauge('grow_relative_humidity_percentage',
                     'Grow Tent Relative Humidity Percentage')
    temp = Gauge('grow_temperature', 'Grow Tent Temperature', ['units'])
    light = Gauge('grow_light', 'Grow Tent Light', ['spectrum'])
    pi = Gauge('rpi', 'Raspberry Pi', ['internal_device'])

    # Capture Metrics
    while True:
        currentTemp = sht31dSensor.temperature

        temp.labels('fahrenheit').set((currentTemp * (9 / 5)) + 32)
        temp.labels('celsius').set(currentTemp)
        humidity.set(sht31dSensor.relative_humidity)
        light.labels('total').set(tsl12591Sensor.lux)
        light.labels('infrared').set(tsl12591Sensor.infrared)
        light.labels('visable').set(tsl12591Sensor.visible)
        light.labels('full_spectrum').set(tsl12591Sensor.full_spectrum)
        pi.labels('cpu_temperature_celsius').set(CPUTemperature().temperature)
        pi.labels('load_average_5_min').set(LoadAverage().load_average)
        pi.labels('disk_usage_percent').set(DiskUsage().usage)

        time.sleep(1)
Beispiel #10
0
            except Exception as e:
                logger.exception(f"Exception raised: {e}")
        else:
            self.cpu = cpu
            self.la = la
            self.disk = disk
            self.cpu_threshold = False
            self.la_threshold = False
            self.disk_threshold = True
        logger.info(f"Successfully initialised PiStats Object")


if real_run:
    cpu = CPUTemperature(min_temp=50, max_temp=90, threshold=70)
    la = LoadAverage(min_load_average=0, max_load_average=2, threshold=1)
    disk = DiskUsage(threshold=80)
else:
    cpu = 12
    la = 20
    disk = 89

current = PiStats(cpu, la, disk)
insert_to_db(datetime.now(), current.cpu, current.la, current.disk)

# Add in notification system for thresholds
if current.cpu_threshold or current.la_threshold or current.disk_threshold:
    logger.warning(
        f"Threshold exceeded: CPU {current.cpu_threshold}, Load Avg {current.la_threshold}, Disk % {current.disk_threshold}"
    )
    send_email()
else:
from gpiozero import (
        CPUTemperature, PingServer,
        LoadAverage, DiskUsage
    )

cpu = CPUTemperature()
print(cpu.temperature)

# ps = PingServer(host="localhost")
# print(ps.pin_factory)

la = LoadAverage()
print(la.load_average)

du = DiskUsage()
print(du.value)

Beispiel #12
0
#!/usr/bin/env python3

import random
import os
from time import sleep
from paho.mqtt import client as mqtt_client
from gpiozero import CPUTemperature, DiskUsage

cpu = CPUTemperature()
disk_usage = DiskUsage()

broker = os.getenv('MQTT_SERVER', '127.0.0.1')
port = os.getenv('MQTT_PORT', 1833)
hostname = os.getenv('HOSTNAME', 'raspberry')

client_id = f'python-mqtt-{random.randint(0, 100)}'


def connect_mqtt() -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, int(port))
    return client

Beispiel #13
0
import time
from gpiozero import CPUTemperature, LoadAverage, DiskUsage
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException

max_blockcount = 300000
delay = 10
rpc_user = "******"
rpc_password = "******"

# rpc_user and rpc_password are set in the bitcoin.conf file
rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332" %
                                  (rpc_user, rpc_password))
blockcount = rpc_connection.getblockcount()

while blockcount < max_blockcount:
    timestamp = time.time()
    cpu = CPUTemperature().temperature
    load = LoadAverage(minutes=1).load_average
    disk = DiskUsage().usage
    blockcount = rpc_connection.getblockcount()
    print('{}% {}% {}% {}% {}%'.format(timestamp, cpu, load, disk, blockcount))
    time.sleep(delay)