アルファ版。新版→https://osdn.jp/users/tacticsrealize/pf/ChlorophyllUploader/wiki/FrontPage
Révision | 82b375367456635f711775be0d76dcafef88ca32 |
---|---|
Taille | 2,140 octets |
l'heure | 2015-07-08 20:15:01 |
Auteur | |
Message de Log | 新ファイル形式に対応しArduinoとの連携 |
package ants.chlorofilsender;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.function.IntConsumer;
public class OutputChlorofilSender
{
protected static final int ARDUINO_MAX_BUFFER = 63;
protected PrintStream out;
public OutputChlorofilSender(OutputStream outputStream)
{
try {
out = new PrintStream(outputStream, false, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
protected int sentChars = 0;
protected transient int acceptedChars = 0;
public IntConsumer getConsumerAcceptedChars()
{
return acceptedChars -> {
this.acceptedChars = acceptedChars;
};
}
public void send(String string)
{
synchronized (sendingStrings) {
sendingStrings.add(string);
}
}
protected LinkedList<String> sendingStrings = new LinkedList<>();
protected Thread thread;
public Thread startSenderThread()
{
thread = new Thread(() -> {
try {
while (true) {
synchronized (sendingStrings) {
for (Iterator<String> iterator = sendingStrings.iterator(); iterator.hasNext();) {
String string = iterator.next();
sendImpl(string);
iterator.remove();
}
}
Thread.sleep(5);
}
} catch (InterruptedException e) {
}
});
thread.setDaemon(true);
thread.start();
return thread;
}
protected void sendImpl(String string) throws InterruptedException
{
do {
int bufferedChars = sentChars - acceptedChars;
int bufferSpace = ARDUINO_MAX_BUFFER - bufferedChars;
int sendingChars = Math.min(string.length(), bufferSpace);
sendImpl2(string.substring(0, sendingChars));
string = string.substring(sendingChars);
if (string.isEmpty()) break;
Thread.sleep(5);
} while (true);
}
protected void sendImpl2(String string)
{
sentChars += string.length();
out.print(string);
out.flush();
}
public void close()
{
thread.interrupt();
out.close();
}
}