Kemp’s Blog

A technical blog about technical things

Plotting hardware stats via plotly (code listing)

This page lists the code referred to in my blog post here.

# Temperature/usage stats based on:
#   http://www.raspberrypi.org/phpBB3/viewtopic.php?f=32&t=22180
#   http://rollcode.com/use-python-get-raspberry-pis-temperature/


from subprocess import PIPE, Popen
import psutil
import datetime
import plotly
import time
import calendar


USERNAME = 'username'
APIKEY   = 'api_key'


def get_cpu_temp():
    tempFile = open("/sys/class/thermal/thermal_zone0/temp")
    cpu_temp = tempFile.read()
    tempFile.close()
    return float(cpu_temp.strip()) / 1000.


def get_gpu_temp():
    process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE)
    output, _error = process.communicate()
    return float(output[output.index('=') + 1:output.rindex("'")])


def get_ram_used():
    return psutil.phymem_usage().percent


def get_cpu_usage():
    return psutil.cpu_percent()



filename = 'cam1_test'

layout = {
    'title'       : 'Camera 1 hardware',
    'xaxis'       : {'title':'Time', 'type':'date'},
    'yaxis'       : {'title':'Temperature (deg. C)'},
    'yaxis2'      : {'title':'% usage', 'side':'right', 'overlaying':'y'},
    'showlegend'  : True,
    'legend'      : {'x' : 0, 'y' : 1},
}

py = plotly.plotly(username_or_email=USERNAME, key=APIKEY)
py.layout(layout, filename=filename)

camera_started = False
end_time = datetime.datetime.utcnow() + datetime.timedelta(minutes = 6)
curr_time = datetime.datetime.utcnow()
expected_update = curr_time + datetime.timedelta()

while curr_time <= end_time:
    cpu_temp = {'x': [curr_time], 'y': [get_cpu_temp()],  'type': 'scatter', 'mode': 'lines', 'name':'CPU temperature'}
    gpu_temp = {'x': [curr_time], 'y': [get_gpu_temp()],  'type': 'scatter', 'mode': 'lines', 'name':'GPU temperature'}
    ram_used = {'x': [curr_time], 'y': [get_ram_used()],  'type': 'scatter', 'mode': 'lines', 'name':'RAM usage', 'yaxis':'y2'}
    cpu_load = {'x': [curr_time], 'y': [get_cpu_usage()], 'type': 'scatter', 'mode': 'lines', 'name':'CPU usage', 'yaxis':'y2'}

    _cpu_load = cpu_load['y'][0]

    if _cpu_load > 75 and not(camera_started):
        layout['annotations'] = [{'text':'Camera enabled', 'xref':'x', 'yref':'y2', 'x':calendar.timegm(curr_time.utctimetuple())*1000, 'y':_cpu_load, 'ax':-100, 'ay':10, 'showarrow':True, 'arrowhead':7}]
        py.layout(layout, filename=filename)
        end_time = curr_time + datetime.timedelta(minutes = 6)
        camera_started = True

    if _cpu_load < 50 and camera_started:
        layout['annotations'].append({'text':'Camera disabled', 'xref':'x', 'yref':'y2', 'x':calendar.timegm(curr_time.utctimetuple())*1000, 'y':_cpu_load, 'ax':100, 'ay':10, 'showarrow':True, 'arrowhead':7})
        py.layout(layout, filename=filename)
        end_time = curr_time + datetime.timedelta(minutes = 5)
        camera_started = False

    response = py.plot([cpu_temp, gpu_temp, ram_used, cpu_load], filename=filename, fileopt='extend')
    print curr_time.isoformat(' ')

    expected_update += datetime.timedelta(seconds = 30)
    time.sleep((expected_update - datetime.datetime.utcnow()).total_seconds()) # Compensate for the loop taking some time

    curr_time = datetime.datetime.utcnow()