Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Baskerville42 committed Aug 2, 2024
0 parents commit d186695
Show file tree
Hide file tree
Showing 26 changed files with 2,225 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
build/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Alexander Tartmin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
91 changes: 91 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# SvitloBoard Firmware

**SvitloBoard** - це прошивка для ESP8266, яка дозволяє налаштувати пристрій для сповіщення про наявність світла через систему [СвітлоБот](https://svitlobot.in.ua).

## Зміст

- [Опис проекту](#опис-проекту)
- [Веб-інтерфейс](#веб-інтерфейс)
- [Функціональність](#функціональність)
- [Установка](#установка)
- [Використання](#використання)
- [Налаштування](#налаштування)
- [Внесок](#внесок)
- [Ліцензія](#ліцензія)
- [Known Issues](#known-issues)
- [TODO](#todo)

## Опис проекту

Ідея SvitloBoard полягає у створенні простого та зручного рішення для інтеграції з системою СвітлоБот, що дозволяє автоматично повідомляти про наявність світла.

## Веб-інтерфейс
![setup](https://github.com/user-attachments/assets/ac7de3c6-39fd-4ee9-ad62-49505e1f6eca)
![channel_key](https://github.com/user-attachments/assets/97ef9f16-f66d-4283-843c-aa5ab2e5e801)
![wifi](https://github.com/user-attachments/assets/3a816514-3790-4fea-91db-b3d18a09c51f)
![status](https://github.com/user-attachments/assets/8b42f446-78e8-44f3-9809-b458cda9b4fa)

**Увага:** Цей проект був протестований поки лише на контролері ESP8266 і є бета-версією, яка може містити помилки в роботі.

## Функціональність
- **Налаштування Channel Key**: Введення унікального коду каналу для підключення до СвітлоБот.
- **Налаштування мережі Wi-Fi**: Конфігурація основної та резервних мереж Wi-Fi через веб-інтерфейс.
- **Перевірка статусу**: Отримання інформації про запити до API СвітлоБот.
- **Скидання до заводських налаштувань**: Можливість скидання всіх налаштувань через веб-інтерфейс або через 4 послідовних ввімкнення/вимкнення.
- **Підключення до мережі**: Автоматичне підключення до першої доступної мережі. Є можливість вказувати до 2-х додаткових резервних точок Wi-Fi.
- **Точка доступу**: Пристрій працює як точка доступу за замовчуванням, якщо не задано мережу.

## Установка

1. Завантажте та встановіть [Arduino IDE](https://www.arduino.cc/en/software).
2. Додайте підтримку ESP8266 до Arduino IDE через Менеджер плат.
3. Завантажте цей репозиторій або склонуйте його:
```bash
git clone https://github.com/Baskerville42/svitloboard.git
```
4. Відкрийте файл `svitloboard.ino` в Arduino IDE.
5. Підключіть ESP8266 до комп'ютера і виберіть відповідну плату та порт у меню "Інструменти".
6. Завантажте прошивку на ESP8266.
## Використання
1. **Підключення до точки доступу**: Пристрій автоматично створить точку доступу з SSID "SVITLOBOARD". Підключіться до цієї мережі з вашого пристрою.
2. **Налаштування через веб-інтерфейс**: Відкрийте веб-браузер і перейдіть за адресою `192.168.4.1`. Це відкриє сторінку налаштування.
3. **Введіть Channel Key та дані мережі Wi-Fi**: На сторінці налаштування введіть унікальний код каналу та дані для основної Wi-Fi мережі.
4. **Збережіть налаштування**: Натисніть "Зберегти" для збереження налаштувань. Пристрій автоматично перезавантажиться і спробує підключитися до нової мережі.
## Налаштування
Усі подальші налаштування будуть доступні за новою IP-адресою підключеної мережі.
1. **Знайти адресу пристрою**: У панелі керування (чи додатку) вашого пристрою Wi-Fi знайдіть список клієнтів. У цьому списку знайдіть SvitloBoard 1.0 та перегляньте його IP-адресу.
2. **Налаштування через веб-інтерфейс**: Відкрийте веб-браузер і перейдіть за адресою з попереднього кроку. Це відкриє сторінку налаштування.
## Внесок
Внесок до проекту вітається! Якщо ви хочете внести зміни, будь ласка, створіть pull request або відкрийте issue для обговорення змін.
## Ліцензія
Цей проект ліцензується під ліцензією MIT - подробиці дивіться у файлі [LICENSE](LICENSE).
## Known Issues
Перед використанням цієї прошивки варто очистити пам'ять EEPROM, інакше можуть бути проблеми в роботі. Як тимчасове рішення - можна скинути пристрій після прошивки 4-ма послідовними увімкненнями та вимкненнями.

Можливі проблеми в роботі на інших мікроконтролерах, відмінних від ESP8266 (ESP-01).

Якщо раптом мікроконтролер перестав посилати запити, але підключається до мережі і веб-інтерфейс доступний - можливо на сервері змінився https сертифікат і потрібно змінити його в файлі [channel_ping_request.cpp](https://github.com/Baskerville42/svitloboard/blob/main/channel_ping_request.cpp#L13).

## TODO

- [x] Реалізувати переключення між основною та резервними мережами WiFi
- [x] Скидання пристрою через 4 послідовних вимкнення та увімкнення
- [ ] Можливість вказувати кастомний URL для інтервальних запитів в 1 хв
- [ ] Очищувати EEPROM при першому увімкненні до ініціалізації читання конфігурації
- [ ] Можливість змінювати Fingerprint сертифікату сервера API
- [ ] Видалення збережених резервних мереж

---

**Автор**: Alexander Tartmin
**GitHub**: [baskerville42](https://github.com/baskerville42)
115 changes: 115 additions & 0 deletions Ticker.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/* Ticker library code is placed under the MIT license
* Copyright (c) 2018 Stefan Staub
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

#include "Ticker.h"

Ticker::Ticker(fptr callback, uint32_t timer, uint32_t repeat, resolution_t resolution) {
this->resolution = resolution;
if (resolution == MICROS) timer = timer * 1000;
this->timer = timer;
this->repeat = repeat;
this->callback = callback;
enabled = false;
lastTime = 0;
counts = 0;
}

Ticker::~Ticker() {}

void Ticker::start() {
if (callback == NULL) return;
if (resolution == MILLIS) lastTime = millis();
else lastTime = micros();
enabled = true;
counts = 0;
status = RUNNING;
}

void Ticker::resume() {
if (callback == NULL) return;
if (resolution == MILLIS) lastTime = millis() - diffTime;
else lastTime = micros() - diffTime;
if (status == STOPPED) counts = 0;
enabled = true;
status = RUNNING;
}

void Ticker::stop() {
enabled = false;
counts = 0;
status = STOPPED;
}

void Ticker::pause() {
if (resolution == MILLIS) diffTime = millis() - lastTime;
else diffTime = micros() - lastTime;
enabled = false;
status = PAUSED;
}

void Ticker::update() {
if (tick()) callback();
}

bool Ticker::tick() {
if (!enabled) return false;
uint32_t currentTime = (resolution == MILLIS) ? millis() : micros();
if ((currentTime - lastTime) >= timer) {
lastTime = currentTime;
if (repeat - counts == 1 && counts != 0xFFFFFFFF) {
enabled = false;
status = STOPPED;
}
counts++;
return true;
}
return false;
}

void Ticker::interval(uint32_t timer) {
if (resolution == MICROS) timer *= 1000;
this->timer = timer;
}

uint32_t Ticker::interval() {
if (resolution == MILLIS) return timer / 1000;
else return timer;
}

uint32_t Ticker::elapsed() {
if (resolution == MILLIS) return millis() - lastTime;
else return micros() - lastTime;
}

uint32_t Ticker::remaining() {
return timer - elapsed();
}

status_t Ticker::state() {
return status;
}

uint32_t Ticker::counter() {
return counts;
}
160 changes: 160 additions & 0 deletions Ticker.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
/* Ticker library code is placed under the MIT license
* Copyright (c) 2018 Stefan Staub
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

#ifndef TICKER_H
#define TICKER_H

#include "Arduino.h"

/** Ticker internal resolution
*
* @param MICROS default, the resoöution is in micro seconds, max is 70 minutes, the real resoltuion is 4 microseconds at 16MHz CPU cycle
* @param MILLIS set the resolution to millis, for longer cycles over 70 minutes
*
*/
enum resolution_t {
MICROS,
MILLIS,
MICROS_MICROS
};

/** Ticker status
*
* @param STOPPED default, ticker is stopped
* @param RUNNIBG ticker is running
* @param PAUSED ticker is paused
*
*/
enum status_t {
STOPPED,
RUNNING,
PAUSED};

#if defined(__arm__) || defined(ESP8266) || defined(ESP32)
#include <functional>
using fptr = std::function<void()>;
#else
typedef void (*fptr)();
#endif


class Ticker {

public:

/** create a Ticker object
*
* @param callback the name of the function to call
* @param timer interval length in ms or us
* @param repeat default 0 -> endless, repeat > 0 -> number of repeats
* @param resolution default MICROS for tickers under 70min, use MILLIS for tickers over 70 min
*
*/
Ticker(fptr callback, uint32_t timer, uint32_t repeat = 0, resolution_t resolution = MICROS);

/** destructor for the Ticker object
*
*/
~Ticker();

/** start the ticker
*
*/
void start();

/** resume the ticker. If not started, it will start it.
*
*/
void resume();

/** pause the ticker
*
*/
void pause();

/** stops the ticker
*
*/
void stop();

/** must to be called in the main loop(), it will check the Ticker, and if necessary, will run the callback
*
*/
void update();

/**
* @brief set the interval timer
*
* @param timer interval length in ms or us
*/
void interval(uint32_t timer);

/**
* @brief get the interval time
*
* @returns the interval time
*/
uint32_t interval();

/** actual ellapsed time
*
* @returns the elapsed time after the last tick
*
*/
uint32_t elapsed();

/** time remaining to the next tick
*
* @returns the remaining time to the next tick in ms or us depending from mode
*
*/
uint32_t remaining();

/** get the state of the ticker
*
* @returns the state of the ticker: STOPPED, RUNNING or PAUSED
*/
status_t state();

/** get the numbers of executed repeats
*
* @returns the number of executed repeats
*
*/
uint32_t counter();

private:
bool tick();
bool enabled;
uint32_t timer;
uint32_t repeat;
resolution_t resolution = MICROS;
uint32_t counts;
status_t status;
fptr callback;
uint32_t lastTime;
uint32_t diffTime;
};

#endif
Loading

0 comments on commit d186695

Please sign in to comment.