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/uptime.h>
26
27#include "supla/device/security_logger.h"
28
29#define STATUS_UNKNOWN -1
30#define STATUS_ALREADY_INITIALIZED 1
31#define STATUS_MISSING_NETWORK_INTERFACE 2
32#define STATUS_UNKNOWN_SERVER_ADDRESS 3
33#define STATUS_UNKNOWN_LOCATION_ID 4
34#define STATUS_INITIALIZED 5
35#define STATUS_SERVER_DISCONNECTED 6
36#define STATUS_ITERATE_FAIL 7
37#define STATUS_NETWORK_DISCONNECTED 8
38#define STATUS_ALL_PROTOCOLS_DISABLED 9
39
40#define STATUS_REGISTER_IN_PROGRESS 10 // Don't change
41#define STATUS_REGISTERED_AND_READY 17 // Don't change
42
43#define STATUS_TEMPORARILY_UNAVAILABLE 21
44#define STATUS_INVALID_GUID 22
45#define STATUS_CHANNEL_LIMIT_EXCEEDED 23
46#define STATUS_PROTOCOL_VERSION_ERROR 24
47#define STATUS_BAD_CREDENTIALS 25
48#define STATUS_LOCATION_CONFLICT 26
49#define STATUS_CHANNEL_CONFLICT 27
50#define STATUS_DEVICE_IS_DISABLED 28
51#define STATUS_LOCATION_IS_DISABLED 29
52#define STATUS_DEVICE_LIMIT_EXCEEDED 30
53#define STATUS_REGISTRATION_DISABLED 31
54#define STATUS_MISSING_CREDENTIALS 32
55#define STATUS_INVALID_AUTHKEY 33
56#define STATUS_NO_LOCATION_AVAILABLE 34
57#define STATUS_UNKNOWN_ERROR 35
58#define STATUS_COUNTRY_REJECTED 36
59
60#define STATUS_CONFIG_MODE 40
61#define STATUS_SOFTWARE_RESET 41
62#define STATUS_SW_DOWNLOAD 50
63#define STATUS_SUPLA_PROTOCOL_DISABLED 60
64#define STATUS_TEST_WAIT_FOR_CFG_BUTTON 70
65#define STATUS_OFFLINE_MODE 80
66#define STATUS_NOT_CONFIGURED_MODE 90
67
68typedef void (*_impl_arduino_status)(int status, const char *msg);
69
70#ifdef ARDUINO
71class __FlashStringHelper;
72#else
73#define __FlashStringHelper char
74#endif
75
76namespace Supla {
77class Clock;
78class Mutex;
79class Element;
80
81// 10 days
82constexpr uint32_t AutomaticOtaCheckInterval = (10ULL * 24 * 60 * 60 * 1000);
83
84enum class SwUpdateMode : uint8_t {
85 NotSet,
86 PeriodicCheckAndUpdate,
87 OnlyCheck,
88 CheckAndUpdate,
89 RetryCheckAndUpdate,
90};
91
95enum class InitialMode : uint8_t {
99 StartInCfgMode = 0,
104 StartOffline = 1,
108 StartWithCfgModeThenOffline = 2,
112 StartInNotConfiguredMode = 3
113};
114
115enum class CfgModeState : uint8_t {
116 NotSet = 0,
117 CfgModeStartedFor1hPending = 1,
118 CfgModeStartedPending = 2,
119 CfgModeOngoing = 3,
120 Done = 4,
121};
122
123struct ConfigurationState {
124 uint8_t wifiEnabled : 1;
125 uint8_t wifiSsidFilled : 1;
126 uint8_t wifiPassFilled : 1;
127 uint8_t protocolFilled : 1;
128 uint8_t protocolNotEmpty : 1;
129 uint8_t configNotComplete : 1;
130 uint8_t atLeastOneProtoIsEnabled : 1;
131
132 bool isEmpty() const;
133
134 ConfigurationState() {
135 wifiEnabled = 0;
136 wifiSsidFilled = 0;
137 wifiPassFilled = 0;
138 protocolFilled = 0;
139 protocolNotEmpty = 0;
140 configNotComplete = 0;
141 atLeastOneProtoIsEnabled = 0;
142 }
143};
144
145const char *getInitialModeName(const InitialMode mode);
146
147namespace Device {
148class SwUpdate;
149class ChannelConflictResolver;
150class SubdevicePairingHandler;
151class StatusLed;
152class LastStateLogger;
153class SecurityLogger;
154} // namespace Device
155
156namespace Protocol {
157class SuplaSrpc;
158} // namespace Protocol
159
160} // namespace Supla
161
162class SuplaDeviceClass : public Supla::ActionHandler,
163 public Supla::LocalAction {
164 public:
165 SuplaDeviceClass();
166 ~SuplaDeviceClass();
167
168 void fillStateData(TDSC_ChannelState *channelState) const;
169 void addClock(Supla::Clock *clock); // DEPRECATED
170 Supla::Clock *getClock() const;
171
172 bool begin(const char GUID[SUPLA_GUID_SIZE],
173 const char *Server,
174 const char *email,
175 const char authkey[SUPLA_AUTHKEY_SIZE],
176 unsigned char protoVersion = 23);
177
178 bool begin(unsigned char protoVersion = 23);
179
180 // Use ASCII only in name
181 void setName(const char *Name);
182
183 void setGUID(const char GUID[SUPLA_GUID_SIZE]);
184 void setAuthKey(const char authkey[SUPLA_AUTHKEY_SIZE]);
185 void setEmail(const char *email);
186 void setServer(const char *server);
187 void setSwVersion(const char *);
188
189 // Do not set the manufacturer ID to anything other than 0. Values other than
190 // 0 are reserved for official Supla products only
191 void setManufacturerId(int16_t);
192
193 // Do not set the product ID to anything other than 0. Values other than
194 // 0 are reserved for official Supla products only
195 void setProductId(int16_t);
196
197 void addFlags(int32_t);
198 void removeFlags(int32_t);
199 bool isSleepingDeviceEnabled() const;
200
201 int generateHostname(char *, int macSize = 6);
202
203 // Timer with 100 Hz frequency (10 ms)
204 void onTimer(void);
205 // Timer with 2000 Hz frequency (0.5 ms or 1 ms)
206 void onFastTimer(void);
207 void iterate(void);
208
209 void status(int status,
210 const __FlashStringHelper *msg,
211 bool alwaysLog = false);
212 void setStatusFuncImpl(_impl_arduino_status impl_arduino_status);
213 void setServerPort(int value);
214
215 int handleCalcfgFromServer(TSD_DeviceCalCfgRequest *request,
216 TDS_DeviceCalCfgResult *result = nullptr);
217
218 void enterConfigMode();
219 void leaveConfigModeWithoutRestart();
220 void enterNormalMode();
221 // Schedules timeout to restart device. When provided timeout is 0
222 // then restart will be done asap.
223 void scheduleSoftRestart(int timeout = 0);
224 void scheduleProtocolsRestart(int timeout = 0);
225 void softRestart();
226 void saveStateToStorage();
227 void restartCfgModeTimeout(bool requireRestart);
228 void resetToFactorySettings();
229 void disableLocalActionsIfNeeded();
230 void requestCfgMode();
231
232 int8_t getCurrentStatus() const;
233 bool loadDeviceConfig();
234 bool prepareLastStateLog();
235 char *getLastStateLog();
236 void addLastStateLog(const char *);
237 void enableLastStateLog();
238 void disableLastStateLog();
239 void setRsaPublicKeyPtr(const uint8_t *ptr);
240 const uint8_t *getRsaPublicKey() const;
241 enum Supla::DeviceMode getDeviceMode() const;
242
243 void setActivityTimeout(_supla_int_t newActivityTimeout);
244 uint32_t getActivityTimeout();
245
246 void handleAction(int event, int action) override;
247
256 void setAutomaticResetOnConnectionProblem(unsigned int timeSec);
257
258 void setLastStateLogger(Supla::Device::LastStateLogger *logger);
259
260 void setSuplaCACert(const char *);
261 void setSupla3rdPartyCACert(const char *);
262 const char *getSuplaCACert() const;
263
264 Supla::Uptime uptime;
265
266 Supla::Protocol::SuplaSrpc *getSrpcLayer();
267
268 void enableNetwork();
269 void disableNetwork();
270 bool getStorageInitResult();
271 bool isSleepingAllowed();
272
284 void allowWorkInOfflineMode(int mode = 1);
285
293 void setInitialMode(Supla::InitialMode mode);
294
301 Supla::InitialMode getInitialMode() const {
302 return initialMode;
303 }
304
310 bool isRemoteDeviceConfigEnabled() const;
311
317 void setShowUptimeInChannelState(bool value);
318
327 void setLogLevel(int level);
328
334 int getLogLevel();
335
344 void setProtoVerboseLog(bool value);
345
346 Supla::Mutex *getTimerAccessMutex();
347
348 void setChannelConflictResolver(
350 void setSubdevicePairingHandler(
352
361 void setMacLengthInHostname(int value);
362
375 void setCustomHostnamePrefix(const char *prefix);
376
377 void setStatusLed(Supla::Device::StatusLed *led);
378
386 void setLeaveCfgModeAfterInactivityMin(int valueMin);
387
397
404
411
416 void identifyStatusLed();
417
423 void testStepStatusLed(int times);
424
433 void addSecurityLog(uint32_t source, const char *log) const;
434
442 void addSecurityLog(Supla::SecurityLogSource source, const char *log) const;
443
450
456 bool isSecurityLogEnabled() const;
457
458 protected:
463 void iterateSwUpdate();
464
474 bool initSwUpdateInstance(Supla::SwUpdateMode mode, int securityOnly = -1);
475
476 void iterateAlwaysElements(uint32_t _millis);
477 bool iterateNetworkSetup();
478 bool iterateSuplaProtocol(uint32_t _millis);
479 void handleLocalActionTriggers();
480 void checkIfLeaveCfgModeOrRestartIsNeeded();
481 void createSrpcLayerIfNeeded();
482 void setupDeviceMode();
483
484 uint32_t networkIsNotReadyCounter = 0;
485 uint32_t deviceRestartTimeoutTimestamp = 0;
486 uint32_t protocolRestartTimeoutTimestamp = 0;
487 uint32_t waitForIterate = 0;
488 uint32_t lastIterateTime = 0;
489 uint32_t enterConfigModeTimestamp = 0;
490 uint32_t forceRestartTimeMs = 0;
491 uint32_t protocolRestartTimeMs = 0;
492 uint32_t resetOnConnectionFailTimeoutSec = 0;
493 uint32_t lastSwUpdateCheckTimestamp = 0;
494
495 enum Supla::DeviceMode deviceMode = Supla::DEVICE_MODE_NOT_SET;
496 bool triggerResetToFactorySettings = false;
497 bool triggerStartLocalWebServer = false;
498 bool triggerStopLocalWebServer = false;
499 bool triggerCheckSwUpdate = false;
500 bool requestNetworkLayerRestart = false;
501 bool isNetworkSetupOk = false;
502 bool skipNetwork = false;
503 bool storageInitResult = false;
504 bool showUptimeInChannelState = true;
505 bool lastStateLogEnabled = true;
506 // used to indicate if begin() method was called - it will be set to
507 // true even if initialization procedure failed for some reason
508 bool initializationDone = false;
509 bool goToConfigModeAsap = false;
510
511 uint8_t leaveCfgModeAfterInactivityMin = 5;
512 uint8_t macLengthInHostname = 6;
513 int8_t currentStatus = STATUS_UNKNOWN;
514 uint8_t swUpdateAttempts = 0;
515
516 Supla::InitialMode initialMode = Supla::InitialMode::StartInNotConfiguredMode;
517 Supla::CfgModeState cfgModeState = Supla::CfgModeState::NotSet;
518 Supla::ConfigurationState configurationState = {};
519
520 Supla::Protocol::SuplaSrpc *srpcLayer = nullptr;
521 Supla::Device::SwUpdate *swUpdate = nullptr;
522 Supla::Element *iterateConnectedPtr = nullptr;
523 Supla::Device::LastStateLogger *lastStateLogger = nullptr;
524 Supla::Mutex *timerAccessMutex = nullptr;
525 Supla::Device::SubdevicePairingHandler *subdevicePairingHandler = nullptr;
526 Supla::Device::StatusLed *statusLed = nullptr;
527 Supla::Device::SecurityLogger *securityLogger = nullptr;
528 const uint8_t *rsaPublicKey = nullptr;
529 char *customHostnamePrefix = nullptr;
530 _impl_arduino_status impl_arduino_status = nullptr;
531};
532
533extern SuplaDeviceClass SuplaDevice;
534#endif // SRC_SUPLADEVICE_H_
Definition security_logger.h:62
Definition SuplaDevice.h:163
void identifyStatusLed()
Triggers "identify" action on status LED.
Definition SuplaDevice.cpp:1878
void setShowUptimeInChannelState(bool value)
Sets if "uptime" should be added to channel state (i).
Definition SuplaDevice.cpp:1799
int getLogLevel()
Returns current global Supla log level.
Definition SuplaDevice.cpp:1807
void setCustomHostnamePrefix(const char *prefix)
Sets custom hostname prefix to be used in hostname and Wi-Fi Soft AP name.
Definition SuplaDevice.cpp:1700
void testStepStatusLed(int times)
Triggers special status LED flashing sequence based on provided "times".
Definition SuplaDevice.cpp:1885
void setInitialMode(Supla::InitialMode mode)
Sets the initial mode of the device.
Definition SuplaDevice.cpp:1916
void addSecurityLog(uint32_t source, const char *log) const
Adds security log.
Definition SuplaDevice.cpp:1899
void allowWorkInOfflineMode(int mode=1)
Allows device to work in offline mode DEPRECATED: use setInitialMode() instead.
Definition SuplaDevice.cpp:1768
void setProtoVerboseLog(bool value)
Enables/disables verbose logging of Supla protocol.
Definition SuplaDevice.cpp:1811
bool isSecurityLogEnabled() const
Checks if security log is enabled.
Definition SuplaDevice.cpp:1912
void setSecurityLogger(Supla::Device::SecurityLogger *logger)
Sets instance of Supla::Device::SecurityLogger.
Definition SuplaDevice.cpp:1891
void setMacLengthInHostname(int value)
Sets the byte length of MAC address in hostname and Wi-Fi Soft AP name.
Definition SuplaDevice.cpp:1839
void setAutomaticResetOnConnectionProblem(unsigned int timeSec)
Enables automatic software reset of device in case of network/server connection problems longer than ...
Definition SuplaDevice.cpp:1650
Supla::InitialMode getInitialMode() const
Returns the initial mode of the device @See Supla::InitialMode.
Definition SuplaDevice.h:301
bool isLeaveCfgModeAfterInactivityEnabled() const
Checks if leave configuration mode after inactivity is enabled.
Definition SuplaDevice.cpp:1963
void setLeaveCfgModeAfterInactivityMin(int valueMin)
Sets the leave configuration mode after inactivity timeout in minutes.
Definition SuplaDevice.cpp:1855
void iterateSwUpdate()
Performs software update if needed.
Definition SuplaDevice.cpp:700
void setLogLevel(int level)
Sets global Supla log level.
Definition SuplaDevice.cpp:1803
void setAutomaticFirmwareUpdateSupported(bool value)
Sets automatic firmware update support.
Definition SuplaDevice.cpp:1866
bool isRemoteDeviceConfigEnabled() const
Checks if remote device configuration is enabled.
Definition SuplaDevice.cpp:1787
bool isAutomaticFirmwareUpdateEnabled() const
Checks if automatic firmware update is supported.
Definition SuplaDevice.cpp:1862
bool initSwUpdateInstance(Supla::SwUpdateMode mode, int securityOnly=-1)
Initializes SW update instance.
Definition SuplaDevice.cpp:612
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:37
Definition local_action.h:52
Definition mutex.h:22
Definition supla_srpc.h:61
Definition uptime.h:24
Definition SuplaDevice.h:123
Definition proto.h:2699
Definition proto.h:2321
Definition proto.h:2311