controller-legacy/models/schedule_save.c

87 lines
2.4 KiB
C

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <uuid/uuid.h>
#include <models/schedule.h>
#include <models/relay.h>
#include <macros.h>
static int
schedule_save_single(MDB_txn *mdb_txn, MDB_dbi mdb_dbi, db_key_schedule_e key_schedule, uint8_t relay_num, uint8_t weekday, MDB_val value)
{
int err;
size_t key_size = sizeof(db_key_schedule_e) + (2 * sizeof(uint8_t));
uint8_t *key_data = malloc(key_size);
uint8_t *key_data_writer = key_data;
memmove(key_data_writer, &relay_num, sizeof(uint8_t));
key_data_writer += sizeof(uint8_t);
memmove(key_data_writer, &weekday, sizeof(uint8_t));
key_data_writer += sizeof(uint8_t);
memmove(key_data_writer, &key_schedule, sizeof(db_key_schedule_e));
MDB_val key;
key.mv_size = key_size;
key.mv_data = key_data;
if((err = mdb_put(mdb_txn, mdb_dbi, &key, &value, 0)) != 0)
{
LOG_ERROR("mdb_put error %s\n", mdb_strerror(err));
mdb_txn_abort(mdb_txn);
free(key_data);
return 1;
}
free(key_data);
return 0;
}
int
schedule_save(schedule_t *schedule, uint8_t relay_num, MDB_env *mdb_env)
{
char uuid_str[37];
uuid_unparse(schedule->id, uuid_str);
LOG_TRACE("saving schedule %s @ %p\n", uuid_str, schedule);
int err;
MDB_txn *mdb_txn;
MDB_dbi mdb_dbi;
MDB_val value;
if((err = mdb_txn_begin(mdb_env, NULL, 0, &mdb_txn)) != 0)
{
LOG_ERROR("mdb_txn_begin error %s\n", mdb_strerror(err));
exit(1);
}
if((err = mdb_dbi_open(mdb_txn, "schedules", MDB_CREATE, &mdb_dbi)) != 0)
{
LOG_ERROR("mdb_dbi_open error %s\n", mdb_strerror(err));
exit(1);
}
value.mv_size = sizeof(uuid_t);
value.mv_data = schedule->id;
if(schedule_save_single(mdb_txn, mdb_dbi, DB_KEY_SCHEDULE_ID, relay_num, schedule->weekday, value))
{
LOG_ERROR("failed to save ID\n");
return 1;
}
// save periods blob
uint16_t *periods_blob = schedule_periods_to_blob(schedule);
value.mv_size = sizeof(uint16_t) * ((periods_blob[0] * 2) + 1);
value.mv_data = periods_blob;
if(schedule_save_single(mdb_txn, mdb_dbi, DB_KEY_SCHEDULE_PERIODS, relay_num, schedule->weekday, value))
{
free(periods_blob);
LOG_ERROR("failed to save periods\n");
return 1;
}
free(periods_blob);
mdb_txn_commit(mdb_txn);
return 0;
}