Removed "koc" from package names

Former-commit-id: 93e426a87e8a82a83783d68cf7a814c88df375aa
This commit is contained in:
Ziver Koc 2016-01-11 17:48:02 +01:00
parent 1ab72ffbc3
commit 5b2dffeb43
56 changed files with 2289 additions and 2313 deletions

10
build.xml Normal file → Executable file
View file

@ -26,7 +26,7 @@
<target name="run-local-sensor" depends="">
<java fork="true" failonerror="true" classname="se.koc.hal.plugin.localsensor.ImpulseTracker">
<java fork="true" failonerror="true" classname="se.hal.plugin.localsensor.ImpulseTracker">
<classpath>
<pathelement path="${buildDir}/hal.jar"/> <!--wildcard may not be platform independent, ok?-->
<pathelement path="${libDir}/*"/> <!--wildcard may not be platform independent, ok?-->
@ -35,7 +35,7 @@
</target>
<target name="run-remote-sensor" depends="">
<java fork="true" failonerror="true" classname="se.koc.hal.plugin.tellstick.TelstickSerialCommTest">
<java fork="true" failonerror="true" classname="se.hal.plugin.tellstick.TelstickSerialCommTest">
<classpath>
<pathelement path="${buildDir}/hal.jar"/> <!--wildcard may not be platform independent, ok?-->
<pathelement path="${libDir}/*"/> <!--wildcard may not be platform independent, ok?-->
@ -44,7 +44,7 @@
</target>
<target name="run-main-server" depends="">
<java fork="true" failonerror="true" classname="se.koc.hal.PowerChallenge">
<java fork="true" failonerror="true" classname="se.hal.PowerChallenge">
<classpath>
<pathelement path="${buildDir}/hal.jar"/> <!--wildcard may not be platform independent, ok?-->
<pathelement path="${libDir}/*"/> <!--wildcard may not be platform independent, ok?-->
@ -70,12 +70,12 @@
<mkdir dir="${buildDir}" />
<javac srcdir="${srcDir}" destdir="${buildDir}" fork="yes">
<include name="**/*.java" />
<exclude name="se/koc/hal/tts/GoogleTTSClient.java" />
<exclude name="se/hal/tts/GoogleTTSClient.java" />
<classpath refid="classpath.build" />
</javac>
<javac srcdir="${testDir}" destdir="${buildDir}" fork="yes">
<include name="**/*.java" />
<exclude name="se/koc/hal/test/JarvisSyntersizerTest.java" />
<exclude name="se/hal/test/JarvisSyntersizerTest.java" />
<classpath refid="classpath.build" />
</javac>
<jar destfile="${buildDir}/hal.jar" basedir="${buildDir}" excludes="hal.jar" />

2
run.sh
View file

@ -1,6 +1,6 @@
#!/bin/bash
#screen -S hal -L -d -m \
# java -cp sqlite-jdbc-3.7.2.jar:jSerialComm-1.3.4.jar:hal.jar:. se.koc.hal.plugin.tellstick.TelstickSerialCommTest
# java -cp sqlite-jdbc-3.7.2.jar:jSerialComm-1.3.4.jar:hal.jar:. se.hal.plugin.tellstick.TelstickSerialCommTest
#ant clean
ant build

View file

@ -1,9 +1,8 @@
package se.koc.hal;
package se.hal;
import se.koc.hal.intf.*;
import se.koc.hal.plugin.tellstick.protocols.Oregon0x1A2D;
import se.koc.hal.struct.Event;
import se.koc.hal.struct.Sensor;
import se.hal.intf.*;
import se.hal.struct.Event;
import se.hal.struct.Sensor;
import zutil.db.DBConnection;
import zutil.log.LogUtil;
import zutil.plugin.PluginData;

View file

@ -1,12 +1,12 @@
package se.koc.hal;
package se.hal;
import se.koc.hal.bot.AliceBot;
import se.koc.hal.intf.HalBot;
import se.koc.hal.intf.HalSpeachToText;
import se.koc.hal.intf.HalTextToSpeach;
import se.koc.hal.struct.SwitchEvent;
import se.koc.hal.stt.ManualSTTClient;
import se.koc.hal.tts.MaryRemoteTTSClient;
import se.hal.bot.AliceBot;
import se.hal.intf.HalBot;
import se.hal.intf.HalSpeachToText;
import se.hal.intf.HalTextToSpeach;
import se.hal.struct.SwitchEvent;
import se.hal.stt.ManualSTTClient;
import se.hal.tts.MaryRemoteTTSClient;
import java.util.HashMap;
import java.util.regex.Matcher;

View file

@ -1,4 +1,4 @@
package se.koc.hal;
package se.hal;
import zutil.db.DBConnection;
import zutil.db.DBUpgradeHandler;

View file

