Exemplo n.º 1
1
 def __init__(self, host, port):
     CoAP.__init__(self, (host, port))
     path_1 = 'basic/'
     self.add_resource(path_1, BasicResource())
     path_2 = 'temperature/'
     self.add_resource(path_2, BasicResource())
     path_3 = 'brightness/'
     self.add_resource(path_3, BasicResource())
Exemplo n.º 2
0
 def __init__(self, host, port):
     CoAP.__init__(self, (host, port))
     self.add_resource('b/', BasicResource())
     self.add_resource('config/', BasicResource())
     self.add_resource('cj/', BasicResource())
     self.add_resource('fw/', BasicResource())
     self.add_resource('fv/', BasicResource())
Exemplo n.º 3
0
 def __init__(self, host, port):
     CoAP.__init__(self, (host, port))
     
     self.add_resource('HelloWorld/', HelloWorld())
     self.add_resource('InitialImageSet/', InitialImageSet())
     self.add_resource('SetMode/', SetMode())
     self.add_resource('TheftDetectionSystem/',BeginTDS())
Exemplo n.º 4
0
    def __init__(self, server_id, name):

        self.id = server_id
        self.name = name

        self.coapaddress = settings.COAP_ADDR
        self.coapport = settings.COAP_PORT
        self.multicast = settings.COAP_MULTICAST

        self.proxyaddress = settings.PROXY_ADDR
        self.proxyport = settings.PROXY_PORT

        self.timeout = settings.HOME_SERVER_TIMEOUT

        logger.info("Starting CoAP Server...")
        CoAP.__init__(self, (self.coapaddress, self.coapport), self.multicast)

        self.info = HomeServerInfo(self)

        self.devices = DevicesList(self)
        self.id_gen = IDGenerator(self)
        self.services = HomeServerServices(self)
        self.configs = HomeServerConfigs(self)

        logger.info("CoAP Server start on " + self.coapaddress + ":" +
                    str(self.coapport))
        logger.info(self.root.dump())
Exemplo n.º 5
0
 def __init__(self, host, port):
     CoAP.__init__(self, (host, port), multicast=True)
     threading.Thread.__init__(self)
     self.add_resource('.well-known/core/', WKResource.WKResource())
     self.add_resource('rd/', RDResource.RDResource())
     self.add_resource('rd-lookup/ep/', LookupResource.LookupResource("endpoints"))
     self.add_resource('rd-lookup/res/', LookupResource.LookupResource("resources"))
Exemplo n.º 6
0
 def __init__(self, host, port):
     CoAP.__init__(self, (host, port))
     global threshRes
     threshRes = ThresholdResource()
     self.add_resource(
         'threshold/',
         threshRes)  # Adds /threshold resource to the CoAP Server
Exemplo n.º 7
0
    def __init__(self, host, port, multicast=False, starting_mid=None):
        CoAP.__init__(self, (host, port), multicast, starting_mid)

        # create logger
        logger = logging.getLogger(__name__)
        logger.setLevel(logging.DEBUG)

        # create console handler and set level to debug
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)

        # create formatter
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')

        # add formatter to ch
        ch.setFormatter(formatter)

        # add ch to logger
        logger.addHandler(ch)

        self.add_resource('test/', TestResource())
        self.add_resource('separate/', SeparateResource())
        self.add_resource('seg1/', TestResource())
        self.add_resource('seg1/seg2/', TestResource())
        self.add_resource('seg1/seg2/seg3/', TestResource())
        self.add_resource('query/', TestResource())
        self.add_resource("obs/", ObservableResource(coap_server=self))
        self.add_resource("large/", LargeResource(coap_server=self))
        self.add_resource("large-update/",
                          LargeUpdateResource(coap_server=self))
        self.add_resource('long/', LongResource())
Exemplo n.º 8
0
    def __init__(self, host, port):
        CoAP.__init__(self, (host, port))
        self.add_resource('pir_sensor/', Exam_Resource2.PIR_sensor(coap_server=self))
        self.add_resource('buzzer/', Exam_Resource2.Buzzer(coap_server=self))

        self.add_resource('th_sensor/', Exam_Resource2.TH_sensor(coap_server=self))
        self.add_resource('led/', Exam_Resource2.LED(coap_server=self))
Exemplo n.º 9
0
 def __init__(self):
     Thread.__init__(self)
     self.__port = find_port()
     self.__server = CoAP(("0.0.0.0", int(self.__port)))
     self.__started = False
     self.__amsconf_resource = AmsCoapResource(coap_server=self.__server)
     self.start_server()
Exemplo n.º 10
0
    def __init__(self, ipAddr="localhost", port=5683, multicast=False):

        CoAP.__init__(self, (ipAddr, port), multicast)
        self.port = 5683
        self.ipAddr = ipAddr
        self.useMulticast = multicast
        self.initResources()
