Raspberry temp: Skirtumas tarp puslapio versijų

Iš Žinynas.
Jump to navigation Jump to search
 
(Jokio skirtumo)

Dabartinė 22:03, 13 birželio 2019 versija

RasperryPI/OrangePI temp[keisti]

Screenshot 2019-06-13 at 18.37.39.png

#!/usr/bin/python
import os
import time

def measure_temp():
        tFile = open('/sys/class/thermal/thermal_zone0/temp')
        temp = round((float(tFile.read())/1000),2)
        return temp

print(measure_temp())

Sudedam į /usr/local/bin/cpu_temp.py

chmod +x /usr/local/bin/cpu_temp.py

CPU Temp tinklo resursas[keisti]

Screenshot 2019-06-13 at 23.01.00.png

Užkūrus šį resursą ant įvairių įrenginių RaspberryPI, OrangePI ir t.t. Galima kreipiantis į http REST API, pasiimt informaciją apie įrenginį, kol kas jis atiduoda tik temperatūrą. Bet ateityje galima pridėti daugiau įvairių dalykų. Taip atiduodamą informaciją nesunkiai galima panaudoti tinklo monitoringo sistemose pvz.: braižyti grafikus, arba tikrinti ir raportuoti apie tam tikras problemas jeigu gautas rezultatas neatitinka nustatyto.

#!/usr/bin/python2.7
# HW Reporting REST API
# (c) 2018-2019 justinas@eofnet.lt
# INSTALL: apt-get install python-pip; pip install python-daemon bottle
import sys, os
from time import sleep
import argparse
import daemon
import logging
import subprocess
import json
import re
from bottle import run, post, request, response, get, route

if not os.getegid() == 0:
      sys.exit('Script must be run as root')

def measure_temp():
        tFile = open('/sys/class/thermal/thermal_zone0/temp')
        temp = round((float(tFile.read())/1000),2)
        return temp

def daemonize():
	    print ("Daemonizing..")
            @route('/temp')
            def returntemp():
               temp = measure_temp()
               respond = { "answer": temp }
               return json.dumps(respond)
	    run(host='0.0.0.0', port=1414, debug=False)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='HW info REST API (c) 2019 justinas@eofnet.lt, EOFNET LAB10',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--temp', action='store_true')
    parser.add_argument('--daemonize',action='store_true')
    args = parser.parse_args()
    try:
       if args.temp:
         print measure_temp()
       elif args.daemonize:
         daemonize()
       else:
          print "No arguments specified"
    except KeyboardInterrupt:
        pass

hw_info.service

[Unit]
Description=Power Switch Relay Network Service
After=network.target


[Service]
Type=simple
ExecStart=/usr/local/bin/hw_info.py --daemonize

[Install]
WantedBy=multi-user.target

Įdedam šį servisą į /etc/systemd/system ir įjungiam

systemctl enable hw_info
systemctl start hw_info

RRD Temperatūrų grafikai keliems įrenginiams[keisti]

Sugalvota užduotis, monitorinti kelių Raspberių ir Orange'ų temperatūras centriniame serveryje. Turime šiuos įrenginius:

  1. lokalus serveris 127.0.0.1 # monitorinsime taip.
  2. relayswitch 192.168.254.102
  3. cam1 192.168.254.101
  4. cam4 192.168.254.104
  5. cam5 192.168.254.105
  6. rpitv 192.168.254.9

Įdiegiame mums reikalingus įrankius[keisti]

apt-get install rrdtool python2.7 python-requests python-rrdtool

Sukuriame RRD[keisti]

rrdtool create /etc/mods/devices_temp.rrd --step 60 \
DS:server:GAUGE:120:0:100 \
DS:relay:GAUGE:120:0:100 \
DS:cam1:GAUGE:120:0:100 \
DS:cam4:GAUGE:120:0:100 \
DS:cam5:GAUGE:120:0:100 \
DS:rpitv:GAUGE:120:0:100 \
RRA:AVERAGE:0.5:1:1440 \
RRA:MIN:0.5:1:1440 \
RRA:MAX:0.5:1:1440

Python scriptas atnaujinimui ir grafikų braižymui[keisti]

iot_rrd.py

#!/usr/bin/python2.7
# Bidon script for gathering networked devices informations such as temperatures and other equipment and make nice RRD Graphs :)
# (c) 2019 justinas@eofnet.lt
# apt install python-rrdtool
import time
import argparse as ap
from rrdtool import update as rrd_update
import rrdtool
import requests
import json

rrd_file = "/etc/mods/devices_temp.rrd"
devices = [{"name":"server", "host":"127.0.0.1", "color":"#ff0000"},
              {"name":"relay", "host":"192.168.254.102", "color":"#0000ff"},
              {"name":"cam1", "host":"192.168.254.101", "color":"#3cb371"},
              {"name":"cam4", "host":"192.168.254.104", "color":"#ee82ee"},
              {"name":"cam5", "host":"192.168.254.105", "color":"#ffa500"},
              {"name":"rpitv", "host":"192.168.254.9", "color":"#6a5acd"}]

def temp_data(host):
      try:
        response = requests.get('http://'+host+':1414/temp')
        data = json.loads(response.content)
        if data["answer"] is not None:
          return str(data["answer"])
        else:
          return "0"
      except:
        return "0"

def UpdateRRD():
   template = "N"
   for device in devices:
     tempc = temp_data(device["host"])
     template = template + ":"+tempc
     print "Device: "+device["name"]+" temp: "+tempc+"C"
   ret = rrd_update(rrd_file, template)
   if ret:
     print rrdtool.error()

def GenDefs():
  defs = []
  for device in devices:
    defs.append("DEF:"+device["name"]+"="+rrd_file+":"+device["name"]+":AVERAGE")
  return defs

def GenLines():
  lines = []
  count = 1
  for device in devices:
    lines.append("LINE"+str(count)+":"+device["name"]+device["color"]+":"+device["name"])
    lines.append("GPRINT:"+device["name"]+":LAST:Last\:%8.2lf %s")
    lines.append("GPRINT:"+device["name"]+":MIN:Min\:%8.2lf %s")
    lines.append("GPRINT:"+device["name"]+":AVERAGE:Average\:%8.2lf %s")
    lines.append("GPRINT:"+device["name"]+":MAX:Max\:%8.2lf %s\\n")
    count += 1
  return lines

def MakeNiceGraph():
   for sched in ['daily' , 'weekly', 'monthly', 'yearly']:
    if sched == 'weekly':
        period = 'w'
    elif sched == 'daily':
        period = 'd'
    elif sched == 'monthly':
        period = 'm'
    elif  sched == 'yearly':
        period = 'y'
    ret = rrdtool.graph( "/var/www/html/temp-%s.png" %(sched), "--start", "-1%s" %(period), "--vertical-label=Temperatura",
         '--watermark=Temperatures of the devices',
         "-w 800 -h 400",
         GenDefs(), GenLines())

parser = ap.ArgumentParser(description="Just another script")
parser.add_argument("--graph")
parser.add_argument("--update")
args, leftovers = parser.parse_known_args()
if args.graph is not None:
 MakeNiceGraph()
elif args.update is not None:
 UpdateRRD()
else:
 for device in devices:
   print "Device: "+device["name"]+" temp: "+temp_data(device["host"])

Sudedam visa malonumą į crontab:

* * * * * root /usr/local/bin/iot_rrd.py --update RRD > /dev/null 2>&1
*/5  * * * * root /usr/local/bin/iot_rrd.py --graph RRD > /dev/null 2>&1