#include #include #include #include #include #include #include static int relay_save_single(MDB_txn *mdb_txn, MDB_dbi mdb_dbi, db_key_relay_e key_relay, uint8_t num, MDB_val value) { int err; size_t key_size = sizeof(db_key_relay_e) + sizeof(uint8_t); void *key_data = malloc(key_size); memmove(key_data, &key_relay, sizeof(db_key_relay_e)); memmove(key_data + sizeof(db_key_relay_e), &num, sizeof(uint8_t)); 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", mdb_strerror(err)); mdb_txn_abort(mdb_txn); free(key_data); return 1; } free(key_data); return 0; } int relay_save(relay_t *relay, MDB_env *mdb_env) { LOG_TRACE("saving relay %d @ %p", relay->number, relay); 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", mdb_strerror(err)); exit(1); } if((err = mdb_dbi_open(mdb_txn, "relays", MDB_CREATE, &mdb_dbi)) != 0) { LOG_ERROR("mdb_dbi_open error %s", mdb_strerror(err)); exit(1); } value.mv_size = sizeof(char) * (strlen(relay->name) + 1); value.mv_data = relay->name; if(relay_save_single(mdb_txn, mdb_dbi, DB_KEY_RELAY_NAME, relay->number, value)) { LOG_ERROR("failed to save name"); return 1; } value.mv_size = sizeof(uuid_t); value.mv_data = relay->schedule->id; if(relay_save_single(mdb_txn, mdb_dbi, DB_KEY_RELAY_SCHEDULE_ID, relay->number, value)) { LOG_ERROR("failed to save ID"); return 1; } // save periods blob uint16_t *periods_blob = schedule_periods_to_blob(relay->schedule); value.mv_size = sizeof(uint16_t) * ((periods_blob[0] * 2) + 1); value.mv_data = periods_blob; if(relay_save_single(mdb_txn, mdb_dbi, DB_KEY_RELAY_SCHEDULE_PERIODS, relay->number, value)) { free(periods_blob); LOG_ERROR("failed to save periods"); return 1; } free(periods_blob); mdb_txn_commit(mdb_txn); return 0; }