Remove ALFA module

This commit is contained in:
douggillespie 2022-01-13 15:04:37 +00:00
parent ace7132184
commit a6e3a36a37
56 changed files with 7 additions and 6046 deletions

View File

@ -63,7 +63,6 @@ import PamController.PamSettings;
import PamDetection.RawDataUnit;
import PamView.dialog.warn.WarnOnce;
import PamguardMVC.PamDataBlock;
import alfa.ALFAControl;
import analogarraysensor.ArraySensorControl;
import backupmanager.BackupManager;
import beamformer.continuous.BeamFormerControl;
@ -419,10 +418,11 @@ final public class PamModel implements PamModelInterface, PamSettings {
mi.setModulesMenuGroup(utilitiesGroup);
mi.setHidden(SMRUEnable.isEnable() == false);
mi = PamModuleInfo.registerControlledUnit(ALFAControl.class.getName(), "Master Controller");
mi.setToolTipText("Big brother - will keep an eye on you and look after you");
mi.setModulesMenuGroup(utilitiesGroup);
mi.setHidden(SMRUEnable.isEnable() == false);
// now releagate to a plugin module.
// mi = PamModuleInfo.registerControlledUnit(ALFAControl.class.getName(), "Master Controller");
// mi.setToolTipText("Big brother - will keep an eye on you and look after you");
// mi.setModulesMenuGroup(utilitiesGroup);
// mi.setHidden(SMRUEnable.isEnable() == false);
mi = PamModuleInfo.registerControlledUnit(PrintScreenControl.class.getName(), "Print Screen");
mi.setToolTipText(PrintScreenControl.getToolTip());

View File

@ -1,338 +0,0 @@
package alfa;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import java.util.ArrayList;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import Acquisition.AcquisitionControl;
import GPS.GPSControl;
import Map.MapController;
import NMEA.NMEAControl;
import PamController.PamControlledUnit;
import PamController.PamControlledUnitSettings;
import PamController.PamController;
import PamController.PamSettingManager;
import PamController.PamSettings;
import PamController.status.ModuleStatus;
import PamView.PamSidePanel;
import PamView.PamTabPanel;
import alfa.clickmonitor.ClickMonitorProcess;
import alfa.clickmonitor.eventaggregator.ClickEventAggregate;
import alfa.comms.MessageProcess;
import alfa.effortmonitor.AngleHistogram;
import alfa.effortmonitor.EffortMonitor;
import alfa.logger.LoggerMonitor;
import alfa.status.StatusMonitor;
import alfa.status.StatusObserver;
import alfa.swinggui.ALFADialog;
import alfa.swinggui.ALFAGUITransformer;
import alfa.swinggui.ALFASidePanel;
import alfa.swinggui.BBSwingTabPanel;
import alfa.utils.MiraScreen;
import binaryFileStorage.BinaryStore;
import clickDetector.ClickControl;
import clickTrainDetector.ClickTrainControl;
import detectiongrouplocaliser.DetectionGroupDataUnit;
import generalDatabase.DBControlUnit;
import rockBlock.RockBlockControl;
/**
* ALFA module shows status of various modules in PAMGuard for real time operation detecting
* sperm whales for the Alaska Fishermen's Association.
*
* @author Doug Gillespie
*
*/
public class ALFAControl extends PamControlledUnit implements PamSettings {
private static String unitType = "ALFA Sperm Tracker";
private StatusMonitor statusMonitor;
private BBSwingTabPanel bbSwingTabPanel;
private boolean initialisationComplete;
private ClickMonitorProcess clickMonitorProcess;
private EffortMonitor effortMonitor;
private LoggerMonitor loggerMonitor;
private MessageProcess messageProcess;
private ALFAParameters alfaParameters = new ALFAParameters();
private ALFASidePanel alfaSidePanel;
private ALFAGUITransformer alfaGuiTransformer;
public ALFAControl(String unitName) {
super(unitType, unitName);
ArrayList<ControlledModuleInfo> controlledModulesList = new ArrayList<>();
controlledModulesList.add(new ControlledModuleInfo(DBControlUnit.class));
controlledModulesList.add(new ControlledModuleInfo(BinaryStore.class));
controlledModulesList.add(new ControlledModuleInfo(NMEAControl.class));
controlledModulesList.add(new ControlledModuleInfo(GPSControl.class));
controlledModulesList.add(new ControlledModuleInfo(MapController.class));
controlledModulesList.add(new ControlledModuleInfo(AcquisitionControl.class));
controlledModulesList.add(new ControlledModuleInfo(ClickControl.class));
controlledModulesList.add(new ControlledModuleInfo(ClickTrainControl.class));
// controlledModulesList.add(new ControlledModuleInfo(FormsControl.class));
controlledModulesList.add(new ControlledModuleInfo(RockBlockControl.class, "Sat Comms"));
controlledModulesList.add(new ControlledModuleInfo(ALFAControl.class));
statusMonitor = new StatusMonitor(false, controlledModulesList);
statusMonitor.addObserver(new StatusObserver() {
@Override
public void newStatus() {
statusUpdated();
}
@Override
public void newModuleList() {
}
});
clickMonitorProcess = new ClickMonitorProcess(this);
addPamProcess(clickMonitorProcess);
effortMonitor = new EffortMonitor(this);
addPamProcess(effortMonitor);
messageProcess = new MessageProcess(this);
addPamProcess(messageProcess);
addPamProcess(loggerMonitor = new LoggerMonitor(this));
PamSettingManager.getInstance().registerSettings(this);
if (alfaParameters.autoScreenMirror) {
MiraScreen.startMirror();
}
alfaSidePanel = new ALFASidePanel(this);
if (!this.isViewer()) {
//GUI alterations for real time mode.
alfaGuiTransformer = new ALFAGUITransformer(this);
}
}
protected void statusUpdated() {
if (alfaSidePanel != null) {
alfaSidePanel.statusUpdate();
}
}
/* (non-Javadoc)
* @see PamController.PamControlledUnit#getTabPanel()
*/
@Override
public PamTabPanel getTabPanel() {
if (bbSwingTabPanel == null) {
bbSwingTabPanel = new BBSwingTabPanel(this);
}
return bbSwingTabPanel;
}
public MapController findMapController() {
return (MapController) PamController.getInstance().findControlledUnit(MapController.unitType);
}
/**
* @return the statusMonitor
*/
public StatusMonitor getStatusMonitor() {
return statusMonitor;
}
/* (non-Javadoc)
* @see PamController.PamControlledUnit#notifyModelChanged(int)
*/
@Override
public void notifyModelChanged(int changeType) {
super.notifyModelChanged(changeType);
if (changeType == PamController.INITIALIZATION_COMPLETE) {
// probably need to do something ?
initialisationComplete = true;
bbSwingTabPanel.updateUnits();
findClickTrainDetector();
}
if (initialisationComplete) {
switch (changeType) {
case PamController.ADD_CONTROLLEDUNIT:
case PamController.REMOVE_CONTROLLEDUNIT:
bbSwingTabPanel.updateUnits();
findClickTrainDetector();
}
}
if (alfaGuiTransformer!=null) this.alfaGuiTransformer.notifyModelChanged(changeType);
//this.alfaSidePanel.notifyModelChanged(changeType);
}
/**
* Called when the model changes.
*/
private void findClickTrainDetector() {
ClickTrainControl clickControl = (ClickTrainControl) PamController.getInstance().findControlledUnit(ClickTrainControl.class, null);
clickMonitorProcess.setClickTrainDetector(clickControl);
}
/**
* @return the clickMonitorProcess
*/
public ClickMonitorProcess getClickMonitorProcess() {
return clickMonitorProcess;
}
/**
* @return the effortMonitor
*/
public EffortMonitor getEffortMonitor() {
return effortMonitor;
}
/**
* @return the messageProcess
*/
public MessageProcess getMessageProcess() {
return messageProcess;
}
/**
* Generic updated information from the click monitor and aggregator which can
* be used to update the effort data.
* @param aggregateEvent
* @param detectionGroupDataUnit
*/
public void updateClickInformation(ClickEventAggregate aggregateEvent,
DetectionGroupDataUnit detectionGroupDataUnit) {
effortMonitor.updateClickInformation(aggregateEvent, detectionGroupDataUnit);
}
@Override
public JMenuItem createDetectionMenu(Frame parentFrame) {
JMenu menu = new JMenu(getUnitName() + " options ...");
// menu.add(loggerMonitor.getMenuItem(parentFrame));
JMenuItem menuItem = new JMenuItem(getUnitName() + " Options ...");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
showAlfaDialog(parentFrame);
}
});
menu.add(menuItem);
return menu;
}
public void showAlfaDialog() {
showAlfaDialog(getGuiFrame());
}
public void showAlfaDialog(Frame parentFrame) {
ALFAParameters newParams = ALFADialog.showDialog(parentFrame, this);
if (newParams != null) {
setAlfaParameters(newParams);
}
}
/**
* @return the alfaParameters
*/
public ALFAParameters getAlfaParameters() {
return alfaParameters;
}
/**
* @param alfaParameters the alfaParameters to set
*/
public void setAlfaParameters(ALFAParameters alfaParameters) {
this.alfaParameters = alfaParameters;
if (alfaParameters.autoScreenMirror) {
MiraScreen.startMirror();
}
this.setupControlledUnit();
}
/**
* @return the loggerMonitor
*/
public LoggerMonitor getLoggerMonitor() {
return loggerMonitor;
}
@Override
public Serializable getSettingsReference() {
return alfaParameters;
}
@Override
public long getSettingsVersion() {
return ALFAParameters.serialVersionUID;
}
@Override
public boolean restoreSettings(PamControlledUnitSettings pamControlledUnitSettings) {
alfaParameters = ((ALFAParameters) pamControlledUnitSettings.getSettings()).clone();
return alfaParameters != null;
}
@Override
public ModuleStatus getModuleStatus() {
return statusMonitor.getSummaryStatus();
}
@Override
public PamSidePanel getSidePanel() {
return alfaSidePanel;
}
/**
* Get a status object (for display in the side panel) which
* summarises the number of whales recently detected.
* @return whale summary.
*/
public ModuleStatus getWhaleStatus() {
return effortMonitor.getWhaleStatus();
}
public AngleHistogram getStatusAngleHistogram() {
return effortMonitor.getAveragedAngleHistogram();
}
/**
* called just before data acquisition starts. Note that
* PamObservers get a call to setSampleRate anyway so this mainly needs
* to be used for display elements that may need their scales
* adjusted before startup.
*
*/
@Override
public void pamToStart() {
// SwingUtilities.invokeLater(new Runnable() {
// @Override
// public void run() {
alfaSidePanel.notifyModelChanged(PamController.PAM_RUNNING);
// }
// });
}
/**
* Called for all controlled units after Pam acquisition has stopped
*
*/
@Override
public void pamHasStopped() {
// SwingUtilities.invokeLater(new Runnable() {
// @Override
// public void run() {
alfaSidePanel.notifyModelChanged(PamController.PAM_IDLE);
// }
// });
}
}

View File

@ -1,87 +0,0 @@
package alfa;
import java.io.Serializable;
import PamModel.parametermanager.ManagedParameters;
import PamModel.parametermanager.PamParameterSet;
import loggerForms.FormDescription;
public class ALFAParameters implements Serializable, Cloneable, ManagedParameters {
public static final long serialVersionUID = 1L;
/**
* interval for sending effort data when no
* whales are present in SECONDS
*/
public int effortMsgIntervalNoWhales = 3600;
/**
* interval for sending effort data when
* whales are present in SECONDS
*/
// public int effortMsgIntervalWhales = 900;
public int histosPerReportInterval = 4;
/**
* The histogram bin interval for a 0-180 degree bearing.
*/
private int binsPerhistogram = 5;
/**
*
* True to use click train median angle for angle histogram.
* False to use clicks in angle histogram.
*/
public boolean useClkTrains = false;
/**
* Reload old reports at startup. This is important if
* the system crashes to reload old data and continue histogram.
*/
public boolean reloadOldReports = true;
/**
* Automatically launch the screen mirror service
*/
public boolean autoScreenMirror = true;
public int loggerFormFormat = FormDescription.LOGGER_FORMS_JSON;
public boolean followOffline = false;
@Override
public ALFAParameters clone() {
try {
return (ALFAParameters) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
/**
* @return the binsPerhistogram
*/
public int getBinsPerhistogram() {
if (binsPerhistogram <= 0) {
binsPerhistogram = 4;
}
return binsPerhistogram;
}
/**
* @param binsPerhistogram the binsPerhistogram to set
*/
public void setBinsPerhistogram(int binsPerhistogram) {
this.binsPerhistogram = binsPerhistogram;
}
@Override
public PamParameterSet getParameterSet() {
PamParameterSet ps = PamParameterSet.autoGenerate(this);
return ps;
}
}

View File

@ -1,93 +0,0 @@
package alfa;
import PamModel.PamModuleInfo;
/**
* Information about a module that needs to be monitored for status. <br>
* Wraps around and extends PamModuleInfo to give extra functionality for
* advanced status monitoring.
* @author dg50
*
*/
public class ControlledModuleInfo {
/**
* Standard PAMGuard module info for the class, tells
* PAMGuard how to construct it, a default name, etc.
*/
private PamModuleInfo pamModuleInfo;
/**
* A fixed module name. Can be used to force a particular name rather
* than just using the default value.
*/
private String fixedModuleName;
public ControlledModuleInfo(PamModuleInfo pamModuleInfo) {
this.pamModuleInfo = pamModuleInfo;
}
/**
* @param pamModuleInfo
* @param fixedModuleName
*/
public ControlledModuleInfo(PamModuleInfo pamModuleInfo, String fixedModuleName) {
super();
this.pamModuleInfo = pamModuleInfo;
this.fixedModuleName = fixedModuleName;
}
/**
* @param className
* @param fixedModuleName
*/
public ControlledModuleInfo(Class className, String fixedModuleName) {
this(PamModuleInfo.findModuleInfo(className.getName()), fixedModuleName);
}
/**
* @param className
*/
public ControlledModuleInfo(Class className) {
this(PamModuleInfo.findModuleInfo(className.getName()));
}
/**
* @return the pamModuleInfo
*/
public PamModuleInfo getPamModuleInfo() {
return pamModuleInfo;
}
/**
* @param pamModuleInfo the pamModuleInfo to set
*/
public void setPamModuleInfo(PamModuleInfo pamModuleInfo) {
this.pamModuleInfo = pamModuleInfo;
}
/**
* @return the fixedModuleName
*/
public String getFixedModuleName() {
return fixedModuleName;
}
/**
* @param fixedModuleName the fixedModuleName to set
*/
public void setFixedModuleName(String fixedModuleName) {
this.fixedModuleName = fixedModuleName;
}
public String getDefaultName() {
if (fixedModuleName != null) {
return fixedModuleName;
}
else {
return pamModuleInfo.getDefaultName();
}
}
}

View File

@ -1,148 +0,0 @@
package alfa.clickmonitor;
import javax.swing.JComponent;
import PamController.PamControlledUnit;
import PamguardMVC.PamDataUnit;
import PamguardMVC.PamObservable;
import PamguardMVC.PamProcess;
import alfa.ALFAControl;
import alfa.clickmonitor.eventaggregator.ClickAggregateDataBlock;
import alfa.clickmonitor.eventaggregator.ClickEventAggregate;
import alfa.clickmonitor.swing.ClickAggregatOverlayGraphics;
import alfa.clickmonitor.swing.ClickMonitorComponent;
import clickDetector.ClickControl;
import clickDetector.offlineFuncs.OfflineEventDataUnit;
import clickTrainDetector.ClickTrainControl;
import detectiongrouplocaliser.DetectionGroupDataUnit;
/**
* PAM Process which will automatically subscribe to the click train detector output and prepare status messages for display and transmission
* @author dg50
*
*/
public class ClickMonitorProcess extends PamProcess {
private ALFAControl bigBrotherControl;
// private ClickControl clickControl;
private ClickTrainControl clickTrainControl;
private SimpleClickEventAggregator clickEventAggregator;
private ClickAggregateDataBlock clickAggregateDataBlock;
private ClickMonitorComponent clickMonitorComponent;
public ClickMonitorProcess(ALFAControl bigBrotherControl) {
super(bigBrotherControl, null);
this.bigBrotherControl = bigBrotherControl;
clickEventAggregator = new SimpleClickEventAggregator(1000e6);
clickAggregateDataBlock = new ClickAggregateDataBlock("Sperm Whale Groups", this, 0);
clickAggregateDataBlock.setNaturalLifetime(3600);
clickAggregateDataBlock.setOverlayDraw(new ClickAggregatOverlayGraphics(clickAggregateDataBlock));
addOutputDataBlock(clickAggregateDataBlock);
}
@Override
public void pamStart() {
clickEventAggregator.reset();
}
@Override
public void pamStop() {
}
public void setClickTrainDetector(ClickTrainControl clickTrainControl) {
if (this.clickTrainControl != clickTrainControl) {
this.clickTrainControl = clickTrainControl;
if (clickTrainControl != null) {
setParentDataBlock(clickTrainControl.getClssfdClickTrainDataBlock());
}
}
}
/* (non-Javadoc)
* @see PamguardMVC.PamProcess#setupProcess()
*/
@Override
public void setupProcess() {
super.setupProcess();
}
/* (non-Javadoc)
* @see PamguardMVC.PamProcess#newData(PamguardMVC.PamObservable, PamguardMVC.PamDataUnit)
*/
@Override
public void newData(PamObservable o, PamDataUnit arg) {
if (arg instanceof DetectionGroupDataUnit) {
newClickEvent((DetectionGroupDataUnit) arg);
}
}
/* (non-Javadoc)
* @see PamguardMVC.PamProcess#updateData(PamguardMVC.PamObservable, PamguardMVC.PamDataUnit)
*/
@Override
public void updateData(PamObservable o, PamDataUnit arg) {
if (arg instanceof DetectionGroupDataUnit) {
newClickEvent((DetectionGroupDataUnit) arg);
}
}
private void newClickEvent(DetectionGroupDataUnit detectionGroupDataUnit) {
aggregateEvent(detectionGroupDataUnit);
}
/**
* Bring click events together into larger aggregations to avoid transmitting to0 much stuff
* @param detectionGroupDataUnit.
*/
private void aggregateEvent(DetectionGroupDataUnit detectionGroupDataUnit) {
ClickEventAggregate aggregateEvent = clickEventAggregator.aggregateData(detectionGroupDataUnit);
if (aggregateEvent == null) {
bigBrotherControl.updateClickInformation(null, detectionGroupDataUnit);
return;
}
if (aggregateEvent.getParentDataBlock() == null) {
clickAggregateDataBlock.addPamData(aggregateEvent);
}
else {
clickAggregateDataBlock.updatePamData(aggregateEvent, aggregateEvent.getLastUpdateTime());
}
bigBrotherControl.updateClickInformation(aggregateEvent, detectionGroupDataUnit);
}
@Override
public long getRequiredDataHistory(PamObservable o, Object arg) {
return 1000*3600;
}
public JComponent getSwingComponent() {
if (clickMonitorComponent == null) {
clickMonitorComponent = new ClickMonitorComponent(this);
}
return clickMonitorComponent.getComponent();
}
/**
* @return the clickControl
*/
public ClickTrainControl getClickTrainControl() {
return clickTrainControl;
}
/**
* @return the clickEventAggregator
*/
public SimpleClickEventAggregator getClickEventAggregator() {
return clickEventAggregator;
}
/**
* @return the clickAggregateDataBlock
*/
public ClickAggregateDataBlock getClickAggregateDataBlock() {
return clickAggregateDataBlock;
}
}

View File

@ -1,155 +0,0 @@
package alfa.clickmonitor;
/*
* Adapted from the following by Doug Gillespie. November 2018
*
* Convex hull algorithm - Library (Java)
*
* Copyright (c) 2017 Project Nayuki
* https://www.nayuki.io/page/convex-hull-algorithm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program (see COPYING.txt and COPYING.LESSER.txt).
* If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import PamUtils.LatLong;
public final class LatLongHull {
private static LatLongCamparator latLongCamparator = new LatLongCamparator();
// Returns a new list of points representing the convex hull of
// the given set of points. The convex hull excludes collinear points.
// This algorithm runs in O(n log n) time.
public static List<LatLong> makeHull(List<LatLong> points) {
List<LatLong> newPoints = new ArrayList<>(points);
Collections.sort(newPoints, latLongCamparator);
return makeHullPresorted(newPoints);
}
// Returns the convex hull, assuming that each points[i] <= points[i + 1]. Runs in O(n) time.
public static List<LatLong> makeHullPresorted(List<LatLong> points) {
if (points.size() <= 1)
return new ArrayList<>(points);
// Andrew's monotone chain algorithm. Positive y coordinates correspond to "up"
// as per the mathematical convention, instead of "down" as per the computer
// graphics convention. This doesn't affect the correctness of the result.
List<LatLong> upperHull = new ArrayList<>();
for (LatLong p : points) {
while (upperHull.size() >= 2) {
LatLong q = upperHull.get(upperHull.size() - 1);
LatLong r = upperHull.get(upperHull.size() - 2);
if ((q.getLongitude() - r.getLongitude()) * (p.getLatitude() - r.getLatitude()) >=
(q.getLatitude() - r.getLatitude()) * (p.getLongitude() - r.getLongitude()))
upperHull.remove(upperHull.size() - 1);
else
break;
}
upperHull.add(p);
}
upperHull.remove(upperHull.size() - 1);
List<LatLong> lowerHull = new ArrayList<>();
for (int i = points.size() - 1; i >= 0; i--) {
LatLong p = points.get(i);
while (lowerHull.size() >= 2) {
LatLong q = lowerHull.get(lowerHull.size() - 1);
LatLong r = lowerHull.get(lowerHull.size() - 2);
if ((q.getLongitude() - r.getLongitude()) * (p.getLatitude() - r.getLatitude()) >=
(q.getLatitude() - r.getLatitude()) * (p.getLongitude() - r.getLongitude()))
lowerHull.remove(lowerHull.size() - 1);
else
break;
}
lowerHull.add(p);
}
lowerHull.remove(lowerHull.size() - 1);
if (!(upperHull.size() == 1 && upperHull.equals(lowerHull)))
upperHull.addAll(lowerHull);
return upperHull;
}
}
class LatLongCamparator implements Comparator<LatLong> {
@Override
public int compare(LatLong ll1, LatLong ll2) {
/*
*
if (x != other.x)
return Double.compare(x, other.x);
else
return Double.compare(y, other.y);
*/
if (ll1.getLongitude() != ll2.getLongitude()) {
return Double.compare(ll1.getLongitude(), ll2.getLongitude());
}
else {
return Double.compare(ll1.getLatitude(), ll2.getLatitude());
}
}
}
final class LatLongPoint implements Comparable<LatLongPoint> {
public final double x;
public final double y;
public LatLongPoint(double x, double y) {
this.x = x;
this.y = y;
}
public String toString() {
return String.format("Point(%g, %g)", x, y);
}
public boolean equals(Object obj) {
if (!(obj instanceof LatLongPoint))
return false;
else {
LatLongPoint other = (LatLongPoint)obj;
return x == other.x && y == other.y;
}
}
public int hashCode() {
return Objects.hash(x, y);
}
public int compareTo(LatLongPoint other) {
if (x != other.x)
return Double.compare(x, other.x);
else
return Double.compare(y, other.y);
}
}

