Compare commits

..

106 Commits

Author SHA1 Message Date
d355f76226 upm: v0.6.2
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-04-19 16:42:19 -07:00
4f6be750c7 vcap: Initial implementation
This UPM module captures a still frame from a Linux V4L device, such
as a USB webcam, and and then allows you to save it as a JPEG image
into a file.

The camera and driver in use must support streaming, mmap-able buffers
and must provide data in YUYV format.  This should encompass most
video cameras out there.  It has been tested with a few off the shelf
USB cameras without any problems.

Signed-off-by: Jon Trulson <jtrulson@ics.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-04-19 15:38:48 -07:00
bf7d7d1bda examples: changed default bus from 6 to 0 for SSD1306 examples
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-04-18 16:27:11 -07:00
9acc752074 java: add dependency on java targets for java examples
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-04-15 10:01:55 -07:00
b6b7d892c2 cmake: fix RPM generation when VERSION_COMMIT is empty string
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-04-15 10:01:27 -07:00
1ca8d100ea e50hx: add bacnetmstp includes so example can build
Signed-off-by: Jon Trulson <jtrulson@ics.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-04-15 10:01:02 -07:00
96f1afffe3 e50hx: remove add_dependency() call from CMakeLists.txt
Signed-off-by: Jon Trulson <jtrulson@ics.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-04-15 10:00:38 -07:00
899d873cbc e50hx: Initial implementation
This driver requires the UPM BACNETMSTP driver (PR #385) to be merged
first.

This module implements support for the Veris E50H2 and E50H5
BACnet Energy Meters.

From the datasheet: The E50H5 BACnet MS/TP DIN Rail Meter with
Data Logging combines exceptional performance and easy
installation to deliver a cost-effective solution for power
monitoring applications. Native serial communication via BACnet
MS/TP provides complete accessibility of all measurements to your
Building Automation System. The data logging capability protects
data in the event of a power failure. The E50H5 can be easily
installed on standard DIN rail, surface mounted or contained in
an optional NEMA 4 enclosure, as needed. The front-panel LCD
display makes device installation and setup easy and provides
local access to the full set of detailed measurements.

This module was developed using the upm::BACNETMSTP module, based
on libbacnet-stack 0.8.3.  Both libbacnet 0.8.3 and the
upm::BACNETMSTP libraries must be present in order to build this
module.  This driver was developed on the E50H5.  The Trend Log
functionality is not currently supported.

The Binary Input Objects are also not supported as these are only
used for the Alarm bits which are already available from Analog
Input Object 52 as an alarm bitfield incorporating all of the
supported alarm indicators.

It was connected using an RS232->RS485 interface.  You cannot use
the built in MCU TTL UART pins for accessing this device -- you
must use a full Serial RS232->RS485 or USB-RS485 interface
connected via USB.

Signed-off-by: Jon Trulson <jtrulson@ics.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-04-15 10:00:04 -07:00
dc8be495a9 docs: fix spelling errors
Signed-off-by: Fathi Boudra <fathi.boudra@linaro.org>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-04-15 09:59:29 -07:00
c7b5204fe4 bacnetmstp: initial BACnet MS/TP implementation
This driver is implemented as a singleton due to it's reliance on the
bacnet-stack implementation.  This implementation does not currently
support multiple BACnet networks at the same time, though in the
future it might, depending on the future of bacnet-stack development.
The version of bacnet-stack used in developing this driver was 0.8.3.

This driver is not intended to be used directly by end users, rather
it is intended for UPM drivers supporting specific BACnet devices,
such as the Veris E50H5 Energy Meter.

Unfortunately, this means that a process can only support a single
RS-485 BACnet network, though you can support multiple devices on that
network.

No examples are provided.  Please look at the E50HX driver for an
example of how to use this class in a BACnet MS/TP device driver if
you want to write one.

When initialized, the bacnet-stack library will attach to your RS-485
based BACnet network, and start a Master Finite State Machine (FSM) in
a separate thread.  This thread will handle the details of token
passing and locating other Masters in the network (Poll For Master).

This driver will appear as a BACnet Master device on the BACnet
network, which supports only the required Device Object and any
required services (readProp) and Device Object properties.

When initializing the driver, it is important to select a Device
Object Instance ID that is unique on your BACnet network.  This is the
unique identifier that will be used to identify your Master to the
rest of the BACnet network.

In addition, it may take some time after initialization before you
will be able to communicate on the network, as the first thing that
has to happen is that all Masters on the network need to be identified
(handled by the Master FSM) and a token needs to be received before
your Master can begin transmitting (making requests).  This may take a
couple of minutes on a large network.

You can speed this process up by specifying a maxMaster (to
initMaster()) that is smaller than the default (127) -- but only if
you are CERTAIN that there are no masters with a MAC address higher
than the value you choose.  If you fail to follow this rule, you may
introduce hard to identify token passing problems on the network for
yourself and other BACnet Masters.

Currently, this driver only supports the readProperty and
writeProperty requests to other BACnet devices.  In addition, array
property reading and writing is not currently supported.

Signed-off-by: Jon Trulson <jtrulson@ics.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-04-15 09:58:36 -07:00
527615758a cmake: Fixed builddoc flow for javascript documentation
Fixed a few small typos for handling node as well as a
small conditional for building PYTHON.

    * Fixed some NODE_EXECUTABLE->NODEJS_EXECUTABLE instances
    which must have been missed from a previous commit.

    * Added a qualifier for python documentation so both
    BUILDSWIGPYTHON AND BUILDSWIG must be set to add
    dependencies for pydoc.

Signed-off-by: Noel Eck <noel.eck@intel.com>
2016-04-12 16:56:55 -07:00
16b6fcf807 cmake: set CMAKE_INSTALL_LIBDIR before using it
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-04-06 12:51:20 -07:00
5a9f234a3e cmake: Solved issue with nodejs installation path
Changed ${LIB_INSTALL_DIR} with lib, because the variable expands to
/usr/lib, making the install path /usr/usr/lib/node_modules, which
is incorrect. Now the install path is /usr/lib/node_modules.

Signed-off-by: Andrei Vasiliu <andrei.vasiliu@intel.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-04-06 12:45:14 -07:00
c7bd37b322 docs: added new API compatibility section
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-04-06 12:44:56 -07:00
edcaed90e6 extdep: Removed add_dependencies call from CMakeLists
Small change to get rid of a warning in newer cmake versions.

Versions of cmake (>= 3.0) throw a warning on the add_dependecy
method for non-existant dependencies (add_dependency call before
target_link_libraries call).

Removed the call to add_dependency since target_link_libraries should
provide the same functionality for ozw and modbus dependencies.

Signed-off-by: Noel Eck <noel.eck@intel.com>
2016-04-06 12:44:35 -07:00
655ccee9af upm: v0.6.1
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-31 17:22:16 -07:00
102d86870a bme280: added missing return in non-void function
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-31 17:21:54 -07:00
a88ec4237d gfx: renamed GFX headers to avoid overlap on install
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-31 17:21:07 -07:00
cf2b8c9a6e ssd1351: Changed SPI to MODE0 for compatibilty and listed SPI PM issue in description
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-31 16:16:46 -07:00
68aa067f82 SWIG: Added include carrays_uint8_t.i for nrf24l01 python and js bindings
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-30 10:30:12 -07:00
24062f6a9d Java: Added examples for AM2315 and TSL2561
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-30 10:23:24 -07:00
db8d708798 cmake: node install path is now same for both package and .node
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-29 17:28:28 -07:00
edfdf6ec34 cmake: added include_directories(..) to python too, for consistency
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-29 17:08:12 -07:00
7c66d5c321 examples/c++: Fix syntax errors in ads1x15.cxx
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-29 16:59:38 -07:00
0e365590c4 cmake: Add parent directory to include path for UPM modules
This avoids using include files from a pre-existing UPM installation
as they can break the build if API changes are made.

Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-29 16:59:00 -07:00
ba127ec4d4 cmake: honor LIB_INSTALL_DIR and also for Node install path
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-28 17:51:54 -07:00
b6572e1f28 cmake: Add upm header files directory
Signed-off-by: Eugene Bolshakov <pub@relvarsoft.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-28 16:24:45 -07:00
02974f242e cmake: fix node modules install path when install prefix is given
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-28 16:22:49 -07:00
e809016152 cmake: added back PYTHON_VERSION_* when not building docs for install path
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-28 16:22:35 -07:00
39c55b23d9 upm: version 0.6.0
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-25 14:13:16 -07:00
09b0f0adaa .travis.yml: updated cmake and fixed builds
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-25 14:12:53 -07:00
00b0092fc1 cmake: fixed flow for finding libs & include dirs
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-25 14:10:31 -07:00
ec85072011 upm: removed some temporary files left over among sources
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-24 14:25:13 -07:00
60221dbcd6 cmake: disable TGZ from builds when IPK used
Signed-off-by: Brendan Le Foll <brendan.le.foll@intel.com>
2016-03-24 13:23:23 -07:00
a35e58c54c curieimu: Adds examples for both JS and Python that load MRAA Firmata subplatform
Signed-off-by: deadprogram <ron@hybridgroup.com>
Signed-off-by: Brendan Le Foll <brendan.le.foll@intel.com>
2016-03-24 13:23:18 -07:00
1b8cb1361c cmake: add workaround for cmake 2.7
Signed-off-by: Brendan Le Foll <brendan.le.foll@intel.com>
2016-03-24 13:23:13 -07:00
aeb948282a cmake: Fix issues with node v4/v5
Signed-off-by: Brendan Le Foll <brendan.le.foll@intel.com>
2016-03-24 13:23:06 -07:00
1b649021f1 .travis.yml: Make travis test node4/node5 and node0.12
Signed-off-by: Brendan Le Foll <brendan.le.foll@intel.com>
2016-03-24 13:23:01 -07:00
10d784ea7e cmake: add BUILDPYTHON3 flag
Use the same methodology as in mraa, by default build for python2, if requested
use python3 for everything

Signed-off-by: Brendan Le Foll <brendan.le.foll@intel.com>
2016-03-24 13:18:50 -07:00
a48f457057 FindNode.cmake: Improve FindNode cmake module
Use mraa's FindNode since it's alot more robus and can handle NVM better

Signed-off-by: Brendan Le Foll <brendan.le.foll@intel.com>
2016-03-24 13:18:44 -07:00
d8fc664178 curieimu: Add WIP for Python example
Signed-off-by: deadprogram <ron@hybridgroup.com>
Signed-off-by: Brendan Le Foll <brendan.le.foll@intel.com>
2016-03-24 13:13:34 -07:00
83b0512ffb Updates implementation and examples to use dynamic-friendly interface
Signed-off-by: deadprogram <ron@hybridgroup.com>
Signed-off-by: Brendan Le Foll <brendan.le.foll@intel.com>
2016-03-24 13:13:29 -07:00
3e7fca21ee Complete accel and gyro implementations for new dynamic friendly interface
Signed-off-by: deadprogram <ron@hybridgroup.com>
Signed-off-by: Brendan Le Foll <brendan.le.foll@intel.com>
2016-03-24 13:13:22 -07:00
8c7d6483d3 curieimu: modify calls to use update methodology to fix python/java/js API
Signed-off-by: Brendan Le Foll <brendan.le.foll@intel.com>
2016-03-24 13:13:17 -07:00
22636fb47a curieimu: Make compilation dependant on mraa_firmata_init
Signed-off-by: Brendan Le Foll <brendan.le.foll@intel.com>
2016-03-24 13:13:11 -07:00
fb5c809ff8 curieimu: Plugin to interface with the arduino101's IMU
Internal sensor onboard the Curie/Arduino101 can be accessed via Firmata using
this plugin. You will need mraa compiled with -DFIRMATA=ON for this to work and
be using Firmata with the CurieIMU firmata extension for ExtensibleFirmata

Signed-off-by: Ron Evans <ron@hybridgroup.com>
Signed-off-by: Justin Zemlyansky <jlstigman@live.com>
Signed-off-by: Brendan Le Foll <brendan.le.foll@intel.com>
2016-03-24 13:11:31 -07:00
0d20cdb25a doxygen: removed Bosch base lib from docs since only used internally
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-24 12:57:57 -07:00
f2b10afa35 pn532: fix a couple more narrowing conversions (c++11)
Signed-off-by: Jon Trulson <jtrulson@ics.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-24 11:06:57 -07:00
56e1d2214f grovescam: fix a couple more narrowing conversions (c++11)
Signed-off-by: Jon Trulson <jtrulson@ics.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-24 11:06:49 -07:00
e80e1bda2c am2315: fix narrowing conversions (c++11)
Signed-off-by: Jon Trulson <jtrulson@ics.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-24 11:06:40 -07:00
98f9dc54ff zfm20: fix narrowing conversions (c++11)
Signed-off-by: Jon Trulson <jtrulson@ics.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-24 11:06:29 -07:00
611f72c491 sx1276: fix narrowing conversions (c++11)
Signed-off-by: Jon Trulson <jtrulson@ics.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-24 11:06:20 -07:00
6f68e07aa5 pn532: fix narrowing conversions (c++11)
Signed-off-by: Jon Trulson <jtrulson@ics.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-24 11:06:11 -07:00
be34f53a51 grovescam: fix narrowing conversions (c++11)
Signed-off-by: Jon Trulson <jtrulson@ics.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-24 11:06:03 -07:00
7a133cf891 cmake: Enable C++11 standards support
This patch checks for, and enables C++11 support for building UPM.
This should work for all cmake versions currently supported by UPM
(2.8.11+), and any compiler (clang/gcc) that was released in this
decade.

Support can be specifically disabled by passing '-DENABLECXX11=OFF' to
cmake, though modules requiring this support will not build.

C++11 support is enabled by default.

Signed-off-by: Jon Trulson <jtrulson@ics.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-24 11:05:54 -07:00
49611e5ac0 smartdrive: build example and add manufacturer to list
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-24 11:05:07 -07:00
e5385eb510 smartdrive: patch example
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-24 11:00:47 -07:00
de1a46aa59 smartdrive: Replace mraa_result_t by mraa::Result in smartdrive.cxx
Signed-off-by: Oussema Harbi <oussema.elharbi@gmail.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-23 17:15:43 -07:00
7e402ede34 smartdrive: upm implementation for SmartDrive from openelectronics.com
Signed-off-by: Oussema Harbi <oussema.elharbi@gmail.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-23 17:13:10 -07:00
4381f8bd2e apa102: addded C++ snippet to documentation
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-23 17:05:33 -07:00
757104e013 java: turned on sanity checks in travis
Signed-off-by: Stefan Andritoiu <stefan.andritoiu@intel.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-23 17:04:46 -07:00
6c08313cb7 doxy: Corrected sample mapping
Signed-off-by: Stefan Andritoiu <stefan.andritoiu@intel.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-23 17:03:41 -07:00
6d4714df3c java: Added kxcjk1013 to javaswig blacklist because of unclean bindings. Removed javaupm_kxcjk1013.i and javaupm_nrf8001.i
Signed-off-by: Stefan Andritoiu <stefan.andritoiu@intel.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-23 17:02:37 -07:00
75e42c6731 java: eliminated loadlibrary code from examples
Signed-off-by: Stefan Andritoiu <stefan.andritoiu@intel.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
2016-03-23 17:01:19 -07:00
5a5637a431 h803x: Initial implementation
This module implements support for the Veris H8035 and H8036 Energy
Meters.

The H8036 is similar to the H8035, but provides much more data.

The Enercept H8035/H8036 is an innovative three-phase networked
(Modbus RTU) power transducer that combines electronics and high
accuracy industrial grade CTs in a single package. The need for
external electrical enclosures is eliminated, greatly reducing
installation time and cost. Color-coordination between voltage leads
and CTs makes phase matching easy. Additionally, these transducers
automatically detect and compensate for phase reversal, eliminating
the concern of CT load orientation. Up to 63 Transducers can be
daisy-chained on a single RS-485 network.

This module was developed using libmodbus 3.1.2, and the H8035.  The
H8036 has not been tested.  libmodbus 3.1.2 must be present for this
module to build.

Signed-off-by: Jon Trulson <jtrulson@ics.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-22 22:58:17 -07:00
e062b9b85c bmi160: Initial implementation
The Bosch BMI160 is a 3-axis Accelerometer and Gyroscope.
Additionally it supports an external Magnetometer, accessed through
the BMI160's register interface.  This driver was developed with a
BMI160 "Shuttle" board, which included a BMM150 Magnetometer.

The device is driven by either 1.8v or 3.3vdc.  This driver
incorporates the Bosch BMI160 driver code at
https://github.com/BoschSensortec/BMI160_driver .

While not all of the functionality of this device is supported
initially, the inclusion of the Bosch driver in the source code
makes it possible to support whatever features are required that
the driver bosch driver itself can support.

Signed-off-by: Jon Trulson <jtrulson@ics.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-22 22:52:31 -07:00
b778476597 tex00: Initial Implementation
The Veris TEX00 temperature sensor family is made up of a series of
RTD thermistors in wall mount packaging.

This driver was developed using the TED00, which utilizes a 10K Ohm
Type 2 thermistor.  However, this driver can support the other 12
variants of the TE series as well by providing the correct sensor type
to the class constructor.  These other sensor types have not been
tested.  Only the TED00 hardware was tested with this driver.

This sensor must be connected as part of a voltage divider, with the
balancing resistor ideally matched to the sensor's 25C detection
range.  For the TED00 (10kt2), a 10K Ohm (1% tolerance) resistor was
used in a circuit like the following:

GND o----|TED00(10k2)|----o----|balanceResistor(10K)|----o VCC (+5vdc)
                          |
                          |
                          |----o A0 (analog input to MCU)

A 3.3vdc voltage can be used as well if desired.

Signed-off-by: Jon Trulson <jtrulson@ics.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-22 17:16:21 -07:00
9fb4be1b44 APA102: Initial implementation
Signed-off-by: Yannick Adam <yannick.adam@gmail.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-22 16:57:08 -07:00
42ff8b3a6e teams: Initial implementation
The driver adds support for the Veris TEAMS Temperature Transmitter.

It provides it's output via a 4-20ma current loop.  The supported
temperature range is 10C to 35C.

This sensor was developed with a Cooking Hacks (Libelium)
4-channel 4-20ma Arduino interface shield.  For this interface,
the receiver resistance (rResistor) was specified as 165.0
ohms.

Signed-off-by: Jon Trulson <jtrulson@ics.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-22 16:49:37 -07:00
a8d96bd2d9 cwlsxxa: Initial implementation
The driver was developed using the Veris CWLSHTA CO2 Gas sensor.  The
'T' variant supports a temperature sensor, and the 'H' variant
supports a humidity sensor.

All 3 signals are provided by the device as analog 0-5Vdc, 0-10Vdc, or
4-20ma loop current outputs.  For devices supporting temperature, the
valid temperature range is 10C to 50C.  The humidity ranges from 0% to
100% (non-condensing).  The CO2 sensor ranges from 0 to 2000 ppm.

This driver was developed using the 5Vdc outputs and the 4-20ma
outputs.  For voltage outputs, your MCU must be configured for 5V
operation.  In addition, you must configure the sensor (via it's
configuration switches) to output 0-5VDC only.  Using any other analog
reference voltage will require the appropriate external circuitry
(such as a voltage divider) in order to interface safely with your
MCU.

In addition, the sensor can be configured for 4-20ma usage, by
specifying the correct receiver resistance (in ohms) in the
constructor.  This sensor was tested with a Cooking Hacks (Libelium)
4-channel 4-20ma Arduino interface shield.  For this interface, the
receiver resistance was specified as 165.0 ohms.

Signed-off-by: Jon Trulson <jtrulson@ics.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-22 16:36:10 -07:00
f3a2e0d77c CMakeCache.txt: Removing CMakeCache files which are breaking the build on Ninja
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-22 14:14:48 -07:00
a348f23a3b SWIG: Corrected Swig interface files
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-22 12:17:08 -07:00
efe80a4450 SWIG: Added python and node swig files for interfaces
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-22 12:16:52 -07:00
411656d965 SWIG: Added java swig interface files
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-22 12:16:03 -07:00
c007385847 Example: bme280 Javascript sample
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 16:05:33 -07:00
8490a63309 FindNode: Update cmake module to support Fedora22 and check for errors
FindNode.cmake reports failure it cannot detect all required include files.
Module is now called with REQUIRED flag to prevent generation of makefiles
that will not build.

Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 16:04:53 -07:00
2331548f25 Example: t6713 C++ example
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 16:03:43 -07:00
777f081f84 Example: si7005 C++ example
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 16:03:16 -07:00
56666872d9 Example: si1132 C++ example
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 16:02:46 -07:00
c16f80f226 Example: max44009 C++ example
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 16:02:20 -07:00
ee8433d92a Example: lp8860 C++ example
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 16:01:32 -07:00
dd3e88fa59 Example: hlg150h C++ example
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:56:41 -07:00
224fe03d98 Example: ds1808lc C++ example
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:56:26 -07:00
9e7eae070a Example: bme280 C++ example
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:55:02 -07:00
9bc3d2ded0 interfaces: Removed isConfigured() from IModuleStaus
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:54:35 -07:00
f268437cd5 upm.h: Added C++ interface doxygen categories.
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:53:55 -07:00
aff6e9c77f interfaces: Removed get*Raw() methods
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:53:31 -07:00
d642d63d21 Swig: Added JavaScript and Python swig files for bme280
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:52:30 -07:00
17fd502cb5 ads1x15: ads1015 module now implements IADC. Removed ads1015_iadc.
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:51:06 -07:00
b08da722f7 cmake: Updated RPM packaging config to match DEB.
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:50:43 -07:00
4220dd25b4 examples: Updated IADC example to use updated interface
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:50:33 -07:00
bbdbe56355 ads1015: Added ads1015_iadc module that implements IADC.
An ADS1015 implementation existed in the inferface fork before the ADS1x15
moulde was added to upstream repo. This retrofits the IADC interface onto
an implementation derived from ads1x15

Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:49:13 -07:00
e7a5118f86 cmake: Added src folder to include directory list
This is required so that interface include files are taken from
local src folder before looking in /usr/include/upm where an older version
may exist.

Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:48:50 -07:00
fe8906fb51 interface: Updated IADC
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:48:37 -07:00
f35f6cc064 README: Added overview of C++ interfaces
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:48:17 -07:00
389bd32f81 examples: Added c++ interface based sensor/actuator examples
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:46:55 -07:00
f2b8921f1e t6713: Initial Implementation Amphenol Telaire 6713 Series CO2 sensor
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:45:26 -07:00
6f080db5cb si7005: Initial Implementation Silicon Labs Si7005 humidity and temperature sensor
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:44:48 -07:00
4aeccf7714 si1132: Initial Implementation Silicon Labs SI1132 light sensor.
Only visible light readings are currently supported.

Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:43:37 -07:00
33734dc2e2 max44009: Initial Implementation Maxim 44009 light sensor
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:42:15 -07:00
1f1a1bce8e lp8860: Initial Implementation TI LP8860 LED lighting controller
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:41:18 -07:00
bd7930f249 hlg150: Initial Implementation Meanwell HLG150 based LED light controller
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:40:33 -07:00
d183c9574d ds1808lc: Initial Implementation Maxim DS1808 based LED lighting controller
DS1808 is a general purpose potentiometer but this implementation
is limited to controlling brightness of custom LED lighting hardware.
Ideally there should be a DS1808 module used by a seperate
lighting module.

Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:38:52 -07:00
63066bcc0b bmp180: Added Bosch BMP180 temperature/pressure sensor
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:38:12 -07:00
15d91d4797 bme280: Added Bosch BME280 temperature/humidity/pressure sensor
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:37:35 -07:00
031ed7bf95 interfaces: Added initial set of sensor/actuator interfaces
Signed-off-by: Henry Bruce <henry.bruce@intel.com>
Signed-off-by: Abhishek Malik <abhishek.malik@intel.com>
2016-03-17 15:35:38 -07:00
280 changed files with 55000 additions and 206 deletions

View File

@ -6,11 +6,9 @@ env:
- NODE5=true
- NODE012=true
install:
- if [ "${NODE4}" ]; then export CC=gcc-4.8 CXX=g++-4.8; fi
- sudo add-apt-repository --yes ppa:kalakris/cmake
- sudo add-apt-repository --yes ppa:fenics-packages/fenics-exp/swig
- sudo apt-get update -qq
- sudo apt-get install -y -qq swig3.0 python git cmake
- sudo apt-get install -y -qq swig3.0 git
- sudo ln -s /usr/bin/swig3.0 /usr/bin/swig
- sudo update-java-alternatives -s java-8-oracle
before_script:
@ -22,13 +20,19 @@ before_script:
- if [ "${NODE012}" ]; then nvm install 0.12; export NODE_ROOT_DIR="/home/travis/.nvm/versions/node/`nvm version`"; fi
script:
- git clone https://github.com/intel-iot-devkit/mraa.git
- cd mraa && mkdir build && cd build && cmake -DBUILDSWIGJAVA=$BUILDJAVA -DBUILDSWIGNODE=OFF -DBUILDSWIGPYTHON=OFF -DFIRMATA=ON -DENABLEEXAMPLES=OFF -DCMAKE_INSTALL_PREFIX:PATH=/usr .. && make && sudo make install
- cd mraa && mkdir build && cd build && cmake -DBUILDSWIGJAVA=$BUILDJAVA -DBUILDSWIGNODE=OFF -DBUILDSWIGPYTHON=OFF -DFIRMATA=ON -DENABLEEXAMPLES=OFF -DCMAKE_INSTALL_PREFIX:PATH=. .. && make && make install
- export PKG_CONFIG_PATH=$PWD/lib/pkgconfig:$PWD/lib/x86_64-linux-gnu/pkgconfig
- export CPLUS_INCLUDE_PATH=$PWD/include
- export LIBRARY_PATH=$PWD/lib:$PWD/lib/x86_64-linux-gnu
- cd ../.. && mkdir build && cd build && cmake -DNODE_ROOT_DIR:PATH="${NODE_ROOT_DIR}" -DBUILDSWIGJAVA=$BUILDJAVA -DBUILDEXAMPLES=ON -DBUILDJAVAEXAMPLES=$BUILDJAVA .. && make
addons:
apt:
sources:
- llvm-toolchain-precise-3.6
- ubuntu-toolchain-r-test
- george-edison55-precise-backports
packages:
- clang-3.6
- g++-4.8
- cmake
- cmake-data

View File

@ -15,17 +15,17 @@ message (INFO " found mraa version: ${MRAA_VERSION}")
# Appends the cmake/modules path to MAKE_MODULE_PATH variable.
set (CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules ${CMAKE_MODULE_PATH})
set (LIB_INSTALL_DIR "${CMAKE_INSTALL_LIBDIR}" CACHE PATH "Installation path for libraries")
# Set CMAKE_LIB_INSTALL_DIR if not defined
# Set CMAKE_INSTALL_LIBDIR if not defined
include(GNUInstallDirs)
set (LIB_INSTALL_DIR "${CMAKE_INSTALL_LIBDIR}" CACHE PATH "Installation path for libraries")
# Make a version file containing the current version from git.
include (GetGitRevisionDescription)
git_describe (VERSION "--tags")
if ("x_${VERSION}" STREQUAL "x_GIT-NOTFOUND" OR "x_${VERSION}" STREQUAL "x_-128-NOTFOUND")
message (WARNING " - Install git to compile a production UPM!")
set (VERSION "v0.5.1-dirty")
set (VERSION "v0.6.2-dirty")
endif ()
message (INFO " - UPM Version ${VERSION}")
@ -58,7 +58,8 @@ option (BUILDJAVAEXAMPLES "Build java example jars" OFF)
option (BUILDSWIGJAVA "Build swig java modules" OFF)
option (IPK "Generate IPK using CPack" OFF)
option (RPM "Generate RPM using CPack" OFF)
option (BUILDTESTS "Generate check-ups for upm" OFF)
option (BUILDTESTS "Generate check-ups for upm" ON)
option (ENABLECXX11 "Enable C++11 standards support" ON)
# Find swig
if (BUILDSWIG)
@ -77,6 +78,27 @@ include (TargetArch)
target_architecture (DETECTED_ARCH)
message( INFO " - Target arch is ${DETECTED_ARCH}")
# enable c++11 standards support
if (ENABLECXX11)
include(CheckCXXCompilerFlag)
if (CMAKE_VERSION VERSION_LESS "3.1")
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if (COMPILER_SUPPORTS_CXX11)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif (COMPILER_SUPPORTS_CXX0X)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
message(WARNING "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please update your C++ compiler.")
endif()
else()
# 3.1+ uses this generic method to enable c++11
set (CMAKE_CXX_STANDARD 11)
endif()
else()
message(WARNING "Some modules require C++11 support, and may not build without it.")
endif()
if (BUILDDOC)
# Add a target to generate API documentation with Doxygen
find_package (Doxygen)
@ -100,11 +122,10 @@ if (BUILDDOC)
find_package (Sphinx)
if(SPHINX_FOUND AND BUILDSWIG AND BUILDSWIGPYTHON)
# Python required for Sphinx build
find_package (PythonLibs)
find_package (PythonLibs ${PYTHONBUILD_VERSION} REQUIRED)
string (REPLACE "." ";" PYTHON_VERSION_LIST ${PYTHONLIBS_VERSION_STRING})
list (GET PYTHON_VERSION_LIST 0 PYTHON_VERSION_MAJOR)
list (GET PYTHON_VERSION_LIST 1 PYTHON_VERSION_MINOR)
set (SITE_PACKAGES ${CMAKE_INSTALL_PREFIX}/${LIB_INSTALL_DIR}/python${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}/site-packages)
configure_file (${CMAKE_CURRENT_SOURCE_DIR}/doxy/conf.py.in ${CMAKE_CURRENT_BINARY_DIR}/pydoc/conf.py @ONLY)
configure_file (${CMAKE_CURRENT_SOURCE_DIR}/doxy/index.rst ${CMAKE_CURRENT_BINARY_DIR}/pydoc/index.rst COPYONLY)
add_custom_target (pydoc ALL
@ -131,9 +152,9 @@ if (BUILDDOC)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/doxy/node/${JSDOC_FILE} ${CMAKE_CURRENT_BINARY_DIR}/${JSDOC_FILE} COPYONLY)
endforeach()
add_custom_target(jsdoc ALL
COMMAND ${NODE_EXECUTABLE} docgen -m upm -i xml -t ${CMAKE_CURRENT_SOURCE_DIR}/src -g ../../
COMMAND ${NODEJS_EXECUTABLE} docgen -m upm -i xml -t ${CMAKE_CURRENT_SOURCE_DIR}/src -g ../../
COMMAND ${YUIDOC_EXECUTABLE} -C --no-sort --helpers generators/yuidoc/helper.js --themedir generators/yuidoc/tmpl -o html/node jsdoc/yuidoc/upm
COMMAND ${NODE_EXECUTABLE} tolower -i html/node
COMMAND ${NODEJS_EXECUTABLE} tolower -i html/node
DEPENDS doc
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
COMMENT "Generating API documentation with Yuidoc" VERBATIM
@ -183,21 +204,25 @@ if (RPM)
message (INFO " - RPM packaging enabled for ${DETECTED_ARCH}")
set(CPACK_PACKAGE_VERSION ${VERSION})
set(CPACK_GENERATOR "RPM")
set(CPACK_PACKAGE_NAME "libupm${upm_VERSION_MAJOR}")
set(CPACK_PACKAGE_RELEASE 1)
set(CPACK_PACKAGE_NAME "upm")
set(upm_PACKAGE_ON_TAG ".")
if ("${VERSION_COMMIT}" STREQUAL "")
set(upm_PACKAGE_ON_TAG "")
endif()
set(CPACK_PACKAGE_VERSION
"${upm_VERSION_MAJOR}.${upm_VERSION_MINOR}.${upm_VERSION_PATCH}-${upm_PACKAGE_ON_TAG}${VERSION_COMMIT}")
"${upm_VERSION_MAJOR}.${upm_VERSION_MINOR}.${upm_VERSION_PATCH}${upm_PACKAGE_ON_TAG}${VERSION_COMMIT}")
set(CPACK_PACKAGE_CONTACT "Intel IoT-Devkit")
set(CPACK_PACKAGE_VENDOR "Intel IoT-Devkit")
set(CPACK_RPM_PACKAGE_REQUIRES "mraa >= ${MRAA_VERSION}")
set(CPACK_RPM_PACKAGE_PROVIDES "${CPACK_PACKAGE_NAME}-devel")
set(CPACK_RPM_PACKAGE_LICENSE "MIT")
EXECUTE_PROCESS(COMMAND rpm --showrc
COMMAND grep -E "dist[[:space:]]*\\."
COMMAND sed -e "s/^.*dist\\s*\\.//"
COMMAND tr \\n \\t
COMMAND sed -e s/\\t//
OUTPUT_VARIABLE DIST_TAG)
set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}-${CPACK_PACKAGE_RELEASE}.${DIST_TAG}.${DETECTED_ARCH}")
set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}.${DIST_TAG}.${DETECTED_ARCH}")
include(CPack)
endif()
@ -217,12 +242,10 @@ if (BUILDSWIGPYTHON OR BUILDTESTS)
else ()
set (PYTHONBUILD_VERSION 2.7)
endif ()
find_package (PythonInterp ${PYTHONBUILD_VERSION} REQUIRED)
find_package (PythonLibs ${PYTHONBUILD_VERSION} REQUIRED)
include_directories(${PYTHON_INCLUDE_PATH})
endif ()
if (BUILDTESTS)
find_package (PythonInterp ${PYTHONBUILD_VERSION} REQUIRED)
enable_testing ()
add_subdirectory (tests)
endif()

