xref: /openbmc/linux/drivers/iio/chemical/sps30.c (revision be709d48)
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;
121 		/* fall through */
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 	s32 data[4 + 2]; /* PM1, PM2P5, PM4, PM10, timestamp */
234 
235 	mutex_lock(&state->lock);
236 	ret = sps30_do_meas(state, data, 4);
237 	mutex_unlock(&state->lock);
238 	if (ret)
239 		goto err;
240 
241 	iio_push_to_buffers_with_timestamp(indio_dev, data,
242 					   iio_get_time_ns(indio_dev));
243 err:
244 	iio_trigger_notify_done(indio_dev->trig);
245 
246 	return IRQ_HANDLED;
247 }
248 
249 static int sps30_read_raw(struct iio_dev *indio_dev,
250 			  struct iio_chan_spec const *chan,
251 			  int *val, int *val2, long mask)
252 {
253 	struct sps30_state *state = iio_priv(indio_dev);
254 	int data[4], ret = -EINVAL;
255 
256 	switch (mask) {
257 	case IIO_CHAN_INFO_PROCESSED:
258 		switch (chan->type) {
259 		case IIO_MASSCONCENTRATION:
260 			mutex_lock(&state->lock);
261 			/* read up to the number of bytes actually needed */
262 			switch (chan->channel2) {
263 			case IIO_MOD_PM1:
264 				ret = sps30_do_meas(state, data, 1);
265 				break;
266 			case IIO_MOD_PM2P5:
267 				ret = sps30_do_meas(state, data, 2);
268 				break;
269 			case IIO_MOD_PM4:
270 				ret = sps30_do_meas(state, data, 3);
271 				break;
272 			case IIO_MOD_PM10:
273 				ret = sps30_do_meas(state, data, 4);
274 				break;
275 			}
276 			mutex_unlock(&state->lock);
277 			if (ret)
278 				return ret;
279 
280 			*val = data[chan->address] / 100;
281 			*val2 = (data[chan->address] % 100) * 10000;
282 
283 			return IIO_VAL_INT_PLUS_MICRO;
284 		default:
285 			return -EINVAL;
286 		}
287 	case IIO_CHAN_INFO_SCALE:
288 		switch (chan->type) {
289 		case IIO_MASSCONCENTRATION:
290 			switch (chan->channel2) {
291 			case IIO_MOD_PM1:
292 			case IIO_MOD_PM2P5:
293 			case IIO_MOD_PM4:
294 			case IIO_MOD_PM10:
295 				*val = 0;
296 				*val2 = 10000;
297 
298 				return IIO_VAL_INT_PLUS_MICRO;
299 			default:
300 				return -EINVAL;
301 			}
302 		default:
303 			return -EINVAL;
304 		}
305 	}
306 
307 	return -EINVAL;
308 }
309 
310 static int sps30_do_cmd_reset(struct sps30_state *state)
311 {
312 	int ret;
313 
314 	ret = sps30_do_cmd(state, SPS30_RESET, NULL, 0);
315 	msleep(300);
316 	/*
317 	 * Power-on-reset causes sensor to produce some glitch on i2c bus and
318 	 * some controllers end up in error state. Recover simply by placing
319 	 * some data on the bus, for example STOP_MEAS command, which
320 	 * is NOP in this case.
321 	 */
322 	sps30_do_cmd(state, SPS30_STOP_MEAS, NULL, 0);
323 	state->state = RESET;
324 
325 	return ret;
326 }
327 
328 static ssize_t start_cleaning_store(struct device *dev,
329 				    struct device_attribute *attr,
330 				    const char *buf, size_t len)
331 {
332 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
333 	struct sps30_state *state = iio_priv(indio_dev);
334 	int val, ret;
335 
336 	if (kstrtoint(buf, 0, &val) || val != 1)
337 		return -EINVAL;
338 
339 	mutex_lock(&state->lock);
340 	ret = sps30_do_cmd(state, SPS30_START_FAN_CLEANING, NULL, 0);
341 	mutex_unlock(&state->lock);
342 	if (ret)
343 		return ret;
344 
345 	return len;
346 }
347 
348 static ssize_t cleaning_period_show(struct device *dev,
349 				      struct device_attribute *attr,
350 				      char *buf)
351 {
352 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
353 	struct sps30_state *state = iio_priv(indio_dev);
354 	u8 tmp[4];
355 	int ret;
356 
357 	mutex_lock(&state->lock);
358 	ret = sps30_do_cmd(state, SPS30_READ_AUTO_CLEANING_PERIOD, tmp, 4);
359 	mutex_unlock(&state->lock);
360 	if (ret)
361 		return ret;
362 
363 	return sprintf(buf, "%d\n", get_unaligned_be32(tmp));
364 }
365 
366 static ssize_t cleaning_period_store(struct device *dev,
367 				       struct device_attribute *attr,
368 				       const char *buf, size_t len)
369 {
370 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
371 	struct sps30_state *state = iio_priv(indio_dev);
372 	int val, ret;
373 	u8 tmp[4];
374 
375 	if (kstrtoint(buf, 0, &val))
376 		return -EINVAL;
377 
378 	if ((val < SPS30_AUTO_CLEANING_PERIOD_MIN) ||
379 	    (val > SPS30_AUTO_CLEANING_PERIOD_MAX))
380 		return -EINVAL;
381 
382 	put_unaligned_be32(val, tmp);
383 
384 	mutex_lock(&state->lock);
385 	ret = sps30_do_cmd(state, SPS30_AUTO_CLEANING_PERIOD, tmp, 0);
386 	if (ret) {
387 		mutex_unlock(&state->lock);
388 		return ret;
389 	}
390 
391 	msleep(20);
392 
393 	/*
394 	 * sensor requires reset in order to return up to date self cleaning
395 	 * period
396 	 */
397 	ret = sps30_do_cmd_reset(state);
398 	if (ret)
399 		dev_warn(dev,
400 			 "period changed but reads will return the old value\n");
401 
402 	mutex_unlock(&state->lock);
403 
404 	return len;
405 }
406 
407 static ssize_t cleaning_period_available_show(struct device *dev,
408 					      struct device_attribute *attr,
409 					      char *buf)
410 {
411 	return snprintf(buf, PAGE_SIZE, "[%d %d %d]\n",
412 			SPS30_AUTO_CLEANING_PERIOD_MIN, 1,
413 			SPS30_AUTO_CLEANING_PERIOD_MAX);
414 }
415 
416 static IIO_DEVICE_ATTR_WO(start_cleaning, 0);
417 static IIO_DEVICE_ATTR_RW(cleaning_period, 0);
418 static IIO_DEVICE_ATTR_RO(cleaning_period_available, 0);
419 
420 static struct attribute *sps30_attrs[] = {
421 	&iio_dev_attr_start_cleaning.dev_attr.attr,
422 	&iio_dev_attr_cleaning_period.dev_attr.attr,
423 	&iio_dev_attr_cleaning_period_available.dev_attr.attr,
424 	NULL
425 };
426 
427 static const struct attribute_group sps30_attr_group = {
428 	.attrs = sps30_attrs,
429 };
430 
431 static const struct iio_info sps30_info = {
432 	.attrs = &sps30_attr_group,
433 	.read_raw = sps30_read_raw,
434 };
435 
436 #define SPS30_CHAN(_index, _mod) { \
437 	.type = IIO_MASSCONCENTRATION, \
438 	.modified = 1, \
439 	.channel2 = IIO_MOD_ ## _mod, \
440 	.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED), \
441 	.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE), \
442 	.address = _mod, \
443 	.scan_index = _index, \
444 	.scan_type = { \
445 		.sign = 'u', \
446 		.realbits = 19, \
447 		.storagebits = 32, \
448 		.endianness = IIO_CPU, \
449 	}, \
450 }
451 
452 static const struct iio_chan_spec sps30_channels[] = {
453 	SPS30_CHAN(0, PM1),
454 	SPS30_CHAN(1, PM2P5),
455 	SPS30_CHAN(2, PM4),
456 	SPS30_CHAN(3, PM10),
457 	IIO_CHAN_SOFT_TIMESTAMP(4),
458 };
459 
460 static void sps30_stop_meas(void *data)
461 {
462 	struct sps30_state *state = data;
463 
464 	sps30_do_cmd(state, SPS30_STOP_MEAS, NULL, 0);
465 }
466 
467 static const unsigned long sps30_scan_masks[] = { 0x0f, 0x00 };
468 
469 static int sps30_probe(struct i2c_client *client)
470 {
471 	struct iio_dev *indio_dev;
472 	struct sps30_state *state;
473 	u8 buf[32];
474 	int ret;
475 
476 	if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C))
477 		return -EOPNOTSUPP;
478 
479 	indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*state));
480 	if (!indio_dev)
481 		return -ENOMEM;
482 
483 	state = iio_priv(indio_dev);
484 	i2c_set_clientdata(client, indio_dev);
485 	state->client = client;
486 	state->state = RESET;
487 	indio_dev->dev.parent = &client->dev;
488 	indio_dev->info = &sps30_info;
489 	indio_dev->name = client->name;
490 	indio_dev->channels = sps30_channels;
491 	indio_dev->num_channels = ARRAY_SIZE(sps30_channels);
492 	indio_dev->modes = INDIO_DIRECT_MODE;
493 	indio_dev->available_scan_masks = sps30_scan_masks;
494 
495 	mutex_init(&state->lock);
496 	crc8_populate_msb(sps30_crc8_table, SPS30_CRC8_POLYNOMIAL);
497 
498 	ret = sps30_do_cmd_reset(state);
499 	if (ret) {
500 		dev_err(&client->dev, "failed to reset device\n");
501 		return ret;
502 	}
503 
504 	ret = sps30_do_cmd(state, SPS30_READ_SERIAL, buf, sizeof(buf));
505 	if (ret) {
506 		dev_err(&client->dev, "failed to read serial number\n");
507 		return ret;
508 	}
509 	/* returned serial number is already NUL terminated */
510 	dev_info(&client->dev, "serial number: %s\n", buf);
511 
512 	ret = devm_add_action_or_reset(&client->dev, sps30_stop_meas, state);
513 	if (ret)
514 		return ret;
515 
516 	ret = devm_iio_triggered_buffer_setup(&client->dev, indio_dev, NULL,
517 					      sps30_trigger_handler, NULL);
518 	if (ret)
519 		return ret;
520 
521 	return devm_iio_device_register(&client->dev, indio_dev);
522 }
523 
524 static const struct i2c_device_id sps30_id[] = {
525 	{ "sps30" },
526 	{ }
527 };
528 MODULE_DEVICE_TABLE(i2c, sps30_id);
529 
530 static const struct of_device_id sps30_of_match[] = {
531 	{ .compatible = "sensirion,sps30" },
532 	{ }
533 };
534 MODULE_DEVICE_TABLE(of, sps30_of_match);
535 
536 static struct i2c_driver sps30_driver = {
537 	.driver = {
538 		.name = "sps30",
539 		.of_match_table = sps30_of_match,
540 	},
541 	.id_table = sps30_id,
542 	.probe_new = sps30_probe,
543 };
544 module_i2c_driver(sps30_driver);
545 
546 MODULE_AUTHOR("Tomasz Duszynski <tduszyns@gmail.com>");
547 MODULE_DESCRIPTION("Sensirion SPS30 particulate matter sensor driver");
548 MODULE_LICENSE("GPL v2");
549