EnigmaIOT  0.9.8
Secure sensor and gateway platform based on ESP8266 and ESP32
LedController.cpp
Go to the documentation of this file.
1 //
2 //
3 //
4 
5 #include <functional>
6 #include "LedController.h"
7 
8 using namespace std;
9 using namespace placeholders;
10 
11 constexpr auto CONFIG_FILE = "/customconf.json";
12 
13 // -----------------------------------------
14 // You may add some global variables you need here,
15 // like serial port instances, I2C, etc
16 // -----------------------------------------
17 
18 const char* ledKey = "led";
19 const char* commandKey = "cmd";
20 
21 
22 bool CONTROLLER_CLASS_NAME::processRxCommand (const uint8_t* address, const uint8_t* buffer, uint8_t length, nodeMessageType_t command, nodePayloadEncoding_t payloadEncoding) {
23  // Process incoming messages here
24  // They are normally encoded as MsgPack so you can confert them to JSON very easily
25 
26  // Check command type
28  DEBUG_WARN ("Wrong message type");
29  return false;
30  }
31  // Check payload encoding
32  if (payloadEncoding != MSG_PACK) {
33  DEBUG_WARN ("Wrong payload encoding");
34  return false;
35  }
36 
37  // Decode payload
38  DynamicJsonDocument doc (256);
39  uint8_t tempBuffer[MAX_MESSAGE_LENGTH];
40 
41  memcpy (tempBuffer, buffer, length);
42  DeserializationError error = deserializeMsgPack (doc, tempBuffer, length);
43  // Check decoding
44  if (error != DeserializationError::Ok) {
45  DEBUG_WARN ("Error decoding command: %s", error.c_str ());
46  return false;
47  }
48 
49  DEBUG_WARN ("Command: %d = %s", command, command == nodeMessageType_t::DOWNSTREAM_DATA_GET ? "GET" : "SET");
50 
51  // Dump debug data
52  size_t strLen = measureJson (doc) + 1;
53  char* strBuffer = (char*)malloc (strLen);
54  serializeJson (doc, strBuffer, strLen);
55  DEBUG_WARN ("Data: %s", strBuffer);
56  free (strBuffer);
57 
58  // Check cmd field on JSON data
59  if (!doc.containsKey (commandKey)) {
60  DEBUG_WARN ("Wrong format");
61  return false;
62  }
63 
64  // Get state
66  if (!strcmp (doc[commandKey], ledKey)) {
67  DEBUG_WARN ("Request LED status. LED = %s", led == _LED_ON ? "ON" : "OFF");
68  if (!sendLedStatus ()) {
69  DEBUG_WARN ("Error sending LED status");
70  return false;
71  }
72  }
73  }
74 
75  // Set state
77  if (!strcmp (doc[commandKey], ledKey)) {
78  if (doc.containsKey (ledKey)) {
79  if (doc[ledKey].as<int> () == 1) {
80  led = _LED_ON;
81  } else if (doc[ledKey].as<int> () == 0) {
82  led = _LED_OFF;
83  } else {
84  DEBUG_WARN ("Wrong LED value: %d", doc[ledKey].as<int> ());
85  return false;
86  }
87  DEBUG_WARN ("Set LED status to %s", led == _LED_ON ? "ON" : "OFF");
88  } else {
89  DEBUG_WARN ("Wrong format");
90  return false;
91  }
92 
93  // Confirm command execution with send state
94  if (!sendLedStatus ()) {
95  DEBUG_WARN ("Error sending LED status");
96  return false;
97  }
98  }
99  }
100 
101 
102  return true;
103 }
104 
106  const size_t capacity = JSON_OBJECT_SIZE (2);
107  DynamicJsonDocument json (capacity);
108 
109  json[commandKey] = ledKey;
110  json[ledKey] = led ? _LED_ON : _LED_OFF;
111 
112  return sendJson (json);
113 }
114 
115 
116 bool CONTROLLER_CLASS_NAME::sendCommandResp (const char* command, bool result) {
117  // Respond to command with a result: true if successful, false if failed
118  return true;
119 }
120 
122 
123 #if SUPPORT_HA_DISCOVERY
124  // Register every HAEntity discovery function here. As many as you need
125  addHACall (std::bind (&CONTROLLER_CLASS_NAME::buildHADiscovery, this));
126  addHACall (std::bind (&CONTROLLER_CLASS_NAME::sendLedStatus, this));
127 #endif
128 
130 }
131 
133  enigmaIotNode = node;
134 
135  // You do node setup here. Use it as it was the normal setup() Arduino function
136  pinMode (LED_PIN, OUTPUT);
137  digitalWrite (LED_PIN, _LED_ON);
138 
139  // Send a 'hello' message when initalizing is finished
140  sendStartAnouncement ();
141 
142  sendLedStatus ();
143 
144  DEBUG_DBG ("Finish begin");
145 
146  // If your node should sleep after sending data do all remaining tasks here
147 }
148 
150 
151  // If your node stays allways awake do your periodic task here
152  digitalWrite (LED_PIN, led);
153 }
154 
156  // It your class uses dynamic data free it up here
157  // This is normally not needed but it is a good practice
158 }
159 
161  DEBUG_INFO ("==== CCost Controller Configuration start ====");
162  // If you need to add custom configuration parameters do it here
163 }
164 
166  DEBUG_INFO ("==== CCost Controller Configuration result ====");
167  // You can read configuration paramenter values here
168 }
169 
171  // If you need to read custom configuration data do it here
172  return true;
173 }
174 
176  // If you need to save custom configuration data do it here
177  return true;
178 }
179 
180 #if SUPPORT_HA_DISCOVERY
181 // Repeat this method for every entity
183  // Select corresponding HAEntiny type
184  HASwitch* haEntity = new HASwitch ();
185 
186  uint8_t* msgPackBuffer;
187 
188  if (!haEntity) {
189  DEBUG_WARN ("JSON object instance does not exist");
190  return;
191  }
192 
193  // *******************************
194  // Add your characteristics here
195  // There is no need to futher modify this function
196 
197  //haEntity->setNameSufix ("switch");
198  haEntity->setPayloadOff ("{\"cmd\":\"led\",\"led\":0}");
199  haEntity->setPayloadOn ("{\"cmd\":\"led\",\"led\":1}");
200  haEntity->setValueField ("led");
201  haEntity->setStateOff (0);
202  haEntity->setStateOn (1);
203 
204  // *******************************
205 
206  size_t bufferLen = haEntity->measureMessage ();
207 
208  msgPackBuffer = (uint8_t*)malloc (bufferLen);
209 
210  size_t len = haEntity->getAnounceMessage (bufferLen, msgPackBuffer);
211 
212  DEBUG_INFO ("Resulting MSG pack length: %d", len);
213 
214  if (!sendHADiscovery (msgPackBuffer, len)) {
215  DEBUG_WARN ("Error sending HA discovery message");
216  }
217 
218  if (haEntity) {
219  delete (haEntity);
220  }
221 
222  if (msgPackBuffer) {
223  free (msgPackBuffer);
224  }
225 }
226 #endif // SUPPORT_HA_DISCOVERY
CONFIG_FILE
constexpr auto CONFIG_FILE
Custom configuration file name.
Definition: LedController.cpp:11
HAEntity::measureMessage
size_t measureMessage()
Gets needed buffer size for discovery message.
Definition: haEntity.h:217
nodeMessageType
nodeMessageType
Message code definition.
Definition: EnigmaIOTNode.h:35
MAX_MESSAGE_LENGTH
static const uint8_t MAX_MESSAGE_LENGTH
Maximum payload size on ESP-NOW.
Definition: EnigmaIoTconfigAdvanced.h:21
HAEntity::getAnounceMessage
size_t getAnounceMessage(int bufferlen, uint8_t *buffer)
Gets entity anounce message to be sent over EnigmaIOT message.
Definition: haEntity.h:153
EnigmaIOTjsonController::connectInform
virtual void connectInform()
Used to notify controller that it is registered on EnigmaIOT network.
Definition: EnigmaIOTjsonController.h:81
CONTROLLER_CLASS_NAME::loop
void loop() override
This should be called periodically for module handling.
Definition: ButtonController.cpp:53
CONTROLLER_CLASS_NAME::buildHADiscovery
void buildHADiscovery()
Definition: ButtonController.cpp:124
DOWNSTREAM_DATA_GET
@ DOWNSTREAM_DATA_GET
Definition: EnigmaIOTGateway.h:44
DOWNSTREAM_DATA_SET
@ DOWNSTREAM_DATA_SET
Definition: EnigmaIOTGateway.h:42
CONTROLLER_CLASS_NAME::configManagerStart
void configManagerStart() override
Called when wifi manager starts config portal.
Definition: ButtonController.cpp:103
HASwitch::setStateOn
void setStateOn(const char *payload)
The payload that represents the on state. Used when value that represents on state in the state_topic...
Definition: haSwitch.cpp:34
_LED_ON
#define _LED_ON
Definition: LedController.h:30
CONTROLLER_CLASS_NAME::sendLedStatus
bool sendLedStatus()
Definition: LedController.cpp:105
CONTROLLER_CLASS_NAME::~CONTROLLER_CLASS_NAME
~CONTROLLER_CLASS_NAME()
Definition: ButtonController.cpp:98
ledKey
const char * ledKey
Definition: LedController.cpp:18
HASwitch
Definition: haSwitch.h:94
nodePayloadEncoding_t
nodePayloadEncoding_t
Definition: EnigmaIOTNode.h:58
HASwitch::setStateOff
void setStateOff(const char *payload)
The payload that represents the off state. Used when value that represents off state in the state_top...
Definition: haSwitch.cpp:40
HASwitch::setPayloadOff
void setPayloadOff(const char *payload)
The payload that represents off state. If specified, will be used for both comparing to the value in ...
Definition: haSwitch.cpp:20
commandKey
const char * commandKey
Definition: LedController.cpp:19
CONTROLLER_CLASS_NAME::saveConfig
bool saveConfig() override
Saves output module configuration.
Definition: ButtonController.cpp:119
MSG_PACK
@ MSG_PACK
Definition: EnigmaIOTGateway.h:65
CONTROLLER_CLASS_NAME::connectInform
void connectInform()
Used to notify controller that it is registered on EnigmaIOT network.
Definition: ButtonController.cpp:31
LedController.h
LED_PIN
#define LED_PIN
Definition: LedController.h:29
data
@ data
Definition: GwOutput_generic.h:23
CONTROLLER_CLASS_NAME::sendCommandResp
bool sendCommandResp(const char *command, bool result) override
Sends command processing response acknowledge.
Definition: ButtonController.cpp:26
CONTROLLER_CLASS_NAME::configManagerExit
void configManagerExit(bool status) override
Called when wifi manager exits config portal.
Definition: ButtonController.cpp:109
EnigmaIOTNodeClass
Main node class. Manages communication with gateway and allows sending and receiving user data.
Definition: EnigmaIOTNode.h:134
HASwitch::setPayloadOn
void setPayloadOn(const char *payload)
The payload that represents on state. If specified, will be used for both comparing to the value in t...
Definition: haSwitch.cpp:14
CONTROLLER_CLASS_NAME::setup
void setup(EnigmaIOTNodeClass *node, void *data=NULL)
Initialize data structures.
Definition: ButtonController.cpp:40
HASwitch::setValueField
void setValueField(const char *payload)
Defines a json key to extract device’s state from the state_topic. To determine the switches’s state ...
Definition: haSwitch.cpp:54
_LED_OFF
#define _LED_OFF
Definition: LedController.h:31
CONTROLLER_CLASS_NAME::processRxCommand
bool processRxCommand(const uint8_t *address, const uint8_t *buffer, uint8_t length, nodeMessageType_t command, nodePayloadEncoding_t payloadEncoding) override
Called to process a downlink command.
Definition: ButtonController.cpp:19
CONTROLLER_CLASS_NAME::loadConfig
bool loadConfig() override
Loads output module configuration.
Definition: ButtonController.cpp:114
status
@ status
Definition: GwOutput_generic.h:25