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 void saveStateToStorage();
231 void restartCfgModeTimeout(bool requireRestart);
232 void resetToFactorySettings();
233 void disableLocalActionsIfNeeded();
234 void restoreLocalActionsAfterConfigMode();
235 void requestCfgMode();
236
237 int8_t getCurrentStatus() const;
238 bool getSelfTestFailed() const;
239 int getSelfTestFailureReason() const;
240 bool loadDeviceConfig();
241 bool prepareLastStateLog();
242 char *getLastStateLog();
243 void addLastStateLog(const char *);
244 void enableLastStateLog();
245 void disableLastStateLog();
246 void setRsaPublicKeyPtr(const uint8_t *ptr);
247 const uint8_t *getRsaPublicKey() const;
248 enum Supla::DeviceMode getDeviceMode() const;
249
250 void setActivityTimeout(_supla_int_t newActivityTimeout);
251 uint32_t getActivityTimeout();
252
253 void handleAction(int event, int action) override;
254
263 void setAutomaticResetOnConnectionProblem(unsigned int timeSec);
264
265 void setLastStateLogger(Supla::Device::LastStateLogger *logger);
266
267 void setSuplaCACert(const char *);
268 void setSupla3rdPartyCACert(const char *);
269 const char *getSuplaCACert() const;
270
271 Supla::Uptime uptime;
272
273 Supla::Protocol::SuplaSrpc *getSrpcLayer();
274
275 void enableNetwork();
276 void disableNetwork();
277 bool getStorageInitResult();
284 void deferSleep(uint32_t delayMs);
285 bool isSleepingAllowed();
286
298 void allowWorkInOfflineMode(int mode = 1);
299
307 void setInitialMode(Supla::InitialMode mode);
308
315 Supla::InitialMode getInitialMode() const {
316 return initialMode;
317 }
318
324 bool isRemoteDeviceConfigEnabled() const;
325
331 void setShowUptimeInChannelState(bool value);
332
341 void setLogLevel(int level);
342
348 int getLogLevel();
349
358 void setProtoVerboseLog(bool value);
359
360 Supla::Mutex *getTimerAccessMutex();
361
362 void setChannelConflictResolver(
364 bool addChannelConflictResolver(
366 bool removeChannelConflictResolver(
368 void setSupletRuntime(Supla::Suplet::Manager *manager,
369 Supla::Suplet::Registry *registry);
370 void setSupletCapabilityRegistry(Supla::Suplet::CapabilityRegistry *registry);
371 void setSupletServerConfigHandler(
373 Supla::Suplet::ServerConfigResult applySupletCommandJson(
374 const char *commandJson);
375 Supla::Suplet::ServerConfigResult validateSupletCommandJson(
376 const char *commandJson) const;
377 void setSubdevicePairingHandler(
379
388 void setMacLengthInHostname(int value);
389
402 void setCustomHostnamePrefix(const char *prefix);
403
404 void setStatusLed(Supla::Device::StatusLed *led);
405
413 void setLeaveCfgModeAfterInactivityMin(int valueMin);
414 uint32_t getCfgModeInactivityTimeLeftMs() const;
415 void setSwUpdateObserver(Supla::Device::SwUpdateObserver *observer);
416
426
433
440
445 void identifyStatusLed();
446
452 void testStepStatusLed(int times);
453
462 void addSecurityLog(uint32_t source, const char *log) const;
463
471 void addSecurityLog(Supla::SecurityLogSource source, const char *log) const;
472
479
485 bool isSecurityLogEnabled() const;
486
487 protected:
492 void iterateSwUpdate();
493
503 bool initSwUpdateInstance(Supla::SwUpdateMode mode, int securityOnly = -1);
504
505 void iterateAlwaysElements(uint32_t _millis);
506 bool iterateNetworkSetup();
507 bool iterateSuplaProtocol(uint32_t _millis);
508 void handleLocalActionTriggers();
509 void checkIfLeaveCfgModeOrRestartIsNeeded();
510 void createSrpcLayerIfNeeded();
511 bool loadSupletRuntime();
512 bool handleSupletRuntimeRefresh();
513 void rewriteStateStorageIfInvalidAfterTopologyChange();
514 void setupDeviceMode();
515
516 uint32_t networkIsNotReadyCounter = 0;
517 uint32_t deviceRestartTimeoutTimestamp = 0;
518 uint32_t protocolRestartTimeoutTimestamp = 0;
519 uint32_t waitForIterate = 0;
520 uint32_t lastIterateTime = 0;
521 uint32_t enterConfigModeTimestamp = 0;
522 uint32_t forceRestartTimeMs = 0;
523 uint32_t protocolRestartTimeMs = 0;
524 uint32_t resetOnConnectionFailTimeoutSec = 0;
525 uint32_t lastSwUpdateCheckTimestamp = 0;
526 uint32_t sleepDeferStartMs = 0;
527 uint32_t sleepDeferDurationMs = 0;
528
529 enum Supla::DeviceMode deviceMode = Supla::DEVICE_MODE_NOT_SET;
530 bool triggerResetToFactorySettings = false;
531 bool triggerStartLocalWebServer = false;
532 bool triggerStopLocalWebServer = false;
533 bool triggerCheckSwUpdate = false;
534 bool requestNetworkLayerRestart = false;
535 bool isNetworkSetupOk = false;
536 bool skipNetwork = false;
537 bool storageInitResult = false;
538 bool showUptimeInChannelState = true;
539 bool lastStateLogEnabled = true;
540 // used to indicate if begin() method was called - it will be set to
541 // true even if initialization procedure failed for some reason
542 bool initializationDone = false;
543 bool goToConfigModeAsap = false;
544 bool selfTestFailed = false;
545 int selfTestFailureReason = 0;
546
547 uint8_t leaveCfgModeAfterInactivityMin = 5;
548 uint8_t macLengthInHostname = 6;
549 int8_t currentStatus = STATUS_UNKNOWN;
550 uint8_t swUpdateAttempts = 0;
551
552 Supla::InitialMode initialMode = Supla::InitialMode::StartInNotConfiguredMode;
553 Supla::CfgModeState cfgModeState = Supla::CfgModeState::NotSet;
554 Supla::ConfigurationState configurationState = {};
555
556 Supla::Protocol::SuplaSrpc *srpcLayer = nullptr;
557 Supla::Device::SwUpdate *swUpdate = nullptr;
558 Supla::Device::SwUpdateObserver *swUpdateObserver = nullptr;
559 Supla::Device::ChannelConflictResolverList *channelConflictResolvers =
560 nullptr;
561#if SUPLA_SUPLET_ENABLED
562 Supla::Suplet::Manager *supletManager = nullptr;
563#endif
564 Supla::Element *iterateConnectedPtr = nullptr;
565 Supla::Device::LastStateLogger *lastStateLogger = nullptr;
566 Supla::Mutex *timerAccessMutex = nullptr;
567 Supla::Device::SubdevicePairingHandler *subdevicePairingHandler = nullptr;
568 Supla::Device::StatusLed *statusLed = nullptr;
569 Supla::Device::SecurityLogger *securityLogger = nullptr;
570 const uint8_t *rsaPublicKey = nullptr;
571 char *customHostnamePrefix = nullptr;
572 _impl_arduino_status impl_arduino_status = nullptr;
573};
574
575extern SuplaDeviceClass SuplaDevice;
576#endif // SRC_SUPLADEVICE_H_
Definition SuplaDevice.h:167
void identifyStatusLed()
Triggers "identify" action on status LED.
Definition SuplaDevice.cpp:2169
void setShowUptimeInChannelState(bool value)
Sets if "uptime" should be added to channel state (i)
Definition SuplaDevice.cpp:1904
int getLogLevel()
Returns current global Supla log level.
Definition SuplaDevice.cpp:1912
void setCustomHostnamePrefix(const char *prefix)
Sets custom hostname prefix to be used in hostname and Wi-Fi Soft AP name.
Definition SuplaDevice.cpp:1752
void testStepStatusLed(int times)
Triggers special status LED flashing sequence based on provided "times".
Definition SuplaDevice.cpp:2177
void setInitialMode(Supla::InitialMode mode)
Sets the initial mode of the device.
Definition SuplaDevice.cpp:2208
void addSecurityLog(uint32_t source, const char *log) const
Adds security log.
Definition SuplaDevice.cpp:2191
void allowWorkInOfflineMode(int mode=1)
Allows device to work in offline mode DEPRECATED: use setInitialMode() instead.
Definition SuplaDevice.cpp:1873
void deferSleep(uint32_t delayMs)
Defers permission to enter sleep mode for the given number of milliseconds.
Definition SuplaDevice.cpp:1853
void setProtoVerboseLog(bool value)
Enables/disables verbose logging of Supla protocol.
Definition SuplaDevice.cpp:1916
bool isSecurityLogEnabled() const
Checks if security log is enabled.
Definition SuplaDevice.cpp:2204
void setSecurityLogger(Supla::Device::SecurityLogger *logger)
Sets instance of Supla::Device::SecurityLogger.
Definition SuplaDevice.cpp:2183
void setMacLengthInHostname(int value)
Sets the byte length of MAC address in hostname and Wi-Fi Soft AP name.
Definition SuplaDevice.cpp:2106
void setAutomaticResetOnConnectionProblem(unsigned int timeSec)
Enables automatic software reset of device in case of network/server connection problems longer than ...
Definition SuplaDevice.cpp:1702
Supla::InitialMode getInitialMode() const
Returns the initial mode of the device @See Supla::InitialMode.
Definition SuplaDevice.h:315
bool isLeaveCfgModeAfterInactivityEnabled() const
Checks if leave configuration mode after inactivity is enabled.
Definition SuplaDevice.cpp:2255
void setLeaveCfgModeAfterInactivityMin(int valueMin)
Sets the leave configuration mode after inactivity timeout in minutes.
Definition SuplaDevice.cpp:2122
void iterateSwUpdate()
Performs software update if needed.
Definition SuplaDevice.cpp:710
void setLogLevel(int level)
Sets global Supla log level.
Definition SuplaDevice.cpp:1908
void setAutomaticFirmwareUpdateSupported(bool value)
Sets automatic firmware update support.
Definition SuplaDevice.cpp:2157
bool isRemoteDeviceConfigEnabled() const
Checks if remote device configuration is enabled.
Definition SuplaDevice.cpp:1892
bool isAutomaticFirmwareUpdateEnabled() const
Checks if automatic firmware update is supported.
Definition SuplaDevice.cpp:2153
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:27
Definition local_action.h:42
Definition mutex.h:9
Definition supla_srpc.h:47
Definition capability_registry.h:13
Definition manager.h:29
Definition registry.h:13
Definition server_config.h:55
Definition uptime.h:11
Definition SuplaDevice.h:118
Definition proto.h:2705
Definition proto.h:2325
Definition proto.h:2315