Exemplo n.º 11
0
    def __init__(self, host, port, multicast=False, starting_mid=None):
        CoAP.__init__(self, (host, port), multicast, starting_mid)

        # create logger
        logger = logging.getLogger(__name__)
        logger.setLevel(logging.DEBUG)

        # create console handler and set level to debug
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)

        # create formatter
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

        # add formatter to ch
        ch.setFormatter(formatter)

        # add ch to logger
        logger.addHandler(ch)

        self.add_resource('test/', TestResource())
        self.add_resource('separate/', SeparateResource())
        self.add_resource('seg1/', TestResource())
        self.add_resource('seg1/seg2/', TestResource())
        self.add_resource('seg1/seg2/seg3/', TestResource())
        self.add_resource('query/', TestResource())
        self.add_resource("obs/", ObservableResource(coap_server=self))
        self.add_resource("large/", LargeResource(coap_server=self))
        self.add_resource("large-update/", LargeUpdateResource(coap_server=self))
        self.add_resource('long/', LongResource())
Exemplo n.º 12
0
    def __init__(self, host, port):
        CoAP.__init__(self, (host, port))

        all_resources = AvailableResources().get_all()

        # quantidade de recursos por nodo
        quantity = random.randint(0, len(all_resources))

        # lista com id dos recursos
        ids = random.sample(range(0, quantity), quantity)

        for id in ids:
            if  id == 0:
                self.add_resource('/sensor-light', LightResource()) # 0
            elif id == 1:
                self.add_resource('/sensor-presence', PresenceResource()) # 1
            elif id == 2:
                self.add_resource('/cam-front', CamResource()) # 2
            elif id == 3:
                self.add_resource('/cam-back', CamResource()) # 3
            elif id == 4:
                self.add_resource('cam-right', CamResource()) # 2
            elif id == 5:
                self.add_resource('cam-left', CamResource()) # 3


        print 'CoAP Server start on ' + host + ':' + str(port)
        print self.root.dump()
 def __init__(self, host, port):
     CoAP.__init__(self, (host, port))
     self.add_resource('auth/', AuthenticationResource())
     self.add_resource('login/', LoginBasicResource())
     self.add_resource('basic/', BasicResource())
     self.add_resource('register/', RegisterResource())
     self.add_resource('sala/teste', TesteResource())
     self.add_resource('jardim/teste', TesteResource())
Exemplo n.º 14
0
    def __init__(self, host, port):
        CoAP.__init__(self, (host, port))
        #clientMongo = MongoClient('mongodb://localhost:27017')
        #self.database = clientMongo.aquaponey

        self.add_resource('waterLevelSensor/', WaterLevelRest())
        #self.add_resource( 'waterLevelSensor/', PowerManagment( element, 'waterLevelSensor_1'))
        self.add_resource('basic/', BasicResource())
Exemplo n.º 15
0
 def __init__(self, host, port, config):
     '''
     Constructor
     '''
     CoAP.__init__(self, (host, port))
     self.add_resource(
         "temperature/", TempResourceHandler(config=config)
     )  #Add Temperature resource while initializing server
Exemplo n.º 16
0
 def __init__(self):
     self.SERVER = "192.168.0.3"  # Access IP address
     self.PORT = 5683  # Access port
     # Bind IP and port to the CoAP server
     CoAP.__init__(self, (self.SERVER, self.PORT))
     # Declare the available resources and their indexes
     self.add_resource("index/", COAPResource())
     print("Server listening on %s:%d" % (self.SERVER, self.PORT))
Exemplo n.º 17
0
    def __init__(self, host, port, multicast=False):
        CoAP.__init__(self, (host, port), multicast)
        self.add_resource('basic/', BasicResource())
        self.add_resource('long/', Long())
        self.add_resource('xml/', XMLResource())

        print(("CoAP Server start on " + host + ":" + str(port)))
        print((self.root.dump()))
Exemplo n.º 18
0
    def __init__(self, host, port, config_file, config_cloud):
        CoAP.__init__(self, (host, port))

        self.config_file = config_file
        self.config_cloud = config_cloud

        self.add_resource(
            'shadow',
            AdvancedResource("DataBridge", None, config_file, config_cloud))
Exemplo n.º 19
0
 def __init__(self, host, port):
     CoAP.__init__(self, (host, port))
     try:
         if(MONGO):
             self.add_resource('/temp', MongoResource())
         else:
             self.add_resource('/temp', BasicResource())
     except NameError:
         self.add_resource('/temp', MongoResource())
Exemplo n.º 20
0
    def __init__(self, host, port, multicast=False):
        CoAP.__init__(self, (host, port), multicast)
        self.add_resource('request/', RequestOfferResource())
        self.add_resource('task/', RunTaskResource())
        self.add_resource('kill/', KillTaskResource())
        self.add_resource('ping/', PingResource())

        print("CoAP Server start on " + host + ":" + str(port))
        print(self.root.dump())
