コード例 #1
0
class ConIgnoreServer(object):
    def __init__(self, ignores):
        """Pass in count of confirmable messages to ignore."""
        self._server = CoapServer(port=5683)
        self._server.registerForResourceGet(self._getResource)
        self._ignores = ignores

    def _getResource(self, resource):
        """Sets the value for the provided resource, for a GET request."""
        if resource.path == '/time':
            if self._ignores > 0:
                self._ignores = self._ignores - 1
                raise IgnoreRequestException
                return
            else:
                resource.type = 'string'
                now = datetime.datetime.now()
                resource.value = now.strftime("%Y-%m-%d %H:%M").encode('ascii')
        else:
            raise NotImplementedError('Unknown path')
            return

    def start(self):
        self._server.start()
コード例 #2
0
ファイル: manager.py プロジェクト: kb2ma/nethead
        :return: The created host
        :rtype: Host
        '''
        host = Host()
        host.interface_id = resource.value
        host.address      = resource.sourceAddress[0]
        host.name         = getInvariantName(host)    # requires ipAddress
        host.coords       = "100,100"                 # arbitrary values, so shows on map
        
        return host

    
if __name__ == "__main__":
    logging.basicConfig(filename='nethead.log', level=logging.DEBUG, 
                        format='%(asctime)s %(module)s %(message)s')
    log.info('Initializing Nethead server')

    formattedPath = '\n\t'.join(str(p) for p in sys.path)
    log.info('Running server with sys.path:\n\t{0}'.format(formattedPath))

    server = None
    try:
        coapServer = CoapServer()
        if coapServer:
            server = HostManager( coapServer )
            coapServer.start()
    except KeyboardInterrupt:
        pass
    except:
        log.exception('Catch-all handler for Nethead server')
コード例 #3
0
ファイル: recorder.py プロジェクト: kb2ma/soscoap
class ValueRecorder(object):
    '''Records the values posted to a provided URI. Records the values to a file.
    
    Attributes:
        :uripath:  str URI for resource
        :filename: str Name of target file for recording
        :_chanfile: File Recording target
        :_server:   CoapServer Provides CoAP message protocol
    
    Usage:
        #. cr = ValueRecorder(uripath, filename)  -- Create instance
        #. cr.start()  -- Starts to listen and record messages
        #. cr.close()  -- Releases sytem resources
        
    URIs:
        | /ver -- GET program version
        | /<uripath-attribute> -- PUT/POST to <filename-attribute> file, where
                                  the attribute names are provided to the class
                                  constructor
    '''
    def __init__(self, uripath, filename):
        self.uripath   = uripath
        self.filename  = filename
        # Must be defined for use by close().
        self._chanfile = None
        
        self._server = CoapServer()
        self._server.registerForResourceGet(self._getResource)
        self._server.registerForResourcePut(self._putResource)
        self._server.registerForResourcePost(self._postResource)
        
    def close(self):
        '''Releases system resources.
        '''
        if self._chanfile:
            self._chanfile.close() 
                
    def _getResource(self, resource):
        '''Sets the value for the provided resource, for a GET request.
        '''
        log.debug('Resource path is {0}'.format(resource.path))
        if resource.path == '/ver':
            resource.type  = 'string'
            resource.value = VERSION
            log.debug('Got resource value')
        else:
            log.debug('Unknown path')
    
    def _postResource(self, resource):
        '''Records the value for the provided resource, for a POST request.
        
        :param resource.value: str ASCII in CSV format, with two fields:
                               1. int Time
                               2. int Value
        '''
        log.debug('Resource path is {0}'.format(resource.path))
        if resource.path == self.uripath:
            self._chanfile.writelines((resource.value, '\n'))
            self._chanfile.flush()
            log.debug('POST resource value done')
        else:
            raise NotImplementedError('Unknown path')
    
    def _putResource(self, resource):
        '''Records the value for the provided resource, for a PUT request.
        
        :param resource.value: str ASCII in CSV format, with two fields:
                               1. int Time
                               2. int Value
        '''
        log.debug('Resource path is {0}'.format(resource.path))
        if resource.path == self.uripath:
            self._chanfile.writelines((resource.value, '\n'))
            self._chanfile.flush()
            log.debug('PUT resource value done')
        else:
            raise NotImplementedError('Unknown path')
    
    def start(self):
        '''Creates the server, and opens the file for this recorder.
        
        :raises IOError: If cannot open file
        '''
        self._chanfile = open(self.filename, 'w')
        self._server.start()
コード例 #4
0
ファイル: tester.py プロジェクト: kb2ma/gcoap-test
class GcoapTester(object):
    '''Provides a server for testing gcoap client commands.
    
    Attributes:
        :_server:   CoapServer Provides CoAP message protocol
        :_delay:    Time in seconds to delay a response; useful for testing
    
    Usage:
        #. cr = GcoapTester()  -- Create instance
        #. cr.start()  -- Starts to listen
        #. cr.close()  -- Releases sytem resources
        
    URIs:
        | /ver -- GET program version
        | /toobig -- GET large text payload. CoAP PDU exceeds 128-byte buffer
                     used by gcoap.
        | /ignore -- GET that does not respond.
        | Configuration
        | /cf/delay -- POST integer seconds to delay future responses
        | /ver/ignores -- PUT count of /ver requests to ignore before responding;
                          tests client retry mechanism
    '''
    def __init__(self, port=soscoap.COAP_PORT):
        '''Pass in port for non-standard CoAP port.
        '''
        self._server = CoapServer(port=port)
        self._server.registerForResourceGet(self._getResource)
        self._server.registerForResourcePut(self._putResource)
        self._server.registerForResourcePost(self._postResource)
        self._delay = 0
        self._verIgnores = 0

    def close(self):
        '''Releases system resources.
        '''
        pass

    def _getResource(self, resource):
        '''Sets the value for the provided resource, for a GET request.
        '''
        log.debug('Resource path is {0}'.format(resource.path))
        if resource.path == '/ver':
            if self._verIgnores > 0:
                self._verIgnores = self._verIgnores - 1
                raise IgnoreRequestException
                return
            else:
                resource.type = 'string'
                resource.value = VERSION
        elif resource.path == '/toobig':
            resource.type = 'string'
            resource.value = '1234567890' * 13
        elif resource.path == '/ignore':
            time.sleep(self._delay)
            raise IgnoreRequestException
            return
        else:
            time.sleep(self._delay)
            raise NotImplementedError('Unknown path')
            return

        time.sleep(self._delay)

    def _postResource(self, resource):
        '''Accepts the value for the provided resource, for a POST request.
        '''
        log.debug('Resource path is {0}'.format(resource.path))
        if resource.path == '/cf/delay':
            self._delay = int(resource.value)
            log.debug('Post delay value: {0}'.format(self._delay))
        else:
            time.sleep(self._delay)
            raise NotImplementedError('Unknown path: {0}'.format(
                resource.path))

    def _putResource(self, resource):
        '''Accepts the value for the provided resource, for a PUT request.
        '''
        if resource.path == '/ver/ignores':
            self._verIgnores = int(resource.value)
            log.debug('Ignores for /ver: {0}'.format(self._verIgnores))
        else:
            raise NotImplementedError('Unknown path: {0}'.format(
                resource.path))

    def start(self):
        '''Creates the server, and opens the file for this recorder.
        
        :raises IOError: If cannot open file
        '''
        self._server.start()