HOWTO: Visa elförbrukning som stapeldiagram 1.0

Hur gör man för att ... ? Hur fungerar ... ? Steg för steg-guider och förklarande artiklar finns i detta forum.
Många guider finner också på vår blogg: https://blog.m.nu/
Kategoriregler
Vill du visa bilder i ditt inlägg? Använd funktionen "Ladda upp bilaga" nedanför textrutan!
buffedelic
Wannabe
Inlägg: 18
Blev medlem: 19 apr 2014, 00:12
Ort: Huddinge

HOWTO: Visa elförbrukning som stapeldiagram 1.0

Inlägg av buffedelic »

Version 1.0 av simple_bar_generator har bytt namn till genRRDbars.sh och gar fått utökad funktionalitet.
Det finns ingen felhantering av argument, kommer förmodligen inte heller, så se till att köra scriptet enl. nedan.


Använd såhär:

Kod: Markera allt

$ ./genRRDbars.sh 
Usage: ./genRRDbars.sh [OPTION] [ARGUMENT]...

  	-c YYYY+YYYY 
  		Compares total per month of two specified years
  	-d YYYYMM
  		Total per day, specified month
  	-h
  		Display this help	
  	-m YYYY
  		Total per month, specified year
  	-t YYYYMMDD
  		Total per hour, specified day
  	-y YYYY
  		Total specified year and five years back in time
  	
Scriptet är i första han gjort för att plotta energiförbrukning men kan såklart användas till andra typer av data, ping, mail, inloggningar osv. Det som behövs ändras för andra data hittar du i denna funktion:

Kod: Markera allt

function plot_graph() {
....
....
}
Om du vill skapa diagram kontinuerligt kan crontab (sudo crontab -e) updateras enl. nedan. Ändra bara filvägen till scriptet.

Ändra crontab

Kod: Markera allt

#Generate power comsumption last day
3 0 * * * /home/pi/bin/genRRDbars.sh -t $(date -d "yesterday" +"\%Y\%m\%d")
*/5.0 * * * * /home/pi/bin/genRRDbars.sh -t $(date -d "today" +"\%Y\%m\%d")

#Generate power consumption month, every hour for current and the first for last month
3 0 1 * * /home/pi/bin/genRRDbars.sh -d $(date -d "-1 month -$(($(date +\%d)-1)) days" +"\%Y\%m")
*/59 * * * * /home/pi/bin/genRRDbars.sh -d $(date -d "-0 month -$(($(date +\%d)-1)) days" +"\%Y\%m")
Kopiera hela koden och spara som "genRRDbars.sh" i tex. "/home/pi/bin/"
Gör man så slipper man ändra något i crontab, observera att alla filvägar i "User Variables" inte kan vara relativa (tex. ~/rrd/elmatare.rrd) om man använder crontab.

Spara koden som genRRDbars.sh

Kod: Markera allt

#!/bin/bash
# A Simple Shell Script To Generate A Bars Diagram For Rrd Databases
# Christofer Andersson - 21/Oct/2014
# Contact: buffedelic@hotmail.com

#######User variables##############
#
source /etc/elmatare.conf              # You probably want to comment this one :)
DS="Tot"                               # Datastore to compute
#DSunit="kWh"                           # Unit of generated data
#unitArgs=( )                           # Might be easier to just edit template loop!??
DBPath=$powerDBPath                    # /path/to/rrddb.rrd
imgPath="/var/www/img/"                # Path to put generated .png image
#tempPath"/tmp/"                        # This is where .png is generated
#location=""
monthArray=(null Januari Februari      # Please edit to your flavor
  Mars April Maj Juni Juli Augusti 
  September Oktober November December
)
#
###################################
####### TO DO #####################
# Make graphing for any unit
# Or maybe not
###################################