View File

@ -1,154 +0,0 @@
package alfa.clickmonitor;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import PamDetection.AbstractLocalisation;
import PamDetection.LocContents;
import PamUtils.LatLong;
import alfa.clickmonitor.eventaggregator.ClickEventAggregate;
import alfa.clickmonitor.eventaggregator.EventAggregator;
import clickDetector.offlineFuncs.OfflineEventDataUnit;
import detectiongrouplocaliser.DetectionGroupDataUnit;
public class SimpleClickEventAggregator implements EventAggregator<DetectionGroupDataUnit, ClickEventAggregate> {
private List<ClickEventAggregate> growingList = new LinkedList<>();
private double minSeparationMetres;
/**
* @param minSeparationMetres
*/
public SimpleClickEventAggregator(double minSeparationMetres) {
super();
this.minSeparationMetres = minSeparationMetres;
}
@Override
public ClickEventAggregate aggregateData(DetectionGroupDataUnit detectionGroupDataUnit) {
if (wantDataUnit(detectionGroupDataUnit) == false) {
return null;
}
ClickEventAggregate currentAggregate = findInCurrent(detectionGroupDataUnit);
if (currentAggregate != null) {
/**
* Data is already part of an aggregate event, so no need to do anything at all.
*/
}
else {
/*
* Try to match into existing developing aggregations.
*/
currentAggregate = matchToAggregate(detectionGroupDataUnit);
if (currentAggregate != null) {
currentAggregate.addSubDetection(detectionGroupDataUnit);
}
}
if (currentAggregate == null) {
currentAggregate = new ClickEventAggregate(detectionGroupDataUnit);
growingList.add(currentAggregate);
}
currentAggregate.setLastUpdateTime(detectionGroupDataUnit.getLastUpdateTime());
if (wantAggregate(currentAggregate)) {
return currentAggregate;
}
return null;
}
private boolean wantAggregate(ClickEventAggregate currentAggregate) {
return true;
}
private ClickEventAggregate matchToAggregate(DetectionGroupDataUnit detectionGroupDataUnit) {
ClickEventAggregate bestAggregate = null;
double bestRange = Double.MAX_VALUE;
Iterator<ClickEventAggregate> it = growingList.iterator();
while (it.hasNext()) {
ClickEventAggregate agg = it.next();
Double d = minRangeToAggregate(detectionGroupDataUnit, agg);
if (d == null) {
continue;
}
if (d < bestRange) {
bestRange = d;
bestAggregate = agg;
}
}
if (bestRange < minSeparationMetres) {
return bestAggregate;
}
else {
return null;
}
}
private Double minRangeToAggregate(DetectionGroupDataUnit detectionGroupDataUnit, ClickEventAggregate agg) {
AbstractLocalisation dLoc = detectionGroupDataUnit.getLocalisation();
if (dLoc == null || dLoc.hasLocContent(LocContents.HAS_LATLONG) == false) {
return null;
}
int nLL = dLoc.getAmbiguityCount();
double closestOther = Double.MAX_VALUE;
int nSub = agg.getSubDetectionsCount();
for (int i = 0; i < nSub; i++) {
AbstractLocalisation aggLoc = agg.getSubDetection(i).getLocalisation();
int nALL = aggLoc.getAmbiguityCount();
for (int is = 0; is < Math.min(nLL,nALL); is++) {
LatLong uLL = dLoc.getLatLong(is);
LatLong aLL = aggLoc.getLatLong(is);
if (aLL == null || uLL == null) {
continue;
}
double d = aLL.distanceToMetres(uLL);
closestOther = Math.min(closestOther, d);
}
}
return closestOther;
}
/**
* Do we want this data unit ?
* Only if it's got a lat long already.
* @param detectionGroupDataUnit
* @return true if we want to use this in the aggregator.
*/
private boolean wantDataUnit(DetectionGroupDataUnit detectionGroupDataUnit) {
AbstractLocalisation localisation = detectionGroupDataUnit.getLocalisation();
if (localisation == null) {
return false;
}
if (localisation.getLocContents().hasLocContent(LocContents.HAS_LATLONG)) {
return true;
}
return false;
}
/**
* Find the current data unit in any of the currently growing aggregate lists.
* @param dataUnit
* @return
*/
private ClickEventAggregate findInCurrent(DetectionGroupDataUnit dataUnit) {
synchronized (growingList) {
Iterator<ClickEventAggregate> it = growingList.iterator();
while (it.hasNext()) {
ClickEventAggregate agg = it.next();
int foundUnit = agg.findSubdetectionInfo(dataUnit);
if (foundUnit >= 0) {
return agg;
}
}
}
return null;
}
@Override
public void reset() {
growingList.clear();
}
}

View File

@ -1,25 +0,0 @@
package alfa.clickmonitor.eventaggregator;
import PamguardMVC.DataUnitBaseData;
import PamguardMVC.PamDataUnit;
import PamguardMVC.superdet.SuperDetection;;
public abstract class AggregateDataUnit<T extends PamDataUnit> extends SuperDetection<T> {
public AggregateDataUnit(DataUnitBaseData basicData) {
super(basicData);
}
/**
* @param timeMilliseconds
*/
public AggregateDataUnit(long timeMilliseconds, T firstSubDetection) {
super(timeMilliseconds);
if (firstSubDetection != null) {
setChannelBitmap(firstSubDetection.getChannelBitmap());
addSubDetection(firstSubDetection);
}
}
}

View File

@ -1,108 +0,0 @@
package alfa.clickmonitor.eventaggregator;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.math3.geometry.euclidean.twod.Vector2D;
import org.apache.commons.math3.geometry.euclidean.twod.hull.ConvexHull2D;
import com.sun.javafx.geom.Area;
import com.sun.javafx.geom.PathIterator;
import com.sun.javafx.geom.Rectangle;
import com.sun.javafx.geom.Shape;
import PamDetection.AbstractLocalisation;
import PamDetection.LocContents;
import PamUtils.LatLong;
import PamguardMVC.PamDataUnit;
import alfa.clickmonitor.LatLongHull;
import javafx.geometry.Rectangle2D;
import pamMaths.PamVector;
public class AggregateLocalisation extends AbstractLocalisation {
private AggLatLong[] sideLatLongs = new AggLatLong[2];
public AggregateLocalisation(PamDataUnit pamDataUnit) {
super(pamDataUnit, LocContents.HAS_LATLONG, pamDataUnit.getChannelBitmap());
addLocalisation(pamDataUnit.getLocalisation());
}
public void addLocalisation(AbstractLocalisation localisation) {
if (localisation == null) {
return;
}
int nLL = localisation.getAmbiguityCount();
for (int i = 0; i < nLL; i++) {
LatLong latLong = localisation.getLatLong(i);
if (latLong != null) {
if (sideLatLongs[i] == null) {
sideLatLongs[i] = new AggLatLong(latLong);
}
else {
sideLatLongs[i].add(latLong);
}
}
}
}
public class AggLatLong {
private ArrayList<LatLong> latLongList = new ArrayList<>();
public AggLatLong(LatLong latLong) {
latLongList.add(latLong);
}
public void add(LatLong latLong) {
latLongList.add(latLong);
}
public Rectangle2D getOuterRectangle() {
if (latLongList.size() == 0) {
return null;
}
double minX, maxX, minY, maxY;
minX = maxX = latLongList.get(0).getLongitude();
minY = maxY = latLongList.get(0).getLatitude();
for (int i = 0; i < latLongList.size(); i++) {
LatLong ll = latLongList.get(i);
minX = Math.min(minX, ll.getLongitude());
maxX = Math.max(maxX, ll.getLongitude());
minY = Math.min(minY, ll.getLatitude());
maxY = Math.max(maxY, ll.getLatitude());
}
return new Rectangle2D(minX, minY, maxX-minX, maxY-minY);
}
// public ConvexHull2D getOuterHull() {
// if (latLongList.size() == 0) {
// return null;
// }
// Vector2D[] v2ds = new Vector2D[latLongList.size()];
// for (int i = 0; i < latLongList.size(); i++) {
// LatLong ll = latLongList.get(i);
// v2ds[i] = new Vector2D(ll.getLongitude(), ll.getLatitude());
// }
// try {
// ConvexHull2D ch2d = new ConvexHull2D(v2ds, 0);
// return ch2d;
// }
// catch (Exception e) {
// return null;
// }
// }
public List<LatLong> getOuterHull() {
return LatLongHull.makeHull(latLongList);
}
}
/**
* @return the sideLatLongs
*/
public AggLatLong[] getSideLatLongs() {
return sideLatLongs;
}
}

View File

@ -1,14 +0,0 @@
package alfa.clickmonitor.eventaggregator;
import PamguardMVC.PamDataBlock;
import PamguardMVC.PamProcess;
import clickDetector.offlineFuncs.OfflineClickLogging;
import clickDetector.offlineFuncs.OfflineEventDataUnit;
public class ClickAggregateDataBlock extends PamDataBlock<ClickEventAggregate> {
public ClickAggregateDataBlock(String dataName, PamProcess parentProcess, int channelMap) {
super(ClickEventAggregate.class, dataName, parentProcess, channelMap);
}
}

View File

@ -1,20 +0,0 @@
package alfa.clickmonitor.eventaggregator;
import PamguardMVC.DataUnitBaseData;
import detectiongrouplocaliser.DetectionGroupDataUnit;
public class ClickEventAggregate extends AggregateDataUnit<DetectionGroupDataUnit> {
public ClickEventAggregate(DataUnitBaseData basicData) {
super(basicData);
}
public ClickEventAggregate(long timeMilliseconds, DetectionGroupDataUnit firstSubDetection) {
super(timeMilliseconds, firstSubDetection);
}
public ClickEventAggregate(DetectionGroupDataUnit dataUnit) {
this(dataUnit.getTimeMilliseconds(), dataUnit);
}
}

View File

@ -1,14 +0,0 @@
package alfa.clickmonitor.eventaggregator;
import PamguardMVC.PamDataUnit;
public interface EventAggregator<T extends PamDataUnit, U extends AggregateDataUnit<T>> {
public U aggregateData(T dataUnit);
/**
* Call when PAMguard starts.
*/
public void reset();
}

View File

@ -1,95 +0,0 @@
package alfa.clickmonitor.swing;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.List;
import org.apache.commons.math3.geometry.euclidean.twod.Vector2D;
import org.apache.commons.math3.geometry.euclidean.twod.hull.ConvexHull2D;
import PamUtils.Coordinate3d;
import PamUtils.LatLong;
import PamView.GeneralProjector;
import PamView.PamDetectionOverlayGraphics;
import PamView.PamSymbol;
import PamView.PamSymbolType;
import PamView.GeneralProjector.ParameterType;
import PamView.GeneralProjector.ParameterUnits;
import PamguardMVC.PamDataBlock;
import PamguardMVC.PamDataUnit;
import alfa.clickmonitor.eventaggregator.AggregateLocalisation;
import alfa.clickmonitor.eventaggregator.ClickEventAggregate;
import alfa.clickmonitor.eventaggregator.AggregateLocalisation.AggLatLong;
public class ClickAggregatOverlayGraphics extends PamDetectionOverlayGraphics {
/**
* Default symbol for click aggregate overalays
*/
private static PamSymbol defaultSymbol = new PamSymbol(PamSymbolType.SYMBOL_CIRCLE, 9, 9, true, Color.BLACK, Color.RED);
public ClickAggregatOverlayGraphics(PamDataBlock parentDataBlock) {
super(parentDataBlock, defaultSymbol);
}
/* (non-Javadoc)
* @see PamView.PamDetectionOverlayGraphics#canDraw(PamView.GeneralProjector)
*/
@Override
public boolean canDraw(ParameterType[] parameterTypes, ParameterUnits[] parameterUnits) {
if (parameterTypes[0] == ParameterType.LATITUDE
&& parameterTypes[1] == ParameterType.LONGITUDE) {
return true;
}
return false;
}
/* (non-Javadoc)
* @see PamView.PamDetectionOverlayGraphics#drawOnMap(java.awt.Graphics, PamguardMVC.PamDataUnit, PamView.GeneralProjector)
*/
@Override
protected Rectangle drawOnMap(Graphics g, PamDataUnit pamDetection, GeneralProjector generalProjector) {
ClickEventAggregate agg = (ClickEventAggregate) pamDetection;
if (agg.getSubDetectionsCount() < 3) {
return null;
// return super.drawOnMap(g, pamDetection, generalProjector);
}
Graphics2D g2d = (Graphics2D) g;
/*
* need to make a complex hull for each side and try to draw them.
* Started coding a localisation - but probably don't want it as such.
*/
AggregateLocalisation aggLoc = new AggregateLocalisation(agg.getSubDetection(0));
for (int i = 1; i < agg.getSubDetectionsCount(); i++) {
aggLoc.addLocalisation(agg.getSubDetection(i).getLocalisation());
}
AggLatLong[] aggShapes = aggLoc.getSideLatLongs();
PamSymbol symbol = getPamSymbol(pamDetection, generalProjector);
for (int i = 0; i < Math.min(1, aggShapes.length); i++) {
AggLatLong all = aggShapes[i];
if (all == null) {
continue;
}
List<LatLong> outline = all.getOuterHull();
int[] xPoints = new int[outline.size()];
int[] yPoints = new int[outline.size()];
for (int p = 0; p < outline.size(); p++) {
LatLong ll = outline.get(p);
Coordinate3d pt3 = generalProjector.getCoord3d(ll.getLatitude(), ll.getLongitude(), 0);
xPoints[p] = (int) pt3.x;
yPoints[p] = (int) pt3.y;
}
g.setColor(symbol.getLineColor());
g.drawPolygon(xPoints, yPoints, yPoints.length);
Color fillCol = new Color(0.2f, .2f, 0.2f, 0.5f);//.getFillColor()
g.setColor(fillCol);
g2d.fillPolygon(xPoints, yPoints, yPoints.length);
}
return null;
}
}

View File

@ -1,46 +0,0 @@
package alfa.clickmonitor.swing;
import PamUtils.PamCalendar;
import PamView.component.DataBlockTableView;
import alfa.clickmonitor.ClickMonitorProcess;
import alfa.clickmonitor.eventaggregator.ClickEventAggregate;
public class ClickAggregateTable extends DataBlockTableView<ClickEventAggregate>{
/**
* Seem to have to make this static so it get's made before the super class
* constructor is called, otherwise the calls to getColumnNames will return
* null on the first couple of calls while the table is being constructed
* and will mess everything up.
*/
private String[] colNames = {"UID", "Date Time", "N", "TX"};
public ClickAggregateTable(ClickMonitorProcess clickMonitorProcess) {
super(clickMonitorProcess.getClickAggregateDataBlock(), clickMonitorProcess.getProcessName() + " Data table");
}
@Override
public String[] getColumnNames() {
return colNames;
}
@Override
public Object getColumnData(ClickEventAggregate dataUnit, int columnIndex) {
if (dataUnit == null) {
return null;
}
switch (columnIndex) {
case 0:
return dataUnit.getUID();
case 1:
return PamCalendar.formatTodaysTime(dataUnit.getTimeMilliseconds());
case 2:
return dataUnit.getSubDetectionsCount();
case 3:
return false;
}
return null;
}
}

View File

@ -1,30 +0,0 @@
package alfa.clickmonitor.swing;
import java.awt.BorderLayout;
import javax.swing.JComponent;
import javax.swing.border.TitledBorder;
import PamView.panel.PamPanel;
import alfa.clickmonitor.ClickMonitorProcess;
public class ClickMonitorComponent {
private ClickMonitorProcess clickMonitorProcess;
private PamPanel mainPanel;
private ClickAggregateTable clickAggregateTable;
public ClickMonitorComponent(ClickMonitorProcess clickMonitorProcess) {
this.clickMonitorProcess = clickMonitorProcess;
clickAggregateTable = new ClickAggregateTable(clickMonitorProcess);
mainPanel = new PamPanel(new BorderLayout());
mainPanel.setBorder(new TitledBorder("Sperm whale detection results"));
mainPanel.add(clickAggregateTable.getComponent(), BorderLayout.CENTER);
}
public JComponent getComponent() {
return mainPanel;
}
}

View File

@ -1,63 +0,0 @@
package alfa.comms;
import PamguardMVC.DataUnitBaseData;
import PamguardMVC.PamDataUnit;
/**
* Abstract data unit class that will be used by anything that's going to produce
* data that will ultimately get sent through the messaging interface.
* @author dg50
*
*/
abstract public class ALFACommsDataUnit extends PamDataUnit {
private boolean readyToSend;
/**
* @param basicData
*/
public ALFACommsDataUnit(DataUnitBaseData basicData) {
super(basicData);
// TODO Auto-generated constructor stub
}
/**
* @param timeMilliseconds
* @param channelBitmap
* @param startSample
* @param durationSamples
*/
public ALFACommsDataUnit(long timeMilliseconds, int channelBitmap, long startSample, long durationSamples) {
super(timeMilliseconds, channelBitmap, startSample, durationSamples);
// TODO Auto-generated constructor stub
}
/**
* @param timeMilliseconds
*/
public ALFACommsDataUnit(long timeMilliseconds) {
super(timeMilliseconds);
// TODO Auto-generated constructor stub
}
/**
* @return A summary String to send via satellite.
*/
abstract public String getCommsString();
/**
* @return the readyToSend
*/
public boolean isReadyToSend() {
return readyToSend;
}
/**
* @param readyToSend the readyToSend to set
*/
public void setReadyToSend(boolean readyToSend) {
this.readyToSend = readyToSend;
}
}

View File

@ -1,91 +0,0 @@
package alfa.comms;
import javax.swing.JComponent;
import PamController.PamController;
import PamguardMVC.PamDataUnit;
import PamguardMVC.PamObservable;
import PamguardMVC.PamProcess;
import alfa.ALFAControl;
import alfa.swinggui.SwingMessagePanel;
import rockBlock.RockBlockControl;
public class MessageProcess extends PamProcess {
private RockBlockControl rockBlockControl;
public MessageProcess(ALFAControl alfaControl) {
super(alfaControl, null);
setParentDataBlock(alfaControl.getEffortMonitor().getIntervalDataBlock());
}
@Override
public void pamStart() {
// TODO Auto-generated method stub
}
@Override
public void pamStop() {
// TODO Auto-generated method stub
}
@Override
public void newData(PamObservable o, PamDataUnit arg) {
updateData(o, arg);
}
@Override
public void updateData(PamObservable o, PamDataUnit arg) {
if (arg instanceof ALFACommsDataUnit) {
newALFAComms((ALFACommsDataUnit) arg);
}
}
private void newALFAComms(ALFACommsDataUnit alfaCommsDataUnit) {
if (alfaCommsDataUnit.isReadyToSend() == false) {
return;
}
if (rockBlockControl == null) {
return;
}
String txt = alfaCommsDataUnit.getCommsString();
System.out.println(txt);
rockBlockControl.sendText(txt);
}
@Override
public void notifyModelChanged(int changeType) {
super.notifyModelChanged(changeType);
switch (changeType) {
case PamController.INITIALIZATION_COMPLETE:
case PamController.ADD_CONTROLLEDUNIT:
case PamController.REMOVE_CONTROLLEDUNIT:
if (PamController.getInstance().isInitializationComplete()) {
findRockBlock();
}
}
}
public RockBlockControl findRockBlock() {
if (rockBlockControl == null) {
rockBlockControl = (RockBlockControl) PamController.getInstance().findControlledUnit(RockBlockControl.class, null);
}
return rockBlockControl;
}
/**
* Get a panel with tables for incoming and outgoing messages
* @param showWhat 1 = outgoing, 2 = incoming 3 = both
* @return
*/
public JComponent getSwingCommsPanel(int showWhat) {
SwingMessagePanel swingMessagePanel = new SwingMessagePanel(this, showWhat);
return swingMessagePanel.getComponent();
}
}

