Пример #1
0
    def step(self, value, data={}, listeners=[]):
        """
        This function will compute the average for each device and port.

        :param value: The input value to be processesed
        :type value: int, float, string, etc
        :param data: a dictionary containing more information about the value.
        :param listeners: a list of the subscribed routines to send the data to
        :returns: new_value, new_data, new_listeners
        :rtype: int, dict, listeners
        :raises: None

        >>> from steps.average import Average
        >>> avg = Average()
        >>> avg.step(0.0, {'device': 'xyz', 'port': 'abc'}, ['a', 'b'])
        (0, {'device': 'xyz', 'units': 'V', 'port': 'abc'}, ['a', 'b'])
        >>> avg.step(1.0, {'device': 'xyz', 'port': 'abc'}, ['a', 'b'])
        (0.5, {'device': 'xyz', 'units': 'V', 'port': 'abc'}, ['a', 'b'])

        """
        device, port = Common.getDeviceAndPort(data)

        number_of_samples = self.get_number_of_samples(device, port)

        samples = self.get_samples(device, port, number_of_samples)
        samples.append(value)
        average = sum(samples) / len(samples)

        self.save_samples(device, port, samples)
        self.logger.debug("average = {}".format(average))
        return average, data, listeners
Пример #2
0
    def step( self, value, data={}, listeners=[] ):
        """
        This function will compare the value with the previous value and if they are different send the data to
        the next listener else don't send the data along.

        :param value: The number to add to the list of numbers.
        :type value: boolean, int or float
        :param data: a dictionary containing more information about the value. 
        :param listeners: a list of the subscribed routines to send the data to
        :returns: value, data, listeners
        :rtype: float, dict, listeners
        :Raises: ValueError, KeyError

        """

        device, port = Common.getDeviceAndPort( data )

        new_entry = Common.generateDevicePortTree( value, device, port, self.current_value )

        if ( ( value == self.current_value[device][port] ) and not new_entry ):
            listeners = []
            self.logger.debug( 'No change detected: steps discontinued: device = {} port = {} volue = {} previous value = {}'.format( device, port, value, self.current_value[device][port] ) )
        else:
            self.logger.debug( 'Change detected: continue stepping device = {} port = {} volue = {} previous value = {}'.format( device, port, value, self.current_value[device][port] ) )

        self.current_value[device][port] = value
        return value, data, listeners
Пример #3
0
    def step( self, value, data={}, listeners=[] ):
        """
        This function will compute the average for each device and port.

        :param value: The input value to be processesed
        :type value: int, float, string, etc
        :param data: a dictionary containing more information about the value.
        :param listeners: a list of the subscribed routines to send the data to
        :returns: new_value, new_data, new_listeners
        :rtype: int, dict, listeners
        :raises: None

        >>> from steps.average import Average
        >>> avg = Average()
        >>> avg.step(0.0, {'device': 'xyz', 'port': 'abc'}, ['a', 'b'])
        (0, {'device': 'xyz', 'units': 'V', 'port': 'abc'}, ['a', 'b'])
        >>> avg.step(1.0, {'device': 'xyz', 'port': 'abc'}, ['a', 'b'])
        (0.5, {'device': 'xyz', 'units': 'V', 'port': 'abc'}, ['a', 'b'])

        """
        device, port = Common.getDeviceAndPort( data )

        number_of_samples = self.get_number_of_samples( device, port )

        samples = self.get_samples( device, port, number_of_samples )
        samples.append( value )
        average = sum( samples ) / len( samples )

        self.save_samples( device, port, samples )
        self.logger.debug( "average = {}".format( average ) )
        return average, data, listeners
Пример #4
0
    def output( self, data={}, http=None ):
        """
        Output the results to COSMSend.com
        
        If the data dictionary contain 'action' and it is set to 'send' this routine will
        send data to COSM.
        
        if the key is not set to send the this routine will store the data as a data point and
        transmit with an other packet going to COSM.


        :param value: the current value
        :type value:
        :param data: additional data about the value
        :type dict:
        :returns: None
        :raises: None

        """
        try:
            device, port = Common.getDeviceAndPort( data )
            self.createDataStream( device, port, data )
            if Constants.DataPacket.action in data and data[Constants.DataPacket.action] == Constants.DataPacket.send:
                self.json = self.createJSONReport( device, port, data )
                self.report_data( self.json, data, http=http )
                self.empty_datastream_list()
        except Exception as ex:
            self.logger.exception( "exception in send.output {}".format( ex ) )
Пример #5
0
    def step(self, value, data={}, listeners=[]):
        """
        This function will compare the value with the previous value and if they are different send the data to
        the next listener else don't send the data along.

        :param value: The number to add to the list of numbers.
        :type value: boolean, int or float
        :param data: a dictionary containing more information about the value. 
        :param listeners: a list of the subscribed routines to send the data to
        :returns: value, data, listeners
        :rtype: float, dict, listeners
        :Raises: ValueError, KeyError

        """

        device, port = Common.getDeviceAndPort(data)

        new_entry = Common.generateDevicePortTree(value, device, port,
                                                  self.current_value)

        if ((value == self.current_value[device][port]) and not new_entry):
            listeners = []
            self.logger.debug(
                'No change detected: steps discontinued: device = {} port = {} volue = {} previous value = {}'
                .format(device, port, value, self.current_value[device][port]))
        else:
            self.logger.debug(
                'Change detected: continue stepping device = {} port = {} volue = {} previous value = {}'
                .format(device, port, value, self.current_value[device][port]))

        self.current_value[device][port] = value
        return value, data, listeners
