SimpleLink

master
Harald Christian Joachim Wolff 2017-07-27 19:50:15 +02:00
parent 5fcc6bc22a
commit 35c61e2331
1 changed files with 107 additions and 0 deletions

View File

@ -0,0 +1,107 @@
package org.hwo.servicelink;
import java.awt.TexturePaint;
import java.io.BufferedReader;
import java.io.IOException;
import org.hwo.ByteArrayHexlifier;
import java.io.InputStreamReader;
import org.hwo.io.NewSerialPort.BaudRate;
import org.hwo.io.NewSerialPort.NewSerialPort;
import org.hwo.servicelink.exceptions.ServiceLinkException;
import static org.hwo.logging.Logging.*;
import static org.hwo.logging.LogLevel.*;
public class SimpleLink {
NewSerialPort port;
BufferedReader br;
public SimpleLink(NewSerialPort port){
this.port = port;
this.br = new BufferedReader(new InputStreamReader(this.port.getInputStream()));
}
public void close(){
this.port.close();
}
public boolean isOpen(){
return this.port.isOpen();
}
public void open() throws IOException, ServiceLinkException{
this.port.setBaudRate(BaudRate.B57600);
this.port.open();
}
public NewSerialPort getSerialPort(){
return this.port;
}
public void setTimeOut(int timeout) throws IOException, ServiceLinkException{
this.port.setTimeOut(timeout);
}
public String fixhexstring(String hs,int digits){
StringBuilder sb = new StringBuilder();
for (int n=0;n<digits-hs.length();n++)
{
sb.append("0");
}
sb.append(hs);
return sb.toString().substring(0,digits);
}
public synchronized float readFloat(int reg) throws IOException, ServiceLinkException{
String sreg = fixhexstring(Integer.toHexString(reg),4);
String ol = String.format("R%s\n\r", sreg);
port.getOutputStream().write(ol.getBytes());
String reply = br.readLine();
if (reply.length() != 9){
throw new ServiceLinkException();
}
return Float.intBitsToFloat(Integer.parseUnsignedInt(reply.substring(1), 16));
}
public synchronized int readInt(int reg) throws IOException, ServiceLinkException{
String sreg = fixhexstring(Integer.toHexString(reg),4);
String ol = String.format("R%s\n\r", sreg);
port.getOutputStream().write(ol.getBytes());
String reply = br.readLine();
if (reply.length() != 9){
throw new ServiceLinkException("Short read: " + reply);
}
return Integer.parseUnsignedInt(reply.substring(1), 16);
}
public synchronized void writeInt(int reg,int value) throws IOException, ServiceLinkException{
String sreg = fixhexstring(Integer.toHexString(reg),4);
String svalue = fixhexstring(Integer.toHexString(value),8);
String ol = String.format("W%s%s\n\r", sreg, svalue);
port.getOutputStream().write(ol.getBytes());
String reply = br.readLine();
if ((reply.length() != 1)){
throw new ServiceLinkException("Failed: " + reply);
}
if (!reply.equals("A")){
throw new ServiceLinkException("Failed: " + reply);
}
}
public synchronized void writeFloat(int reg,float value) throws IOException, ServiceLinkException{
}
}