R&D Publishing‎ > ‎

OpenHab Smart Home DIY

Raspberry-Openhab-Mqtt
DIY Your Smart Home



Reference Site for configuration and install

http://www.homeautomationforgeeks.com/openhab_start.shtml
https://mcuoneclipse.com/2015/12/24/autostarting-openhab-on-raspberry-pi/
https://github.com/openhab/openhab1-addons/wiki/Linux-and-OS-X
https://openhabdoc.readthedocs.io/de/latest/Autostart/

Translate into Vietnamese

OpenHAB là phần mềm miễn phí nguồn mở có chức năng là bộ điều khiển trung tâm với khả năng nói chuyện và điều khiển rất nhiều các loại thiết bị khác nhau trong hệ thống Smart Home, kể cả các thiết bị thương mại đang bán trong lĩnh vực này.

OpenHAB được cài đặt dưới dạng một website trên máy tính Raspberry Pi. Khi truy cập vào website này từ các thiết bị như PC, smart phone hay tablet, ta có thể xem trạng thái căn nhà và điều khiển các thiết bị. Ngoài ra OpenHAB còn có một engine quản lý và thực thi các rules giúp cho căn nhà thông minh hơn bằng cách tự động điều chỉnh khi trạng thái các cảm biến thay đổi.

Cài Đặt Raspberry Pi
1 Cài Đặt Raspberry Pi
2 Mosquitto
3 Test Mosquitto
4 Cài Đặt OpenHAB
5 Cấu Hình MQTT Binding
6 Cấu Hình Các Thiết Bị (Items) và Giao Diện (Sitemap) Cho OpenHAB
7 Tự Động Chạy OpenHAB Khi Pi Khởi Động
Nếu bạn không dùng Raspberry Pi mà dùng PC chạy Windows để thay thế thì tham khảo bài này.

Nếu bạn mới mua Raspberry Pi và chưa cài đặt hệ điều hành thì bạn phải tiến hành cài đặt ban đầu trước khi cài đặt OpenHAB. Các bạn có thể tham khảo hướng dẫn rất chi tiết cách cài đặt Raspberry Pi ở đây http://codientu.org/threads/18821/ (có thể bỏ qua các bước 8 trở đi)

Mosquitto
Mosquitto là một MQTT broker nguồn mở, đóng vai trò trung gian giúp cho các chương trình và thiết bị dễ dàng trao đổi data với nhau. Data được truyền và nhận thông qua các channel (hay còn gọi là topic). Với các channel, ta có thể gửi data tới đó hoặc đăng ký nhận bất kỳ dữ liệu nào gửi tới nó.

Ví dụ, ta có 1 channel cho mỗi thiết bị cảm biến trong nhà được nhóm lại theo phòng:

/FirstFloor/Living/Temperature
/FirstFloor/Living/Humidity
/FirstFloor/Kitchen/Temperature
...
Trên OpenHAB ta sẽ tao ra giao diện gồm các item và cấu hình cho các item này đăng ký nhận dữ liệu từ các thiết bị cảm biến dùng các channel tương ứng.

Để cài đặt Mosquitto trên Raspberry Pi, copy paste các lệnh sau vào cửa sổ Putty console kết nối tới Pi:

wget http://repo.mosquitto.org/debian/mosquitto-repo.gpg.key
sudo apt-key add mosquitto-repo.gpg.key
rm mosquitto-repo.gpg.key
cd /etc/apt/sources.list.d/
sudo wget http://repo.mosquitto.org/debian/mosquitto-wheezy.list
sudo apt-get update
sudo apt-get install mosquitto mosquitto-clients python-mosquitto
Test Mosquitto
Mosquitto sẽ tự động chạy sau khi được cài đặt. Để kiểm tra, bạn mở 1 terminal khác (terminal 2) kết nối vào Pi.

Trong terminal 1 chạy lệnh lắng nghe data trên channel tên là hello/world (“-d” là yêu cầu in ra thông tin debug, “-t” là tên channel hay còn gọi là topic):

mosquitto_sub -d -t hello/world
Cho terminal 2 gửi data bất kỳ vào channel cùng tên hello/world như đăng ký trong terminal 1(“-m” là nội dung data cần gửi):

mosquitto_pub -d -t hello/world -m "Greetings from Terminal window 2"
Nếu Mosquitto đang chạy thì ta sẽ thấy message gửi đi từ terminal 2 trong terminal 1.