Пример #6
0
    def output(self, data={}, http=None):
        """
        Output the results to COSMSend.com
        
        If the data dictionary contain 'action' and it is set to 'send' this routine will
        send data to COSM.
        
        if the key is not set to send the this routine will store the data as a data point and
        transmit with an other packet going to COSM.


        :param value: the current value
        :type value:
        :param data: additional data about the value
        :type dict:
        :returns: None
        :raises: None

        """
        try:
            device, port = Common.getDeviceAndPort(data)
            self.createDataStream(device, port, data)
            if Constants.DataPacket.action in data and data[Constants.DataPacket.action] == Constants.DataPacket.send:
                self.json = self.createJSONReport(device, port, data)
                self.report_data(self.json, data, http=http)
                self.empty_datastream_list()
        except Exception as ex:
            self.logger.exception("exception in send.output {}".format(ex))
Пример #7
0
    def step( self, value, data={}, listeners=[] ):
        """
        This function will take one sample out of limit samples.

        :param value: The input value to be processesed
        :type value: int, float, string, etc
        :param data: a dictionary containing more information about the value.
        :param listeners: a list of the subscribed routines to send the data to
        :returns: new_value, new_data, new_listeners
        :rtype: int, dict, listeners
        :raises: KeyError

        >>> from steps.oneInN import oneInN
        >>> oneInN = oneInN()
        >>> c2f.step(0, {'device': 'test', 'port': 'test'}, ['a', 'b'])
        (32.0, {'device': 'test', 'units': 'F', 'port': 'test'}, [])
        >>> c2f.step(100, {'device': 'test', 'port': 'test'}, ['a', 'b'])
        (212.0, {'device': 'test', 'units': 'F', 'port': 'test'}, ['a', 'b'])

        """
        device, port = Common.getDeviceAndPort( data )
        limit = int( self.config[device][port] )

        Common.generateDevicePortTree( 0, device, port, self.count )
        if ( self.count[device][port] % limit ) != 0:
            listeners = []
            self.logger.debug( "count is {}: don't send data".format( self.count[device][port] ) )
        else:
            self.logger.debug( "count is {}: send data".format( self.count[device][port] ) )
        self.count[device][port] += 1
        return value, data, listeners
Пример #8
0
    def report_data(self, json, data, http=None):
        """
        reportData - Sends the json object to the COSMSend web site

        if the options.in_test_mode is NOT set then don't send data to COSM web site.
        The options.in_test_mode is set with the command line argument --test

        the httplib2 debuglevel is set with the command line argument --http N
        where N is a positive integer.

        :param json: the current value
        :type json:
        :param data: the data that is pasted between steps
        :type dict:
        :returns: None
        :raises: None
        """
        device, port = Common.getDeviceAndPort(data)
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "X-PachubeApiKey": self.config[device][port][Constants.Cosm.apikey],
        }
        try:
            url = self.config[device][port][Constants.Cosm.url].format(self.config[device][port][Constants.Cosm.id])
            if http == None:
                http = httplib2.Http()
            httplib2.debuglevel = self.options.http2lib_debug_level
            self.logger.debug("send packet {}".format(json))
            # if the test flag --test or -t is set at startup
            if not self.options.in_test_mode:
                response, content = http.request(url, method="PUT", body=json, headers=headers)
                if response.status == 200:
                    self.logger.info("Successfully sent data to COSM")
                else:
                    self.logger.error(
                        "Error sending data to {} status = {} response = {} content = ".format(
                            url, response.status, response, content
                        )
                    )

        except HttpLib2Error as error:
            self.logger.error("exception from httplib2 {}".format(error))
        except AttributeError as error:
            self.logger.exception("exception from httplib2 {}".format(error))
Пример #9
0
    def step( self, value, data={}, listeners=[] ):
        """
        This function will record the max value.

        :param value: The number to add to the list of numbers.
        :type value: boolean, int or float
        :param data: a dictionary containing more information about the value. 
        :param listeners: a list of the subscribed routines to send the data to
        :returns: value, data, listeners
        :rtype: float, dict, listeners
        :raises: ValueError, KeyError
        
        """
        device, port = Common.getDeviceAndPort( data )
        Common.generateDevicePortTree( value, device, port, self.max_value )

        if value > self.max_value[device][port]:
            self.max_value[device][port] = value

        return value, data, listeners
