/*
 * capab.c
 *
 *  Created on: Dec 1, 2016
 *      Author: jklug
 *
 *  capabilities from EE-PROM, enumerated in /sys/devices/platform/mts-io/capability
 *  an associative array, written the hard way in C.
 */

/* This array is not in any order. */
struct capab_map_s {
	unsigned int bitvalue;
	const char *name;
};

/*
 * Should match mts_eeprom.h capabilities
 */
static struct capab_map_s capabilities_map[] = {
		{ CAPA_GPS,       "gps"},
		{ CAPA_DIN,       "din"},
		{ CAPA_DOUT,      "dout"},
		{ CAPA_ADC,       "adc"},
		{ CAPA_BLUETOOTH, "bluetooth"},
		{ CAPA_WIFI,      "wifi"},
		{ CAPA_LORA,      "lora"},
};

static ssize_t capab_show_value(struct kobject *kobj, struct kobj_attribute *attr, char *buf) {
	int i;
	const int count = sizeof(capabilities_map)/sizeof(capabilities_map[0]);

	for (i = 0; i < count; i++) {
		if (strcmp(capabilities_map[i].name, attr->attr.name) == 0) {
			return snprintf(buf, 32, "%u\n", DEVICE_CAPA(id_eeprom.capa, capabilities_map[i].bitvalue) != 0);
		}
	}

	return (ssize_t)-1;
}

static DEVICE_ATTR_RO_MTS(capa_attr_gps,  "gps",       capab_show_value);
static DEVICE_ATTR_RO_MTS(capa_attr_din,  "din",       capab_show_value);
static DEVICE_ATTR_RO_MTS(capa_attr_dout, "dout",      capab_show_value);
static DEVICE_ATTR_RO_MTS(capa_attr_adc,  "adc",       capab_show_value);
static DEVICE_ATTR_RO_MTS(capa_attr_bt,   "bluetooth", capab_show_value);
static DEVICE_ATTR_RO_MTS(capa_attr_wifi, "wifi",      capab_show_value);
static DEVICE_ATTR_RO_MTS(capa_attr_lora, "lora",      capab_show_value);

static struct attribute *mts_capa_attributes[] = {
		&capa_attr_gps.attr,
		&capa_attr_din.attr,
		&capa_attr_dout.attr,
		&capa_attr_adc.attr,
		&capa_attr_bt.attr,
		&capa_attr_wifi.attr,
		&capa_attr_lora.attr,
		NULL,
};

static struct attribute_group mts_capa_attr_group = {
	.attrs = mts_capa_attributes
};

static struct kobject *mts_capa_kobject = NULL;

static int mts_capab_dir_create(void)
{
	mts_capa_kobject = kobject_create_and_add("capability", &mts_io_platform_device->dev.kobj);
	if (!mts_capa_kobject) {
		log_error("kobject_create_and_add for capability directory failed");
		return -ENOMEM;
	}

	if (sysfs_create_group(mts_capa_kobject, &mts_capa_attr_group)) {
		log_error("sysfs_create_group failed to create capability group");
		return -ENOMEM;
	}

	return 0;
}

static void mts_capab_dir_delete(void)
{
	if (mts_capa_kobject) {
		kobject_put(mts_capa_kobject);
	}
}