Cài Đặt OpenHAB
Ta sẽ install OpenHAB trong thư mục /opt/openhab:
sudo mkdir /opt/openhab
cd /opt/openhab
Download OpenHAB ở trang download page của OpenHAB dùng version mới nhất (là 1.8.2 tại thời điểm bài viết). Nếu bạn download version mới hơn thì chỉ cần thay “1.8.2” trong các command dưới đây thành version đó là được. Trước tiên ta sẽ download file core runtime, giải nén và xóa file zip:

sudo wget https://bintray.com/artifact/download/openhab/bin/distribution-1.8.2-runtime.zip
sudo unzip distribution-1.8.2-runtime.zip
sudo rm distribution-1.8.2-runtime.zip
Tiếp đến là các addons, ta sẽ download hết và bỏ vào folder riêng. Sau đó ta sẽ copy những addon nào cần mà thôi, giảm thời gian khởi động của OpenHAB:

sudo mkdir addons_repo
cd addons_repo
sudo wget https://bintray.com/artifact/download/openhab/bin/distribution-1.8.2-addons.zip
sudo unzip distribution-1.8.2-addons.zip
sudo rm distribution-1.8.2-addons.zip
Trước mắt ta chỉ cần addon binding cho MQTT:

cd /opt/openhab
sudo cp addons_repo/org.openhab.binding.mqtt-1.8.2.jar addons/org.openhab.binding.mqtt-1.8.2.jar
Cấu Hình MQTT Binding
Tạo ra file config cho OpenHAB từ file config default và sửa lại:

sudo cp /opt/openhab/configurations/openhab_default.cfg /opt/openhab/configurations/openhab.cfg
sudo nano /opt/openhab/configurations/openhab.cfg
Trong cửa sổ editor, scroll xuống phần MQTT Transport section (trong mục Transport Configurations), bỏ qua phần MQTT Persistence. Tìm đến dòng <broker>.url và <broker>.retain, bỏ dấu # ở đầu mỗi dòng và sửa thành:

mqtt:mymosquitto.url=tcp://localhost:1883
mqtt:mymosquitto.retain=true
Thoát và lưu lại (CTRL + X, Y, Enter).

Cấu Hình Các Thiết Bị (Items) và Giao Diện (Sitemap) Cho OpenHAB
Sau khi OpenHAB được cài đặt, ta cần cấu hình 2 file:

items file, chứa danh sách các thiết bị ta cần OpenHAB theo dõi và điều khiển.
sitemap file, chứa layout sắp xếp các thiết bị hiển thị trên giao diện website của OpenHAB.
Các bạn có thể download file cấu hình mẫu trong link này openhab_sample_config và giải nén. Bạn sẽ được một thư mục có một danh sách các thư mục con như sau:

sample_openhab

Upload toàn bộ các thư mục con và file openhab.cfg vào trong thư mục /opt/openhab/configurations/ trên Raspberry Pi. Các bạn có thể dùng Ftp hoặc cấu hình Samba theo hướng dẫn này để dễ dàng chuyển file qua lại giữa PC Windows và Raspberry Pi.

Danh sách các thiết bị được khai báo cho OpenHAB nằm trong file/opt/openhab/configurations/items/default.items. Trong file mẫu, ta có một nhóm tên là “All” và 3 nhóm tượng trưng cho 3 phòng trong nhà nằm trong nhóm “All”:

Group All
Group Living "Living Room" <sofa> (All)
Group Kitchen "Kitchen" <kitchen> (All)
Group Bedroom1 "Main Bedroom" <bedroom> (All)
Group Bedroom2 "Second Bedroom" <bedroom> (All)

//Living room
Number Temperature1 "Temperature [%.1f C]" <temperature> (Living) {mqtt="<[mymosquitto:/Living/Temperature:state:default]"}
Switch Light1 "Light" (Living) { mqtt="<[mymosquitto:/Living/Light/Status:state:default],>[mymosquitto:/Living/Light/Command:command:ON:1],>[mymosquitto:/Living/Light/Command:command:OFF:0]" }

//Kitchen
Number Temperature2 "Temperature [%.1f C]" <temperature> (Kitchen) {mqtt="<[mymosquitto:/Kitchen/Temperature:state:default]"}
Switch Light2 "Light" (Kitchen) { mqtt="<[mymosquitto:/Kitchen/Light/Status:state:default],>[mymosquitto:/Kitchen/Light/Command:command:ON:1],>[mymosquitto:/Living/Light/Command:command:OFF:0]" }

