コード例 #1
0
ファイル: command.py プロジェクト: RaigK/smeterd
    def run(self, args, parser):
        meter = SmartMeter(args.serial_port,
                           baudrate=args.baudrate)

        try:
            packet = meter.read_one_packet()
        except SerialException as e:
            parser.error(e)
        finally:
            meter.disconnect()

        if args.raw:
            print(str(packet))
            return 0

        data = [
            ('Time', datetime.now()),
            ('Total kWh High consumed', int(packet['kwh']['high']['consumed']*1000)),
            ('Total kWh Low consumed', int(packet['kwh']['low']['consumed']*1000)),
            ('Total gas consumed', int(packet['gas']['total']*1000)),
            ('Current kWh tariff', packet['kwh']['tariff'])
        ]

        if args.tsv:
            print('\t'.join(map(str, [d for k,d in data])))
        else:
            print('\n'.join(['%-25s %s' % (k,d) for k,d in data]))
コード例 #2
0
    def run(self, args, parser):
        meter = SmartMeter(args.serial_port, baudrate=args.baudrate)

        try:
            packet = meter.read_one_packet()
        except SerialException as e:
            parser.error(e)
        finally:
            meter.disconnect()

        if args.raw:
            print(str(packet))
            return 0

        data = [('Time', datetime.now()),
                ('Total kWh High consumed',
                 int(packet['kwh']['high']['consumed'] * 1000)),
                ('Total kWh Low consumed',
                 int(packet['kwh']['low']['consumed'] * 1000)),
                ('Total gas consumed', int(packet['gas']['total'] * 1000)),
                ('Current kWh tariff', packet['kwh']['tariff'])]

        if args.tsv:
            print('\t'.join(map(str, [d for k, d in data])))
        else:
            print('\n'.join(['%-25s %s' % (k, d) for k, d in data]))
コード例 #3
0
ファイル: test_meter.py プロジェクト: jac1nt0/smeterd
def test_meter_connect_twice():
    serial.Serial = SerialMock
    meter = SmartMeter('/dev/ttyUSB0')
    assert meter.connected() == True
    meter.connect()
    assert meter.connected() == True
    meter.connect()
    assert meter.connected() == True
コード例 #4
0
ファイル: test_meter.py プロジェクト: jac1nt0/smeterd
def test_meter_disconnect_and_connect():
    serial.Serial = SerialMock
    meter = SmartMeter('/dev/ttyUSB0')
    assert meter.connected() == True
    meter.disconnect()
    assert meter.connected() == False
    meter.connect()
    assert meter.connected() == True
コード例 #5
0
ファイル: test_meter.py プロジェクト: qsmits/smeterd
def test_meter_disconnect_and_connect():
    serial.Serial = SerialMock
    meter = SmartMeter('/dev/ttyUSB0')
    assert meter.connected() == True
    meter.disconnect()
    assert meter.connected() == False
    meter.connect()
    assert meter.connected() == True
コード例 #6
0
ファイル: test_meter.py プロジェクト: qsmits/smeterd
def test_meter_connect_twice():
    serial.Serial = SerialMock
    meter = SmartMeter('/dev/ttyUSB0')
    assert meter.connected() == True
    meter.connect()
    assert meter.connected() == True
    meter.connect()
    assert meter.connected() == True
コード例 #7
0
class P1Device:
    E_LAAG = 'low'
    E_HOOG = 'high'
    E_CONSUMED = 'consumed'
    E_PRODUCED = 'produced'
    G_M3 = 'm3'
    G_TIMESTAMP = 'timestamp'

    def __init__(self, file='/dev/ttyUSB0'):
        self.meter = SmartMeter(file,
                                baudrate=115200,
                                parity='N',
                                stopbits=1,
                                bytesize=8)

    def get_data(self):
        with self.meter:
            packet = self.meter.read_one_packet()
        e = {}
        metername = str(packet['header'])[:1]

        for tarief in [P1Device.E_LAAG, P1Device.E_HOOG]:
            e[tarief] = {}
            for richting in [P1Device.E_CONSUMED, P1Device.E_PRODUCED]:
                e[tarief][richting] = packet['kwh'][tarief][richting]
        g = {
            P1Device.G_M3: packet['gas']['total'],
            P1Device.G_TIMESTAMP: packet['gas']['measured_at']
        }
        data = {"electra": e, 'gas': g, 'header': packet['header']}
        return str(json.dumps(data))
コード例 #8
0
ファイル: test_meter.py プロジェクト: jac1nt0/smeterd
def test_meter_read_one_packet_1003():
    serial.Serial = SerialMock
    meter = SmartMeter('/dev/ttyUSB0')
    meter.serial.lines_in_buffer = NORMAL_PACKET_1003.splitlines(True)

    p = meter.read_one_packet()
    assert p['header'] == '/ISk5\2ME382-1003'
    assert p['kwh']['eid'] == '5A424556303035303933313937373132'
    assert p['kwh']['low']['consumed'] == 608.400
    assert p['kwh']['high']['consumed'] == 490.342
    assert p['kwh']['low']['produced'] == 0.001
    assert p['kwh']['high']['produced'] == 0
    assert p['kwh']['tariff'] == 1
    assert p['kwh']['current_consumed'] == 1.51
    assert p['kwh']['current_produced'] == 0
    assert p['kwh']['treshold'] == 999
    assert p['kwh']['switch'] == 1
    assert p['msg']['code'] == None
    assert p['msg']['text'] == None
    assert p._datagram == NORMAL_PACKET_1003
コード例 #9
0
ファイル: test_meter.py プロジェクト: qsmits/smeterd
def test_meter_read_one_packet_1003():
    serial.Serial = SerialMock
    meter = SmartMeter('/dev/ttyUSB0')
    meter.serial.lines_in_buffer = NORMAL_PACKET_1003.split('\n')

    p = meter.read_one_packet()
    assert p['header'] == '/ISk5\2ME382-1003'
    assert p['kwh']['eid'] == '5A424556303035303933313937373132'
    assert p['kwh']['low']['consumed'] == 608.400
    assert p['kwh']['high']['consumed'] == 490.342
    assert p['kwh']['low']['produced'] == 0.001
    assert p['kwh']['high']['produced'] == 0
    assert p['kwh']['tariff'] == 1
    assert p['kwh']['current_consumed'] == 1.51
    assert p['kwh']['current_produced'] == 0
    assert p['kwh']['treshold'] == 999
    assert p['kwh']['switch'] == 1
    assert p['msg']['code'] == None
    assert p['msg']['text'] == None
    assert str(p) == NORMAL_PACKET_1003
コード例 #10
0
    def collect(self):
        metrics = {
            'p1_total_electricity_used_rate_1': GaugeMetricFamily('p1_total_electricity_used_rate_1', 'Gebruik elektra dal'),
            'p1_total_electricity_used_rate_2': GaugeMetricFamily('p1_total_electricity_used_rate_2', 'Gebruik elektra piek'),
            'p1_total_electricity_provided_rate_1': GaugeMetricFamily('p1_total_electricity_provided_rate_1', 'Geleverd elektra dal'),
            'p1_total_electricity_provided_rate_2': GaugeMetricFamily('p1_total_electricity_provided_rate_2', 'Geleverd elektra piek'),
            'p1_total_electricity_used': GaugeMetricFamily('p1_total_electricity_used', 'Totaal gebruik elektra'),
            'p1_total_electricity_provided': GaugeMetricFamily('p1_total_electricity_provided', 'Totaal geleverd elektra'),
            'p1_l1_voltage': GaugeMetricFamily('p1_l1_voltage', 'Totaal geleverd elektra'),
            'p1_l2_voltage': GaugeMetricFamily('p1_l2_voltage', 'Totaal geleverd elektra'),
            'p1_l3_voltage': GaugeMetricFamily('p1_l3_voltage', 'Totaal geleverd elektra'),
            'p1_current_tarrif': GaugeMetricFamily('p1_current_tarrif', 'Totaal geleverd elektra')
        }

        meter = SmartMeter('/dev/ttyUSB0', baudrate=115200)
        metrics = self.get_p1_metrics(meter.read_one_packet(), metrics)
        meter.disconnect()

        for metric in metrics.values():
            yield metric