Exemplo n.º 21
0
 def __init__(self, host, port):
     CoAP.__init__(self, (host, port))
     self.add_resource("resources/", Resources())
     self.add_resource("living_room/", LivingRoomResources())
     self.add_resource("kitchen/", KitchenResources())
     self.add_resource("bedroom/", BedroomResources())
     self.add_resource("utility_room/", UtilityRoomResources())
     self.add_resource("bathroom/", BathroomResources())
     self.add_resource("outside/", OutsideResources())
 def __init__(self):
     Thread.__init__(self)
     self.__port = find_port()
     self.__server = CoAP(("0.0.0.0", int(self.__port)))
     self.__started = False
     self.__rdmonitor_resource = RdMoniorResource(coap_server=self.__server)
     self.__dtrefresh_resource = DataRefreshResource(
         coap_server=self.__server)
     self.start_server()
    def __init__(self, host, port, multicast=False):
        CoAP.__init__(self, (host, port), multicast)

        self.add_resource('direction/', Direction())
        self.add_resource('accident/', AccidentOccurence())
        self.add_resource('suddenbreakes/', SuddenBreakes())
        self.add_resource('location/', Location())
        print "CoAP Server start on " + host + ":" + str(port)
        print self.root.dump()
Exemplo n.º 24
0
    def __init__(self, host, port, multicast=False):
        CoAP.__init__(self, (host, port), multicast)
        self.add_resource('/temp', TempResource())
        self.add_resource('/temp_threshold', TempThreshold())
        self.add_resource('/humi', HumidityResource())
        self.add_resource('/humi_threshold', HumiThreshold())
        # self.add_resource('/led', LEDResource())

        print("CoAP Server started on " + host + ":" + str(port))
        print(self.root.dump())
Exemplo n.º 25
0
 def __init__(self):
     self.path = ""
     self.config = ConfigUtil(
         '../../../config/ConnectedDevicesConfig.props')
     self.host = self.config.getProperty(ConfigConst.COAP_DEVICE_SECTION,
                                         ConfigConst.HOST_KEY)
     self.port = int(
         self.config.getProperty(ConfigConst.COAP_DEVICE_SECTION,
                                 ConfigConst.PORT_KEY))
     CoAP.__init__(self, (self.host, self.port))
Exemplo n.º 26
0
    def __init__(self, host, port, multicast=False):
        CoAP.__init__(self, (host, port), multicast)
        self.add_resource('display_res/', DisplayResource())
        self.add_resource('green_led_res/', GreenLEDResource())
        self.add_resource('blue_led_res/', BlueLEDResource())
        #for i in range(1):
        #    self.add_resource('basic_' + str(i) + '/', BasicResource())

        print "CoAP Server start on " + host + ":" + str(port)
        print self.root.dump()
Exemplo n.º 27
0
    def __init__(self, host, port, multicast=False):
        CoAP.__init__(self, (host, port), multicast)
        '''Adding resources to the server along with the HTTP endpoints for the resource '''
        self.add_resource('electricitymeters/', ElectricityResource())
        self.add_resource('watermeters/', WaterResource())
        self.add_resource('allmeters/', AllMetersResource())
        self.add_resource('basic/', BasicResource())

        print("CoAP server starting on " + host + ":" + str(port))
        print(self.root.dump())
Exemplo n.º 28
0
def main():
    serversocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    serversocket.settimeout(300)
    cert_path = path.join(path.abspath(path.dirname(__file__)), "certs")
    host_address = ("212.201.8.88", 6657)

    # Create a server side DTLS socket
    dtls_sock = wrap_server(serversocket,
                            keyfile=path.join(cert_path, "keycert.pem"),
                            certfile=path.join(cert_path, "keycert.pem"),
                            ca_certs=path.join(cert_path, "ca-cert.pem"),
                            do_handshake_on_connect=True)

    dtls_sock.bind(host_address)
    dtls_sock.listen(1)
    print ("Waiting for CoAP Client to Connect ..")

    # Connect the Listening DTLS socket to CoAP
    server = CoAPServer(host_address, sock=dtls_sock)
    server.add_resource('temperature/', Temperature())
    server.add_resource('humidity/', Humidity())
    server.add_resource('pressure/', Pressure())
    print("CoAP Server start on " + host_address[0] + ":" + str(host_address[1]))
    while True:
        time.sleep(0.5)
        try:
            server.listen(1)
        except KeyboardInterrupt:
            print "Server Shutdown"
            server.close()
            print "Exiting..."
Exemplo n.º 29
0
    def __init__(self, host, port):
        CoAP.__init__(self, (host, port))

        self.add_resource('/temperature', TemperatureResource())
        self.add_resource('/identifier', IdentifierResource())
        self.add_resource('/weight', WeightResource())
        self.add_resource('/food', FoodResource())
        self.add_resource('/water', WaterResource())

        print 'CoAP Server start on ' + host + ':' + str(port)
        print self.root.dump()