//Main Bedroom
Number Temperature3 "Temperature [%.1f C]" <temperature> (MainBedroom) {mqtt="<[mymosquitto:/MainBedroom/Temperature:state:default]"}
Switch Light3 "Light" (MainBedroom) { mqtt="<[mymosquitto:/MainBedroom/Light/Status:state:default],>[mymosquitto:/MainBedroom/Light/Command:command:ON:1],>[mymosquitto:/Living/Light/Command:command:OFF:0]" }

//Second Bedroom
Number Temperature4 "Temperature [%.1f C]" <temperature> (SecondBedroom) {mqtt="<[mymosquitto:/SecondBedroom/Temperature:state:default]"}
Switch Light4 "Light" (SecondBedroom) { mqtt="<[mymosquitto:/SecondBedroom/Light/Status:state:default],>[mymosquitto:/SecondBedroom/Light/Command:command:ON:1],>[mymosquitto:/Living/Light/Command:command:OFF:0]" }

Mỗi phòng đều có 1 công tắc đèn và cảm biến nhiệt độ. Ý nghĩa các tham số của cảm biến nhiệt độ:

Number: loại dữ liệu mà sensor này gửi/nhận, ta dùng Number vì nhiệt độ là số.
Temperature1/2/3/4: tên của thiết bị (item).
“Temperature [%.1f C]”: format data mình muốn hiển thị. “%.1f” là hiển thị data là số thập phân 1 số lẻ và C là độ C).
<temperature>: icon hiển thị kèm với thiết bị này (hình nhiệt kế).
(Living): nhóm mà thiết bị này thuộc về.
{mqtt=”<[mymosquitto:/Living/Temperature:state:default]”}: nguồn lấy dữ liệu. OpenHAB sẽ sử dụng MQTT tên là “mymosquitto” (giống như mình cấu hình ở phần trên) và lắng nghe data gửi tới channel tên là /Living/Temperature. “state” là loại, thể hiện là OpenHAB hiển thị trạng thái (một loại khác là “command” yêu cầu OpenHAB điều khiển) và “default” là công thức chuyển đổi data (mình không dùng trong trường hợp này). Dấu < ở đầu ý nghĩa là yêu cầu OpenHAB đọc data từ channel thay vì gửi tới đó.
Ý nghĩa các tham số của công tắc đèn:

Switch: thiết bị này là loại công tắc On/off
Light1/2/3/4: Tên thiết bị
(Living): nhóm mà thiết bị này thuộc về
<[mymosquitto:/Living/Light/Status:state:default]: Dấu < là báo cho OpenHAB biết nguồn lấy trạng thái của công tắc. OpenHAB sẽ lắng nghe trạng thái của công tắc ở channel tương ứng để cập nhật lên giao diện người dùng. Sau này chúng ta sẽ lập trình cho các công tắc điện trong phòng gửi trạng thái On/Off (khi có người bật/tắt bằng công tắc) đến cho OpenHAB ở channel tương ứng
>[mymosquitto:/Living/Light/Command:command:ON:1]: Dấu > là báo cho OpenHAB biết khi người dùng bật công tắc trên giao diện web, OpenHAB sẽ gửi lệnh tên là 1 tới channel tương ứng. Khi đó ta sẽ lập trình cho công tắc điện lắng nghe trên channel này và bật lên nếu nhận được command 1 từ OpenHAB
>[mymosquitto:/Living/Light/Command:command:OFF:0]: Tương tự cho trường hợp OFF, OpenHAB sẽ gửi đến channel tương ứng command là 0
File sitemap nằm trong thư mục /opt/openhab/configurations/sitemaps/default.sitemap

Trong sitemap, ta sẽ add một frame cho toàn bộ giao diện. Bên trong gồm 4 frame dành cho 4 phòng tương ứng:

sitemap default label="My Smart Home"
{
    Frame label="Living Room" {
        Text item=Temperature1
        Switch item=Light1
    }
 
    Frame label="Kitchen" {
         Text item=Temperature2
         Switch item=Light2
     }
 
     Frame label="Main Bedroom" {
         Text item=Temperature3
         Switch item=Light3
     }
 
     Frame label="Second Bedroom" {
         Text item=Temperature4
         Switch item=Light4
     }
}