View File

@ -12,6 +12,19 @@ to provide identification/pin location on the board.
Typically an update() function will be called in order to get new data from the
sensor in order to reduce load when doing multiple reads to sensor data.
Although implementation and API design is up to the developer, C++ interfaces have
been defined for the following sensor/actuator types and developers are encouraged to
implement them. Interface header files are in the src/upm folder.
* Light controller
* Light sensor
* Temperature sensor
* Humidity sensor
* Pressure sensor
* Analog to digital converter
Feedback on interface design and additions for new types are welcome
### Example
A sensor/actuator is expected to work as such (here is the MMA7660 accelerometer API):
@ -51,10 +64,6 @@ A sensor/actuator is expected to work as such (here is the MMA7660 accelerometer
}
```
However implementation and API design is completely up to the developer, some
enumerable sensors for example may provide much clever instantiation. Displays
may also create more complex structures in order to interface with them.
Browse through the list of all [examples](https://github.com/intel-iot-devkit/upm/tree/master/examples).
Multi-sensor samples for the starter and specialized kits can be found in the
@ -81,7 +90,7 @@ See building documentation [here](docs/building.md).
Porting [link](docs/porting.md) has more information on making new UPM modules.
There is also an example available for max31855 [sensor](docs/max31855.md).
There is also an example available gfor max31855 [sensor](docs/max31855.md).
Guide on creating Java [bindings](docs/creating_java_bindings.md).
@ -105,6 +114,15 @@ API Documentation
<a href="http://iotdk.intel.com/docs/master/upm/python"><img src="docs/icons/python.png"/></a>
<a href="http://iotdk.intel.com/docs/master/upm/node"><img src="docs/icons/node.png"/></a>
### API Compatibility
Even if we try our best not to, every once in a while we are forced to modify
our API in a way that will break backwards compatibility. If you find yourself
unable to compile code that was working fine before a library update, make sure
you check the [API changes](docs/apichanges.md) section first.
**NOTE** - Our **C++ header files** will change their extension from *.h* to
*.hpp* in the upcoming version.
### Changelog
Version changelog [here](docs/changelog.md).

View File

@ -94,4 +94,4 @@ if (NODEJS_EXECUTABLE)
mark_as_advanced (NODEJS_EXECUTABLE)
endif ()
mark_as_advanced (NODE_EXECUTABLE)
mark_as_advanced (NODEJS_EXECUTABLE)

20
docs/apichanges.md Normal file
View File

@ -0,0 +1,20 @@
API Changes {#apichanges}
===============
**IMPORTANT NOTICE**
Our **C++ header files** will change their extension from *.h* to *.hpp*. This
change is anticipated in the upcoming version and unfortunately will break
source compatibility with previous versions of UPM for every library. You will
need to update your code and change to the new extension format in your
`#include` directives.
Here's a list of other API changes made to the library that break source/binary
compatibility between releases:
* **my9221**, **groveledbar** and **grovecircularled** are now all part of the
same library (my9221) and new functionality was added going to v.0.5.1
* **stepmotor** driver API was changed significantly from v.0.4.1 to v.0.5.0
* **eboled** library was greatly improved in version 0.4.0 and the `draw()`
function was removed in favor of a more complete GFX library implementation

View File