Exemplo n.º 30
0
    def __init__(self, host, port, multicast=False):
        CoAP.__init__(self, (host, port), multicast)

        # CREATE meta-resource: resource used to create resources
        add = Add()
        add.set_server(self)
        self.add_resource('add/', add)

        # LOG
        print "CoAP server started on {}:{}".format(str(host), str(port))
        print self.root.dump()
Exemplo n.º 31
0
 def __init__(self, host, port):
     CoAP.__init__(self, (host, port))
     #        pdb.set_trace()
     try:
         if (MONGO == True):
             self.add_resource('/temp',
                               TempMongoResource.TempMongoResource())
         else:
             self.add_resource('/temp', TempResource.TempResource())
     except NameError:
         self.add_resource('/temp', TempMongoResource.TempMongoResource())
     self.add_resource('/time', TimeResource.TimeResource())
Exemplo n.º 32
0
 def __init__(self, host, port, multicast=False):
     CoAP.__init__(self, (host, port), multicast)
     self.add_resource('basic/', BasicResource())
     self.add_resource('storage/', Storage())
     self.add_resource('separate/', Separate())
     self.add_resource('long/', Long())
     self.add_resource('big/', Big())
     self.add_resource('void/', voidResource())
     self.add_resource('xml/', XMLResource())
     self.add_resource('etag/', ETAGResource())
     self.add_resource('child/', Child())
     print "CoAP Server start on " + host + ":" + str(port)
     print self.root.dump()
Exemplo n.º 33
0
    def __init__(self, host, port, multicast=False):
        CoAP.__init__(self, (host, port), multicast) 
        self.add_resource('basic/', BasicResource())
        self.add_resource('storage/', Storage())
        self.add_resource('separate/', Separate())
        self.add_resource('long/', Long())
        self.add_resource('big/', Big())
        self.add_resource('void/', voidResource())
        self.add_resource('xml/', XMLResource())
        self.add_resource('encoding/', MultipleEncodingResource())
        self.add_resource('etag/', ETAGResource())
        self.add_resource('child/', Child())

        self.host = host
        self.port = port
Exemplo n.º 34
0
    def __init__(self, host, port, multicast=False):
        CoAP.__init__(self, (host, port), multicast)

        self.client = HelperClient(server=(defines.RD_HOST, defines.RD_PORT))
        self.node_resource_schema = json.load(open(defines.NODE_RESOURCE_SCHEMA_PATH, "r"))
        self.node_name = self.node_resource_schema["node"]["name"]["value"]

        self.parameter_schema = json.load(open(defines.SERIAL_PARAMETER_SCHEMA_PATH, "r"))
        self.parameter_schema_lock = threading.Lock()

        serial_listener = threading.Thread(target=self.serial_listen)
        serial_listener.setDaemon(True)
        serial_listener.start()

        self.rd_discovery()

        print "CoAP Server start on " + host + ":" + str(port)
Exemplo n.º 35
0
    def __run_server(self):
        log.debug("starting CoAP server at IP:port %s:%d" % (self._hostname, self._port))

        try:
            self._server = CoapthonServer(self._hostname, self._port, self._multicast)
        except TypeError:
            # coapthon 4.0.2 has a different constructor API
            self._server = CoapthonServer((self._hostname, self._port), self._multicast)

        if self._events_root is not None:
            root_event = self.make_event(source=self._events_root, data='root of SCALE events resources', priority=1)
            self.store_event(root_event, self._events_root)

        self._server_running = True
        self._notify_running()

        # Listen for remote connections GETting data, etc.
        self._server.listen()
Exemplo n.º 36
0
    def setUp(self):
        self.host_address = ("127.0.0.1", 5684)
        self.current_mid = random.randint(1, 1000)
        self.server_mid = random.randint(1000, 2000)
        self.server_read_timeout = 0.1

        self.pem = self._setUpPems()

        # Set up a server side DTLS socket
        _sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        _sock = wrap_server(_sock,
                            keyfile=self.pem['SERVER_KEY'],
                            certfile=self.pem['SERVER_KEY'],
                            ca_certs=self.pem['CA_CERT'])
        _sock.bind(self.host_address)
        _sock.listen(0)

        # Connect the CoAP server to the newly created socket
        self.server = CoAPServer(self.host_address,
                                 starting_mid=self.server_mid,
                                 sock=_sock,
                                 cb_ignore_listen_exception=self._cb_ignore_listen_exception)
        self.server.add_resource('storage/', Storage())

        # Test code to "pseudo" capture the udp communication between server and client on the loopback device
        try:
            from proxy import proxy_thread
            self.server_address, self.runFlag = proxy_thread(0, self.host_address[0], self.host_address[1])
        except ImportError:
            self.server_address = self.host_address
            self.runFlag = None

        # Start the server listen routine
        self.server_thread = threading.Thread(target=self.server.listen,
                                              name='ServerThread',
                                              args=(self.server_read_timeout,))
        self.server_thread.start()
