Browse Source

initial commit

master
Brian Salcedo 1 year ago
commit
ff9e8c4d22
3 changed files with 71 additions and 0 deletions
  1. +9
    -0
      Dockerfile
  2. +3
    -0
      requirements.txt
  3. +59
    -0
      rtlamr-mqtt-postgres.py

+ 9
- 0
Dockerfile View File

@@ -0,0 +1,9 @@
FROM python:3

WORKDIR /usr/src/app

COPY . ./
RUN pip install --no-cache-dir -r requirements.txt

USER nobody
CMD ["python", "/usr/src/app/rtlamr-mqtt-postgres.py"]

+ 3
- 0
requirements.txt View File

@@ -0,0 +1,3 @@
paho-mqtt==1.4.0
psycopg2==2.8.3
SQLAlchemy==1.3.5

+ 59
- 0
rtlamr-mqtt-postgres.py View File

@@ -0,0 +1,59 @@
import json
import os
import sys

from paho.mqtt.client import Client

from sqlalchemy import Column, DateTime, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker


DATABASE_URL = os.getenv('DATABASE_URL')
if DATABASE_URL is None:
print('Please set DATABASE_URL')
sys.exit(1)

MQTT_SERVER = os.getenv('MQTT_SERVER') or 'localhost'
MQTT_PORT = os.getenv('MQTT_PORT') or '1883'

mqtt = Client('rtlamr-postgres')

engine = create_engine(DATABASE_URL)
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()


class Consumption(Base):
__tablename__ = 'consumption'

id = Column(Integer, primary_key=True)
timestamp = Column(DateTime, index=True)
metertype = Column(String(4))
meterid = Column(String(32))
consumption = Column(Integer)


def on_message(c, obj, msg):
payload = json.loads(msg.payload)

session.add(Consumption(
timestamp=payload['time'],
metertype=msg.topic.split('/')[1],
meterid=msg.topic.split('/')[2],
consumption=payload['consumption']
))

session.commit()


if __name__ == '__main__':
Base.metadata.create_all(engine)

mqtt.on_message = on_message

mqtt.connect(MQTT_SERVER, int(MQTT_PORT), 60)
mqtt.subscribe('meter/#')

mqtt.loop_forever()

Loading…
Cancel
Save