summaryrefslogtreecommitdiffstats
path: root/src/canutil
diff options
context:
space:
mode:
Diffstat (limited to 'src/canutil')
-rw-r--r--src/canutil/read.c14
-rw-r--r--src/canutil/read.h13
-rw-r--r--src/canutil/write.c18
-rw-r--r--src/canutil/write.h13
4 files changed, 58 insertions, 0 deletions
diff --git a/src/canutil/read.c b/src/canutil/read.c
new file mode 100644
index 00000000..6b4e40aa
--- /dev/null
+++ b/src/canutil/read.c
@@ -0,0 +1,14 @@
+#include <bitfield/bitfield.h>
+
+float parseFloat(uint64_t data, uint8_t bitPosition, uint8_t bitSize,
+ float factor, float offset) {
+ uint64_t rawValue = getBitField(data, bitPosition,
+ bitSize, true);
+ return rawValue * factor + offset;
+}
+
+bool parseBoolean(uint64_t data, uint8_t bitPosition, uint8_t bitSize,
+ float factor, float offset) {
+ float value = parseFloat(data, bitPosition, bitSize, factor, offset);
+ return value == 0.0 ? false : true;
+}
diff --git a/src/canutil/read.h b/src/canutil/read.h
new file mode 100644
index 00000000..815f26b0
--- /dev/null
+++ b/src/canutil/read.h
@@ -0,0 +1,13 @@
+#ifndef __READ_H__
+#define __READ_H__
+
+#include <stdint.h>
+#include <stdbool.h>
+
+float parseFloat(uint64_t data, uint8_t bitPosition, uint8_t bitSize,
+ float factor, float offset);
+
+bool parseBoolean(uint64_t data, uint8_t bitPosition, uint8_t bitSize,
+ float factor, float offset);
+
+#endif // __READ_H__
diff --git a/src/canutil/write.c b/src/canutil/write.c
new file mode 100644
index 00000000..fdcba1f5
--- /dev/null
+++ b/src/canutil/write.c
@@ -0,0 +1,18 @@
+#include "write.h"
+
+uint64_t encodeFloat(float value, float offset, float factor, uint8_t bitPosition,
+ uint8_t bitSize) {
+ float rawValue = (value - offset) / factor;
+ if(rawValue > 0) {
+ // round up to avoid losing precision when we cast to an int
+ rawValue += 0.5;
+ }
+ uint64_t result = 0;
+ setBitField(&result, rawValue, bitPosition, bitSize);
+ return result;
+}
+
+uint64_t encodeBoolean(bool value, float offset, float factor,
+ uint8_t bitPosition, uint8_t bitSize) {
+ return encodeFloat(value, offset, factor, bitPosition, bitSize);
+}
diff --git a/src/canutil/write.h b/src/canutil/write.h
new file mode 100644
index 00000000..85a5c1a0
--- /dev/null
+++ b/src/canutil/write.h
@@ -0,0 +1,13 @@
+#ifndef __WRITE_H__
+#define __WRITE_H__
+
+#include <stdint.h>
+#include <stdbool.h>
+
+uint64_t encodeFloat(float value, float offset, float factor, uint8_t bitPosition,
+ uint8_t bitSize);
+
+uint64_t encodeBoolean(bool value, float offset, float factor,
+ uint8_t bitPosition, uint8_t bitSize);
+
+#endif // __WRITE_H__