Beispiel #1
0
 def activate(self, conf, glob):
     protocols.activate(self, conf, glob)
     self.pin2index={}
     self.name2index={}
     for key,value in self.conf.iteritems():
         try:
             pin_name = key.split('_')[0]
             pin_data = key.split('_')[1]
             if not self.pin2index.has_key(pin_name):
                 itemList.append({'min':'', 'max':'', 'unit':'', 'type':'R', 'description':''})
                 self.pin2index[pin_name] = len(itemList)-1
             if pin_data == 'function':
                 itemList[self.pin2index[pin_name]]['function'] = value
                 if value in ['counter', 'output', 'timer']:
                     itemList[self.pin2index[pin_name]]['type'] = 'R/W'
             elif pin_data == 'item':
                 itemList[self.pin2index[pin_name]]['name'] = value
                 itemTags[value] = ['All', 'raspberryGPIO', 'Basic']
                 self.name2index[value]=self.pin2index[pin_name]
             elif pin_data == 'pin':
                 itemList[self.pin2index[pin_name]]['pin'] = int(value)
             elif pin_data == 'active':
                 itemList[self.pin2index[pin_name]]['active'] = int(value)
         except Exception,e:
             logger.info(str(e))
Beispiel #2
0
 def activate(self, conf, glob, db, *args, **kwargs):
     protocols.activate(self, conf, glob, db, *args, **kwargs)
     self.power = 0
     self.lock = Lock()
     self.pin2index={}
     self.name2index={}
     self.itemrefs = []
     for key,value in self.conf.iteritems():
         try:
             pin_name = key.split('_')[0]
             pin_data = key.split('_')[1]
             if not self.pin2index.has_key(pin_name):
                 itemList.append({'min':'', 'max':'', 'unit':'', 'type':'R', 'description':''})
                 self.pin2index[pin_name] = len(itemList)-1
             if pin_data == 'function':
                 itemList[self.pin2index[pin_name]]['function'] = value
                 if value in ['counter', 'output', 'timer']:
                     itemList[self.pin2index[pin_name]]['type'] = 'R/W'
             elif pin_data == 'item':
                 itemList[self.pin2index[pin_name]]['name'] = value
                 self.name2index[value]=self.pin2index[pin_name]
             elif pin_data == 'pin':
                 itemList[self.pin2index[pin_name]]['pin'] = int(value)
             elif pin_data == 'active':
                 itemList[self.pin2index[pin_name]]['active'] = int(value)
         except Exception,e:
             logger.info(str(e))
Beispiel #3
0
    def activate(self, conf, glob, db, *args, **kwargs):
        protocols.activate(self, conf, glob, db, *args, **kwargs)
        self.itemrefs = []
        self.itemvalues = {}

        for key, value in self.conf.iteritems():
            itemList.append({'name':key, 'value':value, 'min':'0', 'max':'100', 'unit':'km', 'type':'R/W'})
            itemTags[key] = ['All', 'testplugin', 'Basic']

        for item in itemList:
            self.itemvalues[item['name']] = item['value']

            dbitem = Getsetitem(item['name'], item['value'], lambda i:self.getItem(i), lambda i,v:self.setItem(i,v))
            for key, value in item.iteritems():
                if key is not 'value':
                    dbitem.__setattr__(key, value)
            if dbitem.name in itemTags:
                dbitem.__setattr__('tags', itemTags[dbitem.name])
            self.db.insert(dbitem)
            self.itemrefs.append(dbitem)
            def mysetter(name, value):
                print 'testplugin set: ', name, value
            i = Storeditem('stored', 'defaultvalue', setter=mysetter)
            i.tags = ['All', 'testplugin', 'Basic'] 
            i.type = 'R/W'
            i.min = '0'
            i.max = '120'
            i.unit = 'm'
            i.description = "this is a test item"
            i.longname = "stored item"
            self.db.insert(i)
            self.itemrefs.append(i)
Beispiel #4
0
    def activate(self, conf, glob):
        protocols.activate(self, conf, glob)
        self.request = Queue()
        self.response = Queue()
        self.p = Process(target=root, args=(self.request, self.response))
        self.p.start()
        self.valuestore = ConfigParser()
        self.valuestore.add_section('values')
        self.valuesfile = path.join(path.dirname(__file__), 'values.conf')
        for item in itemList:
            self.valuestore.set('values', item['name'], item['value'])
        self.valuestore.read(self.valuesfile)
        f = open(self.valuesfile, 'w')
        self.valuestore.write(f)
        f.close()
        try:
            uid = pwd.getpwnam(self.glob['conf'].USER).pw_uid
            gid = grp.getgrnam(self.glob['conf'].GROUP).gr_gid
            os.chown(self.valuesfile, uid, gid)
        except:
            pass

        t = Timer(5, self.calc_thread)
        t.setDaemon(True)
        t.start()
Beispiel #5
0
    def activate(self, conf, glob):
        protocols.activate(self, conf, glob)
        global itemList
        if not 'timer' in conf:
            itemList += counter_mode_items
            itemTags.update(counter_mode_tags)

        if not 'state_tracker' in self.conf:
            self.conf['state_tracker'] = 'generic'

        try:
            self.power_window = int(self.conf['power_window'])
            if self.power_window < 60 or self.power_window > 1800:
                raise ValueError
        except:
            self.power_window = 300
        try:
            self.running_timeout = int(self.conf['running_timeout'])
            if self.running_timeout < 5 or self.power_window > 300:
                raise ValueError
        except:
            self.running_timeout = 60
        try:
            self.ignition_timeout = int(self.conf['ignition_timeout'])
            if self.ignition_timeout < 60 or self.ignition_timeout > 1200:
                raise ValueError
        except:
            self.ignition_timeout = 600
        try:
            self.starting_power = float(self.conf['starting_power'])
            if self.starting_power < 0.5 or self.starting_power > 10:
                raise ValueError
        except:
            self.starting_power = 5
        try:
            self.startup_feed_wait = float(self.conf['startup_feed_wait'])
            if self.startup_feed_wait < 10 or self.startup_feed_wait > 300:
                raise ValueError
        except:
            self.startup_feed_wait = 60
        try:
            self.log_changes = [
                s.strip() for s in self.conf['log_changes'].split(',')
            ]
        except:
            self.log_changes = ['mode', 'alarm']

        if conf['state_tracker'] == 'generic':
            itemList += state_tracker_items
            itemTags.update(state_tracker_tags)

        for item in itemList:
            if item['type'] == 'R/W':
                self.store_setting(item['name'], confval=str(item['value']))
        self.migrate_settings('pelletcalc')

        if self.conf['state_tracker'] == 'generic':
            t = Timer(5, self.calc_thread)
            t.setDaemon(True)
            t.start()
Beispiel #6
0
 def activate(self, conf, glob, db, *args, **kwargs):
     protocols.activate(self, conf, glob, db, *args, **kwargs)
     self.power = 0
     self.lock = Lock()
     self.pin2index = {}
     self.name2index = {}
     self.itemrefs = []
     for key, value in self.conf.iteritems():
         try:
             pin_name = key.split('_')[0]
             pin_data = key.split('_')[1]
             if not self.pin2index.has_key(pin_name):
                 itemList.append({
                     'min': '',
                     'max': '',
                     'unit': '',
                     'type': 'R',
                     'description': ''
                 })
                 self.pin2index[pin_name] = len(itemList) - 1
             if pin_data == 'function':
                 itemList[self.pin2index[pin_name]]['function'] = value
                 if value in ['counter', 'output', 'timer']:
                     itemList[self.pin2index[pin_name]]['type'] = 'R/W'
             elif pin_data == 'item':
                 itemList[self.pin2index[pin_name]]['name'] = value
                 self.name2index[value] = self.pin2index[pin_name]
             elif pin_data == 'pin':
                 itemList[self.pin2index[pin_name]]['pin'] = int(value)
             elif pin_data == 'active':
                 itemList[self.pin2index[pin_name]]['active'] = int(value)
         except Exception, e:
             logger.info(str(e))
Beispiel #7
0
    def activate(self, conf, glob):
        protocols.activate(self, conf, glob)
        self.logger = logging.getLogger('pellMon')
        self.dbvalues = {}

        # Initialize protocol and setup the database according to version_string
        try:
            try:
                self.protocol = Protocol(self.conf['serialport'],
                                         self.conf['chipversion'])
            except:
                # Create testprotocol if conf is missing
                self.protocol = Protocol(None, '')
            self.allparameters = self.protocol.getDataBase()

            # Create and start settings_pollthread to log settings changed locally
            settings = menus.getDbWithTags(('Settings', ))
            ht = threading.Timer(3,
                                 self.settings_pollthread,
                                 args=(settings, ))
            ht.setDaemon(True)
            ht.start()

            # Create and start alarm_pollthread to log settings changed locally
            ht = threading.Timer(5,
                                 self.alarm_pollthread,
                                 args=(('mode', 'alarm'), ))
            ht.setDaemon(True)
            ht.start()

            self.dataDescriptions = dataDescriptions
        except:
            self.logger.info('scottecom protocol setup failed')
