Skip to content

Commit 06ae1b6

Browse files
committedNov 21, 2021
added elasticsearch authorization
1 parent 9174f0a commit 06ae1b6

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed
 

‎rpi-powermeter/powermeter.json

+3-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
"meter-pin": 15,
99
"data-store": {
1010
"elastic": "192.168.1.101:9200",
11-
"index": "power-meter"
11+
"index": "power-meter",
12+
"user": "elastic",
13+
"password": "supersecret"
1214
}
1315
}

‎rpi-powermeter/powermeter.py

+20-4
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import sys
66
import time
77
import logging
8+
import base64
89
import http.client
910

1011
cf = open(sys.argv[1])
@@ -26,11 +27,14 @@
2627
pulse_value = config["pulse-value"]
2728
voltage_ac = config["voltage-ac"]
2829
cost_kwh = config["cost-kwh"]
29-
elastic = config["data-store"]["elastic"]
30-
index = config["data-store"]["index"]
3130
co2g_per_kwh = config["co2g-per-kwh"]
3231
max_power_kw = config["max-power-kw"]
3332

33+
elastic = config["data-store"]["elastic"]
34+
index = config["data-store"]["index"]
35+
elastic_user = config["data-store"]["user"]
36+
elastic_pass = config["data-store"]["password"]
37+
3438
logging.info('device_id: %s', device_id)
3539
logging.info('pulse_value: %s', pulse_value)
3640
logging.info('voltage_ac: %s', voltage_ac)
@@ -41,11 +45,22 @@
4145
logging.info('max-power-kw: %s', max_power_kw)
4246
logging.info('meter_pin: %s', meter_pin)
4347

48+
49+
def get_authorization(username, password):
50+
auth_str = username + ":" + password
51+
return "Basic " + base64.b64encode(auth_str.encode('ascii')).decode('ascii')
52+
53+
54+
elastic_authorization = get_authorization(elastic_user, elastic_pass)
4455
last_timestamp = 0
56+
logging.info('elastic_authorization: %s', elastic_authorization)
57+
elastic_headers = {
58+
"Content-type": "application/json",
59+
"Authorization": elastic_authorization
60+
}
4561

4662
def write_to_elastic(device_id, now_timestamp, interval, voltage, consumed, price, power, current, co2_produced):
4763
now_timestamp = int(now_timestamp * 1000)
48-
headers = {"Content-type": "application/json"}
4964
body = {
5065
"timestamp": now_timestamp,
5166
"deviceId": device_id,
@@ -60,10 +75,11 @@ def write_to_elastic(device_id, now_timestamp, interval, voltage, consumed, pric
6075
}
6176
}
6277
connection = http.client.HTTPConnection(elastic)
63-
connection.request("POST", index + "/_doc", headers = headers, body = json.dumps(body))
78+
connection.request("POST", index + "/_doc", headers = elastic_headers, body = json.dumps(body))
6479
response = connection.getresponse()
6580
logging.info("elastic response: %s", response.status)
6681

82+
6783
while True:
6884
GPIO.wait_for_edge(meter_pin, GPIO.FALLING)
6985
now_timestamp = time.time()

0 commit comments

Comments
 (0)
Please sign in to comment.