локальный сервер blynk на windows
Blynk сервер
D_Jackas
Всем привет. Имею у себя Home-сервер и на нем висит сервер не мало известного Blynk’a. Т.к. присутствует возможность, могу поделиться с сообществом. Ибо для пары девайсов жирновато будет, да и наличие халявной энергии не помешает.
Можно пользоваться. По сути делюсь из-за того, что опять-же жирно для нескольких девайсов и могу поделиться т.к. не жадный, да и вам не придется арендовать белый IP у провайдера.
Немного информации о сервере:
Адрес сервера | trsh.su |
Порт сервера | 9443 |
Порт для подключения (в скетче) | 8080 |
Кол-во энергии по умолчанию | 1 |
Почта сервера | trshfiles@gmail.com |
Возможность генерации QR | + |
Текущая версия сервера | 0.41.15 |
Статус сервера | Online |
Q: Зачем тебе оно?
A: Просто. Нечего делать
Q: Можно пополнять энергию? И сколько будет стоить?
A: Да можно. Бесплатно. Просто напиши мне.
Q: Обновляешь ли сервер?
A: По мере выхода обновлений
Q: Будешь ли смотреть за моим проектами?
A: Оно мне надо? За своими стараюсь не забывать смотреть.
Q: А если отключишь сервер?
A: Отключится только если по тех. причинам и то буду стараться оповещать заранее.
Q: Забьешь на проект?
A: Только если не будет актуальным. А мне он нужен постоянно.
P.S. Если есть вопросы или пожелания, пишите. Данный «сервер» отдам полностью под комьюнити если будет интересно.
. ВНИМАНИЕ.
На данный момент по умолчанию выдаётся 1 единица энергии! Сделано это для фильтрации от ботов (такие имеются ). Чтобы получить энергию (БЕСПЛАТНО), пишите мне в ЛС.
Локальный сервер blynk на windows
Blynk is a platform with iOS and Android apps to control Arduino, ESP8266, Raspberry Pi and the likes over the Internet.
You can easily build graphic interfaces for all your projects by simply dragging and dropping widgets. If you need more information, please follow these links:
Blynk Server is an Open-Source Netty based Java server, responsible for forwarding messages between Blynk mobile application and various microcontroller boards and SBCs (i.e. Arduino, Raspberry Pi. etc).
Download latest server build here.
For Windows download Java here and install.
Quick local server setup
Make sure you are using Java 11
Run the server on default ‘hardware port 8080’ and default ‘application port 9443’ (SSL port)
NOTE: /path should be real existing path to folder where you want to store all your data.
As an output you should see something like that:
Enabling mail on Local server
To enable mail notifications on Local server you need to provide your own mail credentials. Create file mail.properties within same folder where server.jar is. Mail properties:
WARNING : only gmail accounts are allowed.
NOTE : you’ll need to setup Gmail to allow less secured applications. Go here and then click «Allow less secure apps».
Quick local server setup on Raspberry PI
Login to Raspberry Pi via ssh;
Make sure you are using Java 8
Download Blynk server jar file (or manually copy it to Raspberry Pi via ssh and scp command):
Run the server on default ‘hardware port 8080’ and default ‘application port 9443’ (SSL port)
As output you will see something like that:
Docker container setup
Run Docker container
Quick Launch on Raspberry Pi
Run Docker container
Enabling server auto restart on unix-like systems
To enable server auto restart find /etc/rc.local file and add:
Or if the approach above doesn’t work, execute
add the following line
Enabling server auto restart on Windows
Put in it one line:
Put bat file to windows startup folder
You can also use this script to run server.
Update instruction for unix-like systems
IMPORTANT Server should be always updated before you update Blynk App. To update your server to a newer version you would need to kill old process and start a new one.
Find process id of Blynk server
You should see something like that
Kill the old process
After this steps you can update Blynk app. Server version downgrade is not supported.
WARNING! Please do not revert your server to lower versions. You may loose all of your data.
Update instruction for Windows
App and sketch changes
Change your ethernet sketch from
Change your WIFI sketch from
Change your rasp PI javascript from
or in case of USB when running blynk-ser.sh provide ‘-s’ option with address of your local server
IMPORTANT Blynk is being constantly developed. Mobile apps and server are updated often. To avoid problems during updates either turn off auto-update for Blynk app, or update both local server and blynk app at same time to avoid possible migration issues.
IMPORTANT Blynk local server is different from Blynk Cloud server. They are not related at all. You have to create new account when using Blynk local server.
Advanced local server setup
Available server options:
Blynk app, https, web sockets, admin port
Http, hardware and web sockets port
For simplicity Blynk already provides server jar with built in SSL certificates, so you have working server out of the box via SSL/TLS sockets. But as certificate and it’s private key are in public this is totally not secure. So in order to fix that you need to provide your own certificates. And change below properties with path to your cert. and private key and it’s password. See how to generate self-signed certificates here
Note: if you use Let’s Encrypt certificates you’ll have to add #define BLYNK_SSL_USE_LETSENCRYPT before #include in the Arduino Sketch for your hardware.
User profiles folder. Folder in which all users profiles will be stored. By default System.getProperty(«java.io.tmpdir»)/blynk used. Will be created if not exists
Folder for all application logs. Will be created if it doesn’t exist. «.» is dir from which you are running script.
Maximum allowed number of user dashboards.
100 Req/sec rate limit per user. You also may want to extend this limit on hardware side.
this setting defines how often you can send mail/tweet/push or any other notification. Specified in seconds
Maximum allowed user profile size. In Kb’s.
Number of strings to store in terminal widget (terminal history data)
Period for flushing all user DB to disk. In millis
Specifies maximum period of time when hardware socket could be idle. After which socket will be closed due to non activity. In seconds. Leave it empty for infinity timeout
Mostly required for local servers setup in case user want to log raw data in CSV format. See [raw data] (#raw-data-storage) section for more info.
Url for opening admin page. Must start from «/». For «/admin» url path will look like that «https://127.0.0.1:9443/admin».
Comma separated list of administrator IPs. Allow access to admin UI only for those IPs. You may set it for 0.0.0.0/0 to allow access for all. You may use CIDR notation. For instance, 192.168.0.53/24.
Default admin name and password. Will be created on initial server start
Host for reset password redirect and certificate generation. By default current server IP is taken from «eth» network interface. Could be replaced with more friendly hostname. It is recommended to override this property with your server IP to avoid possible problems of host resolving.
Email used for certificate registration, could be omitted in case you already specified it in mail.properties.
Blynk server provides administration panel where you can monitor your server. It is accessible at this URL:
WARNING Please change default admin password and name right after login to admin page. THIS IS SECURITY MEASURE.
Turn off chrome https warning on localhost
You should see highlighted text saying: «Allow invalid certificates for resources loaded from localhost». Click enable.
Blynk HTTP/S RESTful API allows to easily read and write values to/from Pins in Blynk apps and Hardware. Http API description could be found here.
Enabling sms on local server
Enabling raw data storage
By default raw data storage is disabled (as it consumes disk space a lot). When you enable it, every Blynk.virtualWrite command will be saved to DB. You will need to install PostgreSQL Database (minimum required version is 9.5) to enable this functionality:
1. Enabling raw data on server
Enable raw data in server.properties :
2. Install PostgreSQL. Option A
2. Install PostgreSQL. Option B
3. Download Blynk DB script
4. Move create_schema.sql and reporting_schema.sql to temp folder (to avoid permission problems)
Copy it to clipboard from your console.
5. Connect to PostgreSQL
6. Create Blynk DB and Reporting DB, test user and tables
You should see next output:
Now start your server and you should see next text in postgres.log file :
WARNING: Raw data may consume your disk space very quickly!
Automatic Let’s Encrypt certificates generation
Add server.host property in server.properties file. For example :
IP is not supported, this is the limitation of Let’s Encrypt. Also have in mind that myhost.com should be resolved by public DNS severs.
That’s it! Run server as regular and certificates will be generated automatically.
Manual Let’s Encrypt SSL/TLS Certificates
First install certbot on your server (machine where you going to run Blynk Server)
Generate and verify certificates (your server should be connected to internet and have open 80/443 ports)
Then add to your server.properties file (in folder with server.jar)
Generate own SSL certificates
Generate self-signed certificate and key
Convert server.key to PKCS#8 private key file in PEM format
If you connect hardware with USB script you have to provide an option ‘-s’ pointing to «common name» (hostname) you did specified during certificate generation.
As an output you’ll retrieve server.crt and server.pem files that you need to provide for server.ssl properties.
Install java for Ubuntu
or if above doesn’t work:
Port forwarding for HTTP/S API
Enabling QR generation on server
Behind wifi router
If you want to run Blynk server behind WiFi-router and want it to be accessible from the Internet, you have to add port-forwarding rule on your router. This is required in order to forward all of the requests that come to the router within the local network to Blynk server.
Blynk has a bunch of integration tests that require DB, so you have to skip tests during build.
When hardware connects to Blynk cloud it opens either keep-alive ssl/tls connection on port 443 (9443 for local servers) or keep-alive plain tcp/ip connection on port 8080. Blynk app opens mutual ssl/tls connection to Blynk Cloud on port 443 (9443 for local servers). Blynk Cloud is responsible for forwarding messages between hardware and app. In both (app and hardware) connections Blynk uses own binary protocol described below.
Hardware side protocol
Blynk transfers binary messages between the server and the hardware with the following structure:
Command | Message Id | Length/Status | Body |
---|---|---|---|
1 byte | 2 bytes | 2 bytes | Variable |
Command and Status definitions: BlynkProtocolDefs.h
Mobile app side protocol
Blynk transfers binary messages between the server and mobile app with the following structure:
Command | Message Id | Length/Status | Body |
---|---|---|---|
1 byte | 2 bytes | 4 bytes | Variable |
Websockets web side protocol
Blynk transfers binary messages between the server and websockets (for web) with the following structure:
Websocket header | Command | Message Id | Body |
---|---|---|---|
1 byte | 2 bytes | Variable |
When command code == 0, than message structure is next:
Websocket header | Command | Message Id | Response code |
---|---|---|---|
1 byte | 2 bytes | 4 bytes |
Message Id and Length are big endian. Body has a command-specific format.
How to install a local Blynk Legacy Server in your PC and get a Local Blynk Token
Blynk Legacy is a very powerful Internet of Things(IoT ) software solution which allows you to design your own IoT APP without Android and iOS APP programming knowledge.
Following tutorial will guide to install Blynk legacy server in your local Windows, Mac computer or Linux like Raspberry Pi.
Picture 1.1 shows how Blynk systems works:
Picture 1.1
From Above picture, you can see Blynk software consists three parts:
In this Lesson, we will teach students how to install Blynk Legacy local Server and setup APP and Arduino sketch code to make them working in Blynk Local Server.
Install Server on local PC
You can install local Blynk server on any computer which has Java 11 (or higher version). Java environment is a basic module which comes with those popular OS such as Windows, MacOS and Linux. So if your computer is not too old, you no need install any Java software to run Blynk server.
In this tutorial, we will teach how to install local Blynk server on Windows, MacOS and Raspbian(Raspberry Pi OS). If you use other OS, the installation is similar, just make sure you have Java 11 and JDK 8+ installed in your OS.
Install Blynk local server on Windows
3)After open the command window, go to the fold where blynk-server.jar file is saved. Test your java environment by typing following command in cmd terminal:
You should see something as following
If you can’t see java version, it means your haven’t installed Java properly, please read this article to install Java
4)Go to your download folder, replace the bold font path with your folder path
Then run following command to start the local Blynk server:
you will see following result:
Now your local Blynk server has been successfully installed and running in your Windows.
Install Blynk local server on Apple Macbook Computer
1)Download Blynk local server from https://osoyoo.com/driver/blynk/blynk-server.jar
2)Open MacBook terminal window,
Go to your download folder, Run following command to start the local Blynk server:
you will see following result:
Install Blynk local server on Raspberry Pi or similar Linux computer
1)Open your Pi shell terminal or use SSH to connect Raspberry Pi remote terminal
2)Download Blynk local server by following command
2)Go to your download folder, Run following command to start the local Blynk server:
The java server will start in one or two minutes, then you will see following result:
After that, use Ctrl-X to save and exit the file and reboot your computer. Your Blynk server will automatically start every time.
You can visit the admin page of Blynk Server url:
Cell Phone APP download and configure:
Prerequisite:
You have successfully installed Blynk server in your local computer. Next step is to install Blynk Legacy APP in your cell phone.
Before install and setup your Blynk APP, you need to know your local server’s LAN IP address first, if you don’t know how to do it, read following article:
3)Click the three dot icon in above UI to set local server IP and port.
Do following settings:
See following picture:
After you have set up the local server IP and port, you can use following steps to connect APP to local Blynk server:
If your Local Blynk is not running properly or IP address setting is wrong, APP will show Can’t connect to Server, Try later…If server running and IP setting are all ok, you will a New Project UI as following:
Congratulations! You have successfully installed local Blynk Server and connected your APP to the server.
Suppose you are using Arduino as terminal device, you click +New Project to add an Arduino project:
You can name your Project Lesson1 and select Arduino UNO (or Arduino MEGA if you are using MEGA2560),
In above UI, Click Create Project, you will see a blank project named lesson1 as following picture, In future, you can click (+) sign to add control Widget to create your APP UI
Get Auth Token
Blynk Auth token is the password to let your Arduino board to exchange project data with local Blynk server. You need to set this token in your Arduino code file in future. Token is associated with a project, so you must create a project in APP before getting a Token.
You have two methods to get Blynk Token:
After open the the file, you will see following content:
In above picture, you can see that, on the right of the word “token“, there is a long string
eVEnM2WCQykIIY9w5KPfxrzzWEUfk4N–
Method 2) Get token from local blynk control panel:
Please open your browser and visit following url:
https://your_server_ip:9443/admin
your_server_ip is the IP address of your local Blynk server.
Above https:// url default certificate is self-signed. It will therefore be considered unreliable. You will have to accept the alert message displayed by your internet browser. If you are using Google Chrome browser, You will see following alert:
Click Advanced, then select proceed to the unsafe IP as following:
You will go to Server login page, please use user name [email protected] and password admin to login to control panel.
then please click Users->[email protected]:
Click [email protected], then you will find the Token which was just assigned for your project:
Локальный сервер blynk на windows
Перевод файла с репозитория blynk-server
Автор перевода: Титенко Максим
Blynk Local Server
Платформа с приложением для iOS и Android для управления Arduino, ESP8266, Raspberry Pi и других плат микроконтроллеров через Интернет.
Скачать последнею версию сервера здесь.
Для Windows загрузите Java здесь и установите.
Быстрая настройка локального сервера
Вот и всё!
ПРИМЕЧАНИЕ: / path должен быть реальным существующим путем в папку, где вы хотите хранить все свои данные.
Blynk Server successfully started. All server output is stored in current folder in ‘logs/blynk.log’ file.
Включение почты на локальном сервере
mail.smtp.auth=true mail.smtp.starttls.enable=true mail.smtp.host=smtp.gmail.com mail.smtp.port=587 mail.smtp.username=YOUR_EMAIL_HERE mail.smtp.password=YOUR_EMAIL_PASS_HERE
Пример настройки почты здесь.
ПРЕДУПРЕЖДЕНИЕ: разрешены только учетные записи gmail.
ПРИМЕЧАНИЕ. Вам нужно настроить Gmail для работы с ненадежными приложениями. Нажмите здесь, а затем нажмите «Ненадежные приложения заблокированы ».
Быстрая настройка локального сервера на Raspberry Pi
sudo apt-get install oracle-java8-jdk
Вот и всё!
Blynk Server successfully started. All server output is stored in current folder in ‘logs/blynk.log’ file.
Включение автоматического перезапуска сервера в UNIX-системах
Сохранить и выйти.
Включение автоматического перезапуска сервера в Windows
Вы также можете использовать этот скрипт для запуска сервера.
После этого вы можете обновить приложение Blynk. Понижение версии сервера не поддерживается.
ВНИМАНИЕ! Не переустанавливайте сервер на более низкие версии. Вы можете потерять все свои данные.
Инструкцию по обновлению для Windows
Открыть диспетчер задач;
Запустить новый сервер как обычно
Изменения в приложение и эскизе
Изменить тип вашего проводного подключения к интернету с
Измените ваше WiFi подключения с
Изменить ваш Raspberry Pi Javascript c
или в случае USB при запуске blynk-ser.sh предоставить опцию «-s» с адресом вашего локального сервера
ВАЖНО Блинк постоянно развивается. Мобильные приложения и сервер часто обновляются. Чтобы избежать проблем во время обновлений, отключите автоматическое обновление для приложения Blynk или одновременно обновите локальный сервер и приложение blynk, чтобы избежать возможных проблем с миграцией.
ВАЖНО Локальный сервер Blynk отличается от сервера Blynk Cloud. Они не связаны вообще. Вы должны создать новую учетную запись при использовании локального сервера Blynk.
Расширенная настройка локального сервера
Доступные параметры сервера:
Для простоты Blynk уже предоставляет серверную банку со встроенными сертификатами SSL, поэтому у вас есть рабочий сервер из коробки через SSL / TLS-сокеты. Но поскольку сертификат и его частный ключ находятся на публике, это совершенно небезопасно. Поэтому, чтобы исправить это, вам нужно предоставить свои собственные сертификаты. И измените ниже свойства с указанием пути к вашему сертификату. и закрытый ключ, и это пароль. Узнайте, как создавать самозаверяющие сертификаты [здесь](# generate-ssl-certificate)
Указывает на cert и ключ, который помещается в ту же папку, что и jar.
server.ssl.cert=./server_embedded.crt server.ssl.key=./server_embedded.pem server.ssl.key.pass=pupkin123
Сервер Blynk предоставляет панель администрирования, где вы можете контролировать свой сервер. Она доступна по этому URL-адресу:
ПРЕДУПРЕЖДЕНИЕ Пожалуйста, измените пароль администратора и его имя сразу после входа на страницу администратора. ЭТО МЕРЫ БЕЗОПАСНОСТИ.
Отключение chrome https warning на localhost
Blynk HTTP / S RESTful API позволяет легко считывать и записывать значения в / из Pins в приложениях и оборудовании Blynk. Описание API Http можно найти здесь.
Включение смс на локальном сервере
Включение хранилища необработанных данных
1. Включение необработанных данных на сервере
Включить необработанные данные в server.properties :
2. Установите PostgreSQL. Вариант A
sudo apt-get update sudo apt-get install postgresql postgresql-contrib
2. Установите PostgreSQL. Вариант Б
3. Скачать Blynk DB скрипт
4. Переместите файл create_schema.sql в папку temp (чтобы избежать проблем с разрешением)
mv create_schema.sql /tmp
Скопируйте его в буфер обмена с консоли.
5. Подключитесь к PostgreSQL
6. Создать Blynk DB, проверить пользователя и таблицы
Вы должны увидеть следующий вывод:
postgres=# \i /tmp/create_schema.sql CREATE DATABASE You are now connected to database «blynk» as user «postgres». CREATE TABLE CREATE TABLE CREATE TABLE CREATE TABLE CREATE TABLE CREATE TABLE CREATE TABLE CREATE TABLE CREATE TABLE CREATE TABLE CREATE TABLE CREATE ROLE GRANT GRANT
Теперь запустите свой сервер, и вы увидите следующий текст в файле postgres.log :
ПРЕДУПРЕЖДЕНИЕ: Исходные данные могут очень быстро сократить пространство на диске!
значение, метка времени, DeviceId
= ((Column / (60 * 60 * 24) / 1000 + 25569))
Автоматическое создание шифрования сертификатов
IP не поддерживается, это ограничение Let’s Encrypt. Также имейте в виду, что myhost.com должны быть разрешены публичными DNS-серверами.
Это оно! Запускать сервер как обычный, а сертификаты будут генерироваться автоматически.
Руководство шифровки сертификатов SSL / TLS
server.ssl.cert = / и т.д. / letsencrypt / живой / YOUR_HOST / fullchain.pem server.ssl.key = / и т.д. / letsencrypt / живой / YOUR_HOST / privkey.pem server.ssl.key.pass =
Создание собственных сертификатов SSL
Если вы подключаете аппаратное обеспечение с помощью USB-скрипта, вы должны указать опцию ‘-s’, указывающую на «общее имя» (имя хоста), вы указанных во время создания сертификата.
В качестве вывода вы получите файлы server.crt и server.pem, которые необходимо предоставить для свойств server.ssl.
Установить java для Ubuntu
sudo apt-add-repository ppa:webupd8team/java sudo apt-get update sudo apt-get install oracle-java9-installer
sudo apt-get install oracle-java8-installer
в случае, если в вашей системе еще нет Java 9.
Перенаправление портов для API HTTP / S
Включение генерации QR на сервере
sudo apt-get install libxrender1
За маршрутизатором wifi
Если вы хотите запустить сервер Blynk за WiFi-маршрутизатором и хотите, чтобы он был доступен из Интернета, вам необходимо добавить правило переадресации портов на вашем маршрутизаторе. Это необходимо для перенаправления всех запросов, которые поступают на маршрутизатор в локальной сети на сервер Blynk.
Blynk имеет кучу интеграционных тестов, требующих DB, поэтому вам нужно пропустить тесты во время сборки.
Как работает Блинк?
Когда аппаратное обеспечение подключается к облаку Blynk, оно открывает либо соединение ssl / tls keep-alive на порту 8441, либо в режиме keep-alive plain tcp / ip на порту 8442. Приложение Blynk открывает взаимное соединение ssl / tls с Blynk Cloud на порту 443 (9443 для локальных серверов). Blynk Cloud отвечает за пересылку сообщений между оборудованием и приложением. В обоих приложениях (приложениях и оборудовании) Blynk использует собственный двоичный протокол, описанный ниже.
Blynk передает двоичные сообщения со следующей структурой:
Команда | Идентификатор сообщения | Длина / Статус | Тело |
---|---|---|---|
1 байт | 2 байта | 2 байта | Переменная |
Идентификатор сообщения и длина big endian. Тело имеет формат, специфичный для команд.
Определения команд и состояний: BlynkProtocolDefs.h
Типичная библиотека Blynk знает, как отправить (S) / процесс (P):
S BLYNK_CMD_LOGIN + токен аутентификации SP BLYNK_CMD_PING SP BLYNK_CMD_RESPONSE SP BLYNK_CMD_BRIDGE SP BLYNK_CMD_HARDWARE S BLYNK_CMD_TWEET S BLYNK_CMD_EMAIL S BLYNK_CMD_PUSH_NOTIFICATION
About
Платформа с приложением для iOS и Android для управления Arduino, ESP8266, Raspberry Pi и других плат микроконтроллеров через Интернет.