/ TFT_Sidekick_With_FT232H / tft_sidekick_cpu.py
tft_sidekick_cpu.py
  1  # SPDX-FileCopyrightText: 2019 Carter Nelson for Adafruit Industries
  2  #
  3  # SPDX-License-Identifier: MIT
  4  
  5  from collections import deque
  6  import psutil
  7  # Blinka CircuitPython
  8  import board
  9  import digitalio
 10  import adafruit_rgb_display.ili9341 as ili9341
 11  # Matplotlib
 12  import matplotlib.pyplot as plt
 13  # Python Imaging Library
 14  from PIL import Image
 15  
 16  #pylint: disable=bad-continuation
 17  #==| User Config |========================================================
 18  REFRESH_RATE = 1
 19  HIST_SIZE = 61
 20  PLOT_CONFIG = (
 21      #--------------------
 22      # PLOT 1 (upper plot)
 23      #--------------------
 24      {
 25      'title' : 'LOAD',
 26      'ylim' : (0, 100),
 27      'line_config' : (
 28          {'color' : '#0000FF', 'width' : 2},
 29          {'color' : '#0060FF', 'width' : 2},
 30          {'color' : '#00FF60', 'width' : 2},
 31          {'color' : '#60FF00', 'width' : 2},
 32          )
 33      },
 34      #--------------------
 35      # PLOT 2 (lower plot)
 36      #--------------------
 37      {
 38      'title' : 'TEMP',
 39      'ylim' : (20, 50),
 40      'line_config' : (
 41          {'color' : '#FF0000', 'width' : 2},
 42          {'color' : '#FF3000', 'width' : 2},
 43          {'color' : '#FF8000', 'width' : 2},
 44          {'color' : '#Ff0080', 'width' : 2},
 45          )
 46      }
 47  )
 48  
 49  CPU_COUNT = 4
 50  
 51  def update_data():
 52      ''' Do whatever to update your data here. General form is:
 53             y_data[plot][line].append(new_data_point)
 54      '''
 55      cpu_percs = psutil.cpu_percent(interval=REFRESH_RATE, percpu=True)
 56      for cpu in range(CPU_COUNT):
 57          y_data[0][cpu].append(cpu_percs[cpu])
 58  
 59      cpu_temps = []
 60      for shwtemp in psutil.sensors_temperatures()['coretemp']:
 61          if 'Core' in shwtemp.label:
 62              cpu_temps.append(shwtemp.current)
 63      for cpu in range(CPU_COUNT):
 64          y_data[1][cpu].append(cpu_temps[cpu])
 65  
 66  #==| User Config |========================================================
 67  #pylint: enable=bad-continuation
 68  
 69  # Setup X data storage
 70  x_time = [x * REFRESH_RATE for x in range(HIST_SIZE)]
 71  x_time.reverse()
 72  
 73  # Setup Y data storage
 74  y_data = [ [deque([None] * HIST_SIZE, maxlen=HIST_SIZE) for _ in plot['line_config']]
 75             for plot in PLOT_CONFIG
 76           ]
 77  
 78  # Setup display
 79  disp = ili9341.ILI9341(board.SPI(), baudrate = 24000000,
 80                         cs  = digitalio.DigitalInOut(board.D4),
 81                         dc  = digitalio.DigitalInOut(board.D5),
 82                         rst = digitalio.DigitalInOut(board.D6))
 83  
 84  # Setup plot figure
 85  plt.style.use('dark_background')
 86  fig, ax = plt.subplots(2, 1, figsize=(disp.width / 100, disp.height / 100))
 87  
 88  # Setup plot axis
 89  ax[0].xaxis.set_ticklabels([])
 90  for plot, a in enumerate(ax):
 91      # add grid to all plots
 92      a.grid(True, linestyle=':')
 93      # limit and invert x time axis
 94      a.set_xlim(min(x_time), max(x_time))
 95      a.invert_xaxis()
 96      # custom settings
 97      if 'title' in PLOT_CONFIG[plot]:
 98          a.set_title(PLOT_CONFIG[plot]['title'], position=(0.5, 0.8))
 99      if 'ylim' in PLOT_CONFIG[plot]:
100          a.set_ylim(PLOT_CONFIG[plot]['ylim'])
101  
102  # Setup plot lines
103  #pylint: disable=redefined-outer-name
104  plot_lines = []
105  for plot, config in enumerate(PLOT_CONFIG):
106      lines = []
107      for index, line_config in enumerate(config['line_config']):
108          # create line
109          line, = ax[plot].plot(x_time, y_data[plot][index])
110          # custom settings
111          if 'color' in line_config:
112              line.set_color(line_config['color'])
113          if 'width' in line_config:
114              line.set_linewidth(line_config['width'])
115          if 'style' in line_config:
116              line.set_linestyle(line_config['style'])
117          # add line to list
118          lines.append(line)
119      plot_lines.append(lines)
120  
121  def update_plot():
122      # update lines with latest data
123      for plot, lines in enumerate(plot_lines):
124          for index, line in enumerate(lines):
125              line.set_ydata(y_data[plot][index])
126          # autoscale if not specified
127          if 'ylim' not in PLOT_CONFIG[plot].keys():
128              ax[plot].relim()
129              ax[plot].autoscale_view()
130      # draw the plots
131      canvas = plt.get_current_fig_manager().canvas
132      plt.tight_layout()
133      canvas.draw()
134      # transfer into PIL image and display
135      image = Image.frombytes('RGB', canvas.get_width_height(),
136                              canvas.tostring_rgb())
137      disp.image(image)
138  
139  print("looping")
140  while True:
141      update_data()
142      update_plot()
143      # update rate controlled by psutil.cpu_percent()