コード例 #11
0
ファイル: read_meter.py プロジェクト: nrocco/smeterd
    def run(self, args, parser):
        meter = SmartMeter(
            args.serial_port,
            baudrate=args.serial_baudrate,
            bytesize=args.serial_bytesize,
            parity=args.serial_parity,
            stopbits=args.serial_stopbits,
            xonxoff=args.serial_xonxoff,
            timeout=args.serial_timeout,
        )

        try:
            packet = meter.read_one_packet()
        except SerialException as e:
            parser.error(e)
        finally:
            meter.disconnect()

        if args.raw:
            print(str(packet))
            return 0

        data = [
            ('Time', datetime.now()),
            ('Total kWh High consumed', int(packet['kwh']['high']['consumed']*1000)),
            ('Total kWh Low consumed', int(packet['kwh']['low']['consumed']*1000)),
            ('Total gas consumed', int(packet['gas']['total']*1000)),
            ('Current kWh tariff', packet['kwh']['tariff']),
            ('Gas Measured At', packet['gas']['measured_at']),
        ]

        if args.tsv:
            print('\t'.join(map(str, [d for k,d in data])))
        else:
            print('\n'.join(['%-25s %s' % (k,d) for k,d in data]))

        return 0
コード例 #12
0
ファイル: test_meter.py プロジェクト: qsmits/smeterd
def test_meter_read_one_packet():
    serial.Serial = SerialMock
    meter = SmartMeter('/dev/ttyUSB0')
    meter.serial.lines_in_buffer = NORMAL_PACKET.split('\n')

    p = meter.read_one_packet()
    assert p['header'] == '/ISk5\2ME382-1004'
    assert p['kwh']['eid'] == '4B414C37303035313135383130323132'
    assert p['kwh']['low']['consumed'] == 608.400
    assert p['kwh']['high']['consumed'] == 490.342
    assert p['kwh']['low']['produced'] == 0.001
    assert p['kwh']['high']['produced'] == 0
    assert p['kwh']['tariff'] == 1
    assert p['kwh']['current_consumed'] == 1.51
    assert p['kwh']['current_produced'] == 0
    assert p['kwh']['treshold'] == 999
    assert p['kwh']['switch'] == 1
    assert p['msg']['code'] == None
    assert p['msg']['text'] == None
    assert p['gas']['device_type'] == 3
    assert p['gas']['eid'] == '3238303131303031323332313337343132'
    assert p['gas']['total'] == 947.680
    assert p['gas']['valve'] == 1
    assert str(p) == NORMAL_PACKET
コード例 #13
0
    def run(self, args, parser):
        meter = SmartMeter(
            args.serial_port,
            baudrate=args.serial_baudrate,
            bytesize=args.serial_bytesize,
            parity=args.serial_parity,
            stopbits=args.serial_stopbits,
            xonxoff=args.serial_xonxoff,
            timeout=args.serial_timeout,
        )

        try:
            packet = meter.read_one_packet()
        except SerialException as e:
            parser.error(e)
        finally:
            meter.disconnect()

        if args.raw:
            print(str(packet))
            return 0

        data = [('Telegram Time', self.convertTime(packet['kwh']['etime'])),
                ('Total kWh High consumed',
                 int(packet['kwh']['high']['consumed'] * 1000)),
                ('Total kWh Low consumed',
                 int(packet['kwh']['low']['consumed'] * 1000)),
                ('Total gas consumed', int(packet['gas']['total'] * 1000)),
                ('Current kWh tariff', packet['kwh']['tariff'])]

        if args.tsv:
            print('\t'.join(map(str, [d for k, d in data])))
        else:
            print('\n'.join(['%-25s %s' % (k, d) for k, d in data]))

        return 0
コード例 #14
0
ファイル: test_meter.py プロジェクト: jac1nt0/smeterd
def test_meter_read_one_packet():
    serial.Serial = SerialMock
    meter = SmartMeter('/dev/ttyUSB0')
    meter.serial.lines_in_buffer = NORMAL_PACKET.splitlines(True)

    p = meter.read_one_packet()
    assert p['header'] == '/ISk5\2ME382-1004'
    assert p['kwh']['eid'] == 'XXXXXXXXXXXXXXMYSERIALXXXXXXXXXXXXXX'
    assert p['kwh']['low']['consumed'] == 608.400
    assert p['kwh']['high']['consumed'] == 490.342
    assert p['kwh']['low']['produced'] == 0.001
    assert p['kwh']['high']['produced'] == 0
    assert p['kwh']['tariff'] == 1
    assert p['kwh']['current_consumed'] == 1.51
    assert p['kwh']['current_produced'] == 0
    assert p['kwh']['treshold'] == 999
    assert p['kwh']['switch'] == 1
    assert p['msg']['code'] == None
    assert p['msg']['text'] == None
    assert p['gas']['device_type'] == 3
    assert p['gas']['eid'] == '3238303131303031323332313337343132'
    assert p['gas']['total'] == 947.680
    assert p['gas']['valve'] == 1
    assert p._datagram == NORMAL_PACKET
コード例 #15
0
ファイル: test_meter.py プロジェクト: jac1nt0/smeterd
def test_meter_tty_not_available():
    meter = SmartMeter('/dev/ttyUSB0')
コード例 #16
0
ファイル: test_meter.py プロジェクト: jac1nt0/smeterd
def test_meter_typeerror():
    meter = SmartMeter()
コード例 #17
0
ファイル: test_meter.py プロジェクト: jac1nt0/smeterd
def test_meter_read_long_broken_packet():
    serial.Serial = SerialMock
    meter = SmartMeter('/dev/ttyUSB0')
    meter.serial.lines_in_buffer = LONG_BROKEN_PACKET.splitlines(True)
    meter.read_one_packet()
コード例 #18
0
ファイル: test_meter.py プロジェクト: qsmits/smeterd
def test_meter_read_broken_packet():
    serial.Serial = SerialMock
    meter = SmartMeter('/dev/ttyUSB0')
    meter.serial.lines_in_buffer = BROKEN_PACKET.split('\n')
    meter.read_one_packet()
コード例 #19
0
ファイル: smeter-api.py プロジェクト: Infern1/smeterd-rest
#description    :Script to make Smartmeter available over the network
#author                 :Rob Lensen
#date                   :20180709
#version                :0.1
#usage                  :python smeter-api.py.py
#notes                  :
#python_version :2.6.6
#==============================================================================

from flask import Flask
from flask_restplus import Resource, Api
from flask import make_response, Flask

from smeterd.meter import SmartMeter

meter = SmartMeter('/dev/cuaU0')


def output_plain(data, code, headers=None):
    resp = make_response(str(data), code)
    resp.headers.extend(headers or {})
    return resp


app = Flask(__name__)
api = Api(app, default_mediatype='text/plain')
api.representations['text/plain'] = output_plain


@api.route('/smart')
class HelloWorld(Resource):
コード例 #20
0
ファイル: main.py プロジェクト: sbkg0002/prometheus_esmr5
            print("[{}] p1_total_electricity_provided: {}".format(
                datetime.datetime.now(), markup_helper(p1_line)))
            p1_total_electricity_provided.set(markup_helper(p1_line))
        elif '0-1:24.2.1' in p1_line:
            print("[{}] p1_total_gas_used: {}".format(datetime.datetime.now(),
                                                      markup_helper(p1_line)))
            p1_total_gas_used.set(markup_helper(p1_line))


def markup_helper(str_line):
    '''
    Read raw string and return only the value
    '''
    return int(str_line.split('(')[-1].split('*')[0].replace('.', ''))


if __name__ == '__main__':
    # Start up the server to expose the metrics.
    start_http_server(8000)
    # Generate some requests.
    while True:
        try:
            # Define device
            meter = SmartMeter('/dev/ttyUSB0', baudrate=115200)
            get_p1_metrics(meter.read_one_packet())
            meter.disconnect()
        except:
            sys.exit("Serial port cannot be read. Will try again.")
        print("")
        time.sleep(interval)
コード例 #21
0
import os
dir_path = os.path.dirname(os.path.realpath(__file__))

#config
Config = ConfigParser.ConfigParser()
Config.read(dir_path + '/config.ini')

#logging
numeric_level = getattr(logging,
                        Config.get('logging', 'level').upper(),
                        10)  #convert log level to numeric loglevel
logging.basicConfig(level=numeric_level)
log = logging.getLogger(__name__)
log.info('Starting..')