Bạn có thể xem tài liệu hướng dẫn chi tiết cách cấu hình của OpenHAB ở link này
https://github.com/openhab/openhab/wiki/Explanation-of-items
https://github.com/openhab/openhab/wiki/Explanation-of-Sitemaps
https://github.com/openhab/openhab/wiki/MQTT-Binding
Bật OpenHAB bằng command:

sudo /opt/openhab/start.sh
OpenHAB có thể cần 1-2 phút để khởi động. Màn hình hiển thị khi chạy của OpenHAB giống như thế này:

start_openhab

Mở browser và đến URL http://192.168.1.80:8080/openhab.app (thay 192.168.1.80 bằng IP của con Pi nhà bạn) và bạn sẽ thấy giao diện OpenHAB.

openhab_fresh_rasp

Bạn có thể giả lập sensor gửi data tới OpenHAB để kiểm tra xem. Trong Putty terminal kết nối tới Pi, chạy lệnh:

mosquitto_pub -t /Living/Temperature -m 33.2
mosquitto_pub -t /Living/Light/Status -m ON

Khi đó trên giao diện OpenHAB bạn sẽ thấy số này được hiển thị ở nhiệt độ phòng Living room và công tắc đèn sẽ được bật. Ban có thể phải refresh lại trang web nếu chưa thấy data được cập nhật. Ở các bài viết sau, mình sẽ hướng dẫn xây dựng các cảm biến và gửi dữ liệu thật về cho OpenHAB

openhab_updated_rasp

Note: Dừng OpenHAB bằng CTRL+C.

Tự Động Chạy OpenHAB Khi Pi Khởi Động
Bước trên mình chạy OpenHAB bằng lệnh nhưng ta muốn OpenHAB sẽ tự động bật khi Pi khởi động. Khi đó ta không phải chạy lệnh mỗi khi mất điện hay tắt mở Pi.

Tạo ra file tên là openhab trong thư mục /etc/init.d

sudo nano /etc/init.d/openhab

Copy và paste nội dung script này vào cửa sổ editor và save lại. Gán quyền execute choa script:

#!/bin/sh
### BEGIN INIT INFO
# Provides:          openhab
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: OpenHAB Daemon
# Description: Build your smart home in no time!
### END INIT INFO


ROOT_DIR=/opt/openhab


# set path to eclipse folder. If local folder, use '.'; otherwise, use /path/to/eclipse/
eclipsehome="$ROOT_DIR/server";


# set ports for HTTP(S) server
HTTP_PORT=8080
HTTPS_PORT=8443


# get path to equinox jar inside $eclipsehome folder
cp=$(find $eclipsehome -name "org.eclipse.equinox.launcher_*.jar" | sort | tail -1);




# This next line determines what user the script runs as.
# Root generally not recommended but necessary if you are using the Raspberry Pi GPIO from Python.
#USER=root
DAEMON_USER=root
DAEMON_NAME=openhab


DAEMON=/usr/bin/java
DAEMON_ARGS="-Djna.boot.library.path=/usr/lib/jni -Dgnu.io.rxtx.SerialPorts=/dev/ttyAMA0 -Dosgi.clean=true -Declipse.ignoreApp=true -Dosgi.noShutdown=true -Djetty.port=$HTTP_PORT -Djetty.port.ssl=$HTTPS_PORT -Djetty.home=. -Dlogback.configurationFile=configurations/logback.xml -Dfelix.fileinstall.dir=addons -Djava.library.path=lib -Djava.security.auth.login.config=./etc/login.conf -Dorg.quartz.properties=./etc/quartz.properties -Dequinox.ds.block_timeout=240000 -Dequinox.scr.waitTimeOnBlock=60000 -Dfelix.fileinstall.active.level=4 -Djava.awt.headless=true -jar $cp $* -console "
PIDFILE=/var/run/$DAEMON_NAME.pid


. /lib/lsb/init-functions

do_start() {      
  log_daemon_msg "Starting system $DAEMON_NAME daemon"
  start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --user $DAEMON_USER --chuid $DAEMON_USER --chdir $ROOT_DIR --exec $DAEMON -- $DAEMON_ARGS
  log_end_msg $?
}
do_stop() {
  log_daemon_msg "Stopping system $DAEMON_NAME daemon"
  start-stop-daemon --stop --pidfile $PIDFILE --retry 10
  log_end_msg $?
}

