Using yaml for configuration

This commit is contained in:
2021-10-20 10:09:16 +02:00
parent 3048dd5400
commit 3f91b6bb62
3 changed files with 16 additions and 14 deletions
+6
View File
@@ -0,0 +1,6 @@
# Server address of the mqtt broker
mqtt_server: mqtt://192.168.178.48
sensors:
zigbee2mqtt/0x00158d00073a7ba8:
name: Test Sensor
-1
View File
@@ -1 +0,0 @@
2021-10-19 22:22:08 +0200,Test Sensor,62.97,26.99,972,100,3195,46
1 2021-10-19 22:22:08 +0200 Test Sensor 62.97 26.99 972 100 3195 46
+10 -13
View File
@@ -4,35 +4,32 @@ require 'rubygems'
require 'mqtt' require 'mqtt'
require 'json' require 'json'
require 'CSV' require 'CSV'
require 'yaml'
config = YAML.load_file('config.yaml')
# MQTT Server configuration # MQTT Server configuration
SERVER = '192.168.178.48' SERVER = '192.168.178.48'
# Sensor configuration # Sensor configuration
sensors = { sensors_config = config['sensors']
'zigbee2mqtt/0x00158d00073a7ba8': {
'name': 'Test Sensor',
'min_humidity': 61,
'max_humidity': 64
}
}
# Connect to the MQTT broker # Connect to the MQTT broker
MQTT::Client.connect(SERVER) do |client| MQTT::Client.connect(config['mqtt_server']) do |client|
# For each sensor # For each sensor
sensors.each_key do |sensor_topic| sensors_config.each_key do |sensor_topic|
sensor = sensors[sensor_topic] sensor = sensors_config[sensor_topic]
# Subscribe its topic # Subscribe its topic
client.get(sensor_topic.to_s) do |topic, message| client.get(sensor_topic.to_s) do |topic, message|
# Log the output # Log the output
puts "#{sensor[:name]}: #{message}" puts "#{sensor["name"]}: #{message}"
payload = JSON.parse(message) payload = JSON.parse(message)
# Log payload in a csv file # Log payload in a csv file
CSV.open('data.csv', 'wb') do |csv| CSV.open('data.csv', 'wb+') do |csv|
csv << [Time.now, csv << [Time.now,
sensor[:name], sensor["name"],
topic, topic,
payload['humidity'], payload['humidity'],
payload['temperature'], payload['temperature'],