Exemple #1
0
    def start_server(self):
        """
        Starts the CoAP server and creates the resource tree that is the
        endpoint resources that clients access.
        """
        self.logger.info("Starting the CoAP server")
        site = resource.Site()

        # Default resources for the CoAP server
        self.logger.info("Creating default resources")
        site.add_resource(
            ['.well-known', 'core'],
            resource.WKCResource(site.get_resources_as_linkheader)
        )

        # Time from the server
        site.add_resource(
            ['time'],
            server_time.TimeResource()
        )

        site.add_resource(
            ['get_updates'],
            get_updates.FeederUpdateResource()
        )

        asyncio.Task(aiocoap.Context.create_server_context(site))
        self.logger.info("CoAP server has started!")
        asyncio.get_event_loop().run_forever()
def main(database: str, flush: bool = False):
    logger.info("Starting mqtt-coap bridge")

    loop = asyncio.get_event_loop()

    if flush:
        try:
            os.remove(database)
        except FileNotFoundError:
            pass

    coap_site = resource.Site()
    coap_site.add_resource(['.well-known', 'core'],
                           resource.WKCResource(
                               coap_site.get_resources_as_linkheader,
                               impl_info=None))

    bridge = MQTTCOAPBridge(database)
    coap_site.add_resource(['mqtt'], bridge.coap_connector)

    # May want to catch other signals too
    signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT)
    for sig in signals:
        loop.add_signal_handler(
            sig,
            lambda sig=sig: asyncio.create_task(shutdown(sig, loop, bridge)))

    try:
        loop.create_task(start(coap_site, bridge))
        loop.run_forever()
    finally:
        loop.close()
        logger.info("Successfully shutdown the mqtt-coap bridge.")
Exemple #3
0
def main():
    config.read('config.ini')

    hostsfromconfig(config['HOSTS']['known_hosts'],known_hosts)
    hostsfromconfig(config['HOSTS']['unknown_hosts'],unknown_hosts)
    
    clog.info("Routes configured:")
    for hosts in known_hosts:
        clog.info(f"{hosts} as {known_hosts[hosts]}")

    client.on_connect = on_connect
    client.username_pw_set(config['MQTT'].get('username',MQTTdefault['username']),config['MQTT'].get('password',MQTTdefault['password']))
    client.connect(config['MQTT'].get('host',MQTTdefault['host']),config['MQTT'].getint('port',MQTTdefault['port']))
    client.loop_start()

    root = PrintingLogSite()
    root.add_resource(['.well-known', 'core'],
            resource.WKCResource(root.get_resources_as_linkheader))
    root.add_resource(['temp'], TempResource())

    clog.info("Routes configured:")
    for route in root._resources:
        clog.info(route)

    logging.info(f"Starting coap server on: [{config['COAP']['interface']}]:{config['COAP'].getint('port')}")
    asyncio.Task(aiocoap.Context.create_server_context(root,bind=(config['COAP']['interface'],config['COAP'].getint('port'))))
    asyncio.get_event_loop().run_forever()
