subrascasse

Sub Rascasse: an iPhone dive log for Subsurface cloud storage, with a pure-Swift git client (GPL-2.0)
git clone https://git.schurger.org/subrascasse.git
Log | Files | Refs | README | LICENSE

reefnet_sensus.c (12609B)


      1 /*
      2  * libdivecomputer
      3  *
      4  * Copyright (C) 2008 Jef Driesen
      5  *
      6  * This library is free software; you can redistribute it and/or
      7  * modify it under the terms of the GNU Lesser General Public
      8  * License as published by the Free Software Foundation; either
      9  * version 2.1 of the License, or (at your option) any later version.
     10  *
     11  * This library is distributed in the hope that it will be useful,
     12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     14  * Lesser General Public License for more details.
     15  *
     16  * You should have received a copy of the GNU Lesser General Public
     17  * License along with this library; if not, write to the Free Software
     18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
     19  * MA 02110-1301 USA
     20  */
     21 
     22 #include <string.h> // memcmp, memcpy
     23 #include <stdlib.h> // malloc, free
     24 
     25 #include "reefnet_sensus.h"
     26 #include "context-private.h"
     27 #include "device-private.h"
     28 #include "checksum.h"
     29 #include "array.h"
     30 
     31 #define ISINSTANCE(device) dc_device_isinstance((device), &reefnet_sensus_device_vtable)
     32 
     33 #define SZ_MEMORY    32768
     34 #define SZ_HANDSHAKE 10
     35 
     36 typedef struct reefnet_sensus_device_t {
     37 	dc_device_t base;
     38 	dc_iostream_t *iostream;
     39 	unsigned char handshake[SZ_HANDSHAKE];
     40 	unsigned int waiting;
     41 	unsigned int timestamp;
     42 	unsigned int devtime;
     43 	dc_ticks_t systime;
     44 } reefnet_sensus_device_t;
     45 
     46 static dc_status_t reefnet_sensus_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size);
     47 static dc_status_t reefnet_sensus_device_dump (dc_device_t *abstract, dc_buffer_t *buffer);
     48 static dc_status_t reefnet_sensus_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata);
     49 static dc_status_t reefnet_sensus_device_close (dc_device_t *abstract);
     50 
     51 static const dc_device_vtable_t reefnet_sensus_device_vtable = {
     52 	sizeof(reefnet_sensus_device_t),
     53 	DC_FAMILY_REEFNET_SENSUS,
     54 	reefnet_sensus_device_set_fingerprint, /* set_fingerprint */
     55 	NULL, /* read */
     56 	NULL, /* write */
     57 	reefnet_sensus_device_dump, /* dump */
     58 	reefnet_sensus_device_foreach, /* foreach */
     59 	NULL, /* timesync */
     60 	reefnet_sensus_device_close /* close */
     61 };
     62 
     63 static dc_status_t
     64 reefnet_sensus_extract_dives (dc_device_t *device, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata);
     65 
     66 static dc_status_t
     67 reefnet_sensus_cancel (reefnet_sensus_device_t *device)
     68 {
     69 	dc_status_t status = DC_STATUS_SUCCESS;
     70 	dc_device_t *abstract = (dc_device_t *) device;
     71 
     72 	// Send the command to the device.
     73 	unsigned char command = 0x00;
     74 	status = dc_iostream_write (device->iostream, &command, 1, NULL);
     75 	if (status != DC_STATUS_SUCCESS) {
     76 		ERROR (abstract->context, "Failed to send the command.");
     77 		return status;
     78 	}
     79 
     80 	// The device leaves the waiting state.
     81 	device->waiting = 0;
     82 
     83 	return DC_STATUS_SUCCESS;
     84 }
     85 
     86 
     87 dc_status_t
     88 reefnet_sensus_device_open (dc_device_t **out, dc_context_t *context, dc_iostream_t *iostream)
     89 {
     90 	dc_status_t status = DC_STATUS_SUCCESS;
     91 	reefnet_sensus_device_t *device = NULL;
     92 
     93 	if (out == NULL)
     94 		return DC_STATUS_INVALIDARGS;
     95 
     96 	// Allocate memory.
     97 	device = (reefnet_sensus_device_t *) dc_device_allocate (context, &reefnet_sensus_device_vtable);
     98 	if (device == NULL) {
     99 		ERROR (context, "Failed to allocate memory.");
    100 		return DC_STATUS_NOMEMORY;
    101 	}
    102 
    103 	// Set the default values.
    104 	device->iostream = iostream;
    105 	device->waiting = 0;
    106 	device->timestamp = 0;
    107 	device->systime = (dc_ticks_t) -1;
    108 	device->devtime = 0;
    109 	memset (device->handshake, 0, sizeof (device->handshake));
    110 
    111 	// Set the serial communication protocol (19200 8N1).
    112 	status = dc_iostream_configure (device->iostream, 19200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE);
    113 	if (status != DC_STATUS_SUCCESS) {
    114 		ERROR (context, "Failed to set the terminal attributes.");
    115 		goto error_free;
    116 	}
    117 
    118 	// Set the timeout for receiving data (3000 ms).
    119 	status = dc_iostream_set_timeout (device->iostream, 3000);
    120 	if (status != DC_STATUS_SUCCESS) {
    121 		ERROR (context, "Failed to set the timeout.");
    122 		goto error_free;
    123 	}
    124 
    125 	// Make sure everything is in a sane state.
    126 	dc_iostream_purge (device->iostream, DC_DIRECTION_ALL);
    127 
    128 	*out = (dc_device_t*) device;
    129 
    130 	return DC_STATUS_SUCCESS;
    131 
    132 error_free:
    133 	dc_device_deallocate ((dc_device_t *) device);
    134 	return status;
    135 }
    136 
    137 
    138 static dc_status_t
    139 reefnet_sensus_device_close (dc_device_t *abstract)
    140 {
    141 	dc_status_t status = DC_STATUS_SUCCESS;
    142 	reefnet_sensus_device_t *device = (reefnet_sensus_device_t*) abstract;
    143 	dc_status_t rc = DC_STATUS_SUCCESS;
    144 
    145 	// Safely close the connection if the last handshake was
    146 	// successful, but no data transfer was ever initiated.
    147 	if (device->waiting) {
    148 		rc = reefnet_sensus_cancel (device);
    149 		if (rc != DC_STATUS_SUCCESS) {
    150 			dc_status_set_error(&status, rc);
    151 		}
    152 	}
    153 
    154 	return status;
    155 }
    156 
    157 
    158 dc_status_t
    159 reefnet_sensus_device_get_handshake (dc_device_t *abstract, unsigned char data[], unsigned int size)
    160 {
    161 	reefnet_sensus_device_t *device = (reefnet_sensus_device_t*) abstract;
    162 
    163 	if (!ISINSTANCE (abstract))
    164 		return DC_STATUS_INVALIDARGS;
    165 
    166 	if (size < SZ_HANDSHAKE) {
    167 		ERROR (abstract->context, "Insufficient buffer space available.");
    168 		return DC_STATUS_INVALIDARGS;
    169 	}
    170 
    171 	memcpy (data, device->handshake, SZ_HANDSHAKE);
    172 
    173 	return DC_STATUS_SUCCESS;
    174 }
    175 
    176 
    177 static dc_status_t
    178 reefnet_sensus_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size)
    179 {
    180 	reefnet_sensus_device_t *device = (reefnet_sensus_device_t*) abstract;
    181 
    182 	if (size && size != 4)
    183 		return DC_STATUS_INVALIDARGS;
    184 
    185 	if (size)
    186 		device->timestamp = array_uint32_le (data);
    187 	else
    188 		device->timestamp = 0;
    189 
    190 	return DC_STATUS_SUCCESS;
    191 }
    192 
    193 
    194 static dc_status_t
    195 reefnet_sensus_handshake (reefnet_sensus_device_t *device)
    196 {
    197 	dc_status_t status = DC_STATUS_SUCCESS;
    198 	dc_device_t *abstract = (dc_device_t *) device;
    199 
    200 	// Send the command to the device.
    201 	unsigned char command = 0x0A;
    202 	status = dc_iostream_write (device->iostream, &command, 1, NULL);
    203 	if (status != DC_STATUS_SUCCESS) {
    204 		ERROR (abstract->context, "Failed to send the command.");
    205 		return status;
    206 	}
    207 
    208 	// Receive the answer from the device.
    209 	unsigned char handshake[SZ_HANDSHAKE + 2] = {0};
    210 	status = dc_iostream_read (device->iostream, handshake, sizeof (handshake), NULL);
    211 	if (status != DC_STATUS_SUCCESS) {
    212 		ERROR (abstract->context, "Failed to receive the handshake.");
    213 		return status;
    214 	}
    215 
    216 	// Verify the header of the packet.
    217 	if (handshake[0] != 'O' || handshake[1] != 'K') {
    218 		ERROR (abstract->context, "Unexpected answer header.");
    219 		return DC_STATUS_PROTOCOL;
    220 	}
    221 
    222 	HEXDUMP (abstract->context, DC_LOGLEVEL_DEBUG, "Handshake", handshake + 2, sizeof(handshake) - 2);
    223 
    224 	// The device is now waiting for a data request.
    225 	device->waiting = 1;
    226 
    227 	// Store the clock calibration values.
    228 	device->systime = dc_datetime_now ();
    229 	device->devtime = array_uint32_le (handshake + 8);
    230 
    231 	// Store the handshake packet.
    232 	memcpy (device->handshake, handshake + 2, SZ_HANDSHAKE);
    233 
    234 	// Emit a clock event.
    235 	dc_event_clock_t clock;
    236 	clock.systime = device->systime;
    237 	clock.devtime = device->devtime;
    238 	device_event_emit (&device->base, DC_EVENT_CLOCK, &clock);
    239 
    240 	// Emit a device info event.
    241 	dc_event_devinfo_t devinfo;
    242 	devinfo.model = handshake[2] - '0';
    243 	devinfo.firmware = handshake[3] - '0';
    244 	devinfo.serial = array_uint16_le (handshake + 6);
    245 	device_event_emit (&device->base, DC_EVENT_DEVINFO, &devinfo);
    246 
    247 	// Emit a vendor event.
    248 	dc_event_vendor_t vendor;
    249 	vendor.data = device->handshake;
    250 	vendor.size = sizeof (device->handshake);
    251 	device_event_emit (abstract, DC_EVENT_VENDOR, &vendor);
    252 
    253 	// Wait at least 10 ms to ensures the data line is
    254 	// clear before transmission from the host begins.
    255 
    256 	dc_iostream_sleep (device->iostream, 10);
    257 
    258 	return DC_STATUS_SUCCESS;
    259 }
    260 
    261 
    262 static dc_status_t
    263 reefnet_sensus_device_dump (dc_device_t *abstract, dc_buffer_t *buffer)
    264 {
    265 	dc_status_t status = DC_STATUS_SUCCESS;
    266 	reefnet_sensus_device_t *device = (reefnet_sensus_device_t*) abstract;
    267 
    268 	// Pre-allocate the required amount of memory.
    269 	if (!dc_buffer_reserve (buffer, SZ_MEMORY)) {
    270 		ERROR (abstract->context, "Insufficient buffer space available.");
    271 		return DC_STATUS_NOMEMORY;
    272 	}
    273 
    274 	// Enable progress notifications.
    275 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
    276 	progress.maximum = 4 + SZ_MEMORY + 2 + 3;
    277 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    278 
    279 	// Wake-up the device.
    280 	dc_status_t rc = reefnet_sensus_handshake (device);
    281 	if (rc != DC_STATUS_SUCCESS)
    282 		return rc;
    283 
    284 	// Send the command to the device.
    285 	unsigned char command = 0x40;
    286 	status = dc_iostream_write (device->iostream, &command, 1, NULL);
    287 	if (status != DC_STATUS_SUCCESS) {
    288 		ERROR (abstract->context, "Failed to send the command.");
    289 		return status;
    290 	}
    291 
    292 	// The device leaves the waiting state.
    293 	device->waiting = 0;
    294 
    295 	// Receive the answer from the device.
    296 	unsigned int nbytes = 0;
    297 	unsigned char answer[4 + SZ_MEMORY + 2 + 3] = {0};
    298 	while (nbytes < sizeof (answer)) {
    299 		unsigned int len = sizeof (answer) - nbytes;
    300 		if (len > 128)
    301 			len = 128;
    302 
    303 		status = dc_iostream_read (device->iostream, answer + nbytes, len, NULL);
    304 		if (status != DC_STATUS_SUCCESS) {
    305 			ERROR (abstract->context, "Failed to receive the answer.");
    306 			return status;
    307 		}
    308 
    309 		// Update and emit a progress event.
    310 		progress.current += len;
    311 		device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    312 
    313 		nbytes += len;
    314 	}
    315 
    316 	// Verify the headers of the package.
    317 	if (memcmp (answer, "DATA", 4) != 0 ||
    318 		memcmp (answer + sizeof (answer) - 3, "END", 3) != 0) {
    319 		ERROR (abstract->context, "Unexpected answer start or end byte(s).");
    320 		return DC_STATUS_PROTOCOL;
    321 	}
    322 
    323 	// Verify the checksum of the package.
    324 	unsigned short crc = array_uint16_le (answer + 4 + SZ_MEMORY);
    325 	unsigned short ccrc = checksum_add_uint16 (answer + 4, SZ_MEMORY, 0x00);
    326 	if (crc != ccrc) {
    327 		ERROR (abstract->context, "Unexpected answer checksum.");
    328 		return DC_STATUS_PROTOCOL;
    329 	}
    330 
    331 	dc_buffer_append (buffer, answer + 4, SZ_MEMORY);
    332 
    333 	return DC_STATUS_SUCCESS;
    334 }
    335 
    336 
    337 static dc_status_t
    338 reefnet_sensus_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata)
    339 {
    340 	dc_buffer_t *buffer = dc_buffer_new (SZ_MEMORY);
    341 	if (buffer == NULL)
    342 		return DC_STATUS_NOMEMORY;
    343 
    344 	dc_status_t rc = reefnet_sensus_device_dump (abstract, buffer);
    345 	if (rc != DC_STATUS_SUCCESS) {
    346 		dc_buffer_free (buffer);
    347 		return rc;
    348 	}
    349 
    350 	rc = reefnet_sensus_extract_dives (abstract,
    351 		dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), callback, userdata);
    352 
    353 	dc_buffer_free (buffer);
    354 
    355 	return rc;
    356 }
    357 
    358 
    359 static dc_status_t
    360 reefnet_sensus_extract_dives (dc_device_t *abstract, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata)
    361 {
    362 	reefnet_sensus_device_t *device = (reefnet_sensus_device_t*) abstract;
    363 	dc_context_t *context = (abstract ? abstract->context : NULL);
    364 
    365 	if (abstract && !ISINSTANCE (abstract))
    366 		return DC_STATUS_INVALIDARGS;
    367 
    368 	// Search the entire data stream for start markers.
    369 	unsigned int previous = size;
    370 	unsigned int current = (size >= 7 ? size - 7 : 0);
    371 	while (current > 0) {
    372 		current--;
    373 		if (data[current] == 0xFF && data[current + 6] == 0xFE) {
    374 			// Once a start marker is found, start searching
    375 			// for the end of the dive. The search is now
    376 			// limited to the start of the previous dive.
    377 			int found = 0;
    378 			unsigned int nsamples = 0, count = 0;
    379 			unsigned int offset = current + 7; // Skip non-sample data.
    380 			while (offset + 1 <= previous) {
    381 				// Depth (adjusted feet of seawater).
    382 				unsigned char depth = data[offset++];
    383 
    384 				// Temperature (degrees Fahrenheit)
    385 				if ((nsamples % 6) == 0) {
    386 					if (offset + 1 > previous)
    387 						break;
    388 					offset++;
    389 				}
    390 
    391 				// Current sample is complete.
    392 				nsamples++;
    393 
    394 				// The end of a dive is reached when 17 consecutive
    395 				// depth samples of less than 3 feet have been found.
    396 				if (depth < 13 + 3) {
    397 					count++;
    398 					if (count == 17) {
    399 						found = 1;
    400 						break;
    401 					}
    402 				} else {
    403 					count = 0;
    404 				}
    405 			}
    406 
    407 			// Report an error if no end of dive was found.
    408 			if (!found) {
    409 				ERROR (context, "No end of dive found.");
    410 				return DC_STATUS_DATAFORMAT;
    411 			}
    412 
    413 			// Automatically abort when a dive is older than the provided timestamp.
    414 			unsigned int timestamp = array_uint32_le (data + current + 2);
    415 			if (device && timestamp <= device->timestamp)
    416 				return DC_STATUS_SUCCESS;
    417 
    418 			if (callback && !callback (data + current, offset - current, data + current + 2, 4, userdata))
    419 				return DC_STATUS_SUCCESS;
    420 
    421 			// Prepare for the next dive.
    422 			previous = current;
    423 			current = (current >= 7 ? current - 7 : 0);
    424 		}
    425 	}
    426 
    427 	return DC_STATUS_SUCCESS;
    428 }