Uniot Core
0.9.0
Loading...
Searching...
No Matches
LispDevice.h
Go to the documentation of this file.
1/*
2 * This is a part of the Uniot project.
3 * Copyright (C) 2016-2023 Uniot <contact@uniot.io>
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19#pragma once
20
21#include <CBORStorage.h>
22#include <Date.h>
23#include <EventListener.h>
24#include <LispEvents.h>
25#include <MQTTDevice.h>
26#include <unLisp.h>
27
28#include <functional>
29
30namespace uniot {
31struct LispEvent {
32 struct Sender {
33 String type;
34 String id;
36 String eventID;
37 int32_t value;
38 uint64_t timestamp;
39};
40
41using LispEventInterceptor = std::function<bool(const LispEvent &event)>;
42
53class LispDevice : public MQTTDevice, public CBORStorage, public CoreEventListener {
54 public:
73
80 virtual void syncSubscriptions() override {
81 mTopicScript = MQTTDevice::subscribeDevice("script");
82 mTopicEvents = MQTTDevice::subscribeGroup("all", "event/+");
83 }
84
91 return unLisp::getInstance();
92 }
93
95 mEventInterceptor = interceptor;
96 }
97
99 getLisp().setStartHook(hook);
100 }
101
103 getLisp().setStopHook(hook);
104 }
105
106 void publishLispEvent(const String &eventID, int32_t value) {
107 CBORObject event;
108 event.put("eventID", eventID.c_str());
109 event.put("value", static_cast<int64_t>(value));
110 _populateAndPublishEvent(event.build());
111 }
112
120 if (CBORStorage::restore()) {
121 auto code = object().getString("code");
122 mPersist = object().getInt("persist");
123 mChecksum = object().getInt("checksum");
124
125 if (mPersist && code.length() > 0) {
127 }
128 }
129 }
130
140 bool store() {
141 object()
142 .put("persist", mPersist)
143 .put("checksum", (int)mChecksum)
144 .put("code", mPersist ? getLisp().getLastCode().c_str() : "")
145 .forceDirty(); // Avoid optimization. The pointer to the data may be the same. Read the warnings.
146
147 return CBORStorage::store();
148 }
149
159 virtual void onEventReceived(unsigned int topic, int msg) override {
163 if (!empty) {
164 mFailedWithError = true;
165
166 CBORObject packet;
167 packet.put("type", "error");
168 packet.put("timestamp", static_cast<int64_t>(Date::now()));
169 packet.put("msg", data.c_str());
170 publishDevice("debug/err", packet.build(), true);
171 UNIOT_LOG_ERROR("lisp error: %s", data.c_str());
172 }
173 });
174 return;
175 }
178 if (!empty) {
179 CBORObject packet;
180 packet.put("type", "log");
181 packet.put("timestamp", static_cast<int64_t>(Date::now()));
182 packet.put("msg", data.c_str());
183 publishDevice("debug/log", packet.build());
184 UNIOT_LOG_INFO("lisp log: %s", data.c_str());
185 }
186 });
187 return;
188 }
191 // NOTE: it is currently only used for debugging purposes
192 // UNIOT_LOG_TRACE_IF(!empty, "lisp: %s", data.toString().c_str());
193 });
194 return;
195 }
196 return;
197 }
200 // This is necessary to retrieve events marked as `retained` during the execution of a new script
201 this->unsubscribe(mTopicEvents);
202 this->subscribe(mTopicEvents);
203 return;
204 }
205 return;
206 }
209 CoreEventListener::receiveDataFromChannel(events::lisp::Channel::OUT_EVENT, [this](unsigned int id, bool empty, Bytes data) {
210 if (!empty) {
211 _populateAndPublishEvent(data);
212 }
213 });
214 }
215 return;
216 }
217 }
218
227 virtual void handle(const String &topic, const Bytes &payload) override {
228 if (MQTTDevice::isTopicMatch(mTopicScript, topic)) {
229 MQTTDevice::publishEmptyDevice("debug/err"); // clear previous errors
230 handleScript(payload);
231 return;
232 }
233 if (MQTTDevice::isTopicMatch(mTopicEvents, topic)) {
234 handleEvent(payload);
235 return;
236 }
237 }
238
248 void handleScript(const Bytes &payload) {
249 static bool firstPacketReceived = false;
250 CBORObject packet(payload);
251
252 // An empty "code" is a request to stop the machine, but getString() also returns ""
253 // when the key is absent -- and a payload that fails to decode reads as an empty map.
254 // Without this, a malformed packet would stop the running script. Returning before
255 // any state changes also leaves firstPacketReceived for the real retained packet.
256 if (!packet.hasKey("code")) {
257 UNIOT_LOG_WARN("script packet has no code, ignored");
258 return;
259 }
260
261 auto script = Bytes(packet.getString("code"));
262 auto newPersist = packet.getBool("persist");
263 auto newChecksum = script.terminate().checksum();
264
265 auto ignoreScript = false;
266
267 if (!firstPacketReceived) {
268 auto isEqual = mChecksum == newChecksum;
269 ignoreScript = isEqual && mPersist && !mFailedWithError;
270 firstPacketReceived = true;
271 }
272
273 if (!ignoreScript) {
274 mChecksum = newChecksum;
275 mPersist = newPersist;
276 mFailedWithError = false;
277
278 // TODO: check signature here later
281 } else {
282 UNIOT_LOG_INFO("script ignored: %s", script.c_str());
283 }
284
285 // Free memory to avoid fragmentation
286 object().clean();
287 // NOTE: you may need getLasCode() somewhere else, but it has already cleaned here
288 getLisp().cleanLastCode(); // Is it safe?
289 }
290
298 void handleEvent(const Bytes &payload) {
299 if (payload.size() > 0) {
300 CBORObject event(payload);
301 auto eventID = event.getString("eventID");
302 auto valueStr = event.getValueAsString("value");
303
304 if (eventID.isEmpty()) {
305 UNIOT_LOG_WARN("received event with empty eventID, ignoring");
306 return;
307 }
308
309 if (valueStr.isEmpty()) {
310 UNIOT_LOG_WARN("received event '%s' with empty value, ignoring", eventID.c_str());
311 return;
312 }
313
314 auto value = valueStr.toInt();
315 auto isNumber = value || valueStr == "0";
316
317 if (!isNumber) {
318 UNIOT_LOG_WARN("received event '%s' with non-numeric value '%s', ignoring", eventID.c_str(), valueStr.c_str());
319 return;
320 }
321
322 auto sender = event.getMap("sender");
323 LispEvent lispEvent;
324 lispEvent.eventID = eventID;
325 lispEvent.value = value;
326 lispEvent.timestamp = event.getInt("timestamp");
327 lispEvent.sender.type = sender.getString("type");
328 lispEvent.sender.id = sender.getString("id");
329
330 if (mEventInterceptor && !mEventInterceptor(lispEvent)) {
331 // The event was not accepted by the interceptor
332 return;
333 }
334
337 }
338 }
339
340 private:
341 void _populateAndPublishEvent(const Bytes &eventData) {
342 CBORObject event(eventData);
343 event.put("timestamp", static_cast<int64_t>(Date::now()))
344 .putMap("sender")
345 .put("type", "device")
346 .put("id", MQTTDevice::getDeviceId().c_str());
347 auto eventDataBuilt = event.build();
348 auto eventID = event.getString("eventID");
349 MQTTDevice::publishGroup("all", "event/" + eventID, eventDataBuilt, true);
350 // NOTE: Do we need to have a separate primitive to publish not retained events?
351 }
352
353 LispEventInterceptor mEventInterceptor;
354 uint32_t mChecksum;
355 bool mPersist;
356 bool mFailedWithError;
357
358 String mTopicScript;
359 String mTopicEvents;
360};
361
362} // namespace uniot
Lisp interpreter event definitions for the Uniot event system.
Definition Bytes.h:38
const char * c_str() const
Gets the byte array as a C string.
Definition Bytes.h:306
size_t size() const
Gets the size of the byte array.
Definition Bytes.h:343
Definition CBORObject.h:40
bool hasKey(const char *key) const
Check if the map contains a specific string key.
Definition CBORObject.h:120
long getInt(int key) const
Get an integer value at a specific integer key.
Definition CBORObject.h:409
CBORObject & put(int key, int value)
Put an integer value at a specific integer key.
Definition CBORObject.h:180
void forceDirty()
Force the object to be marked as dirty (modified)
Definition CBORObject.h:536
String getString(int key) const
Get a string value at a specific integer key.
Definition CBORObject.h:429
void clean()
Reset the object to an empty state.
Definition CBORObject.h:545
Bytes build() const
Build the CBOR data into binary format.
Definition CBORObject.h:509
bool getBool(int key) const
Get a boolean value at a specific integer key.
Definition CBORObject.h:389
virtual bool restore() override
Restore the CBOR object from the filesystem.
Definition CBORStorage.h:102
virtual bool store() override
Store the CBOR object to the filesystem.
Definition CBORStorage.h:74
CBORStorage(const String &path)
Constructs a new CBORStorage object.
Definition CBORStorage.h:46
CBORObject & object()
Get access to the underlying CBORObject.
Definition CBORStorage.h:60
static time_t now()
Returns the current Unix timestamp.
Definition Date.h:75
void emitEvent(unsigned int topic, int msg)
void receiveDataFromChannel(T_topic channel, DataChannelCallback callback)
Receives data from a specific channel on all connected EventBus instances.
Definition EventEntity.h:117
bool sendDataToChannel(T_topic channel, T_data data)
Sends data to a specific channel on all connected EventBus instances.
Definition EventEntity.h:98
EventListener * listenToEvent(unsigned int topic)
virtual void syncSubscriptions() override
Sets up MQTT topic subscriptions for the device.
Definition LispDevice.h:80
void setStartHook(LispStartHook hook)
Definition LispDevice.h:98
virtual void handle(const String &topic, const Bytes &payload) override
Processes MQTT messages received on subscribed topics.
Definition LispDevice.h:227
LispDevice()
Constructs a LispDevice instance.
Definition LispDevice.h:61
void runStoredCode()
Loads and executes previously stored code from persistent storage.
Definition LispDevice.h:119
void handleScript(const Bytes &payload)
Processes script payloads received via MQTT.
Definition LispDevice.h:248
void setEventInterceptor(LispEventInterceptor interceptor)
Definition LispDevice.h:94
virtual void onEventReceived(unsigned int topic, int msg) override
Processes events received from the unLisp interpreter.
Definition LispDevice.h:159
unLisp & getLisp()
Provides access to the unLisp interpreter instance.
Definition LispDevice.h:90
bool store()
Stores the current script state to persistent storage.
Definition LispDevice.h:140
void handleEvent(const Bytes &payload)
Processes event payloads received via MQTT.
Definition LispDevice.h:298
void setStopHook(LispStopHook hook)
Definition LispDevice.h:102
void publishLispEvent(const String &eventID, int32_t value)
Definition LispDevice.h:106
const String & subscribe(const String &topic)
Subscribes to a specific MQTT topic.
Definition MQTTDevice.cpp:74
MQTTDevice()
Constructs a new MQTTDevice instance.
Definition MQTTDevice.h:44
bool isTopicMatch(const String &storedTopic, const String &incomingTopic) const
Determines if a stored topic matches an incoming topic string using MQTT wildcards.
Definition MQTTDevice.cpp:137
void publishGroup(const String &groupId, const String &subTopic, const Bytes &payload, bool retained=false, bool sign=false)
Publishes a message to a group-specific subtopic.
Definition MQTTDevice.cpp:114
const String & subscribeGroup(const String &groupId, const String &subTopic)
Subscribes to a group-specific subtopic.
Definition MQTTDevice.cpp:92
const String & getDeviceId() const
Gets the device identifier.
Definition MQTTDevice.cpp:37
bool unsubscribe(const String &topic)
Unsubscribes from a specific topic.
Definition MQTTDevice.cpp:64
void publishEmptyDevice(const String &subTopic)
Publishes an empty message to a device-specific subtopic with retained flag set.
Definition MQTTDevice.cpp:120
void publishDevice(const String &subTopic, const Bytes &payload, bool retained=false, bool sign=false)
Publishes a message to a device-specific subtopic.
Definition MQTTDevice.cpp:108
const String & subscribeDevice(const String &subTopic)
Subscribes to a device-specific subtopic.
Definition MQTTDevice.cpp:83
static unLisp & getInstance()
Definition Singleton.h:73
Definition unLisp.h:209
void setStopHook(LispStopHook hook)
Set the hook called when a script stops.
Definition unLisp.h:319
void setStartHook(LispStartHook hook)
Set the hook called when a script starts.
Definition unLisp.h:301
void cleanLastCode()
Clear the stored last executed code.
Definition unLisp.h:371
void runCode(const Bytes &data, LispStartReason reason=LispStartReason::Received)
Run Lisp code in the interpreter.
Definition unLisp.h:259
EventListener< unsigned int, int, Bytes > CoreEventListener
Type alias for the common EventListener configuration used in the core system.
Definition EventListener.h:100
#define UNIOT_LOG_INFO(...)
Log an INFO level message Used for general information about system operation. Only compiled if UNIOT...
Definition Logger.h:315
#define UNIOT_LOG_WARN(...)
Log an WARN level message Used for warnings about potentially problematic situations....
Definition Logger.h:294
#define UNIOT_LOG_ERROR(...)
Log an ERROR level message Used for critical errors that may prevent normal operation....
Definition Logger.h:273
std::function< void(LispStartReason)> LispStartHook
Called after the interpreter is built and before the script is evaluated.
Definition LispHelper.h:186
std::function< void(LispStopReason)> LispStopHook
Called before the interpreter is destroyed.
Definition LispHelper.h:192
@ Restored
A stored script, run from AppKit::attach() during boot.
Definition LispHelper.h:167
@ Received
A script that arrived over MQTT.
Definition LispHelper.h:168
@ OUT_LISP_REQUEST
Topic for Lisp requests to the application services.
Definition LispEvents.h:89
@ OUT_LISP_MSG
Topic for Lisp output messages and notifications.
Definition LispEvents.h:88
@ IN_LISP_EVENT
Topic for incoming events from application to Lisp.
Definition LispEvents.h:91
@ OUT_LISP_EVENT
Topic for outgoing events from Lisp to application.
Definition LispEvents.h:90
@ IN_NEW_EVENT
New incoming event received from application for Lisp processing.
Definition LispEvents.h:107
@ OUT_MSG_ADDED
Standard output message was added to the output buffer.
Definition LispEvents.h:102
@ OUT_MSG_LOG
Log message was generated by the Lisp interpreter.
Definition LispEvents.h:103
@ OUT_NEW_EVENT
New outgoing event generated by Lisp for the application.
Definition LispEvents.h:106
@ OUT_REFRESH_EVENTS
Request to refresh the event queue and process pending events.
Definition LispEvents.h:105
@ OUT_MSG_ERROR
Error message was generated due to Lisp execution failure.
Definition LispEvents.h:104
@ OUT_LISP_LOG
Channel for Lisp log messages and debug information.
Definition LispEvents.h:74
@ IN_EVENT
Channel for incoming events from the application to Lisp.
Definition LispEvents.h:77
@ OUT_LISP
Channel for standard Lisp output (stdout equivalent)
Definition LispEvents.h:73
@ OUT_LISP_ERR
Channel for Lisp error messages and exceptions.
Definition LispEvents.h:75
@ OUT_EVENT
Channel for outgoing events from Lisp to the application.
Definition LispEvents.h:76
Contains all classes and functions related to the Uniot Core.
std::function< bool(const LispEvent &event)> LispEventInterceptor
Definition LispDevice.h:41
Definition LispDevice.h:32
String type
Definition LispDevice.h:33
String id
Definition LispDevice.h:34
Definition LispDevice.h:31
String eventID
Definition LispDevice.h:36
uint64_t timestamp
Definition LispDevice.h:38
struct uniot::LispEvent::Sender sender
int32_t value
Definition LispDevice.h:37