Exemplo n.º 37
0
 def __init__(self, host, port, multicast=False, disc=None):
     CoAP.__init__(self, (host, port), multicast)
     self.disc = disc
     self.add_resource('message/', MsgResource(disc=disc))
Exemplo n.º 38
0
class Tests(unittest.TestCase):

    def setUp(self):
        self.host_address = ("127.0.0.1", 5684)
        self.current_mid = random.randint(1, 1000)
        self.server_mid = random.randint(1000, 2000)
        self.server_read_timeout = 0.1

        self.pem = self._setUpPems()

        # Set up a server side DTLS socket
        _sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        _sock = wrap_server(_sock,
                            keyfile=self.pem['SERVER_KEY'],
                            certfile=self.pem['SERVER_KEY'],
                            ca_certs=self.pem['CA_CERT'])
        _sock.bind(self.host_address)
        _sock.listen(0)

        # Connect the CoAP server to the newly created socket
        self.server = CoAPServer(self.host_address,
                                 starting_mid=self.server_mid,
                                 sock=_sock,
                                 cb_ignore_listen_exception=self._cb_ignore_listen_exception)
        self.server.add_resource('storage/', Storage())

        # Test code to "pseudo" capture the udp communication between server and client on the loopback device
        try:
            from proxy import proxy_thread
            self.server_address, self.runFlag = proxy_thread(0, self.host_address[0], self.host_address[1])
        except ImportError:
            self.server_address = self.host_address
            self.runFlag = None

        # Start the server listen routine
        self.server_thread = threading.Thread(target=self.server.listen,
                                              name='ServerThread',
                                              args=(self.server_read_timeout,))
        self.server_thread.start()

    def tearDown(self):
        if self.runFlag is not None:
            self.runFlag.clear()

        # Stop the server from listening (also closes the socket)
        self.server.close()
        self.server_thread.join(timeout=self.server_read_timeout*1.2)
        self.server = None

        self._tearDownPems(self.pem)

    def _setUpPems(self):
        def _createPemFile(fname, content):
            with open(fname, mode='w') as f:
                f.write(content)
            f.close()
            return fname

        self._tmp_dir = tempfile.mkdtemp()

        pem = dict()
        pem['SERVER_KEY'] = _createPemFile(os.path.join(self._tmp_dir, 'serverkey.pem'), KEY_CERT_VALID)
        pem['CA_CERT'] = _createPemFile(os.path.join(self._tmp_dir, 'ca_cert.pem'), CA_CERT_VALID)
        pem['CA_CERT_WRONG'] = _createPemFile(os.path.join(self._tmp_dir, 'ca_cert_wrong.pem'), CA_CERT_WRONG)

        return pem

    def _tearDownPems(self, pem):
        def _removePemFile(fname):
            os.remove(fname)

        for v in pem.itervalues():
            _removePemFile(v)

        os.rmdir(self._tmp_dir)

    def _create_test_sequence(self, bValidResponse=True):
        exchange = list()
        req = Request()
        req.code = defines.Codes.POST.number
        req.uri_path = "/storage/new_res?id=1"
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address
        req.payload = "test"
        req.add_if_none_match()

        if bValidResponse:
            expected = Response()
            expected.type = defines.Types["ACK"]
            expected._mid = self.current_mid
            expected.code = defines.Codes.CREATED.number
            expected.token = None
            expected.payload = None
            expected.location_path = "storage/new_res"
            expected.location_query = "id=1"
        else:
            expected = None

        exchange.append((req, expected))
        self.current_mid += 1

        req = Request()
        req.code = defines.Codes.GET.number
        req.uri_path = "/storage/new_res"
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address
        req.if_match = ["test", "not"]

        if bValidResponse:
            expected = Response()
            expected.type = defines.Types["ACK"]
            expected._mid = self.current_mid
            expected.code = defines.Codes.CONTENT.number
            expected.token = None
            expected.payload = "test"
        else:
            expected = None

        exchange.append((req, expected))
        self.current_mid += 1

        return exchange

    def _test_with_client(self, client, message_list):  # pragma: no cover
        for message, expected in message_list:
            if message is not None:
                try:
                    received_message = client.send_request(message)
                except Exception as e:
                    if expected is not None:
                        self.assertEqual(None, expected)
            if expected is not None:
                if expected.type is not None:
                    self.assertEqual(received_message.type, expected.type)
                if expected.mid is not None:
                    self.assertEqual(received_message.mid, expected.mid)
                self.assertEqual(received_message.code, expected.code)
                if expected.source is not None:
                    self.assertEqual(received_message.source, self.server_address)
                if expected.token is not None:
                    self.assertEqual(received_message.token, expected.token)
                if expected.payload is not None:
                    self.assertEqual(received_message.payload, expected.payload)
                if expected.options:
                    self.assertEqual(len(received_message.options), len(expected.options))
                    for o in expected.options:
                        assert isinstance(o, Option)
                        option_value = getattr(expected, o.name.lower().replace("-", "_"))
                        option_value_rec = getattr(received_message, o.name.lower().replace("-", "_"))
                        self.assertEqual(option_value, option_value_rec)

    def _cb_ignore_listen_exception(self, exception, server):
        """
        In the CoAP server listen method, different exceptions can arise from the DTLS stack. Depending on the type of exception, a
        continuation might not be possible, or a logging might be desirable. With this callback both needs can be satisfied.

        :param exception: What happened inside the DTLS stack
        :param server: Reference to the running CoAP server
        :return: True if further processing should be done, False processing should be stopped
        """
        if isinstance(exception, ssl.SSLError):
            # A client which couldn't verify the server tried to connect, continue but log the event
            if exception.errqueue[-1][0] == ssl.ERR_TLSV1_ALERT_UNKNOWN_CA:
                _logger.debug("Ignoring ERR_TLSV1_ALERT_UNKNOWN_CA from client %s" %
                              ('unknown' if not hasattr(exception, 'peer') else str(exception.peer)))
                return True
            # ... and more ...
        return False

    def _cb_ignore_write_exception(self, exception, client):
        """
        In the CoAP client write method, different exceptions can arise from the DTLS stack. Depending on the type of exception, a
        continuation might not be possible, or a logging might be desirable. With this callback both needs can be satisfied.

        note: Default behaviour of CoAPthon without DTLS if no _cb_ignore_write_exception would be called is with "return True"

        :param exception: What happened inside the DTLS stack
        :param client: Reference to the running CoAP client
        :return: True if further processing should be done, False processing should be stopped
        """
        return False

    def _cb_ignore_read_exception(self, exception, client):
        """
        In the CoAP client read method, different exceptions can arise from the DTLS stack. Depending on the type of exception, a
        continuation might not be possible, or a logging might be desirable. With this callback both needs can be satisfied.

        note: Default behaviour of CoAPthon without DTLS if no _cb_ignore_read_exception would be called is with "return False"

        :param exception: What happened inside the DTLS stack
        :param client: Reference to the running CoAP client
        :return: True if further processing should be done, False processing should be stopped
        """
        return False

    def test_ok_with_handshake_on_send(self):
        """
        Test a valid CoAP sequence with DTLS encryption. The handshake is triggered from the client
        at its first write access towards the server.
        """
        _logger.info("Called test_ok_with_handshake_on_send ...")

        exchange = self._create_test_sequence()

        # Set up a client side DTLS socket
        _sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        _sock = wrap_client(_sock,
                            cert_reqs=ssl.CERT_REQUIRED,
                            ca_certs=self.pem['CA_CERT'],
                            ciphers="RSA",
                            do_handshake_on_connect=False)

        # Connect the CoAP client to the newly created socket
        client = HelperClient(self.server_address,
                              sock=_sock,
                              cb_ignore_read_exception=self._cb_ignore_read_exception,
                              cb_ignore_write_exception=self._cb_ignore_write_exception)

        # Do the communication
        try:
            self._test_with_client(client, exchange)
        except:
            raise
        # Stop the client (also closes the socket)
        finally:
            client.stop()

    def test_ok_with_handshake_on_connect(self):
        """
        Test a valid CoAP sequence with DTLS encryption. The handshake is triggered from the client
        during the connect call.
        """
        _logger.info("Called test_ok_with_handshake_on_connect ...")

        exchange = self._create_test_sequence()

        # Set up a client side DTLS socket
        _sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        _sock = wrap_client(_sock,
                            cert_reqs=ssl.CERT_REQUIRED,
                            ca_certs=self.pem['CA_CERT'],
                            ciphers="RSA",
                            do_handshake_on_connect=True)

        # Connect the CoAP client to the newly created socket
        client = HelperClient(self.server_address,
                              sock=_sock,
                              cb_ignore_read_exception=self._cb_ignore_read_exception,
                              cb_ignore_write_exception=self._cb_ignore_write_exception)

        # Do the communication
        try:
            self._test_with_client(client, exchange)
        except:
            raise
        # Stop the client (also closes the socket)
        finally:
            client.stop()

    def test_fail_with_handshake_on_send(self):
        """
        Test an invalid CoAP sequence with DTLS encryption. The handshake is triggered from the client
        at its first write access towards the server.
        """

        _logger.info("Called test_fail_with_handshake_on_send ...")

        exchange = self._create_test_sequence(bValidResponse=False)

        # Set up a client side DTLS socket
        _sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        _sock = wrap_client(_sock,
                            cert_reqs=ssl.CERT_REQUIRED,
                            ca_certs=self.pem['CA_CERT_WRONG'],
                            ciphers="RSA",
                            do_handshake_on_connect=False)

        # Connect the CoAP client to the newly created socket
        client = HelperClient(self.server_address,
                              sock=_sock,
                              cb_ignore_read_exception=self._cb_ignore_read_exception,
                              cb_ignore_write_exception=self._cb_ignore_write_exception)

        # Do the communication
        try:
            self._test_with_client(client, exchange)
        except:
            raise
        # Stop the client (also closes the socket)
        finally:
            client.stop()

    def test_fail_with_handshake_on_connect(self):
        """
        Test an invalid CoAP sequence with DTLS encryption. The handshake is triggered from the client
        during the connect call.
        """
        _logger.info("Called test_fail_with_handshake_on_connect ...")

        exchange = self._create_test_sequence(bValidResponse=False)

        # Set up a client side DTLS socket
        _sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        _sock = wrap_client(_sock,
                            cert_reqs=ssl.CERT_REQUIRED,
                            ca_certs=self.pem['CA_CERT_WRONG'],
                            ciphers="RSA",
                            do_handshake_on_connect=True)

        # Connect the CoAP client to the newly created socket
        client = HelperClient(self.server_address,
                              sock=_sock,
                              cb_ignore_read_exception=self._cb_ignore_read_exception,
                              cb_ignore_write_exception=self._cb_ignore_write_exception)

        # Do the communication
        try:
            self._test_with_client(client, exchange)
        except:
            raise
        # Stop the client (also closes the socket)
        finally:
            client.stop()
