]> git.basschouten.com Git - openhab-addons.git/blob
a1d891c05b99bac9faab2736afbf2082e868b2ec
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.io.transport.modbus.endpoint;
14
15 import org.apache.commons.lang.builder.EqualsBuilder;
16 import org.apache.commons.lang.builder.HashCodeBuilder;
17 import org.apache.commons.lang.builder.StandardToStringStyle;
18 import org.apache.commons.lang.builder.ToStringBuilder;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21
22 /**
23  * Common base class for ip based endpoints. Endpoint differentiates different modbus slaves only by the ip address
24  * (string) and port name.
25  *
26  * @author Sami Salonen - Initial contribution
27  */
28 @NonNullByDefault
29 public abstract class ModbusIPSlaveEndpoint implements ModbusSlaveEndpoint {
30
31     private String address;
32     private int port;
33
34     private static StandardToStringStyle toStringStyle = new StandardToStringStyle();
35
36     static {
37         toStringStyle.setUseShortClassName(true);
38     }
39
40     public ModbusIPSlaveEndpoint(String address, int port) {
41         this.address = address;
42         this.port = port;
43     }
44
45     public String getAddress() {
46         return address;
47     }
48
49     public int getPort() {
50         return port;
51     }
52
53     @Override
54     public int hashCode() {
55         // differentiate different protocols using the class name, and after that use address and port
56         int protocolHash = this.getClass().getName().hashCode();
57         if (protocolHash % 2 == 0) {
58             protocolHash += 1;
59         }
60         return new HashCodeBuilder(11, protocolHash).append(address).append(port).toHashCode();
61     }
62
63     @Override
64     public String toString() {
65         return new ToStringBuilder(this, toStringStyle).append("address", address).append("port", port).toString();
66     }
67
68     @Override
69     public boolean equals(@Nullable Object obj) {
70         if (obj == null) {
71             return false;
72         }
73         if (obj == this) {
74             return true;
75         }
76         if (obj.getClass() != getClass()) {
77             // different protocol -> not equal!
78             return false;
79         }
80         ModbusIPSlaveEndpoint rhs = (ModbusIPSlaveEndpoint) obj;
81         return new EqualsBuilder().append(address, rhs.address).append(port, rhs.port).isEquals();
82     }
83 }