Beispiel #8
0
    def activate(self, conf, glob):
        protocols.activate(self, conf, glob)
        self.logger = logging.getLogger('pellMon')
        self.dbvalues={}

        # Initialize protocol and setup the database according to version_string
        try:
            try:
                self.protocol = Protocol(self.conf['serialport'], self.conf['chipversion'])
            except:
                # Create testprotocol if conf is missing
                self.protocol = Protocol(None, '')
            self.allparameters = self.protocol.getDataBase()

            # Create and start settings_pollthread to log settings changed locally
            settings = menus.getDbWithTags(('Settings',))
            ht = threading.Timer(3, self.settings_pollthread, args=(settings,))
            ht.setDaemon(True)
            ht.start()

            # Create and start alarm_pollthread to log settings changed locally
            ht = threading.Timer(5, self.alarm_pollthread, args=(('mode', 'alarm'),))
            ht.setDaemon(True)
            ht.start()

            self.dataDescriptions = dataDescriptions
        except:
            self.logger.info('scottecom protocol setup failed')
Beispiel #9
0
    def activate(self, conf, glob, db, *args, **kwargs):
        protocols.activate(self, conf, glob, db, *args, **kwargs)

        self.rrdfile = self.glob['conf'].db
        self.feeder_time = self.glob['conf'].item_to_ds_name['feeder_time']
        self.feeder_capacity = self.glob['conf'].item_to_ds_name['feeder_capacity']
        self.itemrefs = []

        self.migrate_settings('cleaning')

        i = Cacheditem('clean_kg', 0, getter = lambda i:self.get_kg(i), cachetime = 600)
        i.longname = 'Cleaning counter'
        i.type = 'R'
        i.unit = 'kg'
        i.description = 'Amount burned since last cleaning'
        i.tags = ['All', 'Basic', 'Cleaning', 'Overview']
        self.db.insert(i)
        self.itemrefs.append(i)

        i = Storeditem('clean_time', '01/01/14 12:00', setter = lambda i,v:self.set_time(i,v))
        i.longname = 'Last cleaning time'
        i.type = 'R/W'
        i.description = 'dd/mm/yy hh:mm Time when the boiler was cleaned'
        i.tags = ['All', 'Basic', 'Cleaning']
        self.db.insert(i)
        self.itemrefs.append(i)
        
        i = Getsetitem('clean', '-', setter = lambda i,v:self.clean_now(i,v))
        i.type = 'W'
        i.tags = ['All', 'Basic', 'Cleaning']
        self.db.insert(i)
        self.itemrefs.append(i)
Beispiel #10
0
    def activate(self, conf, glob, db, *args, **kwargs):
        protocols.activate(self, conf, glob, db, *args, **kwargs)
        self.logger = logging.getLogger('pellMon')
        self.dbvalues = {}
        self.itemrefs = []

        # Initialize protocol and setup the database according to version_string
        try:
            try:
                self.protocol = Protocol(self.conf['serialport'],
                                         self.conf['chipversion'])
            except:
                # Create testprotocol if conf is missing
                self.protocol = Protocol(None, '')
            self.allparameters = self.protocol.getDataBase()
            """Get list of all data/parameter/command items"""
            params = self.protocol.getDataBase()
            for item in params:
                dbitem = Getsetitem(item, None, lambda i: self.getItem(i),
                                    lambda i, v: self.setItem(i, v))
                if hasattr(params[item], 'max'):
                    dbitem.max = str(params[item].max)
                if hasattr(params[item], 'min'):
                    dbitem.min = str(params[item].min)
                if hasattr(params[item], 'frame'):
                    if hasattr(params[item], 'address'):
                        dbitem.type = 'R/W'
                    else:
                        dbitem.type = 'R'
                else:
                    dbitem.type = 'W'
                dbitem.longname = dataDescriptions[item][0]
                dbitem.unit = dataDescriptions[item][1]
                dbitem.description = dataDescriptions[item][2]
                dbitem.tags = menus.itemtags(item)
                self.db.insert(dbitem)
                self.itemrefs.append(dbitem)

            # Create and start settings_pollthread to log settings changed locally
            settings = [
                item for item in params if 'Settings' in menus.itemtags(item)
            ]
            ht = threading.Timer(3,
                                 self.settings_pollthread,
                                 args=(settings, ))
            ht.setDaemon(True)
            ht.start()

            # Create and start alarm_pollthread to log settings changed locally
            ht = threading.Timer(5,
                                 self.alarm_pollthread,
                                 args=(('mode', 'alarm'), ))
            ht.setDaemon(True)
            ht.start()

            self.dataDescriptions = dataDescriptions
        except:
            self.logger.info('scottecom protocol setup failed')
Beispiel #11
0
    def activate(self, conf, glob):
        protocols.activate(self, conf, glob)
        global itemList
        if not 'timer' in conf:
            itemList += counter_mode_items
            itemTags.update(counter_mode_tags)

        if not 'state_tracker' in self.conf:
            self.conf['state_tracker'] = 'generic'

        try:
            self.power_window = int(self.conf['power_window'])
            if self.power_window < 60 or self.power_window > 1800:
                raise ValueError
        except:
            self.power_window = 300
        try:
            self.running_timeout = int(self.conf['running_timeout'])
            if self.running_timeout < 5 or self.power_window > 300:
                raise ValueError
        except:
            self.running_timeout = 60
        try:
            self.ignition_timeout = int(self.conf['ignition_timeout'])
            if self.ignition_timeout < 60 or self.ignition_timeout > 1200:
                raise ValueError
        except:
            self.ignition_timeout = 600
        try:
            self.starting_power = float(self.conf['starting_power'])
            if self.starting_power < 0.5 or self.starting_power > 10:
                raise ValueError
        except:
            self.starting_power = 5
        try:
            self.startup_feed_wait = float(self.conf['startup_feed_wait'])
            if self.startup_feed_wait < 10 or self.startup_feed_wait > 300:
                raise ValueError
        except:
            self.startup_feed_wait = 60
        try:
            self.log_changes = [s.strip() for s in self.conf['log_changes'].split(',')]
        except:
            self.log_changes = ['mode', 'alarm']

        if conf['state_tracker'] == 'generic':
            itemList += state_tracker_items
            itemTags.update(state_tracker_tags)

        for item in itemList:
            if item['type'] == 'R/W':
                self.store_setting(item['name'], confval = str(item['value']))
        self.migrate_settings('pelletcalc')

        if self.conf['state_tracker'] == 'generic':
            t = Timer(5, self.calc_thread)
            t.setDaemon(True)
            t.start()
Beispiel #12
0
    def activate(self, conf, glob, db, *args, **kwargs):
        protocols.activate(self, conf, glob, db, *args, **kwargs)
        self.itemrefs = []

        config = {}
        for index_key, value in self.conf.items():
            if '_' in index_key:
                index, key = index_key.split('_')
                try:
                    config[index][key] = value
                except KeyError:
                    config[index] = {key: value}
        for index, itemconf in config.items():
            try:
                itemname = itemconf.pop('item')
                itemvalue = itemconf.pop('value', '0')
                readscript = itemconf.pop('readscript', None)
                writescript = itemconf.pop('writescript', None)
                try:
                    cachetime = float(itemconf.pop('cachetime', '0'))
                except:
                    cachetime = 0

                getter = None
                setter = None
                itemtype = 'R'
                if readscript:
                    if writescript:
                        itemtype = 'R/W'
                    getter = lambda item, script=readscript: self.execute_readscript(
                        item, script)
                else:
                    if writescript:
                        itemtype = 'W'
                if writescript:
                    self.writescript = writescript
                    setter = lambda item, value, script=writescript: self.execute_writescript(
                        item, value, script)

                item = Cacheditem(itemname,
                                  itemvalue,
                                  getter=getter,
                                  setter=setter,
                                  cachetime=cachetime)

                for key, value in itemconf.items():
                    setattr(item, key, value)

                item.tags = itemconf.pop('tags', 'All Basic Exec').split(' ')
                item.type = itemtype
                item.min = itemconf.pop('min', '')
                item.max = itemconf.pop('max', '')
                self.db.insert(item)
                self.itemrefs.append(item)

            except Exception, e:
                logger.info('Exec plugin config error: %s', str(e))
                raise
Beispiel #13
0
 def activate(self, conf, glob):
     protocols.activate(self, conf, glob)
     for i in itemList:
         try:
             i['value'] = i['min']
         except:
             i['value'] = '1234'
     for key, value in self.conf.iteritems():
         itemList.append({'name':key, 'value':value, 'min':0, 'max':100, 'unit':'W', 'type':'R/W'})
Beispiel #14
0
 def activate(self, conf, glob):
     protocols.activate(self, conf, glob)
     for i in itemList:
         try:
             i['value'] = i['min']
         except:
             i['value'] = '1234'
     for key, value in self.conf.iteritems():
         itemList.append({'name':key, 'value':value, 'min':0, 'max':100, 'unit':'W', 'type':'R/W'})
         itemTags[key] = ['All', 'testplugin', 'Basic']
     logger.info('testplugin activated...')
