Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

SensiNact/Tutorial Bridge

< SensiNact
Revision as of 10:40, 17 May 2017 by Remi.druilhe.gmail.com (Talk | contribs) (The project skeleton)

A sensiNact Bridge tutorial - the weather station example

Required knowledge

This tutorial requires knowledge about:

The project skeleton

Let start by defining a simple weather station providing four kind of information:

  • temperature
  • humidity
  • atmospheric pressure
  • wind speed

We will first create the weather station module skeleton by the way of the ``sensinact-archetype``. You just have to invoke the ``mvn archetype:generate`` command in your favorite terminal emulator like specified below

> mvn archetype:generate -DarchetypeGroupId=org.eclipse.sensinact.archetypes -DarchetypeArtifactId=sensinact-archetype -DarchetypeVersion=1.0 -DgroupId=org.eclipse.sensinact.gateway.simulated -DartifactId=weather-station

Weather station skeleton

A new maven project has been created containing :

  • weather-station/pom.xml: this is the maven project description file in which dependencies are referenced, as well as the configuration of the [maven-bundle-plugin](http://felix.apache.org/documentation/subprojects/apache-felix-maven-bundle-plugin-bnd.html) that will be used to create our executable [bundle](https://fr.wikipedia.org/wiki/OSGi).
  • weather-station/schema/sensinact-resource.xsd: this is the schema on which the XML description of the resources of our weather station is based on. It will not be added to the compiled module, but is provided by the sensinact-archetype while not accessible remotely.
  • weather-station/src/main/java/fr/cea/sna/gateway/simulated/osgi/Activator.java: this java class is the [1]'s [2]. We will have to complete it later.
  • weather-station/src/main/resources/sensiNact-conf.xml: this java xml properties file will be loaded at initialization time and allows to configure our module by adding properties.
  • weather-station/src/main/resources/resource.xml: we will later amend this xml file in which are described the resources provided by the weather station.

The simplest possible implementation

The first sample implementation does not operate the schema and thus the fine configuration possibilities offered by the XML resources description file;

The generic implementation we are using to create our weather station implies to provide some 'objects' that are required to synchronize the new sensiNact's resource model instance to its connected counterpart:

  • an XmlModelConfiguration, its initialization requires the name of the XML resources description (the resource.xml in our case);
  • a ProtocolStackEndpoint which is the connecting point to the remote counterpart of the resource model instance.

sensiNact resource model generic

To feed our weather station we also have to define the kind of data that will be used and how to consume them. To manage processing data, the sensiNact resource model implementation expects a data structure implementing the Packet interface, representing a communication object wrapping the raw transmitted data. Moreover we have to provide an appropriate PacketReader able to identify in an handled Packet type the relevant information for the sensiNact system. In our bridge example we will cope with JSON formated data structures, in which the properties' keys and values will refer respectively to our resources' identifiers and values. We will so define our own Packet type that we will call WeatherPacket, and the PacketReader in charge of parsing it, the WeatherPacketReader.

First of all, as mentioned above we instantiate the components that are required to create the bridge: the model instances configuration and the protocol stack connector endpoint. The configuration object (XmlModelConfiguration) allows to specify whether the elements of the resource model can be created dynamically when identified by the PacketReader; in this case it allows to define the extended DataResource type to use, as well as its embedded data type. Both XmlModelConfiguration and ProtocolStackEndpoint have next to be connected by the way of the connect method of the protocol stack connector endpoint.


package org.eclipse.sensinact.gateway.simulated.osgi;
 
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.eclipse.sensinact.gateway.generic.core.impl.ExtProtocolStackEndpoint;
import org.eclipse.sensinact.gateway.generic.core.impl.ExtXmlModelConfiguration;
import org.eclipse.sensinact.gateway.common.bundle.AbstractActivator;
import org.eclipse.sensinact.gateway.common.bundle.Mediator;
import org.eclipse.sensinact.gateway.simulated.weather.WeatherPacket;
 
/**
 * The weather station bundle activator
 */
public class Activator extends AbstractActivator<Mediator>
{      
	private ExtProtocolStackEndpoint<WeatherPacket> connector;
	private ExtXmlModelConfiguration<WeatherPacket> manager;
 
       /**
	* @inheritDoc
	*
	* @see org.eclipse.sensinact.gateway.common.bundle.AbstractActivator#doStart()
	*/
	@Override
	public void doStart() throws Exception
	{        
	   manager = new XmlModelInstanceBuilder<ExtXmlModelConfiguration,
        	XmlModelInstance>(super.mediator,XmlModelInstance.class,
        	ExtXmlModelConfiguration.class
        		).withPacketType(WeatherPacket.class
                ).withBuildDynamically(true
                ).withDataResourceType(SensorDataResource.class
                ).withDataType(float.class
                ).withStartAtInitializationTime(true
                ).buildConfiguration("resource.xml", Collections.<String,String>emptyMap());             
       connector = new ExtProtocolStackEndpoint<WeatherPacket>(super.mediator);
       connector.connect(manager);
	}
 
   /**
	* @inheritDoc
	*
	* @see org.eclipse.sensinact.gateway.common.bundle.AbstractActivator#doStop()
	*/
	@Override
	public void doStop() throws Exception
	{
	   connector.stop();
	}
 
   /**
	* @inheritDoc
	*
	* @see org.eclipse.sensinact.gateway.common.bundle.AbstractActivator#
	* doInstantiate(org.osgi.framework.BundleContext)
	*/
	@Override
	public Mediator doInstantiate(BundleContext context) 
	throws InvalidSyntaxException
	{
	   return new Mediator(context);
	}    
}

The mediator argument, needed by both XmlModelConfiguration and ProtocolStackEndpoint constructors allows to interact with the OSGi host environment by the way of the [BundleContext](https://osgi.org/javadoc/r4v43/core/org/osgi/framework/BundleContext.html) from one hand, and on the other hand provides logging feature.


package org.eclipse.sensinact.gateway.simulated.weather;
 
import org.eclipse.sensinact.gateway.generic.core.packet.Packet;
 
/**
 * Extended {@link Packet} implementation wrapping 
 * a communication object targeting the weather station
 */
public class WeatherPacket implements Packet
{ 
   /**
	* the bytes array content of this WeatherPacket
	*/
	private byte[] content;
 
   /**
	* Constructor
	*
	* @param content
	*      the bytes array content of the WeatherPacket to
	*      instantiate
	*/
	public WeatherPacket(byte[] content)
	{
		int length = content==null?0:content.length;
		this.content = new byte[length];
		if(length > 0)
		{
			System.arraycopy(content, 0, this.content, 0, length);
		}
	}
 
   /**
	* @inheritDoc
	*
	* @see org.eclipse.sensinact.gateway.generic.core.packet.Packet#getBytes()
	*/
	@Override
	public byte[] getBytes()
	{
		byte[] content = new byte[this.content.length];
		if(this.content.length> 0)
		{
			System.arraycopy(this.content, 0, content, 0, this.content.length);
		}
		return content;
	}
}

the getBytes method is the only one specified in the Packet interface. We could have to define other methods to extract protocol specific information from the wrapped communication object, but in our case it is not needed.

The WeatherPacketReader will extend the SimplePacketReader abstract class which requires to only implement the **parse** method. The SimplePacketReader parsing mechanism consists in building a hierarchical data structure of contained information to map to the hierarchical sensiNact's resource model :

Packet reader mechanism

When a complete branch of the tree is built we just have to call the configure method before to complete a new one


package org.eclipse.sensinact.gateway.simulated.weather;
 
import org.json.JSONObject;
import org.eclipse.sensinact.gateway.generic.core.InvalidPacketException;
import org.eclipse.sensinact.gateway.generic.core.packet.SimplePacketReader;
import org.eclipse.sensinact.gateway.common.bundle.Mediator;
 
/**
 * {@link PacketReader} dedicated to {@link WeatherPacket} parsing
 */
public class WeatherPacketReader extends SimplePacketReader<WeatherPacket>
{
   /**
	* Constructor
	* 
	* @param mediator
	*/
    protected WeatherPacketReader(Mediator mediator)
    {
	    super(mediator);
    }
 
   /**
	* @inheritDoc
	*
	* @see org.eclipse.sensinact.gateway.generic.core.packet.PacketReader#
	* parse(org.eclipse.sensinact.gateway.generic.core.packet.Packet)
	*/
    @Override
    public void parse(WeatherPacket packet) throws InvalidPacketException
    {
       JSONObject jsonObject = new JSONObject(new String(packet.getBytes()));
 
      super.setServiceProviderId("station");
      super.setServiceId("weather");    	
      super.setResourceId("temperature");
      super.setData(jsonObject.opt("temperature"));
      super.configure();
 
      super.setServiceProviderId("station");
      super.setServiceId("weather");    	
      super.setResourceId("humidity");
      super.setData(jsonObject.opt("humidity"));
      super.configure();
 
      super.setServiceProviderId("station");
      super.setServiceId("weather");    	
      super.setResourceId("pressure");
      super.setData(jsonObject.opt("pressure"));
      super.configure();
 
      super.setServiceProviderId("station");
      super.setServiceId("weather");    	
      super.setResourceId("wind");
      super.setData(jsonObject.opt("wind"));
      super.configure();
   }
}

Our sensiNact's resource model instance can be updated by parsing a JSONObject of the form :

{
  "temperature" : 5.2,
  "humidity" : 52,
  "pressure" : 1027.5,
  "wind" : 6.4
}

To simulate a communication with a distant weather station we just have to wrap a JSONObject whose format is as described above into a WeatherPacket and ask the ProtocolStackEndpoint to process it.

We could have adopted a more efficient data structure, but this one has the advantage to be easily understandable. To allow our sensiNact's resource model instance to use our WeatherPacketReader we still have to provide an appropriate factory and to reference it for the java's [ServiceLoader](https://docs.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html). The searched factory will be one implementing the PacketReaderFactory interface which defines two methods :

  • the handle method taking a Packet type as parameter and returning a boolean defining whether the specified Packet type is handled by the factory ;
  • the newInstance method instantiating a new PacketReader used to parse the Packet parameter.

package org.eclipse.sensinact.gateway.simulated.weather;
 
import org.eclipse.sensinactgateway.generic.core.InvalidPacketException;
import org.eclipse.sensinact.gateway.generic.core.impl.ExtXmlModelConfiguration;
import org.eclipse.sensinact.gateway.generic.core.XmlModelConfiguration;
import org.eclipse.sensinact.gateway.generic.core.impl.PacketReaderFactory;
import org.eclipse.sensinact.gateway.generic.core.packet.Packet;
import org.eclipse.sensinact.gateway.generic.core.packet.PacketReader;
import org.eclipse.sensinact.gateway.common.bundle.Mediator;
 
public class WeatherPacketReaderFactory implements PacketReaderFactory<WeatherPacket> {
   /**
	* @inheritDoc
	*
	* @see org.eclipse.sensinact.gateway.generic.core.impl.PacketReaderFactory#
	* handle(java.lang.Class)
	*/
    @Override
    public boolean handle(Class<? extends Packet> packetType) {
	    return WeatherPacket.class.isAssignableFrom(packetType);
    }
 
   /**
    * @inheritDoc
    *
    * @see org.eclipse.sensinact.gateway.generic.core.impl.PacketReaderFactory#
    * newInstance(org.eclipse.sensinact.gateway.common.bundle.Mediator, 
    * org.eclipse.sensinact.gateway.generic.core.XmlModelConfiguration, 
    * org.eclipse.sensinact.gateway.generic.core.packet.Packet)
    */
    @Override
    public PacketReader<WeatherPacket> newInstance(
      Mediator mediator, XmlModelConfiguration<WeatherPacket> manager,
      WeatherPacket packet) throws InvalidPacketException
    {    	
    	 WeatherPacketReader packetReader = new WeatherPacketReader(mediator);
    	 packetReader.parse(packet);
    	 return packetReader;
    }
}

Finally, in the META-INF/services/org.eclipse.sensinact.gateway.generic.core.impl.PacketReaderFactory text file we specify the canonical name of our factory class to make it accessible by the java's ServiceLoader: org.eclipse.sensinact.gateway.simulated.weather.WeatherPacketReaderFactory.

Let see below what our project looks like now:

Sna weather-station-skeleton2.png

The connected counterpart - Let's start with a simulation

For this first example we will use a simulated counterpart; a simple java thread sanding random values in a loop:


package org.eclipse.sensinact.gateway.simulated.weather;
 
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONObject;
import org.eclipse.sensinact.gateway.generic.core.InvalidPacketException;
import org.eclipse.sensinact.gateway.generic.core.ProtocolStackEndpoint;
 
public class WeatherStation implements Runnable {
	private static final Logger LOGGER = Logger.getLogger(WeatherStation.class.getName());
 
	private static final Random RANDOM = new Random();
 
	private double temperature = 20.0d;
	private double humidity = 53.0d;
	private double pressure = 1024.0d;
	private double wind = 22.0d;
 
	private ProtocolStackEndpoint<WeatherPacket> endpoint;
	private boolean running;
 
	/**
	 * Constructor
	 */
	public WeatherStation(ProtocolStackEndpoint<WeatherPacket> endpoint)
	{
		this.endpoint = endpoint;
		this.running = false;
	}
 
	/**
	 * @inheritDoc
	 *
	 * @see java.lang.Runnable#run()
	 */
	public void run()
	{
		this.running = true;
		while(running)
		{			
			temperature = RANDOM.nextBoolean()
					?addition(temperature):subtraction(temperature);
			humidity = RANDOM.nextBoolean()
					?addition(humidity):subtraction(humidity);
			pressure = RANDOM.nextBoolean()
					?addition(pressure):subtraction(pressure);
			wind = RANDOM.nextBoolean()
					?addition(wind):subtraction(wind);
 
			JSONObject content = new JSONObject();
			content.put("temperature", temperature);
			content.put("humidity", humidity);
			content.put("pressure", pressure);
			content.put("wind", wind);
 
			WeatherPacket packet= new WeatherPacket(
					content.toString().getBytes());
			try
			{
				this.endpoint.process(packet);
			}
			catch (InvalidPacketException e)
			{
				LOGGER.log(Level.SEVERE, e.getMessage(), e);
 
			} finally
			{
				try
				{
					Thread.sleep(60000);
 
				} catch(InterruptedException e)
				{
					Thread.interrupted();
					this.stop();
				}
			}
		}
	}
 
	public void stop()
	{
		this.running = false;
	}
 
	private double addition(double value)
	{
		value +=((value/10d)*RANDOM.nextDouble());
		return value;
	}
 
	private double subtraction(double value)
	{
		value -=((value/10d)*RANDOM.nextDouble());
		return value;
	}
}

Download the simulator [here](documents/tutorial/WeatherStation.java).

Download this first complete example [here](documents/tutorial/weather-station-sample.jar).

Operate finer configuration features

The XML resources definition ( the resource.xml file ) is made of a set of <resourceInfo> XML tags describing resources held by the service(s) of the connected device(s) (called ServiceProvider in sensiNact). We can distinguish the resources providing data (called DataResource in sensiNact) from those referring to actuators (called ActionResource in sensiNact). For the first ones a default attribute holding the value of the provided data is created ; It constraints us to define the type of this data, and allows to specify an initial value. Apart from the properties of the 'value' attribute of a DataResource, it is possible to specify as many attributes as we want :


<complexType name="metadata">
	<complexContent>
		<extension base="sensinact:nameTypeValue">
			<sequence>
				<element name="type" type="sensinact:restrictedTypeType" minOccurs="1" maxOccurs="1"/>
				<element name="value" type="sensinact:valueType" minOccurs="0" maxOccurs="unbounded"/>
			</sequence>
			<attribute name="name" use="required" type="sensinact:modifiableHiddenKeyWordsExcludedString"/>
		</extension>
	</complexContent>
</complexType>
 
<complexType name="attribute">
	<complexContent>
		<extension base="sensinact:nameTypeValue">
			<sequence>
				<element name="type" type="sensinact:typeType" minOccurs="1" maxOccurs="unbounded"/>
				<element name="value" type="sensinact:valueType" minOccurs="0" maxOccurs="unbounded"/>
				<element name="metadata"  minOccurs="0" maxOccurs="unbounded" type="sensinact:metadata">
					<unique name="uniqueMetadataValueTarget">
						<selector xpath="./sensinact:value"/>
						<field xpath="@target"/>
					</unique>
				</element>
				<element name="constraints" type="sensinact:constraints" minOccurs="0" maxOccurs="1"/>
			</sequence>
			<attribute name="name" use="required" type="sensinact:nameTypeValueKeyWordsExcludedString"/>
			<attribute name="modifiable" type="boolean" default="true" use="optional"/>
			<attribute name="hidden" type="boolean" default="false" use="optional"/>
		</extension>
	</complexContent>
</complexType>

The restriction applying on the name prevents using 'name', 'type' and 'value'. The modifiable and hidden attributes allow to define respectively whether the resulting attribute can be changed and is visible to the user. As an attribute holds a data, its type must be specified ; Allowed types are: boolean, byte, short, int, long, float, double, string, object array, or any java canonical class name. We can also append metadata to our attribute description, to precise any helpful information to understand the meaning of the provided data. As it is the case for an attribute's name, the one of a metadata is constrained, preventing to use 'modifiable' and 'hidden' values.

A <resourceInfo> XML tag must contain an <identifier> whose content defines how to identify specifically the resource while communicating with the connected counterpart ServiceProvider.


<complexType name="resourceInfo" abstract="true">
	<sequence maxOccurs="1" minOccurs="1">	
		<element name="policy" type="sensinact:policy" minOccurs="0" maxOccurs="1"/>
		<element name="subscriptionModes" type="sensinact:subscriptionModes" minOccurs="0" maxOccurs="1"/>
		<element name="identifier" type="sensinact:simpleContent" minOccurs="1" maxOccurs="1"/>	 
		<element name="attribute" type="sensinact:attribute" minOccurs="0" maxOccurs="unbounded">
			<unique name="uniqueAttributeTypeTarget">
				<selector xpath="./sensinact:type"/>
				<field xpath="@target"/>
			</unique>
			<unique name="uniqueAttributeValueTarget">
				<selector xpath="./sensinact:value"/>
				<field xpath="@target"/>
			</unique>
		</element>		
	</sequence>	
	<attribute name="name" type="string" use="required"/>
	<attribute name="target" type="sensinact:targets" use="optional"/>
	<attribute name="profile" type="sensinact:targets" use="optional"/>
</complexType>

More precisely a DataResource definition can refer to a SensorDataResource, commonly mapped to a sensor whose value cannot be changed by the user; a StateVariableResource, commonly mapped to the state of the service to which it belongs and whose value can be linked to the invocation of an ActionResource; a PropertyResource commonly mapped to a configuration property of the service to which it belongs


	<complexType name="resourceInfoData" abstract="true">
		<complexContent>
			<extension base="sensinact:resourceInfo">			
				<sequence>
					<element name="type" type="sensinact:typeType" minOccurs="1" maxOccurs="unbounded">
					</element>
					<element name="value" type="sensinact:valueType" minOccurs="0" maxOccurs="unbounded">
					</element>	
					<element name="metadata" type="sensinact:metadata" minOccurs="0" maxOccurs="unbounded">
						<unique name="uniqueResourceInfoMetadataValueTarget">
							<selector xpath="./sensinact:value"/>
							<field xpath="@target"/>
						</unique>
					</element>					
					<element name="constraints" type="sensinact:constraints" minOccurs="0" maxOccurs="1"/>	
					<element name="parameters" type="sensinact:dataResourceParameters" minOccurs="0" maxOccurs="unbounded">
						<key name="uniqueDataParameterName">
							<selector xpath="./sensinact:parameter"/>
							<field xpath="@name"/>
						</key>
					</element>		
				</sequence>
				<attribute name="modifiable" type="sensinact:modifiable_enum" use="optional" />
				<attribute name="hidden" type="boolean" use="optional" default="false" />
			</extension>
		</complexContent>
	</complexType>
 
<complexType name="resourceInfoVariable" >
	<complexContent>
		<extension base="sensinact:resourceInfoData">
			<attribute name="policy" type="sensinact:policy_enum" use="optional" fixed="STATE_VARIABLE"/>
		</extension>
	</complexContent>
</complexType>
 
<complexType name="resourceInfoProperty" >
	<complexContent>
		<extension base="sensinact:resourceInfoData">
			<attribute name="policy" type="sensinact:policy_enum" use="optional" fixed="PROPERTY"/>
		</extension>
	</complexContent>
</complexType>
 
<complexType name="resourceInfoSensor" >
	<complexContent>
		<extension base="sensinact:resourceInfoData">
			<attribute name="policy" type="sensinact:policy_enum" use="optional" fixed="SENSOR"/>
		</extension>
	</complexContent>
</complexType>

The type value, metadata and constraints elements, as well as the modifiable and hidden attributes refer to the value attribute that will be automatically created and attached to the DataResource.

You can have a look to the entire schema if you want to know more about the sensiNact resource XML definition, but for now you know enough to continue this tutorial.

As specified above, our weather station will provide four kind of information : temperature, humidity, atmospheric pressure, and wind speed. Each of them will be a readable measure of the physical environment, but not supposed to be changed by the user. We will so use SensorDataResources to define them, to which we will add two metadata, precising the unit and a short description of the resource:


<resourceInfos xmlns="http://org.eclipse.sensinact/resource" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://org.eclipse.sensinact/resource ../../../schema/sensinact-resource.xsd"> 
  <resourceInfo xsi:type="resourceInfoSensor" name="TEMPERATURE" modifiable="UPDATABLE">
    <identifier xsi:type="stringContent">temp</identifier>
    <type>float</type>
    <metadata name="unit">
        <type>string</type>
        <value>celcius (C°)</value>
    </metadata>
    <metadata name="description">
        <type>string</type>
        <value>temperature</value>
    </metadata>
  </resourceInfo>
  <resourceInfo xsi:type="resourceInfoSensor" name="HUMIDITY" modifiable="UPDATABLE">
    <identifier xsi:type="stringContent">humidity</identifier>
    <type>int</type>
    <metadata name="unit">
        <type>string</type>
        <value>percent (%)</value>
    </metadata>
    <metadata name="description">
        <type>string</type>
        <value>relative humidity</value>
    </metadata>
  </resourceInfo>
  <resourceInfo xsi:type="resourceInfoSensor" name="ATMOSPHERIC_PRESSURE" modifiable="UPDATABLE">
    <identifier xsi:type="stringContent">pressure</identifier>
    <type>float</type>
    <metadata name="unit">
        <type>string</type>
        <value>hecto pascal (hpa)</value>
    </metadata>
    <metadata name="description">
        <type>string</type>
        <value>atmospheric pressure</value>
    </metadata>
  </resourceInfo>
  <resourceInfo xsi:type="resourceInfoSensor" name="WIND_SPEED" modifiable="UPDATABLE">
    <identifier xsi:type="stringContent">wind</identifier>
    <type>float</type>
    <metadata name="unit">
        <type>string</type>
        <value>meters by second (m/s)</value>
    </metadata>
    <metadata name="description">
        <type>string</type>
        <value>wind speed</value>
    </metadata>
  </resourceInfo>
</resourceInfos>

By default a ServiceProvider is created with one Service called admin and providing a location Resource. To link a new Resource to this admin Service, it is enough to define the target attribute of the <resourceInfo> XML tag to 'admin'. Otherwise, the new created Resource will be attached to all discovered Services or to those whose names are specified (by the way of a comma separated list of names) in the optional target attribute of the <resourceInfo> XML tag.

After having specified our set of <resourceInfo>, it is also possible to statically define a set of devices with their services, which will give birth to ServiceProviders and their Services in the system at launch time.


<devices>
     <device identifier="station">
          <service name="weather"/>
     </device>      
</devices>

It is enough to create a new ServiceProvider in the system, holding two Services including the weather one, and providing the four Resources described in the resource.xml file.

The connected counterpart - OpenWeather service

We are going now to connect our weather station to a real remote service providing the appropriate data. For this example we will use the OpenWeatherMap service, available for free, and invokable using the GPS location we are interested in.

First, we can adapt our WeatherPacketReader to be able to read the content of the Http response of an Http request send to the OpenWeatherMap service (weather map API) :


package org.eclipse.sensinact.gateway.simulated.weather;
 
import org.json.JSONArray;
import org.json.JSONObject;
import org.eclipse.sensinact.gateway.common.bundle.Mediator;
import org.eclipse.sensinact.gateway.core.LocationResource;
import org.eclipse.sensinact.gateway.core.ServiceProvider;
import org.eclipse.sensinact.gateway.generic.core.InvalidPacketException;
import org.eclipse.sensinact.gateway.generic.core.Task.CommandType;
import org.eclipse.sensinact.gateway.generic.core.packet.SimplePacketReader;
import org.eclipse.sensinact.gateway.sthbnd.http.HttpPacket;
import org.eclipse.sensinact.gateway.util.JSONUtils;
 
/**
 * {@link PacketReader} dedicated to {@link HttpPacket} response to 
 * Http request send to the OpenWeatherMap service
 */
public class WeatherPacketReader extends SimplePacketReader<HttpPacket>
{
	/**
	 * @param mediator
	 */
	protected WeatherPacketReader(Mediator mediator)
	{
		super(mediator);
	}
 
	/**
	 * @inheritDoc
	 *
	 * @see org.eclipse.sensinact.gateway.generic.core.packet.PacketReader#parse(org.eclipse.sensinact.gateway.generic.core.packet.Packet)
	 */
	public void parse(HttpPacket packet) throws InvalidPacketException
	{
      JSONObject object = new JSONObject(new String(packet.getBytes()));
 
      long timestamp = object.optLong("dt")*1000L;
		JSONObject coord = object.optJSONObject("coord");
		if(coord != null)
		{
			super.setServiceProviderId("station");
			super.setServiceId(ServiceProvider.ADMINISTRATION_SERVICE_NAME);
			super.setResourceId(LocationResource.LOCATION);
			super.setData(new StringBuilder().append(coord.optDouble("lat")).append(JSONUtils.COLON
					).append(coord.optDouble("lon")).toString());
			super.setCommand(CommandType.GET);
			super.configure();
		}
		JSONArray weather = object.optJSONArray("weather");
		JSONObject content = null;
		if(weather != null && (content = weather.optJSONObject(0))!=null)
		{
			super.setServiceProviderId("station");
			super.setServiceId("weather");
			super.setResourceId("state");
			super.setData(content.opt("main"));
			super.setTimestamp(timestamp);
			super.setCommand(CommandType.GET);
			super.configure();
 
			super.setServiceProviderId("station");
			super.setServiceId("weather");
			super.setResourceId("description");
			super.setData(content.opt("description"));
			super.setTimestamp(timestamp);
			super.setCommand(CommandType.GET);
			super.configure();
		}
		JSONObject wind = object.optJSONObject("wind");
		if(wind != null)
		{
			super.setServiceProviderId("station");
			super.setServiceId("weather");
			super.setResourceId("wind");
			super.setData(wind.opt("speed"));
			super.setTimestamp(timestamp);
			super.setCommand(CommandType.GET);
			super.configure();
 
			super.setServiceProviderId("station");
			super.setServiceId("weather");
			super.setResourceId("orientation");
			super.setData(wind.opt("deg"));
			super.setTimestamp(timestamp);
			super.setCommand(CommandType.GET);
			super.configure();
		}
		JSONObject main = object.optJSONObject("main");
		if(main != null)
		{
			super.setServiceProviderId("station");
			super.setServiceId("weather");
			super.setResourceId("temperature");
			super.setData(main.opt("temp"));
			super.setTimestamp(timestamp);
			super.setCommand(CommandType.GET);
			super.configure();
 
			super.setServiceProviderId("station");
			super.setServiceId("weather");
			super.setResourceId("humidity");
			super.setData(main.opt("humidity"));
			super.setTimestamp(timestamp);
			super.setCommand(CommandType.GET);
			super.configure();
 
			super.setServiceProviderId("station");
			super.setServiceId("weather");
			super.setResourceId("pressure");
			super.setData(main.opt("pressure"));
			super.setTimestamp(timestamp);
			super.setCommand(CommandType.GET);
			super.configure();
		}
	}
}

We are now able to understand the response coming from the OpenWeatherMap service, but we still have to send the appropriate requests; for this purpose we will use the sensiNact Http bridge, which provides a set of tools helping to create them.

Our Bundle Activator becomes an HttpActivator; allowing us to configure an annotated SimpleHttpTaskConfigurationAdapter, used to automatically generate the appropriate requests. The ExtProtocolStackEndpoint becomes a SimpleHttpProtocolStackEndpoint, and the ExtXmlModelConfiguration becomes an HttpModelConfiguration.

The SimpleHttpTask' annotation allows to configure every parameter of an Http request to create, including an SimpleHttpTaskContentConfiguration class in charge of building the Http requests content.


package org.eclipse.sensinact.gateway.simulated.osgi;
 
import java.util.Collections;
 
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.eclipse.sensinact.gateway.common.bundle.Mediator;
import org.eclipse.sensinact.gateway.generic.core.Task.CommandType;
import org.eclipse.sensinact.gateway.generic.core.XmlModelInstance;
import org.eclipse.sensinact.gateway.generic.core.XmlModelInstanceBuilder;
import org.eclipse.sensinact.gateway.sthbnd.http.HttpModelConfiguration;
import org.eclipse.sensinact.gateway.sthbnd.http.HttpPacket;
import org.eclipse.sensinact.gateway.sthbnd.http.impl.HttpActivator;
import org.eclipse.sensinact.gateway.sthbnd.http.impl.SimpleHttpProtocolStackEndpoint;
import org.eclipse.sensinact.gateway.sthbnd.http.impl.SimpleHttpTask;
import org.eclipse.sensinact.gateway.sthbnd.http.impl.SimpleHttpTaskQuery;
import org.eclipse.sensinact.gateway.sthbnd.http.impl.SimpleHttpTaskConfigurationAdapter;
 
/**
 * Bundle Activator
 */
public class Activator extends HttpActivator<Mediator>
{		
	private SimpleHttpProtocolStackEndpoint connector;
	private HttpModelConfiguration manager;
 
	@SimpleHttpTask(command = CommandType.GET, 
	host = "api.openweathermap.org", 
	path = "data/2.5/weather",
	query = 
	{	@SimpleHttpTaskQuery(key = "lat", value = "<latitude>"),
		@SimpleHttpTaskQuery(key = "lon", value = "<longitude>"),
		@SimpleHttpTaskQuery(key = "APPID", value = "<your-key>")
	})
	private SimpleHttpTaskConfigurationAdapter adapter;
 
 
    /**
	 * @inheritDoc
	 *
	 * @see org.eclipse.sensinact.gateway.common.bundle.AbstractActivator#doStart()
	 */
	@Override
	public void doStart() throws Exception
	{    		     
	   adapter = new SimpleHttpTaskConfigurationAdapter();
	   manager = new XmlModelInstanceBuilder<HttpModelConfiguration,
        	XmlModelInstance>(super.mediator,XmlModelInstance.class,
        	HttpModelConfiguration.class
        		).withPacketType(HttpPacket.class
                ).withStartAtInitializationTime(true
                ).buildConfiguration("resource.xml", Collections.<String,String>emptyMap());             
 
       super.configureAdapter(); 
 
	   connector = new SimpleHttpProtocolStackEndpoint(super.mediator, adapter);
	   connector.connect(manager);
	}
 
	/**
	 * @inheritDoc
	 *
	 * @see org.eclipse.sensinact.gateway.common.bundle.AbstractActivator#
	 * doStop()
	 */
	@Override
	public void doStop() throws Exception
	{
		   connector.stop();
	}
 
	/**
	 * @inheritDoc
	 *
	 * @see org.eclipse.sensinact.gateway.common.bundle.AbstractActivator#
	 * doInstantiate(org.osgi.framework.BundleContext, int, java.io.FileOutputStream)
	 */
	@Override
	public Mediator doInstantiate(BundleContext context) 
			throws InvalidSyntaxException
	{
		return new Mediator(context);
	}	
}

After the adaptation of the WeatherPacketReaderFactory to be able to handle HttpPacket type, the WeatherPacket and WeatherStation classes can be deleted.


package org.eclipse.sensinact.gateway.simulated.weather;
 
import org.eclipse.sensinact.gateway.common.bundle.Mediator;
import org.eclipse.sensinact.gateway.generic.core.InvalidPacketException;
import org.eclipse.sensinact.gateway.generic.core.XmlModelConfiguration;
import org.eclipse.sensinact.gateway.generic.core.impl.PacketReaderFactory;
import org.eclipse.sensinact.gateway.generic.core.packet.Packet;
import org.eclipse.sensinact.gateway.generic.core.packet.PacketReader;
import org.eclipse.sensinact.gateway.sthbnd.http.HttpPacket;
 
public class WeatherPacketReaderFactory implements PacketReaderFactory<HttpPacket>
{
	/**
	 * @inheritDoc
	 *
	 * @see org.eclipse.sensinact.gateway.generic.core.impl.PacketReaderFactory#
	 * handle(java.lang.Class)
	 */
	public boolean handle(Class<? extends Packet> packetType)
	{
	    return HttpPacket.class.isAssignableFrom(packetType);
	}
 
	/**
	 * @inheritDoc
	 *
	 * @see org.eclipse.sensinact.gateway.generic.core.impl.PacketReaderFactory#
	 * newInstance(org.eclipse.sensinact.gateway.common.bundle.Mediator, 
	 * org.eclipse.sensinact.gateway.generic.core.XmlModelConfiguration, 
	 * org.eclipse.sensinact.gateway.generic.core.packet.Packet)
	 */
	public PacketReader<HttpPacket> newInstance(Mediator mediator,
	        XmlModelConfiguration<HttpPacket> manager, 
	        HttpPacket packet)
	        throws InvalidPacketException
	{
   	 	WeatherPacketReader packetReader = new WeatherPacketReader(mediator);
   	 	packetReader.parse(packet);
   	 	return packetReader;
	}
}

Back to the top