View File

@ -1,34 +0,0 @@
package alfa.effortmonitor;
import pamMaths.PamHistogram;
public class AngleHistogram extends PamHistogram implements Cloneable {
private long startTime;
public AngleHistogram(long startTime, double minVal, double maxVal, int nBins) {
super(minVal, maxVal, nBins);
this.startTime = startTime;
}
/**
* @return the startTime
*/
public long getStartTime() {
return startTime;
}
/**
* @param startTime the startTime to set
*/
public void setStartTime(long startTime) {
this.startTime = startTime;
}
@Override
protected AngleHistogram clone() {
AngleHistogram angleHist = (AngleHistogram) super.clone();
return angleHist;
}
}

View File

@ -1,388 +0,0 @@
package alfa.effortmonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.ListIterator;
import javax.swing.Timer;
import GPS.GPSControl;
import GPS.GPSDataBlock;
import GPS.GpsData;
import GPS.GpsDataUnit;
import PamController.PamController;
import PamController.status.ModuleStatus;
import PamDetection.AbstractLocalisation;
import PamUtils.PamCalendar;
import PamguardMVC.PamDataBlock;
import PamguardMVC.PamDataUnit;
import PamguardMVC.PamProcess;
import alfa.ALFAControl;
import alfa.ALFAParameters;
import alfa.clickmonitor.eventaggregator.ClickEventAggregate;
import alfa.server.ServerIntervalDataBlock;
import alfa.swinggui.IntervalOverlayDraw;
import clickDetector.ClickTrainDetector;
import detectiongrouplocaliser.DetectionGroupDataUnit;
/**
* Monitors incoming data from the click train detector, summarises angles into a histogram, monitors
* total effort within an interval (usually around an hour), keeps summary of the GPS track lines and handles
* making summary satellite messgaes.
*
* @author Doug Gillespie
*
*/
public class EffortMonitor extends PamProcess {
private GPSDataBlock gpsDataBlock;
private ClickTrainDetector clickTrainDetector;
private Timer effortTimer;
private IntervalDataBlock intervalDataBlock;
private ServerIntervalDataBlock serverIntervalData;
private IntervalDataLogging intervalLogging;
private long effortStartTime;
private long timerStartTime;
private ALFAControl alfaControl;
private AngleHistogram currentHistogram, prevHistogram;
private IntervalDataUnit currentDataUnit;
public EffortMonitor(ALFAControl alfaControl) {
super(alfaControl, null, "Effort Monitor");
this.alfaControl = alfaControl;
effortTimer = new Timer(2000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
timerAction();
}
});
intervalDataBlock = new IntervalDataBlock(this, "ALFA Track Summary");
intervalDataBlock.SetLogging(intervalLogging = new IntervalDataLogging(intervalDataBlock));
intervalDataBlock.setOverlayDraw(new IntervalOverlayDraw(alfaControl));
addOutputDataBlock(intervalDataBlock);
if (alfaControl.isViewer()) {
serverIntervalData = new ServerIntervalDataBlock(this, "ALFA Server Data");
serverIntervalData.setOverlayDraw(new IntervalOverlayDraw(alfaControl));
// serverIntervalData.SetLogging(new ALFAServerLoader(serverIntervalData));
addOutputDataBlock(serverIntervalData);
}
}
/* (non-Javadoc)
* @see PamguardMVC.PamProcess#notifyModelChanged(int)
*/
@Override
public void notifyModelChanged(int changeType) {
super.notifyModelChanged(changeType);
switch (changeType) {
case PamController.INITIALIZATION_COMPLETE:
loadOldData();
case PamController.ADD_CONTROLLEDUNIT:
case PamController.REMOVE_CONTROLLEDUNIT:
findGpsDataBlock();
break;
default:
break;
}
}
private synchronized void timerAction() {
long now = PamCalendar.getTimeInMillis();
long newEffort = now-timerStartTime;
currentDataUnit.addActualEffort(newEffort);
currentDataUnit.setDurationInMilliseconds(now-currentDataUnit.getTimeMilliseconds());
GpsData gpsData = getLatestGPS();
if (gpsData != null) {
currentDataUnit.setLastGPSData(gpsData);
}
if (readyToSend(currentDataUnit)) {
currentDataUnit.setReadyToSend(true);
intervalDataBlock.updatePamData(currentDataUnit, now);
currentDataUnit = createNewData(now);
}
else {
checkAngleHistogram(now);
}
timerStartTime = now;
}
private void checkAngleHistogram(long now) {
if (currentHistogram == null) {
return;
}
ALFAParameters params = alfaControl.getAlfaParameters();
long histoInterval = params.effortMsgIntervalNoWhales / Math.max(params.histosPerReportInterval,1);
histoInterval = Math.max(120, histoInterval);
long histoEndTime = currentHistogram.getStartTime() + histoInterval * 1000;
if (now >= histoEndTime) {
currentHistogram = makeAngleHistogram(now);
currentDataUnit.addAngleHistogram(currentHistogram);
intervalDataBlock.updatePamData(currentDataUnit, now);
}
}
private boolean endDataUnit(IntervalDataUnit intervalDataUnit, long timeMilliseconds) {
if (intervalDataUnit == null) {
return true;
}
return intervalDataUnit.getTimeMilliseconds() + alfaControl.getAlfaParameters().effortMsgIntervalNoWhales*1000 < timeMilliseconds;
}
/**
* Called on initialisation complete to reload old data.
*/
private void loadOldData() {
if (alfaControl.getAlfaParameters().reloadOldReports) {
intervalLogging.loadDataFrom(PamCalendar.getTimeInMillis() - 2*1000*alfaControl.getAlfaParameters().effortMsgIntervalNoWhales);
currentDataUnit = intervalDataBlock.getLastUnit();
if (currentDataUnit != null) {
currentHistogram = currentDataUnit.getLastHistrogram();
}
// if (currentDataUnit != null && currentDataUnit.getTimeMilliseconds() < PamCa)
}
}
// /**
// *
// * @return the current latest data unit, or create one.
// */
// private IntervalDataUnit findDataUnit(long currentTime) {
// IntervalDataUnit dataunit = intervalDataBlock.getLastUnit();
// if (dataunit == null) {
// dataunit = createNewData(currentTime);
// }
// if (currentHistogram == null) {
// currentHistogram = makeAngleHistogram(currentTime);
// dataunit.addAngleHistogram(currentHistogram);
// }
//
// return dataunit;
// }
/**
* Create a new data unit, add current GPS data and
* add it to the data block. Also add it's first angle histogram.
* @param timeMilliseconds
* @return data unit
*/
private IntervalDataUnit createNewData(long timeMilliseconds) {
IntervalDataUnit dataUnit = new IntervalDataUnit(timeMilliseconds, getLatestGPS());
currentHistogram = makeAngleHistogram(timeMilliseconds);
dataUnit.addAngleHistogram(currentHistogram);
intervalDataBlock.addPamData(dataUnit);
return dataUnit;
}
private AngleHistogram makeAngleHistogram(long timeMilliseconds) {
prevHistogram = currentHistogram;
return new AngleHistogram(timeMilliseconds, 0, Math.PI, alfaControl.getAlfaParameters().getBinsPerhistogram());
}
@Override
public void pamStart() {
if (alfaControl.getAlfaParameters().reloadOldReports == false) {
intervalDataBlock.clearAll();
}
effortTimer.start();
timerStartTime = effortStartTime = PamCalendar.getTimeInMillis();
if (currentDataUnit != null && endDataUnit(currentDataUnit, effortStartTime)) {
currentDataUnit = null;
}
if (currentDataUnit == null) {
currentDataUnit = createNewData(effortStartTime);
}
if (currentHistogram == null) {
currentHistogram = makeAngleHistogram(effortStartTime);
currentDataUnit.addAngleHistogram(currentHistogram);
}
}
@Override
public void pamStop() {
effortTimer.stop();
// timerAction();
}
/**
* See if it's time to send the current data unit.
* @param dataUnit data unit
* @return true if it's time to send it.
*/
private boolean readyToSend(IntervalDataUnit dataUnit) {
if (dataUnit == null) {
return false;
}
double durationSecs = dataUnit.getDurationInMilliseconds() / 1000.;
ALFAParameters params = alfaControl.getAlfaParameters();
return durationSecs >= params.effortMsgIntervalNoWhales;
}
/**
*
* @return the latest GPS data
*/
private GpsData getLatestGPS() {
if (gpsDataBlock == null) {
return null;
}
GpsDataUnit lastGPSUnit = gpsDataBlock.getLastUnit();
if (lastGPSUnit == null) {
return null;
}
return lastGPSUnit.getGpsData();
}
private boolean findGpsDataBlock() {
GPSControl gpsControl = GPSControl.getGpsControl();
if (gpsControl == null) {
gpsDataBlock = null;
}
else {
gpsDataBlock = gpsControl.getGpsDataBlock();
}
setParentDataBlock(gpsDataBlock);
return gpsDataBlock != null;
}
/**
* @return the intervalDataBlock
*/
public IntervalDataBlock getIntervalDataBlock() {
return intervalDataBlock;
}
/**
* Update the click historgram information.
* @param aggregateEvent - the event.
* @param detectionGroupDataUnit - the detection group data unit.
*/
public void updateClickInformation(ClickEventAggregate aggregateEvent,
DetectionGroupDataUnit detectionGroupDataUnit) {
currentDataUnit.addClickTrain(detectionGroupDataUnit);
double medAngle = getMedianAngle(detectionGroupDataUnit);
if (this.alfaControl.getAlfaParameters().useClkTrains) {
currentHistogram.addData(medAngle);
}
else {
for (int i=0; i<detectionGroupDataUnit.getSubDetectionsCount(); i++) {
if (detectionGroupDataUnit.getSubDetection(i).getLocalisation()!=null) {
currentHistogram.addData(Math.abs(detectionGroupDataUnit.getSubDetection(i).getLocalisation().getAngles()[0]));
}
}
}
}
/**
* Get the median angle from the detectionGroupDataUnit.
* @param detectionGroupDataUnit
* @return median angle in radians.
*/
public double getMedianAngle(DetectionGroupDataUnit detectionGroupDataUnit) {
int nSub = detectionGroupDataUnit.getSubDetectionsCount();
if (nSub<=0) return Double.NaN;
int nLoc = 0;
double[] angleList = new double[nSub];
for (int i =0; i < nSub; i++) {
PamDataUnit subDet = detectionGroupDataUnit.getSubDetection(i);
if (subDet == null) {
continue;
}
AbstractLocalisation subLoc = subDet.getLocalisation();
if (subLoc == null) {
continue;
}
double[] angles = subLoc.getAngles();
if (angles == null) {
continue;
}
angleList[nLoc++] = Math.abs(angles[0]);
}
if (nLoc < nSub) {
angleList = Arrays.copyOf(angleList, nLoc);
}
Arrays.sort(angleList);
int medInd = nLoc/2;
if (angleList.length==0) return Double.NaN;
return angleList[medInd];
}
public ModuleStatus getWhaleStatus() {
long timeSpan = 15*60*1000;
int nWhales;
synchronized (intervalDataBlock.getSynchLock()) {
ListIterator<IntervalDataUnit> intIt = intervalDataBlock.getListIterator(PamDataBlock.ITERATOR_END);
}
if (currentHistogram == null) {
return new ModuleStatus(ModuleStatus.STATUS_WARNING, "No data");
}
else {
double n = currentHistogram.getTotalContent();
if (n == 0) {
return new ModuleStatus(ModuleStatus.STATUS_OK, "No Whales");
}
else if (n == 1) {
return new ModuleStatus(ModuleStatus.STATUS_WARNING, "One whale detection");
}
else {
return new ModuleStatus(ModuleStatus.STATUS_ERROR, String.format("%d whales detected", (int) n));
}
}
}
@Override
public void setupProcess() {
super.setupProcess();
intervalLogging.checkHistogramColumns(alfaControl.getAlfaParameters().histosPerReportInterval);
if (serverIntervalData != null) {
serverIntervalData.getAlfaServerLoader().runAutoUpdates(alfaControl.getAlfaParameters().followOffline);
}
}
/**
* Get a slightly averaged angle histogram for status display.
* @return averaged angle histogram.
*/
public AngleHistogram getAveragedAngleHistogram() {
if (currentHistogram == null) {
return null;
}
AngleHistogram angleHist = currentHistogram.clone();
if (prevHistogram != null) {
double[] data = angleHist.getData();
double[] data2 = prevHistogram.getData();
int n = Math.min(data.length, data2.length);
for (int i = 0; i < n; i++) {
data[i] = (data[i] + data2[i]);
}
}
return angleHist;
}
}

View File

@ -1,37 +0,0 @@
package alfa.effortmonitor;
import PamController.PamController;
import PamguardMVC.PamDataBlock;
import PamguardMVC.PamDataUnit;
import PamguardMVC.PamProcess;
import PamguardMVC.dataOffline.OfflineDataLoadInfo;
import alfa.server.ALFAServerLoader;
import pamScrollSystem.ViewLoadObserver;
public class IntervalDataBlock extends PamDataBlock<IntervalDataUnit> {
public IntervalDataBlock(PamProcess parentProcess, String name) {
super(IntervalDataUnit.class, name, parentProcess, 0);
setNaturalLifetime(3600*10); // 10 hours worth.
// setClearAtStart(PamController.getInstance().getRunMode() == PamController.RUN_NORMAL);
/**
* Will call explicitly from start() if we want to depending on delected options.
*/
setClearAtStart(false);
}
@Override
public int getNumRequiredBeforeLoadTime() {
return 10;
}
@Override
public boolean getShouldLog(PamDataUnit pamDataUnit) {
IntervalDataUnit idu = (IntervalDataUnit) pamDataUnit;
return super.getShouldLog(pamDataUnit) & idu.getDurationInMilliseconds() > 0;
}
}

View File

