Skip to content

Commit

Permalink
Add OemGatewayFileInterface
Browse files Browse the repository at this point in the history
Command line arguments allow the choice between a config file and
a config obtained through emoncms API.

The gateway can now be run without a local emoncms intallation.
  • Loading branch information
Jérôme Lafréchoux committed Jun 14, 2013
1 parent 9362982 commit b46cab7
Show file tree
Hide file tree
Showing 3 changed files with 102 additions and 20 deletions.
25 changes: 19 additions & 6 deletions oemgateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"""

import sys
import time
import logging, logging.handlers
import signal
Expand Down Expand Up @@ -41,7 +42,6 @@ def __init__(self, interface):

# Initialize gateway interface and get settings
self._interface = interface
self._interface.check_settings()
settings = self._interface.settings

# Initialize logging
Expand Down Expand Up @@ -173,11 +173,17 @@ def _set_logging_level(self, level):
if __name__ == "__main__":

# Command line arguments parser
parser = argparse.ArgumentParser(description='RFM2Pi Gateway')
parser = argparse.ArgumentParser(description='OpenEnergyMonitor Gateway')
# Settings source
settings_group = parser.add_mutually_exclusive_group()
settings_group.add_argument("--config-file", action="store", help='Configuration file')
settings_group.add_argument("--config-emoncms", action="store_true", help='Get configuration from emoncms')
# Logfile
parser.add_argument('--logfile', action='store', type=argparse.FileType('a'),
help='path to optional log file (default: log to Standard error stream STDERR)')
# Show settings
parser.add_argument('--show-settings', action='store_true',
help='show RFM2Pi settings and exit (for debugging purposes)')
help='show settings and exit (for debugging purposes)')
args = parser.parse_args()

# Logging configuration
Expand All @@ -200,9 +206,16 @@ def _set_logging_level(self, level):
logger.setLevel(logging.CRITICAL)

# Initialize gateway interface
# TODO: cmd line arg to choose another type of interface
interface = ogi.OemGatewayEmoncmsInterface()

if args.config_emoncms:
interface = ogi.OemGatewayEmoncmsInterface()
elif args.config_file is None:
args.config_file = 'oemgateway.conf'
try:
interface = ogi.OemGatewayFileInterface(args.config_file)
except ogi.OemGatewayInterfaceInitError as e:
logger.critical(e)
sys.exit(0)

# If in "Show settings" mode, print settings and exit
if args.show_settings:
interface.check_settings()
Expand Down
78 changes: 74 additions & 4 deletions oemgatewayinterface.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import time
import logging
import csv
#import configobj
from configobj import ConfigObj

"""class OemGatewayInterface
Expand Down Expand Up @@ -88,15 +88,17 @@ def __init__(self):
# Initialization
super(OemGatewayEmoncmsInterface, self).__init__()

# Initialize status update timestamp
# Initialize update timestamps
self._status_update_timestamp = 0
self._settings_update_timestamp = 0
self._retry_time_interval = 60

# Check settings
self.check_settings()

def run(self):
"""Run in background.
Return True if settings changed, None otherwise.
Update raspberry_pi running status.
"""
Expand Down Expand Up @@ -145,6 +147,7 @@ def check_settings(self):
import traceback
self._log.warning("Couldn't get settings, Exception: " +
traceback.format_exc())
self._settings_update_timestamp = now + self._retry_time_interval
return

settings = {}
Expand Down Expand Up @@ -206,3 +209,70 @@ def _gateway_running(self):
"Couldn't update \"running\" status, Exception: " +
traceback.format_exc())

class OemGatewayFileInterface(OemGatewayInterface):

def __init__(self, filename):

# Initialization
super(OemGatewayFileInterface, self).__init__()

# Initialize update timestamp
self._settings_update_timestamp = 0
self._retry_time_interval = 60

# Initialize attribute settings as a ConfigObj instance
try:
self.settings = ConfigObj(filename, file_error=True)
except IOError as e:
raise OemGatewayInterfaceInitError(e)
except SyntaxError as e:
raise OemGatewayInterfaceInitError( \
'Error parsing config file \"%s\": ' % filename + str(e))

def check_settings(self):
"""Check settings
Update attribute settings and return True if modified.
"""

# Check settings only once per second
now = time.time()
if (now - self._settings_update_timestamp < 1):
return
# Update timestamp
self._settings_update_timestamp = now

# Backup settings
settings = dict(self.settings)

# Get settings from file
try:
self.settings.reload()
except IOError as e:
self._log.warning('Could not get settings: ' + str(e))
self._settings_update_timestamp = now + self._retry_time_interval
return
except SyntaxError as e:
self._log.warning('Could not get settings: ' +
'Error parsing config file: ' + str(e))
self._settings_update_timestamp = now + self._retry_time_interval
return
except Exception:
import traceback
self._log.warning("Couldn't get settings, Exception: " +
traceback.format_exc())
self._settings_update_timestamp = now + self._retry_time_interval
return

if self.settings != settings:
return True

"""class OemGatewayInterfaceInitError
Raise this when init fails.
"""
class OemGatewayInterfaceInitError(Exception):
pass

19 changes: 9 additions & 10 deletions oemgatewaylistener.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,6 @@
import logging
import re


"""class OemGatewayListenerInitError
Raise this when init fails.
"""
class OemGatewayListenerInitError(Exception):
pass

"""class OemGatewayListener
Monitors a data source.
Expand Down Expand Up @@ -198,7 +189,7 @@ def set(self, **kwargs):
time.sleep(1)
elif key == 'sendtimeinterval':
if value != self._settings[key]:
self._log.info("Setting time interval to %s", value)
self._log.info("Setting send time interval to %s", value)
self._settings[key] = value

def run(self):
Expand Down Expand Up @@ -234,3 +225,11 @@ def _send_time(self):

self._ser.write("%02d,00,%02d,00,s" % (now.hour, now.minute))

"""class OemGatewayListenerInitError
Raise this when init fails.
"""
class OemGatewayListenerInitError(Exception):
pass

0 comments on commit b46cab7

Please sign in to comment.