@ -4,6 +4,38 @@ Changelog {#changelog}
Here's a list summarizing some of the key undergoing changes to our library
from earlier versions:
### v0.6.2
* Added a generic driver for taking snapshots from an USB camera device
* New API changes section in documentation to let users know when the UPM API
gets modified
* Fixed some spelling errors and improved JavaScript documentation builds with
newer versions of YUI and Node
* Enhanced Cmake scripts and the build process
* New sensors: vcap, e50hx
### v0.6.1
* Fixed library build process for different configurations across multiple
environments reported by users.
* Fixed multiple GFX library header clash and improved SSD1351 compatibility
by changing SPI mode
* Added Node and Python array typemaps for nrf24l01
* Added 2 new JAVA examples
### v0.6.0
* Introduced C++ Interfaces for several sensor categories that will help
consolidate the sensor APIs with uniform function names upon implementation
* Greatly improved Node.js detection and handling during build and install,
and should be now compatible with all major versions
* Added a driver for the Curie IMU (accelerometer + gyroscope) that works with
the new Firmata support implemented by MRAA
* Continued to provide several JAVA fixes and examples
* Many new industrial and maker sensors: cwlsxxa, teams, tex00, h803x, apa102,
smartdrive, bmi160, bme280, ds1808lc, hlg150, lp8860, max44009, si1132, t6713,
si7005, ssd1351
### v0.5.1
* Updated the API and added new functionality for the MY9221 class and derived

BIN
docs/images/apa102.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

View File

@ -859,7 +859,7 @@ EXCLUDE_SYMLINKS = NO
# Note that the wildcards are matched against the file with absolute path, so to
# exclude all test directories for example use the pattern */test/*
EXCLUDE_PATTERNS =
EXCLUDE_PATTERNS = bosch_*
# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
# (namespaces, classes, functions, etc.) that should be excluded from the

View File

@ -48,7 +48,7 @@ mpu9150.cxx MPU9150Sample.java
mq2.cxx MQ2Sample.java
mq303a.cxx MQ303ASample.java
mq5.cxx MQ5Sample.java
my9221-ledbar.cxx MY9221_ledbarSample.java
groveledbar GroveLEDBar
nrf24l01-receiver.cxx NRF24L01_receiverSample.java
nrf24l01-transmitter.cxx NRF24L01_transmitterSample.java
nunchuck.cxx NUNCHUCKSample.java

View File

@ -234,15 +234,37 @@ if (MODBUS_FOUND)
include_directories(${MODBUS_INCLUDE_DIRS})
add_example (t3311)
add_example (hwxpxx)
add_example (h803x)
endif()
add_example (hdxxvxta)
add_example (rhusb)
add_example (apds9930)
add_example (kxcjk1013)
add_example (ssd1351)
add_example (bme280)
add_example (ds1808lc)
add_example (hlg150h)
add_example (lp8860)
add_example (max44009)
add_example (si1132)
add_example (si7005)
add_example (t6713)
add_example (cwlsxxa)
add_example (teams)
add_example (apa102)
add_example (tex00)
add_example (bmi160)
add_example (smartdrive)
if (HAVE_FIRMATA)
add_example (curieimu)
endif ()
if (BACNET_FOUND)
include_directories(${BACNET_INCLUDE_DIRS})
# we need access to bacnetmstp headers too
include_directories(${PROJECT_SOURCE_DIR}/src/bacnetmstp)
add_example (e50hx)
endif()
add_example (vcap)
# These are special cases where you specify example binary, source file and module(s)
include_directories (${PROJECT_SOURCE_DIR}/src)
@ -261,3 +283,10 @@ add_custom_example (ak8975-example ak8975.cxx mpu9150)
add_custom_example (mpu9250-example mpu9250.cxx mpu9150)
add_custom_example (groveledbar-example groveledbar.cxx my9221)
add_custom_example (grovecircularled-example grovecircularled.cxx my9221)
add_custom_example (temperature-sensor-example temperature-sensor.cxx "si7005;bmp180;bme280")
add_custom_example (humidity-sensor-example humidity-sensor.cxx "si7005;bme280")
add_custom_example (pressure-sensor-example pressure-sensor.cxx "bmp180;bme280")
add_custom_example (co2-sensor-example co2-sensor.cxx "t6713")
add_custom_example (adc-example adc-sensor.cxx "ads1x15")
add_custom_example (light-sensor-example light-sensor.cxx "si1132;max44009")
add_custom_example (light-controller-example light-controller.cxx "lp8860;ds1808lc;hlg150h")

View File

@ -0,0 +1,80 @@
/*
* Author: Henry Bruce <henry.bruce@intel.com>
* Copyright (c) 2015 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include "ads1015.h"
#include "mraa/gpio.hpp"
#define EDISON_I2C_BUS 1
#define FT4222_I2C_BUS 0
#define EDISON_GPIO_SI7005_CS 20
//! [Interesting]
// Simple example of using IADC to determine
// which sensor is present and return its name.
// IADC is then used to get readings from sensor
upm::IADC* getADC()
{
upm::IADC* adc = NULL;
try {
adc = new upm::ADS1015(EDISON_I2C_BUS);
mraa::Gpio gpio(EDISON_GPIO_SI7005_CS);
gpio.dir(mraa::DIR_OUT_HIGH);
return adc;
} catch (std::exception& e) {
std::cerr << "ADS1015: " << e.what() << std::endl;
}
return adc;
}
int main ()
{
upm::IADC* adc = getADC();
if (adc == NULL) {
std::cout << "ADC not detected" << std::endl;
return 1;
}
std::cout << "ADC " << adc->getModuleName() << " detected. " ;
std::cout << adc->getNumInputs() << " inputs available" << std::endl;
while (true) {
for (unsigned int i=0; i<adc->getNumInputs(); ++i) {
std::cout << "Input " << i;
try {
float voltage = adc->getVoltage(i);
std::cout << ": Voltage = " << voltage << "V" << std::endl;
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
}
sleep(1);
}
delete adc;
return 0;
}
//! [Interesting]

View File

@ -286,7 +286,7 @@ int main()
else ads->setCompMode();
break;
case 18:
cout << ads->getCompLatch() << cout;
cout << ads->getCompLatch() << endl;
break;
case 19:
cout << "select one of the following:" << endl;
@ -296,7 +296,7 @@ int main()
else ads->setCompLatch();
break;
case 20:
cout << ads->getContinuous() << cout;
cout << ads->getContinuous() << endl;
break;
case 21:
cout << "select one of the following:" << endl;

51
examples/c++/apa102.cxx Normal file
View File

@ -0,0 +1,51 @@
/*
* Author: Yannick Adam <yannick.adam@gmail.com>
* Copyright (c) 2016 Yannick Adam
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "apa102.h"
#include <iostream>
#include <signal.h>
#include <unistd.h>
using namespace std;
int
main(int argc, char** argv)
{
//! [Interesting]
// Instantiate a strip of 30 LEDs on SPI bus 0
upm::APA102* ledStrip = new upm::APA102(800, 0);
// Set all LEDs to Red
ledStrip->setAllLeds(31, 255, 0, 0);
// Set a section (10 to 20) to blue
ledStrip->setLeds(10, 20, 31, 0, 0, 255);
// Set a single LED to green
ledStrip->setLed(15, 31, 0, 255, 0);
delete ledStrip;
//! [Interesting]
return 0;
}

51
examples/c++/bme280.cxx Normal file
View File

@ -0,0 +1,51 @@
/*
* Author: Henry Bruce <henry.bruce@intel.com>
* Copyright (c) 2015 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include "bme280.h"
#define FT4222_I2C_BUS 0
int main ()
{
try {
upm::BME280* bme280 = new upm::BME280 (mraa_get_sub_platform_id(FT4222_I2C_BUS));
while (true) {
int temperature = bme280->getTemperatureCelcius();
int humidity = bme280->getHumidityRelative();
int pressure = bme280->getPressurePa();
std::cout << "Temperature = " << temperature << "C" << std::endl;
std::cout << "Humidity = " << humidity << "%" << std::endl;
std::cout << "Pressure = " << pressure << "Pa" << std::endl;
sleep(1);
}
delete bme280;
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
//! [Interesting]

82
examples/c++/bmi160.cxx Normal file
View File

@ -0,0 +1,82 @@
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include <signal.h>
#include "bmi160.h"
using namespace std;
int shouldRun = true;
void sig_handler(int signo)
{
if (signo == SIGINT)
shouldRun = false;
}
int main(int argc, char **argv)
{
signal(SIGINT, sig_handler);
//! [Interesting]
// Instantiate a BMI160 instance using default i2c bus and address
upm::BMI160 *sensor = new upm::BMI160();
while (shouldRun)
{
// update our values from the sensor
sensor->update();
float dataX, dataY, dataZ;
sensor->getAccelerometer(&dataX, &dataY, &dataZ);
cout << "Accelerometer: ";
cout << "AX: " << dataX << " AY: " << dataY << " AZ: "
<< dataZ << endl;
sensor->getGyroscope(&dataX, &dataY, &dataZ);
cout << "Gryoscope: ";
cout << "GX: " << dataX << " GY: " << dataY << " GZ: "
<< dataZ << endl;
sensor->getMagnetometer(&dataX, &dataY, &dataZ);
cout << "Magnetometer: ";
cout << "MX: " << dataX << " MY: " << dataY << " MZ: "
<< dataZ << endl;
cout << endl;
usleep(500000);
}
//! [Interesting]
cout << "Exiting..." << endl;
delete sensor;
return 0;
}

View File

@ -0,0 +1,71 @@
/*
* Author: Henry Bruce <henry.bruce@intel.com>
* Copyright (c) 2015 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include "t6713.h"
#define EDISON_I2C_BUS 1
#define FT4222_I2C_BUS 0
//! [Interesting]
// Simple example of using ICO2Sensor to determine
// which sensor is present and return its name.
// ICO2Sensor is then used to get readings from sensor
upm::ICO2Sensor* getCO2Sensor()
{
upm::ICO2Sensor* cO2Sensor = NULL;
try {
cO2Sensor = new upm::T6713(mraa_get_sub_platform_id(FT4222_I2C_BUS));
return cO2Sensor;
} catch (std::exception& e) {
std::cerr << "T6713: " << e.what() << std::endl;
}
return cO2Sensor;
}
int main ()
{
upm::ICO2Sensor* cO2Sensor = getCO2Sensor();
if (cO2Sensor == NULL) {
std::cout << "CO2 sensor not detected" << std::endl;
return 1;
}
std::cout << "CO2 sensor " << cO2Sensor->getModuleName() << " detected" << std::endl;
while (true) {
try {
uint16_t value = cO2Sensor->getPpm();
std::cout << "CO2 level = " << value << " ppm" << std::endl;
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
sleep(1);
}
delete cO2Sensor;
return 0;
}
//! [Interesting]

82
examples/c++/cwlsxxa.cxx Normal file
View File

@ -0,0 +1,82 @@
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include <signal.h>
#include "cwlsxxa.h"
using namespace std;
bool shouldRun = true;
void sig_handler(int signo)
{
if (signo == SIGINT)
shouldRun = false;
}
int main(int argc, char **argv)
{
signal(SIGINT, sig_handler);
//! [Interesting]
cout << "Initializing..." << endl;
// Instantiate an CWLSXXA instance, using A0 for CO2, A1 for
// humidity and A2 for temperature
upm::CWLSXXA *sensor = new upm::CWLSXXA(0, 1, 2);
// update and print available values every second
while (shouldRun)
{
// update our values from the sensor
sensor->update();
// we show both C and F for temperature
cout << "Temperature: " << sensor->getTemperature()
<< " C / " << sensor->getTemperature(true) << " F"
<< endl;
cout << "Humidity: " << sensor->getHumidity()
<< " %" << endl;
cout << "CO2: " << sensor->getCO2()
<< " ppm" << endl;
cout << endl;
sleep(1);
}
cout << "Exiting..." << endl;
delete sensor;
//! [Interesting]
return 0;
}

51
examples/c++/ds1808lc.cxx Normal file
View File

@ -0,0 +1,51 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <string>
#include "ds1808lc.h"
#define EDISON_I2C_BUS 1 // Edison I2C-1
#define DS1808_GPIO_PWR 15 // Edison GP165
void printState(upm::ILightController *lightController)
{
if (lightController->isPowered())
{
std::cout << "Light is powered, brightness = " << lightController->getBrightness() << std::endl;
}
else
{
std::cout << "Light is not powered." << std::endl;
}
}
int main( int argc, char **argv )
{
int status = 0;
upm::ILightController* lightController;
try {
lightController = new upm::DS1808LC(DS1808_GPIO_PWR, EDISON_I2C_BUS);
std::cout << "Existing state: "; printState(lightController);
if (argc == 2)
{
std::string arg = argv[1];
int brightness = ::atoi(argv[1]);
if (brightness > 0) {
lightController->setPowerOn();
lightController->setBrightness(brightness);
} else
lightController->setPowerOff();
}
std::cout << "Now: ";printState(lightController);
} catch (std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
status = 1;
}
delete lightController;
return status;
}

112
examples/c++/e50hx.cxx Normal file
View File

@ -0,0 +1,112 @@
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include <signal.h>
#include "e50hx.h"
using namespace std;
using namespace upm;
bool shouldRun = true;
void sig_handler(int signo)
{
if (signo == SIGINT)
shouldRun = false;
}
int main(int argc, char **argv)
{
signal(SIGINT, sig_handler);
//! [Interesting]
// You will need to edit this example to conform to your site and your
// devices, specifically the Device Object Instance ID passed to the
// constructor, and the arguments to initMaster() that are
// appropriate for your BACnet network.
string defaultDev = "/dev/ttyUSB0";
// if an argument was specified, use it as the device instead
if (argc > 1)
defaultDev = string(argv[1]);
cout << "Using device " << defaultDev << endl;
cout << "Initializing..." << endl;
// Instantiate an E50HX object for an E50HX device that has 1075425
// as it's unique Device Object Instance ID. NOTE: You will
// certainly want to change this to the correct value for your
// device(s).
E50HX *sensor = new E50HX(1075425);
// Initialize our BACnet master, if it has not already been
// initialized, with the device and baudrate, choosing 1000001 as
// our unique Device Object Instance ID, 2 as our MAC address and
// using default values for maxMaster and maxInfoFrames
sensor->initMaster(defaultDev, 38400, 1000001, 2);
// Uncomment to enable debugging output
// sensor->setDebug(true);
cout << endl;
cout << "Device Description: " << sensor->getDescription() << endl;
cout << "Device Location: " << sensor->getLocation() << endl;
cout << endl;
// update and print a few values every 5 seconds
while (shouldRun)
{
cout << "System Voltage: "
<< sensor->getAnalogValue(E50HX::AV_System_Voltage)
<< " " << sensor->getAnalogValueUnits(E50HX::AV_System_Voltage)
<< endl;
cout << "System Type: "
<< sensor->getAnalogValue(E50HX::AV_System_Type)
<< endl;
cout << "Energy Consumption: " << sensor->getAnalogInput(E50HX::AI_Energy)
<< " " << sensor->getAnalogInputUnits(E50HX::AI_Energy)
<< endl;
cout << "Power Up Counter: "
<< sensor->getAnalogInput(E50HX::AI_Power_Up_Count)
<< endl;
cout << endl;
sleep(5);
}
cout << "Exiting..." << endl;
delete sensor;
//! [Interesting]
return 0;
}

149
examples/c++/h803x.cxx Normal file
View File

@ -0,0 +1,149 @@
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include <signal.h>
#include "h803x.h"
using namespace std;
bool shouldRun = true;
void sig_handler(int signo)
{
if (signo == SIGINT)
shouldRun = false;
}
int main(int argc, char **argv)
{
signal(SIGINT, sig_handler);
//! [Interesting]
string defaultDev = "/dev/ttyUSB0";
// if an argument was specified, use it as the device instead
if (argc > 1)
defaultDev = string(argv[1]);
cout << "Using device " << defaultDev << endl;
cout << "Initializing..." << endl;
// Instantiate an H803X instance, using MODBUS slave address 1, and
// default comm parameters (9600, 8, N, 2)
upm::H803X *sensor = new upm::H803X(defaultDev, 1);
// output the Slave ID string
cout << "Slave ID: " << sensor->getSlaveID() << endl;
cout << endl;
// update and print available values every second
while (shouldRun)
{
// update our values from the sensor
sensor->update();
// H8035 / H8036
cout << "Consumption (kWh): " << sensor->getConsumption() << endl;
cout << "Real Power (kW): " << sensor->getRealPower() << endl;
if (sensor->isH8036())
{
// The H8036 has much more data available...
cout << "Reactive Power (kVAR): " << sensor->getReactivePower()
<< endl;
cout << "Apparent Power (kVA): " << sensor->getApparentPower()
<< endl;
cout << "Power Factor: " << sensor->getPowerFactor()
<< endl;
cout << "Volts Line to Line: " << sensor->getVoltsLineToLine()
<< endl;
cout << "Volts Line to Neutral: " << sensor->getVoltsLineToNeutral()
<< endl;
cout << "Current: " << sensor->getCurrent()
<< endl;
cout << "Real Power Phase A (kW): " << sensor->getRealPowerPhaseA()
<< endl;
cout << "Real Power Phase B (kW): " << sensor->getRealPowerPhaseB()
<< endl;
cout << "Real Power Phase C (kW): " << sensor->getRealPowerPhaseC()
<< endl;
cout << "Power Factor Phase A: " << sensor->getPowerFactorPhaseA()
<< endl;
cout << "Power Factor Phase B: " << sensor->getPowerFactorPhaseB()
<< endl;
cout << "Power Factor Phase C: " << sensor->getPowerFactorPhaseC()
<< endl;
cout << "Volts Phase A to B: " << sensor->getVoltsPhaseAToB()
<< endl;
cout << "Volts Phase B to C: " << sensor->getVoltsPhaseBToC()
<< endl;
cout << "Volts Phase A to C: " << sensor->getVoltsPhaseAToC()
<< endl;
cout << "Volts Phase A to Neutral: "
<< sensor->getVoltsPhaseAToNeutral()
<< endl;
cout << "Volts Phase B to Neutral: "
<< sensor->getVoltsPhaseBToNeutral()
<< endl;
cout << "Volts Phase C to Neutral: "
<< sensor->getVoltsPhaseCToNeutral()
<< endl;
cout << "Current Phase A: " << sensor->getCurrentPhaseA()
<< endl;
cout << "Current Phase B: " << sensor->getCurrentPhaseB()
<< endl;
cout << "Current Phase C: " << sensor->getCurrentPhaseC()
<< endl;
cout << "Avg Real Power (kW): " << sensor->getAvgRealPower()
<< endl;
cout << "Min Real Power (kW): " << sensor->getMinRealPower()
<< endl;
cout << "Max Real Power (kW): " << sensor->getMaxRealPower()
<< endl;
}
cout << endl;
sleep(2);
}
cout << "Exiting..." << endl;
delete sensor;
//! [Interesting]
return 0;
}

51
examples/c++/hlg150h.cxx Normal file
View File

@ -0,0 +1,51 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <string>
#include "hlg150h.h"
#define HLG150H_GPIO_RELAY 21
#define HLG150H_GPIO_PWM 22
void printState(upm::ILightController *lightController)
{
if (lightController->isPowered())
{
std::cout << "Light is powered, brightness = " << lightController->getBrightness() << std::endl;
}
else
{
std::cout << "Light is not powered." << std::endl;
}
}
int main( int argc, char **argv )
{
int status = 0;
upm::ILightController* lightController;
try {
lightController = new upm::HLG150H(HLG150H_GPIO_RELAY, HLG150H_GPIO_PWM);
std::cout << "Existing state: "; printState(lightController);
if (argc == 2)
{
std::string arg = argv[1];
int brightness = ::atoi(argv[1]);
if (brightness > 0) {
lightController->setPowerOn();
lightController->setBrightness(brightness);
} else
lightController->setPowerOff();
}
std::cout << "Now: ";printState(lightController);
delete lightController;
} catch (std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
status = 1;
}
return status;
}

View File

@ -135,7 +135,7 @@ int main (int argc, char **argv)
if (rv > 0)
cout << "Received: " << radioBuffer << endl;
if (rv < 0) // some sort of read error occured
if (rv < 0) // some sort of read error occurred
{
cerr << "Port read error." << endl;
break;

View File

@ -0,0 +1,82 @@
/*
* Author: Henry Bruce <henry.bruce@intel.com>
* Copyright (c) 2015 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include "si7005.h"
#include "bme280.h"
#define EDISON_I2C_BUS 1
#define FT4222_I2C_BUS 0
#define EDISON_GPIO_SI7005_CS 20
//! [Interesting]
// Simple example of using ILightSensor to determine
// which sensor is present and return its name.
// ILightSensor is then used to get readings from sensor
upm::IHumiditySensor* getHumiditySensor()
{
upm::IHumiditySensor* humiditySensor = NULL;
try {
humiditySensor = new upm::BME280 (mraa_get_sub_platform_id(FT4222_I2C_BUS));
return humiditySensor ;
} catch (std::exception& e)
{
std::cerr <<"BME280: "<<e.what() << std::endl;
}
try {
humiditySensor = new upm::SI7005(EDISON_I2C_BUS, EDISON_GPIO_SI7005_CS);
return humiditySensor;
} catch (std::exception& e) {
std::cerr << "SI7005: " << e.what() << std::endl;
}
return humiditySensor;
}
int main ()
{
upm::IHumiditySensor* humiditySensor = getHumiditySensor();
if (humiditySensor == NULL) {
std::cout << "Humidity sensor not detected" << std::endl;
return 1;
}
std::cout << "Humidity sensor " << humiditySensor->getModuleName() << " detected" << std::endl;
while (true) {
try {
int value = humiditySensor->getHumidityRelative();
std::cout << "Humidity = " << value << "%" << std::endl;
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
sleep(1);
}
delete humiditySensor;
return 0;
}
//! [Interesting]

View File

@ -0,0 +1,98 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <string>
#include "lp8860.h"
#include "ds1808lc.h"
#include "hlg150h.h"
#define EDISON_I2C_BUS 1 // Edison I2C-1
#define GPIO_SI7005_CS 20 // Edison GP12
#define HLG150H_GPIO_RELAY 21
#define HLG150H_GPIO_PWM 22
#define LP8860_GPIO_PWR 45 // Edison GP45
#define DS1808_GPIO_PWR 15 // Edison GP165
#define DS1808_GPIO_EDISON_LIVE 36 // Edison GP14
//! [Interesting]
// Simple example of using ILightController to determine
// which controller is present and return its name.
// ILightController is then used to get readings from sensor
upm::ILightController* getLightController()
{
upm::ILightController* lightController = NULL;
try {
lightController = new upm::LP8860(LP8860_GPIO_PWR, EDISON_I2C_BUS);
return lightController;
} catch (std::exception& e) {
std::cerr << "LP8860: " << e.what() << std::endl;
}
try {
lightController = new upm::DS1808LC(DS1808_GPIO_PWR, EDISON_I2C_BUS);
return lightController;
} catch (std::exception& e) {
std::cerr << "DS1808LC: " << e.what() << std::endl;
}
try {
lightController = new upm::HLG150H(HLG150H_GPIO_RELAY, HLG150H_GPIO_PWM);
return lightController;
} catch (std::exception& e) {
std::cerr << "HLG150H: " << e.what() << std::endl;
}
return lightController;
}
void printState(upm::ILightController *lightController)
{
if (lightController->isPowered())
{
std::cout << "Light is powered, brightness = " << lightController->getBrightness() << std::endl;
}
else
{
std::cout << "Light is not powered." << std::endl;
}
}
int main( int argc, char **argv )
{
int status = 0;
// MraaUtils::setGpio(GPIO_SI7005_CS, 1);
upm::ILightController *lightController = getLightController();
if (lightController != NULL)
{
std::cout << "Detected light controller " << lightController->getModuleName() << std::endl;
}
else
{
std::cerr << "Error. Unsupported platform." << std::endl;
return 1;
}
try {
std::cout << "Existing state: "; printState(lightController);
if (argc == 2)
{
std::string arg = argv[1];
int brightness = ::atoi(argv[1]);
if (brightness > 0) {
lightController->setPowerOn();
lightController->setBrightness(brightness);
} else
lightController->setPowerOff();
}
std::cout << "Now: ";printState(lightController);
} catch (std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
status = 1;
}
delete lightController;
return status;
}

View File

@ -0,0 +1,78 @@
/*
* Author: Henry Bruce <henry.bruce@intel.com>
* Copyright (c) 2015 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include "max44009.h"
#include "si1132.h"
#define EDISON_I2C_BUS 1
#define FT4222_I2C_BUS 0
//! [Interesting]
// Simple example of using ILightSensor to determine
// which sensor is present and return its name.
// ILightSensor is then used to get readings from sensor
upm::ILightSensor* getLightSensor()
{
upm::ILightSensor* lightSensor = NULL;
try {
lightSensor = new upm::SI1132(mraa_get_sub_platform_id(FT4222_I2C_BUS));
return lightSensor;
} catch (std::exception& e) {
std::cerr << "SI1132: " << e.what() << std::endl;
}
try {
lightSensor = new upm::MAX44009(EDISON_I2C_BUS);
return lightSensor;
} catch (std::exception& e) {
std::cerr << "MAX44009: " << e.what() << std::endl;
}
return lightSensor;
}
int main ()
{
upm::ILightSensor* lightSensor = getLightSensor();
if (lightSensor == NULL) {
std::cout << "Light sensor not detected" << std::endl;
return 1;
}
std::cout << "Light sensor " << lightSensor->getModuleName() << " detected" << std::endl;
while (true) {
try {
float value = lightSensor->getVisibleLux();
std::cout << "Light level = " << value << " lux" << std::endl;
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
sleep(1);
}
delete lightSensor;
return 0;
}
//! [Interesting]

52
examples/c++/lp8860.cxx Normal file
View File

@ -0,0 +1,52 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <string>
#include "lp8860.h"
#define EDISON_I2C_BUS 1 // Edison I2C-1
#define LP8860_GPIO_PWR 45 // Edison GP45
void printState(upm::ILightController *lightController)
{
if (lightController->isPowered())
{
std::cout << "Light is powered, brightness = " << lightController->getBrightness() << std::endl;
}
else
{
std::cout << "Light is not powered." << std::endl;
}
}
int main( int argc, char **argv )
{
int status = 0;
upm::LP8860* lightController;
try {
lightController = new upm::LP8860(LP8860_GPIO_PWR, EDISON_I2C_BUS);
std::cout << "Existing state: "; printState(lightController);
if (argc == 2)
{
std::string arg = argv[1];
int brightness = ::atoi(argv[1]);
if (brightness > 0) {
lightController->setPowerOn();
lightController->setBrightness(brightness);
} else
lightController->setPowerOff();
}
std::cout << "Now: ";printState(lightController);
delete lightController;
} catch (std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
status = 1;
}
return status;
}

46
examples/c++/max44009.cxx Normal file
View File

@ -0,0 +1,46 @@
/*
* Author: Henry Bruce <henry.bruce@intel.com>
* Copyright (c) 2015 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include "max44009.h"
#define EDISON_I2C_BUS 1
int main ()
{
try {
upm::MAX44009* lightSensor = new upm::MAX44009(EDISON_I2C_BUS);
while (true) {
float value = lightSensor->getVisibleLux();
std::cout << "Light level = " << value << " lux" << std::endl;
sleep(1);
}
delete lightSensor;
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}

View File

@ -0,0 +1,81 @@
/*
* Author: Henry Bruce <henry.bruce@intel.com>
* Copyright (c) 2015 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include "bmp180.h"
#include "bme280.h"
#define EDISON_I2C_BUS 1
#define FT4222_I2C_BUS 0
//! [Interesting]
// Simple example of using ILightSensor to determine
// which sensor is present and return its name.
// ILightSensor is then used to get readings from sensor
upm::IPressureSensor* getPressureSensor()
{
upm::IPressureSensor* pressureSensor = NULL;
try {
pressureSensor = new upm::BME280 (mraa_get_sub_platform_id(FT4222_I2C_BUS));
return pressureSensor ;
} catch (std::exception& e)
{
std::cerr <<"BME280: "<<e.what() << std::endl;
}
try {
pressureSensor = new upm::BMP180(EDISON_I2C_BUS);
return pressureSensor;
} catch (std::exception& e) {
std::cerr << "BMP180: " << e.what() << std::endl;
}
return pressureSensor;
}
int main ()
{
upm::IPressureSensor* pressureSensor = getPressureSensor();
if (pressureSensor == NULL) {
std::cout << "Pressure sensor not detected" << std::endl;
return 1;
}
std::cout << "Pressure sensor " << pressureSensor->getModuleName() << " detected" << std::endl;
while (true) {
try {
int value = pressureSensor->getPressurePa();
std::cout << "Pressure = " << value << " Pa" << std::endl;
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
sleep(1);
}
delete pressureSensor;
return 0;
}
//! [Interesting]

46
examples/c++/si1132.cxx Normal file
View File

@ -0,0 +1,46 @@
/*
* Author: Henry Bruce <henry.bruce@intel.com>
* Copyright (c) 2015 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include "si1132.h"
#define FT4222_I2C_BUS 1
int main ()
{
try {
upm::SI1132* lightSensor = new upm::SI1132(mraa_get_sub_platform_id(FT4222_I2C_BUS));
while (true) {
float value = lightSensor->getVisibleLux();
std::cout << "Light level = " << value << " lux" << std::endl;
sleep(1);
}
delete lightSensor;
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}

51
examples/c++/si7005.cxx Normal file
View File

@ -0,0 +1,51 @@
/*
* Author: Henry Bruce <henry.bruce@intel.com>
* Copyright (c) 2015 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include "si7005.h"
#define EDISON_I2C_BUS 1
#define EDISON_GPIO_SI7005_CS 20
int main ()
{
try {
upm::SI7005* sensor = new upm::SI7005(EDISON_I2C_BUS, EDISON_GPIO_SI7005_CS);
while (true) {
int temperature = sensor->getTemperatureCelcius();
int humidity = sensor->getHumidityRelative();
std::cout << "Temperature = " << temperature << "C" << std::endl;
std::cout << "Humidity = " << humidity << "%" << std::endl;
sleep(1);
}
delete sensor;
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
//! [Interesting]

View File

@ -0,0 +1,75 @@
/*
* The MIT License (MIT)
*
* Author: Oussema Harbi <oussema.elharbi@gmail.com>
* Copyright (c) <2016> <Oussema Harbi>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include "smartdrive.h"
#include <signal.h>
upm::SmartDrive *drive = NULL;
void
sig_handler(int signo)
{
printf("got signal\n");
if (signo == SIGINT) {
printf("exiting application\n");
if (drive != NULL)
delete drive;
exit (0);
}
}
int
main(int argc, char **argv)
{
float voltage = 0;
std::cout << "SmartDrive demo is starting. Please make sure drive is connected to board" << std::endl;
sleep(2); //Wait for 2 seconds in case you want to fix your h/w setup
//! [Interesting]
// Instantiate a SmartDrive connected to /dev/i2c-0 bus, using DefaultAddress
drive = new upm::SmartDrive(0);
std::cout << "Battery Voltage before motor run : " << drive->GetBattVoltage() << std::endl;
//Set motor M1 to run for 120 seconds, with speed of 15RPM, waith for it to finish and then Brake It
drive->Run_Seconds(SmartDrive_Motor_ID_1, SmartDrive_Dir_Forward, 15, 120, true, SmartDrive_Action_Brake);
std::cout << "Battery Voltage after motor run : " << drive->GetBattVoltage() << std::endl;
//Rotate motor M2 2270 degrees, in reverse sense, with speed of 10RPM, return immediately from function call
drive->Run_Degrees(SmartDrive_Motor_ID_2, SmartDrive_Dir_Reverse, 10, 2270, false, SmartDrive_Action_Float);
//While motor is running, Display its status
drive->PrintMotorStatus(SmartDrive_Motor_ID_2);
sleep(2); //Sleep for 2 seconds
//Stop motor M2 and then finish program
drive->StopMotor(SmartDrive_Motor_ID_2, SmartDrive_Action_BrakeHold);
//! [Interesting]
std::cout << "Demo complete. GoodBye" << std::endl;
delete drive;
drive = NULL;
return 0;
}

View File

@ -29,7 +29,7 @@
#include "ssd1306.h"
#define DEVICE_ADDRESS 0x3C
#define BUS_NUMBER 0x6
#define BUS_NUMBER 0x0
static uint8_t intel_logo[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

48
examples/c++/t6713.cxx Normal file
View File

@ -0,0 +1,48 @@
/*
* Author: Henry Bruce <henry.bruce@intel.com>
* Copyright (c) 2015 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include "t6713.h"
#define FT4222_I2C_BUS 0
int main ()
{
try {
upm::T6713* cO2Sensor = new upm::T6713(mraa_get_sub_platform_id(FT4222_I2C_BUS));
while (true) {
uint16_t value = cO2Sensor->getPpm();
std::cout << "CO2 level = " << value << " ppm" << std::endl;
sleep(1);
}
delete cO2Sensor;
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}

84
examples/c++/teams.cxx Normal file
View File

@ -0,0 +1,84 @@
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include <signal.h>
#include "teams.h"
using namespace std;
bool shouldRun = true;
void sig_handler(int signo)
{
if (signo == SIGINT)
shouldRun = false;
}
int main(int argc, char **argv)
{
signal(SIGINT, sig_handler);
//! [Interesting]
cout << "Initializing..." << endl;
// Instantiate an TEAMS instance, using A0 for temperature, and
// 165.0 ohms for the rResistor value (for the libelium 4-20ma
// interface)
upm::TEAMS *sensor = new upm::TEAMS(0, 165.0);
// update and print available values every second
while (shouldRun)
{
// update our values from the sensor
sensor->update();
// is the sensor connected? (current >= 4ma)
cout << "Is Connected: " << sensor->isConnected() << endl;
// print computed current on the loop. This includes the offset,
// if one was set by setOffsetMilliamps().
cout << "Milliamps: " << sensor->getRawMilliamps() << endl;
// we show both C and F for temperature
cout << "Temperature: " << sensor->getTemperature()
<< " C / " << sensor->getTemperature(true) << " F"
<< endl;
cout << endl;
sleep(1);
}
cout << "Exiting..." << endl;
delete sensor;
//! [Interesting]
return 0;
}

View File

@ -0,0 +1,90 @@
/*
* Author: Henry Bruce <henry.bruce@intel.com>
* Copyright (c) 2015 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include "si7005.h"
#include "bmp180.h"
#include "bme280.h"
#define EDISON_I2C_BUS 1
#define FT4222_I2C_BUS 0
#define EDISON_GPIO_SI7005_CS 20
//! [Interesting]
// Simple example of using ITemperatureSensor to determine
// which sensor is present and return its name.
// ITemperatureSensor is then used to get readings from sensor
upm::ITemperatureSensor* getTemperatureSensor()
{
upm::ITemperatureSensor* temperatureSensor = NULL;
try {
temperatureSensor = new upm::BME280 (mraa_get_sub_platform_id(FT4222_I2C_BUS));
return temperatureSensor;
} catch (std::exception& e)
{
std::cerr <<"BME280: "<<e.what() << std::endl;
}
try {
temperatureSensor = new upm::SI7005(EDISON_I2C_BUS, EDISON_GPIO_SI7005_CS);
return temperatureSensor;
} catch (std::exception& e) {
std::cerr << "SI7005: " << e.what() << std::endl;
}
try {
temperatureSensor = new upm::BMP180(EDISON_I2C_BUS);
return temperatureSensor;
} catch (std::exception& e) {
std::cerr << "BMP180: " << e.what() << std::endl;
}
return temperatureSensor;
}
int main ()
{
upm::ITemperatureSensor* temperatureSensor = getTemperatureSensor();
if (temperatureSensor == NULL) {
std::cout << "Temperature sensor not detected" << std::endl;
return 1;
}
std::cout << "Temperature sensor " << temperatureSensor->getModuleName() << " detected" << std::endl;
while (true) {
try {
int value = temperatureSensor->getTemperatureCelcius();
std::cout << "Temperature = " << value << "C" << std::endl;
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
sleep(1);
}
delete temperatureSensor;
return 0;
}
//! [Interesting]

91
examples/c++/tex00.cxx Normal file
View File

@ -0,0 +1,91 @@
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include <signal.h>
#include "tex00.h"
using namespace std;
bool shouldRun = true;
void sig_handler(int signo)
{
if (signo == SIGINT)
shouldRun = false;
}
int main(int argc, char **argv)
{
signal(SIGINT, sig_handler);
//! [Interesting]
cout << "Initializing..." << endl;
// Instantiate an TEX00 instance, using A0 for the analog input. In
// this example, we are using a 10K Ohm balance resistor and a TED
// (10k type 2) thermistor.
upm::TEX00 *sensor = new upm::TEX00(0, 10000,
upm::TEX00::STYPE_THERMISTOR_TED);
cout << "Minimum temperature: " << sensor->getTemperatureRangeMin()
<< " C" << endl;
cout << "Maximum temperature: " << sensor->getTemperatureRangeMax()
<< " C" << endl;
cout << endl;
// update and print available values every second
while (shouldRun)
{
// update our values from the sensor
sensor->update();
if (sensor->isOutOfRange())
{
cout << "Temperature out of range" << endl;
}
else
{
// we show both C and F for temperature
cout << "Temperature: " << sensor->getTemperature()
<< " C / " << sensor->getTemperature(true) << " F"
<< endl;
}
cout << endl;
sleep(1);
}
cout << "Exiting..." << endl;
delete sensor;
//! [Interesting]
return 0;
}

View File

@ -77,7 +77,7 @@ int main (int argc, char **argv)
if (rv > 0)
write(1, nmeaBuffer, rv);
if (rv < 0) // some sort of read error occured
if (rv < 0) // some sort of read error occurred
{
cerr << "Port read error." << endl;
break;

70
examples/c++/vcap.cxx Normal file
View File

@ -0,0 +1,70 @@
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include "vcap.hpp"
using namespace std;
int main(int argc, char **argv)
{
//! [Interesting]
string defaultDev = "/dev/video0";
// if an argument was specified, use it as the device instead
if (argc > 1)
defaultDev = string(argv[1]);
cout << "Using device " << defaultDev << endl;
cout << "Initializing..." << endl;
// Instantiate an VCAP instance, using the specified video device
upm::VCAP *sensor = new upm::VCAP(defaultDev);
// enable some debug/verbose output
sensor->setDebug(true);
// This is just a hint. The kernel can change this to a lower
// resolution that the hardware supports. Use getWidth() and
// getHeight() methods to see what the kernel actually chose if you
// care.
sensor->setResolution(1920, 1080);
// capture an image
sensor->captureImage();
// convert and save it as a jpeg
sensor->saveImage("video-img1.jpg");
cout << "Exiting..." << endl;
delete sensor;
//! [Interesting]
return 0;
}

View File

@ -0,0 +1,66 @@
/*
* Author: Abhishek Malik <abhishek.malik@intel.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import upm_am2315.AM2315;
public class AM2315Example {
static {
try {
System.loadLibrary("javaupm_am2315");
System.loadLibrary("mraajava");
} catch (UnsatisfiedLinkError e) {
System.err.println(
"Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" +
e);
System.exit(1);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//! [Interesting]
float humidity = 0;
float temperature = 0;
// Instantiate the sensor
AM2315 sensor = new AM2315(0, upm_am2315.javaupm_am2315Constants.AM2315_I2C_ADDRESS);
sensor.testSensor();
while(true){
// retrieving the humidity and temperature values
humidity = sensor.getHumidity();
temperature = sensor.getTemperature();
System.out.println("Temperature : "+temperature+" Humidity: "+humidity);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("The following exception occurred: "+e.getMessage());
}
}
//! [Interesting]
}
}

View File

@ -0,0 +1,44 @@
/*
* Author: Yannick Adam <yannick.adam@gmail.com>
* Copyright (c) 2016 Yannick Adam
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
public class APA102Sample {
public static void main(String[] args) throws InterruptedException {
// ! [Interesting]
// Instantiate a strip of 30 LEDs on SPI bus 0
upm_apa102.APA102 ledStrip =
new upm_apa102.APA102(30, (short)0, false, (byte)-1);
System.out.println("Set all LEDs to blue");
ledStrip.setAllLeds((short)31, (short)0, (short)0, (short)255);
System.out.println("Set LEDs between 10 and 20 to green");
ledStrip.setLeds(10, 20, (short)31, (short)0, (short)255, (short)0);
System.out.println("Set a single LED to red at index 15");
ledStrip.setLed(15, (short)31, (short)255, (short)0, (short)0);
// ! [Interesting]
}
}

View File

@ -25,18 +25,6 @@ import upm_ad8232.AD8232;
public class Ad8232Example {
static {
try {
System.loadLibrary("javaupm_ad8232");
System.loadLibrary("mraajava");
} catch (UnsatisfiedLinkError e) {
System.err.println(
"Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" +
e);
System.exit(1);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//! [Interesting]
@ -54,7 +42,7 @@ public class Ad8232Example {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("The following error has occured: "+e.getMessage());
System.out.println("The following error has occurred: "+e.getMessage());
}
}
}

View File

@ -38,7 +38,7 @@ public class Apds9002 {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("The following exception occured: "+e.getMessage());
System.out.println("The following exception occurred: "+e.getMessage());
}
}
//! [Interesting]

View File

@ -0,0 +1,78 @@
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import upm_bmi160.BMI160;
public class BMI160_Example
{
public static void main(String[] args) throws InterruptedException
{
// ! [Interesting]
System.out.println("Initializing...");
// Instantiate a BMI160 instance using default i2c bus and address
BMI160 sensor = new BMI160();
while (true)
{
// update our values from the sensor
sensor.update();
float dataA[] = sensor.getAccelerometer();
System.out.println("Accelerometer: "
+ "AX: "
+ dataA[0]
+ " AY: "
+ dataA[1]
+ " AZ: "
+ dataA[2]);
float dataG[] = sensor.getGyroscope();
System.out.println("Gryoscope: "
+ "GX: "
+ dataG[0]
+ " GY: "
+ dataG[1]
+ " GZ: "
+ dataG[2]);
float dataM[] = sensor.getMagnetometer();
System.out.println("Magnetometer: "
+ "MX: "
+ dataM[0]
+ " MY: "
+ dataM[1]
+ " MZ: "
+ dataM[2]);
System.out.println();
Thread.sleep(500);
}
// ! [Interesting]
}
}

View File

@ -6,13 +6,15 @@ macro(add_example example_name jar_name)
set(example_jar "${CMAKE_CURRENT_BINARY_DIR}/../../src/${jar_name}/upm_${jar_name}.jar")
add_jar(${example_name} SOURCES ${example_src} INCLUDE_JARS ${example_jar})
add_dependencies(${example_name} javaupm_${jar_name})
endmacro()
macro(add_example_with_path example_name jar_path)
macro(add_example_with_path example_name jar_path jar_name)
set(example_src "${example_name}.java")
set(example_jar "${CMAKE_CURRENT_BINARY_DIR}/../../src/${jar_path}")
set(example_jar "${CMAKE_CURRENT_BINARY_DIR}/../../src/${jar_path}/upm_${jar_name}.jar")
add_jar(${example_name} SOURCES ${example_src} INCLUDE_JARS ${example_jar})
add_dependencies(${example_name} javaupm_${jar_name})
endmacro()
add_example(A110X_intrSample a110x)
@ -105,12 +107,25 @@ add_example(Ad8232Example ad8232)
add_example(Gp2y0aExample gp2y0a)
add_example(Th02Example th02)
add_example(FlexSensorExample flex)
add_example(CWLSXXA_Example cwlsxxa)
add_example(TEAMS_Example teams)
add_example(APA102Sample apa102)
add_example(TEX00_Example tex00)
add_example(BMI160_Example bmi160)
add_example(Tsl2561 tsl2561)
add_example(AM2315Example am2315)
if (MODBUS_FOUND)
add_example(H803X_Example h803x)
endif()
if (BACNET_FOUND)
add_example(E50HX_Example e50hx)
endif()
add_example(VCAP_Example vcap)
add_example_with_path(Jhd1313m1_lcdSample lcd/upm_i2clcd.jar)
add_example_with_path(Jhd1313m1Sample lcd/upm_i2clcd.jar)
add_example_with_path(Lcm1602_i2cSample lcd/upm_i2clcd.jar)
add_example_with_path(Lcm1602_parallelSample lcd/upm_i2clcd.jar)
add_example_with_path(SSD1308_oledSample lcd/upm_i2clcd.jar)
add_example_with_path(SSD1327_oledSample lcd/upm_i2clcd.jar)
add_example_with_path(Jhd1313m1_lcdSample lcd i2clcd)
add_example_with_path(Jhd1313m1Sample lcd i2clcd)
add_example_with_path(Lcm1602_i2cSample lcd i2clcd)
add_example_with_path(Lcm1602_parallelSample lcd i2clcd)
add_example_with_path(SSD1308_oledSample lcd i2clcd)
add_example_with_path(SSD1327_oledSample lcd i2clcd)

View File

@ -0,0 +1,62 @@
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import upm_cwlsxxa.CWLSXXA;
public class CWLSXXA_Example
{
public static void main(String[] args) throws InterruptedException
{
// ! [Interesting]
// Instantiate an CWLSXXA instance, using A0 for CO2, A1 for
// humidity and A2 for temperature
CWLSXXA sensor = new CWLSXXA(0, 1, 2);
while (true)
{
// update our values from the sensor
sensor.update();
// we show both C and F for temperature
System.out.println("Temperature: "
+ sensor.getTemperature()
+ " C / "
+ sensor.getTemperature(true)
+ " F");
System.out.println("Humidity: "
+ sensor.getHumidity()
+ " %");
System.out.println("CO2: "
+ sensor.getCO2()
+ " ppm");
Thread.sleep(1000);
}
// ! [Interesting]
}
}

View File

@ -0,0 +1,90 @@
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import upm_e50hx.E50HX;
public class E50HX_Example
{
private static String defaultDev = "/dev/ttyUSB0";
public static void main(String[] args) throws InterruptedException
{
// ! [Interesting]
// You will need to edit this example to conform to your site
// and your devices, specifically the Device Object Instance
// ID passed to the constructor, and the arguments to
// initMaster() that are appropriate for your BACnet network.
if (args.length > 0)
defaultDev = args[0];
System.out.println("Using device " + defaultDev);
System.out.println("Initializing...");
// Instantiate an E50HX object for an E50HX device that has
// 1075425 as it's unique Device Object Instance ID. NOTE:
// You will certainly want to change this to the correct value
// for your device(s).
E50HX sensor = new E50HX(1075425);
// Initialize our BACnet master, if it has not already been
// initialized, with the device and baudrate, choosing 1000001 as
// our unique Device Object Instance ID, 2 as our MAC address and
// using default values for maxMaster and maxInfoFrames
sensor.initMaster(defaultDev, 38400, 1000001, 2);
// Uncomment to enable debugging output
// sensor.setDebug(true);
System.out.println();
System.out.println("Device Description: " + sensor.getDescription());
System.out.println("Device Location: " + sensor.getLocation());
System.out.println();
// update and print a few values every 5 seconds
while (true)
{
System.out.println("System Voltage: "
+ sensor.getAnalogValue(E50HX.ANALOG_VALUES_T.AV_System_Voltage)
+ " "
+ sensor.getAnalogValueUnits(E50HX.ANALOG_VALUES_T.AV_System_Voltage));
System.out.println("System Type: "
+ sensor.getAnalogValue(E50HX.ANALOG_VALUES_T.AV_System_Type));
System.out.println("Energy Consumption: "
+ sensor.getAnalogInput(E50HX.ANALOG_INPUTS_T.AI_Energy)
+ " "
+ sensor.getAnalogInputUnits(E50HX.ANALOG_INPUTS_T.AI_Energy));
System.out.println("Power Up Counter: "
+ sensor.getAnalogInput(E50HX.ANALOG_INPUTS_T.AI_Power_Up_Count));
System.out.println();
Thread.sleep(5000);
}
// ! [Interesting]
}
}

View File

@ -59,7 +59,7 @@ public class Gp2y0aExample {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("The following exception occured: "+e.getMessage());
System.out.println("The following exception occurred: "+e.getMessage());
}
}
//! [Interesting]

View File

@ -39,7 +39,7 @@ public class GroveEmg {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("The following exception occured: "+e.getMessage());
System.out.println("The following exception occurred: "+e.getMessage());
}
}
}

View File

@ -41,7 +41,7 @@ public class GroveGsr {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("The following exception occured: "+e.getMessage());
System.out.println("The following exception occurred: "+e.getMessage());
}
}
//! [Interesting]

View File

@ -38,7 +38,7 @@ public class GroveO2Example {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("The following exception has occured: "+e.getMessage());
System.out.println("The following exception has occurred: "+e.getMessage());
}
}
//! [Interesting]

View File

@ -0,0 +1,123 @@
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import upm_h803x.H803X;
public class H803X_Example
{
private static String defaultDev = "/dev/ttyUSB0";
public static void main(String[] args) throws InterruptedException
{
// ! [Interesting]
if (args.length > 0)
defaultDev = args[0];
System.out.println("Using device " + defaultDev);
System.out.println("Initializing...");
// Instantiate an H803X instance, using MODBUS slave address 1, and
// default comm parameters (9600, 8, N, 2)
H803X sensor = new H803X(defaultDev, 1);
// output the Slave ID (manufacturer, model, serno)
System.out.println("Slave ID: " + sensor.getSlaveID());
System.out.println();
while (true)
{
// update our values from the sensor
sensor.update();
// H8035 / H8036
System.out.println("Consumption (kWh): "
+ sensor.getConsumption());
System.out.println("Real Power (kW): "
+ sensor.getRealPower());
if (sensor.isH8036())
{
// The H8036 has much more data available...
System.out.println("Reactive Power (kVAR): "
+ sensor.getReactivePower());
System.out.println("Apparent Power (kVA): "
+ sensor.getApparentPower());
System.out.println("Power Factor: "
+ sensor.getPowerFactor());
System.out.println("Volts Line to Line: "
+ sensor.getVoltsLineToLine());
System.out.println("Volts Line to Neutral: "
+ sensor.getVoltsLineToNeutral());
System.out.println("Current: " + sensor.getCurrent());
System.out.println("Real Power Phase A (kW): "
+ sensor.getRealPowerPhaseA());
System.out.println("Real Power Phase B (kW): "
+ sensor.getRealPowerPhaseB());
System.out.println("Real Power Phase C (kW): "
+ sensor.getRealPowerPhaseC());
System.out.println("Power Factor Phase A: "
+ sensor.getPowerFactorPhaseA());
System.out.println("Power Factor Phase B: "
+ sensor.getPowerFactorPhaseB());
System.out.println("Power Factor Phase C: "
+ sensor.getPowerFactorPhaseC());
System.out.println("Volts Phase A to B: "
+ sensor.getVoltsPhaseAToB());
System.out.println("Volts Phase B to C: "
+ sensor.getVoltsPhaseBToC());
System.out.println("Volts Phase A to C: "
+ sensor.getVoltsPhaseAToC());
System.out.println("Volts Phase A to Neutral: "
+ sensor.getVoltsPhaseAToNeutral());
System.out.println("Volts Phase B to Neutral: "
+ sensor.getVoltsPhaseBToNeutral());
System.out.println("Volts Phase C to Neutral: "
+ sensor.getVoltsPhaseCToNeutral());
System.out.println("Current Phase A: "
+ sensor.getCurrentPhaseA());
System.out.println("Current Phase B: "
+ sensor.getCurrentPhaseB());
System.out.println("Current Phase C: "
+ sensor.getCurrentPhaseC());
System.out.println("Avg Real Power (kW): "
+ sensor.getAvgRealPower());
System.out.println("Min Real Power (kW): "
+ sensor.getMinRealPower());
System.out.println("Max Real Power (kW): "
+ sensor.getMaxRealPower());
}
System.out.println();
Thread.sleep(2000);
}
// ! [Interesting]
}
}

View File

@ -42,7 +42,7 @@ public class HP20xExample {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("The following exception occured: "+e.getMessage());
System.out.println("The following exception occurred: "+e.getMessage());
}
}
//! [Interesting]

View File

@ -0,0 +1,64 @@
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import upm_teams.TEAMS;
public class TEAMS_Example
{
public static void main(String[] args) throws InterruptedException
{
// ! [Interesting]
System.out.println("Initializing...");
// Instantiate an TEAMS instance, using A0 for temperature, and
// 165.0 ohms for the rResistor value (for the libelium 4-20ma
// interface)
TEAMS sensor = new TEAMS(0, 165.0f);
while (true)
{
// update our values from the sensor
sensor.update();
// is the sensor connected? (current >= 4ma)
System.out.println("Is Connected: " + sensor.isConnected());
// print computed current on the loop. This includes
// the offset, if one was set by setOffsetMilliamps().
System.out.println("Milliamps: " + sensor.getRawMilliamps());
// we show both C and F for temperature
System.out.println("Temperature: "
+ sensor.getTemperature()
+ " C / "
+ sensor.getTemperature(true)
+ " F");
System.out.println();
Thread.sleep(1000);
}
// ! [Interesting]
}
}

View File

@ -0,0 +1,71 @@
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import upm_tex00.TEX00;
public class TEX00_Example
{
public static void main(String[] args) throws InterruptedException
{
// ! [Interesting]
System.out.println("Initializing...");
// Instantiate an TEX00 instance, using A0 for the analog input. In
// this example, we are using a 10K Ohm balance resistor and a TED
// (10k type 2) thermistor.
TEX00 sensor = new TEX00(0, 10000.0f,
TEX00.SENSOR_TYPES_T.STYPE_THERMISTOR_TED);
System.out.println("Minimum temperature: "
+ sensor.getTemperatureRangeMin());
System.out.println("Maximum temperature: "
+ sensor.getTemperatureRangeMax());
System.out.println();
while (true)
{
// update our values from the sensor
sensor.update();
if (sensor.isOutOfRange())
{
System.out.println("Temperature out of range");
}
else
{
// we show both C and F for temperature
System.out.println("Temperature: "
+ sensor.getTemperature()
+ " C / "
+ sensor.getTemperature(true)
+ " F");
}
System.out.println();
Thread.sleep(1000);
}
// ! [Interesting]
}
}

View File

@ -25,18 +25,6 @@ import upm_th02.TH02;
public class Th02Example {
static {
try {
System.loadLibrary("javaupm_th02");
System.loadLibrary("mraajava");
} catch (UnsatisfiedLinkError e) {
System.err.println(
"Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" +
e);
System.exit(1);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
float temperature = 0;
@ -51,7 +39,7 @@ public class Th02Example {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("The following exception has occured: "+e.getMessage());
System.out.println("The following exception has occurred: "+e.getMessage());
}
}
}

View File

@ -0,0 +1,61 @@
/*
* Author: Abhishek Malik <abhishek.malik@intel.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import upm_tsl2561.TSL2561;
public class Tsl2561 {
static {
try {
System.loadLibrary("javaupm_tsl2561");
System.loadLibrary("mraajava");
} catch (UnsatisfiedLinkError e) {
System.err.println(
"Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" +
e);
System.exit(1);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//! [Interesting]
TSL2561 sensor = null;
int loopCount = 100;
// Instantiate the sensor object
sensor = new TSL2561();
for (int i=0; i<loopCount; i++){
// retrieving and displaying the Lux value
System.out.println("Lux: "+sensor.getLux());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("The following exception occurred: "+e.getMessage());
}
}
//! [Interesting]
}
}

View File

@ -0,0 +1,60 @@
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import upm_vcap.VCAP;
public class VCAP_Example
{
private static String defaultDev = "/dev/video0";
public static void main(String[] args) throws InterruptedException
{
// ! [Interesting]
if (args.length > 0)
defaultDev = args[0];
System.out.println("Using device " + defaultDev);
System.out.println("Initializing...");
// Instantiate an VCAP instance, using the specified video device
VCAP sensor = new VCAP(defaultDev);
// enable some debug/verbose output
sensor.setDebug(true);
// This is just a hint. The kernel can change this to a lower
// resolution that the hardware supports. Use getWidth() and
// getHeight() methods to see what the kernel actually chose if you
// care.
sensor.setResolution(1920, 1080);
// capture an image
sensor.captureImage();
// convert and save it as a jpeg
sensor.saveImage("video-img1.jpg");
// ! [Interesting]
}
}

View File

@ -43,7 +43,7 @@ public class WaterLevelSensor {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("The following exception occured: "+e.getMessage());
System.out.println("The following exception occurred: "+e.getMessage());
}
}
//! [Interesting]

View File

@ -0,0 +1,44 @@
/*jslint node:true, vars:true, bitwise:true, unparam:true */
/*jshint unused:true */
/*
* Author: Yannick Adam <yannick.adam@gmail.com>
* Copyright (c) 2016 Yannick Adam
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var lib = require('jsupm_apa102');
// Instantiate a strip of 30 LEDs on SPI Bus 0
var ledStrip = new lib.APA102(30, 0);
// Set all LEDs to blue
ledStrip.setAllLeds(31, 0, 0, 255);
// Set a mid-section to red
ledStrip.setLeds(10,20, 31, 255, 0, 0);
// Set a single led to green
ledStrip.setLed(15, 31, 0, 255, 0);
// Exit
ledStrip = null;
process.exit(0);

View File

@ -0,0 +1,51 @@
/*jslint node:true, vars:true, bitwise:true, unparam:true */
/*jshint unused:true */
/*
* Author: Henry Bruce <henry.bruce@intel.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var bme280pkg = require('jsupm_bme280');
// Instantiate a BME280 Sensor on I2C sub-platform bus 0
var bme280 = new bme280pkg.BME280(512);
// update every second and print the values
var myInterval = setInterval(function()
{
// print detected value
console.log("Temperature: " + bme280.getTemperatureCelcius() + "C");
console.log("Humidity: " + bme280.getHumidityRelative() + "%");
console.log("Pressure: " + bme280.getPressurePa() + "Pa");
}, 1000);
// When exiting: clear interval and print message
process.on('SIGINT', function()
{
clearInterval(myInterval);
bme280 = null
bme280pkg = null;
console.log("Exiting");
process.exit(0);
});

View File

@ -0,0 +1,71 @@
/*jslint node:true, vars:true, bitwise:true, unparam:true */
/*jshint unused:true */
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var sensorObj = require('jsupm_bmi160');
// Instantiate a BMI160 instance using default i2c bus and address
var sensor = new sensorObj.BMI160();
var x = new sensorObj.new_floatp();
var y = new sensorObj.new_floatp();
var z = new sensorObj.new_floatp();
// Output data every half second until interrupted
setInterval(function()
{
// update our values from the sensor
sensor.update();
sensor.getAccelerometer(x, y, z);
console.log("Accelerometer: AX: " + sensorObj.floatp_value(x) +
" AY: " + sensorObj.floatp_value(y) +
" AZ: " + sensorObj.floatp_value(z));
sensor.getGyroscope(x, y, z);
console.log("Gyroscope: GX: " + sensorObj.floatp_value(x) +
" AY: " + sensorObj.floatp_value(y) +
" AZ: " + sensorObj.floatp_value(z));
sensor.getMagnetometer(x, y, z);
console.log("Magnetometer: MX: " + sensorObj.floatp_value(x) +
" MY: " + sensorObj.floatp_value(y) +
" MZ: " + sensorObj.floatp_value(z));
console.log();
}, 500);
// exit on ^C
process.on('SIGINT', function()
{
sensor = null;
sensorObj.cleanUp();
sensorObj = null;
console.log("Exiting.");
process.exit(0);
});

View File

@ -0,0 +1,66 @@
/*jslint node:true, vars:true, bitwise:true, unparam:true */
/*jshint unused:true */
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var sensorObj = require('jsupm_cwlsxxa');
/************** Main code **************/
console.log("Initializing...");
// Instantiate an CWLSXXA instance, using A0 for CO2, A1 for
// humidity and A2 for temperature
var sensor = new sensorObj.CWLSXXA(0, 1, 2);
// update and print available values every second
setInterval(function()
{
// update our values from the sensor
sensor.update();
// we show both C and F for temperature
console.log("Temperature:", sensor.getTemperature(),
"C /", sensor.getTemperature(true), "F");
console.log("Humidity:", sensor.getHumidity(), "%");
console.log("CO2:", sensor.getCO2(), "ppm");
console.log("");
}, 1000);
process.on('SIGINT', function()
{
sensor = null;
sensorObj.cleanUp();
sensorObj = null;
console.log("Exiting...");
process.exit(0);
});

View File

@ -0,0 +1,101 @@
/*jslint node:true, vars:true, bitwise:true, unparam:true */
/*jshint unused:true */
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var sensorObj = require('jsupm_e50hx');
/************** Main code **************/
// You will need to edit this example to conform to your site and your
// devices, specifically the Device Object Instance ID passed to the
// constructor, and the arguments to initMaster() that are
// appropriate for your BACnet network.
var defaultDev = "/dev/ttyUSB0";
// if an argument was specified, use it as the device instead
if (process.argv.length > 2)
{
defaultDev = process.argv[2];
}
console.log("Using device " + defaultDev);
console.log("Initializing...");
// Instantiate an E50HX object for an E50HX device that has 1075425
// as it's unique Device Object Instance ID. NOTE: You will
// certainly want to change this to the correct value for your
// device(s).
var sensor = new sensorObj.E50HX(1075425);
// Initialize our BACnet master, if it has not already been
// initialized, with the device and baudrate, choosing 1000001 as
// our unique Device Object Instance ID, 2 as our MAC address and
// using default values for maxMaster and maxInfoFrames
sensor.initMaster(defaultDev, 38400, 1000001, 2);
// Uncomment to enable debugging output
// sensor.setDebug(true);
console.log("");
console.log("Device Description:", sensor.getDescription());
console.log("Device Location:", sensor.getLocation());
console.log("");
// update and print a few values every 5 seconds
setInterval(function()
{
console.log("System Voltage:",
sensor.getAnalogValue(sensorObj.E50HX.AV_System_Voltage),
" ",
sensor.getAnalogValueUnits(sensorObj.E50HX.AV_System_Voltage));
console.log("System Type:",
sensor.getAnalogValue(sensorObj.E50HX.AV_System_Type));
console.log("Energy Consumption:",
sensor.getAnalogInput(sensorObj.E50HX.AI_Energy),
" ",
sensor.getAnalogInputUnits(sensorObj.E50HX.AI_Energy));
console.log("Power Up Counter:",
sensor.getAnalogInput(sensorObj.E50HX.AI_Power_Up_Count));
console.log("");
}, 5000);
process.on('SIGINT', function()
{
sensor = null;
sensorObj.cleanUp();
sensorObj = null;
console.log("Exiting...");
process.exit(0);
});

View File

@ -0,0 +1,115 @@
/*jslint node:true, vars:true, bitwise:true, unparam:true */
/*jshint unused:true */
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var sensorObj = require('jsupm_h803x');
/************** Main code **************/
var defaultDev = "/dev/ttyUSB0";
// if an argument was specified, use it as the device instead
if (process.argv.length > 2)
{
defaultDev = process.argv[2];
}
console.log("Using device " + defaultDev);
console.log("Initializing...");
// Instantiate an H803X instance, using MODBUS slave address 1, and
// default comm parameters (9600, 8, N, 2)
var sensor = new sensorObj.H803X(defaultDev, 1);
// output the Slave ID (manufacturer, model, serno)
console.log("Slave ID:", sensor.getSlaveID());
console.log("");
// update and print available values every second
setInterval(function()
{
// update our values from the sensor
sensor.update();
// H8035 / H8036
console.log("Consumption (kWh):", sensor.getConsumption());
console.log("Real Power (kW):", sensor.getRealPower());
if (sensor.isH8036())
{
// The H8036 has much more data available...
console.log("Reactive Power (kVAR):", sensor.getReactivePower());
console.log("Apparent Power (kVA):", sensor.getApparentPower());
console.log("Power Factor:", sensor.getPowerFactor());
console.log("Volts Line to Line:", sensor.getVoltsLineToLine());
console.log("Volts Line to Neutral:", sensor.getVoltsLineToNeutral());
console.log("Current:", sensor.getCurrent());
console.log("Real Power Phase A (kW):", sensor.getRealPowerPhaseA());
console.log("Real Power Phase B (kW):", sensor.getRealPowerPhaseB());
console.log("Real Power Phase C (kW):", sensor.getRealPowerPhaseC());
console.log("Power Factor Phase A:", sensor.getPowerFactorPhaseA());
console.log("Power Factor Phase B:", sensor.getPowerFactorPhaseB());
console.log("Power Factor Phase C:", sensor.getPowerFactorPhaseC());
console.log("Volts Phase A to B:", sensor.getVoltsPhaseAToB());
console.log("Volts Phase B to C:", sensor.getVoltsPhaseBToC());
console.log("Volts Phase A to C:", sensor.getVoltsPhaseAToC());
console.log("Volts Phase A to Neutral: ",
sensor.getVoltsPhaseAToNeutral());
console.log("Volts Phase B to Neutral: ",
sensor.getVoltsPhaseBToNeutral());
console.log("Volts Phase C to Neutral: ",
sensor.getVoltsPhaseCToNeutral());
console.log("Current Phase A:", sensor.getCurrentPhaseA());
console.log("Current Phase B:", sensor.getCurrentPhaseB());
console.log("Current Phase C:", sensor.getCurrentPhaseC());
console.log("Avg Real Power (kW):", sensor.getAvgRealPower());
console.log("Min Real Power (kW):", sensor.getMinRealPower());
console.log("Max Real Power (kW):", sensor.getMaxRealPower());
}
console.log("");
}, 2000);
process.on('SIGINT', function()
{
sensor = null;
sensorObj.cleanUp();
sensorObj = null;
console.log("Exiting...");
process.exit(0);
});

View File

@ -128,7 +128,7 @@ function runRadio()
console.log("Received: " + resultStr);
}
if (rv < 0) // some sort of read error occured
if (rv < 0) // some sort of read error occurred
{
console.log("Port read error.");
return;

View File

@ -90,7 +90,7 @@ function exit()
// Load i2clcd module
var lcdObj = require('jsupm_i2clcd');
var lcd = new lcdObj.SSD1306(6, 0x3c);
var lcd = new lcdObj.SSD1306(0, 0x3C);
var next = 0;
lcd.clear();

View File

@ -0,0 +1,70 @@
/*jslint node:true, vars:true, bitwise:true, unparam:true */
/*jshint unused:true */
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var sensorObj = require('jsupm_teams');
/************** Main code **************/
console.log("Initializing...");
// Instantiate an TEAMS instance, using A0 for temperature, and
// 165.0 ohms for the rResistor value (for the libelium 4-20ma
// interface)
var sensor = new sensorObj.TEAMS(0, 165.0);
// update and print available values every second
setInterval(function()
{
// update our values from the sensor
sensor.update();
// is the sensor connected? (current >= 4ma)
console.log("Is Connected:", sensor.isConnected());
// print computed current on the loop. This includes the offset,
// if one was set by setOffsetMilliamps().
console.log("Milliamps:", sensor.getRawMilliamps());
// we show both C and F for temperature
console.log("Temperature:", sensor.getTemperature(),
"C /", sensor.getTemperature(true), "F");
console.log("");
}, 1000);
process.on('SIGINT', function()
{
sensor = null;
sensorObj.cleanUp();
sensorObj = null;
console.log("Exiting...");
process.exit(0);
});

View File

@ -0,0 +1,77 @@
/*jslint node:true, vars:true, bitwise:true, unparam:true */
/*jshint unused:true */
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var sensorObj = require('jsupm_tex00');
/************** Main code **************/
console.log("Initializing...");
// Instantiate an TEX00 instance, using A0 for the analog input. In
// this example, we are using a 10K Ohm balance resistor and a TED
// (10k type 2) thermistor.
var sensor = new sensorObj.TEX00(0, 10000,
sensorObj.TEX00.STYPE_THERMISTOR_TED);
console.log("Minimum temperature:", sensor.getTemperatureRangeMin(),
"C");
console.log("Maximum temperature:", sensor.getTemperatureRangeMax(),
"C");
console.log("");
// update and print available values every second
setInterval(function()
{
// update our values from the sensor
sensor.update();
if (sensor.isOutOfRange())
{
console.log("Temperature out of range");
}
else
{
// we show both C and F for temperature
console.log("Temperature:", sensor.getTemperature(),
"C /", sensor.getTemperature(true), "F");
}
console.log("");
}, 1000);
process.on('SIGINT', function()
{
sensor = null;
sensorObj.cleanUp();
sensorObj = null;
console.log("Exiting...");
process.exit(0);
});

View File

@ -66,7 +66,7 @@ function getGPSInfo()
process.stdout.write(GPSData)
}
if (rv < 0) // some sort of read error occured
if (rv < 0) // some sort of read error occurred
{
console.log("Port read error.");
process.exit(0);

View File

@ -0,0 +1,69 @@
/*jslint node:true, vars:true, bitwise:true, unparam:true */
/*jshint unused:true */
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var sensorObj = require('jsupm_vcap');
/************** Main code **************/
var defaultDev = "/dev/video0";
// if an argument was specified, use it as the device instead
if (process.argv.length > 2)
{
defaultDev = process.argv[2];
}
console.log("Using device " + defaultDev);
console.log("Initializing...");
// Instantiate an VCAP instance, using the specified video device
var sensor = new sensorObj.VCAP(defaultDev);
// enable some debug/verbose output
sensor.setDebug(true);
// This is just a hint. The kernel can change this to a lower
// resolution that the hardware supports. Use getWidth() and
// getHeight() methods to see what the kernel actually chose if you
// care.
sensor.setResolution(1920, 1080);
// capture an image
sensor.captureImage();
// convert and save it as a jpeg
sensor.saveImage("video-img1.jpg");
// make sure we clean up
sensor = null;
sensorObj.cleanUp();
sensorObj = null;
console.log("Exiting...");
process.exit(0);

48
examples/python/apa102.py Normal file
View File

@ -0,0 +1,48 @@
#!/usr/bin/python
# Author: Yannick Adam <yannick.adam@gmail.com>
# Copyright (c) 2016 Yannick Adam
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import time, sys, signal, atexit
import pyupm_apa102 as mylib
# Instantiate a strip of 30 LEDs on SPI bus 0
ledStrip = mylib.APA102(30, 0, False)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# Register exit handlers
signal.signal(signal.SIGINT, SIGINTHandler)
print "Setting all LEDs to Green"
ledStrip.setAllLeds(31, 0, 255, 0)
print "Setting LEDs between 10 and 20 to Red"
ledStrip.setLeds(10, 20, 31, 255, 0, 0)
print "Setting LED 15 to Blue"
ledStrip.setLed(15, 31, 0, 0, 255)

66
examples/python/bmi160.py Normal file
View File

@ -0,0 +1,66 @@
#!/usr/bin/python
# Author: Jon Trulson <jtrulson@ics.com>
# Copyright (c) 2016 Intel Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import time, sys, signal, atexit
import pyupm_bmi160 as sensorObj
# Instantiate a BMI160 instance using default i2c bus and address
sensor = sensorObj.BMI160()
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit
def exitHandler():
print "Exiting"
sys.exit(0)
# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
x = sensorObj.new_floatp()
y = sensorObj.new_floatp()
z = sensorObj.new_floatp()
while (1):
sensor.update()
sensor.getAccelerometer(x, y, z)
print "Accelerometer: AX: ", sensorObj.floatp_value(x),
print " AY: ", sensorObj.floatp_value(y),
print " AZ: ", sensorObj.floatp_value(z)
sensor.getGyroscope(x, y, z)
print "Gyroscope: GX: ", sensorObj.floatp_value(x),
print " GY: ", sensorObj.floatp_value(y),
print " GZ: ", sensorObj.floatp_value(z)
sensor.getMagnetometer(x, y, z)
print "Magnetometer: MX: ", sensorObj.floatp_value(x),
print " MY: ", sensorObj.floatp_value(y),
print " MZ: ", sensorObj.floatp_value(z)
print
time.sleep(.5)

View File

@ -0,0 +1,61 @@
#!/usr/bin/python
# Author: Jon Trulson <jtrulson@ics.com>
# Copyright (c) 2016 Intel Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import time, sys, signal, atexit
import pyupm_cwlsxxa as sensorObj
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit
def exitHandler():
print "Exiting"
sys.exit(0)
# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
print "Initializing..."
# Instantiate an CWLSXXA instance, using A0 for CO2, A1 for
# humidity and A2 for temperature
sensor = sensorObj.CWLSXXA(0, 1, 2)
# update and print available values every second
while (1):
# update our values from the sensor
sensor.update()
# we show both C and F for temperature
print "Temperature:", sensor.getTemperature(), "C /",
print sensor.getTemperature(True), "F"
print "Humidity:", sensor.getHumidity(), "%"
print "CO2:", sensor.getCO2(), "ppm"
print
time.sleep(1)

95
examples/python/e50hx.py Normal file
View File

@ -0,0 +1,95 @@
#!/usr/bin/python
# Author: Jon Trulson <jtrulson@ics.com>
# Copyright (c) 2016 Intel Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import time, sys, signal, atexit
import pyupm_e50hx as sensorObj
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit
def exitHandler():
print "Exiting..."
sys.exit(0)
# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
# You will need to edit this example to conform to your site and your
# devices, specifically the Device Object Instance ID passed to the
# constructor, and the arguments to initMaster() that are
# appropriate for your BACnet network.
defaultDev = "/dev/ttyUSB0"
# if an argument was specified, use it as the device instead
if (len(sys.argv) > 1):
defaultDev = sys.argv[1]
print "Using device", defaultDev
print "Initializing..."
# Instantiate an E50HX object for an E50HX device that has 1075425
# as it's unique Device Object Instance ID. NOTE: You will
# certainly want to change this to the correct value for your
# device(s).
sensor = sensorObj.E50HX(1075425)
# Initialize our BACnet master, if it has not already been
# initialized, with the device and baudrate, choosing 1000001 as
# our unique Device Object Instance ID, 2 as our MAC address and
# using default values for maxMaster and maxInfoFrames
sensor.initMaster(defaultDev, 38400, 1000001, 2)
# Uncomment to enable debugging output
# sensor.setDebug(True);
# output the serial number and firmware revision
print
print "Device Description:", sensor.getDescription()
print "Device Location:", sensor.getLocation()
print
# update and print available values every second
while (1):
print "System Voltage:",
print sensor.getAnalogValue(sensorObj.E50HX.AV_System_Voltage),
print " ",
print sensor.getAnalogValueUnits(sensorObj.E50HX.AV_System_Voltage)
print "System Type:",
print sensor.getAnalogValue(sensorObj.E50HX.AV_System_Type)
print "Energy Consumption:",
print sensor.getAnalogInput(sensorObj.E50HX.AI_Energy),
print " ",
print sensor.getAnalogInputUnits(sensorObj.E50HX.AI_Energy)
print "Power Up Counter:",
print sensor.getAnalogInput(sensorObj.E50HX.AI_Power_Up_Count)
print
time.sleep(5)

106
examples/python/h803x.py Normal file
View File

@ -0,0 +1,106 @@
#!/usr/bin/python
# Author: Jon Trulson <jtrulson@ics.com>
# Copyright (c) 2016 Intel Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import time, sys, signal, atexit
import pyupm_h803x as sensorObj
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit
def exitHandler():
print "Exiting..."
sys.exit(0)
# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
defaultDev = "/dev/ttyUSB0"
# if an argument was specified, use it as the device instead
if (len(sys.argv) > 1):
defaultDev = sys.argv[1]
print "Using device", defaultDev
print "Initializing..."
# Instantiate an H803X instance, using MODBUS slave address 1, and
# default comm parameters (9600, 8, N, 2)
sensor = sensorObj.H803X(defaultDev, 1)
# output the serial number and firmware revision
print "Slave ID:", sensor.getSlaveID()
print
# update and print available values every second
while (1):
# update our values from the sensor
sensor.update()
# H8035 / H8036
print "Consumption (kWh):", sensor.getConsumption()
print "Real Power (kW):", sensor.getRealPower()
if (sensor.isH8036()):
# The H8036 has much more data available...
print "Reactive Power (kVAR):", sensor.getReactivePower()
print "Apparent Power (kVA):", sensor.getApparentPower()
print "Power Factor:", sensor.getPowerFactor()
print "Volts Line to Line:", sensor.getVoltsLineToLine()
print "Volts Line to Neutral:", sensor.getVoltsLineToNeutral()
print "Current:", sensor.getCurrent()
print "Real Power Phase A (kW):", sensor.getRealPowerPhaseA()
print "Real Power Phase B (kW):", sensor.getRealPowerPhaseB()
print "Real Power Phase C (kW):", sensor.getRealPowerPhaseC()
print "Power Factor Phase A:", sensor.getPowerFactorPhaseA()
print "Power Factor Phase B:", sensor.getPowerFactorPhaseB()
print "Power Factor Phase C:", sensor.getPowerFactorPhaseC()
print "Volts Phase A to B:", sensor.getVoltsPhaseAToB()
print "Volts Phase B to C:", sensor.getVoltsPhaseBToC()
print "Volts Phase A to C:", sensor.getVoltsPhaseAToC()
print "Volts Phase A to Neutral: ",
print sensor.getVoltsPhaseAToNeutral()
print "Volts Phase B to Neutral: ",
print sensor.getVoltsPhaseBToNeutral()
print "Volts Phase C to Neutral: ",
print sensor.getVoltsPhaseCToNeutral()
print "Current Phase A:", sensor.getCurrentPhaseA()
print "Current Phase B:", sensor.getCurrentPhaseB()
print "Current Phase C:", sensor.getCurrentPhaseC()
print "Avg Real Power (kW):", sensor.getAvgRealPower()
print "Min Real Power (kW):", sensor.getMinRealPower()
print "Max Real Power (kW):", sensor.getMaxRealPower()
print
time.sleep(2)

View File

@ -123,7 +123,7 @@ else:
resultStr += radioBuffer.__getitem__(x)
print "Received:", resultStr
if (rv < 0): # some sort of read error occured
if (rv < 0): # some sort of read error occurred
print "Port read error."
sys.exit(0)
myCounter += 1

65
examples/python/teams.py Normal file
View File

@ -0,0 +1,65 @@
#!/usr/bin/python
# Author: Jon Trulson <jtrulson@ics.com>
# Copyright (c) 2016 Intel Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import time, sys, signal, atexit
import pyupm_teams as sensorObj
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit
def exitHandler():
print "Exiting"
sys.exit(0)
# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
print "Initializing..."
# Instantiate an TEAMS instance, using A0 for temperature, and
# 165.0 ohms for the rResistor value (for the libelium 4-20ma
# interface)
sensor = sensorObj.TEAMS(0, 165.0)
# update and print available values every second
while (1):
# update our values from the sensor
sensor.update()
# is the sensor connected? (current >= 4ma)
print "Is Connected:", sensor.isConnected()
# print computed current on the loop. This includes the offset,
# if one was set by setOffsetMilliamps().
print "Milliamps:", sensor.getRawMilliamps()
# we show both C and F for temperature
print "Temperature:", sensor.getTemperature(), "C /",
print sensor.getTemperature(True), "F"
print
time.sleep(1)

65
examples/python/tex00.py Normal file
View File

@ -0,0 +1,65 @@
#!/usr/bin/python
# Author: Jon Trulson <jtrulson@ics.com>
# Copyright (c) 2016 Intel Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import time, sys, signal, atexit
import pyupm_tex00 as sensorObj
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit
def exitHandler():
print "Exiting"
sys.exit(0)
# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
print "Initializing..."
# Instantiate an TEX00 instance, using A0 for the analog input. In
# this example, we are using a 10K Ohm balance resistor and a TED
# (10k type 2) thermistor.
sensor = sensorObj.TEX00(0, 10000, sensorObj.TEX00.STYPE_THERMISTOR_TED)
print "Minimum temperature:", sensor.getTemperatureRangeMin(), "C"
print "Maximum temperature:", sensor.getTemperatureRangeMax(), "C"
print
# update and print available values every second
while (1):
# update our values from the sensor
sensor.update()
if (sensor.isOutOfRange()):
print "Temperature out of range"
else:
# we show both C and F for temperature
print "Temperature:", sensor.getTemperature(), "C /",
print sensor.getTemperature(True), "F"
print
time.sleep(1)

View File

@ -73,7 +73,7 @@ def getGPSInfo():
GPSData += nmeaBuffer.__getitem__(x)
sys.stdout.write(GPSData)
if (rv < 0): # some sort of read error occured
if (rv < 0): # some sort of read error occurred
print "Port read error."
sys.exit(0)

67
examples/python/vcap.py Normal file
View File

@ -0,0 +1,67 @@
#!/usr/bin/python
# Author: Jon Trulson <jtrulson@ics.com>
# Copyright (c) 2016 Intel Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import time, sys, signal, atexit
import pyupm_vcap as sensorObj
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit
def exitHandler():
print "Exiting..."
sys.exit(0)
# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
defaultDev = "/dev/video0"
# if an argument was specified, use it as the device instead
if (len(sys.argv) > 1):
defaultDev = sys.argv[1]
print "Using device", defaultDev
print "Initializing..."
# Instantiate an VCAP instance, using the specified video device
sensor = sensorObj.VCAP(defaultDev)
# enable some debug/verbose output
sensor.setDebug(True);
# This is just a hint. The kernel can change this to a lower
# resolution that the hardware supports. Use getWidth() and
# getHeight() methods to see what the kernel actually chose if you
# care.
sensor.setResolution(1920, 1080);
# capture an image
sensor.captureImage();
# convert and save it as a jpeg
sensor.saveImage("video-img1.jpg");

View File

@ -28,6 +28,11 @@ endmacro (upm_CREATE_INSTALL_PKGCONFIG)
macro(upm_SWIG_PYTHON)
if (BUILDSWIGPYTHON AND BUILDSWIG)
include_directories (
${CMAKE_CURRENT_SOURCE_DIR}/..
)
set_source_files_properties (pyupm_${libname}.i PROPERTIES CPLUSPLUS ON)
set_source_files_properties (pyupm_${libname}.i PROPERTIES SWIG_FLAGS "-I${CMAKE_CURRENT_BINARY_DIR}/..")
swig_add_module (pyupm_${libname} python pyupm_${libname}.i ${module_src})
@ -39,7 +44,7 @@ macro(upm_SWIG_PYTHON)
)
install (FILES ${CMAKE_CURRENT_BINARY_DIR}/_pyupm_${libname}.so
${CMAKE_CURRENT_BINARY_DIR}/pyupm_${libname}.py
DESTINATION ${CMAKE_INSTALL_LIBDIR}/python${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}/site-packages/
DESTINATION ${LIB_INSTALL_DIR}/python${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}/site-packages/
COMPONENT ${libname})
endif()
endmacro()
@ -57,6 +62,10 @@ macro(upm_SWIG_NODE)
string (LENGTH "${V8_VERSION_HEX}" V8_VERSION_HEX_length)
endwhile ()
include_directories (
${CMAKE_CURRENT_SOURCE_DIR}/..
)
set_property (SOURCE jsupm_${libname}.i PROPERTY SWIG_FLAGS "-node" "-DV8_VERSION=${V8_VERSION_HEX}")
set_source_files_properties (jsupm_${libname}.i PROPERTIES CPLUSPLUS ON)
swig_add_module (jsupm_${libname} javascript jsupm_${libname}.i ${module_src})
@ -77,24 +86,26 @@ macro(upm_SWIG_NODE)
message(FATAL_ERROR " **ERROR** GCC 4.7 or above is required to compile jsupm_${libname} ")
endif()
endif()
set_property (TARGET jsupm_${libname} PROPERTY CXX_STANDARD 11)
set_property (TARGET jsupm_${libname} PROPERTY CXX_STANDARD_REQUIRED ON)
if (CMAKE_VERSION VERSION_LESS "3.1")
if (CMAKE_COMPILER_IS_GNUCXX)
if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.7")
message (FATAL_ERROR " FATAL ERROR: GNU gcc compiler is also too old (need 4.7+, but ${CMAKE_CXX_COMPILER_VERSION}) and does not support C++11 standard.")
if (NOT ENABLECXX11)
set_property (TARGET jsupm_${libname} PROPERTY CXX_STANDARD 11)
set_property (TARGET jsupm_${libname} PROPERTY CXX_STANDARD_REQUIRED ON)
if (CMAKE_VERSION VERSION_LESS "3.1")
if (CMAKE_COMPILER_IS_GNUCXX)
if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.7")
message (FATAL_ERROR " FATAL ERROR: GNU gcc compiler is also too old (need 4.7+, but ${CMAKE_CXX_COMPILER_VERSION}) and does not support C++11 standard.")
endif ()
set (UPM_CXX11_WORKAROUND_OPTION "-std=gnu++11")
else ()
set (UPM_CXX11_WORKAROUND_OPTION "-std=c++11")
endif ()
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${UPM_CXX11_WORKAROUND_OPTION} ")
endif ()
set (UPM_CXX11_WORKAROUND_OPTION "-std=gnu++11")
else ()
set (UPM_CXX11_WORKAROUND_OPTION "-std=c++11")
endif ()
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${UPM_CXX11_WORKAROUND_OPTION} ")
endif ()
endif()
createpackagejson(${libname})
set (NODE_MODULE_INSTALL_PATH ${NODE_ROOT_DIR}/lib/node_modules/jsupm_${libname}/)
install (FILES ${CMAKE_CURRENT_BINARY_DIR}/jsupm_${libname}.node
DESTINATION ${NODE_MODULE_INSTALL_PATH} COMPONENT ${libname})
endif()
@ -126,8 +137,8 @@ macro(upm_SWIG_JAVA)
PREFIX "lib"
SUFFIX ".so"
)
install (TARGETS javaupm_${libname} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
install (FILES ${CMAKE_CURRENT_BINARY_DIR}/upm_${libname}.jar DESTINATION ${CMAKE_INSTALL_LIBDIR}/../lib/java)
install (TARGETS javaupm_${libname} LIBRARY DESTINATION ${LIB_INSTALL_DIR})
install (FILES ${CMAKE_CURRENT_BINARY_DIR}/upm_${libname}.jar DESTINATION ${LIB_INSTALL_DIR}/../lib/java)
if (NOT DEFINED $ENV{JAVA_HOME_NATIVE})
set (JAVAC $ENV{JAVA_HOME}/bin/javac)
@ -155,7 +166,7 @@ macro(upm_doxygen)
set (classname ${libname})
endif()
set (CMAKE_SWIG_FLAGS -DDOXYGEN=${DOXYGEN_FOUND})
if (BUILDSWIG)
if (BUILDSWIGPYTHON AND BUILDSWIG)
add_dependencies (_pyupm_${libname} pyupm_doxy2swig)
add_dependencies (pydoc _pyupm_${libname})
else ()
@ -165,6 +176,14 @@ macro(upm_doxygen)
endmacro()
if (SWIG_FOUND)
if (BUILDSWIGPYTHON)
if(NOT PYTHONLIBS_FOUND)
find_package (PythonLibs ${PYTHONBUILD_VERSION} REQUIRED)
string (REPLACE "." ";" PYTHON_VERSION_LIST ${PYTHONLIBS_VERSION_STRING})
list (GET PYTHON_VERSION_LIST 0 PYTHON_VERSION_MAJOR)
list (GET PYTHON_VERSION_LIST 1 PYTHON_VERSION_MINOR)
endif()
endif(BUILDSWIGPYTHON)
if (BUILDSWIGNODE)
if(NOT NODE_FOUND)
find_package(Node)
@ -180,14 +199,20 @@ if (SWIG_FOUND)
${NODE_ROOT_DIR}/include/deps/uv/include
)
macro(createpackagejson)
configure_file (${PROJECT_SOURCE_DIR}/src/package.json.in ${CMAKE_CURRENT_BINARY_DIR}/package.json @ONLY)
configure_file (${PROJECT_SOURCE_DIR}/src/package.json.in ${CMAKE_CURRENT_BINARY_DIR}/package.json @ONLY)
# If a CMAKE_INSTALL_PREFIX has NOT been provided, set NODE_MODULE_INSTALL_PATH
# base on the NODE_ROOT_DIR.
if (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
set (NODE_MODULE_INSTALL_PATH ${NODE_ROOT_DIR}/lib/node_modules/jsupm_${libname}/)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/package.json
DESTINATION ${NODE_MODULE_INSTALL_PATH} COMPONENT ${libname})
# If a CMAKE_INSTALL_PREFIX has been provided, set NODE_MODULE_INSTALL_PATH
# relative to the provided install directory.
else ()
set (NODE_MODULE_INSTALL_PATH ${CMAKE_INSTALL_PREFIX}/lib/node_modules/jsupm_${libname}/)
endif ()
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/package.json
DESTINATION ${NODE_MODULE_INSTALL_PATH} COMPONENT ${libname})
endmacro()
endif(BUILDSWIGNODE)
endif()
macro(upm_module_init)
@ -196,7 +221,7 @@ macro(upm_module_init)
foreach (linkflag ${ARGN})
target_link_libraries (${libname} ${linkflag})
endforeach ()
include_directories (${MRAA_INCLUDE_DIRS} .)
include_directories (${MRAA_INCLUDE_DIRS} . ..)
target_link_libraries (${libname} ${MRAA_LIBRARIES})
set_target_properties(
${libname}
@ -204,7 +229,7 @@ macro(upm_module_init)
SOVERSION ${upm_VERSION_MAJOR}
VERSION ${upm_VERSION_STRING}
)
upm_create_install_pkgconfig (upm-${libname}.pc ${CMAKE_INSTALL_LIBDIR}/pkgconfig)
upm_create_install_pkgconfig (upm-${libname}.pc ${LIB_INSTALL_DIR}/pkgconfig)
if (SWIG_FOUND)
if (NOT ";${PYTHONSWIG_BLACKLIST};" MATCHES ";${libname};")
upm_swig_python()
@ -219,7 +244,7 @@ macro(upm_module_init)
if (BUILDDOC)
upm_doxygen()
endif()
install(TARGETS ${libname} DESTINATION ${CMAKE_INSTALL_LIBDIR})
install(TARGETS ${libname} DESTINATION ${LIB_INSTALL_DIR})
install (FILES ${module_h} DESTINATION include/upm COMPONENT ${libname})
if (IPK)

