package Program;
import Common.StaticValues;
import Communication.Messages.TCP.TCPMessageService;
import Communication.Messages.UDP.UDPMessageService;
import Multicast.MulticastJsonReceivingThread;
import Multicast.MulticastWebProgram;
import SerialImpl.DefaultSerial;
import java.io.IOException;
public class ClientManager
{
private static ClientManager instance = null;
private static final String accelerometerOutBase = "accel.csv";
public static ClientManager getInstance()
{
if (instance == null)
{
instance = new ClientManager();
}
return instance;
}
private MulticastJsonReceivingThread finder;
private MulticastWebProgram webProgram = null;
private TCPMessageService tcp = null;
private UDPMessageService udp = null;
private DefaultSerial serial = null;
private Process videoStream = null;
private ClientManager()
{
this.finder = new MulticastJsonReceivingThread<>(StaticValues.MulticastPort, StaticValues.MulticastAddress, new MulticastWebProgram());
this.finder.start();
}
public MulticastWebProgram getWebProgram()
{
return this.webProgram;
}
public TCPMessageService getTCP()
{
if (this.tcp == null || !this.tcp.isAlive())
{
try {
this.startTCP();
}
catch (Exception e)
{
e.printStackTrace();
}
}
return tcp;
}
private void startTCP() throws IOException, InterruptedException
{
this.webProgram = this.finder.getNextDataPack();
this.tcp = new TCPMessageService(this.webProgram.tcpPort);
this.tcp.start();
}
public UDPMessageService getUDP()
{
if (this.udp == null || !this.udp.isAlive())
{
try {
this.startTCP();
}
catch (Exception e)
{
e.printStackTrace();
}
}
return this.udp;
}
private void startUdp() throws IOException, InterruptedException
{
this.webProgram = this.finder.getNextDataPack();
this.udp = new UDPMessageService(this.webProgram.udpPort);
this.udp.start();
}
public void start(long time) throws IOException
{
String folder = Client.getContainingFolder().getAbsolutePath();
this.videoStream = new ProcessBuilder(folder + "/startStreaming", this.webProgram.getURL()).start();
this.serial = new DefaultSerial(new ClientAccelerometer(folder + "/" + time + "-" + accelerometerOutBase));
this.serial.open();
}
public void stop() throws IOException
{
if (this.videoStream != null && this.videoStream.isAlive())
{
this.videoStream.destroy();
this.videoStream = null;
}
if (this.serial != null && this.serial.isOpen())
{
this.serial.close();
this.serial = null;
}
}
}