如何通过与外部硬件的通信来制作一个asnychron REST Server

时间:2019-06-17 10:05:28

标签: java rest spring-boot tcp

我目前在Spring Boot的REST服务器上工作,该服务器还通过USB或TCP / IP与外部硬件通信。命令被发送到外部设备,然后我等待2秒钟以获得响应并将其返回给RestController。

对于USB通信,我目前正在使用jSerialComm。
对于TCP / IP通信,我使用套接字。

到目前为止,当我使用Thread.sleep时,整个过程仍然有效。但是,我希望它更具动态性,即无需睡眠,因为TCP / IP可能会导致延迟。

对我来说,Java和REST仍然很新。有没有办法让服务器与硬件异步通信?

@RestController
@RequestMapping("/api/v1")
public class CommController {

@GetMapping("/Version")
  public String getVersion() {

    Serial serial = new Serial();
    String s_response = null;

    s_response = serial.getVersion();

    return s_response;
  }

@GetMapping("/VersionTCPIP")
  public String getVersionTCPIP() {

    Serial serial = new Serial();
    String s_response = null;

    s_response = serial.getVersionTCPIP();

    return s_response;
  }
}

USB /串行类:

public class Serial {

private static SerialPort port;
private static List<Byte> l_readBuffer;

private static final class MessageListener implements SerialPortDataListener
{
   @Override
   public int getListeningEvents()
   {
       return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
   }

   @Override
   public void serialEvent(SerialPortEvent event)
   {
       if (event.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE)
           return;
       byte[] newData = new byte[port.bytesAvailable()];
       int numRead = port.readBytes(newData, newData.length);
       for (int i = 0; i < numRead; i++)
       {
           l_readBuffer.add(newData[i]);
       }
       System.out.println("Read " + numRead + " bytes.");
   }
}

public String getVersion() {

   SerialPort[] ports = SerialPort.getCommPorts();
   port = null;

   for (SerialPort currentPort :
           ports)
   {

       if (currentPort.getDescriptivePortName().contains("XXX"))
       {
           port = currentPort;
           break;
       }
   }

   Objects.requireNonNull(port).setBaudRate(9600);
   port.setParity(SerialPort.NO_PARITY);
   port.setNumStopBits(SerialPort.ONE_STOP_BIT);
   port.setNumDataBits(8);

   port.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
   //port.clearRTS();
   port.setComPortTimeouts(SerialPort.LISTENING_EVENT_DATA_AVAILABLE, 5000, 5000);

   port.openPort();

   MessageListener listener = new MessageListener();
   port.addDataListener(listener);

   l_readBuffer = new ArrayList<>();

   byte[] sendBuffer = new byte[5];

   // fill sendBuffer

   port.writeBytes(sendBuffer, sendBuffer.length);

   try
   {
       Thread.sleep(2000);
   } catch (Exception e)
   {
       e.printStackTrace();
   }

   System.out.println("Data raw: " + l_readBuffer.toString());

   byte[] ba_responseBuffer = new byte[l_readBuffer.size()];
   for (int i = 0; i < l_readBuffer.size(); i++)
   {
       ba_responseBuffer[i] = l_readBuffer.get(i);
   }

   String s_version = new String(ba_responseBuffer);

   System.out.println("Version: " + s_version);

   port.removeDataListener();

   port.closePort();

   return s_version;
   }

public String getVersionTCPIP()
{
   Socket socket;
   String s_versionString = null;

   try
   {
       socket = new Socket();
       socket.connect(new InetSocketAddress(s_hostnameTCPIP, i_port), 1000);

       byte[] ba_sendBuffer = new byte[1024];
       Arrays.fill(ba_sendBuffer, (byte) 0x00);

       // fill sendBuffer

       // send data
       DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());

       dOut.write(ba_sendBuffer);      // write the message
       dOut.writeInt(i_sendLength);    // write length of the message
       dOut.flush();

       try
       {
           Thread.sleep(2000);
       } catch (Exception e)
       {
           e.printStackTrace();
       }

       byte[] ba_responseBuffer = new byte[0];

       if (socket.isConnected())
       {
           try
           {
               InputStream inFromServer = socket.getInputStream();
               DataInputStream dIn = new DataInputStream(inFromServer);

               synchronized (dIn)
               {
                   int length = dIn.available();
                   ba_responseBuffer = new byte[length];

                   // receive data
                   dIn.readFully(ba_responseBuffer);
               }

           } catch (IOException ex)
           {
               ex.printStackTrace();
           }

           String s_version = new String(ba_responseBuffer);

           System.out.println("Version: " + s_version);

           s_versionString = s_version;

           socket.close();
       }

   } catch (IOException e)
   {
       e.printStackTrace();
   }

   return s_versionString;
}
}

0 个答案:

没有答案