meter = SmartMeter(Config.get('smeter', 'device'),
                   baudrate=Config.get('smeter', 'baudrate'))

solar = rsReader(**dict(Config.items('rs485')))


def p1PostPacket(packet, poster):
    eqid = str(packet['kwh']['eid']).decode('hex')
    tariff = packet['kwh']['tariff']

    body = ''
    bodyTemplate_energy = 'emeter_energy,eqid=' + eqid + ',tarif={tarif},direction={dir} value={value}\n'
    bodyTemplate_power = 'emeter_power,eqid=' + eqid + ',tarif={tarif},direction={dir},phase={phase} value={value}\n'

    body += bodyTemplate_energy.format(dir='in',
                                       tarif='2',
                                       value=packet['kwh']['high']['consumed'])
コード例 #22
0
    def clock(self):
        """ Runs every minute and updates which devices are still connected """
        if self.DEBUG:
            print("clock thread init")

        seconds_counter = 50
        minutes_counter = 0
        while self.running:
            try:
                current_time = int(time.time())
                if self.DEBUG:
                    print("CLOCK TICK " + str(current_time))

                packet = self.meter.read_one_packet()
                if self.DEBUG:
                    print("packet = " + str(packet))

                property_counter_before = len(self.thing.properties)

                #
                #  KWH
                #

                try:
                    kwh = packet['kwh']

                    if self.DEBUG:
                        print("--------KWH---------")

                        for key, value in kwh.items():
                            print(key, ' : ', value)

                        print("--------------------")

                    if 'low' in kwh:
                        if 'consumed' in kwh['low']:
                            targetProperty = self.thing.find_property(
                                'kwh-low-consumed')
                            if targetProperty == None:
                                if self.DEBUG:
                                    print(
                                        "-property did not exist yet. Creating it now."
                                    )
                                self.thing.properties[
                                    "kwh-low-consumed"] = P1Property(
                                        self.thing, "kwh-low-consumed", {
                                            'label': "Low consumed",
                                            'type': 'number',
                                            'unit': 'kwh',
                                            'readOnly': True,
                                            'multipleOf': 0.001,
                                        }, kwh['low']['consumed'])
                                targetProperty = self.thing.find_property(
                                    'kwh-low-consumed')

                            new_value = get_int_or_float(
                                kwh['low']['consumed'])
                            targetProperty.update(new_value)

                        if 'produced' in kwh['low']:
                            targetProperty = self.thing.find_property(
                                'kwh-low-produced')
                            if targetProperty == None:
                                self.thing.properties[
                                    "kwh-low-produced"] = P1Property(
                                        self.thing, "kwh-low-produced", {
                                            'label': "Low produced",
                                            'type': 'number',
                                            'unit': 'kwh',
                                            'readOnly': True,
                                            'multipleOf': 0.001,
                                        }, kwh['low']['produced'])
                                targetProperty = self.thing.find_property(
                                    'kwh-low-produced')

                            new_value = get_int_or_float(
                                kwh['low']['produced'])
                            targetProperty.update(new_value)

                    if 'high' in kwh:
                        if 'consumed' in kwh['high']:
                            targetProperty = self.thing.find_property(
                                'kwh-high-consumed')
                            if targetProperty == None:
                                self.thing.properties[
                                    "kwh-high-consumed"] = P1Property(
                                        self.thing, "kwh-high-consumed", {
                                            'label': "High consumed",
                                            'type': 'number',
                                            'unit': 'kwh',
                                            'readOnly': True,
                                            'multipleOf': 0.001,
                                        }, kwh['high']['consumed'])
                                targetProperty = self.thing.find_property(
                                    'kwh-high-consumed')

                            new_value = get_int_or_float(
                                kwh['high']['consumed'])
                            targetProperty.update(new_value)

                        if 'produced' in kwh['high']:
                            targetProperty = self.thing.find_property(
                                'kwh-high-produced')
                            if targetProperty == None:
                                self.thing.properties[
                                    "kwh-high-produced"] = P1Property(
                                        self.thing, "kwh-high-produced", {
                                            'label': "High produced",
                                            'type': 'number',
                                            'unit': 'kwh',
                                            'readOnly': True,
                                            'multipleOf': 0.001,
                                        }, kwh['high']['produced'])

                                targetProperty = self.thing.find_property(
                                    'kwh-high-produced')

                            new_value = get_int_or_float(
                                kwh['high']['produced'])
                            targetProperty.update(new_value)

                    if 'high' in kwh:
                        if 'consumed' in kwh['high']:
                            if 'low' in kwh:
                                if 'consumed' in kwh['low']:
                                    consumed_total = get_int_or_float(
                                        kwh['high']
                                        ['consumed']) + get_int_or_float(
                                            kwh['low']['consumed'])
                                    if self.DEBUG:
                                        print("total consumed = " +
                                              str(consumed_total))

                                    if self.previous_consumed_total == None:
                                        self.previous_consumed_total = consumed_total

                                    targetProperty = self.thing.find_property(
                                        'kwh-total-consumed')
                                    if targetProperty == None:
                                        self.thing.properties[
                                            "kwh-total-consumed"] = P1Property(
                                                self.thing,
                                                "kwh-total-consumed", {
                                                    '@type': 'LevelProperty',
                                                    'label': "Total consumed",
                                                    'type': 'number',
                                                    'unit': 'kwh',
                                                    'readOnly': True,
                                                    'multipleOf': 0.001,
                                                }, consumed_total)

                                        targetProperty = self.thing.find_property(
                                            'kwh-total-consumed')

                                    new_value = get_int_or_float(
                                        consumed_total)
                                    targetProperty.update(new_value)

                    if 'high' in kwh:
                        if 'produced' in kwh['high']:
                            if 'low' in kwh:
                                if 'produced' in kwh['low']:
                                    produced_total = get_int_or_float(
                                        kwh['high']
                                        ['produced']) + get_int_or_float(
                                            kwh['low']['produced'])
                                    if self.DEBUG:
                                        print("total produced = " +
                                              str(produced_total))

                                    if self.previous_produced_total == None:
                                        self.previous_produced_total = produced_total

                                    targetProperty = self.thing.find_property(
                                        'kwh-total-produced')
                                    if targetProperty == None:
                                        self.thing.properties[
                                            "kwh-total-produced"] = P1Property(
                                                self.thing,
                                                "kwh-total-produced", {
                                                    'label': "Total produced",
                                                    'type': 'number',
                                                    'unit': 'kwh',
                                                    'readOnly': True,
                                                    'multipleOf': 0.001,
                                                }, produced_total)

                                        targetProperty = self.thing.find_property(
                                            'kwh-total-produced')

                                    new_value = get_int_or_float(
                                        produced_total)
                                    targetProperty.update(new_value)

                    if 'current_consumed' in kwh:
                        targetProperty = self.thing.find_property(
                            'kwh-current-consumed')
                        if targetProperty == None:
                            self.thing.properties[
                                "kwh-current-consumed"] = P1Property(
                                    self.thing, "kwh-current-consumed", {
                                        'label': "Current consumed",
                                        'type': 'number',
                                        'unit': 'kwh',
                                        'readOnly': True,
                                        'multipleOf': 0.001,
                                    }, kwh['current_consumed'])
                            targetProperty = self.thing.find_property(
                                'kwh-current-consumed')

                        new_value = get_int_or_float(kwh['current_consumed'])
                        targetProperty.update(new_value)

                    if 'current_produced' in kwh:
                        targetProperty = self.thing.find_property(
                            'kwh-current-produced')
                        if targetProperty == None:
                            self.thing.properties[
                                "kwh-current-produced"] = P1Property(
                                    self.thing, "kwh-current-consumed", {
                                        'label': "Current produced",
                                        'type': 'number',
                                        'unit': 'kwh',
                                        'readOnly': True,
                                        'multipleOf': 0.001,
                                    }, kwh['current_consumed'])
                            targetProperty = self.thing.find_property(
                                'kwh-current-produced')

                        new_value = get_int_or_float(kwh['current_produced'])
                        targetProperty.update(new_value)

                    if 'tariff' in kwh:
                        targetProperty = self.thing.find_property('kwh-tariff')
                        if targetProperty == None:
                            self.thing.properties["kwh-tariff"] = P1Property(
                                self.thing,
                                "kwh-tariff",
                                {
                                    'label': "Tariff",
                                    'type': 'integer',
                                    'readOnly': True,
                                    #'multipleOf':0.001,
                                },
                                kwh['tariff'])
                            targetProperty = self.thing.find_property(
                                'kwh-tariff')

                        new_value = get_int_or_float(kwh['tariff'])
                        targetProperty.update(new_value)

                except Exception as ex:
                    if self.DEBUG:
                        print("Energy use update error: " + str(ex))

                #
                #  INSTANTANEOUS POWER
                #

                try:
                    instant = packet['instantaneous']

                    instant_total_watts = 0

                    if self.DEBUG:
                        print("--------INSTANTANEOUS---------")

                        for key, value in instant.items():
                            print(key, ' : ', value)

                        print("--------------------")

                    if 'l1' in instant:
                        if 'watts' in instant['l1']:
                            targetProperty = self.thing.find_property(
                                'instant-l1-watts')
                            if targetProperty == None:
                                if self.DEBUG:
                                    print(
                                        "-instant-l1-watts property did not exist yet. Creating it now."
                                    )
                                self.thing.properties[
                                    "instant-l1-watts"] = P1Property(
                                        self.thing, "instant-l1-watts", {
                                            'label': "L1 wattage",
                                            'type': 'number',
                                            'unit': 'Watt',
                                            'readOnly': True,
                                            'multipleOf': 0.001,
                                        }, instant['l1']['watts'])
                                targetProperty = self.thing.find_property(
                                    'instant-l1-watts')

                            new_value = get_int_or_float(
                                instant['l1']['watts'])
                            targetProperty.update(new_value)

                            instant_total_watts += new_value

                    if 'l2' in instant:
                        if 'watts' in instant['l2']:
                            targetProperty = self.thing.find_property(
                                'instant-l2-watts')
                            if targetProperty == None:
                                if self.DEBUG:
                                    print(
                                        "-instant-l2-watts property did not exist yet. Creating it now."
                                    )
                                self.thing.properties[
                                    "instant-l2-watts"] = P1Property(
                                        self.thing, "instant-l2-watts", {
                                            'label': "L2 wattage",
                                            'type': 'number',
                                            'unit': 'Watt',
                                            'readOnly': True,
                                            'multipleOf': 0.001,
                                        }, instant['l2']['watts'])
                                targetProperty = self.thing.find_property(
                                    'instant-l2-watts')

                            new_value = get_int_or_float(
                                instant['l2']['watts'])
                            targetProperty.update(new_value)

                            instant_total_watts += new_value

                    if 'l3' in instant:
                        if 'watts' in instant['l3']:
                            targetProperty = self.thing.find_property(
                                'instant-l3-watts')
                            if targetProperty == None:
                                if self.DEBUG:
                                    print(
                                        "-instant-l3-watts property did not exist yet. Creating it now."
                                    )
                            self.thing.properties[
                                "instant-l3-watts"] = P1Property(
                                    self.thing, "instant-l3-watts", {
                                        'label': "L3 wattage",
                                        'type': 'number',
                                        'unit': 'Watt',
                                        'readOnly': True,
                                        'multipleOf': 0.001,
                                    }, instant['l3']['watts'])
                            targetProperty = self.thing.find_property(
                                'instant-l3-watts')

                            new_value = get_int_or_float(
                                instant['l3']['watts'])
                            targetProperty.update(new_value)

                            instant_total_watts += new_value

                    if instant_total_watts != 0:
                        targetProperty = self.thing.find_property(
                            'instant-total-watts')
                        if targetProperty == None:
                            if self.DEBUG:
                                print(
                                    "-instant-total-watts property did not exist yet. Creating it now."
                                )

                            self.thing._type.append('EnergyMonitor')
                            self.thing.properties[
                                "instant-total-watts"] = P1Property(
                                    self.thing, "instant-total-watts", {
                                        '@type': 'InstantaneousPowerProperty',
                                        'label': "Wattage",
                                        'type': 'number',
                                        'unit': 'Watt',
                                        'readOnly': True,
                                        'multipleOf': 0.001,
                                    }, instant_total_watts)
                            targetProperty = self.thing.find_property(
                                'instant-total-watts')

                        new_value = get_int_or_float(instant_total_watts)
                        targetProperty.update(instant_total_watts)

                except Exception as ex:
                    if self.DEBUG:
                        print(
                            "Instantaneous energy use update error (your device simply may not support this): "
                            + str(ex))

                #
                #  GAS
                #

                try:
                    gas = packet['gas']

                    if self.DEBUG:
                        print("--------GAS---------")

                        for key, value in gas.items():
                            print(key, ' : ', value)

                        print("---------------------")

                    if 'total' in gas:
                        targetProperty = self.thing.find_property('gas-total')
                        if targetProperty == None:
                            if self.DEBUG:
                                print(
                                    "gas property did not exist yet, creating it now"
                                )
                            self.thing.properties["gas-total"] = P1Property(
                                self.thing, "gas-total", {
                                    'label': "Gas total",
                                    'type': 'number',
                                    'unit': 'm3',
                                    'readOnly': True,
                                    'multipleOf': 0.001,
                                }, gas['total'])
                            targetProperty = self.thing.find_property(
                                'gas-total')
                            #print("targetProperty gas is now: " + str(targetProperty))

                        new_value = get_int_or_float(gas['total'])
                        gas_total = new_value
                        if self.previous_gas_total == None:
                            self.previous_gas_total = gas_total

                        #print("new gas value: " + str(new_value))
                        targetProperty.update(new_value)

                except Exception as ex:
                    if self.DEBUG:
                        print("Gas update error: " + str(ex))

                try:
                    if seconds_counter > 60:
                        seconds_counter = 0
                        minutes_counter += 1
                        #print("")
                        #print("MINUTE")
                        #print("")
                        #if self.DEBUG:

                        if minutes_counter > 60:  # every hour
                            minutes_counter = 0
                            #print("total consumed = " + str(consumed_total))

                            consumed_delta = consumed_total - self.previous_consumed_total
                            self.previous_consumed = consumed_total

                            produced_delta = produced_total - self.previous_produced_total
                            self.previous_produced_total = produced_total

                            gas_delta = gas_total - self.previous_gas_total
                            self.previous_gas_total = gas_total

                            # Hourly KWH consumption
                            targetProperty = self.thing.find_property(
                                'kwh-hourly-consumed')
                            if targetProperty == None:
                                self.thing.properties[
                                    "kwh-hourly-consumed"] = P1Property(
                                        self.thing, "kwh-hourly-consumed", {
                                            'label': "Hourly consumption",
                                            'type': 'number',
                                            'unit': 'kwh',
                                            'readOnly': True,
                                            'multipleOf': 0.001,
                                        }, consumed_delta)

                                targetProperty = self.thing.find_property(
                                    'kwh-total-consumed')

                            targetProperty.update(consumed_delta)

                            # Hourly KWH production
                            targetProperty = self.thing.find_property(
                                'kwh-hourly-produced')
                            if targetProperty == None:
                                self.thing.properties[
                                    "kwh-hourly-produced"] = P1Property(
                                        self.thing, "kwh-hourly-produced", {
                                            'label': "Hourly production",
                                            'type': 'number',
                                            'unit': 'kwh',
                                            'readOnly': True,
                                            'multipleOf': 0.001,
                                        }, produced_delta)

                                targetProperty = self.thing.find_property(
                                    'kwh-total-consumed')

                            targetProperty.update(produced_delta)

                            # Hourly GAS consumption
                            targetProperty = self.thing.find_property(
                                'gas-hourly')
                            if targetProperty == None:
                                self.thing.properties[
                                    "gas-hourly"] = P1Property(
                                        self.thing, "gas-hourly", {
                                            'label': "Hourly gas consumption",
                                            'type': 'number',
                                            'unit': 'm3',
                                            'readOnly': True,
                                            'multipleOf': 0.001,
                                        }, gas_delta)

                                targetProperty = self.thing.find_property(
                                    'gas-hourly')

                            targetProperty.update(gas_delta)

                except Exception as ex:
                    if self.DEBUG:
                        print("Hourly values update error: " + str(ex))

                # If the amount of properties has increased, tell the Gateway about this.
                if property_counter_before != len(self.thing.properties):
                    self.handle_device_added(self.thing)

                if self.thing.connected == False:
                    self.thing.connected = True
                    self.thing.connected_notify(True)

            except Exception as ex:
                print("Error handling incoming data: " + str(ex))
                try:
                    self.thing.connected = False
                    self.thing.connected_notify(False)
                except Exception as ex:
                    print("Error updating connection status: " + str(ex))

                try:
                    if str(ex).startswith(
                            'read failed: device reports readiness'):
                        print(
                            "It's likely that the wrong USB port has been selected. Will attempt to switch."
                        )
                        print("len(self.initial_serial_devices) = " +
                              str(len(self.initial_serial_devices)))
                        print("self.initial_serial_devices = " +
                              str(self.initial_serial_devices))
                        print(
                            "str(self.initial_serial_devices[0]['port_id']) = "
                            + str(self.initial_serial_devices[0]))

                        if len(self.initial_serial_devices
                               ) > 1 and self.usb_port == str(
                                   self.initial_serial_devices[0]):
                            self.usb_port = str(self.initial_serial_devices[1])
                        elif len(self.initial_serial_devices
                                 ) > 2 and self.usb_port == str(
                                     self.initial_serial_devices[1]):
                            self.usb_port = str(self.initial_serial_devices[2])
                        elif len(self.initial_serial_devices
                                 ) > 1 and self.usb_port == str(
                                     self.initial_serial_devices[1]):
                            self.usb_port = str(self.initial_serial_devices[0])

                        print("Will try a new USB port: " + str(self.usb_port))
                        self.meter = SmartMeter(self.usb_port)

                except Exception as ex:
                    print(
                        "Automatic switching to different USB port failed: " +
                        str(ex))

            time.sleep(1)
            seconds_counter += 1

        if self.DEBUG:
            print("While-loop in clock thread has been exited")
