SlideShare ist ein Scribd-Unternehmen logo
1 von 76
Building a Sensor
       Network Controller
                                               Michael Pigg
                                             Chariot Solutions
                                                    November 5, 2010




This work is licensed under the Creative Commons Attribution-
Noncommercial-Share Alike 3.0 United States License.
Chariot Solutions

Practical, smart software development
powered by Java, open source and
emerging technologies
Agenda

• What are we building?
• Why use OSGi?
• Look at interesting code features
• Run the system
An engineer* walks
                 into a room ...


*Software guy with old, dusty electrical technology degree, really
and notices it’s too
      cold.
He walks into another
 and notices it’s too
       warm.
Hire someone to fix it?
No Way!
Build a system to
monitor temperature in
   multiple rooms.
What should it do?
Requirements




     Collect temperature
      data from multiple
           locations
Requirements




    Record data for later
          analysis
Requirements




               No wires
Requirements




          Easily add new
            capabilities
Proposed Solution

• Hardware
 • Custom wireless sensor module
• Software
 • Controller software based on Apache
    Felix
Why OSGi and Felix?
• Highly modular architecture
 • Capable of being updated at runtime
• Already implemented solutions
 • console shell commands
 • configuration implementation
 • web-based configuration UI
Hardware
Sensor Module

• Digi XBee wireless mesh network module
• Has integrated ADC
• Operates in voltage range of 2 AA batteries
• Relatively low power consumption
Wireless
                       Module     Vref
  Temp
 Sensor
(under board)                     Text


Super Soldering Job*



                                   Professional Wiring*




*Not so much
Life of a Node

• Sleep for 5 minutes, then wake up
• Sample ADC port
• Send sample data over network
• Go back to sleep
XBee   XBee
                     XBee




XBee
        XBee   USB
Software
XBee Communication
Connect XBee to PC


•   XBee to USB

•   Appears as serial port
XBee has custom
   protocol
XBeeLib

• Implementation of XBee API protocol
 • Open source, BSD license
 • http://kenai.com/projects/xbeelib
Apache Mina

• Eases implementation of custom protocol
  encoder/decoder
 • Support for fragmented packets
• Comes with serial port transport
XBeeService

                  XbeeLib
                                            xb

                             Mina            xbr
                             Serial
                                            xbconfig
XBee        USB              RXTX



       ManagedServiceFactory
                             metatype.xml

       Config                                     Mina
       Admin                   Metatype          Core
                               Service

         Indirect
         Exported Packages
RXTX requires native
      library
Where to put native
     library?
How to get native
 library installed?
Bundle-NativeCode

• Parameters
 • path to native code in bundle JAR
 • osname (MacOS, Linux, etc.)
 • processor (x86, PowerPC, etc.)
 • osversion
<plugin>
   <groupId>org.apache.felix</groupId>
   <artifactId>maven-bundle-plugin</artifactId>
   <version>2.0.1</version>
   <extensions>true</extensions>
   <configuration>
      <instructions>
         <Import-Package>*</Import-Package>
         <Export-Package>net.michaelpigg.xbeelib.protocol,net.michaelpigg.xbeelib</Export-Package>
         <Embed-Dependency>rxtx,mina-transport-serial</Embed-Dependency>


     <Bundle-NativeCode>lib/rxtx/mac/x86_64/
librxtxSerial.jnilib; osname=MacOSX; processor=x86_64</Bundle-
NativeCode>
          <Bundle-Activator>net.michaelpigg.xbeelib.impl.BundleActivator</Bundle-Activator>
       </instructions>
   </configuration>
</plugin>
XBeeLib dependencies
• Mina and most other dependencies are
  deployed as bundles
• Mina serial transport and RXTX are
  embedded into XBeeLib bundle
 • RXTX is not OSGi-ready
 • Mina serial depends on RXTX
<plugin>
   <groupId>org.apache.felix</groupId>
   <artifactId>maven-bundle-plugin</artifactId>
   <version>2.0.1</version>
   <extensions>true</extensions>
   <configuration>
      <instructions>
         <Import-Package>*</Import-Package>
         <Export-Package>net.michaelpigg.xbeelib.protocol,net.michaelpigg.xbeelib</Export-Package>


         <Embed-Dependency>rxtx,mina-transport-serial</Embed-
         Dependency>
          <Bundle-NativeCode>lib/rxtx/mac/x86_64/librxtxSerial.jnilib; osname=MacOSX; processor=x86_64</Bundle-
          NativeCode>
          <Bundle-Activator>net.michaelpigg.xbeelib.impl.BundleActivator</Bundle-Activator>
       </instructions>
   </configuration>
</plugin>
First Contact

• XBeeLib provides simple shell commands
  for sending commands to XBee modules
 • xb - send command to local XBee
 • xbr - send command to remote XBee
Shell Commands

• Felix provides the Gogo shell as of 3.0
• Bundles contribute commands by
  registering a service with two properties
  • osgi.command.scope
  • osgi.command.function
