supla-device
Loading...
Searching...
No Matches
SuplaDevice.h
1/*
2 Copyright (C) AC SOFTWARE SP. Z O.O.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
12 You should have received a copy of the GNU General Public License
13 along with this program; if not, write to the Free Software
14 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
15*/
16
17#ifndef SRC_SUPLADEVICE_H_
18#define SRC_SUPLADEVICE_H_
19
20#include <supla-common/log.h>
21#include <supla-common/proto.h>
22#include <supla/action_handler.h>
23#include <supla/device/device_mode.h>
24#include <supla/local_action.h>
25#include <supla/suplet/config.h>
26#if SUPLA_SUPLET_ENABLED
27#include <supla/suplet/definition_cache.h>
28#include <supla/suplet/storage.h>
29#endif
30#include <supla/uptime.h>
31
32#include "supla/device/security_logger.h"
33
34#define STATUS_UNKNOWN -1
35#define STATUS_ALREADY_INITIALIZED 1
36#define STATUS_MISSING_NETWORK_INTERFACE 2
37#define STATUS_UNKNOWN_SERVER_ADDRESS 3
38#define STATUS_UNKNOWN_LOCATION_ID 4
39#define STATUS_INITIALIZED 5
40#define STATUS_SERVER_DISCONNECTED 6
41#define STATUS_ITERATE_FAIL 7
42#define STATUS_NETWORK_DISCONNECTED 8
43#define STATUS_ALL_PROTOCOLS_DISABLED 9
44
45#define STATUS_REGISTER_IN_PROGRESS 10 // Don't change
46#define STATUS_REGISTERED_AND_READY 17 // Don't change
47
48#define STATUS_TEMPORARILY_UNAVAILABLE 21
49#define STATUS_INVALID_GUID 22
50#define STATUS_CHANNEL_LIMIT_EXCEEDED 23
51#define STATUS_PROTOCOL_VERSION_ERROR 24
52#define STATUS_BAD_CREDENTIALS 25
53#define STATUS_LOCATION_CONFLICT 26
54#define STATUS_CHANNEL_CONFLICT 27
55#define STATUS_DEVICE_IS_DISABLED 28
56#define STATUS_LOCATION_IS_DISABLED 29
57#define STATUS_DEVICE_LIMIT_EXCEEDED 30
58#define STATUS_REGISTRATION_DISABLED 31
59#define STATUS_MISSING_CREDENTIALS 32
60#define STATUS_INVALID_AUTHKEY 33
61#define STATUS_NO_LOCATION_AVAILABLE 34
62#define STATUS_UNKNOWN_ERROR 35
63#define STATUS_COUNTRY_REJECTED 36
64
65#define STATUS_CONFIG_MODE 40
66#define STATUS_SOFTWARE_RESET 41
67#define STATUS_SW_DOWNLOAD 50
68#define STATUS_SUPLA_PROTOCOL_DISABLED 60
69#define STATUS_TEST_WAIT_FOR_CFG_BUTTON 70
70#define STATUS_OFFLINE_MODE 80
71#define STATUS_NOT_CONFIGURED_MODE 90
72
73typedef void (*_impl_arduino_status)(int status, const char *msg);
74
75#ifdef ARDUINO
76class __FlashStringHelper;
77#else
78#define __FlashStringHelper char
79#endif
80
81namespace Supla {
82class Clock;
83class Mutex;
84class Element;
85
86// 10 days
87constexpr uint32_t AutomaticOtaCheckInterval = (10ULL * 24 * 60 * 60 * 1000);
88
89enum class SwUpdateMode : uint8_t {
90 NotSet,
91 PeriodicCheckAndUpdate,
92 OnlyCheck,
93 CheckAndUpdate,
94 RetryCheckAndUpdate,
95};
96
100enum class InitialMode : uint8_t {
104 StartInCfgMode = 0,
109 StartOffline = 1,
113 StartWithCfgModeThenOffline = 2,
117 StartInNotConfiguredMode = 3
118};
119
120enum class CfgModeState : uint8_t {
121 NotSet = 0,
122 CfgModeStartedFor1hPending = 1,
123 CfgModeStartedPending = 2,
124 CfgModeOngoing = 3,
125 Done = 4,
126};
127
128struct ConfigurationState {
129 uint8_t wifiEnabled : 1;
130 uint8_t wifiSsidFilled : 1;
131 uint8_t wifiPassFilled : 1;
132 uint8_t protocolFilled : 1;
133 uint8_t protocolNotEmpty : 1;
134 uint8_t configNotComplete : 1;
135 uint8_t atLeastOneProtoIsEnabled : 1;
136
137 bool isEmpty() const;
138
139 ConfigurationState() {
140 wifiEnabled = 0;
141 wifiSsidFilled = 0;
142 wifiPassFilled = 0;
143 protocolFilled = 0;
144 protocolNotEmpty = 0;
145 configNotComplete = 0;
146 atLeastOneProtoIsEnabled = 0;
147 }
148};
149
150const char *getInitialModeName(const InitialMode mode);
151
152namespace Device {
153class SwUpdate;
154class ChannelConflictResolver;
155class ChannelConflictResolverList;
156class SubdevicePairingHandler;
157class StatusLed;
158class LastStateLogger;
159class SecurityLogger;
160} // namespace Device
161
162namespace Protocol {
163class SuplaSrpc;
164} // namespace Protocol
165
166namespace Suplet {
168class Manager;
169class Registry;
171enum class ServerConfigResult : uint8_t;
172} // namespace Suplet
173
174} // namespace Supla
175
176class SuplaDeviceClass : public Supla::ActionHandler,
177 public Supla::LocalAction {
178 public:
179 SuplaDeviceClass();
180 ~SuplaDeviceClass();
181
182 void fillStateData(TDSC_ChannelState *channelState) const;
183 void addClock(Supla::Clock *clock); // DEPRECATED
184 Supla::Clock *getClock() const;
185
186 bool begin(const char GUID[SUPLA_GUID_SIZE],
187 const char *Server,
188 const char *email,
189 const char authkey[SUPLA_AUTHKEY_SIZE],
190 unsigned char protoVersion = 23);
191
192 bool begin(unsigned char protoVersion = 23);
193
194 // Use ASCII only in name
195 void setName(const char *Name);
196
197 void setGUID(const char GUID[SUPLA_GUID_SIZE]);
198 void setAuthKey(const char authkey[SUPLA_AUTHKEY_SIZE]);
199 void setEmail(const char *email);
200 void setServer(const char *server);
201 void setSwVersion(const char *);
202
203 // Do not set the manufacturer ID to anything other than 0. Values other than
204 // 0 are reserved for official Supla products only
205 void setManufacturerId(int16_t);
206
207 // Do not set the product ID to anything other than 0. Values other than
208 // 0 are reserved for official Supla products only
209 void setProductId(int16_t);
210
211 void addFlags(int32_t);
212 void removeFlags(int32_t);
213 bool isSleepingDeviceEnabled() const;
214
215 int generateHostname(char *, int macSize = 6);
216
217 // Timer with 100 Hz frequency (10 ms)
218 void onTimer(void);
219 // Timer with 2000 Hz frequency (0.5 ms or 1 ms)
220 void onFastTimer(void);
221 void iterate(void);
222
223 void status(int status,
224 const __FlashStringHelper *msg,
225 bool alwaysLog = false);
226 void setStatusFuncImpl(_impl_arduino_status impl_arduino_status);
227 void setServerPort(int value);
228
229 int handleCalcfgFromServer(TSD_DeviceCalCfgRequest *request,
230 TDS_DeviceCalCfgResult *result = nullptr);
231
232 void enterConfigMode();
233 void leaveConfigModeWithoutRestart();
234 void enterNormalMode();
235 // Schedules timeout to restart device. When provided timeout is 0
236 // then restart will be done asap.
237 void scheduleSoftRestart(int timeout = 0);
238 void scheduleProtocolsRestart(int timeout = 0);
239 void softRestart();
240 void saveStateToStorage();
241 void restartCfgModeTimeout(bool requireRestart);
242 void resetToFactorySettings();
243 void disableLocalActionsIfNeeded();
244 void requestCfgMode();
245
246 int8_t getCurrentStatus() const;
247 bool loadDeviceConfig();
248 bool prepareLastStateLog();
249 char *getLastStateLog();
250 void addLastStateLog(const char *);
251 void enableLastStateLog();
252 void disableLastStateLog();
253 void setRsaPublicKeyPtr(const uint8_t *ptr);
254 const uint8_t *getRsaPublicKey() const;
255 enum Supla::DeviceMode getDeviceMode() const;
256
257 void setActivityTimeout(_supla_int_t newActivityTimeout);
258 uint32_t getActivityTimeout();
259
260 void handleAction(int event, int action) override;
261
270 void setAutomaticResetOnConnectionProblem(unsigned int timeSec);
271
272 void setLastStateLogger(Supla::Device::LastStateLogger *logger);
273
274 void setSuplaCACert(const char *);
275 void setSupla3rdPartyCACert(const char *);
276 const char *getSuplaCACert() const;
277
278 Supla::Uptime uptime;
279
280 Supla::Protocol::SuplaSrpc *getSrpcLayer();
281
282 void enableNetwork();
283 void disableNetwork();
284 bool getStorageInitResult();
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
424
431
438
443 void identifyStatusLed();
444
450 void testStepStatusLed(int times);
451
460 void addSecurityLog(uint32_t source, const char *log) const;
461
469 void addSecurityLog(Supla::SecurityLogSource source, const char *log) const;
470
477
483 bool isSecurityLogEnabled() const;
484
485 protected:
490 void iterateSwUpdate();
491
501 bool initSwUpdateInstance(Supla::SwUpdateMode mode, int securityOnly = -1);
502
503 void iterateAlwaysElements(uint32_t _millis);
504 bool iterateNetworkSetup();
505 bool iterateSuplaProtocol(uint32_t _millis);
506 void handleLocalActionTriggers();
507 void checkIfLeaveCfgModeOrRestartIsNeeded();
508 void createSrpcLayerIfNeeded();
509 bool loadSupletRuntime();
510 bool handleSupletRuntimeRefresh();
511 void rewriteStateStorageIfInvalidAfterTopologyChange();
512 void setupDeviceMode();
513
514 uint32_t networkIsNotReadyCounter = 0;
515 uint32_t deviceRestartTimeoutTimestamp = 0;
516 uint32_t protocolRestartTimeoutTimestamp = 0;
517 uint32_t waitForIterate = 0;
518 uint32_t lastIterateTime = 0;
519 uint32_t enterConfigModeTimestamp = 0;
520 uint32_t forceRestartTimeMs = 0;
521 uint32_t protocolRestartTimeMs = 0;
522 uint32_t resetOnConnectionFailTimeoutSec = 0;
523 uint32_t lastSwUpdateCheckTimestamp = 0;
524
525 enum Supla::DeviceMode deviceMode = Supla::DEVICE_MODE_NOT_SET;
526 bool triggerResetToFactorySettings = false;
527 bool triggerStartLocalWebServer = false;
528 bool triggerStopLocalWebServer = false;
529 bool triggerCheckSwUpdate = false;
530 bool requestNetworkLayerRestart = false;
531 bool isNetworkSetupOk = false;
532 bool skipNetwork = false;
533 bool storageInitResult = false;
534 bool showUptimeInChannelState = true;
535 bool lastStateLogEnabled = true;
536 // used to indicate if begin() method was called - it will be set to
537 // true even if initialization procedure failed for some reason
538 bool initializationDone = false;
539 bool goToConfigModeAsap = false;
540
541 uint8_t leaveCfgModeAfterInactivityMin = 5;
542 uint8_t macLengthInHostname = 6;
543 int8_t currentStatus = STATUS_UNKNOWN;
544 uint8_t swUpdateAttempts = 0;
545
546 Supla::InitialMode initialMode = Supla::InitialMode::StartInNotConfiguredMode;
547 Supla::CfgModeState cfgModeState = Supla::CfgModeState::NotSet;
548 Supla::ConfigurationState configurationState = {};
549
550 Supla::Protocol::SuplaSrpc *srpcLayer = nullptr;
551 Supla::Device::SwUpdate *swUpdate = nullptr;
552 Supla::Device::ChannelConflictResolverList *channelConflictResolvers =
553 nullptr;
554#if SUPLA_SUPLET_ENABLED
555 Supla::Suplet::Manager *supletManager = nullptr;
556#endif
557 Supla::Element *iterateConnectedPtr = nullptr;
558 Supla::Device::LastStateLogger *lastStateLogger = nullptr;
559 Supla::Mutex *timerAccessMutex = nullptr;
560 Supla::Device::SubdevicePairingHandler *subdevicePairingHandler = nullptr;
561 Supla::Device::StatusLed *statusLed = nullptr;
562 Supla::Device::SecurityLogger *securityLogger = nullptr;
563 const uint8_t *rsaPublicKey = nullptr;
564 char *customHostnamePrefix = nullptr;
565 _impl_arduino_status impl_arduino_status = nullptr;
566};
567
568extern SuplaDeviceClass SuplaDevice;
569#endif // SRC_SUPLADEVICE_H_
Definition security_logger.h:62
Definition SuplaDevice.h:177
void identifyStatusLed()
Triggers "identify" action on status LED.
Definition SuplaDevice.cpp:2085
void setShowUptimeInChannelState(bool value)
Sets if "uptime" should be added to channel state (i).
Definition SuplaDevice.cpp:1844
int getLogLevel()
Returns current global Supla log level.
Definition SuplaDevice.cpp:1852
void setCustomHostnamePrefix(const char *prefix)
Sets custom hostname prefix to be used in hostname and Wi-Fi Soft AP name.
Definition SuplaDevice.cpp:1745
void testStepStatusLed(int times)
Triggers special status LED flashing sequence based on provided "times".
Definition SuplaDevice.cpp:2092
void setInitialMode(Supla::InitialMode mode)
Sets the initial mode of the device.
Definition SuplaDevice.cpp:2123
void addSecurityLog(uint32_t source, const char *log) const
Adds security log.
Definition SuplaDevice.cpp:2106
void allowWorkInOfflineMode(int mode=1)
Allows device to work in offline mode DEPRECATED: use setInitialMode() instead.
Definition SuplaDevice.cpp:1813
void setProtoVerboseLog(bool value)
Enables/disables verbose logging of Supla protocol.
Definition SuplaDevice.cpp:1856
bool isSecurityLogEnabled() const
Checks if security log is enabled.
Definition SuplaDevice.cpp:2119
void setSecurityLogger(Supla::Device::SecurityLogger *logger)
Sets instance of Supla::Device::SecurityLogger.
Definition SuplaDevice.cpp:2098
void setMacLengthInHostname(int value)
Sets the byte length of MAC address in hostname and Wi-Fi Soft AP name.
Definition SuplaDevice.cpp:2046
void setAutomaticResetOnConnectionProblem(unsigned int timeSec)
Enables automatic software reset of device in case of network/server connection problems longer than ...
Definition SuplaDevice.cpp:1695
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:2170
void setLeaveCfgModeAfterInactivityMin(int valueMin)
Sets the leave configuration mode after inactivity timeout in minutes.
Definition SuplaDevice.cpp:2062
void iterateSwUpdate()
Performs software update if needed.
Definition SuplaDevice.cpp:713
void setLogLevel(int level)
Sets global Supla log level.
Definition SuplaDevice.cpp:1848
void setAutomaticFirmwareUpdateSupported(bool value)
Sets automatic firmware update support.
Definition SuplaDevice.cpp:2073
bool isRemoteDeviceConfigEnabled() const
Checks if remote device configuration is enabled.
Definition SuplaDevice.cpp:1832
bool isAutomaticFirmwareUpdateEnabled() const
Checks if automatic firmware update is supported.
Definition SuplaDevice.cpp:2069
bool initSwUpdateInstance(Supla::SwUpdateMode mode, int securityOnly=-1)
Initializes SW update instance.
Definition SuplaDevice.cpp:625
Definition action_handler.h:21
Definition clock.h:29
Definition channel_conflict_resolver.h:27
Definition last_state_logger.h:28
Definition security_logger.h:62
Definition status_led.h:58
Definition subdevice_pairing_handler.h:32
Base class for all elements of SuplaDevice.
Definition element.h:42
Definition local_action.h:52
Definition mutex.h:22
Definition supla_srpc.h:61
Definition capability_registry.h:28
Definition manager.h:44
Definition registry.h:28
Definition server_config.h:70
Definition uptime.h:24
Definition SuplaDevice.h:128
Definition proto.h:2981
Definition proto.h:2603
Definition proto.h:2593