####### Take care of optins and arguments ##################################################################
usage () 
{
  echo "Usage: $0 [OPTION] [ARGUMENT]...

  	-c YYYY+YYYY 
  		Compares total per month of two specified years
  	-d YYYYMM
  		Total per day, specified month
  	-h
  		Display this help	
  	-m YYYY
  		Total per month, specified year
  	-t YYYYMMDD
  		Total per hour, specified day
  	-y YYYY
  		Total specified year and five years back in time
  	"
}

datearg=""
while getopts ":c:d:h:m:t:y:" option; do
  case "$option" in
	c)  datearg="$OPTARG" ;;
	d)	datearg="$OPTARG" ;;
	h)  echo "it's always useful to provide some help"
      usage
      exit 0
      ;;
	m)	datearg="$OPTARG" ;;
	t)	datearg="$OPTARG" ;;
	y)	datearg="$OPTARG" ;;
  :)  echo "Error: -$OPTARG requires an argument
              "
      usage
      exit 1
      ;;
  ?)  echo "Error: unknown option -$OPTARG
              " 
      usage
      exit 1
      ;;
  esac
done  

if [ -z "$datearg" ]; then #if no option is passed correctly
  usage
  exit 1
fi

#echo "Argument: $datearg"
############################################################################################################################################################################################################
function plot_graph()
{
  #######Create graph from template##################
  echo "Plotting from '$firstDay' to '$lastDay'"
  /usr/bin/rrdtool graph $tempPath \
     --start "$(date -d "$firstDay" "+%Y%m%d")" \
     --end "$(date -d "$lastDay" "+%Y%m%d")" \
     --width 1600 \
     --height 400 \
     --title "Förbrukning $usageString" \
     --vertical-label 'kWh' \
     --alt-y-grid \
     --right-axis 1:0 \
     --units-exponent 2 \
     --color GRID#00000050 \
     --color MGRID#00000080 \
     --watermark '© Copyright Buffedelic.no-ip.org 2014' \
     "${args[@]}"
  mv $tempPath $imgPath
###################################################
}
function arg_loop() 
{
  ####### Loop arguments for bars ##################
  args=( )
  day=$firstDay
  i=1

  while [[ $day != $(date -d "$lastDay" "$stopFormat") ]]; do
    dayStop=$(date -d "$day $stopOffset" "$stopFormat")
    args+=(
     DEF:tot$i=$DBPath:$DS:AVERAGE:start="$(date -d "$day" "+%Y%m%d %H\:%M")'":end="$(date -d "$dayStop" "+%Y%m%d %H\:%M")'"
     CDEF:w$i=tot$i,3600,*
     CDEF:energiK$i=tot$i,1000,/
     VDEF:value_sum$i=energiK$i,TOTAL
     CDEF:value_area$i=w$i,w$i,-,value_sum$i,+
     AREA:value_area$i#AAAAee
     LINE1:value_area$i#000000
     #GPRINT:value_sum$i:"$day %0.2lfkWh\n"
     )
     day=$(date -d "$day $stopOffset" "$stopFormat")
     i=$[$i+1]
  done
}
###################################################
function arg_compare_loop() 
{
  ####### Loop arguments for bars ##################
  args=( )
  day=$firstDay
  i=1

  while [[ $day != $(date -d "$lastDay" "$stopFormat") ]]; do
    dayStop=$(date -d "$day $stopOffset" "$stopFormat")
    args+=(
     DEF:totX$i=$DBPath:$DS:AVERAGE:start="$(date -d "$day" "+%Y%m%d %H\:%M")'":end="$(date -d "$dayStop" "+%Y%m%d %H\:%M")'"
     CDEF:wX$i=totX$i,3600,*
     CDEF:energiKX$i=totX$i,1000,/
     VDEF:value_sumX$i=energiKX$i,TOTAL
     CDEF:value_areaX$i=wX$i,wX$i,-,value_sumX$i,+
     AREA:value_areaX$i#00000090
     LINE1:value_areaX$i#000000
     #GPRINT:value_sumX$i:"$day %0.2lfkWh\n"
     )
     day=$(date -d "$day $stopOffset" "$stopFormat")
     i=$[$i+1]
  done
}

