fork/GramFirmware
git clone https://git.julia.blue/fork/GramFirmware
818d962
gram
1#ifndef _COMMS_NEOPIXELBACKEND_HPP 2#define _COMMS_NEOPIXELBACKEND_HPP 3 4#include "core/CommunicationBackend.hpp" 5 6#include <FastLED.h> 7#include <config.pb.h> 8#include <time.h> 9 10template < uint8_t data_pin ,int led_count > class NeoPixelBackend :public CommunicationBackend { 11public : 12NeoPixelBackend ( 13InputState & inputs , 14InputSource ** input_sources , 15size_t input_source_count , 16const Button * button_mappings , 17const RgbConfig * rgb_configs , 18const size_t rgb_configs_count , 19const uint8_t & brightness 20 ) 21 :CommunicationBackend (inputs ,input_sources ,input_source_count ), 22_button_mappings (button_mappings ), 23_rgb_configs (rgb_configs ), 24_rgb_configs_count (rgb_configs_count ), 25_brightness (brightness ) { 26FastLED .addLeds < NEOPIXEL ,data_pin > (_leds ,led_count ); 27FastLED .setMaxPowerInVoltsAndMilliamps (5 ,200 ); 28FastLED .setMaxRefreshRate (0 ); 29 } 30 31 ~NeoPixelBackend () {FastLED .clear (true); } 32 33virtual void SetGameMode (InputMode * gamemode ) { 34// Clear current button colors. 35for (size_t i = 0 ;i < button_colors_count ;i ++ ) { 36_button_colors [i ]= 0 ; 37 } 38 39if (gamemode == nullptr || gamemode -> GetConfig ()== nullptr ) { 40_config = nullptr ; 41return ; 42 } 43 44uint8_t rgb_config_id = gamemode -> GetConfig ()-> rgb_config ; 45if (rgb_config_id == 0 || rgb_config_id > _rgb_configs_count ) { 46_config = nullptr ; 47return ; 48 } 49_config = & _rgb_configs [rgb_config_id - 1 ]; 50 51// Build new mapping array to give O(n) lookup later. 52for (size_t i = 0 ;i < _config -> button_colors_count ;i ++ ) { 53ButtonToColorMapping mapping = _config -> button_colors [i ]; 54_button_colors [max (0 ,mapping .button - 1 )]= mapping .color ; 55 } 56 } 57 58virtual void SendReport () { 59// Use timeout to avoid refreshing too fast which results in FastLED library blocking. 60if (!time_reached (_refresh_timeout )) { 61return ; 62 } 63_refresh_timeout = make_timeout_time_ms (refresh_interval_ms ); 64 65for (int i = 0 ;i < led_count ;i ++ ) { 66Button button = this -> _button_mappings [i ]; 67_leds [i ]= _config != nullptr ?_button_colors [max (0 ,button - 1 )] :0 ; 68 } 69FastLED .setBrightness (_brightness ); 70FastLED .show (); 71 } 72 73protected : 74static constexpr size_t button_colors_count = 75sizeof (RgbConfig ::button_colors ) /sizeof (ButtonToColorMapping ); 76static constexpr uint64_t refresh_interval_ms = 4 ;// 250Hz refresh rate 77 78const Button * _button_mappings ; 79const RgbConfig * _rgb_configs ; 80const size_t _rgb_configs_count ; 81const RgbConfig * _config = nullptr ; 82const uint8_t & _brightness ; 83 84CRGB _leds [led_count ]; 85uint32_t _button_colors [button_colors_count ]; 86absolute_time_t _refresh_timeout = 0 ; 87}; 88 89#endif