View File

@ -30,15 +30,63 @@ ADS1015::setSPS(ADSSAMPLERATE rate){
updateConfigRegister((m_config_reg & ~ADS1X15_DR_MASK) | rate);
}
ADS1015::ADS1015(int bus, uint8_t address) : ADS1X15(bus, address) {
ADS1015::ADS1015(int bus, uint8_t address, float vref) : ADS1X15(bus, address) {
m_name = "ADS1015";
m_conversionDelay = ADS1015_CONVERSIONDELAY;
m_bitShift = 4;
ADS1X15::getCurrentConfig();
if (vref < 0.0 || vref > 6.144)
UPM_THROW("vref out of range");
else if (vref > 4.096)
setGain(GAIN_TWOTHIRDS);
else if (vref > 2.048)
setGain(GAIN_ONE);
else if (vref > 1.024)
setGain(GAIN_TWO);
else if (vref > 0.512)
setGain(GAIN_FOUR);
else if (vref > 0.256)
setGain(GAIN_EIGHT);
else
setGain(GAIN_SIXTEEN);
}
ADS1015::~ADS1015(){};
const char*
ADS1015::getModuleName() {
return m_name.c_str();
}
unsigned int
ADS1015::getNumInputs() {
return 4;
}
unsigned int
ADS1015::getResolutionInBits() {
return 12;
}
uint16_t
ADS1015::getRawValue(unsigned int input) {
ADS1X15::ADSMUXMODE mode = getMuxMode(input);
updateConfigRegister((m_config_reg & ~ADS1X15_MUX_MASK) | mode, true);
usleep(m_conversionDelay);
uint16_t value = i2c->readWordReg(ADS1X15_REG_POINTER_CONVERT);
value = value >> m_bitShift;
return swapWord(value);
}
float
ADS1015::getVoltage(unsigned int input) {
ADSMUXMODE mode = getMuxMode(input);
return getSample(mode);
}
//Private functions
float
ADS1015::getMultiplier(void){
@ -99,4 +147,20 @@ ADS1015::setDelay(){
}
}
ADS1X15::ADSMUXMODE
ADS1015::getMuxMode(unsigned int input) {
ADS1X15::ADSMUXMODE mode;
switch (input) {
case 0:
return SINGLE_0;
case 1:
return SINGLE_1;
case 2:
return SINGLE_2;
case 3:
return SINGLE_3;
default:
UPM_THROW("Invalid input");
}
}

View File

@ -26,8 +26,9 @@
#pragma once
#include "ads1x15.h"
#include "upm/iADC.h"
#define ADS1015_VREF 2.048
/*=========================================================================
CONVERSION DELAY (in microS)
@ -82,7 +83,7 @@ namespace upm {
* @image html ads1015.jpg
* @snippet ads1x15.cxx Interesting
*/
class ADS1015 : public ADS1X15 {
class ADS1015 : public ADS1X15, public IADC {
public:
@ -111,12 +112,16 @@ namespace upm {
/**
* ADS1X15 constructor
* ADS1015 constructor
*
* This constructor includes a vref parameter that can be used
* to set gain so it matches full scale value of input
*
* @param bus i2c bus the sensor is attached to.
* @param address. Device address. Default is 0x48.
* @param address. Optional device address. Default is 0x48.
* @param vref. Optional reference (i.e. half full swing) voltage. Default is 2.048V
*/
ADS1015 (int bus, uint8_t address = 0x48);
ADS1015 (int bus, uint8_t address = 0x48, float vref = ADS1015_VREF);
/**
* ADS1X15 destructor
@ -132,9 +137,48 @@ namespace upm {
*/
void setSPS(ADSSAMPLERATE rate = SPS_1600);
/**
* Get number of inputs
*
* @return number of inputs
*/
unsigned int getNumInputs();
/**
* Read current value for current single ended analogue input
*
* @return current conversion value
*/
uint16_t getRawValue(unsigned int input);
/**
* Read current voltage for current single ended analogue input
*
* @return current voltage
*/
float getVoltage(unsigned int input);
/**
* Read current voltage for current single ended analogue input
*
* @return current voltage
*/
unsigned int getResolutionInBits();
/**
* Returns module name
*
* @return modulename as const char*
*/
const char* getModuleName();
protected:
float getMultiplier(void);
void setDelay(void);
private:
ADS1X15::ADSMUXMODE getMuxMode(unsigned int input);
};
}

View File

@ -113,7 +113,7 @@ namespace upm {
/**
* Set the zero point. This is the point measured and averaged
* when the sensor is not moving. It is set at construction time
* (averaged over a number of samples), but can be overriden here.
* (averaged over a number of samples), but can be overridden here.
*
* @param zeroPoint The averaged zero point of the sensor at rest
*/

View File

@ -233,7 +233,8 @@ AM2315::i2cWriteReg(uint8_t reg, uint8_t* data, uint8_t ilen)
uint8_t
AM2315::i2cReadReg(int reg, uint8_t* data, int ilen)
{
uint8_t tdata[16] = { AM2315_READ, reg, ilen };
uint8_t tdata[16] = { AM2315_READ, static_cast<uint8_t>(reg),
static_cast<uint8_t>(ilen) };
mraa_result_t ret = mraa_i2c_address(m_i2ControlCtx, m_controlAddr);
int iLoops = 5;

View File

@ -0,0 +1,5 @@
set (libname "apa102")
set (libdescription "upm apa102 led strip spi output module")
set (module_src ${libname}.cxx)
set (module_h ${libname}.h)
upm_module_init()

166
src/apa102/apa102.cxx Normal file
View File

@ -0,0 +1,166 @@
/*
* Author: Yannick Adam <yannick.adam@gmail.com>
* Copyright (c) 2016 Yannick Adam
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <cstring>
#include <iostream>
#include <stdexcept>
#include <stdlib.h>
#include <unistd.h>
#include "apa102.h"
using namespace upm;
APA102::APA102(uint16_t ledCount, uint8_t spiBus, bool batchMode, int8_t csn)
: m_ledCount(ledCount), m_batchMode(batchMode)
{
mraa::Result res = mraa::SUCCESS;
m_leds = NULL;
// Optional chip select pin
m_csnPinCtx = NULL;
if (csn > -1) {
m_csnPinCtx = new mraa::Gpio(csn);
res = m_csnPinCtx->dir(mraa::DIR_OUT);
if (res != mraa::SUCCESS) {
throw std::invalid_argument(std::string(__FUNCTION__) +
": GPIO failed to set direction");
}
}
CSOff();
// Initialize SPI
m_spi = new mraa::Spi(spiBus);
// Initialize LED array
uint16_t endFrameLength = (m_ledCount + 15) / 16; // End frame should be (leds/2) bits
m_frameLength = endFrameLength + (m_ledCount + 1) * 4;
if ((m_leds = (uint8_t*) malloc(m_frameLength))) {
memset(m_leds, 0x00, m_frameLength - 4); // Clear state
memset(&m_leds[m_frameLength - endFrameLength], 0xFF, endFrameLength); // Frame End
// Need to set the brightness to "0" for each Led
for (int i = 1; i <= m_ledCount; i++) {
m_leds[i * 4] = 224;
}
} else {
throw std::runtime_error(std::string(__FUNCTION__) +
": Failed to allocate memory for LED Strip");
}
}
APA102::~APA102()
{
// Clear leds
if (m_leds) {
free(m_leds);
}
// Clear SPI
if (m_spi) {
delete m_spi;
}
// Clear GPIO
if (m_csnPinCtx) {
delete m_csnPinCtx;
}
}
void
APA102::setLed(uint16_t ledIdx, uint8_t brightness, uint8_t r, uint8_t g, uint8_t b)
{
setLeds(ledIdx, ledIdx, brightness, r, g, b);
}
void
APA102::setAllLeds(uint8_t brightness, uint8_t r, uint8_t g, uint8_t b)
{
setLeds(0, m_ledCount - 1, brightness, r, g, b);
}
void
APA102::setLeds(uint16_t startIdx, uint16_t endIdx, uint8_t brightness, uint8_t r, uint8_t g, uint8_t b)
{
uint16_t s_idx = (startIdx + 1) * 4;
uint16_t e_idx = (endIdx + 1) * 4;
for (uint16_t i = s_idx; i <= e_idx; i += 4) {
m_leds[i] = brightness | 224;
m_leds[i + 1] = b;
m_leds[i + 2] = g;
m_leds[i + 3] = r;
}
if (!m_batchMode) {
pushState();
}
}
void
APA102::setLeds(uint16_t startIdx, uint16_t endIdx, uint8_t* colors)
{
uint16_t s_idx = (startIdx + 1) * 4;
memcpy(&m_leds[s_idx], colors, (endIdx - startIdx + 1) * 4);
if (!m_batchMode) {
pushState();
}
}
void
APA102::pushState(void)
{
CSOn();
m_spi->write(m_leds, m_frameLength);
CSOff();
}
/*
* **************
* private area
* **************
*/
mraa::Result
APA102::CSOn()
{
if (m_csnPinCtx) {
return m_csnPinCtx->write(HIGH);
}
return mraa::ERROR_FEATURE_NOT_SUPPORTED;
}
mraa::Result
APA102::CSOff()
{
if (m_csnPinCtx) {
return m_csnPinCtx->write(LOW);
}
return mraa::ERROR_FEATURE_NOT_SUPPORTED;
}

143
src/apa102/apa102.h Normal file
View File

@ -0,0 +1,143 @@
/*
* Author: Yannick Adam <yannick.adam@gmail.com>
* Copyright (c) 2016 Yannick Adam
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <mraa/gpio.hpp>
#include <mraa/spi.hpp>
#include <string>
#define HIGH 1
#define LOW 0
namespace upm
{
/**
* @brief APA102 RGB LED Strip driver library
* @defgroup apa102 libupm-apa102
* @ingroup spi led
*/
/**
* @library apa102
* @sensor apa102
* @comname APA102/DotStar LED Strip
* @type led
* @man adafruit
* @con spi
*
* @brief API for controlling APA102/DotStar RGB LED Strips
*
* APA102 LED Strips provide individually controllable LEDs through a SPI interface.
* For each LED, brightness (0-31) and RGB (0-255) values can be set.
*
* @image html apa102.jpg
* @snippet apa102.cxx Interesting
*/
class APA102
{
public:
/**
* Instantiates a new APA102 LED Strip
*
* @param ledCount Number of APA102 leds in the strip
* @param spiBus SPI Bus number
* @param batchMode (optional) Immediately write to SPI (false, default) or wait for a pushState
* call (true)
* @param csn (optional) Chip Select Pin
*/
APA102(uint16_t ledCount, uint8_t spiBus, bool batchMode = false, int8_t csn = -1);
/**
* APA102 destructor
*/
~APA102();
/**
* Change the color for a single led
*
* @param ledIdx Index of the LED in the strip (0 based)
* @param brightness Brightness value (0-31)
* @param r Red component (0-255)
* @param g Green component (0-255)
* @param b Blue component (0-255)
*/
void setLed(uint16_t ledIdx, uint8_t brightness, uint8_t r, uint8_t g, uint8_t b);
/**
* Change the color for all leds
*
* @param brightness Brightness value (0-31)
* @param r Red component (0-255)
* @param g Green component (0-255)
* @param b Blue component (0-255)
*/
void setAllLeds(uint8_t brightness, uint8_t r, uint8_t g, uint8_t b);
/**
* Change the color for a range of leds
*
* @param startIdx Start index of the range of LEDs in the strip (0 based)
* @param endIdx End index of the range of LEDs in the strip (0 based)
* @param brightness Brightness value (0-31)
* @param r Red component (0-255)
* @param g Green component (0-255)
* @param b Blue component (0-255)
*/
void
setLeds(uint16_t startIdx, uint16_t endIdx, uint8_t brightness, uint8_t r, uint8_t g, uint8_t b);
/**
* (Advanced) Manually control the colors of a range of LEDS
* Best used to maximize performance
*
* @param startIdx Start index of the range of LEDs to update (0 based)
* @param endIdx End index of the range of LEDs to update (0 based)
* @param colors Pointer to an array of bytes. Each color is described as the following:
* B1: Brightness (224-255) B2: Blue (0-255) B3: Green (0-255) B4: Red
*(0-255)
* No check done on the boundaries
*/
void setLeds(uint16_t startIdx, uint16_t endIdx, uint8_t* colors);
/**
* Outputs the current LED data to the SPI bus
* Note: Only required if batch mode is set to TRUE
*
*/
void pushState();
private:
mraa::Spi* m_spi;
mraa::Gpio* m_csnPinCtx;
uint16_t m_ledCount;
uint8_t* m_leds;
uint16_t m_frameLength;
bool m_batchMode;
mraa::Result CSOn();
mraa::Result CSOff();
};
}

View File

@ -0,0 +1,30 @@
%module javaupm_apa102
%include "../upm.i"
%include "typemaps.i"
%typemap(jtype) (uint8_t *colors) "byte[]"
%typemap(jstype) (uint8_t *colors) "byte[]"
%typemap(jni) (uint8_t *colors) "jbyteArray"
%typemap(javain) (uint8_t *colors) "$javainput"
%typemap(in) (uint8_t *colors) {
$1 = (uint8_t*)JCALL2(GetByteArrayElements, jenv, $input, NULL);
}
%{
#include "apa102.h"
%}
%include "apa102.h"
%pragma(java) jniclasscode=%{
static {
try {
System.loadLibrary("javaupm_apa102");
} catch (UnsatisfiedLinkError e) {
System.err.println("Native code library failed to load. \n" + e);
System.exit(1);
}
}
%}

19
src/apa102/jsupm_apa102.i Normal file
View File

@ -0,0 +1,19 @@
%module jsupm_apa102
%include "../upm.i"
%inline %{
#include <node_buffer.h>
%}
%typemap(in) (uint8_t *colors) {
if (!node::Buffer::HasInstance($input)) {
SWIG_exception_fail(SWIG_ERROR, "Expected a node Buffer");
}
$1 = (uint8_t*) node::Buffer::Data($input);
}
%include "apa102.h"
%{
#include "apa102.h"
%}

25
src/apa102/pyupm_apa102.i Normal file
View File

@ -0,0 +1,25 @@
// Include doxygen-generated documentation
%include "pyupm_doxy2swig.i"
%module pyupm_apa102
%include "../upm.i"
%feature("autodoc", "3");
// setLeds
%typemap(in) (uint8_t *colors) {
if (PyByteArray_Check($input)) {
$1 = (uint8_t*) PyByteArray_AsString($input);
} else {
PyErr_SetString(PyExc_ValueError, "bytearray expected");
return NULL;
}
}
%include "apa102.h"
%{
#include "apa102.h"
%}

View File

@ -0,0 +1,24 @@
set (libname "bacnetmstp")
set (libdescription "upm driver module for BACnet MS/TP devices")
set (module_src ${libname}.cxx device-client.c)
set (module_h ${libname}.h)
pkg_search_module(BACNET libbacnet)
if (BACNET_FOUND)
set (reqlibname "libbacnet")
include_directories(${BACNET_INCLUDE_DIRS})
upm_module_init()
add_dependencies(${libname} ${BACNET_LIBRARIES})
target_link_libraries(${libname} ${BACNET_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT})
if (BUILDSWIG)
if (BUILDSWIGNODE)
swig_link_libraries (jsupm_${libname} ${BACNET_LIBRARIES} ${MRAA_LIBRARIES} ${NODE_LIBRARIES})
endif()
if (BUILDSWIGPYTHON)
swig_link_libraries (pyupm_${libname} ${BACNET_LIBRARIES} ${PYTHON_LIBRARIES} ${MRAA_LIBRARIES})
endif()
if (BUILDSWIGJAVA)
swig_link_libraries (javaupm_${libname} ${BACNET_LIBRARIES} ${MRAAJAVA_LDFLAGS} ${JAVA_LDFLAGS})
endif()
endif()
endif ()

View File

@ -0,0 +1,880 @@
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <iostream>
#include <stdexcept>
#include <string>
#include <sstream>
#include "bacnetmstp.h"
#include "handlers.h"
#include "client.h"
#include "txbuf.h"
#include "mstpdef.h"
using namespace upm;
using namespace std;
// our singleton instance
BACNETMSTP* BACNETMSTP::m_instance = 0;
BACNETMSTP::BACNETMSTP()
{
// set defaults here
m_maxInfoFrames = DEFAULT_MAX_INFO_FRAMES;
m_maxMaster = DEFAULT_MAX_MASTER;
m_baudRate = 38400;
m_macAddr = DEFAULT_MAX_MASTER;
m_initialized = false;
// 60 sec, for MS/TP
m_adpuTimeoutMS = 60000;
m_deviceInstanceID = BACNET_MAX_INSTANCE;
memset(m_rxBuffer, 0, MAX_MPDU);
m_returnedValue = {0};
m_targetAddress = {0};
m_invokeID = 0;
m_errorDetected = false;
setDebug(false);
}
BACNETMSTP::~BACNETMSTP()
{
if (m_initialized)
datalink_cleanup();
}
void BACNETMSTP::setDebug(bool enable)
{
m_debugging = enable;
}
void BACNETMSTP::clearErrors()
{
m_errorType = BACERR_TYPE_NONE;
// empty out all of our error/reject/abort info
m_rejectReason = REJECT_REASON_OTHER;
m_rejectString.clear();
m_abortReason = ABORT_REASON_OTHER;
m_abortString.clear();
m_errorClass = ERROR_CLASS_DEVICE;
m_errorCode = ERROR_CODE_OTHER;
m_errorString.clear();
m_upmErrorString.clear();
}
void BACNETMSTP::handlerError(BACNET_ADDRESS* src,
uint8_t invoke_id,
BACNET_ERROR_CLASS error_class,
BACNET_ERROR_CODE error_code)
{
if (instance()->m_debugging)
cerr << __FUNCTION__ << ": entered" << endl;
if (address_match(&(instance()->m_targetAddress), src) &&
(invoke_id == instance()->m_invokeID))
{
instance()->m_errorType = BACERR_TYPE_ERROR;
instance()->m_errorClass = error_class;
instance()->m_errorCode = error_code;
instance()->m_errorString =
bactext_error_class_name((int)error_class)
+ string(": ") + bactext_error_code_name((int)error_code);
instance()->m_errorDetected = true;
}
}
void BACNETMSTP::handlerAbort(BACNET_ADDRESS* src,
uint8_t invoke_id,
uint8_t abort_reason,
bool server)
{
(void)server; // not used
if (instance()->m_debugging)
cerr << __FUNCTION__ << ": entered" << endl;
if (address_match(&(instance()->m_targetAddress), src) &&
(invoke_id == instance()->m_invokeID))
{
instance()->m_errorType = BACERR_TYPE_ABORT;
instance()->m_abortReason = abort_reason;
instance()->m_abortString =
bactext_abort_reason_name((int)abort_reason);
instance()->m_errorDetected = true;
}
}
void BACNETMSTP::handlerReject(BACNET_ADDRESS* src,
uint8_t invoke_id,
uint8_t reject_reason)
{
if (instance()->m_debugging)
cerr << __FUNCTION__ << ": entered" << endl;
if (address_match(&(instance()->m_targetAddress), src) &&
(invoke_id == instance()->m_invokeID))
{
instance()->m_errorType = BACERR_TYPE_REJECT;
instance()->m_rejectReason = reject_reason;
instance()->m_rejectString =
bactext_reject_reason_name((int)reject_reason);
instance()->m_errorDetected = true;
}
}
void BACNETMSTP::handlerReadPropertyAck(uint8_t* service_request,
uint16_t service_len,
BACNET_ADDRESS* src,
BACNET_CONFIRMED_SERVICE_ACK_DATA* service_data)
{
int len = 0;
BACNET_READ_PROPERTY_DATA data;
if (address_match(&(instance()->m_targetAddress), src) &&
(service_data->invoke_id == instance()->m_invokeID))
{
if (instance()->m_debugging)
cerr << __FUNCTION__ << ": got readProp ack" << endl;
len = rp_ack_decode_service_request(service_request, service_len,
&data);
// FIXME: we don't currently handle arrays (len < service_len)
if (len > 0)
{
bacapp_decode_application_data(data.application_data,
data.application_data_len,
&(instance()->m_returnedValue));
}
else
{
// shouldn't happen?
cerr << __FUNCTION__ << ": decode app data failed" << endl;
}
}
}
void BACNETMSTP::handlerWritePropertyAck(BACNET_ADDRESS* src,
uint8_t invoke_id)
{
if (address_match(&(instance()->m_targetAddress), src) &&
(invoke_id == instance()->m_invokeID))
{
if (instance()->m_debugging)
cerr << __FUNCTION__ << ": got writeProp ack" << endl;
}
}
void BACNETMSTP::initServiceHandlers()
{
// this is in device-client.c
Device_Init(NULL);
// These are service requests we must handle from other masters
// we need to handle who-is to support dynamic device binding to us
apdu_set_unconfirmed_handler(SERVICE_UNCONFIRMED_WHO_IS, handler_who_is);
// handle i-am to support binding to other devices
apdu_set_unconfirmed_handler(SERVICE_UNCONFIRMED_I_AM, handler_i_am_bind);
// set the handler for all the services we don't implement
// It is required to send the proper reject message...
apdu_set_unrecognized_service_handler_handler(handler_unrecognized_service);
// we must implement read property (it's required)
apdu_set_confirmed_handler(SERVICE_CONFIRMED_READ_PROPERTY,
handler_read_property);
// These are related to requests we make
// handle the data coming back from confirmed readProp requests
apdu_set_confirmed_ack_handler(SERVICE_CONFIRMED_READ_PROPERTY,
handlerReadPropertyAck);
// handle the simple ack for confirmed writeProp requests
apdu_set_confirmed_simple_ack_handler(SERVICE_CONFIRMED_WRITE_PROPERTY,
handlerWritePropertyAck);
// handle any errors coming back
apdu_set_error_handler(SERVICE_CONFIRMED_READ_PROPERTY, handlerError);
apdu_set_abort_handler(handlerAbort);
apdu_set_reject_handler(handlerReject);
}
BACNETMSTP* BACNETMSTP::instance()
{
if (!m_instance)
m_instance = new BACNETMSTP;
return m_instance;
}
void BACNETMSTP::initMaster(std::string port, int baudRate,
int deviceInstanceID, int macAddr, int maxMaster,
int maxInfoFrames)
{
// first some checking
// if we are already initialized, then it's too late to change things now
if (m_initialized)
{
if (m_debugging)
cerr << __FUNCTION__ << ": Instance is already initialized, ignored."
<< endl;
return;
}
// baudrate
// The standard allows (as of at least 2010) the following baud rates
if ( !(baudRate == 9600 || baudRate == 19200 || baudRate == 38400
|| baudRate == 57600 || baudRate == 76800 || baudRate == 115200) )
{
throw std::invalid_argument(std::string(__FUNCTION__)
+ ": baudRate must be 9600, 19200, 38400, "
+ " 57600, 76800, or 115200");
}
// maxMaster
// maxMaster must be less than or equal to 127
if (maxMaster < 0 || maxMaster > DEFAULT_MAX_MASTER)
{
throw std::out_of_range(std::string(__FUNCTION__)
+ ": maxMaster must be between 0 and "
+ std::to_string(DEFAULT_MAX_MASTER));
}
// As a master ourselves, we must have a MAC address also within the
// constraints of maxMaster
if (macAddr < 0 || macAddr > DEFAULT_MAX_MASTER)
{
throw std::out_of_range(std::string(__FUNCTION__)
+ ": macAddr must be between 0 and "
+ std::to_string(DEFAULT_MAX_MASTER));
}
// this should be unique on the network
if (deviceInstanceID >= BACNET_MAX_INSTANCE)
{
throw std::out_of_range(std::string(__FUNCTION__)
+ ": deviceInstanceID must be less than "
+ std::to_string(BACNET_MAX_INSTANCE)
+ ", and must be unique on the network");
}
m_port = port;
m_baudRate = baudRate;
m_maxInfoFrames = maxInfoFrames;
m_macAddr = macAddr;
m_maxMaster = maxMaster;
m_deviceInstanceID = deviceInstanceID;
// Let the fun begin...
// setup our info
Device_Set_Object_Instance_Number(m_deviceInstanceID);
address_init();
initServiceHandlers();
dlmstp_set_max_info_frames(m_maxInfoFrames);
dlmstp_set_max_master(m_maxMaster);
dlmstp_set_baud_rate(m_baudRate);
dlmstp_set_mac_address(m_macAddr);
// FIXME - allow to change?
apdu_timeout_set(m_adpuTimeoutMS);
// Ordinarily, I'd like to check the return value of this function,
// but even in the face of errors, it always returns true :( This
// function starts the ball rolling, and initializes the Master FSM
// thread. Unfortunately, it doesn't appear this can be turned back
// off without exiting the application.
datalink_init((char *)port.c_str());
m_initialized = true;
}
bool BACNETMSTP::dispatchRequest()
{
uint16_t pdu_len = 0;
unsigned timeout = 100; // milliseconds
unsigned max_apdu = 0;
time_t elapsed_seconds = 0;
time_t last_seconds = 0;
time_t current_seconds = 0;
time_t timeout_seconds = 0;
bool found = false;
// address where message came from
BACNET_ADDRESS src = {0};
clearErrors();
m_errorDetected = false;
uint32_t targetDeviceInstanceID = BACNET_MAX_INSTANCE;
switch (m_command.cmd)
{
case BACCMD_READ_PROPERTY:
targetDeviceInstanceID = m_command.readPropArgs.targetDeviceInstanceID;
break;
case BACCMD_WRITE_PROPERTY:
targetDeviceInstanceID = m_command.writePropArgs.targetDeviceInstanceID;
break;
case BACCMD_NONE:
{
m_errorType = BACERR_TYPE_UPM;
m_upmErrorString = string(__FUNCTION__) +
": called with BACCMD_NONE, ignoring";
return true; // error
}
break;
default:
{
// should this throw?
m_errorType = BACERR_TYPE_UPM;
m_upmErrorString = string(__FUNCTION__) +
": internal error, called with unknown command, ignoring";
return true; // error
}
break;
}
// timeouts
last_seconds = time(NULL);
timeout_seconds = (apdu_timeout() / 1000) * apdu_retries();
// we use 0 to indicate that request hasn't been made yet, so that
// it will be made once the address is bound.
m_invokeID = 0;
// bind to the device first.
found = address_bind_request(targetDeviceInstanceID, &max_apdu,
&(instance()->m_targetAddress));
if (!found)
{
if (m_debugging)
cerr << __FUNCTION__ << ": Address not found, Sending WhoIs..." << endl;
Send_WhoIs(targetDeviceInstanceID, targetDeviceInstanceID);
}
else
{
if (m_debugging)
cerr << __FUNCTION__ << ": Address was found" << endl;
}
// loop until either we get our data, an error occurs, or we timeout
while (true)
{
current_seconds = time(NULL);
// at least one second has passed
if (current_seconds != last_seconds)
tsm_timer_milliseconds((uint16_t) ((current_seconds -
last_seconds) * 1000));
if (m_errorDetected)
break;
// we have to wait until the address is bound before proceeding
if (!found)
{
found =
address_bind_request(targetDeviceInstanceID, &max_apdu,
&(instance()->m_targetAddress));
}
if (found)
{
// address is bound, and we have not sent our request yet. Make it so.
if (m_invokeID == 0)
{
switch (m_command.cmd)
{
case BACCMD_READ_PROPERTY:
m_invokeID =
Send_Read_Property_Request(targetDeviceInstanceID,
m_command.readPropArgs.objType,
m_command.readPropArgs.objInstance,
m_command.readPropArgs.objProperty,
m_command.readPropArgs.arrayIndex);
if (m_debugging)
cerr << __FUNCTION__
<< ": Called Send_Read_Property_Request(), m_invokeID = "
<< (int)m_invokeID << endl;
break;
case BACCMD_WRITE_PROPERTY:
m_invokeID =
Send_Write_Property_Request(targetDeviceInstanceID,
m_command.writePropArgs.objType,
m_command.writePropArgs.objInstance,
m_command.writePropArgs.objProperty,
m_command.writePropArgs.propValue,
m_command.writePropArgs.propPriority,
m_command.writePropArgs.arrayIndex);
if (m_debugging)
cerr << __FUNCTION__
<< ": Called Send_Write_Property_Request(), m_invokeID = "
<< (int)m_invokeID << endl;
break;
}
}
else if (tsm_invoke_id_free(m_invokeID))
{
// transaction completed successfully
if (m_debugging)
cerr << __FUNCTION__ << ": Success, m_invokeID = "
<< (int)m_invokeID << endl;
break;
}
else if (tsm_invoke_id_failed(m_invokeID))
{
// transaction state machine failed, most likely timeout
tsm_free_invoke_id(m_invokeID);
m_errorType = BACERR_TYPE_UPM;
m_upmErrorString = string(__FUNCTION__) +
": TSM Timed Out.";
if (m_debugging)
cerr << m_upmErrorString << endl;
m_errorDetected = true;
break;
}
}
else
{
// still waiting to bind. timeout if we've waited too long.
elapsed_seconds += (current_seconds - last_seconds);
if (elapsed_seconds > timeout_seconds)
{
m_errorType = BACERR_TYPE_UPM;
m_upmErrorString = string(__FUNCTION__) +
": Timed out waiting to bind address.";
// We output this error unconditionally as this is an
// error you will get if you supply a non-existant
// Device Obeject Instance ID.
cerr << m_upmErrorString << endl;
cerr << __FUNCTION__
<< ": Did you supply the correct Device Object Instance ID "
<< "for your device?"
<< endl;
m_errorDetected = true;
break;
}
}
// returns 0 bytes on timeout
pdu_len = datalink_receive(&src, m_rxBuffer, MAX_MPDU, timeout);
// process the packet if valid. This will call our handlers as needed.
if (pdu_len)
npdu_handler(&src, m_rxBuffer, pdu_len);
// keep track of time for next check
last_seconds = current_seconds;
}
return m_errorDetected;
}
bool BACNETMSTP::readProperty(uint32_t targetDeviceInstanceID,
BACNET_OBJECT_TYPE objType,
uint32_t objInstance,
BACNET_PROPERTY_ID objProperty,
uint32_t arrayIndex)
{
// some sanity checking...
if (objInstance >= BACNET_MAX_INSTANCE)
{
throw std::out_of_range(std::string(__FUNCTION__)
+ ": objInstance must be less than "
+ std::to_string(BACNET_MAX_INSTANCE));
}
// fill in the command structure and dispatch
m_command.cmd = BACCMD_READ_PROPERTY;
m_command.readPropArgs.targetDeviceInstanceID = targetDeviceInstanceID;
m_command.readPropArgs.objType = objType;
m_command.readPropArgs.objInstance = objInstance;
m_command.readPropArgs.objProperty = objProperty;
m_command.readPropArgs.arrayIndex = arrayIndex; // not implemented in the ack handler!
if (m_debugging)
cerr << __FUNCTION__ << ": calling dispatchRequest()..." << endl;
// send it off
bool error = dispatchRequest();
// clear the command to avoid accidental re-calls
m_command.cmd = BACCMD_NONE;
return error;
}
bool BACNETMSTP::writeProperty(uint32_t targetDeviceInstanceID,
BACNET_OBJECT_TYPE objType,
uint32_t objInstance,
BACNET_PROPERTY_ID objProperty,
BACNET_APPLICATION_DATA_VALUE* propValue,
uint8_t propPriority,
int32_t arrayIndex)
{
// some sanity checking...
if (objInstance >= BACNET_MAX_INSTANCE)
{
throw std::out_of_range(std::string(__FUNCTION__)
+ ": objInstance must be less than "
+ std::to_string(BACNET_MAX_INSTANCE));
}
// fill in the command structure and dispatch
m_command.cmd = BACCMD_WRITE_PROPERTY;
m_command.writePropArgs.targetDeviceInstanceID = targetDeviceInstanceID;
m_command.writePropArgs.objType = objType;
m_command.writePropArgs.objInstance = objInstance;
m_command.writePropArgs.objProperty = objProperty;
m_command.writePropArgs.propValue = propValue;
m_command.writePropArgs.propPriority = propPriority;
m_command.writePropArgs.arrayIndex = arrayIndex; // not implemented!
if (m_debugging)
cerr << __FUNCTION__ << ": calling dispatchRequest()..." << endl;
// send it off
bool error = dispatchRequest();
// clear the command to avoid accidental re-calls
m_command.cmd = BACCMD_NONE;
return error;
}
BACNET_APPLICATION_DATA_VALUE BACNETMSTP::getData()
{
return m_returnedValue;
}
uint8_t BACNETMSTP::getDataType()
{
return m_returnedValue.tag;
}
float BACNETMSTP::getDataTypeReal()
{
if (getDataType() == BACNET_APPLICATION_TAG_REAL)
return m_returnedValue.type.Real;
else
{
if (m_debugging)
cerr << __FUNCTION__ << ": Not of Real type, trying to convert..." << endl;
// try to convert or throw
switch (getDataType())
{
case BACNET_APPLICATION_TAG_BOOLEAN:
return (getDataTypeBoolean() ? 1.0 : 0.0);
case BACNET_APPLICATION_TAG_UNSIGNED_INT:
return float(getDataTypeUnsignedInt());
case BACNET_APPLICATION_TAG_SIGNED_INT:
return float(getDataTypeSignedInt());
default:
throw std::invalid_argument(std::string(__FUNCTION__)
+ ": data type ("
+ std::to_string(int(getDataType()))
+ ") is not convertible to Real");
}
}
}
bool BACNETMSTP::getDataTypeBoolean()
{
if (getDataType() == BACNET_APPLICATION_TAG_BOOLEAN)
return ((m_returnedValue.type.Boolean) ? true : false);
else
throw std::invalid_argument(std::string(__FUNCTION__)
+ ": data type ("
+ std::to_string(int(getDataType()))
+ ") is not convertible to Bool");
}
unsigned int BACNETMSTP::getDataTypeUnsignedInt()
{
if (getDataType() == BACNET_APPLICATION_TAG_UNSIGNED_INT)
return m_returnedValue.type.Unsigned_Int;
else
throw std::invalid_argument(std::string(__FUNCTION__)
+ ": data type ("
+ std::to_string(int(getDataType()))
+ ") is not convertible to UnsignedInt");
}
int BACNETMSTP::getDataTypeSignedInt()
{
if (getDataType() == BACNET_APPLICATION_TAG_SIGNED_INT)
return m_returnedValue.type.Signed_Int;
else
throw std::invalid_argument(std::string(__FUNCTION__)
+ ": data type ("
+ std::to_string(int(getDataType()))
+ ") is not convertible to SignedInt");
}
#if defined(BACAPP_DOUBLE)
double BACNETMSTP::getDataTypeDouble()
{
if (getDataType() == BACNET_APPLICATION_TAG_DOUBLE)
return m_returnedValue.type.Double;
else
{
if (m_debugging)
cerr << __FUNCTION__ << ": Not of Double type, trying to convert..." << endl;
// try to convert or throw
switch (getDataType())
{
case BACNET_APPLICATION_TAG_REAL:
return double(getDataTypeReal());
case BACNET_APPLICATION_TAG_BOOLEAN:
return (getDataTypeBoolean() ? 1.0 : 0.0);
case BACNET_APPLICATION_TAG_UNSIGNED_INT:
return double(getDataTypeUnsignedInt());
case BACNET_APPLICATION_TAG_SIGNED_INT:
return double(getDataTypeSignedInt());
default:
throw std::invalid_argument(std::string(__FUNCTION__)
+ ": data type ("
+ std::to_string(int(getDataType()))
+ ") is not convertible to Double");
}
}
}
#endif // BACAPP_DOUBLE
unsigned int BACNETMSTP::getDataTypeEnum()
{
if (getDataType() == BACNET_APPLICATION_TAG_ENUMERATED)
return m_returnedValue.type.Enumerated;
else
throw std::invalid_argument(std::string(__FUNCTION__)
+ ": data type ("
+ std::to_string(int(getDataType()))
+ ") is not convertible to Enum");
}
std::string BACNETMSTP::getDataTypeString()
{
string retval;
// Here, we can try to accomodate all the types
switch(getDataType())
{
case BACNET_APPLICATION_TAG_REAL:
retval = std::to_string(getDataTypeReal());
break;
#if defined(BACAPP_DOUBLE)
case BACNET_APPLICATION_TAG_DOUBLE:
retval = std::to_string(getDataTypeDouble());
break;
#endif // BACAPP_DOUBLE
case BACNET_APPLICATION_TAG_UNSIGNED_INT:
retval = std::to_string(getDataTypeUnsignedInt());
break;
case BACNET_APPLICATION_TAG_SIGNED_INT:
retval = std::to_string(getDataTypeSignedInt());
break;
case BACNET_APPLICATION_TAG_BOOLEAN:
retval = (getDataTypeBoolean() ? string("true") : string("false"));
break;
case BACNET_APPLICATION_TAG_CHARACTER_STRING:
retval = string(characterstring_value(&m_returnedValue.type.Character_String),
characterstring_length(&m_returnedValue.type.Character_String));
break;
case BACNET_APPLICATION_TAG_OCTET_STRING:
{
string tmpstr((char *)octetstring_value(&m_returnedValue.type.Octet_String),
octetstring_length(&m_returnedValue.type.Octet_String));
retval = string2HexString(tmpstr);
}
break;
case BACNET_APPLICATION_TAG_BIT_STRING:
{
int len = bitstring_bits_used(&m_returnedValue.type.Bit_String);
for (int i=0; i<len; i++)
{
if (bitstring_bit(&m_returnedValue.type.Bit_String, uint8_t(i)))
retval += "1";
else
retval += "0";
if (i != 0 && ((i % 8) == 0))
retval += " ";
}
}
break;
default:
throw std::invalid_argument(std::string(__FUNCTION__)
+ ": data type ("
+ std::to_string(int(getDataType()))
+ ") is not convertible to String");
break;
}
return retval;
}
BACNET_APPLICATION_DATA_VALUE BACNETMSTP::createDataReal(float value)
{
BACNET_APPLICATION_DATA_VALUE data;
memset(&data, 0, sizeof(BACNET_APPLICATION_DATA_VALUE));
data.tag = BACNET_APPLICATION_TAG_REAL;
data.type.Real = value;
return data;
}
BACNET_APPLICATION_DATA_VALUE BACNETMSTP::createDataBool(bool value)
{
BACNET_APPLICATION_DATA_VALUE data;
memset(&data, 0, sizeof(BACNET_APPLICATION_DATA_VALUE));
data.tag = BACNET_APPLICATION_TAG_BOOLEAN;
data.type.Boolean = value;
return data;
}
BACNET_APPLICATION_DATA_VALUE BACNETMSTP::createDataSignedInt(int value)
{
BACNET_APPLICATION_DATA_VALUE data;
memset(&data, 0, sizeof(BACNET_APPLICATION_DATA_VALUE));
data.tag = BACNET_APPLICATION_TAG_SIGNED_INT;
data.type.Signed_Int = value;
return data;
}
BACNET_APPLICATION_DATA_VALUE BACNETMSTP::createDataUnsignedInt(unsigned int value)
{
BACNET_APPLICATION_DATA_VALUE data;
memset(&data, 0, sizeof(BACNET_APPLICATION_DATA_VALUE));
data.tag = BACNET_APPLICATION_TAG_UNSIGNED_INT;
data.type.Unsigned_Int = value;
return data;
}
BACNET_APPLICATION_DATA_VALUE BACNETMSTP::createDataString(string value)
{
if (value.size() > (MAX_CHARACTER_STRING_BYTES - 1))
{
throw std::invalid_argument(std::string(__FUNCTION__)
+ ": value must be less than or equal to "
+ std::to_string(MAX_CHARACTER_STRING_BYTES - 1)
+ " characters long");
}
BACNET_APPLICATION_DATA_VALUE data;
memset(&data, 0, sizeof(BACNET_APPLICATION_DATA_VALUE));
data.tag = BACNET_APPLICATION_TAG_CHARACTER_STRING;
characterstring_init_ansi(&data.type.Character_String, value.c_str());
return data;
}
string BACNETMSTP::string2HexString(string input)
{
static const char* const lut = "0123456789abcdef";
size_t len = input.size();
string output;
output.reserve(3 * len);
for (size_t i = 0; i < len; ++i)
{
const unsigned char c = input[i];
output.push_back(lut[c >> 4]);
output.push_back(lut[c & 15]);
output.push_back(' ');
}
return output;
}

716
src/bacnetmstp/bacnetmstp.h Normal file
View File

@ -0,0 +1,716 @@
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <string>
// we only support a BACnet RS-485 MS/TP datalink
#define BACDL_MSTP 1
#undef BACDL_ALL
// get a variety of bacnet-stack includes...
#include "bacdef.h"
#include "config.h"
#include "bactext.h"
#include "bacerror.h"
#include "iam.h"
#include "arf.h"
#include "tsm.h"
#include "address.h"
#include "npdu.h"
#include "apdu.h"
#include "device.h"
#include "datalink.h"
#include "whois.h"
#include "mstpdef.h"
#include "dlmstp.h"
namespace upm {
/**
* @brief BACNETMSTP base class
* @defgroup bacnetmstp libupm-bacnetmstp
* @ingroup uart
*/
/**
* @library bacnetmstp
* @sensor bacnetmstp
* @comname UPM API for BACNET MS/TP communications
* @con uart
* @web http://bacnet.sourceforge.net/
* @brief UPM API for BACNETMSTP
*
* This is a singleton class that provides services to UPM BACnet
* drivers (like E50HX) based on the bacnet-stack at
* http://bacnet.sourceforge.net . This class is implemented as a
* singleton due to the fact that the bacnet-stack implementation
* does not currently allow multiple simultaneous datalinks. We are
* using 0.8.3 of bacnet-stack. In the future this restriction may
* be lifted depending on bacnet-stack, but for now, you are
* stuck with only a single BACnet MS/TP datalink.
*
* This driver is not intended to be used by end users. It is
* intended for use with other UPM drivers that require access to a
* BACnet MS/TP (Master Slave/Token Passing) network over RS-485.
*
* For this reason, no examples are provided. If you wish to
* implement your own BACnet MS/TP driver, please look at the E50HX
* driver to see how this class can be used.
*
* Currently, only readProperty and writeProperty BACnet requests
* are supported. In the future, any other BACnet requests could be
* supported as well. readProperty and writeProperty should provide
* most of what you will need when communicating with BACnet
* devices. Since the source code is open, feel free to add other
* services as you see fit :)
*
* In order to make requests over an MS/TP network, you must be a
* BACnet master. initMaster() is responsible for configuring your
* underlying RS-485 network and starting a Master FSM (finite state
* machine) thread that will be responsible for identifying other
* Masters on the network and negotiating token passing. Your
* master can only transmit when it has the token.
*
* Fortunately, all of these messy details are handled for you by
* this class, or the underlying bacnet-stack library this class
* relies on.
*/
class BACNETMSTP {
// Constructor and destructor are protected
public:
// error types
typedef enum {
BACERR_TYPE_NONE = 0,
BACERR_TYPE_REJECT,
BACERR_TYPE_ABORT,
BACERR_TYPE_ERROR,
BACERR_TYPE_UPM
} BACERR_TYPE_T;
// command types we currently support
typedef enum {
BACCMD_NONE = 0,
BACCMD_READ_PROPERTY,
BACCMD_WRITE_PROPERTY
} BACCMD_TYPE_T;
/**
* Get our singleton instance, initializing it if neccessary. All
* requests to this class should be done through this instance
* accessor.
*
* @return static pointer to our class instance
*/
static BACNETMSTP* instance();
/**
* This function initializes the underlying BACNETMSTP Master
* singleton in the event it has not already been initialized. If
* the BACNETMSTP Master singleton has already been initialized,
* then this call will be ignored. There can be only one.
*
* @param port The serial port that the RS-485 interface is
* connected to.
* @param baudRate The baudrate of the RS-485 interface. All
* devices on a BACnet RS-485 bus must run at the same baudrate.
* Valid values are 9600, 19200, 38400, 57600, 76800, and 115200.
* @param deviceInstanceNumber This is the unique Device Object
* Instance number that will be used for our BACnet Master in
* order to communicate over the BACnet interface. This number
* must be between 1-4194302 and must be unique on the BACnet
* network.
* @param macAddr This is the MAC address of our BACnet Master.
* It must be unique on the BACnet segment, and must be between
* 1-127.
* @param maxMaster This specifies to our Master the maximum MAC
* address used by any other Masters on the BACnet network. This
* must be between 1-127, the default is 127. Do not change this
* unless you know what you are doing or you could introduce
* token passing errors on the BACnet network.
* @param maxInfoFrames This number specifies the maximum number
* of transmissions (like requests for data) our Master is allowed
* to make before passing the token to the next Master. The
* default is 1.
*/
void initMaster(std::string port, int baudRate, int deviceInstanceNumber,
int macAddr, int maxMaster=DEFAULT_MAX_MASTER,
int maxInfoFrames=1);
/**
* Perform a BACnet readProperty transaction. This function will
* return when either the transaction has completed, or an error
* has occurred. It requests the value of a property, belonging
* to a specific object instance on a specific device.
*
* @param targetDeviceInstanceID This is the Device Object
* Instance ID of the device to send the request to. This number
* will be unique for every device on the network. An address
* lookup will be performed the first time a request is made to a
* device using the WhoHas BACnet service. The result will be
* cached for further use.
* @param objType This is the BACnet object type of the object you
* wish to query. It should be one of the BACNET_OBJECT_TYPE
* values.
* @param objInstance This is the instance number of the Object
* you wish to access. It is an integer starting from 1.
* @param objProperty This is the property of the Object and
* instance you wish to access. It should be one of the
* BACNET_PROPERTY_ID values.
* @param arrayIndex This specifies the index number of an array
* property. This is not currently supported. Until it is, leave
* the default at BACNET_ARRAY_ALL.
* @return true if an error occurred, false otherwise.
*/
bool readProperty(uint32_t targetDeviceInstanceID,
BACNET_OBJECT_TYPE objType,
uint32_t objInstance,
BACNET_PROPERTY_ID objProperty,
uint32_t arrayIndex=BACNET_ARRAY_ALL);
/**
* Perform a BACnet writeProperty transaction. This function will
* return when either the transaction has completed, or an error
* has occurred. It writes the supplied value to a property,
* belonging to a specific object instance on a specific device.
*
* @param targetDeviceInstanceID This is the Device Object
* Instance ID of the device to send the request to. This number
* will be unique for every device on the network. An address
* lookup will be performed the first time a request is made to a
* device using the WhoHas BACnet service. The result will be
* cached for further use.
* @param objType This is the BACnet object type of the object you
* wish to query. It should be one of the BACNET_OBJECT_TYPE
* values.
* @param objInstance This is the instance number of the Object
* you wish to access. It is an integer starting from 1.
* @param objProperty This is the property of the Object and
* instance you wish to access. It should be one of the
* BACNET_PROPERTY_ID values.
* @param propValue This is a pointer to a
* BACNET_APPLICATION_DATA_VALUE structure containg the data value
* to write to the property. Use the createData*() methods to
* properly create these structures.
* @param propPriority This specifies the priority of a
* commandable property. Leave it at the default unless you know
* what you are doing. In addition, there is conflicting
* information in the bacnet-stack documentation as to whether
* this is even supported.
* @param arrayIndex This specifies the index number of an array
* property. This is not currently supported. Until it is, leave
* the default at BACNET_ARRAY_ALL.
* @return true if an error occurred, false otherwise.
*/
bool writeProperty(uint32_t targetDeviceInstanceID,
BACNET_OBJECT_TYPE objType,
uint32_t objInstance,
BACNET_PROPERTY_ID objProperty,
BACNET_APPLICATION_DATA_VALUE* propValue,
uint8_t propPriority=BACNET_NO_PRIORITY,
int32_t arrayIndex=BACNET_ARRAY_ALL);
/**
* After a successful readProperty request, this method can be used
* to return a BACNET_APPLICATION_DATA_VALUE structure containing
* the returned data.
*
* @return a BACNET_APPLICATION_DATA_VALUE structure containing
* the returned data.
*/
BACNET_APPLICATION_DATA_VALUE getData();
/**
* After a successful readProperty request, this method can be
* used to return the BACnet data type of the returned data. It
* will be one of the BACNET_APPLICATION_TAG_* values.
*
* @return A BACNET_APPLICATION_TAG_* value
*/
uint8_t getDataType();
/**
* After a successful readProperty request, this method can be
* used to return the BACnet dataype of the returned data as a
* Real. If the data type (getDataType()) is not a
* BACNET_APPLICATION_TAG_REAL, and the value returned cannot be
* safely converted, an exception is thrown.
*
* @return A floating point value representing the returned data
*/
float getDataTypeReal();
/**
* After a successful readProperty request, this method can be
* used to return the BACnet dataype of the returned data as a
* Boolean. If the data type (getDataType()) is not a
* BACNET_APPLICATION_TAG_BOOLEAN, and the value returned cannot
* be safely converted, an exception is thrown.
*
* @return A boolean value representing the returned data
*/
bool getDataTypeBoolean();
/**
* After a successful readProperty request, this method can be
* used to return the BACnet dataype of the returned data as a
* unsigned int. If the data type (getDataType()) is not a
* BACNET_APPLICATION_TAG_UNSIGNED_INT, and the value returned
* cannot be safely converted, an exception is thrown.
*
* @return An unsigned int value representing the returned data
*/
unsigned int getDataTypeUnsignedInt();
/**
* After a successful readProperty request, this method can be
* used to return the BACnet dataype of the returned data as a
* signed int. If the data type (getDataType()) is not a
* BACNET_APPLICATION_TAG_SIGNED_INT, and the value returned
* cannot be safely converted, an exception is thrown.
*
* @return A signed int value representing the returned data
*/
int getDataTypeSignedInt();
/**
* After a successful readProperty request, this method can be
* used to return the BACnet dataype of the returned data as a
* string. Most of the data types except Enum can be converted to
* a string. If the data type (getDataType()) is not a
* BACNET_APPLICATION_TAG_CHARACTER_STRING, and the value returned
* cannot be safely converted, an exception is thrown.
*
* @return A string value representing the returned data
*/
std::string getDataTypeString();
/**
* After a successful readProperty request, this method can be
* used to return the BACnet dataype of the returned data as an
* enumeration. If the data type (getDataType()) is not a
* BACNET_APPLICATION_TAG_ENUMERATED an exception is thrown.
*
* @return An unsigned int representing a BACnet enumerant
*/
unsigned int getDataTypeEnum();
#if defined(BACAPP_DOUBLE)
/**
* After a successful readProperty request, this method can be
* used to return the BACnet dataype of the returned data as a
* double. If the data type (getDataType()) is not a
* BACNET_APPLICATION_TAG_DOUBLE, and the value returned cannot be
* safely converted, an exception is thrown.
*
* @return A double floating point value representing the returned data
*/
double getDataTypeDouble();
#endif // BACAPP_DOUBLE
/**
* This method is used to create and return an initialized
* BACNET_APPLICATION_DATA_VALUE containing a real (floating point
* value). A pointer to this returned structure can then be used
* with writeProperty().
*
* @param value The floating point value to initialize the structure to.
* @return An initialized structure containing the value
*/
BACNET_APPLICATION_DATA_VALUE createDataReal(float Real);
/**
* This method is used to create and return an initialized
* BACNET_APPLICATION_DATA_VALUE containing a boolean. A pointer
* to this returned structure can then be used with
* writeProperty().
*
* @param value The boolean value to initialize the structure to.
* @return An initialized structure containing the value
*/
BACNET_APPLICATION_DATA_VALUE createDataBool(bool value);
/**
* This method is used to create and return an initialized
* BACNET_APPLICATION_DATA_VALUE containing a signed integer. A
* pointer to this returned structure can then be used with
* writeProperty().
*
* @param value The signed integer value to initialize the structure to.
* @return An initialized structure containing the value
*/
BACNET_APPLICATION_DATA_VALUE createDataSignedInt(int value);
/**
* This method is used to create and return an initialized
* BACNET_APPLICATION_DATA_VALUE containing a unsigned integer. A
* pointer to this returned structure can then be used with
* writeProperty().
*
* @param value The unsigned integer value to initialize the
* structure to.
* @return An initialized structure containing the value
*/
BACNET_APPLICATION_DATA_VALUE createDataUnsignedInt(unsigned int value);
/**
* This method is used to create and return an initialized
* BACNET_APPLICATION_DATA_VALUE containing a character string. A
* pointer to this returned structure can then be used with
* writeProperty(). Strings are typically limited to 63 characters.
*
* @param value The character string value to initialize the
* structure to.
* @return An initialized structure containing the value
*/
BACNET_APPLICATION_DATA_VALUE createDataString(std::string value);
/**
* Return an enumration of the last error type to occur. The
* value returned will be one of the BACERR_TYPE_T values.
*
* @return The last error type to occur, one of the BACERR_TYPE_T
* values.
*/
BACERR_TYPE_T getErrorType()
{
return m_errorType;
};
/**
* In the event of a BACnet Reject error, return the error code.
*
* @return The Reject error code.
*/
uint8_t getRejectReason()
{
return m_rejectReason;
};
/**
* In the event of a BACnet Reject error, return the error string.
*
* @return The Reject error string.
*/
std::string getRejectString()
{
return m_rejectString;
};
/**
* In the event of a BACnet Abort error, return the Abort reason code.
*
* @return The Abort reason code.
*/
uint8_t getAbortReason()
{
return m_abortReason;
};
/**
* In the event of a BACnet Abort error, return the Abort string.
*
* @return The Abort error string.
*/
std::string getAbortString()
{
return m_abortString;
};
/**
* In the event of a general BACnet error, return the BACnet error class.
*
* @return One of the BACNET_ERROR_CLASS error class codes
*/
BACNET_ERROR_CLASS getErrorClass()
{
return m_errorClass;
};
/**
* In the event of a general BACnet error, return the BACnet error code.
*
* @return One of the BACNET_ERROR_CODE error codes
*/
BACNET_ERROR_CODE getErrorCode()
{
return m_errorCode;
};
/**
* In the event of a general BACnet error, return the BACnet error
* string.
*
* @return A string representing the BACnet error class and code.
*/
std::string getErrorString()
{
return m_errorString;
};
/**
* In the event of a non-BACnet UPM error, return a string
* describing the error.
*
* @return A string representing the UPM error.
*/
std::string getUPMErrorString()
{
return m_upmErrorString;
};
/**
* Check to see if initMaster) has already been called, and out
* master is initialized.
*
* @return true if the master is initialized, false otherwise
*/
bool isInitialized()
{
return m_initialized;
};
/**
* Return the port that was specified to initMaster().
*
* @return The port specified to initMaster().
*/
std::string getPort()
{
return m_port;
};
/**
* Return the Object Device Instance ID for our Master was
* specified to initMaster().
*
* @return The Object Device Instance ID for our Master.
*/
uint32_t getDeviceInstanceID()
{
return m_deviceInstanceID;
};
/**
* Return the maxInfoFrames parameter that was specified to initMaster().
*
* @return The maxInfoFrames parameter specified to initMaster().
*/
int getMaxInfoFrames()
{
return m_maxInfoFrames;
};
/**
* Return the maxMaster parameter that was specified to initMaster().
*
* @return The maxMaster parameter specified to initMaster().
*/
int getMaxMaster()
{
return m_maxMaster;
};
/**
* Return the baud rate parameter that was specified to initMaster().
*
* @return The baud rate parameter specified to initMaster().
*/
int getBaudRate()
{
return m_baudRate;
};
/**
* Return the MAC address parameter that was specified to initMaster().
*
* @return The MAC address parameter specified to initMaster().
*/
int getMACAddress()
{
return m_macAddr;
};
/**
* Enable or disable debugging output.
*
* @param enable true to enable debugging, false otherwise
*/
void setDebug(bool enable);
protected:
/**
* BACNETMSTP constructor
*/
BACNETMSTP();
/**
* BACNETMSTP Destructor
*/
~BACNETMSTP();
// clear/reset error states
void clearErrors();
// error handler
static void handlerError(BACNET_ADDRESS * src,
uint8_t invoke_id,
BACNET_ERROR_CLASS error_class,
BACNET_ERROR_CODE error_code);
// abort handler
static void handlerAbort(BACNET_ADDRESS * src,
uint8_t invoke_id,
uint8_t abort_reason,
bool server);
// reject handler
static void handlerReject(BACNET_ADDRESS * src,
uint8_t invoke_id,
uint8_t reject_reason);
// our handler for dealing with return data from a ReadProperty call
static void handlerReadPropertyAck(uint8_t* service_request,
uint16_t service_len,
BACNET_ADDRESS* src,
BACNET_CONFIRMED_SERVICE_ACK_DATA* service_data);
// our handler for writeProp acks
static void handlerWritePropertyAck(BACNET_ADDRESS* src,
uint8_t invoke_id);
// initialize our service handlers
void initServiceHandlers();
// utility function
std::string string2HexString(std::string input);
// responsible for dispatching a request to the BACnet network
bool dispatchRequest();
private:
// prevent copying and assignment
BACNETMSTP(BACNETMSTP const &) {};
BACNETMSTP& operator=(BACNETMSTP const&) {};
// our class instance
static BACNETMSTP* m_instance;
// has the class been created yet?
bool m_initialized;
// Some items we can set for our master
std::string m_port;
int m_maxInfoFrames;
int m_maxMaster;
int m_baudRate;
int m_macAddr;
// the unique Instance Number of our Master Device Object
uint32_t m_deviceInstanceID;
// adpu timeout in milliseconds
uint16_t m_adpuTimeoutMS;
// buffer used for receiving data
uint8_t m_rxBuffer[MAX_MPDU];
// our error classfication
BACERR_TYPE_T m_errorType;
// BACnet reject info
uint8_t m_rejectReason;
std::string m_rejectString;
// BACnet abort info
uint8_t m_abortReason;
std::string m_abortString;
// BACnet error info
BACNET_ERROR_CLASS m_errorClass;
BACNET_ERROR_CODE m_errorCode;
std::string m_errorString;
// generic UPM related errors - we just set the error text to
// something informative.
std::string m_upmErrorString;
// our returned data from readProperty()
BACNET_APPLICATION_DATA_VALUE m_returnedValue;
// current bound target address of dispatched service request
// (read/write prop, etc)
BACNET_ADDRESS m_targetAddress;
// current invokeID (for transaction handling)
uint8_t m_invokeID;
// error detected flag
bool m_errorDetected;
// Commands - we create a struct to hold the arguments for each
// command type we support. Then, we create a command struct
// which contains the command type and a union containing the
// relevant arguments. This is used by dispatchRequest() to issue
// the correct request.
// these may generate SWIG warnings, but they can be ignored as we
// do not expose these outside the class
typedef struct {
uint32_t targetDeviceInstanceID;
BACNET_OBJECT_TYPE objType;
uint32_t objInstance;
BACNET_PROPERTY_ID objProperty;
uint32_t arrayIndex;
} READ_PROPERTY_ARGS_T;
typedef struct {
uint32_t targetDeviceInstanceID;
BACNET_OBJECT_TYPE objType;
uint32_t objInstance;
BACNET_PROPERTY_ID objProperty;
BACNET_APPLICATION_DATA_VALUE* propValue;
uint8_t propPriority;
int32_t arrayIndex;
} WRITE_PROPERTY_ARGS_T;
struct {
BACCMD_TYPE_T cmd;
union {
READ_PROPERTY_ARGS_T readPropArgs;
WRITE_PROPERTY_ARGS_T writePropArgs;
};
} m_command;
bool m_debugging;
};
}

File diff suppressed because it is too large Load Diff

465
src/bacnetmstp/device.h Normal file
View File

@ -0,0 +1,465 @@
/**************************************************************************
*
* Copyright (C) 2005 Steve Karg <skarg@users.sourceforge.net>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*********************************************************************/
/** @file device.h Defines functions for handling all BACnet objects belonging
* to a BACnet device, as well as Device-specific properties. */
#ifndef DEVICE_H
#define DEVICE_H
#include <stdbool.h>
#include <stdint.h>
#include "bacdef.h"
#include "bacenum.h"
#include "wp.h"
#include "rd.h"
#include "rp.h"
#include "rpm.h"
#include "readrange.h"
/** Called so a BACnet object can perform any necessary initialization.
* @ingroup ObjHelpers
*/
typedef void (
*object_init_function) (
void);
/** Counts the number of objects of this type.
* @ingroup ObjHelpers
* @return Count of implemented objects of this type.
*/
typedef unsigned (
*object_count_function) (
void);
/** Maps an object index position to its corresponding BACnet object instance number.
* @ingroup ObjHelpers
* @param index [in] The index of the object, in the array of objects of its type.
* @return The BACnet object instance number to be used in a BACNET_OBJECT_ID.
*/
typedef uint32_t(
*object_index_to_instance_function)
(
unsigned index);
/** Provides the BACnet Object_Name for a given object instance of this type.
* @ingroup ObjHelpers
* @param object_instance [in] The object instance number to be looked up.
* @param object_name [in,out] Pointer to a character_string structure that
* will hold a copy of the object name if this is a valid object_instance.
* @return True if the object_instance is valid and object_name has been
* filled with a copy of the Object's name.
*/
typedef bool(
*object_name_function)
(
uint32_t object_instance,
BACNET_CHARACTER_STRING * object_name);
/** Look in the table of objects of this type, and see if this is a valid
* instance number.
* @ingroup ObjHelpers
* @param [in] The object instance number to be looked up.
* @return True if the object instance refers to a valid object of this type.
*/
typedef bool(
*object_valid_instance_function) (
uint32_t object_instance);
/** Helper function to step through an array of objects and find either the
* first one or the next one of a given type. Used to step through an array
* of objects which is not necessarily contiguious for each type i.e. the
* index for the 'n'th object of a given type is not necessarily 'n'.
* @ingroup ObjHelpers
* @param [in] The index of the current object or a value of ~0 to indicate
* start at the beginning.
* @return The index of the next object of the required type or ~0 (all bits
* == 1) to indicate no more objects found.
*/
typedef unsigned (
*object_iterate_function) (
unsigned current_index);
/** Look in the table of objects of this type, and get the COV Value List.
* @ingroup ObjHelpers
* @param [in] The object instance number to be looked up.
* @param [out] The value list
* @return True if the object instance supports this feature, and has changed.
*/
typedef bool(
*object_value_list_function) (
uint32_t object_instance,
BACNET_PROPERTY_VALUE * value_list);
/** Look in the table of objects for this instance to see if value changed.
* @ingroup ObjHelpers
* @param [in] The object instance number to be looked up.
* @return True if the object instance has changed.
*/
typedef bool(
*object_cov_function) (
uint32_t object_instance);
/** Look in the table of objects for this instance to clear the changed flag.
* @ingroup ObjHelpers
* @param [in] The object instance number to be looked up.
*/
typedef void (
*object_cov_clear_function) (
uint32_t object_instance);
/** Intrinsic Reporting funcionality.
* @ingroup ObjHelpers
* @param [in] Object instance.
*/
typedef void (
*object_intrinsic_reporting_function) (
uint32_t object_instance);
/** Defines the group of object helper functions for any supported Object.
* @ingroup ObjHelpers
* Each Object must provide some implementation of each of these helpers
* in order to properly support the handlers. Eg, the ReadProperty handler
* handler_read_property() relies on the instance of Object_Read_Property
* for each Object type, or configure the function as NULL.
* In both appearance and operation, this group of functions acts like
* they are member functions of a C++ Object base class.
*/
typedef struct object_functions {
BACNET_OBJECT_TYPE Object_Type;
object_init_function Object_Init;
object_count_function Object_Count;
object_index_to_instance_function Object_Index_To_Instance;
object_valid_instance_function Object_Valid_Instance;
object_name_function Object_Name;
read_property_function Object_Read_Property;
write_property_function Object_Write_Property;
rpm_property_lists_function Object_RPM_List;
rr_info_function Object_RR_Info;
object_iterate_function Object_Iterator;
object_value_list_function Object_Value_List;
object_cov_function Object_COV;
object_cov_clear_function Object_COV_Clear;
object_intrinsic_reporting_function Object_Intrinsic_Reporting;
} object_functions_t;
/* String Lengths - excluding any nul terminator */
#define MAX_DEV_NAME_LEN 32
#define MAX_DEV_LOC_LEN 64
#define MAX_DEV_MOD_LEN 32
#define MAX_DEV_VER_LEN 16
#define MAX_DEV_DESC_LEN 64
/** Structure to define the Object Properties common to all Objects. */
typedef struct commonBacObj_s {
/** The BACnet type of this object (ie, what class is this object from?).
* This property, of type BACnetObjectType, indicates membership in a
* particular object type class. Each inherited class will be of one type.
*/
BACNET_OBJECT_TYPE mObject_Type;
/** The instance number for this class instance. */
uint32_t Object_Instance_Number;
/** Object Name; must be unique.
* This property, of type CharacterString, shall represent a name for
* the object that is unique within the BACnet Device that maintains it.
*/
char Object_Name[MAX_DEV_NAME_LEN];
} COMMON_BAC_OBJECT;
/** Structure to define the Properties of Device Objects which distinguish
* one instance from another.
* This structure only defines fields for properties that are unique to
* a given Device object. The rest may be fixed in device.c or hard-coded
* into the read-property encoding.
* This may be useful for implementations which manage multiple Devices,
* eg, a Gateway.
*/
typedef struct devObj_s {
/** The BACnet Device Address for this device; ->len depends on DLL type. */
BACNET_ADDRESS bacDevAddr;
/** Structure for the Object Properties common to all Objects. */
COMMON_BAC_OBJECT bacObj;
/** Device Description. */
char Description[MAX_DEV_DESC_LEN];
/** The upcounter that shows if the Device ID or object structure has changed. */
uint32_t Database_Revision;
} DEVICE_OBJECT_DATA;
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
void Device_Init(
object_functions_t * object_table);
bool Device_Reinitialize(
BACNET_REINITIALIZE_DEVICE_DATA * rd_data);
BACNET_REINITIALIZED_STATE Device_Reinitialized_State(
void);
rr_info_function Device_Objects_RR_Info(
BACNET_OBJECT_TYPE object_type);
void Device_getCurrentDateTime(
BACNET_DATE_TIME * DateTime);
int32_t Device_UTC_Offset(void);
bool Device_Daylight_Savings_Status(void);
void Device_Property_Lists(
const int **pRequired,
const int **pOptional,
const int **pProprietary);
void Device_Objects_Property_List(
BACNET_OBJECT_TYPE object_type,
struct special_property_list_t *pPropertyList);
/* functions to support COV */
bool Device_Encode_Value_List(
BACNET_OBJECT_TYPE object_type,
uint32_t object_instance,
BACNET_PROPERTY_VALUE * value_list);
bool Device_Value_List_Supported(
BACNET_OBJECT_TYPE object_type);
bool Device_COV(
BACNET_OBJECT_TYPE object_type,
uint32_t object_instance);
void Device_COV_Clear(
BACNET_OBJECT_TYPE object_type,
uint32_t object_instance);
uint32_t Device_Object_Instance_Number(
void);
bool Device_Set_Object_Instance_Number(
uint32_t object_id);
bool Device_Valid_Object_Instance_Number(
uint32_t object_id);
unsigned Device_Object_List_Count(
void);
bool Device_Object_List_Identifier(
unsigned array_index,
int *object_type,
uint32_t * instance);
unsigned Device_Count(
void);
uint32_t Device_Index_To_Instance(
unsigned index);
bool Device_Object_Name(
uint32_t object_instance,
BACNET_CHARACTER_STRING * object_name);
bool Device_Set_Object_Name(
BACNET_CHARACTER_STRING * object_name);
/* Copy a child object name, given its ID. */
bool Device_Object_Name_Copy(
BACNET_OBJECT_TYPE object_type,
uint32_t object_instance,
BACNET_CHARACTER_STRING * object_name);
bool Device_Object_Name_ANSI_Init(const char * value);
BACNET_DEVICE_STATUS Device_System_Status(
void);
int Device_Set_System_Status(
BACNET_DEVICE_STATUS status,
bool local);
const char *Device_Vendor_Name(
void);
uint16_t Device_Vendor_Identifier(
void);
void Device_Set_Vendor_Identifier(
uint16_t vendor_id);
const char *Device_Model_Name(
void);
bool Device_Set_Model_Name(
const char *name,
size_t length);
const char *Device_Firmware_Revision(
void);
const char *Device_Application_Software_Version(
void);
bool Device_Set_Application_Software_Version(
const char *name,
size_t length);
const char *Device_Description(
void);
bool Device_Set_Description(
const char *name,
size_t length);
const char *Device_Location(
void);
bool Device_Set_Location(
const char *name,
size_t length);
/* some stack-centric constant values - no set methods */
uint8_t Device_Protocol_Version(
void);
uint8_t Device_Protocol_Revision(
void);
BACNET_SEGMENTATION Device_Segmentation_Supported(
void);
uint32_t Device_Database_Revision(
void);
void Device_Set_Database_Revision(
uint32_t revision);
void Device_Inc_Database_Revision(
void);
bool Device_Valid_Object_Name(
BACNET_CHARACTER_STRING * object_name,
int *object_type,
uint32_t * object_instance);
bool Device_Valid_Object_Id(
int object_type,
uint32_t object_instance);
int Device_Read_Property(
BACNET_READ_PROPERTY_DATA * rpdata);
bool Device_Write_Property(
BACNET_WRITE_PROPERTY_DATA * wp_data);
bool DeviceGetRRInfo(
BACNET_READ_RANGE_DATA * pRequest, /* Info on the request */
RR_PROP_INFO * pInfo); /* Where to put the information */
int Device_Read_Property_Local(
BACNET_READ_PROPERTY_DATA * rpdata);
bool Device_Write_Property_Local(
BACNET_WRITE_PROPERTY_DATA * wp_data);
#if defined(INTRINSIC_REPORTING)
void Device_local_reporting(
void);
#endif
/* Prototypes for Routing functionality in the Device Object.
* Enable by defining BAC_ROUTING in config.h and including gw_device.c
* in the build (lib/Makefile).
*/
void Routing_Device_Init(
uint32_t first_object_instance);
uint16_t Add_Routed_Device(
uint32_t Object_Instance,
BACNET_CHARACTER_STRING * Object_Name,
const char *Description);
DEVICE_OBJECT_DATA *Get_Routed_Device_Object(
int idx);
BACNET_ADDRESS *Get_Routed_Device_Address(
int idx);
void routed_get_my_address(
BACNET_ADDRESS * my_address);
bool Routed_Device_Address_Lookup(
int idx,
uint8_t address_len,
uint8_t * mac_adress);
bool Routed_Device_GetNext(
BACNET_ADDRESS * dest,
int *DNET_list,
int *cursor);
bool Routed_Device_Is_Valid_Network(
uint16_t dest_net,
int *DNET_list);
uint32_t Routed_Device_Index_To_Instance(
unsigned index);
bool Routed_Device_Valid_Object_Instance_Number(
uint32_t object_id);
bool Routed_Device_Name(
uint32_t object_instance,
BACNET_CHARACTER_STRING * object_name);
uint32_t Routed_Device_Object_Instance_Number(
void);
bool Routed_Device_Set_Object_Instance_Number(
uint32_t object_id);
bool Routed_Device_Set_Object_Name(
uint8_t encoding,
const char *value,
size_t length);
bool Routed_Device_Set_Description(
const char *name,
size_t length);
void Routed_Device_Inc_Database_Revision(
void);
int Routed_Device_Service_Approval(
BACNET_CONFIRMED_SERVICE service,
int service_argument,
uint8_t * apdu_buff,
uint8_t invoke_id);
#ifdef __cplusplus
}
#endif /* __cplusplus */
/** @defgroup ObjFrmwk Object Framework
* The modules in this section describe the BACnet-stack's framework for
* BACnet-defined Objects (Device, Analog Input, etc). There are two submodules
* to describe this arrangement:
* - The "object helper functions" which provide C++-like common functionality
* to all supported object types.
* - The interface between the implemented Objects and the BAC-stack services,
* specifically the handlers, which are mediated through function calls to
* the Device object.
*//** @defgroup ObjHelpers Object Helper Functions
* @ingroup ObjFrmwk
* This section describes the function templates for the helper functions that
* provide common object support.
*//** @defgroup ObjIntf Handler-to-Object Interface Functions
* @ingroup ObjFrmwk
* This section describes the fairly limited set of functions that link the
* BAC-stack handlers to the BACnet Object instances. All of these calls are
* situated in the Device Object, which "knows" how to reach its child Objects.
*
* Most of these calls have a common operation:
* -# Call Device_Objects_Find_Functions( for the desired Object_Type )
* - Gets a pointer to the object_functions for this Type of Object.
* -# Call the Object's Object_Valid_Instance( for the desired object_instance )
* to make sure there is such an instance.
* -# Call the Object helper function needed by the handler,
* eg Object_Read_Property() for the RP handler.
*
*/
#endif

View File

@ -0,0 +1,23 @@
%module javaupm_bacnetmstp
%include "../upm.i"
%include "typemaps.i"
%include "cpointer.i"
%include "arrays_java.i";
%include "../java_buffer.i"
%{
#include "bacnetmstp.h"
%}
%include "bacnetmstp.h"
%pragma(java) jniclasscode=%{
static {
try {
System.loadLibrary("javaupm_bacnetmstp");
} catch (UnsatisfiedLinkError e) {
System.err.println("Native code library failed to load. \n" + e);
System.exit(1);
}
}
%}

View File

@ -0,0 +1,11 @@
%module jsupm_bacnetmstp
%include "../upm.i"
%include "stdint.i"
%include "cpointer.i"
%pointer_functions(float, floatp);
%include "bacnetmstp.h"
%{
#include "bacnetmstp.h"
%}

View File

@ -0,0 +1,15 @@
// Include doxygen-generated documentation
%include "pyupm_doxy2swig.i"
%module pyupm_bacnetmstp
%include "../upm.i"
%include "stdint.i"
%include "cpointer.i"
%feature("autodoc", "3");
%pointer_functions(float, floatp);
%include "bacnetmstp.h"
%{
#include "bacnetmstp.h"
%}

65
src/bacnetmstp/timer.h Normal file
View File

@ -0,0 +1,65 @@
/**************************************************************************
*
* Copyright (C) 2009 Steve Karg <skarg@users.sourceforge.net>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
#ifndef TIMER_H
#define TIMER_H
#include <stdbool.h>
#include <stdint.h>
#include <sys/time.h> /* for timeval */
/* Timer Module */
#ifndef MAX_MILLISECOND_TIMERS
#define TIMER_SILENCE 0
#define MAX_MILLISECOND_TIMERS 1
#endif
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
uint32_t timeGetTime(
void);
void timer_init(
void);
uint32_t timer_milliseconds(
unsigned index);
bool timer_elapsed_milliseconds(
unsigned index,
uint32_t value);
bool timer_elapsed_seconds(
unsigned index,
uint32_t value);
bool timer_elapsed_minutes(
unsigned index,
uint32_t seconds);
uint32_t timer_milliseconds_set(
unsigned index,
uint32_t value);
uint32_t timer_reset(
unsigned index);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif

Some files were not shown because too many files have changed in this diff Show More