case "$1" in

    start|stop)
        do_${1}
        ;;

    restart|reload|force-reload)
        do_stop
        do_start
        ;;

    status)
        status_of_proc "$DAEMON_NAME" "$DAEMON" && exit 0 || exit $?
        ;;
    *)
        echo "Usage: /etc/init.d/$DAEMON_NAME {start|stop|restart|status}"
        exit 1
        ;;

esac
exit 0


sudo chmod 777 /etc/init.d/openhab
Bật script này chạy khi Pi khởi động:

sudo update-rc.d openhab defaults
Bạn có thể dùng các lệnh sau để start, stop, restart và xem status hiện tại của OpenHAB:

sudo /etc/init.d/openhab start
sudo /etc/init.d/openhab status
sudo /etc/init.d/openhab stop
sudo /etc/init.d/openhab restart
 

Bạn có thể xóa script đi nếu muốn làm lại:

sudo update-rc.d -f openhab remove

CHANGE OPENHAB TO ROOT USER FOR EXE BINDING

When changing USER_AND_GROUP on Raspian Jessie Debian distr. to root do the following:

1> /etc/default/openhab - change to root (USER_AND_GROUP=root:root)
2> /usr/lib/systemd/system/openhab.service
- change user and group inside the file
User=root
Group=root
- systemctl daemon-reload
- systemctl start openhab

Pretty simple when you know what to change. Maybe we can document it somewhere?


DS18B20 One wire GPIO with openHab

Step 1: Install and configure openHABianPi

For this tutorial, I used the openHABian image for Raspberry Pi: 
http://docs.openhab.org/installation/openhabian.html4

Also, github page with download link:
https://github.com/openhab/openhabian/releases5

Follow the instructions on the link above to download the .img file, flash to SD card, boot up Pi, wait approximately 45min. It's really that simple.

Connect power and Ethernet to your RasPi, and you should now have a working openHAB with SSH access.

Step 2: Build 1-wire sensor network

Visit the manufacturer's reference document here to help with properly building your network of (wired) 1-wire sensors: https://www.maximintegrated.com/en/app-notes/index.mvp/id/1485

Connect the 1-wire sensors to GPIO pin 4 on the RasPi. 
Below is an example breadboard configuration of the connections on an original Raspberry Pi model B. 
3.3V, GND, and GPIO pin 4 (as labeled) are the only connections on the RasPi side. Once I confirmed this was working I then used CAT-5 cable to run the temp sensors to different rooms of my house.

Note: the 4.7k pull-up resistor on the data pin of the DS18b20. Only one of these is required in total for the 1-wire network. Also note that the RasPi is used to power the 1-wire sensor network so keep that in mind and make sure your RasPi power supply is adequate. This setup is working successfully for me with a 2-amp power supply.

Step 3: Reading Temperature sensors through GPIO on RasPi

The 1-wire Binding for openHAB relies on ow-server, and is therefore limited to serial, USB, or network sockets/tcp for the 1-wire connection. There is no current configuration for GPIO sensors, so instead you will need to use Exec Binding and a script that polls the sensors.
There is a good starter script here: http://www.itbasic.de/openhab-onewire-sensoren-einbinden/13
Below is a modified script for those of us in the USA, which converts the output value to Fahrenheit:

#!/bin/bash
wert=`cat /sys/bus/w1/devices/$1/w1_slave | tail -n1 | cut -d '=' -f2`   
wert2=`echo "scale=3; $wert/1000 * 9.0 / 5.0 + 32.0" | bc`
echo $wert2

Save this script to /etc/openhab2/scripts for use later. Next, configure the RasPi to load the 1-wire devices at boot: **Option 1:SSH into your openHABianPi, and nevigate to /boot. Then use vi or your favorite text editor to open the RasPi config.txt file:

pi@openHABianPi:~$ cd /boot
pi@openHABianPi:/boot$ sudo vi config.txt

**Or, option 2:Power down your RasPi and put the SD card in your PC to access the FAT formatted boot partition. With either method, once you open config.txt, add the following line:

dtoverlay=w1-gpio,gpiopin=4

Note that the config.txt that comes with openHABian contains 3 sections for the various version of RasPi’s: 1, 2, and 3, so the correct section must be modified for the corresponding RasPi version. So, for my Pi model B (aka Pi1), my config.txt looks like this:

