-
Notifications
You must be signed in to change notification settings - Fork 358
/
BridgeModbusTcpImpl.java
191 lines (168 loc) · 6.05 KB
/
BridgeModbusTcpImpl.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package io.openems.edge.bridge.modbus;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Objects;
import io.openems.edge.bridge.modbus.api.LogVerbosity;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;
import org.osgi.service.event.propertytypes.EventTopics;
import org.osgi.service.metatype.annotations.Designate;
import com.ghgande.j2mod.modbus.io.ModbusTCPTransaction;
import com.ghgande.j2mod.modbus.io.ModbusTransaction;
import com.ghgande.j2mod.modbus.net.TCPMasterConnection;
import io.openems.common.exceptions.OpenemsException;
import io.openems.common.utils.InetAddressUtils;
import io.openems.edge.bridge.modbus.api.AbstractModbusBridge;
import io.openems.edge.bridge.modbus.api.BridgeModbus;
import io.openems.edge.bridge.modbus.api.BridgeModbusTcp;
import io.openems.edge.common.component.OpenemsComponent;
import io.openems.edge.common.event.EdgeEventConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provides a service for connecting to, querying and writing to a Modbus/TCP
* device.
*/
@Designate(ocd = ConfigTcp.class, factory = true)
@Component(//
name = "Bridge.Modbus.Tcp", //
immediate = true, //
configurationPolicy = ConfigurationPolicy.REQUIRE //
)
@EventTopics({ //
EdgeEventConstants.TOPIC_CYCLE_BEFORE_PROCESS_IMAGE, //
EdgeEventConstants.TOPIC_CYCLE_EXECUTE_WRITE //
})
public class BridgeModbusTcpImpl extends AbstractModbusBridge
implements BridgeModbus, BridgeModbusTcp, OpenemsComponent, EventHandler {
/** The configured IP address. */
private InetAddress ipAddress = null;
private int port;
private final Logger log = LoggerFactory.getLogger(BridgeModbusTcpImpl.class);
private boolean shouldSkip = false;
private int noSkipIdx = 0;
private long cycleIdx = 0;
@Reference
protected ConfigurationAdmin cm;
public BridgeModbusTcpImpl() {
super(//
OpenemsComponent.ChannelId.values(), //
BridgeModbus.ChannelId.values(), //
BridgeModbusTcp.ChannelId.values() //
);
}
@Activate
private void activate(ComponentContext context, ConfigTcp config) throws UnknownHostException {
super.activate(context, config.id(), config.alias(), config.enabled(), config.logVerbosity(),
config.invalidateElementsAfterReadErrors());
this.applyConfig(config);
}
@Modified
private void modified(ComponentContext context, ConfigTcp config) throws UnknownHostException {
super.modified(context, config.id(), config.alias(), config.enabled(), config.logVerbosity(),
config.invalidateElementsAfterReadErrors());
this.applyConfig(config);
this.closeModbusConnection();
}
private void applyConfig(ConfigTcp config) {
this.setIpAddress(InetAddressUtils.parseOrNull(config.ip()));
this.port = config.port();
int coreCycleTime = 1000;
try {
// the default cycleTime is not persisted and won't be returned, only modified cycleTime will!
coreCycleTime = (int) (Integer) this.cm.getConfiguration("Core.Cycle").getProperties().get("cycleTime");
} catch (Exception e) {
this.logCycle("cycleTime reading failed, use default value " + coreCycleTime);
}
this.noSkipIdx = (int)Math.ceil(config.intervalBetweenAccesses() * 1.0 / coreCycleTime);
this.noSkipIdx = Math.max(this.noSkipIdx, 1);
this.logCycle("applyConfig: cycleTime=" + coreCycleTime
+ ", interval=" + config.intervalBetweenAccesses()
+ ", noSkipIdx=" + this.noSkipIdx);
}
@Override
@Deactivate
protected void deactivate() {
super.deactivate();
}
@Override
public void closeModbusConnection() {
if (this._connection != null) {
this._connection.close();
this._connection = null;
}
}
@Override
public ModbusTransaction getNewModbusTransaction() throws OpenemsException {
var connection = this.getModbusConnection();
var transaction = new ModbusTCPTransaction(connection);
transaction.setRetries(AbstractModbusBridge.DEFAULT_RETRIES);
return transaction;
}
private TCPMasterConnection _connection = null;
private synchronized TCPMasterConnection getModbusConnection() throws OpenemsException {
if (this._connection == null) {
/*
* create new connection
*/
var connection = new TCPMasterConnection(this.getIpAddress());
connection.setPort(this.port);
this._connection = connection;
}
if (!this._connection.isConnected()) {
try {
this._connection.connect();
} catch (Exception e) {
throw new OpenemsException(
"Connection to [" + this.getIpAddress().getHostAddress() + "] failed: " + e.getMessage());
}
this._connection.getModbusTransport().setTimeout(AbstractModbusBridge.DEFAULT_TIMEOUT);
}
return this._connection;
}
@Override
public InetAddress getIpAddress() {
return this.ipAddress;
}
public void setIpAddress(InetAddress ipAddress) {
this.ipAddress = ipAddress;
}
private boolean isNewCycle(Event event) {
return Objects.equals(event.getTopic(), EdgeEventConstants.TOPIC_CYCLE_BEFORE_PROCESS_IMAGE);
}
private void logCycle(String msg) {
if (this.getLogVerbosity() == LogVerbosity.DEBUG_LOG) {
this.logInfo(this.log, msg);
}
}
@Override
public void handleEvent(Event event) {
if (!this.isEnabled()) {
return;
}
if (this.isNewCycle(event)) {
this.shouldSkip = this.cycleIdx % this.noSkipIdx != 0;
this.logCycle("handleEvent: Cycle " + this.cycleIdx + (this.shouldSkip ? " will" : " won't") + " be skipped");
this.cycleIdx++;
}
if (this.shouldSkip) {
return;
}
switch (event.getTopic()) {
case EdgeEventConstants.TOPIC_CYCLE_BEFORE_PROCESS_IMAGE:
this.worker.onBeforeProcessImage();
break;
case EdgeEventConstants.TOPIC_CYCLE_EXECUTE_WRITE:
this.worker.onExecuteWrite();
break;
}
}
}