How to make friends OpenHAB and Arduino
We all want to make life better, add technical innovations to our home, automate it and make it safer. Often these desires turn into a rake movement. It is known that proprietary systems are often expensive and not compatible with each other, and not every professional can create his own solution. What to do, how to find a simple solution accessible to amateurs, but also interesting to professionals?
Arduino is a simple electronic designer that is well-respected by amateurs, they say that professionals dislike it, although they secretly use it in their terrible experiments. What is the secret of its popularity, how to use it to solve our problem?
Arduino is suitable for local monitoring and control in the house, there are a lot of projects on the network for this - excellent, but not enough, because you need to think globally! We need a network connection and a mobile interface!
It’s good that thanks to this article we are already familiar with OpenHAB, an open source platform that combines a large number of devices with different protocols into a single network. OpenHAB is implemented in Java, therefore it works in various OSs, it can be run on a single-board computer and even a router, it has a mobile and Web interface. Sounds like a good set of spells against ours, already bored rake, check?
First, install OpenHAB , open the download page, download Runtime core and Demo setup, unpack them in C: \ openhab. When unpacking the Demo setup, we will allow the replacement of the README.txt file. If Java is not available on the computer (check with the java –version command), then install it in accordance with the instructions .
Now run OpenHAB by doing C: \ openhab \ start.bat, wait a bit and open the Web interface - localhost : 8080 / openhab.app? Sitemap = demo
(if we need to stop OpenHAB - press Ctl + C or close the program console)

It works! Let's continue. Our goal is to find a simple solution, so let's start with the experiments. In one of the comments on the articleIt was proposed to connect the controller to OpenHub via the serial port using Serial-Binding. Quite an interesting solution, try to implement it.
To install the add-on, open the download page , download Addons, unpack org.openhab.binding.serial-1.6.1.jar (the version of the plugin may differ) in the C: \ openhab \ addons folder. If desired, read the documentation .
Since debugging interaction with a real device is usually a lot of trouble, let's try to send commands through the terminal first, connecting it to OpenHAB via a null modem cable emulator.
Download and install com0com emulator , run the utility
Setup from the program menu and we see that during installation a virtual pair of serial ports is already created - I have COM35 + COM36. We will use them in our work.

I used Hercules SETUP utility as a terminal , this is a free program that allows you to select ports with large numbers and enter several commands, sending them by pressing the appropriate button. Download it, run hercules_3-2-8.exe, go to the “Serial” tab, select the second port of the virtual pair (I have COM36) and enter the following settings - speed 9600, 8 bits, 1 stop bit, no parity. We open the port.

Now you need to configure openHAB, for this we will use its designer. Open the download page, download openHAB Designer and unpack it into the C: \ openhab \ designer folder, run C: \ openhab \ designer \ openHAB-Designer.exe and specify the folder in which the configuration is located - C: \ openhab \ configurations.

First, create an item and associate it with the first serial port in the virtual pair (I have COM35). To do this, add the following code to the end of the demo.items file, then right-click in the editor window and use the command “Save”, instead you can simply press ctl + S.

For testing, we write a rule that will send a command to the created element every minute. To do this, add the following code to the end of the demo.rules file and then save it.

If OpenHAB is running, we will almost immediately begin to accept the text of the command in the terminal program, and in the console we will see a report on its progress:

Now let's try to send the commands to OpenHAB. In the terminal, enter the text “ON_1” in the first field of the “Send” panel and “OFF_1” in the second. Press the first “Send” button, then the second. As a result of this, the following messages appear in the console:

To ensure that our efforts are not wasted, we will create a rule that will process our commands. To do this, add the following code to the end of the demo.rules file and save it.
Open the WEB interface, click on the item “First Floor” then on the item “Corridor” or copy the link to the browser: localhost : 8080 / openhab.app? Sitemap = demo # _FF_Corridor, send the text “ON_1”, and then OFF_1 ”from the terminal. We will control the switch in the WEB application, its state should change.

Now click “Home”, select “Ground Floor” then “Kitchen” or copy the link in the browser: localhost : 8080 / openhab.app? Sitemap = demo # _GF_Kitchen, send the text “ON_2” and then “OFF_2” from the terminal . We will control the switch in the WEB application, its state should also change.

The result of our experiment can be observed in the application console, in which the following messages will appear:

Everything works on a computer, it's time to connect to the real world!
Most Arduino boards already have an adapter from a COM port to USB, so we won’t have any problems connecting to a computer or laptop. We will assemble the layout from the tools at hand, for this we need an Arduino controller, a breadboard, wires, a button, an LED, 10k and 1k ohm resistors.

There are enough instructions and examples on the network, so you do not need to describe in detail the installation process and work in the development environment for Arduino. We proceed immediately to the creation of a simple sketch that will process a button press and send text commands through the serial port. In order to avoid false sending of commands, we will add a simple protection against contact bounce to the sketch.
Open the editor, add the following code to it, and save the sketch in the btn.ino file.