Beispiel #15
0
    def activate(self, conf, glob, db, *args, **kwargs):
        protocols.activate(self, conf, glob, db, *args, **kwargs)
        self.itemrefs = []
        for key, value in self.conf.iteritems():
            try:
                alarm_name = key.split('_')[0]
                alarm_data = key.split('_')[1]
                if alarm_data == 'status':
                    alarm_type = 'R'
                    description = 'The name of the parameter that has the status for this alarm'
                elif alarm_data == 'comparator':
                    alarm_type = 'R/W'
                    description = 'Allowed values: >|>=|<|<=|==|!='
                elif alarm_data == 'level':
                    alarm_type = 'R/W'
                    description = 'compare against this value'
                elif alarm_data == 'item':
                    alarm_type = 'R/W'
                    description = 'Parameter to read from'
                elif alarm_data == 'enum':
                    alarm_type = 'R/W'
                    description = 'set to: alarm OFF text|alarm ON text'

                itemList.append({
                    'name': key,
                    'value': value,
                    'min': '',
                    'max': '',
                    'unit': '',
                    'type': alarm_type,
                    'description': description
                })
                itemTags[key] = ['All', 'CustomAlarms', 'Basic']

                if not alarms.has_key(alarm_name):
                    alarms[alarm_name] = {}
                alarm_data = key.split('_')[1]
                if alarm_data == 'status':
                    itemList.append({
                        'name': value,
                        'value': 0,
                        'unit': '',
                        'type': 'R',
                        'description': '%s status' % alarm_name
                    })
                    itemTags[value] = ['All', 'CustomAlarms', 'Basic']

                if alarm_data in ['item', 'comparator', 'level', 'status']:
                    if not alarms.has_key(alarm_name):
                        alarms[alarm_name] = {}
                    alarms[alarm_name][alarm_data] = value
            except Exception, e:
                logger.info(str(e))
            itemTags[key].append(alarm_name)
Beispiel #16
0
 def activate(self, conf, glob, db, *args, **kwargs):
     protocols.activate(self, conf, glob, db, *args, **kwargs)
     self.updateTime = 0
     self.siloData = None
     self.silo_days_left = None
     self.silo_level = 0
     try:
         self.feeder_time = self.glob['conf'].item_to_ds_name['feeder_time']
     except Exception, e:
         logger.info('Silolevel plugin error: feeder_time is missing from the database')
         raise
Beispiel #17
0
    def activate(self, conf, glob):
        protocols.activate(self, conf, glob)

        self.sensors = {}
        self.attributes = {}
        for key, value in self.conf.iteritems():
            itempath = path.dirname(value)
            itemattribute = path.basename(value)
            itemList.append({'name':key, 'value':value, 'min':'', 'max':'', 'unit':'', 'type':'R', 'description':''})           
            itemTags[key] = ['All', 'OWFS', 'Basic']
            self.sensors[key] = ownet.Sensor(itempath, 'localhost', 4304)
            self.attributes[key] = itemattribute
Beispiel #18
0
 def activate(self, conf, glob):
     protocols.activate(self, conf, glob)
     self.items = {i["name"]: i for i in itemList}
     self.db = self.glob["conf"].db
     self.feeder_time = self.glob["conf"].item_to_ds_name["feeder_time"]
     self.feeder_capacity = self.glob["conf"].item_to_ds_name["feeder_capacity"]
     for item in itemList:
         if item["type"] == "R/W":
             self.store_setting(item["name"], confval=item["value"])
         else:
             itemValues[item["name"]] = item["value"]
     self.migrate_settings("cleaning")
Beispiel #19
0
    def activate(self, conf, glob, db, *args, **kwargs):
        protocols.activate(self, conf, glob, db, *args, **kwargs)
        self.itemrefs = []

        config = {}
        for index_key, value in self.conf.items():
            if '_' in index_key:
                index, key = index_key.split('_')
                try:
                    config[index][key] = value
                except KeyError:
                    config[index] = {key:value}
        for index, itemconf in config.items():
            try:
                itemname = itemconf.pop('item')
                itemvalue = itemconf.pop('value', '0')
                readscript = itemconf.pop('readscript', None);
                writescript = itemconf.pop('writescript', None);
                try:
                    cachetime = float(itemconf.pop('cachetime', '0'))
                except:
                    cachetime = 0

                getter = None
                setter = None
                itemtype = 'R'
                if readscript:
                    if writescript:
                        itemtype = 'R/W'
                    getter = lambda item, script=readscript:self.execute_readscript(item, script)
                else:
                    if writescript:
                        itemtype = 'W'
                if writescript:
                    self.writescript = writescript
                    setter = lambda item, value, script=writescript:self.execute_writescript(item, value, script)

                item = Cacheditem(itemname, itemvalue, getter=getter, setter=setter, cachetime=cachetime)

                for key, value in itemconf.items():
                    setattr(item, key, value)

                item.tags = itemconf.pop('tags', 'All Basic Exec').split(' ')
                item.type = itemtype
                item.min = itemconf.pop('min', '')
                item.max = itemconf.pop('max', '')
                self.db.insert(item)
                self.itemrefs.append(item)

            except Exception, e:
                logger.info('Exec plugin config error: %s', str(e))
                raise
Beispiel #20
0
    def activate(self, conf, glob, db, *args, **kwargs):
        """ Create the items described in the configuration file and activate the plugin """
        self.itemList=[]
        self.items = {}
        self.itemTags={}
        self.w1_therm_temperature = re.compile(r't=([0-9]+)')
        self.itemrefs = []
        protocols.activate(self, conf, glob, db, *args, **kwargs)
        try:
            itemconfigs = {}

            # Group item configuration values according to the part before '_' in the key
            for key, value in conf.iteritems():
                lvalue, itemconfig = key.split('_')

                # Use 'item' for the item name in the configuration file as usual
                if itemconfig == 'item':
                    itemconfig = 'name'

                if lvalue not in itemconfigs:
                    itemconfigs[lvalue] = {}
                itemconfigs[lvalue][itemconfig] = value

            # Add the configuration values to itemList
            for lvalue, itemconfig in itemconfigs.items():
                # First add the defaults
                item = {'min':'', 'max':'', 'unit':'', 'type':'R', 'description':'', 'family':'w1_therm', 'value':'0'}
                # Then update with the data from the configuration file
                item.update(itemconfig)
                # And add the item to the list
                self.itemList.append(item)
                # Put the item in the items dictionary also where it's accessible by name
                name = item['name']
                self.items[name] = item

            # Create dbitems from the list and insert into the database
            for item in self.itemList:
                dbitem = Getsetitem(item['name'], item['value'], lambda i:self.getItem(i), lambda i,v:self.setItem(i,v))
                for key, value in item.iteritems():
                    if key is not 'value':
                        dbitem.__setattr__(key, value)
                # Give it some default tags so it's visible in the web interface
                dbitem.__setattr__('tags', ['Basic', 'All', 'Onewire'])
                self.db.insert(dbitem)
                self.itemrefs.append(dbitem)

            t = Timer(0.1, self.background_polling_thread)
            t.setDaemon(True)
            t.start()
        except Exception as e:
            logger.debug('Onewire activate failed: %s'%str(e))
            print e
Beispiel #21
0
 def activate(self, conf, glob, db, *args, **kwargs):
     protocols.activate(self, conf, glob, db, *args, **kwargs)
     self.updateTime = 0
     self.siloData = None
     self.silo_days_left = None
     self.silo_level = 0
     try:
         self.feeder_time = self.glob['conf'].item_to_ds_name['feeder_time']
     except Exception, e:
         logger.info(
             'Silolevel plugin error: feeder_time is missing from the database'
         )
         raise
Beispiel #22
0
 def activate(self, conf, glob):
     protocols.activate(self, conf, glob)
     self.items = {i['name']: i for i in itemList}
     self.db = self.glob['conf'].db
     self.feeder_time = self.glob['conf'].item_to_ds_name['feeder_time']
     self.feeder_capacity = self.glob['conf'].item_to_ds_name[
         'feeder_capacity']
     for item in itemList:
         if item['type'] == 'R/W':
             self.store_setting(item['name'], confval=item['value'])
         else:
             itemValues[item['name']] = item['value']
     self.migrate_settings('cleaning')