Exemple #4
0
def main():
    # Resource tree creation
    root = resource.Site()

    root.add_resource(['.well-known', 'core'],
                      resource.WKCResource(root.get_resources_as_linkheader))

    server_credentials = aiocoap.credentials.CredentialsMap()

    root = oscore_sitewrapper.OscoreSiteWrapper(root, server_credentials)

    protocol = asyncio.get_event_loop().run_until_complete(
        aiocoap.Context.create_server_context(root))

    # Keys from IETF109 plug test: Rikard Test 2 Entity 1
    server_credentials[":a"] = \
            aiocoap.oscore.SimpleGroupContext(
                    algorithm = aiocoap.oscore.algorithms[aiocoap.oscore.DEFAULT_ALGORITHM],
                    hashfun = aiocoap.oscore.hashfunctions[aiocoap.oscore.DEFAULT_HASHFUNCTION],
                    alg_countersign = aiocoap.oscore.Ed25519(),
                    group_id = bytes.fromhex('DD11'),
                    master_secret = bytes.fromhex('11223344556677889900AABBCCDDEEFF'),
                    master_salt = bytes.fromhex('1F2E3D4C5B6A7081'),
                    sender_id = bytes.fromhex('0A'),
                    private_key = bytes.fromhex('397CEB5A8D21D74A9258C20C33FC45AB152B02CF479B2E3081285F77454CF347'),
                    peers = {
                        bytes.fromhex('51'): bytes.fromhex('2668BA6CA302F14E952228DA1250A890C143FDBA4DAED27246188B9E42C94B6D'),
                        bytes.fromhex('52'): bytes.fromhex('5394E43633CDAC96F05120EA9F21307C9355A1B66B60A834B53E9BF60B1FB7DF'),
                        bytes.fromhex('dc'): aiocoap.oscore.DETERMINISTIC_KEY,
                        },
                    )

    asyncio.get_event_loop().run_forever()
Exemple #5
0
def MyCoap():
    # Resource tree creation
    root = resource.Site()

    lock = threading.Lock()

    root.add_resource(('.well-known', 'core'),
                      resource.WKCResource(root.get_resources_as_linkheader))

    # root.add_resource(('time',), TimeResource())

    # root.add_resource(('other', 'lockrequest'), BlockResource())

    root.add_resource(('hello', ), HelloResource())

    root.add_resource(('receiveData', ), ReceiveData())

    root.add_resource(('queryData', ), QueryData())

    root.add_resource(('mobileEvent', ), MobileEventDeal())

    # root.add_resource(('other','gpsinfo'), GPSPositionResource())

    asyncio.Task(aiocoap.Context.create_server_context(root))

    asyncio.get_event_loop().run_forever()
Exemple #6
0
    def main_func():
        led1 = LEDResource(21)
        led2 = LEDResource(22)
        shutter_func = lambda: (led1.resource.off(), led2.resource.off())

        root = resource.Site()
        root.add_resource(['.well-known', 'core'],
                          resource.WKCResource(
                              root.get_resources_as_linkheader))
        root.add_resource(['led1'], led1)
        root.add_resource(['led2'], led2)
        root.add_resource(['button1'],
                          ButtonResource(11,
                                         lambda: led1.resource.toggle(),
                                         loop=event_loop))
        root.add_resource(['button2'],
                          ButtonResource(12,
                                         lambda: led2.resource.toggle(),
                                         loop=event_loop))

        tasks = []

        asyncio.set_event_loop(event_loop)
        asyncio.Task(
            Context.create_server_context(root, bind=(SERVER_IP, 5683)))
        tasks.append(
            asyncio.ensure_future(
                observe_button('127.0.0.3', 'shutter', shutter_func)))
        event_loop.run_forever()

        for t in tasks:
            t.cancel()
Exemple #7
0
def start_coap_test():
    root = resource.Site()
    root.add_resource(('.well-known', 'core'),
                      resource.WKCResource(root.get_resources_as_linkheader))
    root.add_resource(('other', 'block'), BlockResource())
    asyncio.Task(aiocoap.Context.create_server_context(root))
    asyncio.get_event_loop().run_forever()
Exemple #8
0
async def setup(port):
    # set up address and port
    address = '127.0.0.1'
    port = int(port)

    # resource tree creation
    root = resource.Site()

    root.add_resource(['.well-known', 'core'],
                      resource.WKCResource(root.get_resources_as_linkheader))
    root.add_resource(['knn'], KNNResource())

    protocol = await asyncio.Task(
        aiocoap.Context.create_server_context(root, bind=('127.0.0.1', port)))

    # create payload for parallelism entity registration
    payload = {"entity": 0, "address": address, "port": port}
    s_payload = json.dumps(payload).encode('ascii')
    uri = 'coap://127.0.0.1:5000/parallelism-entity'

    # add this worker to base parallelism entity (id 0)
    request = aiocoap.Message(code=aiocoap.PUT, payload=s_payload, uri=uri)

    try:
        response = await protocol.request(request).response
    except Exception as e:
        print('Failed to join parallelism entity')
    else:
        print('Result: %s\n%r' %
              (response.code, json.loads(response.payload.decode('ascii'))))
