controller-legacy/models/controller.c
Tobias Reisinger d8ad2c205a init
2019-11-15 01:23:43 +01:00

94 lines
No EOL
1.8 KiB
C

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <uuid/uuid.h>
#include "controller.h"
#include <macros.h>
controller*
controller_create(void)
{
controller *result = malloc(sizeof(*result));
uuid_generate(result->uuid);
strcpy(result->name, "new emgauwa device");
result->port = 0;
result->relay_count = 10;
result->relays = malloc(sizeof(*result->relays) * result->relay_count);
uint8_t i;
for(i = 0; i < result->relay_count; i++)
{
result->relays[i] = relay_init(i);
}
return result;
}
controller*
controller_read(void)
{
FILE *fp;
controller *result;;
fp = fopen(CONTROLLER_FILE_NAME, "rb");
if(fp == NULL)
{
LOG_ERROR("Error opening file");
result = controller_create();
return result;
}
uint8_t header[CONTROLLER_FILE_HEADER_SIZE];
size_t read_size;
read_size = fread(header, sizeof(*header), CONTROLLER_FILE_HEADER_SIZE, fp);
if(ferror(fp) || read_size != CONTROLLER_FILE_HEADER_SIZE)
{
LOG_ERROR("Error reading header");
result = controller_create();
return result;
}
uint8_t version = header[0];
printf("%d\n", version);
// size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
fclose(fp);
result = controller_create();
return result;
}
int
controller_save(controller* ci)
{
FILE *fp;
fp = fopen(CONTROLLER_FILE_NAME, "w+b");
if(fp == NULL)
{
LOG_ERROR("Error creating or opening file");
return 1;
}
uint8_t header[CONTROLLER_FILE_HEADER_SIZE];
header[0] = CONTROLLER_FILE_VERSION;
fwrite(header, sizeof(*header), CONTROLLER_FILE_HEADER_SIZE, fp);
fwrite(ci->name, sizeof(*ci->name), CONTROLLER_NAME_LENGTH, fp);
fclose(fp);
return 0;
}