@ -1,196 +0,0 @@
package alfa.effortmonitor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.Types;
import java.util.Arrays;
import javax.swing.JTree;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.core.JsonParser;
//import org.codehaus.jackson.JsonToken;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import GPS.GpsData;
import PamUtils.LatLong;
import PamUtils.LatLongDatabaseSet;
import PamguardMVC.PamDataBlock;
import PamguardMVC.PamDataUnit;
import PamguardMVC.debug.Debug;
import generalDatabase.DBControlUnit;
import generalDatabase.DBProcess;
import generalDatabase.PamConnection;
import generalDatabase.PamTableDefinition;
import generalDatabase.PamTableItem;
import generalDatabase.SQLLogging;
import generalDatabase.SQLTypes;
public class IntervalDataLogging extends SQLLogging {
private PamTableItem secondsMonitored, endTime;
private LatLongDatabaseSet startGPS, endGPS;
private PamTableItem clickTrains, clicks;
private PamTableItem[] histogramColumns;
private PamTableDefinition tableDefinition;
private static final int HISTO_TEXT_LENGTH = 30;
public IntervalDataLogging(PamDataBlock pamDataBlock) {
super(pamDataBlock);
tableDefinition = new PamTableDefinition("Sperm Whale Intervals");
tableDefinition.addTableItem(endTime = new PamTableItem("End Time", Types.TIMESTAMP));
tableDefinition.addTableItem(secondsMonitored = new PamTableItem("Monitored Seconds", Types.INTEGER));
startGPS = new LatLongDatabaseSet("Start", LatLongDatabaseSet.VERTICAL_NONE, true, true);
endGPS = new LatLongDatabaseSet("End", LatLongDatabaseSet.VERTICAL_NONE, true, true);
startGPS.addTableItems(tableDefinition);
endGPS.addTableItems(tableDefinition);
tableDefinition.addTableItem(clickTrains = new PamTableItem("Click Trains", Types.INTEGER));
tableDefinition.addTableItem(clicks = new PamTableItem("Clicks", Types.INTEGER));
tableDefinition.setUpdatePolicy(SQLLogging.UPDATE_POLICY_OVERWRITE);
setTableDefinition(tableDefinition);
}
public boolean checkHistogramColumns(int nColumns) {
PamConnection con = DBControlUnit.findConnection();
if (con == null || con.getConnection() == null) {
return false;
}
if (histogramColumns == null) {
histogramColumns = new PamTableItem[nColumns];
}
else if (histogramColumns.length < nColumns) {
histogramColumns = Arrays.copyOf(histogramColumns, nColumns);
}
boolean ok = true;
for (int i = 0; i < nColumns; i++) {
ok |= checkHistogramColumn(con, i);
}
return ok;
}
private boolean checkHistogramColumn(PamConnection con, int iColumn) {
DBProcess dbProc = DBControlUnit.findDatabaseControl().getDbProcess();
String columnName = "AngleHistogram_"+iColumn;
histogramColumns[iColumn] = tableDefinition.findTableItem(columnName);
if (histogramColumns[iColumn] == null) {
histogramColumns[iColumn] = new PamTableItem(columnName, Types.CHAR, HISTO_TEXT_LENGTH);
tableDefinition.addTableItem(histogramColumns[iColumn]);
}
return dbProc.checkColumn(tableDefinition, histogramColumns[iColumn]);
}
@Override
public void setTableData(SQLTypes sqlTypes, PamDataUnit pamDataUnit) {
IntervalDataUnit intervalDataUnit = (IntervalDataUnit) pamDataUnit;
endTime.setValue(sqlTypes.getTimeStamp(intervalDataUnit.getEndTimeInMilliseconds()));
secondsMonitored.setValue((int) intervalDataUnit.getActualEffort()/1000);
startGPS.setLatLongData(intervalDataUnit.getFirstGPSData());
endGPS.setLatLongData(intervalDataUnit.getLastGPSData());
clickTrains.setValue(intervalDataUnit.getnClickTrains());
clicks.setValue(intervalDataUnit.getnClicks());
if (histogramColumns != null) for (int i = 0; i < histogramColumns.length; i++) {
writeAngleHistogram(sqlTypes, intervalDataUnit, i);
}
}
private void writeAngleHistogram(SQLTypes sqlTypes, IntervalDataUnit intervalDataUnit, int iAngleHist) {
AngleHistogram angleHist = intervalDataUnit.getAngleHistogram(iAngleHist);
if (angleHist == null) {
histogramColumns[iAngleHist].setValue(null);
return;
}
JsonFactory jf = new JsonFactory();
ByteArrayOutputStream os = new ByteArrayOutputStream();
String str = null;
try {
JsonGenerator jg = jf.createJsonGenerator(os, JsonEncoding.UTF8);
jg.writeStartObject();
// jg.writeNumberField("NCOL", angleHist.getNBins());
jg.writeArrayFieldStart("NW");
double[] data = angleHist.getData();
for (int i = 0; i < data.length; i++) {
jg.writeNumber((int) data[i]);
}
jg.writeEndArray();
jg.writeEndObject();
jg.close();
String jsonString = os.toString();
histogramColumns[iAngleHist].setValue(jsonString);
}catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected PamDataUnit createDataUnit(SQLTypes sqlTypes, long timeMilliseconds, int databaseIndex) {
LatLong startLL = startGPS.getLatLongData(sqlTypes);
LatLong endLL = endGPS.getLatLongData(sqlTypes);
if (startLL==null || endLL==null) return null; //for corrupt entries.
long monTime = secondsMonitored.getIntegerValue()*1000;
long endTimeMillis = SQLTypes.millisFromTimeStamp(endTime.getValue());
int nClickTrains = clickTrains.getIntegerValue();
int nClicks = clickTrains.getIntegerValue();
GpsData sGPS = new GpsData(timeMilliseconds, startLL);
GpsData eGPS = new GpsData(endTimeMillis, endLL);
IntervalDataUnit du = new IntervalDataUnit(timeMilliseconds, sGPS);
du.setDurationInMilliseconds(endTimeMillis-timeMilliseconds);
du.setActualEffort(monTime);
du.setLastGPSData(eGPS);
du.setnClickTrains(nClickTrains);
du.setnClicks(nClicks);
if (histogramColumns != null) {
long histInterval = (endTimeMillis-timeMilliseconds) / histogramColumns.length;
for (int i = 0; i < histogramColumns.length; i++) {
AngleHistogram angleHist = readAngleHistogram(i);
if (angleHist != null) {
long histTime = timeMilliseconds + histInterval*i;
angleHist.setStartTime(histTime);
du.addAngleHistogram(angleHist);
}
}
}
return du;
}
private AngleHistogram readAngleHistogram(int iHist) {
String jString = histogramColumns[iHist].getDeblankedStringValue();
if (jString == null || jString.length() == 0) {
return null;
}
JsonFactory jf = new JsonFactory();
int[] data = null;
try {
ObjectMapper om = new ObjectMapper();
JsonNode jTree = om.readTree(new ByteArrayInputStream(jString.getBytes()));
JsonNode jNode = jTree.findValue("NW");
if (jNode.isArray()) {
ArrayNode an = (ArrayNode) jNode;
int n = an.size();
data = new int[n];
int i = 0;
for (JsonNode jn : an) {
data[i++] = jn.intValue();
}
}
} catch (IOException e) {
Debug.out.printf("Interval data logging unable to interpret histogram string: %s", jString);
return null;
}
if (data == null) {
return null;
}
AngleHistogram angleHist = new AngleHistogram(0, 0, Math.PI, data.length);
angleHist.setData(data);
return angleHist;
}
}

View File

@ -1,298 +0,0 @@
package alfa.effortmonitor;
import java.util.ArrayList;
import GPS.GpsData;
import PamUtils.LatLong;
import PamUtils.PamCalendar;
import PamUtils.time.CalendarControl;
import alfa.comms.ALFACommsDataUnit;
import alfa.server.ServerRawData;
import detectiongrouplocaliser.DetectionGroupDataUnit;
/**
* Data unit to summarise what's been going on in some defined time interval (e.g. an hour)
* @author Doug Gillespie
*
*/
public class IntervalDataUnit extends ALFACommsDataUnit {
/**
* Actual effort in milliseconds.
*/
private long actualEffort;
private GpsData firstGPSData, lastGPSData;
private int nClickTrains, nClicks;
private ArrayList<AngleHistogram> angleHistograms = new ArrayList<>();
private Long imeiNumber;
private ServerRawData serverRawData;
public IntervalDataUnit(long timeMilliseconds, GpsData gpsData) {
super(timeMilliseconds);
getBasicData().setEndTime(timeMilliseconds);
firstGPSData = lastGPSData = gpsData;
}
/**
* Add a period of effort to the data unit.
* @param effort active time in milliseconds.
* @return new total effort.
*/
public long addActualEffort(long effort) {
actualEffort += effort;
return actualEffort;
}
/**
* @return the actualEffort
*/
public long getActualEffort() {
return actualEffort;
}
/**
* @param actualEffort the actualEffort to set
*/
public void setActualEffort(long actualEffort) {
this.actualEffort = actualEffort;
}
/**
*
* @return percentage of up time of PAMguard.
*/
public double getPercentEffort() {
double duration = getDurationInMilliseconds();
if (duration == 0) {
return 0;
}
return (double) actualEffort / duration * 100.;
}
/**
* @return the firstGPSData
*/
public GpsData getFirstGPSData() {
return firstGPSData;
}
/**
* @param firstGPSData the firstGPSData to set
*/
public void setFirstGPSData(GpsData firstGPSData) {
this.firstGPSData = firstGPSData;
}
/**
* @return the lastGPSData
*/
public GpsData getLastGPSData() {
return lastGPSData;
}
/**
* @param lastGPSData the lastGPSData to set
*/
public void setLastGPSData(GpsData lastGPSData) {
this.lastGPSData = lastGPSData;
if (firstGPSData == null) {
firstGPSData = lastGPSData;
}
}
/**
*
* @return straight line track length between start and end in metres
*/
public Double getTrackLengthMetres() {
if (firstGPSData == null || lastGPSData == null) {
return null;
}
return firstGPSData.distanceToMetres(lastGPSData);
}
/**
*
* @return straight line track length between start and end in miles
*/
public Double getTrackLengthMiles() {
Double m = getTrackLengthMetres();
if (m == null) {
return null;
}
return m / LatLong.MetersPerMile;
}
@Override
public String getCommsString() {
double duration = Math.max(0, getDurationInMilliseconds() / 1000. / 60);
LatLong startLat = firstGPSData;
if (startLat == null) {
startLat = new LatLong();
}
LatLong endLat = lastGPSData;
if (endLat == null) {
endLat = new LatLong();
}
String str = String.format("$PGSTA,1,%s,%s,%4.4f,%4.4f,%d,%d,%4.4f,%4.4f,%d,%d",
PamCalendar.formatDate2(getTimeMilliseconds(),false), PamCalendar.formatTime2(getTimeMilliseconds(), 0, false),
startLat.getLatitude(), startLat.getLongitude(),
(int) duration, (int) getPercentEffort(),
endLat.getLatitude(), endLat.getLongitude(),
nClickTrains, nClicks);
synchronized (angleHistograms) {
int nHist = angleHistograms.size();
for (int i = 0; i < nHist; i++) {
AngleHistogram angleHistogram = angleHistograms.get(i);
int nBins = angleHistogram.getNBins();
String hStr = String.format(",H,%d",nBins);
double[] data = angleHistogram.getData();
for (int b = 0; b < nBins; b++) {
hStr += String.format(",%d", (int) data[b]);
}
str += hStr;
}
}
return str;
}
@Override
public String getSummaryString() {
String str = "<html>";
str += "UID: " + getUID() + "<p>";
if (getParentDataBlock() != null) {
str += getParentDataBlock().getDataName() + "<p>";
}
if (imeiNumber != null) {
str += String.format("imei: %d<p>", imeiNumber);
}
Integer momsn = getMOMSN();
if (momsn != null) {
str += String.format("momsn: %d<p>", momsn);
}
str += String.format("%s %s %s<p>", PamCalendar.formatDate(getTimeMilliseconds(), true),
PamCalendar.formatTime(getTimeMilliseconds(), 3, true),
CalendarControl.getInstance().getTZCode(true));
if (CalendarControl.getInstance().isUTC() == false) {
str += String.format("(%s %s %s)<p>", PamCalendar.formatDate(getTimeMilliseconds(), false),
PamCalendar.formatTime(getTimeMilliseconds(), 3, false),
"UTC");
}
double duration = Math.max(0, getDurationInMilliseconds() / 1000.);
LatLong startLat = firstGPSData;
if (startLat == null) {
startLat = new LatLong();
}
LatLong endLat = lastGPSData;
if (endLat == null) {
endLat = new LatLong();
}
str += String.format("Start %s<p>End %s<p>Click Trains: %d<p>Clicks %d</html>",
startLat.toString(), endLat.toString(), nClickTrains, nClicks);
return str;
}
@Override
public Double getDurationInMilliseconds() {
return Math.max(0,super.getDurationInMilliseconds());
}
public void addClickTrain(DetectionGroupDataUnit detectionGroupDataUnit) {
nClickTrains++;
nClicks += detectionGroupDataUnit.getSubDetectionsCount();
}
/**
* @return the nClickTrains
*/
public int getnClickTrains() {
return nClickTrains;
}
/**
* @param nClickTrains the nClickTrains to set
*/
public void setnClickTrains(int nClickTrains) {
this.nClickTrains = nClickTrains;
}
/**
* @return the nClicks
*/
public int getnClicks() {
return nClicks;
}
/**
* @param nClicks the nClicks to set
*/
public void setnClicks(int nClicks) {
this.nClicks = nClicks;
}
public void addAngleHistogram(AngleHistogram angleHistogram) {
synchronized (angleHistograms) {
angleHistograms.add(angleHistogram);
}
}
public AngleHistogram getAngleHistogram(int iHist) {
synchronized (angleHistograms) {
if (angleHistograms == null || angleHistograms.size() <= iHist) {
return null;
}
return angleHistograms.get(iHist);
}
}
/**
* @return the angleHistograms
*/
public ArrayList<AngleHistogram> getAngleHistograms() {
return angleHistograms;
}
public AngleHistogram getLastHistrogram() {
if (angleHistograms == null) {
return null;
}
else {
return angleHistograms.get(angleHistograms.size()-1);
}
}
/**
* @return the imeiNumber
*/
public Long getImeiNumber() {
return imeiNumber;
}
/**
* @param imeiNumber the imeiNumber to set
*/
public void setImeiNumber(Long imeiNumber) {
this.imeiNumber = imeiNumber;
}
public void setServerRawData(ServerRawData serverRaw) {
this.serverRawData = serverRaw;
}
public Integer getMOMSN() {
if (serverRawData == null) {
return null;
}
else {
return serverRawData.getMOMSN();
}
}
}

View File

@ -1,11 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>ALFA Help Page</title>
</head>
<body>
<p>this is a page of help text</p>
</body>
</html>

View File

@ -1,53 +0,0 @@
package alfa.help.gui;
import java.awt.BorderLayout;
import java.awt.Component;
import java.net.URL;
import javax.help.JHelpContentViewer;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.ScrollPaneConstants;
import PamView.panel.PamPanel;
import alfa.ALFAControl;
public class ALFAHelpPanel {
private ALFAControl alfaControl;
private PamPanel mainPanel;
private JEditorPane htmlPane;
private static final String helpFile = "alfa/help/doc/ALFAOnePageHelp.html";
// private static final String helpFile = "alfa/help/doc/TestRTF.rtf";
public ALFAHelpPanel(ALFAControl alfaControl) {
this.alfaControl = alfaControl;
mainPanel = new PamPanel(new BorderLayout());
htmlPane = new JEditorPane();
// htmlPane.setEditable(false);
JScrollPane scrollPane = new JScrollPane(htmlPane);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
mainPanel.add(BorderLayout.CENTER, scrollPane);
/*
* Stick the single html file into it ...
*/
try {
URL help = ClassLoader.getSystemResource(helpFile);
htmlPane.setPage(help);
}
catch (Exception e) {
e.printStackTrace();
}
}
public JComponent getComponent() {
return mainPanel;
}
}

View File

@ -1,28 +0,0 @@
package alfa.logger;
import PamUtils.PamCalendar;
import alfa.comms.ALFACommsDataUnit;
public class LoggerCommsDataUnit extends ALFACommsDataUnit {
// public static final int CURRENT_VERSION = 1;
private String jsonString;
private int loggerFormFormat;
public LoggerCommsDataUnit(long timeMilliseconds, String jsonString, int loggerFormFormat) {
super(timeMilliseconds);
this.jsonString = jsonString;
this.loggerFormFormat = loggerFormFormat;
setReadyToSend(true);
}
@Override
public String getCommsString() {
return String.format("$PGLGR,%d,%s,%s,%s", loggerFormFormat,
PamCalendar.formatDate2(getTimeMilliseconds(),false), PamCalendar.formatTime2(getTimeMilliseconds(), 0, false),
jsonString);
}
}

View File

@ -1,116 +0,0 @@
package alfa.logger;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
import PamController.PamController;
import PamUtils.PamCalendar;
import PamguardMVC.PamDataUnit;
import PamguardMVC.PamObservable;
import PamguardMVC.PamProcess;
import PamguardMVC.dataSelector.DataSelector;
import alfa.ALFAControl;
import loggerForms.FormDescription;
import loggerForms.FormsControl;
import loggerForms.FormsDataUnit;
public class LoggerMonitor extends PamProcess {
private ALFAControl alfaControl;
private DataSelector formsSelector;
private FormsControl loggerControl;
public LoggerMonitor(ALFAControl alfaControl) {
super(alfaControl, null);
this.alfaControl = alfaControl;
}
private boolean linkLogger() {
loggerControl = (FormsControl) PamController.getInstance().findControlledUnit(FormsControl.class, null);
if (loggerControl == null) {
return false;
}
loggerControl.getFormsMonitor().addObserver(this, true);
formsSelector = loggerControl.getFormsMonitor().getDataSelector(alfaControl.getUnitName());
return false;
}
@Override
public void pamStart() {
// TODO Auto-generated method stub
}
@Override
public void pamStop() {
// TODO Auto-generated method stub
}
@Override
public void notifyModelChanged(int changeType) {
super.notifyModelChanged(changeType);
if (changeType == PamController.INITIALIZATION_COMPLETE) {
linkLogger();
}
}
public JMenuItem getMenuItem(Frame parentFrame) {
JMenuItem menuItem = new JMenuItem("Logger forms ...");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
showOptionsMenu(parentFrame);
}
});
if (loggerControl == null) {
menuItem.setEnabled(false);
menuItem.setToolTipText("No logger forms available");
}
else {
menuItem.setToolTipText("Select logger forms for satellite messaging");
}
return menuItem;
}
public boolean showOptionsMenu(Frame frame) {
if (formsSelector == null) {
return false;
}
return formsSelector.showSelectDialog(frame);
}
@Override
public void newData(PamObservable o, PamDataUnit arg) {
FormsDataUnit formsUnit = (FormsDataUnit) arg;
if (formsSelector.scoreData(formsUnit) > 0) {
newFormsData(formsUnit);
}
}
private void newFormsData(FormsDataUnit formsUnit) {
// Debug.out.println(formsUnit.getSummaryString());
FormDescription desc = formsUnit.getLoggerForm().getFormDescription();
// Debug.out.println(desc.getXMLData(formsUnit));
// Debug.out.println(desc.getJSONData(formsUnit));
String jsonString = desc.getStringData(formsUnit, alfaControl.getAlfaParameters().loggerFormFormat);
if (jsonString != null) {
LoggerCommsDataUnit lcdu = new LoggerCommsDataUnit(formsUnit.getTimeMilliseconds(), jsonString, alfaControl.getAlfaParameters().loggerFormFormat);
alfaControl.getMessageProcess().newData(null, lcdu);
}
}
/**
* @return the formsSelector
*/
public DataSelector getFormsSelector() {
return formsSelector;
}
}

View File

@ -1,76 +0,0 @@
package alfa.server;
import java.lang.reflect.Field;
import PamModel.parametermanager.ManagedParameters;
import PamModel.parametermanager.PamParameterSet;
import PamModel.parametermanager.PrivatePamParameterData;
import dataMap.OfflineDataMapPoint;
public class ALFADataMapPoint extends OfflineDataMapPoint implements ManagedParameters {
/**
*
*/
private static final long serialVersionUID = 1L;
public static final String name = "ALFA Server";
private Long lowUID, highUID;
public ALFADataMapPoint(long startTime, long endTime, int nDatas, long missingUIDs) {
super(startTime, endTime, nDatas, missingUIDs);
}
@Override
public String getName() {
// TODO Auto-generated method stub
return name;
}
@Override
public Long getLowestUID() {
return lowUID;
}
@Override
public void setLowestUID(Long uid) {
lowUID = uid;
}
@Override
public Long getHighestUID() {
return highUID;
}
@Override
public void setHighestUID(Long uid) {
highUID = uid;
}
@Override
public PamParameterSet getParameterSet() {
PamParameterSet ps = super.getParameterSet();
try {
Field field = this.getClass().getDeclaredField("highUID");
ps.put(new PrivatePamParameterData(this, field) {
@Override
public Object getData() throws IllegalArgumentException, IllegalAccessException {
return highUID;
}
});
} catch (NoSuchFieldException | SecurityException e) {
e.printStackTrace();
}
try {
Field field = this.getClass().getDeclaredField("lowUID");
ps.put(new PrivatePamParameterData(this, field) {
@Override
public Object getData() throws IllegalArgumentException, IllegalAccessException {
return lowUID;
}
});
} catch (NoSuchFieldException | SecurityException e) {
e.printStackTrace();
}
return ps;
}
}

View File

@ -1,13 +0,0 @@
package alfa.server;
import PamguardMVC.PamDataBlock;
import dataMap.OfflineDataMap;
public class ALFAOfflineDataMap extends OfflineDataMap<ALFADataMapPoint>{
public ALFAOfflineDataMap(ALFAServerLoader alfaServerLoader, PamDataBlock parentDataBlock) {
super(alfaServerLoader, parentDataBlock);
}
}

View File

