]> git.basschouten.com Git - openhab-addons.git/blob
a9b8cd5d37680b73f46a5f5361dcaecb75008d89
[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.lifx.internal.fields;
14
15 import java.nio.ByteBuffer;
16 import java.nio.charset.Charset;
17 import java.nio.charset.StandardCharsets;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20
21 /**
22  * @author Tim Buckley - Initial contribution
23  */
24 @NonNullByDefault
25 public class StringField extends Field<String> {
26
27     public static final Charset CHARSET = StandardCharsets.US_ASCII;
28
29     private Charset charset;
30
31     public StringField() {
32         charset = StandardCharsets.US_ASCII;
33     }
34
35     public StringField(int length) {
36         super(length);
37
38         charset = StandardCharsets.US_ASCII;
39     }
40
41     public StringField(int length, Charset charset) {
42         super(length);
43
44         this.charset = charset;
45     }
46
47     @Override
48     public int defaultLength() {
49         return 3;
50     }
51
52     @Override
53     public String value(ByteBuffer bytes) {
54         byte[] buf = new byte[length];
55         bytes.get(buf);
56
57         ByteBuffer field = ByteBuffer.wrap(buf);
58
59         String ret = charset.decode(field).toString();
60         ret = ret.replace("\0", "");
61
62         return ret;
63     }
64
65     @Override
66     public ByteBuffer bytesInternal(String value) {
67         return CHARSET.encode(value);
68     }
69
70     public StringField ascii() {
71         charset = StandardCharsets.US_ASCII;
72         return this;
73     }
74
75     public StringField utf8() {
76         charset = StandardCharsets.UTF_8;
77         return this;
78     }
79 }