Beispiel #23
0
    def activate(self, conf, glob, db, *args, **kwargs):
        protocols.activate(self, conf, glob, db, *args, **kwargs)
        self.logger = logging.getLogger('pellMon')
        self.dbvalues={}
        self.itemrefs = []

        # Initialize protocol and setup the database according to version_string
        try:
            try:
                self.protocol = Protocol(self.conf['serialport'], self.conf['chipversion'])
            except:
                # Create testprotocol if conf is missing
                self.protocol = Protocol(None, '')
            self.allparameters = self.protocol.getDataBase()

            """Get list of all data/parameter/command items"""
            params = self.protocol.getDataBase()
            for item in params:
                dbitem = Getsetitem(item, None, lambda i:self.getItem(i), lambda i,v:self.setItem(i,v))
                if hasattr(params[item], 'max'): 
                    dbitem.max = str(params[item].max)
                if hasattr(params[item], 'min'): 
                    dbitem.min = str(params[item].min)
                if hasattr(params[item], 'frame'): 
                    if hasattr(params[item], 'address'): 
                        dbitem.type = 'R/W'
                    else:
                        dbitem.type = 'R'
                else:
                    dbitem.type = 'W'
                dbitem.longname = dataDescriptions[item][0]
                dbitem.unit = dataDescriptions[item][1]
                dbitem.description = dataDescriptions[item][2]
                dbitem.tags = menus.itemtags(item)
                self.db.insert(dbitem)
                self.itemrefs.append(dbitem)

            # Create and start settings_pollthread to log settings changed locally
            settings = [item for item in params if 'Settings' in menus.itemtags(item)]
            ht = threading.Timer(3, self.settings_pollthread, args=(settings,))
            ht.setDaemon(True)
            ht.start()

            # Create and start alarm_pollthread to log settings changed locally
            ht = threading.Timer(5, self.alarm_pollthread, args=(('mode', 'alarm'),))
            ht.setDaemon(True)
            ht.start()

            self.dataDescriptions = dataDescriptions
        except:
            self.logger.info('scottecom protocol setup failed')
Beispiel #24
0
    def activate(self, conf, glob, db, **kwargs):
        global Proxy
        from nbeprotocol.protocol import Proxy
        global event_text, state_text, lang_longname, lang_description, set_langfile_location
        from nbeprotocol.language import event_text, state_text, lang_longname, lang_description
        self.db_ready = False

        protocols.activate(self, conf, glob, db, **kwargs)
        self.itemrefs = []
        self.conf = conf
        try:
            self.password = self.conf['password']
        except:
            self.password = '******'
        try:
            self.serial = self.conf['serial']
        except:
            self.serial = None

        item = Getsetitem('controller_online', None, getter=lambda i:1 if self.proxy.controller_online else 0)
        item.tags = ['All','Basic','advanced_data']
        item.type = 'R'
        item.longname = 'Controller online'
        item.description = 'Controller communication status'
        self.itemrefs.append(item)
        self.db.insert(item)

        item = Getsetitem('controller_IP', None, getter=lambda i:self.proxy.addr[0] if self.proxy.controller_online else '')
        item.tags = ['All','Basic','advanced_data']
        item.type = 'R'
        item.longname = 'Controller IP'
        item.description = 'Controller IP address'
        self.itemrefs.append(item)
        self.db.insert(item)

        item = Storeditem('logged_event_id_list', '')
        self.itemrefs.append(item)
        self.db.insert(item)

        self.startthread = threading.Thread(target=lambda:self.start())
        self.startthread.setDaemon(True)
        self.startthread.start()

        self.eventthread = threading.Thread(target=lambda:self.eventlogger())
        self.eventthread.setDaemon(True)
        self.eventthread.start()

        self.alarmthread = threading.Thread(target=lambda:self.alarm_poller())
        self.alarmthread.setDaemon(True)
        self.alarmthread.start()
Beispiel #25
0
    def activate(self, conf, glob):
        """ Create the items described in the configuration file and activate the plugin """
        protocols.activate(self, conf, glob)
        try:
            itemconfigs = {}

            # Group item configuration values according to the part before '_' in the key
            for key, value in conf.iteritems():
                lvalue, itemconfig = key.split('_')

                # Use 'item' for the item name in the configuration file as usual
                if itemconfig == 'item':
                    itemconfig = 'name'

                if lvalue not in itemconfigs:
                    itemconfigs[lvalue] = {}
                itemconfigs[lvalue][itemconfig] = value

            # Add the configuration values to itemList
            for lvalue, itemconfig in itemconfigs.items():
                # First add the defaults
                item = {
                    'min': '',
                    'max': '',
                    'unit': '',
                    'type': 'R',
                    'description': '',
                    'family': 'w1_therm'
                }
                # Then update with the data from the configuration file
                item.update(itemconfig)
                # And add the item to the list
                self.itemList.append(item)
                # Put the item in the items dictionary also where it's accessible by name
                name = item['name']
                self.items[name] = item
                # And give it some default tags so it's visibla in the web interface
                self.itemTags[name] = ['Basic', 'All', 'Onewire']

            t = Timer(0.1, self.background_polling_thread)
            t.setDaemon(True)
            t.start()
        except Exception as e:
            logger.debug('Onewire activate failed: %s' % str(e))
            print e
Beispiel #26
0
    def activate(self, conf, glob, db):
        protocols.activate(self, conf, glob, db)

        self.itemrefs = []

        for key, value in self.conf.iteritems():
            if key == 'output_open':
                self.output_open = value
            if key == 'output_close':
                self.output_close = value
            if key == 'hctemp':
                self.hctemp_item = value
            if key == 'outside_temp':
                self.outside_temp = value

        def additem(i):
            i.tags = ['All', 'Basic', 'Heating circuit']
            i.type = 'R/W'
            i.min = ''
            i.max = ''
            self.db.insert(i)
            self.itemrefs.append(i)

        additem(Plainitem('desired_hctemp', 20))
        additem(Plainitem('hc_out', 30))
        additem(Storeditem('curve_1x', -20))
        additem(Storeditem('curve_1y', 60))
        additem(Storeditem('curve_2x', 20))
        additem(Storeditem('curve_2y', 20))
        additem(Storeditem('hc_gain', 8))

        self.desired_temp = float(self.db[self.hctemp_item].value)

        self.feedforwardthread = Thread(target=lambda: self.feedforward())
        self.feedforwardthread.setDaemon(True)
        self.feedforwardthread.start()

        self.valvecontrollerthread = Thread(
            target=lambda: self.valvecontroller())
        self.valvecontrollerthread.setDaemon(True)
        self.valvecontrollerthread.start()

        self.controllerthread = Thread(target=lambda: self.controller())
        self.controllerthread.setDaemon(True)
Beispiel #27
0
    def activate(self, conf, glob, db):
        protocols.activate(self, conf, glob, db)

        self.itemrefs = []

        for key, value in self.conf.iteritems():
            if key == 'output_open':
                self.output_open = value
            if key == 'output_close':
                self.output_close = value
            if key == 'hctemp':
                self.hctemp_item = value
            if key == 'outside_temp':
                self.outside_temp = value

        def additem(i):
            i.tags = ['All', 'Basic', 'Heating circuit']
            i.type = 'R/W'
            i.min = ''
            i.max = ''
            self.db.insert(i)
            self.itemrefs.append(i)

        additem(Plainitem('desired_hctemp', 20))
        additem(Plainitem('hc_out', 30))
        additem(Storeditem('curve_1x', -20))
        additem(Storeditem('curve_1y', 60))
        additem(Storeditem('curve_2x', 20))
        additem(Storeditem('curve_2y', 20))
        additem(Storeditem('hc_gain', 8))

        self.desired_temp = float(self.db[self.hctemp_item].value)

        self.feedforwardthread = Thread(target = lambda:self.feedforward())
        self.feedforwardthread.setDaemon(True)
        self.feedforwardthread.start()

        self.valvecontrollerthread = Thread(target = lambda:self.valvecontroller())
        self.valvecontrollerthread.setDaemon(True)
        self.valvecontrollerthread.start()

        self.controllerthread = Thread(target = lambda:self.controller())
        self.controllerthread.setDaemon(True)
Beispiel #28
0
 def activate(self, conf, glob):
     protocols.activate(self, conf, glob)
     self.valuestore = ConfigParser()
     self.valuestore.add_section('values')
     self.valuesfile = path.join(path.dirname(__file__), 'values.conf')
     for item in itemList:
         if item['type'] == 'R/W':
             self.valuestore.set('values', item['name'], item['value'])
         else:
             itemValues[item['name']] = item['value']
     self.valuestore.read(self.valuesfile)
     f = open(self.valuesfile, 'w')
     self.valuestore.write(f)
     f.close()
     try:
         uid = pwd.getpwnam(self.glob['conf'].USER).pw_uid
         gid = grp.getgrnam(self.glob['conf'].GROUP).gr_gid
         os.chown(self.valuesfile, uid, gid)
     except:
         pass
Beispiel #29
0
    def activate(self, conf, glob, db, *args, **kwargs):
        protocols.activate(self, conf, glob, db, *args, **kwargs)
        self.itemrefs = []
        for key, value in self.conf.iteritems():
            try:
                alarm_name = key.split('_')[0]
                alarm_data = key.split('_')[1]
                if alarm_data == 'status':
                    alarm_type = 'R'
                    description = 'The name of the parameter that has the status for this alarm'
                elif alarm_data == 'comparator':
                    alarm_type = 'R/W'
                    description = 'Allowed values: >|>=|<|<=|==|!='
                elif alarm_data == 'level':
                    alarm_type = 'R/W'
                    description = 'compare against this value'
                elif alarm_data == 'item':
                    alarm_type = 'R/W'
                    description = 'Parameter to read from'
                elif alarm_data == 'enum':
                    alarm_type = 'R/W'
                    description = 'set to: alarm OFF text|alarm ON text'

                itemList.append({'name':key, 'value':value, 'min':'', 'max':'', 'unit':'', 'type':alarm_type, 'description':description})
                itemTags[key] = ['All', 'CustomAlarms', 'Basic']

                if not alarms.has_key(alarm_name):
                    alarms[alarm_name] = {}
                alarm_data = key.split('_')[1]
                if alarm_data == 'status':
                    itemList.append({'name':value, 'value':0, 'unit':'', 'type':'R', 'description':'%s status'%alarm_name})
                    itemTags[value] = ['All', 'CustomAlarms', 'Basic']

                if alarm_data in ['item','comparator','level','status']:
                    if not alarms.has_key(alarm_name):
                        alarms[alarm_name] = {}
                    alarms[alarm_name][alarm_data] = value
            except Exception,e:
                logger.info(str(e))
            itemTags[key].append(alarm_name)