Exemple #9
0
def setup_server(device):
    root = resource.Site()
    root.add_resource(('.well-known', 'core'),
                      resource.WKCResource(root.get_resources_as_linkheader))

    for sensor in device.sensors:
        root.add_resource(sensor.route, sensor.resource)

    return root
Exemple #10
0
 def coap_event_server(self, comm_wrapper, ip6_address, coap_port):
     root = resource.Site()
     root.add_resource(
         ('.well-known', 'core'),
         resource.WKCResource(root.get_resources_as_linkheader))
     root.add_resource(('wishful_events', ), EventResource(comm_wrapper))
     yield from aiocoap.Context.create_server_context(root,
                                                      bind=(ip6_address,
                                                            coap_port))
Exemple #11
0
def main():
    # Resource tree creation
    root = resource.Site()
    root.add_resource(('twitter', ), RiotTwitterResource())
    root.add_resource(('.well-known', 'core'),
                      resource.WKCResource(root.get_resources_as_linkheader))
    asyncio. async (aiocoap.Context.create_server_context(root))

    asyncio.get_event_loop().run_forever()
Exemple #12
0
def main():
    root = resource.Site()

    root.add_resource((".well-known", "core"),
                      resource.WKCResource(root.get_resources_as_linkheader))
    root.add_resource(("testing", "things"), SimpleResource())

    asyncio.Task(coap.Context.create_server_context(root))
    asyncio.get_event_loop().run_forever()
Exemple #13
0
def main():
    # Resource tree creation
    root = resource.Site()
    root.add_resource(('.well-known', 'core'),
                      resource.WKCResource(root.get_resources_as_linkheader))
    root.add_resource(('time', ), TimeResource())
    root.add_resource(('other', 'block'), BlockResource())
    root.add_resource(('other', 'separate'), SeparateLargeResource())
    asyncio. async (aiocoap.Context.create_server_context(root))
    asyncio.get_event_loop().run_forever()
def Coap_server():
    loop_func = asyncio.new_event_loop()
    asyncio.set_event_loop(loop_func)
    root = resource.Site()
    root.add_resource(('.well-known', 'core'),
                      resource.WKCResource(root.get_resources_as_linkheader))
    root.add_resource(('other', 'block'), resources_block())
    asyncio.Task(aiocoap.Context.create_server_context(root))
    loop_func = asyncio.get_event_loop()
    loop_func.run_forever()
Exemple #15
0
def piccolo_server(serverCfg):

    log = logging.getLogger("piccolo.server")

    log.info("piccolo3 server version %s" % piccolo.__version__)

    # creat system info
    psys = piccolo.PiccoloSysinfo()
    # create data directory
    pdata = piccolo.PiccoloDataDir(serverCfg.cfg['datadir']['datadir'],
                                   device=serverCfg.cfg['datadir']['device'],
                                   mntpnt=serverCfg.cfg['datadir']['mntpnt'],
                                   mount=serverCfg.cfg['datadir']['mount'])
    # read the piccolo instrument configuration file
    piccoloCfg = piccolo.PiccoloConfig()
    cfgFilename = pdata.join(
        serverCfg.cfg['config'])  # Usually /mnt/piccolo2_data/piccolo.config
    piccoloCfg.readCfg(cfgFilename)

    # initialise the shutters
    try:
        shutters = piccolo.PiccoloShutters(piccoloCfg.cfg['channels'])
    except:
        log.error('failed to initialise shutters')
        sys.exit(1)

    # initialise the spectrometers
    try:
        spectrometers = piccolo.PiccoloSpectrometers(
            piccoloCfg.cfg['spectrometers'], shutters.keys())
    except Exception as e:
        log.error('failed to initialise spectrometers: {}'.format(str(e)))
        sys.exit(1)

    # initialise the piccolo controller
    controller = piccolo.PiccoloControl(pdata, shutters, spectrometers)

    root = resource.Site()
    # add the components
    for c in [psys, pdata, shutters, spectrometers, controller]:
        root.add_resource(*c.coapSite)

    root.add_resource(('.well-known', 'core'),
                      resource.WKCResource(root.get_resources_as_linkheader))
    asyncio.Task(
        aiocoap.Context.create_server_context(root,
                                              bind=serverCfg.bind,
                                              loggername='piccolo.coapserver'))

    if piccoloStatusLED is not None:
        piccoloStatusLED.blink()
    else:
        log.warning('no hardware support')

    asyncio.get_event_loop().run_forever()