@ -1,452 +0,0 @@
package alfa.server;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.Timer;
import org.postgresql.jdbc.PgConnection;
import GPS.GpsData;
import PamController.OfflineDataStore;
import PamController.PamController;
import PamUtils.LatLong;
import PamUtils.PamCalendar;
import PamView.dialog.warn.WarnOnce;
import PamguardMVC.PamDataBlock;
import PamguardMVC.PamDataUnit;
import PamguardMVC.dataOffline.OfflineDataLoadInfo;
import PamguardMVC.debug.Debug;
import alfa.effortmonitor.AngleHistogram;
import alfa.effortmonitor.IntervalDataBlock;
import alfa.effortmonitor.IntervalDataUnit;
import dataGram.DatagramManager;
import dataMap.OfflineDataMapPoint;
import generalDatabase.SQLLogging;
import generalDatabase.SQLTypes;
import pamScrollSystem.AbstractScrollManager;
import pamScrollSystem.PamScroller;
import pamScrollSystem.ViewLoadObserver;
/**
* Connect to the web server hosting satellite messages
* @author Jamie Macaulay
*
*/
public class ALFAServerLoader extends SQLLogging implements OfflineDataStore{
private IntervalDataBlock intervalDataBlock;
private static String password = "notneeded";
private ArrayList<Long> imeiNumbers;
private int errorCount;
private int highestId;
private ALFAOfflineDataMap dataMap;
private static final String dataTable = "data_manager_rawposteddata";
private javax.swing.Timer autoUpdateTimer;
private PgConnection currentConnection;
public ALFAServerLoader(IntervalDataBlock intervalDataBlock) {
super(intervalDataBlock);
this.intervalDataBlock = intervalDataBlock;
autoUpdateTimer = new Timer(15*60*1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
autoUpdateAction();
}
});
}
private PgConnection makeConnection() {
if (currentConnection != null) {
return currentConnection;
}
if (checkPassword() == false) {
return null;
}
String db_user = "alfa_db_user";
String db_pw = "spermwhale";
String dbName = "alfa_sw_db";
// String conStr = "http://157.230.166.95:8000/api/raw_data_string/";
String driverClass = "org.postgresql.Driver";
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
// try {
String url = "jdbc:postgresql://157.230.166.95:5432/"+dbName;
// System.out.println("Open connection " + url);
PgConnection conn = null;
try {
conn = (PgConnection) DriverManager.getConnection(url, db_user, db_pw);
} catch (SQLException e) {
WarnOnce.showWarning(PamController.getMainFrame(), "Server Error", "Unable to Connect to ALFA sperm whale database", WarnOnce.WARNING_MESSAGE);
currentConnection = null;
return null;
}
// Debug.out.println("server connection open");
// DatabaseMetaData dbm = conn.getMetaData();
// ResultSet tables = dbm.getTables(null, null, null, null);
return currentConnection = conn;
}
private void closeConnection( ) {
if (currentConnection != null) {
try {
currentConnection.close();
} catch (SQLException e) {
// e.printStackTrace();
}
currentConnection = null;
}
}
/**
* Called from controller to set up or disable auto updates.
* @param autoUpdates
*/
public void runAutoUpdates(boolean autoUpdates) {
autoUpdateTimer.stop();
if (autoUpdates) {
autoUpdateTimer.start();
checkForUpdates(true); // check immediately.
}
}
private synchronized boolean checkForUpdates(boolean scrollAnyway) {
int newHighestId = getHighestId();
boolean needUpdate = (newHighestId > highestId);
Debug.out.printf("Current ALFA server map highest id = %d, new highest id = %d\n", highestId, newHighestId);
if (needUpdate) {
if (dataMap != null) {
// clear existing data map
dataMap.clear();
}
/*
* make new data map - just do the entire thing from scratch
* since there is so little data.
*/
createOfflineDataMap(PamController.getMainFrame());
}
if (needUpdate || scrollAnyway) {
AbstractScrollManager scrollManager = AbstractScrollManager.getScrollManager();
long lastTime = dataMap.getLastDataTime();
if (lastTime > 0) {
Debug.out.printf("Moving ALFA display to center at %s\n", PamCalendar.formatDateTime(lastTime, true));
// just call the center function - it will auto adjust to this becomes the last time.
scrollManager.centreDataAt(intervalDataBlock, lastTime);
}
}
return needUpdate;
}
protected void autoUpdateAction() {
checkForUpdates(false);
}
/**
* Check the highest id in the database
* @return
*/
public int getHighestId() {
PgConnection conn = makeConnection();
if (conn == null) {
return 0;
}
int id = 0;
String qStr = "SELECT id FROM data_manager_rawposteddata WHERE decoded_message LIKE '%%$PGSTA%%' ORDER By Id DESC";
try {
ResultSet dResult = conn.execSQLQuery(qStr);
if (dResult.next()) {
id = dResult.getInt(1);
}
dResult.close();
}
catch (SQLException e) {
e.printStackTrace();
closeConnection();
}
return id;
}
public boolean loadALFAServerData(long startMillis, long endMillis) {
String clause = String.format("WHERE decoded_message LIKE '%%$PGSTA%%' AND datetime_sent BETWEEN '%s' AND '%s'",
PamCalendar.formatDBDateTime(startMillis, false), PamCalendar.formatDBDateTime(endMillis+5000*3600L, false));
String qStr = String.format("SELECT id, imei, date_received, decoded_message, raw_posted_data FROM data_manager_rawposteddata %s ORDER BY datetime_sent", clause);
Debug.out.println(qStr);
PgConnection conn = makeConnection();
if (conn == null) {
return false;
}
try {
ResultSet dResult = conn.execSQLQuery(qStr);
while (dResult.next()) {
int id = dResult.getInt(1);
long imei = dResult.getLong(2);
String date = dResult.getString(3);
Object dateObject = dResult.getObject(3);
String strData = dResult.getString(4);
String rawData = dResult.getString(5);
// Debug.out.printf("%d %d %s \"%s\" %s\n", id, imei, date, dateObject.toString(), strData);
IntervalDataUnit intervalDataUnit = parseDataString(strData);
if (intervalDataUnit != null) {
intervalDataUnit.setImeiNumber(imei);
intervalDataUnit.setUID(id);
}
/*
* Try to unpack the rawPostedData to get additional information such as the
* message number.
*/
ServerRawData serverRaw = ServerRawData.unpackRawJson(rawData);
if (serverRaw != null) {
intervalDataUnit.setServerRawData(serverRaw);
}
intervalDataBlock.addPamData(intervalDataUnit);
}
dResult.close();
// System.out.println(conn);
// conn.close();
} catch (SQLException e) {
e.printStackTrace();
closeConnection();
return false;
}
intervalDataBlock.sortData();
// Debug.out.printf("%d data units loaded for ALFA intervals", intervalDataBlock.getUnitsCount());
IntervalDataUnit idu = intervalDataBlock.getFirstUnit();
if (idu != null) {
// MasterReferencePoint.
}
return true;
}
private IntervalDataUnit parseDataString(String strData) {
String[] parts = strData.split(",");
String stringId = parts[0];
int version = Integer.valueOf(parts[1]);
String date = parts[2];
String time = parts[3];
long startMillis = parseDateTime(date, time);
double lat1 = Double.valueOf(parts[4]);
double lon1 = Double.valueOf(parts[5]);
int minutes = Integer.valueOf(parts[6]);
long endMillis = startMillis + minutes*60000;
int percActive = Integer.valueOf(parts[7]);
double lat2 = Double.valueOf(parts[8]);
double lon2 = Double.valueOf(parts[9]);
int nClickTrains = Integer.valueOf(parts[10]);
int nClicks = Integer.valueOf(parts[11]);
LatLong ll1 = new LatLong(lat1, lon1);
LatLong ll2 = new LatLong(lat2, lon2);
GpsData gps1 = new GpsData(startMillis, ll1);
GpsData gps2 = new GpsData(endMillis, ll2);
IntervalDataUnit idu = new IntervalDataUnit(startMillis, gps1);
idu.setDurationInMilliseconds(endMillis-startMillis);
idu.setActualEffort(minutes*60000);
idu.setLastGPSData(gps2);
idu.setnClickTrains(nClickTrains);
idu.setnClicks(nClicks);
int iCol = 12;
while (iCol < parts.length) {
String h = parts[iCol++];
if (h.equals("H") == false) {
break;
}
int nH = Integer.valueOf(parts[iCol++]);
int[] hDat = new int[nH];
for (int i = 0; i < nH; i++) {
hDat[i] = Integer.valueOf(parts[iCol++]);
}
AngleHistogram angleHist = new AngleHistogram(0, 0, Math.PI, nH);
angleHist.setData(hDat);
idu.addAngleHistogram(angleHist);
}
int nhists = idu.getAngleHistograms().size();
if (nhists > 0) {
long histInterval = minutes / nhists * 60*1000;
for (int i = 0; i < nhists; i++) {
AngleHistogram angleHist = idu.getAngleHistogram(i);
long histStart = startMillis + i*histInterval;
angleHist.setStartTime(histStart);
}
}
return idu;
}
private long parseDateTime(String date, String time) {try {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_hhmmss");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date d = df.parse("20"+date+"_"+time); //throws ParseException if no match
long millis = d.getTime();
// Debug.out.printf("%s %s parses as %s\n", date, time, PamCalendar.formatDateTime(millis));
return millis;
}
catch (java.text.ParseException ex) {
//No problem, just go on to next format to try.
}
return 0;
}
private boolean checkPassword() {
if (password != null) {
return true;
}
JPasswordField pwd = new JPasswordField(10);
int action = JOptionPane.showConfirmDialog(null, pwd,"Enter server Password",JOptionPane.OK_CANCEL_OPTION);
if(action < 0) {
return false;
}
char[] pw = pwd.getPassword();
if (pw == null || pw.length == 0) {
return false;
}
password = new String(pw);
// System.out.println(password);
return true;
}
public List<Long> getImeiList() {
if (imeiNumbers == null) {
imeiNumbers = makeImeiList();
}
return imeiNumbers;
}
private ArrayList<Long> makeImeiList() {
PgConnection conn = makeConnection();
if (conn == null) {
return null;
}
imeiNumbers = new ArrayList<>();
String qStr = "SELECT DISTINCT imei FROM data_manager_rawposteddata";
try {
ResultSet dResult = conn.execSQLQuery(qStr);
while (dResult.next()) {
Long id = dResult.getLong(1);
imeiNumbers.add(id);
}
// conn.close();
} catch (SQLException e) {
e.printStackTrace();
return null;
}
return imeiNumbers;
}
@Override
public void setTableData(SQLTypes sqlTypes, PamDataUnit pamDataUnit) {
// TODO Auto-generated method stub
}
@Override
public synchronized void createOfflineDataMap(Window parentFrame) {
PgConnection conn = makeConnection();
if (dataMap == null) {
dataMap = new ALFAOfflineDataMap(this, intervalDataBlock);
intervalDataBlock.addOfflineDataMap(dataMap);
}
ALFADataMapPoint admp = null;
long mapInterval = 3600L*1L*1000L;
if (conn == null) {
return;
}
long wantedIMEI = 300234068339920L;
String selStr = String.format("Select id, datetime_sent, imei FROM %s WHERE decoded_message LIKE '%%$PGSTA%%' ORDER BY datetime_sent", dataTable);
// String selStr = String.format("Select id, utc, imei FROM %s WHERE decoded_message LIKE '%%$PGSTA%%' ORDER BY datetime_sent", dataTable);
// String selStr = String.format("Select id, datetime_sent FROM %s ORDER BY datetime_sent", dataTable);
// Debug.out.println(selStr);
highestId = 0;
try {
ResultSet dResult = conn.execSQLQuery(selStr);
while (dResult.next()) {
int id = dResult.getInt(1);
highestId = Math.max(id, highestId);
Timestamp dateObject = (Timestamp) dResult.getObject(2);
// long millis = SQLTypes.millisFromTimeStamp(dateObject);
long millis = dateObject.getTime()+3600000L;
long imei = dResult.getLong(3);
if (imei != wantedIMEI) continue;
// PamCalendar.
// System.out.println(dateObject + " " + PamCalendar.formatDateTime(millis));
if (admp == null || millis-admp.getStartTime() > mapInterval) {
admp = new ALFADataMapPoint(millis, millis, 1, 0);
admp.setLowestUID((long) id);
dataMap.addDataPoint(admp);
}
else {
admp.setNDatas(admp.getNDatas()+1);
admp.setHighestUID((long) id);
admp.setEndTime(millis);
}
}
dResult.close();
// conn.close();
} catch (SQLException e) {
e.printStackTrace();
return ;
}
dataMap.sortRanges();
}
@Override
public String getDataSourceName() {
return "ALFA Server";
}
@Override
public boolean loadData(PamDataBlock dataBlock, OfflineDataLoadInfo offlineDataLoadInfo,
ViewLoadObserver loadObserver) {
return loadALFAServerData(offlineDataLoadInfo.getStartMillis(), offlineDataLoadInfo.getEndMillis());
}
@Override
public boolean saveData(PamDataBlock dataBlock) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean rewriteIndexFile(PamDataBlock dataBlock, OfflineDataMapPoint dmp) {
// TODO Auto-generated method stub
return false;
}
@Override
public DatagramManager getDatagramManager() {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -1,28 +0,0 @@
package alfa.server;
import PamguardMVC.PamDataBlock;
import PamguardMVC.dataSelector.DataSelectParams;
import PamguardMVC.dataSelector.DataSelector;
import PamguardMVC.dataSelector.DataSelectorCreator;
public class SIDSCreator extends DataSelectorCreator {
private ServerIntervalDataBlock serverIntervalDataBlock;
public SIDSCreator(ServerIntervalDataBlock serverIntervalDataBlock) {
super(serverIntervalDataBlock);
this.serverIntervalDataBlock = serverIntervalDataBlock;
}
@Override
public DataSelector createDataSelector(String selectorName, boolean allowScores, String selectorType) {
// TODO Auto-generated method stub
return new ServerIntervalDataSelector(serverIntervalDataBlock, selectorName);
}
@Override
public DataSelectParams createNewParams(String name) {
return new SIDSParams();
}
}

View File

@ -1,107 +0,0 @@
package alfa.server;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.ButtonGroup;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.TitledBorder;
import PamView.dialog.PamDialog;
import PamView.dialog.PamDialogPanel;
import PamView.dialog.PamGridBagContraints;
public class SIDSDialogPanel implements PamDialogPanel {
private ServerIntervalDataSelector sids;
private JPanel mainPanel;
private JRadioButton showAll, showSystem;
private JComboBox<Long> systemList;
private List<Long> imeiList;
public SIDSDialogPanel(ServerIntervalDataSelector sids) {
this.sids = sids;
mainPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new PamGridBagContraints();
mainPanel.setBorder(new TitledBorder("Online ALFA data selection"));
showAll = new JRadioButton("Show all systems");
showSystem = new JRadioButton("Show only the selected system data");
systemList = new JComboBox<>();
ButtonGroup bg = new ButtonGroup();
bg.add(showAll);
bg.add(showSystem);
mainPanel.add(showAll, c);
c.gridy++;
mainPanel.add(showSystem, c);
c.gridy++;
mainPanel.add(systemList, c);
showAll.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
enableControls();
}
});
showSystem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
enableControls();
}
});
imeiList = sids.getServerDataBlock().getImeiList();
if (imeiList != null) {
for (Long imei : imeiList) {
systemList.addItem(imei);
}
}
}
protected void enableControls() {
systemList.setEnabled(showSystem.isSelected());
if (imeiList == null || imeiList.size() == 0) {
systemList.setEnabled(false);
showSystem.setEnabled(false);
systemList.setToolTipText("No system data available from online database");
}
}
@Override
public JComponent getDialogComponent() {
return mainPanel;
}
@Override
public void setParams() {
SIDSParams params = sids.getParams();
showAll.setSelected(params.showAll);
showSystem.setSelected(params.showAll == false);
if (params.selectedSystemId != null) {
systemList.setSelectedItem(params.selectedSystemId);
}
}
@Override
public boolean getParams() {
SIDSParams params = sids.getParams();
params.showAll = showAll.isSelected();
if (!params.showAll) {
Long selVal = (Long) systemList.getSelectedItem();
if (selVal == null) {
return PamDialog.showWarning(null, "Error", "You must select a valid system from the drop down list");
}
else {
params.selectedSystemId = selVal;
}
}
return true;
}
}

View File

@ -1,48 +0,0 @@
package alfa.server;
import java.io.Serializable;
import java.lang.reflect.Field;
import PamModel.parametermanager.ManagedParameters;
import PamModel.parametermanager.PamParameterSet;
import PamModel.parametermanager.PrivatePamParameterData;
import PamguardMVC.dataSelector.DataSelectParams;
public class SIDSParams extends DataSelectParams implements Serializable, Cloneable, ManagedParameters {
public static final long serialVersionUID = 1L;
protected boolean showAll = true;
protected Long selectedSystemId = null;
@Override
public PamParameterSet getParameterSet() {
PamParameterSet ps = PamParameterSet.autoGenerate(this);
try {
Field field = this.getClass().getDeclaredField("showAll");
ps.put(new PrivatePamParameterData(this, field) {
@Override
public Object getData() throws IllegalArgumentException, IllegalAccessException {
return showAll;
}
});
} catch (NoSuchFieldException | SecurityException e) {
e.printStackTrace();
}
try {
Field field = this.getClass().getDeclaredField("selectedSystemId");
ps.put(new PrivatePamParameterData(this, field) {
@Override
public Object getData() throws IllegalArgumentException, IllegalAccessException {
return selectedSystemId;
}
});
} catch (NoSuchFieldException | SecurityException e) {
e.printStackTrace();
}
return ps;
}
}

View File

@ -1,56 +0,0 @@
package alfa.server;
import java.util.List;
import PamController.PamController;
import PamguardMVC.PamProcess;
import PamguardMVC.dataOffline.OfflineDataLoadInfo;
import PamguardMVC.dataSelector.DataSelectorCreator;
import alfa.effortmonitor.IntervalDataBlock;
import pamScrollSystem.ViewLoadObserver;
public class ServerIntervalDataBlock extends IntervalDataBlock {
private ALFAServerLoader alfaServerLoader;
private SIDSCreator sidsCreator;
public ServerIntervalDataBlock(PamProcess parentProcess, String name) {
super(parentProcess, name);
alfaServerLoader = new ALFAServerLoader(this);
sidsCreator = new SIDSCreator(this);
alfaServerLoader.createOfflineDataMap(PamController.getMainFrame());
}
@Override
public boolean loadViewerData(OfflineDataLoadInfo offlineDataLoadInfo, ViewLoadObserver loadObserver) {
this.setCurrentViewDataStart(offlineDataLoadInfo.getStartMillis());
this.setCurrentViewDataEnd(offlineDataLoadInfo.getEndMillis());
return loadOnlineDatabaseData(offlineDataLoadInfo, loadObserver);
}
private boolean loadOnlineDatabaseData(OfflineDataLoadInfo offlineDataLoadInfo, ViewLoadObserver loadObserver) {
// if (needViewerDataLoad(offlineDataLoadInfo) == false) {
// return true;
// }
clearAll();
return alfaServerLoader.loadALFAServerData(offlineDataLoadInfo.getStartMillis(), offlineDataLoadInfo.getEndMillis());
}
/**
* @return the alfaServerLoader
*/
public ALFAServerLoader getAlfaServerLoader() {
return alfaServerLoader;
}
public List<Long> getImeiList() {
return alfaServerLoader.getImeiList();
}
@Override
public DataSelectorCreator getDataSelectCreator() {
return sidsCreator;
}
}

View File

@ -1,68 +0,0 @@
package alfa.server;
import PamView.dialog.PamDialogPanel;
import PamguardMVC.PamDataBlock;
import PamguardMVC.PamDataUnit;
import PamguardMVC.dataSelector.DataSelectParams;
import PamguardMVC.dataSelector.DataSelector;
import alfa.effortmonitor.IntervalDataUnit;
import pamViewFX.fxSettingsPanes.DynamicSettingsPane;
public class ServerIntervalDataSelector extends DataSelector {
private ServerIntervalDataBlock serverDataBlock;
private SIDSParams sidsParams = new SIDSParams();
public ServerIntervalDataSelector(ServerIntervalDataBlock serverDataBlock, String selectorName) {
super(serverDataBlock, selectorName, false);
this.serverDataBlock = serverDataBlock;
}
@Override
public void setParams(DataSelectParams dataSelectParams) {
if (dataSelectParams instanceof SIDSParams) {
this.sidsParams = (SIDSParams) dataSelectParams;
}
}
@Override
public SIDSParams getParams() {
return sidsParams;
}
@Override
public PamDialogPanel getDialogPanel() {
return new SIDSDialogPanel(this);
}
@Override
public DynamicSettingsPane<Boolean> getDialogPaneFX() {
// TODO Auto-generated method stub
return null;
}
@Override
public double scoreData(PamDataUnit pamDataUnit) {
if (sidsParams.showAll) {
return 1;
}
IntervalDataUnit idu = (IntervalDataUnit) pamDataUnit;
Long imei = idu.getImeiNumber();
if (imei == null) {
return 0;
}
return imei.equals(sidsParams.selectedSystemId) ? 1 : 0;
}
/**
* @return the serverDataBlock
*/
protected ServerIntervalDataBlock getServerDataBlock() {
return serverDataBlock;
}
}

View File

@ -1,53 +0,0 @@
package alfa.server;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import PamguardMVC.debug.Debug;
/**
* Class to handle the raw data string from the server, which contains EVERYTHING as json.
* Example string is {"imei": "300234068339920", "device_type": "ROCKBLOCK", "serial": "16945", "momsn": "27", "transmit_time": "19-06-21 19:28:40", "iridium_latitude": "57.9165",
* "iridium_longitude": "-148.9899", "iridium_cep": "4.0", "iridium_session_status": "0", "data":
* "2450475354412c312c3139303632312c3138323833332c35372e383838332c2d3134392e323034342c36302c3130302c35372e383936362c2d3134392e303136342c312c31302c482c342c302c302c302c312c482c342c302c302c302c302c482c342c302c302c302c302c482c342c302c302c302c30"}
* @author dg50
*
*/
public class ServerRawData {
private Integer momsn;
private ServerRawData(Integer momsn) {
this.momsn = momsn;
}
public static ServerRawData unpackRawJson(String jString) {
JsonFactory jf = new JsonFactory();
Integer momsn;
try {
ObjectMapper om = new ObjectMapper();
JsonNode jTree = om.readTree(new ByteArrayInputStream(jString.getBytes()));
JsonNode jNode = jTree.findValue("momsn");
momsn = jNode.asInt();
} catch (IOException e) {
Debug.out.printf("Interval data logging unable to interpret histogram string: %s", jString);
return null;
}
return new ServerRawData(momsn);
}
/**
* @return the momsn
*/
public Integer getMOMSN() {
return momsn;
}
}

View File

@ -1,119 +0,0 @@
package alfa.server;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.postgresql.jdbc.PgConnection;
public class ServerTest {
public ServerTest() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
ServerTest st = new ServerTest();
st.run();
}
private void run() {
/*
* https://jdbc.postgresql.org/documentation/head/connect.html
*/
// String ip_address = "157.230.166.95";
String db_user = "alfa_db_user";
String db_pw = "spermwhale";
String dbName = "alfa_sw_db";
// String conStr = "http://157.230.166.95:8000/api/raw_data_string/";
String driverClass = "org.postgresql.Driver";
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return;
}
try {
String url = "jdbc:postgresql://157.230.166.95:5432/"+dbName;
System.out.println("Open connection " + url);
PgConnection conn = (PgConnection) DriverManager.getConnection(url, db_user, db_pw);
System.out.println("connection open");
DatabaseMetaData dbm = conn.getMetaData();
ResultSet tables = dbm.getTables(null, null, null, null);
// if (tables.next()){
// haveTable = true;
// }
// if (databaseControll.databaseSystem.getSystemName().equals(OOoDBSystem.SYSTEMNAME)){
String dataTable = "data_manager_rawposteddata";
ResultSet oodbTables = dbm.getTables(null, null, dataTable, null);
while (oodbTables.next()){
String tableName = oodbTables.getString(3).trim();
// if (tableName.startsWith("pg_")) {
// continue;
// }
// System.out.println("Found table named " + oodbTables.getString(3).trim());
// if (oodbTables.getString(3).trim().equalsIgnoreCase(tableDef.getTableName())){
// // System.out.println("Table Found: "+oodbTables.getString(3));
// tableDef.setTableName(oodbTables.getString(3).trim().toUpperCase());
// haveTable = true;
// }
// try the table data_manager_rawposteddata_id_seq to see what's in it ...
ResultSet columns = dbm.getColumns(null, null, tableName, null);
int ncol = 0;
boolean interesting = false;
while (columns.next()) {
// now check the format
String colName = columns.getString(4);
int colType = columns.getInt(5);
// if (colName.toLowerCase().contains("iridium_latitude")) {
System.out.printf("Table %s has column %s type %d\n",tableName, colName, colType);
interesting = true;
// }
// // if (colType == tableItem.getSqlType()) return true;
// // //String strColType = columns.getString(6);
// if (columnName.equalsIgnoreCase(colName)) {
// haveColumn = true;
// }
ncol++;
}
if (interesting)
System.out.printf("found %d columns in table %s\n", ncol, tableName);
// System.out.println("Table Not Found: "+tableDef.getTableName().toUpperCase());
// }
}
tables.close();
// ResultSet dResult = conn.execSQLQuery("SELECT id, imei, date_received, decoded_message, datetime_sent, raw_posted_data, hist_string FROM data_manager_rawposteddata WHERE decoded_message LIKE '%$PGSTA%' ORDER BY id");
ResultSet dResult = conn.execSQLQuery("SELECT id, imei, date_received, decoded_message, datetime_sent, raw_posted_data, "
+ "hist_string FROM data_manager_rawposteddata ORDER BY raw_posted_data");
while (dResult.next()) {
int id = dResult.getInt(1);
long imei = dResult.getLong(2);
String date = dResult.getString(3);
Object dateObject = dResult.getObject(5);
String strData = dResult.getString(4);
String rawData = dResult.getString(6);
String histString = dResult.getString(7);
if (dateObject == null) dateObject = "no Date";
System.out.println(rawData);
System.out.printf("%d %d %s \"%s\" %s\n", id, imei, date, dateObject.toString(), strData);
}
dResult.close();
System.out.println(conn);
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

View File

@ -1,37 +0,0 @@
package alfa.status;
import PamController.PamControlledUnit;
import PamController.PamController;
import PamController.status.ModuleStatus;
import PamController.status.RemedialAction;
import PamModel.PamModuleInfo;
import PamView.PamGui;
import alfa.ControlledModuleInfo;
public class CreateModuleAction implements RemedialAction {
private ControlledModuleInfo moduleInfo;
public CreateModuleAction(ControlledModuleInfo moduleInfo) {
this.moduleInfo = moduleInfo;
}
@Override
public String getInfo() {
String info = "Create module " + moduleInfo.getDefaultName();
return info;
}
@Override
public ModuleStatus takeAction(ModuleStatus currentStatus) {
PamController pamController = PamController.getInstance();
PamControlledUnit newUnit = pamController.addModule(moduleInfo.getPamModuleInfo(), moduleInfo.getDefaultName());
if (newUnit == null) {
return null;
}
else {
return newUnit.getModuleStatus();
}
}
}

View File

@ -1,252 +0,0 @@
package alfa.status;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.Timer;
import PamController.PamControlledUnit;
import PamController.PamController;
import PamController.status.ModuleStatus;
import PamModel.PamModuleInfo;
import alfa.ALFAControl;
import alfa.ControlledModuleInfo;
import alfa.clickmonitor.eventaggregator.ClickEventAggregate;
import detectiongrouplocaliser.DetectionGroupDataUnit;
/**
* Status monitor, will scan a list of modules for
* @author dg50
*
*/
public class StatusMonitor {
private boolean monitorAll;
private ArrayList<ControlledModuleInfo> modulesList;
private int monitorInterval = 2; // monitor interval in seconds.
private Timer checkTimer;
private ModuleStatus[] moduleStatus;
private boolean[] moduleExists;
private ArrayList<StatusObserver> statusObservers = new ArrayList<>();
/**
* @param monitorAll
*/
public StatusMonitor(boolean monitorAll) {
this(monitorAll, null);
}
/**
* @param monitorAll
* @param essentialModulesList
*/
public StatusMonitor(boolean monitorAll, ArrayList<ControlledModuleInfo> essentialModulesList) {
super();
this.monitorAll = monitorAll;
this.modulesList = essentialModulesList;
checkTimer = new Timer(2000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
checkTimerActions();
}
});
checkTimer.start();
}
protected void checkTimerActions() {
checkAllModules();
}
private synchronized void checkAllModules() {
/**
* Get some single status object array for all of the modules.
*/
checkStatusAllocation();
int index = 0;
for (ControlledModuleInfo moduleInfo:modulesList) {
checkModule(moduleInfo, index++);
}
notifyStatusUpdate();
}
private synchronized void checkStatusAllocation() {
int n = modulesList.size();
if (moduleStatus == null || moduleStatus.length != n) {
moduleStatus = new ModuleStatus[n];
}
if (moduleExists == null || moduleExists.length != n) {
moduleExists = new boolean[n];
}
}
private Integer checkModule(ControlledModuleInfo moduleInfo, int index) {
PamController pamController = PamController.getInstance();
if (pamController == null) return null;
PamControlledUnit pamControlledUnit = pamController.findControlledUnit(moduleInfo.getPamModuleInfo().getModuleClass(), moduleInfo.getFixedModuleName());
moduleExists[index] = (pamControlledUnit != null);
if (moduleExists[index]) {
moduleStatus[index] = pamControlledUnit.getModuleStatus();
if (moduleStatus[index] != null) {
moduleStatus[index].setName(pamControlledUnit.getUnitName());
return moduleStatus[index].getStatus();
}
else {
return null;
}
}
else {
moduleStatus[index] = new ModuleStatus(ModuleStatus.STATUS_ERROR, "Module not present");
moduleStatus[index].setRemedialAction(new CreateModuleAction(moduleInfo));
return moduleStatus[index].getStatus();
}
// sayModuleStatus(index);
}
private void sayModuleStatus(int index) {
ControlledModuleInfo moduleInfo = modulesList.get(index);
if (moduleExists[index]) {
System.out.printf("Module %s Status %s\n", moduleInfo.getDefaultName(), moduleStatus[index]);
}
else {
System.out.printf("Module %s is not present\n", moduleInfo.getDefaultName());
}
}
/**
* Add an observer to get status updates.
* @param statusObserver Status observer
*/
public void addObserver(StatusObserver statusObserver) {
if (statusObservers.contains(statusObserver) == false) {
statusObservers.add(statusObserver);
}
}
/**
* Remove a status update observer
* @param statusObserver to remove
* @return true if the observer existed in the list
*/
public boolean removeObserver(StatusObserver statusObserver) {
return statusObservers.remove(statusObserver);
}
/**
* Notify all observers that the status has changed.
*/
private void notifyStatusUpdate() {
for (StatusObserver obs:statusObservers) {
obs.newStatus();
}
}
/**
* @return monitorAll flag to monitor all Modules in PAMGuard.
*/
public boolean isMonitorAll() {
return monitorAll;
}
/**
* @param monitorAll set flag to monitor all Modules in PAMGuard
*/
public void setMonitorAll(boolean monitorAll) {
this.monitorAll = monitorAll;
}
/**
* Set list of modules to monitor
* @return the modulesList
*/
public ArrayList<ControlledModuleInfo> getModulesList() {
return modulesList;
}
/**
* List of modules to monitor
* @param modulesList the modulesList to set
*/
public void setModulesList(ArrayList<ControlledModuleInfo> modulesList) {
this.modulesList = modulesList;
}
/**
* Monitor interval in seconds.
* @return the monitorInterval
*/
public int getMonitorInterval() {
return monitorInterval;
}
/**
* interval in seconds, set to zero for no timed monitoring
* @param monitorInterval the monitorInterval to set
*/
public void setMonitorInterval(int monitorInterval) {
this.monitorInterval = monitorInterval;
if (monitorInterval <= 0) {
checkTimer.stop();
}
else {
checkTimer.setDelay(monitorInterval*1000);
checkTimer.start();
}
}
/**
* @return the moduleStatus of all modules monitored
*/
public ModuleStatus[] getModuleStatus() {
return moduleStatus;
}
/**
* @return the moduleExists existence of all modules monitored
*/
public boolean[] getModuleExists() {
return moduleExists;
}
public synchronized ModuleStatus getSummaryStatus() {
if (moduleStatus == null || moduleStatus.length == 0) {
return new ModuleStatus(ModuleStatus.STATUS_ERROR, "No PAM modules present");
}
int maxStatus = 0;
String statusString = null;
int n = Math.min(moduleStatus.length, modulesList.size());
for (int i = 0; i < n; i++) {
if (modulesList.get(i).getPamModuleInfo().getClassName().equals(ALFAControl.class.getName())) {
continue;
}
ModuleStatus ms = moduleStatus[i];
if (ms == null) continue;
maxStatus = Math.max(maxStatus, ms.getStatus());
if (ms.getStatus() > 0) {
String sBit = String.format("%s: %s %s", ModuleStatus.getStatusString(ms.getStatus()),
modulesList.get(i).getDefaultName(), ms.getMessage());
if (statusString == null) {
statusString = "<p>" + sBit;
}
else {
statusString += "<p>" + sBit;
}
}
}
// if (statusString != null) {
// statusString += "</html>";
// }
return new ModuleStatus(maxStatus, statusString);
}
}

