90 lines
2.5 KiB
C

#ifndef DEVICE_PROTOCOL_H
#define DEVICE_PROTOCOL_H
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#define DEVICE_CHANNELS 8
#define DEVICE_CAPACITY 32
#define DEVICE_HISTORY 64
#define DEVICE_LINE 2048
#ifndef APP_FEATURE
#define APP_FEATURE 0
#endif
#ifndef APP_VERSION
#define APP_VERSION 1
#endif
#ifndef BUILD_PROFILE
#define BUILD_PROFILE 1
#endif
typedef enum {
REQUEST_RESET,
REQUEST_PUT,
REQUEST_DRAIN,
REQUEST_DROP,
REQUEST_STATE,
REQUEST_INVALID
} RequestKind;
typedef struct {
uint32_t sequence;
uint32_t channel;
int32_t value;
} DeviceRecord;
typedef struct {
RequestKind kind;
uint32_t argument;
DeviceRecord record;
} Request;
typedef struct {
int status;
uint32_t epoch;
uint32_t accepted;
uint32_t dropped;
uint32_t pending;
uint32_t digest;
int backend;
int feature;
int version;
size_t count;
int64_t values[DEVICE_CAPACITY];
} Response;
typedef struct {
DeviceRecord records[DEVICE_CAPACITY];
size_t count;
} Journal;
typedef struct {
unsigned char bytes[128];
size_t cursor;
size_t available;
int ended;
int failed;
} InputBuffer;
typedef enum {
INPUT_END,
INPUT_READY,
INPUT_REJECTED,
INPUT_FAILED
} InputResult;
void input_init(InputBuffer *input);
InputResult input_next(FILE *stream, InputBuffer *input, char *line, size_t capacity);
int text_request(const char *line, Request *out);
void text_response(const Response *response);
uint32_t bytes_crc(const unsigned char *raw, size_t size);
void record_encode(const DeviceRecord *record, unsigned char out[16]);
int record_decode(const unsigned char *raw, size_t size, DeviceRecord *out);
uint32_t read_le32(const unsigned char *raw);
void write_le32(unsigned char *raw, uint32_t value);
int parse_u32(const char *text, uint32_t *out);
int parse_i32(const char *text, int32_t *out);
int hex_decode(const char *text, unsigned char *out, size_t limit, size_t *size);
void journal_init(Journal *journal);
int journal_append(Journal *journal, DeviceRecord record);
int journal_remove(Journal *journal, size_t index, DeviceRecord *out);
size_t journal_discard(Journal *journal, uint32_t channel);
uint32_t journal_digest(const Journal *journal);
int journal_find(const Journal *journal, uint32_t sequence);
void engine_reset(uint32_t epoch);
void engine_execute(const Request *request, Response *response);
int64_t calibration_apply(int32_t value, uint32_t channel);
int calibration_identity(void);
#endif