Skip to content

Formula

deng_ran edited this page Jul 8, 2021 · 1 revision

English | 中文

In order to help developers reduce intermediate steps, FastProto supports specifing decoding formulas and encoding formulas. Specify the decoding formula through the afterDecode field, and specify the encoding formula through the beforeEncode field.

For example, the pressure signal in the protocol table below corresponds to a conversion formula, which needs to be multiplied by 0.1, that is very common in IoT communications.

Byte Offset Bit Offset Data Type(C/C++) Signal Name Unit Formula
14-17 unsigned int pressure Pa p * 0.1

Decode Formula

Define a decoding conversion formula, which must implement the java.lang.function.Function. The input type of the decoding formula must be the same as the annotation type, and the output type must be the same as the field type.

public class PressureDecodeFormula implements Function<Long, Double> {
    @Override
    public Double apply(Long value) {
        return value * 0.1;
    }
}

Modify the annotation and data type of the pressure field to add the above decoding formula.

@UInteger32Type(value = 14, afterDecode = DecodeSpeedFormula.class)
double pressure;

Encode Formula

An encoding formula is needed if serialize the object, which also need to implement the java.lang.function.Function. The input type of the encoding formula must be the same as the field type, and the output type must be the same as the annotation type.

public class PressureEncodeFormula implements Function<Double, Long> {
    @Override
    public Long apply(Double value) {
        return (long) (value * 10);
    }
}

Modify the annotation of the pressure field to add the above encoding formula.

@UInteger32Type(value = 14, afterDecode = PressureDecodeFormula.class, beforeEncode = PressureEncodeFormula.class)
double pressure;
Clone this wiki locally