View File

@ -1,9 +0,0 @@
package alfa.status;
public interface StatusObserver {
public void newModuleList();
public void newStatus();
}

View File

@ -1,235 +0,0 @@
package alfa.status.swing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.border.TitledBorder;
import PamController.status.ModuleStatus;
import PamController.status.RemedialAction;
import PamView.PamColors;
import PamView.PamColors.PamColor;
import PamView.PamSymbol;
import PamView.PamSymbolType;
import PamView.dialog.PamLabel;
import PamView.panel.PamPanel;
public class StatusButton {
protected JLabel textOutput;
private DIYButton diyButton;
protected PamPanel mainPanel;
private static final int DEFULATSIZE = 30;
private PamSymbol colouredIcon = new PamSymbol(PamSymbolType.SYMBOL_CIRCLE, 20, 20, true, Color.BLUE, Color.BLUE);
protected PamLabel nameLabel;
protected ModuleStatus latestStatus;
protected Color[] buttonColours = {Color.GREEN, Color.ORANGE, Color.RED};
public StatusButton(String name) {
this(name, new Dimension(DEFULATSIZE, DEFULATSIZE));
}
public StatusButton(String name, Dimension size) {
this.mainPanel = createButton(name, size);
}
protected PamPanel createButton(String name, Dimension size) {
mainPanel = new PamPanel(PamColor.BORDER);
// simpleButton = new JButton(colouredIcon);
// Border bb = simpleButton.getBorder();
// System.out.println(bb);
textOutput = new PamLabel("Status information");
diyButton = new DIYButton(size);
nameLabel = new PamLabel(name + " ", JLabel.RIGHT);
// if (false) {
// mainPanel.setBorder(new TitledBorder(name));
// mainPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
// mainPanel.add(diyButton);
// mainPanel.add(textOutput);
// }
// else {
mainPanel.setLayout(new BorderLayout());
mainPanel.add(nameLabel);
mainPanel.add(diyButton, BorderLayout.EAST);
// mainPanel.add(textOutput);
// }
diyButton.addMouseListener(new StatusMouse());
return mainPanel;
}
/**
* Get the main component.
* @return the main component.
*/
public JComponent getComponent() {
return mainPanel;
}
/**
* Set the colour for a particular state
* @param state 0 1 or 2
* @param color colour to display.
*/
public void setColor(int state, Color color) {
if (state >= buttonColours.length) {
return;
}
buttonColours[state] = color;
}
private class DIYButton extends PamPanel {
public DIYButton(Dimension d) {
super(PamColor.BORDER);
setPreferredSize(d);
}
/**
*
*/
public DIYButton() {
this(new Dimension(DEFULATSIZE, DEFULATSIZE));
}
/* (non-Javadoc)
* @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
double h = g.getClipBounds().getHeight();
double w = g.getClipBounds().getWidth();
int h2 = getHeight();
int sz = (int) Math.min(h, getWidth());
int ww = sz - 6;
colouredIcon.draw(g, new Point(getWidth()/2-1, getHeight()/2-1), ww, ww);
}
}
public void setName(String name) {
nameLabel.setText(name + " ");
}
/**
* Update the status of this control, tooltips, colour, etc
* all depend on the status
* @param b
* @param moduleStatus
*/
public synchronized void setStatus(boolean exists, ModuleStatus moduleStatus) {
String txt;
Color col = null;
if (moduleStatus != null) {
txt = moduleStatus.toString();
int stat = Math.max(0, Math.min(moduleStatus.getStatus(), buttonColours.length-1));
col = buttonColours[stat];
// switch (moduleStatus.getStatus()) {
// case 0:
// col = Color.GREEN;
// break;
// case 1:
// col = Color.ORANGE;
// break;
// default:
// col = Color.RED;
// break;
// }
if (moduleStatus.getName() != null) {
nameLabel.setText(moduleStatus.getName() + " ");
}
}
else if (exists == false) {
txt = "not present\n";
col = Color.RED;
}
else {
txt = "No status data";
col = Color.ORANGE;
}
latestStatus = moduleStatus;
textOutput.setText(txt);
diyButton.setToolTipText("<html>"+txt);
if (col == null) {
// simpleButton.setIcon(null);
}
else {
colouredIcon.setFillColor(col);
colouredIcon.setLineThickness(1);
colouredIcon.setLineColor(PamColors.getInstance().getForegroudColor(PamColor.AXIS));
// simpleButton.setIcon(colouredIcon);
}
diyButton.repaint();
}
private class StatusMouse extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
showRemedialMenu(e);
}
}
}
public synchronized void showRemedialMenu(MouseEvent e) {
if (latestStatus == null) {
return;
}
RemedialAction remedialAction = latestStatus.getRemedialAction();
if (remedialAction == null) {
return;
}
JPopupMenu popMenu = new JPopupMenu(remedialAction.getInfo());
JMenuItem menuItem = new JMenuItem("Fix problem: " + remedialAction.getInfo());
menuItem.addActionListener(new RemedialActionListener(latestStatus, remedialAction));
popMenu.add(menuItem);
popMenu.show(e.getComponent(), e.getX(), e.getY());
}
private class RemedialActionListener implements ActionListener {
private RemedialAction RemedialAction;
private ModuleStatus currentStatus;
public RemedialActionListener(ModuleStatus currentStatus, RemedialAction remedialAction) {
super();
this.currentStatus = currentStatus;
RemedialAction = remedialAction;
}
@Override
public void actionPerformed(ActionEvent e) {
RemedialAction.takeAction(currentStatus);
}
}
}

View File

@ -1,133 +0,0 @@
package alfa.status.swing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.SwingConstants;
import PamController.status.ModuleStatus;
import PamView.dialog.PamLabel;
import PamView.panel.PamPanel;
/**
* Create a square status button.
*
* @author Jamie Macaulay
*
*/
public class StatusButtonSquare extends StatusButton {
/**
* Label for the panel
*/
private PamLabel label;
/**
* Holder panel.
*/
private PamPanel holder;
/**
* The name text.
*/
private String name;
private Dimension prefDim;
/**
* Constructor for the status button
* @param name - the name of the button
* @param buttonsize
*/
public StatusButtonSquare(String name, Dimension size) {
super(name);
this.name=name;
}
@Override
protected PamPanel createButton(String name, Dimension size) {
label = new PamLabel(name, SwingConstants.CENTER);
label.setSize(size);
label.setFont(new Font(null, Font.BOLD, 16));
label.setOpaque(true);
holder = new PamPanel(new BorderLayout());
holder.add(label, BorderLayout.CENTER);
holder.setPreferredSize(size);
holder.setOpaque(true);
return holder;
}
@Override
public synchronized void setStatus(boolean exists, ModuleStatus moduleStatus) {
String txt;
Color col = null;
// Debug.out.println("Hello STATUS BUTTON I am: " +moduleStatus.getStatus());
if (moduleStatus != null) {
txt = moduleStatus.toString();
int stat = Math.max(0, Math.min(moduleStatus.getStatus(), buttonColours.length-1));
col = buttonColours[stat];
// Debug.out.println("Hello STATUS BUTTON Col: " +col + " stat: " +stat);
// switch (moduleStatus.getStatus()) {
// case 0:
// col = Color.GREEN;
// break;
// case 1:
// col = Color.ORANGE;
// break;
// default:
// col = Color.RED;
// break;
// }
if (moduleStatus.getName() != null) {
nameLabel.setText(moduleStatus.getName() + " ");
}
}
else if (exists == false) {
txt = "not present\n";
col = Color.RED;
}
else {
txt = "No status data";
col = Color.ORANGE;
}
latestStatus = moduleStatus;
switch (moduleStatus.getStatus()) {
case ModuleStatus.STATUS_OK:
label.setText(name +" OK");
break;
case ModuleStatus.STATUS_WARNING :
label.setText(name +" WARNING");
break;
case ModuleStatus.STATUS_ERROR :
label.setText(name +" ERROR");
break;
}
label.setToolTipText("<html>"+txt);
if (col == null) {
// simpleButton.setIcon(null);
label.setBackground(Color.RED);
holder.setBackground(Color.RED);
}
else {
label.setText(txt);
label.setBackground(col);
holder.setBackground(col);
}
label.setOpaque(true);
holder.setOpaque(true);
label.validate();
label.repaint();
}
}

View File

@ -1,90 +0,0 @@
package alfa.status.swing;
import java.awt.BorderLayout;
import java.util.ArrayList;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.border.TitledBorder;
import PamController.status.ModuleStatus;
import PamModel.PamModuleInfo;
import PamView.PamColors.PamColor;
import PamView.panel.PamPanel;
import alfa.ControlledModuleInfo;
import alfa.status.StatusMonitor;
import alfa.status.StatusObserver;
/**
* Swing status display panel to go with the status monitor.
* @author Doug Gillespie
*
*/
public class StatusPanel implements StatusObserver {
private StatusMonitor statusMonitor;
private PamPanel statusPanel;
private PamPanel buttonPanel;
private StatusButton[] statusButtons;
public StatusPanel(StatusMonitor statusMonitor) {
this.statusMonitor = statusMonitor;
statusPanel = new PamPanel(PamColor.BORDER);
statusPanel.setBorder(new TitledBorder("Module Status"));
buttonPanel = new PamPanel(PamColor.BORDER);
statusPanel.setLayout(new BorderLayout());
statusPanel.add(buttonPanel, BorderLayout.NORTH);
refillButtonPanel();
statusMonitor.addObserver(this);
}
public JComponent getPanel() {
return statusPanel;
}
private void refillButtonPanel() {
buttonPanel.removeAll();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
ArrayList<ControlledModuleInfo> list = statusMonitor.getModulesList();
if (list == null) {
statusButtons = null;
return;
}
statusButtons = new StatusButton[list.size()];
for (int i = 0; i < list.size(); i++) {
statusButtons[i] = new StatusButton(list.get(i).getDefaultName());
buttonPanel.add(statusButtons[i].getComponent());
}
}
@Override
public void newModuleList() {
refillButtonPanel();
}
@Override
public void newStatus() {
updateAllStatus();
}
private void updateAllStatus() {
if (statusButtons == null) {
return;
}
ModuleStatus[] statuss = statusMonitor.getModuleStatus();
if (statuss == null) {
return;
}
if (statuss.length != statusButtons.length) {
return;
}
boolean[] existss = statusMonitor.getModuleExists();
for (int i = 0; i < statuss.length; i++) {
statusButtons[i].setStatus(existss[i], statuss[i]);
}
}
}

View File

@ -1,243 +0,0 @@
package alfa.swinggui;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Window;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import PamController.PamController;
import PamView.dialog.PamDialog;
import PamView.dialog.PamDialogPanel;
import PamView.dialog.PamGridBagContraints;
import PamView.panel.WestAlignedPanel;
import PamguardMVC.dataSelector.DataSelector;
import alfa.ALFAControl;
import alfa.ALFAParameters;
import loggerForms.FormDescription;
public class ALFADialog extends PamDialog {
private static final long serialVersionUID = 1L;
private static ALFADialog singleInstance;
private ALFAControl alfaControl;
private ALFAParameters alfaParameters;
private JTextField effIntNoWhales;
// private JTextField effIntWhales;
private JTextField histosPerInterval, binsPerHisto;
private JCheckBox reloadOldReports;
private JCheckBox launchScreenMirror;
private PamDialogPanel loggerPanel;
private PamDialogPanel loggerDialogPanel;
private JRadioButton loggerComma, loggerJson, loggerXML;
private JRadioButton jRadioButtonClks;
private JRadioButton jRadioButtonTrns;
private JCheckBox followOffline;
private static final int TSCALE = 60;
private ALFADialog(Window parentFrame, ALFAControl alfaControl) {
super(parentFrame, alfaControl.getUnitName() + " options", true);
this.alfaControl = alfaControl;
JTabbedPane tabPane = new JTabbedPane();
JPanel reportPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new PamGridBagContraints();
reportPanel.setBorder(new TitledBorder("Effort Intervals"));
c.gridwidth = 3;
reportPanel.add(new JLabel("DataType ", JLabel.LEFT), c);
c.gridy++;
jRadioButtonClks = new JRadioButton("No. Clicks in Trains");
reportPanel.add(jRadioButtonClks, c);
c.gridy++;
jRadioButtonTrns= new JRadioButton("Click Trains");
reportPanel.add(jRadioButtonTrns, c);
c.gridy++;
ButtonGroup group = new ButtonGroup();
group.add(jRadioButtonClks);
group.add(jRadioButtonTrns);
c.gridwidth = 3;
reportPanel.add(new JLabel("Standard Reporting Intervals ", JLabel.LEFT), c);
c.gridwidth = 1;
c.gridy++;
reportPanel.add(new JLabel("Reporting interval ", JLabel.RIGHT), c);
c.gridx++;
reportPanel.add(effIntNoWhales = new JTextField(5), c);
c.gridx++;
reportPanel.add(new JLabel( "(minutes)"), c);
c.gridx = 0;
c.gridy++;
reportPanel.add(new JLabel("Angle Histograms ", JLabel.RIGHT), c);
c.gridx++;
reportPanel.add(histosPerInterval = new JTextField(5), c);
c.gridx++;
reportPanel.add(new JLabel( "(per report)"), c);
c.gridx = 0;
c.gridy++;
reportPanel.add(new JLabel("Bins per Histogram ", JLabel.RIGHT), c);
c.gridx++;
reportPanel.add(binsPerHisto = new JTextField(5), c);
c.gridy++;
c.gridx = 0;
c.gridwidth = 3;
reportPanel.add(reloadOldReports = new JCheckBox("Reload old reports at start up"), c);
tabPane.add("Messaging", reportPanel);
DataSelector loggerformsSelector = alfaControl.getLoggerMonitor().getFormsSelector();
JPanel logStPanel = new JPanel(new GridBagLayout());
GridBagConstraints lc = new PamGridBagContraints();
loggerComma = new JRadioButton("Comma separated");
loggerJson = new JRadioButton("JSON String");
loggerXML = new JRadioButton("XML");
ButtonGroup bg = new ButtonGroup();
bg.add(loggerComma);
bg.add(loggerJson);
bg.add(loggerXML);
logStPanel.setBorder(new TitledBorder("Message Style"));
logStPanel.add(loggerComma, c);
c.gridy++;
logStPanel.add(loggerJson,c);
// c.gridy++;
// logStPanel.add(loggerXML,c);
if (loggerformsSelector != null) {
loggerDialogPanel = loggerformsSelector.getDialogPanel();
JPanel lp = new JPanel();
lp.setLayout(new BoxLayout(lp, BoxLayout.Y_AXIS));
lp.add(logStPanel);
lp.add(loggerDialogPanel.getDialogComponent());
tabPane.addTab("Logger Forms", lp);
}
JPanel dispPanel = new JPanel(new GridBagLayout());
dispPanel.setBorder(new TitledBorder("Display Options"));
c = new PamGridBagContraints();
dispPanel.add(launchScreenMirror = new JCheckBox("Launch Screen Mirror"), c);
tabPane.add("Display", dispPanel);
followOffline = new JCheckBox("Follow data offline");
followOffline.setToolTipText("Automaticlly check server for new data arrival, update data map and display");
if (PamController.getInstance().getRunMode() == PamController.RUN_PAMVIEW) {
JPanel offlinePanel = new JPanel(new GridBagLayout());
offlinePanel.setBorder(new TitledBorder("Offline"));
c = new PamGridBagContraints();
offlinePanel.add(followOffline, c);
tabPane.add("Offline", offlinePanel);
}
effIntNoWhales.setToolTipText("Interval for sending ship track data ");
// effIntWhales.setToolTipText("Interval for sending data when whale have been detected");
histosPerInterval.setToolTipText("Number of angle histograms per reporting interval");
binsPerHisto.setToolTipText("Number of angle bins per histogram");
reloadOldReports.setToolTipText("Reload old reports when the system restarts");
setDialogComponent(tabPane);
}
public static ALFAParameters showDialog(Window parentFrame, ALFAControl alfaControl) {
// if (singleInstance == null || singleInstance.getOwner() != parentFrame || singleInstance.alfaControl != alfaControl) {
singleInstance = new ALFADialog(parentFrame, alfaControl);
// }
singleInstance.setParams(alfaControl.getAlfaParameters().clone());
singleInstance.setVisible(true);
return singleInstance.alfaParameters;
}
private void setParams(ALFAParameters alfaParameters) {
this.alfaParameters = alfaParameters;
effIntNoWhales.setText(String.format("%d", alfaParameters.effortMsgIntervalNoWhales/TSCALE));
histosPerInterval.setText(String.format("%d", alfaParameters.histosPerReportInterval));
binsPerHisto.setText(String.format("%d", alfaParameters.getBinsPerhistogram()));
reloadOldReports.setSelected(alfaParameters.reloadOldReports);
loggerComma.setSelected(alfaParameters.loggerFormFormat == FormDescription.LOGGER_FORMS_COMMA);
loggerJson.setSelected(alfaParameters.loggerFormFormat == FormDescription.LOGGER_FORMS_JSON);
loggerXML.setSelected(alfaParameters.loggerFormFormat == FormDescription.LOGGER_FORMS_XML);
if (loggerDialogPanel != null) {
loggerDialogPanel.setParams();
}
jRadioButtonClks.setSelected(!alfaParameters.useClkTrains);
launchScreenMirror.setSelected(alfaParameters.autoScreenMirror);
followOffline.setSelected(alfaParameters.followOffline);
this.pack();
}
@Override
public boolean getParams() {
try {
int inval = Integer.valueOf(effIntNoWhales.getText());
alfaParameters.effortMsgIntervalNoWhales = inval*TSCALE;
inval = Integer.valueOf(histosPerInterval.getText());
alfaParameters.histosPerReportInterval = inval;
int bins = Integer.valueOf(binsPerHisto.getText());
alfaParameters.setBinsPerhistogram(bins);
}
catch (NumberFormatException e) {
return showWarning("Invalid interval data, must be an Integer (whole) number");
}
if (loggerDialogPanel != null) {
if (loggerDialogPanel.getParams() == false) {
return showWarning("Error in logger forms selection");
}
}
alfaParameters.reloadOldReports = reloadOldReports.isSelected();
alfaParameters.autoScreenMirror = launchScreenMirror.isSelected();
if (loggerJson.isSelected()) {
alfaParameters.loggerFormFormat = FormDescription.LOGGER_FORMS_JSON;
}
else if (loggerComma.isSelected()) {
alfaParameters.loggerFormFormat = FormDescription.LOGGER_FORMS_COMMA;
}
else if (loggerXML.isSelected()) {
alfaParameters.loggerFormFormat = FormDescription.LOGGER_FORMS_XML;
}
alfaParameters.followOffline = followOffline.isSelected();
if (this.jRadioButtonClks.isSelected()) alfaParameters.useClkTrains = false;
else alfaParameters.useClkTrains = true;
return true;
}
@Override
public void cancelButtonPressed() {
alfaParameters = null;
}
@Override
public void restoreDefaultSettings() {
setParams(new ALFAParameters());
}
}