@ -1,17 +1,17 @@
package se.koc.hal;
package se.hal;
import se.koc.hal.deamon.DataAggregatorDaemon;
import se.koc.hal.deamon.DataCleanupDaemon;
import se.koc.hal.deamon.DataSynchronizationClient;
import se.koc.hal.deamon.DataSynchronizationDaemon;
import se.koc.hal.intf.HalDaemon;
import se.koc.hal.intf.HalHttpPage;
import se.koc.hal.page.PCConfigureHttpPage;
import se.koc.hal.page.PCHeatMapHttpPage;
import se.koc.hal.page.PCOverviewHttpPage;
import se.koc.hal.struct.Event;
import se.koc.hal.struct.Sensor;
import se.hal.deamon.DataAggregatorDaemon;
import se.hal.deamon.DataCleanupDaemon;
import se.hal.deamon.DataSynchronizationClient;
import se.hal.deamon.DataSynchronizationDaemon;
import se.hal.intf.HalDaemon;
import se.hal.intf.HalHttpPage;
import se.hal.page.PCConfigureHttpPage;
import se.hal.page.PCHeatMapHttpPage;
import se.hal.page.PCOverviewHttpPage;
import se.hal.struct.Event;
import se.hal.struct.Sensor;
import zutil.db.DBConnection;
import zutil.io.file.FileUtil;
import zutil.log.CompactLogFormatter;
@ -35,8 +35,8 @@ public class PowerChallenge {
public static void main(String[] args) throws Exception {
// init logging
CompactLogFormatter formatter = new CompactLogFormatter();
LogUtil.setLevel("se.koc.hal", Level.FINEST);
LogUtil.setFormatter("se.koc.hal", formatter);
LogUtil.setLevel("se.hal", Level.FINEST);
LogUtil.setFormatter("se.hal", formatter);
LogUtil.setLevel("zutil", Level.FINEST);
LogUtil.setFormatter("zutil", formatter);
LogUtil.setGlobalFormatter(formatter);

View file

@ -1,58 +1,58 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.hal.bot;
import org.alicebot.ab.Bot;
import org.alicebot.ab.Chat;
import org.alicebot.ab.MagicBooleans;
import se.koc.hal.intf.HalBot;
import zutil.io.file.FileUtil;
import java.io.File;
/**
* Created by Ziver on 2015-05-07.
*/
public class AliceBot implements HalBot{
private Chat chatSession;
@Override
public void initialize() {
MagicBooleans.trace_mode = false;
File path = FileUtil.find("resource");
if(path == null || !path.exists()){
System.err.println("Bot folder does not exist");
System.exit(1);
}
Bot bot = new Bot(
"super",
path.getAbsolutePath());
chatSession = new Chat(bot);
}
@Override
public String respond(String question) {
return chatSession.multisentenceRespond(question);
}
}
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.bot;
import org.alicebot.ab.Bot;
import org.alicebot.ab.Chat;
import org.alicebot.ab.MagicBooleans;
import se.hal.intf.HalBot;
import zutil.io.file.FileUtil;
import java.io.File;
/**
* Created by Ziver on 2015-05-07.
*/
public class AliceBot implements HalBot{
private Chat chatSession;
@Override
public void initialize() {
MagicBooleans.trace_mode = false;
File path = FileUtil.find("resource");
if(path == null || !path.exists()){
System.err.println("Bot folder does not exist");
System.exit(1);
}
Bot bot = new Bot(
"super",
path.getAbsolutePath());
chatSession = new Chat(bot);
}
@Override
public String respond(String question) {
return chatSession.multisentenceRespond(question);
}
}

View file

@ -1,11 +1,11 @@
package se.koc.hal.deamon;
package se.hal.deamon;
import se.koc.hal.HalContext;
import se.koc.hal.intf.HalDaemon;
import se.koc.hal.struct.Sensor;
import se.koc.hal.intf.HalSensor.AggregationMethod;
import se.koc.hal.struct.PowerConsumptionSensor;
import se.koc.hal.util.TimeUtility;
import se.hal.HalContext;
import se.hal.intf.HalDaemon;
import se.hal.struct.Sensor;
import se.hal.intf.HalSensor.AggregationMethod;
import se.hal.struct.PowerConsumptionSensor;
import se.hal.util.TimeUtility;
import zutil.db.DBConnection;
import zutil.db.SQLResultHandler;
import zutil.db.handler.SimpleSQLResult;

View file

@ -1,10 +1,10 @@
package se.koc.hal.deamon;
package se.hal.deamon;
import se.koc.hal.HalContext;
import se.koc.hal.intf.HalDaemon;
import se.koc.hal.struct.Sensor;
import se.koc.hal.struct.PowerConsumptionSensor;
import se.koc.hal.util.TimeUtility;
import se.hal.HalContext;
import se.hal.intf.HalDaemon;
import se.hal.struct.Sensor;
import se.hal.struct.PowerConsumptionSensor;
import se.hal.util.TimeUtility;
import zutil.db.DBConnection;
import zutil.db.SQLResultHandler;
import zutil.db.handler.SimpleSQLResult;

View file

@ -1,134 +1,134 @@
package se.koc.hal.deamon;
import se.koc.hal.HalContext;
import se.koc.hal.deamon.DataSynchronizationDaemon.*;
import se.koc.hal.intf.HalDaemon;
import se.koc.hal.struct.Sensor;
import se.koc.hal.struct.User;
import zutil.db.DBConnection;
import zutil.log.LogUtil;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ConnectException;
import java.net.NoRouteToHostException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DataSynchronizationClient implements HalDaemon {
private static final Logger logger = LogUtil.getLogger();
private static final long SYNC_INTERVAL = 5 * 60 * 1000; // 5 min
@Override
public void initiate(ScheduledExecutorService executor){
executor.scheduleAtFixedRate(this, 10000, SYNC_INTERVAL, TimeUnit.MILLISECONDS);
}
@Override
public void run() {
try {
DBConnection db = HalContext.getDB();
List<User> users = User.getExternalUsers(db);
for(User user : users){
if(user.getHostname() == null){
logger.fine("Hostname not defined for user: "+ user.getUserName());
continue;
}
logger.fine("Synchronizing user: "+ user.getUserName() +" ("+user.getHostname()+":"+user.getPort()+")");
try (Socket s = new Socket(user.getHostname(), user.getPort());){
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
// Request peer data
out.writeObject(new PeerDataReqDTO());
PeerDataRspDTO peerData = (PeerDataRspDTO) in.readObject();
user.setUserName(peerData.username);
user.setAddress(peerData.address);
user.save(db);
for(SensorDTO sensorDTO : peerData.sensors){
Sensor sensor = Sensor.getExternalSensor(db, sensorDTO.sensorId);
if(sensor != null) { // new sensor
sensor = new Sensor();
logger.fine("Created new external sensor with external_id: "+ sensorDTO.sensorId);
}
else
logger.fine("Updating external sensor with external_id: "+ sensorDTO.sensorId);
sensor.setExternalId(sensorDTO.sensorId);
sensor.setName(sensorDTO.name);
sensor.setType(sensorDTO.type);
sensor.setConfig(sensorDTO.config);
sensor.save(db);
}
// Request sensor data
List<Sensor> sensors = Sensor.getSensors(db, user);
for(Sensor sensor : sensors){
if(sensor.isSynced()) {
SensorDataReqDTO req = new SensorDataReqDTO();
req.sensorId = sensor.getExternalId();
req.offsetSequenceId = Sensor.getHighestSequenceId(sensor.getId());
out.writeObject(req);
SensorDataListDTO dataList = (SensorDataListDTO) in.readObject();
for (SensorDataDTO data : dataList) {
PreparedStatement stmt = db.getPreparedStatement("INSERT INTO sensor_data_aggr(sensor_id, sequence_id, timestamp_start, timestamp_end, data, confidence) VALUES(?, ?, ?, ?, ?, ?)");
stmt.setLong(1, sensor.getId());
stmt.setLong(2, data.sequenceId);
stmt.setLong(3, data.timestampStart);
stmt.setLong(4, data.timestampEnd);
stmt.setInt(5, data.data);
stmt.setFloat(6, data.confidence);
DBConnection.exec(stmt);
}
logger.fine("Stored " + dataList.size() + " entries for sensor " + sensor.getId() + " from " + user.getUserName());
}
else
logger.fine("Skipped sensor " + sensor.getId());
}
out.writeObject(null); // Tell server we are disconnecting
out.close();
in.close();
s.close();
} catch (NoRouteToHostException |UnknownHostException|ConnectException e) {
logger.warning("Unable to connect to "+ user.getHostname()+":"+user.getPort() +", "+ e.getMessage());
} catch (ClassNotFoundException|IOException e) {
logger.log(Level.SEVERE, null, e);
}
}
} catch (SQLException e) {
logger.log(Level.SEVERE, null, e);
}
}
/////////////// DTO ///////////////////////
/**
* Request Peer information and available sensors
*/
protected static class PeerDataReqDTO implements Serializable{}
/**
* Request aggregate data for a specific sensor and offset
*/
protected static class SensorDataReqDTO implements Serializable{
private static final long serialVersionUID = -9066734025245139989L;
public long sensorId;
public long offsetSequenceId; // highest known sequence id
}
}
package se.hal.deamon;
import se.hal.HalContext;
import se.hal.deamon.DataSynchronizationDaemon.*;
import se.hal.intf.HalDaemon;
import se.hal.struct.Sensor;
import se.hal.struct.User;
import zutil.db.DBConnection;
import zutil.log.LogUtil;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ConnectException;
import java.net.NoRouteToHostException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DataSynchronizationClient implements HalDaemon {
private static final Logger logger = LogUtil.getLogger();
private static final long SYNC_INTERVAL = 5 * 60 * 1000; // 5 min
@Override
public void initiate(ScheduledExecutorService executor){
executor.scheduleAtFixedRate(this, 10000, SYNC_INTERVAL, TimeUnit.MILLISECONDS);
}
@Override
public void run() {
try {
DBConnection db = HalContext.getDB();
List<User> users = User.getExternalUsers(db);
for(User user : users){
if(user.getHostname() == null){
logger.fine("Hostname not defined for user: "+ user.getUserName());
continue;
}
logger.fine("Synchronizing user: "+ user.getUserName() +" ("+user.getHostname()+":"+user.getPort()+")");
try (Socket s = new Socket(user.getHostname(), user.getPort());){
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
// Request peer data
out.writeObject(new PeerDataReqDTO());
PeerDataRspDTO peerData = (PeerDataRspDTO) in.readObject();
user.setUserName(peerData.username);
user.setAddress(peerData.address);
user.save(db);
for(SensorDTO sensorDTO : peerData.sensors){
Sensor sensor = Sensor.getExternalSensor(db, sensorDTO.sensorId);
if(sensor != null) { // new sensor
sensor = new Sensor();
logger.fine("Created new external sensor with external_id: "+ sensorDTO.sensorId);
}
else
logger.fine("Updating external sensor with external_id: "+ sensorDTO.sensorId);
sensor.setExternalId(sensorDTO.sensorId);
sensor.setName(sensorDTO.name);
sensor.setType(sensorDTO.type);
sensor.setConfig(sensorDTO.config);
sensor.save(db);
}
// Request sensor data
List<Sensor> sensors = Sensor.getSensors(db, user);
for(Sensor sensor : sensors){
if(sensor.isSynced()) {
SensorDataReqDTO req = new SensorDataReqDTO();
req.sensorId = sensor.getExternalId();
req.offsetSequenceId = Sensor.getHighestSequenceId(sensor.getId());
out.writeObject(req);
SensorDataListDTO dataList = (SensorDataListDTO) in.readObject();
for (SensorDataDTO data : dataList) {
PreparedStatement stmt = db.getPreparedStatement("INSERT INTO sensor_data_aggr(sensor_id, sequence_id, timestamp_start, timestamp_end, data, confidence) VALUES(?, ?, ?, ?, ?, ?)");
stmt.setLong(1, sensor.getId());
stmt.setLong(2, data.sequenceId);
stmt.setLong(3, data.timestampStart);
stmt.setLong(4, data.timestampEnd);
stmt.setInt(5, data.data);
stmt.setFloat(6, data.confidence);
DBConnection.exec(stmt);
}
logger.fine("Stored " + dataList.size() + " entries for sensor " + sensor.getId() + " from " + user.getUserName());
}
else
logger.fine("Skipped sensor " + sensor.getId());
}
out.writeObject(null); // Tell server we are disconnecting
out.close();
in.close();
s.close();
} catch (NoRouteToHostException |UnknownHostException|ConnectException e) {
logger.warning("Unable to connect to "+ user.getHostname()+":"+user.getPort() +", "+ e.getMessage());
} catch (ClassNotFoundException|IOException e) {
logger.log(Level.SEVERE, null, e);
}
}
} catch (SQLException e) {
logger.log(Level.SEVERE, null, e);
}
}
/////////////// DTO ///////////////////////
/**
* Request Peer information and available sensors
*/
protected static class PeerDataReqDTO implements Serializable{}
/**
* Request aggregate data for a specific sensor and offset
*/
protected static class SensorDataReqDTO implements Serializable{
private static final long serialVersionUID = -9066734025245139989L;
public long sensorId;
public long offsetSequenceId; // highest known sequence id
}
}

View file

@ -1,167 +1,166 @@
package se.koc.hal.deamon;
import se.koc.hal.HalContext;
import se.koc.hal.deamon.DataSynchronizationClient.*;
import se.koc.hal.intf.HalDaemon;
import se.koc.hal.struct.Sensor;
import se.koc.hal.struct.User;
import zutil.db.DBConnection;
import zutil.db.SQLResultHandler;
import zutil.log.LogUtil;
import zutil.net.threaded.ThreadedTCPNetworkServer;
import zutil.net.threaded.ThreadedTCPNetworkServerThread;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DataSynchronizationDaemon extends ThreadedTCPNetworkServer implements HalDaemon {
private static final Logger logger = LogUtil.getLogger();
public DataSynchronizationDaemon() {
super(HalContext.getIntegerProperty("sync_port"));
}
@Override
public void initiate(ScheduledExecutorService executor){
this.start();
}
@Override
protected ThreadedTCPNetworkServerThread getThreadInstance(Socket s) {
try {
return new DataSynchronizationDaemonThread(s);
} catch (IOException e) {
logger.log(Level.SEVERE, "Unable to create DataSynchronizationDaemonThread", e);
}
return null;
}
private class DataSynchronizationDaemonThread implements ThreadedTCPNetworkServerThread{
private Socket s;
private ObjectOutputStream out;
private ObjectInputStream in;
public DataSynchronizationDaemonThread(Socket s) throws IOException{
this.s = s;
this.out = new ObjectOutputStream(s.getOutputStream());
this.in = new ObjectInputStream(s.getInputStream());
}
public void run(){
logger.fine("User connected: "+ s.getInetAddress().getHostName());
DBConnection db = HalContext.getDB();
try {
Object obj = null;
while((obj = in.readObject()) != null){
if(obj instanceof PeerDataReqDTO){
logger.fine("Client requesting peer data");
PeerDataRspDTO rsp = new PeerDataRspDTO();
User localUser = User.getLocalUser(db);
rsp.username = localUser.getUserName();
rsp.address = localUser.getAddress();
rsp.sensors = new ArrayList<>();
for(Sensor sensor : Sensor.getLocalSensors(db)){
if(sensor.isSynced()) {
SensorDTO dto = new SensorDTO();
dto.sensorId = sensor.getId();
dto.name = sensor.getName();
dto.type = sensor.getType();
dto.config = sensor.getConfig();
rsp.sensors.add(dto);
}
}
out.writeObject(rsp);
}
if(obj instanceof SensorDataReqDTO){
SensorDataReqDTO req = (SensorDataReqDTO) obj;
Sensor sensor = Sensor.getSensor(db, req.sensorId);
if(sensor.isSynced()) {
PreparedStatement stmt = db.getPreparedStatement("SELECT * FROM sensor_data_aggr WHERE sensor_id == ? AND sequence_id > ?");
stmt.setLong(1, sensor.getId());
stmt.setLong(2, req.offsetSequenceId);
logger.fine("Client requesting sensor data: sensorId: " + req.sensorId + ", offset: " + req.offsetSequenceId);
SensorDataListDTO rsp = DBConnection.exec(stmt, new SQLResultHandler<SensorDataListDTO>() {
@Override
public SensorDataListDTO handleQueryResult(Statement stmt, ResultSet result) throws SQLException {
SensorDataListDTO list = new SensorDataListDTO();
while (result.next()) {
SensorDataDTO data = new SensorDataDTO();
data.sequenceId = result.getLong("sensor_id");
data.timestampStart = result.getLong("timestamp_start");
data.timestampEnd = result.getLong("timestamp_end");
data.data = result.getInt("data");
data.confidence = result.getFloat("confidence");
list.add(data);
}
return list;
}
});
logger.fine("Sending " + rsp.size() + " sensor data items to client");
out.writeObject(rsp);
}
else{
logger.warning("Client requesting non synced sensor data: sensorId: " + req.sensorId + ", offset: " + req.offsetSequenceId);
SensorDataListDTO rsp = new SensorDataListDTO();
out.writeObject(rsp);
}
}
}
out.close();
in.close();
s.close();
} catch (ClassNotFoundException|IOException|SQLException e) {
logger.log(Level.SEVERE, null, e);
}
logger.fine("User disconnected: "+ s.getInetAddress().getHostName());
}
}
/////////////// DTO ///////////////////////
protected static class PeerDataRspDTO implements Serializable{
public String username;
public String address;
public ArrayList<SensorDTO> sensors;
}
protected static class SensorDTO implements Serializable{
public long sensorId;
public String name;
public String type;
public String config;
}
protected static class SensorDataListDTO extends ArrayList<SensorDataDTO> implements Serializable{
private static final long serialVersionUID = -5701618637734020691L;
}
protected static class SensorDataDTO implements Serializable{
private static final long serialVersionUID = 8494331502087736809L;
public long sequenceId;
public long timestampStart;
public long timestampEnd;
public int data;
public float confidence;
}
}
package se.hal.deamon;
import se.hal.HalContext;
import se.hal.deamon.DataSynchronizationClient.*;
import se.hal.intf.HalDaemon;
import se.hal.struct.Sensor;
import se.hal.struct.User;
import zutil.db.DBConnection;
import zutil.db.SQLResultHandler;
import zutil.log.LogUtil;
import zutil.net.threaded.ThreadedTCPNetworkServer;
import zutil.net.threaded.ThreadedTCPNetworkServerThread;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DataSynchronizationDaemon extends ThreadedTCPNetworkServer implements HalDaemon {
private static final Logger logger = LogUtil.getLogger();
public DataSynchronizationDaemon() {
super(HalContext.getIntegerProperty("sync_port"));
}
@Override
public void initiate(ScheduledExecutorService executor){
this.start();
}
@Override
protected ThreadedTCPNetworkServerThread getThreadInstance(Socket s) {
try {
return new DataSynchronizationDaemonThread(s);
} catch (IOException e) {
logger.log(Level.SEVERE, "Unable to create DataSynchronizationDaemonThread", e);
}
return null;
}
private class DataSynchronizationDaemonThread implements ThreadedTCPNetworkServerThread{
private Socket s;
private ObjectOutputStream out;
private ObjectInputStream in;
public DataSynchronizationDaemonThread(Socket s) throws IOException{
this.s = s;
this.out = new ObjectOutputStream(s.getOutputStream());
this.in = new ObjectInputStream(s.getInputStream());
}
public void run(){
logger.fine("User connected: "+ s.getInetAddress().getHostName());
DBConnection db = HalContext.getDB();
try {
Object obj = null;
while((obj = in.readObject()) != null){
if(obj instanceof PeerDataReqDTO){
logger.fine("Client requesting peer data");
PeerDataRspDTO rsp = new PeerDataRspDTO();
User localUser = User.getLocalUser(db);
rsp.username = localUser.getUserName();
rsp.address = localUser.getAddress();
rsp.sensors = new ArrayList<>();
for(Sensor sensor : Sensor.getLocalSensors(db)){
if(sensor.isSynced()) {
SensorDTO dto = new SensorDTO();
dto.sensorId = sensor.getId();
dto.name = sensor.getName();
dto.type = sensor.getType();
dto.config = sensor.getConfig();
rsp.sensors.add(dto);
}
}
out.writeObject(rsp);
}
if(obj instanceof SensorDataReqDTO){
SensorDataReqDTO req = (SensorDataReqDTO) obj;
Sensor sensor = Sensor.getSensor(db, req.sensorId);
if(sensor.isSynced()) {
PreparedStatement stmt = db.getPreparedStatement("SELECT * FROM sensor_data_aggr WHERE sensor_id == ? AND sequence_id > ?");
stmt.setLong(1, sensor.getId());
stmt.setLong(2, req.offsetSequenceId);
logger.fine("Client requesting sensor data: sensorId: " + req.sensorId + ", offset: " + req.offsetSequenceId);
SensorDataListDTO rsp = DBConnection.exec(stmt, new SQLResultHandler<SensorDataListDTO>() {
@Override
public SensorDataListDTO handleQueryResult(Statement stmt, ResultSet result) throws SQLException {
SensorDataListDTO list = new SensorDataListDTO();
while (result.next()) {
SensorDataDTO data = new SensorDataDTO();
data.sequenceId = result.getLong("sensor_id");
data.timestampStart = result.getLong("timestamp_start");
data.timestampEnd = result.getLong("timestamp_end");
data.data = result.getInt("data");
data.confidence = result.getFloat("confidence");
list.add(data);
}
return list;
}
});
logger.fine("Sending " + rsp.size() + " sensor data items to client");
out.writeObject(rsp);
}
else{
logger.warning("Client requesting non synced sensor data: sensorId: " + req.sensorId + ", offset: " + req.offsetSequenceId);
SensorDataListDTO rsp = new SensorDataListDTO();
out.writeObject(rsp);
}
}
}
out.close();
in.close();
s.close();
} catch (ClassNotFoundException|IOException|SQLException e) {
logger.log(Level.SEVERE, null, e);
}
logger.fine("User disconnected: "+ s.getInetAddress().getHostName());
}
}
/////////////// DTO ///////////////////////
protected static class PeerDataRspDTO implements Serializable{
public String username;
public String address;
public ArrayList<SensorDTO> sensors;
}
protected static class SensorDTO implements Serializable{
public long sensorId;
public String name;
public String type;
public String config;
}
protected static class SensorDataListDTO extends ArrayList<SensorDataDTO> implements Serializable{
private static final long serialVersionUID = -5701618637734020691L;
}
protected static class SensorDataDTO implements Serializable{
private static final long serialVersionUID = 8494331502087736809L;
public long sequenceId;
public long timestampStart;
public long timestampEnd;
public int data;
public float confidence;
}
}

View file

@ -1,33 +1,33 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.hal.intf;
/**
* Created by Ziver on 2015-05-07.
*/
public interface HalBot {
public void initialize();
public String respond(String question);
}
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.intf;
/**
* Created by Ziver on 2015-05-07.
*/
public interface HalBot {
public void initialize();
public String respond(String question);
}

View file

@ -1,4 +1,4 @@
package se.koc.hal.intf;
package se.hal.intf;
import java.util.concurrent.ScheduledExecutorService;

View file

@ -1,6 +1,4 @@
package se.koc.hal.intf;
import zutil.parser.DataNode;
package se.hal.intf;
/**
* Created by Ziver on 2015-12-23.

View file

@ -1,4 +1,4 @@
package se.koc.hal.intf;
package se.hal.intf;
/**
* Created by Ziver on 2015-12-15.

View file

@ -1,4 +1,4 @@
package se.koc.hal.intf;
package se.hal.intf;
public interface HalEventReportListener {

View file

@ -1,7 +1,7 @@
package se.koc.hal.intf;
package se.hal.intf;
import se.koc.hal.HalContext;
import se.koc.hal.struct.User;
import se.hal.HalContext;
import se.hal.struct.User;
import zutil.db.DBConnection;
import zutil.io.file.FileUtil;
import zutil.net.http.HttpHeaderParser;

View file

@ -1,6 +1,4 @@
package se.koc.hal.intf;
import zutil.parser.DataNode;
package se.hal.intf;
/**
* Created by Ziver on 2015-12-23.

View file

@ -1,4 +1,4 @@
package se.koc.hal.intf;
package se.hal.intf;
/**
* Created by Ziver on 2015-12-15.

View file

@ -1,4 +1,4 @@
package se.koc.hal.intf;
package se.hal.intf;
public interface HalSensorReportListener {

View file

@ -1,35 +1,35 @@
/*
* Copyright (c) 2013 ezivkoc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.hal.intf;
/**
* Created with IntelliJ IDEA.
* User: ezivkoc
* Date: 2013-12-17
* Time: 13:40
*/
public interface HalSpeachToText {
public void initSTT();
public String listen();
}
/*
* Copyright (c) 2013 ezivkoc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.intf;
/**
* Created with IntelliJ IDEA.
* User: ezivkoc
* Date: 2013-12-17
* Time: 13:40
*/
public interface HalSpeachToText {
public void initSTT();
public String listen();
}

View file

@ -1,35 +1,35 @@
/*
* Copyright (c) 2013 ezivkoc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.hal.intf;
/**
* Created with IntelliJ IDEA.
* User: ezivkoc
* Date: 2013-12-17
* Time: 13:40
*/
public interface HalTextToSpeach {
public void initTTS();
public void speak(String msg);
}
/*
* Copyright (c) 2013 ezivkoc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.intf;
/**
* Created with IntelliJ IDEA.
* User: ezivkoc
* Date: 2013-12-17
* Time: 13:40
*/
public interface HalTextToSpeach {
public void initTTS();
public void speak(String msg);
}

View file

@ -1,135 +1,135 @@
package se.koc.hal.page;
import se.koc.hal.ControllerManager;
import se.koc.hal.HalContext;
import se.koc.hal.intf.HalHttpPage;
import se.koc.hal.struct.Sensor;
import se.koc.hal.struct.User;
import zutil.db.DBConnection;
import zutil.io.file.FileUtil;
import zutil.parser.Templator;
import zutil.ui.Configurator;
import zutil.ui.Configurator.*;
import java.util.Map;
public class PCConfigureHttpPage extends HalHttpPage {
private class SensorDataParams{
public Class clazz;
public ConfigurationParam[] params;
}
private SensorDataParams[] sensorConfigurations;
public PCConfigureHttpPage() {
super("Configuration", "config");
sensorConfigurations = new SensorDataParams[
ControllerManager.getInstance().getAvailableSensors().size()];
int i=0;
for(Class c : ControllerManager.getInstance().getAvailableSensors()){
sensorConfigurations[i] = new SensorDataParams();
sensorConfigurations[i].clazz = c;
sensorConfigurations[i].params = Configurator.getConfiguration(c);
++i;
}
}
@Override
public Templator httpRespond(
Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request)
throws Exception{
DBConnection db = HalContext.getDB();
User localUser = User.getLocalUser(db);
// Save new input
if(request.containsKey("action")){
String action = request.get("action");
int id = (request.containsKey("id") ? Integer.parseInt(request.get("id")) : -1);
Sensor sensor;
User user;
switch(action) {
// Local User
case "modify_local_user":
localUser.setUserName(request.get("username"));
localUser.setAddress(request.get("address"));
localUser.save(db);
break;
// Local Sensors
case "create_local_sensor":
sensor = new Sensor();
sensor.setName(request.get("name"));
sensor.setType(request.get("type"));
sensor.setSynced(Boolean.parseBoolean(request.get("sync")));
//sensor.setConfig(request.get("config"));
sensor.setUser(localUser);
sensor.save(db);
case "modify_local_sensor":
sensor = Sensor.getSensor(db, id);
if(sensor != null){
sensor.setName(request.get("name"));
sensor.setType(request.get("type"));
sensor.setSynced(Boolean.parseBoolean(request.get("sync")));
//sensor.setConfig(request.get("config"));
sensor.save(db);
}
break;
case "remove_local_sensor":
sensor = Sensor.getSensor(db, id);
if(sensor != null)
sensor.delete(db);
break;
// External Users
case "create_external_user":
user = new User();
user.setHostname(request.get("hostname"));
user.setPort(Integer.parseInt(request.get("port")));
user.setExternal(true);
user.save(db);
break;
case "modify_external_user":
user = User.getUser(db, id);
if(user != null){
user.setHostname(request.get("hostname"));
user.setPort(Integer.parseInt(request.get("port")));
user.save(db);
}
break;
case "remove_external_user":
user = User.getUser(db, id);
if(user != null)
user.delete(db);
break;
// External Sensors
case "modify_external_sensor":
sensor = Sensor.getSensor(db, id);
if(sensor != null){
sensor.setSynced(Boolean.parseBoolean(request.get("sync")));
sensor.save(db);
}
break;
}
}
// Output
Templator tmpl = new Templator(FileUtil.find("web-resource/configure.tmpl"));
tmpl.set("user", localUser);
tmpl.set("localSensors", Sensor.getLocalSensors(db));
tmpl.set("localSensorConf", sensorConfigurations);
tmpl.set("detectedSensors", ControllerManager.getInstance().getDetectedSensors());
tmpl.set("extUsers", User.getExternalUsers(db));
tmpl.set("extSensor", Sensor.getExternalSensors(db));
tmpl.set("availableSensors", ControllerManager.getInstance().getAvailableSensors());
return tmpl;
}
}
package se.hal.page;
import se.hal.ControllerManager;
import se.hal.HalContext;
import se.hal.intf.HalHttpPage;
import se.hal.struct.Sensor;
import se.hal.struct.User;
import zutil.db.DBConnection;
import zutil.io.file.FileUtil;
import zutil.parser.Templator;
import zutil.ui.Configurator;
import zutil.ui.Configurator.*;
import java.util.Map;
public class PCConfigureHttpPage extends HalHttpPage {
private class SensorDataParams{
public Class clazz;
public ConfigurationParam[] params;
}
private SensorDataParams[] sensorConfigurations;
public PCConfigureHttpPage() {
super("Configuration", "config");
sensorConfigurations = new SensorDataParams[
ControllerManager.getInstance().getAvailableSensors().size()];
int i=0;
for(Class c : ControllerManager.getInstance().getAvailableSensors()){
sensorConfigurations[i] = new SensorDataParams();
sensorConfigurations[i].clazz = c;
sensorConfigurations[i].params = Configurator.getConfiguration(c);
++i;
}
}
@Override
public Templator httpRespond(
Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request)
throws Exception{
DBConnection db = HalContext.getDB();
User localUser = User.getLocalUser(db);
// Save new input
if(request.containsKey("action")){
String action = request.get("action");
int id = (request.containsKey("id") ? Integer.parseInt(request.get("id")) : -1);
Sensor sensor;
User user;
switch(action) {
// Local User
case "modify_local_user":
localUser.setUserName(request.get("username"));
localUser.setAddress(request.get("address"));
localUser.save(db);
break;
// Local Sensors
case "create_local_sensor":
sensor = new Sensor();
sensor.setName(request.get("name"));
sensor.setType(request.get("type"));
sensor.setSynced(Boolean.parseBoolean(request.get("sync")));
//sensor.setConfig(request.get("config"));
sensor.setUser(localUser);
sensor.save(db);
case "modify_local_sensor":
sensor = Sensor.getSensor(db, id);
if(sensor != null){
sensor.setName(request.get("name"));
sensor.setType(request.get("type"));
sensor.setSynced(Boolean.parseBoolean(request.get("sync")));
//sensor.setConfig(request.get("config"));
sensor.save(db);
}
break;
case "remove_local_sensor":
sensor = Sensor.getSensor(db, id);
if(sensor != null)
sensor.delete(db);
break;
// External Users
case "create_external_user":
user = new User();
user.setHostname(request.get("hostname"));
user.setPort(Integer.parseInt(request.get("port")));
user.setExternal(true);
user.save(db);
break;
case "modify_external_user":
user = User.getUser(db, id);
if(user != null){
user.setHostname(request.get("hostname"));
user.setPort(Integer.parseInt(request.get("port")));
user.save(db);
}
break;
case "remove_external_user":
user = User.getUser(db, id);
if(user != null)
user.delete(db);
break;
// External Sensors
case "modify_external_sensor":
sensor = Sensor.getSensor(db, id);
if(sensor != null){
sensor.setSynced(Boolean.parseBoolean(request.get("sync")));
sensor.save(db);
}
break;
}
}
// Output
Templator tmpl = new Templator(FileUtil.find("web-resource/configure.tmpl"));
tmpl.set("user", localUser);
tmpl.set("localSensors", Sensor.getLocalSensors(db));
tmpl.set("localSensorConf", sensorConfigurations);
tmpl.set("detectedSensors", ControllerManager.getInstance().getDetectedSensors());
tmpl.set("extUsers", User.getExternalUsers(db));
tmpl.set("extSensor", Sensor.getExternalSensors(db));
tmpl.set("availableSensors", ControllerManager.getInstance().getAvailableSensors());
return tmpl;
}
}

View file

@ -1,26 +1,26 @@
package se.koc.hal.page;
import se.koc.hal.intf.HalHttpPage;
import zutil.io.file.FileUtil;
import zutil.parser.Templator;
import java.util.Map;
public class PCHeatMapHttpPage extends HalHttpPage {
public PCHeatMapHttpPage() {
super("Heatmap", "map");
}
@Override
public Templator httpRespond(
Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request)
throws Exception{
Templator tmpl = new Templator(FileUtil.find("web-resource/heatmap.tmpl"));
return tmpl;
}
}
package se.hal.page;
import se.hal.intf.HalHttpPage;
import zutil.io.file.FileUtil;
import zutil.parser.Templator;
import java.util.Map;
public class PCHeatMapHttpPage extends HalHttpPage {
public PCHeatMapHttpPage() {
super("Heatmap", "map");
}
@Override
public Templator httpRespond(
Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request)
throws Exception{
Templator tmpl = new Templator(FileUtil.find("web-resource/heatmap.tmpl"));
return tmpl;
}
}

View file

@ -1,8 +1,8 @@
package se.koc.hal.page;
package se.hal.page;
import se.koc.hal.HalContext;
import se.koc.hal.intf.HalHttpPage;
import se.koc.hal.util.TimeUtility;
import se.hal.HalContext;
import se.hal.intf.HalHttpPage;
import se.hal.util.TimeUtility;
import zutil.db.DBConnection;
import zutil.db.SQLResultHandler;
import zutil.io.file.FileUtil;

View file

@ -1,4 +1,4 @@
package se.koc.hal.plugin.localsensor;
package se.hal.plugin.localsensor;
import com.pi4j.io.gpio.*;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;

View file

@ -1,100 +1,100 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.hal.plugin.tellstick;
import se.koc.hal.plugin.tellstick.protocols.NexaSelfLearning;
import se.koc.hal.plugin.tellstick.protocols.Oregon0x1A2D;
import zutil.converters.Converter;
import zutil.log.LogUtil;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by Ziver on 2015-02-18.
*/
public class TellstickParser {
private static final Logger logger = LogUtil.getLogger();
private static HashMap<String, Class<? extends TellstickProtocol>> protocolMap;
static {
registerProtocol(NexaSelfLearning.class);
registerProtocol(Oregon0x1A2D.class);
}
public TellstickProtocol decode(String data) {
if (data.startsWith("+W")) {
data = data.substring(2);
HashMap<String, String> map = new HashMap<String, String>();
String[] parameters = data.split(";");
for (String parameter : parameters) {
String[] keyValue = parameter.split(":");
map.put(keyValue[0], keyValue[1]);
}
Class<? extends TellstickProtocol> protClass =
getProtocolClass(map.get("protocol"), map.get("model"));
if (protClass != null) {
try {
TellstickProtocol protocol = protClass.newInstance();
String binData = map.get("data");
protocol.decode(Converter.hexToByte(binData));
logger.finest("Decoded: " + protocol);
return protocol;
} catch (Exception e) {
logger.log(Level.WARNING, null, e);
}
} else {
logger.warning("Unknown protocol: " + data);
}
} else if (data.startsWith("+S") || data.startsWith("+T")) {
// This is confirmation of send commands
}else {
logger.severe("Unknown prefix: " + data);
}
return null;
}
public static void registerProtocol(Class<? extends TellstickProtocol> protClass) {
try {
if (protocolMap == null)
protocolMap = new HashMap<String, Class<? extends TellstickProtocol>>();
TellstickProtocol tmp = protClass.newInstance();
protocolMap.put(
tmp.getProtocolName() + "-" + tmp.getModelName(),
protClass);
} catch (Exception e) {
logger.log(Level.SEVERE, null, e);
}
}
public static Class<? extends TellstickProtocol> getProtocolClass(String protocol, String model) {
return protocolMap.get(protocol + "-" + model);
}
}
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.plugin.tellstick;
import se.hal.plugin.tellstick.protocols.NexaSelfLearning;
import se.hal.plugin.tellstick.protocols.Oregon0x1A2D;
import zutil.converters.Converter;
import zutil.log.LogUtil;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by Ziver on 2015-02-18.
*/
public class TellstickParser {
private static final Logger logger = LogUtil.getLogger();
private static HashMap<String, Class<? extends TellstickProtocol>> protocolMap;
static {
registerProtocol(NexaSelfLearning.class);
registerProtocol(Oregon0x1A2D.class);
}
public TellstickProtocol decode(String data) {
if (data.startsWith("+W")) {
data = data.substring(2);
HashMap<String, String> map = new HashMap<String, String>();
String[] parameters = data.split(";");
for (String parameter : parameters) {
String[] keyValue = parameter.split(":");
map.put(keyValue[0], keyValue[1]);
}
Class<? extends TellstickProtocol> protClass =
getProtocolClass(map.get("protocol"), map.get("model"));
if (protClass != null) {
try {
TellstickProtocol protocol = protClass.newInstance();
String binData = map.get("data");
protocol.decode(Converter.hexToByte(binData));
logger.finest("Decoded: " + protocol);
return protocol;
} catch (Exception e) {
logger.log(Level.WARNING, null, e);
}
} else {
logger.warning("Unknown protocol: " + data);
}
} else if (data.startsWith("+S") || data.startsWith("+T")) {
// This is confirmation of send commands
}else {
logger.severe("Unknown prefix: " + data);
}
return null;
}
public static void registerProtocol(Class<? extends TellstickProtocol> protClass) {
try {
if (protocolMap == null)
protocolMap = new HashMap<String, Class<? extends TellstickProtocol>>();
TellstickProtocol tmp = protClass.newInstance();
protocolMap.put(
tmp.getProtocolName() + "-" + tmp.getModelName(),
protClass);
} catch (Exception e) {
logger.log(Level.SEVERE, null, e);
}
}
public static Class<? extends TellstickProtocol> getProtocolClass(String protocol, String model) {
return protocolMap.get(protocol + "-" + model);
}
}

View file

@ -1,68 +1,68 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.hal.plugin.tellstick;
import se.koc.hal.intf.HalEventController;
import se.koc.hal.intf.HalSensorController;
/**
* Created by Ziver on 2015-02-18.
*/
public abstract class TellstickProtocol {
private String protocol;
private String model;
private long timestamp = -1;
public TellstickProtocol(String protocol, String model){
this.protocol = protocol;
this.model = model;
}
public String getProtocolName(){
return protocol;
}
public String getModelName(){
return model;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public Class<? extends HalEventController> getEventController() {
return TellstickSerialComm.class;
}
public Class<? extends HalSensorController> getSensorController() {
return TellstickSerialComm.class;
}
public abstract String encode();
public abstract void decode(byte[] data);
}
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.plugin.tellstick;
import se.hal.intf.HalEventController;
import se.hal.intf.HalSensorController;
/**
* Created by Ziver on 2015-02-18.
*/
public abstract class TellstickProtocol {
private String protocol;
private String model;
private long timestamp = -1;
public TellstickProtocol(String protocol, String model){
this.protocol = protocol;
this.model = model;
}
public String getProtocolName(){
return protocol;
}
public String getModelName(){
return model;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public Class<? extends HalEventController> getEventController() {
return TellstickSerialComm.class;
}
public Class<? extends HalSensorController> getSensorController() {
return TellstickSerialComm.class;
}
public abstract String encode();
public abstract void decode(byte[] data);
}

View file

@ -1,209 +1,207 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.hal.plugin.tellstick;
import com.fazecast.jSerialComm.SerialPort;
import se.koc.hal.HalContext;
import se.koc.hal.intf.*;
import zutil.io.file.FileUtil;
import zutil.log.InputStreamLogger;
import zutil.log.LogUtil;
import zutil.log.OutputStreamLogger;
import zutil.struct.TimedHashSet;
import java.io.*;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This version of the TwoWaySerialComm example makes use of the
* SerialPortEventListener to avoid polling.
*/
public class TellstickSerialComm implements Runnable, HalSensorController, HalEventController {
private static final long TRANSMISSION_UNIQUENESS_TTL = 300; // milliseconds
private static final Logger logger = LogUtil.getLogger();
private SerialPort serial;
private InputStream in;
private OutputStream out;
private TimedHashSet set; // To check for retransmissions
private TellstickParser parser;
private HalSensorReportListener sensorListener;
private HalEventReportListener eventListener;
private int registeredObjects;
public TellstickSerialComm() {
set = new TimedHashSet(TRANSMISSION_UNIQUENESS_TTL);
parser = new TellstickParser();
registeredObjects = 0;
}
@Override
public void initialize() throws Exception {
// Read properties
String port = HalContext.getStringProperty("tellstick.com_port");
if (port == null)
port = "COM1"; // defaults
connect(port);
}
public void connect(String portName) throws Exception {
logger.info("Connecting to com port... ("+ portName +")");
serial = SerialPort.getCommPort(portName);
serial.setBaudRate(9600);
if(!serial.openPort())
throw new IOException("Could not open port: "+portName);
serial.setComPortTimeouts(
SerialPort.TIMEOUT_READ_BLOCKING, 0, 0);
in = new InputStreamLogger(serial.getInputStream());
out = new OutputStreamLogger(serial.getOutputStream());
Executors.newSingleThreadExecutor().execute(this);
}
public void close() {
if(serial != null) {
try {
serial.closePort();
in.close();
out.close();
} catch (IOException e) {
logger.log(Level.SEVERE, null, e);
}
}
serial = null;
in = null;
out = null;
}
public void run() {
try {
String data;
while (in != null && (data = readLine()) != null) {
if ((data.startsWith("+S") || data.startsWith("+T"))) {
synchronized (this) {
this.notifyAll();
}
}
else {
if(!set.contains(data)) {
TellstickProtocol protocol = parser.decode(data);
if(protocol != null) {
if (protocol.getTimestamp() < 0)
protocol.setTimestamp(System.currentTimeMillis());
set.add(data);
if (sensorListener != null && protocol instanceof HalSensor)
sensorListener.reportReceived((HalSensor) protocol);
else if (eventListener != null && protocol instanceof HalEvent)
eventListener.reportReceived((HalEvent) protocol);
}
}
}
}
} catch (IOException e) {
logger.log(Level.SEVERE, null, e);
}
}
/**
* There seems to be an issue with read(...) methods only read() is working
*/
private String readLine() throws IOException {
StringBuilder str = new StringBuilder(50);
char c = 0;
while((c = (char)in.read()) >= 0){
switch(c) {
case '\n':
case '\r':
if(str.length() > 0)
return str.toString();
break;
default:
str.append(c);
}
}
return str.toString();
}
@Override
public void send(HalEvent event) {
if(event instanceof TellstickProtocol)
write((TellstickProtocol) event);
}
public synchronized void write(TellstickProtocol prot) {
write(prot.encode());
try {
this.wait();
} catch (InterruptedException e) {
logger.log(Level.SEVERE, null, e);
}
}
public void write(String data) {
try {
for(int i=0; i<data.length();i++)
out.write(0xFF & data.charAt(i));
out.write('\n');
out.flush();
} catch (IOException e) {
logger.log(Level.SEVERE, null, e);
}
}
@Override
public void register(HalEvent event) {++registeredObjects;}
@Override
public void register(HalSensor sensor) {++registeredObjects;}
@Override
public void deregister(HalSensor sensor) {--registeredObjects;}
@Override
public void deregister(HalEvent event) {--registeredObjects;}
@Override
public int size() {
return registeredObjects;
}
@Override
public void setListener(HalEventReportListener listener) {
eventListener = listener;
}
@Override
public void setListener(HalSensorReportListener listener) {
sensorListener = listener;
}
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.plugin.tellstick;
import com.fazecast.jSerialComm.SerialPort;
import se.hal.HalContext;
import se.hal.intf.*;
import zutil.log.InputStreamLogger;
import zutil.log.LogUtil;
import zutil.log.OutputStreamLogger;
import zutil.struct.TimedHashSet;
import java.io.*;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This version of the TwoWaySerialComm example makes use of the
* SerialPortEventListener to avoid polling.
*/
public class TellstickSerialComm implements Runnable, HalSensorController, HalEventController {
private static final long TRANSMISSION_UNIQUENESS_TTL = 300; // milliseconds
private static final Logger logger = LogUtil.getLogger();
private SerialPort serial;
private InputStream in;
private OutputStream out;
private TimedHashSet set; // To check for retransmissions
private TellstickParser parser;
private HalSensorReportListener sensorListener;
private HalEventReportListener eventListener;
private int registeredObjects;
public TellstickSerialComm() {
set = new TimedHashSet(TRANSMISSION_UNIQUENESS_TTL);
parser = new TellstickParser();
registeredObjects = 0;
}
@Override
public void initialize() throws Exception {
// Read properties
String port = HalContext.getStringProperty("tellstick.com_port");
if (port == null)
port = "COM1"; // defaults
connect(port);
}
public void connect(String portName) throws Exception {
logger.info("Connecting to com port... ("+ portName +")");
serial = SerialPort.getCommPort(portName);
serial.setBaudRate(9600);
if(!serial.openPort())
throw new IOException("Could not open port: "+portName);
serial.setComPortTimeouts(
SerialPort.TIMEOUT_READ_BLOCKING, 0, 0);
in = new InputStreamLogger(serial.getInputStream());
out = new OutputStreamLogger(serial.getOutputStream());
Executors.newSingleThreadExecutor().execute(this);
}
public void close() {
if(serial != null) {
try {
serial.closePort();
in.close();
out.close();
} catch (IOException e) {
logger.log(Level.SEVERE, null, e);
}
}
serial = null;
in = null;
out = null;
}
public void run() {
try {
String data;
while (in != null && (data = readLine()) != null) {
if ((data.startsWith("+S") || data.startsWith("+T"))) {
synchronized (this) {
this.notifyAll();
}
}
else {
if(!set.contains(data)) {
TellstickProtocol protocol = parser.decode(data);
if(protocol != null) {
if (protocol.getTimestamp() < 0)
protocol.setTimestamp(System.currentTimeMillis());
set.add(data);
if (sensorListener != null && protocol instanceof HalSensor)
sensorListener.reportReceived((HalSensor) protocol);
else if (eventListener != null && protocol instanceof HalEvent)
eventListener.reportReceived((HalEvent) protocol);
}
}
}
}
} catch (IOException e) {
logger.log(Level.SEVERE, null, e);
}
}
/**
* There seems to be an issue with read(...) methods only read() is working
*/
private String readLine() throws IOException {
StringBuilder str = new StringBuilder(50);
char c = 0;
while((c = (char)in.read()) >= 0){
switch(c) {
case '\n':
case '\r':
if(str.length() > 0)
return str.toString();
break;
default:
str.append(c);
}
}
return str.toString();
}
@Override
public void send(HalEvent event) {
if(event instanceof TellstickProtocol)
write((TellstickProtocol) event);
}
public synchronized void write(TellstickProtocol prot) {
write(prot.encode());
try {
this.wait();
} catch (InterruptedException e) {
logger.log(Level.SEVERE, null, e);
}
}
public void write(String data) {
try {
for(int i=0; i<data.length();i++)
out.write(0xFF & data.charAt(i));
out.write('\n');
out.flush();
} catch (IOException e) {
logger.log(Level.SEVERE, null, e);
}
}
@Override
public void register(HalEvent event) {++registeredObjects;}
@Override
public void register(HalSensor sensor) {++registeredObjects;}
@Override
public void deregister(HalSensor sensor) {--registeredObjects;}
@Override
public void deregister(HalEvent event) {--registeredObjects;}
@Override
public int size() {
return registeredObjects;
}
@Override
public void setListener(HalEventReportListener listener) {
eventListener = listener;
}
@Override
public void setListener(HalSensorReportListener listener) {
sensorListener = listener;
}
}

View file

@ -1,177 +1,175 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.hal.plugin.tellstick.protocols;
import se.koc.hal.intf.HalEventController;
import se.koc.hal.plugin.tellstick.TellstickProtocol;
import se.koc.hal.struct.DimmerEvent;
import se.koc.hal.struct.SwitchEvent;
import zutil.ui.Configurator;
/**
* Created by Ziver on 2015-02-18.
*/
public class NexaSelfLearning extends TellstickProtocol implements SwitchEvent {
@Configurator.Configurable("House code")
private int house = 0;
@Configurator.Configurable("Group code")
private int group = 0;
@Configurator.Configurable("Unit code")
private int unit = 0;
private boolean enable = false;
public NexaSelfLearning() {
super("arctech", "selflearning");
}
public String encode(){
StringBuilder enc = new StringBuilder();
enc.append(new char[]{'T', 127, 255, 24, 1});
enc.append((char)132);
// House
StringBuilder m = new StringBuilder();
for (int i = 25; i >= 0; --i) {
m.append( (house & (1 << i)) == 0 ? "01" : "10" );
}
// Group
m.append("01");
// On or OFF
if (enable)
m.append("10");
else
m.append("01");
// Unit
for (int i = 3; i >= 0; --i) {
m.append( (unit & (1 << i)) == 0 ? "01" : "10" );
}
// The number of data is odd add this to make it even
m.append("0");
//01011001101001011010100110010101010101101001011010 01 01 1001011010 0
char code = 9; // b1001, startcode
for (int i = 0; i < m.length(); ++i) {
code <<= 4;
if (m.charAt(i) == '1') {
code |= 0x08; // b1000
} else {
code |= 0x0A; // b1010
}
if (i % 2 == 0) {
enc.append(code);
code = 0x00;
}
}
enc.append("+");
return enc.toString();
}
public void decode(byte[] data){
// Data positions
// house = 0xFFFFFFC0
// group = 0x00000020
// method = 0x00000010
// unit = 0x0000000F
// ----------------h------------ g m --u-
// 0x2CE81990 - 00101100_11101000_00011001_10 0 1 0000 - ON
// 0x2CE81980 - 00101100_11101000_00011001_10 0 0 0000 - OFF
house = 0;
house |= (data[3] & 0xFF) << 18;
house |= (data[2] & 0xFF) << 10;
house |= (data[1] & 0xFF) << 2;
house |= (data[0] & 0xC0) >>> 6;
group = data[0] & 0x20;
group >>>= 5;
enable = (data[0] & 0x10) != 0;
unit = data[0] & 0x0F;
unit++;
}
public int getHouse() {
return house;
}
public void setHouse(int house) {
this.house = house;
}
public int getGroup() {
return group;
}
public void setGroup(int group) {
this.group = group;
}
public int getUnit() {
return unit;
}
public void setUnit(int unit) {
this.unit = unit;
}
public boolean isOn() {
return enable;
}
public void turnOn() {
enable = true;
}
public void turnOff() {
enable = false;
}
public String toString(){
return "protocol:arctech;model:selflearning;" +
"house:"+house+
";group:"+group+
";unit:"+unit+
";method:"+enable;
}
public boolean equals(Object obj){
if(obj instanceof NexaSelfLearning)
return ((NexaSelfLearning) obj).house == house &&
((NexaSelfLearning)obj).unit == unit;
return false;
}
@Override
public double getData() {
return (enable ? 1 : 0);
}
}
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.plugin.tellstick.protocols;
import se.hal.plugin.tellstick.TellstickProtocol;
import se.hal.struct.SwitchEvent;
import zutil.ui.Configurator;
/**
* Created by Ziver on 2015-02-18.
*/
public class NexaSelfLearning extends TellstickProtocol implements SwitchEvent {
@Configurator.Configurable("House code")
private int house = 0;
@Configurator.Configurable("Group code")
private int group = 0;
@Configurator.Configurable("Unit code")
private int unit = 0;
private boolean enable = false;
public NexaSelfLearning() {
super("arctech", "selflearning");
}
public String encode(){
StringBuilder enc = new StringBuilder();
enc.append(new char[]{'T', 127, 255, 24, 1});
enc.append((char)132);
// House
StringBuilder m = new StringBuilder();
for (int i = 25; i >= 0; --i) {
m.append( (house & (1 << i)) == 0 ? "01" : "10" );
}
// Group
m.append("01");
// On or OFF
if (enable)
m.append("10");
else
m.append("01");
// Unit
for (int i = 3; i >= 0; --i) {
m.append( (unit & (1 << i)) == 0 ? "01" : "10" );
}
// The number of data is odd add this to make it even
m.append("0");
//01011001101001011010100110010101010101101001011010 01 01 1001011010 0
char code = 9; // b1001, startcode
for (int i = 0; i < m.length(); ++i) {
code <<= 4;
if (m.charAt(i) == '1') {
code |= 0x08; // b1000
} else {
code |= 0x0A; // b1010
}
if (i % 2 == 0) {
enc.append(code);
code = 0x00;
}
}
enc.append("+");
return enc.toString();
}
public void decode(byte[] data){
// Data positions
// house = 0xFFFFFFC0
// group = 0x00000020
// method = 0x00000010
// unit = 0x0000000F
// ----------------h------------ g m --u-
// 0x2CE81990 - 00101100_11101000_00011001_10 0 1 0000 - ON
// 0x2CE81980 - 00101100_11101000_00011001_10 0 0 0000 - OFF
house = 0;
house |= (data[3] & 0xFF) << 18;
house |= (data[2] & 0xFF) << 10;
house |= (data[1] & 0xFF) << 2;
house |= (data[0] & 0xC0) >>> 6;
group = data[0] & 0x20;
group >>>= 5;
enable = (data[0] & 0x10) != 0;
unit = data[0] & 0x0F;
unit++;
}
public int getHouse() {
return house;
}
public void setHouse(int house) {
this.house = house;
}
public int getGroup() {
return group;
}
public void setGroup(int group) {
this.group = group;
}
public int getUnit() {
return unit;
}
public void setUnit(int unit) {
this.unit = unit;
}
public boolean isOn() {
return enable;
}
public void turnOn() {
enable = true;
}
public void turnOff() {
enable = false;
}
public String toString(){
return "protocol:arctech;model:selflearning;" +
"house:"+house+
";group:"+group+
";unit:"+unit+
";method:"+enable;
}
public boolean equals(Object obj){
if(obj instanceof NexaSelfLearning)
return ((NexaSelfLearning) obj).house == house &&
((NexaSelfLearning)obj).unit == unit;
return false;
}
@Override
public double getData() {
return (enable ? 1 : 0);
}
}

View file

@ -1,11 +1,7 @@
package se.koc.hal.plugin.tellstick.protocols;
package se.hal.plugin.tellstick.protocols;
import se.koc.hal.intf.HalSensor;
import se.koc.hal.intf.HalSensorController;
import se.koc.hal.plugin.tellstick.TellstickProtocol;
import se.koc.hal.plugin.tellstick.TellstickSerialComm;
import se.koc.hal.struct.PowerConsumptionSensor;
import zutil.parser.DataNode;
import se.hal.plugin.tellstick.TellstickProtocol;
import se.hal.struct.PowerConsumptionSensor;
import zutil.ui.Configurator;
/**

View file

@ -20,9 +20,9 @@
* THE SOFTWARE.
*/
package se.koc.hal.struct;
package se.hal.struct;
import se.koc.hal.intf.HalEvent;
import se.hal.intf.HalEvent;
/**
* Created by Ziver on 2015-05-07.

View file

@ -1,7 +1,7 @@
package se.koc.hal.struct;
package se.hal.struct;
import se.koc.hal.intf.HalEvent;
import se.koc.hal.intf.HalEventController;
import se.hal.intf.HalEvent;
import se.hal.intf.HalEventController;
import zutil.db.DBConnection;
import zutil.db.bean.DBBean;
import zutil.db.bean.DBBeanSQLResultHandler;
@ -10,8 +10,6 @@ import zutil.io.StringOutputStream;
import zutil.log.LogUtil;
import zutil.parser.json.JSONObjectInputStream;
import zutil.parser.json.JSONObjectOutputStream;
import zutil.parser.json.JSONParser;
import zutil.parser.json.JSONWriter;
import java.io.IOException;
import java.sql.PreparedStatement;

View file

@ -1,6 +1,6 @@
package se.koc.hal.struct;
package se.hal.struct;
import se.koc.hal.intf.HalSensor;
import se.hal.intf.HalSensor;
/**
* Created by Ziver on 2015-12-03.

View file

@ -1,8 +1,8 @@
package se.koc.hal.struct;
package se.hal.struct;
import se.koc.hal.HalContext;
import se.koc.hal.intf.HalSensor;
import se.koc.hal.intf.HalSensorController;
import se.hal.HalContext;
import se.hal.intf.HalSensor;
import se.hal.intf.HalSensorController;
import zutil.db.DBConnection;
import zutil.db.bean.DBBean;
import zutil.db.bean.DBBeanSQLResultHandler;
@ -10,13 +10,8 @@ import zutil.db.handler.SimpleSQLResult;
import zutil.io.StringInputStream;
import zutil.io.StringOutputStream;
import zutil.log.LogUtil;
import zutil.parser.DataNode;
import zutil.parser.json.JSONObjectInputStream;
import zutil.parser.json.JSONObjectOutputStream;
import zutil.parser.json.JSONParser;
import zutil.parser.json.JSONWriter;
import zutil.ui.Configurator;
import zutil.ui.Configurator.ConfigurationParam;
import java.io.IOException;
import java.sql.PreparedStatement;

View file

@ -20,11 +20,9 @@
* THE SOFTWARE.
*/
package se.koc.hal.struct;
package se.hal.struct;
import se.koc.hal.intf.HalEvent;
import se.koc.hal.plugin.tellstick.TellstickSerialComm;
import se.koc.hal.plugin.tellstick.protocols.NexaSelfLearning;
import se.hal.intf.HalEvent;
/**
* Created by Ziver on 2015-05-07.

View file

@ -1,6 +1,6 @@
package se.koc.hal.struct;
package se.hal.struct;
import se.koc.hal.intf.HalSensor;
import se.hal.intf.HalSensor;
/**
* Created by Ziver on 2015-12-03.

View file

@ -1,4 +1,4 @@
package se.koc.hal.struct;
package se.hal.struct;
import zutil.db.DBConnection;
import zutil.db.bean.DBBean;

View file

@ -1,123 +1,123 @@
package se.koc.hal.stt;
import com.darkprograms.speech.microphone.MicrophoneAnalyzer;
import com.darkprograms.speech.recognizer.FlacEncoder;
import com.darkprograms.speech.recognizer.GSpeechDuplex;
import com.darkprograms.speech.recognizer.GSpeechResponseListener;
import com.darkprograms.speech.recognizer.GoogleResponse;
import se.koc.hal.intf.HalSpeachToText;
import zutil.io.file.FileUtil;
import javax.sound.sampled.AudioFileFormat;
import java.io.File;
public class GoogleSTTClient implements HalSpeachToText, GSpeechResponseListener {
private MicrophoneAnalyzer mic;
private File audioFile;
private File flacFile;
private int ambientVolume;
private GSpeechDuplex google;
private String response;
@Override
public void initSTT() {
try{
this.mic = new MicrophoneAnalyzer(AudioFileFormat.Type.WAVE);
this.audioFile = File.createTempFile("input", "wav");
this.flacFile = File.createTempFile("input", "flac");
this.google = new GSpeechDuplex("AIzaSyBGAQ29aMvts9MObj739_HYa-tvNeEI0X8");
this.google.addResponseListener(this);
/*System.out.println("Messuring ambient noise...");
mic.captureAudioToFile(audioFile);
Thread.sleep(300);
ambientVolume = mic.getAudioVolume();
Thread.sleep(300);
mic.close();*/
}catch(Exception e){
e.printStackTrace();
}
}
@Override
public synchronized String listen() {
try {
String request = null;
while(request == null){
/*mic.captureAudioToFile(audioFile);
try{Thread.sleep(2000);}catch(Exception e){}
mic.close();*/
FlacEncoder flacEncoder = new FlacEncoder();
//flacEncoder.convertWaveToFlac(audioFile, flacFile);
flacEncoder.convertWaveToFlac(FileUtil.find("edu/cmu/sphinx/demo/speakerid/test.wav"), flacFile);
response = null;
google.recognize(flacFile, 8000);
this.wait();
flacFile.delete();
audioFile.delete();
}
}catch(Exception e){
e.printStackTrace();
}
return response;
}
public String thresholdListen(){
try{
boolean speaking = false;
while(!speaking){
mic.captureAudioToFile(audioFile);
System.out.print("_");
final int THRESHOLD = 10; //YOUR THRESHOLD VALUE.
mic.open();
int speakingVolume = -2;
do{
int volume = mic.getAudioVolume();
if(volume>ambientVolume+THRESHOLD){
speakingVolume = volume;
speaking = true;
System.out.print(".");
Thread.sleep(1000);
}
if(speaking && volume+THRESHOLD<speakingVolume){
break;
}
Thread.sleep(100);
}while(speaking);
mic.close();
}
mic.close();
FlacEncoder flacEncoder = new FlacEncoder();
flacEncoder.convertWaveToFlac(audioFile, flacFile);
response = null;
google.recognize(flacFile, 8000);
this.wait();
flacFile.delete();
}catch(Exception e){
e.printStackTrace();
}
return response;
}
@Override
public void onResponse(GoogleResponse googleResponse) {
response = googleResponse.getResponse();
this.notifyAll();
}
}
package se.hal.stt;
import com.darkprograms.speech.microphone.MicrophoneAnalyzer;
import com.darkprograms.speech.recognizer.FlacEncoder;
import com.darkprograms.speech.recognizer.GSpeechDuplex;
import com.darkprograms.speech.recognizer.GSpeechResponseListener;
import com.darkprograms.speech.recognizer.GoogleResponse;
import se.hal.intf.HalSpeachToText;
import zutil.io.file.FileUtil;
import javax.sound.sampled.AudioFileFormat;
import java.io.File;
public class GoogleSTTClient implements HalSpeachToText, GSpeechResponseListener {
private MicrophoneAnalyzer mic;
private File audioFile;
private File flacFile;
private int ambientVolume;
private GSpeechDuplex google;
private String response;
@Override
public void initSTT() {
try{
this.mic = new MicrophoneAnalyzer(AudioFileFormat.Type.WAVE);
this.audioFile = File.createTempFile("input", "wav");
this.flacFile = File.createTempFile("input", "flac");
this.google = new GSpeechDuplex("AIzaSyBGAQ29aMvts9MObj739_HYa-tvNeEI0X8");
this.google.addResponseListener(this);
/*System.out.println("Messuring ambient noise...");
mic.captureAudioToFile(audioFile);
Thread.sleep(300);
ambientVolume = mic.getAudioVolume();
Thread.sleep(300);
mic.close();*/
}catch(Exception e){
e.printStackTrace();
}
}
@Override
public synchronized String listen() {
try {
String request = null;
while(request == null){
/*mic.captureAudioToFile(audioFile);
try{Thread.sleep(2000);}catch(Exception e){}
mic.close();*/
FlacEncoder flacEncoder = new FlacEncoder();
//flacEncoder.convertWaveToFlac(audioFile, flacFile);
flacEncoder.convertWaveToFlac(FileUtil.find("edu/cmu/sphinx/demo/speakerid/test.wav"), flacFile);
response = null;
google.recognize(flacFile, 8000);
this.wait();
flacFile.delete();
audioFile.delete();
}
}catch(Exception e){
e.printStackTrace();
}
return response;
}
public String thresholdListen(){
try{
boolean speaking = false;
while(!speaking){
mic.captureAudioToFile(audioFile);
System.out.print("_");
final int THRESHOLD = 10; //YOUR THRESHOLD VALUE.
mic.open();
int speakingVolume = -2;
do{
int volume = mic.getAudioVolume();
if(volume>ambientVolume+THRESHOLD){
speakingVolume = volume;
speaking = true;
System.out.print(".");
Thread.sleep(1000);
}
if(speaking && volume+THRESHOLD<speakingVolume){
break;
}
Thread.sleep(100);
}while(speaking);
mic.close();
}
mic.close();
FlacEncoder flacEncoder = new FlacEncoder();
flacEncoder.convertWaveToFlac(audioFile, flacFile);
response = null;
google.recognize(flacFile, 8000);
this.wait();
flacFile.delete();
}catch(Exception e){
e.printStackTrace();
}
return response;
}
@Override
public void onResponse(GoogleResponse googleResponse) {
response = googleResponse.getResponse();
this.notifyAll();
}
}

View file

@ -1,49 +1,49 @@
/*
* Copyright (c) 2015 ezivkoc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.hal.stt;
import se.koc.hal.intf.HalSpeachToText;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ManualSTTClient implements HalSpeachToText {
private BufferedReader in;
@Override
public void initSTT() {
// open up standard input
in = new BufferedReader(new InputStreamReader(System.in));
}
@Override
public String listen() {
try {
return in.readLine();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
}
/*
* Copyright (c) 2015 ezivkoc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.stt;
import se.hal.intf.HalSpeachToText;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ManualSTTClient implements HalSpeachToText {
private BufferedReader in;
@Override
public void initSTT() {
// open up standard input
in = new BufferedReader(new InputStreamReader(System.in));
}
@Override
public String listen() {
try {
return in.readLine();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
}

View file

@ -1,68 +1,68 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.hal.stt;
import edu.cmu.sphinx.api.Configuration;
import edu.cmu.sphinx.api.LiveSpeechRecognizer;
import edu.cmu.sphinx.api.SpeechResult;
import se.koc.hal.intf.HalSpeachToText;
import java.io.IOException;
/**
* Created by Ziver on 2015-05-08.
*/
public class Sphinx4STTClient implements HalSpeachToText {
private LiveSpeechRecognizer recognizer;
@Override
public void initSTT() {
Configuration configuration = new Configuration();
// Set path to acoustic model.
configuration.setAcousticModelPath("resource:/sphinx-models/en-us");
// Set path to dictionary.
configuration.setDictionaryPath("resource:/sphinx-models/cmudict-en-us.dict");
// Set language model.
configuration.setLanguageModelPath("resource:/sphinx-models/en-us.lm.dmp");
try {
recognizer = new LiveSpeechRecognizer(configuration);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
@Override
public String listen() {
// Start recognition process pruning previously cached data.
recognizer.startRecognition(true);
SpeechResult result = recognizer.getResult();
// Pause recognition process. It can be resumed then with startRecognition(false).
recognizer.stopRecognition();
return result.getHypothesis();
}
}
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.stt;
import edu.cmu.sphinx.api.Configuration;
import edu.cmu.sphinx.api.LiveSpeechRecognizer;
import edu.cmu.sphinx.api.SpeechResult;
import se.hal.intf.HalSpeachToText;
import java.io.IOException;
/**
* Created by Ziver on 2015-05-08.
*/
public class Sphinx4STTClient implements HalSpeachToText {
private LiveSpeechRecognizer recognizer;
@Override
public void initSTT() {
Configuration configuration = new Configuration();
// Set path to acoustic model.
configuration.setAcousticModelPath("resource:/sphinx-models/en-us");
// Set path to dictionary.
configuration.setDictionaryPath("resource:/sphinx-models/cmudict-en-us.dict");
// Set language model.
configuration.setLanguageModelPath("resource:/sphinx-models/en-us.lm.dmp");
try {
recognizer = new LiveSpeechRecognizer(configuration);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
@Override
public String listen() {
// Start recognition process pruning previously cached data.
recognizer.startRecognition(true);
SpeechResult result = recognizer.getResult();
// Pause recognition process. It can be resumed then with startRecognition(false).
recognizer.stopRecognition();
return result.getHypothesis();
}
}

View file

@ -1,101 +1,101 @@
/*
* Copyright (c) 2013 ezivkoc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.hal.tts;
import com.darkprograms.speech.synthesiser.SynthesiserV2;
import javafx.embed.swing.JFXPanel;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import se.koc.hal.intf.HalTextToSpeach;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
/**
* Created with IntelliJ IDEA.
* User: ezivkoc
* Date: 2013-12-17
* Time: 13:45
*/
public class GoogleTTSClient implements HalTextToSpeach {
private static final String API_KEY = "AIzaSyBGAQ29aMvts9MObj739_HYa-tvNeEI0X8";
private SynthesiserV2 synthesiser;
private File tmpAudioFile;
public void initTTS() {
try {
// JavaFX should be initialized
JFXPanel fxPanel = new JFXPanel();
synthesiser = new SynthesiserV2(API_KEY);
tmpAudioFile = File.createTempFile("tts", "tmp");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void speak(String msg) {
try{
String language = synthesiser.detectLanguage(msg);
InputStream is = synthesiser.getMP3Data(msg);
BufferedInputStream buff = new BufferedInputStream(is);
DataInputStream di = new DataInputStream(buff);
FileOutputStream fos = new FileOutputStream(tmpAudioFile);
while(di.available() != 0){
fos.write(di.readByte());
}
fos.close();
URL resource = tmpAudioFile.toURI().toURL();
Media media = new Media(resource.toURI().toString());
final MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
mediaPlayer.setOnEndOfMedia(new Runnable() {
@Override public void run() {
mediaPlayer.stop();
}
});
while(mediaPlayer.getStatus() != MediaPlayer.Status.STOPPED){
try{Thread.sleep(200);}catch(Exception e){}
}
}catch(URISyntaxException e){
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/*
* Copyright (c) 2013 ezivkoc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.tts;
import com.darkprograms.speech.synthesiser.SynthesiserV2;
import javafx.embed.swing.JFXPanel;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import se.hal.intf.HalTextToSpeach;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
/**
* Created with IntelliJ IDEA.
* User: ezivkoc
* Date: 2013-12-17
* Time: 13:45
*/
public class GoogleTTSClient implements HalTextToSpeach {
private static final String API_KEY = "AIzaSyBGAQ29aMvts9MObj739_HYa-tvNeEI0X8";
private SynthesiserV2 synthesiser;
private File tmpAudioFile;
public void initTTS() {
try {
// JavaFX should be initialized
JFXPanel fxPanel = new JFXPanel();
synthesiser = new SynthesiserV2(API_KEY);
tmpAudioFile = File.createTempFile("tts", "tmp");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void speak(String msg) {
try{
String language = synthesiser.detectLanguage(msg);
InputStream is = synthesiser.getMP3Data(msg);
BufferedInputStream buff = new BufferedInputStream(is);
DataInputStream di = new DataInputStream(buff);
FileOutputStream fos = new FileOutputStream(tmpAudioFile);
while(di.available() != 0){
fos.write(di.readByte());
}
fos.close();
URL resource = tmpAudioFile.toURI().toURL();
Media media = new Media(resource.toURI().toString());
final MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
mediaPlayer.setOnEndOfMedia(new Runnable() {
@Override public void run() {
mediaPlayer.stop();
}
});
while(mediaPlayer.getStatus() != MediaPlayer.Status.STOPPED){
try{Thread.sleep(200);}catch(Exception e){}
}
}catch(URISyntaxException e){
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

View file

@ -1,71 +1,71 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.hal.tts;
import marytts.LocalMaryInterface;
import marytts.MaryInterface;
import marytts.exceptions.MaryConfigurationException;
import marytts.exceptions.SynthesisException;
import marytts.util.data.audio.AudioPlayer;
import se.koc.hal.intf.HalTextToSpeach;
import javax.sound.sampled.AudioInputStream;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
* User: ezivkoc
* Date: 2013-12-17
* Time: 14:36
*/
public class MaryLocalTTSClient implements HalTextToSpeach {
private MaryInterface marytts;
@Override
public void initTTS() {
try {
marytts = new LocalMaryInterface();
Set<String> voices = marytts.getAvailableVoices();
marytts.setVoice(voices.iterator().next());
} catch (MaryConfigurationException e) {
e.printStackTrace();
System.exit(1);
}
}
@Override
public void speak(String msg) {
try {
AudioInputStream audio = marytts.generateAudio(msg);
AudioPlayer player = new AudioPlayer(audio);
player.start();
player.join();
} catch (SynthesisException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.tts;
import marytts.LocalMaryInterface;
import marytts.MaryInterface;
import marytts.exceptions.MaryConfigurationException;
import marytts.exceptions.SynthesisException;
import marytts.util.data.audio.AudioPlayer;
import se.hal.intf.HalTextToSpeach;
import javax.sound.sampled.AudioInputStream;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
* User: ezivkoc
* Date: 2013-12-17
* Time: 14:36
*/
public class MaryLocalTTSClient implements HalTextToSpeach {
private MaryInterface marytts;
@Override
public void initTTS() {
try {
marytts = new LocalMaryInterface();
Set<String> voices = marytts.getAvailableVoices();
marytts.setVoice(voices.iterator().next());
} catch (MaryConfigurationException e) {
e.printStackTrace();
System.exit(1);
}
}
@Override
public void speak(String msg) {
try {
AudioInputStream audio = marytts.generateAudio(msg);
AudioPlayer player = new AudioPlayer(audio);
player.start();
player.join();
} catch (SynthesisException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

View file

@ -1,72 +1,72 @@
/*
* Copyright (c) 2013 ezivkoc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.hal.tts;
import marytts.MaryInterface;
import marytts.client.RemoteMaryInterface;
import marytts.exceptions.SynthesisException;
import marytts.util.data.audio.AudioPlayer;
import se.koc.hal.intf.HalTextToSpeach;
import javax.sound.sampled.AudioInputStream;
import java.io.IOException;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
* User: ezivkoc
* Date: 2013-12-17
* Time: 14:36
*/
public class MaryRemoteTTSClient implements HalTextToSpeach {
private MaryInterface marytts;
@Override
public void initTTS() {
try {
marytts = new RemoteMaryInterface("127.0.0.1", 59125);
Set<String> voices = marytts.getAvailableVoices();
marytts.setVoice(voices.iterator().next());
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
@Override
public synchronized void speak(String msg) {
try {
AudioInputStream audio = marytts.generateAudio(msg);
AudioPlayer player = new AudioPlayer(audio);
player.start();
player.join();
} catch (SynthesisException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/*
* Copyright (c) 2013 ezivkoc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.tts;
import marytts.MaryInterface;
import marytts.client.RemoteMaryInterface;
import marytts.exceptions.SynthesisException;
import marytts.util.data.audio.AudioPlayer;
import se.hal.intf.HalTextToSpeach;
import javax.sound.sampled.AudioInputStream;
import java.io.IOException;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
* User: ezivkoc
* Date: 2013-12-17
* Time: 14:36
*/
public class MaryRemoteTTSClient implements HalTextToSpeach {
private MaryInterface marytts;
@Override
public void initTTS() {
try {
marytts = new RemoteMaryInterface("127.0.0.1", 59125);
Set<String> voices = marytts.getAvailableVoices();
marytts.setVoice(voices.iterator().next());
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
@Override
public synchronized void speak(String msg) {
try {
AudioInputStream audio = marytts.generateAudio(msg);
AudioPlayer player = new AudioPlayer(audio);
player.start();
player.join();
} catch (SynthesisException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

View file

@ -1,4 +1,4 @@
package se.koc.hal.util;
package se.hal.util;
import java.util.Calendar;

View file

@ -1,6 +1,6 @@
package se.koc.hal.plugin.tellstick;
package se.hal.plugin.tellstick;
import se.koc.hal.plugin.tellstick.protocols.NexaSelfLearning;
import se.hal.plugin.tellstick.protocols.NexaSelfLearning;
/**
* Created by Ziver on 2015-11-19.

View file

@ -1,10 +1,9 @@
package se.koc.hal.plugin.tellstick;
package se.hal.plugin.tellstick;
import se.koc.hal.HalContext;
import se.koc.hal.intf.HalSensor;
import se.koc.hal.intf.HalSensorController;
import se.koc.hal.intf.HalSensorReportListener;
import se.koc.hal.plugin.tellstick.protocols.Oregon0x1A2D;
import se.hal.HalContext;
import se.hal.intf.HalSensor;
import se.hal.intf.HalSensorReportListener;
import se.hal.plugin.tellstick.protocols.Oregon0x1A2D;
import zutil.db.DBConnection;
import zutil.log.CompactLogFormatter;
import zutil.log.LogUtil;

View file

@ -1,67 +1,67 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.hal.plugin.tellstick.protocols;
import zutil.converters.Converter;
import static org.junit.Assert.*;
public class NexaSelfLearningTest {
@org.junit.Test
public void testEncode() throws Exception {
NexaSelfLearning nexa = new NexaSelfLearning();
nexa.setHouse(11772006);
nexa.setUnit(3);
nexa.turnOn();
assertArrayEquals(
new char[]{
84, 127, 255, 24, 1, 132, 154, 138, 136, 170,
136, 168, 170, 138, 136, 168, 168, 170, 136, 170,
138, 138, 138, 138, 138, 136, 168, 170, 138, 136,
168, 170, 138, 136, 170, 138, 136, 168, 170, 43},
nexa.encode().toCharArray()
);
}
@org.junit.Test
public void decode_ON() throws Exception {
NexaSelfLearning nexa = new NexaSelfLearning();
nexa.decode(Converter.hexToByte("0x2CE81990"));
assertEquals("House Code", 11772006, nexa.getHouse());
assertEquals("Unit Code", 1, nexa.getUnit());
assertTrue("Enabled", nexa.isOn());
}
@org.junit.Test
public void decode_OFF() throws Exception {
NexaSelfLearning nexa = new NexaSelfLearning();
nexa.decode(Converter.hexToByte("0x2CE81980"));
assertEquals("House Code", 11772006, nexa.getHouse());
assertEquals("Unit Code", 1, nexa.getUnit());
assertFalse("Enabled", nexa.isOn());
}
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.plugin.tellstick.protocols;
import zutil.converters.Converter;
import static org.junit.Assert.*;
public class NexaSelfLearningTest {
@org.junit.Test
public void testEncode() throws Exception {
NexaSelfLearning nexa = new NexaSelfLearning();
nexa.setHouse(11772006);
nexa.setUnit(3);
nexa.turnOn();
assertArrayEquals(
new char[]{
84, 127, 255, 24, 1, 132, 154, 138, 136, 170,
136, 168, 170, 138, 136, 168, 168, 170, 136, 170,
138, 138, 138, 138, 138, 136, 168, 170, 138, 136,
168, 170, 138, 136, 170, 138, 136, 168, 170, 43},
nexa.encode().toCharArray()
);
}
@org.junit.Test
public void decode_ON() throws Exception {
NexaSelfLearning nexa = new NexaSelfLearning();
nexa.decode(Converter.hexToByte("0x2CE81990"));
assertEquals("House Code", 11772006, nexa.getHouse());
assertEquals("Unit Code", 1, nexa.getUnit());
assertTrue("Enabled", nexa.isOn());
}
@org.junit.Test
public void decode_OFF() throws Exception {
NexaSelfLearning nexa = new NexaSelfLearning();
nexa.decode(Converter.hexToByte("0x2CE81980"));
assertEquals("House Code", 11772006, nexa.getHouse());
assertEquals("Unit Code", 1, nexa.getUnit());
assertFalse("Enabled", nexa.isOn());
}
}

View file

@ -1,83 +1,83 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.hal.test;
import zutil.io.DynamicByteArrayStream;
import javax.sound.sampled.*;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* Created with IntelliJ IDEA.
* User: ezivkoc
* Date: 2013-12-17
* Time: 11:24
*/
public class GoogleTTSTest {
public static void main(String[] args){
try {
/* URL url = new URL("http://translate.google.com/translate_tts?q=I+love+techcrunch");
InputStream in = url.openStream();
byte[] data = getContent(in);
in.close();
*/
Clip push = AudioSystem.getClip();
URL url = new URL("http://translate.google.com/translate_tts?ie=UTF-8&q=Hello%20World&tl=en-us");
URLConnection con = url.openConnection();
con.setRequestProperty("Cookie", "JSESSIONID=UX61oaN8vRhLE5pYXAjTWg; _ga=GA1.3.53937642.1385651778; HSID=AINSMauAFJWBs84WQ; APISID=RgytV3HJnm0dWjVr/AtidsIB_LJQzDmBMc; NID=67=R0kMLqIXXiOkrU8jlk4vgqLUiWUYUZRvxjf1Un0DQbQxGKt9pXXzDv-v0zSCSqLi_YNzcZujTDDr9r_KGsiPhEMfk-oKQSKvHe-DVVuwHZb2UZraJKCBAb6mPJO6AxBExoXHzU2pHd-DI1yIMxuLyVJA9RxhM_2kB4h7U0w9WiWqRNN7sU5DPVeLpF_ScW1VH9_igIR2ACK0WHvmoZXBjXDDrnUiVJt9DjkbMpHxU1o_1PnuUXi5FmfJLjrQspI; SID=DQAAANgAAADcaXZk9dA01UfdydUwIH32OGbA0k6mhbV2GSsiqcGYTUhNqLn_Z9TAlUsizBVoG-3g-ghXzpev46P--fqcR4UACZ2iVawFbfUB44B2hBmQQsFbyjGop1smPLu3cJORBLUKQ4PiZQb23GtXYg28prWlK3IFj8Wc3AHY5yoIpnssRY24k9DybwSSVt2Ww7c4ySzfw4uXxwtbSDTy0q8lmdAorjT4R6DCJwhaCGV4ysexY-vJaQE2kiRe3fPY2z9jQ6Mi9z_XjGRamLTI_AvJj-_XdQIfv0ZSo7JiEEjTUMb10Q; PREF=ID=8bf4d3a7414e8137:U=4ebb392cf34740cf:LD=sv:CR=2:TM=1368543367:LM=1387278509:GM=1:SG=1:S=fpteokIgX46FW8tp");
con.connect();
AudioInputStream audioPush = AudioSystem.getAudioInputStream(con.getInputStream());
push.open(audioPush);
push.start();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
public static byte[] getContent(InputStream stream) throws IOException{
BufferedInputStream in = new BufferedInputStream(stream);
byte[] tmp = new byte[256];
int len;
DynamicByteArrayStream buff = new DynamicByteArrayStream();
while((len=in.read(tmp)) != -1){
buff.append(tmp, 0, len);
}
return buff.getBytes();
}
}
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.test;
import zutil.io.DynamicByteArrayStream;
import javax.sound.sampled.*;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* Created with IntelliJ IDEA.
* User: ezivkoc
* Date: 2013-12-17
* Time: 11:24
*/
public class GoogleTTSTest {
public static void main(String[] args){
try {
/* URL url = new URL("http://translate.google.com/translate_tts?q=I+love+techcrunch");
InputStream in = url.openStream();
byte[] data = getContent(in);
in.close();
*/
Clip push = AudioSystem.getClip();
URL url = new URL("http://translate.google.com/translate_tts?ie=UTF-8&q=Hello%20World&tl=en-us");
URLConnection con = url.openConnection();
con.setRequestProperty("Cookie", "JSESSIONID=UX61oaN8vRhLE5pYXAjTWg; _ga=GA1.3.53937642.1385651778; HSID=AINSMauAFJWBs84WQ; APISID=RgytV3HJnm0dWjVr/AtidsIB_LJQzDmBMc; NID=67=R0kMLqIXXiOkrU8jlk4vgqLUiWUYUZRvxjf1Un0DQbQxGKt9pXXzDv-v0zSCSqLi_YNzcZujTDDr9r_KGsiPhEMfk-oKQSKvHe-DVVuwHZb2UZraJKCBAb6mPJO6AxBExoXHzU2pHd-DI1yIMxuLyVJA9RxhM_2kB4h7U0w9WiWqRNN7sU5DPVeLpF_ScW1VH9_igIR2ACK0WHvmoZXBjXDDrnUiVJt9DjkbMpHxU1o_1PnuUXi5FmfJLjrQspI; SID=DQAAANgAAADcaXZk9dA01UfdydUwIH32OGbA0k6mhbV2GSsiqcGYTUhNqLn_Z9TAlUsizBVoG-3g-ghXzpev46P--fqcR4UACZ2iVawFbfUB44B2hBmQQsFbyjGop1smPLu3cJORBLUKQ4PiZQb23GtXYg28prWlK3IFj8Wc3AHY5yoIpnssRY24k9DybwSSVt2Ww7c4ySzfw4uXxwtbSDTy0q8lmdAorjT4R6DCJwhaCGV4ysexY-vJaQE2kiRe3fPY2z9jQ6Mi9z_XjGRamLTI_AvJj-_XdQIfv0ZSo7JiEEjTUMb10Q; PREF=ID=8bf4d3a7414e8137:U=4ebb392cf34740cf:LD=sv:CR=2:TM=1368543367:LM=1387278509:GM=1:SG=1:S=fpteokIgX46FW8tp");
con.connect();
AudioInputStream audioPush = AudioSystem.getAudioInputStream(con.getInputStream());
push.open(audioPush);
push.start();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
public static byte[] getContent(InputStream stream) throws IOException{
BufferedInputStream in = new BufferedInputStream(stream);
byte[] tmp = new byte[256];
int len;
DynamicByteArrayStream buff = new DynamicByteArrayStream();
while((len=in.read(tmp)) != -1){
buff.append(tmp, 0, len);
}
return buff.getBytes();
}
}

View file

@ -1,198 +1,198 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.hal.test;
import com.darkprograms.speech.microphone.MicrophoneAnalyzer;
import com.darkprograms.speech.recognizer.FlacEncoder;
import com.darkprograms.speech.recognizer.GoogleResponse;
import javax.sound.sampled.AudioFileFormat;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JarvisRecognizerTest {
public static void main(String[] args){
try {
new JarvisRecognizerTest();
} catch (Exception e) {
e.printStackTrace();
}
}
public JarvisRecognizerTest() throws Exception{
MicrophoneAnalyzer mic = new MicrophoneAnalyzer(AudioFileFormat.Type.WAVE);
File audioFile = new File("bin/tmp.wav");
boolean speaking = false;
while(!speaking){
mic.captureAudioToFile(audioFile);
final int THRESHOLD = 10;//YOUR THRESHOLD VALUE.
mic.open();
int ambientVolume = mic.getAudioVolume();//
int speakingVolume = -2;
do{
int volume = mic.getAudioVolume();
System.out.println(volume);
if(volume>ambientVolume+THRESHOLD){
speakingVolume = volume;
speaking = true;
Thread.sleep(1000);
System.out.println("SPEAKING");
}
if(speaking && volume+THRESHOLD<speakingVolume){
break;
}
}while(speaking);
mic.close();
}
Thread.sleep(100);
mic.close();
FlacEncoder flacEncoder = new FlacEncoder();
File flacFile = new File(audioFile + ".flac");
flacEncoder.convertWaveToFlac(audioFile, flacFile);
audioFile.delete();
Path path = Paths.get("bin/tmp.wav.flac");
byte[] data = Files.readAllBytes(path);
String request = "https://www.google.com/"+
"speech-api/v1/recognize?"+
"xjerr=1&client=speech2text&lang=en-US&maxresults=1";
URL url = new URL(request);
Proxy proxy =new Proxy(Proxy.Type.HTTP, new InetSocketAddress("www-proxy.ericsson.se", 8080));
HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "audio/x-flac; rate=8000");
connection.setRequestProperty("User-Agent", "speech2text");
connection.setConnectTimeout(60000);
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.write(data);
wr.flush();
wr.close();
connection.disconnect();
flacFile.delete();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String decodedString = in.readLine();
GoogleResponse googleResponse = new GoogleResponse();
parseResponse(decodedString, googleResponse);
System.out.println(googleResponse);
}
private void parseResponse(String rawResponse, GoogleResponse googleResponse) {
if(rawResponse == null)
return;
if (!rawResponse.contains("utterance"))
return;
String array = substringBetween(rawResponse, "[", "]");
String[] parts = array.split("}");
boolean first = true;
for( String s : parts ) {
if( first ) {
first = false;
String utterancePart = s.split(",")[0];
String confidencePart = s.split(",")[1];
String utterance = utterancePart.split(":")[1];
String confidence = confidencePart.split(":")[1];
utterance = stripQuotes(utterance);
confidence = stripQuotes(confidence);
if( utterance.equals("null") ) {
utterance = null;
}
if( confidence.equals("null") ) {
confidence = null;
}
//googleResponse.setResponse(utterance);
//googleResponse.setConfidence(confidence);
} else {
String utterance = s.split(":")[1];
utterance = stripQuotes(utterance);
if( utterance.equals("null") ) {
utterance = null;
}
googleResponse.getOtherPossibleResponses().add(utterance);
}
}
}
private String substringBetween(String s, String part1, String part2) {
String sub = null;
int i = s.indexOf(part1);
int j = s.indexOf(part2, i + part1.length());
if (i != -1 && j != -1) {
int nStart = i + part1.length();
sub = s.substring(nStart, j);
}
return sub;
}
private String stripQuotes(String s) {
int start = 0;
if( s.startsWith("\"") ) {
start = 1;
}
int end = s.length();
if( s.endsWith("\"") ) {
end = s.length() - 1;
}
return s.substring(start, end);
}
}
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.test;
import com.darkprograms.speech.microphone.MicrophoneAnalyzer;
import com.darkprograms.speech.recognizer.FlacEncoder;
import com.darkprograms.speech.recognizer.GoogleResponse;
import javax.sound.sampled.AudioFileFormat;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JarvisRecognizerTest {
public static void main(String[] args){
try {
new JarvisRecognizerTest();
} catch (Exception e) {
e.printStackTrace();
}
}
public JarvisRecognizerTest() throws Exception{
MicrophoneAnalyzer mic = new MicrophoneAnalyzer(AudioFileFormat.Type.WAVE);
File audioFile = new File("bin/tmp.wav");
boolean speaking = false;
while(!speaking){
mic.captureAudioToFile(audioFile);
final int THRESHOLD = 10;//YOUR THRESHOLD VALUE.
mic.open();
int ambientVolume = mic.getAudioVolume();//
int speakingVolume = -2;
do{
int volume = mic.getAudioVolume();
System.out.println(volume);
if(volume>ambientVolume+THRESHOLD){
speakingVolume = volume;
speaking = true;
Thread.sleep(1000);
System.out.println("SPEAKING");
}
if(speaking && volume+THRESHOLD<speakingVolume){
break;
}
}while(speaking);
mic.close();
}
Thread.sleep(100);
mic.close();
FlacEncoder flacEncoder = new FlacEncoder();
File flacFile = new File(audioFile + ".flac");
flacEncoder.convertWaveToFlac(audioFile, flacFile);
audioFile.delete();
Path path = Paths.get("bin/tmp.wav.flac");
byte[] data = Files.readAllBytes(path);
String request = "https://www.google.com/"+
"speech-api/v1/recognize?"+
"xjerr=1&client=speech2text&lang=en-US&maxresults=1";
URL url = new URL(request);
Proxy proxy =new Proxy(Proxy.Type.HTTP, new InetSocketAddress("www-proxy.ericsson.se", 8080));
HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "audio/x-flac; rate=8000");
connection.setRequestProperty("User-Agent", "speech2text");
connection.setConnectTimeout(60000);
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.write(data);
wr.flush();
wr.close();
connection.disconnect();
flacFile.delete();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String decodedString = in.readLine();
GoogleResponse googleResponse = new GoogleResponse();
parseResponse(decodedString, googleResponse);
System.out.println(googleResponse);
}
private void parseResponse(String rawResponse, GoogleResponse googleResponse) {
if(rawResponse == null)
return;
if (!rawResponse.contains("utterance"))
return;
String array = substringBetween(rawResponse, "[", "]");
String[] parts = array.split("}");
boolean first = true;
for( String s : parts ) {
if( first ) {
first = false;
String utterancePart = s.split(",")[0];
String confidencePart = s.split(",")[1];
String utterance = utterancePart.split(":")[1];
String confidence = confidencePart.split(":")[1];
utterance = stripQuotes(utterance);
confidence = stripQuotes(confidence);
if( utterance.equals("null") ) {
utterance = null;
}
if( confidence.equals("null") ) {
confidence = null;
}
//googleResponse.setResponse(utterance);
//googleResponse.setConfidence(confidence);
} else {
String utterance = s.split(":")[1];
utterance = stripQuotes(utterance);
if( utterance.equals("null") ) {
utterance = null;
}
googleResponse.getOtherPossibleResponses().add(utterance);
}
}
}
private String substringBetween(String s, String part1, String part2) {
String sub = null;
int i = s.indexOf(part1);
int j = s.indexOf(part2, i + part1.length());
if (i != -1 && j != -1) {
int nStart = i + part1.length();
sub = s.substring(nStart, j);
}
return sub;
}
private String stripQuotes(String s) {
int start = 0;
if( s.startsWith("\"") ) {
start = 1;
}
int end = s.length();
if( s.endsWith("\"") ) {
end = s.length() - 1;
}
return s.substring(start, end);
}
}

View file

@ -1,85 +1,85 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.hal.test;
import com.darkprograms.speech.synthesiser.Synthesiser;
import javafx.application.Application;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
import java.io.*;
import java.net.URL;
@SuppressWarnings("restriction")
public class JarvisSyntersizerTest extends Application {
public static void main(String[] args){
try {
Application a = new JarvisSyntersizerTest();
a.launch();
} catch (Exception e) {
e.printStackTrace();
}
}
public JarvisSyntersizerTest(){
}
/**
* Returns the URL to the given file
*
* @param path is the path to the file (no / if not absolute path)
* @return A URL object for the file
*/
public static URL findURL(String path){
return Thread.currentThread().getContextClassLoader().getResource(path);
}
@Override
public void start(Stage arg0) throws Exception {
Synthesiser synthesiser = new Synthesiser("auto");
String language = synthesiser.detectLanguage("hi what is your name?");
System.out.println(language);
InputStream is = synthesiser.getMP3Data("hi what is your name?");
BufferedInputStream buff = new BufferedInputStream(is);
DataInputStream di = new DataInputStream(buff);
File f = new File("bin\\tmp.mp3");
FileOutputStream fos = new FileOutputStream(f);
while(di.available() != 0){
fos.write(di.readByte());
}
fos.close();
URL resource = findURL("tmp.mp3");
Media hit = new Media(resource.toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
}
}
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.test;
import com.darkprograms.speech.synthesiser.Synthesiser;
import javafx.application.Application;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
import java.io.*;
import java.net.URL;
@SuppressWarnings("restriction")
public class JarvisSyntersizerTest extends Application {
public static void main(String[] args){
try {
Application a = new JarvisSyntersizerTest();
a.launch();
} catch (Exception e) {
e.printStackTrace();
}
}
public JarvisSyntersizerTest(){
}
/**
* Returns the URL to the given file
*
* @param path is the path to the file (no / if not absolute path)
* @return A URL object for the file
*/
public static URL findURL(String path){
return Thread.currentThread().getContextClassLoader().getResource(path);
}
@Override
public void start(Stage arg0) throws Exception {
Synthesiser synthesiser = new Synthesiser("auto");
String language = synthesiser.detectLanguage("hi what is your name?");
System.out.println(language);
InputStream is = synthesiser.getMP3Data("hi what is your name?");
BufferedInputStream buff = new BufferedInputStream(is);
DataInputStream di = new DataInputStream(buff);
File f = new File("bin\\tmp.mp3");
FileOutputStream fos = new FileOutputStream(f);
while(di.available() != 0){
fos.write(di.readByte());
}
fos.close();
URL resource = findURL("tmp.mp3");
Media hit = new Media(resource.toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
}
}

View file

@ -1,63 +1,63 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.hal.test;
import edu.cmu.sphinx.api.Configuration;
import edu.cmu.sphinx.api.LiveSpeechRecognizer;
import edu.cmu.sphinx.api.SpeechResult;
import edu.cmu.sphinx.result.WordResult;
public class LiveSpeechRecognizerTest {
public static void main(String[] args) throws Exception {
System.out.println("Loading models...");
Configuration configuration = new Configuration();
// Set path to acoustic model.
configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us");
// Set path to dictionary.
configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict");
// Set language model.
configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.dmp");
System.out.println("Listening...");
LiveSpeechRecognizer recognizer = new LiveSpeechRecognizer(configuration);
// Start recognition process pruning previously cached data.
recognizer.startRecognition(false);
SpeechResult result = recognizer.getResult();
// Pause recognition process. It can be resumed then with startRecognition(false).
recognizer.stopRecognition();
// Print utterance string without filler words.
System.out.println("Hypothesis: " + result.getHypothesis());
// Get individual words and their times.
for (WordResult r : result.getWords()) {
System.out.println("Word: "+r);
}
// Save lattice in a graphviz format.
result.getLattice().dumpDot("lattice.dot", "lattice");
}
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.test;
import edu.cmu.sphinx.api.Configuration;
import edu.cmu.sphinx.api.LiveSpeechRecognizer;
import edu.cmu.sphinx.api.SpeechResult;
import edu.cmu.sphinx.result.WordResult;
public class LiveSpeechRecognizerTest {
public static void main(String[] args) throws Exception {
System.out.println("Loading models...");
Configuration configuration = new Configuration();
// Set path to acoustic model.
configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us");
// Set path to dictionary.
configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict");
// Set language model.
configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.dmp");
System.out.println("Listening...");
LiveSpeechRecognizer recognizer = new LiveSpeechRecognizer(configuration);
// Start recognition process pruning previously cached data.
recognizer.startRecognition(false);
SpeechResult result = recognizer.getResult();
// Pause recognition process. It can be resumed then with startRecognition(false).
recognizer.stopRecognition();
// Print utterance string without filler words.
System.out.println("Hypothesis: " + result.getHypothesis());
// Get individual words and their times.
for (WordResult r : result.getWords()) {
System.out.println("Word: "+r);
}
// Save lattice in a graphviz format.
result.getLattice().dumpDot("lattice.dot", "lattice");
}
}

View file

@ -1,50 +1,50 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.hal.test;
import marytts.MaryInterface;
import marytts.client.RemoteMaryInterface;
import marytts.util.data.audio.AudioPlayer;
import javax.sound.sampled.AudioInputStream;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
* User: ezivkoc
* Date: 2013-12-17
* Time: 12:39
*/
public class MaryTTS {
public static void main(String[] args) throws Exception {
MaryInterface marytts = new RemoteMaryInterface("127.0.0.1", 59125);
Set<String> voices = marytts.getAvailableVoices();
marytts.setVoice(voices.iterator().next());
AudioInputStream audio = marytts.generateAudio("Hello world.");
AudioPlayer player = new AudioPlayer(audio);
player.start();
player.join();
System.exit(0);
}
}
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.test;
import marytts.MaryInterface;
import marytts.client.RemoteMaryInterface;
import marytts.util.data.audio.AudioPlayer;
import javax.sound.sampled.AudioInputStream;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
* User: ezivkoc
* Date: 2013-12-17
* Time: 12:39
*/
public class MaryTTS {
public static void main(String[] args) throws Exception {
MaryInterface marytts = new RemoteMaryInterface("127.0.0.1", 59125);
Set<String> voices = marytts.getAvailableVoices();
marytts.setVoice(voices.iterator().next());
AudioInputStream audio = marytts.generateAudio("Hello world.");
AudioPlayer player = new AudioPlayer(audio);
player.start();
player.join();
System.exit(0);
}
}

View file

@ -20,7 +20,7 @@
* THE SOFTWARE.
*/
package se.koc.hal.test;
package se.hal.test;
import com.darkprograms.speech.microphone.MicrophoneAnalyzer;
import edu.cmu.sphinx.api.Configuration;

View file

@ -1,4 +1,4 @@
package se.koc.hal.util;
package se.hal.util;
import org.junit.Before;
import org.junit.Test;