Skip to content

Commit

Permalink
Merge pull request jasonacox#3 from jasonacox/main
Browse files Browse the repository at this point in the history
Upgrade InfluxDB Client
  • Loading branch information
BJReplay authored Feb 27, 2023
2 parents 3f5ef11 + 81dd824 commit b64435f
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 23 deletions.
2 changes: 1 addition & 1 deletion weather/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
FROM python:3.8-alpine
WORKDIR /app
RUN pip3 install influxdb
RUN pip3 install requests influxdb-client
COPY server.py server.py
COPY README.md README.md
CMD ["python3", "server.py"]
Expand Down
13 changes: 10 additions & 3 deletions weather/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ Docker: docker pull [jasonacox/weather411](https://hub.docker.com/r/jasonacox/we

## Quick Start


1. Create a `weather411.conf` file (`cp weather411.conf.sample weather411.conf`) and update with your specific location details:

* Enter your OpenWeatherMap API Key (APIKEY) You can get a free account and key at [OpenWeatherMap.org](https://openweathermap.org/).
Expand Down Expand Up @@ -49,9 +48,13 @@ Docker: docker pull [jasonacox/weather411](https://hub.docker.com/r/jasonacox/we
PORT = 8086
DB = powerwall
FIELD = weather
# Leave blank if not used
USERNAME =
# Auth - Leave blank if not used
USERNAME =
PASSWORD =
# Influx 2.x - Leave blank if not used
TOKEN =
ORG =
URL =
```

2. Run the Docker Container to listen on port 8676.
Expand Down Expand Up @@ -141,6 +144,10 @@ docker start weather411

## Release Notes

### 0.2.0 - Upgrade InfluxDB Client

* Upgrade end of life `influxdb` client library to `influxdb-client` (refer discussion #191 and issue #195), providing support for InfluxDB 1.8 and 2.x.

### 0.1.2 - Snow and Rain Data

* Fix rain and snow values not being retrieved (refer issue #42) by @mcbirse (PR #69)
Expand Down
58 changes: 41 additions & 17 deletions weather/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,13 @@
PORT = 8086
DB = powerwall
FIELD = weather
# Auth - Leave blank if not used
USERNAME =
PASSWORD =
# Auth - Influx 2.x - Leave blank if not used
TOKEN =
ORG =
URL =
ENVIRONMENTAL:
WEATHERCONF = "Path to weather411.conf file"
Expand All @@ -69,15 +76,16 @@
import json
import requests
import resource
import datetime
from datetime import datetime
import sys
import os
from http.server import BaseHTTPRequestHandler, HTTPServer, ThreadingHTTPServer
from socketserver import ThreadingMixIn
import configparser
from influxdb import InfluxDBClient
from influxdb_client import InfluxDBClient
from influxdb_client.client.write_api import SYNCHRONOUS

BUILD = "0.1.2"
BUILD = "0.2.0"
CLI = False
LOADED = False
CONFIG_LOADED = False
Expand Down Expand Up @@ -110,7 +118,13 @@
IPASS = config["InfluxDB"]["PASSWORD"]
IDB = config["InfluxDB"]["DB"]
IFIELD = config["InfluxDB"]["FIELD"]
# Check for InfluxDB 2.x settings
ITOKEN = config.get('InfluxDB', 'TOKEN', fallback="")
IORG = config.get('InfluxDB', 'ORG', fallback="")
IURL = config.get('InfluxDB', 'URL', fallback="")

if ITOKEN != "" and IURL == "":
IURL = "http://%s:%s" % (IHOST, IPORT)
else:
# No config file - Display Error
sys.stderr.write("Weather411 Server %s\nERROR: No config file. Fix and restart.\n" % BUILD)
Expand Down Expand Up @@ -252,22 +266,29 @@ def fetchWeather():
if INFLUX:
log.debug("Writing to InfluxDB")
try:
client = InfluxDBClient(host=IHOST,
port=IPORT,
username=IUSER,
password=IPASS,
database=IDB)
if ITOKEN == "":
# Influx 1.8
client = InfluxDBClient(
url="http://%s:%s" % (IHOST,IPORT),
username=IUSER,
password=IPASS,
database=IDB)
else :
# Influx 2.x
client = InfluxDBClient(
url=IURL,
token=ITOKEN,
org=IORG)
output = [{}]
output[0]["measurement"] = IFIELD
output[0]["time"] = weather["dt"]
output[0]["time"] = datetime.utcfromtimestamp(weather["dt"])
output[0]["fields"] = {}
for i in weather:
output[0]["fields"][i] = weather[i]
# print(output)
if client.write_points(output, time_precision='s'):
serverstats['influxdb'] += 1
else:
serverstats['influxdberrors'] += 1
write_api = client.write_api(write_options=SYNCHRONOUS)
write_api.write(IDB,IORG,output)
serverstats['influxdb'] += 1
client.close()
except:
log.debug("Error writing to InfluxDB")
Expand Down Expand Up @@ -325,9 +346,9 @@ def do_GET(self):
message = message + '<tr><td align ="right">%s</td><td align ="right">%s</td></tr>\n' % (i, weather[i])
message = message + "</table>\n"
message = message + '<p>Last data update: %s<br><font size=-2>From URL: %s</font></p>' % (
str(datetime.datetime.fromtimestamp(weather['dt'])), URL)
str(datetime.fromtimestamp(weather['dt'])), URL)
message = message + '\n<p>Page refresh: %s</p>\n</body>\n</html>' % (
str(datetime.datetime.fromtimestamp(time.time())))
str(datetime.fromtimestamp(time.time())))
elif self.path == '/stats':
# Give Internal Stats
serverstats['ts'] = int(time.time())
Expand All @@ -339,9 +360,9 @@ def do_GET(self):
message = json.dumps(raw)
elif self.path == '/time':
ts = time.time()
result["local_time"] = str(datetime.datetime.fromtimestamp(ts))
result["local_time"] = str(datetime.fromtimestamp(ts))
result["ts"] = ts
result["utc"] = str(datetime.datetime.utcfromtimestamp(ts))
result["utc"] = str(datetime.utcfromtimestamp(ts))
result["tz"] = weather["tz"]
message = json.dumps(result)
elif self.path == '/temp':
Expand Down Expand Up @@ -418,6 +439,9 @@ def api(port):
% (OWKEY, OWWAIT, OWUNITS, OWLAT, OWLON, TIMEOUT))
sys.stderr.write(" + InfluxDB - Enable: %s, Host: %s, Port: %s, DB: %s, Field: %s\n"
% (INFLUX, IHOST, IPORT, IDB, IFIELD))
if ITOKEN != "" or IORG != "":
sys.stderr.write(" + InfluxDB - URL: %s, Org: %s, Token: %s\n"
% (IURL, IORG, ITOKEN))

# Start threads
sys.stderr.write("* Starting threads\n")
Expand Down
8 changes: 6 additions & 2 deletions weather/weather411.conf.sample
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@ HOST = influxdb
PORT = 8086
DB = powerwall
FIELD = weather
# Leave blank if not used
USERNAME =
# Auth - Leave blank if not used
USERNAME =
PASSWORD =
# Influx 2.x - Leave blank if not used
TOKEN =
ORG =
URL =

0 comments on commit b64435f

Please sign in to comment.