-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
RawByteRemoteEntity.java
91 lines (76 loc) · 2.13 KB
/
RawByteRemoteEntity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package com.marginallyclever.robotOverlord.entity.remoteEntity;
import com.marginallyclever.communications.NetworkConnection;
import com.marginallyclever.communications.NetworkConnectionListener;
import com.marginallyclever.communications.NetworkConnectionManager;
import com.marginallyclever.robotOverlord.log.Log;
import com.marginallyclever.robotOverlord.swingInterface.view.ViewPanel;
/**
* Wraps all network connection stuff into a neat entity package.
*
* See also https://en.wikipedia.org/wiki/Messaging_pattern
*
* @author Dan Royer
* @since 1.6.0
*
*/
public class RawByteRemoteEntity extends OneLineAtATimeRemoteEntity implements NetworkConnectionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
public NetworkConnection connection;
public RawByteRemoteEntity() {
super();
setName("Connected to");
}
public void closeConnection() {
connection.closeConnection();
connection.removeListener(this);
connection=null;
}
public void openConnection() {
connection = NetworkConnectionManager.requestNewConnection(null);
if(connection!=null) {
connection.addListener(this);
}
}
@Override
public void update(double dt) {
if(connection!=null) {
connection.update();
}
}
@Override
public void lineError(NetworkConnection arg0, int lineNumber) {}
@Override
public void sendBufferEmpty(NetworkConnection arg0) {}
@Override
public void dataAvailable(NetworkConnection arg0, String data) {
setChanged();
notifyObservers(data);
}
public boolean isConnectionOpen() {
return (connection!=null) && (connection.isOpen());
}
/**
* called by someone else to start the process of sending a message
* @param command
*/
public void sendMessage(String command) {
if(!isConnectionOpen()) return;
if(command.isEmpty()) return;
sendQueuedMessage(command);
}
private void sendQueuedMessage(String command) {
if(command==null) return;
try {
connection.sendMessage(command);
} catch (Exception e) {
Log.error("RemoteEntity.sendQueuedMessage failed: "+e.getLocalizedMessage());
}
}
@Override
public void getView(ViewPanel view) {
super.getView(view);
}
}