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/proto.h>
21#include <supla/uptime.h>
22#include <supla/action_handler.h>
23#include <supla/local_action.h>
24#include <supla/device/device_mode.h>
25#include "supla/device/security_logger.h"
26
27#define STATUS_UNKNOWN -1
28#define STATUS_ALREADY_INITIALIZED 1
29#define STATUS_MISSING_NETWORK_INTERFACE 2
30#define STATUS_UNKNOWN_SERVER_ADDRESS 3
31#define STATUS_UNKNOWN_LOCATION_ID 4
32#define STATUS_INITIALIZED 5
33#define STATUS_SERVER_DISCONNECTED 6
34#define STATUS_ITERATE_FAIL 7
35#define STATUS_NETWORK_DISCONNECTED 8
36#define STATUS_ALL_PROTOCOLS_DISABLED 9
37
38#define STATUS_REGISTER_IN_PROGRESS 10 // Don't change
39#define STATUS_REGISTERED_AND_READY 17 // Don't change
40
41#define STATUS_TEMPORARILY_UNAVAILABLE 21
42#define STATUS_INVALID_GUID 22
43#define STATUS_CHANNEL_LIMIT_EXCEEDED 23
44#define STATUS_PROTOCOL_VERSION_ERROR 24
45#define STATUS_BAD_CREDENTIALS 25
46#define STATUS_LOCATION_CONFLICT 26
47#define STATUS_CHANNEL_CONFLICT 27
48#define STATUS_DEVICE_IS_DISABLED 28
49#define STATUS_LOCATION_IS_DISABLED 29
50#define STATUS_DEVICE_LIMIT_EXCEEDED 30
51#define STATUS_REGISTRATION_DISABLED 31
52#define STATUS_MISSING_CREDENTIALS 32
53#define STATUS_INVALID_AUTHKEY 33
54#define STATUS_NO_LOCATION_AVAILABLE 34
55#define STATUS_UNKNOWN_ERROR 35
56#define STATUS_COUNTRY_REJECTED 36
57
58#define STATUS_CONFIG_MODE 40
59#define STATUS_SOFTWARE_RESET 41
60#define STATUS_SW_DOWNLOAD 50
61#define STATUS_SUPLA_PROTOCOL_DISABLED 60
62#define STATUS_TEST_WAIT_FOR_CFG_BUTTON 70
63#define STATUS_OFFLINE_MODE 80
64#define STATUS_NOT_CONFIGURED_MODE 90
65
66// 10 days
67#define SUPLA_AUTOMATIC_OTA_CHECK_INTERVAL (10ULL * 24 * 60 * 60 * 1000)
68
69typedef void (*_impl_arduino_status)(int status, const char *msg);
70
71#ifdef ARDUINO
72class __FlashStringHelper;
73#else
74#define __FlashStringHelper char
75#endif
76
77namespace Supla {
78class Clock;
79class Mutex;
80class Element;
81
85enum class InitialMode: uint8_t {
89 StartInCfgMode = 0,
94 StartOffline = 1,
98 StartWithCfgModeThenOffline = 2,
102 StartInNotConfiguredMode = 3
103};
104
105enum class CfgModeState: uint8_t {
106 NotSet = 0,
107 CfgModeStartedFor1hPending = 1,
108 CfgModeStartedPending = 2,
109 CfgModeOngoing = 3,
110 Done = 4,
111};
112
113struct ConfigurationState {
114 uint8_t wifiEnabled: 1;
115 uint8_t wifiSsidFilled: 1;
116 uint8_t wifiPassFilled: 1;
117 uint8_t protocolFilled: 1;
118 uint8_t protocolNotEmpty: 1;
119 uint8_t configNotComplete: 1;
120 uint8_t atLeastOneProtoIsEnabled: 1;
121
122 bool isEmpty() const;
123
124 ConfigurationState() {
125 wifiEnabled = 0;
126 wifiSsidFilled = 0;
127 wifiPassFilled = 0;
128 protocolFilled = 0;
129 protocolNotEmpty = 0;
130 configNotComplete = 0;
131 atLeastOneProtoIsEnabled = 0;
132 }
133};
134
135const char *getInitialModeName(const InitialMode mode);
136
137namespace Device {
138class SwUpdate;
139class ChannelConflictResolver;
140class SubdevicePairingHandler;
141class StatusLed;
142class LastStateLogger;
143class SecurityLogger;
144} // namespace Device
145
146namespace Protocol {
147class SuplaSrpc;
148} // namespace Protocol
149
150} // namespace Supla
151
152class SuplaDeviceClass : public Supla::ActionHandler,
153 public Supla::LocalAction {
154 public:
155 SuplaDeviceClass();
156 ~SuplaDeviceClass();
157
158 void fillStateData(TDSC_ChannelState *channelState) const;
159 void addClock(Supla::Clock *clock); // DEPRECATED
160 Supla::Clock *getClock() const;
161
162 bool begin(const char GUID[SUPLA_GUID_SIZE],
163 const char *Server,
164 const char *email,
165 const char authkey[SUPLA_AUTHKEY_SIZE],
166 unsigned char protoVersion = 23);
167
168 bool begin(unsigned char protoVersion = 23);
169
170 // Use ASCII only in name
171 void setName(const char *Name);
172
173 void setGUID(const char GUID[SUPLA_GUID_SIZE]);
174 void setAuthKey(const char authkey[SUPLA_AUTHKEY_SIZE]);
175 void setEmail(const char *email);
176 void setServer(const char *server);
177 void setSwVersion(const char *);
178
179 // Do not set the manufacturer ID to anything other than 0. Values other than
180 // 0 are reserved for official Supla products only
181 void setManufacturerId(int16_t);
182
183 // Do not set the product ID to anything other than 0. Values other than
184 // 0 are reserved for official Supla products only
185 void setProductId(int16_t);
186
187 void addFlags(int32_t);
188 void removeFlags(int32_t);
189 bool isSleepingDeviceEnabled() const;
190
191 int generateHostname(char*, int macSize = 6);
192
193 // Timer with 100 Hz frequency (10 ms)
194 void onTimer(void);
195 // Timer with 2000 Hz frequency (0.5 ms or 1 ms)
196 void onFastTimer(void);
197 void iterate(void);
198
199 void status(int status,
200 const __FlashStringHelper *msg,
201 bool alwaysLog = false);
202 void setStatusFuncImpl(_impl_arduino_status impl_arduino_status);
203 void setServerPort(int value);
204
205 int handleCalcfgFromServer(TSD_DeviceCalCfgRequest *request,
206 TDS_DeviceCalCfgResult *result = nullptr);
207
208 void enterConfigMode();
209 void leaveConfigModeWithoutRestart();
210 void enterNormalMode();
211 // Schedules timeout to restart device. When provided timeout is 0
212 // then restart will be done asap.
213 void scheduleSoftRestart(int timeout = 0);
214 void scheduleProtocolsRestart(int timeout = 0);
215 void softRestart();
216 void saveStateToStorage();
217 void restartCfgModeTimeout(bool requireRestart);
218 void resetToFactorySettings();
219 void disableLocalActionsIfNeeded();
220 void requestCfgMode();
221
222 int8_t getCurrentStatus() const;
223 bool loadDeviceConfig();
224 bool prepareLastStateLog();
225 char *getLastStateLog();
226 void addLastStateLog(const char*);
227 void enableLastStateLog();
228 void disableLastStateLog();
229 void setRsaPublicKeyPtr(const uint8_t *ptr);
230 const uint8_t *getRsaPublicKey() const;
231 enum Supla::DeviceMode getDeviceMode() const;
232
233 void setActivityTimeout(_supla_int_t newActivityTimeout);
234 uint32_t getActivityTimeout();
235
236 void handleAction(int event, int action) override;
237
238 // Enables automatic software reset of device in case of network/server
239 // connection problems longer than timeSec.
240 // timeSec is always round down to multiplication of 10 s.
241 // timeSec <= 60 will disable automatic restart.
242 void setAutomaticResetOnConnectionProblem(unsigned int timeSec);
243
244 void setLastStateLogger(Supla::Device::LastStateLogger *logger);
245
246 void setSuplaCACert(const char *);
247 void setSupla3rdPartyCACert(const char *);
248 const char* getSuplaCACert() const;
249
250 Supla::Uptime uptime;
251
252 Supla::Protocol::SuplaSrpc *getSrpcLayer();
253
254 void setCustomHostnamePrefix(const char *prefix);
255
256 void enableNetwork();
257 void disableNetwork();
258 bool getStorageInitResult();
259 bool isSleepingAllowed();
260
272 void allowWorkInOfflineMode(int mode = 1);
273
281 void setInitialMode(Supla::InitialMode mode);
282
289 Supla::InitialMode getInitialMode() const { return initialMode; }
290
296 bool isRemoteDeviceConfigEnabled() const;
297
303 void setShowUptimeInChannelState(bool value);
304
310 void setProtoVerboseLog(bool value);
311
312 Supla::Mutex *getTimerAccessMutex();
313
314 void setChannelConflictResolver(
316 void setSubdevicePairingHandler(
318
319 void setMacLengthInHostname(int value);
320
321 void setStatusLed(Supla::Device::StatusLed *led);
322
330 void setLeaveCfgModeAfterInactivityMin(int valueMin);
331
341
348
355
360 void identifyStatusLed();
361
367 void testStepStatusLed(int times);
368
377 void addSecurityLog(uint32_t source, const char *log) const;
378
386 void addSecurityLog(Supla::SecurityLogSource source, const char *log) const;
387
394
400 bool isSecurityLogEnabled() const;
401
402 protected:
407 void iterateSwUpdate();
408
418 bool initSwUpdateInstance(bool performUpdate, int securityOnly = -1);
419
420 void iterateAlwaysElements(uint32_t _millis);
421 bool iterateNetworkSetup();
422 bool iterateSuplaProtocol(uint32_t _millis);
423 void handleLocalActionTriggers();
424 void checkIfLeaveCfgModeOrRestartIsNeeded();
425 void createSrpcLayerIfNeeded();
426 void setupDeviceMode();
427
428 uint32_t networkIsNotReadyCounter = 0;
429 uint32_t deviceRestartTimeoutTimestamp = 0;
430 uint32_t protocolRestartTimeoutTimestamp = 0;
431 uint32_t waitForIterate = 0;
432 uint32_t lastIterateTime = 0;
433 uint32_t enterConfigModeTimestamp = 0;
434 uint32_t forceRestartTimeMs = 0;
435 uint32_t protocolRestartTimeMs = 0;
436 uint32_t resetOnConnectionFailTimeoutSec = 0;
437 uint32_t lastSwUpdateCheckTimestamp = 0;
438
439 enum Supla::DeviceMode deviceMode = Supla::DEVICE_MODE_NOT_SET;
440 bool triggerResetToFactorySettings = false;
441 bool triggerStartLocalWebServer = false;
442 bool triggerStopLocalWebServer = false;
443 bool triggerCheckSwUpdate = false;
444 bool requestNetworkLayerRestart = false;
445 bool isNetworkSetupOk = false;
446 bool skipNetwork = false;
447 bool storageInitResult = false;
448 bool showUptimeInChannelState = true;
449 bool lastStateLogEnabled = true;
450 // used to indicate if begin() method was called - it will be set to
451 // true even if initialization procedure failed for some reason
452 bool initializationDone = false;
453 bool goToConfigModeAsap = false;
454 bool triggerSwUpdateIfAvailable = false;
455
456 uint8_t leaveCfgModeAfterInactivityMin = 5;
457 uint8_t macLengthInHostname = 6;
458 int8_t currentStatus = STATUS_UNKNOWN;
459
460 Supla::InitialMode initialMode = Supla::InitialMode::StartInNotConfiguredMode;
461 Supla::CfgModeState cfgModeState = Supla::CfgModeState::NotSet;
462 Supla::ConfigurationState configurationState = {};
463
464 Supla::Protocol::SuplaSrpc *srpcLayer = nullptr;
465 Supla::Device::SwUpdate *swUpdate = nullptr;
466 Supla::Element *iterateConnectedPtr = nullptr;
467 Supla::Device::LastStateLogger *lastStateLogger = nullptr;
468 Supla::Mutex *timerAccessMutex = nullptr;
469 Supla::Device::SubdevicePairingHandler *subdevicePairingHandler = nullptr;
470 Supla::Device::StatusLed *statusLed = nullptr;
471 Supla::Device::SecurityLogger *securityLogger = nullptr;
472 const uint8_t *rsaPublicKey = nullptr;
473 char *customHostnamePrefix = nullptr;
474 _impl_arduino_status impl_arduino_status = nullptr;
475};
476
477extern SuplaDeviceClass SuplaDevice;
478#endif // SRC_SUPLADEVICE_H_
Definition security_logger.h:62
Definition SuplaDevice.h:153
void identifyStatusLed()
Triggers "identify" action on status LED.
Definition SuplaDevice.cpp:1807
void setShowUptimeInChannelState(bool value)
Sets if "uptime" should be added to channel state (i)
Definition SuplaDevice.cpp:1743
void testStepStatusLed(int times)
Triggers special status LED flashing sequence based on provided "times".
Definition SuplaDevice.cpp:1814
void setInitialMode(Supla::InitialMode mode)
Sets the initial mode of the device.
Definition SuplaDevice.cpp:1845
void addSecurityLog(uint32_t source, const char *log) const
Adds security log.
Definition SuplaDevice.cpp:1828
void allowWorkInOfflineMode(int mode=1)
Allows device to work in offline mode DEPRECATED: use setInitialMode() instead.
Definition SuplaDevice.cpp:1712
bool initSwUpdateInstance(bool performUpdate, int securityOnly=-1)
Initializes SW update instance.
Definition SuplaDevice.cpp:587
void setProtoVerboseLog(bool value)
Enables/disables verbose logging of Supla protocol.
Definition SuplaDevice.cpp:1747
bool isSecurityLogEnabled() const
Checks if security log is enabled.
Definition SuplaDevice.cpp:1841
void setSecurityLogger(Supla::Device::SecurityLogger *logger)
Sets instance of Supla::Device::SecurityLogger.
Definition SuplaDevice.cpp:1820
Supla::InitialMode getInitialMode() const
Returns the initial mode of the device @See Supla::InitialMode.
Definition SuplaDevice.h:289
bool isLeaveCfgModeAfterInactivityEnabled() const
Checks if leave configuration mode after inactivity is enabled.
Definition SuplaDevice.cpp:1892
void setLeaveCfgModeAfterInactivityMin(int valueMin)
Sets the leave configuration mode after inactivity timeout in minutes.
Definition SuplaDevice.cpp:1785
void iterateSwUpdate()
Performs software update if needed.
Definition SuplaDevice.cpp:659
void setAutomaticFirmwareUpdateSupported(bool value)
Sets automatic firmware update support.
Definition SuplaDevice.cpp:1795
bool isRemoteDeviceConfigEnabled() const
Checks if remote device configuration is enabled.
Definition SuplaDevice.cpp:1731
bool isAutomaticFirmwareUpdateEnabled() const
Checks if automatic firmware update is supported.
Definition SuplaDevice.cpp:1791
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:55
Definition uptime.h:24
Definition SuplaDevice.h:113
Definition proto.h:2620
Definition proto.h:2273
Definition proto.h:2263