Coder Social home page Coder Social logo

liana's Introduction

Проект Liana: световая анимация на ESP8266/WS2812

Как быстро запустить

  1. Подключите плату ESP, светодиодную ленту (гирлянду) и источник питания как показано ниже (подключение)

  2. Загрузите в ESP файлы: основную прошивку по адресу 0x000000 и файловую систему по адресу 0x100000. Нужно соответствующим образом выставить настройки: номер COM-порта, размер flash-памяти, режим SPI. Я использовал официальный инструмент Flash download tools (скачать можно здесь), и работающие настройки для платы NodeMCU выглядили так: Настройки Flash download tools для NodeMCU

  3. После запуска подключитесь к беспроводной сети под названием "Liana" и нажмите на всплывающую панель с требованием авторизации - откроется web-интерфейс Liana. Если панель не появляется, перейдите по адресу http://192.168.4.1/ в браузере. В интерфейсе можно подключиться к домашней сети WiFi.

  4. После подключения Liana к сети WiFi, откройте "http://liana.local" в браузере на устройстве с iOS, MacOS or Windows, находящимися в той же сети. К большому сожалению, это не работает для Android - нужно знать IP-адрес Liana (в админской консоли роутера, посмотрев вывод Liana в COM-порт после старта, либо используя клиент mDNS вроде https://play.google.com/store/apps/details?id=com.dokoden.dotlocalfinder). Потом подключайтесь браузером к "http://<IP_ADDRESS>".

Подключение

Wiring diagram

В качестве примера показана плата NodeMCU, но можно использовать любую плату с ESP8266. Нужно иметь в виду, что для других плат возможно потребуется перекомпиляция кода! Т.е. достаточно просто подвести питание к плате, ленте/гирлянде светодиодов WS2812, и подключить выход GPIO2 модуля ESP ко входу данных первого WS2812 в цепочке. Будьте внимательны при выборе блока питания - большинство плат с ESP8266 имеют стабилизатор напряжения, но голая ESP8266 требует точно 3,3 В. Ленты/гирлянды WS2812 требуют 5 В или 12В. Можно использовать разные блоки питания для светодиодов и для ESP; в этом случае у них объединяются "земли". Также убедитесь, что блок питания достаточно мощный для светодиодов и модуля ESP. Слишком слабый блок может вызвать нежелательные побочные эффекты вроде спонтанных перезагрузок, искажения цветов и т.п. Модулю ESP обычно хватает 500 мА, каждый светодиод WS2812 может кушать до 60 мА.

Как собрать

  1. Сейчас проект собран для PlatformIO (https://platformio.org/) и Visual Studio Code (https://code.visualstudio.com/)
  2. Настройки PlatformIO и Visual Studio code хорошо описаны, например, здесь: https://docs.platformio.org/en/latest/integration/ide/vscode.html
  3. Все зависимости прописаны в файле platformio.ini и загружаются автоматически.
  4. Не забудьте прописать параметры платы ESP в platformio.ini (как минимум номер COM-порта для загрузки)
  5. Не забудьте при прошивке также загрузить образ файловой системы (выполнить задачу "Upload Filesystem Image")

Управление модулем

Сейчас после подачи питания модуль начинает проигрывать эффекты в случайном порядке со сменой каждые 30 секунд. В web-интерфейсе можно вручную переключать анимации и палитры, а также включать и выключать ленту. Пока открыта основная страница web-интерфейса, автоматической смены эффектов не происходит! Длительным нажатием на кнопку эффекта или палитры можно исключить их из случайного перебора при закрытом web-интерфейсе. Так можно оставить только понравившиеся эффекты и палитры. В конце списка находится особенный эффект (Магия), разработанный преимущественно для новогодних ёлок. Когда он выбран, можно управлять светом при помощи наклонов устройства, на котором открыт web-интерфейс. Пример показан в этом видео: https://youtu.be/ZXqNeq31DUs. Наклоняйте устройство для смены "целевой точки", поворачивайте его для смены цвета и делайте выпад для подсветки. ВАЖНО: Этот эффект не показывается, если браузер устройства запрещает доступ к датчикам (https://w3c.github.io/deviceorientation/#security-and-privacy). К сожалению это ограничение распространяется на все сайты, работающие не по HTTPS. Т.к. настройка HTTPS в локальной сети ни разу не тривиальная, единственный известный мне способ заставить эффект работать - использовать браузер Chrome, включить опцию --unsafely-treat-insecure-origin-as-secure на странице chrome://flags и указать IP-адрес модуля в этой опции.

Управление по MQTT

Соединение с брокером MQTT настраивается через web-интерфейс. Liana работает только как клиент MQTT. Команды отправляются простым текстом. Ниже перечислены эти команды. Выражения в фигурных скобках {XXX} должны быть заменены на соответствующие значения В конце команд, содержащих параметры, рекомендуется добавлять пробел или символы CR/LF.

  1. on - включить
  2. off - выключить
  3. palette={номер палитры} - выбрать палитру, номера начинаются с 0
  4. animation={номер эффекта} - выбрать анимацию, номера начинаются с 0
  5. duration={секунды} - устанавливает длительность текущего эффекта; после истечения времени возобновляется случайный перебор
  6. brightness={яркость} - устанавливается яркость (0..255)
  7. brightness up - увеличивает яркость
  8. brightness down - уменьшает яркость

Project Liana: ESP8266/WS2812 LIght ANimation

How to start

  1. Connect your ESP, LED strip and power source as shown below (Wiring)
  2. Upload binary files: program file at 0x000000, and SPIFFS file at 0x100000. You should adjust settings for your board, particuarly COM port number, flash size, and SPI mode. I used official Flash download tools (can be found here), and my working settings for NodeMCU board looked like this:

Flash download tools settings

  1. Connect to "Liana" wireless network and tap on pop-up authorization panel. You'll be brought directly to the Liana web interface. If the panel didn't open, go to http://192.168.4.1/ in the browser. You can configure connection to your WiFi network there.
  2. Once you have connected Liana to your WiFi, open "http://liana.local" in web browser of any iOS, MacOS or Windows device on the same network. This does not work for Android however, you should find IP address of the Liana (e.g. in your router admin console, seeing Liana COM port output after startup, or using mDNS client like https://play.google.com/store/apps/details?id=com.dokoden.dotlocalfinder). Then type "http://<IP_ADDRESS>" in Android browser.

Wiring

Wiring diagram

Here example of NodeMCU is shown, but you can use any ESP8266 board. But note you may have to recompile the code! You power the board, power the WS2812 chain, and connect GPIO2 output of ESP to the data input of the firsh WS2812 in chain, that's all. Be sure you use appropriate power source; most of ESP8266 board have voltage stabilizer but "raw" ESP8266 require 3.3V while WS2812 strips require 5V or 12V. You can use different power sources for ESP and the strip, you connect grounds then. Also, be sure that there's enough power for your LEDs and ESP; too weak power source can cause unintended side effects like random rebooting, wrong coloring etc. 500 mA is typically enough for ESP board. Each WS2812 LED eats up to 60 mA.

How to compile

  1. Currently the project is built with PlatformIO (https://platformio.org/) and Visual Studio Code (https://code.visualstudio.com/)
  2. Setting up PlatformIO and Visual Studio Code is described here: https://docs.platformio.org/en/latest/integration/ide/vscode.html
  3. All library dependencies are enumerated in platformio.ini file and should be downloaded automatically.
  4. Be sure to set up your board settings in platformio.ini file (at least COM port for downloading)
  5. Don't forget to upload SPIFFS image (Run task "Upload Filesystem Image")

Controlling the unit

Currently, when unit is powered on, it starts to play animations in random order, changing every 30 seconds. With web browser, you can control animations and palettes manually. Also you can switch the strip on and off. While main web page is open, no automatic change occurs. Long tapping on animation or palette disables it (excludes from random enumeration when web interface is closed). There's special animation at the end of the list (called 'Magic'), designed for New Year trees mainly. When it's selected, you can control the lights with your device accelerometer (as shown in this video: https://youtu.be/ZXqNeq31DUs). You tilt the device to alter "target point", roll it to change color and lunge to highlight. IMPORTANT NOTE: the Magic animation is hidden when browser restricts access to mobile device sensors (https://w3c.github.io/deviceorientation/#security-and-privacy). Unfortunately the restriction applies to all non-HTTPS sites. Since setting up proper HTTPS on local devices is cumbersome, the only way I know to make this animation work is using Chrome and enable --unsafely-treat-insecure-origin-as-secure option in chrome://flags and specify your IP address in the option value textbox.

MQTT operation

MQTT broker connection is set up in web interface. Liana works as MQTT client only. Commands are sent in plain text. Below description of commands goes. {XXX} is replaced with actual value of parameter. It's recommended to add a space or CR/LF chars to the end of parametrized commands.

  1. on - turn on
  2. off - turn off
  3. palette={palette index} - set palette, index numbering starts from 0
  4. animation={animation index} - set animation, index numbering starts from 0
  5. duration={seconds} - sets current effect (palette/animation) duration; random cycling starts after specified time elapses
  6. brightness={brightness} - sets brightness (0..255)
  7. brightness up - increases brightness (exponential)
  8. brightness down - decreases brightness (exponential)

liana's People

Contributors

disdis avatar vasil-pahomov avatar witska avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

liana's Issues

ошибка компиляции

Что это может означить?
In file included from sketch/anim_magic.cpp:1:0:
/Users/.../Library/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/SoftwareSerial/src/SoftwareSerial.h:113:2: error: 'ssize_t' does not name a type
ssize_t m_swsInstsIdx = -1;

Пожелания и комментарии

Добрый день!
Вчера скачал обновлённый вариант прошивки с возможностью смены настроек Wi-Fi программно.
Проблема возникла при попытке записать spiffs, писало, что python не установлен, нашёл его расположение в папке с платами (требовался файл python3.exe, пришлось создать хардлинк у меня был только python.exe и создать пути в операционке к этой папке, ошибка пропала, но ничего не происходило. У меня версия arduino IDE 1.8.10 и версия библиотеки плат 8266 на тот момент была 2.5.2. В общем побился-побился, не выходит. Сохранил свой бинарник и попробовал залить с приложенным для spiffs, но после прошивки гирлянда почему-то не стартанула... Тогда я решился обновить платы до версии 2.6.2, после чего питон переустановился и запись spiffs заработала, так же прошил и плату. Теперь всё работает отлично.
По поводу пожеланий - я думаю, что было бы уместно и не очень сложно теперь, переименовать страничку из настроек wi-fi просто в настройки и добавить туда поле для смены сетевого имени, переключение режимов цвета (RGB/GRB и т.п.) и количество диодов в ленте. А из глобальных - конечно же добавить больше эффектов, возможно не все, но самые интересные из порядка 50 имеющихся в наборе neopixel где по одному бегают, навстречу друг другу, смена направлений и цвета заполнения гирлянды и т.п. Может быть на основную страницу управления эффектами добавить управление яркостью и скоростью (в идеале для каждого эффекта и сохранять для авто-плэя :))... мечты
Вообще большущее спасибо!!! внукам очень нравится!

Use only websocket for communication

Now communication is done both with HTTP and WebSockets. It's better to replace HTTP calls with WebSocket messages. Also it provides realtime update of webface.

@Vasil-Pahomov Need your approve to use your code in the expurna project

Hi Vasil,
Sorry for this, but it is only one way that I found to contact with you. I used your code (don't sure the latest one, possibly it was even old Arduino version), refactor it a bit and now want to push as module to xoseperez/espurna ESP8266 project. It is non-commercial open source project.
xoseperez/espurna#2408 - this is the pull request.
There is licensing question arise now. Unfortunately, I didn't found any license in your repository or in the code.
So, I kindly ask your permission to use module, originally derived by your library in xoseperez/espurna project.
You can contact to me by email [email protected] or just write your message in the pull-request discussion under this comment: xoseperez/espurna#2408 (review)
Thank you!

Управление не из браузера.

Подскажите, пожалуйста, как можно управлять гирляндой не через браузер? Хочется встроить управление в Majordomo.

The board does not revert to AP mode

STR:

  1. Connect board to WiFi
  2. Go to WiFi settings, click "AP" button, confirm
  3. Reset the board
    Act: board connects to WiFi
    Exp: board keeps AP mode

Support ESP32

В текущий момент код не поддерживает ESP32.
В данный момент у меня есть ветка с предварительной поддержкой ESP32, как будут решены все проблемы вышлю MR

Automate HTML embedding

Make some automated script that embeds source HTML file into the ESP code (minifies, escapes)

Цветовой режим ленты

Добрый день.
С наступившим Вас новым годом! Третий год уже светит гирлянда на елке, но решил обновить саму ленту и столкнулся с проблемой отсутствия режима ленты BGR. Возможно добавить?
Скачал VSCode но ничерта в нем не пойму, а строк с режимами нашел в нескольких местах, чего дальше делать, если даже добавлю новую строку - не знаю...

Перезагрузки

При попытке зайти в веб-интерфейс нода перезагружается. Питание от БП 5В 2,1А (пока без ленты), куда смотреть?

Уменьшение яркости стартового эффекта (БП уходит в защиту)

Мой блок питания на 12В 2А во время стартового эффекта, когда ярко мигают белым все светодиоды, уходит в защиту, т.к. ток потребления достигает 3,5А. ВСЕ другие эффекты с максимальной яркостью работают отлично, максимальный ток потребления не превышает 1,1 - 1,2А.
Нужна возможность снизить яркость именно первого эффекта, в файле или через настройки.

Only binary file works well.

Hello!
I has compile the ino-file, but the lights always drop the colors to blue/green or red/blue combinations,,, it is not depend on the power supply - the battery power bank show the same results: one time work good, another - only 2 colors mode,,, And no web page on the interface. While I has download the bin file and write it to esp all becomes fine... What can be wrong with compilation?

Support OTA

Поддержка OTA.
Включение через веб морду.
Поддержка в прошивке через флаг SUPPORT_OTA в ota.h
Авторизация для OTA.
Всё прописано в конфиге, проверено только на ESP32

---- MR уже в пути ---

Add AP configuration

So that you don't have to recompile the sketch in order to connect to your WiFi network.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.