コード例 #1
0
ファイル: bot.py プロジェクト: AndreasH96/Discord-bot-ture
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!"
        )
コード例 #2
0
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)
コード例 #3
0
    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')
コード例 #4
0
ファイル: rpi_status.py プロジェクト: Szbuli/smart-gateway
    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
コード例 #5
0
ファイル: Thread_to_MQTT.py プロジェクト: SteveCossy/IOT
def ReadLoadThread(Freq,CSVPath,ClientID,client):
  DoRead = True
  while DoRead :
    try:
      Value = LoadAverage().load_average
#    logging.info("Load Loop: %s", Value)
      Channel = 'LoadAvg'
      Save2CSV (CSVPath, ClientID, Channel, Value)
      Save2Cayenne (client, Channel, Value, 1)
      time.sleep(Freq)
#      raise Exception('Test exception at line 79 of Thread2MQTT.py')
    except :
      Message = "Exception reading Load Average"
      CSV_Message = Message
      DoRead = ProcessError(CSVPath, ClientID, '', CSV_Message, Message)
コード例 #6
0
ファイル: bot.py プロジェクト: myhrmans/toersten-discord-bot
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}%")
コード例 #7
0
ファイル: rpi_thermo2cx.py プロジェクト: femanov/services
    def __init__(self):
        srv = "cxhw:5."
        hostname = node()
        cx_devname = hostname.replace('-', '_')
        base_dir = '/sys/bus/w1/devices/'
        device_folder = glob.glob(base_dir + '28*')[0]
        device_file = device_folder + '/w1_slave'

        self.cpu_t = CPUTemperature()
        self.la = LoadAverage()

        self.cpu_t_chan = cda.DChan(srv + cx_devname + ".cputemp")
        self.room_t_chan = cda.DChan(srv + cx_devname + ".roomtemp")
        self.la_chan = cda.DChan(srv + cx_devname + ".loadaverage")

        self.room_t_dev = open(device_file, 'r')
        os.set_blocking(self.room_t_dev.fileno(), False)  # make it nonblocking
        self.file_ev = cda.FdEvent(self.room_t_dev)
        self.file_ev.ready.connect(self.fd_ready)
コード例 #8
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)
コード例 #9
0
 def println():
     gateway = Gateway.gateway()
         
     ping = Gateway.pingGateway()
     
     temp = CPUTemperature().temperature
     
     load = LoadAverage().load_average
     
     pid = os.getpid()
     
     ppid = os.getppid()
     
     data = {
         "pid": pid,
         "parent pid": ppid,
         "ping gateway": gateway,
         "ping response": ping,
         "temperature": temp,
         "average load": load
         }
     
     logging.debug("Diagnostics: %s", str(data))
コード例 #10
0
from gpiozero import LEDBarGraph, LoadAverage
import random
from time import sleep
from signal import pause

bar = LEDBarGraph(26, 19, 13, 6, 5, pwm=True)
la = LoadAverage(minutes=1, max_load_average=5)

bar.source = la

pause()
コード例 #11
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)
コード例 #12
0
                self.disk_threshold = disk.is_active
            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()
コード例 #13
0
from gpiozero import LEDBarGraph, LoadAverage
from signal import pause

la = LoadAverage(min_load_average=0, max_load_average=2)
graph = LEDBarGraph(4, 17, 27, 22, pwm=True)

graph.source = la

pause()
コード例 #14
0
import time
import json
import datetime
from gpiozero import CPUTemperature, LoadAverage
from kafka import KafkaProducer

producer = KafkaProducer(
    bootstrap_servers="localhost:9092",
    value_serializer=lambda x: json.dumps(x).encode('utf-8'),
    request_timeout_ms=10000)

while True:
    cpu = CPUTemperature()
    la = LoadAverage()
    producer.send(
        "temp-hum", {
            "temp": cpu.temperature,
            "load": la.load_average,
            "time": str(datetime.datetime.now())
        })
    time.sleep(1)
コード例 #15
0
cpu_temp = 0
cpu_percent = 0
fan_speed = 100
screen_no = -1
disk_total = 0
disk_used = 0
disk_free = 0
disk_percent = 0
date_text = "01.01.1970"
time_text = "00.00.00"
weekday_text = "Sunday"
RST = None

# Loading Classes
cpu = CPUTemperature()
loadAvarage = LoadAverage(min_load_average=0, max_load_average=2, minutes=1)
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)