Exemple #16
0
def run():
    print("starting coap")
    root = resource.Site()
    root.add_resource((
        '.well-known',
        'core',
    ), resource.WKCResource(root.get_resources_as_linkheader))
    root.add_resource(('time', ), TimeResource())

    asyncio.Task(aiocoap.Context.create_server_context(site=root))
    asyncio.get_event_loop().run_forever()
def main():
    root = resource.Site()

    root.add_resource(('.well-known', 'core'),
                      resource.WKCResource(root.get_resources_as_linkheader))

    root.add_resource(('var', ), VariableResource())

    asyncio.Task(aiocoap.Context.create_server_context(root))

    asyncio.get_event_loop().run_forever()
Exemple #18
0
def start_loop(loop):
    root = resource.Site()
    root.add_resource(('.well-known', 'core'),
                      resource.WKCResource(root.get_resources_as_linkheader))
    root.add_resource(('time', ), TimeResource())
    root.add_resource(('other', 'block'), BlockResource())
    root.add_resource(('other', 'separate'), SeparateLargeResource())
    asyncio.set_event_loop(loop)
    loop.run_until_complete(
        aiocoap.Context.create_server_context(root, bind=("localhost", 5683)))
    loop.run_forever()
Exemple #19
0
def CoAPserver():
    #Creation of resource tree
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    root = resource.Site()
    root.add_resource(('.well-known', 'core'),
                      resource.WKCResource(root.get_resources_as_linkheader))
    root.add_resource(('other', 'block'), BlockResource())
    asyncio.Task(aiocoap.Context.create_server_context(root))
    loop = asyncio.get_event_loop()
    loop.run_forever()
Exemple #20
0
def main():
    # Resource tree creation
    root = resource.Site()

    root.add_resource(['.well-known', 'core'],
                      resource.WKCResource(root.get_resources_as_linkheader))
    root.add_resource(['time'], TimeResource())
    root.add_resource(['ctxRobot', 'basicrobot'], BasicrobotResource())

    asyncio.Task(aiocoap.Context.create_server_context(root))
    asyncio.get_event_loop().run_forever()
Exemple #21
0
def main():
    # setup gpio
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(led_pin, GPIO.OUT)

    # Resource tree creation
    root = resource.Site()
    root.add_resource(('.well-known', 'core'),
                      resource.WKCResource(root.get_resources_as_linkheader))
    root.add_resource(('gpio', ), GPIOResource())
    asyncio.Task(aiocoap.Context.create_server_context(root))
    asyncio.get_event_loop().run_forever()
Exemple #22
0
def main():
        root = resource.Site()

        root.add_resource(('.well-known', 'core'), resource.WKCResource(root.get_resources_as_linkheader))

        root.add_resource(('mine',), MinecraftResource())

        root.add_resource(('id',), IdResource())

        asyncio.Task(Context.create_server_context(root))

        asyncio.get_event_loop().run_forever()
