Необходимо создать пустой файл с именем ssh в корне флеш-карты.

По умолчанию логин — pi, а пароль — raspberry

Подключение по SSH

sudo apt-get update
sudo apt-get upgrade


sudo apt-get install python-smbus

sudo apt-get install mosquitto

sudo apt-get install python3-pip

sudo pip3 install paho-mqtt

# Библиотека работы с GPIO
sudo apt-get install rpi.gpio



# Установка Icinga2
sudo apt-get install icinga2
sudo apt-get install nagios-plugins

sudo icinga2 node wizard
Включение автоматической проверки и восстановления диска

Добавить в файл /boot/cmdline.txt:

fsck.mode=force

Убедитесь, что файл остается одной строкой. Параметры должны быть разделены пробелами.

Добавляем мониторинг температуры процессора с отправкой в MQTT
#!/usr/bin/env python3
import paho.mqtt.publish as publish
from subprocess import check_output
from re import findall

def get_temp():
    temp = check_output(["vcgencmd","measure_temp"]).decode("UTF-8")
    return(findall("\d+\.\d+",temp)[0])

def publish_message(topic, message):
    print("Publishing to MQTT topic: " + topic)
    print("Message: " + message)

    publish.single(topic, message, hostname="192.168.1.16")

temp = get_temp()
publish_message("/device/rpi_54/temperature", temp)

Добавим в crone:

crontab -e


*/1 * * * * /home/pi/cputemp.py
Сервис управления GPIO

Скрипт /home/pi/mqtt/mqtt_relay_onoff.py:

#!/usr/bin/env python3
#

import RPi.GPIO as GPIO
import time
import paho.mqtt.client as mqtt


Relay = [5, 6, 13, 16, 19, 20, 21, 26]

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

for i in range(0,8):
    GPIO.setup(Relay[i], GPIO.OUT)
    GPIO.output(Relay[i], GPIO.HIGH)



def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe([("/openhab/items/rpi_54_relay1",0),("/openhab/items/rpi_54_relay2",0),("/openhab/items/rpi_54_relay3",0),("/openhab/items/rpi_54_relay4",0),("/openhab/items/rpi_54_relay5",0),("/openhab/items/rpi_54_relay6",0),("/openhab/items/rpi_54_relay7",0),("/openhab/items/rpi_54_relay8",0)])


def on_message(client, userdata, msg):
    msgload = msg.payload.decode()
    msgtopic = msg.topic
    msgrelay = int(msgtopic[-1])-1
    ## rpi_54_relay3 - нормально замкнуто (NC), поэтому переворачиваем, остальные нормально открытые (NO)
    if (msgrelay == 2):
        if (msgload == "OFF"):
                GPIO.output(Relay[msgrelay],GPIO.LOW)
                #print("Relay "+str(msgtopic[-1]))
        else:
                GPIO.output(Relay[msgrelay],GPIO.HIGH)
    else:
        if (msgload == "ON"):
                GPIO.output(Relay[msgrelay],GPIO.LOW)
                #print("Relay "+str(msgtopic[-1]))
        else:
                GPIO.output(Relay[msgrelay],GPIO.HIGH)


client = mqtt.Client()
client.connect("127.0.0.1",1883,60)

client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()

Создать файл /etc/systemd/system/mqttrelay.service

[Unit]
Description=MQTT GPIO relay service
After=multi-user.target

[Service]
Type=idle
ExecStart=/usr/bin/python3 "/home/pi/mqtt/mqtt_relay_onoff.py"
Restart=always

[Install]
WantedBy=multi-user.target

Регестрируем сервис и запускаем:

sudo systemctl daemon-reload
sudo systemctl enable mqttrelay.service
sudo systemctl start mqttrelay.service
Установка OpenHAB2
sudo apt-get install openjdk-8-jdk-headless -y
sudo apt-get install openjdk-8-jdk -y

java -version



wget -qO - 'https://bintray.com/user/downloadSubjectPublicKey?username=openhab' | sudo apt-key add -
echo 'deb https://dl.bintray.com/openhab/apt-repo2 stable main' | sudo tee /etc/apt/sources.list.d/openhab2.list

sudo apt-get update

sudo apt-get install openhab2-addons openhab2-addons-legacy openhab2 -y

