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

sporasub_sp2.c (14527B)


      1 /*
      2  * libdivecomputer
      3  *
      4  * Copyright (C) 2021 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> // memcpy, memcmp
     23 #include <stdlib.h> // malloc, free
     24 
     25 #include "sporasub_sp2.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), &sporasub_sp2_device_vtable)
     32 
     33 #define SZ_MEMORY 0x10000
     34 
     35 #define RB_PROFILE_BEGIN 0x0060
     36 #define RB_PROFILE_END   SZ_MEMORY
     37 
     38 #define MAXRETRIES 4
     39 #define MAXPACKET 256
     40 
     41 #define HEADER_HI  0xA0
     42 #define HEADER_LO  0xA2
     43 #define TRAILER_HI 0xB0
     44 #define TRAILER_LO 0xB3
     45 
     46 #define CMD_VERSION  0x10
     47 #define CMD_READ     0x12
     48 #define CMD_TIMESYNC 0x39
     49 
     50 #define SZ_VERSION  23
     51 #define SZ_READ     128
     52 
     53 #define SZ_HEADER   32
     54 #define SZ_SAMPLE    4
     55 
     56 typedef struct sporasub_sp2_device_t {
     57 	dc_device_t base;
     58 	dc_iostream_t *iostream;
     59 	unsigned char version[SZ_VERSION];
     60 	unsigned char fingerprint[6];
     61 } sporasub_sp2_device_t;
     62 
     63 static dc_status_t sporasub_sp2_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size);
     64 static dc_status_t sporasub_sp2_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size);
     65 static dc_status_t sporasub_sp2_device_dump (dc_device_t *abstract, dc_buffer_t *buffer);
     66 static dc_status_t sporasub_sp2_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata);
     67 static dc_status_t sporasub_sp2_device_timesync (dc_device_t *abstract, const dc_datetime_t *datetime);
     68 
     69 static const dc_device_vtable_t sporasub_sp2_device_vtable = {
     70 	sizeof(sporasub_sp2_device_t),
     71 	DC_FAMILY_SPORASUB_SP2,
     72 	sporasub_sp2_device_set_fingerprint, /* set_fingerprint */
     73 	sporasub_sp2_device_read, /* read */
     74 	NULL, /* write */
     75 	sporasub_sp2_device_dump, /* dump */
     76 	sporasub_sp2_device_foreach, /* foreach */
     77 	sporasub_sp2_device_timesync, /* timesync */
     78 	NULL /* close */
     79 };
     80 
     81 static unsigned int
     82 iceil (unsigned int x, unsigned int n)
     83 {
     84 	// Round up to next higher multiple.
     85 	return ((x + n - 1) / n) * n;
     86 }
     87 
     88 static dc_status_t
     89 sporasub_sp2_send (sporasub_sp2_device_t *device, unsigned char command, const unsigned char data[], unsigned int size)
     90 {
     91 	dc_status_t status = DC_STATUS_SUCCESS;
     92 	dc_device_t *abstract = (dc_device_t *) device;
     93 
     94 	if (size > MAXPACKET) {
     95 		return DC_STATUS_INVALIDARGS;
     96 	}
     97 
     98 	unsigned int len = size + 1;
     99 	unsigned int csum = checksum_add_uint16 (data, size, command);
    100 
    101 	unsigned char packet[MAXPACKET + 9] = {0};
    102 	packet[0] = HEADER_HI;
    103 	packet[1] = HEADER_LO;
    104 	packet[2] = (len >> 8) & 0xFF;
    105 	packet[3] = (len     ) & 0xFF;
    106 	packet[4] = command;
    107 	if (size) {
    108 		memcpy(packet + 5, data, size);
    109 	}
    110 	packet[size + 5] = (csum >> 8) & 0xFF;
    111 	packet[size + 6] = (csum     ) & 0xFF;
    112 	packet[size + 7] = TRAILER_HI;
    113 	packet[size + 8] = TRAILER_LO;
    114 
    115 	// Send the command to the device.
    116 	status = dc_iostream_write (device->iostream, packet, size + 9, NULL);
    117 	if (status != DC_STATUS_SUCCESS) {
    118 		ERROR (abstract->context, "Failed to send the command.");
    119 		return status;
    120 	}
    121 
    122 	return DC_STATUS_SUCCESS;
    123 }
    124 
    125 static dc_status_t
    126 sporasub_sp2_receive (sporasub_sp2_device_t *device, unsigned char command, unsigned char data[], unsigned int size)
    127 {
    128 	dc_status_t status = DC_STATUS_SUCCESS;
    129 	dc_device_t *abstract = (dc_device_t *) device;
    130 
    131 	if (size > MAXPACKET) {
    132 		return DC_STATUS_INVALIDARGS;
    133 	}
    134 
    135 	// Receive the answer of the device.
    136 	unsigned char packet[MAXPACKET + 9] = {0};
    137 	status = dc_iostream_read (device->iostream, packet, size + 9, NULL);
    138 	if (status != DC_STATUS_SUCCESS) {
    139 		ERROR (abstract->context, "Failed to receive the answer.");
    140 		return status;
    141 	}
    142 
    143 	// Verify the header and trailer of the packet.
    144 	if (packet[0] != HEADER_HI || packet[1] != HEADER_LO ||
    145 		packet[size + 7] != TRAILER_HI || packet[size + 8] != TRAILER_LO) {
    146 		ERROR (abstract->context, "Unexpected answer header/trailer byte.");
    147 		return DC_STATUS_PROTOCOL;
    148 	}
    149 
    150 	// Verify the packet length.
    151 	unsigned int len = array_uint16_be (packet + 2);
    152 	if (len != size + 1) {
    153 		ERROR (abstract->context, "Unexpected packet length.");
    154 		return DC_STATUS_PROTOCOL;
    155 	}
    156 
    157 	// Verify the command byte.
    158 	if (packet[4] != command) {
    159 		ERROR (abstract->context, "Unexpected answer header/trailer byte.");
    160 		return DC_STATUS_PROTOCOL;
    161 	}
    162 
    163 	// Verify the checksum of the packet.
    164 	unsigned short crc = array_uint16_be (packet + size + 5);
    165 	unsigned short ccrc = checksum_add_uint16 (packet + 4, size + 1, 0);
    166 	if (crc != ccrc) {
    167 		ERROR (abstract->context, "Unexpected answer checksum.");
    168 		return DC_STATUS_PROTOCOL;
    169 	}
    170 
    171 	if (size) {
    172 		memcpy (data, packet + 5, size);
    173 	}
    174 
    175 	return DC_STATUS_SUCCESS;
    176 }
    177 
    178 static dc_status_t
    179 sporasub_sp2_packet (sporasub_sp2_device_t *device, unsigned char cmd, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize)
    180 {
    181 	dc_status_t status = DC_STATUS_SUCCESS;
    182 	dc_device_t *abstract = (dc_device_t *) device;
    183 
    184 	if (device_is_cancelled (abstract))
    185 		return DC_STATUS_CANCELLED;
    186 
    187 	// Send the command to the device.
    188 	status = sporasub_sp2_send (device, cmd, command, csize);
    189 	if (status != DC_STATUS_SUCCESS) {
    190 		ERROR (abstract->context, "Failed to send the command.");
    191 		return status;
    192 	}
    193 
    194 	// Receive the answer of the device.
    195 	status = sporasub_sp2_receive (device, cmd + 1, answer, asize);
    196 	if (status != DC_STATUS_SUCCESS) {
    197 		ERROR (abstract->context, "Failed to receive the answer.");
    198 		return status;
    199 	}
    200 
    201 	return DC_STATUS_SUCCESS;
    202 }
    203 
    204 static dc_status_t
    205 sporasub_sp2_transfer (sporasub_sp2_device_t *device, unsigned char cmd, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize)
    206 {
    207 	unsigned int nretries = 0;
    208 	dc_status_t rc = DC_STATUS_SUCCESS;
    209 	while ((rc = sporasub_sp2_packet (device, cmd, command, csize, answer, asize)) != DC_STATUS_SUCCESS) {
    210 		// Automatically discard a corrupted packet,
    211 		// and request a new one.
    212 		if (rc != DC_STATUS_PROTOCOL && rc != DC_STATUS_TIMEOUT)
    213 			return rc;
    214 
    215 		// Abort if the maximum number of retries is reached.
    216 		if (nretries++ >= MAXRETRIES)
    217 			return rc;
    218 
    219 		// Discard any garbage bytes.
    220 		dc_iostream_sleep (device->iostream, 100);
    221 		dc_iostream_purge (device->iostream, DC_DIRECTION_INPUT);
    222 	}
    223 
    224 	return rc;
    225 }
    226 
    227 dc_status_t
    228 sporasub_sp2_device_open (dc_device_t **out, dc_context_t *context, dc_iostream_t *iostream)
    229 {
    230 	dc_status_t status = DC_STATUS_SUCCESS;
    231 	sporasub_sp2_device_t *device = NULL;
    232 
    233 	if (out == NULL)
    234 		return DC_STATUS_INVALIDARGS;
    235 
    236 	// Allocate memory.
    237 	device = (sporasub_sp2_device_t *) dc_device_allocate (context, &sporasub_sp2_device_vtable);
    238 	if (device == NULL) {
    239 		ERROR (context, "Failed to allocate memory.");
    240 		return DC_STATUS_NOMEMORY;
    241 	}
    242 
    243 	// Set the default values.
    244 	device->iostream = iostream;
    245 	memset (device->fingerprint, 0, sizeof (device->fingerprint));
    246 
    247 	// Set the serial communication protocol (460800 8N1).
    248 	status = dc_iostream_configure (device->iostream, 460800, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE);
    249 	if (status != DC_STATUS_SUCCESS) {
    250 		ERROR (context, "Failed to set the terminal attributes.");
    251 		goto error_free;
    252 	}
    253 
    254 	// Set the timeout for receiving data (1000 ms).
    255 	status = dc_iostream_set_timeout (device->iostream, 1000);
    256 	if (status != DC_STATUS_SUCCESS) {
    257 		ERROR (context, "Failed to set the timeout.");
    258 		goto error_free;
    259 	}
    260 
    261 	// Clear the RTS line.
    262 	status = dc_iostream_set_rts (device->iostream, 0);
    263 	if (status != DC_STATUS_SUCCESS) {
    264 		ERROR (context, "Failed to clear the RTS line.");
    265 		goto error_free;
    266 	}
    267 
    268 	// Set the DTR line.
    269 	status = dc_iostream_set_dtr (device->iostream, 1);
    270 	if (status != DC_STATUS_SUCCESS) {
    271 		ERROR (context, "Failed to set the DTR line.");
    272 		goto error_free;
    273 	}
    274 
    275 	dc_iostream_sleep (device->iostream, 100);
    276 	dc_iostream_purge (device->iostream, DC_DIRECTION_ALL);
    277 
    278 	// Read the version packet.
    279 	status = sporasub_sp2_packet(device, CMD_VERSION, NULL, 0, device->version, sizeof(device->version));
    280 	if (status != DC_STATUS_SUCCESS) {
    281 		ERROR (context, "Failed to read the version packet.");
    282 		goto error_free;
    283 	}
    284 
    285 	HEXDUMP (context, DC_LOGLEVEL_DEBUG, "Version", device->version, sizeof(device)->version);
    286 
    287 	*out = (dc_device_t *) device;
    288 
    289 	return DC_STATUS_SUCCESS;
    290 
    291 error_free:
    292 	dc_device_deallocate ((dc_device_t *) device);
    293 	return status;
    294 }
    295 
    296 static dc_status_t
    297 sporasub_sp2_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size)
    298 {
    299 	sporasub_sp2_device_t *device = (sporasub_sp2_device_t *) abstract;
    300 
    301 	if (size && size != sizeof (device->fingerprint))
    302 		return DC_STATUS_INVALIDARGS;
    303 
    304 	if (size)
    305 		memcpy (device->fingerprint, data, sizeof (device->fingerprint));
    306 	else
    307 		memset (device->fingerprint, 0, sizeof (device->fingerprint));
    308 
    309 	return DC_STATUS_SUCCESS;
    310 }
    311 
    312 static dc_status_t
    313 sporasub_sp2_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size)
    314 {
    315 	dc_status_t status = DC_STATUS_SUCCESS;
    316 	sporasub_sp2_device_t *device = (sporasub_sp2_device_t *) abstract;
    317 
    318 	unsigned int nbytes = 0;
    319 	while (nbytes < size) {
    320 		// Calculate the packet size.
    321 		unsigned int len = size - nbytes;
    322 		if (len > SZ_READ)
    323 			len = SZ_READ;
    324 
    325 		// Build the raw command.
    326 		unsigned char command[] = {
    327 			(address     ) & 0xFF,
    328 			(address >> 8) & 0xFF,
    329 			len};
    330 
    331 		// Send the command and receive the answer.
    332 		status = sporasub_sp2_transfer (device, CMD_READ, command, sizeof(command), data + nbytes, len);
    333 		if (status != DC_STATUS_SUCCESS)
    334 			return status;
    335 
    336 		nbytes += len;
    337 		address += len;
    338 		data += len;
    339 	}
    340 
    341 	return status;
    342 }
    343 
    344 static dc_status_t
    345 sporasub_sp2_device_dump (dc_device_t *abstract, dc_buffer_t *buffer)
    346 {
    347 	sporasub_sp2_device_t *device = (sporasub_sp2_device_t *) abstract;
    348 
    349 	// Allocate the required amount of memory.
    350 	if (!dc_buffer_resize (buffer, SZ_MEMORY)) {
    351 		ERROR (abstract->context, "Insufficient buffer space available.");
    352 		return DC_STATUS_NOMEMORY;
    353 	}
    354 
    355 	// Emit a device info event.
    356 	dc_event_devinfo_t devinfo;
    357 	devinfo.model = 0;
    358 	devinfo.firmware = 0;
    359 	devinfo.serial = array_uint16_be (device->version + 1);
    360 	device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo);
    361 
    362 	// Emit a vendor event.
    363 	dc_event_vendor_t vendor;
    364 	vendor.data = device->version;
    365 	vendor.size = sizeof (device->version);
    366 	device_event_emit (abstract, DC_EVENT_VENDOR, &vendor);
    367 
    368 	return device_dump_read (abstract, 0, dc_buffer_get_data (buffer),
    369 		dc_buffer_get_size (buffer), SZ_READ);
    370 }
    371 
    372 static dc_status_t
    373 sporasub_sp2_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata)
    374 {
    375 	dc_status_t status = DC_STATUS_SUCCESS;
    376 	sporasub_sp2_device_t *device = (sporasub_sp2_device_t *) abstract;
    377 
    378 	dc_buffer_t *buffer = dc_buffer_new (SZ_MEMORY);
    379 	if (buffer == NULL) {
    380 		status = DC_STATUS_NOMEMORY;
    381 		goto error_exit;
    382 	}
    383 
    384 	status = sporasub_sp2_device_dump (abstract, buffer);
    385 	if (status != DC_STATUS_SUCCESS) {
    386 		goto error_free_buffer;
    387 	}
    388 
    389 	unsigned char *data = dc_buffer_get_data (buffer);
    390 
    391 	// Get the number of dives.
    392 	unsigned int ndives = array_uint16_le (data + 0x02);
    393 
    394 	// Get the profile pointer.
    395 	unsigned int eop = array_uint16_le (data + 0x04);
    396 	if (eop < RB_PROFILE_BEGIN || eop > RB_PROFILE_END) {
    397 		ERROR (abstract->context, "Invalid profile pointer (0x%04x).", eop);
    398 		status = DC_STATUS_DATAFORMAT;
    399 		goto error_free_buffer;
    400 	}
    401 
    402 	unsigned short *logbook = (unsigned short *) malloc(ndives * sizeof (unsigned short));
    403 	if (logbook == NULL) {
    404 		ERROR (abstract->context, "Out of memory.");
    405 		status = DC_STATUS_NOMEMORY;
    406 		goto error_free_buffer;
    407 	}
    408 
    409 	// Find all dives.
    410 	unsigned int count = 0;
    411 	unsigned int address = RB_PROFILE_BEGIN;
    412 	while (address + SZ_HEADER <= RB_PROFILE_END && count < ndives) {
    413 		if (address == eop) {
    414 			WARNING (abstract->context, "Reached end of profile pointer.");
    415 			break;
    416 		}
    417 
    418 		// Get the dive length.
    419 		unsigned int nsamples = array_uint16_le (data + address);
    420 		unsigned int length = SZ_HEADER + nsamples * SZ_SAMPLE;
    421 		if (address + length > RB_PROFILE_END) {
    422 			WARNING (abstract->context, "Reached end of memory.");
    423 			break;
    424 		}
    425 
    426 		// Store the address.
    427 		logbook[count] = address;
    428 		count++;
    429 
    430 		// The start of the next dive is always aligned to 32 bytes.
    431 		address += iceil (length, SZ_HEADER);
    432 	}
    433 
    434 	// Process the dives in reverse order (newest first).
    435 	for (unsigned int i = 0; i < count; ++i) {
    436 		unsigned int idx = count - 1 - i;
    437 		unsigned int offset = logbook[idx];
    438 
    439 		// Get the dive length.
    440 		unsigned int nsamples = array_uint16_le (data + offset);
    441 		unsigned int length = SZ_HEADER + nsamples * SZ_SAMPLE;
    442 
    443 		// Check the fingerprint data.
    444 		if (memcmp (data + offset + 2, device->fingerprint, sizeof (device->fingerprint)) == 0)
    445 			break;
    446 
    447 		if (callback && !callback (data + offset, length, data + offset + 2, sizeof (device->fingerprint), userdata)) {
    448 			break;
    449 		}
    450 	}
    451 
    452 	free (logbook);
    453 error_free_buffer:
    454 	dc_buffer_free (buffer);
    455 error_exit:
    456 	return status;
    457 }
    458 
    459 
    460 static dc_status_t
    461 sporasub_sp2_device_timesync (dc_device_t *abstract, const dc_datetime_t *datetime)
    462 {
    463 	dc_status_t status = DC_STATUS_SUCCESS;
    464 	sporasub_sp2_device_t *device = (sporasub_sp2_device_t *) abstract;
    465 
    466 	if (datetime->year < 2000) {
    467 		ERROR (abstract->context, "Invalid parameter specified.");
    468 		return DC_STATUS_INVALIDARGS;
    469 	}
    470 
    471 	// Build the raw command.
    472 	unsigned char command[] = {
    473 		datetime->year - 2000,
    474 		datetime->month,
    475 		datetime->day,
    476 		datetime->hour,
    477 		datetime->minute,
    478 		datetime->second};
    479 
    480 	// Send the command and receive the answer.
    481 	unsigned char answer[1] = {0};
    482 	status = sporasub_sp2_transfer (device, CMD_TIMESYNC, command, sizeof(command), answer, sizeof(answer));
    483 	if (status != DC_STATUS_SUCCESS)
    484 		return status;
    485 
    486 	// Verify the response code.
    487 	if (answer[0] != 0) {
    488 		ERROR (abstract->context, "Invalid response code 0x%02x returned.", answer[0]);
    489 		return DC_STATUS_PROTOCOL;
    490 	}
    491 
    492 	return DC_STATUS_SUCCESS;
    493 }