Beispiel #30
0
    def activate(self, conf, glob):
        protocols.activate(self, conf, glob)

        for key, value in self.conf.iteritems():
            try:
                calc_name = key.split("_")[0]
                calc_data = key.split("_")[1]
                if calc_data == "calc":
                    itemList.append(
                        {
                            "name": key,
                            "value": value,
                            "min": "",
                            "max": "",
                            "unit": "",
                            "type": "R/W",
                            "description": "",
                        }
                    )
                elif calc_data == "read":
                    itemList.append(
                        {"name": key, "value": value, "min": "", "max": "", "unit": "", "type": "R", "description": ""}
                    )
                    itemList.append(
                        {
                            "name": value,
                            "value": "",
                            "calc_item": calc_name + "_calc",
                            "min": "",
                            "max": "",
                            "unit": "",
                            "type": "R",
                            "description": "",
                        }
                    )
                    itemTags[value] = ["All", "Calculate", "Basic"]
                itemTags[key] = ["All", "Calculate", "Basic"]
                itemTags[key].append(calc_name)
            except Exception, e:
                print e
Beispiel #31
0
    def activate(self, conf, glob):
        """ Create the items described in the configuration file and activate the plugin """
        protocols.activate(self, conf, glob)
        try:
            itemconfigs = {}

            # Group item configuration values according to the part before '_' in the key
            for key, value in conf.iteritems():
                lvalue, itemconfig = key.split('_')

                # Use 'item' for the item name in the configuration file as usual
                if itemconfig == 'item':
                    itemconfig = 'name'

                if lvalue not in itemconfigs:
                    itemconfigs[lvalue] = {}
                itemconfigs[lvalue][itemconfig] = value

            # Add the configuration values to itemList
            for lvalue, itemconfig in itemconfigs.items():
                # First add the defaults
                item = {'min':'', 'max':'', 'unit':'', 'type':'R', 'description':'', 'family':'w1_therm'}
                # Then update with the data from the configuration file
                item.update(itemconfig)
                # And add the item to the list
                self.itemList.append(item)
                # Put the item in the items dictionary also where it's accessible by name
                name = item['name']
                self.items[name] = item
                # And give it some default tags so it's visibla in the web interface
                self.itemTags[name] = ['Basic', 'All', 'Onewire']

            t = Timer(0.1, self.background_polling_thread)
            t.setDaemon(True)
            t.start()
        except Exception as e:
            logger.debug('Onewire activate failed: %s'%str(e))
            print e
Beispiel #32
0
    def activate(self, conf, glob):
        protocols.activate(self, conf, glob)
        self.db = self.glob['conf'].db
        self.feeder_time = self.glob['conf'].item_to_ds_name['feeder_time']
        self.feeder_capacity = self.glob['conf'].item_to_ds_name[
            'feeder_capacity']
        self.totals = WeakValueDictionary()
        self.totals_fifo = [None] * 200
        self.cache_lock = threading.Lock()
        self._insert_template(
            'consumption', """
<h4>Consumption</h4>

<div class="image-responsive" id="consumption" style="height:400px">
</div>

<script type="text/javascript">
    var baroptions = {
            series: {
                color: '#6989b7', 
                bars: {
                    show: true,
                    barWidth: 3300000, 
                    lineWidth: 0,
                },
            },
            legend: { 
                show: false,
            },
            yaxes: {
                min: 0
            },
            xaxis: {
                mode: 'time',
                tickColor: '#f9f9f9',
            },
            grid: {
                hoverable: true,
                backgroundColor:'#f9f9f9',
                borderWidth: 1,
                borderColor: '#e7e7e7'
            },
    };

    var refreshConsumption = function() {
        $.get(
            'flotconsumption'+'?period=3600&bars=24',
            function(jsondata) {
                var data = JSON.parse(jsondata);
                var graph = $('#consumption');
                plot = $.plot(graph, data.bardata, baroptions);
                $('<p>' + 'last 24h: ' + data.total.toFixed(1).toString() + ' kg' + '</p>').insertAfter(graph);
                $('<p> average: ' + data.average.toFixed(1).toString() + ' kg/h ' + '</p>').insertAfter(graph).css('float', 'right');
            })
    }

    document.addEventListener("DOMContentLoaded", function(event) { 
        refreshConsumption();
    });

</script>
""")
        self.updatetime24h = 0
        self.updatetime7d = 0
        self.updatetime8w = 0
        self.updatetime1y = 0
Beispiel #33
0
    def activate(self, conf, glob, db, *args, **kwargs):
        try:
            self.protocol = __import__('pyownet.protocol').protocol
        except ImportError:
            logger.info('OWFS: python module pyownet is missing')
            raise
        protocols.activate(self, conf, glob, db, *args, **kwargs)
        self.ow2index = {}
        self.name2index = {}
        self.sensors = {}
        self.latches = {}
        self.counters = []
        self.proxies = {}
        self.itemrefs = []

        for key, value in self.conf.iteritems():
            port = 4304
            server = 'localhost'
            ow_name = key.split('_')[0]
            ow_data = key.split('_')[1]

            if not self.ow2index.has_key(ow_name):
                itemList.append({
                    'min': '',
                    'max': '',
                    'unit': '',
                    'type': 'R',
                    'description': '',
                    'function': 'input'
                })
                self.ow2index[ow_name] = len(itemList) - 1

            if ow_data == 'item':
                itemList[self.ow2index[ow_name]]['name'] = value
                self.name2index[value] = self.ow2index[ow_name]

            if ow_data == 'path':
                val = value.split('::')
                if len(val) == 2:
                    server = val[0]
                    val[0] = val[1]
                val = val[0].split(':')
                if len(val) == 2:
                    port = int(val[1])
                owpath = val[0]

                if 'uncached' in owpath:
                    itemList[self.ow2index[ow_name]]['uncached'] = True
                else:
                    itemList[self.ow2index[ow_name]]['uncached'] = False

                self.sensors[self.ow2index[ow_name]] = (owpath, server)
                if not server in self.proxies:
                    try:
                        self.proxies[server] = self.protocol.proxy(host=server,
                                                                   port=port)
                    except self.protocol.ConnError, e:
                        self.proxies[server] = (server, port)

            if ow_data == 'type' and value == 'COUNTER':
                itemList[self.ow2index[ow_name]]['function'] = 'COUNTER'
                itemList[self.ow2index[ow_name]]['value'] = 0
                itemList[self.ow2index[ow_name]]['last_i'] = b'0'
                itemList[self.ow2index[ow_name]]['toggle'] = 0
                t = Timer(5,
                          self.counter_thread,
                          args=(self.ow2index[ow_name], ))
                t.setDaemon(True)
                t.start()

            if ow_data == 'latch':
                val = value.split('::')
                if len(val) == 2:
                    server = val[0]
                    val[0] = val[1]
                val = val[0].split(':')
                if len(val) == 2:
                    port = int(val[1])
                owpath = val[0]
                self.latches[self.ow2index[ow_name]] = (owpath, server)
                if not server in self.proxies:
                    try:
                        self.proxies[server] = self.protocol.proxy(host=server,
                                                                   port=port)
                    except self.protocol.ConnError, e:
                        self.proxies[server] = (server, port)