[pi1]
kernel=vmlinuz-4.4.0-1-rpi
initramfs initrd.img-4.4.0-1-rpi followkernel
# to disable DeviceTree, uncomment the next line 
device_tree=
dtoverlay=w1-gpio,gpiopin=4

Reboot, and then confirm the RasPi can see the temp sensors by checking here:

pi@openHABianPi:/boot$ cd /sys/bus/w1/devices
pi@openHABianPi:/sys/bus/w1/devices$ ls
28-xxxxxxxxxxxx  28-xxxxxxxxxxxx  28-xxxxxxxxxxxx  w1_bus_master1

If the w1 directory does not exist, the 1-wire driver was not loaded, and you need to check config.txt and make sure it is correct. The 1-wire temp sensors each have a UID (28-xxxxxxxxxxxx) that is displayed in this folder. This UID must be specified when running the sample script. Now that you know your RasPi can see the sensors, head to the scripts folder where you previously saved the 1-wire script. Manually run the script and include the UID of one of your identified sensors. You should get a temperature value output:

pi@openHABianPi:/etc/openhab2/scripts$ sudo bash ./onewiretemp.sh 28-xxxxxxxxxxxx
70.586

If you receive an error, double check the UID, try a different sensor UID, and also check your script for syntax errors. ## Step 4: Creating the openHAB items, things, sitemap, etc The next step is to install Exec Binding, and created the appropriate openHAB files (optionally you may use the wizards to create things and items). In openHAB’s Paper UI (http://192.168.blah.blah:8080/paperui/index.html), the Exec Binding can be installed by navigating to: Add-ons>Bindings>Exec Binding <img src="//community-openhab-org.s3-eu-central-1.amazonaws.com/original/2X/9/9edbb2e596cda7cd0d3889f3b00cc46615441dd7.png" width="690" height="210"> **Next, create things and items files, and place them in their respective openHAB folders:** /etc/openhab2/things and /etc/openhab2/items example onewire.things file:

exec:command:onewiretemp1 [command="bash /etc/openhab2/scripts/onewiretemp.sh 28-xxxxxxxxxxxx"]
exec:command:onewiretemp2 [command="bash /etc/openhab2/scripts/onewiretemp.sh 28-xxxxxxxxxxxx"]
exec:command:onewiretemp3 [command="bash /etc/openhab2/scripts/onewiretemp.sh 28-xxxxxxxxxxxx"]

example onewire.items file:

String onewiretemp1Value "Temp 1 is [%s °F]" {channel="exec:command:onewiretemp1:output"}
String onewiretemp2Value "Temp 2 is [%s °F]" {channel="exec:command:onewiretemp2:output"}
String onewiretemp3Value "Temp 3 is [%s °F]" {channel="exec:command:onewiretemp3:output"}

It is important that you specify “output” for the channel that links the item to the thing. Other value options will not work with this ‘script method’ . Sample sitemap entries:

