@@ -6,7 +6,7 @@ use std::{
6
6
str:: FromStr ,
7
7
} ;
8
8
9
- use serde:: de ;
9
+ use serde:: { de , Serialize , Serializer } ;
10
10
use serde:: { Deserialize , Deserializer } ;
11
11
12
12
use crate :: {
@@ -112,7 +112,7 @@ impl std::error::Error for Homie5ValueConversionError {
112
112
/// attribute of the property, and the value must conform to that format.
113
113
///
114
114
/// For more details on the color formats and their constraints, refer to the Homie specification.
115
- #[ derive( Debug , Clone , Copy , Deserialize ) ]
115
+ #[ derive( Debug , Clone , Copy ) ]
116
116
pub enum HomieColorValue {
117
117
/// Represents a color in the RGB format, using three integers for red, green, and blue channels.
118
118
/// Each value must be an integer between 0 and 255.
@@ -138,6 +138,38 @@ impl HomieColorValue {
138
138
}
139
139
}
140
140
141
+ /// Serialize the ColorValue to its string representation
142
+ ///
143
+ /// - Example: `"rgb,255,0,0"` for red.
144
+ /// - Example: `"hsv,120,100,100"` for bright green.
145
+ /// - Example: `"xyz,0.25,0.34"`.
146
+ impl Serialize for HomieColorValue {
147
+ fn serialize < S > ( & self , serializer : S ) -> Result < S :: Ok , S :: Error >
148
+ where
149
+ S : Serializer ,
150
+ {
151
+ // Serialize the enum as its string representation.
152
+ serializer. serialize_str ( & self . to_string ( ) )
153
+ }
154
+ }
155
+
156
+ /// Deserialize the ColorValue from its string representation
157
+ ///
158
+ /// - Example: `"rgb,255,0,0"` for red.
159
+ /// - Example: `"hsv,120,100,100"` for bright green.
160
+ /// - Example: `"xyz,0.25,0.34"`.
161
+ impl < ' de > Deserialize < ' de > for HomieColorValue {
162
+ fn deserialize < D > ( deserializer : D ) -> Result < HomieColorValue , D :: Error >
163
+ where
164
+ D : Deserializer < ' de > ,
165
+ {
166
+ // Deserialize into a string first.
167
+ let s = String :: deserialize ( deserializer) ?;
168
+ // Use the FromStr implementation to parse the string.
169
+ HomieColorValue :: from_str ( & s) . map_err ( serde:: de:: Error :: custom)
170
+ }
171
+ }
172
+
141
173
impl PartialEq for HomieColorValue {
142
174
fn eq ( & self , other : & Self ) -> bool {
143
175
const EPSILON : f64 = 1e-6 ; // this is already way to precise for color values
0 commit comments