def updateGauges(id): myValue = 0 #if (useRandom == True): # myValue = random.randint(0,100) # return myValue # update Lowest Percent Moisture Sensor if (id['GaugeType'] == "pi-disk"): #timeDelta = datetime.timedelta(days = 5) #myRecord = returnLowestSensorValue("C1", timeDelta) #print("driestValue=",myRecord) #return (myRecord[0][1],myRecord[0][2], myRecord[0][3],myRecord[0][5]) myValue = psutil.disk_usage('/') myDPercent = myValue[3] #print("myDPercent=", myDPercent) myDPercent = 100.0 - myDPercent return myDPercent # update CPU Loading if (id['GaugeType'] == "pi-loading"): myValue = psutil.cpu_percent() return myValue # update Pi Memory usage if (id['GaugeType'] == "pi-memory"): myValue = psutil.virtual_memory().percent return myValue # update Pi Temperature usage if (id['GaugeType'] == "pi-temp"): cpu = gpiozero.CPUTemperature() CPUTemperature = cpu.temperature myValue = CPUTemperature return myValue
def _measure_utilities(self): """ システムのハードウェア情報を取得します。 return 測定結果 """ # CPU使用率(1秒平均) cpu_usage = psutil.cpu_percent(interval=1) # CPU温度 try: import gpiozero cpu_temp = gpiozero.CPUTemperature().temperature except Exception: cpu_temp = None # メモリ使用量 memory_usage = psutil.virtual_memory().percent # ディスク使用率 # 取得する場合は Greengrass Lambda の設定で「コンテナなし」にする。 # Greengrassコンテナ上でLambdaを動作させている場合は、ディスク使用率が0になる。 disk_usage = psutil.disk_usage(path='/').percent utilities = { 'cpu_usage': cpu_usage, 'cpu_temp': cpu_temp, 'memory_usage': memory_usage, 'disk_usage': disk_usage } # None要素の除去 filtered = {k: v for k, v in utilities.items() if v is not None} utilities.clear() utilities.update(filtered) return utilities
def update_function(self): '''update function for pi_dash providing basic system information This plugin displays system information for this raspberry pi and requires that the user running this plugin has access to the GPIO group. Args: self(`namespace`) Returns: tuple: (is_updated(bool), data(dict), priority(int)) %U''' logging.debug( f'## {constants.name} v{constants.version} update_function ##') data = constants.data failure = False, data, self.max_priority try: pi_temp = gpiozero.CPUTemperature() pi_load = gpiozero.LoadAverage() pi_disk = gpiozero.DiskUsage() pi_info = gpiozero.pi_info() except gpiozero.GPIOZeroError as e: logging.warning(f'error getting gpio data: {e}') logging.warning(f'returning: {failure}') return failure img_path = Path(constants.img_path) logging.debug(f'using images stored in: {img_path}') try: hostname = socket.gethostname() except Exception as e: logging.warning(f'error getting hostname: {e}') hostname = 'Unknown' try: data = { 'temp': f'{int(pi_temp.temperature)}C', 'temp_icon': img_path / 'Thermometer_icon.png', 'load': f'{pi_load.load_average}', 'cpu_icon': img_path / 'CPU_icon.png', 'disk_use': f'{int(pi_disk.usage)}%', 'disk_icon': img_path / 'SSD_icon.png', 'pi_model': f'Pi {pi_info.model} rev {pi_info.revision}', 'pi_logo': img_path / 'pi_logo.png', 'hostname': hostname } except Exception as e: logging.warning(f'failed to read GPIO data: {e}') logging.waringin(f'returning: {failure}') return failure return True, data, self.max_priority
def run(self): influx_url = 'http://%s:8086/write' % ( self.settings['heartbeatServer'], ) while self.running: cpu = gpiozero.CPUTemperature() s = 'raspi.temperature_celsius,host=%s value=%f %d' % ( socket.gethostname(), math.floor( cpu.temperature), time.time_ns()) r = requests.post(influx_url, params={'db': 'cube'}, data=s) time.sleep(30)
def behave(self): current_temp = gpiozero.CPUTemperature().temperature if self._fan_state == 1 and current_temp <= 30: self._fan_state = False self._fan.value = self._fan_state self.log_cpu_temp_and_fan_state(current_temp) elif self._fan_state == 0 and current_temp >= 35: self._fan_state = True self._fan.value = self._fan_state self.log_cpu_temp_and_fan_state(current_temp)
def __getStatusMessage__(): """ concatenates multiple System informations and returns them as a string. WARNING: cpu-temperature works on raspberry pis only and os.getloadavg does not work on Windows --- RETURNS: string """ message = "time: " message += str(datetime.now().time()) message += " |CPU-Temp: " message += str(gpiozero.CPUTemperature().temperature) message += " |Load: " message += str(os.getloadavg()) return message
def monitor_update(): """ returns json pertaining to current system status """ cpu_load = psutil.cpu_percent() if hostname == "raspberryduck": cpu_temp = gpiozero.CPUTemperature().temperature print(f"temp: {cpu_temp}") else: cpu_temp = "not on raspi" return jsonify({ "response": "Hello", "cpu_load": cpu_load, "host": hostname, "cpu_temp": f"{cpu_temp} C" })
def _read(self, **kwargs): logger.debug("Reading CPU usage using psutil") cpu_usage = psutil.cpu_percent() logger.debug("Reading Load Average using psutil") load_avg = psutil.getloadavg() logger.debug("Reading CPU temperature using gpiozero") cpu_temp = gpiozero.CPUTemperature().temperature logger.debug("Reading uptime from /proc/uptime") with open('/proc/uptime', 'r') as uptime_file: uptime = float(uptime_file.readline().split()[0]) logger.info("Read {}% CPU usage at {}°C, load: {}".format( cpu_usage, cpu_temp, load_avg)) return [cpu_usage, cpu_temp, *load_avg, uptime]
def drawheader(self): cpu = gpiozero.CPUTemperature() loadaverage = gpiozero.LoadAverage(minutes=1) nowstring = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") cputempstring = f'CPU Temp: {cpu.temperature:0.0f}C' loadavgstring = f'CPU Load: {loadaverage.load_average:0.2f}' textImage = self.font3.render(nowstring, True, gcfg.g_white) self.screen.blit(textImage, (0, 0)) textImage = self.font3.render(cputempstring, True, gcfg.g_white) self.screen.blit(textImage, ((self.size[0] // 2) - (textImage.get_rect()[2] // 2), 0)) textImage = self.font3.render(loadavgstring, True, gcfg.g_white) self.screen.blit(textImage, (self.size[0] - textImage.get_rect()[2], 0)) pygame.display.update()
def getCpuTemperature(): cpu = gpiozero.CPUTemperature() return cpu.temperature
true_label = filename.split('_')[1].split('.')[0] # increment total correct if needed if pred_class == true_label: total_correct = total_correct + 1 total = total + 1 dict(psutil.virtual_memory()._asdict()) cumulative_memory = cumulative_memory + ( psutil.virtual_memory().used / 1000000 - pre_inference_memory) count = count + 1 # after inference, save the statistics for cpu usage and power consumption last_time = time.time() #time_stamp total_power = getTelnetPower(SP2_tel, total_power) cpu_temp = gpiozero.CPUTemperature().temperature time_stamp = last_time fmt_str = "{}\t" * 3 out_ln = fmt_str.format(time_stamp, total_power, cpu_temp) out_file.write(out_ln) out_file.write("\n") #Loop to keep gathering data for a total of 20 min while ((time.time() - true_start) < 1200): # after inference, save the statistics for cpu usage and power consumption last_time = time.time() #time_stamp total_power = getTelnetPower(SP2_tel, total_power) cpu_temp = gpiozero.CPUTemperature().temperature time_stamp = last_time fmt_str = "{}\t" * 3 out_ln = fmt_str.format(time_stamp, total_power, cpu_temp)
def draw_thread(noGui = None, guiRefresh = 1): if noGui == None: noGui = not hasTerminal() lastNetSentBytes = None lastNetRecvBytes = None lastNetTime = None while True: logCurrentPlayed() if noGui: pass else: clear() terminalCols, terminalLines = getScreenSize() iconWidth = 1 nameWidth = 20 freqWidth = 8 bandWidth = 3 descWidth = terminalCols - iconWidth - nameWidth - freqWidth - bandWidth - 4*2 if descWidth < 15: descWidth = 0 nameWidth = terminalCols - iconWidth - freqWidth - bandWidth - 3*2 if nameWidth < 15: nameWidth += bandWidth + 2 bandWidth = 0 radios = myRadios.getRadios() for idx in range(len(radios)): radio = radios[idx] color = None tuneFactor = radio.tuneFactor(mySerial.getFreq()) if mySerial.getFreq() != None else None if tuneFactor and tuneFactor == 1: color = colors["green"] elif tuneFactor and tuneFactor > 0: color = colors["yellow"] media = radio.getMedia() if descWidth > 0 and media: if media.get_meta(vlc.Meta.Artist) != None: description = "{artist} – {track}".format( artist = pad(radio.getPlayer().get_media().get_meta(vlc.Meta.Artist), math.floor((descWidth - 3) / 2)), track = pad(radio.getPlayer().get_media().get_meta(vlc.Meta.Title), math.ceil((descWidth - 3) / 2)) ) else: description = pad(media.get_meta(vlc.Meta.Title), descWidth) else: description = pad("", descWidth) if radio.getPlayer(): if radio.getPlayer().get_state() == vlc.State.Buffering: icon = "◐" elif radio.getPlayer().get_state() == vlc.State.Ended: icon = "✘" elif radio.getPlayer().get_state() == vlc.State.Error: icon = "🕱" elif radio.getPlayer().get_state() == vlc.State.NothingSpecial: icon = "◌" elif radio.getPlayer().get_state() == vlc.State.Opening: icon = "🖿" elif radio.getPlayer().get_state() == vlc.State.Paused: icon = "⏸" elif radio.getPlayer().get_state() == vlc.State.Playing: icon = "▶" elif radio.getPlayer().get_state() == vlc.State.Stopped: icon = "⏹" else: icon = "?" else: icon = "?" line = "" if iconWidth > 0: line += icon + " " if nameWidth > 0: line += pad(radio.name, nameWidth) + " " if descWidth > 0: line += description + " " if bandWidth > 0: line += "{:>3s}".format(radio.band) + " " if freqWidth > 0: line += formatFreq(radio.freq) writeLine(line, color) endLine() # ############## # # current radio # # ############## if mySerial.currentRadio: radio = mySerial.currentRadio player = radio.getPlayer() media = radio.getMedia() if media: if media.get_meta(vlc.Meta.Artist) != None: description = "{artist} – {track}".format( artist = radio.getPlayer().get_media().get_meta(vlc.Meta.Artist), track = radio.getPlayer().get_media().get_meta(vlc.Meta.Title) ) else: description = media.get_meta(vlc.Meta.Title) else: description = "" writeLine(radio.name) writeLine("{}/{} {}".format(formatTime(player.get_time()), formatTime(player.get_length()), description)) # ##### # # panel # # ##### currentDict = mySerial.getDict() if currentDict != None and "On" in currentDict: if currentDict["On"] == 1: write(" ON ", colors["green_badge"]) else: write(" OFF ", colors["red_badge"]) else: write(" ??? ", colors["yellow_dim"]) write(" ") for band in ["LW", "MW", "KW", "UKW"]: if currentDict != None and band in currentDict: if currentDict[band] == 1: write(band, colors["green"]) else: write(band, colors["grey"]) else: write(band, colors["yellow_dim"]) write(" ") if currentDict != None and "Vol" in currentDict: vol = round(currentDict["Vol"] * 100 / 255) if vol > 0: icon = "🔈" icon = "🔉" if vol > 50 else icon icon = "🔊" if vol > 75 else icon write("{icon} {:>3}%".format(vol, icon=icon)) else: write("🔇 0%", colors["red"]) else: write("🔇 ???%", colors["yellow_dim"]) write(" ") if mySerial.getFreq(): write("📶 {:>8s}".format(formatFreq(mySerial.getFreq()))) else: write("📶 ??????Hz", colors["yellow_dim"]) write(" ") try: temp = gpiozero.CPUTemperature().temperature except gpiozero.exc.BadPinFactory: temp = None if temp: color = None if temp >= 70: color = colors["red"] elif temp >= 80: color = colors["red_badge"] write("🌡 {:>3d}°C".format(round(temp)), color) else: write("🌡 ???°C", colors["yellow_dim"]) write(" ") try: load, _, _ = os.getloadavg() except OSError: load = None if load: color = None if load >= 3: color = colors["red"] elif load >= 4: color = colors["red_badge"] write("🏋 {:>5.2f}".format(load), color) else: write("🏋 ?????", colors["yellow_dim"]) write(" ") mem = psutil.virtual_memory() mem_usage = round((mem.total - mem.available) / mem.total * 100) if mem_usage: color = None if load >= 80: color = colors["red"] elif load >= 95: color = colors["red_badge"] write("🧠 {:>3d}%".format(mem_usage), color) else: write("🧠 ???%", colors["yellow_dim"]) write(" ") net = psutil.net_io_counters() if lastNetSentBytes != None and lastNetRecvBytes != None and lastNetTime != None: net_sent = net.bytes_sent - lastNetSentBytes net_recv = net.bytes_recv - lastNetRecvBytes time_delta = time.time() - lastNetTime net_sent_pers = net_sent / time_delta net_recv_pers = net_recv / time_delta else: net_sent_pers = None net_recv_pers = None lastNetSentBytes = net.bytes_sent lastNetRecvBytes = net.bytes_recv lastNetTime = time.time() if net_recv_pers != None: write("▼ {:>5.1f}kB/s".format(net_recv_pers / 1024)) else: write("▼ ??????kB/s", colors["yellow_dim"]) if net_sent_pers != None: write("▲ {:>5.1f}kB/s".format(net_sent_pers / 1024)) else: write("▲ ??????kB/s", colors["yellow_dim"]) endLine() endLine() logHeight = max(1, terminalLines - len(radios) - 4) logsToDisplay = min(logHeight, len(myLog.logs)) if logsToDisplay > 0: theLogs = myLog.logs[0:logsToDisplay] theLogs.reverse() for theLog in theLogs: color = colors["grey"] if theLog["severity"] == "ERROR": color = colors["red"] elif theLog["severity"] == "SUCCESS": color = colors["green"] elif theLog["severity"] == "WARNING": color = colors["yellow"] writeLine(pad(theLog["msg"], terminalCols), color) flush() time.sleep(1 / guiRefresh)
def read_temperature(): return gpiozero.CPUTemperature().value * 100
def get_cpu_temp(): cpu = gpiozero.CPUTemperature() return cpu.temperature
def update(): # THIS DEF UPDATES ALL THE STATS # REMOTE STATS # Read the PH api values # Check to make sure web server is reachable and api page is up PH1URLcheck = urllib.request.urlopen(PH1apiURL, timeout=URLtimeout).getcode() if PH1URLcheck != 200: PH1URLstatus = "down" else: PH1URLstatus = "up" PH1URLpage = urllib.request.urlopen( PH1apiURL, timeout=URLtimeout).read().decode() if not 'Did you mean to go to the admin panel?' in PH1URLpage: PH1stats = json.load( urllib.request.urlopen(PH1apiURL, timeout=URLtimeout)) else: PH1URLstatus = "down" PH2URLcheck = urllib.request.urlopen(PH2apiURL, timeout=URLtimeout).getcode() if PH2URLcheck != 200: PH2URLstatus = "down" else: PH2URLstatus = "up" PH2URLpage = urllib.request.urlopen( PH2apiURL, timeout=URLtimeout).read().decode() if not 'Did you mean to go to the admin panel?' in PH2URLpage: PH2stats = json.load( urllib.request.urlopen(PH2apiURL, timeout=URLtimeout)) else: PH2URLstatus = "down" # REMOTE STATS # GET PIHOLE STATUS & DNS RESOLUTION STATUS # Use api JSON get PI-Hole reported status if PH1URLstatus == "up": PH1ReportedStatus = PH1stats['status'] else: PH1ReportedStatus = "PH1 URL Down" if PH2URLstatus == "up": PH2ReportedStatus = PH2stats['status'] else: PH2ReportedStatus = "PH2 URL Down" # Get actual DNS status through dig probe if "NOERROR" in subprocess.check_output( ["dig", DNSGoodCheck, "@" + PH1IPAddress]).decode(): PH1DNSStatus = "enabled" else: PH1DNSStatus = "dnsdown" if "NOERROR" in subprocess.check_output( ["dig", DNSGoodCheck, "@" + PH2IPAddress]).decode(): PH2DNSStatus = "enabled" else: PH2DNSStatus = "dnsdown" # Conditions for Status text output if PH1ReportedStatus == PH2ReportedStatus == PH1DNSStatus == PH2DNSStatus == "enabled": PHStatusstrtxt = "[✓] Status PH1:[✓] PH2:[✓]" PHStatusstrtxtclr = inkyBLACK PHStatusstrtxtfnt = fontS elif PH2ReportedStatus != PH2DNSStatus: if PH2ReportedStatus != "enabled": PHStatusstrtxt = "[✗]{} PH:[✗] DNS:[✓]".format(PH2Name) PHStatusstrtxtclr = inkyRED PHStatusstrtxtfnt = fontM msg_send("{} Problem", PHStatusstrtxt, 8).format(PH2Name) else: PHStatusstrtxt = "[✗]{} PH:[✓] DNS:[✗]".format(PH2Name) PHStatusstrtxtclr = inkyRED PHStatusstrtxtfnt = fontM msg_send("{} Problem", PHStatusstrtxt, 8).format(PH2Name) elif PH1ReportedStatus != PH1DNSStatus: if PH1ReportedStatus != "enabled": PHStatusstrtxt = "[✗]{} PH:[✗] DNS:[✓]".format(PH1Name) PHStatusstrtxtclr = inkyRED PHStatusstrtxtfnt = fontM msg_send("{} Problem", PHStatusstrtxt, 8).format(PH1Name) else: PHStatusstrtxt = "[✗]{} PH:[✓] DNS:[✗]".format(PH1Name) PHStatusstrtxtclr = inkyRED PHStatusstrtxtfnt = fontM msg_send("{} Problem", PHStatusstrtxt, 8).format(PH1Name) else: PHStatusstrtxt = " [✗] [✗] AWOOGA !! [✗] [✗]" PHStatusstrtxtclr = inkyRED PHStatusstrtxtfnt = fontL msg_send("WHEELS OFF!", PHStatusstrtxt, 8) # Moved print(PHStatusstrtxt) down to better emulate display in run-time terminal output # REMOTE STATS # GET PIHOLE STATISTICS # First for 1st PH. Uses api JSON if PH1URLstatus == "up": PH1unique_clients = PH1stats['unique_clients'] PH1ads_blocked_today = PH1stats['ads_blocked_today'] PH1blockp = round(PH1stats['ads_percentage_today'], 1) PH1GravDBDays = PH1stats['gravity_last_updated']['relative']['days'] PH1GravDBHours = PH1stats['gravity_last_updated']['relative']['hours'] else: PH1blockp = 0 PH1GravDBDays = GravDBDaysbad + 1 PH1GravDBHours = 0 # Then for 2nd PH. Uses api JSON if PH2URLstatus == "up": PH2unique_clients2 = PH2stats['unique_clients'] PH2ads_blocked_today = PH2stats['ads_blocked_today'] PH2blockp = round(PH2stats['ads_percentage_today'], 1) PH2GravDBDays = PH2stats['gravity_last_updated']['relative']['days'] PH2GravDBHours = PH2stats['gravity_last_updated']['relative']['hours'] else: PH2blockp = 0 PH2GravDBDays = GravDBDaysbad + 1 PH2GravDBHours = 0 # Conditions for Block% text output if PH1blockp > blockpbad and PH2blockp > blockpbad and (PH1blockp + PH2blockp) != 0: blockpstr = "[✓] {}: {}% {}: {}%".format(PH1Name, PH1blockp, PH2Name, PH2blockp) blockpstrclr = inkyBLACK blockpstrfnt = fontS elif PH1blockp <= blockpbad: blockpstr = "[✗] ALERT Block % {}:{}".format(PH1Name, PH1blockp) blockpstrclr = inkyRED blockpstrfnt = fontL msg_send("BLOCKING PROBLEM?", blockpstr, 4) elif PH2blockp <= blockpbad: blockpstr = "[✗] ALERT Block % {}:{}".format(PH2Name, PH2blockp) blockpstrclr = inkyRED blockpstrfnt = fontL msg_send("BLOCKING PROBLEM?", blockpstr, 4) print(blockpstr) print(PHStatusstrtxt) # Conditions for GravDB age text output if PH1GravDBDays <= GravDBDaysbad and PH2GravDBDays <= GravDBDaysbad: GDBagestr = "[✓] GDB {}:{}d{}h {}:{}d{}h".format( PH1Name, PH1GravDBDays, PH1GravDBHours, PH2Name, PH2GravDBDays, PH2GravDBHours) GDBagestrclr = inkyBLACK GDBagestrfnt = fontS elif PH1GravDBDays > GravDBDaysbad: GDBagestr = "[✗] GDB Age {}:{} days".format(PH1Name, PH1GravDBDays) GDBagestrclr = inkyRED GDBagestrfnt = fontM elif PH2GravDBDays > GravDBDaysbad: GDBagestr = "[✗] GDB Age {}:{} days".format(PH2Name, PH2GravDBDays) GDBagestrclr = inkyRED GDBagestrfnt = fontM print(GDBagestr) # LOCAL STAT # GET IP ADDRESS try: ip = ni.ifaddresses(INTERFACE)[ni.AF_INET][0]['addr'] except KeyError: ip_str = "[×] Can't connect to {}".format(INTERFACE) ip = "" if "192.168" in ip: ip_str = "[✓] IP of {}: {}".format(hostname, ip) ip_clr = inkyBLACK ip_fnt = fontS else: ip_str = "[×] Can't get local address" ip_clr = inkyRED ip_fnt = fontL # LOCAL STAT # GET TEMPERATURE # Query GPIO for the temperature cpu_temp = gz.CPUTemperature().temperature cpu_temp = round(cpu_temp, 1) # Conditions for Temp text output if cpu_temp <= cpucooltemp: cputempstr = "[✓] Cool {}C".format(cpu_temp) cputempstrclr = inkyBLACK cputempstrfnt = fontS elif cpu_temp > cpucooltemp <= cpuoktemp: cputempstr = "[✓] Warm {}".format(cpu_temp) cputempstrclr = inkyBLACK cputempstrfnt = fontM msg_send("WARM", cputempstr, 4) elif cpu_temp > cpuoktemp <= cpubadtemp: cputempstr = "[✗] WARNING {}".format(cpu_temp) cputempstrclr = inkyRED cputempstrfnt = fontL msg_send("WARNING", cputempstr, 8) elif cpu_temp > cpubadtemp: cputempstr = "[✗] DANGER {}".format(cpu_temp) cputempstrclr = inkyRED cputempstrfnt = fontL msg_send("DANGER", cputempstr, 8) print(cputempstr) # LOCAL STAT # GET LOAD # Get Load 5 min from uptime cmd = "/usr/bin/uptime" process = subprocess.Popen(cmd.split(','), stdout=subprocess.PIPE) output = process.stdout.read().decode().split(",") load5min = float(output[-2]) # Get CPU %age from stat # last_idle = last_total = 0 with open('/proc/stat') as f: fields = [float(column) for column in f.readline().strip().split()[1:]] idle, total = fields[3], sum(fields) # idle_delta, total_delta = idle - last_idle, total - last_total # utilisation = 100.0 * (1.0 - idle_delta / total_delta) utilisation = 100.0 * (1.0 - idle / total) utilisation = round(utilisation, 1) # Conditions for Load text output if load5min < loadhigh: loadstr = "[✓] [✓]: {} at CPU: {}%".format(load5min, utilisation) loadstrclr = inkyBLACK loadstrfnt = fontS elif load5min >= loadhigh and utilisation < utilhigh: loadstr = "[✗] WRKN:{} at CPU:{}%".format(load5min, utilisation) loadstrclr = inkyBLACK loadstrfnt = fontM elif load5min >= loadhigh and utilisation >= utilhigh: loadstr = "[✗] DANGER {} at CPU:{}%".format(load5min, utilisation) loadstrclr = inkyRED loadstrfnt = fontL msg_send("LOAD HIGH", loadstr, 8) print(loadstr) # Creates the different output lines based on above # TUP is str, clr, fnt LINE1TXT = cputempstr LINE1CLR = cputempstrclr LINE1FNT = cputempstrfnt LINE1TUP = (LINE1TXT, LINE1CLR, LINE1FNT) # LINE1TUP = (cputempstr,cputempstrclr,cputempfnt) LINE2TXT = loadstr LINE2CLR = loadstrclr LINE2FNT = loadstrfnt LINE2TUP = (LINE2TXT, LINE2CLR, LINE2FNT) # LINE2TUP = (loadstr,loadstrclr,loadstrfnt) LINE3TXT = GDBagestr LINE3CLR = GDBagestrclr LINE3FNT = GDBagestrfnt LINE3TUP = (LINE3TXT, LINE3CLR, LINE3FNT) LINE4TXT = blockpstr LINE4CLR = blockpstrclr LINE4FNT = blockpstrfnt LINE4TUP = (LINE4TXT, LINE1CLR, LINE1FNT) LINE5TXT = PHStatusstrtxt LINE5CLR = PHStatusstrtxtclr LINE5FNT = PHStatusstrtxtfnt LINE5TUP = (LINE5TXT, LINE5CLR, LINE5FNT) # OUTPUT_EXAMPLE = ip_str # OUTPUT_EXAMPLE = PH1ReportedStatus[6].strip().replace('✗', '×') # OUTPUT_EXAMPLE = "[✓] There are {} clients connected".format(unique_clients) # OUTPUT_EXAMPLE = "[✓] Blocked {} objects".format(ads_blocked_today) draw_dashboard(LINE1TXT, LINE1CLR, LINE1FNT, LINE2TXT, LINE2CLR, LINE2FNT, LINE3TXT, LINE3CLR, LINE3FNT, LINE4TXT, LINE4CLR, LINE4FNT, LINE5TXT, LINE5CLR, LINE5FNT) # draw_dashboard(LINE1TUP,LINE2TUP,LINE3TUP,LINE4TUP,LINE5TUP)
camera.resolution = (2592, 1944) #camera.rotation = 180 camera.capture('/home/pi/images/' + curr.strftime("%d_%m_%Y_%H_%M_%S") + '.jpg') camera.close() #for i in range(num_samples): # signal_strength = hologram.network.signal_strength # print('Signal strength: ' + signal_strength) # rssi, qual = signal_strength.split(',') # sum_RSSI = sum_RSSI +int(rssi) # sum_quality = sum_quality +int(qual) # time.sleep(2) #print('Average RSSI' + str(sum_RSSI/num_samples)) #print('Average quality' + str(sum_quality/num_samples)) cpu = gpz.CPUTemperature() cpu_temp = cpu.temperature print("CPU Temperature:", cpu_temp) file = '/home/pi/Pictures/000006.jpg' im = imread(file) print("resizing image") im_final = resize(im, (200, 200)) #Model was trained on 200x200 images # Load TFLite model and allocate tensors. print("allocating tensors") interpreter = tflite.Interpreter(model_path="/home/pi/converted_model.tflite") interpreter.allocate_tensors() # Get input and output tensors. input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() Xtest = np.array(im_final, dtype=np.float32)
import board import busio import adafruit_si7021 import RPi.GPIO as GPIO import gpiozero config = configparser.ConfigParser() config.read('/home/pi/etc/si7021.cfg') config.sections() INTERVAL = int(config['SI7021']['INTERVAL']) LOGLEVEL = config['LOGGING']['LEVEL'] LOGNAME = config['LOGGING']['FILE'] i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_si7021.SI7021(i2c) cpu = gpiozero.CPUTemperature() cpu_c = cpu.temperature cpu_f = 9 / 5 * cpu_c + 32 ## Add logging information logging.basicConfig(filename=LOGNAME, level=LOGLEVEL) logging.info(" ") logging.info("==============================================") logging.info("Started up @ " + time.asctime()) logging.info("==============================================") logging.info(" ") logging.info("{} -- TYPE = {}".format(time.asctime(), GPIO.RPI_INFO['TYPE'])) logging.info("{} -- RAM = {}".format(time.asctime(), GPIO.RPI_INFO['RAM'])) logging.info("{} -- P1_REVISION = {}".format(time.asctime(), GPIO.RPI_INFO['P1_REVISION'])) logging.info("{} -- PROCESSOR = {}".format(time.asctime(),
async def _temp(ctx): temperature = gpiozero.CPUTemperature() message = "Temperature: " + str(temperature) embedVar = discord.Embed(title=message, description=' ', color=0x00ff00) await ctx.send(embed=embedVar)
def cpu_temp_helper(): cpu = gpio.CPUTemperature(min_temp=50, max_temp=90) return cpu.temperature
def writeWeatherRecord(): Rain24Hour = getCalendarDayRain() print("Rain24Hour=", Rain24Hour) WeatherUnderground.sendWeatherUndergroundData(Rain24Hour) state.Rain60Minutes = get60MinuteRain() if (config.enable_MySQL_Logging == True): # open mysql database # write log # commit # close try: cpu = gpiozero.CPUTemperature() state.CPUTemperature = cpu.temperature print("CPUT=", state.CPUTemperature) # first calculate the 24 hour moving average for AQI print("trying database") con = mdb.connect('localhost', 'root', config.MySQL_Password, 'SkyWeather2') cur = con.cursor() timeDelta = datetime.timedelta(days=1) now = datetime.datetime.now() before = now - timeDelta before = before.strftime('%Y-%m-%d %H:%M:%S') query = "SELECT id, AQI, TimeStamp FROM WeatherData WHERE (TimeStamp > '%s') ORDER BY TimeStamp " % ( before) cur.execute(query) myAQIRecords = cur.fetchall() myAQITotal = 0.0 #print("AQIRecords=",myAQIRecords) if (len(myAQIRecords) > 0): for i in range(0, len(myAQIRecords)): myAQITotal = myAQITotal + myAQIRecords[i][1] myAQI24 = (myAQITotal + float(state.AQI)) / (len(myAQIRecords) + 1) else: myAQI24 = 0.0 state.Hour24_AQI = myAQI24 fields = "OutdoorTemperature, OutdoorHumidity, IndoorTemperature, IndoorHumidity, TotalRain, SunlightVisible, SunlightUVIndex, WindSpeed, WindGust, WindDirection,BarometricPressure, BarometricPressureSeaLevel, BarometricTemperature, AQI, AQI24Average, BatteryOK, CPUTemperature" values = "%6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f,%6.2f,%6.2f,%6.2f,%6.2f,%6.2f, \'%s\',%6.2f" % ( state.OutdoorTemperature, state.OutdoorHumidity, state.IndoorTemperature, state.IndoorHumidity, state.TotalRain, state.SunlightVisible, state.SunlightUVIndex, state.WindSpeed, state.WindGust, state.WindDirection, state.BarometricPressure, state.BarometricPressureSeaLevel, state.BarometricTemperature, float(state.AQI), state.Hour24_AQI, state.BatteryOK, state.CPUTemperature) query = "INSERT INTO WeatherData (%s) VALUES(%s )" % (fields, values) #print("query=", query) cur.execute(query) con.commit() except mdb.Error as e: traceback.print_exc() print("Error %d: %s" % (e.args[0], e.args[1])) con.rollback() #sys.exit(1) finally: cur.close() con.close() del cur del con
def main(): print(str(datetime.now()) + ' peripheralManager.py: Starting up...') logDataIntervalSeconds = 60 # log data every 60 seconds pumpCheckIntervalSeconds = 1 # check the pump queue every _ (testing w 1 second) pumpCheckTickCount = 0 pumpRunDurationSeconds = 0 pumpRunTickCount = 0 logDataTickCount = 0 pumpRunning = False currentPumpNumber = 0 while True: if not pumpRunning and pumpCheckTickCount >= pumpCheckIntervalSeconds: # wait til pump is off to check for next item in queue. for gpio in GetGpioNumbers(): status, durationSeconds = GetCurrentStatus( str(gpio)) # get latest row in pump status table if status == 'requestrun': # if == requestrun, update status to running, run pump for specified time SetCurrentStatus(gpio, 'running', durationSeconds) print( str(datetime.now()) + ' peripheralManager.py: Turning ON gpio: ' + str(gpio) + ' for ' + str(durationSeconds) + ' seconds') if str(gpio) in relays: relays[str(gpio)].on() else: print( str(datetime.now()) + ' peripheralManager.py: error: unknown gpio number' ) pumpRunning = True currentPumpNumber = gpio pumpRunDurationSeconds = durationSeconds #pumpRunDurationSeconds = 2 pumpRunTickCount = 0 break if pumpRunning and pumpRunTickCount >= pumpRunDurationSeconds: print( str(datetime.now()) + ' peripheralManager.py: Turning OFF gpio: ' + str(gpio) + ' for ' + str(durationSeconds) + ' seconds') if str(currentPumpNumber) in relays: relays[str(currentPumpNumber)].off() else: print( str(datetime.now()) + ' peripheralManager.py: error: unknown gpio number') pumpRunning = False pumpRunTickCount = 0 SetCurrentStatus(gpio, 'ready', 0) if logDataTickCount >= logDataIntervalSeconds: cpu = gpiozero.CPUTemperature() # get rpi temp / ram data ram = psutil.virtual_memory() ram_percent_used = (ram.total - ram.available) / ram.total logPiData(cpu.temperature, ram_percent_used) # log to db i = 0 for chan in channels: # get ADC data try: logAdcData(i, chan.value, chan.voltage) # log to db except: print( str(datetime.now()) + ' peripheralManager.py: error: couldn\'t read adc') i += 1 logDataTickCount = 0 time.sleep(1) logDataTickCount += 1 pumpCheckTickCount += 1 if pumpRunning: pumpRunTickCount += 1