Frame label="Environment" {
Text label=”Temperatures” icon=”temperature_hot” {
Text item=onewiretemp1Value
Text item=onewiretemp2Value
Text item=onewiretemp3Value
}

Step 5: Testing the UI display

Assign your custom sitemap to the Basic UI. 
You can do this through Paper UI>Configuration>Services>BasicUI>Configure.

You should now have a fully functioning 1-wire temperature sensor network, displaying live temps:


LOCATION FILE FOR OPENHAB INSTALL BY APT-GET INSTALL METHOD

/usr/share/openhab


Set the autostart of openHAB

The Linux system on the Raspberry PI can be set up so that openHAB is started automatically when it is restarted. A precondition for the correct operation of the following instructions is an installation of openHAB following the steps of the previous instructions. If openHAB was not installed according to this guide, the paths must be adapted accordingly. Depending on the used init system using the installed Linux, one of the two solutions must be used. The command cat /proc/1/commcan be used to determine which init system is using the installed Linux version.

Autostart with systemd

(For current Linux versions, for example, Raspbian Jessy)

In order for openHAB to start automatically at boot time, the two script files openhab and openhab.service are required. 
The files to download, unpack, and then copy my WINSCP or USB stick on the Paspberry PI.

If you are using modbus serial binding please add -Dgnu.io.rxtx.SerialPorts=/dev/ttyAMA0:/dev/ttyS0 to Java 

The script file openhab:

#! /bin/sh
# Author: Pierre Metzner

# set path to openhab
OPENHAB_PATH=/opt/openhab

# set ports for HTTP(S) server
HTTP_PORT=8080
HTTPS_PORT=8443

# change directory to openHAB runtime
cd $OPENHAB_PATH

# get path to equinox jar inside $OPENHAB_PATH folder
cp=$(find ./server -name "org.eclipse.equinox.launcher_*.jar" | sort | tail -1);

# starting openHAB
echo "Launching the openHAB runtime.."
java -Dgnu.io.rxtx.SerialPorts=/dev/ttyAMA0:/dev/ttyS0 -Dosgi.clean=true -Declipse.ignoreApp=true -Dosgi.noShutdown=true -Djetty.port=$HTTP_PORT -Djetty.port.ssl=$HTTPS_PORT -Djetty.home=. -Dlogback.configurationFile=configurations/logback.xml -Dfelix.fileinstall.dir=addons -Djava.library.path=lib -Djava.security.auth.login.config=./etc/login.conf -Dorg.quartz.properties=./etc/quartz.properties -Dequinox.ds.block_timeout=240000 -Dequinox.scr.waitTimeOnBlock=60000 -Djava.awt.headless=true -jar $cp -console &> /dev/null
exit 0

The autostart script openhab.service:

[Unit]
Description=A vendor and technology agnostic open source automation software for your smart home.
After=network.target

[Service]
Type=forking
ExecStart=/usr/bin/openhab

[Install]
WantedBy=multi-user.target

After the files have been downloaded and unpacked, copy them to the Raspberry PI in the following directories.

  • Copy the script file openhab to the directory / usr / bin
  • Copy the autostart script openhab.service to / etc / systemd / system

To set the autostart, the following steps must be carried out on the Raspberry:

  1. Change to the directory where the script open / is copied
    cd /usr/bin

  2. Change the file properties so that it can be executed
    sudo chmod a+x openhab

  3. Change the group and owner of the file
    sudo chgrp root openhab
    sudo chown root openhab

  4. Checking the changes 
    ls -l
    The output should look as follows:
    -rwxr-xr-x 1 root root 1757 Apr 16 23:27 openhab

  5. If steps 1-4 have been carried out, openHAB can be started and terminated with the following commands: 
    sudo service openhab startstarted 
    sudo service openhab stopstopped and queried with 
    sudo service openhab statusthe status

  6. Finally, the system must be instructed to start openhab at booting
    sudo systemctl enable openhab.service

Additional links: - https://wiki.ubuntuusers.de/Dienste/ - https://wiki.ubuntuusers.de/systemd/

Autostart with SysVinit

(For older Linux versions, such as Raspbian Wheezy or Debia Wheety)

For openHAB to start automatically when booting, the two script files openhab and openhab.cfg are needed. 
Simply download the files , unzip them and then copy them to the Paspberry PI using WINSCP or USB stick.

The script file openhab:

#! /bin/sh
### BEGIN INIT INFO
# Provides:          starts openhab from home
# Required-Start:    $local_fs $network $named $portmap $remote_fs $syslog $time
# Required-Stop:     $local_fs $network $named $portmap $remote_fs $syslog $time
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Kurze Beschreibung
# Description:       Längere Bechreibung
### END INIT INFO
# Author:

# set ports for HTTP(S) server
HTTP_PORT=8080
HTTPS_PORT=8443

if test -f /etc/default/openhab.conf; then
    . /etc/default/openhab.conf
else
    echo "Please set OPENHABPATH in /etc/default/openhab.conf"
    exit 1
fi

# Aktionen
case "$1" in
    start)
        if [ -f /var/run/openhab.pid ]; then
                echo "openhab seems to run allready. If not, please delete /var/run/openhab.pid"
        else

                cd $OPENHABPATH
                # get path to equinox jar inside $OPENHABPATH folder
                cp=$(find ./server -name "org.eclipse.equinox.launcher_*.jar" | sort | tail -1);

                echo Launching the openHAB runtime..
                java -Dosgi.clean=true -Declipse.ignoreApp=true -Dosgi.noShutdown=true -Djetty.port=$HTTP_PORT -Djetty.port.ssl=$HTTP$

                echo $! > /var/run/openhab.pid
        fi
        ;;
    stop)
        echo "stopping openhab"
        kill `cat /var/run/openhab.pid`
        rm /var/run/openhab.pid
        ;;
    restart)
        echo "does not work"
        ;;