# Initialize display.
disp.begin()
disp.clear()
disp.display()
width = disp.width
height = disp.height
image = Image.new('1', (width, height))
#image = Image.open("./icon/temperature.bmp").convert("1")
draw = ImageDraw.Draw(image)
draw.rectangle((0, 0, width, height), outline=0, fill=0)
padding = -2
top = padding
bottom = height - padding
コード例 #16
0
ファイル: main.py プロジェクト: rottenoasis/inky-hole
    adsblocked = parsed_json['ads_blocked_today']
    ratioblocked = parsed_json['ads_percentage_today']
    dnsqueries = parsed_json['dns_queries_today']
    clients = parsed_json['unique_clients']
    f.close()
except:
    adsblocked = 'wtf?'
    ratioblocked = 'something wrong'
    # have not seen an exception yet

# Get the temperature
cpu = CPUTemperature()
cpu_temp = str(round(cpu.temperature, 1)) + chr(176) + "C"

# Get the load average
load = LoadAverage(min_load_average=0, max_load_average=1.0)
cpu_load = str(load.value)

# Get the disk usage percentage
du = DiskUsage()
disk_use = str(round(du.usage, 1))

# Set the font
font = ImageFont.truetype(FredokaOne, 19)
# draw the display
draw.text((20, 0), str(current_time.strftime("%Y-%m-%d %H:%M:%S")),
          inky_display.RED, font)
draw.text((20, 17), "CPU:" + str(cpu_load) + " DSK:" + str(disk_use) + "%",
          inky_display.BLACK, font)
draw.text((20, 34), "BLOCKED: " + str(adsblocked), inky_display.RED, font)
draw.text((20, 51),
コード例 #17
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)
コード例 #18
0
def main():
  lumi_sensor = utils.LuminositySensor()
  cpu_temp = CPUTemperature()
  load_average = LoadAverage()
  
  cache = []
  
  last_luminosity = -1
  last_co2 = -1
  update_frequency = 30 # in s
  
  while True:
    with open ("config.json", "r") as f:
        config = json.loads(f.read())
  
    ping_router = PingServer(config["MQTT_SERVER"])
    online = ping_router.value
  
    luminosity = lumi_sensor.get_luminosity(keep_open=update_frequency < 31)
  
    sensor_values = mh_z19.read_all(True)
    sensor_values["time"] = datetime.now().astimezone().isoformat()
    sensor_values["online"] = online
    sensor_values["luminosity"] = luminosity
    sensor_values["cpu_temperature"] =  cpu_temp.temperature
    sensor_values["cpu_load_percent"] = load_average.load_average * 100
    sensor_values["mem_percent"] = psutil.virtual_memory().percent
  
    #print(sensor_values)
   
    # MQTT publish
    if online:
        try:
          publish.single(config["MQTT_PATH"], json.dumps(sensor_values), hostname=config["MQTT_SERVER"])
        except Exception as e:
            print(e)
            sensor_values["exception"] = str(e)
            online = False
  
    # if not online, write to cache
    if not online:
        cache += [sensor_values]
    if len(cache) > 59 or (online and len(cache) > 0):
      with open (f"""cache/sensors-{datetime.now().strftime("%Y%m%d-%H%M%S")}.json""", "w") as f:
        f.write(json.dumps(cache))
      cache = []
  
    # change off/online depending on luminosity
    if luminosity < config["DISABLE_WIFI_LUMINOSITY"]:
        if online:
            utils.disable_wifi()
        online = False
    else:
        if not online:
            utils.activate_wifi()
            for i in range(30):
                online = ping_router.value
                if not online:
                    time.sleep(1)
                    continue
                break
  
    if online:
        utils.turn_led_on()
        utils.upload_cache()
    else:
        utils.turn_led_off()
  
    delta_luminosity = luminosity - last_luminosity
    last_luminosity = luminosity
    delta_co2 = sensor_values["co2"] - last_co2 
    last_co2 = sensor_values["co2"]
  
    if abs(delta_luminosity) > 0.01 or abs(delta_co2) > 10:
        update_frequency = 30
    else:
        if luminosity > 0.1:
            update_frequency = 60
        else:
            update_frequency = 60 * 5

  
    utils.wait_for_next_run(seconds=update_frequency)
コード例 #19
0
def get_cpu_usage():
    return int(LoadAverage(minutes=1).load_average * 100)