]> git.basschouten.com Git - openhab-addons.git/blob
250df897333998af2e2a3ce0b6ab08c6134e29f8
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.plclogo.internal.handler;
14
15 import static org.openhab.binding.plclogo.internal.PLCLogoBindingConstants.*;
16
17 import java.util.Collections;
18 import java.util.HashMap;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Set;
22 import java.util.concurrent.atomic.AtomicReference;
23
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.openhab.binding.plclogo.internal.PLCLogoClient;
26 import org.openhab.binding.plclogo.internal.config.PLCDigitalConfiguration;
27 import org.openhab.core.config.core.Configuration;
28 import org.openhab.core.library.types.DecimalType;
29 import org.openhab.core.library.types.OnOffType;
30 import org.openhab.core.library.types.OpenClosedType;
31 import org.openhab.core.thing.Bridge;
32 import org.openhab.core.thing.Channel;
33 import org.openhab.core.thing.ChannelUID;
34 import org.openhab.core.thing.Thing;
35 import org.openhab.core.thing.ThingStatus;
36 import org.openhab.core.thing.ThingTypeUID;
37 import org.openhab.core.thing.binding.builder.ChannelBuilder;
38 import org.openhab.core.thing.binding.builder.ThingBuilder;
39 import org.openhab.core.thing.type.ChannelTypeUID;
40 import org.openhab.core.types.Command;
41 import org.openhab.core.types.RefreshType;
42 import org.openhab.core.types.State;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 import Moka7.S7;
47 import Moka7.S7Client;
48
49 /**
50  * The {@link PLCDigitalHandler} is responsible for handling commands, which are
51  * sent to one of the channels.
52  *
53  * @author Alexander Falkenstern - Initial contribution
54  */
55 @NonNullByDefault
56 public class PLCDigitalHandler extends PLCCommonHandler {
57
58     public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_DIGITAL);
59
60     private final Logger logger = LoggerFactory.getLogger(PLCDigitalHandler.class);
61     private AtomicReference<PLCDigitalConfiguration> config = new AtomicReference<>();
62
63     private static final Map<String, Integer> LOGO_BLOCKS_0BA7;
64     static {
65         Map<String, Integer> buffer = new HashMap<>();
66         buffer.put(I_DIGITAL, 24); // 24 digital inputs
67         buffer.put(Q_DIGITAL, 16); // 16 digital outputs
68         buffer.put(M_DIGITAL, 27); // 27 digital markers
69         LOGO_BLOCKS_0BA7 = Collections.unmodifiableMap(buffer);
70     }
71
72     private static final Map<String, Integer> LOGO_BLOCKS_0BA8;
73     static {
74         Map<String, Integer> buffer = new HashMap<>();
75         buffer.put(I_DIGITAL, 24); // 24 digital inputs
76         buffer.put(Q_DIGITAL, 20); // 20 digital outputs
77         buffer.put(M_DIGITAL, 64); // 64 digital markers
78         buffer.put(NI_DIGITAL, 64); // 64 network inputs
79         buffer.put(NQ_DIGITAL, 64); // 64 network outputs
80         LOGO_BLOCKS_0BA8 = Collections.unmodifiableMap(buffer);
81     }
82
83     private static final Map<String, Map<String, Integer>> LOGO_BLOCK_NUMBER;
84     static {
85         Map<String, Map<String, Integer>> buffer = new HashMap<>();
86         buffer.put(LOGO_0BA7, LOGO_BLOCKS_0BA7);
87         buffer.put(LOGO_0BA8, LOGO_BLOCKS_0BA8);
88         LOGO_BLOCK_NUMBER = Collections.unmodifiableMap(buffer);
89     }
90
91     /**
92      * Constructor.
93      */
94     public PLCDigitalHandler(Thing thing) {
95         super(thing);
96     }
97
98     @Override
99     public void handleCommand(ChannelUID channelUID, Command command) {
100         if (!isThingOnline()) {
101             return;
102         }
103
104         Channel channel = getThing().getChannel(channelUID.getId());
105         String name = getBlockFromChannel(channel);
106         if (!isValid(name) || (channel == null)) {
107             logger.debug("Can not update channel {}, block {}.", channelUID, name);
108             return;
109         }
110
111         int bit = getBit(name);
112         int address = getAddress(name);
113         PLCLogoClient client = getLogoClient();
114         if ((address != INVALID) && (bit != INVALID) && (client != null)) {
115             if (command instanceof RefreshType) {
116                 int base = getBase(name);
117                 byte[] buffer = new byte[getBufferLength()];
118                 int result = client.readDBArea(1, base, buffer.length, S7Client.S7WLByte, buffer);
119                 if (result == 0) {
120                     updateChannel(channel, S7.GetBitAt(buffer, address - base, bit));
121                 } else {
122                     logger.debug("Can not read data from LOGO!: {}.", S7Client.ErrorText(result));
123                 }
124             } else if ((command instanceof OpenClosedType) || (command instanceof OnOffType)) {
125                 byte[] buffer = new byte[1];
126                 String type = channel.getAcceptedItemType();
127                 if (DIGITAL_INPUT_ITEM.equalsIgnoreCase(type)) {
128                     S7.SetBitAt(buffer, 0, 0, ((OpenClosedType) command) == OpenClosedType.CLOSED);
129                 } else if (DIGITAL_OUTPUT_ITEM.equalsIgnoreCase(type)) {
130                     S7.SetBitAt(buffer, 0, 0, ((OnOffType) command) == OnOffType.ON);
131                 } else {
132                     logger.debug("Channel {} will not accept {} items.", channelUID, type);
133                 }
134                 int result = client.writeDBArea(1, 8 * address + bit, buffer.length, S7Client.S7WLBit, buffer);
135                 if (result != 0) {
136                     logger.debug("Can not write data to LOGO!: {}.", S7Client.ErrorText(result));
137                 }
138             } else {
139                 logger.debug("Channel {} received not supported command {}.", channelUID, command);
140             }
141         } else {
142             logger.info("Invalid channel {} or client {} found.", channelUID, client);
143         }
144     }
145
146     @Override
147     public void setData(final byte[] data) {
148         if (!isThingOnline()) {
149             return;
150         }
151
152         if (data.length != getBufferLength()) {
153             logger.info("Received and configured data sizes does not match.");
154             return;
155         }
156
157         List<Channel> channels = thing.getChannels();
158         if (channels.size() != getNumberOfChannels()) {
159             logger.info("Received and configured channel sizes does not match.");
160             return;
161         }
162
163         Boolean force = config.get().isUpdateForced();
164         for (Channel channel : channels) {
165             ChannelUID channelUID = channel.getUID();
166             String name = getBlockFromChannel(channel);
167
168             int bit = getBit(name);
169             int address = getAddress(name);
170             if ((address != INVALID) && (bit != INVALID)) {
171                 DecimalType state = (DecimalType) getOldValue(name);
172                 boolean value = S7.GetBitAt(data, address - getBase(name), bit);
173                 if ((state == null) || ((value ? 1 : 0) != state.intValue()) || force) {
174                     updateChannel(channel, value);
175                 }
176                 if (logger.isTraceEnabled()) {
177                     int buffer = (data[address - getBase(name)] & 0xFF) + 0x100;
178                     logger.trace("Channel {} received [{}].", channelUID, Integer.toBinaryString(buffer).substring(1));
179                 }
180             } else {
181                 logger.info("Invalid channel {} found.", channelUID);
182             }
183         }
184     }
185
186     @Override
187     protected void updateState(ChannelUID channelUID, State state) {
188         super.updateState(channelUID, state);
189         DecimalType value = state.as(DecimalType.class);
190         if (state instanceof OpenClosedType) {
191             OpenClosedType type = (OpenClosedType) state;
192             value = new DecimalType(type == OpenClosedType.CLOSED ? 1 : 0);
193         }
194
195         Channel channel = thing.getChannel(channelUID.getId());
196         setOldValue(getBlockFromChannel(channel), value);
197     }
198
199     @Override
200     protected void updateConfiguration(Configuration configuration) {
201         super.updateConfiguration(configuration);
202         config.set(getConfigAs(PLCDigitalConfiguration.class));
203     }
204
205     @Override
206     protected boolean isValid(final String name) {
207         if (2 <= name.length() && (name.length() <= 4)) {
208             String kind = getBlockKind();
209             if (Character.isDigit(name.charAt(1)) || Character.isDigit(name.charAt(2))) {
210                 boolean valid = I_DIGITAL.equalsIgnoreCase(kind) || NI_DIGITAL.equalsIgnoreCase(kind);
211                 valid = valid || Q_DIGITAL.equalsIgnoreCase(kind) || NQ_DIGITAL.equalsIgnoreCase(kind);
212                 return name.startsWith(kind) && (valid || M_DIGITAL.equalsIgnoreCase(kind));
213             }
214         }
215         return false;
216     }
217
218     @Override
219     protected String getBlockKind() {
220         return config.get().getBlockKind();
221     }
222
223     @Override
224     protected int getNumberOfChannels() {
225         String kind = getBlockKind();
226         String family = getLogoFamily();
227         logger.debug("Get block number of {} LOGO! for {} blocks.", family, kind);
228
229         Map<?, Integer> blocks = LOGO_BLOCK_NUMBER.get(family);
230         Integer number = (blocks != null) ? blocks.get(kind) : null;
231         return (number != null) ? number.intValue() : 0;
232     }
233
234     @Override
235     protected int getAddress(final String name) {
236         int address = super.getAddress(name);
237         if (address != INVALID) {
238             address = getBase(name) + (address - 1) / 8;
239         } else {
240             logger.info("Wrong configurated LOGO! block {} found.", name);
241         }
242         return address;
243     }
244
245     @Override
246     protected void doInitialization() {
247         Thing thing = getThing();
248         logger.debug("Initialize LOGO! digital input blocks handler.");
249
250         config.set(getConfigAs(PLCDigitalConfiguration.class));
251
252         super.doInitialization();
253         if (ThingStatus.OFFLINE != thing.getStatus()) {
254             String kind = getBlockKind();
255             String type = config.get().getChannelType();
256             String text = DIGITAL_INPUT_ITEM.equalsIgnoreCase(type) ? "input" : "output";
257
258             ThingBuilder tBuilder = editThing();
259
260             String label = thing.getLabel();
261             if (label == null) {
262                 Bridge bridge = getBridge();
263                 label = (bridge == null) || (bridge.getLabel() == null) ? "Siemens Logo!" : bridge.getLabel();
264                 label += (": digital " + text + "s");
265             }
266             tBuilder.withLabel(label);
267
268             for (int i = 0; i < getNumberOfChannels(); i++) {
269                 String name = kind + String.valueOf(i + 1);
270                 ChannelUID uid = new ChannelUID(thing.getUID(), name);
271                 ChannelBuilder cBuilder = ChannelBuilder.create(uid, type);
272                 cBuilder.withType(new ChannelTypeUID(BINDING_ID, type.toLowerCase()));
273                 cBuilder.withLabel(name);
274                 cBuilder.withDescription("Digital " + text + " block " + name);
275                 cBuilder.withProperties(Collections.singletonMap(BLOCK_PROPERTY, name));
276                 tBuilder.withChannel(cBuilder.build());
277                 setOldValue(name, null);
278             }
279
280             updateThing(tBuilder.build());
281             updateStatus(ThingStatus.ONLINE);
282         }
283     }
284
285     /**
286      * Calculate bit within address for block with given name.
287      *
288      * @param name Name of the LOGO! block
289      * @return Calculated bit
290      */
291     private int getBit(final String name) {
292         int bit = INVALID;
293
294         logger.debug("Get bit of {} LOGO! for block {} .", getLogoFamily(), name);
295
296         if (isValid(name) && (getAddress(name) != INVALID)) {
297             if (Character.isDigit(name.charAt(1))) {
298                 bit = Integer.parseInt(name.substring(1));
299             } else if (Character.isDigit(name.charAt(2))) {
300                 bit = Integer.parseInt(name.substring(2));
301             }
302             bit = (bit - 1) % 8;
303         } else {
304             logger.info("Wrong configurated LOGO! block {} found.", name);
305         }
306
307         return bit;
308     }
309
310     private void updateChannel(final Channel channel, boolean value) {
311         ChannelUID channelUID = channel.getUID();
312         String type = channel.getAcceptedItemType();
313         if (DIGITAL_INPUT_ITEM.equalsIgnoreCase(type)) {
314             updateState(channelUID, value ? OpenClosedType.CLOSED : OpenClosedType.OPEN);
315             logger.debug("Channel {} accepting {} was set to {}.", channelUID, type, value);
316         } else if (DIGITAL_OUTPUT_ITEM.equalsIgnoreCase(type)) {
317             updateState(channelUID, value ? OnOffType.ON : OnOffType.OFF);
318             logger.debug("Channel {} accepting {} was set to {}.", channelUID, type, value);
319         } else {
320             logger.debug("Channel {} will not accept {} items.", channelUID, type);
321         }
322     }
323 }