public void start(BundleContext context) throws Exception {
  Hashtable cmdProps = new Hashtable();

    // these commands are in scope “xbee”
    cmdProps.put(CommandProcessor.COMMAND_SCOPE, “xbee”);

    // “xb” and “xbr” are functions that can act as commands
    cmdProps.put(CommandProcessor.COMMAND_FUNCTION,
      new String[] {“xb”, “xbr”});

    context.registerService(
        ToXbeeCommand.class.getName(),
        new ToXbeeCommand(context),
        cmdProps);
}
Listing Shell Commands
      g! help
      felix:bundlelevel
         .....
      felix:which
      gogo:cat
         ....
      gogo:until
      obr:deploy
         ....
      obr:source
      xbee:listports
      xbee:xb
      xbee:xbconfig
      xbee:xbr
      xbee:xmon
      xbee:xsample
      g!
Using Commands
             Send node discover command
g! xb nd
ND response: Frame ID = 109;Status = OK;Address =
0013a200403c5e93;Signal strength = 32;

g! x1 = "0013a200403c5e93"
0013a200403c5e93

g! xbr $x1 is
                     Request sample
IS response: Frame ID = 11;Status = OK;Data: 010200013c

g!
Transform Data
Incoming Data


• Number resulting from ADC sample on
  XBee
XbeeAnalogData
Transformer Interface

• Implementations convert raw ADC reading
  to useful data
• TemperatureSensorTransformer does this
  for our temperature sensor hardware
xbee-temp-sensor
     bundle
                             xbee-
                           listener

               XbeeAnalogDataTransfomer


                           temp-
                           sensor

            metatype.xml     ManagedServiceFactory


                                             Config
 Metatype
                                             Admin
Sample with no
  Transformer
g! xsample $x1
Command returned with status OK
Raw data in response:1200dd
Number of samples 1
Digital I/O
     No digital I/O data in response.
Analog Data
     1: DD(221)
g!
Configuring
Temperature Sensors
Config file?
NO!
Configuration Admin
      Service
• Stores configuration for a service
• Sends configuration to service
 • at startup
 • when configuration changes
ManagedService or
ManagedServiceFactory?
• ManagedService
 • Configures at most one instance
• ManagedServiceFactory
 • Configures one or more instances
We need to configure
 multiple sensors
Implementation

• Make up a PID
• Implement ManagedServiceFactory
• Register implementation as a service with
  the chosen PID
public class XbeeTemperatureSensorFactory implements ManagedServiceFactory {

    public void updated(String pid, Dictionary properties) throws ConfigurationException {
      // get configuration properties and copy to registration properties
      String address = properties.get(LOCATION_ADDRESS);
      String name = properties.get(LOCATION_NAME);
      Dictionary<String, String> registrationProperties = new Hashtable<String, String>();
      registrationProperties.put( LOCATION_NAME, name);
      registrationProperties.put( LOCATION_ADDRESS, address);

        // create new transformer
        TemperatureSensorTransformer transformer = new TemperatureSensorTransformer();

        // register newly configured transformer
        ServiceRegistration registration = bundleContext.registerService(
                          XbeeAnalogDataTransformer.class.getName(),
                          transformer,
                          registrationProperties);
    }
}
public class BundleActivator implements BundleActivator {
  // factory PID - will be used as base PID for configured instances
  public static String PID = "com.pigglogic.phomenet.xbee.sensor.temperature";

  public void start(BundleContext context) throws Exception {
    // create ManagedServiceFactory instance
    sensorFactory = new XbeeTemperatureSensorFactory(context);
    Dictionary properties = new Hashtable<String, String>();
    // set SERVICE_PID property to our factory PID
    properties.put(Constants.SERVICE_PID, PID);
    // register factory instance
    factoryRegistration = context.registerService(
           ManagedServiceFactory.class.getName(),
           sensorFactory,
           properties);
  }
What is allowed in
  configuration?

• What are the attribute names?
• What type of data do they take?
• Are they required?
Metatype Specification

• Specify attributes used in configuration
 • name, type, required, default value, etc.
• XML file in OSGI-INF/metatype
• Felix web console will use this data to
  dynamically create a configuration UI
<metatype:MetaData xmlns:metatype="http://www.osgi.org/xmlns/metatype/v1.0.0">

  <OCD description="xbee-temperature-sensor"
    name="com.pigglogic.phomenet.xbee.sensor.temperature"
    id="com.pigglogic.phomenet.xbee.sensor.temperature">

  <AD name="Location Name" id="location.name" required="true" type="String"
      default="Temperature Sensor"/>
  <AD name="Location Address" id="location.address" required="true" type="String"/>
  <AD name="Correction" id="location.correction" required="false" type="Double" default="0.0"/>

 </OCD>

  <Designate pid="com.pigglogic.phomenet.xbee.sensor.temperature"
      factoryPid="com.pigglogic.phomenet.xbee.sensor.temperature">
    <Object ocdref="com.pigglogic.phomenet.xbee.sensor.temperature"/>
  </Designate>

</metatype:MetaData>
Configure Sensor
Sample with Transfomer
   g! xsample $x1
   Command returned with status OK
   Raw data in response:12013e
   Number of samples 1
   Digital I/O
        No digital I/O data in response.
   Analog Data
        1: 13E(318)
   Transformer reports value of -11.609971
Collecting and
Recording Data
xbee-listener bundle
                          temp-
                          sensor
   recorder
                  XbeeAnalogDataTransfomer       XbeeLib


  Observation Recorder
                                             XBeeService
                            xbee-
                          listener

                         Event Admin