Пример #10
0
    def step(self, value, data={}, listeners=[]):
        """
        This function will record the max value.

        :param value: The number to add to the list of numbers.
        :type value: boolean, int or float
        :param data: a dictionary containing more information about the value. 
        :param listeners: a list of the subscribed routines to send the data to
        :returns: value, data, listeners
        :rtype: float, dict, listeners
        :raises: ValueError, KeyError
        
        """
        device, port = Common.getDeviceAndPort(data)
        Common.generateDevicePortTree(value, device, port, self.max_value)

        if value > self.max_value[device][port]:
            self.max_value[device][port] = value

        return value, data, listeners
Пример #11
0
    def report_data( self, json, data, http=None ):
        """
        reportData - Sends the json object to the COSMSend web site

        if the options.in_test_mode is NOT set then don't send data to COSM web site.
        The options.in_test_mode is set with the command line argument --test

        the httplib2 debuglevel is set with the command line argument --http N
        where N is a positive integer.

        :param json: the current value
        :type json:
        :param data: the data that is pasted between steps
        :type dict:
        :returns: None
        :raises: None
        """
        device, port = Common.getDeviceAndPort( data )
        headers = {'Content-Type': 'application/x-www-form-urlencoded',
           'X-PachubeApiKey': self.config[device][port][Constants.Cosm.apikey]}
        try:
            url = self.config[device][port][Constants.Cosm.url].\
                        format( self.config[device][port][Constants.Cosm.id] )
            if ( http == None ):
                http = httplib2.Http()
            httplib2.debuglevel = self.options.http2lib_debug_level
            self.logger.debug( "send packet {}".format( json ) )
            # if the test flag --test or -t is set at startup
            if ( not self.options.in_test_mode ):
                response, content = http.request( url, method="PUT", body=json, headers=headers )
                if ( response.status == 200 ):
                    self.logger.info( 'Successfully sent data to COSM' )
                else:
                    self.logger.error( 'Error sending data to {} status = {} response = {} content = '.format( url, response.status, response, content ) )

        except HttpLib2Error as error:
            self.logger.error( "exception from httplib2 {}".format( error ) )
        except AttributeError as error:
            self.logger.exception( "exception from httplib2 {}".format( error ) )
Пример #12
0
    def step( self, value, data={}, listeners=[] ):
        """
        This function will format value as specified in the format stored in formatvalue.xml.

        :param value: The input value to be processesed
        :type value: int, float, string, etc
        :param data: a dictionary containing more information about the value.
        :param listeners: a list of the subscribed routines to send the data to
        :returns: new_value, new_data, new_listeners
        :rtype: int, dict, listeners
        :raises: ValueError, KeyError

        """
        device, port = Common.getDeviceAndPort( data )
        format_specification = self.config[device][port]
        try:
            new_value = format_specification.format( value )
            self.logger.debug( "FormatValue received {} sent out {}".format( value, new_value ) )
        except ValueError as ve:
            error = "The format is incompatable with the input data type {}: device {} port {} file {}: error message {}".\
                    format( format_specification, device, port, self.configuration_file_name, ve )
            raise ValueError( error )
        return new_value, data, listeners
Пример #13
0
    def step(self, value, data={}, listeners=[]):
        """
        Store the current value.

        :param value: The number to add to the list of numbers.
        :type value: boolean, int or float
        :param data: a dictionary containing more information about the
                value.        :param value: The input value to be processesed
        :type value: int, float, string, etc
        :param data: a dictionary containing more information about the value.
        :param listeners: a list of the subscribed routines to send the data to
        :returns: new_value, new_data, new_listeners
        :rtype: int, dict, listeners
        :raises: None

        """
        device, port = Common.getDeviceAndPort(data)

        current_data = self.current_values.buildDataBlock(value, data)
        self.current_values.store(value, device, port, current_data)
        self.logger.debug("currentvalue table {} {} {}".format(
            device, port, value))
        #        pprint.pprint(self.current_values.get())
        return value, data, listeners
Пример #14
0
    def step(self, value, data={}, listeners=[]):
        """
        This function will format value as specified in the format stored in formatvalue.xml.

        :param value: The input value to be processesed
        :type value: int, float, string, etc
        :param data: a dictionary containing more information about the value.
        :param listeners: a list of the subscribed routines to send the data to
        :returns: new_value, new_data, new_listeners
        :rtype: int, dict, listeners
        :raises: ValueError, KeyError

        """
        device, port = Common.getDeviceAndPort(data)
        format_specification = self.config[device][port]
        try:
            new_value = format_specification.format(value)
            self.logger.debug("FormatValue received {} sent out {}".format(
                value, new_value))
        except ValueError as ve:
            error = "The format is incompatable with the input data type {}: device {} port {} file {}: error message {}".\
                    format( format_specification, device, port, self.configuration_file_name, ve )
            raise ValueError(error)
        return new_value, data, listeners
Пример #15
0
 def test_getDeviceAndPort_with_missing_device( self ):
     data = {'port': 'def'}
     with self.assertRaisesRegexp( KeyError, 'The device is missing from the data block:' ):
         device, port = Common.getDeviceAndPort( data )
Пример #16
0
 def test_getDeviceAndPort_with_good_data( self ):
     data = {'device': 'abc',
             'port': 'def'}
     device, port = Common.getDeviceAndPort( data )
     self.assertEqual( device, 'abc' )
     self.assertEqual( port, 'def' )