Fixed merge issues

This commit is contained in:
Ziver Koc 2019-11-12 14:26:37 +01:00
parent 81a85320a2
commit 09ae1b2667
37 changed files with 22 additions and 24 deletions

View file

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="RaspberryPi Plugin" >
<!-- ________________________ PROPERTIES AND SETTINGS ________________________ -->
<!--common properties-->
<property name="root" value="." />
<property name="srcDir" value="${root}/src" />
<property name="testDir" value="${root}/test" />
<property name="libDir" value="${root}/lib" />
<property name="buildRoot" value="${root}/build" />
<property name="compileDir" value="${buildRoot}/production" />
<property name="compileTestDir" value="${buildRoot}/test" />
<property name="releaseDir" value="${buildRoot}/release" />
<property name="releaseJar" value="raspberry.jar" />
<property name="reportsDir" value="../../${buildRoot}/reports" /> <!-- Use Hal reports folder -->
<!-- ________________________ TARGETS ________________________ -->
<import file="../../build_plugin.xml"/>
</project>

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

View file

@ -0,0 +1,33 @@
=========================================================================
Pi4J :: Java library for Raspberry Pi
=========================================================================
Pi4J Library
Copyright (C) 2012-2016 Pi4J.com
This product includes software developed at:
The Pi4J Project (http://www.pi4j.com/).
This product was originally authored by: Robert Savage
This software is licensed under the GNU LGPLv3 license.
More information about licensing terms can be found at:
http://pi4j.com/license.html
Additional information about this project and its authors can be found at:
- http://www.pi4j.com/
- http://www.raspicentral.com
- http://www.savagehomeautomation.com
This software compiles against libraries from the WiringPi project.
The Wiring Pi project is provided by Gordon Henderson and is available
from
http://wiringpi.com/
The WiringPi project is licensed under the GNU LGPLv3 license
http://www.gnu.org/licenses/lgpl.html
=========================================================================
Subject to the terms of the software license, this NOTICE file must be
included in any Derivative Works that You distribute as a readable copy.
(Section 4d)

View file

@ -0,0 +1,98 @@
package se.hal.plugin.raspberry;
import se.hal.intf.*;
import se.hal.plugin.raspberry.hardware.RPiDS18B20;
import se.hal.plugin.raspberry.hardware.RPiInteruptPulseFlankCounter;
import zutil.log.LogUtil;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RPiController implements HalSensorController {
private static final Logger logger = LogUtil.getLogger();
private HashMap<String, RPiSensor> pinToSensorMap = new HashMap<>();
private HalSensorReportListener sensorListener;
public RPiController(){
}
@Override
public void initialize() throws Exception {
}
@Override
public void register(HalSensorConfig sensor) {
if(sensor instanceof RPiPowerConsumptionSensor){
RPiPowerConsumptionSensor powerConsumptionSensor = (RPiPowerConsumptionSensor) sensor;
int gpioPin = powerConsumptionSensor.getGpioPin();
if(!pinToSensorMap.containsKey("GPIO_"+gpioPin)){
RPiInteruptPulseFlankCounter impulseCounter = new RPiInteruptPulseFlankCounter(gpioPin, this);
pinToSensorMap.put("GPIO_"+gpioPin, impulseCounter);
}else{
logger.warning("Cannot create a RPiPowerConsumptionSensor on GPIO pin " + gpioPin + " since is already is in use by another sensor.");
}
} else if(sensor instanceof RPiTemperatureSensor){
RPiTemperatureSensor temperatureSensor = (RPiTemperatureSensor) sensor;
String w1Address = temperatureSensor.get1WAddress();
if(!pinToSensorMap.containsKey("W1_"+w1Address)){
RPiDS18B20 ds12b20 = new RPiDS18B20(w1Address, this);
pinToSensorMap.put("W1_"+w1Address, ds12b20);
}else{
logger.warning("Cannot create a RPi1WireTemperatureSensor on 1-Wire address " + w1Address + " since is already is in use by another sensor.");
}
}else{
logger.warning("Cannot register a non-supported sensor");
}
}
@Override
public void deregister(HalSensorConfig sensor) {
if(sensor instanceof RPiPowerConsumptionSensor){
RPiPowerConsumptionSensor powerConsumprtionSensor = (RPiPowerConsumptionSensor) sensor;
RPiSensor sensorToDeregister = pinToSensorMap.remove("GPIO_"+powerConsumprtionSensor.getGpioPin());
if(sensorToDeregister != null){
sensorToDeregister.close();
}
} else if(sensor instanceof RPiTemperatureSensor){
RPiTemperatureSensor temperatureSensor = (RPiTemperatureSensor) sensor;
RPiSensor sensorToDeregister = pinToSensorMap.remove("W1_"+temperatureSensor.get1WAddress());
if(sensorToDeregister != null){
sensorToDeregister.close();
}
}else{
logger.warning("Cannot deregister a non-supported sensor");
return;
}
}
@Override
public int size() {
return pinToSensorMap.size();
}
@Override
public void setListener(HalSensorReportListener listener) {
sensorListener = listener;
}
@Override
public void close() {
for(String key : this.pinToSensorMap.keySet()){
pinToSensorMap.get(key).close();
pinToSensorMap.remove(key);
}
}
public void sendDataReport(HalSensorConfig sensorConfig, HalSensorData sensorData){
if(sensorListener != null){
sensorListener.reportReceived(sensorConfig, sensorData);
}else{
logger.log(Level.WARNING, "Could not report data. No registered listener");
}
}
}

View file

@ -0,0 +1,56 @@
package se.hal.plugin.raspberry;
import se.hal.intf.HalSensorConfig;
import se.hal.intf.HalSensorController;
import se.hal.intf.HalSensorData;
import se.hal.struct.devicedata.PowerConsumptionSensorData;
import zutil.ui.Configurator;
public class RPiPowerConsumptionSensor implements HalSensorConfig {
@Configurator.Configurable("GPIO-Pin")
private int gpioPin = -1;
public RPiPowerConsumptionSensor(){ } //need to be empty for the framework to create an instance
public RPiPowerConsumptionSensor(int gpioPin) {
this.gpioPin = gpioPin;
}
@Override
public long getDataInterval(){
return 60*1000; // 1 min
}
@Override
public AggregationMethod getAggregationMethod() {
return AggregationMethod.SUM;
}
@Override
public Class<? extends HalSensorController> getSensorControllerClass() {
return RPiController.class;
}
@Override
public Class<? extends HalSensorData> getSensorDataClass() {
return PowerConsumptionSensorData.class;
}
@Override
public boolean equals(Object obj){
if(obj instanceof RPiPowerConsumptionSensor)
return ((RPiPowerConsumptionSensor)obj).gpioPin == gpioPin;
return false;
}
public int getGpioPin() {
return gpioPin;
}
public String toString(){
return "gpioPin:" + gpioPin;
}
}

View file

@ -0,0 +1,7 @@
package se.hal.plugin.raspberry;
public interface RPiSensor {
void close();
}

View file

@ -0,0 +1,53 @@
package se.hal.plugin.raspberry;
import se.hal.intf.HalSensorConfig;
import se.hal.intf.HalSensorController;
import se.hal.intf.HalSensorData;
import se.hal.struct.devicedata.TemperatureSensorData;
import zutil.ui.Configurator;
public class RPiTemperatureSensor implements HalSensorConfig {
@Configurator.Configurable("1-Wire Address")
private String w1Address;
public RPiTemperatureSensor() { }
public RPiTemperatureSensor(String w1Address) {
this.w1Address = w1Address;
}
@Override
public long getDataInterval() {
return 10*60*1000; // 10 min
}
@Override
public AggregationMethod getAggregationMethod() {
return AggregationMethod.AVERAGE;
}
@Override
public Class<? extends HalSensorController> getSensorControllerClass() {
return RPiController.class;
}
@Override
public Class<? extends HalSensorData> getSensorDataClass() {
return TemperatureSensorData.class;
}
@Override
public boolean equals(Object obj){
if(obj instanceof RPiTemperatureSensor && w1Address != null)
return this.get1WAddress().equals(((RPiTemperatureSensor) obj).w1Address);
return false;
}
public String get1WAddress() {
return w1Address;
}
}

View file

@ -0,0 +1,75 @@
package se.hal.plugin.raspberry;
import com.pi4j.io.gpio.Pin;
import com.pi4j.io.gpio.RaspiPin;
public class RPiUtility {
public static Pin getPin(int gpioPin){
switch(gpioPin){
case 0:
return RaspiPin.GPIO_00;
case 1:
return RaspiPin.GPIO_01;
case 2:
return RaspiPin.GPIO_02;
case 3:
return RaspiPin.GPIO_03;
case 4:
return RaspiPin.GPIO_04;
case 5:
return RaspiPin.GPIO_05;
case 6:
return RaspiPin.GPIO_06;
case 7:
//used by 1-wire divices
case 8:
//used by I2C devices
case 9:
//used by I2C devices
case 10:
//used by SPI devices
case 11:
//used by SPI devices
case 12:
//used by SPI devices
case 13:
//used by SPI devices
case 14:
//used by SPI devices
case 15:
//used by Serial devices
case 16:
//used by Serial devices
case 17:
//reserved for future use
case 18:
//reserved for future use
case 19:
//reserved for future use
case 20:
//reserved for future use
case 21:
//reserved for future use
case 22:
//reserved for future use
case 23:
//reserved for future use
case 24:
//reserved for future use
case 25:
//reserved for future use
case 26:
//reserved for future use
case 27:
//reserved for future use
case 28:
//reserved for future use
case 29:
//reserved for future use
default:
return null;
}
}
}

View file

@ -0,0 +1,68 @@
package se.hal.plugin.raspberry.hardware;
import com.pi4j.component.temperature.TemperatureSensor;
import com.pi4j.io.w1.W1Master;
import com.pi4j.temperature.TemperatureScale;
import se.hal.plugin.raspberry.RPiController;
import se.hal.plugin.raspberry.RPiSensor;
import se.hal.plugin.raspberry.RPiTemperatureSensor;
import se.hal.struct.devicedata.TemperatureSensorData;
import zutil.log.LogUtil;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
public class RPiDS18B20 implements RPiSensor, Runnable {
private static final Logger logger = LogUtil.getLogger();
private final String DEGREE_SIGN = "\u00b0";
private RPiController controller;
private String w1Address;
private ScheduledExecutorService scheduler;
private W1Master w1Mater;
public RPiDS18B20(String w1Address, RPiController controller){
this.controller = controller;
this.w1Address = w1Address;
scheduler = Executors.newScheduledThreadPool(1);
w1Mater = new W1Master();
//print out all sensors found
for(TemperatureSensor device : w1Mater.getDevices(TemperatureSensor.class)){
logger.info(String.format("1-Wire temperature sensor divice found: %-20s: %3.1f"+DEGREE_SIGN+"C\n", device.getName(), device.getTemperature(TemperatureScale.CELSIUS)));
}
//schedule job
scheduler.scheduleAtFixedRate(this, 10, 60, TimeUnit.SECONDS); //wait 10s and run every 60s
}
public void close() {
scheduler.shutdown();
try {
scheduler.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
//noop
}
}
@Override
public void run() {
for(TemperatureSensor device : w1Mater.getDevices(TemperatureSensor.class)){
if(device.getName().equals(w1Address)){
controller.sendDataReport(
new RPiTemperatureSensor(w1Address),
new TemperatureSensorData(
device.getTemperature(TemperatureScale.CELSIUS),
System.currentTimeMillis()
));
break;
}
}
}
}

View file

@ -0,0 +1,145 @@
package se.hal.plugin.raspberry.hardware;
import com.pi4j.io.gpio.*;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;
import com.pi4j.wiringpi.GpioUtil;
import se.hal.plugin.raspberry.RPiController;
import se.hal.plugin.raspberry.RPiPowerConsumptionSensor;
import se.hal.plugin.raspberry.RPiSensor;
import se.hal.plugin.raspberry.RPiUtility;
import se.hal.struct.devicedata.PowerConsumptionSensorData;
import zutil.log.LogUtil;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RPiInteruptPulseFlankCounter implements Runnable, GpioPinListenerDigital, RPiSensor {
private static final int REPORT_TIMEOUT = 60_000; //one minute
private static final Logger logger = LogUtil.getLogger();
private RPiController controller;
private ExecutorService executorPool;
private long nanoSecondsSleep = REPORT_TIMEOUT * 1_000_000L;
private volatile Integer impulseCount = 0;
private GpioPinDigitalInput irLightSensor;
private final int gpioPin;
public RPiInteruptPulseFlankCounter(int gpioPin, RPiController controller){
this.controller = controller;
this.gpioPin = gpioPin;
// setup a thread pool for executing jobs
this.executorPool = Executors.newCachedThreadPool();
//Enable non privileged access to the GPIO pins (no sudo required from now)
GpioUtil.enableNonPrivilegedAccess();
// create gpio controller
GpioController gpio = null;
try{
gpio = GpioFactory.getInstance();
}catch(IllegalArgumentException e){
logger.log(Level.SEVERE, "", e);
throw e;
}catch(UnsatisfiedLinkError e){
logger.log(Level.SEVERE, "", e);
throw e;
}
// provision gpio pin as an input pin with its internal pull up resistor enabled
irLightSensor = gpio.provisionDigitalInputPin(RPiUtility.getPin(gpioPin), PinPullResistance.PULL_UP);
// create and register gpio pin listener. May require the program to be run as sudo if the GPIO pin has not been exported
irLightSensor.addListener(this);
//start a daemon thread to save the impulse count every minute
Thread thread = new Thread(this);
thread.setDaemon(false);
thread.start();
}
public void close() {
irLightSensor.removeListener(this);
executorPool.shutdown();
}
/**
* GpioPinListenerDigital interface
*/
@Override
public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
if(event.getState() == PinState.LOW){ //low = light went on
//System.out.println("IR LED turned ON");
//logger.log(Level.INFO, "IR LED turned on");
synchronized(impulseCount){
impulseCount++;
}
}
}
@Override
public void run() {
long startTime = System.nanoTime();
synchronized(impulseCount){
impulseCount = 0; //reset the impulse count
}
while(!executorPool.isShutdown()) {
sleepNano(nanoSecondsSleep); //sleep for some time. This variable will be modified every loop to compensate for the loop time spent.
int count = -1;
synchronized(impulseCount){
count = impulseCount;
impulseCount = 0;
}
save(System.currentTimeMillis(), count); //save the impulse count
long estimatedNanoTimeSpent = System.nanoTime() - startTime; //this is where the loop ends
startTime = System.nanoTime(); //this is where the loop starts from now on
if(estimatedNanoTimeSpent > 0){ //if no overflow
long nanoSecondsTooMany = estimatedNanoTimeSpent - (REPORT_TIMEOUT*1000000L);
//System.out.println("the look took ~" + estimatedNanoTimeSpent + "ns. That is " + nanoSecondsTooMany/1000000L + "ms off");
nanoSecondsSleep -= nanoSecondsTooMany / 3; //divide by constant to take into account varaiations im loop time
}
}
}
/**
* Sleep for [ns] nanoseconds
* @param ns
*/
private void sleepNano(long ns){
//System.out.println("will go to sleep for " + ns + "ns");
try{
Thread.sleep(ns/1000000L, (int)(ns%1000000L));
}catch(InterruptedException e){
//ignore
}
}
/**
* Saves the data to the database.
* This method should block the caller as short time as possible.
* This method should try block the same amount of time every time it is called.
* Try to make the time spent in the method the same for every call (low variation).
*
* @param timestamp_end
* @param data
*/
private void save(final long timestamp_end, final int data){
//offload the timed loop by not doing the db interaction in this thread.
executorPool.execute(new Runnable(){
@Override
public void run() {
logger.log(Level.INFO, "Reporting data. timestamp_end="+timestamp_end+", data="+data);
controller.sendDataReport(
new RPiPowerConsumptionSensor(gpioPin),
new PowerConsumptionSensorData(
timestamp_end, data
));
}
});
}
}

View file

@ -0,0 +1,8 @@
{
"version": 1.1,
"name": "Raspberry Pi Sensors",
"interfaces": [
{"se.hal.intf.HalSensorConfig": "se.hal.plugin.raspberry.RPiPowerConsumptionSensor"},
{"se.hal.intf.HalSensorConfig": "se.hal.plugin.raspberry.RPiTemperatureSensor"}
]
}