Beispiel #34
0
    def activate(self, conf, glob):
        protocols.activate(self, conf, glob)
        self.updateTime = 0
        self.siloData = None
        self.silo_days_left = None
        self.silo_level = 0
        self.feeder_time = self.glob['conf'].item_to_ds_name['feeder_time']
        self.feeder_capacity = self.glob['conf'].item_to_ds_name[
            'feeder_capacity']
        for item in itemList:
            if item['type'] == 'R/W':
                self.store_setting(item['name'], confval=str(item['value']))
            else:
                itemValues[item['name']] = item['value']
        self.migrate_settings('silolevel')
        self._insert_template(
            'silolevel', """
<h4>Silo level</h4>
<div class="image-responsive" id="silolevel" style="height:400px">
</div>

<script type="text/javascript">
var refreshSilolevel = function() {
    $.get(
        'flotsilolevel',
        function(jsondata) {
            var data = JSON.parse(jsondata);
            var graph = $('#silolevel');
            plot = $.plot(graph, data.graphdata, siloleveloptions);
            $('<p>' + 'current level: ' + data.silo_level + ' kg' + '</p>').insertAfter(graph);
            $('<p>' + data.silo_days_left + ' days to empty' + '</p>').insertAfter(graph).css('float', 'right');
        })
}

var siloleveloptions = {
        series: {
                    lines: { show: true, lineWidth: 1, fill: true, fillColor: "rgba(105, 137, 183, 0.6)"},
                    color:"rgba(105, 137, 183, 0)",
                    points: { show: false },
                    shadowSize: 0,
                },
        xaxes:  [{
                    mode: "time",       
                    position: "bottom",
                }],
        legend: { 
                    show: false,
                },
        grid:   {
                hoverable: true,
                backgroundColor:'#f9f9f9',
                borderWidth: 1,
                borderColor: '#e7e7e7'
                },
    };

document.addEventListener("DOMContentLoaded", function(event) { 
    refreshSilolevel();
});

</script>

""")
Beispiel #35
0
    def activate(self, conf, glob, db, *args, **kwargs):
        protocols.activate(self, conf, glob, db, *args, **kwargs)
        self.power = 0
        self.state = 'Off'
        self.oldstate = self.state
        self.time_count = time()
        self.time_state = self.time_count
        self.feeder_time = None
        self.alarm_state = 'OK'
        self.itemrefs = []

        global itemList
        if not 'timer' in conf:
            itemList += counter_mode_items
            itemTags.update(counter_mode_tags)

        if not 'state_tracker' in self.conf:
            self.conf['state_tracker'] = 'generic'

        try:
            self.power_window = int(self.conf['power_window'])
            if self.power_window < 60 or self.power_window > 1800:
                raise ValueError
        except:
            self.power_window = 300
        try:
            self.running_timeout = int(self.conf['running_timeout'])
            if self.running_timeout < 5 or self.power_window > 300:
                raise ValueError
        except:
            self.running_timeout = 60
        try:
            self.ignition_timeout = int(self.conf['ignition_timeout'])
            if self.ignition_timeout < 60 or self.ignition_timeout > 1200:
                raise ValueError
        except:
            self.ignition_timeout = 600
        try:
            self.starting_power = float(self.conf['starting_power'])
            if self.starting_power < 0.5 or self.starting_power > 10:
                raise ValueError
        except:
            self.starting_power = 5
        try:
            self.startup_feed_wait = float(self.conf['startup_feed_wait'])
            if self.startup_feed_wait < 10 or self.startup_feed_wait > 300:
                raise ValueError
        except:
            self.startup_feed_wait = 60
        try:
            self.log_changes = [s.strip() for s in self.conf['log_changes'].split(',')]
        except:
            self.log_changes = ['mode', 'alarm']

        if conf['state_tracker'] == 'generic':
            itemList += state_tracker_items
            itemTags.update(state_tracker_tags)

        self.migrate_settings('pelletcalc')

        for item in itemList:
            if item['type'] == 'R/W':
                self.store_setting(item['name'], confval = item['value'])
                value = self.load_setting(item['name'])
            else:
                value = item['value']

        for item in itemList:
            dbitem = Getsetitem(item['name'], value, lambda i:self.getItem(i), lambda i,v:self.setItem(i,v))
            for key, value in item.iteritems():
                if key is not 'value':
                    dbitem.__setattr__(key, value)
            if dbitem.name in itemTags:
                dbitem.__setattr__('tags', itemTags[dbitem.name])
            self.db.insert(dbitem)
            self.itemrefs.append(dbitem)

        if self.conf['state_tracker'] == 'generic':
            t = Timer(5, self.calc_thread)
            t.setDaemon(True)
            t.start()
Beispiel #36
0
    def activate(self, conf, glob):
        protocols.activate(self, conf, glob)
        self.calc2index = {}
        self.name2index = {}
        self.tasks = {}
        try:
            for key, value in self.conf.iteritems():
                try:
                    calc_name = key.split('_')[0]
                    calc_data = key.split('_')[1]

                    if not self.calc2index.has_key(calc_name):
                        itemList.append({
                            'min': '',
                            'max': '',
                            'unit': '',
                            'type': 'R',
                            'description': ''
                        })
                        self.calc2index[calc_name] = len(itemList) - 1

                    if calc_data == 'prog':
                        itemList[self.calc2index[calc_name]]['name'] = key
                        itemList[self.calc2index[calc_name]]['value'] = value
                        #itemList[self.calc2index[calc_name]]['type'] = 'R/W'
                        self.name2index[key] = self.calc2index[calc_name]
                        itemTags[key] = ['All', 'Calculate']

                    elif calc_data == 'readitem':
                        itemList.append({
                            'name': value,
                            'value': '',
                            'calc_item': calc_name + '_prog',
                            'min': '',
                            'max': '',
                            'unit': '',
                            'type': 'R',
                            'description': ''
                        })
                        itemList.append({
                            'name':
                            key,
                            'value':
                            value,
                            'min':
                            '',
                            'max':
                            '',
                            'unit':
                            '',
                            'type':
                            'R',
                            'description':
                            'Contains the item name to read to execute %s and retrieve the result'
                            % calc_name
                        })
                        itemTags[value] = ['All', 'Calculate', 'Basic']
                        itemTags[key] = ['All', 'Calculate']
                        self.name2index[value] = len(itemList) - 2
                        self.name2index[key] = len(itemList) - 1

                    elif calc_data == 'readwriteitem':
                        itemList.append({
                            'name': value,
                            'value': '',
                            'calc_item': calc_name + '_prog',
                            'min': '',
                            'max': '',
                            'unit': '',
                            'type': 'R/W',
                            'description': ''
                        })
                        itemList.append({
                            'name':
                            key,
                            'value':
                            value,
                            'min':
                            '',
                            'max':
                            '',
                            'unit':
                            '',
                            'type':
                            'R',
                            'description':
                            'Contains the item name to read to execute %s and retrieve the result'
                            % calc_name
                        })
                        itemTags[value] = ['All', 'Calculate', 'Basic']
                        itemTags[key] = ['All', 'Calculate']
                        self.name2index[value] = len(itemList) - 2
                        self.name2index[key] = len(itemList) - 1

                    elif calc_data == 'writeitem':
                        itemList.append({
                            'name': value,
                            'value': '',
                            'calc_item': calc_name + '_prog',
                            'min': '',
                            'max': '',
                            'unit': '',
                            'type': 'W',
                            'description': ''
                        })
                        itemList.append({
                            'name':
                            key,
                            'value':
                            value,
                            'min':
                            '',
                            'max':
                            '',
                            'unit':
                            '',
                            'type':
                            'R',
                            'description':
                            'Contains the item name to read to execute %s and retrieve the result'
                            % calc_name
                        })
                        itemTags[value] = ['All', 'Calculate', 'Basic']
                        itemTags[key] = ['All', 'Calculate']
                        self.name2index[value] = len(itemList) - 2
                        self.name2index[key] = len(itemList) - 1

                    elif calc_data == 'progtype':
                        if value in ['R', 'R/W']:
                            itemList[
                                self.calc2index[calc_name]]['type'] = value
                        else:
                            raise ValueError('unknown type %s in %s' %
                                             (value, key))

                    elif calc_data == 'taskcycle':
                        try:
                            taskcycle = float(value)
                            self.tasks[calc_name] = calcthread(
                                taskcycle, calc_name + '_prog', self)
                        except Exception, e:
                            raise e  #ValueError('%s has invalid task time %s'%(key, value))

                except Exception, e:
                    logger.info(str(e))
                    raise e
            for item in itemList:
                if item['type'] == 'R/W':
                    self.store_setting(item['name'], confval=item['value'])
                else:
                    itemValues[item['name']] = item['value']
            self.migrate_settings('calculate')
Beispiel #37
0
    def activate(self, conf, glob):
        protocols.activate(self, conf, glob)
        self.db = self.glob['conf'].db
        self.feeder_time = self.glob['conf'].item_to_ds_name['feeder_time']
        self.feeder_capacity = self.glob['conf'].item_to_ds_name['feeder_capacity']
        self.totals=WeakValueDictionary()
        self.totals_fifo=[None]*200
        self.cache_lock = threading.Lock()
        self._insert_template('consumption', """
<h4>Consumption</h4>

<div class="image-responsive" id="consumption" style="height:400px">
</div>

<script type="text/javascript">
    var baroptions = {
            series: {
                color: '#6989b7', 
                bars: {
                    show: true,
                    barWidth: 3300000, 
                    lineWidth: 0,
                },
            },
            legend: { 
                show: false,
            },
            yaxes: {
                min: 0
            },
            xaxis: {
                mode: 'time',
                tickColor: '#f9f9f9',
            },
            grid: {
                hoverable: true,
                backgroundColor:'#f9f9f9',
                borderWidth: 1,
                borderColor: '#e7e7e7'
            },
    };

    var refreshConsumption = function() {
        $.get(
            'flotconsumption'+'?period=3600&bars=24',
            function(jsondata) {
                var data = JSON.parse(jsondata);
                var graph = $('#consumption');
                plot = $.plot(graph, data.bardata, baroptions);
                $('<p>' + 'last 24h: ' + data.total.toFixed(1).toString() + ' kg' + '</p>').insertAfter(graph);
                $('<p> average: ' + data.average.toFixed(1).toString() + ' kg/h ' + '</p>').insertAfter(graph).css('float', 'right');
            })
    }

    document.addEventListener("DOMContentLoaded", function(event) { 
        refreshConsumption();
    });

</script>
""")
        self.updatetime24h = 0
        self.updatetime7d = 0
        self.updatetime8w = 0
        self.updatetime1y = 0