View File

@ -1,189 +0,0 @@
package alfa.swinggui;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import PamController.PamController;
import PamView.FullScreen;
import PamView.GuiFrameManager;
import PamView.PamGui;
import PamView.panel.PamTabbedPane;
import PamguardMVC.debug.Debug;
import alfa.ALFAControl;
/**
* Changes the PAMGuard <i>Swing<i> GUI to make it more touch friendly and remove some clutter so that
* the UI is a little easier to use on tablets.
*
* @author Jamie Macaulay
*
*/
public class ALFAGUITransformer {
/**
* The height of the main tabs
*/
public static final int TABHEIGHT = 65;
public static final int TABWIDTH = 90;
/**
* The main menu
*/
private JPopupMenu menu;
/**
* Reference ot hte GUI frame manager.
*/
private GuiFrameManager guiFrameManager;
private Container glassPane;
public static ImageIcon settings = new ImageIcon(ClassLoader
.getSystemResource("Resources/MenuButton.png"));
public ALFAGUITransformer(ALFAControl alfaControl) {
this.guiFrameManager = PamController.getInstance().getGuiFrameManager();
//set the tab size.
guiFrameManager.getFrameGui(0).setTabsSize(new Dimension(TABWIDTH, TABHEIGHT));
//guiFrameManager.getFrameGui(0).setTabFont(new Font(null, Font.BOLD, 16));
//get rid of the top tool bar
guiFrameManager.getFrameGui(0).setToolBarVisible(false);
guiFrameManager.getFrameGui(0).getSidePanel().showPanel(true);
guiFrameManager.getFrameGui(0).getSidePanel().disableShowButton(true);
//total HACK to add button to tab pane
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
addButtonToPane(guiFrameManager.getFrameGui(0));
}
});
//get rid of all those menus that are going to confuse folk.
guiFrameManager.getFrameGui(0).getGuiFrame().setJMenuBar(null);
setMenuItems();
FullScreen.setGoFullScreen(true);
}
/**
* Set the menu items
*/
private synchronized void setMenuItems() {
guiFrameManager.getFrameGui(0).getGuiFrame().setJMenuBar(null);
if (menu!=null) {
menu.removeAll();
}
JMenuBar menuBar = guiFrameManager.getFrameGui(0).makeGuiMenu();
// for (int i=0; i<menuBar.getMenuCount(); i++) {
// Debug.out.println("ALFA 2: MenuBar: " + menuBar.getMenu(i).getText() + " N: " + menuBar.getMenuCount());
// }
if (menu!=null && menuBar!=null) {
final int count = menuBar.getMenuCount();
ArrayList<JMenu> newMenuItems = new ArrayList<JMenu>();
for (int i=0; i<count; i++) {
//Debug.out.println("MenuBar: " + menuBar.getMenu(i).getText()+ " N: " + menuBar.getMenuCount() );
newMenuItems.add(menuBar.getMenu(i));
}
//another total HACK. Don;t know why but simply adding one menu item from another cause all sorts of issues...
//maybe should replace with while loops
for (int i=0; i<count; i++) {
menu.add(newMenuItems.get(i));
}
}
}
/**
* Add button to the tab pane with all menus etc. Again, pretty HACKY with a glass pane to put button on.
* @param gui -the gui frame to add the button to.
*/
private void addButtonToPane(PamGui gui) {
PamTabbedPane tabbedPane = gui.getTabbedPane();
tabbedPane.setTabsDrag(false);
// Rectangle tabBounds = tabbedPane.getBoundsAt(0);
glassPane = (Container) gui.getGuiFrame().getGlassPane();
glassPane.setVisible(true);
glassPane.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.NONE;
gbc.insets = new Insets(0, 0, 0, 0);
gbc.anchor = GridBagConstraints.NORTHEAST;
JButton button = new JButton(settings);
//navigation menu
button.setPreferredSize(new Dimension(button.getPreferredSize().width,
(int) TABHEIGHT+5));
glassPane.add(button, gbc);
menu = new JPopupMenu();
menu.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
menu.show(button, 0, button.getBounds().height);
}
});
ChangeListener changeListener = new ChangeListener() {
public void stateChanged(ChangeEvent changeEvent) {
glassPane.setVisible(true); //HACK
setMenuItems();
}
};
tabbedPane.addChangeListener(changeListener);
// button.setPreferredSize(new Dimension(button.getPreferredSize().width,
// (int) tabBounds.getHeight() - 2));
}
/**
* Notification passed from controller to the GUI transformer
* @param changeType - the change type flag.
*/
public synchronized void notifyModelChanged(int changeType) {
setMenuItems();
}
}

View File

@ -1,32 +0,0 @@
package alfa.swinggui;
import javax.swing.JComponent;
/**
* Layout options for ALFA data display.
* Made interface so can play with a few different ideas.
* @author Doug
*
*/
public interface ALFALayout {
/**
*
* @return component to slot into CENTER of main display area.
*/
public JComponent getComponent();
public void setOptionsComponent(JComponent optionsComponent);
public void setWestStatusComponent(JComponent statusComponent);
public void setMapComponent(JComponent mapComponent);
public void setSpermSummaryComponents(JComponent spermSummary);
public void setCommsComponent(JComponent commsComponent);
public void setNorthStatusComponents(JComponent northComponent);
public void setHelpcomponent(JComponent helpComponent);
}

View File

@ -1,107 +0,0 @@
package alfa.swinggui;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JTabbedPane;
import javax.swing.border.TitledBorder;
import PamView.PamColors.PamColor;
import PamView.panel.PamPanel;
public class ALFALayout1 implements ALFALayout {
private PamPanel alfaPanel;
private PamPanel mainCentral, mainNorth, mainSplit, mainWest;
private PamPanel splitWestNorth, splitWestSouth, splitWest, splitEast, helpPane;
public ALFALayout1() {
alfaPanel = new PamPanel(new BorderLayout());
mainCentral = new PamPanel(new BorderLayout());
mainWest = new PamPanel(new BorderLayout());
mainNorth = new PamPanel();
mainSplit = new PamPanel();
splitWest = new PamPanel();
splitEast = new PamPanel(new BorderLayout());
splitWestNorth = new PamPanel();
splitWestSouth = new PamPanel();
helpPane = new PamPanel(new BorderLayout());
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Messaging", mainCentral);
tabbedPane.addTab("HELP", helpPane);
alfaPanel.setLayout(new BorderLayout());
alfaPanel.add(BorderLayout.CENTER, tabbedPane);
alfaPanel.add(BorderLayout.WEST, mainWest);
mainCentral.setLayout(new BorderLayout());
mainCentral.add(BorderLayout.NORTH, mainNorth);
mainCentral.add(BorderLayout.CENTER, mainSplit);
// mainSplit.setLayout(new BoxLayout(mainSplit, BoxLayout.X_AXIS));
mainSplit.setLayout(new GridLayout(1, 1));
mainSplit.add(splitWest);
// mainSplit.add(splitEast);
// splitWest.setLayout(new BoxLayout(splitWest, BoxLayout.Y_AXIS));
splitWest.setLayout(new GridLayout(2, 1));
splitWest.add(splitWestNorth);
splitWest.add(splitWestSouth);
// splitEast.setBorder(new TitledBorder("Map"));
splitWestNorth.setBorder(new TitledBorder("Sperm Whales"));
splitWestSouth.setBorder(new TitledBorder("Comms"));
}
@Override
public JComponent getComponent() {
return alfaPanel;
}
@Override
public void setOptionsComponent(JComponent optionsComponent) {
mainWest.add(optionsComponent, BorderLayout.NORTH);
}
@Override
public void setWestStatusComponent(JComponent statusComponent) {
// mainWest.removeAll();
mainWest.add(statusComponent, BorderLayout.CENTER);
}
@Override
public void setMapComponent(JComponent mapComponent) {
splitEast.removeAll();
splitEast.add(mapComponent);
}
@Override
public void setSpermSummaryComponents(JComponent spermSummary) {
splitWestNorth.setLayout(new BorderLayout());
splitWestNorth.setBorder(null);
splitWestNorth.removeAll();
splitWestNorth.add(spermSummary, BorderLayout.CENTER);
}
@Override
public void setCommsComponent(JComponent commsComponent) {
splitWestSouth.setLayout(new BorderLayout());
splitWestSouth.add(BorderLayout.CENTER, commsComponent);
}
@Override
public void setNorthStatusComponents(JComponent northComponent) {
// TODO Auto-generated method stub
}
@Override
public void setHelpcomponent(JComponent helpComponent) {
helpPane.setLayout(new BorderLayout());
helpPane.add(BorderLayout.CENTER, helpComponent);
}
}

View File

@ -1,46 +0,0 @@
package alfa.swinggui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import PamView.dialog.PamButton;
import PamView.panel.PamPanel;
import alfa.ALFAControl;
public class ALFAOptionsPanel {
private ALFAControl alfaControl;
private JPanel mainPanel;
private JButton optsButton;
public ALFAOptionsPanel(ALFAControl alfaControl) {
this.alfaControl = alfaControl;
mainPanel = new PamPanel();
mainPanel.setBorder(new TitledBorder("Options"));
optsButton = new PamButton("Settings...");
optsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
optionsButton();
}
});
mainPanel.add(optsButton);
}
public JComponent getComponent() {
return mainPanel;
}
private void optionsButton() {
alfaControl.showAlfaDialog();
}
}

View File

@ -1,243 +0,0 @@
package alfa.swinggui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Label;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import PamController.PamController;
import PamController.status.ModuleStatus;
import PamView.PamSidePanel;
import PamView.PamSymbol;
import PamView.PamSymbolType;
import PamView.dialog.PamButton;
import PamView.dialog.PamGridBagContraints;
import PamView.dialog.PamLabel;
import PamView.panel.PamPanel;
import PamguardMVC.debug.Debug;
import alfa.ALFAControl;
import alfa.effortmonitor.AngleHistogram;
import alfa.status.swing.StatusButton;
import alfa.status.swing.StatusButtonSquare;
/**
* The side pane holds status info and a big button to start and stop PAMGuard.
* @author Jamie Macaulay
*
*/
public class ALFASidePanel implements PamSidePanel {
private ALFAControl alfaControl;
private JPanel mainPanel;
private static String[] whaleButtonNames = {"Ahead", "Abeam", "Astern"};
private StatusButton[] whaleStatus = new StatusButton[whaleButtonNames.length];
private StatusButton systemStatus;
private PamPanel mainHolder;
/**
* The button to start and stop PAMGuard.
*/
private JButton startStopButton;
private static final int BUTTONSIZE = 40;
private static final int BUTTONWIDTH = 220;
public ALFASidePanel(ALFAControl alfaControl) {
this.alfaControl = alfaControl;
//button
mainHolder = new PamPanel(new BorderLayout());
startStopButton = new JButton();
startStopButton.setPreferredSize(new Dimension(BUTTONWIDTH, ALFAGUITransformer.TABHEIGHT));
startStopButton.setHorizontalAlignment(SwingConstants.CENTER);
startStopButton.addActionListener((action )->{
if (PamController.getInstance().getPamStatus() == PamController.PAM_RUNNING) {
// Debug.out.println("ALFA: PAMStop Pressed!!!--------------------");
PamController.getInstance().toolBarStopButton(null);
}
else if (PamController.getInstance().getPamStatus() == PamController.PAM_IDLE) {
// Debug.out.println("ALFA: PAMStart Pressed!!!--------------------");
PamController.getInstance().pamStart();
}
//button decoration occurs on notification
});
setStartStopStatus(false);
//the status pane
Color clearColour = new Color(0,0,0,0);
for (int i = 0; i < whaleButtonNames.length; i++) {
whaleStatus[i] = new StatusButton(whaleButtonNames[i], new Dimension(BUTTONWIDTH, ALFAGUITransformer.TABHEIGHT/2));
whaleStatus[i].setColor(0, clearColour);
whaleStatus[i].setStatus(true, new ModuleStatus(ModuleStatus.STATUS_OK));
}
// whaleStatus = new StatusButton(" Whales");
systemStatus = new StatusButtonSquare("System Diagnostics",new Dimension(BUTTONWIDTH, ALFAGUITransformer.TABHEIGHT));
mainPanel = new PamPanel();
mainPanel.setLayout(new GridBagLayout());
//mainPanel.setBorder(new TitledBorder("Status"));
GridBagConstraints c = new PamGridBagContraints();
// mainPanel.add(new PamView.dialog.PamLabel("System", JLabel.CENTER),c);
// c.gridx++;
// mainPanel.add(new PamView.dialog.PamLabel("Whales", JLabel.CENTER),c);
// c.gridx = 0;
// c.gridy++;
c.gridx = 0;
c.gridwidth=3;
c.gridheight=3;
if (!alfaControl.isViewer()) mainPanel.add(systemStatus.getComponent(),c);
c.gridwidth=1;
c.gridheight=1;
c.gridx = 2;
c.gridy ++;
c.gridy ++;
mainPanel.add(new JLabel("Sperm Whale Detections"),c);
c.gridy ++;
mainPanel.add(whaleStatus[0].getComponent(),c);
c.gridy ++;
mainPanel.add(whaleStatus[1].getComponent(),c);
c.gridy ++;
mainPanel.add(whaleStatus[2].getComponent(),c);
//advanced label
c.gridy ++;
c.gridwidth=3;
mainPanel.add(new JSeparator(),c);
PamLabel advLabel = new PamLabel("System Details", SwingConstants.CENTER);
//advLabel.setPreferredSize(new Dimension(BUTTONWIDTH, 2*BUTTONSIZE));
advLabel.setFont(new Font(null, Font.BOLD, 20));
advLabel.setVerticalTextPosition(JLabel.BOTTOM);
if (!alfaControl.isViewer()) mainHolder.add(BorderLayout.NORTH, startStopButton);
mainHolder.add(BorderLayout.CENTER, mainPanel);
if (!alfaControl.isViewer()) mainHolder.add(BorderLayout.SOUTH, advLabel);
}
/**
* Set the status of the go button.
* @param running
*/
public synchronized void setStartStopStatus(boolean running) {
//Debug.out.println("ALFA:p Run: !!" + running);
startStopButton.setFont(new Font(null, Font.BOLD, 20));
if (!running) {
startStopButton.setText("Press to Start");
// startStopButton.setBackground(Color.GREEN);
// startStopButton.setOpaque(true);
//startStopButton.setBorderPainted(false);
// startStopButton.setIcon( new PamSymbol(PamSymbolType.SYMBOL_TRIANGLER, 25, 25, true,
// Color.BLACK, Color.BLACK));
startStopButton.setBorder(BorderFactory.createLineBorder(Color.GREEN, 5)); // Line Border + Thickness of the Border }
startStopButton.setIconTextGap(1);
}
else {
startStopButton.setText("Press to Stop");
// startStopButton.setOpaque(true);
// startStopButton.setBackground(Color.GRAY);
// startStopButton.setIcon( new PamSymbol(PamSymbolType.SYMBOL_SQUARE, 25, 25, true,
// Color.BLACK, Color.BLACK));
startStopButton.setBorder(BorderFactory.createLineBorder(Color.GRAY, 5)); // Line Border + Thickness of the Border }
}
startStopButton.repaint();
startStopButton.validate();
startStopButton.repaint();
}
@Override
public JComponent getPanel() {
return mainHolder;
}
@Override
public void rename(String newName) {
// TODO Auto-generated method stub
}
public void statusUpdate() {
systemStatus.setStatus(true, alfaControl.getModuleStatus());
AngleHistogram aHist = alfaControl.getStatusAngleHistogram();
if (aHist != null) {
double[] data = aHist.getData();
double front = data[0];
double aft = data[data.length-1];
double abeam = aHist.getTotalContent()-front-aft;
setButtonState(0, front);
setButtonState(1, abeam);
setButtonState(2, aft);
}
// whaleStatus[0].setStatus(true, alfaControl.getWhaleStatus());
}
/**
* Set the state of the button.
* @param i - the state of the button.
* @param nClickTrains - the number of click trains.
*/
private void setButtonState(int i, double nClickTrains) {
StatusButton button = whaleStatus[i];
int state = ModuleStatus.STATUS_OK;
String msg;
if (nClickTrains >= 1) {
state = ModuleStatus.STATUS_WARNING;
}
if (nClickTrains >= 3) {
state = ModuleStatus.STATUS_ERROR;
}
msg = String.format("%d click trains detected %s", (int)nClickTrains, whaleButtonNames[i].toLowerCase());
button.setStatus(true, new ModuleStatus(state, msg));
}
/**
* Notification passed from controller to side panel
* @param changeType - the change type flag.
*/
public synchronized void notifyModelChanged(int changeType) {
//Debug.out.println("ALFA SIDE PANE: " + changeType);
switch (changeType) {
case PamController.PAM_RUNNING:
setStartStopStatus(true);
break;
case PamController.PAM_IDLE:
setStartStopStatus(false);
break;
case PamController.PAM_STALLED:
setStartStopStatus(false);
break;
}
}
}

View File

@ -1,83 +0,0 @@
package alfa.swinggui;
import java.awt.Frame;
import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JToolBar;
import Map.MapController;
import Map.SimpleMap;
import PamView.PamTabPanel;
import alfa.ALFAControl;
import alfa.help.gui.ALFAHelpPanel;
import alfa.status.swing.StatusPanel;
public class BBSwingTabPanel implements PamTabPanel {
private ALFAControl alfaControl;
// private PamPanel mainPanel;
private StatusPanel statusPanel;
// private PamPanel mapSpace;
// private SimpleMap simpleMap;
private ALFALayout alfaLayout;
public BBSwingTabPanel(ALFAControl alfaControl) {
this.alfaControl = alfaControl;
alfaLayout = new ALFALayout1();
statusPanel = new StatusPanel(alfaControl.getStatusMonitor());
alfaLayout.setWestStatusComponent(statusPanel.getPanel());
ALFAOptionsPanel alfaOptionsPanel = new ALFAOptionsPanel(alfaControl);
alfaLayout.setOptionsComponent(alfaOptionsPanel.getComponent());
alfaLayout.setHelpcomponent(new ALFAHelpPanel(alfaControl).getComponent());
}
@Override
public JMenu createMenu(Frame parentFrame) {
// TODO Auto-generated method stub
return null;
}
@Override
public JComponent getPanel() {
return alfaLayout.getComponent();
}
@Override
public JToolBar getToolBar() {
// TODO Auto-generated method stub
return null;
}
/**
* Called when units are added or removed.
*/
public void updateUnits() {
// if (mapSpace.getComponentCount() == 0) {
// MapController mapCon = bigBrotherControl.findMapController();
// if (mapCon != null) {
// simpleMap = new SimpleMap(mapCon, false);
// mapSpace.setLayout(new BorderLayout());
// mapSpace.add(simpleMap, BorderLayout.CENTER);
// }
//// mapCon.
// MapController mapCon = alfaControl.findMapController();
// if (mapCon != null) {
// simpleMap = new SimpleMap(mapCon, false);
// alfaLayout.setMapComponent(simpleMap);
// }
// alfaLayout.setSpermSummaryComponents(bigBrotherControl.getClickMonitorProcess().getSwingComponent());
IntervalTablePanel intervalTablePanel = new IntervalTablePanel(alfaControl,alfaControl.getEffortMonitor().getIntervalDataBlock());
alfaLayout.setSpermSummaryComponents(intervalTablePanel.getComponent());
JComponent commsPanel = alfaControl.getMessageProcess().getSwingCommsPanel(SwingMessagePanel.SHOW_OUTGOING);
alfaLayout.setCommsComponent(commsPanel);
}
}

