+static void handle_packet(const uint8_t *buf, struct sr_dev_inst *sdi,
+ void *info)
+{
+ struct scale_info *scale;
+ float floatval;
+ struct sr_datafeed_packet packet;
+ struct sr_datafeed_analog analog;
+ struct sr_analog_encoding encoding;
+ struct sr_analog_meaning meaning;
+ struct sr_analog_spec spec;
+ struct dev_context *devc;
+
+ scale = (struct scale_info *)sdi->driver;
+
+ devc = sdi->priv;
+
+ /* Note: digits/spec_digits will be overridden later. */
+ sr_analog_init(&analog, &encoding, &meaning, &spec, 0);
+
+ analog.meaning->channels = sdi->channels;
+ analog.num_samples = 1;
+ analog.meaning->mq = 0;
+
+ scale->packet_parse(buf, &floatval, &analog, info);
+ analog.data = &floatval;
+
+ if (analog.meaning->mq != 0) {
+ /* Got a measurement. */
+ packet.type = SR_DF_ANALOG;
+ packet.payload = &analog;
+ sr_session_send(sdi, &packet);
+ sr_sw_limits_update_samples_read(&devc->limits, 1);
+ }
+}
+
+static void handle_new_data(struct sr_dev_inst *sdi, void *info)
+{
+ struct scale_info *scale;
+ struct dev_context *devc;
+ int len, offset;
+ struct sr_serial_dev_inst *serial;
+
+ scale = (struct scale_info *)sdi->driver;
+
+ devc = sdi->priv;
+ serial = sdi->conn;
+
+ /* Try to get as much data as the buffer can hold. */
+ len = SCALE_BUFSIZE - devc->buflen;
+ len = serial_read_nonblocking(serial, devc->buf + devc->buflen, len);
+ if (len == 0)
+ return; /* No new bytes, nothing to do. */
+ if (len < 0) {
+ sr_err("Serial port read error: %d.", len);
+ return;
+ }
+ devc->buflen += len;
+
+ /* Now look for packets in that data. */
+ offset = 0;
+ while ((devc->buflen - offset) >= scale->packet_size) {
+ if (scale->packet_valid(devc->buf + offset)) {
+ handle_packet(devc->buf + offset, sdi, info);
+ offset += scale->packet_size;
+ } else {
+ offset++;
+ }
+ }
+
+ /* If we have any data left, move it to the beginning of our buffer. */
+ if (offset < devc->buflen)
+ memmove(devc->buf, devc->buf + offset, devc->buflen - offset);
+ devc->buflen -= offset;
+}
+