esac

exit 0

The configuration file openhab.cfg

# PATH TO OPENHAB
OPENHABPATH=/opt/openhab

# set ports for HTTP(S) server
HTTP_PORT=8080
HTTPS_PORT=8443

After the files have been downloaded and unpacked, copy them to the Raspberry PI in the following directories.

  • Copy the script file openhab to the /etc/init.d/ directory
  • Copy the configuration file openhab.cfg to / etc / default

In order to set the autostart, the following steps must now be carried out on the Raspberry:

  1. Change to the directory where the script open / is copied
    cd /etc/init.d

  2. Change the file properties so that it can be executed
    sudo chmod a+x openhab

  3. Change the group and owner of the file
    sudo chgrp root openhab
    sudo chown root openhab

  4. Checking the changes 
    ls -l
    The output should look as follows:
    -rwxr-xr-x 1 root root 1757 Apr 13 23:27 /etc/init.d/openhab

  5. Change to the directory where the configuration file openhab.cfg is copied
    ch /etc/default

  6. After the script is executable, it must be entered into the runnnlevel. 
    Execute the following command:
    sudo update-rc.d openhab defaults

  7. Now openhab can use the command 
    sudo /etc/init.d/openhab startstarts with bez sudo /etc/init.d/openhab stopbe stopped.

Install Oracle Java 8 on Debian Jessie and Raspbian Jessie Via PPA

Update Java 8 for raspberry Pi to run cloud connector Openhab

https://www.linuxbabe.com/desktop-linux/install-oracle-java-8-debian-jessie-raspbian-jessie-via-ppa

In a previous tutorial, I showed you how to install Oracle Java 8 on Ubuntu, Linux Mint and Elementary OS via PPA. You can also use the same PPA to install Oracle Java 8 on Debian Jessie and Raspbian Jessie. But the process of adding PPA to Debian and Raspbian is a little different. So I dedicated a whole article to guide you through the process.

Install Oracle Java 8 on Debian Jessie and Raspbian Jessie

Step1: Add the PPA and install Oracle Java 8

First remove OpenJDK

sudo apt-get remove openjdk*

Next, fetch the GPG signing key for this PPA with this command:

sudo apt-key adv --recv-key --keyserver keyserver.ubuntu.com EEA14886

Then, edit /etc/apt/sources.list file.

sudo nano /etc/apt/sources.list

Append the following two lines at the end of the file.

deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main 
deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main

Save and close the file. Now update local package index and install Oracle Java 8.


sudo apt-get update

sudo apt-get install oracle-java8-installer

oracle-java8-installer is not the Java binary. Instead it’s a installer that can fetch Java binary from Oracle website and then install it on your Debian or Raspbian machine.

Install Oracle Java 8 on Debian

Step2: Check Version.

Once the installation is complete, we can check Oracle Java version with this command:

java -version

Install Oracle Java 8 on Debian and Raspbian

Check Java compiler version.

javac -version

Install Oracle Java 8 on Debian and Raspbian

Step3: Set Java Environment Variables


n order to let Debian or Raspbian to know where Java JDK and JRE is located, we need to set environment variables. Run the following command to set Java environment variables.

sudo apt-get install oracle-java8-set-default

Once installed, there will be two new files under /etc/profile.d/ directory: jdk.csh and jdk.sh. These two files are shell scripts that contains commands to set 5 enviroment variables. We can use cat command to check out its content.

cat /etc/profile.d/jdk.sh

Output:

export J2SDKDIR=/usr/lib/jvm/java-8-oracle
export J2REDIR=/usr/lib/jvm/java-8-oracle/jre
export PATH=$PATH:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin
export JAVA_HOME=/usr/lib/jvm/java-8-oracle
export DERBY_HOME=/usr/lib/jvm/java-8-oracle/db

What we need to do is to use the source command to execute the /etc/profile bash shell script to let these environment variables to take effect.

source /etc/profile

source is used specifically to execute commands in a shell script. If you are using the bash shell, then source can be abbreviated to a dot like this:

. /etc/profile

This has the same effect. Now you can check these 5 environment variables like below:

echo $JAVA_HOME

Install Oracle Java 8 on Debian and Raspbian

As you can see, the process of installing Oracle Java 8 on Debian Jessie and Raspbian Jessie via PPA is roughly the same, except that the method of adding PPA is little bit different.

Comments