ESPHome  2022.9.1
graph.cpp
Go to the documentation of this file.
1 #include "graph.h"
3 #include "esphome/core/color.h"
4 #include "esphome/core/log.h"
5 #include "esphome/core/hal.h"
6 #include <algorithm>
7 #include <sstream>
8 #include <iostream> // std::cout, std::fixed
9 #include <iomanip>
10 namespace esphome {
11 namespace graph {
12 
13 using namespace display;
14 
15 static const char *const TAG = "graph";
16 static const char *const TAGL = "graphlegend";
17 
18 void HistoryData::init(int length) {
19  this->length_ = length;
20  this->samples_.resize(length, NAN);
21  this->last_sample_ = millis();
22 }
23 
24 void HistoryData::take_sample(float data) {
25  uint32_t tm = millis();
26  uint32_t dt = tm - last_sample_;
27  last_sample_ = tm;
28 
29  // Step data based on time
30  this->period_ += dt;
31  while (this->period_ >= this->update_time_) {
32  this->samples_[this->count_] = data;
33  this->period_ -= this->update_time_;
34  this->count_ = (this->count_ + 1) % this->length_;
35  ESP_LOGV(TAG, "Updating trace with value: %f", data);
36  }
37  if (!std::isnan(data)) {
38  // Recalc recent max/min
39  this->recent_min_ = data;
40  this->recent_max_ = data;
41  for (int i = 0; i < this->length_; i++) {
42  if (!std::isnan(this->samples_[i])) {
43  if (this->recent_max_ < this->samples_[i])
44  this->recent_max_ = this->samples_[i];
45  if (this->recent_min_ > this->samples_[i])
46  this->recent_min_ = this->samples_[i];
47  }
48  }
49  }
50 }
51 
53  ESP_LOGI(TAG, "Init trace for sensor %s", this->get_name().c_str());
54  this->data_.init(g->get_width());
55  sensor_->add_on_state_callback([this](float state) { this->data_.take_sample(state); });
56  this->data_.set_update_time_ms(g->get_duration() * 1000 / g->get_width());
57 }
58 
59 void Graph::draw(DisplayBuffer *buff, uint16_t x_offset, uint16_t y_offset, Color color) {
61  if (this->border_) {
62  buff->horizontal_line(x_offset, y_offset, this->width_, color);
63  buff->horizontal_line(x_offset, y_offset + this->height_ - 1, this->width_, color);
64  buff->vertical_line(x_offset, y_offset, this->height_, color);
65  buff->vertical_line(x_offset + this->width_ - 1, y_offset, this->height_, color);
66  }
68  float ymin = NAN;
69  float ymax = NAN;
70  for (auto *trace : traces_) {
71  float mx = trace->get_tracedata()->get_recent_max();
72  float mn = trace->get_tracedata()->get_recent_min();
73  if (std::isnan(ymax) || (ymax < mx))
74  ymax = mx;
75  if (std::isnan(ymin) || (ymin > mn))
76  ymin = mn;
77  }
78  // Adjust if manually overridden
79  if (!std::isnan(this->min_value_))
80  ymin = this->min_value_;
81  if (!std::isnan(this->max_value_))
82  ymax = this->max_value_;
83 
84  float yrange = ymax - ymin;
85  if (yrange > this->max_range_) {
86  // Look back in trace data to best-fit into local range
87  float mx = NAN;
88  float mn = NAN;
89  for (uint32_t i = 0; i < this->width_; i++) {
90  for (auto *trace : traces_) {
91  float v = trace->get_tracedata()->get_value(i);
92  if (!std::isnan(v)) {
93  if ((v - mn) > this->max_range_)
94  break;
95  if ((mx - v) > this->max_range_)
96  break;
97  if (std::isnan(mx) || (v > mx))
98  mx = v;
99  if (std::isnan(mn) || (v < mn))
100  mn = v;
101  }
102  }
103  }
104  yrange = this->max_range_;
105  if (!std::isnan(mn)) {
106  ymin = mn;
107  ymax = ymin + this->max_range_;
108  }
109  ESP_LOGV(TAG, "Graphing at max_range. Using local min %f, max %f", mn, mx);
110  }
111 
112  float y_per_div = this->min_range_;
113  if (!std::isnan(this->gridspacing_y_)) {
114  y_per_div = this->gridspacing_y_;
115  }
116  // Restrict drawing too many gridlines
117  if (yrange > 10 * y_per_div) {
118  while (yrange > 10 * y_per_div) {
119  y_per_div *= 2;
120  }
121  ESP_LOGW(TAG, "Graphing reducing y-scale to prevent too many gridlines");
122  }
123 
124  // Adjust limits to nice y_per_div boundaries
125  int yn = int(ymin / y_per_div);
126  int ym = int(ymax / y_per_div) + int(1 * (fmodf(ymax, y_per_div) != 0));
127  ymin = yn * y_per_div;
128  ymax = ym * y_per_div;
129  yrange = ymax - ymin;
130 
132  if (!std::isnan(this->gridspacing_y_)) {
133  for (int y = yn; y <= ym; y++) {
134  int16_t py = (int16_t) roundf((this->height_ - 1) * (1.0 - (float) (y - yn) / (ym - yn)));
135  for (uint32_t x = 0; x < this->width_; x += 2) {
136  buff->draw_pixel_at(x_offset + x, y_offset + py, color);
137  }
138  }
139  }
140  if (!std::isnan(this->gridspacing_x_) && (this->gridspacing_x_ > 0)) {
141  int n = this->duration_ / this->gridspacing_x_;
142  // Restrict drawing too many gridlines
143  if (n > 20) {
144  while (n > 20) {
145  n /= 2;
146  }
147  ESP_LOGW(TAG, "Graphing reducing x-scale to prevent too many gridlines");
148  }
149  for (int i = 0; i <= n; i++) {
150  for (uint32_t y = 0; y < this->height_; y += 2) {
151  buff->draw_pixel_at(x_offset + i * (this->width_ - 1) / n, y_offset + y, color);
152  }
153  }
154  }
155 
157  ESP_LOGV(TAG, "Updating graph. ymin %f, ymax %f", ymin, ymax);
158  for (auto *trace : traces_) {
159  Color c = trace->get_line_color();
160  uint16_t thick = trace->get_line_thickness();
161  for (uint32_t i = 0; i < this->width_; i++) {
162  float v = (trace->get_tracedata()->get_value(i) - ymin) / yrange;
163  if (!std::isnan(v) && (thick > 0)) {
164  int16_t x = this->width_ - 1 - i;
165  uint8_t b = (i % (thick * LineType::PATTERN_LENGTH)) / thick;
166  if (((uint8_t) trace->get_line_type() & (1 << b)) == (1 << b)) {
167  int16_t y = (int16_t) roundf((this->height_ - 1) * (1.0 - v)) - thick / 2;
168  for (uint16_t t = 0; t < thick; t++) {
169  buff->draw_pixel_at(x_offset + x, y_offset + y + t, c);
170  }
171  }
172  }
173  }
174  }
175 }
176 
179  parent_ = g;
180 
181  // Determine maximum expected text and value width / height
182  int txtw = 0, txth = 0;
183  int valw = 0, valh = 0;
184  int lt = 0;
185  for (auto *trace : g->traces_) {
186  std::string txtstr = trace->get_name();
187  int fw, fos, fbl, fh;
188  this->font_label_->measure(txtstr.c_str(), &fw, &fos, &fbl, &fh);
189  if (fw > txtw)
190  txtw = fw;
191  if (fh > txth)
192  txth = fh;
193  if (trace->get_line_thickness() > lt)
194  lt = trace->get_line_thickness();
195  ESP_LOGI(TAGL, " %s %d %d", txtstr.c_str(), fw, fh);
196 
197  if (this->values_ != VALUE_POSITION_TYPE_NONE) {
198  std::stringstream ss;
199  ss << std::fixed << std::setprecision(trace->sensor_->get_accuracy_decimals()) << trace->sensor_->get_state();
200  std::string valstr = ss.str();
201  if (this->units_) {
202  valstr += trace->sensor_->get_unit_of_measurement();
203  }
204  this->font_value_->measure(valstr.c_str(), &fw, &fos, &fbl, &fh);
205  if (fw > valw)
206  valw = fw;
207  if (fh > valh)
208  valh = fh;
209  ESP_LOGI(TAGL, " %s %d %d", valstr.c_str(), fw, fh);
210  }
211  }
212  // Add extra margin
213  txtw *= 1.2;
214  valw *= 1.2;
215 
216  uint8_t n = g->traces_.size();
217  uint16_t w = this->width_;
218  uint16_t h = this->height_;
219  DirectionType dir = this->direction_;
220  ValuePositionType valpos = this->values_;
221  if (!this->font_value_) {
222  valpos = VALUE_POSITION_TYPE_NONE;
223  }
224  // Line sample always goes below text for compactness
225  this->yl_ = txth + (txth / 4) + lt / 2;
226 
227  if (dir == DIRECTION_TYPE_AUTO) {
228  dir = DIRECTION_TYPE_HORIZONTAL; // as default
229  if (h > 0) {
231  }
232  }
233 
234  if (valpos == VALUE_POSITION_TYPE_AUTO) {
235  // TODO: do something smarter?? - fit to w and h?
236  valpos = VALUE_POSITION_TYPE_BELOW;
237  }
238 
239  if (valpos == VALUE_POSITION_TYPE_BELOW) {
240  this->yv_ = txth + (txth / 4);
241  if (this->lines_)
242  this->yv_ += txth / 4 + lt;
243  } else if (valpos == VALUE_POSITION_TYPE_BESIDE) {
244  this->xv_ = (txtw + valw) / 2;
245  }
246 
247  // If width or height is specified we divide evenly within, else we do tight-fit
248  if (w == 0) {
249  this->x0_ = txtw / 2;
250  this->xs_ = txtw;
251  if (valpos == VALUE_POSITION_TYPE_BELOW) {
252  this->xs_ = std::max(txtw, valw);
253  ;
254  this->x0_ = this->xs_ / 2;
255  } else if (valpos == VALUE_POSITION_TYPE_BESIDE) {
256  this->xs_ = txtw + valw;
257  }
258  if (dir == DIRECTION_TYPE_VERTICAL) {
259  this->width_ = this->xs_;
260  } else {
261  this->width_ = this->xs_ * n;
262  }
263  } else {
264  this->xs_ = w / n;
265  this->x0_ = this->xs_ / 2;
266  }
267 
268  if (h == 0) {
269  this->ys_ = txth;
270  if (valpos == VALUE_POSITION_TYPE_BELOW) {
271  this->ys_ = txth + txth / 2 + valh;
272  if (this->lines_) {
273  this->ys_ += lt;
274  }
275  } else if (valpos == VALUE_POSITION_TYPE_BESIDE) {
276  if (this->lines_) {
277  this->ys_ = std::max(txth + txth / 4 + lt + txth / 4, valh + valh / 4);
278  } else {
279  this->ys_ = std::max(txth + txth / 4, valh + valh / 4);
280  }
281  this->height_ = this->ys_ * n;
282  }
283  if (dir == DIRECTION_TYPE_HORIZONTAL) {
284  this->height_ = this->ys_;
285  } else {
286  this->height_ = this->ys_ * n;
287  }
288  } else {
289  this->ys_ = h / n;
290  }
291 
292  if (dir == DIRECTION_TYPE_HORIZONTAL) {
293  this->ys_ = 0;
294  } else {
295  this->xs_ = 0;
296  }
297 }
298 
299 void Graph::draw_legend(display::DisplayBuffer *buff, uint16_t x_offset, uint16_t y_offset, Color color) {
300  if (!legend_)
301  return;
302 
304  if (this->border_) {
305  int w = legend_->width_;
306  int h = legend_->height_;
307  buff->horizontal_line(x_offset, y_offset, w, color);
308  buff->horizontal_line(x_offset, y_offset + h - 1, w, color);
309  buff->vertical_line(x_offset, y_offset, h, color);
310  buff->vertical_line(x_offset + w - 1, y_offset, h, color);
311  }
312 
313  int x = x_offset + legend_->x0_;
314  int y = y_offset;
315  for (auto *trace : traces_) {
316  std::string txtstr = trace->get_name();
317  ESP_LOGV(TAG, " %s", txtstr.c_str());
318 
319  buff->printf(x, y, legend_->font_label_, trace->get_line_color(), TextAlign::TOP_CENTER, "%s", txtstr.c_str());
320 
321  if (legend_->lines_) {
322  uint16_t thick = trace->get_line_thickness();
323  for (int i = 0; i < legend_->x0_ * 4 / 3; i++) {
324  uint8_t b = (i % (thick * LineType::PATTERN_LENGTH)) / thick;
325  if (((uint8_t) trace->get_line_type() & (1 << b)) == (1 << b)) {
326  buff->vertical_line(x - legend_->x0_ * 2 / 3 + i, y + legend_->yl_ - thick / 2, thick,
327  trace->get_line_color());
328  }
329  }
330  }
331 
332  if (legend_->values_ != VALUE_POSITION_TYPE_NONE) {
333  int xv = x + legend_->xv_;
334  int yv = y + legend_->yv_;
335  std::stringstream ss;
336  ss << std::fixed << std::setprecision(trace->sensor_->get_accuracy_decimals()) << trace->sensor_->get_state();
337  std::string valstr = ss.str();
338  if (legend_->units_) {
339  valstr += trace->sensor_->get_unit_of_measurement();
340  }
341  buff->printf(xv, yv, legend_->font_value_, trace->get_line_color(), TextAlign::TOP_CENTER, "%s", valstr.c_str());
342  ESP_LOGV(TAG, " value: %s", valstr.c_str());
343  }
344  x += legend_->xs_;
345  y += legend_->ys_;
346  }
347 }
348 
349 void Graph::setup() {
350  for (auto *trace : traces_) {
351  trace->init(this);
352  }
353 }
354 
356  for (auto *trace : traces_) {
357  ESP_LOGCONFIG(TAG, "Graph for sensor %s", trace->get_name().c_str());
358  }
359 }
360 
361 } // namespace graph
362 } // namespace esphome
void printf(int x, int y, Font *font, Color color, TextAlign align, const char *format,...) __attribute__((format(printf
Evaluate the printf-format format and print the result with the anchor point at [x,y] with font.
uint32_t get_width()
Definition: graph.h:158
void take_sample(float data)
Definition: graph.cpp:24
void setup() override
Definition: graph.cpp:349
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:26
void vertical_line(int x, int y, int height, Color color=COLOR_ON)
Draw a vertical line from the point [x,y] to [x,y+width] with the given color.
std::vector< GraphTrace * > traces_
Definition: graph.h:172
void horizontal_line(int x, int y, int width, Color color=COLOR_ON)
Draw a horizontal line from the point [x,y] to [x+width,y] with the given color.
void dump_config() override
Definition: graph.cpp:355
void init(int length)
Definition: graph.cpp:18
void init(Graph *g)
Determine the best coordinates of drawing text + lines.
Definition: graph.cpp:178
uint32_t get_duration()
Definition: graph.h:157
ValuePositionType
Definition: graph.h:37
void draw(display::DisplayBuffer *buff, uint16_t x_offset, uint16_t y_offset, Color color)
Definition: graph.cpp:59
uint8_t h
Definition: bl0939.h:21
void init(Graph *g)
Definition: graph.cpp:52
Definition: a4988.cpp:4
void draw_legend(display::DisplayBuffer *buff, uint16_t x_offset, uint16_t y_offset, Color color)
Definition: graph.cpp:299
void draw_pixel_at(int x, int y, Color color=COLOR_ON)
Set a single pixel at the specified coordinates to the given color.
bool state
Definition: fan.h:34