Fix filter bitmask generation
[apps/agl-service-can-low-level.git] / low-can-binding / can / can-encoder.cpp
1 /*
2  * Copyright (C) 2015, 2016 "IoT.bzh"
3  * Author "Romain Forlot" <romain.forlot@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *       http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include "can-encoder.hpp"
19
20 #include "canutil/write.h"
21 #include "../utils/openxc-utils.hpp"
22 #include "message-definition.hpp"
23 #include "../utils/converter.hpp"
24
25 /**
26  * @brief Allows to encode data for a signal
27  *
28  * @param sig The signal to know its location
29  * @param data The data to encod
30  * @param filter If true that will generate the filter BCM for the signal
31  * @param factor If true that will use the factor of the signal else 1
32  * @param offset If true that will use the offset of the signal else 0
33  */
34 void encoder_t::encode_data(std::shared_ptr<signal_t> sig, std::vector<uint8_t> &data, bool filter, bool factor, bool offset)
35 {
36         uint32_t bit_size = sig->get_bit_size();
37         uint32_t bit_position = sig->get_bit_position();
38         int new_start_byte = 0;
39         int new_end_byte = 0;
40         int new_start_bit_tmp = 0;
41         int new_end_bit = 0;
42
43         converter_t::signal_to_bits_bytes(bit_position, bit_size, new_start_byte, new_end_byte, new_start_bit_tmp, new_end_bit);
44
45         int len_signal_bytes_tmp = new_end_byte - new_start_byte + 1;
46
47         uint8_t len_signal_bytes = 0;
48         if(len_signal_bytes_tmp > 255)
49         {
50                 AFB_ERROR("Error signal %s too long",sig->get_name().c_str());
51         }
52         else
53         {
54                 len_signal_bytes = (uint8_t) len_signal_bytes_tmp;
55         }
56
57         uint8_t new_start_bit = 0;
58         if(new_start_bit_tmp > 255)
59         {
60                 AFB_ERROR("Error signal %s too long",sig->get_name().c_str());
61         }
62         else
63         {
64                 new_start_bit = (uint8_t) new_start_bit_tmp;
65         }
66
67         uint8_t new_bit_size = 0;
68         if(bit_size > 255)
69         {
70                 AFB_ERROR("Error signal %s to long bit size",sig->get_name().c_str());
71         }
72         else
73         {
74                 new_bit_size = (uint8_t) bit_size;
75         }
76
77         uint8_t data_signal[len_signal_bytes] = {0};
78         float factor_v = 1;
79         if(factor)
80         {
81                 factor_v = sig->get_factor();
82         }
83
84         float offset_v = 0;
85         if(factor)
86         {
87                 offset_v = sig->get_offset();
88         }
89
90         if(filter)
91         {
92                 uint8_t tmp = 0;
93                 int j=0;
94                 for(int i=0;i<new_bit_size;i++)
95                 {
96                         int mask = 0x80 >> ((i%8)+new_start_bit);
97
98                         uint8_t mask_v = 0;
99                         if(mask > 255)
100                         {
101                                 AFB_ERROR("Error mask too large");
102                         }
103                         else
104                         {
105                                 mask_v = (uint8_t) mask;
106                         }
107                         tmp = tmp|mask_v;
108
109                         if(i%8 == 7)
110                         {
111                                 data_signal[j] = tmp;
112                                 tmp = 0;
113                                 j++;
114                         }
115                 }
116                 data_signal[j]=tmp;
117         }
118         else
119         {
120                 bitfield_encode_float(  sig->get_last_value(),
121                                                 new_start_bit,
122                                                 new_bit_size,
123                                                 factor_v,
124                                                 offset_v,
125                                                 data_signal,
126                                                 len_signal_bytes);
127         }
128
129         for(size_t i = new_start_byte; i <= new_end_byte ; i++)
130         {
131                 data[i] = data[i] | data_signal[i-new_start_byte];
132         }
133 }
134
135 /**
136  * @brief Allows to build a multi frame message with correct data to be send
137  *
138  * @param signal The CAN signal to write, including the bit position and bit size.
139  * @param value The encoded integer value to write in the CAN signal.
140  * @param message A multi frame message to complete
141  * @param factor If true that will use the factor of the signal else 1
142  * @param offset If true that will use the offset of the signal else 0
143  * @return message_t*  The message that is generated
144  */
145 message_t* encoder_t::build_frame(const std::shared_ptr<signal_t>& signal, uint64_t value, message_t *message, bool factor, bool offset)
146 {
147         signal->set_last_value((float)value);
148         std::vector<uint8_t> data;
149         for(int i = 0; i<message->get_length();i++)
150         {
151                 data.push_back(0);
152         }
153
154         for(const auto& sig: signal->get_message()->get_signals())
155         {
156                 encode_data(sig,data,false,factor,offset);
157         }
158         message->set_data(data);
159         return message;
160 }
161
162 /**
163  * @brief Allows to build a message_t with correct data to be send
164  *
165  * @param signal The CAN signal to write, including the bit position and bit size.
166  * @param value The encoded integer value to write in the CAN signal.
167  * @param factor If true that will use the factor of the signal else 1
168  * @param offset If true that will use the offset of the signal else 0
169  * @return message_t* The message that is generated
170  */
171 message_t* encoder_t::build_message(const std::shared_ptr<signal_t>& signal, uint64_t value, bool factor, bool offset)
172 {
173         message_t *message;
174         std::vector<uint8_t> data;
175         if(signal->get_message()->is_fd())
176         {
177                 message = new can_message_t( CANFD_MAX_DLEN,
178                                                                          signal->get_message()->get_id(),
179                                                                          CANFD_MAX_DLEN,
180                                                                          false,
181                                                                          signal->get_message()->get_flags(),
182                                                                          data,
183                                                                          0);
184
185                 return build_frame(signal,value,message, factor, offset);
186         }
187 #ifdef USE_FEATURE_J1939
188         else if(signal->get_message()->is_j1939())
189         {
190                 message = new j1939_message_t( signal->get_message()->get_length(),
191                                                                            data,
192                                                                            0,
193                                                                            J1939_NO_NAME,
194                                                                            signal->get_message()->get_id(),
195                                                                            J1939_NO_ADDR);
196                 return build_frame(signal,value,message, factor, offset);
197         }
198 #endif
199         else
200         {
201                 message = new can_message_t(CAN_MAX_DLEN,
202                                                                         signal->get_message()->get_id(),
203                                                                         CAN_MAX_DLEN,
204                                                                         false,
205                                                                         signal->get_message()->get_flags(),
206                                                                         data,
207                                                                         0);
208                 return build_frame(signal,value,message, factor, offset);
209         }
210 }
211
212 /// @brief Encode a boolean into an integer, fit for a CAN signal bitfield.
213 ///
214 /// This is a shortcut for encodeDynamicField(CanSignal*, openxc_DynamicField*,
215 /// bool*) that takes care of creating the DynamicField object for you with the
216 /// boolean value.
217 ///
218 /// @param[in] signal  - The CAN signal to encode this value for..
219 /// @param[in] value - The boolean value to encode
220 /// @param[out] send - An output argument that will be set to false if the value should
221 ///     not be sent for any reason.
222 ///
223 /// @return Returns the encoded integer. If 'send' is changed to false, the field could
224 /// not be encoded and the return value is undefined.
225 ///
226 uint64_t encoder_t::encode_boolean(const signal_t& signal, bool value, bool* send)
227 {
228         return encode_number(signal, float(value), send);
229 }
230 /// @brief Encode a float into an integer, fit for a CAN signal's bitfield.
231 ///
232 /// This is a shortcut for encodeDynamicField(CanSignal*, openxc_DynamicField*,
233 /// bool*) that takes care of creating the DynamicField object for you with the
234 /// float value.
235 ///
236 /// @param[in] signal  - The CAN signal to encode this value for.
237 /// @param[in] value - The float value to encode.
238 /// @param[out] send - This output argument will always be set to false, so the caller will
239 ///      know not to publish this value to the pipeline.
240 ///
241 /// @return Returns the encoded integer. If 'send' is changed to false, the field could
242 /// not be encoded and the return value is undefined.
243 ///
244 uint64_t encoder_t::encode_number(const signal_t& signal, float value, bool* send)
245 {
246         return float_to_fixed_point(value, signal.get_factor(), signal.get_offset());
247 }
248
249 /// @brief Encode a string into an integer, fit for a CAN signal's bitfield.
250 ///
251 /// Be aware that the behavior is undefined if there are multiple values assigned
252 /// to a single state. See https://github.com/openxc/vi-firmware/issues/185.
253 ///
254 /// This is a shortcut for encodeDynamicField(CanSignal*, openxc_DynamicField*,
255 /// bool*) that takes care of creating the DynamicField object for you with the
256 /// string state value.
257 ///
258 /// @param[in] signal  - The details of the signal that contains the state mapping.
259 /// @param[in] value - The string state value to encode.
260 /// @param[out] send - An output argument that will be set to false if the value should
261 ///     not be sent for any reason.
262 ///
263 /// @return Returns the encoded integer. If 'send' is changed to false, the field could
264 /// not be encoded and the return value is undefined.
265 ///
266 uint64_t encoder_t::encode_state(const signal_t& signal, const std::string& state, bool* send)
267 {
268         uint64_t value = 0;
269         if(state == "")
270         {
271                 AFB_DEBUG("Can't write state of "" -- not sending");
272                 *send = false;
273         }
274         else
275         {
276                 uint64_t signal_state = signal.get_states(state);
277                 if(signal_state != -1) {
278                         value = signal_state;
279                 } else {
280                         AFB_DEBUG("Couldn't find a valid signal state for %s", state.c_str());
281                         *send = false;
282                 }
283         }
284         return value;
285 }
286
287 /// @brief Parse a signal from a CAN message and apply any required
288 /// transforations to get a human readable value.
289 ///
290 /// If the signal_t has a non-NULL 'decoder' field, the raw CAN signal value
291 /// will be passed to the decoder before returning.
292 ///
293 /// @param[in] signal - The details of the signal to decode and forward.
294 /// @param[in] value - The numerical value that will be converted to a boolean.
295 /// @param[out] send - An output parameter that will be flipped to false if the value could
296 ///      not be decoded.
297 ///
298 /// @return The decoder returns an openxc_DynamicField, which may contain a number,
299 /// string or boolean. If 'send' is false, the return value is undefined.
300 ///
301 uint64_t encoder_t::encode_DynamicField( signal_t& signal, const openxc_DynamicField& field, bool* send)
302 {
303         uint64_t value = 0;
304         switch(field.type) {
305                 case openxc_DynamicField_Type_STRING:
306                         value = encode_state(signal, field.string_value, send);
307                         break;
308                 case openxc_DynamicField_Type_NUM:
309                         value = encode_number(signal, (float)field.numeric_value, send);
310                         break;
311                 case openxc_DynamicField_Type_BOOL:
312                         value = encode_boolean(signal, field.boolean_value, send);
313                         break;
314                 default:
315                         AFB_DEBUG("Dynamic field didn't have a value, can't encode");
316                         *send = false;
317                         break;
318         }
319         return value;
320 }