sudo systemctl daemon-reload
sudo systemctl enable openhab2
sudo systemctl start openhab2
Настройка OpenHAB2

Через paper UI http://192.168.0.54:8080/paperui/index.htm устанавливаем необходимые плагины:

  • Exec Binding
  • HTTP Binding
  • MQTT Binding (1.x)
  • SNMP Binding
  • InfluxDB (v 1.0) Persistence
root@raspberrypi-1:/etc/openhab2/items# cat rpi_relays.items
Group Lights
Group RpiRelays

Switch rpi_54_relay1 "Подсветка потолка" <light> (Lights, RpiRelays) {mqtt=">[mainbroker:/openhab/items/rpi_54_relay1:command:ON:ON],>[mainbroker:/openhab/items/rpi_54_relay1:command:OFF:OFF]"}
Switch rpi_54_relay2 "Освещение над камином" <light> (Lights, RpiRelays) {mqtt=">[mainbroker:/openhab/items/rpi_54_relay2:command:ON:ON],>[mainbroker:/openhab/items/rpi_54_relay2:command:OFF:OFF]"}
Switch rpi_54_relay3 "Освещение прохода" <light> (Lights, RpiRelays) {mqtt=">[mainbroker:/openhab/items/rpi_54_relay3:command:ON:ON],>[mainbroker:/openhab/items/rpi_54_relay3:command:OFF:OFF]"}
Switch rpi_54_relay4 "Освещение над столом" <light> (Lights, RpiRelays) {mqtt=">[mainbroker:/openhab/items/rpi_54_relay4:command:ON:ON],>[mainbroker:/openhab/items/rpi_54_relay4:command:OFF:OFF]"}
Switch rpi_54_relay5 "Освещение в углу кухни" <light> (Lights, RpiRelays) {mqtt=">[mainbroker:/openhab/items/rpi_54_relay5:command:ON:ON],>[mainbroker:/openhab/items/rpi_54_relay5:command:OFF:OFF]"}
Switch rpi_54_relay6 "Освещение над островом" <light> (Lights, RpiRelays) {mqtt=">[mainbroker:/openhab/items/rpi_54_relay6:command:ON:ON],>[mainbroker:/openhab/items/rpi_54_relay6:command:OFF:OFF]"}
Switch rpi_54_relay7 "Освещение кухни" <light> (Lights, RpiRelays) {mqtt=">[mainbroker:/openhab/items/rpi_54_relay7:command:ON:ON],>[mainbroker:/openhab/items/rpi_54_relay7:command:OFF:OFF]"}
//Switch rpi_54_relay8 "Резерв" <light> (Lights, RpiRelays) {mqtt=">[mainbroker:/openhab/items/rpi_54_relay8:command:ON:ON],>[mainbroker:/openhab/items/rpi_54_relay8:command:OFF:OFF]"}




root@raspberrypi-1:/etc/openhab2/items# cat noolite_channels.items
Group NooliteChannels


Switch noolite_168_ch1 "Лестница" <light> (Lights, NooliteChannels) { http=">[ON:POST:http://192.168.0.168/api.htm?ch=0&cmd=2] >[OFF:POST:http://192.168.0.168/api.htm?ch=0&cmd=0]" }
Switch noolite_168_ch2 "Прихожая (2/3)" <light> (Lights, NooliteChannels) { http=">[ON:POST:http://192.168.0.168/api.htm?ch=1&cmd=2] >[OFF:POST:http://192.168.0.168/api.htm?ch=1&cmd=0]" }
Switch noolite_168_ch3 "Прихожая (1/3)" <light> (Lights, NooliteChannels) { http=">[ON:POST:http://192.168.0.168/api.htm?ch=2&cmd=2] >[OFF:POST:http://192.168.0.168/api.htm?ch=2&cmd=0]" }





root@raspberrypi-1:/etc/openhab2/items# cat rpi_status.items
Group RpiStatus

Number rpi_54_cpu_Chart_Period        "Период"
Number rpi_54_cpu_temperature "Температура ЦП [%.2f]" <temperature>     (RpiStatus)     {mqtt="<[mainbroker:/device/rpi_54/temperature:state:default]"}






