Ejemplo n.º 1
0
 def __init__(self, file='/dev/ttyUSB0'):
     self.meter = SmartMeter(file,
                             baudrate=115200,
                             parity='N',
                             stopbits=1,
                             bytesize=8)
Ejemplo n.º 2
0
def test_meter_typeerror():
    meter = SmartMeter()
Ejemplo n.º 3
0
def test_meter_ok():
    serial.Serial = SerialMock
    meter = SmartMeter('/dev/ttyUSB0')
    assert meter.port == '/dev/ttyUSB0'
    assert meter.connected() == True
Ejemplo n.º 4
0
            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)
Ejemplo n.º 5
0
def test_meter_tty_not_available():
    meter = SmartMeter('/dev/ttyUSB0')
Ejemplo n.º 6
0
def test_meter_tty_not_available_again():
    meter = SmartMeter('/dev/ttyUSB0')
    packet = meter.read_one_packet()
Ejemplo n.º 7
0
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()
Ejemplo n.º 8
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()
Ejemplo n.º 9
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'])
Ejemplo n.º 10
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")
Ejemplo n.º 11
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")