View File

@ -1,423 +0,0 @@
package alfa.swinggui;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import GPS.GPSControl;
import GPS.GPSDataBlock;
import GPS.GpsDataUnit;
import PamController.PamController;
import PamUtils.Coordinate3d;
import PamUtils.LatLong;
import PamView.ColourArray;
import PamView.GeneralProjector;
import PamView.GeneralProjector.ParameterType;
import PamView.GeneralProjector.ParameterUnits;
import PamView.PamColors;
import PamView.PamColors.PamColor;
import PamView.PamKeyItem;
import PamView.PamSymbol;
import PamView.PamSymbolType;
import PamView.PanelOverlayDraw;
import PamguardMVC.PamDataBlock;
import PamguardMVC.PamDataUnit;
import alfa.ALFAControl;
import alfa.effortmonitor.AngleHistogram;
import alfa.effortmonitor.IntervalDataUnit;
/**
* Draws the satellite summary data on the map for the summary module. This shows a ships
* track line and the summary localisation data.
*
* @author Doug Gillespie
*
*/
public class IntervalOverlayDraw extends PanelOverlayDraw {
private static PamSymbol defaultSymbol = new PamSymbol();
private ALFAControl alfaControl;
private double[] colourLims = new double[] {0, 400};
private ColourArray colourArray;
private boolean isViewer;
int DRAW_SEGMENTS = 1;
int DRAW_ARROWS = 2;
int drawType = DRAW_ARROWS;
PamSymbol nullSymbol = new PamSymbol(PamSymbolType.SYMBOL_CIRCLE, 5, 5, true, Color.RED, Color.RED);
public IntervalOverlayDraw(ALFAControl alfaControl) {
super(defaultSymbol );
this.alfaControl = alfaControl;
//dodger blue, green, yellow, orange, red.
// colourArray = ColourArray.createMultiColouredArray(100, new Color(30, 144, 255), Color.YELLOW, Color.ORANGE, Color.RED);
colourArray = ColourArray.createMultiColouredArray(100, Color.BLUE, Color.CYAN, Color.GREEN, Color.YELLOW, Color.ORANGE, Color.RED);
// colourArray.setAlpha(255);
// colourArray.setAlpha(128);
isViewer = PamController.getInstance().getRunMode() == PamController.RUN_PAMVIEW;
checkColorLims();
}
/**
* Check the colour limits for click trains.
*/
private void checkColorLims() {
if (this.alfaControl.getAlfaParameters().useClkTrains) {
colourLims[0] = 0;
colourLims[1] = 10;
}
else {
colourLims[0] = 0;
colourLims[1] = 400;
}
}
@Override
public boolean canDraw(ParameterType[] parameterTypes, ParameterUnits[] parameterUnits) {
if (parameterTypes[0] == ParameterType.LATITUDE
&& parameterTypes[1] == ParameterType.LONGITUDE) {
return true;
}
else {
return false;
}
}
@Override
public Rectangle drawDataUnit(Graphics g, PamDataUnit pamDataUnit, GeneralProjector generalProjector) {
Rectangle r = null;
if (generalProjector.getParmeterType(0) == ParameterType.LATITUDE
&& generalProjector.getParmeterType(1) == ParameterType.LONGITUDE) {
r = drawOnMap(g, pamDataUnit, generalProjector);
}
return r;
}
private Rectangle drawOnMap(Graphics g, PamDataUnit pamDataUnit, GeneralProjector generalProjector) {
IntervalDataUnit idu = (IntervalDataUnit) pamDataUnit;
if (idu.getnClickTrains() == 0) {
// return null;
}
Rectangle r = drawGPSLine(g, idu, generalProjector);
if (r == null) {
// r = drawEndPoints(g, idu, generalProjector);
}
ArrayList<AngleHistogram> angleHists = idu.getAngleHistograms();
long defHistLength = alfaControl.getAlfaParameters().effortMsgIntervalNoWhales /
alfaControl.getAlfaParameters().histosPerReportInterval * 1000;
synchronized (angleHists) {
int iHist = 0;
long histStart, histEnd;
for (AngleHistogram angleHist : angleHists) {
if (isViewer) {
histStart = (long) (idu.getTimeMilliseconds() + idu.getDurationInMilliseconds() / angleHists.size() * iHist);
histEnd = (long) (idu.getTimeMilliseconds() + idu.getDurationInMilliseconds() / angleHists.size() * (iHist+1));
}
else {
histStart = idu.getTimeMilliseconds() + (iHist*defHistLength);
histEnd = histStart+defHistLength;
}
drawAngleHistogram(g, idu, generalProjector, angleHist, iHist, histStart, histEnd);
iHist++;
}
}
return r;
}
private void drawAngleHistogram(Graphics g, IntervalDataUnit pamDataUnit, GeneralProjector generalProjector,
AngleHistogram angleHist, int iAngleHist, long histStart, long histEnd) {
Graphics2D g2d = (Graphics2D) g;
//check colour limits.
checkColorLims();
double[] data = angleHist.getData();
if (data == null || data.length == 0) {
return;
}
double angStep = 180/data.length;
int[] polyX = new int[4];
int[] polyY = new int[4];
LatLong ll1 = findGpsPos(histStart, pamDataUnit);
LatLong ll2 = findGpsPos(histEnd, pamDataUnit);
Point coord1 = generalProjector.getCoord3d(ll1).getXYPoint();
Point coord2 = generalProjector.getCoord3d(ll2).getXYPoint();
LatLong lll = findGpsPos((histStart+histEnd)/2, pamDataUnit);
Coordinate3d c3d0 = generalProjector.getCoord3d(lll);
if (ll1 == null || ll2 == null || lll == null) return;
double angPM = 6;
double r = 5000;
r = ll1.distanceToMetres(ll2)/2.;
if (r == 0) {
r = 1000;
}
/**
* Draw the trackline segment coloured by status.
*/
int nWhale = 0;
Color lineCol = PamColors.getInstance().getColor(PamColor.GPSTRACK);
for (int i = 0; i < data.length; i++) {
nWhale += data[i];
}
if (nWhale == 1) {
lineCol = Color.ORANGE;
}
else if (nWhale >= 2) {
lineCol = Color.RED;
}
g.setColor(lineCol);
Stroke stroke = g2d.getStroke();
g2d.setStroke(new BasicStroke(3));
g.drawLine(coord1.x, coord1.y, coord2.x, coord2.y);
// if (data[i] == 0) {
// nullSymbol.setFillColor(lineCol);
nullSymbol.setLineColor(lineCol);
nullSymbol.draw(g, c3d0.getXYPoint());
// continue;
// }
g2d.setStroke(new BasicStroke(5));
generalProjector.addHoverData(c3d0, pamDataUnit);
for (int i = 0; i < data.length; i++) {
// data[i] = i+1;
if (data[i] == 0) {
continue;
}
// if (ll1 == null || ll2 == null) {
// continue;
// }
double[] angles;
if (i == 0) {
double[] aa = {0};
angles = aa;
// ll2 = ll1;
lll = ll2;
angPM = angStep;
}
else if (i == data.length-1) {
double[] aa = {180};
angles = aa;
// ll1 = ll2;
lll = ll1;
angPM = angStep;
}
else {
double ang = ((double) i + 0.5) * angStep;
double[] aa = {-ang, ang};
angles = aa;
angPM = angStep/2;
}
angPM = 20;
// g.drawString("h", (int) c3d0.x, (int) c3d0.y);
polyX[0] = (int) c3d0.x;
polyY[0] = (int) c3d0.y;
// Coordinate3d c3d1 = generalProjector.getCoord3d(ll2);
// polyX[1] = (int) c3d1.x;
// polyY[1] = (int) c3d1.y;
double shipHead = ll1.bearingTo(ll2);
for (int s = 0; s < angles.length; s++) {
double ang = shipHead + angles[s]-angPM;
LatLong ll = lll.travelDistanceMeters(ang, r*.8);
Coordinate3d c3d = generalProjector.getCoord3d(ll);
polyX[1] = (int) c3d.x;
polyY[1] = (int) c3d.y;
ang = shipHead + angles[s];
ll = lll.travelDistanceMeters(ang, r);
c3d = generalProjector.getCoord3d(ll);
polyX[2] = (int) c3d.x;
polyY[2] = (int) c3d.y;
ang = shipHead + angles[s]+angPM;
ll = lll.travelDistanceMeters(ang, r*.8);
c3d = generalProjector.getCoord3d(ll);
polyX[3] = (int) c3d.x;
polyY[3] = (int) c3d.y;
// Color col = colourArray.checkColour((int) data[i]*2);
Color col = colourArray.getColour(data[i], colourLims[0], colourLims[1]);
g.setColor(col);
if (drawType == DRAW_SEGMENTS) {
g.fillPolygon(polyX, polyY, 4);
int xT = (polyX[2]+polyX[3])/2;
int yT = (polyY[2]+polyY[3])/2;
g.setColor(Color.black);
g.drawString(String.format("%.0f", data[i]), xT, yT);
}
else if (drawType == DRAW_ARROWS) {
g2d.drawLine(polyX[0], polyY[0], polyX[2], polyY[2]);
g2d.drawLine(polyX[1], polyY[1], polyX[2], polyY[2]);
g2d.drawLine(polyX[3], polyY[3], polyX[2], polyY[2]);
int xT = (polyX[2]+polyX[3])/2;
int yT = (polyY[2]+polyY[3])/2;
g.setColor(Color.black);
g.drawString(String.format("%.0f", data[i]), xT, yT);
}
}
}
g2d.setStroke(stroke);
}
/**
* find lat long either from striahg tline in data unit or from tru gps data.
* @param histStart
* @param pamDataUnit
* @return
*/
private LatLong findGpsPos(long time, IntervalDataUnit pamDataUnit) {
// LatLong ll = findRealGPS(time);
// if (ll != null) {
// return ll;
// }
double interpFac = (time - pamDataUnit.getTimeMilliseconds()) / pamDataUnit.getDurationInMilliseconds();
interpFac = Math.max(0, Math.min(interpFac, 1.));
LatLong ll1 = pamDataUnit.getFirstGPSData();
LatLong ll2 = pamDataUnit.getLastGPSData();
if (ll1 == null || ll2 == null) {
return null;
}
LatLong ll = new LatLong(ll1.getLatitude() + (ll2.getLatitude()-ll1.getLatitude())*interpFac,
ll1.getLongitude() + (ll2.getLongitude()-ll1.getLongitude())*interpFac);
return ll;
}
private LatLong findRealGPS(long time) {
GPSControl gpsControl = GPSControl.getGpsControl();
if (gpsControl == null) {
return null;
}
GPSDataBlock gpsDataBlock = gpsControl.getGpsDataBlock();
if (gpsDataBlock == null) {
return null;
}
GpsDataUnit gpsDataUnit = gpsDataBlock.getClosestUnitMillis(time);
if (gpsDataUnit != null) {
return gpsDataUnit.getGpsData();
}
else {
return null;
}
}
private Rectangle drawGPSLine(Graphics g, IntervalDataUnit idu, GeneralProjector generalProjector) {
GPSControl gpsControl = GPSControl.getGpsControl();
if (gpsControl == null) {
return null;
}
GPSDataBlock gpsDataBlock = gpsControl.getGpsDataBlock();
if (gpsDataBlock == null) {
return null;
}
// see if we can find some GPS points in this range of track, if so draw a line between them.
List<Point> points = new LinkedList<>();
Point lastPoint = new Point(-1000, -1000);
synchronized (gpsDataBlock.getSynchLock()) {
ListIterator<GpsDataUnit> iter = gpsDataBlock.getListIterator(idu.getTimeMilliseconds(), 0, PamDataBlock.MATCH_BEFORE, PamDataBlock.MATCH_BEFORE);
if (iter == null) {
return null;
}
while (iter.hasNext()) {
GpsDataUnit gpsDataUnit = iter.next();
if (gpsDataUnit.getTimeMilliseconds() > idu.getEndTimeInMilliseconds()) {
break;
}
Point p = generalProjector.getCoord3d(gpsDataUnit.getGpsData()).getXYPoint();
if (p.equals(lastPoint)) {
continue;
}
points.add(p);
lastPoint = p;
}
}
if (points.isEmpty()) {
return null;
}
lastPoint = points.get(0);
g.setColor(Color.RED);
ListIterator<Point> pIter = points.listIterator(1);
int meanX = lastPoint.x, meanY = lastPoint.y;
int minX, maxX, minY, maxY;
minX = maxX = meanX;
minY = maxY = meanY;
while (pIter.hasNext()) {
Point p = pIter.next();
g.drawLine(lastPoint.x, lastPoint.y, p.x, p.y);
lastPoint = p;
meanX += p.x;
meanY += p.y;
minX = Math.min(minX, p.x);
maxX = Math.max(maxX, p.x);
minY = Math.min(minY, p.y);
maxY = Math.max(maxY, p.y);
}
Coordinate3d meanPt = new Coordinate3d(meanX/points.size(), meanY/points.size());
generalProjector.addHoverData(meanPt, idu);
return new Rectangle(minX, minY, maxX-minX, maxY-minY);
}
/**
* Just draw a straight line between the end points of the segment.
* @param g
* @param pamDataUnit
* @param generalProjector
* @return
*/
private Rectangle drawEndPoints(Graphics g, IntervalDataUnit idu, GeneralProjector generalProjector) {
int nTrains = idu.getnClickTrains();
if (nTrains == 0) {
// return null;
}
LatLong ll1 = idu.getFirstGPSData();
LatLong ll2 = idu.getLastGPSData();
if (ll1 == null || ll2 == null) {
return null;
}
Coordinate3d c3d1 = generalProjector.getCoord3d(ll1);
Coordinate3d c3d2 = generalProjector.getCoord3d(ll2);
Point pt1 = c3d1.getXYPoint();
Point pt2 = c3d2.getXYPoint();
g.setColor(Color.RED);
g.drawLine(pt1.x, pt1.y, pt2.x, pt2.y);
Rectangle r = new Rectangle(Math.min(pt1.y, pt2.x), Math.min(pt1.y, pt2.y),
Math.abs(pt1.y-pt2.x), Math.abs(pt1.y-pt2.y));
generalProjector.addHoverData(c3d1, idu);
generalProjector.addHoverData(c3d2, idu);
return r;
}
@Override
public PamKeyItem createKeyItem(GeneralProjector generalProjector, int keyType) {
return null;
}
@Override
public String getHoverText(GeneralProjector generalProjector, PamDataUnit dataUnit, int iSide) {
return dataUnit.getSummaryString();
}
}

View File

@ -1,117 +0,0 @@
package alfa.swinggui;
import java.awt.BorderLayout;
import java.util.Arrays;
import javax.swing.JComponent;
import GPS.GpsData;
import PamUtils.PamCalendar;
import PamView.component.DataBlockTableView;
import PamView.panel.PamPanel;
import alfa.ALFAControl;
import alfa.effortmonitor.AngleHistogram;
import alfa.effortmonitor.IntervalDataBlock;
import alfa.effortmonitor.IntervalDataUnit;
public class IntervalTablePanel {
private IntervalDataBlock intervalDataBlock;
private IntervalTable intervalTable;
private PamPanel mainPanel;
private ALFAControl alfaControl;
private final String[] baseColumnNames = {"Start", "Position", "End", "Postion", "% Effort", "Trains", "Clicks"};
public IntervalTablePanel(ALFAControl alfaControl, IntervalDataBlock intervalDataBlock) {
this.alfaControl = alfaControl;
intervalTable = new IntervalTable(intervalDataBlock);
mainPanel = new PamPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(BorderLayout.CENTER, intervalTable.getComponent());
}
public JComponent getComponent() {
return mainPanel;
}
private class IntervalTable extends DataBlockTableView<IntervalDataUnit>{
public IntervalTable(IntervalDataBlock intervalDataBlock) {
super(intervalDataBlock, "Monitor intervals");
}
@Override
public String[] getColumnNames() {
int nHistos = alfaControl.getAlfaParameters().histosPerReportInterval;
String[] columnNames = Arrays.copyOf(baseColumnNames, baseColumnNames.length +nHistos);
for (int i = 0; i < nHistos; i++) {
columnNames[i+baseColumnNames.length] = "Interval_" + (i+1);
}
return columnNames;
}
@Override
public Object getColumnData(IntervalDataUnit dataUnit, int column) {
if (dataUnit == null) {
return null;
}
switch (column) {
case 0:
return formatTime(dataUnit.getTimeMilliseconds());
case 1:
GpsData gpsData = dataUnit.getFirstGPSData();
if (gpsData == null) {
return "no GPS";
}
else {
return gpsData.formatLatitude() + ", " + gpsData.formatLongitude();
}
case 2:
return formatTime(dataUnit.getEndTimeInMilliseconds());
case 3:
GpsData endGpsData = dataUnit.getFirstGPSData();
if (endGpsData == null) {
return "no GPS";
}
else {
return endGpsData.formatLatitude() + ", " + endGpsData.formatLongitude();
}
case 4:
double duration = dataUnit.getDurationInMilliseconds();
return String.format("%3.0f %% of %s", dataUnit.getPercentEffort(), PamCalendar.formatTime((long) duration));
case 5:
return dataUnit.getnClickTrains();
case 6:
return dataUnit.getnClicks();
}
int iHist = column-baseColumnNames.length;
if (iHist < 0) return null;
AngleHistogram angleHist = dataUnit.getAngleHistogram(iHist);
if (angleHist == null) {
return null;
}
double[] data = angleHist.getData();
if (data == null || data.length == 0) {
return null;
}
String str = String.format("(%.0f",data[0]);
for (int i = 1; i < data.length; i++) {
str += String.format(",%.0f", data[i]);
}
str += ")";
return str;
}
private String formatTime(long timeMilliseconds) {
return PamCalendar.formatTodaysTime(timeMilliseconds, true);
}
}
}

View File

@ -1,47 +0,0 @@
package alfa.swinggui;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import PamView.panel.PamPanel;
import alfa.comms.MessageProcess;
import rockBlock.RockBlockControl;
import rockBlock.swing.RockBlockMessageInTable;
import rockBlock.swing.RockBlockMessageOutTable;
public class SwingMessagePanel {
private MessageProcess messageProcess;
private RockBlockMessageOutTable rockBlockMessageTable;
private RockBlockMessageInTable messageInTable;
private PamPanel mainPanel;
public static final int SHOW_OUTGOING = 0x1;
public static final int SHOW_INCOMING = 0x2;
public static final int SHOW_BOTH = 0x3;
public SwingMessagePanel(MessageProcess messageProcess, int showWhat) {
this.messageProcess = messageProcess;
mainPanel = new PamPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
RockBlockControl rockBlockControl = messageProcess.findRockBlock();
if (rockBlockControl != null) {
rockBlockMessageTable = new RockBlockMessageOutTable(rockBlockControl);
if ((showWhat & SHOW_OUTGOING) != 0) {
mainPanel.add(rockBlockMessageTable.getComponent());
}
messageInTable = new RockBlockMessageInTable(rockBlockControl);
if ((showWhat & SHOW_INCOMING) != 0) {
mainPanel.add(messageInTable.getComponent());
}
}
}
public JComponent getComponent() {
return mainPanel;
}
}

View File

@ -1,82 +0,0 @@
package alfa.utils;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
/**
* Functions to launch Microsoft Screen mirror service.
* We've been unable to work out a way of calling these functions
* directly so have instead implemented a system of key strokes.
* <p>May end up being very fragile !
* @author MER Torp
*
*/
public class MiraScreen {
// public static void main(String[] args) {
//
//// new Stage();
// new JFXPanel();
//
// ObservableList<Screen> screens = Screen.getScreens();
// for (Screen s:screens) {
// System.out.println(s);
// }
//
//
//
// startMirror();
//
// }
private static volatile boolean running = false;
public static boolean startMirror() {
if (running) {
return false;
}
Thread t = new Thread(new Runnable() {
@Override
public void run() {
startMirrorFunc();
}
});
t.start();
return true;
}
private static synchronized void startMirrorFunc() {
Robot robot;
running = true;
try {
robot = new Robot();
robot.keyPress(KeyEvent.VK_WINDOWS);
robot.keyPress(KeyEvent.VK_K);
robot.keyRelease(KeyEvent.VK_WINDOWS);
robot.keyRelease(KeyEvent.VK_K);
pause(5000);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
} catch (AWTException e) {
e.printStackTrace();
}
running = false;
}
private static void pause(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

View File

@ -8,6 +8,7 @@ public class BeamFormerLocalisation extends AbstractLocalisation implements Clon
double[] angles = new double[1];
double[] angleErrors = new double[1];
public BeamFormerLocalisation(PamDataUnit pamDataUnit, int locContents, int referenceHydrophones, double[] angles, double angleError) {
super(pamDataUnit, locContents, referenceHydrophones);
this.angles = angles;

View File

@ -23,6 +23,7 @@ public class OneBandAlarmCounter extends AlarmDecibelCounter implements PamSetti
this.oneBandControl = oneBandControl;
PamSettingManager.getInstance().registerSettings(this);
}
@Override
public double getValue(int countType, PamDataUnit dataUnit) {

View File

@ -1,11 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>ALFA Help Page</title>
</head>
<body>
<p>this is a page of help text</p>
</body>
</html>