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:
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 openHABianPiFor this tutorial, I used the openHABian image for Raspberry Pi: Also, github page with download link: 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 networkVisit 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. 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 RasPiThe 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.
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:
**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:
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:
Reboot, and then confirm the RasPi can see the temp sensors by checking here:
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:
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:
example onewire.items file:
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:
Step 5: Testing the UI displayAssign your custom sitemap to the Basic UI. 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
|
R&D Publishing >