Home | History | Annotate | Line # | Download | only in i2c
      1 /*	$NetBSD: am2315.c,v 1.7 2022/03/30 00:06:50 pgoyette Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2017 Brad Spencer <brad (at) anduin.eldar.org>
      5  *
      6  * Permission to use, copy, modify, and distribute this software for any
      7  * purpose with or without fee is hereby granted, provided that the above
      8  * copyright notice and this permission notice appear in all copies.
      9  *
     10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     17  */
     18 
     19 #include <sys/cdefs.h>
     20 __KERNEL_RCSID(0, "$NetBSD: am2315.c,v 1.7 2022/03/30 00:06:50 pgoyette Exp $");
     21 
     22 /*
     23  * Driver for the Aosong AM2315
     24  */
     25 
     26 #include <sys/param.h>
     27 #include <sys/systm.h>
     28 #include <sys/kernel.h>
     29 #include <sys/device.h>
     30 #include <sys/module.h>
     31 #include <sys/sysctl.h>
     32 #include <sys/condvar.h>
     33 #include <sys/mutex.h>
     34 #include <sys/time.h>
     35 
     36 #include <dev/sysmon/sysmonvar.h>
     37 #include <dev/i2c/i2cvar.h>
     38 #include <dev/i2c/am2315reg.h>
     39 #include <dev/i2c/am2315var.h>
     40 
     41 static uint16_t am2315_crc(uint8_t *, size_t);
     42 static int 	am2315_poke(struct am2315_sc *);
     43 static int 	am2315_poke_m(i2c_tag_t, i2c_addr_t, const char *, bool);
     44 static int 	am2315_match(device_t, cfdata_t, void *);
     45 static void 	am2315_attach(device_t, device_t, void *);
     46 static int 	am2315_detach(device_t, int);
     47 static void 	am2315_refresh(struct sysmon_envsys *, envsys_data_t *);
     48 static int 	am2315_verify_sysctl(SYSCTLFN_ARGS);
     49 
     50 #define AM2315_DEBUG
     51 #ifdef AM2315_DEBUG
     52 #define DPRINTF(s, l, x) \
     53     do { \
     54 	if (l <= s->sc_am2315debug) \
     55 	printf x; \
     56     } while (/*CONSTCOND*/0)
     57 #else
     58 #define DPRINTF(s, l, x)
     59 #endif
     60 
     61 CFATTACH_DECL_NEW(am2315temp, sizeof(struct am2315_sc),
     62     am2315_match, am2315_attach, am2315_detach, NULL);
     63 
     64 static struct am2315_sensor am2315_sensors[] = {
     65 	{
     66 		.desc = "humidity",
     67 		.type = ENVSYS_SRELHUMIDITY,
     68 	},
     69 	{
     70 		.desc = "temperature",
     71 		.type = ENVSYS_STEMP,
     72 	}
     73 };
     74 
     75 static uint16_t
     76 am2315_crc(uint8_t *data, size_t len)
     77 {
     78 	uint16_t crc = 0xffff;
     79 
     80 	for (size_t j = 0; j < len; j++) {
     81 		crc ^= data[j];
     82 		for (size_t i = 0; i < 8; i++) {
     83 			if (crc & 0x01) {
     84 				crc >>= 1;
     85 				crc ^= 0xA001;
     86 			} else {
     87 				crc >>= 1;
     88 			}
     89 		}
     90 	}
     91 
     92 	return crc;
     93 }
     94 
     95 int
     96 am2315_verify_sysctl(SYSCTLFN_ARGS)
     97 {
     98 	int error, t;
     99 	struct sysctlnode node;
    100 
    101 	node = *rnode;
    102 	t = *(int *)rnode->sysctl_data;
    103 	node.sysctl_data = &t;
    104 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    105 	if (error || newp == NULL)
    106 		return error;
    107 
    108 	if (t < 0)
    109 		return EINVAL;
    110 
    111 	*(int *) rnode->sysctl_data = t;
    112 
    113 	return 0;
    114 }
    115 
    116 static int
    117 am2315_cmd(i2c_tag_t tag, i2c_addr_t addr, uint8_t dir, uint8_t cmd,
    118     uint8_t clen, uint8_t *buf, size_t blen)
    119 {
    120 	uint8_t command[] = { dir, cmd, clen };
    121 	if (buf)
    122 		memset(buf, 0xff, blen);
    123 	uint8_t reg = dir == AM2315_READ_REGISTERS ?
    124 	    I2C_OP_READ_WITH_STOP : I2C_OP_WRITE_WITH_STOP;
    125 
    126 	return iic_exec(tag, reg, addr, command,
    127 	    __arraycount(command), buf, blen, 0);
    128 }
    129 
    130 static int
    131 am2315_read_regs(struct am2315_sc *sc, uint8_t cmd, uint8_t clen, uint8_t *buf,
    132     size_t blen)
    133 {
    134 	return am2315_cmd(sc->sc_tag, sc->sc_addr, AM2315_READ_REGISTERS,
    135 	    cmd, clen, buf, blen);
    136 }
    137 
    138 static int
    139 am2315_poke(struct am2315_sc *sc)
    140 {
    141 	return am2315_poke_m(sc->sc_tag, sc->sc_addr, device_xname(sc->sc_dev),
    142 	    sc->sc_am2315debug >= 2);
    143 }
    144 
    145 static int
    146 am2315_poke_m(i2c_tag_t tag, i2c_addr_t addr, const char *name, bool debug)
    147 {
    148 	uint8_t buf[5];
    149 	int error;
    150 
    151 	error = am2315_cmd(tag, addr, AM2315_WRITE_REGISTERS,
    152 	    AM2315_REGISTER_HIGH_USER1, 1, NULL, 0);
    153 	if (debug)
    154 		printf("%s: poke 1: %d\n", name, error);
    155 
    156 	if (error)
    157 		delay(2800);
    158 
    159 	error = am2315_cmd(tag, addr, AM2315_READ_REGISTERS,
    160 	    AM2315_REGISTER_STATUS, 1, buf, __arraycount(buf));
    161 	if (debug)
    162 		printf("%s: poke 2: %d %02x %02x %02x %02x%02x\n", name, error,
    163 		    buf[0], buf[1], buf[2], buf[3], buf[4]);
    164 
    165 	if (error)
    166 		delay(2800);
    167 	return error;
    168 }
    169 
    170 static int
    171 am2315_match(device_t parent, cfdata_t match, void *aux)
    172 {
    173 	struct i2c_attach_args *ia = aux;
    174 	int match_result;
    175 
    176 	if (iic_use_direct_match(ia, match, NULL, &match_result))
    177 		return match_result;
    178 
    179 	/* indirect config - check for standard address */
    180 	if (ia->ia_addr == AM2315_TYPICAL_ADDR)
    181 		return I2C_MATCH_ADDRESS_ONLY;
    182 
    183 	return 0;
    184 }
    185 
    186 static void
    187 am2315_attach(device_t parent, device_t self, void *aux)
    188 {
    189 	struct am2315_sc *sc = device_private(self);
    190 	struct i2c_attach_args *ia = aux;
    191 	uint8_t buf[11];
    192 	int error;
    193 	uint16_t crc, readcrc, model;
    194 	uint8_t chipver;
    195 	uint32_t id;
    196 	bool modelgood, chipvergood, idgood;
    197 
    198 	sc->sc_dev = self;
    199 	sc->sc_tag = ia->ia_tag;
    200 	sc->sc_addr = ia->ia_addr;
    201 	sc->sc_am2315debug = 0;
    202 	sc->sc_readcount = 2;
    203 	sc->sc_readticks = 100;
    204 	sc->sc_sme = NULL;
    205 
    206 	aprint_normal("\n");
    207 
    208 	mutex_init(&sc->sc_mutex, MUTEX_DEFAULT, IPL_NONE);
    209 	mutex_init(&sc->sc_waitmutex, MUTEX_DEFAULT, IPL_NONE);
    210 	cv_init(&sc->sc_condwait, "am2315wait");
    211 
    212 	sc->sc_numsensors = __arraycount(am2315_sensors);
    213 
    214 	if ((sc->sc_sme = sysmon_envsys_create()) == NULL) {
    215 		aprint_error_dev(self, "unable to create sysmon structure\n");
    216 		return;
    217 	}
    218 
    219 	/* XXX: sysctl's not destroyed on failure */
    220 	const struct sysctlnode *cnode;
    221 	int sysctlroot_num;
    222 	if ((error = sysctl_createv(&sc->sc_am2315log, 0, NULL, &cnode, 0,
    223 	    CTLTYPE_NODE, device_xname(self),
    224 	    SYSCTL_DESCR("am2315 controls"), NULL, 0, NULL, 0, CTL_HW,
    225 	    CTL_CREATE, CTL_EOL)) != 0)
    226 		goto badsysctl;
    227 	sysctlroot_num = cnode->sysctl_num;
    228 
    229 #ifdef AM2315_DEBUG
    230 	if ((error = sysctl_createv(&sc->sc_am2315log, 0, NULL, &cnode,
    231 	    CTLFLAG_READWRITE, CTLTYPE_INT, "debug",
    232 	    SYSCTL_DESCR("Debug level"), am2315_verify_sysctl, 0,
    233 	    &sc->sc_am2315debug, 0, CTL_HW, sysctlroot_num, CTL_CREATE,
    234 	    CTL_EOL)) != 0)
    235 		goto badsysctl;
    236 
    237 #endif
    238 
    239 	if ((error = sysctl_createv(&sc->sc_am2315log, 0, NULL, &cnode,
    240 	    CTLFLAG_READWRITE, CTLTYPE_INT, "readcount",
    241 	    SYSCTL_DESCR("Number of times to read the sensor"),
    242 	    am2315_verify_sysctl, 0, &sc->sc_readcount, 0, CTL_HW,
    243 	    sysctlroot_num, CTL_CREATE, CTL_EOL)) != 0)
    244 		goto badsysctl;
    245 
    246 	if ((error = sysctl_createv(&sc->sc_am2315log, 0, NULL, &cnode,
    247 	    CTLFLAG_READWRITE, CTLTYPE_INT, "readticks",
    248 	    SYSCTL_DESCR("Number of ticks between reads"),
    249 	    am2315_verify_sysctl, 0, &sc->sc_readticks, 0, CTL_HW,
    250 	    sysctlroot_num, CTL_CREATE, CTL_EOL)) != 0)
    251 		goto badsysctl;
    252 
    253 	if ((error = iic_acquire_bus(sc->sc_tag, 0)) != 0) {
    254 		aprint_error_dev(self,
    255 		    "Could not acquire iic bus: %d\n", error);
    256 		return;
    257 	}
    258 	am2315_poke(sc);
    259 
    260 #define DUMP(a) \
    261     DPRINTF(sc, 2, ("%s: read cmd+len+%s+crcl+crch values: %02x %02x " \
    262 	"%02x%02x %02x%02x -- %02x%02x%02x%02x%02x -- %04x %04x\n", a, \
    263 	device_xname(self), buf[0], buf[1], buf[2], buf[3], \
    264 	buf[4], buf[5], buf[6], buf[7], buf[8], buf[9], \
    265 	buf[10], crc, readcrc))
    266 
    267 	error = am2315_read_regs(sc, AM2315_REGISTER_HIGH_MODEL, 2, buf, 6);
    268 	if (error)
    269 		aprint_error_dev(sc->sc_dev, "read model: %d\n", error);
    270 	readcrc = buf[5] << 8 | buf[4];
    271 	crc = am2315_crc(buf, 4);
    272 	DUMP("modh+modl");
    273 	model = buf[2] << 8 | buf[3];
    274 	modelgood = buf[0] == AM2315_READ_REGISTERS && buf[1] == 2
    275 	    && crc == readcrc;
    276 
    277 	error = am2315_read_regs(sc, AM2315_REGISTER_VERSION, 1, buf, 5);
    278 	if (error)
    279 		aprint_error_dev(self, "read chipver: %d\n", error);
    280 	readcrc = buf[4] << 8 | buf[3];
    281 	crc = am2315_crc(buf, 3);
    282 	DUMP("ver");
    283 	chipver = buf[2];
    284 	chipvergood = buf[0] == AM2315_READ_REGISTERS && buf[1] == 1
    285 	    && crc == readcrc;
    286 
    287 	error = am2315_read_regs(sc, AM2315_REGISTER_ID_PT_24_31, 2, buf, 6);
    288 	if (error)
    289 		aprint_error_dev(self, "read id 1: %d\n", error);
    290 	readcrc = buf[5] << 8 | buf[4];
    291 	crc = am2315_crc(buf, 4);
    292 	DUMP("id1+id2");
    293 	id = buf[2] << 8 | buf[3];
    294 	idgood = buf[0] == AM2315_READ_REGISTERS && buf[1] == 2
    295 	    && crc == readcrc;
    296 
    297 	error = am2315_read_regs(sc, AM2315_REGISTER_ID_PT_8_15, 2, buf, 6);
    298 	if (error)
    299 		aprint_error_dev(self, "read id 2: %d\n", error);
    300 	readcrc = buf[5] << 8 | buf[4];
    301 	crc = am2315_crc(buf, 4);
    302 	DUMP("id3+id4");
    303 	id = id << 8 | buf[2];
    304 	id = id << 8 | buf[3];
    305 	idgood = buf[0] == AM2315_READ_REGISTERS && buf[1] == 2
    306 	    && crc == readcrc && idgood;
    307 
    308 	iic_release_bus(sc->sc_tag, 0);
    309 
    310 	for (int i = 0; i < sc->sc_numsensors; i++) {
    311 		strlcpy(sc->sc_sensors[i].desc, am2315_sensors[i].desc,
    312 		    sizeof(sc->sc_sensors[i].desc));
    313 
    314 		sc->sc_sensors[i].units = am2315_sensors[i].type;
    315 		sc->sc_sensors[i].state = ENVSYS_SINVALID;
    316 
    317 		DPRINTF(sc, 2, ("am2315_attach: registering sensor %d (%s)\n",
    318 		    i, sc->sc_sensors[i].desc));
    319 
    320 		error = sysmon_envsys_sensor_attach(sc->sc_sme,
    321 		    &sc->sc_sensors[i]);
    322 		if (error) {
    323 			aprint_error_dev(self, "unable to attach sensor %d\n",
    324 			    error);
    325 			goto badregister;
    326 		}
    327 	}
    328 
    329 	sc->sc_sme->sme_name = device_xname(sc->sc_dev);
    330 	sc->sc_sme->sme_cookie = sc;
    331 	sc->sc_sme->sme_refresh = am2315_refresh;
    332 
    333 	DPRINTF(sc, 2, ("am2315_attach: registering with envsys\n"));
    334 
    335 	error = sysmon_envsys_register(sc->sc_sme);
    336 	if (error) {
    337 		aprint_error_dev(self, "unable to register with sysmon %d\n",
    338 		    error);
    339 		goto badregister;
    340 	}
    341 	aprint_normal_dev(self, "Aosong AM2315, Model: %04x%s Version: %02x%s"
    342 	    " ID: %08x%s",
    343 	    model, (modelgood ? "," : "(inaccurate),"),
    344 	    chipver, (chipvergood ? "," : "(inaccurate),"),
    345 	    id, (idgood ? "\n" : "(inaccurate)\n"));
    346 	return;
    347 
    348 badsysctl:
    349 	aprint_error_dev(self, ": can't setup sysctl tree (%d)\n", error);
    350 	return;
    351 badregister:
    352 	sysmon_envsys_destroy(sc->sc_sme);
    353 	sc->sc_sme = NULL;
    354 }
    355 
    356 static void
    357 am2315_refresh(struct sysmon_envsys * sme, envsys_data_t * edata)
    358 {
    359 	struct am2315_sc *sc;
    360 	uint8_t buf[11], thecommand;
    361 	uint16_t crc, readcrc;
    362 	int  error, rv;
    363 	uint32_t val32;
    364 	bool istempneg = false;
    365 
    366 	sc = sme->sme_cookie;
    367 	edata->state = ENVSYS_SINVALID;
    368 
    369 	mutex_enter(&sc->sc_mutex);
    370 	error = iic_acquire_bus(sc->sc_tag, 0);
    371 	if (error) {
    372 		DPRINTF(sc, 2, ("%s: Could not acquire i2c bus: %d\n",
    373 		    device_xname(sc->sc_dev), error));
    374 		goto out;
    375 	}
    376 
    377 	switch (edata->sensor) {
    378 	case AM2315_HUMIDITY_SENSOR:
    379 		thecommand = AM2315_REGISTER_HIGH_RH;
    380 		break;
    381 	case AM2315_TEMP_SENSOR:
    382 		thecommand = AM2315_REGISTER_HIGH_TEMP;
    383 		break;
    384 	default:
    385 		DPRINTF(sc, 2, ("%s: bad sensor %d\n",
    386 		    device_xname(sc->sc_dev), edata->sensor));
    387 		goto out;
    388 	}
    389 
    390 	for (int count = 0; ;) {
    391 		am2315_poke(sc);
    392 
    393 		if ((error = am2315_read_regs(sc, thecommand, 2, buf, 6)) != 0)
    394 			  DPRINTF(sc, 2, ("%s: Read sensor %d error: %d\n",
    395 			      device_xname(sc->sc_dev),edata->sensor, error));
    396 
    397 		readcrc = buf[5] << 8 | buf[4];
    398 		crc = am2315_crc(buf, 4);
    399 
    400 		DPRINTF(sc, 2, ("%s: read cmd+len+dh+dl+crch+crcl values: %02x"
    401 		    " %02x %02x%02x %02x%02x -- %04x %04x -- %d\n",
    402 		    device_xname(sc->sc_dev), buf[0], buf[1], buf[2],
    403 		    buf[3], buf[4], buf[5], crc, readcrc, count));
    404 		if (++count == sc->sc_readcount)
    405 			break;
    406 		mutex_enter(&sc->sc_waitmutex);
    407 		rv = cv_timedwait(&sc->sc_condwait, &sc->sc_waitmutex,
    408 		    sc->sc_readticks);
    409 		DPRINTF(sc, 2, ("%s: wait rv: %d\n", device_xname(sc->sc_dev),
    410 		    rv));
    411 		mutex_exit(&sc->sc_waitmutex);
    412 	}
    413 
    414 	iic_release_bus(sc->sc_tag, 0);
    415 
    416 	if (buf[0] != AM2315_READ_REGISTERS || buf[1] != 2 ||
    417 	    crc != readcrc) {
    418 		DPRINTF(sc, 2, ("%s: Invalid sensor data for %d\n",
    419 		    device_xname(sc->sc_dev), edata->sensor));
    420 		goto out;
    421 	}
    422 
    423 	switch (edata->sensor) {
    424 	case AM2315_HUMIDITY_SENSOR:
    425 		val32 = buf[2] << 8 | buf[3];
    426 		val32 = val32 * 100000;
    427 		DPRINTF(sc, 2, ("%s: read translated values RH: %x\n",
    428 		    device_xname(sc->sc_dev), val32));
    429 		edata->value_cur = val32;
    430 		edata->state = ENVSYS_SVALID;
    431 		break;
    432 	case AM2315_TEMP_SENSOR:
    433 		istempneg = (buf[2] & AM2315_TEMP_NEGATIVE);
    434 		buf[2] = buf[2] & (~AM2315_TEMP_NEGATIVE);
    435 		val32 = buf[2] << 8 | buf[3];
    436 		if (istempneg) {
    437 			val32 = 273150000 - (val32 * 100000);
    438 		} else {
    439 			val32 = (val32 * 100000) + 273150000;
    440 		}
    441 		DPRINTF(sc, 2, ("%s: read translated values TEMP: %x\n",
    442 		    device_xname(sc->sc_dev), val32));
    443 		edata->value_cur = val32;
    444 		edata->state = ENVSYS_SVALID;
    445 		break;
    446 	default:
    447 		panic("bad sensor %d\n", edata->sensor);
    448 	}
    449 out:
    450 	mutex_exit(&sc->sc_mutex);
    451 }
    452 
    453 static int
    454 am2315_detach(device_t self, int flags)
    455 {
    456 	struct am2315_sc *sc = device_private(self);
    457 
    458 	mutex_enter(&sc->sc_mutex);
    459 
    460 	/* Remove the sensors */
    461 	if (sc->sc_sme != NULL)
    462 		sysmon_envsys_unregister(sc->sc_sme);
    463 	mutex_exit(&sc->sc_mutex);
    464 
    465 	/* Destroy the wait cond */
    466 	cv_destroy(&sc->sc_condwait);
    467 
    468 	/* Remove the sysctl tree */
    469 	sysctl_teardown(&sc->sc_am2315log);
    470 
    471 	/* Remove the mutex */
    472 	mutex_destroy(&sc->sc_waitmutex);
    473 	mutex_destroy(&sc->sc_mutex);
    474 
    475 	return 0;
    476 }
    477 
    478 MODULE(MODULE_CLASS_DRIVER, am2315temp, "iic,sysmon_envsys");
    479 
    480 #ifdef _MODULE
    481 #include "ioconf.c"
    482 #endif
    483 
    484 static int
    485 am2315temp_modcmd(modcmd_t cmd, void *opaque)
    486 {
    487 	switch (cmd) {
    488 	case MODULE_CMD_INIT:
    489 #ifdef _MODULE
    490 		return config_init_component(cfdriver_ioconf_am2315temp,
    491 		    cfattach_ioconf_am2315temp, cfdata_ioconf_am2315temp);
    492 #else
    493 		return 0;
    494 #endif
    495 	case MODULE_CMD_FINI:
    496 #ifdef _MODULE
    497 		return config_fini_component(cfdriver_ioconf_am2315temp,
    498 		    cfattach_ioconf_am2315temp, cfdata_ioconf_am2315temp);
    499 #else
    500 		return 0;
    501 #endif
    502 	default:
    503 		return ENOTTY;
    504 	}
    505 }
    506