                          Event
                          Admin
Piping Hot Data
• xbee-listener gets data from XBeeService,
  but what to do with it?
• Needs to find a transformer that will
  handle the data
• There should be a number of transformers
  registered
• Chooses based on source address
Recording data


• xbee-listener records transformed data
 • Finds an instance of
    ObservationRecorder service
Default Storage
    Observation Recorder




          phomenet
           service




                           Config
  Derby
                           Admin
NoSql?

• What if we wanted to be cool and store
  data in Cassandra?
• We could provide a different bundle that
  implements ObservationRecorder
 • but uses Cassandra instead of Derby
Visualizing Sensor Data
Show me a GUI!


• Web page GUI
• Show latest observation for each sensor
phomenet-web
            phomenet-
               web


       Servlet   Event Handler



Felix Web                 Event
 Console                  Admin
Observation Events

• xbee-listener posts an OSGi event when
  data is transformed
• Event topic is “phomenet/Observation/
  Temperature/<address>”
OSGi Event Admin


• Bundles can post events
• Bundles can register to be notified of
  posted events
Posting an Event
// build Map containing event data
Map<String, Object> eventProperties = new HashMap<String, Object>();
eventProperties.put("location.name", locationName);
final String addressString = frame.getSourceAddress().toString();
eventProperties.put("location.address", addressString);
eventProperties.put("observedValue", value);

// create Event with topic and properties
final Event event = new Event(
     "phomenet/Observation/Temperature/" + addressString,
     eventProperties);

// call postEvent with event
eventAdmin.postEvent(event);
Listening to Events
public void start(BundleContext context) throws Exception {

    Hashtable<String, Object> props = new Hashtable<String, Object>();

    // Felix web console extension properties
    props.put("felix.webconsole.label", "phomenet");
    props.put("felix.webconsole.title", "pHomeNet Console");

    // property to say that we want all Observation events
    props.put(EventConstants.EVENT_TOPIC, "phomenet/Observation/*");
    // register under Servlet and EventHandler interfaces
    webConsoleRegistration = context.registerService(
       new String[] {Servlet.class.getName(), EventHandler.class.getName()},
       new PhomenetConsolePlugin(context), props);
}
Extending Web
          Console
• Register a class that extends HTTPServlet
• Add properties
 • felix.webconsole.label - used in URL
 • felix.webconsole.title - title of page
Registering Extension
public void start(BundleContext context) throws Exception {

    Hashtable<String, Object> props = new Hashtable<String, Object>();

    // Felix web console extension properties
    props.put("felix.webconsole.label", "phomenet");
    props.put("felix.webconsole.title", "pHomeNet Console");

    // property to say that we want all Observation events
    props.put(EventConstants.EVENT_TOPIC, "phomenet/Observation/*");
    // register under Servlet and EventHandler interfaces
    webConsoleRegistration = context.registerService(
          new String[] {Servlet.class.getName(), EventHandler.class.getName()},
          new PhomenetConsolePlugin(context), props);
}
Resources


• XBeeLib - kenai.com/projects/xbeelib
• pHomeNet - kenai.com/projects/phomenet
Resources
•   XBee 802.15.4 OEM module

    •   http://www.digi.com/products/wireless/point-multipoint/xbee-series1-
        module.jsp#overview

•   Droids XBee USB board

    •   http://www.droids.it/990_002.html

•   MCP9700 Temperature Sensor

