问题
I am using server program to connect with arduino board I am using hc-05 bluetooth in my arduino board so that it is wireless and then scratch program will open which will display some output.I am using serial port communication where I am displaying COM ports and it displays well.I will select one com port from the combobox and when i press the connect button scratch file will open. This works fine for the first time. When I again run my application my program throws an exception "gnu.io.nosuchportexception
" or "gnu.io.portinuseexception
" I don't know how to solve this issue. I am using the following code in server program.
import java.io.*;
import java.net.*;
import java.util.*;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.UnsupportedCommOperationException;
import org.firmata.Firmata;
public class A4S {
private static int[] firmataPinModes= {Firmata.INPUT,Firmata.OUTPUT,Firmata.ANALOG,Firmata.PWM,Firmata.SERVO };
private static String[] a4sPinModes={"Digital%20Input", "Digital%20Output","Analog%20Input","Analog%20Output%28PWM%29","Servo"};
private static final int PORT = 12345; // set to your extension's port number
private static int volume = 8; // replace with your extension's data, if any
private static InputStream sockIn;
private static OutputStream sockOut;
private static SerialPort serialPort;
private static Firmata arduino;
private static SerialReader reader;
public static class SerialReader implements SerialPortEventListener {
public void serialEvent(SerialPortEvent e) {
try {
while (serialPort.getInputStream().available() > 0) {
int n = serialPort.getInputStream().read();
//System.out.println(">" + n);
arduino.processInput(n);
}
} catch (IOException err) {
System.err.println(err);
}
}
}
public static class FirmataWriter implements Firmata.Writer {
public void write(int val) {
try {
//System.out.println("<" + val);
serialPort.getOutputStream().write(val);
} catch (IOException err) {
System.err.println(err);
}
}
}
//public static void main(String[] args) throws IOException
public A4S(String args[]) throws IOException
{
try {
System.out.println(args[0]);
if (args.length < 1) {
System.err.println("Please specify serial port on command line.");
return;
}
//CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM3");
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(args[0]);
CommPort commPort = portIdentifier.open("A4S",2000);
if ( commPort instanceof SerialPort )
{
serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(57600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
arduino = new Firmata(new FirmataWriter());
reader = new SerialReader();
serialPort.addEventListener(reader);
serialPort.notifyOnDataAvailable(true);
try {
Thread.sleep(3000); // let bootloader timeout
} catch (InterruptedException e)
{
throw new RuntimeException("sorry",e) ; //added line
}
arduino.init();
}
else
{
System.out.println("Error: Only serial ports are handled by this example.");
return;
}
} catch (Exception e) {
System.err.println(e);
return;
}
InetAddress addr = InetAddress.getLocalHost();
System.out.println("HTTPExtensionExample helper app started on " + addr.toString());
ServerSocket serverSock = new ServerSocket(PORT);
while (true) {
Socket sock = serverSock.accept();
sockIn = sock.getInputStream();
sockOut = sock.getOutputStream();
try {
handleRequest();
} catch (Exception e) {
e.printStackTrace(System.err);
sendResponse("unknown server error");
}
sock.close();
// serverSock.close();
}
}
private static void handleRequest() throws IOException {
String httpBuf = "";
int i;
// read data until the first HTTP header line is complete (i.e. a '\n' is seen)
while ((i = httpBuf.indexOf('\n')) < 0) {
byte[] buf = new byte[5000];
int bytes_read = sockIn.read(buf, 0, buf.length);
if (bytes_read < 0) {
System.out.println("Socket closed; no HTTP header.");
return;
}
httpBuf += new String(Arrays.copyOf(buf, bytes_read));
}
String header = httpBuf.substring(0, i);
if (header.indexOf("GET ") != 0) {
System.out.println("This server only handles HTTP GET requests.");
return;
}
i = header.indexOf("HTTP/1");
if (i < 0) {
System.out.println("Bad HTTP GET header.");
return;
}
header = header.substring(5, i - 1);
if (header.equals("favicon.ico")) return; // igore browser favicon.ico requests
else if (header.equals("crossdomain.xml")) sendPolicyFile();
else if (header.length() == 0) doHelp();
else doCommand(header);
}
private static void sendPolicyFile() {
// Send a Flash null-teriminated cross-domain policy file.
String policyFile =
"<cross-domain-policy>\n" +
" <allow-access-from domain=\"*\" to-ports=\"" + PORT + "\"/>\n" +
"</cross-domain-policy>\n\0";
sendResponse(policyFile);
}
private static void sendResponse(String s) {
String crlf = "\r\n";
String httpResponse = "HTTP/1.1 200 OK" + crlf;
httpResponse += "Content-Type: text/html; charset=ISO-8859-1" + crlf;
httpResponse += "Access-Control-Allow-Origin: *" + crlf;
httpResponse += crlf;
httpResponse += s + crlf;
try {
byte[] outBuf = httpResponse.getBytes();
sockOut.write(outBuf, 0, outBuf.length);
} catch (Exception ignored) { }
}
private static void doCommand(String cmdAndArgs) {
// Essential: handle commands understood by this server
String response = "okay";
String[] parts = cmdAndArgs.split("/");
String cmd = parts[0];
//System.out.print(cmdAndArgs);
if (cmd.equals("pinOutput")) {
arduino.pinMode(Integer.parseInt(parts[1]), Firmata.OUTPUT);
} else if (cmd.equals("pinInput")) {
arduino.pinMode(Integer.parseInt(parts[1]), Firmata.INPUT);
} else if (cmd.equals("pinHigh")) {
arduino.digitalWrite(Integer.parseInt(parts[1]), Firmata.HIGH);
} else if (cmd.equals("pinLow")) {
arduino.digitalWrite(Integer.parseInt(parts[1]), Firmata.LOW);
} else if (cmd.equals("pinMode")) {
arduino.pinMode(Integer.parseInt(parts[1]), getFirmataPinMode(parts[2]) );
} else if (cmd.equals("digitalWrite"))
{
// if(parts[1].equals(""))
arduino.digitalWrite(Integer.parseInt(parts[1]), "high".equals(parts[2]) ? Firmata.HIGH : Firmata.LOW);
} else if (cmd.equals("analogWrite"))
{
if(parts[1].equals("Speaker"))//addedline
{
int value=3;
arduino.analogWrite(value, Integer.parseInt(parts[2]));//addedline
}
else if(parts[1].equals("Left_RED"))//addedline
{
int value=4;
arduino.analogWrite(value, Integer.parseInt(parts[2]));//addedline
}
else if(parts[1].equals("Left_GREEN"))//addedline
{
int value=5;
arduino.analogWrite(value, Integer.parseInt(parts[2]));//addedline
}
else if(parts[1].equals("Left_BLUE"))//addedline
{
int value=6;
arduino.analogWrite(value, Integer.parseInt(parts[2]));//addedline
}
else if(parts[1].equals("Right_RED"))//addedline
{
int value=7;
arduino.analogWrite(value, Integer.parseInt(parts[2]));//addedline
}
else if(parts[1].equals("Right_GREEN"))//addedline
{
int value=8;
arduino.analogWrite(value, Integer.parseInt(parts[2]));//addedline
}
else if(parts[1].equals("Right_BLUE"))//addedline
{
int value=9;
arduino.analogWrite(value, Integer.parseInt(parts[2]));//addedline
}
else if(parts[1].equals("Left_Motor_Forward"))//addedline
{
int value=10;
arduino.analogWrite(value, Integer.parseInt(parts[2]));//addedline
}
else if(parts[1].equals("Left_Motor_Backward"))//addedline
{
int value=11;
arduino.analogWrite(value, Integer.parseInt(parts[2]));//addedline
}
else if(parts[1].equals("Right_Motor_Forward"))//addedline
{
int value=12;
arduino.analogWrite(value, Integer.parseInt(parts[2]));//addedline
}
else if (parts[1].equals("Right_Motor_Backward"))//addedline
{
int value=13;
arduino.analogWrite(value, Integer.parseInt(parts[2]));//addedline
}
}
else if (cmd.equals("servoWrite")) {
arduino.servoWrite(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]));
} else if (cmd.equals("poll")) {
// set response to a collection of sensor, value pairs, one pair per line
// in this example there is only one sensor, "volume"
//response = "volume " + volume + "\n";
response = "";
for (int i = 2; i <= 13; i++) {
response += "digitalRead/" + i + " " + (arduino.digitalRead(i) == Firmata.HIGH ? "true" : "false") + "\n";
}
for (int i = 0; i <= 5; i++) //defaultline
{response += "analogRead/" + i + " " + (arduino.analogRead(i)) + "\n";} //defaultline */
} else {
response = "unknown command: " + cmd;
}
System.out.println(" " + response);
sendResponse(response);
}
private static int getFirmataPinMode(String a4sPinMode){
int idx=0;
while (idx < a4sPinModes.length-1 && (! a4sPinMode.equals(a4sPinModes[idx]))) idx++;
if (! a4sPinMode.equals(a4sPinModes[idx]) ) idx=0;
return firmataPinModes[idx];
}
private static void doHelp() {
// Optional: return a list of commands understood by this server
String help = "HTTP Extension Example Server<br><br>";
sendResponse(help);
}
}
and following code in Listing the ports.
package listserialports;
import gnu.io.CommPortIdentifier;
import java.util.Enumeration;
import java.util.Vector;
import jssc.SerialPortList;
/*
* Get list of ports available on this particular computer
*/
public class ListSerialPorts
{
public static void main(String[] args)
{
}
public Vector LoadComPorts()
{
int totalElements;
CommPortIdentifier portId;
Enumeration en = CommPortIdentifier.getPortIdentifiers();
Vector listData = new Vector(8);
// Walk through the list of port identifiers and, if it
// is a serial port, add its name to the list.
while (en.hasMoreElements())
{
portId = (CommPortIdentifier) en.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
listData.addElement(portId.getName());
}
//
// listData.addElement("COM30"); //ADDEDLINE
}
// listData.addElement("COM29"); //ADDEDLINE
totalElements = listData.size();
//Iterate through the vector
for (int index = 0; index < totalElements; index ++)
{
System.out.println(listData.get(index));
}
return listData;
}
public Vector LoadComPorts2() //addedline
{
Vector listData = new Vector(8);
String[] portNames = SerialPortList.getPortNames();
for (String port : portNames)
{
listData.add(port);
}
return listData;
}
}
So kindly help me to solve this issue.
来源:https://stackoverflow.com/questions/33561947/close-my-ports-programatically-using-netbeans