We compile and load the sketch into Arduino, open the port monitor, select the speed of 9600 and try to press the button on the board. As a result, we can observe the receipt of commands:

Now close the port monitor and configure the OpenHAB connection with the controller, for this we will edit the settings of our element (in my case, you need to change the value to COM18 since the Arduino USB adapter is installed on this port).
At the end, we will control the passage of commands using the console and WEB interface.
What we got as a result of our work:
1 installed, configured OpenHAB, learned how to add items (item) and automate processing using rules (rule);
2 learned to test the exchange using software tools. These tools will help in the future when troubleshooting and in setting up their own experiments;
3 made the simplest sketch for Arduino, connected it to OpenHAB, created a rule that processes text commands, tested the ability to control via the serial port.
Conclusions:
Sending commands in text form is common in Arduino practice; processing of such commands can be implemented in OpenHAB, therefore this method of interaction deserves attention and discussion.
The disadvantage of this solution is that the teams are not separated by anything except a pause, this can lead to their “sticking together” and unreliable processing. To solve this problem, you need to modify the sketch and the rule for processing commands or make changes to the Serial-Binding module.
Many will call this option of interaction with OpenHAB amateur, so before continuing to work on it, we will try to connect OpenHAB and Arduino through the Modbus protocol.
About this in the following publications:
Arduino & Modbus habrahabr.ru/post/249043
Arduino & OpenHABhabrahabr.ru/post/252555
Open smart home controller based on Arduino vk.com/myremoter
Arduino is a simple electronic designer that is well-respected by amateurs, they say that professionals dislike it, although they secretly use it in their terrible experiments. What is the secret of its popularity, how to use it to solve our problem?
Arduino is suitable for local monitoring and control in the house, there are a lot of projects on the network for this - excellent, but not enough, because you need to think globally! We need a network connection and a mobile interface!
It’s good that thanks to this article we are already familiar with OpenHAB, an open source platform that combines a large number of devices with different protocols into a single network. OpenHAB is implemented in Java, therefore it works in various OSs, it can be run on a single-board computer and even a router, it has a mobile and Web interface. Sounds like a good set of spells against ours, already bored rake, check?
First, install OpenHAB , open the download page, download Runtime core and Demo setup, unpack them in C: \ openhab. When unpacking the Demo setup, we will allow the replacement of the README.txt file. If Java is not available on the computer (check with the java –version command), then install it in accordance with the instructions .
Now run OpenHAB by doing C: \ openhab \ start.bat, wait a bit and open the Web interface - localhost : 8080 / openhab.app? Sitemap = demo
(if we need to stop OpenHAB - press Ctl + C or close the program console)
It works! Let's continue. Our goal is to find a simple solution, so let's start with the experiments. In one of the comments on the articleIt was proposed to connect the controller to OpenHub via the serial port using Serial-Binding. Quite an interesting solution, try to implement it.
To install the add-on, open the download page , download Addons, unpack org.openhab.binding.serial-1.6.1.jar (the version of the plugin may differ) in the C: \ openhab \ addons folder. If desired, read the documentation .
Since debugging interaction with a real device is usually a lot of trouble, let's try to send commands through the terminal first, connecting it to OpenHAB via a null modem cable emulator.
Download and install com0com emulator , run the utility
I used Hercules SETUP utility as a terminal , this is a free program that allows you to select ports with large numbers and enter several commands, sending them by pressing the appropriate button. Download it, run hercules_3-2-8.exe, go to the “Serial” tab, select the second port of the virtual pair (I have COM36) and enter the following settings - speed 9600, 8 bits, 1 stop bit, no parity. We open the port.
Now you need to configure openHAB, for this we will use its designer. Open the download page, download openHAB Designer and unpack it into the C: \ openhab \ designer folder, run C: \ openhab \ designer \ openHAB-Designer.exe and specify the folder in which the configuration is located - C: \ openhab \ configurations.
First, create an item and associate it with the first serial port in the virtual pair (I have COM35). To do this, add the following code to the end of the demo.items file, then right-click in the editor window and use the command “Save”, instead you can simply press ctl + S.
String Serial_string "Текст [%s]" { serial="COM35" }
For testing, we write a rule that will send a command to the created element every minute. To do this, add the following code to the end of the demo.rules file and then save it.
rule "Test serial string"
when
System started or
Time cron "0 * * * * ?"
then
Serial_string.sendCommand("Test")
end
If OpenHAB is running, we will almost immediately begin to accept the text of the command in the terminal program, and in the console we will see a report on its progress:
Now let's try to send the commands to OpenHAB. In the terminal, enter the text “ON_1” in the first field of the “Send” panel and “OFF_1” in the second. Press the first “Send” button, then the second. As a result of this, the following messages appear in the console:
To ensure that our efforts are not wasted, we will create a rule that will process our commands. To do this, add the following code to the end of the demo.rules file and save it.
rule "Serial control"
when
Item Serial_string received update
then
if(Serial_string.state=="ON_1") sendCommand(Light_FF_Corridor_Ceiling, ON)
if(Serial_string.state=="OFF_1") sendCommand(Light_FF_Corridor_Ceiling, OFF)
if(Serial_string.state=="ON_2") sendCommand(Light_GF_Kitchen_Ceiling, ON)
if(Serial_string.state=="OFF_2") sendCommand(Light_GF_Kitchen_Ceiling, OFF)
end
Open the WEB interface, click on the item “First Floor” then on the item “Corridor” or copy the link to the browser: localhost : 8080 / openhab.app? Sitemap = demo # _FF_Corridor, send the text “ON_1”, and then OFF_1 ”from the terminal. We will control the switch in the WEB application, its state should change.
Now click “Home”, select “Ground Floor” then “Kitchen” or copy the link in the browser: localhost : 8080 / openhab.app? Sitemap = demo # _GF_Kitchen, send the text “ON_2” and then “OFF_2” from the terminal . We will control the switch in the WEB application, its state should also change.
The result of our experiment can be observed in the application console, in which the following messages will appear:
Everything works on a computer, it's time to connect to the real world!
Most Arduino boards already have an adapter from a COM port to USB, so we won’t have any problems connecting to a computer or laptop. We will assemble the layout from the tools at hand, for this we need an Arduino controller, a breadboard, wires, a button, an LED, 10k and 1k ohm resistors.
There are enough instructions and examples on the network, so you do not need to describe in detail the installation process and work in the development environment for Arduino. We proceed immediately to the creation of a simple sketch that will process a button press and send text commands through the serial port. In order to avoid false sending of commands, we will add a simple protection against contact bounce to the sketch.
Open the editor, add the following code to it, and save the sketch in the btn.ino file.
// задаем константы
const int buttonPin = 2; // номер входа, подключенный к кнопке
const int ledPin = 13; // номер выхода светодиода
// переменные
int buttonState = 3; // переменная для хранения состояния кнопки
int buttonCnt = 0; // переменная для защиты от дребезга кнопки
void setup() {
// инициализируем пин, подключенный к светодиоду, как выход
pinMode(ledPin, OUTPUT);
// инициализируем пин, подключенный к кнопке, как вход
pinMode(buttonPin, INPUT);
// настраиваем последовательный порт
Serial.begin(9600);
}
void loop(){
// обработка дребезга кнопки
delay(1);
if (buttonState != digitalRead(buttonPin)) buttonCnt++; else buttonCnt = 0;
if (buttonCnt > 100)
{
// считываем значения с входа кнопки
buttonState = digitalRead(buttonPin);
buttonCnt = 0;
// проверяем нажата ли кнопка
// если нажата, то buttonState будет LOW:
if (buttonState == LOW) {
// включаем светодиод
digitalWrite(ledPin, HIGH);
// отправляем команду
Serial.print("ON_1");
} else {
// выключаем светодиод
digitalWrite(ledPin, LOW);
// отправляем команду
Serial.print("OFF_1");
}
}
}
We compile and load the sketch into Arduino, open the port monitor, select the speed of 9600 and try to press the button on the board. As a result, we can observe the receipt of commands:
Now close the port monitor and configure the OpenHAB connection with the controller, for this we will edit the settings of our element (in my case, you need to change the value to COM18 since the Arduino USB adapter is installed on this port).
String Serial_string "Текст [%s]" { serial="COM18" }
At the end, we will control the passage of commands using the console and WEB interface.
What we got as a result of our work:
1 installed, configured OpenHAB, learned how to add items (item) and automate processing using rules (rule);
2 learned to test the exchange using software tools. These tools will help in the future when troubleshooting and in setting up their own experiments;
3 made the simplest sketch for Arduino, connected it to OpenHAB, created a rule that processes text commands, tested the ability to control via the serial port.
Conclusions:
Sending commands in text form is common in Arduino practice; processing of such commands can be implemented in OpenHAB, therefore this method of interaction deserves attention and discussion.
The disadvantage of this solution is that the teams are not separated by anything except a pause, this can lead to their “sticking together” and unreliable processing. To solve this problem, you need to modify the sketch and the rule for processing commands or make changes to the Serial-Binding module.
Many will call this option of interaction with OpenHAB amateur, so before continuing to work on it, we will try to connect OpenHAB and Arduino through the Modbus protocol.
About this in the following publications:
Arduino & Modbus habrahabr.ru/post/249043
Arduino & OpenHABhabrahabr.ru/post/252555
Open smart home controller based on Arduino vk.com/myremoter