def sms(message, subscriber='Default'): ''' Sends an SMS message through ClickaTell gateway. Example: sms("Hello") Example: sms("Hello", 'Amanda') @param param1: SMS Text @param param2: Subscriber. A numeric phone number or a phonebook name entry (String) ''' log = logging.getLogger(LOG_PREFIX) phoneNumber = config.clickatell['phonebook'].get(subscriber, None) if phoneNumber is None: if subscriber.isdigit(): phoneNumber = subscriber else: log.error("Subscriber " + subscriber + " wasn't found in the phone book") return gateway = Clickatell(config.clickatell['user'], config.clickatell['password'], config.clickatell['apiid'], config.clickatell['sender']) message = {'to': phoneNumber, 'text': message} log.info("Sending SMS to: " + str(phoneNumber)) retval, msg = gateway.sendmsg(message) if retval == True: log.info("SMS Sent: " + msg) else: log.error("Error while sending SMS: " + str(retval)) return
def __init__(self, parent, zoneNumber, cfg): ''' Initialise the IdeAlarmZone class Expects: - Parent object - zoneNumber (integer) The zone's ordinal number - cfg (dictionary) The zone's configuration dictionary ''' self._armingMode = None self._zoneStatus = None self.zoneNumber = zoneNumber self.alertDevices = cfg['alertDevices'] self.name = cfg['name'] self.armAwayToggleSwitch = cfg['armAwayToggleSwitch'] self.armHomeToggleSwitch = cfg['armHomeToggleSwitch'] self.mainZone = cfg['mainZone'] self.canArmWithTrippedSensors = cfg['canArmWithTrippedSensors'] self.alarmTestMode = parent.alarmTestMode self.parent = weakref.ref(parent) # <= garbage-collector safe! self.log = logging.getLogger(LOG_PREFIX + '.IdeAlarmZone.' + self.name.decode('utf8')) self.sensors = [] for sensor in cfg['sensors']: self.sensors.append(IdeAlarmSensor(self, sensor)) self.armingModeItem = cfg['armingModeItem'] self.statusItem = cfg['statusItem'] self.openSections = self.countOpenSections() self.setArmingMode( getItemValue(self.armingModeItem, ARMINGMODE['DISARMED']) ) # Will also set the zone status to normal self.log.info('ideAlarm Zone ' + self.name.decode('utf8') + ' initialized with ' + str(self.openSections) + ' open sensors')
def playsound(fileName, ttsPrio=PRIO['MODERATE'], **keywords): ''' Play a sound mp3 file function. First argument is positional and mandatory. Remaining arguments are optionally keyword arguments. Example: playsound("Hello.mp3") Example: playsound("Hello.mp3", PRIO['HIGH'], room='Kitchen', volume=42) @param param1: Sound file name to play (positional argument) (files need to be put in the folder conf/sounds) @param param2: Priority as defined by PRIO. Defaults to PRIO['MODERATE'] @param room: Room to play in. Defaults to "All". @return: this is a description of what is returned ''' module_name = 'playsound' log = logging.getLogger(LOG_PREFIX+'.'+module_name) log.setLevel(logging.INFO) def getDefaultRoom(): # Search for the default room to speak in for the_key, the_value in config.sonos['rooms'].iteritems(): if the_value['defaultttsdevice']: return the_key return 'All' if ((getItemValue(config.customItemNames['allowTTSSwitch'], ON) != ON) and (ttsPrio <= PRIO['MODERATE'])): log.info(unicode(config.customItemNames['allowTTSSwitch']) + " is OFF and ttsPrio is to low to play sound \'" + fileName + "\' at this moment.") return False room = getDefaultRoom() if 'room' not in keywords else keywords['room'] rooms = [] if room == 'All' or room is None: for the_key, the_value in config.sonos['rooms'].iteritems(): rooms.append(config.sonos['rooms'][the_key]) log.debug('Room found: ' + config.sonos['rooms'][the_key]['name']) else: sonosSpeaker = config.sonos['rooms'].get(room, None) if sonosSpeaker is None: log.error("Room "+room+" wasn't found in the sonos rooms dictionary") return rooms.append(sonosSpeaker) log.debug('Room found: ' + sonosSpeaker['name']) for aRoom in rooms: ttsVol = None if 'ttsVol' not in keywords else keywords['ttsVol'] if not ttsVol or ttsVol >= 70: if ttsPrio == PRIO['LOW']: ttsVol = 30 elif ttsPrio == PRIO['MODERATE']: ttsVol = 40 elif ttsPrio == PRIO['HIGH']: ttsVol = 60 elif ttsPrio == PRIO['EMERGENCY']: ttsVol = 70 else: ttsVol = aRoom['ttsvolume'] Audio.playSound(aRoom['audiosink'], fileName) log.info("playSound: \'" + fileName + "\'" + ' in room: \'' + aRoom['name'] + '\' at volume: \'' + str(ttsVol) + '\'.') return True
def __init__(self, callback, triggers, extended=False, name=None): self.triggers = triggers self.callback = callback self.extended = extended if name is None and hasattr(callback, '__name__'): name = callback.__name__ self.log = logging.getLogger(LOG_PREFIX + ("" if name is None else ("." + name)))
class OsgiEventAdmin(object): log = logging.getLogger("jython.lucid.osgi.events.OsgiEventAdmin") _event_handler = None _event_listeners = [] # Singleton class OsgiEventHandler(EventHandler): def __init__(self): self.log = logging.getLogger("jython.lucid.osgi.events.OsgiEventHandler") self.registration = bundle_context.registerService( EventHandler, self, hashtable((EventConstants.EVENT_TOPIC, ["*"]))) self.log.info("Registered lucid OSGI event listener service") self.log.debug("registration=%s", self.registration) def handleEvent(self, event): self.log.debug("handling event %s", event) for listener in OsgiEventAdmin._event_listeners: try: listener(event) except: self.log.error("Listener failed: %s", traceback.format_exc()) def dispose(self): self.registration.unregister() @classmethod def add_listener(cls, listener): cls.log.debug("adding listener admin=%s %s", id(cls), listener) cls._event_listeners.append(listener) if len(cls._event_listeners) == 1: if cls._event_handler is None: cls._event_handler = cls.OsgiEventHandler() @classmethod def remove_listener(cls, listener): cls.log.debug("removing listener %s", listener) if listener in cls._event_listeners: cls._event_listeners.remove(listener) if len(cls._event_listeners) == 0: if cls._event_handler is not None: cls.log.info("Unregistering lucid OSGI event listener service") cls._event_handler.dispose() cls._event_handler = None
def __init__(self, parent, cfg): ''' Initialise the IdeAlarmSensor class Expects: - Parent object - cfg (dictionary) The sensor's configuration dictionary ''' self.name = cfg['name'] _label = itemRegistry.getItem(self.name).label self.label = _label if _label is not None else 'Sensor has no label' self.parent = weakref.ref(parent) # <= garbage-collector safe! self.sensorClass = cfg['sensorClass'] self.nag = cfg['nag'] self.nagTimeoutMins = cfg['nagTimeoutMins'] self.armWarn = cfg['armWarn'] self.enabled = cfg['enabled'] self.log = logging.getLogger(LOG_PREFIX + '.IdeAlarmSensor.' + self.name.decode('utf8'))
def __init__(self): ''' Initialise the IdeAlarm class Expects: - Nothing really... ''' self.__version__ = '3.0.1' self.__version_info__ = tuple( [int(num) for num in self.__version__.split('.')]) self.log = logging.getLogger(LOG_PREFIX + '.IdeAlarm V' + self.__version__) import idealarm.config ######### TEMP #reload(idealarm.config) ######### TEMP #self.log.debug('Configuration file has been reloaded!!!') ######### TEMP import idealarm.config as _cfg self.alarmTestMode = _cfg.ALARM_TEST_MODE self.loggingLevel = _cfg.LOGGING_LEVEL self.nagIntervalMinutes = _cfg.NAG_INTERVAL_MINUTES self.timeCreated = DateTime.now() self.alarmZones = [] for i in range(len(_cfg.ALARM_ZONES)): zoneNumber = i + 1 self.alarmZones.append( IdeAlarmZone(self, zoneNumber, _cfg.ALARM_ZONES[i])) for alarmZone in self.alarmZones: alarmZone.getNagSensors() self.log.info('ideAlarm object initialized with ' + str(len(self.alarmZones)) + ' zones at ' + str(self.timeCreated))
def __init__(self): self.log = logging.getLogger("jython.lucid.osgi.events.OsgiEventHandler") self.registration = bundle_context.registerService( EventHandler, self, hashtable((EventConstants.EVENT_TOPIC, ["*"]))) self.log.info("Registered lucid OSGI event listener service") self.log.debug("registration=%s", self.registration)
from org.osgi.service.cm import ManagedService from org.eclipse.smarthome.config.core import Configuration from org.eclipse.smarthome.automation.handler import TriggerHandler import lucid from lucid.jsr223 import scope scope.scriptExtension.importPreset("RuleSupport") from lucid.osgi import bundle_context from lucid.log import logging import uuid import java.util log = logging.getLogger("jython.lucid.osgi.events") def hashtable(*key_values): """ :param key_values: 2-tuples of (key, value) :return: initialized Hashtable """ ht = java.util.Hashtable() for k, v in key_values: ht.put(k, v) return ht class OsgiEventAdmin(object): log = logging.getLogger("jython.lucid.osgi.events.OsgiEventAdmin") _event_handler = None
# -*- coding: utf-8 -*- from org.eclipse.smarthome.core.types import UnDefType from org.eclipse.smarthome.core.library.types import IncreaseDecreaseType, NextPreviousType, OnOffType, OpenClosedType, PlayPauseType, RewindFastforwardType, StopMoveType, UpDownType, DecimalType import org.joda.time.DateTime as DateTime from org.joda.time.format import DateTimeFormat from lucid.log import logging, LOG_PREFIX import lucid.config as config log = logging.getLogger(LOG_PREFIX + '.utils') import random import time # Get direct access to the JSR223 scope types and objects (for Jython modules imported into scripts) from lucid.jsr223.scope import events, itemRegistry # Some useful dictionaries PRIO = {'LOW': 0, 'MODERATE': 1, 'HIGH': 2, 'EMERGENCY': 3} LUX_LEVEL = {'BLACK': 6, 'DARK': 60, 'SHADY': 380} LIGHT_LEVEL = {'BLACK': 0, 'DARK': 1, 'SHADY': 2, 'BRIGHT': 3} PUSHOVER_PRIO = { 'LOWEST': -2, 'LOW': -1, 'NORMAL': 0, 'HIGH': 1, 'EMERGENCY': 2 } MODE = {'OFF': 0, 'ON': 1} LIGHTING_THEME = { 'OFF': 0, 'NORMAL': 1, 'MOVIE': 2, 'DINNER': 3,
# -*- coding: utf-8 -*- import weakref # Using this to prevent problems with garbage collection # Get direct access to the JSR223 scope types and objects (for Jython modules imported into scripts) from lucid.jsr223.scope import events, itemRegistry from org.eclipse.smarthome.model.persistence.extensions import PersistenceExtensions from org.eclipse.smarthome.core.types import UnDefType from org.eclipse.smarthome.core.library.types import OnOffType, OpenClosedType from logging import DEBUG, INFO, WARNING, ERROR from lucid.triggers import ItemCommandTrigger, ItemStateChangeTrigger from org.joda.time import DateTime from lucid.log import logging, LOG_PREFIX log = logging.getLogger(LOG_PREFIX + '.ideAlarm') from lucid.utils import isActive, getItemValue, postUpdateCheckFirst, sendCommandCheckFirst, kw from idealarm import custom ZONESTATUS = {'NORMAL': 0, 'ALERT': 1, 'ERROR': 2, 'TRIPPED': 3, 'ARMING': 4} ARMINGMODE = {'DISARMED': 0, 'ARMED_HOME': 1, 'ARMED_AWAY': 2} NULL = UnDefType.NULL UNDEF = UnDefType.UNDEF ON = OnOffType.ON OFF = OnOffType.OFF OPEN = OpenClosedType.OPEN CLOSED = OpenClosedType.CLOSED class IdeAlarmError(Exception):
def tts(ttsSay, ttsPrio=PRIO['MODERATE'], **keywords): ''' Text To Speak function. First argument is positional and mandatory. Remaining arguments are optionally keyword arguments. Example: tts("Hello") Example: tts("Hello", PRIO['HIGH'], ttsRoom='Kitchen', ttsVol=42, ttsLang='en-GB', ttsVoice='Brian') @param param1: Text to speak (positional argument) @param param2: Priority as defined by PRIO. Defaults to PRIO['MODERATE'] @param ttsRoom: Room to speak in @return: this is a description of what is returned ''' module_name = 'speak' log = logging.getLogger(LOG_PREFIX + '.' + module_name) log.setLevel(logging.INFO) def getDefaultRoom(): # Search for the default room to speak in for the_key, the_value in config.sonos['rooms'].iteritems(): if the_value['defaultttsdevice']: return the_key return 'All' if ((getItemValue('Sonos_Allow_TTS_And_Sounds', ON) != ON) and (ttsPrio <= PRIO['MODERATE'])): log.info( "Item Sonos_Allow_TTS_And_Sounds is OFF and ttsPrio is to low to speak \'" + ttsSay + "\' at this moment.") return False ttsRoom = getDefaultRoom( ) if 'ttsRoom' not in keywords else keywords['ttsRoom'] ttsRooms = [] if ttsRoom == 'All' or ttsRoom is None: for the_key, the_value in config.sonos['rooms'].iteritems(): ttsRooms.append(config.sonos['rooms'][the_key]) log.debug('TTS room found: ' + config.sonos['rooms'][the_key]['name']) else: sonosSpeaker = config.sonos['rooms'].get(ttsRoom, None) if sonosSpeaker is None: log.error("Room " + ttsRoom + " wasn't found in the sonos rooms dictionary") return ttsRooms.append(sonosSpeaker) log.debug('TTS room found: ' + sonosSpeaker['name']) for room in ttsRooms: ttsVol = None if 'ttsVol' not in keywords else keywords['ttsVol'] if not ttsVol or ttsVol >= 70: if ttsPrio == PRIO['LOW']: ttsVol = 30 elif ttsPrio == PRIO['MODERATE']: ttsVol = 40 elif ttsPrio == PRIO['HIGH']: ttsVol = 60 elif ttsPrio == PRIO['EMERGENCY']: ttsVol = 70 else: ttsVol = room['ttsvolume'] ttsLang = room['ttslang'] if 'ttsLang' not in keywords else keywords[ 'ttsLang'] ttsVoice = room[ 'ttsvoice'] if 'ttsVoice' not in keywords else keywords['ttsVoice'] ttsEngine = room[ 'ttsengine'] if 'ttsEngine' not in keywords else keywords[ 'ttsEngine'] #Voice.say(ttsSay, ttsEngine + ':' + ttsVoice, room['audiosink'], PercentType(10)) # Notification sound volume doesn't seem to be supported Voice.say(ttsSay, ttsEngine + ':' + ttsVoice, room['audiosink']) log.info("TTS: Speaking \'" + ttsSay + "\'" + ' in room: \'' + room['name'] + '\' at volume: \'' + str(ttsVol) + '\'.') return True