supla-device
Loading...
Searching...
No Matches
SuplaDevice.h
1// SPDX-FileCopyrightText: AC SOFTWARE SP. Z O.O.
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#ifndef SRC_SUPLADEVICE_H_
5#define SRC_SUPLADEVICE_H_
6
7#include <supla-common/log.h>
8#include <supla-common/proto.h>
9#include <supla/action_handler.h>
10#include <supla/device/device_mode.h>
11#include <supla/local_action.h>
12#include <supla/suplet/config.h>
13#if SUPLA_SUPLET_ENABLED
14#include <supla/suplet/definition_cache.h>
15#include <supla/suplet/storage.h>
16#endif
17#include <supla/uptime.h>
18
19#include "supla/device/security_logger.h"
20
21#define STATUS_UNKNOWN -1
22#define STATUS_ALREADY_INITIALIZED 1
23#define STATUS_MISSING_NETWORK_INTERFACE 2
24#define STATUS_UNKNOWN_SERVER_ADDRESS 3
25#define STATUS_UNKNOWN_LOCATION_ID 4
26#define STATUS_INITIALIZED 5
27#define STATUS_SERVER_DISCONNECTED 6
28#define STATUS_ITERATE_FAIL 7
29#define STATUS_NETWORK_DISCONNECTED 8
30#define STATUS_ALL_PROTOCOLS_DISABLED 9
31
32#define STATUS_REGISTER_IN_PROGRESS 10 // Don't change
33#define STATUS_REGISTERED_AND_READY 17 // Don't change
34
35#define STATUS_TEMPORARILY_UNAVAILABLE 21
36#define STATUS_INVALID_GUID 22
37#define STATUS_CHANNEL_LIMIT_EXCEEDED 23
38#define STATUS_PROTOCOL_VERSION_ERROR 24
39#define STATUS_BAD_CREDENTIALS 25
40#define STATUS_LOCATION_CONFLICT 26
41#define STATUS_CHANNEL_CONFLICT 27
42#define STATUS_DEVICE_IS_DISABLED 28
43#define STATUS_LOCATION_IS_DISABLED 29
44#define STATUS_DEVICE_LIMIT_EXCEEDED 30
45#define STATUS_REGISTRATION_DISABLED 31
46#define STATUS_MISSING_CREDENTIALS 32
47#define STATUS_INVALID_AUTHKEY 33
48#define STATUS_NO_LOCATION_AVAILABLE 34
49#define STATUS_UNKNOWN_ERROR 35
50#define STATUS_COUNTRY_REJECTED 36
51
52#define STATUS_CONFIG_MODE 40
53#define STATUS_SOFTWARE_RESET 41
54#define STATUS_SW_DOWNLOAD 50
55#define STATUS_SUPLA_PROTOCOL_DISABLED 60
56#define STATUS_TEST_WAIT_FOR_CFG_BUTTON 70
57#define STATUS_OFFLINE_MODE 80
58#define STATUS_NOT_CONFIGURED_MODE 90
59
60typedef void (*_impl_arduino_status)(int status, const char *msg);
61
62#ifdef ARDUINO
63class __FlashStringHelper;
64#else
65#define __FlashStringHelper char
66#endif
67
68namespace Supla {
69class Clock;
70class Mutex;
71class Element;
72namespace Device {
73class SwUpdateObserver;
74}
75
76// 10 days
77constexpr uint32_t AutomaticOtaCheckInterval = (10ULL * 24 * 60 * 60 * 1000);
78
79enum class SwUpdateMode : uint8_t {
80 NotSet,
81 PeriodicCheckAndUpdate,
82 OnlyCheck,
83 CheckAndUpdate,
84 RetryCheckAndUpdate,
85};
86
90enum class InitialMode : uint8_t {
94 StartInCfgMode = 0,
99 StartOffline = 1,
103 StartWithCfgModeThenOffline = 2,
107 StartInNotConfiguredMode = 3
108};
109
110enum class CfgModeState : uint8_t {
111 NotSet = 0,
112 CfgModeStartedFor1hPending = 1,
113 CfgModeStartedPending = 2,
114 CfgModeOngoing = 3,
115 Done = 4,
116};
117
119 uint8_t wifiEnabled : 1;
120 uint8_t wifiSsidFilled : 1;
121 uint8_t wifiPassFilled : 1;
122 uint8_t protocolFilled : 1;
123 uint8_t protocolNotEmpty : 1;
124 uint8_t configNotComplete : 1;
125 uint8_t atLeastOneProtoIsEnabled : 1;
126
127 bool isEmpty() const;
128
130 wifiEnabled = 0;
131 wifiSsidFilled = 0;
132 wifiPassFilled = 0;
133 protocolFilled = 0;
134 protocolNotEmpty = 0;
135 configNotComplete = 0;
136 atLeastOneProtoIsEnabled = 0;
137 }
138};
139
140const char *getInitialModeName(const InitialMode mode);
141
142namespace Device {
143class SwUpdate;
144class ChannelConflictResolver;
145class ChannelConflictResolverList;
146class SubdevicePairingHandler;
147class StatusLed;
148class LastStateLogger;
149class SecurityLogger;
150} // namespace Device
151
152namespace Protocol {
153class SuplaSrpc;
154} // namespace Protocol
155
156namespace Suplet {
157class CapabilityRegistry;
158class Manager;
159class Registry;
160class ServerConfigHandler;
161enum class ServerConfigResult : uint8_t;
162} // namespace Suplet
163
164} // namespace Supla
165
167 public Supla::LocalAction {
168 public:
171
172 void fillStateData(TDSC_ChannelState *channelState) const;
173 void addClock(Supla::Clock *clock); // DEPRECATED
174 Supla::Clock *getClock() const;
175
176 bool begin(const char GUID[SUPLA_GUID_SIZE],
177 const char *Server,
178 const char *email,
179 const char authkey[SUPLA_AUTHKEY_SIZE],
180 unsigned char protoVersion = 23);
181
182 bool begin(unsigned char protoVersion = 23);
183
184 // Use ASCII only in name
185 void setName(const char *Name);
186
187 void setGUID(const char GUID[SUPLA_GUID_SIZE]);
188 void setAuthKey(const char authkey[SUPLA_AUTHKEY_SIZE]);
189 void setEmail(const char *email);
190 void setServer(const char *server);
191 void setSwVersion(const char *);
192
193 // Do not set the manufacturer ID to anything other than 0. Values other than
194 // 0 are reserved for official Supla products only
195 void setManufacturerId(int16_t);
196
197 // Do not set the product ID to anything other than 0. Values other than
198 // 0 are reserved for official Supla products only
199 void setProductId(int16_t);
200
201 void addFlags(int32_t);
202 void removeFlags(int32_t);
203 bool isSleepingDeviceEnabled() const;
204
205 int generateHostname(char *, int macSize = 6);
206
207 // Timer with 100 Hz frequency (10 ms)
208 void onTimer(void);
209 // Timer with 2000 Hz frequency (0.5 ms or 1 ms)
210 void onFastTimer(void);
211 void iterate(void);
212
213 void status(int status,
214 const __FlashStringHelper *msg,
215 bool alwaysLog = false);
216 void setStatusFuncImpl(_impl_arduino_status impl_arduino_status);
217 void setServerPort(int value);
218
219 int handleCalcfgFromServer(TSD_DeviceCalCfgRequest *request,
220 TDS_DeviceCalCfgResult *result = nullptr);
221
222 void enterConfigMode();
223 void leaveConfigModeWithoutRestart();
224 void enterNormalMode();
225 // Schedules timeout to restart device. When provided timeout is 0
226 // then restart will be done asap.
227 void scheduleSoftRestart(int timeout = 0);
228 void scheduleProtocolsRestart(int timeout = 0);
229 void softRestart();
230 // Shared reset/stop preparation; the caller selects the platform action.
231 bool prepareForShutdown();
232 void saveStateToStorage();
233 void restartCfgModeTimeout(bool requireRestart);
234 void resetToFactorySettings();
235 void disableLocalActionsIfNeeded();
236 void restoreLocalActionsAfterConfigMode();
237 void requestCfgMode();
238
239 int8_t getCurrentStatus() const;
240 bool getSelfTestFailed() const;
241 int getSelfTestFailureReason() const;
242 bool loadDeviceConfig();
243 bool prepareLastStateLog();
244 char *getLastStateLog();
245 void addLastStateLog(const char *);
246 void enableLastStateLog();
247 void disableLastStateLog();
248 void setRsaPublicKeyPtr(const uint8_t *ptr);
249 const uint8_t *getRsaPublicKey() const;
250 enum Supla::DeviceMode getDeviceMode() const;
251
252 void setActivityTimeout(_supla_int_t newActivityTimeout);
253 uint32_t getActivityTimeout();
254
255 void handleAction(int event, int action) override;
256
265 void setAutomaticResetOnConnectionProblem(unsigned int timeSec);
266
267 void setLastStateLogger(Supla::Device::LastStateLogger *logger);
268
269 void setSuplaCACert(const char *);
270 void setSupla3rdPartyCACert(const char *);
271 const char *getSuplaCACert() const;
272
273 Supla::Uptime uptime;
274
275 Supla::Protocol::SuplaSrpc *getSrpcLayer();
276
277 void enableNetwork();
278 void disableNetwork();
279 bool getStorageInitResult();
286 void deferSleep(uint32_t delayMs);
287 bool isSleepingAllowed();
288
300 void allowWorkInOfflineMode(int mode = 1);
301
309 void setInitialMode(Supla::InitialMode mode);
310
317 Supla::InitialMode getInitialMode() const {
318 return initialMode;
319 }
320
326 bool isRemoteDeviceConfigEnabled() const;
327
333 void setShowUptimeInChannelState(bool value);
334
343 void setLogLevel(int level);
344
350 int getLogLevel();
351
360 void setProtoVerboseLog(bool value);
361
362 Supla::Mutex *getTimerAccessMutex();
363
364 void setChannelConflictResolver(
366 bool addChannelConflictResolver(
368 bool removeChannelConflictResolver(
370 void setSupletRuntime(Supla::Suplet::Manager *manager,
371 Supla::Suplet::Registry *registry);
372 void setSupletCapabilityRegistry(Supla::Suplet::CapabilityRegistry *registry);
373 void setSupletServerConfigHandler(
375 Supla::Suplet::ServerConfigResult applySupletCommandJson(
376 const char *commandJson);
377 Supla::Suplet::ServerConfigResult validateSupletCommandJson(
378 const char *commandJson) const;
379 void setSubdevicePairingHandler(
381
390 void setMacLengthInHostname(int value);
391
404 void setCustomHostnamePrefix(const char *prefix);
405
406 void setStatusLed(Supla::Device::StatusLed *led);
407
415 void setLeaveCfgModeAfterInactivityMin(int valueMin);
416 uint32_t getCfgModeInactivityTimeLeftMs() const;
417 void setSwUpdateObserver(Supla::Device::SwUpdateObserver *observer);
418
428
435
442
447 void identifyStatusLed();
448
454 void testStepStatusLed(int times);
455
464 void addSecurityLog(uint32_t source, const char *log) const;
465
473 void addSecurityLog(Supla::SecurityLogSource source, const char *log) const;
474
481
487 bool isSecurityLogEnabled() const;
488
489 protected:
494 void iterateSwUpdate();
495
505 bool initSwUpdateInstance(Supla::SwUpdateMode mode, int securityOnly = -1);
506
507 void iterateAlwaysElements(uint32_t _millis);
508 bool iterateNetworkSetup();
509 bool iterateSuplaProtocol(uint32_t _millis);
510 void handleLocalActionTriggers();
511 void checkIfLeaveCfgModeOrRestartIsNeeded();
512 void createSrpcLayerIfNeeded();
513 bool loadSupletRuntime();
514 bool handleSupletRuntimeRefresh();
515 void rewriteStateStorageIfInvalidAfterTopologyChange();
516 void setupDeviceMode();
517
518 uint32_t networkIsNotReadyCounter = 0;
519 uint32_t deviceRestartTimeoutTimestamp = 0;
520 uint32_t protocolRestartTimeoutTimestamp = 0;
521 uint32_t waitForIterate = 0;
522 uint32_t lastIterateTime = 0;
523 uint32_t enterConfigModeTimestamp = 0;
524 uint32_t forceRestartTimeMs = 0;
525 uint32_t protocolRestartTimeMs = 0;
526 uint32_t resetOnConnectionFailTimeoutSec = 0;
527 uint32_t lastSwUpdateCheckTimestamp = 0;
528 uint32_t sleepDeferStartMs = 0;
529 uint32_t sleepDeferDurationMs = 0;
530
531 enum Supla::DeviceMode deviceMode = Supla::DEVICE_MODE_NOT_SET;
532 bool triggerResetToFactorySettings = false;
533 bool triggerStartLocalWebServer = false;
534 bool triggerStopLocalWebServer = false;
535 bool triggerCheckSwUpdate = false;
536 bool requestNetworkLayerRestart = false;
537 bool isNetworkSetupOk = false;
538 bool skipNetwork = false;
539 bool storageInitResult = false;
540 bool showUptimeInChannelState = true;
541 bool lastStateLogEnabled = true;
542 // used to indicate if begin() method was called - it will be set to
543 // true even if initialization procedure failed for some reason
544 bool initializationDone = false;
545 bool goToConfigModeAsap = false;
546 bool selfTestFailed = false;
547 int selfTestFailureReason = 0;
548
549 uint8_t leaveCfgModeAfterInactivityMin = 5;
550 uint8_t macLengthInHostname = 6;
551 int8_t currentStatus = STATUS_UNKNOWN;
552 uint8_t swUpdateAttempts = 0;
553
554 Supla::InitialMode initialMode = Supla::InitialMode::StartInNotConfiguredMode;
555 Supla::CfgModeState cfgModeState = Supla::CfgModeState::NotSet;
556 Supla::ConfigurationState configurationState = {};
557
558 Supla::Protocol::SuplaSrpc *srpcLayer = nullptr;
559 Supla::Device::SwUpdate *swUpdate = nullptr;
560 Supla::Device::SwUpdateObserver *swUpdateObserver = nullptr;
561 Supla::Device::ChannelConflictResolverList *channelConflictResolvers =
562 nullptr;
563#if SUPLA_SUPLET_ENABLED
564 Supla::Suplet::Manager *supletManager = nullptr;
565#endif
566 Supla::Element *iterateConnectedPtr = nullptr;
567 Supla::Device::LastStateLogger *lastStateLogger = nullptr;
568 Supla::Mutex *timerAccessMutex = nullptr;
569 Supla::Device::SubdevicePairingHandler *subdevicePairingHandler = nullptr;
570 Supla::Device::StatusLed *statusLed = nullptr;
571 Supla::Device::SecurityLogger *securityLogger = nullptr;
572 const uint8_t *rsaPublicKey = nullptr;
573 char *customHostnamePrefix = nullptr;
574 _impl_arduino_status impl_arduino_status = nullptr;
575};
576
577extern SuplaDeviceClass SuplaDevice;
578#endif // SRC_SUPLADEVICE_H_
Definition SuplaDevice.h:167
void identifyStatusLed()
Triggers "identify" action on status LED.
Definition SuplaDevice.cpp:2167
void setShowUptimeInChannelState(bool value)
Sets if "uptime" should be added to channel state (i)
Definition SuplaDevice.cpp:1902
int getLogLevel()
Returns current global Supla log level.
Definition SuplaDevice.cpp:1910
void setCustomHostnamePrefix(const char *prefix)
Sets custom hostname prefix to be used in hostname and Wi-Fi Soft AP name.
Definition SuplaDevice.cpp:1750
void testStepStatusLed(int times)
Triggers special status LED flashing sequence based on provided "times".
Definition SuplaDevice.cpp:2175
void setInitialMode(Supla::InitialMode mode)
Sets the initial mode of the device.
Definition SuplaDevice.cpp:2206
void addSecurityLog(uint32_t source, const char *log) const
Adds security log.
Definition SuplaDevice.cpp:2189
void allowWorkInOfflineMode(int mode=1)
Allows device to work in offline mode DEPRECATED: use setInitialMode() instead.
Definition SuplaDevice.cpp:1871
void deferSleep(uint32_t delayMs)
Defers permission to enter sleep mode for the given number of milliseconds.
Definition SuplaDevice.cpp:1851
void setProtoVerboseLog(bool value)
Enables/disables verbose logging of Supla protocol.
Definition SuplaDevice.cpp:1914
bool isSecurityLogEnabled() const
Checks if security log is enabled.
Definition SuplaDevice.cpp:2202
void setSecurityLogger(Supla::Device::SecurityLogger *logger)
Sets instance of Supla::Device::SecurityLogger.
Definition SuplaDevice.cpp:2181
void setMacLengthInHostname(int value)
Sets the byte length of MAC address in hostname and Wi-Fi Soft AP name.
Definition SuplaDevice.cpp:2104
void setAutomaticResetOnConnectionProblem(unsigned int timeSec)
Enables automatic software reset of device in case of network/server connection problems longer than ...
Definition SuplaDevice.cpp:1700
Supla::InitialMode getInitialMode() const
Returns the initial mode of the device @See Supla::InitialMode.
Definition SuplaDevice.h:317
bool isLeaveCfgModeAfterInactivityEnabled() const
Checks if leave configuration mode after inactivity is enabled.
Definition SuplaDevice.cpp:2253
void setLeaveCfgModeAfterInactivityMin(int valueMin)
Sets the leave configuration mode after inactivity timeout in minutes.
Definition SuplaDevice.cpp:2120
void iterateSwUpdate()
Performs software update if needed.
Definition SuplaDevice.cpp:710
void setLogLevel(int level)
Sets global Supla log level.
Definition SuplaDevice.cpp:1906
void setAutomaticFirmwareUpdateSupported(bool value)
Sets automatic firmware update support.
Definition SuplaDevice.cpp:2155
bool isRemoteDeviceConfigEnabled() const
Checks if remote device configuration is enabled.
Definition SuplaDevice.cpp:1890
bool isAutomaticFirmwareUpdateEnabled() const
Checks if automatic firmware update is supported.
Definition SuplaDevice.cpp:2151
bool initSwUpdateInstance(Supla::SwUpdateMode mode, int securityOnly=-1)
Initializes SW update instance.
Definition SuplaDevice.cpp:621
Definition action_handler.h:8
Definition clock.h:16
Definition channel_conflict_resolver.h:48
Definition channel_conflict_resolver.h:18
Definition last_state_logger.h:15
Definition security_logger.h:47
Definition status_led.h:43
Definition subdevice_pairing_handler.h:26
Definition sw_update.h:20
Definition sw_update.h:32
Base class for all elements of SuplaDevice.
Definition element.h:30
Definition local_action.h:87
Definition mutex.h:9
Definition supla_srpc.h:47
Definition capability_registry.h:13
Definition manager.h:28
Definition registry.h:13
Definition server_config.h:57
Definition uptime.h:11
Definition SuplaDevice.h:118
Definition proto.h:2721
Definition proto.h:2340
Definition proto.h:2330