Exemple #23
0
def main():
    # Resource tree creation
    root = resource.Site()

    root.add_resource(('.well-known', 'core'),
                      resource.WKCResource(root.get_resources_as_linkheader))
    root.add_resource(('data', ), DataResource())
    root.add_resource(('profile', ), ProfileResource())

    asyncio.Task(aiocoap.Context.create_server_context(root))

    asyncio.get_event_loop().run_forever()
Exemple #24
0
def start_server():
    print("COAP SERVER RUNNING")
    root = resource.Site()

    root.add_resource(('.well-known', 'core'),
                      resource.WKCResource(root.get_resources_as_linkheader))
    root.add_resource(('update', ), BasicResource())
    root.add_resource(('register', ), RegisterResource())

    asyncio.Task(aiocoap.Context.create_server_context(root))

    asyncio.get_event_loop().run_forever()
Exemple #25
0
    def start():
        root = resource.Site()

        # Register CoAP methods
        root.add_resource(
            ('.well-known', 'core'),
            resource.WKCResource(root.get_resources_as_linkheader))

        SensorValues().register(root)

        asyncio.Task(aiocoap.Context.create_server_context(root))
        asyncio.get_event_loop().run_forever()
def main():
    # Resource tree creation
    root = resource.Site()

    root.add_resource(['.well-known', 'core'],
                      resource.WKCResource(root.get_resources_as_linkheader))
    root.add_resource(['other', 'separate'], SeparateLargeResource())
    root.add_resource(['whoami'], WhoAmI())
    root.add_resource(['image'], save_image())

    asyncio.Task(aiocoap.Context.create_server_context(root))

    asyncio.get_event_loop().run_forever()
Exemple #27
0
def physical():
    """Run coap resources on real raspberry pi"""
    root = resource.Site()
    root.add_resource(['.well-known', 'core'],
                      resource.WKCResource(root.get_resources_as_linkheader))
    root.add_resource(['led'], LEDResource(17))
    root.add_resource(['buzzer'], BuzzerResource(22, active_high=False))
    root.add_resource(['button'],
                      ButtonResource(27, lambda: print("Button pressed")))

    asyncio.set_event_loop(event_loop)
    asyncio.Task(Context.create_server_context(root, bind=(SERVER_IP, 5683)))
    event_loop.run_forever()
Exemple #28
0
    def __init__(self, *, directory, **kwargs):
        """Constructor

        :param directory: Service directory to use as backend
        :type directory: soa.directory.ServiceDirectory
        """
        super().__init__()
        self._directory = directory
        self.site = ServiceDirectoryCoAP(directory=directory, uri_prefix=('servicediscovery', ))
        self.context = aiocoap.Context.create_server_context(self.site, **kwargs)

        self.site.add_resource(
            ('.well-known', 'core'),
            resource.WKCResource(self.site.get_resources_as_linkheader))
Exemple #29
0
def main():
    # Resource tree creation
    root = resource.Site()

    root.add_resource(['.well-known', 'core'],
                      resource.WKCResource(root.get_resources_as_linkheader))
    root.add_resource(['time'], TimeResource())
    root.add_resource(['other', 'block'], BlockResource())
    root.add_resource(['other', 'separate'], SeparateLargeResource())

    asyncio.Task(
        aiocoap.Context.create_server_context(root, bind=('127.0.0.1', 5683)))

    asyncio.get_event_loop().run_forever()
Exemple #30
0
def coaps():
    """
    Function for coap daemon
    """
    coap_loop = asyncio.new_event_loop()
    asyncio.set_event_loop(coap_loop)
    root = resource.Site()
    root.add_resource(('.well-known', 'core'),
                      resource.WKCResource(root.get_resources_as_linkheader))
    root.add_resource(('other', 'block'), coap_handler())
    asyncio.Task(aiocoap.Context.create_server_context(root))
    coap_loop = asyncio.get_event_loop()
    print("coap daemon started!")
    coap_loop.run_forever()