Uniot Core
0.9.0
Loading...
Searching...
No Matches
AppKit.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
26
34
35#pragma once
36
37#if defined(ESP32)
38#include <esp_system.h>
39#endif
40
41#include <Common.h>
43#include <Date.h>
44#include <EventBus.h>
47#include <LispDevice.h>
48#include <LispPrimitives.h>
49#include <Logger.h>
50#include <MQTTKit.h>
51#include <NetworkController.h>
52#include <Singleton.h>
53#include <TopDevice.h>
54#include <unLisp.h>
55
63
68namespace uniot {
84class AppKit : public ICoreEventBusConnectionKit, public ISchedulerConnectionKit, public Singleton<AppKit> {
85 friend class Singleton<AppKit>;
86
87 public:
96 uint8_t pinBtn = UINT8_MAX;
97 uint8_t activeLevelBtn = LOW;
98 uint8_t pinLed = UINT8_MAX;
99 uint8_t activeLevelLed = HIGH;
102 bool registerLispBtn = true;
103 };
104
110 return unLisp::getInstance();
111 }
112
118 return mMQTT;
119 }
120
126 return mCredentials;
127 }
128
138 bool setWiFiCredentials(const String &ssid, const String &password) {
139 return mNetwork.setCredentials(ssid, password);
140 }
141
151 bool setUserId(const String &userId) {
152 if (!userId.isEmpty()) {
153 mCredentials.setOwnerId(userId);
154 mCredentials.store();
155 return true;
156 }
157 return false;
158 }
159
171 bool addCustomPage(const String &path, const uint8_t *gzData, size_t gzLen, const String &label = "", const char *contentType = "text/html") {
172 return mNetwork.addCustomPage(path, gzData, gzLen, label, contentType);
173 }
174
184 bool addCustomRoute(const String &path, WebRequestMethodComposite method, ArRequestHandlerFunction handler) {
185 return mNetwork.addCustomRoute(path, method, handler);
186 }
187
196 virtual void pushTo(TaskScheduler &scheduler) override {
197 scheduler.push(mNetwork);
198 scheduler.push(mMQTT);
199 scheduler.push("lisp_task", getLisp().getTask());
200 scheduler.push("lisp_cleanup", getLisp().getCleanupTask());
201 scheduler.push("date_sync", Date::getInstance().getSyncTask());
202
203 mTopDevice.setScheduler(scheduler);
204
205 if (mpNetworkDevice) {
206 scheduler.push(*mpNetworkDevice);
207 } else {
208 UNIOT_LOG_WARN("configure the network controller before pushing to the scheduler");
209 }
210 }
211
218 virtual void attach() override {
219 _initPrimitives();
220 mNetwork.attach();
221 mMQTT.attach();
222
223 if (mpNetworkDevice) {
224 mpNetworkDevice->attach();
225 }
226
227 getLisp().getCleanupTask()->attach(15000);
228 mLispDevice.runStoredCode();
229 }
230
239 virtual void registerWithBus(CoreEventBus &eventBus) override {
247 eventBus.registerEntity(&mNetwork);
248 eventBus.registerEntity(&mMQTT);
249 eventBus.registerEntity(&getLisp());
250 eventBus.registerEntity(&mLispDevice);
251 eventBus.registerEntity(mpNetworkEventListener
253 ->listenToEvent(events::mqtt::Topic::CONNECTION));
254
255 if (mpNetworkDevice) {
256 eventBus.registerEntity(mpNetworkDevice.get());
257 } else {
258 UNIOT_LOG_WARN("configure the network controller before registering to the event bus");
259 }
260 }
261
270 virtual void unregisterFromBus(CoreEventBus &eventBus) override {
278 eventBus.unregisterEntity(&mNetwork);
279 eventBus.unregisterEntity(&mMQTT);
280 eventBus.unregisterEntity(&getLisp());
281 eventBus.unregisterEntity(&mLispDevice);
282 eventBus.unregisterEntity(mpNetworkEventListener
283 ->stopListeningToEvent(events::network::Topic::CONNECTION)
284 ->stopListeningToEvent(events::mqtt::Topic::CONNECTION));
285
286 if (mpNetworkDevice) {
287 eventBus.unregisterEntity(mpNetworkDevice.get());
288 }
289 }
290
301 config.activeLevelBtn,
302 config.pinLed,
303 config.activeLevelLed,
304 config.maxRebootCount,
305 config.rebootWindowMs,
306 config.registerLispBtn);
307 }
308
323 void configureNetworkController(uint8_t pinBtn = UINT8_MAX,
324 uint8_t activeLevelBtn = LOW,
325 uint8_t pinLed = UINT8_MAX,
326 uint8_t activeLevelLed = HIGH,
327 uint8_t maxRebootCount = UNIOT_WIFI_REBOOT_RESET_COUNT,
328 uint32_t rebootWindowMs = UNIOT_WIFI_REBOOT_WINDOW_MS,
329 bool registerLispBtn = true) {
330 if (mpNetworkDevice) {
331 UNIOT_LOG_WARN("network controller already configured");
332 return;
333 }
334
335 mpNetworkDevice = MakeUnique<NetworkController>(mNetwork, pinBtn, activeLevelBtn, pinLed, activeLevelLed, maxRebootCount, rebootWindowMs);
336 auto ctrlBtn = mpNetworkDevice->getButton();
337 if (ctrlBtn && registerLispBtn) {
339 }
340 }
341
351 mLispDevice.setEventInterceptor(interceptor);
352 }
353
359 mLispDevice.setStartHook(hook);
360 }
361
367 mLispDevice.setStopHook(hook);
368 }
369
379 void publishLispEvent(const String &eventID, int32_t value) {
380 mLispDevice.publishLispEvent(eventID, value);
381 }
382
383 private:
390 AppKit()
391 : mNetwork(mCredentials),
392 mMQTT(mCredentials, [this](CBORObject &info) {
393 auto obj = info.putMap("primitives");
395
396 auto registers = info.putMap("misc").putMap("registers");
398
399 info.put("timestamp", static_cast<int64_t>(Date::now()));
400 info.put("creator", mCredentials.getCreatorId().c_str());
401 info.put("public_key", mCredentials.getPublicKey().c_str());
402 info.put("mqtt_size", MQTT_MAX_PACKET_SIZE);
403 info.put("debug", UNIOT_LOG_ENABLED);
404 info.put("version", UNIOT_CORE_VERSION);
405 info.put("lisp_version", LISP_VERSION);
406 info.put("lisp_heap", UNIOT_LISP_HEAP);
407 info.put("lisp_stack", UNIOT_LISP_MAX_EVAL_STACK);
408 // The reset reason is an enum of the chip's own, so it only means something
409 // alongside the model.
410#if defined(ESP8266)
411 info.put("mcu", "ESP8266");
412 info.put("reset_reason", static_cast<int64_t>(ESP.getResetInfoPtr()->reason));
413#elif defined(ESP32)
414 info.put("mcu", ESP.getChipModel());
415 info.put("reset_reason", static_cast<int64_t>(esp_reset_reason()));
416#endif
417 }),
418 mpNetworkDevice(nullptr) {
419 _initMqtt();
420 _initTasks();
421 _initListeners();
422 }
423
430 inline void _initMqtt() {
431 mMQTT.setServer(UNIOT_MQTT_HOST, UNIOT_MQTT_PORT);
432 mMQTT.addDevice(mTopDevice);
433 mMQTT.addDevice(mLispDevice);
434 mTopDevice.syncSubscriptions();
435 mLispDevice.syncSubscriptions();
436 }
437
443 inline void _initTasks() {
444 // TODO: init new tasks here
445 }
446
453 inline void _initPrimitives() {
456 }
459 }
460 // Analog values are 10 bits on every chip, so a script reads and writes the same range
461 // wherever it runs. These are global Arduino settings, so they are only applied when a
462 // script can actually use analog, and a sketch that wants different values sets them
463 // after begin().
466#if defined(ESP8266)
467 analogWriteRange(1023);
468#elif defined(ESP32)
469 analogWriteResolution(10);
470#endif
471 }
474 // The ESP8266's ADC is 10 bits already; the ESP32 family returns 12 or 13.
475#if defined(ESP32)
476 analogReadResolution(10);
477#endif
478 }
481 }
482 }
483
490 inline void _initListeners() {
491 mpNetworkEventListener = MakeUnique<CoreCallbackEventListener>([&](int topic, int msg) {
493 switch (msg) {
495 UNIOT_LOG_DEBUG("network connected, ip: %s", WiFi.localIP().toString().c_str());
496 break;
498 UNIOT_LOG_DEBUG("access point mode");
499 mpNetworkEventListener->receiveDataFromChannel(events::network::Channel::OUT_SSID, [this](unsigned int id, bool empty, Bytes data) {
500 if (!empty) {
501 UNIOT_LOG_DEBUG("SSID: %s", data.terminate().c_str());
502 }
503 });
504 break;
505
507 UNIOT_LOG_DEBUG("connecting");
508 mpNetworkEventListener->receiveDataFromChannel(events::network::Channel::OUT_SSID, [this](unsigned int id, bool empty, Bytes data) {
509 if (!empty) {
510 UNIOT_LOG_DEBUG("SSID: %s", data.terminate().c_str());
511 }
512 });
513 break;
514
516 UNIOT_LOG_DEBUG("disconnecting");
517 break;
518
520 UNIOT_LOG_DEBUG("disconnected");
521 break;
522
524 UNIOT_LOG_DEBUG("network available");
525 break;
526
528 default:
529 UNIOT_LOG_DEBUG("connection failed");
530 break;
531 }
532 return;
533 }
534 if (events::mqtt::Topic::CONNECTION == topic) {
535 switch (msg) {
537 UNIOT_LOG_DEBUG("MQTT connected");
538 if (mCredentials.isOwnerChanged()) {
539 UNIOT_LOG_INFO("owner changed, renewing subscriptions");
540 mMQTT.renewSubscriptions();
541 mCredentials.resetOwnerChanged();
542 } else {
543 UNIOT_LOG_INFO("owner not changed, keeping subscriptions");
544 }
545 break;
547 default:
548 UNIOT_LOG_DEBUG("MQTT connection failed");
549 break;
550 }
551 return;
552 }
553 });
554 }
555
556 Credentials mCredentials;
557 NetworkScheduler mNetwork;
558 MQTTKit mMQTT;
559 TopDevice mTopDevice;
560 LispDevice mLispDevice;
561
562 UniquePointer<NetworkController> mpNetworkDevice;
563 UniquePointer<CoreCallbackEventListener> mpNetworkEventListener;
564};
565
566} // namespace uniot
Defines the interface for components that can connect to an EventBus.
High-level network management controller with user interface.
Bytes & terminate()
Ensures the byte array is null-terminated.
Definition Bytes.h:281
const char * c_str() const
Gets the byte array as a C string.
Definition Bytes.h:306
Definition AppKit.h:84
bool setUserId(const String &userId)
Set the user identifier for device association.
Definition AppKit.h:151
MQTTKit & getMQTT()
Get the MQTT communication kit instance.
Definition AppKit.h:117
void setLispStopHook(LispStopHook hook)
Set the hook called when a Lisp script stops.
Definition AppKit.h:366
bool addCustomRoute(const String &path, WebRequestMethodComposite method, ArRequestHandlerFunction handler)
Register a custom HTTP route on the configuration portal.
Definition AppKit.h:184
bool setWiFiCredentials(const String &ssid, const String &password)
Set WiFi network credentials.
Definition AppKit.h:138
bool addCustomPage(const String &path, const uint8_t *gzData, size_t gzLen, const String &label="", const char *contentType="text/html")
Register a custom gzipped page on the configuration portal.
Definition AppKit.h:171
virtual void pushTo(TaskScheduler &scheduler) override
Add all managed tasks to the scheduler.
Definition AppKit.h:196
void setLispEventInterceptor(LispEventInterceptor interceptor)
Set event interceptor for Lisp interpreter.
Definition AppKit.h:350
void publishLispEvent(const String &eventID, int32_t value)
Publish an event to the Lisp interpreter.
Definition AppKit.h:379
virtual void registerWithBus(CoreEventBus &eventBus) override
Register all components with the event bus.
Definition AppKit.h:239
unLisp & getLisp()
Get the Lisp interpreter instance.
Definition AppKit.h:109
void configureNetworkController(uint8_t pinBtn=UINT8_MAX, uint8_t activeLevelBtn=LOW, uint8_t pinLed=UINT8_MAX, uint8_t activeLevelLed=HIGH, uint8_t maxRebootCount=5, uint32_t rebootWindowMs=10000, bool registerLispBtn=true)
Configure the NetworkController with individual parameters.
Definition AppKit.h:323
virtual void unregisterFromBus(CoreEventBus &eventBus) override
Unregister all components from the event bus.
Definition AppKit.h:270
void setLispStartHook(LispStartHook hook)
Set the hook called when a Lisp script starts.
Definition AppKit.h:358
const Credentials & getCredentials()
Get the device credentials.
Definition AppKit.h:125
virtual void attach() override
Initialize and attach all components.
Definition AppKit.h:218
void configureNetworkController(const NetworkControllerConfig &config)
Configure the NetworkController using a config structure.
Definition AppKit.h:299
Definition CBORObject.h:40
Manages device identity and cryptographic credentials for Uniot devices.
Definition Credentials.h:61
const String & getCreatorId() const
Gets the creator ID.
Definition Credentials.h:160
const String & getPublicKey() const
Gets the device's public key as a hexadecimal string.
Definition Credentials.h:178
static time_t now()
Returns the current Unix timestamp.
Definition Date.h:75
bool registerEntity(EventEntity< T_topic, T_msg, T_data > *entity)
Registers an entity (emitter or listener) with this EventBus.
Definition EventBus.cpp:44
void unregisterEntity(EventEntity< T_topic, T_msg, T_data > *entity)
Unregisters an entity from this EventBus.
Definition EventBus.cpp:53
bool closeDataChannel(T_topic topic)
Closes a previously opened data channel.
Definition EventBus.cpp:66
bool openDataChannel(T_topic topic, size_t limit)
Opens a data channel for a specific topic with a size limit.
Definition EventBus.cpp:61
Interface for connecting components to the TaskScheduler.
Definition ISchedulerConnectionKit.h:35
Definition MQTTKit.h:81
static RegisterManager & getRegisterManager()
Gets the static register manager instance.
Definition PrimitiveExpeditor.h:71
void serializeRegisters(CBORObject &obj)
Serializes all registers (GPIO and Object) to a CBOR object.
Definition RegisterManager.h:165
bool link(const String &name, RecordPtr link, uint32_t id=FOURCC(____))
Links an object to a named register.
Definition RegisterManager.h:111
Singleton(const Singleton &)=delete
static unLisp & getInstance()
Definition Singleton.h:73
Definition TaskScheduler.h:183
Definition unLisp.h:209
TaskScheduler::TaskPtr getCleanupTask()
Definition unLisp.h:221
void serializePrimitives(CBORObject &obj)
Serialize all registered primitive functions to CBOR format.
Definition unLisp.h:349
unLisp * pushPrimitive(Primitive *primitive)
Add a new primitive function to the Lisp environment.
Definition unLisp.h:329
Object aread(Root root, VarObject env, VarObject list)
Analog read primitive function for reading analog input.
Definition LispPrimitives.cpp:74
Object bclicked(Root root, VarObject env, VarObject list)
Button clicked primitive function for checking button click status.
Definition LispPrimitives.cpp:91
Object dwrite(Root root, VarObject env, VarObject list)
Definition LispPrimitives.cpp:23
Object awrite(Root root, VarObject env, VarObject list)
Analog write primitive function for setting PWM output.
Definition LispPrimitives.cpp:57
Object dread(Root root, VarObject env, VarObject list)
Digital read primitive function for reading pin input state.
Definition LispPrimitives.cpp:40
#define UNIOT_CORE_VERSION
Version of Uniot Core, reported in the device's status packet.
Definition Common.h:48
std::unique_ptr< T > UniquePointer
Type alias for std::unique_ptr with cleaner syntax.
Definition Common.h:305
#define UNIOT_WIFI_REBOOT_WINDOW_MS
How long after boot a reboot still counts towards the reset, in ms.
Definition Common.h:115
auto MakeUnique(Args &&...args) -> decltype(std::make_unique< T >(std::forward< Args >(args)...))
Creates a unique pointer instance, alias for std::make_unique.
Definition Common.h:332
#define FOURCC(name)
Creates a FourCC constant from a string literal.
Definition Common.h:260
#define UNIOT_MQTT_PORT
TCP port of the MQTT broker.
Definition Common.h:63
#define UNIOT_LISP_HEAP
Bytes of heap the Lisp interpreter is given at startup.
Definition Common.h:130
#define UNIOT_WIFI_REBOOT_RESET_COUNT
Consecutive reboots that reset the stored network configuration.
Definition Common.h:104
#define UNIOT_MQTT_HOST
Hostname of the MQTT broker the device connects to.
Definition Common.h:55
#define UNIOT_LISP_MAX_EVAL_STACK
Bytes of C stack an evaluation may spend before a script is abandoned.
Definition Common.h:158
IEventBusConnectionKit< unsigned int, int, Bytes > ICoreEventBusConnectionKit
A specific instance of IEventBusConnectionKit for core system events.
Definition IEventBusConnectionKit.h:87
EventBus< unsigned int, int, Bytes > CoreEventBus
Standard EventBus configuration used throughout the core system.
Definition EventBus.h:211
#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_DEBUG(...)
Log an DEBUG level message Used for general information about system operation. Only compiled if UNIO...
Definition Logger.h:340
TaskScheduler & push(const char *name, TaskPtr task)
Add a named task to the scheduler.
Definition TaskScheduler.h:233
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
constexpr const char * dread
Primitive for digital read operations.
Definition DefaultPrimitives.h:59
constexpr const char * aread
Primitive for analog read operations.
Definition DefaultPrimitives.h:73
constexpr const char * awrite
Primitive for analog write operations.
Definition DefaultPrimitives.h:66
constexpr const char * dwrite
Primitive for digital write operations.
Definition DefaultPrimitives.h:52
constexpr const char * bclicked
Primitive for detecting button click events.
Definition DefaultPrimitives.h:80
@ 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
@ CONNECTION
MQTT connection state changes and operations.
Definition MQTTEvents.h:61
@ SUCCESS
MQTT connection established successfully.
Definition MQTTEvents.h:73
@ FAILED
MQTT connection failed or was lost.
Definition MQTTEvents.h:72
@ DISCONNECTING
Currently disconnecting from network.
Definition NetworkEvents.h:88
@ SUCCESS
Network operation completed successfully.
Definition NetworkEvents.h:86
@ ACCESS_POINT
Device is operating in access point mode.
Definition NetworkEvents.h:90
@ AVAILABLE
Configured network is available for connection.
Definition NetworkEvents.h:91
@ DISCONNECTED
Network connection has been lost or terminated.
Definition NetworkEvents.h:89
@ FAILED
Network operation failed (connection, scan, etc.)
Definition NetworkEvents.h:85
@ CONNECTING
Currently attempting to connect to network.
Definition NetworkEvents.h:87
@ CONNECTION
WiFi connection state changes and operations.
Definition NetworkEvents.h:74
@ OUT_SSID
Channel for broadcasting current SSID information.
Definition NetworkEvents.h:63
Contains all classes and functions related to the Uniot Core.
std::function< bool(const LispEvent &event)> LispEventInterceptor
Definition LispDevice.h:41
Configuration parameters for NetworkController.
Definition AppKit.h:95
uint8_t pinBtn
Button pin (UINT8_MAX means not used)
Definition AppKit.h:96
bool registerLispBtn
Whether to register the button with the Lisp interpreter.
Definition AppKit.h:102
uint8_t activeLevelLed
Active level for LED (LOW or HIGH)
Definition AppKit.h:99
uint8_t maxRebootCount
Maximum number of consecutive reboots.
Definition AppKit.h:100
uint8_t activeLevelBtn
Active level for button (LOW or HIGH)
Definition AppKit.h:97
uint32_t rebootWindowMs
Time window in ms for counting reboots.
Definition AppKit.h:101
uint8_t pinLed
LED pin (UINT8_MAX means not used)
Definition AppKit.h:98