xref: /openbmc/linux/drivers/iio/chemical/sps30.c (revision 297e77e5)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Sensirion SPS30 particulate matter sensor driver
4  *
5  * Copyright (c) Tomasz Duszynski <tduszyns@gmail.com>
6  *
7  * I2C slave address: 0x69
8  */
9 
10 #include <asm/unaligned.h>
11 #include <linux/crc8.h>
12 #include <linux/delay.h>
13 #include <linux/i2c.h>
14 #include <linux/iio/buffer.h>
15 #include <linux/iio/iio.h>
16 #include <linux/iio/sysfs.h>
17 #include <linux/iio/trigger_consumer.h>
18 #include <linux/iio/triggered_buffer.h>
19 #include <linux/kernel.h>
20 #include <linux/module.h>
21 
22 #define SPS30_CRC8_POLYNOMIAL 0x31
23 /* max number of bytes needed to store PM measurements or serial string */
24 #define SPS30_MAX_READ_SIZE 48
25 /* sensor measures reliably up to 3000 ug / m3 */
26 #define SPS30_MAX_PM 3000
27 /* minimum and maximum self cleaning periods in seconds */
28 #define SPS30_AUTO_CLEANING_PERIOD_MIN 0
29 #define SPS30_AUTO_CLEANING_PERIOD_MAX 604800
30 
31 /* SPS30 commands */
32 #define SPS30_START_MEAS 0x0010
33 #define SPS30_STOP_MEAS 0x0104
34 #define SPS30_RESET 0xd304
35 #define SPS30_READ_DATA_READY_FLAG 0x0202
36 #define SPS30_READ_DATA 0x0300
37 #define SPS30_READ_SERIAL 0xd033
38 #define SPS30_START_FAN_CLEANING 0x5607
39 #define SPS30_AUTO_CLEANING_PERIOD 0x8004
40 /* not a sensor command per se, used only to distinguish write from read */
41 #define SPS30_READ_AUTO_CLEANING_PERIOD 0x8005
42 
43 enum {
44 	PM1,
45 	PM2P5,
46 	PM4,
47 	PM10,
48 };
49 
50 enum {
51 	RESET,
52 	MEASURING,
53 };
54 
55 struct sps30_state {
56 	struct i2c_client *client;
57 	/*
58 	 * Guards against concurrent access to sensor registers.
59 	 * Must be held whenever sequence of commands is to be executed.
60 	 */
61 	struct mutex lock;
62 	int state;
63 };
64 
65 DECLARE_CRC8_TABLE(sps30_crc8_table);
66 
67 static int sps30_write_then_read(struct sps30_state *state, u8 *txbuf,
68 				 int txsize, u8 *rxbuf, int rxsize)
69 {
70 	int ret;
71 
72 	/*
73 	 * Sensor does not support repeated start so instead of
74 	 * sending two i2c messages in a row we just send one by one.
75 	 */
76 	ret = i2c_master_send(state->client, txbuf, txsize);
77 	if (ret != txsize)
78 		return ret < 0 ? ret : -EIO;
79 
80 	if (!rxbuf)
81 		return 0;
82 
83 	ret = i2c_master_recv(state->client, rxbuf, rxsize);
84 	if (ret != rxsize)
85 		return ret < 0 ? ret : -EIO;
86 
87 	return 0;
88 }
89 
90 static int sps30_do_cmd(struct sps30_state *state, u16 cmd, u8 *data, int size)
91 {
92 	/*
93 	 * Internally sensor stores measurements in a following manner:
94 	 *
95 	 * PM1: upper two bytes, crc8, lower two bytes, crc8
96 	 * PM2P5: upper two bytes, crc8, lower two bytes, crc8
97 	 * PM4: upper two bytes, crc8, lower two bytes, crc8
98 	 * PM10: upper two bytes, crc8, lower two bytes, crc8
99 	 *
100 	 * What follows next are number concentration measurements and
101 	 * typical particle size measurement which we omit.
102 	 */
103 	u8 buf[SPS30_MAX_READ_SIZE] = { cmd >> 8, cmd };
104 	int i, ret = 0;
105 
106 	switch (cmd) {
107 	case SPS30_START_MEAS:
108 		buf[2] = 0x03;
109 		buf[3] = 0x00;
110 		buf[4] = crc8(sps30_crc8_table, &buf[2], 2, CRC8_INIT_VALUE);
111 		ret = sps30_write_then_read(state, buf, 5, NULL, 0);
112 		break;
113 	case SPS30_STOP_MEAS:
114 	case SPS30_RESET:
115 	case SPS30_START_FAN_CLEANING:
116 		ret = sps30_write_then_read(state, buf, 2, NULL, 0);
117 		break;
118 	case SPS30_READ_AUTO_CLEANING_PERIOD:
119 		buf[0] = SPS30_AUTO_CLEANING_PERIOD >> 8;
120 		buf[1] = (u8)(SPS30_AUTO_CLEANING_PERIOD & 0xff);
121 		fallthrough;
122 	case SPS30_READ_DATA_READY_FLAG:
123 	case SPS30_READ_DATA:
124 	case SPS30_READ_SERIAL:
125 		/* every two data bytes are checksummed */
126 		size += size / 2;
127 		ret = sps30_write_then_read(state, buf, 2, buf, size);
128 		break;
129 	case SPS30_AUTO_CLEANING_PERIOD:
130 		buf[2] = data[0];
131 		buf[3] = data[1];
132 		buf[4] = crc8(sps30_crc8_table, &buf[2], 2, CRC8_INIT_VALUE);
133 		buf[5] = data[2];
134 		buf[6] = data[3];
135 		buf[7] = crc8(sps30_crc8_table, &buf[5], 2, CRC8_INIT_VALUE);
136 		ret = sps30_write_then_read(state, buf, 8, NULL, 0);
137 		break;
138 	}
139 
140 	if (ret)
141 		return ret;
142 
143 	/* validate received data and strip off crc bytes */
144 	for (i = 0; i < size; i += 3) {
145 		u8 crc = crc8(sps30_crc8_table, &buf[i], 2, CRC8_INIT_VALUE);
146 
147 		if (crc != buf[i + 2]) {
148 			dev_err(&state->client->dev,
149 				"data integrity check failed\n");
150 			return -EIO;
151 		}
152 
153 		*data++ = buf[i];
154 		*data++ = buf[i + 1];
155 	}
156 
157 	return 0;
158 }
159 
160 static s32 sps30_float_to_int_clamped(const u8 *fp)
161 {
162 	int val = get_unaligned_be32(fp);
163 	int mantissa = val & GENMASK(22, 0);
164 	/* this is fine since passed float is always non-negative */
165 	int exp = val >> 23;
166 	int fraction, shift;
167 
168 	/* special case 0 */
169 	if (!exp && !mantissa)
170 		return 0;
171 
172 	exp -= 127;
173 	if (exp < 0) {
174 		/* return values ranging from 1 to 99 */
175 		return ((((1 << 23) + mantissa) * 100) >> 23) >> (-exp);
176 	}
177 
178 	/* return values ranging from 100 to 300000 */
179 	shift = 23 - exp;
180 	val = (1 << exp) + (mantissa >> shift);
181 	if (val >= SPS30_MAX_PM)
182 		return SPS30_MAX_PM * 100;
183 
184 	fraction = mantissa & GENMASK(shift - 1, 0);
185 
186 	return val * 100 + ((fraction * 100) >> shift);
187 }
188 
189 static int sps30_do_meas(struct sps30_state *state, s32 *data, int size)
190 {
191 	int i, ret, tries = 5;
192 	u8 tmp[16];
193 
194 	if (state->state == RESET) {
195 		ret = sps30_do_cmd(state, SPS30_START_MEAS, NULL, 0);
196 		if (ret)
197 			return ret;
198 
199 		state->state = MEASURING;
200 	}
201 
202 	while (tries--) {
203 		ret = sps30_do_cmd(state, SPS30_READ_DATA_READY_FLAG, tmp, 2);
204 		if (ret)
205 			return -EIO;
206 
207 		/* new measurements ready to be read */
208 		if (tmp[1] == 1)
209 			break;
210 
211 		msleep_interruptible(300);
212 	}
213 
214 	if (tries == -1)
215 		return -ETIMEDOUT;
216 
217 	ret = sps30_do_cmd(state, SPS30_READ_DATA, tmp, sizeof(int) * size);
218 	if (ret)
219 		return ret;
220 
221 	for (i = 0; i < size; i++)
222 		data[i] = sps30_float_to_int_clamped(&tmp[4 * i]);
223 
224 	return 0;
225 }
226 
227 static irqreturn_t sps30_trigger_handler(int irq, void *p)
228 {
229 	struct iio_poll_func *pf = p;
230 	struct iio_dev *indio_dev = pf->indio_dev;
231 	struct sps30_state *state = iio_priv(indio_dev);
232 	int ret;
233 	struct {
234 		s32 data[4]; /* PM1, PM2P5, PM4, PM10 */
235 		s64 ts;
236 	} scan;
237 
238 	mutex_lock(&state->lock);
239 	ret = sps30_do_meas(state, scan.data, ARRAY_SIZE(scan.data));
240 	mutex_unlock(&state->lock);
241 	if (ret)
242 		goto err;
243 
244 	iio_push_to_buffers_with_timestamp(indio_dev, &scan,
245 					   iio_get_time_ns(indio_dev));
246 err:
247 	iio_trigger_notify_done(indio_dev->trig);
248 
249 	return IRQ_HANDLED;
250 }
251 
252 static int sps30_read_raw(struct iio_dev *indio_dev,
253 			  struct iio_chan_spec const *chan,
254 			  int *val, int *val2, long mask)
255 {
256 	struct sps30_state *state = iio_priv(indio_dev);
257 	int data[4], ret = -EINVAL;
258 
259 	switch (mask) {
260 	case IIO_CHAN_INFO_PROCESSED:
261 		switch (chan->type) {
262 		case IIO_MASSCONCENTRATION:
263 			mutex_lock(&state->lock);
264 			/* read up to the number of bytes actually needed */
265 			switch (chan->channel2) {
266 			case IIO_MOD_PM1:
267 				ret = sps30_do_meas(state, data, 1);
268 				break;
269 			case IIO_MOD_PM2P5:
270 				ret = sps30_do_meas(state, data, 2);
271 				break;
272 			case IIO_MOD_PM4:
273 				ret = sps30_do_meas(state, data, 3);
274 				break;
275 			case IIO_MOD_PM10:
276 				ret = sps30_do_meas(state, data, 4);
277 				break;
278 			}
279 			mutex_unlock(&state->lock);
280 			if (ret)
281 				return ret;
282 
283 			*val = data[chan->address] / 100;
284 			*val2 = (data[chan->address] % 100) * 10000;
285 
286 			return IIO_VAL_INT_PLUS_MICRO;
287 		default:
288 			return -EINVAL;
289 		}
290 	case IIO_CHAN_INFO_SCALE:
291 		switch (chan->type) {
292 		case IIO_MASSCONCENTRATION:
293 			switch (chan->channel2) {
294 			case IIO_MOD_PM1:
295 			case IIO_MOD_PM2P5:
296 			case IIO_MOD_PM4:
297 			case IIO_MOD_PM10:
298 				*val = 0;
299 				*val2 = 10000;
300 
301 				return IIO_VAL_INT_PLUS_MICRO;
302 			default:
303 				return -EINVAL;
304 			}
305 		default:
306 			return -EINVAL;
307 		}
308 	}
309 
310 	return -EINVAL;
311 }
312 
313 static int sps30_do_cmd_reset(struct sps30_state *state)
314 {
315 	int ret;
316 
317 	ret = sps30_do_cmd(state, SPS30_RESET, NULL, 0);
318 	msleep(300);
319 	/*
320 	 * Power-on-reset causes sensor to produce some glitch on i2c bus and
321 	 * some controllers end up in error state. Recover simply by placing
322 	 * some data on the bus, for example STOP_MEAS command, which
323 	 * is NOP in this case.
324 	 */
325 	sps30_do_cmd(state, SPS30_STOP_MEAS, NULL, 0);
326 	state->state = RESET;
327 
328 	return ret;
329 }
330 
331 static ssize_t start_cleaning_store(struct device *dev,
332 				    struct device_attribute *attr,
333 				    const char *buf, size_t len)
334 {
335 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
336 	struct sps30_state *state = iio_priv(indio_dev);
337 	int val, ret;
338 
339 	if (kstrtoint(buf, 0, &val) || val != 1)
340 		return -EINVAL;
341 
342 	mutex_lock(&state->lock);
343 	ret = sps30_do_cmd(state, SPS30_START_FAN_CLEANING, NULL, 0);
344 	mutex_unlock(&state->lock);
345 	if (ret)
346 		return ret;
347 
348 	return len;
349 }
350 
351 static ssize_t cleaning_period_show(struct device *dev,
352 				      struct device_attribute *attr,
353 				      char *buf)
354 {
355 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
356 	struct sps30_state *state = iio_priv(indio_dev);
357 	u8 tmp[4];
358 	int ret;
359 
360 	mutex_lock(&state->lock);
361 	ret = sps30_do_cmd(state, SPS30_READ_AUTO_CLEANING_PERIOD, tmp, 4);
362 	mutex_unlock(&state->lock);
363 	if (ret)
364 		return ret;
365 
366 	return sprintf(buf, "%d\n", get_unaligned_be32(tmp));
367 }
368 
369 static ssize_t cleaning_period_store(struct device *dev,
370 				       struct device_attribute *attr,
371 				       const char *buf, size_t len)
372 {
373 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
374 	struct sps30_state *state = iio_priv(indio_dev);
375 	int val, ret;
376 	u8 tmp[4];
377 
378 	if (kstrtoint(buf, 0, &val))
379 		return -EINVAL;
380 
381 	if ((val < SPS30_AUTO_CLEANING_PERIOD_MIN) ||
382 	    (val > SPS30_AUTO_CLEANING_PERIOD_MAX))
383 		return -EINVAL;
384 
385 	put_unaligned_be32(val, tmp);
386 
387 	mutex_lock(&state->lock);
388 	ret = sps30_do_cmd(state, SPS30_AUTO_CLEANING_PERIOD, tmp, 0);
389 	if (ret) {
390 		mutex_unlock(&state->lock);
391 		return ret;
392 	}
393 
394 	msleep(20);
395 
396 	/*
397 	 * sensor requires reset in order to return up to date self cleaning
398 	 * period
399 	 */
400 	ret = sps30_do_cmd_reset(state);
401 	if (ret)
402 		dev_warn(dev,
403 			 "period changed but reads will return the old value\n");
404 
405 	mutex_unlock(&state->lock);
406 
407 	return len;
408 }
409 
410 static ssize_t cleaning_period_available_show(struct device *dev,
411 					      struct device_attribute *attr,
412 					      char *buf)
413 {
414 	return snprintf(buf, PAGE_SIZE, "[%d %d %d]\n",
415 			SPS30_AUTO_CLEANING_PERIOD_MIN, 1,
416 			SPS30_AUTO_CLEANING_PERIOD_MAX);
417 }
418 
419 static IIO_DEVICE_ATTR_WO(start_cleaning, 0);
420 static IIO_DEVICE_ATTR_RW(cleaning_period, 0);
421 static IIO_DEVICE_ATTR_RO(cleaning_period_available, 0);
422 
423 static struct attribute *sps30_attrs[] = {
424 	&iio_dev_attr_start_cleaning.dev_attr.attr,
425 	&iio_dev_attr_cleaning_period.dev_attr.attr,
426 	&iio_dev_attr_cleaning_period_available.dev_attr.attr,
427 	NULL
428 };
429 
430 static const struct attribute_group sps30_attr_group = {
431 	.attrs = sps30_attrs,
432 };
433 
434 static const struct iio_info sps30_info = {
435 	.attrs = &sps30_attr_group,
436 	.read_raw = sps30_read_raw,
437 };
438 
439 #define SPS30_CHAN(_index, _mod) { \
440 	.type = IIO_MASSCONCENTRATION, \
441 	.modified = 1, \
442 	.channel2 = IIO_MOD_ ## _mod, \
443 	.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED), \
444 	.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE), \
445 	.address = _mod, \
446 	.scan_index = _index, \
447 	.scan_type = { \
448 		.sign = 'u', \
449 		.realbits = 19, \
450 		.storagebits = 32, \
451 		.endianness = IIO_CPU, \
452 	}, \
453 }
454 
455 static const struct iio_chan_spec sps30_channels[] = {
456 	SPS30_CHAN(0, PM1),
457 	SPS30_CHAN(1, PM2P5),
458 	SPS30_CHAN(2, PM4),
459 	SPS30_CHAN(3, PM10),
460 	IIO_CHAN_SOFT_TIMESTAMP(4),
461 };
462 
463 static void sps30_stop_meas(void *data)
464 {
465 	struct sps30_state *state = data;
466 
467 	sps30_do_cmd(state, SPS30_STOP_MEAS, NULL, 0);
468 }
469 
470 static const unsigned long sps30_scan_masks[] = { 0x0f, 0x00 };
471 
472 static int sps30_probe(struct i2c_client *client)
473 {
474 	struct iio_dev *indio_dev;
475 	struct sps30_state *state;
476 	u8 buf[32];
477 	int ret;
478 
479 	if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C))
480 		return -EOPNOTSUPP;
481 
482 	indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*state));
483 	if (!indio_dev)
484 		return -ENOMEM;
485 
486 	state = iio_priv(indio_dev);
487 	i2c_set_clientdata(client, indio_dev);
488 	state->client = client;
489 	state->state = RESET;
490 	indio_dev->info = &sps30_info;
491 	indio_dev->name = client->name;
492 	indio_dev->channels = sps30_channels;
493 	indio_dev->num_channels = ARRAY_SIZE(sps30_channels);
494 	indio_dev->modes = INDIO_DIRECT_MODE;
495 	indio_dev->available_scan_masks = sps30_scan_masks;
496 
497 	mutex_init(&state->lock);
498 	crc8_populate_msb(sps30_crc8_table, SPS30_CRC8_POLYNOMIAL);
499 
500 	ret = sps30_do_cmd_reset(state);
501 	if (ret) {
502 		dev_err(&client->dev, "failed to reset device\n");
503 		return ret;
504 	}
505 
506 	ret = sps30_do_cmd(state, SPS30_READ_SERIAL, buf, sizeof(buf));
507 	if (ret) {
508 		dev_err(&client->dev, "failed to read serial number\n");
509 		return ret;
510 	}
511 	/* returned serial number is already NUL terminated */
512 	dev_info(&client->dev, "serial number: %s\n", buf);
513 
514 	ret = devm_add_action_or_reset(&client->dev, sps30_stop_meas, state);
515 	if (ret)
516 		return ret;
517 
518 	ret = devm_iio_triggered_buffer_setup(&client->dev, indio_dev, NULL,
519 					      sps30_trigger_handler, NULL);
520 	if (ret)
521 		return ret;
522 
523 	return devm_iio_device_register(&client->dev, indio_dev);
524 }
525 
526 static const struct i2c_device_id sps30_id[] = {
527 	{ "sps30" },
528 	{ }
529 };
530 MODULE_DEVICE_TABLE(i2c, sps30_id);
531 
532 static const struct of_device_id sps30_of_match[] = {
533 	{ .compatible = "sensirion,sps30" },
534 	{ }
535 };
536 MODULE_DEVICE_TABLE(of, sps30_of_match);
537 
538 static struct i2c_driver sps30_driver = {
539 	.driver = {
540 		.name = "sps30",
541 		.of_match_table = sps30_of_match,
542 	},
543 	.id_table = sps30_id,
544 	.probe_new = sps30_probe,
545 };
546 module_i2c_driver(sps30_driver);
547 
548 MODULE_AUTHOR("Tomasz Duszynski <tduszyns@gmail.com>");
549 MODULE_DESCRIPTION("Sensirion SPS30 particulate matter sensor driver");
550 MODULE_LICENSE("GPL v2");
551