コード例 #23
0
ファイル: test_meter.py プロジェクト: qsmits/smeterd
def test_meter_ok():
    serial.Serial = SerialMock
    meter = SmartMeter('/dev/ttyUSB0')
    assert meter.port == '/dev/ttyUSB0'
    assert meter.connected() == True
コード例 #24
0
    def __init__(self, verbose=True):
        """
        Initialize the object.

        verbose -- whether or not to enable verbose logging
        """
        print("Initialising P1 adapter")
        self.pairing = False
        self.name = self.__class__.__name__
        self.addon_name = 'p1-adapter'
        Adapter.__init__(self, 'p1-adapter', 'p1-adapter', verbose=verbose)
        #print("Adapter ID = " + self.get_id())

        self.addon_path = os.path.join(self.user_profile['addonsDir'],
                                       self.addon_name)

        self.DEBUG = True
        self.first_request_done = False
        self.initial_serial_devices = []
        self.running = True
        self.usb_override = False
        self.usb_port = "/dev/ttyUSB0"

        self.previous_consumed_total = None
        self.previous_produced_total = None
        self.previous_gas_total = None

        try:
            self.scan_usb_ports()
        except:
            print("Error during scan of usb ports")

        try:
            self.add_from_config()
        except Exception as ex:
            print("Error loading config (and initialising PyP1 library?): " +
                  str(ex))

        # If only one USB serial device is available, we pick that one anyway, regardless of what the user has selected in the config.
        try:
            if len(self.initial_serial_devices
                   ) == 1 and self.usb_override == False:
                self.usb_port = self.initial_serial_devices[0]
                print("only one Serial USB device found, selecting that one.")
        except Exception as ex:
            print("Error with auto selection of USB port: " + str(ex))

        try:
            print("Attempting to start P1 connection with USB port: " +
                  self.usb_port)
            self.meter = SmartMeter(self.usb_port)
            #print("self.meter is now: " + str(self.meter))

            try:
                # Create the p1 device, and if succesful, start the internal clock
                try:
                    p1_device = P1Device(self)
                    self.handle_device_added(p1_device)
                    self.devices['p1-device'].connected = True
                    self.devices['p1-device'].connected_notify(True)
                    self.thing = self.get_device("p1-device")

                    # Start the clock
                    if self.DEBUG:
                        print("Starting the internal clock")
                    try:
                        t = threading.Thread(target=self.clock)
                        t.daemon = True
                        t.start()
                    except:
                        print("Error starting the clock thread")

                except Exception as ex:
                    print("Could not create p1_device: " + str(ex))

            except Exception as ex:
                print("Error starting p1 meter: " + str(ex))

        except Exception as ex:
            print("Error loading serial: " + str(ex))

        print("End of P1 adapter init process")