Beispiel #38
0
    def activate(self, conf, glob, db, *args, **kwargs):
        try:
            import pyowm
        except ImportError:
            logger.info('Python module pyowm is missing')
            raise
        protocols.activate(self, conf, glob, db, *args, **kwargs)
        self.itemrefs = []
        self.storeditems = {}
        self.itemvalues = {}

        try:
            self.owm = pyowm.OWM(self.conf['apikey'])
        except:
            logger.info('openweathermap init failed, invalid api_key')
            raise

        def additem(i, item_type='R'):
            i.tags = ['All', 'Basic', 'Openweathermap']
            i.type = item_type
            i.min = ''
            i.max = ''
            self.db.insert(i)
            self.itemrefs.append(i)

        def update_location(*args, **kwargs):
            self.update_interval = 1
            self.store_interval = 10

        config = {}
        for index_key, value in self.conf.items():
            if '_' in index_key:
                index, key = index_key.split('_')
                try:
                    config[index][key] = value
                except KeyError:
                    config[index] = {key:value}

        for index, itemconf in config.items():
            try:
                itemname = itemconf.pop('item')
                itemvalue = itemconf.pop('value', '0')
                itemdata = itemconf.pop('data');

                storeditem = Storeditem('owm_stored_'+itemdata, itemvalue)
                self.db.insert(storeditem)
                self.storeditems[itemdata] = storeditem
                self.itemvalues[itemdata] = storeditem.value

                i = Getsetitem(itemname, itemvalue, getter=lambda item, d=itemdata:self.itemvalues[d])

                for key, value in itemconf.items():
                    setattr(i, key, value)
                additem(i)

            except KeyError:
                pass

        i = Storeditem('location', 'copenhagen,dk', setter=update_location)
        i.description = 'Set your location: town,countrycode or zipcode,countrycode'
        additem(i, 'R/W')

        self.update_interval = 5

        t = Timer(0, self.update_thread)
        t.setDaemon(True)
        t.start()
Beispiel #39
0
    def activate(self, conf, glob, db, *args, **kwargs):
        protocols.activate(self, conf, glob, db, *args, **kwargs)
        self.power = 0
        self.state = 'Off'
        self.oldstate = self.state
        self.time_count = time()
        self.time_state = self.time_count
        self.feeder_time = None
        self.alarm_state = 'OK'
        self.itemrefs = []

        global itemList
        if not 'timer' in conf:
            itemList += counter_mode_items
            itemTags.update(counter_mode_tags)

        if not 'state_tracker' in self.conf:
            self.conf['state_tracker'] = 'generic'

        try:
            self.power_window = int(self.conf['power_window'])
            if self.power_window < 60 or self.power_window > 1800:
                raise ValueError
        except:
            self.power_window = 300
        try:
            self.running_timeout = int(self.conf['running_timeout'])
            if self.running_timeout < 5 or self.power_window > 300:
                raise ValueError
        except:
            self.running_timeout = 60
        try:
            self.ignition_timeout = int(self.conf['ignition_timeout'])
            if self.ignition_timeout < 60 or self.ignition_timeout > 1200:
                raise ValueError
        except:
            self.ignition_timeout = 600
        try:
            self.starting_power = float(self.conf['starting_power'])
            if self.starting_power < 0.5 or self.starting_power > 10:
                raise ValueError
        except:
            self.starting_power = 5
        try:
            self.startup_feed_wait = float(self.conf['startup_feed_wait'])
            if self.startup_feed_wait < 10 or self.startup_feed_wait > 300:
                raise ValueError
        except:
            self.startup_feed_wait = 60
        try:
            self.log_changes = [
                s.strip() for s in self.conf['log_changes'].split(',')
            ]
        except:
            self.log_changes = ['mode', 'alarm']

        if conf['state_tracker'] == 'generic':
            itemList += state_tracker_items
            itemTags.update(state_tracker_tags)

        self.migrate_settings('pelletcalc')

        for item in itemList:
            if item['type'] == 'R/W':
                self.store_setting(item['name'], confval=item['value'])
                value = self.load_setting(item['name'])
            else:
                value = item['value']

        for item in itemList:
            dbitem = Getsetitem(item['name'], value, lambda i: self.getItem(i),
                                lambda i, v: self.setItem(i, v))
            for key, value in item.iteritems():
                if key is not 'value':
                    dbitem.__setattr__(key, value)
            if dbitem.name in itemTags:
                dbitem.__setattr__('tags', itemTags[dbitem.name])
            self.db.insert(dbitem)
            self.itemrefs.append(dbitem)

        if self.conf['state_tracker'] == 'generic':
            t = Timer(5, self.calc_thread)
            t.setDaemon(True)
            t.start()
Beispiel #40
0
    def activate(self, conf, glob, db, *args, **kwargs):
        protocols.activate(self, conf, glob, db, *args, **kwargs)
        self.calc2index = {}
        self.name2index = {}
        self.tasks = {}
        self.itemrefs = []
        try:
            for key, value in self.conf.iteritems():
                try:
                    calc_name = key.split('_')[0]
                    calc_data = key.split('_')[1]

                    if not self.calc2index.has_key(calc_name):
                        itemList.append({
                            'min': '',
                            'max': '',
                            'unit': '',
                            'type': 'R',
                            'description': ''
                        })
                        self.calc2index[calc_name] = len(itemList) - 1

                    if calc_data == 'prog':
                        itemList[self.calc2index[calc_name]]['name'] = key
                        value = value.decode('utf-8')
                        value = value.translate({
                            ord(u'\t'): u' ',
                            ord(u'\n'): u' '
                        })
                        itemList[self.calc2index[calc_name]]['value'] = value
                        #itemList[self.calc2index[calc_name]]['type'] = 'R/W'
                        self.name2index[key] = self.calc2index[calc_name]
                        itemTags[key] = ['All', 'Calculate']

                    elif calc_data == 'readitem':
                        itemList.append({
                            'name': value,
                            'value': '',
                            'calc_item': calc_name + '_prog',
                            'min': '',
                            'max': '',
                            'unit': '',
                            'type': 'R',
                            'description': ''
                        })
                        itemList.append({
                            'name':
                            key,
                            'value':
                            value,
                            'min':
                            '',
                            'max':
                            '',
                            'unit':
                            '',
                            'type':
                            'R',
                            'description':
                            'Contains the item name to read to execute %s and retrieve the result'
                            % calc_name
                        })
                        itemTags[value] = ['All', 'Calculate', 'Basic']
                        itemTags[key] = ['All', 'Calculate']
                        self.name2index[value] = len(itemList) - 2
                        self.name2index[key] = len(itemList) - 1

                    elif calc_data == 'readwriteitem':
                        itemList.append({
                            'name': value,
                            'value': '',
                            'calc_item': calc_name + '_prog',
                            'min': '',
                            'max': '',
                            'unit': '',
                            'type': 'R/W',
                            'description': ''
                        })
                        itemList.append({
                            'name':
                            key,
                            'value':
                            value,
                            'min':
                            '',
                            'max':
                            '',
                            'unit':
                            '',
                            'type':
                            'R',
                            'description':
                            'Contains the item name to read to execute %s and retrieve the result'
                            % calc_name
                        })
                        itemTags[value] = ['All', 'Calculate', 'Basic']
                        itemTags[key] = ['All', 'Calculate']
                        self.name2index[value] = len(itemList) - 2
                        self.name2index[key] = len(itemList) - 1

                    elif calc_data == 'writeitem':
                        itemList.append({
                            'name': value,
                            'value': '',
                            'calc_item': calc_name + '_prog',
                            'min': '',
                            'max': '',
                            'unit': '',
                            'type': 'W',
                            'description': ''
                        })
                        itemList.append({
                            'name':
                            key,
                            'value':
                            value,
                            'min':
                            '',
                            'max':
                            '',
                            'unit':
                            '',
                            'type':
                            'R',
                            'description':
                            'Contains the item name to read to execute %s and retrieve the result'
                            % calc_name
                        })
                        itemTags[value] = ['All', 'Calculate', 'Basic']
                        itemTags[key] = ['All', 'Calculate']
                        self.name2index[value] = len(itemList) - 2
                        self.name2index[key] = len(itemList) - 1

                    elif calc_data == 'progtype':
                        if value in ['R', 'R/W']:
                            itemList[
                                self.calc2index[calc_name]]['type'] = value
                        else:
                            raise ValueError('unknown type %s in %s' %
                                             (value, key))

                    elif calc_data == 'taskcycle':
                        try:
                            taskcycle = float(value)
                            self.tasks[calc_name] = calcthread(
                                taskcycle, calc_name + '_prog', self)
                        except Exception, e:
                            raise e  #ValueError('%s has invalid task time %s'%(key, value))

                except Exception, e:
                    logger.info(str(e))
                    raise e
            for item in itemList:
                if item['type'] == 'R/W':
                    self.store_setting(item['name'], confval=item['value'])
                else:
                    itemValues[item['name']] = item['value']

            self.migrate_settings('calculate')

            for item in itemList:
                dbitem = Getsetitem(item['name'], None,
                                    lambda i: self.getItem(i),
                                    lambda i, v: self.setItem(i, v))
                for key, value in item.iteritems():
                    if key != 'value':
                        dbitem.__setattr__(key, value)
                if dbitem.name in itemTags:
                    dbitem.__setattr__('tags', itemTags[dbitem.name])
                self.db.insert(dbitem)
                self.itemrefs.append(dbitem)