####### What to do with arguments ##################################################################
#Compares total per month of two secified years ####
if [ $1 == "-c" ]; then
  #exit 0

  stopOffset='+ 1 month'
  stopFormat='+%Y%m%d'

  yearOne="$( cut -d '+' -f 1 <<< "$datearg" )"
  yearTwo="$( cut -d '+' -f 2 <<< "$datearg" )"

  firstDay=$(date -d "$yearOne"0101"" +%Y%m%d)
  lastDay=$(date -d "$firstDay + 12 month" +%Y%m%d)
  
  arg_loop
  tempArgs=("${args[@]}")

  firstDay=$(date -d "$yearTwo"0101"" +%Y%m%d)
  lastDay=$(date -d "$firstDay + 12 month" +%Y%m%d)
  
  arg_compare_loop
  args+=("${tempArgs[@]}")

  tempPath="/tmp/$yearOne-$yearTwo-bar.png"               # Path to work with image (requires to be run by sudo'er or eg. cron)
  usageString="$yearOne-$yearTwo"

  plot_graph
  
fi
###################################################

####### Total per day, specified month #############
if [ $1 == "-d" ]; then 
  firstDay=$(date -d "$datearg"01"" +%Y%m%d) 
  lastDay=$(date -d "$firstDay + 1 month" +%Y%m%d)
  
  stopOffset='+ 1 days'
  stopFormat='+%Y%m%d'
  
  tempPath="/tmp/$(date -d "$firstDay" "+%Y-%m")-bar.png"               # Path to work with image (requires to be run by sudo'er or eg. cron)
  usageString="${monthArray[$(date -d "$firstDay" +%m)]}"

  arg_loop
  plot_graph
fi
###################################################

####### Total per month, specified year ############
if [ $1 == "-m" ]; then 
  firstDay=$(date -d "$datearg"0101"" +%Y%m%d)
  lastDay=$(date -d "$firstDay + 12 month" +%Y%m%d)

  stopOffset='+ 1 month'
  stopFormat='+%Y%m%d'
  
  tempPath="/tmp/$(date -d "$firstDay" "+%Y")-bar.png"               # Path to work with image (requires to be run by sudo'er or eg. cron)
  usageString=$(date -d "$firstDay" "+%Y")

  arg_loop
  plot_graph
fi
###################################################

####### Total per hour, specified day ##############
if [ $1 == "-t" ]; then 
  firstDay=$(date -d "$datearg" "+%Y%m%d %H%M") 
  lastDay=$(date -d "$firstDay + 1 day" "+%Y%m%d %H%M")

  stopOffset='+ 1 hours'
  stopFormat='+%Y%m%d %H%M'

  tempPath="/tmp/$(date -d "$firstDay" "+%Y%m%d")-bar.png"               # Path to work with image (requires to be run by sudo'er or eg. cron)
  usageString=$(date -d "$firstDay" "+%Y-%m-%d")

  arg_loop
  plot_graph
fi
###################################################

# Total specified year and five years back in time #
if [ $1 == "-y" ]; then
  firstDay=$(date -d "$datearg"0101" - 5 year" +%Y%m%d)
  lastDay=$(date -d "$firstDay + 6 year" +%Y%m%d)

  stopOffset='+ 1 year'
  stopFormat='+%Y%m%d'

  tempPath="/tmp/$(date -d "$firstDay" "+%Y")to$(date -d "$firstDay + 5 year" +%Y)-bar.png"               # Path to work with image (requires to be run by sudo'er or eg. cron)
  usageString="$(date -d "$firstDay" "+%Y")-$(date -d "$firstDay + 5 year" +%Y)"

  arg_loop
  plot_graph
fi
############################################################################################################################################################################################################

En bra guide för att komma igång med att logga elförbrukning är http://wiki.m.nu/index.php/Mäta_elförbr ... ch_RRDTool

Exempel diagram
Bilagor
genRRDbars.sh
genRRDbars.sh