EVで起動しているサーバープログラムに接続し、データを送受信します。
事前にEV3とこのプログラムを動かすPCをペアリングしておいてください。
BlueCovをビルドパスに追加してください。
動作確認環境
- Surfece Pro 4
- Windows 10 pro 64bit
- bluecov-2.1.0.jar
- EV3 lejos 0.9.1 beta
クライアントプログラム
BtPcClient.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connection;
import javax.microedition.io.Connector;
import javax.microedition.io.InputConnection;
import javax.microedition.io.OutputConnection;
public class BtPcClient {
public static void main(String[] args) throws Exception {
int sendMessageNo = 2; // 送信する番号
int recvMessageNo = 3; // 受信する番号
// サーバー側EV3のBluetoothのMACアドレス、チャネル=1
String connectionURL = "btspp://001653999999:1";
System.out.println("Connecting...");
// サーバー側のデバイスからコネクションを取得する
Connection connection = Connector.open(connectionURL);
if (connection == null) {
System.out.println("Connect fail");
System.exit(1);
}
System.out.println("Connected");
// 読み、書きのストリームを取得する
OutputStream os = ((OutputConnection)connection).openOutputStream();
InputStream is = ((InputConnection)connection).openInputStream();
// メッセージを送信する
System.out.println("Sending...");
send(os, sendMessageNo);
// メッセージを受信する
System.out.println("Receivng...");
if (isReceived(is, recvMessageNo)) {
System.out.println("Receive success");
} else {
System.out.println("Receive fail");
}
// 通信の切断を行う
System.out.println("Closing...");
try {
if (null != connection) {
os.close();
is.close();
connection.close();
}
} catch (Exception ioe) {
}
System.out.println("Finished");
}
// 送信する
static void send(OutputStream os, int messageNo) {
byte[] sendBuff = new byte[16];
for (int i = 0; i < sendBuff.length; i++) {
sendBuff[i] = (byte) messageNo;
}
try {
os.write(sendBuff);
} catch (IOException e) {
e.printStackTrace();
}
}
// 指定したメッセージ番号を受信できているかを判定する
static boolean isReceived(InputStream is, int messageNo) {
byte[] recvBuff = receive(is);
for (int i = 0; i < recvBuff.length; i++) {
System.out.print(recvBuff[i]);
if (recvBuff[i] != (byte) messageNo) {
System.out.println();
return false;
}
}
System.out.println();
return true;
}
// 受信する
static byte[] receive(InputStream is) {
byte[] recvBuff = new byte[16];
try {
is.read(recvBuff);
} catch (IOException e) {
e.printStackTrace();
}
return recvBuff;
}
}