UartBus source documentation
PacketAssembler.java
1 package eu.javaexperience.electronic.uartbus;
2 
3 import java.io.ByteArrayOutputStream;
4 import java.io.DataOutputStream;
5 import java.io.IOException;
6 import java.math.BigInteger;
7 
9 
10 public class PacketAssembler extends DataOutputStream
11 {
12  public PacketAssembler()
13  {
14  super(new ByteArrayOutputStream());
15  }
16 
17  public byte[] done() throws IOException
18  {
19  flush();
20  ByteArrayOutputStream baos = (ByteArrayOutputStream) out;
21  byte[] ret = baos.toByteArray();
22  baos.reset();
23  return ret;
24  }
25 
26  public void writePackedValue(boolean signed, Number value) throws IOException
27  {
28  if(value instanceof BigInteger)
29  {
30  writePackedValue(signed, (BigInteger) value);
31  }
32  else
33  {
34  writePackedValue(signed, value.longValue());
35  }
36  }
37 
38  public void writeString(String val) throws IOException
39  {
40  write(val.getBytes());
41  writeByte(0);
42  }
43 
44  public void writePackedValue(boolean signed, BigInteger value) throws IOException
45  {
46  byte[] data = new byte[UartbusTools.calcPackReqBytes(signed, value)];
47  UartbusTools.packValue(signed, value, data, 0);
48  write(data);
49  }
50 
51  public void writePackedValue(boolean signed, long value) throws IOException
52  {
53  writePackedValue(signed, BigInteger.valueOf(value));
54  }
55 
56  public void writePackedValue(boolean signed, int value) throws IOException
57  {
58  writePackedValue(signed, BigInteger.valueOf(value));
59  }
60 
61  public void writeAddress(int val) throws IOException
62  {
63  writePackedValue(true, val);
64  }
65 
66  public void writeAddressing(int from, int to) throws IOException
67  {
68  writeAddress(to);
69  writeAddress(from);
70  }
71 
72  public void appendCrc8() throws IOException
73  {
74  flush();
75  ByteArrayOutputStream baos = (ByteArrayOutputStream) out;
76  writeByte(UartbusTools.crc8(baos.toByteArray()));
77  }
78 
79  public void writeObjects(Object... objects) throws IOException
80  {
81  UbRpcTools.appendElements(this, objects);
82  }
83 }