    •   http://www.microchip.com/wwwproducts/Devices.aspx?
        dDocName=en022289

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (6)

Breaking New Frontiers in Robotics and Edge Computing with AI
Breaking New Frontiers in Robotics and Edge Computing with AIBreaking New Frontiers in Robotics and Edge Computing with AI
Breaking New Frontiers in Robotics and Edge Computing with AI
 
Nio100 demo box
Nio100 demo boxNio100 demo box
Nio100 demo box
 
Hypertracing: Tracing Through Virtualization Layers
Hypertracing: Tracing Through Virtualization LayersHypertracing: Tracing Through Virtualization Layers
Hypertracing: Tracing Through Virtualization Layers
 
Radore Veri Merkezi Topolojisi
Radore Veri Merkezi TopolojisiRadore Veri Merkezi Topolojisi
Radore Veri Merkezi Topolojisi
 
Kubernetes-DX-5G-session
Kubernetes-DX-5G-sessionKubernetes-DX-5G-session
Kubernetes-DX-5G-session
 
Terraforming
Terraforming Terraforming
Terraforming
 

Andere mochten auch

Solving the Wanamaker Problem for Healthcare (keynote file)
Solving the Wanamaker Problem for Healthcare (keynote file)Solving the Wanamaker Problem for Healthcare (keynote file)
Solving the Wanamaker Problem for Healthcare (keynote file)Tim O'Reilly
 
Hardware innovation (keynote file)
Hardware innovation (keynote file)Hardware innovation (keynote file)
Hardware innovation (keynote file)Tim O'Reilly
 
Code curiosity rubyconfindia 2016 talk
Code curiosity rubyconfindia 2016 talkCode curiosity rubyconfindia 2016 talk
Code curiosity rubyconfindia 2016 talkSethupathi Asokan
 
Panorama de l'utilisation des médias sociaux dans les collectivités locales
Panorama de l'utilisation des médias sociaux dans les collectivités localesPanorama de l'utilisation des médias sociaux dans les collectivités locales
Panorama de l'utilisation des médias sociaux dans les collectivités localesEmilie Marquois
 
Introduction to Slideshare at Barcamp Hyderabad
Introduction to Slideshare at Barcamp HyderabadIntroduction to Slideshare at Barcamp Hyderabad
Introduction to Slideshare at Barcamp HyderabadKapil Mohan
 
Pinterest for Business 101
Pinterest for Business 101Pinterest for Business 101
Pinterest for Business 101Nick Armstrong
 
A New Business World Within A Blockchain
A New Business World Within A BlockchainA New Business World Within A Blockchain
A New Business World Within A BlockchainAlex Chepurnoy
 
The Future in One Picture
The Future in One PictureThe Future in One Picture
The Future in One PictureTim O'Reilly
 
Traffic Signal Movie Preview
Traffic Signal Movie PreviewTraffic Signal Movie Preview
Traffic Signal Movie PreviewKapil Mohan
 
What to Do Once You Have an Idea (case study)
What to Do Once You Have an Idea (case study)What to Do Once You Have an Idea (case study)
What to Do Once You Have an Idea (case study)Sergey Sundukovskiy
 
Insight from CloverPoint - 3D Asset and Facilities Management
Insight from CloverPoint - 3D Asset and Facilities ManagementInsight from CloverPoint - 3D Asset and Facilities Management
Insight from CloverPoint - 3D Asset and Facilities ManagementCloverpoint
 
Giving Organisations new Capabilities to ask the Right Business Questions
Giving Organisations new Capabilities to ask the Right Business QuestionsGiving Organisations new Capabilities to ask the Right Business Questions
Giving Organisations new Capabilities to ask the Right Business QuestionsOReillyStrata
 
25 Words Of Social Media Wisdom Project
25 Words Of Social Media Wisdom Project25 Words Of Social Media Wisdom Project
25 Words Of Social Media Wisdom ProjectLiz Strauss
 
Localized methods for diffusions in large graphs
Localized methods for diffusions in large graphsLocalized methods for diffusions in large graphs
Localized methods for diffusions in large graphsDavid Gleich
 
Zero Waste à Gipuzkoa (Pays basque espagnol)
Zero Waste à Gipuzkoa (Pays basque espagnol)Zero Waste à Gipuzkoa (Pays basque espagnol)
Zero Waste à Gipuzkoa (Pays basque espagnol)Zero Waste France, Cniid
 
Kotter Eight Step Plan
Kotter Eight Step PlanKotter Eight Step Plan
Kotter Eight Step PlanCPA Australia
 

Andere mochten auch (20)

Government 2.0
Government 2.0Government 2.0
Government 2.0
 
Solving the Wanamaker Problem for Healthcare (keynote file)
Solving the Wanamaker Problem for Healthcare (keynote file)Solving the Wanamaker Problem for Healthcare (keynote file)
Solving the Wanamaker Problem for Healthcare (keynote file)
 
Hardware innovation (keynote file)
Hardware innovation (keynote file)Hardware innovation (keynote file)
Hardware innovation (keynote file)
 
Code curiosity rubyconfindia 2016 talk
Code curiosity rubyconfindia 2016 talkCode curiosity rubyconfindia 2016 talk
Code curiosity rubyconfindia 2016 talk
 
Panorama de l'utilisation des médias sociaux dans les collectivités locales
Panorama de l'utilisation des médias sociaux dans les collectivités localesPanorama de l'utilisation des médias sociaux dans les collectivités locales
Panorama de l'utilisation des médias sociaux dans les collectivités locales
 
Introduction to Slideshare at Barcamp Hyderabad
Introduction to Slideshare at Barcamp HyderabadIntroduction to Slideshare at Barcamp Hyderabad
Introduction to Slideshare at Barcamp Hyderabad
 
Web 20
Web 20Web 20
Web 20
 
Pinterest for Business 101
Pinterest for Business 101Pinterest for Business 101
Pinterest for Business 101
 
A New Business World Within A Blockchain
A New Business World Within A BlockchainA New Business World Within A Blockchain
A New Business World Within A Blockchain
 
The Future in One Picture
The Future in One PictureThe Future in One Picture
The Future in One Picture
 
Stanford Ee380
Stanford Ee380Stanford Ee380
Stanford Ee380
 
Traffic Signal Movie Preview
Traffic Signal Movie PreviewTraffic Signal Movie Preview
Traffic Signal Movie Preview
 
What to Do Once You Have an Idea (case study)
What to Do Once You Have an Idea (case study)What to Do Once You Have an Idea (case study)
What to Do Once You Have an Idea (case study)
 
Insight from CloverPoint - 3D Asset and Facilities Management
Insight from CloverPoint - 3D Asset and Facilities ManagementInsight from CloverPoint - 3D Asset and Facilities Management
Insight from CloverPoint - 3D Asset and Facilities Management
 
Giving Organisations new Capabilities to ask the Right Business Questions
Giving Organisations new Capabilities to ask the Right Business QuestionsGiving Organisations new Capabilities to ask the Right Business Questions
Giving Organisations new Capabilities to ask the Right Business Questions
 
25 Words Of Social Media Wisdom Project
25 Words Of Social Media Wisdom Project25 Words Of Social Media Wisdom Project
25 Words Of Social Media Wisdom Project
 
Localized methods for diffusions in large graphs
Localized methods for diffusions in large graphsLocalized methods for diffusions in large graphs
Localized methods for diffusions in large graphs
 
Zero Waste à Gipuzkoa (Pays basque espagnol)
Zero Waste à Gipuzkoa (Pays basque espagnol)Zero Waste à Gipuzkoa (Pays basque espagnol)
Zero Waste à Gipuzkoa (Pays basque espagnol)
 
ISIS Captures Ramadi - May 2015
ISIS Captures Ramadi  - May 2015ISIS Captures Ramadi  - May 2015
ISIS Captures Ramadi - May 2015
 
Kotter Eight Step Plan
Kotter Eight Step PlanKotter Eight Step Plan
Kotter Eight Step Plan
 

Ähnlich wie Building A Sensor Network Controller

Building a Wireless Mesh Network Temperature Sensor
Building a Wireless Mesh Network Temperature SensorBuilding a Wireless Mesh Network Temperature Sensor
Building a Wireless Mesh Network Temperature Sensormichaelpigg
 
TechWiseTV Workshop: Catalyst Switching Programmability
TechWiseTV Workshop: Catalyst Switching ProgrammabilityTechWiseTV Workshop: Catalyst Switching Programmability
TechWiseTV Workshop: Catalyst Switching ProgrammabilityRobb Boyd
 
Exploring the Final Frontier of Data Center Orchestration: Network Elements -...
Exploring the Final Frontier of Data Center Orchestration: Network Elements -...Exploring the Final Frontier of Data Center Orchestration: Network Elements -...
Exploring the Final Frontier of Data Center Orchestration: Network Elements -...Puppet
 
Is OSGi modularity always worth it?
Is OSGi modularity always worth it?Is OSGi modularity always worth it?
Is OSGi modularity always worth it?glynnormington
 
Building Hopsworks, a cloud-native managed feature store for machine learning
Building Hopsworks, a cloud-native managed feature store for machine learning Building Hopsworks, a cloud-native managed feature store for machine learning
Building Hopsworks, a cloud-native managed feature store for machine learning Jim Dowling
 
Distributed & Highly Available server applications in Java and Scala
Distributed & Highly Available server applications in Java and ScalaDistributed & Highly Available server applications in Java and Scala
Distributed & Highly Available server applications in Java and ScalaMax Alexejev
 
Cloud Platform Symantec Meetup Nov 2014
Cloud Platform Symantec Meetup Nov 2014Cloud Platform Symantec Meetup Nov 2014
Cloud Platform Symantec Meetup Nov 2014Miguel Zuniga
 
Automation in Network Lifecycle Management - Bay Area Juniper Meetup
Automation in Network Lifecycle Management - Bay Area Juniper MeetupAutomation in Network Lifecycle Management - Bay Area Juniper Meetup
Automation in Network Lifecycle Management - Bay Area Juniper MeetupJorge Bonilla
 
Go Faster with Ansible (PHP meetup)
Go Faster with Ansible (PHP meetup)Go Faster with Ansible (PHP meetup)
Go Faster with Ansible (PHP meetup)Richard Donkin
 
Eclipse Kura Shoot a-pi
Eclipse Kura Shoot a-piEclipse Kura Shoot a-pi
Eclipse Kura Shoot a-piEclipse Kura
 
Vladimir Ulogov - Beyond the Loadable Module
Vladimir Ulogov - Beyond the Loadable ModuleVladimir Ulogov - Beyond the Loadable Module
Vladimir Ulogov - Beyond the Loadable ModuleZabbix
 
Beyond the Loadable Module
Beyond the Loadable ModuleBeyond the Loadable Module
Beyond the Loadable ModuleVladimir Ulogov
 
Architecting for Microservices Part 2
Architecting for Microservices Part 2Architecting for Microservices Part 2
Architecting for Microservices Part 2Elana Krasner
 
Developing Realtime Data Pipelines With Apache Kafka
Developing Realtime Data Pipelines With Apache KafkaDeveloping Realtime Data Pipelines With Apache Kafka
Developing Realtime Data Pipelines With Apache KafkaJoe Stein
 
AFW: Dynamic Firewalls with Chef and Netfilter
AFW: Dynamic Firewalls with Chef and NetfilterAFW: Dynamic Firewalls with Chef and Netfilter
AFW: Dynamic Firewalls with Chef and Netfilterjvehent
 
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at NetflixOSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at NetflixManish Pandit
 
Managing Large-scale Networks with Trigger
Managing Large-scale Networks with TriggerManaging Large-scale Networks with Trigger
Managing Large-scale Networks with Triggerjathanism
 

Ähnlich wie Building A Sensor Network Controller (20)

Building a Wireless Mesh Network Temperature Sensor
Building a Wireless Mesh Network Temperature SensorBuilding a Wireless Mesh Network Temperature Sensor
Building a Wireless Mesh Network Temperature Sensor
 
RISC V in Spacer
RISC V in SpacerRISC V in Spacer
RISC V in Spacer
 
TechWiseTV Workshop: Catalyst Switching Programmability
TechWiseTV Workshop: Catalyst Switching ProgrammabilityTechWiseTV Workshop: Catalyst Switching Programmability
TechWiseTV Workshop: Catalyst Switching Programmability
 
Exploring the Final Frontier of Data Center Orchestration: Network Elements -...
Exploring the Final Frontier of Data Center Orchestration: Network Elements -...Exploring the Final Frontier of Data Center Orchestration: Network Elements -...
Exploring the Final Frontier of Data Center Orchestration: Network Elements -...
 
Is OSGi modularity always worth it?
Is OSGi modularity always worth it?Is OSGi modularity always worth it?
Is OSGi modularity always worth it?
 
Mina2
Mina2Mina2
Mina2
 
Building Hopsworks, a cloud-native managed feature store for machine learning
Building Hopsworks, a cloud-native managed feature store for machine learning Building Hopsworks, a cloud-native managed feature store for machine learning
Building Hopsworks, a cloud-native managed feature store for machine learning
 
Docker meetup
Docker meetupDocker meetup
Docker meetup
 
Distributed & Highly Available server applications in Java and Scala
Distributed & Highly Available server applications in Java and ScalaDistributed & Highly Available server applications in Java and Scala
Distributed & Highly Available server applications in Java and Scala
 
Cloud Platform Symantec Meetup Nov 2014
Cloud Platform Symantec Meetup Nov 2014Cloud Platform Symantec Meetup Nov 2014
Cloud Platform Symantec Meetup Nov 2014
 
Automation in Network Lifecycle Management - Bay Area Juniper Meetup
Automation in Network Lifecycle Management - Bay Area Juniper MeetupAutomation in Network Lifecycle Management - Bay Area Juniper Meetup
Automation in Network Lifecycle Management - Bay Area Juniper Meetup
 
Go Faster with Ansible (PHP meetup)
Go Faster with Ansible (PHP meetup)Go Faster with Ansible (PHP meetup)
Go Faster with Ansible (PHP meetup)
 
Eclipse Kura Shoot a-pi
Eclipse Kura Shoot a-piEclipse Kura Shoot a-pi
Eclipse Kura Shoot a-pi
 
Vladimir Ulogov - Beyond the Loadable Module
Vladimir Ulogov - Beyond the Loadable ModuleVladimir Ulogov - Beyond the Loadable Module
Vladimir Ulogov - Beyond the Loadable Module
 
Beyond the Loadable Module
Beyond the Loadable ModuleBeyond the Loadable Module
Beyond the Loadable Module
 
Architecting for Microservices Part 2
Architecting for Microservices Part 2Architecting for Microservices Part 2
Architecting for Microservices Part 2
 
Developing Realtime Data Pipelines With Apache Kafka
Developing Realtime Data Pipelines With Apache KafkaDeveloping Realtime Data Pipelines With Apache Kafka
Developing Realtime Data Pipelines With Apache Kafka
 
AFW: Dynamic Firewalls with Chef and Netfilter
AFW: Dynamic Firewalls with Chef and NetfilterAFW: Dynamic Firewalls with Chef and Netfilter
AFW: Dynamic Firewalls with Chef and Netfilter
 
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at NetflixOSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
 
Managing Large-scale Networks with Trigger
Managing Large-scale Networks with TriggerManaging Large-scale Networks with Trigger
Managing Large-scale Networks with Trigger
 

Building A Sensor Network Controller