Beispiel #41
0
    def activate(self, conf, glob):
        try:
            self.protocol = __import__('pyownet.protocol').protocol
        except ImportError:
            logger.info('OWFS: python module pyownet is missing')
            raise
        protocols.activate(self, conf, glob)
        self.ow2index={}
        self.name2index={}
        self.sensors={}
        self.latches={}
        self.counters=[]
        self.proxies = {}

        for key, value in self.conf.iteritems():
            port = 4304
            server = 'localhost'
            ow_name = key.split('_')[0]
            ow_data = key.split('_')[1]

            if not self.ow2index.has_key(ow_name):
                itemList.append({'min':'', 'max':'', 'unit':'', 'type':'R', 'description':'', 'function':'input'})
                self.ow2index[ow_name] = len(itemList)-1
                
            if ow_data == 'item':
                itemList[self.ow2index[ow_name]]['name'] = value
                itemTags[value] = ['All', 'OWFS', 'Basic']
                self.name2index[value]=self.ow2index[ow_name]

            if ow_data == 'path':
                val = value.split('::')
                if len(val) == 2:
                    server = val[0]
                    val[0] = val[1]
                val = val[0].split(':')
                if len(val) == 2:
                    port = int(val[1])
                owpath = val[0]

                if 'uncached' in owpath:
                    itemList[self.ow2index[ow_name]]['uncached'] = True
                else:
                    itemList[self.ow2index[ow_name]]['uncached'] = False

                self.sensors[self.ow2index[ow_name]] = (owpath, server)
                if not server in self.proxies:
                    try:
                        self.proxies[server] = self.protocol.proxy(host=server, port=port)
                    except self.protocol.ConnError, e:
                        self.proxies[server] = (server, port)
                    
            if ow_data == 'type' and value == 'COUNTER':
                itemList[self.ow2index[ow_name]]['function'] = 'COUNTER'
                itemList[self.ow2index[ow_name]]['value'] = 0
                itemList[self.ow2index[ow_name]]['last_i'] = b'0'
                itemList[self.ow2index[ow_name]]['toggle'] = 0
                t = Timer(5, self.counter_thread, args=(self.ow2index[ow_name],))
                t.setDaemon(True)
                t.start()

            if ow_data == 'latch':
                val = value.split('::')
                if len(val) == 2:
                    server = val[0]
                    val[0] = val[1]
                val = val[0].split(':')
                if len(val) == 2:
                    port = int(val[1])
                owpath = val[0]
                self.latches[self.ow2index[ow_name]] = (owpath, server)
                if not server in self.proxies:
                    try:
                        self.proxies[server] = self.protocol.proxy(host=server, port=port)
                    except self.protocol.ConnError, e:
                        self.proxies[server] = (server, port)
Beispiel #42
0
    def activate(self, conf, glob):
        protocols.activate(self, conf, glob)
        self.calc2index={}
        self.name2index={}
        self.tasks = {}
        try:
            for key, value in self.conf.iteritems():
                try:
                    calc_name = key.split('_')[0]
                    calc_data = key.split('_')[1]

                    if not self.calc2index.has_key(calc_name):
                        itemList.append({'min':'', 'max':'', 'unit':'', 'type':'R', 'description':''})
                        self.calc2index[calc_name] = len(itemList)-1

                    if calc_data == 'prog':
                        itemList[self.calc2index[calc_name]]['name'] = key 
                        itemList[self.calc2index[calc_name]]['value'] = value 
                        #itemList[self.calc2index[calc_name]]['type'] = 'R/W' 
                        self.name2index[key] = self.calc2index[calc_name]
                        itemTags[key] = ['All', 'Calculate']

                    elif calc_data == 'readitem':
                        itemList.append({'name':value, 'value':'', 'calc_item':calc_name+'_prog', 'min':'', 'max':'', 'unit':'', 'type':'R', 'description':''})  
                        itemList.append({'name':key, 'value':value, 'min':'', 'max':'', 'unit':'', 'type':'R', 'description':'Contains the item name to read to execute %s and retrieve the result'%calc_name})  
                        itemTags[value] = ['All', 'Calculate', 'Basic']
                        itemTags[key] = ['All', 'Calculate']
                        self.name2index[value]=len(itemList)-2
                        self.name2index[key]=len(itemList)-1

                    elif calc_data == 'readwriteitem':
                        itemList.append({'name':value, 'value':'', 'calc_item':calc_name+'_prog','min':'', 'max':'', 'unit':'', 'type':'R/W', 'description':''})
                        itemList.append({'name':key, 'value':value, 'min':'', 'max':'', 'unit':'','type':'R', 'description':'Contains the item name to read to execute %s and retrieve the result'%calc_name})
                        itemTags[value] = ['All', 'Calculate', 'Basic']                                                                                  
                        itemTags[key] = ['All', 'Calculate']                                                                                             
                        self.name2index[value]=len(itemList)-2                                                                                           
                        self.name2index[key]=len(itemList)-1

                    elif calc_data == 'writeitem':
                        itemList.append({'name':value, 'value':'', 'calc_item':calc_name+'_prog','min':'', 'max':'', 'unit':'', 'type':'W', 'description':''})
                        itemList.append({'name':key, 'value':value, 'min':'', 'max':'', 'unit':'','type':'R', 'description':'Contains the item name to read to execute %s and retrieve the result'%calc_name})
                        itemTags[value] = ['All', 'Calculate', 'Basic']                                                                                  
                        itemTags[key] = ['All', 'Calculate']                                                                                             
                        self.name2index[value]=len(itemList)-2                                                                                           
                        self.name2index[key]=len(itemList)-1

                    elif calc_data == 'progtype':
                        if value in ['R','R/W']:                                                                                                            
                            itemList[self.calc2index[calc_name]]['type'] = value
                        else:
                           raise ValueError('unknown type %s in %s'%(value, key)) 

                    elif calc_data == 'taskcycle':
                        try:
                            taskcycle = float(value)
                            self.tasks[calc_name] = calcthread(taskcycle, calc_name+'_prog', self)
                        except Exception, e:
                            raise e #ValueError('%s has invalid task time %s'%(key, value))

                except Exception,e: 
                    logger.info(str(e))
                    raise e
            for item in itemList:
                if item['type'] == 'R/W':
                    self.store_setting(item['name'], confval = item['value'])
                else:
                    itemValues[item['name']] = item['value']
            self.migrate_settings('calculate')
Beispiel #43
0
    def activate(self, conf, glob):
        protocols.activate(self, conf, glob)
        self.updateTime = 0
        self.siloData = None
        self.silo_days_left = None
        self.silo_level = 0
        self.feeder_time = self.glob['conf'].item_to_ds_name['feeder_time']
        self.feeder_capacity = self.glob['conf'].item_to_ds_name['feeder_capacity']
        for item in itemList:
            if item['type'] == 'R/W':
                self.store_setting(item['name'], confval = str(item['value']))
            else:
                itemValues[item['name']] = item['value']
        self.migrate_settings('silolevel')
        self._insert_template('silolevel', """
<h4>Silo level</h4>
<div class="image-responsive" id="silolevel" style="height:400px">
</div>

<script type="text/javascript">
var refreshSilolevel = function() {
    $.get(
        'flotsilolevel',
        function(jsondata) {
            var data = JSON.parse(jsondata);
            var graph = $('#silolevel');
            plot = $.plot(graph, data.graphdata, siloleveloptions);
            $('<p>' + 'current level: ' + data.silo_level + ' kg' + '</p>').insertAfter(graph);
            $('<p>' + data.silo_days_left + ' days to empty' + '</p>').insertAfter(graph).css('float', 'right');
        })
}

var siloleveloptions = {
        series: {
                    lines: { show: true, lineWidth: 1, fill: true, fillColor: "rgba(105, 137, 183, 0.6)"},
                    color:"rgba(105, 137, 183, 0)",
                    points: { show: false },
                    shadowSize: 0,
                },
        xaxes:  [{
                    mode: "time",       
                    position: "bottom",
                }],
        legend: { 
                    show: false,
                },
        grid:   {
                hoverable: true,
                backgroundColor:'#f9f9f9',
                borderWidth: 1,
                borderColor: '#e7e7e7'
                },
    };

document.addEventListener("DOMContentLoaded", function(event) { 
    refreshSilolevel();
});

</script>

""")