Exemplo n.º 39
0
 def __init__(self, host, port, multicast=False):
     CoAP.__init__(self, (host, port), multicast)
     self.add_resource('Pir/', Pir())
     print "CoAP Server start on " + host + ":" + str(port)
     print self.root.dump()
Exemplo n.º 40
0
 def __init__(self, host, port):
     CoAP.__init__(self, (host, port))
     self.add_resource('basic/', BasicResource())
Exemplo n.º 41
0
class CoapServer(ThreadedApplication):
    """
    This special Application runs a CoAP server so that other modules may use it to store CoAP resources
    for external nodes (e.g. those running a CoapSensor) to GET/POST/PUT/etc.  It allows for
    defining custom CoapResources that can handle application-specific logic.

    NOTE: much of the logic for how the server interacts with external requests resides in the CoapResource classes.
    They actually handle exposing APIs, calling callbacks when they're activated, and managing SensedEvents from
    remote sources.
    """

    _DEFAULT_COAP_SERVER_NAME = '__default_scale_coap_server__'

    def __init__(self, broker,
                 events_root=None,
                 server_name=_DEFAULT_COAP_SERVER_NAME,
                 hostname="0.0.0.0",
                 port=DEFAULT_COAP_PORT,
                 multicast=False,
                 **kwargs):
        """
        Simple constructor.  When on_start is called, the server will actually be run.
        :param broker: internal scale_client broker
        :param events_root: if specified, will allow remote clients to store events at this root
        :param server_name: the user-assigned name for this server so as to distinguish between multiple running ones
        (if unspecified only a single server without an explicit name can be run)
        :param hostname: hostname/IP address to bind server to
        :param port: port to run server on
        :param multicast: optionally enable handling multicast requests
        :param kwargs:
        """
        super(CoapServer, self).__init__(broker=broker, **kwargs)

        self._server = None  # Type: coapthon.server.coap.CoAP
        self._events_root = events_root

        self._hostname = hostname
        self._port = port
        self._multicast = multicast
        if multicast and hostname != coapthon.defines.ALL_COAP_NODES:
            log.warning("underlying CoAPthon library currently only supports the ALL_COAP_NODES multicast address of %s" % coapthon.defines.ALL_COAP_NODES)

        self._server_running = False
        self._is_connected = False

        # Users need to access the server in their other CoAP-based modules,
        # so we keep a registry of them indexed by the user-assigned name.
        # XXX: we just set this as an object on the broker instance so it doesn't persist across ScaleClients (mostly for testing)
        # TODO: use Application.name and a registration service for this
        try:
            instances = broker._coap_server_instances
        except AttributeError:
            instances = broker._coap_server_instances = dict()

        # Register this server as a currently-running instance
        if server_name in instances:
            raise ValueError("A CoapServer with server_name %s already exists!  Aborting creation of the second one..." % server_name)
        instances[server_name] = self
        self._server_name = server_name

    def __run_server(self):
        log.debug("starting CoAP server at IP:port %s:%d" % (self._hostname, self._port))

        try:
            self._server = CoapthonServer(self._hostname, self._port, self._multicast)
        except TypeError:
            # coapthon 4.0.2 has a different constructor API
            self._server = CoapthonServer((self._hostname, self._port), self._multicast)

        if self._events_root is not None:
            root_event = self.make_event(source=self._events_root, data='root of SCALE events resources', priority=1)
            self.store_event(root_event, self._events_root)

        self._server_running = True
        self._notify_running()

        # Listen for remote connections GETting data, etc.
        self._server.listen()

    # CIRCUITS-SPECIFIC: not entirely, but may be broker by switch to another runtime...
    # TODO: document this!
    from scale_client.core.sensed_event import Event
    class CoapServerRunning(Event):
        pass

    def _notify_running(self):
        """Publishes an event to let other apps know that this server is now up and running.
        They should be careful to not use this server until this notification!"""
        event = self.CoapServerRunning(self)
        self.publish(event)

    def on_stop(self):
        self._server.close()
        self._server_running = False
        super(CoapServer, self).on_stop()

    def on_start(self):
        self.run_in_background(self.__run_server)

    def store_event(self, event, path=None, disable_post=False, disable_put=False, disable_delete=False):
        """
        Stores the event as a resource at the given path in the CoAP server.
        A SensedEventCoapResource stored this way will be exposed externally at the given CoAP
        path so that GET, PUT, etc. can be called on it unless you disable them through
        the parameters.

        :param event:
        :type event: scale_client.core.sensed_event.SensedEvent
        :param path: the path at which the event should be stored (default=event.get_type())
        :param disable_post:
        :param disable_put:
        :param disable_delete:
        :return:
        """

        if path is None:
            path = event.event_type
        # XXX: Ensure path is formatted properly for CoAP's internals
        if not path.startswith('/'):
            path = '/' + path
        if path.endswith('/'):
            path = path[:-1]

        assert isinstance(self._server, CoapthonServer)  # for type annotation

        # Update the resource if it exists and notify possible observers (unfortunately,
        # CoAPthon doesn't have a clean way to do exactly this since most of the lower APIs
        # assume request/response/transaction objects).
        # Furthermore, we don't want the render_PUT API to fire as we have it currently
        # since that would publish the event internally again.
        try:
            res = self._server.root[path]
            assert isinstance(res, SensedEventCoapResource)
            res.event = event
            self._server.notify(res)
            log.debug("updated resource at path: %s" % path)

        # Create the resource since it didn't exist.
        # We add callbacks so modifications to the resource are published internally.
        except KeyError:
            # post_cb = None if disable_post else lambda req, res: self.publish(res.event)
            # put_cb = None if disable_put else lambda req, res: self.publish(res.event)
            def __default_event_callback(request, resource):
                """
                Default callback to enable logging and internally publish new events.
                :type request: coapthon.messages.request.Request
                :return:
                """
                log.debug("new event received via %s: %s" % (coap_code_to_name(request.code), resource.event))
                return self.publish(resource.event)

            post_cb = None if disable_post else __default_event_callback
            put_cb = None if disable_put else __default_event_callback

            new_resource = SensedEventCoapResource(event, name=event.event_type,
                                                   get_callback=lambda x, y: y,  # always enabled
                                                   post_callback=post_cb, put_callback=put_cb,
                                                   delete_callback=None if disable_delete else lambda x, y: True)
            self.store_resource(path, resource=new_resource)

    def store_resource(self, path, resource):
        """
        Stores a CoapResource in the server at the given path.
        :param path:
        :param resource:
        :return:
        """

        res = self._server.add_resource(path, resource)
        log.debug("%s added resource to path: %s" % ('successfully' if res else 'unsuccessfully', path))

    def is_running(self):
        return self._server_running

    def register_api(self, path, name, get_callback=None, put_callback=None,
                     post_callback=None, delete_callback=None, error_callback=None,
                     observable=False, allow_children=False, visible=True):
        """
        Registers the specified callbacks at the given path to create a custom API.  This will create a Resource
        at that path with the given properties so that a CoAP client can GET/PUT/POST/DELETE it and have the
        corresponding callback fired in response.  If no callback is specified for that method, it returns a
        METHOD_NOT_ALLOWED response.  If an exception is encountered, error_callback is called if specified
        where the default is to simply log the error.

        CALLBACK DEFINITIONS:
        The callbacks should accept the CoAP Request object and the relevant resource as parameters.  The
        error_callback should additionally accept the exception encountered as its third parameter.  If you
        can recover from the error, simply return the resource from the callback after doing so.  Otherwise,
        raise an exception noting that raising NotImplementedError will return a METHOD_NOT_ALLOWED response.
        Thus the callbacks have the following form:

        callback(coapthon.messages.request.Request, ScaleCoapResource, [Exception]) -> ScaleCoapResource

        :param path: full pathname e.g. /sensors/temp0/interval
        :param name: name of the API endpoint (useful when a client does a DISCOVER request)
        :param get_callback:
        :param put_callback:
        :param post_callback:
        :param delete_callback:
        :param error_callback:
        :param observable:
        :param allow_children:
        :param visible:
        :return: the newly added resource
        """
        # TODO: maybe we should use the advanced interface, optionally the separate one, in order to modify response?

        if error_callback is None:
            error_callback = lambda req, res, err: log.error("coap api error with resource %s while answering request %s:\n %s" % (res, req, err))
        res = ScaleCoapResource(name, get_callback=get_callback, put_callback=put_callback,
                                post_callback=post_callback, delete_callback=delete_callback,
                                error_callback=error_callback,
                                coap_server=self._server, visible=visible,
                                observable=observable, allow_children=allow_children)
        self.store_resource(path, res)
        return res