コード例 #25
0
ファイル: test_meter.py プロジェクト: qsmits/smeterd
def test_meter_tty_not_available_again():
    meter = SmartMeter('/dev/ttyUSB0')
    packet = meter.read_one_packet()
コード例 #26
0
ファイル: test_meter.py プロジェクト: qsmits/smeterd
def test_meter_read_long_broken_packet():
    serial.Serial = SerialMock
    meter = SmartMeter('/dev/ttyUSB0')
    meter.serial.lines_in_buffer = LONG_BROKEN_PACKET.split('\n')
    meter.read_one_packet()    
コード例 #27
0
ファイル: test_meter.py プロジェクト: jac1nt0/smeterd
def test_meter_tty_not_available_again():
    meter = SmartMeter('/dev/ttyUSB0')
    packet = meter.read_one_packet()
コード例 #28
0
class P1Adapter(Adapter):
    """Adapter for P1"""
    def __init__(self, verbose=True):
        """
        Initialize the object.

        verbose -- whether or not to enable verbose logging
        """
        print("Initialising P1 adapter")
        self.pairing = False
        self.name = self.__class__.__name__
        self.addon_name = 'p1-adapter'
        Adapter.__init__(self, 'p1-adapter', 'p1-adapter', verbose=verbose)
        #print("Adapter ID = " + self.get_id())

        self.addon_path = os.path.join(self.user_profile['addonsDir'],
                                       self.addon_name)

        self.DEBUG = True
        self.first_request_done = False
        self.initial_serial_devices = []
        self.running = True
        self.usb_override = False
        self.usb_port = "/dev/ttyUSB0"

        self.previous_consumed_total = None
        self.previous_produced_total = None
        self.previous_gas_total = None

        try:
            self.scan_usb_ports()
        except:
            print("Error during scan of usb ports")

        try:
            self.add_from_config()
        except Exception as ex:
            print("Error loading config (and initialising PyP1 library?): " +
                  str(ex))

        # If only one USB serial device is available, we pick that one anyway, regardless of what the user has selected in the config.
        try:
            if len(self.initial_serial_devices
                   ) == 1 and self.usb_override == False:
                self.usb_port = self.initial_serial_devices[0]
                print("only one Serial USB device found, selecting that one.")
        except Exception as ex:
            print("Error with auto selection of USB port: " + str(ex))

        try:
            print("Attempting to start P1 connection with USB port: " +
                  self.usb_port)
            self.meter = SmartMeter(self.usb_port)
            #print("self.meter is now: " + str(self.meter))

            try:
                # Create the p1 device, and if succesful, start the internal clock
                try:
                    p1_device = P1Device(self)
                    self.handle_device_added(p1_device)
                    self.devices['p1-device'].connected = True
                    self.devices['p1-device'].connected_notify(True)
                    self.thing = self.get_device("p1-device")

                    # Start the clock
                    if self.DEBUG:
                        print("Starting the internal clock")
                    try:
                        t = threading.Thread(target=self.clock)
                        t.daemon = True
                        t.start()
                    except:
                        print("Error starting the clock thread")

                except Exception as ex:
                    print("Could not create p1_device: " + str(ex))

            except Exception as ex:
                print("Error starting p1 meter: " + str(ex))

        except Exception as ex:
            print("Error loading serial: " + str(ex))

        print("End of P1 adapter init process")

    def clock(self):
        """ Runs every minute and updates which devices are still connected """
        if self.DEBUG:
            print("clock thread init")

        seconds_counter = 50
        minutes_counter = 0
        while self.running:
            try:
                current_time = int(time.time())
                if self.DEBUG:
                    print("CLOCK TICK " + str(current_time))

                packet = self.meter.read_one_packet()
                if self.DEBUG:
                    print("packet = " + str(packet))

                property_counter_before = len(self.thing.properties)

                #
                #  KWH
                #

                try:
                    kwh = packet['kwh']

                    if self.DEBUG:
                        print("--------KWH---------")

                        for key, value in kwh.items():
                            print(key, ' : ', value)

                        print("--------------------")

                    if 'low' in kwh:
                        if 'consumed' in kwh['low']:
                            targetProperty = self.thing.find_property(
                                'kwh-low-consumed')
                            if targetProperty == None:
                                if self.DEBUG:
                                    print(
                                        "-property did not exist yet. Creating it now."
                                    )
                                self.thing.properties[
                                    "kwh-low-consumed"] = P1Property(
                                        self.thing, "kwh-low-consumed", {
                                            'label': "Low consumed",
                                            'type': 'number',
                                            'unit': 'kwh',
                                            'readOnly': True,
                                            'multipleOf': 0.001,
                                        }, kwh['low']['consumed'])
                                targetProperty = self.thing.find_property(
                                    'kwh-low-consumed')

                            new_value = get_int_or_float(
                                kwh['low']['consumed'])
                            targetProperty.update(new_value)

                        if 'produced' in kwh['low']:
                            targetProperty = self.thing.find_property(
                                'kwh-low-produced')
                            if targetProperty == None:
                                self.thing.properties[
                                    "kwh-low-produced"] = P1Property(
                                        self.thing, "kwh-low-produced", {
                                            'label': "Low produced",
                                            'type': 'number',
                                            'unit': 'kwh',
                                            'readOnly': True,
                                            'multipleOf': 0.001,
                                        }, kwh['low']['produced'])
                                targetProperty = self.thing.find_property(
                                    'kwh-low-produced')

                            new_value = get_int_or_float(
                                kwh['low']['produced'])
                            targetProperty.update(new_value)

                    if 'high' in kwh:
                        if 'consumed' in kwh['high']:
                            targetProperty = self.thing.find_property(
                                'kwh-high-consumed')
                            if targetProperty == None:
                                self.thing.properties[
                                    "kwh-high-consumed"] = P1Property(
                                        self.thing, "kwh-high-consumed", {
                                            'label': "High consumed",
                                            'type': 'number',
                                            'unit': 'kwh',
                                            'readOnly': True,
                                            'multipleOf': 0.001,
                                        }, kwh['high']['consumed'])
                                targetProperty = self.thing.find_property(
                                    'kwh-high-consumed')

                            new_value = get_int_or_float(
                                kwh['high']['consumed'])
                            targetProperty.update(new_value)

                        if 'produced' in kwh['high']:
                            targetProperty = self.thing.find_property(
                                'kwh-high-produced')
                            if targetProperty == None:
                                self.thing.properties[
                                    "kwh-high-produced"] = P1Property(
                                        self.thing, "kwh-high-produced", {
                                            'label': "High produced",
                                            'type': 'number',
                                            'unit': 'kwh',
                                            'readOnly': True,
                                            'multipleOf': 0.001,
                                        }, kwh['high']['produced'])

                                targetProperty = self.thing.find_property(
                                    'kwh-high-produced')

                            new_value = get_int_or_float(
                                kwh['high']['produced'])
                            targetProperty.update(new_value)

                    if 'high' in kwh:
                        if 'consumed' in kwh['high']:
                            if 'low' in kwh:
                                if 'consumed' in kwh['low']:
                                    consumed_total = get_int_or_float(
                                        kwh['high']
                                        ['consumed']) + get_int_or_float(
                                            kwh['low']['consumed'])
                                    if self.DEBUG:
                                        print("total consumed = " +
                                              str(consumed_total))

                                    if self.previous_consumed_total == None:
                                        self.previous_consumed_total = consumed_total

                                    targetProperty = self.thing.find_property(
                                        'kwh-total-consumed')
                                    if targetProperty == None:
                                        self.thing.properties[
                                            "kwh-total-consumed"] = P1Property(
                                                self.thing,
                                                "kwh-total-consumed", {
                                                    '@type': 'LevelProperty',
                                                    'label': "Total consumed",
                                                    'type': 'number',
                                                    'unit': 'kwh',
                                                    'readOnly': True,
                                                    'multipleOf': 0.001,
                                                }, consumed_total)

                                        targetProperty = self.thing.find_property(
                                            'kwh-total-consumed')

                                    new_value = get_int_or_float(
                                        consumed_total)
                                    targetProperty.update(new_value)

                    if 'high' in kwh:
                        if 'produced' in kwh['high']:
                            if 'low' in kwh:
                                if 'produced' in kwh['low']:
                                    produced_total = get_int_or_float(
                                        kwh['high']
                                        ['produced']) + get_int_or_float(
                                            kwh['low']['produced'])
                                    if self.DEBUG:
                                        print("total produced = " +
                                              str(produced_total))

                                    if self.previous_produced_total == None:
                                        self.previous_produced_total = produced_total

                                    targetProperty = self.thing.find_property(
                                        'kwh-total-produced')
                                    if targetProperty == None:
                                        self.thing.properties[
                                            "kwh-total-produced"] = P1Property(
                                                self.thing,
                                                "kwh-total-produced", {
                                                    'label': "Total produced",
                                                    'type': 'number',
                                                    'unit': 'kwh',
                                                    'readOnly': True,
                                                    'multipleOf': 0.001,
                                                }, produced_total)

                                        targetProperty = self.thing.find_property(
                                            'kwh-total-produced')

                                    new_value = get_int_or_float(
                                        produced_total)
                                    targetProperty.update(new_value)

                    if 'current_consumed' in kwh:
                        targetProperty = self.thing.find_property(
                            'kwh-current-consumed')
                        if targetProperty == None:
                            self.thing.properties[
                                "kwh-current-consumed"] = P1Property(
                                    self.thing, "kwh-current-consumed", {
                                        'label': "Current consumed",
                                        'type': 'number',
                                        'unit': 'kwh',
                                        'readOnly': True,
                                        'multipleOf': 0.001,
                                    }, kwh['current_consumed'])
                            targetProperty = self.thing.find_property(
                                'kwh-current-consumed')

                        new_value = get_int_or_float(kwh['current_consumed'])
                        targetProperty.update(new_value)

                    if 'current_produced' in kwh:
                        targetProperty = self.thing.find_property(
                            'kwh-current-produced')
                        if targetProperty == None:
                            self.thing.properties[
                                "kwh-current-produced"] = P1Property(
                                    self.thing, "kwh-current-consumed", {
                                        'label': "Current produced",
                                        'type': 'number',
                                        'unit': 'kwh',
                                        'readOnly': True,
                                        'multipleOf': 0.001,
                                    }, kwh['current_consumed'])
                            targetProperty = self.thing.find_property(
                                'kwh-current-produced')

                        new_value = get_int_or_float(kwh['current_produced'])
                        targetProperty.update(new_value)

                    if 'tariff' in kwh:
                        targetProperty = self.thing.find_property('kwh-tariff')
                        if targetProperty == None:
                            self.thing.properties["kwh-tariff"] = P1Property(
                                self.thing,
                                "kwh-tariff",
                                {
                                    'label': "Tariff",
                                    'type': 'integer',
                                    'readOnly': True,
                                    #'multipleOf':0.001,
                                },
                                kwh['tariff'])
                            targetProperty = self.thing.find_property(
                                'kwh-tariff')

                        new_value = get_int_or_float(kwh['tariff'])
                        targetProperty.update(new_value)

                except Exception as ex:
                    if self.DEBUG:
                        print("Energy use update error: " + str(ex))

                #
                #  INSTANTANEOUS POWER
                #

                try:
                    instant = packet['instantaneous']

                    instant_total_watts = 0

                    if self.DEBUG:
                        print("--------INSTANTANEOUS---------")

                        for key, value in instant.items():
                            print(key, ' : ', value)

                        print("--------------------")

                    if 'l1' in instant:
                        if 'watts' in instant['l1']:
                            targetProperty = self.thing.find_property(
                                'instant-l1-watts')
                            if targetProperty == None:
                                if self.DEBUG:
                                    print(
                                        "-instant-l1-watts property did not exist yet. Creating it now."
                                    )
                                self.thing.properties[
                                    "instant-l1-watts"] = P1Property(
                                        self.thing, "instant-l1-watts", {
                                            'label': "L1 wattage",
                                            'type': 'number',
                                            'unit': 'Watt',
                                            'readOnly': True,
                                            'multipleOf': 0.001,
                                        }, instant['l1']['watts'])
                                targetProperty = self.thing.find_property(
                                    'instant-l1-watts')

                            new_value = get_int_or_float(
                                instant['l1']['watts'])
                            targetProperty.update(new_value)

                            instant_total_watts += new_value

                    if 'l2' in instant:
                        if 'watts' in instant['l2']:
                            targetProperty = self.thing.find_property(
                                'instant-l2-watts')
                            if targetProperty == None:
                                if self.DEBUG:
                                    print(
                                        "-instant-l2-watts property did not exist yet. Creating it now."
                                    )
                                self.thing.properties[
                                    "instant-l2-watts"] = P1Property(
                                        self.thing, "instant-l2-watts", {
                                            'label': "L2 wattage",
                                            'type': 'number',
                                            'unit': 'Watt',
                                            'readOnly': True,
                                            'multipleOf': 0.001,
                                        }, instant['l2']['watts'])
                                targetProperty = self.thing.find_property(
                                    'instant-l2-watts')

                            new_value = get_int_or_float(
                                instant['l2']['watts'])
                            targetProperty.update(new_value)

                            instant_total_watts += new_value

                    if 'l3' in instant:
                        if 'watts' in instant['l3']:
                            targetProperty = self.thing.find_property(
                                'instant-l3-watts')
                            if targetProperty == None:
                                if self.DEBUG:
                                    print(
                                        "-instant-l3-watts property did not exist yet. Creating it now."
                                    )
                            self.thing.properties[
                                "instant-l3-watts"] = P1Property(
                                    self.thing, "instant-l3-watts", {
                                        'label': "L3 wattage",
                                        'type': 'number',
                                        'unit': 'Watt',
                                        'readOnly': True,
                                        'multipleOf': 0.001,
                                    }, instant['l3']['watts'])
                            targetProperty = self.thing.find_property(
                                'instant-l3-watts')

                            new_value = get_int_or_float(
                                instant['l3']['watts'])
                            targetProperty.update(new_value)

                            instant_total_watts += new_value

                    if instant_total_watts != 0:
                        targetProperty = self.thing.find_property(
                            'instant-total-watts')
                        if targetProperty == None:
                            if self.DEBUG:
                                print(
                                    "-instant-total-watts property did not exist yet. Creating it now."
                                )

                            self.thing._type.append('EnergyMonitor')
                            self.thing.properties[
                                "instant-total-watts"] = P1Property(
                                    self.thing, "instant-total-watts", {
                                        '@type': 'InstantaneousPowerProperty',
                                        'label': "Wattage",
                                        'type': 'number',
                                        'unit': 'Watt',
                                        'readOnly': True,
                                        'multipleOf': 0.001,
                                    }, instant_total_watts)
                            targetProperty = self.thing.find_property(
                                'instant-total-watts')

                        new_value = get_int_or_float(instant_total_watts)
                        targetProperty.update(instant_total_watts)

                except Exception as ex:
                    if self.DEBUG:
                        print(
                            "Instantaneous energy use update error (your device simply may not support this): "
                            + str(ex))

                #
                #  GAS
                #

                try:
                    gas = packet['gas']

                    if self.DEBUG:
                        print("--------GAS---------")

                        for key, value in gas.items():
                            print(key, ' : ', value)

                        print("---------------------")

                    if 'total' in gas:
                        targetProperty = self.thing.find_property('gas-total')
                        if targetProperty == None:
                            if self.DEBUG:
                                print(
                                    "gas property did not exist yet, creating it now"
                                )
                            self.thing.properties["gas-total"] = P1Property(
                                self.thing, "gas-total", {
                                    'label': "Gas total",
                                    'type': 'number',
                                    'unit': 'm3',
                                    'readOnly': True,
                                    'multipleOf': 0.001,
                                }, gas['total'])
                            targetProperty = self.thing.find_property(
                                'gas-total')
                            #print("targetProperty gas is now: " + str(targetProperty))

                        new_value = get_int_or_float(gas['total'])
                        gas_total = new_value
                        if self.previous_gas_total == None:
                            self.previous_gas_total = gas_total

                        #print("new gas value: " + str(new_value))
                        targetProperty.update(new_value)

                except Exception as ex:
                    if self.DEBUG:
                        print("Gas update error: " + str(ex))

                try:
                    if seconds_counter > 60:
                        seconds_counter = 0
                        minutes_counter += 1
                        #print("")
                        #print("MINUTE")
                        #print("")
                        #if self.DEBUG:

                        if minutes_counter > 60:  # every hour
                            minutes_counter = 0
                            #print("total consumed = " + str(consumed_total))

                            consumed_delta = consumed_total - self.previous_consumed_total
                            self.previous_consumed = consumed_total

                            produced_delta = produced_total - self.previous_produced_total
                            self.previous_produced_total = produced_total

                            gas_delta = gas_total - self.previous_gas_total
                            self.previous_gas_total = gas_total

                            # Hourly KWH consumption
                            targetProperty = self.thing.find_property(
                                'kwh-hourly-consumed')
                            if targetProperty == None:
                                self.thing.properties[
                                    "kwh-hourly-consumed"] = P1Property(
                                        self.thing, "kwh-hourly-consumed", {
                                            'label': "Hourly consumption",
                                            'type': 'number',
                                            'unit': 'kwh',
                                            'readOnly': True,
                                            'multipleOf': 0.001,
                                        }, consumed_delta)

                                targetProperty = self.thing.find_property(
                                    'kwh-total-consumed')

                            targetProperty.update(consumed_delta)

                            # Hourly KWH production
                            targetProperty = self.thing.find_property(
                                'kwh-hourly-produced')
                            if targetProperty == None:
                                self.thing.properties[
                                    "kwh-hourly-produced"] = P1Property(
                                        self.thing, "kwh-hourly-produced", {
                                            'label': "Hourly production",
                                            'type': 'number',
                                            'unit': 'kwh',
                                            'readOnly': True,
                                            'multipleOf': 0.001,
                                        }, produced_delta)

                                targetProperty = self.thing.find_property(
                                    'kwh-total-consumed')

                            targetProperty.update(produced_delta)

                            # Hourly GAS consumption
                            targetProperty = self.thing.find_property(
                                'gas-hourly')
                            if targetProperty == None:
                                self.thing.properties[
                                    "gas-hourly"] = P1Property(
                                        self.thing, "gas-hourly", {
                                            'label': "Hourly gas consumption",
                                            'type': 'number',
                                            'unit': 'm3',
                                            'readOnly': True,
                                            'multipleOf': 0.001,
                                        }, gas_delta)

                                targetProperty = self.thing.find_property(
                                    'gas-hourly')

                            targetProperty.update(gas_delta)

                except Exception as ex:
                    if self.DEBUG:
                        print("Hourly values update error: " + str(ex))

                # If the amount of properties has increased, tell the Gateway about this.
                if property_counter_before != len(self.thing.properties):
                    self.handle_device_added(self.thing)

                if self.thing.connected == False:
                    self.thing.connected = True
                    self.thing.connected_notify(True)

            except Exception as ex:
                print("Error handling incoming data: " + str(ex))
                try:
                    self.thing.connected = False
                    self.thing.connected_notify(False)
                except Exception as ex:
                    print("Error updating connection status: " + str(ex))

                try:
                    if str(ex).startswith(
                            'read failed: device reports readiness'):
                        print(
                            "It's likely that the wrong USB port has been selected. Will attempt to switch."
                        )
                        print("len(self.initial_serial_devices) = " +
                              str(len(self.initial_serial_devices)))
                        print("self.initial_serial_devices = " +
                              str(self.initial_serial_devices))
                        print(
                            "str(self.initial_serial_devices[0]['port_id']) = "
                            + str(self.initial_serial_devices[0]))

                        if len(self.initial_serial_devices
                               ) > 1 and self.usb_port == str(
                                   self.initial_serial_devices[0]):
                            self.usb_port = str(self.initial_serial_devices[1])
                        elif len(self.initial_serial_devices
                                 ) > 2 and self.usb_port == str(
                                     self.initial_serial_devices[1]):
                            self.usb_port = str(self.initial_serial_devices[2])
                        elif len(self.initial_serial_devices
                                 ) > 1 and self.usb_port == str(
                                     self.initial_serial_devices[1]):
                            self.usb_port = str(self.initial_serial_devices[0])

                        print("Will try a new USB port: " + str(self.usb_port))
                        self.meter = SmartMeter(self.usb_port)

                except Exception as ex:
                    print(
                        "Automatic switching to different USB port failed: " +
                        str(ex))

            time.sleep(1)
            seconds_counter += 1

        if self.DEBUG:
            print("While-loop in clock thread has been exited")

    def unload(self):
        print("Shutting down P1 adapter")
        self.running = False

    def remove_thing(self, device_id):
        if self.DEBUG:
            print("-----REMOVING:" + str(device_id))

        try:
            obj = self.get_device(device_id)
            self.handle_device_removed(obj)  # Remove from device dictionary
            print("Removed device")
        except:
            print("Could not remove things from devices")

    def scan_usb_ports(self):  # Scans for USB serial devices
        if self.DEBUG:
            print("Scanning USB serial devices")
        #initial_serial_devices = set()
        #result = {"state":"stable","port_id":[]}
        self.initial_serial_devices = []

        try:
            ports = prtlst.comports()
            if self.DEBUG:
                print("All serial ports: " + str(ports))
            for port in ports:
                if 'USB' in port[1]:  #check 'USB' string in device description

                    if self.DEBUG:
                        print(
                            "adding possible port with 'USB' in name to list: "
                            + str(port))
                    #if self.DEBUG:
                    #    print("port: " + str(port[0]))
                    #    print("usb device description: " + str(port[1]))
                    if str(port[0]) not in self.initial_serial_devices:
                        self.initial_serial_devices.append(str(port[0]))

        except Exception as e:
            print("Error getting serial ports list: " + str(e))

    def add_from_config(self):
        """Attempt to add all configured devices."""
        try:
            database = Database('p1-adapter')
            if not database.open():
                return

            config = database.load_config()
            database.close()
        except:
            print("Error! Failed to open settings database.")
            return

        if not config:
            print("Error loading config from database")
            return

        # Debug
        try:
            if 'Debugging' in config:
                self.DEBUG = bool(config['Debugging'])
                if self.DEBUG:
                    print("Debugging is set to: " + str(self.DEBUG))
            else:
                self.DEBUG = False
        except:
            print("Error loading debugging preference")

        # USB port from dropdown
        try:
            if 'USB port' in config:
                if str(config['USB port']) == 'USB port 1':
                    self.usb_port = self.initial_serial_devices[0]
                if str(config['USB port']) == 'USB port 2':
                    self.usb_port = self.initial_serial_devices[1]
                if str(config['USB port']) == 'USB port 3':
                    self.usb_port = self.initial_serial_devices[2]
                if str(config['USB port']) == 'USB port 4':
                    self.usb_port = self.initial_serial_devices[3]
        except Exception as ex:
            print("Error with USB port selection: " + str(ex))

        # Custom USB port command. Overrides dropdown selection.
        try:
            if 'Custom USB port command' in config:
                if str(config['Custom USB port command']) != "":
                    self.usb_override = True
                    self.usb_port = str(config['Custom USB port command'])
                else:
                    print("Custom USB port command was empty")

        except Exception as ex:
            print("Error setting custom USB port command:" + str(ex))

        print("selected USB port: " + str(self.usb_port))
