javaosgiosgi-bundlekura

Kura How to communicate between bundles?


I am trying to do an IoT project where I need to implement some OSGi services. The problem is these services need to send information between them. I have seen that this is possible to do with some tools like "bnd", but currently I am working with Kura. So, I would like to know what would be the way to do that with Kura.

Thank you very much for your help.


Solution

  • I have seen that this is possible to do with some tools like "bnd", but currently I am working with Kura.

    The bnd project is a tool that is primarily used at build time to help you assemble the metadata for your OSGi bundle. There's no problem at all with using bnd to help make your bundle and then using it in a platform like Kura at runtime.

    I am trying to do an IoT project where I need to implement some OSGi services.

    The easiest way to implement an OSGi service is using an injection framework called Declarative Services. This allows you to write a simple POJO which will be registered in the OSGi Service Registry. This is as simple as adding @Component to the class:

    @Component
    public class MyComponent implements SomeService {
    
        @Override
        public void someServiceMethod() { }
    
    }
    

    The above component will automatically be registered as a SomeService because it implements the interface. The Kura platform includes a Declarative Services implementation, so there isn't anything else you need to install. You should, however, check the version of the annotations that you use against the version supported by Kura (3.x of Kura uses DS 1.2, 4.x uses DS 1.3).

    The problem is these services need to send information between them.

    OSGi services implemented using DS are able to reference one another in a very clean and simple way using the @Reference annotation.

    @Component
    public class MyComponent implements SomeService {
    
        SomeOtherService someOtherService;
    
        @Reference
        void setSomeOtherService(SomeOtherService sos) {
            someOtherService = sos;
        }
    
        @Override
        public void someServiceMethod() { 
            someOtherService.doSomethingElse();
        }
    }
    

    If you are able to use DS 1.3 then the @Reference annotation can be applied directly to a field:

    @Component
    public class MyComponent implements SomeService {
    
        @Reference
        SomeOtherService someOtherService;
    
        @Override
        public void someServiceMethod() { 
            someOtherService.doSomethingElse();
        }
    }
    

    There are plenty more examples of using Declarative Services and other OSGi specifications in the OSGi enRoute project