embassy-st7789v-plot 0.3.0

Moteur de tracé de graphiques cartésiens (X, Y) adaptatifs et configurables pour écrans TFT LCD **ST7789V 240×320**, construit au-dessus de [`embassy-st7789v`](https://crates.io/crates/embassy-st7789v).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
#![no_std]
#![forbid(unsafe_code)]
//! # embassy-st7789v-plot
//!
//! Moteur de tracé de graphiques cartésiens (X, Y) adaptatifs et configurables
//! pour écrans TFT LCD ST7789V, s'appuyant sur [`embassy-st7789v`](https://docs.rs/embassy-st7789v).
//!
//! ## Caractéristiques principales
//!
//! - **`#![no_std]` + `#![forbid(unsafe_code)]`** : Sûr et optimisé pour le bare-metal.
//! - **Zéro allocation dynamique** : Buffers statiques uniquement (ring buffer).
//! - **Rendu intelligent (Double Phase)** : Cadre, étiquettes et titres tracés une seule fois.
//!   Seuls la grille interne et le signal sont rafraîchis dynamiquement.
//! - **Axes configurables** : Graduations statiques avec labels personnalisés et détection
//!   automatique / coloration du zéro.
//! - **Historique circulaire** : Jusqu'à 240 points (limite physique de l'écran).
//! - **Protection stricte des bordures** : Clamping des primitives à l'espace interne utile.
//! - **Deux modes de rendu** :
//!
//! | Mode | Type | Clignotement |
//! |------|------|:------------:|
//! | [`LineChart`] + [`render()`](LineChart::render) | async, direct SPI | possible |
//! | [`LineChartBuffered`] + [`render_buf()`](LineChartBuffered::render_buf) + `flush()` | sync, RAM | **aucun** |
//!
//! ## Structures principales
//!
//! - [`Graphics`] : Contexte graphique async (direct SPI).
//! - [`AxisConfig`] : Configuration d'un axe (min, max, pas, label).
//! - [`PlotConfig`] : Configuration complète (position, marges, couleurs, axes).
//! - [`LineChart`] : Graphique async avec rendu direct SPI.
//! - [`LineChartBuffered`] : Graphique sync avec rendu framebuffer — zéro clignotement.
//!
//! ## Exemple — mode direct async
//!
//! ```no_run
//! # use embassy_st7789v::{Color, St7789v, NoPin};
//! # use embedded_hal::digital::OutputPin;
//! # use embedded_hal_async::spi::SpiDevice;
//! use embassy_st7789v_plot::{Graphics, AxisConfig, PlotConfig, LineChart};
//!
//! # async fn example<SPI, DC>(display: &mut St7789v<SPI, DC, NoPin>)
//! # where SPI: SpiDevice, DC: OutputPin,
//! # {
//! let x_axis = AxisConfig::new(0.0, 10.0, 2.0, b"Time (s)");
//! let y_axis = AxisConfig::new(-50.0, 50.0, 20.0, b"Volt (mV)");
//!
//! let config = PlotConfig {
//!     x: 10, y: 10, width: 220, height: 200,
//!     margin_left: 30, margin_right: 10,
//!     margin_top: 10, margin_bottom: 30,
//!     x_axis, y_axis,
//!     bg_color:    Color::BLACK,
//!     line_color:  Color::GREEN,
//!     axis_color:  Color::WHITE,
//!     grid_color:  Color::GRAY,
//!     text_color:  Color::WHITE,
//!     label_color: Color::CYAN,
//! };
//!
//! let mut chart: LineChart<100> = LineChart::new(config);
//! chart.push(12.4);
//! chart.push(-5.2);
//! chart.push(22.1);
//!
//! let mut gfx = Graphics::new_no_rst(display);
//! chart.render(&mut gfx).await;
//! # }
//! ```
//!
//! ## Exemple : mode framebuffer sync (zéro clignotement)
//!
//! ```no_run
//! # use embassy_st7789v::{Color, St7789v, St7789vBuffered, NoPin};
//! # use embedded_hal::digital::OutputPin;
//! # use embedded_hal_async::spi::SpiDevice;
//! use embassy_st7789v_plot::{AxisConfig, PlotConfig, LineChartBuffered};
//!
//! # async fn example<SPI, DC>(spi: SPI, dc: DC, rst: NoPin)
//! # where SPI: SpiDevice, DC: OutputPin,
//! # {
//! let config = PlotConfig {
//!     x: 10, y: 10, width: 220, height: 200,
//!     margin_left: 30, margin_right: 10,
//!     margin_top: 10, margin_bottom: 30,
//!     x_axis: AxisConfig::new(0.0, 10.0, 2.0, b"Time (s)"),
//!     y_axis: AxisConfig::new(-50.0, 50.0, 20.0, b"Volt (mV)"),
//!     bg_color:    Color::BLACK,
//!     line_color:  Color::GREEN,
//!     axis_color:  Color::WHITE,
//!     grid_color:  Color::GRAY,
//!     text_color:  Color::WHITE,
//!     label_color: Color::CYAN,
//! };
//!
//! let mut ecran = St7789vBuffered::new(St7789v::new(spi, dc, rst));
//! ecran.driver().init().await.unwrap();
//!
//! let mut chart: LineChartBuffered<100> = LineChartBuffered::new(config);
//!
//! loop {
//!     chart.push(12.4);
//!     chart.render_buf(&mut ecran);  // tout en RAM, synchrone
//!     ecran.flush().await.unwrap();  // envoi unique → zéro clignotement
//! }
//! # }
//! ```
//!
//! ## Patron de borrow : mode direct
//!
//! `Graphics` tient un `&mut St7789v` pour toute sa durée de vie.
//! Pour appeler les méthodes du driver (texte, orientation…),
//! `gfx` doit être sorti de portée au préalable.
//!
//! ```rust,no_run
//! {
//!     let mut gfx = Graphics::new_no_rst(&mut display);
//!     chart.render(&mut gfx).await;
//! } // ← borrow libéré
//! display.draw_str(8, 8, b"OK", Color::WHITE, Color::BLACK).await.unwrap();
//! ```
//!
//! ## Patron de borrow : mode framebuffer
//!
//! `render_buf` prend `&mut St7789vBuffered` directement.
//! Appeler `flush()` après le rendu.
//!
//! ```rust,no_run
//! chart.render_buf(&mut ecran);  // sync
//! ecran.flush().await.unwrap();  // async, envoi SPI unique
//! ```
//!
//! ## Note sur les erreurs SPI
//!
//! Les fonctions de ce crate ignorent silencieusement les erreurs SPI.
//! Si votre application requiert une gestion d'erreur fine, utilisez
//! directement `ecran.draw_pixel()`.
//! Les primitives `render_buf` n'accèdent jamais au SPI — aucune erreur possible.
use embedded_hal::digital::OutputPin;
use embedded_hal_async::spi::SpiDevice;
use embassy_st7789v::{Color, NoPin, St7789v, St7789vBuffered, SCREEN_H, SCREEN_W};
use embassy_st7789v_graphics::{GraphicsBuffered, line_buf};


/// Taille maximale de l'historique des données du graphique.
pub const PLOT_HISTORY_LIMIT: usize = 240;

// ─────────────────────────────────────────────────────────────────────────────
// Contexte graphique embarqué (repris de tes primitives)
// ─────────────────────────────────────────────────────────────────────────────

pub struct Graphics<'a, SPI, DC, RST = NoPin>
where
    SPI: SpiDevice,
    DC: OutputPin,
    RST: OutputPin,
{
    /// Référence vers l'affichage ST7789V
    pub display: &'a mut St7789v<SPI, DC, RST>,
}

impl<'a, SPI, DC> Graphics<'a, SPI, DC, NoPin>
where
    SPI: SpiDevice,
    DC: OutputPin,
{
    /// Crée un nouveau contexte graphique sans broche RST.
    ///
    /// # Arguments
    ///
    /// * `display` - Référence mutable vers l'affichage ST7789V
    #[inline]
    pub fn new_no_rst(display: &'a mut St7789v<SPI, DC, NoPin>) -> Self {
        Self { display }
    }
}

impl<'a, SPI, DC, RST> Graphics<'a, SPI, DC, RST>
where
    SPI: SpiDevice,
    DC: OutputPin,
    RST: OutputPin,
{
    /// Crée un nouveau contexte graphique avec broche RST.
    ///
    /// # Arguments
    ///
    /// * `display` - Référence mutable vers l'affichage ST7789V
    #[inline]
    pub fn new(display: &'a mut St7789v<SPI, DC, RST>) -> Self {
        Self { display }
    }

    /// Trace un pixel à la position (x, y) avec la couleur donnée.
    ///
    /// Les coordonnées négatives ou en dehors de l'écran sont ignorées silencieusement.
    ///
    /// # Arguments
    ///
    /// * `x` - Coordonnée X (peut être négative ou hors écran)
    /// * `y` - Coordonnée Y (peut être négative ou hors écran)
    /// * `color` - Couleur du pixel
 
    #[inline(always)]
    pub async fn pixel(&mut self, x: i32, y: i32, color: Color) {
        if x >= 0 && y >= 0 && x < SCREEN_W as i32 && y < SCREEN_H as i32 {
            let _ = self.display.draw_pixel(x as u16, y as u16, color).await;
        }
    }
}

/// Trace une ligne entre deux points en utilisant l'algorithme de Bresenham.
///
/// Cette fonction utilise l'algorithme de Bresenham pour tracer une ligne
/// entre les points (x0, y0) et (x1, y1). Elle gère correctement les lignes
/// en dehors de l'écran via la vérification de limites dans [`Graphics::pixel`].
///
/// # Arguments
///
/// * `gfx` - Contexte graphique
/// * `x0` - Coordonnée X du point de départ
/// * `y0` - Coordonnée Y du point de départ
/// * `x1` - Coordonnée X du point d'arrivée
/// * `y1` - Coordonnée Y du point d'arrivée
/// * `color` - Couleur de la ligne
pub async fn line<SPI, DC, RST>(
    gfx: &mut Graphics<'_, SPI, DC, RST>,
    mut x0: i32,
    mut y0: i32,
    x1: i32,
    y1: i32,
    color: Color,
) where
    SPI: SpiDevice,
    DC: OutputPin,
    RST: OutputPin,
{
    let dx = (x1 - x0).abs();
    let sx = if x0 < x1 { 1 } else { -1 };
    let dy = -(y1 - y0).abs();
    let sy = if y0 < y1 { 1 } else { -1 };
    let mut err = dx + dy;

    loop {
        gfx.pixel(x0, y0, color).await;
        if x0 == x1 && y0 == y1 {
            break;
        }
        let e2 = 2 * err;
        if e2 >= dy {
            err += dy;
            x0 += sx;
        }
        if e2 <= dx {
            err += dx;
            y0 += sy;
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Configuration des Axes
// ─────────────────────────────────────────────────────────────────────────────

/// Définit un axe avec graduation statique fixe.
///
/// Cette structure configure un axe du graphique avec une plage de valeurs,
/// un pas de graduation régulier et un label descriptif.
///
/// # Champs
///
/// * `start` - Valeur minimale de l'axe (ex: 0.0)
/// * `end` - Valeur maximale de l'axe (ex: 10.0)
/// * `step` - Espacement régulier entre graduations (ex: 1.0)
/// * `label` - Label texte affiché le long de l'axe (ex: b"Temp (C)")
#[derive(Clone, Copy, Debug)]
pub struct AxisConfig {
    pub start: f32,
    pub end: f32,
    pub step: f32,
    pub label: &'static [u8],
}

impl AxisConfig {
    /// Crée une nouvelle configuration d'axe.
    ///
    /// # Arguments
    ///
    /// * `start` - Valeur minimale (doit être < `end`)
    /// * `end` - Valeur maximale (doit être > `start`)
    /// * `step` - Pas de graduation (doit être > 0)
    /// * `label` - Label statique affiché (par exemple b"Temp (C)")
    ///
    /// # Panics
    ///
    /// Ne paniquera pas ici, mais utilisez [`is_valid`](Self::is_valid) après construction
    /// pour vérifier la cohérence.
    pub const fn new(start: f32, end: f32, step: f32, label: &'static [u8]) -> Self {
        Self { start, end, step, label }
    }

    /// Vérifie la cohérence de la configuration.
    ///
    /// Retourne `true` si :
    /// - `step` > 0.0
    /// - `end` > `start`
    ///

    pub fn is_valid(&self) -> bool {
        self.step > 0.0 && self.end > self.start
    }

    /// Calcule le nombre de graduations (incluant start et end).
    ///
    /// En `no_std`, le cast direct remplace `f32::floor()`.
    ///
    /// # Retour
    ///
    /// Nombre de ticks incluant les extrémités, ou 0 si la configuration est invalide.

    pub fn tick_count(&self) -> usize {
        if !self.is_valid() {
            return 0;
        }
        let count = ((self.end - self.start) / self.step) as usize;
        count + 1
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Configuration et Structure de Traçage
// ─────────────────────────────────────────────────────────────────────────────

/// Configuration complète du tracé graphique.
///
/// Cette structure définit tous les paramètres visuels et géométriques du graphique :
/// position, taille, marges, axes, et palette de couleurs.
///
/// # Champs
///
/// * `x`, `y` - Position du coin haut-gauche du graphique (en pixels)
/// * `width`, `height` - Dimensions du graphique (en pixels)
/// * `margin_*` - Marges internes pour les axes et labels
/// * `x_axis`, `y_axis` - Configurations des deux axes
/// * `*_color` - Couleurs pour le fond, les lignes, axes, grille, texte, labels

#[derive(Clone, Copy, Debug)]
pub struct PlotConfig {
    pub x: i32,
    pub y: i32,
    pub width: i32,
    pub height: i32,
    pub margin_left: i32,
    pub margin_right: i32,
    pub margin_top: i32,
    pub margin_bottom: i32,
    pub x_axis: AxisConfig,
    pub y_axis: AxisConfig,
    pub bg_color: Color,
    pub line_color: Color,
    pub axis_color: Color,
    pub grid_color: Color,
    pub text_color: Color,
    pub label_color: Color,
}

/// Gestionnaire du graphique avec axes statiques configurables.
///
/// `LineChart<N>` maintient un historique circulaire de N points de données et
/// gère le rendu du graphique avec grille, axes, graduations et labels.
///
/// # Paramètre générique
///
/// * `N` - Nombre maximum de points historiques (doit être ≤ `PLOT_HISTORY_LIMIT` = 240)
///
/// # Fonctionnement interne
///
/// - **Ring buffer** : Les données sont stockées dans un tableau fixe avec un pointeur
///   `head` qui tourne. Quand le buffer est plein, les nouvelles données écrasent les
///   plus anciennes.
/// - **Historique** : Seuls les N points les plus récents sont affichés.
/// - **Rendu** : Les données sont converties en pixels via `scale_x()` et `scale_y()`,
///   puis connectées par des lignes (Bresenham).
pub struct LineChart<const N: usize> {
    config: PlotConfig,
    data: [f32; N],
    head: usize,
    count: usize,
    plot_x: i32,
    plot_y: i32,
    plot_w: i32,
    plot_h: i32,
    initialized: bool, // Ajout du flag pour suivre l'état du tracé
}

impl<const N: usize> LineChart<N> {
    /// Crée un nouveau gestionnaire de graphique.
    ///
    /// # Arguments
    ///
    /// * `config` - Configuration complète du graphique
    ///
    /// # Panics
    ///
    /// Panique si :
    /// - N > `PLOT_HISTORY_LIMIT` (240)
    /// - La configuration d'axe X est invalide
    /// - La configuration d'axe Y est invalide

    pub fn new(config: PlotConfig) -> Self {
        assert!(N <= PLOT_HISTORY_LIMIT, "L'historique dépasse la limite physique horizontale.");
        assert!(config.x_axis.is_valid(), "Configuration axe X invalide.");
        assert!(config.y_axis.is_valid(), "Configuration axe Y invalide.");
        
        let plot_x = config.x + config.margin_left;
        let plot_y = config.y + config.margin_top;
        let plot_w = config.width - config.margin_left - config.margin_right;
        let plot_h = config.height - config.margin_top - config.margin_bottom;

        Self {
            config,
            data: [0.0; N],
            head: 0,
            count: 0,
            plot_x,
            plot_y,
            plot_w,
            plot_h,
            initialized: false, // Initialisé à false par défaut
        }
    }

    /// Retourne une référence à la configuration du graphique.
    #[inline]
    pub fn config(&self) -> &PlotConfig {
        &self.config
    }

    /// Ajoute une nouvelle valeur à l'historique.
    ///
    /// Si le buffer est plein (N points), la valeur la plus ancienne est remplacée.
    ///
    /// # Arguments
    ///
    /// * `value` - Valeur à ajouter (sera clampée à la plage Y-axis lors du rendu)

    pub fn push(&mut self, value: f32) {
        self.data[self.head] = value;
        self.head = (self.head + 1) % N;
        if self.count < N {
            self.count += 1;
        }
    }

    /// Efface l'historique et réinitialise le graphique.
    pub fn clear(&mut self) {
        self.head = 0;
        self.count = 0;
        self.data.fill(0.0);
        self.initialized = false; // Permet de redessiner le cadre lors du prochain render
    }

    #[inline]
    fn get_sample(&self, index: usize) -> f32 {
        let oldest = if self.count < N { 0 } else { self.head };
        self.data[(oldest + index) % N]
    }

    /// Convertit une valeur Y en coordonnée écran (pixels).
    ///
    /// La valeur est clampée à la plage [y_min, y_max] définie par `y_axis`,
    /// puis convertie linéairement en pixels.
    #[inline]
    fn scale_y(&self, value: f32) -> i32 {
        let y_min = self.config.y_axis.start;
        let y_max = self.config.y_axis.end;
        
        if y_max <= y_min {
            return self.plot_y + self.plot_h - 1;
        }

        let clamped_val = value.max(y_min).min(y_max);
        let ratio = (clamped_val - y_min) / (y_max - y_min);
        
        self.plot_y + self.plot_h - 1 - (ratio * (self.plot_h - 1) as f32) as i32
    }

    /// Convertit un index de données en coordonnée X écran (pixels).
    ///
    /// Les N points sont distribués uniformément sur la largeur de la zone de tracé.
    #[inline]
    fn scale_x(&self, index: usize) -> i32 {
        if N <= 1 {
            return self.plot_x;
        }
        self.plot_x + (index as i32 * (self.plot_w - 1)) / (N as i32 - 1)
    }

    /// Convertit une valeur d'axe X en coordonnée écran (pour labels).
    ///
    /// Similaire à `scale_y`, mais pour l'axe X.
    #[inline]
    fn scale_x_value(&self, value: f32) -> i32 {
        let x_min = self.config.x_axis.start;
        let x_max = self.config.x_axis.end;
        
        if x_max <= x_min {
            return self.plot_x;
        }
        
        let clamped = value.max(x_min).min(x_max);
        let ratio = (clamped - x_min) / (x_max - x_min);
        self.plot_x + (ratio * (self.plot_w - 1) as f32) as i32
    }

    /// Affiche le graphique complet avec grille, axes, graduations et courbe.
    ///
    /// Cette méthode effectue :
    /// 1. Remplissage du fond
    /// 2. Grille horizontale (Y) et labels des graduations
    /// 3. Grille verticale (X) et labels des graduations
    /// 4. Labels des axes (titres)
    /// 5. Bordures externes
    /// 6. Tracé de la courbe (données)
    ///
    /// # Arguments
    ///
    /// * `gfx` - Contexte graphique initialisé
    ///

   pub async fn render<SPI, DC, RST>(&mut self, gfx: &mut Graphics<'_, SPI, DC, RST>)
    where
        SPI: SpiDevice,
        DC: OutputPin,
        RST: OutputPin,
    {
        let right_edge = self.plot_x + self.plot_w - 1;
        let bottom_edge = self.plot_y + self.plot_h - 1;

        //  1. TRACÉ UNIQUE DU CADRE ET DU TEXTE (Uniquement au premier passage) ──
        if !self.initialized {
            // Effacer l'intégralité de l'espace alloué au composant
            let _ = gfx.display.fill_rect(
                self.config.x as u16,
                (self.config.y - 16).max(0) as u16,
                (self.config.x + self.config.width) as u16,
                (self.config.y + self.config.height + 16).min(SCREEN_H as i32) as u16,
                self.config.bg_color,
            ).await;

            //Labels Y
            let y_axis = &self.config.y_axis;
            let y_range = y_axis.end - y_axis.start;
            let tick_count_y = y_axis.tick_count();

            for i in 0..tick_count_y {
                let value = y_axis.start + (i as f32 * y_axis.step);
                let ratio = (value - y_axis.start) / y_range;
                let y_grid = bottom_edge - (ratio * (self.plot_h - 1) as f32) as i32;

                // Couleur spéciale pour le vrai zéro
                let label_color = if value.abs() < 0.001 {
                    Color::GREEN
                } else {
                    self.config.text_color
                };

                let label_y = (y_grid - 4).max(self.config.y + 8).min(self.config.y + self.config.height - 8);

                let _ = gfx.display.draw_f32(
                    (self.config.x + 2) as u16,
                    label_y as u16,
                    value,
                    1,
                    label_color,
                    self.config.bg_color,
                ).await;
            }

            //Labels X
            let x_axis = &self.config.x_axis;
            let tick_count_x = x_axis.tick_count();

            for i in 0..tick_count_x {
                let value = x_axis.start + (i as f32 * x_axis.step);
                let x_grid = self.scale_x_value(value);

                let label_x = (x_grid - 8).max(self.config.x + 2).min(self.config.x + self.config.width - 20);

                let _ = gfx.display.draw_f32(
                    label_x as u16,
                    (bottom_edge + 4) as u16,
                    value,
                    1,
                    self.config.text_color,
                    self.config.bg_color,
                ).await;
            }

            // Titres des axes
            let _ = gfx.display.draw_str(
                (self.config.x + 2) as u16,
                (self.config.y - 16).max(0) as u16,
                y_axis.label,
                self.config.label_color,
                self.config.bg_color,
            ).await;

            let label_x_x = self.plot_x + (self.plot_w / 2) - ((x_axis.label.len() as i32 * 6) / 2);
            let _ = gfx.display.draw_str(
                label_x_x.max(self.config.x + 2) as u16,
                (self.config.y + self.config.height + 4).min(SCREEN_H as i32 - 8) as u16,
                x_axis.label,
                self.config.label_color,
                self.config.bg_color,
            ).await;

            // Bordures externes fixes
            let _ = gfx.display.draw_hline(self.plot_x as u16, self.plot_y as u16, self.plot_w as u16, self.config.axis_color).await;
            let _ = gfx.display.draw_hline(self.plot_x as u16, bottom_edge as u16, self.plot_w as u16, self.config.axis_color).await;
            let _ = gfx.display.draw_vline(self.plot_x as u16, self.plot_y as u16, self.plot_h as u16, self.config.axis_color).await;
            let _ = gfx.display.draw_vline(right_edge as u16, self.plot_y as u16, self.plot_h as u16, self.config.axis_color).await;

            self.initialized = true;
        }

        //  2. NETTOYAGE DYNAMIQUE DE L'INTÉRIEUR STRICT (Sans toucher aux bordures) ──
        let _ = gfx.display.fill_rect(
            (self.plot_x + 1) as u16,
            (self.plot_y + 1) as u16,
            (right_edge - 1) as u16,
            (bottom_edge - 1) as u16,
            self.config.bg_color,
        ).await;

        // Grille horizontale (Y) interne
        let y_axis = &self.config.y_axis;
        let y_range = y_axis.end - y_axis.start;
        let tick_count_y = y_axis.tick_count();
        for i in 1..tick_count_y - 1 {
            let value = y_axis.start + (i as f32 * y_axis.step);
            let ratio = (value - y_axis.start) / y_range;
            let y_grid = bottom_edge - (ratio * (self.plot_h - 1) as f32) as i32;

            // Éviter de dessiner une grille si elle se superpose aux bordures de 1 pixel
            if y_grid > self.plot_y && y_grid < bottom_edge {
                // Si c'est la ligne du zéro, on peut optionnellement lui donner une couleur distinctive
                let color = if value.abs() < 0.001 { Color::GREEN } else { self.config.grid_color };
                
                let _ = gfx.display.draw_hline(
                    (self.plot_x + 1) as u16, 
                    y_grid as u16, 
                    (self.plot_w - 2) as u16, 
                    color
                ).await;
            }
        }

        // Grille verticale (X) interne
        let x_axis = &self.config.x_axis;
        let tick_count_x = x_axis.tick_count();
        for i in 1..tick_count_x - 1 {
            let value = x_axis.start + (i as f32 * x_axis.step);
            let x_grid = self.scale_x_value(value);

            if x_grid > self.plot_x && x_grid < right_edge {
                let _ = gfx.display.draw_vline(
                    x_grid as u16,
                    (self.plot_y + 1) as u16,
                    (self.plot_h - 2) as u16,
                    self.config.grid_color
                ).await;
            }
        }

        //  3. TRACÉ DE LA COURBE DES DONNÉES (Contrainte à l'intérieur strict) ──
        if self.count < 2 {
            if self.count == 1 {
                let px = self.scale_x(0).max(self.plot_x + 1).min(right_edge - 1);
                let py = self.scale_y(self.get_sample(0)).max(self.plot_y + 1).min(bottom_edge - 1);
                gfx.pixel(px, py, self.config.line_color).await;
            }
            return;
        }

        // Récupération et clamping des points pour qu'ils ne bavent jamais sur la bordure blanche
        let mut prev_x = self.scale_x(0).max(self.plot_x + 1).min(right_edge - 1);
        let mut prev_y = self.scale_y(self.get_sample(0)).max(self.plot_y + 1).min(bottom_edge - 1);

        for i in 1..self.count {
            let next_x = self.scale_x(i).max(self.plot_x + 1).min(right_edge - 1);
            let next_y = self.scale_y(self.get_sample(i)).max(self.plot_y + 1).min(bottom_edge - 1);

            line(gfx, prev_x, prev_y, next_x, next_y, self.config.line_color).await;

            prev_x = next_x;
            prev_y = next_y;
        }
    }

}

 // ─────────────────────────────────────────────────────────────────────────────
// LineChart framebuffer — zéro clignotement
// ─────────────────────────────────────────────────────────────────────────────

/// Version framebuffer de [`LineChart`].
///
/// Identique à `LineChart` mais toutes les opérations de dessin écrivent
/// dans le framebuffer RAM via `GraphicsBuffered` et les primitives `*_buf`.
/// Aucun pixel n'est envoyé à l'écran avant l'appel à `flush()`.
///
/// # Patron d'utilisation
///
/// ```rust,no_run
/// let mut chart: LineChartBuffered<100> = LineChartBuffered::new(config);
/// chart.push(12.4);
/// chart.render_buf(&mut ecran);  // tout en RAM, synchrone
/// ecran.flush().await.unwrap();  // envoi unique → zéro clignotement
/// ```
pub struct LineChartBuffered<const N: usize> {
    config: PlotConfig,
    data: [f32; N],
    head: usize,
    count: usize,
    plot_x: i32,
    plot_y: i32,
    plot_w: i32,
    plot_h: i32,
    initialized: bool,
}

impl<const N: usize> LineChartBuffered<N> {
    pub fn new(config: PlotConfig) -> Self {
        assert!(N <= PLOT_HISTORY_LIMIT);
        assert!(config.x_axis.is_valid());
        assert!(config.y_axis.is_valid());

        let plot_x = config.x + config.margin_left;
        let plot_y = config.y + config.margin_top;
        let plot_w = config.width  - config.margin_left - config.margin_right;
        let plot_h = config.height - config.margin_top  - config.margin_bottom;

        Self { config, data: [0.0; N], head: 0, count: 0,
               plot_x, plot_y, plot_w, plot_h, initialized: false }
    }

    pub fn push(&mut self, value: f32) {
        self.data[self.head] = value;
        self.head = (self.head + 1) % N;
        if self.count < N { self.count += 1; }
    }

    pub fn clear(&mut self) {
        self.head = 0; self.count = 0;
        self.data.fill(0.0);
        self.initialized = false;
    }

    #[inline]
    fn get_sample(&self, index: usize) -> f32 {
        let oldest = if self.count < N { 0 } else { self.head };
        self.data[(oldest + index) % N]
    }

    #[inline]
    fn scale_y(&self, value: f32) -> i32 {
        let y_min = self.config.y_axis.start;
        let y_max = self.config.y_axis.end;
        if y_max <= y_min { return self.plot_y + self.plot_h - 1; }
        let ratio = (value.max(y_min).min(y_max) - y_min) / (y_max - y_min);
        self.plot_y + self.plot_h - 1 - (ratio * (self.plot_h - 1) as f32) as i32
    }

    #[inline]
    fn scale_x(&self, index: usize) -> i32 {
        if N <= 1 { return self.plot_x; }
        self.plot_x + (index as i32 * (self.plot_w - 1)) / (N as i32 - 1)
    }

    #[inline]
    fn scale_x_value(&self, value: f32) -> i32 {
        let x_min = self.config.x_axis.start;
        let x_max = self.config.x_axis.end;
        if x_max <= x_min { return self.plot_x; }
        let ratio = (value.max(x_min).min(x_max) - x_min) / (x_max - x_min);
        self.plot_x + (ratio * (self.plot_w - 1) as f32) as i32
    }

    /// Rendu complet dans le framebuffer — **synchrone, sans `.await`**.
    ///
    /// Appeler `ecran.flush().await` après pour envoyer à l'écran.
    pub fn render_buf<SPI, DC, RST>(
        &mut self,
        ecran: &mut St7789vBuffered<SPI, DC, RST>,
    ) where
        SPI: embedded_hal_async::spi::SpiDevice,
        DC: embedded_hal::digital::OutputPin,
        RST: embedded_hal::digital::OutputPin,
    {
        let right_edge  = self.plot_x + self.plot_w - 1;
        let bottom_edge = self.plot_y + self.plot_h - 1;

        // ── 1. Cadre, labels, titres — une seule fois ─────────────────────
        if !self.initialized {
            // Fond
            ecran.fill_rect_buf(
                self.config.x as u16,
                (self.config.y - 16).max(0) as u16,
                (self.config.x + self.config.width) as u16,
                (self.config.y + self.config.height + 16).min(SCREEN_H as i32) as u16,
                self.config.bg_color,
            );

            // Labels Y
            let y_axis = &self.config.y_axis;
            let y_range = y_axis.end - y_axis.start;
            for i in 0..y_axis.tick_count() {
                let value = y_axis.start + i as f32 * y_axis.step;
                let ratio = (value - y_axis.start) / y_range;
                let y_grid = bottom_edge - (ratio * (self.plot_h - 1) as f32) as i32;
                let label_y = (y_grid - 4).max(self.config.y + 8).min(self.config.y + self.config.height - 8);
                let color = if value.abs() < 0.001 { Color::GREEN } else { self.config.text_color };
                // Rendu du label f32 via draw_f32_buf (voir ci-dessous)
                self.draw_f32_buf(ecran, (self.config.x + 2) as u16, label_y as u16, value, 1, color);
            }

            // Labels X
            let x_axis = &self.config.x_axis;
            for i in 0..x_axis.tick_count() {
                let value = x_axis.start + i as f32 * x_axis.step;
                let x_grid = self.scale_x_value(value);
                let label_x = (x_grid - 8).max(self.config.x + 2).min(self.config.x + self.config.width - 20);
                self.draw_f32_buf(ecran, label_x as u16, (bottom_edge + 4) as u16, value, 1, self.config.text_color);
            }

            // Titres
            ecran.draw_str_buf(
                (self.config.x + 2) as u16,
                (self.config.y - 16).max(0) as u16,
                y_axis.label,
                self.config.label_color,
                self.config.bg_color,
            );
            let label_x_x = self.plot_x + (self.plot_w / 2) - (x_axis.label.len() as i32 * 6 / 2);
            ecran.draw_str_buf(
                label_x_x.max(self.config.x + 2) as u16,
                (self.config.y + self.config.height + 4).min(SCREEN_H as i32 - 8) as u16,
                x_axis.label,
                self.config.label_color,
                self.config.bg_color,
            );

            // Bordures
            for px in self.plot_x..=right_edge {
                ecran.set_pixel(px as u16, self.plot_y as u16,   self.config.axis_color);
                ecran.set_pixel(px as u16, bottom_edge as u16,   self.config.axis_color);
            }
            for py in self.plot_y..=bottom_edge {
                ecran.set_pixel(self.plot_x as u16,  py as u16,  self.config.axis_color);
                ecran.set_pixel(right_edge as u16,   py as u16,  self.config.axis_color);
            }

            self.initialized = true;
        }

        // ── 2. Nettoyage intérieur ────────────────────────────────────────
        ecran.fill_rect_buf(
            (self.plot_x + 1) as u16,
            (self.plot_y + 1) as u16,
            (right_edge  - 1) as u16,
            (bottom_edge - 1) as u16,
            self.config.bg_color,
        );

        // ── 3. Grille Y ───────────────────────────────────────────────────
        let y_axis = &self.config.y_axis;
        let y_range = y_axis.end - y_axis.start;
        for i in 1..y_axis.tick_count().saturating_sub(1) {
            let value = y_axis.start + i as f32 * y_axis.step;
            let ratio = (value - y_axis.start) / y_range;
            let y_grid = bottom_edge - (ratio * (self.plot_h - 1) as f32) as i32;
            if y_grid > self.plot_y && y_grid < bottom_edge {
                let color = if value.abs() < 0.001 { Color::GREEN } else { self.config.grid_color };
                ecran.fill_rect_buf(
                    (self.plot_x + 1) as u16, y_grid as u16,
                    (right_edge  - 1) as u16, y_grid as u16,
                    color,
                );
            }
        }

        // ── 4. Grille X ───────────────────────────────────────────────────
        let x_axis = &self.config.x_axis;
        for i in 1..x_axis.tick_count().saturating_sub(1) {
            let value = x_axis.start + i as f32 * x_axis.step;
            let x_grid = self.scale_x_value(value);
            if x_grid > self.plot_x && x_grid < right_edge {
                ecran.fill_rect_buf(
                    x_grid as u16, (self.plot_y + 1) as u16,
                    x_grid as u16, (bottom_edge - 1) as u16,
                    self.config.grid_color,
                );
            }
        }

        // ── 5. Courbe ─────────────────────────────────────────────────────
        if self.count < 2 {
            if self.count == 1 {
                let px = self.scale_x(0).max(self.plot_x + 1).min(right_edge - 1);
                let py = self.scale_y(self.get_sample(0)).max(self.plot_y + 1).min(bottom_edge - 1);
                ecran.set_pixel(px as u16, py as u16, self.config.line_color);
            }
            return;
        }

        let mut gfx = GraphicsBuffered::new(ecran);
        let mut prev_x = self.scale_x(0).max(self.plot_x + 1).min(right_edge - 1);
        let mut prev_y = self.scale_y(self.get_sample(0)).max(self.plot_y + 1).min(bottom_edge - 1);

        for i in 1..self.count {
            let next_x = self.scale_x(i).max(self.plot_x + 1).min(right_edge - 1);
            let next_y = self.scale_y(self.get_sample(i)).max(self.plot_y + 1).min(bottom_edge - 1);
            line_buf(&mut gfx, prev_x, prev_y, next_x, next_y, self.config.line_color);
            prev_x = next_x;
            prev_y = next_y;
        }
    }

    /// Rendu d'un f32 en framebuffer (équivalent de `draw_f32` pour St7789vBuffered).
    fn draw_f32_buf<SPI, DC, RST>(
        &self,
        ecran: &mut St7789vBuffered<SPI, DC, RST>,
        x: u16, y: u16,
        val: f32,
        decimales: u8,
        fg: Color,
    ) where
        SPI: embedded_hal_async::spi::SpiDevice,
        DC: embedded_hal::digital::OutputPin,
        RST: embedded_hal::digital::OutputPin,
    {
        let bg = self.config.bg_color;
        if val.is_nan()      { ecran.draw_str_buf(x, y, b"NaN",  fg, bg); return; }
        if val.is_infinite() {
            if val > 0.0 { ecran.draw_str_buf(x, y, b"+Inf", fg, bg); }
            else         { ecran.draw_str_buf(x, y, b"-Inf", fg, bg); }
            return;
        }
        let negatif = val < 0.0;
        let mut abs = if negatif { -val } else { val };
        let mut cx = x;
        if negatif { cx = ecran.draw_char_buf(cx, y, 10, fg, bg); } // '-'
        let facteur = { let mut f = 1u32; for _ in 0..decimales { f *= 10; } f };
        abs += 0.5 / facteur as f32;
        let entier = abs as u32;
        cx = ecran.draw_u32_buf(cx, y, entier, fg, bg);
        if decimales > 0 {
            cx = ecran.draw_char_buf(cx, y, 38, fg, bg); // '.'
            let mut frac = abs - entier as f32;
            let mut chiffres = [0u8; 8];
            for i in 0..decimales as usize { frac *= 10.0; chiffres[i] = frac as u8; frac -= chiffres[i] as f32; }
            for i in 0..decimales as usize { cx = ecran.draw_char_buf(cx, y, chiffres[i] as usize, fg, bg); }
        }
        let _ = cx;
    }
}