root@raspberrypi-1:/etc/openhab2/services# cat mqtt-eventbus.cfg
broker=mainbroker
commandPublishTopic=/openhab/items/${item}
stateSubscribeTopic=/openhab/items/${item}




root@raspberrypi-1:/etc/openhab2/services#
cat mqtt.cfg
mainbroker.url=tcp://127.0.0.1:1883
mainbroker.clientId=MainBroker
mainbroker.retain=true




root@raspberrypi-1:/etc/openhab2/sitemaps# cat main.sitemap
sitemap main label="Управление домом" {
    Frame label="Зал" {
        Switch item=rpi_54_relay1 label="Подсветка потолка"
        Switch item=rpi_54_relay2 label="Над камином"
        Switch item=rpi_54_relay3 label="Форватер"
        Switch item=rpi_54_relay4 label="Стол"
        Switch item=rpi_54_relay5 label="Угол кухни"
        Switch item=rpi_54_relay6 label="Остров"
        Switch item=rpi_54_relay7 label="Кухня"
        //Switch item=rpi_54_relay8 label="Резерв"
    }

    Frame label="Прихожая" {
        Switch item=noolite_168_ch1 label="Лестница"
        Switch item=noolite_168_ch2 label="Прихожая (2/3)"
        Switch item=noolite_168_ch3 label="Прихожая (1/3)"
    }




}




root@raspberrypi-1:/etc/openhab2/sitemaps# cat rpi.sitemap
sitemap rpi label="Состояние контроллера дома" {
    Frame label="Температура" {
        Text item=rpi_54_cpu_temperature
    }

    Frame label="График температуры" {
        Switch item=rpi_54_cpu_Chart_Period label="Период" mappings=[0="Час", 1="День", 2="Неделя"]
        Chart item=rpi_54_cpu_temperature period=h refresh=30000 visibility=[rpi_54_cpu_Chart_Period==0, rpi_54_cpu_Chart_Period=="Uninitialized"]
        Chart item=rpi_54_cpu_temperature period=D refresh=30000 visibility=[rpi_54_cpu_Chart_Period==1]
        Chart item=rpi_54_cpu_temperature period=W refresh=30000 visibility=[rpi_54_cpu_Chart_Period==2]

    }


}





root@raspberrypi-1:/etc/openhab2/rules# cat lights.rules
//var Timer Coridor_light_timer = null

rule "Off Lights every day in 01:30"
        when
            Time cron "0 30 01 ? * MON-SUN "
        then
            sendCommand(Lights, OFF)

end


rule "ON noolite_168_ch1 every day in 21:30"
        when
            Time cron "0 30 21 ? * MON-SUN "
        then
            noolite_168_ch1.sendCommand(ON)

end
Установка и настройка InfluxDB для OpenHAB2
echo "deb https://repos.influxdata.com/debian stretch stable" | sudo tee /etc/apt/sources.list.d/influxdb.list

sudo curl -sL https://repos.influxdata.com/influxdb.key | sudo apt-key add -

sudo apt-get update
sudo apt-get install -y influxdb

sudo systemctl start influxdb
sudo systemctl enable influxdb

sudo systemctl status influxdb

Запускаем influx для создания базы данных и пользователей:

CREATE DATABASE openhab_db
CREATE USER openhab_admin WITH PASSWORD 'Z123456z' WITH ALL PRIVILEGES
CREATE USER openhab_user WITH PASSWORD 'Z123456z'
CREATE USER grafana_user WITH PASSWORD 'Z123456z'
GRANT ALL ON openhab_db TO openhab_user
GRANT READ ON openhab_db TO grafana_user
exit

Создать файл /etc/openhab2/services/influxdb.cfg

url=http://127.0.0.1:8086
user=openhab_user
password=Z123456z
db=openhab_db

Создать файл /etc/openhab2/persistence/influxdb.persist

/*
Отправка данных в InfluxDB

*/

Strategies {
    everyMinute : "0 * * * * ?"
    everyHour : "0 0 * * * ?"
    everyDay : "0 0 0 * * ?"
    every2Minutes : "0 */2 * ? * *"
    every15minutes : "0 */15 * ? * *"
}

Items {
    rpi_54_cpu_temperature: strategy = everyChange, restoreOnStartup
}

Ссылки