コード例 #29
0
 def __init__(self, file='/dev/ttyUSB0'):
     self.meter = SmartMeter(file,
                             baudrate=115200,
                             parity='N',
                             stopbits=1,
                             bytesize=8)
コード例 #30
0
ファイル: test_meter.py プロジェクト: jac1nt0/smeterd
def test_meter_ok():
    serial.Serial = SerialMock
    meter = SmartMeter('/dev/ttyUSB0')
    assert meter.port == '/dev/ttyUSB0'
    assert meter.connected() == True
コード例 #31
0
    def run(self, args, parser):
        meter = SmartMeter(
            args.serial_port,
            baudrate=args.serial_baudrate,
            bytesize=args.serial_bytesize,
            parity=args.serial_parity,
            stopbits=args.serial_stopbits,
            xonxoff=args.serial_xonxoff,
            timeout=args.serial_timeout,
        )

        try:
            packet = meter.read_one_packet()
        except SerialException as e:
            parser.error(e)
        finally:
            meter.disconnect()

        if args.raw:
            print(str(packet))
            return 0

        # Set multiplication factor based on requested unit
        elec_unit_factor = {
            'Wh': 1000,
            'kWh': 1,
            'J': 1000 * 3600,
            'MJ': 1000 * 3600 / 1000 / 1000
        }
        gas_unit_factor = {
            'm3': 1000,
            'l': 1,
            'J': 43.935,
            'MJ': 1000 *
            43.935  # 43.46 - 44.41 MJ/m^3(n) legal Wobbe-index ('Bovenwaarde') for Dutch Groningen gas, also widely used in north-west Europe: https://wetten.overheid.nl/BWBR0035367/2019-01-01#Bijlage2
        }

        # Construct output depending on user request
        data = []
        if ('time' in args.show_output):
            data.append(('Time', datetime.now()))
        if ('kwh_eid' in args.show_output):
            data.append(('Electricity serial', packet['kwh']['eid']))
        if ('gas_eid' in args.show_output):
            data.append(('Gas serial', packet['gas']['eid']))
        if ('consumed' in args.show_output):
            data.extend([
                ('Total electricity consumed (high, ' + args.elec_unit + ')',
                 int(packet['kwh']['high']['consumed'] *
                     elec_unit_factor[args.elec_unit])),
                ('Total electricity consumed (low, ' + args.elec_unit + ')',
                 int(packet['kwh']['low']['consumed'] *
                     elec_unit_factor[args.elec_unit])),
                ('Total gas consumed (' + args.gas_unit + ')',
                 int(packet['gas']['total'] * gas_unit_factor[args.gas_unit]))
            ])
        if ('produced' in args.show_output):
            data.extend([
                ('Total electricity produced (high, ' + args.elec_unit + ')',
                 int(packet['kwh']['high']['produced'] *
                     elec_unit_factor[args.elec_unit])),
                ('Total electricity produced (low, ' + args.elec_unit + ')',
                 int(packet['kwh']['low']['produced'] *
                     elec_unit_factor[args.elec_unit]))
            ])
        if ('current' in args.show_output):
            data.extend([('Current electricity consumption (W)',
                          int(packet['kwh']['current_consumed'] * 1000)),
                         ('Current electricity production (W)',
                          int(packet['kwh']['current_produced'] * 1000))])
        if ('tariff' in args.show_output):
            data.append(
                ('Current electricity tariff', packet['kwh']['tariff']))
        if ('gas_measured_at' in args.show_output):
            data.append(('Gas measured at', packet['gas']['measured_at']))

        if args.tsv:
            print('\t'.join(map(str, [d for k, d in data])))
        else:
            print('\n'.join(['%-40s %s' % (k, d) for k, d in data]))

        return 0
コード例 #32
0
ファイル: test_meter.py プロジェクト: nrocco/smeterd
def test_meter_read_broken_packet():
    serial.Serial = SerialMock
    meter = SmartMeter('/dev/ttyUSB0')
    meter.serial.lines_in_buffer = BROKEN_PACKET.splitlines(True)
    meter.read_one_packet()
コード例 #33
0
"""
You probably want to run this as a deamon on startup
"""
from smeterd.meter import SmartMeter
import sys
import os
import time
import pyrebase
from time import sleep

meter = SmartMeter("/dev/ttyUSB0")
meter.serial.baudrate = 115200
meter.connect()

api = os.environ["APIKEY"]

config = {
    "apiKey": "AIzaSyC9cO-6W6SJ5oz8I_8Ewysf3S2E9Ubx-KQ",
    "authDomain": "energytracking-65210.firebaseapp.com",
    "databaseURL": "https://energytracking-65210.firebaseio.com",
    "storageBucket": "energytracking-65210.appspot.com",
    "serviceAccount": "sdk-key.json"
}

firebase = pyrebase.initialize_app(config)
auth = firebase.auth()

token = auth.create_custom_token("your_custom_id")
user = auth.sign_in_with_custom_token(token)

db = firebase.database()