  • 1. Building a Sensor Network Controller Michael Pigg Chariot Solutions November 5, 2010 This work is licensed under the Creative Commons Attribution- Noncommercial-Share Alike 3.0 United States License.
  • 2. Chariot Solutions Practical, smart software development powered by Java, open source and emerging technologies
  • 3. Agenda • What are we building? • Why use OSGi? • Look at interesting code features • Run the system
  • 4. An engineer* walks into a room ... *Software guy with old, dusty electrical technology degree, really
  • 5. and notices it’s too cold.
  • 6. He walks into another and notices it’s too warm.
  • 7. Hire someone to fix it?
  • 9. Build a system to monitor temperature in multiple rooms.
  • 11. Requirements Collect temperature data from multiple locations
  • 12. Requirements Record data for later analysis
  • 13. Requirements No wires
  • 14. Requirements Easily add new capabilities
  • 15. Proposed Solution • Hardware • Custom wireless sensor module • Software • Controller software based on Apache Felix
  • 16. Why OSGi and Felix? • Highly modular architecture • Capable of being updated at runtime • Already implemented solutions • console shell commands • configuration implementation • web-based configuration UI
  • 18. Sensor Module • Digi XBee wireless mesh network module • Has integrated ADC • Operates in voltage range of 2 AA batteries • Relatively low power consumption
  • 19. Wireless Module Vref Temp Sensor (under board) Text Super Soldering Job* Professional Wiring* *Not so much
  • 20. Life of a Node • Sleep for 5 minutes, then wake up • Sample ADC port • Send sample data over network • Go back to sleep
  • 21. XBee XBee XBee XBee XBee USB
  • 24. Connect XBee to PC • XBee to USB • Appears as serial port
  • 25. XBee has custom protocol
  • 26. XBeeLib • Implementation of XBee API protocol • Open source, BSD license • http://kenai.com/projects/xbeelib
  • 27. Apache Mina • Eases implementation of custom protocol encoder/decoder • Support for fragmented packets • Comes with serial port transport
  • 28. XBeeService XbeeLib xb Mina xbr Serial xbconfig XBee USB RXTX ManagedServiceFactory metatype.xml Config Mina Admin Metatype Core Service Indirect Exported Packages
  • 30. Where to put native library?
  • 31. How to get native library installed?
  • 32. Bundle-NativeCode • Parameters • path to native code in bundle JAR • osname (MacOS, Linux, etc.) • processor (x86, PowerPC, etc.) • osversion
  • 33. <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <version>2.0.1</version> <extensions>true</extensions> <configuration> <instructions> <Import-Package>*</Import-Package> <Export-Package>net.michaelpigg.xbeelib.protocol,net.michaelpigg.xbeelib</Export-Package> <Embed-Dependency>rxtx,mina-transport-serial</Embed-Dependency> <Bundle-NativeCode>lib/rxtx/mac/x86_64/ librxtxSerial.jnilib; osname=MacOSX; processor=x86_64</Bundle- NativeCode> <Bundle-Activator>net.michaelpigg.xbeelib.impl.BundleActivator</Bundle-Activator> </instructions> </configuration> </plugin>
  • 34. XBeeLib dependencies • Mina and most other dependencies are deployed as bundles • Mina serial transport and RXTX are embedded into XBeeLib bundle • RXTX is not OSGi-ready • Mina serial depends on RXTX
  • 35. <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <version>2.0.1</version> <extensions>true</extensions> <configuration> <instructions> <Import-Package>*</Import-Package> <Export-Package>net.michaelpigg.xbeelib.protocol,net.michaelpigg.xbeelib</Export-Package> <Embed-Dependency>rxtx,mina-transport-serial</Embed- Dependency> <Bundle-NativeCode>lib/rxtx/mac/x86_64/librxtxSerial.jnilib; osname=MacOSX; processor=x86_64</Bundle- NativeCode> <Bundle-Activator>net.michaelpigg.xbeelib.impl.BundleActivator</Bundle-Activator> </instructions> </configuration> </plugin>
  • 36. First Contact • XBeeLib provides simple shell commands for sending commands to XBee modules • xb - send command to local XBee • xbr - send command to remote XBee
  • 37. Shell Commands • Felix provides the Gogo shell as of 3.0 • Bundles contribute commands by registering a service with two properties • osgi.command.scope • osgi.command.function
  • 38. public void start(BundleContext context) throws Exception { Hashtable cmdProps = new Hashtable(); // these commands are in scope “xbee” cmdProps.put(CommandProcessor.COMMAND_SCOPE, “xbee”); // “xb” and “xbr” are functions that can act as commands cmdProps.put(CommandProcessor.COMMAND_FUNCTION, new String[] {“xb”, “xbr”}); context.registerService( ToXbeeCommand.class.getName(), new ToXbeeCommand(context), cmdProps); }
  • 39. Listing Shell Commands g! help felix:bundlelevel ..... felix:which gogo:cat .... gogo:until obr:deploy .... obr:source xbee:listports xbee:xb xbee:xbconfig xbee:xbr xbee:xmon xbee:xsample g!
  • 40. Using Commands Send node discover command g! xb nd ND response: Frame ID = 109;Status = OK;Address = 0013a200403c5e93;Signal strength = 32; g! x1 = "0013a200403c5e93" 0013a200403c5e93 g! xbr $x1 is Request sample IS response: Frame ID = 11;Status = OK;Data: 010200013c g!
  • 42. Incoming Data • Number resulting from ADC sample on XBee
  • 43. XbeeAnalogData Transformer Interface • Implementations convert raw ADC reading to useful data • TemperatureSensorTransformer does this for our temperature sensor hardware
  • 44. xbee-temp-sensor bundle xbee- listener XbeeAnalogDataTransfomer temp- sensor metatype.xml ManagedServiceFactory Config Metatype Admin
  • 45. Sample with no Transformer g! xsample $x1 Command returned with status OK Raw data in response:1200dd Number of samples 1 Digital I/O No digital I/O data in response. Analog Data 1: DD(221) g!
  • 48. NO!
  • 49. Configuration Admin Service • Stores configuration for a service • Sends configuration to service • at startup • when configuration changes
  • 50. ManagedService or ManagedServiceFactory? • ManagedService • Configures at most one instance • ManagedServiceFactory • Configures one or more instances
  • 51. We need to configure multiple sensors
  • 52. Implementation • Make up a PID • Implement ManagedServiceFactory • Register implementation as a service with the chosen PID
  • 53. public class XbeeTemperatureSensorFactory implements ManagedServiceFactory { public void updated(String pid, Dictionary properties) throws ConfigurationException { // get configuration properties and copy to registration properties String address = properties.get(LOCATION_ADDRESS); String name = properties.get(LOCATION_NAME); Dictionary<String, String> registrationProperties = new Hashtable<String, String>(); registrationProperties.put( LOCATION_NAME, name); registrationProperties.put( LOCATION_ADDRESS, address); // create new transformer TemperatureSensorTransformer transformer = new TemperatureSensorTransformer(); // register newly configured transformer ServiceRegistration registration = bundleContext.registerService( XbeeAnalogDataTransformer.class.getName(), transformer, registrationProperties); } }
  • 54. public class BundleActivator implements BundleActivator { // factory PID - will be used as base PID for configured instances public static String PID = "com.pigglogic.phomenet.xbee.sensor.temperature"; public void start(BundleContext context) throws Exception { // create ManagedServiceFactory instance sensorFactory = new XbeeTemperatureSensorFactory(context); Dictionary properties = new Hashtable<String, String>(); // set SERVICE_PID property to our factory PID properties.put(Constants.SERVICE_PID, PID); // register factory instance factoryRegistration = context.registerService( ManagedServiceFactory.class.getName(), sensorFactory, properties); }
  • 55. What is allowed in configuration? • What are the attribute names? • What type of data do they take? • Are they required?
  • 56. Metatype Specification • Specify attributes used in configuration • name, type, required, default value, etc. • XML file in OSGI-INF/metatype • Felix web console will use this data to dynamically create a configuration UI
  • 57. <metatype:MetaData xmlns:metatype="http://www.osgi.org/xmlns/metatype/v1.0.0"> <OCD description="xbee-temperature-sensor" name="com.pigglogic.phomenet.xbee.sensor.temperature" id="com.pigglogic.phomenet.xbee.sensor.temperature"> <AD name="Location Name" id="location.name" required="true" type="String" default="Temperature Sensor"/> <AD name="Location Address" id="location.address" required="true" type="String"/> <AD name="Correction" id="location.correction" required="false" type="Double" default="0.0"/> </OCD> <Designate pid="com.pigglogic.phomenet.xbee.sensor.temperature" factoryPid="com.pigglogic.phomenet.xbee.sensor.temperature"> <Object ocdref="com.pigglogic.phomenet.xbee.sensor.temperature"/> </Designate> </metatype:MetaData>
  • 59. Sample with Transfomer g! xsample $x1 Command returned with status OK Raw data in response:12013e Number of samples 1 Digital I/O No digital I/O data in response. Analog Data 1: 13E(318) Transformer reports value of -11.609971
  • 61. xbee-listener bundle temp- sensor recorder XbeeAnalogDataTransfomer XbeeLib Observation Recorder XBeeService xbee- listener Event Admin Event Admin
  • 62. Piping Hot Data • xbee-listener gets data from XBeeService, but what to do with it? • Needs to find a transformer that will handle the data • There should be a number of transformers registered • Chooses based on source address
  • 63. Recording data • xbee-listener records transformed data • Finds an instance of ObservationRecorder service
  • 64. Default Storage Observation Recorder phomenet service Config Derby Admin
  • 65. NoSql? • What if we wanted to be cool and store data in Cassandra? • We could provide a different bundle that implements ObservationRecorder • but uses Cassandra instead of Derby
  • 67. Show me a GUI! • Web page GUI • Show latest observation for each sensor
  • 68. phomenet-web phomenet- web Servlet Event Handler Felix Web Event Console Admin
  • 69. Observation Events • xbee-listener posts an OSGi event when data is transformed • Event topic is “phomenet/Observation/ Temperature/<address>”
  • 70. OSGi Event Admin • Bundles can post events • Bundles can register to be notified of posted events
  • 71. Posting an Event // build Map containing event data Map<String, Object> eventProperties = new HashMap<String, Object>(); eventProperties.put("location.name", locationName); final String addressString = frame.getSourceAddress().toString(); eventProperties.put("location.address", addressString); eventProperties.put("observedValue", value); // create Event with topic and properties final Event event = new Event( "phomenet/Observation/Temperature/" + addressString, eventProperties); // call postEvent with event eventAdmin.postEvent(event);
  • 72. Listening to Events public void start(BundleContext context) throws Exception { Hashtable<String, Object> props = new Hashtable<String, Object>(); // Felix web console extension properties props.put("felix.webconsole.label", "phomenet"); props.put("felix.webconsole.title", "pHomeNet Console"); // property to say that we want all Observation events props.put(EventConstants.EVENT_TOPIC, "phomenet/Observation/*"); // register under Servlet and EventHandler interfaces webConsoleRegistration = context.registerService( new String[] {Servlet.class.getName(), EventHandler.class.getName()}, new PhomenetConsolePlugin(context), props); }
  • 73. Extending Web Console • Register a class that extends HTTPServlet • Add properties • felix.webconsole.label - used in URL • felix.webconsole.title - title of page
  • 74. Registering Extension public void start(BundleContext context) throws Exception { Hashtable<String, Object> props = new Hashtable<String, Object>(); // Felix web console extension properties props.put("felix.webconsole.label", "phomenet"); props.put("felix.webconsole.title", "pHomeNet Console"); // property to say that we want all Observation events props.put(EventConstants.EVENT_TOPIC, "phomenet/Observation/*"); // register under Servlet and EventHandler interfaces webConsoleRegistration = context.registerService( new String[] {Servlet.class.getName(), EventHandler.class.getName()}, new PhomenetConsolePlugin(context), props); }
  • 75. Resources • XBeeLib - kenai.com/projects/xbeelib • pHomeNet - kenai.com/projects/phomenet
  • 76. Resources • XBee 802.15.4 OEM module • http://www.digi.com/products/wireless/point-multipoint/xbee-series1- module.jsp#overview • Droids XBee USB board • http://www.droids.it/990_002.html • MCP9700 Temperature Sensor • http://www.microchip.com/wwwproducts/Devices.aspx? dDocName=en022289

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n
  78. \n
  79. \n