controller-legacy/models/controller.c

105 lines
2 KiB
C
Raw Normal View History

2019-11-15 00:23:43 +00:00
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <uuid/uuid.h>
2019-12-08 22:39:10 +00:00
#include <models/controller.h>
#include <models/controller_file_reader.h>
2019-11-15 00:23:43 +00:00
#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;
2019-12-08 22:39:10 +00:00
controller *result;
2019-11-15 00:23:43 +00:00
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)
{
2019-12-08 22:39:10 +00:00
fclose(fp);
2019-11-15 00:23:43 +00:00
LOG_ERROR("Error reading header");
result = controller_create();
return result;
}
uint8_t version = header[0];
printf("%d\n", version);
2019-12-08 22:39:10 +00:00
switch(version)
{
case 1:
controller_file_reader_1(fp);
break;
default:
fclose(fp);
LOG_ERROR("Error unsupported version number");
return NULL;
}
2019-11-15 00:23:43 +00:00
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;
}