├── SerialPortSDK
├── .gitignore
├── script
│ └── SimpleScript.js
├── lib
│ └── RXTXcomm.jar
├── dist
│ └── serialPortSDK.jar
├── rxtx-2.1-7-bins-r2.rar
├── .classpath
├── .project
├── build.xml
└── src
│ ├── testcase
│ ├── ListPort.java
│ ├── BatchScript.java
│ ├── SimpleBatch.java
│ ├── SerialFactory.java
│ ├── SimpleScript.java
│ ├── SimpleCommand.java
│ ├── SimpleConsole.java
│ ├── SimpleFileLog.java
│ ├── ConditionCheck.java
│ └── SimpleServer.java
│ └── serialportutil
│ ├── StringOutputStream.java
│ ├── SerialPortConf.java
│ ├── CommandBatch.java
│ ├── AbstractSerialCommand.java
│ └── SerialPortUtil.java
├── .github
└── FUNDING.yml
├── README.md
└── LICENSE
/SerialPortSDK/.gitignore:
--------------------------------------------------------------------------------
1 | /bin/
2 |
--------------------------------------------------------------------------------
/SerialPortSDK/script/SimpleScript.js:
--------------------------------------------------------------------------------
1 | SEND("ls\n", 1000);
2 | SEND("ps\n", 1000);
--------------------------------------------------------------------------------
/SerialPortSDK/lib/RXTXcomm.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fy-create/JavaSerialPort/HEAD/SerialPortSDK/lib/RXTXcomm.jar
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 | custom: ["https://paypal.me/irepo?locale.x=zh_XC"]
3 |
--------------------------------------------------------------------------------
/SerialPortSDK/dist/serialPortSDK.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fy-create/JavaSerialPort/HEAD/SerialPortSDK/dist/serialPortSDK.jar
--------------------------------------------------------------------------------
/SerialPortSDK/rxtx-2.1-7-bins-r2.rar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fy-create/JavaSerialPort/HEAD/SerialPortSDK/rxtx-2.1-7-bins-r2.rar
--------------------------------------------------------------------------------
/SerialPortSDK/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/SerialPortSDK/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | SerialPortSDK
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/SerialPortSDK/build.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/SerialPortSDK/src/testcase/ListPort.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | * Copyright 2015 Bin Liu (flylb1@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *******************************************************************************/
16 | package testcase;
17 |
18 | import serialportutil.AbstractSerialCommand;
19 |
20 | public class ListPort extends AbstractSerialCommand {
21 | public static void main(String[] args) {
22 | System.out.println(listPorts());
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/SerialPortSDK/src/testcase/BatchScript.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | * Copyright 2015 Bin Liu (flylb1@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *******************************************************************************/
16 | package testcase;
17 |
18 | import serialportutil.CommandBatch;
19 |
20 |
21 | public class BatchScript {
22 | public static void main(String[] args) {
23 | CommandBatch.addClazz(SimpleScript.class);
24 | CommandBatch.goScript();
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/SerialPortSDK/src/testcase/SimpleBatch.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | * Copyright 2015 Bin Liu (flylb1@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *******************************************************************************/
16 | package testcase;
17 |
18 | import serialportutil.CommandBatch;
19 |
20 | public class SimpleBatch {
21 | public static void main(String[] args) {
22 | CommandBatch.addClazz(SimpleCommand.class);
23 | CommandBatch.addClazz(ConditionCheck.class);
24 | CommandBatch.go();
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/SerialPortSDK/src/testcase/SerialFactory.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | * Copyright 2015 Bin Liu (flylb1@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *******************************************************************************/
16 | package testcase;
17 |
18 | import serialportutil.SerialPortConf;
19 |
20 | public class SerialFactory {
21 | public static SerialPortConf COM1 = new SerialPortConf("COM1", 115200, 8, 1, 0);
22 |
23 | public static SerialPortConf COM15 = new SerialPortConf("COM15", 115200, 8, 1, 0);
24 |
25 | public static SerialPortConf ttyUSB0 = new SerialPortConf("/dev/ttyUSB0", 115200, 8, 1, 0);
26 |
27 | public static SerialPortConf DEFAULT_PORT = COM15;
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/SerialPortSDK/src/testcase/SimpleScript.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | * Copyright 2015 Bin Liu (flylb1@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *******************************************************************************/
16 | package testcase;
17 |
18 | import serialportutil.AbstractSerialCommand;
19 | import serialportutil.CommandBatch;
20 |
21 | public class SimpleScript extends AbstractSerialCommand {
22 | @Override
23 | protected void setup() {
24 | // Setup serial
25 | setSerialPortConf(SerialFactory.DEFAULT_PORT);
26 |
27 | // Setup OutputStream
28 | addOutputStream(System.out);
29 |
30 | scriptFile = "./script/SimpleScript.js";
31 | }
32 |
33 | public static void main(String[] args) {
34 | CommandBatch.addClazz(SimpleScript.class);
35 | CommandBatch.goScript();
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/SerialPortSDK/src/serialportutil/StringOutputStream.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | * Copyright 2015 Bin Liu (flylb1@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *******************************************************************************/
16 | package serialportutil;
17 |
18 | import java.io.IOException;
19 | import java.io.OutputStream;
20 |
21 | public class StringOutputStream extends OutputStream {
22 | private StringBuilder stringBuilder = new StringBuilder();
23 |
24 | @Override
25 | public void write(int b) throws IOException {
26 | this.stringBuilder.append((char) b);
27 | }
28 |
29 | public String toString() {
30 | return this.stringBuilder.toString();
31 | }
32 |
33 | public String[] toStrings() {
34 | String[] items = toString().split("\n");
35 | return items;
36 | }
37 |
38 | public void clear() {
39 | stringBuilder.delete(0, stringBuilder.length());
40 | }
41 | }
--------------------------------------------------------------------------------
/SerialPortSDK/src/testcase/SimpleCommand.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | * Copyright 2015 Bin Liu (flylb1@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *******************************************************************************/
16 | package testcase;
17 |
18 | import serialportutil.AbstractSerialCommand;
19 | import serialportutil.CommandBatch;
20 |
21 | /**
22 | * Direct send command to serial
23 | * Using System.out as output
24 | *
25 | */
26 | public class SimpleCommand extends AbstractSerialCommand {
27 | @Override
28 | protected void setup() {
29 | // Setup serial
30 | setSerialPortConf(SerialFactory.DEFAULT_PORT);
31 | addOutputStream(System.out);
32 | }
33 |
34 | @Override
35 | protected void processCommand() throws Exception {
36 | // Send command "ps" to serial port,
37 | sendCommand(0x3, 100, 2);
38 | sendCommand("ps | grep sh\n", 100, 10);
39 | }
40 |
41 | public static void main(String[] args) {
42 | CommandBatch.addClazz(SimpleCommand.class);
43 | CommandBatch.go();
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/SerialPortSDK/src/testcase/SimpleConsole.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | * Copyright 2015 Bin Liu (flylb1@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *******************************************************************************/
16 | package testcase;
17 |
18 | import serialportutil.AbstractSerialCommand;
19 | import serialportutil.CommandBatch;
20 |
21 | /**
22 | * Simple console sample
23 | * System console as input and output
24 | *
25 | */
26 | public class SimpleConsole extends AbstractSerialCommand {
27 | @Override
28 | protected void setup() {
29 | // Setup serial
30 | setSerialPortConf(SerialFactory.DEFAULT_PORT);
31 |
32 | // Set output with time stamp
33 | // setSerialPortTimePrefix(true);
34 |
35 | // setSerialPortCRAsLFCR(true);
36 |
37 | // System out as output
38 | addOutputStream(System.out);
39 | }
40 |
41 | @Override
42 | protected void processCommand() throws Exception {
43 | // Add console input support
44 | addConsoleInputSupport();
45 | }
46 |
47 | public static void main(String[] args) {
48 | CommandBatch.addClazz(SimpleConsole.class);
49 | CommandBatch.go();
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/SerialPortSDK/src/testcase/SimpleFileLog.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | * Copyright 2015 Bin Liu (flylb1@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *******************************************************************************/
16 | package testcase;
17 |
18 | import java.io.File;
19 | import java.io.FileNotFoundException;
20 | import java.io.FileOutputStream;
21 |
22 | import serialportutil.AbstractSerialCommand;
23 | import serialportutil.CommandBatch;
24 |
25 | /**
26 | * Direct send command to serial
27 | * Using System.out as output
28 | *
29 | */
30 | public class SimpleFileLog extends AbstractSerialCommand {
31 | @Override
32 | protected void setup() {
33 | // Setup serial
34 | setSerialPortConf(SerialFactory.DEFAULT_PORT);
35 |
36 | // Add file output stream,serial output redirect to file
37 | try {
38 | addOutputStream(new FileOutputStream(new File("./log.txt")));
39 | } catch (FileNotFoundException e) {
40 | e.printStackTrace();
41 | }
42 | }
43 |
44 | @Override
45 | protected void processCommand() throws Exception {
46 | // Send command "ps" to serial port,
47 | sendCommand("ps |grep sh\n", 100, 1);
48 | }
49 |
50 | public static void main(String[] args) {
51 | CommandBatch.addClazz(SimpleFileLog.class);
52 | CommandBatch.go();
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/SerialPortSDK/src/serialportutil/SerialPortConf.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | * Copyright 2015 Bin Liu (flylb1@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *******************************************************************************/
16 | package serialportutil;
17 |
18 | public class SerialPortConf /* implements IPort */{
19 | private String portname;
20 | private int speed;
21 | private int databit;
22 | private int stopbit;
23 | private int parityBit;
24 |
25 | public SerialPortConf(String portname, int speed, int databit, int stopbit, int parityBit) {
26 | super();
27 | this.databit = databit;
28 | this.parityBit = parityBit;
29 | this.portname = portname;
30 | this.speed = speed;
31 | this.stopbit = stopbit;
32 | }
33 |
34 | public String getPortname() {
35 | return portname;
36 | }
37 |
38 | public int getSpeed() {
39 | return speed;
40 | }
41 |
42 | public int getDatabit() {
43 | return databit;
44 | }
45 |
46 | public int getStopbit() {
47 | return stopbit;
48 | }
49 |
50 | public int getParityBit() {
51 | return parityBit;
52 | }
53 |
54 | @Override
55 | public String toString() {
56 | return "Portname:" + getPortname() + " Speed:" + getSpeed() + " Databit:" + getDatabit() + " Stopbit:" + getStopbit()
57 | + " ParityBit:" + getParityBit();
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | SerialPort SDK (Windows, Linux, MAC OS)
2 |
3 | SerialPort SDK is a professional Java serial port SDK. It provides a simple communication interface to connect any serial port devices.
4 |
5 | * You can use it to implement or debug serial protocol.
6 | * You can send and capture data.
7 | * You can change communication channel’s settings easily including the setting for non-standard baudrate.
8 | * You can write Java code to automate some specific tasks.
9 | * You can perform JavaScript to send command.
10 |
11 |
12 | SerialPort SDK can be successfully used for:
13 | * Interception and analysis of data transferring between any serial devices and Windows applications.
14 | * Debugging any serial software or hardware.
15 | * Development of serial peripheral hardware.
16 | * Development of serial device drivers.
17 | * Researching the functionality of any third-party software and hardware.
18 | * Implementing, debugging or testing serial protocol between device and device driver.
19 |
20 | SerialPort SDK can be used by:
21 | * Software developers
22 | * Hardware engineers
23 | * Programmers
24 | * Testers
25 | * Science technicians
26 | * Lab experts
27 | * University students
28 |
29 | This SDK includes the RXTX library.
30 |
31 | ###Setup
32 | RXTX 2.1-7
33 | -- Please uncompress rxtx-2.1-7-bins-r2.rar
34 |
35 | Window32
36 | - rxtx-2.1-7-bins-r2/Windows/i368-mingw32/rxtxSerial.dll copy to system path(e.g. c:\windows\system32\)
37 |
38 | Window64
39 | - [mfz-rxtx-2.2-20081207-win-x64](https://bitbucket.org/jlauer/mfz-cdn/downloads/mfz-rxtx-2.2-20081207-win-x64.zip)
40 |
41 | Linux32
42 | - rxtx-2.1-7-bins-r2/Linux/i686-unknown-linux-gnu/librxtxSerial.so copy to system path(e.g. /lib)
43 |
44 | Linux64
45 | - rxtx-2.1-7-bins-r2/Linux/x86_64-unknown-linux-gnu/librxtxSerial.so copy to system path(e.g. /lib)
46 |
47 | Mac
48 | - rxtx-2.1-7-bins-r2/Mac_OS_X/librxtxSerial.jnilib copy to system path
49 |
50 | ###Wiki
51 | [Link](https://github.com/flylb1/JavaSerialPort/wiki)
52 |
53 | ### License
54 | JavaSerialPort is licensed under the [Apache 2 License](http://www.apache.org/licenses/LICENSE-2.0.html), which means you can use it for free and without strings attached in commercial or non-commercial projects.
55 |
56 | ### Class Diagram
57 | 
58 |
--------------------------------------------------------------------------------
/SerialPortSDK/src/testcase/ConditionCheck.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | * Copyright 2015 Bin Liu (flylb1@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *******************************************************************************/
16 | package testcase;
17 |
18 | import serialportutil.AbstractSerialCommand;
19 | import serialportutil.CommandBatch;
20 | import serialportutil.StringOutputStream;
21 |
22 | /**
23 | * Condition check
24 | * 1. Send command 'ls /system/bin'
25 | * 2. Check result
26 | * 3. If result include 'ps', Send command 'ps |grep sh'
27 | *
28 | */
29 | public class ConditionCheck extends AbstractSerialCommand {
30 | private StringOutputStream stringOutput = new StringOutputStream();
31 |
32 | @Override
33 | protected void setup() {
34 | setSerialPortConf(SerialFactory.DEFAULT_PORT);
35 | addOutputStream(stringOutput);
36 | }
37 |
38 | @Override
39 | protected void processCommand() throws Exception {
40 |
41 | sendCommand("ls /system/bin\n", 1000, 1);
42 | // Get result
43 | String[] items = stringOutput.toStrings();
44 | boolean continueProcess = false;
45 | for (String item : items) {
46 | if (item.indexOf("ps") >= 0) {
47 | continueProcess = true;
48 | System.out.println("Has 'ps' command !");
49 | break;
50 | }
51 | }
52 | if (!continueProcess) {
53 | return;
54 | }
55 |
56 | // Run command 'ps |grep sh' and get new result
57 | System.out.println("Execute 'ps |grep sh' command !");
58 | stringOutput.clear();
59 | sendCommand("ps |grep sh\n", 1000, 1);
60 | System.out.println(stringOutput.toString());
61 | }
62 |
63 | public static void main(String[] args) {
64 | CommandBatch.addClazz(ConditionCheck.class);
65 | CommandBatch.go();
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/SerialPortSDK/src/serialportutil/CommandBatch.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | * Copyright 2015 Bin Liu (flylb1@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *******************************************************************************/
16 | package serialportutil;
17 |
18 | import java.util.ArrayList;
19 | import java.util.List;
20 |
21 | public class CommandBatch {
22 | protected static List> clazzes = new ArrayList>();
23 |
24 | public static void addClazz(Class> clazz) {
25 | clazzes.add(clazz);
26 | }
27 |
28 | public static void go() {
29 | if (clazzes.size() == 0) {
30 | return;
31 | }
32 | try {
33 | try {
34 | for (Class> commandClazz : clazzes) {
35 | Object ins = commandClazz.newInstance();
36 | if (ins instanceof AbstractSerialCommand) {
37 | System.out.println("Start>>" + ins.getClass());
38 | ((AbstractSerialCommand) ins).start();
39 | ((AbstractSerialCommand) ins).join();
40 | System.out.println("End<<<<" + ins.getClass());
41 | System.out.println();
42 | }
43 | }
44 | } catch (InterruptedException e) {
45 | e.printStackTrace();
46 | }
47 | } catch (InstantiationException e) {
48 | e.printStackTrace();
49 | } catch (IllegalAccessException e) {
50 | e.printStackTrace();
51 | }
52 | }
53 |
54 | public static void goScript() {
55 | if (clazzes.size() == 0) {
56 | return;
57 | }
58 | try {
59 | for (Class> commandClazz : clazzes) {
60 | Object ins = commandClazz.newInstance();
61 | if (ins instanceof AbstractSerialCommand) {
62 | ((AbstractSerialCommand) ins).runScript();
63 | }
64 | }
65 | } catch (InstantiationException e) {
66 | e.printStackTrace();
67 | } catch (IllegalAccessException e) {
68 | e.printStackTrace();
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/SerialPortSDK/src/testcase/SimpleServer.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | * Copyright 2015 Bin Liu (flylb1@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *******************************************************************************/
16 | package testcase;
17 |
18 | import java.io.IOException;
19 | import java.io.InputStream;
20 | import java.net.ServerSocket;
21 | import java.net.Socket;
22 |
23 | import serialportutil.AbstractSerialCommand;
24 | import serialportutil.CommandBatch;
25 |
26 | class ClientServiceThread extends Thread {
27 | SimpleServer simpleServer;
28 | Socket clientSocket;
29 | int clientID = -1;
30 | boolean running = true;
31 |
32 | ClientServiceThread(SimpleServer simpleServer, Socket s, int i) {
33 | this.simpleServer = simpleServer;
34 | this.clientSocket = s;
35 | this.clientID = i;
36 | }
37 |
38 | public void run() {
39 | try {
40 | InputStream in = clientSocket.getInputStream();
41 | simpleServer.addOutputStream(clientSocket.getOutputStream());
42 | int cmd;
43 | try {
44 | while ((running && (cmd = in.read()) > 0)) {
45 | simpleServer.sendCommand(cmd, 0);
46 | }
47 | } catch (IOException e) {
48 | e.printStackTrace();
49 | }
50 | } catch (Exception e) {
51 | e.printStackTrace();
52 | }
53 | }
54 | }
55 |
56 | public class SimpleServer extends AbstractSerialCommand {
57 | protected void setup() {
58 | // Setup serial
59 | setSerialPortConf(SerialFactory.DEFAULT_PORT);
60 |
61 | // Set serial port,replace '\r\n' with '\n' (telnet)
62 | setSerialPortCRAsLFCR(true);
63 | }
64 |
65 | @Override
66 | protected void processCommand() throws Exception {
67 | ServerSocket serverSocket = new ServerSocket(88);
68 | int id = 0;
69 | while (true) {
70 | Socket clientSocket = serverSocket.accept();
71 | ClientServiceThread cliThread = new ClientServiceThread(this, clientSocket, id++);
72 | cliThread.start();
73 | }
74 | }
75 |
76 | public static void main(String[] args) throws Exception {
77 | CommandBatch.addClazz(SimpleServer.class);
78 | CommandBatch.go();
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/SerialPortSDK/src/serialportutil/AbstractSerialCommand.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | * Copyright 2015 Bin Liu (flylb1@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *******************************************************************************/
16 | package serialportutil;
17 |
18 | import gnu.io.CommDriver;
19 | import gnu.io.CommPortIdentifier;
20 |
21 | import java.io.BufferedReader;
22 | import java.io.FileReader;
23 | import java.io.IOException;
24 | import java.io.InputStreamReader;
25 | import java.io.OutputStream;
26 | import java.util.ArrayList;
27 | import java.util.Enumeration;
28 | import java.util.List;
29 |
30 | import javax.script.ScriptEngine;
31 |
32 | class ConsoleInput extends Thread {
33 | private volatile boolean stop = false;
34 |
35 | private MySerialPort serialPort;
36 |
37 | public ConsoleInput(MySerialPort serialPort) {
38 | super();
39 | this.serialPort = serialPort;
40 | super.setName("ConsoleInput");
41 | }
42 |
43 | public void run() {
44 | BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
45 | int cmd;
46 | try {
47 | while ((!stop && (cmd = in.read()) > 0)) {
48 | SerialPortUtil.sendCommand(serialPort, cmd, 0);
49 | }
50 | } catch (IOException e) {
51 | e.printStackTrace();
52 | }
53 | }
54 | }
55 |
56 | class MyOutputStream extends OutputStream {
57 | private List outList;
58 |
59 | public List getOutList() {
60 | return outList;
61 | }
62 |
63 | public void setOutList(List consoleList) {
64 | this.outList = consoleList;
65 | }
66 |
67 | public synchronized void addOutputStream(OutputStream out) {
68 | if (outList == null) {
69 | this.outList = new ArrayList();
70 | }
71 |
72 | boolean found = false;
73 | for (int i = 0; i < outList.size(); i++) {
74 | if (outList.get(i).equals(out)) {
75 | found = true;
76 | }
77 | }
78 | if (found == false) {
79 | // log.info("add outputstream:" + out);
80 | outList.add(out);
81 | }
82 | }
83 |
84 | public synchronized void removeOutputStream(OutputStream out) {
85 | if (outList == null)
86 | return;
87 |
88 | boolean found = false;
89 | int pos = 0;
90 | for (int i = 0; i < outList.size(); i++) {
91 | if (outList.get(i).equals(out)) {
92 | found = true;
93 | pos = i;
94 | }
95 | }
96 | if (found == true) {
97 | // log.info("remove outputstream:" + out);
98 | outList.remove(pos);
99 | }
100 | }
101 |
102 | public MyOutputStream() {
103 | super();
104 | setOutList(new ArrayList());
105 | }
106 |
107 | public void write(int b) throws IOException {
108 | if (outList == null || outList.size() == 0)
109 | return;
110 | for (int i = 0; i < outList.size(); i++) {
111 | OutputStream os = null;
112 | try {
113 | os = (OutputStream) outList.get(i);
114 | if (SerialPortUtil.REPLACE_CR_WITH_LFCR && b == '\n') {
115 | os.write('\r');
116 | os.write('\n');
117 | } else {
118 | os.write(b);
119 | }
120 | // System.out.println(b);
121 | if (b == 10 && SerialPortUtil.TIME_PREFIX) {
122 | os.write(SerialPortUtil.now().getBytes());
123 | }
124 |
125 | } catch (IOException e) {
126 | removeOutputStream(os);
127 | System.out.println(e);
128 | }
129 | }
130 | }
131 |
132 | public void write(byte[] b) throws IOException {
133 | for (int i = 0; i < b.length; i++) {
134 | write(b[i]);
135 | }
136 | }
137 |
138 | @Override
139 | public void flush() throws IOException {
140 | if (outList == null || outList.size() == 0)
141 | return;
142 | for (int i = 0; i < outList.size(); i++) {
143 | try {
144 | ((OutputStream) outList.get(i)).flush();
145 | } catch (IOException e) {
146 | System.out.println(e);
147 | }
148 | }
149 | super.flush();
150 | }
151 |
152 | }
153 |
154 | public abstract class AbstractSerialCommand extends Thread {
155 | static {
156 | try {
157 | String driverName = "gnu.io.RXTXCommDriver";
158 | CommDriver commDriver = (CommDriver) Class.forName(driverName).newInstance();
159 | commDriver.initialize();
160 | } catch (InstantiationException e) {
161 | e.printStackTrace();
162 | } catch (IllegalAccessException e) {
163 | e.printStackTrace();
164 | } catch (ClassNotFoundException e) {
165 | e.printStackTrace();
166 | }
167 | }
168 |
169 | protected String scriptFile;
170 | protected MySerialPort serialPort;
171 | protected SerialPortConf serialPortConf;
172 | private List outList = new ArrayList();
173 |
174 | private ConsoleInput consoleInput = null;
175 |
176 | private void removeOutputStreams() {
177 | SerialPortUtil.removeOutputStreams(serialPort);
178 | }
179 |
180 | private void processScript(String scriptFile) throws Exception {
181 | ScriptEngine engine = SerialPortUtil.initScriptEngine(this);
182 | FileReader reader = new FileReader(scriptFile);
183 | engine.eval(reader);
184 | reader.close();
185 | }
186 |
187 | private boolean preProcess() {
188 | /* connect to serialPort and add default outputstrem */
189 | serialPort = SerialPortUtil.connect(serialPortConf);
190 | if (serialPort == null) {
191 | return false;
192 | }
193 | if (serialPort.getPortState() == -1/* serialPort.DISCONNECT */) {
194 | System.out.println("Can not connect serialPort\r\n" + serialPortConf);
195 | serialPort = null;
196 | return false;
197 | }
198 | MyOutputStream myOutputStream = new MyOutputStream();
199 | serialPort.setMyOutputStream(myOutputStream);
200 | for (OutputStream out : outList) {
201 | SerialPortUtil.addOutputStream(serialPort, out);
202 | }
203 | return true;
204 | }
205 |
206 | private void afterProcess() {
207 | if (consoleInput != null) {
208 | try {
209 | consoleInput.join();
210 | } catch (InterruptedException e) {
211 | e.printStackTrace();
212 | }
213 | }
214 |
215 | // close OutputStreams
216 | removeOutputStreams();
217 |
218 | /* Disconnect from serialPort */
219 | if (serialPort != null) {
220 | SerialPortUtil.disConnect(serialPort);
221 | }
222 | }
223 |
224 | protected void setup() {
225 | }
226 |
227 | protected void addConsoleInputSupport() {
228 | consoleInput = new ConsoleInput(serialPort);
229 | consoleInput.start();
230 | }
231 |
232 | protected void processCommand() throws Exception {
233 | }
234 |
235 | public AbstractSerialCommand() {
236 | super();
237 | }
238 |
239 | public void addOutputStream(OutputStream out) {
240 | if (serialPort == null) {
241 | outList.add(out);
242 | } else {
243 | SerialPortUtil.addOutputStream(serialPort, out);
244 | }
245 | }
246 |
247 | public void setSerialPortConf(SerialPortConf serialPortConf) {
248 | this.serialPortConf = serialPortConf;
249 | }
250 |
251 | public void setSerialPortConf(String portname, int speed, int databit, int stopbit, int parityBit) {
252 | this.serialPortConf = // SerialPortConf.build(portname, speed, databit, stopbit, parityBit);
253 | new SerialPortConf(portname, speed, databit, stopbit, parityBit);
254 | }
255 |
256 | /**
257 | * @param flag
258 | * Add date time prefix on output
259 | */
260 | public void setSerialPortTimePrefix(boolean flag) {
261 | SerialPortUtil.TIME_PREFIX = flag;
262 | }
263 |
264 | public void setSerialPortCRAsLFCR(boolean flag) {
265 | SerialPortUtil.REPLACE_CR_WITH_LFCR = flag;
266 | }
267 |
268 | public void sendCommand(String cmd, int delay, int repeat) {
269 | SerialPortUtil.sendCommand(serialPort, cmd, delay, repeat);
270 | }
271 |
272 | public void sendCommand(String cmd, int delay) {
273 | SerialPortUtil.sendCommand(serialPort, cmd, delay);
274 | }
275 |
276 | public void sendCommand(int cmd, int delay, int repeat) {
277 | SerialPortUtil.sendCommand(serialPort, cmd, delay, repeat);
278 | }
279 |
280 | public void sendCommand(int cmd, int delay) {
281 | SerialPortUtil.sendCommand(serialPort, cmd, delay, 1);
282 | }
283 |
284 | public void run() {
285 | try {
286 | setup();
287 | preProcess();
288 | processCommand();
289 | Thread.sleep(500);
290 | } catch (Exception e) {
291 | System.out.println(e);
292 | } finally {
293 | afterProcess();
294 | }
295 | }
296 |
297 | public void runScript() {
298 | try {
299 | setup();
300 | preProcess();
301 | processScript(scriptFile);
302 | Thread.sleep(500);
303 | } catch (Exception e) {
304 | System.out.println(e);
305 | } finally {
306 | afterProcess();
307 | }
308 | }
309 |
310 | public static List listPorts() {
311 | Enumeration> portEnum = CommPortIdentifier.getPortIdentifiers();
312 | List list = new ArrayList();
313 | while (portEnum.hasMoreElements()) {
314 | CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
315 | list.add(currPortId.getName());
316 | }
317 | return list;
318 | }
319 | }
320 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/SerialPortSDK/src/serialportutil/SerialPortUtil.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | * Copyright 2015 Bin Liu (flylb1@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *******************************************************************************/
16 | package serialportutil;
17 |
18 | import gnu.io.CommPortIdentifier;
19 | import gnu.io.PortInUseException;
20 | import gnu.io.SerialPort;
21 | import gnu.io.UnsupportedCommOperationException;
22 |
23 | import java.io.IOException;
24 | import java.io.InputStream;
25 | import java.io.OutputStream;
26 | import java.io.PrintStream;
27 | import java.text.SimpleDateFormat;
28 | import java.util.Calendar;
29 | import java.util.Enumeration;
30 | import java.util.List;
31 | import java.util.Vector;
32 |
33 | import javax.script.ScriptEngine;
34 | import javax.script.ScriptEngineManager;
35 | import javax.script.ScriptException;
36 |
37 | class SerialWriter extends Thread {
38 | private OutputStream out;
39 | private volatile boolean stop = false;
40 | private Vector dataVector = new Vector();
41 |
42 | public SerialWriter(OutputStream out) {
43 | setName("SerialWriter");
44 | this.out = out;
45 | }
46 |
47 | public void write(int c) {
48 | dataVector.add(c);
49 | }
50 |
51 | public void setStop(boolean stop) {
52 | this.stop = stop;
53 | }
54 |
55 | @Override
56 | public void run() {
57 | try {
58 | while (!stop) {// while not stop ,do receive command
59 | if ((dataVector.size() > 0)) {
60 | out.write(dataVector.remove(0));
61 | }
62 | Thread.sleep(3);
63 | }
64 | } catch (IOException e) {
65 | e.printStackTrace();
66 | } catch (InterruptedException e) {
67 | e.printStackTrace();
68 | }
69 | // System.out.println("SerialWriter exit;");
70 | }
71 | }
72 |
73 | class SerialReader extends Thread {
74 | private volatile boolean stop = false;
75 | private MySerialPort mySerialPort;
76 | private InputStream in;
77 |
78 | public SerialReader(MySerialPort mySerialPort) {
79 | setName("SerialReader");
80 | this.mySerialPort = mySerialPort;
81 | this.in = mySerialPort.getPortInStream();
82 | }
83 |
84 | public void setStop(boolean stop) {
85 | this.stop = stop;
86 | }
87 |
88 | public void run() {
89 | byte[] buffer = new byte[1024];
90 | try {
91 | int len = 0;
92 | synchronized (buffer) {
93 | while (!stop) {// while not stop ,do receive command
94 | if ((len = this.in.read(buffer)) > -1) {
95 | for (int i = 0; i < len; i++) {
96 | if ('\r' == (char) buffer[i]) {
97 | if (!SerialPortUtil.IGNORE_OUTPUT_CR) {// skip \r
98 | mySerialPort.consolePrint(buffer[i]);
99 | }
100 | } else {
101 | mySerialPort.consolePrint(buffer[i]);
102 | }
103 | }
104 | }
105 | Thread.sleep(100);
106 | }
107 |
108 | }
109 | } catch (Exception e) {
110 | System.out.println(e);
111 | }
112 | // System.out.println("SerialReader exit;");
113 | }
114 | }
115 |
116 | class MySerialPort {
117 | private MyOutputStream myOutputStream;
118 |
119 | private int CONNECTED = 0;
120 |
121 | private int DISCONNECT = -1;
122 |
123 | private String portName;
124 |
125 | private int portSpeed;
126 |
127 | private int portDataBit;
128 |
129 | private int portStopBit;
130 |
131 | private int portParityBit;
132 |
133 | private InputStream portInStream;
134 |
135 | private OutputStream portOutStream;
136 |
137 | private SerialPort serialPort;
138 |
139 | private int portState;
140 |
141 | private SerialWriter serialWriterThread;
142 |
143 | private SerialReader serialReaderThread;
144 |
145 | public String getPortName() {
146 | return portName;
147 | }
148 |
149 | public void setPortName(String portName) {
150 | this.portName = portName;
151 | }
152 |
153 | public int getPortSpeed() {
154 | return portSpeed;
155 | }
156 |
157 | public void setPortSpeed(int portSpeed) {
158 | this.portSpeed = portSpeed;
159 | }
160 |
161 | public int getPortDataBit() {
162 | return portDataBit;
163 | }
164 |
165 | public void setPortDataBit(int portDataBit) {
166 | this.portDataBit = portDataBit;
167 | }
168 |
169 | public int getPortStopBit() {
170 | return portStopBit;
171 | }
172 |
173 | public void setPortStopBit(int portStopBit) {
174 | this.portStopBit = portStopBit;
175 | }
176 |
177 | public int getPortParityBit() {
178 | return portParityBit;
179 | }
180 |
181 | public void setPortParityBit(int portParityBit) {
182 | this.portParityBit = portParityBit;
183 | }
184 |
185 | public OutputStream getPortOutStream() {
186 | return portOutStream;
187 | }
188 |
189 | public int getPortState() {
190 | return portState;
191 | }
192 |
193 | public void setPortState(int portState) {
194 | this.portState = portState;
195 | }
196 |
197 | public MyOutputStream getMyOutputStream() {
198 | return myOutputStream;
199 | }
200 |
201 | public void setMyOutputStream(MyOutputStream myOutputStream) {
202 | this.myOutputStream = myOutputStream;
203 | }
204 |
205 | public SerialWriter getSerialWriterThread() {
206 | return serialWriterThread;
207 | }
208 |
209 | public InputStream getPortInStream() {
210 | return portInStream;
211 | }
212 |
213 | MySerialPort(String name) {
214 | super();
215 | this.portName = name;
216 | this.setPortState(DISCONNECT);
217 | }
218 |
219 | public String toString() {
220 | StringBuffer sb = new StringBuffer();
221 | sb.append("Name[" + this.getPortName() + "] ");
222 | sb.append("DataBit[" + this.getPortDataBit() + "] ");
223 | sb.append("PortSpeed[" + this.getPortSpeed() + "] ");
224 | sb.append("ParityBit[" + this.getPortParityBit() + "] ");
225 | sb.append("StopBit[" + this.getPortStopBit() + "] ");
226 |
227 | return sb.toString();
228 | }
229 |
230 | public void consolePrint(int v) {
231 | if (myOutputStream != null) {
232 | try {
233 | myOutputStream.write(v);
234 | } catch (IOException e) {
235 | e.printStackTrace();
236 | }
237 | }
238 |
239 | }
240 |
241 | public void consoleFlush() {
242 | if (myOutputStream != null) {
243 | try {
244 | myOutputStream.flush();
245 | } catch (IOException e) {
246 | e.printStackTrace();
247 | }
248 | }
249 | }
250 |
251 | public CommPortIdentifier getPort(String name) {
252 | Enumeration> ports = CommPortIdentifier.getPortIdentifiers();
253 | while (ports.hasMoreElements()) {
254 | CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
255 | if (port.getName().equals(name)) {
256 | return port;
257 | }
258 | }
259 | return null;
260 | }
261 |
262 | public void connect() {
263 | CommPortIdentifier port = getPort(this.portName);
264 | if (port != null) {
265 | try {
266 | System.out.println("Connecting to " + this.portName //
267 | + " [speed:" + this.portSpeed + "]" //
268 | + " [databit:" + this.portDataBit + "] [stopbit:" + this.portStopBit + "] [paritybit:" + this.portParityBit + "]");
269 |
270 | serialPort = (SerialPort) port.open("Java Serial", 10000);
271 | serialPort.setSerialPortParams(this.portSpeed, this.portDataBit, this.portStopBit, this.portParityBit);
272 |
273 | serialPort.notifyOnDataAvailable(true);
274 | serialPort.notifyOnBreakInterrupt(true);
275 | serialPort.notifyOnOutputEmpty(true);
276 | serialPort.enableReceiveTimeout(30);
277 |
278 | try {
279 | portInStream = serialPort.getInputStream();
280 | portOutStream = serialPort.getOutputStream();
281 | serialWriterThread = new SerialWriter(portOutStream);
282 | serialWriterThread.start();
283 |
284 | // SerialReader
285 | serialReaderThread = new SerialReader(this);
286 | serialReaderThread.start();
287 |
288 | this.portState = CONNECTED;
289 | System.out.println("Connected!");
290 |
291 | } catch (IOException e) {
292 | this.portState = DISCONNECT;
293 | System.out.println("Can't open input stream: write-only");
294 | }
295 |
296 | } catch (PortInUseException e) {
297 | this.portState = DISCONNECT;
298 | System.out.println(e.getMessage());
299 | } catch (UnsupportedCommOperationException e) {
300 | this.portState = DISCONNECT;
301 | System.out.println(e.getMessage());
302 | } finally {
303 | }
304 | } else {
305 | }
306 | }
307 |
308 | public void disConnect() {
309 | if (serialPort == null) {
310 | System.out.println("serialPort is null");
311 | return;
312 | }
313 |
314 | if (this.serialPort != null && this.portState == CONNECTED) {
315 | try {
316 | this.portState = DISCONNECT;
317 | serialWriterThread.setStop(true);
318 | serialReaderThread.setStop(true);
319 | serialWriterThread.join();
320 | serialReaderThread.join();
321 | this.portInStream.close();
322 | this.portOutStream.close();
323 |
324 | this.portInStream = null;
325 | this.portOutStream = null;
326 | System.out.println("Disconnected from " + this.portName);
327 |
328 | serialPort.close();
329 | serialPort = null;
330 | } catch (IOException e) {
331 | System.out.println(e.getMessage());
332 | } catch (InterruptedException e) {
333 | e.printStackTrace();
334 | }
335 | }
336 | }
337 | }
338 |
339 | class SerialPortUtil {
340 |
341 | private static PrintStream systemOut;
342 | public static boolean REPLACE_CR_WITH_LFCR = false;
343 | public static boolean TIME_PREFIX = false;
344 | public static boolean IGNORE_OUTPUT_CR = true;
345 |
346 | public static MySerialPort connect(SerialPortConf serialPortConf) {
347 | if (serialPortConf == null) {
348 | return null;
349 | }
350 | MySerialPort serialPort = new MySerialPort(serialPortConf.getPortname());
351 | serialPort.setPortName(serialPortConf.getPortname());
352 | serialPort.setPortSpeed(serialPortConf.getSpeed());
353 | serialPort.setPortDataBit(serialPortConf.getDatabit());
354 | serialPort.setPortStopBit(serialPortConf.getStopbit());
355 | serialPort.setPortParityBit(serialPortConf.getParityBit());
356 |
357 | serialPort.connect();
358 | return serialPort;
359 | }
360 |
361 | public static void disConnect(MySerialPort serialPort) {
362 | if (serialPort != null) {
363 | serialPort.disConnect();
364 | serialPort = null;
365 | }
366 | }
367 |
368 | public static void sendCommand(MySerialPort serialPort, String cmd, int delay, int repeat) {
369 | for (int i = 0; i < repeat; i++) {
370 | sendCommand(serialPort, cmd, delay);
371 | }
372 | }
373 |
374 | public static void sendCommand(MySerialPort serialPort, String cmd, int delay) {
375 | if (serialPort != null) {
376 | try {
377 | SerialWriter serialPortWriterThread = serialPort.getSerialWriterThread();
378 | byte[] databytes = cmd.getBytes();
379 | for (int i = 0; i < databytes.length; i++) {
380 | serialPortWriterThread.write(databytes[i]);
381 | }
382 |
383 | if (delay > 0) {
384 | Thread.sleep(delay);
385 | }
386 | } catch (Exception e) {
387 | e.printStackTrace();
388 | }
389 | }
390 | }
391 |
392 | public static void sendCommand(MySerialPort serialPort, int cmd, int delay) {
393 | sendCommand(serialPort, cmd, delay, 1);
394 | }
395 |
396 | public static void sendCommand(MySerialPort serialPort, int cmd, int delay, int repeat) {
397 | for (int i = 0; i < repeat; i++) {
398 | if (serialPort != null) {
399 | try {
400 | SerialWriter serialPortWriterThread = serialPort.getSerialWriterThread();
401 | serialPortWriterThread.write(cmd);
402 | // serialPort.getPortOutStream().write(cmd);// send to serial port
403 | if (delay > 0) {
404 | Thread.sleep(delay);
405 | }
406 | } catch (Exception e) {
407 | e.printStackTrace();
408 | }
409 | }
410 | }
411 | }
412 |
413 | public static void addOutputStream(MySerialPort serialPort, OutputStream out) {
414 | if (serialPort == null) {
415 | System.out.println("Add OutputStream error");
416 | return;
417 | }
418 | MyOutputStream myOutputStream = serialPort.getMyOutputStream();
419 |
420 | List list = myOutputStream.getOutList();
421 | if (!list.contains(out)) {
422 | myOutputStream.getOutList().add(out);
423 | if (out == System.out) {
424 | systemOut = System.out; // backup
425 | }
426 | }
427 | }
428 |
429 | public static void removeOutputStreams(MySerialPort serialPort) {
430 | if (serialPort == null) {
431 | System.out.println("Add OutputStream error");
432 | return;
433 | }
434 | MyOutputStream myOutputStream = serialPort.getMyOutputStream();
435 |
436 | try {
437 | List list = myOutputStream.getOutList();
438 | for (OutputStream out : list) {
439 | if (systemOut == out) {
440 |
441 | } else {
442 | out.close();
443 | System.out.println("Close:" + out.getClass());
444 | }
445 | }
446 | } catch (IOException e) {
447 | e.printStackTrace();
448 | }
449 | }
450 |
451 | public static final String DATE_FORMAT_NOW = "yyyy.MM.dd HH:mm:ss ";
452 |
453 | public static String now() {
454 | Calendar cal = Calendar.getInstance();
455 | SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
456 | return sdf.format(cal.getTime());
457 | }
458 |
459 | private static ScriptEngine engine = null;
460 | static {
461 | ScriptEngineManager manager = new ScriptEngineManager();
462 | engine = manager.getEngineByName("js");
463 |
464 | try {
465 | /* add file log */
466 | engine.eval("function LOG_FILE(a) { serialCommand.addFileLog(a); }");
467 | /* script datetimeprefix */
468 | engine.eval("function SHOW_DATE_TIME(a) { serialCommand.showDateTime(a) }");
469 | /* script println */
470 | engine.eval("function PRINT_LN(a) { serialCommand.println(a); }");
471 |
472 | engine.eval("function SEND_CMD1(a) { serialCommand.sendCommand(a); }");
473 | engine.eval("function SEND_CMD2(a, b) { serialCommand.sendCommand(a,b); }");
474 | engine.eval("function SEND_CMD3(a, b, c) { serialCommand.sendCommand(a,b,c);}");
475 |
476 | String funcSetSerialPortConfigure = //
477 | "function SET_SERIAL( portName, portSpeed, portDataBit, portStopBit, portParityBit){\r\n"
478 | + " serialCommand.setSerialPortConf(portName,portSpeed,portDataBit,portStopBit,portParityBit);\r\n" //
479 | + "}"//
480 | + "function SEND() {\r\n" + //
481 | " if (arguments.length == 1)\r\n" + //
482 | " {\r\n" + //
483 | " SEND_CMD1(arguments[0]);\r\n" + //
484 | " }\r\n" + //
485 | " if (arguments.length == 2)\r\n" + //
486 | " {\r\n" + //
487 | " SEND_CMD2(arguments[0],arguments[1]);\r\n" + //
488 | " }\r\n" + //
489 | " if (arguments.length == 3)\r\n" + //
490 | " {\r\n" + //
491 | " SEND_CMD3(arguments[0],arguments[1],arguments[2]);\r\n" + //
492 | " }\r\n" + //
493 | "}";
494 |
495 | engine.eval(funcSetSerialPortConfigure);
496 |
497 | } catch (ScriptException e) {
498 | e.printStackTrace();
499 | }
500 | }
501 |
502 | public static ScriptEngine initScriptEngine(AbstractSerialCommand serialCommand) throws ScriptException {
503 | engine.put("serialCommand", serialCommand);
504 | engine.put("SerialPortUnit", serialCommand.serialPortConf);
505 | return engine;
506 | }
507 | }
508 |
--------------------------------------------------------------------------------