python_code
stringlengths
0
1.8M
repo_name
stringclasses
7 values
file_path
stringlengths
5
99
/* * libdivecomputer * * Copyright (C) 2015 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <unistd.h> #include <stdio.h> #ifdef HAVE_GETOPT_H #include <getopt.h> #endif #include <libdivecomputer/context.h> #include <libdivecomputer/descriptor.h> #include <libdivecomputer/iterator.h> #include "dctool.h" static int dctool_list_run (int argc, char *argv[], dc_context_t *context, dc_descriptor_t *dummy) { // Default option values. unsigned int help = 0; // Parse the command-line options. int opt = 0; const char *optstring = "h"; #ifdef HAVE_GETOPT_LONG struct option options[] = { {"help", no_argument, 0, 'h'}, {0, 0, 0, 0 } }; while ((opt = getopt_long (argc, argv, optstring, options, NULL)) != -1) { #else while ((opt = getopt (argc, argv, optstring)) != -1) { #endif switch (opt) { case 'h': help = 1; break; default: return EXIT_FAILURE; } } argc -= optind; argv += optind; // Show help message. if (help) { dctool_command_showhelp (&dctool_list); return EXIT_SUCCESS; } dc_iterator_t *iterator = NULL; dc_descriptor_t *descriptor = NULL; dc_descriptor_iterator (&iterator); while (dc_iterator_next (iterator, &descriptor) == DC_STATUS_SUCCESS) { printf ("%s %s\n", dc_descriptor_get_vendor (descriptor), dc_descriptor_get_product (descriptor)); dc_descriptor_free (descriptor); } dc_iterator_free (iterator); return EXIT_SUCCESS; } const dctool_command_t dctool_list = { dctool_list_run, DCTOOL_CONFIG_NONE, "list", "List supported devices", "Usage:\n" " dctool list [options]\n" "\n" "Options:\n" #ifdef HAVE_GETOPT_LONG " -h, --help Show help message\n" #else " -h Show help message\n" #endif };
libdc-for-dirk-Subsurface-branch
examples/dctool_list.c
/* * libdivecomputer * * Copyright (C) 2015 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <string.h> #ifdef HAVE_GETOPT_H #include <getopt.h> #endif #include <libdivecomputer/context.h> #include <libdivecomputer/descriptor.h> #include <libdivecomputer/device.h> #include <libdivecomputer/parser.h> #include "dctool.h" #include "common.h" #include "output.h" #include "utils.h" typedef struct event_data_t { const char *cachedir; dc_event_devinfo_t devinfo; } event_data_t; typedef struct dive_data_t { dc_device_t *device; dc_buffer_t **fingerprint; unsigned int number; dctool_output_t *output; } dive_data_t; static int dive_cb (const unsigned char *data, unsigned int size, const unsigned char *fingerprint, unsigned int fsize, void *userdata) { dive_data_t *divedata = (dive_data_t *) userdata; dc_status_t rc = DC_STATUS_SUCCESS; dc_parser_t *parser = NULL; divedata->number++; message ("Dive: number=%u, size=%u, fingerprint=", divedata->number, size); for (unsigned int i = 0; i < fsize; ++i) message ("%02X", fingerprint[i]); message ("\n"); // Keep a copy of the most recent fingerprint. Because dives are // guaranteed to be downloaded in reverse order, the most recent // dive is always the first dive. if (divedata->number == 1) { dc_buffer_t *fp = dc_buffer_new (fsize); dc_buffer_append (fp, fingerprint, fsize); *divedata->fingerprint = fp; } // Create the parser. message ("Creating the parser.\n"); rc = dc_parser_new (&parser, divedata->device); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error creating the parser."); goto cleanup; } // Register the data. message ("Registering the data.\n"); rc = dc_parser_set_data (parser, data, size); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error registering the data."); goto cleanup; } // Parse the dive data. message ("Parsing the dive data.\n"); rc = dctool_output_write (divedata->output, parser, data, size, fingerprint, fsize); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error parsing the dive data."); goto cleanup; } cleanup: dc_parser_destroy (parser); return 1; } static void event_cb (dc_device_t *device, dc_event_type_t event, const void *data, void *userdata) { const dc_event_devinfo_t *devinfo = (const dc_event_devinfo_t *) data; event_data_t *eventdata = (event_data_t *) userdata; // Forward to the default event handler. dctool_event_cb (device, event, data, userdata); switch (event) { case DC_EVENT_DEVINFO: // Load the fingerprint from the cache. If there is no // fingerprint present in the cache, a NULL buffer is returned, // and the registered fingerprint will be cleared. if (eventdata->cachedir) { char filename[1024] = {0}; dc_family_t family = DC_FAMILY_NULL; dc_buffer_t *fingerprint = NULL; // Generate the fingerprint filename. family = dc_device_get_type (device); snprintf (filename, sizeof (filename), "%s/%s-%08X.bin", eventdata->cachedir, dctool_family_name (family), devinfo->serial); // Read the fingerprint file. fingerprint = dctool_file_read (filename); // Register the fingerprint data. dc_device_set_fingerprint (device, dc_buffer_get_data (fingerprint), dc_buffer_get_size (fingerprint)); // Free the buffer again. dc_buffer_free (fingerprint); } // Keep a copy of the event data. It will be used for generating // the fingerprint filename again after a (successful) download. eventdata->devinfo = *devinfo; break; default: break; } } static dc_status_t download (dc_context_t *context, dc_descriptor_t *descriptor, const char *devname, const char *cachedir, dc_buffer_t *fingerprint, dctool_output_t *output) { dc_status_t rc = DC_STATUS_SUCCESS; dc_device_t *device = NULL; dc_buffer_t *ofingerprint = NULL; // Open the device. message ("Opening the device (%s %s, %s).\n", dc_descriptor_get_vendor (descriptor), dc_descriptor_get_product (descriptor), devname ? devname : "null"); rc = dc_device_open (&device, context, descriptor, devname); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error opening the device."); goto cleanup; } // Initialize the event data. event_data_t eventdata = {0}; if (fingerprint) { eventdata.cachedir = NULL; } else { eventdata.cachedir = cachedir; } // Register the event handler. message ("Registering the event handler.\n"); int events = DC_EVENT_WAITING | DC_EVENT_PROGRESS | DC_EVENT_DEVINFO | DC_EVENT_CLOCK | DC_EVENT_VENDOR; rc = dc_device_set_events (device, events, event_cb, &eventdata); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error registering the event handler."); goto cleanup; } // Register the cancellation handler. message ("Registering the cancellation handler.\n"); rc = dc_device_set_cancel (device, dctool_cancel_cb, NULL); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error registering the cancellation handler."); goto cleanup; } // Register the fingerprint data. if (fingerprint) { message ("Registering the fingerprint data.\n"); rc = dc_device_set_fingerprint (device, dc_buffer_get_data (fingerprint), dc_buffer_get_size (fingerprint)); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error registering the fingerprint data."); goto cleanup; } } // Initialize the dive data. dive_data_t divedata = {0}; divedata.device = device; divedata.fingerprint = &ofingerprint; divedata.number = 0; divedata.output = output; // Download the dives. message ("Downloading the dives.\n"); rc = dc_device_foreach (device, dive_cb, &divedata); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error downloading the dives."); goto cleanup; } // Store the fingerprint data. if (cachedir && ofingerprint) { char filename[1024] = {0}; dc_family_t family = DC_FAMILY_NULL; // Generate the fingerprint filename. family = dc_device_get_type (device); snprintf (filename, sizeof (filename), "%s/%s-%08X.bin", cachedir, dctool_family_name (family), eventdata.devinfo.serial); // Write the fingerprint file. dctool_file_write (filename, ofingerprint); } cleanup: dc_buffer_free (ofingerprint); dc_device_close (device); return rc; } static int dctool_download_run (int argc, char *argv[], dc_context_t *context, dc_descriptor_t *descriptor) { int exitcode = EXIT_SUCCESS; dc_status_t status = DC_STATUS_SUCCESS; dc_buffer_t *fingerprint = NULL; dctool_output_t *output = NULL; dctool_units_t units = DCTOOL_UNITS_METRIC; // Default option values. unsigned int help = 0; const char *fphex = NULL; const char *filename = NULL; const char *cachedir = NULL; const char *format = "xml"; // Parse the command-line options. int opt = 0; const char *optstring = "ho:p:c:f:u:"; #ifdef HAVE_GETOPT_LONG struct option options[] = { {"help", no_argument, 0, 'h'}, {"output", required_argument, 0, 'o'}, {"fingerprint", required_argument, 0, 'p'}, {"cache", required_argument, 0, 'c'}, {"format", required_argument, 0, 'f'}, {"units", required_argument, 0, 'u'}, {0, 0, 0, 0 } }; while ((opt = getopt_long (argc, argv, optstring, options, NULL)) != -1) { #else while ((opt = getopt (argc, argv, optstring)) != -1) { #endif switch (opt) { case 'h': help = 1; break; case 'o': filename = optarg; break; case 'p': fphex = optarg; break; case 'c': cachedir = optarg; break; case 'f': format = optarg; break; case 'u': if (strcmp (optarg, "metric") == 0) units = DCTOOL_UNITS_METRIC; if (strcmp (optarg, "imperial") == 0) units = DCTOOL_UNITS_IMPERIAL; break; default: return EXIT_FAILURE; } } argc -= optind; argv += optind; // Show help message. if (help) { dctool_command_showhelp (&dctool_download); return EXIT_SUCCESS; } // Convert the fingerprint to binary. fingerprint = dctool_convert_hex2bin (fphex); // Create the output. if (strcasecmp(format, "raw") == 0) { output = dctool_raw_output_new (filename); } else if (strcasecmp(format, "xml") == 0) { output = dctool_xml_output_new (filename, units); } else { message ("Unknown output format: %s\n", format); exitcode = EXIT_FAILURE; goto cleanup; } if (output == NULL) { message ("Failed to create the output.\n"); exitcode = EXIT_FAILURE; goto cleanup; } // Download the dives. status = download (context, descriptor, argv[0], cachedir, fingerprint, output); if (status != DC_STATUS_SUCCESS) { message ("ERROR: %s\n", dctool_errmsg (status)); exitcode = EXIT_FAILURE; goto cleanup; } cleanup: dctool_output_free (output); dc_buffer_free (fingerprint); return exitcode; } const dctool_command_t dctool_download = { dctool_download_run, DCTOOL_CONFIG_DESCRIPTOR, "download", "Download the dives", "Usage:\n" " dctool download [options] <devname>\n" "\n" "Options:\n" #ifdef HAVE_GETOPT_LONG " -h, --help Show help message\n" " -o, --output <filename> Output filename\n" " -p, --fingerprint <data> Fingerprint data (hexadecimal)\n" " -c, --cache <directory> Cache directory\n" " -f, --format <format> Output format\n" " -u, --units <units> Set units (metric or imperial)\n" #else " -h Show help message\n" " -o <filename> Output filename\n" " -p <fingerprint> Fingerprint data (hexadecimal)\n" " -c <directory> Cache directory\n" " -f <format> Output format\n" " -u <units> Set units (metric or imperial)\n" #endif "\n" "Supported output formats:\n" "\n" " XML (default)\n" "\n" " All dives are exported to a single xml file.\n" "\n" " RAW\n" "\n" " Each dive is exported to a raw (binary) file. To output multiple\n" " files, the filename is interpreted as a template and should\n" " contain one or more placeholders.\n" "\n" "Supported template placeholders:\n" "\n" " %f Fingerprint (hexadecimal format)\n" " %n Number (4 digits)\n" " %t Timestamp (basic ISO 8601 date/time format)\n" };
libdc-for-dirk-Subsurface-branch
examples/dctool_download.c
/* * libdivecomputer * * Copyright (C) 2015 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> #include <stdio.h> #ifdef _WIN32 #include <io.h> #include <fcntl.h> #endif #include "common.h" #include "utils.h" #ifdef _WIN32 #define DC_TICKS_FORMAT "%I64d" #else #define DC_TICKS_FORMAT "%lld" #endif #define C_ARRAY_SIZE(array) (sizeof (array) / sizeof *(array)) typedef struct backend_table_t { const char *name; dc_family_t type; unsigned int model; } backend_table_t; static const backend_table_t g_backends[] = { {"solution", DC_FAMILY_SUUNTO_SOLUTION, 0}, {"eon", DC_FAMILY_SUUNTO_EON, 0}, {"vyper", DC_FAMILY_SUUNTO_VYPER, 0x0A}, {"vyper2", DC_FAMILY_SUUNTO_VYPER2, 0x10}, {"d9", DC_FAMILY_SUUNTO_D9, 0x0E}, {"eonsteel", DC_FAMILY_SUUNTO_EONSTEEL, 0}, {"aladin", DC_FAMILY_UWATEC_ALADIN, 0x3F}, {"memomouse", DC_FAMILY_UWATEC_MEMOMOUSE, 0}, {"smart", DC_FAMILY_UWATEC_SMART, 0x10}, {"meridian", DC_FAMILY_UWATEC_MERIDIAN, 0x20}, {"g2", DC_FAMILY_UWATEC_G2, 0x11}, {"sensus", DC_FAMILY_REEFNET_SENSUS, 1}, {"sensuspro", DC_FAMILY_REEFNET_SENSUSPRO, 2}, {"sensusultra", DC_FAMILY_REEFNET_SENSUSULTRA, 3}, {"vtpro", DC_FAMILY_OCEANIC_VTPRO, 0x4245}, {"veo250", DC_FAMILY_OCEANIC_VEO250, 0x424C}, {"atom2", DC_FAMILY_OCEANIC_ATOM2, 0x4342}, {"nemo", DC_FAMILY_MARES_NEMO, 0}, {"puck", DC_FAMILY_MARES_PUCK, 7}, {"darwin", DC_FAMILY_MARES_DARWIN, 0}, {"iconhd", DC_FAMILY_MARES_ICONHD, 0x14}, {"ostc", DC_FAMILY_HW_OSTC, 0}, {"frog", DC_FAMILY_HW_FROG, 0}, {"ostc3", DC_FAMILY_HW_OSTC3, 0x0A}, {"edy", DC_FAMILY_CRESSI_EDY, 0x08}, {"leonardo", DC_FAMILY_CRESSI_LEONARDO, 1}, {"n2ition3", DC_FAMILY_ZEAGLE_N2ITION3, 0}, {"cobalt", DC_FAMILY_ATOMICS_COBALT, 0}, {"predator", DC_FAMILY_SHEARWATER_PREDATOR, 2}, {"petrel", DC_FAMILY_SHEARWATER_PETREL, 3}, {"nitekq", DC_FAMILY_DIVERITE_NITEKQ, 0}, {"aqualand", DC_FAMILY_CITIZEN_AQUALAND, 0}, {"idive", DC_FAMILY_DIVESYSTEM_IDIVE, 0x03}, {"cochran", DC_FAMILY_COCHRAN_COMMANDER, 0}, }; const char * dctool_errmsg (dc_status_t status) { switch (status) { case DC_STATUS_SUCCESS: return "Success"; case DC_STATUS_UNSUPPORTED: return "Unsupported operation"; case DC_STATUS_INVALIDARGS: return "Invalid arguments"; case DC_STATUS_NOMEMORY: return "Out of memory"; case DC_STATUS_NODEVICE: return "No device found"; case DC_STATUS_NOACCESS: return "Access denied"; case DC_STATUS_IO: return "Input/output error"; case DC_STATUS_TIMEOUT: return "Timeout"; case DC_STATUS_PROTOCOL: return "Protocol error"; case DC_STATUS_DATAFORMAT: return "Data format error"; case DC_STATUS_CANCELLED: return "Cancelled"; default: return "Unknown error"; } } dc_family_t dctool_family_type (const char *name) { for (unsigned int i = 0; i < C_ARRAY_SIZE (g_backends); ++i) { if (strcmp (name, g_backends[i].name) == 0) return g_backends[i].type; } return DC_FAMILY_NULL; } const char * dctool_family_name (dc_family_t type) { for (unsigned int i = 0; i < C_ARRAY_SIZE (g_backends); ++i) { if (g_backends[i].type == type) return g_backends[i].name; } return NULL; } unsigned int dctool_family_model (dc_family_t type) { for (unsigned int i = 0; i < C_ARRAY_SIZE (g_backends); ++i) { if (g_backends[i].type == type) return g_backends[i].model; } return 0; } void dctool_event_cb (dc_device_t *device, dc_event_type_t event, const void *data, void *userdata) { const dc_event_progress_t *progress = (const dc_event_progress_t *) data; const dc_event_devinfo_t *devinfo = (const dc_event_devinfo_t *) data; const dc_event_clock_t *clock = (const dc_event_clock_t *) data; const dc_event_vendor_t *vendor = (const dc_event_vendor_t *) data; switch (event) { case DC_EVENT_WAITING: message ("Event: waiting for user action\n"); break; case DC_EVENT_PROGRESS: message ("Event: progress %3.2f%% (%u/%u)\n", 100.0 * (double) progress->current / (double) progress->maximum, progress->current, progress->maximum); break; case DC_EVENT_DEVINFO: message ("Event: model=%u (0x%08x), firmware=%u (0x%08x), serial=%u (0x%08x)\n", devinfo->model, devinfo->model, devinfo->firmware, devinfo->firmware, devinfo->serial, devinfo->serial); break; case DC_EVENT_CLOCK: message ("Event: systime=" DC_TICKS_FORMAT ", devtime=%u\n", clock->systime, clock->devtime); break; case DC_EVENT_VENDOR: message ("Event: vendor="); for (unsigned int i = 0; i < vendor->size; ++i) message ("%02X", vendor->data[i]); message ("\n"); break; default: break; } } dc_status_t dctool_descriptor_search (dc_descriptor_t **out, const char *name, dc_family_t family, unsigned int model) { dc_status_t rc = DC_STATUS_SUCCESS; dc_iterator_t *iterator = NULL; rc = dc_descriptor_iterator (&iterator); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error creating the device descriptor iterator."); return rc; } dc_descriptor_t *descriptor = NULL, *current = NULL; while ((rc = dc_iterator_next (iterator, &descriptor)) == DC_STATUS_SUCCESS) { if (name) { const char *vendor = dc_descriptor_get_vendor (descriptor); const char *product = dc_descriptor_get_product (descriptor); size_t n = strlen (vendor); if (strncasecmp (name, vendor, n) == 0 && name[n] == ' ' && strcasecmp (name + n + 1, product) == 0) { current = descriptor; break; } else if (strcasecmp (name, product) == 0) { current = descriptor; break; } } else { if (family == dc_descriptor_get_type (descriptor)) { if (model == dc_descriptor_get_model (descriptor)) { // Exact match found. Return immediately. dc_descriptor_free (current); current = descriptor; break; } else { // Possible match found. Keep searching for an exact match. // If no exact match is found, the first match is returned. if (current == NULL) { current = descriptor; descriptor = NULL; } } } } dc_descriptor_free (descriptor); } if (rc != DC_STATUS_SUCCESS && rc != DC_STATUS_DONE) { dc_descriptor_free (current); dc_iterator_free (iterator); ERROR ("Error iterating the device descriptors."); return rc; } dc_iterator_free (iterator); *out = current; return DC_STATUS_SUCCESS; } static unsigned char hex2dec (unsigned char value) { if (value >= '0' && value <= '9') return value - '0'; else if (value >= 'A' && value <= 'F') return value - 'A' + 10; else if (value >= 'a' && value <= 'f') return value - 'a' + 10; else return 0; } dc_buffer_t * dctool_convert_hex2bin (const char *str) { // Get the length of the fingerprint data. size_t nbytes = (str ? strlen (str) / 2 : 0); if (nbytes == 0) return NULL; // Allocate a memory buffer. dc_buffer_t *buffer = dc_buffer_new (nbytes); // Convert the hexadecimal string. for (unsigned int i = 0; i < nbytes; ++i) { unsigned char msn = hex2dec (str[i * 2 + 0]); unsigned char lsn = hex2dec (str[i * 2 + 1]); unsigned char byte = (msn << 4) + lsn; dc_buffer_append (buffer, &byte, 1); } return buffer; } void dctool_file_write (const char *filename, dc_buffer_t *buffer) { FILE *fp = NULL; // Open the file. if (filename) { fp = fopen (filename, "wb"); } else { fp = stdout; #ifdef _WIN32 // Change from text mode to binary mode. _setmode (_fileno (fp), _O_BINARY); #endif } if (fp == NULL) return; // Write the entire buffer to the file. fwrite (dc_buffer_get_data (buffer), 1, dc_buffer_get_size (buffer), fp); // Close the file. fclose (fp); } dc_buffer_t * dctool_file_read (const char *filename) { FILE *fp = NULL; // Open the file. if (filename) { fp = fopen (filename, "rb"); } else { fp = stdin; #ifdef _WIN32 // Change from text mode to binary mode. _setmode (_fileno (fp), _O_BINARY); #endif } if (fp == NULL) return NULL; // Allocate a memory buffer. dc_buffer_t *buffer = dc_buffer_new (0); // Read the entire file into the buffer. size_t n = 0; unsigned char block[1024] = {0}; while ((n = fread (block, 1, sizeof (block), fp)) > 0) { dc_buffer_append (buffer, block, n); } // Close the file. fclose (fp); return buffer; }
libdc-for-dirk-Subsurface-branch
examples/common.c
/* * libdivecomputer * * Copyright (C) 2015 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <unistd.h> #include <stdio.h> #ifdef HAVE_GETOPT_H #include <getopt.h> #endif #include <libdivecomputer/context.h> #include <libdivecomputer/descriptor.h> #include <libdivecomputer/device.h> #include <libdivecomputer/hw_ostc.h> #include <libdivecomputer/hw_ostc3.h> #include "dctool.h" #include "common.h" #include "utils.h" static dc_status_t fwupdate (dc_context_t *context, dc_descriptor_t *descriptor, const char *devname, const char *hexfile) { dc_status_t rc = DC_STATUS_SUCCESS; dc_device_t *device = NULL; // Open the device. message ("Opening the device (%s %s, %s).\n", dc_descriptor_get_vendor (descriptor), dc_descriptor_get_product (descriptor), devname ? devname : "null"); rc = dc_device_open (&device, context, descriptor, devname); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error opening the device."); goto cleanup; } // Register the event handler. message ("Registering the event handler.\n"); int events = DC_EVENT_PROGRESS; rc = dc_device_set_events (device, events, dctool_event_cb, NULL); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error registering the event handler."); goto cleanup; } // Register the cancellation handler. message ("Registering the cancellation handler.\n"); rc = dc_device_set_cancel (device, dctool_cancel_cb, NULL); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error registering the cancellation handler."); goto cleanup; } // Update the firmware. message ("Updating the firmware.\n"); switch (dc_device_get_type (device)) { case DC_FAMILY_HW_OSTC: rc = hw_ostc_device_fwupdate (device, hexfile); break; case DC_FAMILY_HW_OSTC3: rc = hw_ostc3_device_fwupdate (device, hexfile); break; default: rc = DC_STATUS_UNSUPPORTED; break; } if (rc != DC_STATUS_SUCCESS) { ERROR ("Error updating the firmware."); goto cleanup; } cleanup: dc_device_close (device); return rc; } static int dctool_fwupdate_run (int argc, char *argv[], dc_context_t *context, dc_descriptor_t *descriptor) { int exitcode = EXIT_SUCCESS; dc_status_t status = DC_STATUS_SUCCESS; // Default option values. unsigned int help = 0; const char *filename = NULL; // Parse the command-line options. int opt = 0; const char *optstring = "hf:"; #ifdef HAVE_GETOPT_LONG struct option options[] = { {"help", no_argument, 0, 'h'}, {"firmware", required_argument, 0, 'f'}, {0, 0, 0, 0 } }; while ((opt = getopt_long (argc, argv, optstring, options, NULL)) != -1) { #else while ((opt = getopt (argc, argv, optstring)) != -1) { #endif switch (opt) { case 'f': filename = optarg; break; case 'h': help = 1; break; default: return EXIT_FAILURE; } } argc -= optind; argv += optind; // Show help message. if (help) { dctool_command_showhelp (&dctool_fwupdate); return EXIT_SUCCESS; } // Check mandatory arguments. if (!filename) { message ("No firmware file specified.\n"); exitcode = EXIT_FAILURE; goto cleanup; } // Update the firmware. status = fwupdate (context, descriptor, argv[0], filename); if (status != DC_STATUS_SUCCESS) { message ("ERROR: %s\n", dctool_errmsg (status)); exitcode = EXIT_FAILURE; goto cleanup; } cleanup: return exitcode; } const dctool_command_t dctool_fwupdate = { dctool_fwupdate_run, DCTOOL_CONFIG_DESCRIPTOR, "fwupdate", "Update the firmware", "Usage:\n" " dctool fwupdate [options]\n" "\n" "Options:\n" #ifdef HAVE_GETOPT_LONG " -h, --help Show help message\n" " -f, --firmware <filename> Firmware filename\n" #else " -h Show help message\n" " -f <filename> Firmware filename\n" #endif };
libdc-for-dirk-Subsurface-branch
examples/dctool_fwupdate.c
/* * libdivecomputer * * Copyright (C) 2015 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <string.h> #ifdef HAVE_GETOPT_H #include <getopt.h> #endif #include <libdivecomputer/context.h> #include <libdivecomputer/descriptor.h> #include <libdivecomputer/parser.h> #include "dctool.h" #include "output.h" #include "common.h" #include "utils.h" #define REACTPROWHITE 0x4354 static dc_status_t parse (dc_buffer_t *buffer, dc_context_t *context, dc_descriptor_t *descriptor, unsigned int devtime, dc_ticks_t systime, dctool_output_t *output) { dc_status_t rc = DC_STATUS_SUCCESS; dc_parser_t *parser = NULL; unsigned char *data = dc_buffer_get_data (buffer); unsigned int size = dc_buffer_get_size (buffer); // Create the parser. message ("Creating the parser.\n"); rc = dc_parser_new2 (&parser, context, descriptor, devtime, systime); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error creating the parser."); goto cleanup; } // Register the data. message ("Registering the data.\n"); rc = dc_parser_set_data (parser, data, size); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error registering the data."); goto cleanup; } // Parse the dive data. message ("Parsing the dive data.\n"); rc = dctool_output_write (output, parser, data, size, NULL, 0); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error parsing the dive data."); goto cleanup; } cleanup: dc_parser_destroy (parser); return rc; } static int dctool_parse_run (int argc, char *argv[], dc_context_t *context, dc_descriptor_t *descriptor) { // Default values. int exitcode = EXIT_SUCCESS; dc_status_t status = DC_STATUS_SUCCESS; dc_buffer_t *buffer = NULL; dctool_output_t *output = NULL; dctool_units_t units = DCTOOL_UNITS_METRIC; // Default option values. unsigned int help = 0; const char *filename = NULL; unsigned int devtime = 0; dc_ticks_t systime = 0; // Parse the command-line options. int opt = 0; const char *optstring = "ho:d:s:u:"; #ifdef HAVE_GETOPT_LONG struct option options[] = { {"help", no_argument, 0, 'h'}, {"output", required_argument, 0, 'o'}, {"devtime", required_argument, 0, 'd'}, {"systime", required_argument, 0, 's'}, {"units", required_argument, 0, 'u'}, {0, 0, 0, 0 } }; while ((opt = getopt_long (argc, argv, optstring, options, NULL)) != -1) { #else while ((opt = getopt (argc, argv, optstring)) != -1) { #endif switch (opt) { case 'h': help = 1; break; case 'o': filename = optarg; break; case 'd': devtime = strtoul (optarg, NULL, 0); break; case 's': systime = strtoll (optarg, NULL, 0); break; case 'u': if (strcmp (optarg, "metric") == 0) units = DCTOOL_UNITS_METRIC; if (strcmp (optarg, "imperial") == 0) units = DCTOOL_UNITS_IMPERIAL; break; default: return EXIT_FAILURE; } } argc -= optind; argv += optind; // Show help message. if (help) { dctool_command_showhelp (&dctool_parse); return EXIT_SUCCESS; } // Create the output. output = dctool_xml_output_new (filename, units); if (output == NULL) { message ("Failed to create the output.\n"); exitcode = EXIT_FAILURE; goto cleanup; } for (unsigned int i = 0; i < argc; ++i) { // Read the input file. buffer = dctool_file_read (argv[i]); if (buffer == NULL) { message ("Failed to open the input file.\n"); exitcode = EXIT_FAILURE; goto cleanup; } // Parse the dive. status = parse (buffer, context, descriptor, devtime, systime, output); if (status != DC_STATUS_SUCCESS) { message ("ERROR: %s\n", dctool_errmsg (status)); exitcode = EXIT_FAILURE; goto cleanup; } // Cleanup. dc_buffer_free (buffer); buffer = NULL; } cleanup: dc_buffer_free (buffer); dctool_output_free (output); return exitcode; } const dctool_command_t dctool_parse = { dctool_parse_run, DCTOOL_CONFIG_DESCRIPTOR, "parse", "Parse previously downloaded dives", "Usage:\n" " dctool parse [options] <filename>\n" "\n" "Options:\n" #ifdef HAVE_GETOPT_LONG " -h, --help Show help message\n" " -o, --output <filename> Output filename\n" " -d, --devtime <timestamp> Device time\n" " -s, --systime <timestamp> System time\n" " -u, --units <units> Set units (metric or imperial)\n" #else " -h Show help message\n" " -o <filename> Output filename\n" " -d <devtime> Device time\n" " -s <systime> System time\n" " -u <units> Set units (metric or imperial)\n" #endif };
libdc-for-dirk-Subsurface-branch
examples/dctool_parse.c
/* * libdivecomputer * * Copyright (C) 2016 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <libdivecomputer/units.h> #include "output-private.h" #include "utils.h" static dc_status_t dctool_xml_output_write (dctool_output_t *output, dc_parser_t *parser, const unsigned char data[], unsigned int size, const unsigned char fingerprint[], unsigned int fsize); static dc_status_t dctool_xml_output_free (dctool_output_t *output); typedef struct dctool_xml_output_t { dctool_output_t base; FILE *ostream; dctool_units_t units; } dctool_xml_output_t; static const dctool_output_vtable_t xml_vtable = { sizeof(dctool_xml_output_t), /* size */ dctool_xml_output_write, /* write */ dctool_xml_output_free, /* free */ }; typedef struct sample_data_t { FILE *ostream; dctool_units_t units; unsigned int nsamples; } sample_data_t; static double convert_depth (double value, dctool_units_t units) { if (units == DCTOOL_UNITS_IMPERIAL) { return value / FEET; } else { return value; } } static double convert_temperature (double value, dctool_units_t units) { if (units == DCTOOL_UNITS_IMPERIAL) { return value * (9.0 / 5.0) + 32.0; } else { return value; } } static double convert_pressure (double value, dctool_units_t units) { if (units == DCTOOL_UNITS_IMPERIAL) { return value * BAR / PSI; } else { return value; } } static double convert_volume (double value, dctool_units_t units) { if (units == DCTOOL_UNITS_IMPERIAL) { return value / 1000.0 / CUFT; } else { return value; } } static void sample_cb (dc_sample_type_t type, dc_sample_value_t value, void *userdata) { static const char *events[] = { "none", "deco", "rbt", "ascent", "ceiling", "workload", "transmitter", "violation", "bookmark", "surface", "safety stop", "gaschange", "safety stop (voluntary)", "safety stop (mandatory)", "deepstop", "ceiling (safety stop)", "floor", "divetime", "maxdepth", "OLF", "PO2", "airtime", "rgbm", "heading", "tissue level warning", "gaschange2"}; static const char *decostop[] = { "ndl", "safety", "deco", "deep"}; sample_data_t *sampledata = (sample_data_t *) userdata; switch (type) { case DC_SAMPLE_TIME: if (sampledata->nsamples++) fprintf (sampledata->ostream, "</sample>\n"); fprintf (sampledata->ostream, "<sample>\n"); fprintf (sampledata->ostream, " <time>%02u:%02u</time>\n", value.time / 60, value.time % 60); break; case DC_SAMPLE_DEPTH: fprintf (sampledata->ostream, " <depth>%.2f</depth>\n", convert_depth(value.depth, sampledata->units)); break; case DC_SAMPLE_PRESSURE: fprintf (sampledata->ostream, " <pressure tank=\"%u\">%.2f</pressure>\n", value.pressure.tank, convert_pressure(value.pressure.value, sampledata->units)); break; case DC_SAMPLE_TEMPERATURE: fprintf (sampledata->ostream, " <temperature>%.2f</temperature>\n", convert_temperature(value.temperature, sampledata->units)); break; case DC_SAMPLE_EVENT: if (value.event.type != SAMPLE_EVENT_GASCHANGE && value.event.type != SAMPLE_EVENT_GASCHANGE2) { fprintf (sampledata->ostream, " <event type=\"%u\" time=\"%u\" flags=\"%u\" value=\"%u\">%s</event>\n", value.event.type, value.event.time, value.event.flags, value.event.value, events[value.event.type]); } break; case DC_SAMPLE_RBT: fprintf (sampledata->ostream, " <rbt>%u</rbt>\n", value.rbt); break; case DC_SAMPLE_HEARTBEAT: fprintf (sampledata->ostream, " <heartbeat>%u</heartbeat>\n", value.heartbeat); break; case DC_SAMPLE_BEARING: fprintf (sampledata->ostream, " <bearing>%u</bearing>\n", value.bearing); break; case DC_SAMPLE_VENDOR: fprintf (sampledata->ostream, " <vendor type=\"%u\" size=\"%u\">", value.vendor.type, value.vendor.size); for (unsigned int i = 0; i < value.vendor.size; ++i) fprintf (sampledata->ostream, "%02X", ((const unsigned char *) value.vendor.data)[i]); fprintf (sampledata->ostream, "</vendor>\n"); break; case DC_SAMPLE_SETPOINT: fprintf (sampledata->ostream, " <setpoint>%.2f</setpoint>\n", value.setpoint); break; case DC_SAMPLE_PPO2: fprintf (sampledata->ostream, " <ppo2>%.2f</ppo2>\n", value.ppo2); break; case DC_SAMPLE_CNS: fprintf (sampledata->ostream, " <cns>%.1f</cns>\n", value.cns * 100.0); break; case DC_SAMPLE_DECO: fprintf (sampledata->ostream, " <deco time=\"%u\" depth=\"%.2f\">%s</deco>\n", value.deco.time, convert_depth(value.deco.depth, sampledata->units), decostop[value.deco.type]); break; case DC_SAMPLE_GASMIX: fprintf (sampledata->ostream, " <gasmix>%u</gasmix>\n", value.gasmix); break; default: break; } } dctool_output_t * dctool_xml_output_new (const char *filename, dctool_units_t units) { dctool_xml_output_t *output = NULL; if (filename == NULL) goto error_exit; // Allocate memory. output = (dctool_xml_output_t *) dctool_output_allocate (&xml_vtable); if (output == NULL) { goto error_exit; } // Open the output file. output->ostream = fopen (filename, "w"); if (output->ostream == NULL) { goto error_free; } output->units = units; fprintf (output->ostream, "<device>\n"); return (dctool_output_t *) output; error_free: dctool_output_deallocate ((dctool_output_t *) output); error_exit: return NULL; } static dc_status_t dctool_xml_output_write (dctool_output_t *abstract, dc_parser_t *parser, const unsigned char data[], unsigned int size, const unsigned char fingerprint[], unsigned int fsize) { dctool_xml_output_t *output = (dctool_xml_output_t *) abstract; dc_status_t status = DC_STATUS_SUCCESS; // Initialize the sample data. sample_data_t sampledata = {0}; sampledata.nsamples = 0; sampledata.ostream = output->ostream; sampledata.units = output->units; fprintf (output->ostream, "<dive>\n<number>%u</number>\n<size>%u</size>\n", abstract->number, size); if (fingerprint) { fprintf (output->ostream, "<fingerprint>"); for (unsigned int i = 0; i < fsize; ++i) fprintf (output->ostream, "%02X", fingerprint[i]); fprintf (output->ostream, "</fingerprint>\n"); } // Parse the datetime. message ("Parsing the datetime.\n"); dc_datetime_t dt = {0}; status = dc_parser_get_datetime (parser, &dt); if (status != DC_STATUS_SUCCESS && status != DC_STATUS_UNSUPPORTED) { ERROR ("Error parsing the datetime."); goto cleanup; } if (dt.timezone == DC_TIMEZONE_NONE) { fprintf (output->ostream, "<datetime>%04i-%02i-%02i %02i:%02i:%02i</datetime>\n", dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second); } else { fprintf (output->ostream, "<datetime>%04i-%02i-%02i %02i:%02i:%02i %+03i:%02i</datetime>\n", dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.timezone / 3600, (dt.timezone % 3600) / 60); } // Parse the divetime. message ("Parsing the divetime.\n"); unsigned int divetime = 0; status = dc_parser_get_field (parser, DC_FIELD_DIVETIME, 0, &divetime); if (status != DC_STATUS_SUCCESS && status != DC_STATUS_UNSUPPORTED) { ERROR ("Error parsing the divetime."); goto cleanup; } fprintf (output->ostream, "<divetime>%02u:%02u</divetime>\n", divetime / 60, divetime % 60); // Parse the maxdepth. message ("Parsing the maxdepth.\n"); double maxdepth = 0.0; status = dc_parser_get_field (parser, DC_FIELD_MAXDEPTH, 0, &maxdepth); if (status != DC_STATUS_SUCCESS && status != DC_STATUS_UNSUPPORTED) { ERROR ("Error parsing the maxdepth."); goto cleanup; } fprintf (output->ostream, "<maxdepth>%.2f</maxdepth>\n", convert_depth(maxdepth, output->units)); // Parse the temperature. message ("Parsing the temperature.\n"); for (unsigned int i = 0; i < 3; ++i) { dc_field_type_t fields[] = {DC_FIELD_TEMPERATURE_SURFACE, DC_FIELD_TEMPERATURE_MINIMUM, DC_FIELD_TEMPERATURE_MAXIMUM}; const char *names[] = {"surface", "minimum", "maximum"}; double temperature = 0.0; status = dc_parser_get_field (parser, fields[i], 0, &temperature); if (status != DC_STATUS_SUCCESS && status != DC_STATUS_UNSUPPORTED) { ERROR ("Error parsing the temperature."); goto cleanup; } if (status != DC_STATUS_UNSUPPORTED) { fprintf (output->ostream, "<temperature type=\"%s\">%.1f</temperature>\n", names[i], convert_temperature(temperature, output->units)); } } // Parse the gas mixes. message ("Parsing the gas mixes.\n"); unsigned int ngases = 0; status = dc_parser_get_field (parser, DC_FIELD_GASMIX_COUNT, 0, &ngases); if (status != DC_STATUS_SUCCESS && status != DC_STATUS_UNSUPPORTED) { ERROR ("Error parsing the gas mix count."); goto cleanup; } for (unsigned int i = 0; i < ngases; ++i) { dc_gasmix_t gasmix = {0}; status = dc_parser_get_field (parser, DC_FIELD_GASMIX, i, &gasmix); if (status != DC_STATUS_SUCCESS && status != DC_STATUS_UNSUPPORTED) { ERROR ("Error parsing the gas mix."); goto cleanup; } fprintf (output->ostream, "<gasmix>\n" " <he>%.1f</he>\n" " <o2>%.1f</o2>\n" " <n2>%.1f</n2>\n" "</gasmix>\n", gasmix.helium * 100.0, gasmix.oxygen * 100.0, gasmix.nitrogen * 100.0); } // Parse the tanks. message ("Parsing the tanks.\n"); unsigned int ntanks = 0; status = dc_parser_get_field (parser, DC_FIELD_TANK_COUNT, 0, &ntanks); if (status != DC_STATUS_SUCCESS && status != DC_STATUS_UNSUPPORTED) { ERROR ("Error parsing the tank count."); goto cleanup; } for (unsigned int i = 0; i < ntanks; ++i) { const char *names[] = {"none", "metric", "imperial"}; dc_tank_t tank = {0}; status = dc_parser_get_field (parser, DC_FIELD_TANK, i, &tank); if (status != DC_STATUS_SUCCESS && status != DC_STATUS_UNSUPPORTED) { ERROR ("Error parsing the tank."); goto cleanup; } fprintf (output->ostream, "<tank>\n"); if (tank.gasmix != DC_GASMIX_UNKNOWN) { fprintf (output->ostream, " <gasmix>%u</gasmix>\n", tank.gasmix); } if (tank.type != DC_TANKVOLUME_NONE) { fprintf (output->ostream, " <type>%s</type>\n" " <volume>%.1f</volume>\n" " <workpressure>%.2f</workpressure>\n", names[tank.type], convert_volume(tank.volume, output->units), convert_pressure(tank.workpressure, output->units)); } fprintf (output->ostream, " <beginpressure>%.2f</beginpressure>\n" " <endpressure>%.2f</endpressure>\n" "</tank>\n", convert_pressure(tank.beginpressure, output->units), convert_pressure(tank.endpressure, output->units)); } // Parse the dive mode. message ("Parsing the dive mode.\n"); dc_divemode_t divemode = DC_DIVEMODE_OC; status = dc_parser_get_field (parser, DC_FIELD_DIVEMODE, 0, &divemode); if (status != DC_STATUS_SUCCESS && status != DC_STATUS_UNSUPPORTED) { ERROR ("Error parsing the dive mode."); goto cleanup; } if (status != DC_STATUS_UNSUPPORTED) { const char *names[] = {"freedive", "gauge", "oc", "ccr", "scr"}; fprintf (output->ostream, "<divemode>%s</divemode>\n", names[divemode]); } // Parse the salinity. message ("Parsing the salinity.\n"); dc_salinity_t salinity = {DC_WATER_FRESH, 0.0}; status = dc_parser_get_field (parser, DC_FIELD_SALINITY, 0, &salinity); if (status != DC_STATUS_SUCCESS && status != DC_STATUS_UNSUPPORTED) { ERROR ("Error parsing the salinity."); goto cleanup; } if (status != DC_STATUS_UNSUPPORTED) { fprintf (output->ostream, "<salinity type=\"%u\">%.1f</salinity>\n", salinity.type, salinity.density); } // Parse the atmospheric pressure. message ("Parsing the atmospheric pressure.\n"); double atmospheric = 0.0; status = dc_parser_get_field (parser, DC_FIELD_ATMOSPHERIC, 0, &atmospheric); if (status != DC_STATUS_SUCCESS && status != DC_STATUS_UNSUPPORTED) { ERROR ("Error parsing the atmospheric pressure."); goto cleanup; } if (status != DC_STATUS_UNSUPPORTED) { fprintf (output->ostream, "<atmospheric>%.5f</atmospheric>\n", convert_pressure(atmospheric, output->units)); } message ("Parsing strings.\n"); int idx; for (idx = 0; idx < 100; idx++) { dc_field_string_t str = { NULL }; status = dc_parser_get_field(parser, DC_FIELD_STRING, idx, &str); if (status != DC_STATUS_SUCCESS && status != DC_STATUS_UNSUPPORTED) { ERROR ("Error parsing strings"); goto cleanup; } if (status == DC_STATUS_UNSUPPORTED) break; if (!str.desc || !str.value) break; fprintf (output->ostream, "<extradata key='%s' value='%s' />\n", str.desc, str.value); } // Parse the sample data. message ("Parsing the sample data.\n"); status = dc_parser_samples_foreach (parser, sample_cb, &sampledata); if (status != DC_STATUS_SUCCESS) { ERROR ("Error parsing the sample data."); goto cleanup; } cleanup: if (sampledata.nsamples) fprintf (output->ostream, "</sample>\n"); fprintf (output->ostream, "</dive>\n"); return status; } static dc_status_t dctool_xml_output_free (dctool_output_t *abstract) { dctool_xml_output_t *output = (dctool_xml_output_t *) abstract; fprintf (output->ostream, "</device>\n"); fclose (output->ostream); return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
examples/output_xml.c
/* * libdivecomputer * * Copyright (C) 2015 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <unistd.h> #include <stdio.h> #ifdef HAVE_GETOPT_H #include <getopt.h> #endif #include <libdivecomputer/context.h> #include <libdivecomputer/descriptor.h> #include <libdivecomputer/device.h> #include "dctool.h" #include "common.h" #include "utils.h" static dc_status_t doread (dc_context_t *context, dc_descriptor_t *descriptor, const char *devname, unsigned int address, dc_buffer_t *buffer) { dc_status_t rc = DC_STATUS_SUCCESS; dc_device_t *device = NULL; // Open the device. message ("Opening the device (%s %s, %s).\n", dc_descriptor_get_vendor (descriptor), dc_descriptor_get_product (descriptor), devname ? devname : "null"); rc = dc_device_open (&device, context, descriptor, devname); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error opening the device."); goto cleanup; } // Register the event handler. message ("Registering the event handler.\n"); int events = DC_EVENT_WAITING | DC_EVENT_PROGRESS | DC_EVENT_DEVINFO | DC_EVENT_CLOCK | DC_EVENT_VENDOR; rc = dc_device_set_events (device, events, dctool_event_cb, NULL); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error registering the event handler."); goto cleanup; } // Register the cancellation handler. message ("Registering the cancellation handler.\n"); rc = dc_device_set_cancel (device, dctool_cancel_cb, NULL); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error registering the cancellation handler."); goto cleanup; } // Read data from the internal memory. message ("Reading data from the internal memory.\n"); rc = dc_device_read (device, address, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer)); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error reading from the internal memory."); goto cleanup; } cleanup: dc_device_close (device); return rc; } static int dctool_read_run (int argc, char *argv[], dc_context_t *context, dc_descriptor_t *descriptor) { int exitcode = EXIT_SUCCESS; dc_status_t status = DC_STATUS_SUCCESS; dc_buffer_t *buffer = NULL; // Default option values. unsigned int help = 0; const char *filename = NULL; unsigned int address = 0, have_address = 0; unsigned int count = 0, have_count = 0; // Parse the command-line options. int opt = 0; const char *optstring = "ha:c:o:"; #ifdef HAVE_GETOPT_LONG struct option options[] = { {"help", no_argument, 0, 'h'}, {"address", required_argument, 0, 'a'}, {"count", required_argument, 0, 'c'}, {"output", required_argument, 0, 'o'}, {0, 0, 0, 0 } }; while ((opt = getopt_long (argc, argv, optstring, options, NULL)) != -1) { #else while ((opt = getopt (argc, argv, optstring)) != -1) { #endif switch (opt) { case 'h': help = 1; break; case 'a': address = strtoul (optarg, NULL, 0); have_address = 1; break; case 'c': count = strtoul (optarg, NULL, 0); have_count = 1; break; case 'o': filename = optarg; break; default: return EXIT_FAILURE; } } argc -= optind; argv += optind; // Show help message. if (help) { dctool_command_showhelp (&dctool_read); return EXIT_SUCCESS; } // Check mandatory arguments. if (!have_address || !have_count) { message ("No memory address or byte count specified.\n"); exitcode = EXIT_FAILURE; goto cleanup; } // Allocate a memory buffer. buffer = dc_buffer_new (count); dc_buffer_resize (buffer, count); if (buffer == NULL) { message ("Failed to allocate a memory buffer.\n"); exitcode = EXIT_FAILURE; goto cleanup; } // Read data from the internal memory. status = doread (context, descriptor, argv[0], address, buffer); if (status != DC_STATUS_SUCCESS) { message ("ERROR: %s\n", dctool_errmsg (status)); exitcode = EXIT_FAILURE; goto cleanup; } // Write the buffer to file. dctool_file_write (filename, buffer); cleanup: dc_buffer_free (buffer); return exitcode; } const dctool_command_t dctool_read = { dctool_read_run, DCTOOL_CONFIG_DESCRIPTOR, "read", "Read data from the internal memory", "Usage:\n" " dctool read [options] <devname>\n" "\n" "Options:\n" #ifdef HAVE_GETOPT_LONG " -h, --help Show help message\n" " -a, --address <address> Memory address\n" " -c, --count <count> Number of bytes\n" " -o, --output <filename> Output filename\n" #else " -h Show help message\n" " -a <address> Memory address\n" " -c <count> Number of bytes\n" " -o <filename> Output filename\n" #endif };
libdc-for-dirk-Subsurface-branch
examples/dctool_read.c
/* * libdivecomputer * * Copyright (C) 2016 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include "output-private.h" #include "utils.h" static dc_status_t dctool_raw_output_write (dctool_output_t *output, dc_parser_t *parser, const unsigned char data[], unsigned int size, const unsigned char fingerprint[], unsigned int fsize); static dc_status_t dctool_raw_output_free (dctool_output_t *output); typedef struct dctool_raw_output_t { dctool_output_t base; char *template; } dctool_raw_output_t; static const dctool_output_vtable_t raw_vtable = { sizeof(dctool_raw_output_t), /* size */ dctool_raw_output_write, /* write */ dctool_raw_output_free, /* free */ }; static int mktemplate_fingerprint (char *buffer, size_t size, const unsigned char fingerprint[], size_t fsize) { const unsigned char ascii[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; if (size < 2 * fsize + 1) return -1; for (size_t i = 0; i < fsize; ++i) { // Set the most-significant nibble. unsigned char msn = (fingerprint[i] >> 4) & 0x0F; buffer[i * 2 + 0] = ascii[msn]; // Set the least-significant nibble. unsigned char lsn = fingerprint[i] & 0x0F; buffer[i * 2 + 1] = ascii[lsn]; } // Null-terminate the string. buffer[fsize * 2] = 0; return fsize * 2; } static int mktemplate_datetime (char *buffer, size_t size, dc_parser_t *parser) { dc_status_t rc = DC_STATUS_SUCCESS; dc_datetime_t datetime = {0}; int n = 0; rc = dc_parser_get_datetime (parser, &datetime); if (rc != DC_STATUS_SUCCESS) return -1; n = snprintf (buffer, size, "%04i%02i%02iT%02i%02i%02i", datetime.year, datetime.month, datetime.day, datetime.hour, datetime.minute, datetime.second); if (n < 0 || n >= size) return -1; return n; } static int mktemplate_number (char *buffer, size_t size, unsigned int number) { int n = 0; n = snprintf (buffer, size, "%04u", number); if (n < 0 || n >= size) return -1; return n; } static int mktemplate (char *buffer, size_t size, const char *format, dc_parser_t *parser, const unsigned char fingerprint[], size_t fsize, unsigned int number) { const char *p = format; size_t n = 0; int len = 0; char ch = 0; while ((ch = *p++) != 0) { if (ch != '%') { if (n >= size) return -1; buffer[n] = ch; n++; continue; } ch = *p++; switch (ch) { case '%': if (n >= size) return -1; buffer[n] = ch; n++; break; case 't': // Timestamp len = mktemplate_datetime (buffer + n, size - n, parser); if (len < 0) return -1; n += len; break; case 'f': // Fingerprint len = mktemplate_fingerprint (buffer + n, size - n, fingerprint, fsize); if (len < 0) return -1; n += len; break; case 'n': // Number len = mktemplate_number (buffer + n, size - n, number); if (len < 0) return -1; n += len; break; default: return -1; } } // Null-terminate the string if (n >= size) return -1; buffer[n] = 0; return n; } dctool_output_t * dctool_raw_output_new (const char *template) { dctool_raw_output_t *output = NULL; if (template == NULL) goto error_exit; // Allocate memory. output = (dctool_raw_output_t *) dctool_output_allocate (&raw_vtable); if (output == NULL) { goto error_exit; } output->template = strdup(template); if (output->template == NULL) { goto error_free; } return (dctool_output_t *) output; error_free: dctool_output_deallocate ((dctool_output_t *) output); error_exit: return NULL; } static dc_status_t dctool_raw_output_write (dctool_output_t *abstract, dc_parser_t *parser, const unsigned char data[], unsigned int size, const unsigned char fingerprint[], unsigned int fsize) { dctool_raw_output_t *output = (dctool_raw_output_t *) abstract; // Generate the filename. char name[1024] = {0}; int ret = mktemplate (name, sizeof(name), output->template, parser, fingerprint, fsize, abstract->number); if (ret < 0) { ERROR("Failed to generate filename from template."); return DC_STATUS_SUCCESS; } // Open the output file. FILE *fp = fopen (name, "wb"); if (fp == NULL) { ERROR("Failed to open the output file."); return DC_STATUS_SUCCESS; } // Write the data. fwrite (data, sizeof (unsigned char), size, fp); fclose (fp); return DC_STATUS_SUCCESS; } static dc_status_t dctool_raw_output_free (dctool_output_t *abstract) { dctool_raw_output_t *output = (dctool_raw_output_t *) abstract; free (output->template); return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
examples/output_raw.c
/* * libdivecomputer * * Copyright (C) 2015 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <unistd.h> #include <stdio.h> #ifdef HAVE_GETOPT_H #include <getopt.h> #endif #include <libdivecomputer/context.h> #include <libdivecomputer/descriptor.h> #include <libdivecomputer/device.h> #include "dctool.h" #include "common.h" #include "utils.h" static dc_status_t dowrite (dc_context_t *context, dc_descriptor_t *descriptor, const char *devname, unsigned int address, dc_buffer_t *buffer) { dc_status_t rc = DC_STATUS_SUCCESS; dc_device_t *device = NULL; // Open the device. message ("Opening the device (%s %s, %s).\n", dc_descriptor_get_vendor (descriptor), dc_descriptor_get_product (descriptor), devname ? devname : "null"); rc = dc_device_open (&device, context, descriptor, devname); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error opening the device."); goto cleanup; } // Register the event handler. message ("Registering the event handler.\n"); int events = DC_EVENT_WAITING | DC_EVENT_PROGRESS | DC_EVENT_DEVINFO | DC_EVENT_CLOCK | DC_EVENT_VENDOR; rc = dc_device_set_events (device, events, dctool_event_cb, NULL); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error registering the event handler."); goto cleanup; } // Register the cancellation handler. message ("Registering the cancellation handler.\n"); rc = dc_device_set_cancel (device, dctool_cancel_cb, NULL); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error registering the cancellation handler."); goto cleanup; } // Write data to the internal memory. message ("Writing data to the internal memory.\n"); rc = dc_device_write (device, address, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer)); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error writing to the internal memory."); goto cleanup; } cleanup: dc_device_close (device); return rc; } static int dctool_write_run (int argc, char *argv[], dc_context_t *context, dc_descriptor_t *descriptor) { int exitcode = EXIT_SUCCESS; dc_status_t status = DC_STATUS_SUCCESS; dc_buffer_t *buffer = NULL; // Default option values. unsigned int help = 0; const char *filename = NULL; unsigned int address = 0, have_address = 0; unsigned int count = 0, have_count = 0; // Parse the command-line options. int opt = 0; const char *optstring = "ha:c:i:"; #ifdef HAVE_GETOPT_LONG struct option options[] = { {"help", no_argument, 0, 'h'}, {"address", required_argument, 0, 'a'}, {"count", required_argument, 0, 'c'}, {"input", required_argument, 0, 'i'}, {0, 0, 0, 0 } }; while ((opt = getopt_long (argc, argv, optstring, options, NULL)) != -1) { #else while ((opt = getopt (argc, argv, optstring)) != -1) { #endif switch (opt) { case 'h': help = 1; break; case 'a': address = strtoul (optarg, NULL, 0); have_address = 1; break; case 'c': count = strtoul (optarg, NULL, 0); have_count = 1; break; case 'i': filename = optarg; break; default: return EXIT_FAILURE; } } argc -= optind; argv += optind; // Show help message. if (help) { dctool_command_showhelp (&dctool_write); return EXIT_SUCCESS; } // Check mandatory arguments. if (!have_address) { message ("No memory address specified.\n"); exitcode = EXIT_FAILURE; goto cleanup; } // Read the buffer from file. buffer = dctool_file_read (filename); if (buffer == NULL) { message ("Failed to read the input file.\n"); exitcode = EXIT_FAILURE; goto cleanup; } // Check the number of bytes (if provided) if (have_count && count != dc_buffer_get_size (buffer)) { message ("Number of bytes doesn't match file length.\n"); exitcode = EXIT_FAILURE; goto cleanup; } // Write data to the internal memory. status = dowrite (context, descriptor, argv[0], address, buffer); if (status != DC_STATUS_SUCCESS) { message ("ERROR: %s\n", dctool_errmsg (status)); exitcode = EXIT_FAILURE; goto cleanup; } cleanup: dc_buffer_free (buffer); return exitcode; } const dctool_command_t dctool_write = { dctool_write_run, DCTOOL_CONFIG_DESCRIPTOR, "write", "Write data to the internal memory", "Usage:\n" " dctool write [options] <devname>\n" "\n" "Options:\n" #ifdef HAVE_GETOPT_LONG " -h, --help Show help message\n" " -a, --address <address> Memory address\n" " -c, --count <count> Number of bytes\n" " -i, --input <filename> Input filename\n" #else " -h Show help message\n" " -a <address> Memory address\n" " -c <count> Number of bytes\n" " -i <filename> Input filename\n" #endif };
libdc-for-dirk-Subsurface-branch
examples/dctool_write.c
/* * libdivecomputer * * Copyright (C) 2015 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <unistd.h> #include <stdio.h> #ifdef HAVE_GETOPT_H #include <getopt.h> #endif #include <libdivecomputer/context.h> #include <libdivecomputer/descriptor.h> #include "dctool.h" #include "utils.h" static int dctool_help_run (int argc, char *argv[], dc_context_t *context, dc_descriptor_t *descriptor) { // Default option values. unsigned int help = 0; // Parse the command-line options. int opt = 0; const char *optstring = "h"; #ifdef HAVE_GETOPT_LONG struct option options[] = { {"help", no_argument, 0, 'h'}, {0, 0, 0, 0 } }; while ((opt = getopt_long (argc, argv, optstring, options, NULL)) != -1) { #else while ((opt = getopt (argc, argv, optstring)) != -1) { #endif switch (opt) { case 'h': help = 1; break; default: return EXIT_FAILURE; } } argc -= optind; argv += optind; // Show help message. if (help) { dctool_command_showhelp (&dctool_help); return EXIT_SUCCESS; } // Try to find the command. const dctool_command_t *command = NULL; if (argv[0] != NULL) { command = dctool_command_find (argv[0]); if (command == NULL) { message ("Unknown command %s.\n", argv[0]); return EXIT_FAILURE; } } // Show help message for the command. dctool_command_showhelp (command); return EXIT_SUCCESS; } const dctool_command_t dctool_help = { dctool_help_run, DCTOOL_CONFIG_NONE, "help", "Show basic help instructions", "Usage:\n" " dctool help [options] [<command>]\n" "\n" "Options:\n" #ifdef HAVE_GETOPT_LONG " -h, --help Show help message\n" #else " -h Show help message\n" #endif };
libdc-for-dirk-Subsurface-branch
examples/dctool_help.c
/* * libdivecomputer * * Copyright (C) 2015 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <string.h> #ifdef HAVE_GETOPT_H #include <getopt.h> #endif #include <libdivecomputer/context.h> #include <libdivecomputer/descriptor.h> #include <libdivecomputer/device.h> #include "dctool.h" #include "common.h" #include "utils.h" static dc_status_t dump (dc_context_t *context, dc_descriptor_t *descriptor, const char *devname, dc_buffer_t *fingerprint, dc_buffer_t *buffer) { dc_status_t rc = DC_STATUS_SUCCESS; dc_device_t *device = NULL; // Open the device. message ("Opening the device (%s %s, %s).\n", dc_descriptor_get_vendor (descriptor), dc_descriptor_get_product (descriptor), devname ? devname : "null"); rc = dc_device_open (&device, context, descriptor, devname); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error opening the device."); goto cleanup; } // Register the event handler. message ("Registering the event handler.\n"); int events = DC_EVENT_WAITING | DC_EVENT_PROGRESS | DC_EVENT_DEVINFO | DC_EVENT_CLOCK | DC_EVENT_VENDOR; rc = dc_device_set_events (device, events, dctool_event_cb, NULL); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error registering the event handler."); goto cleanup; } // Register the cancellation handler. message ("Registering the cancellation handler.\n"); rc = dc_device_set_cancel (device, dctool_cancel_cb, NULL); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error registering the cancellation handler."); goto cleanup; } // Register the fingerprint data. if (fingerprint) { message ("Registering the fingerprint data.\n"); rc = dc_device_set_fingerprint (device, dc_buffer_get_data (fingerprint), dc_buffer_get_size (fingerprint)); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error registering the fingerprint data."); goto cleanup; } } // Download the memory dump. message ("Downloading the memory dump.\n"); rc = dc_device_dump (device, buffer); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error downloading the memory dump."); goto cleanup; } cleanup: dc_device_close (device); return rc; } static int dctool_dump_run (int argc, char *argv[], dc_context_t *context, dc_descriptor_t *descriptor) { int exitcode = EXIT_SUCCESS; dc_status_t status = DC_STATUS_SUCCESS; dc_buffer_t *fingerprint = NULL; dc_buffer_t *buffer = NULL; // Default option values. unsigned int help = 0; const char *fphex = NULL; const char *filename = NULL; // Parse the command-line options. int opt = 0; const char *optstring = "ho:p:"; #ifdef HAVE_GETOPT_LONG struct option options[] = { {"help", no_argument, 0, 'h'}, {"output", required_argument, 0, 'o'}, {"fingerprint", required_argument, 0, 'p'}, {0, 0, 0, 0 } }; while ((opt = getopt_long (argc, argv, optstring, options, NULL)) != -1) { #else while ((opt = getopt (argc, argv, optstring)) != -1) { #endif switch (opt) { case 'h': help = 1; break; case 'o': filename = optarg; break; case 'p': fphex = optarg; break; default: return EXIT_FAILURE; } } argc -= optind; argv += optind; // Show help message. if (help) { dctool_command_showhelp (&dctool_dump); return EXIT_SUCCESS; } // Convert the fingerprint to binary. fingerprint = dctool_convert_hex2bin (fphex); // Allocate a memory buffer. buffer = dc_buffer_new (0); // Download the memory dump. status = dump (context, descriptor, argv[0], fingerprint, buffer); if (status != DC_STATUS_SUCCESS) { message ("ERROR: %s\n", dctool_errmsg (status)); exitcode = EXIT_FAILURE; goto cleanup; } // Write the memory dump to disk. dctool_file_write (filename, buffer); cleanup: dc_buffer_free (buffer); dc_buffer_free (fingerprint); return exitcode; } const dctool_command_t dctool_dump = { dctool_dump_run, DCTOOL_CONFIG_DESCRIPTOR, "dump", "Download a memory dump", "Usage:\n" " dctool dump [options] <devname>\n" "\n" "Options:\n" #ifdef HAVE_GETOPT_LONG " -h, --help Show help message\n" " -o, --output <filename> Output filename\n" " -p, --fingerprint <data> Fingerprint data (hexadecimal)\n" #else " -h Show help message\n" " -o <filename> Output filename\n" " -p <fingerprint> Fingerprint data (hexadecimal)\n" #endif };
libdc-for-dirk-Subsurface-branch
examples/dctool_dump.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdio.h> #include <stdarg.h> #include <string.h> #include <libdivecomputer/datetime.h> #include <libdivecomputer/version.h> #include "utils.h" static FILE* g_logfile = NULL; static unsigned char g_lastchar = '\n'; #ifdef _WIN32 #include <windows.h> static LARGE_INTEGER g_timestamp, g_frequency; #else #include <sys/time.h> static struct timeval g_timestamp; #endif int message (const char* fmt, ...) { va_list ap; if (g_logfile) { if (g_lastchar == '\n') { #ifdef _WIN32 LARGE_INTEGER now, timestamp; QueryPerformanceCounter(&now); timestamp.QuadPart = now.QuadPart - g_timestamp.QuadPart; timestamp.QuadPart *= 1000000; timestamp.QuadPart /= g_frequency.QuadPart; fprintf (g_logfile, "[%I64i.%06I64i] ", timestamp.QuadPart / 1000000, timestamp.QuadPart % 1000000); #else struct timeval now, timestamp; gettimeofday (&now, NULL); timersub (&now, &g_timestamp, &timestamp); fprintf (g_logfile, "[%lli.%06lli] ", (long long)timestamp.tv_sec, (long long)timestamp.tv_usec); #endif } size_t len = strlen (fmt); if (len > 0) g_lastchar = fmt[len - 1]; else g_lastchar = 0; va_start (ap, fmt); vfprintf (g_logfile, fmt, ap); va_end (ap); } va_start (ap, fmt); int rc = vfprintf (stderr, fmt, ap); va_end (ap); return rc; } void message_set_logfile (const char* filename) { if (g_logfile) { fclose (g_logfile); g_logfile = NULL; } if (filename) g_logfile = fopen (filename, "w"); if (g_logfile) { g_lastchar = '\n'; #ifdef _WIN32 QueryPerformanceFrequency(&g_frequency); QueryPerformanceCounter(&g_timestamp); #else gettimeofday (&g_timestamp, NULL); #endif dc_datetime_t dt = {0}; dc_ticks_t now = dc_datetime_now (); dc_datetime_gmtime (&dt, now); message ("DATETIME %u-%02u-%02uT%02u:%02u:%02uZ (%lu)\n", dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, (unsigned long) now); message ("VERSION %s\n", dc_version (NULL)); } }
libdc-for-dirk-Subsurface-branch
examples/utils.c
/* * libdivecomputer * * Copyright (C) 2017 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <unistd.h> #include <stdio.h> #ifdef HAVE_GETOPT_H #include <getopt.h> #endif #include <libdivecomputer/context.h> #include <libdivecomputer/descriptor.h> #include <libdivecomputer/device.h> #include "dctool.h" #include "common.h" #include "utils.h" static dc_status_t do_timesync (dc_context_t *context, dc_descriptor_t *descriptor, const char *devname, const dc_datetime_t *datetime) { dc_status_t rc = DC_STATUS_SUCCESS; dc_device_t *device = NULL; // Open the device. message ("Opening the device (%s %s, %s).\n", dc_descriptor_get_vendor (descriptor), dc_descriptor_get_product (descriptor), devname ? devname : "null"); rc = dc_device_open (&device, context, descriptor, devname); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error opening the device."); goto cleanup; } // Register the event handler. message ("Registering the event handler.\n"); int events = DC_EVENT_WAITING | DC_EVENT_PROGRESS | DC_EVENT_DEVINFO | DC_EVENT_CLOCK | DC_EVENT_VENDOR; rc = dc_device_set_events (device, events, dctool_event_cb, NULL); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error registering the event handler."); goto cleanup; } // Register the cancellation handler. message ("Registering the cancellation handler.\n"); rc = dc_device_set_cancel (device, dctool_cancel_cb, NULL); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error registering the cancellation handler."); goto cleanup; } // Syncronize the device clock. message ("Syncronize the device clock.\n"); rc = dc_device_timesync (device, datetime); if (rc != DC_STATUS_SUCCESS) { ERROR ("Error syncronizing the device clock."); goto cleanup; } cleanup: dc_device_close (device); return rc; } static int dctool_timesync_run (int argc, char *argv[], dc_context_t *context, dc_descriptor_t *descriptor) { int exitcode = EXIT_SUCCESS; dc_status_t status = DC_STATUS_SUCCESS; // Default option values. unsigned int help = 0; // Parse the command-line options. int opt = 0; const char *optstring = "h"; #ifdef HAVE_GETOPT_LONG struct option options[] = { {"help", no_argument, 0, 'h'}, {0, 0, 0, 0 } }; while ((opt = getopt_long (argc, argv, optstring, options, NULL)) != -1) { #else while ((opt = getopt (argc, argv, optstring)) != -1) { #endif switch (opt) { case 'h': help = 1; break; default: return EXIT_FAILURE; } } argc -= optind; argv += optind; // Show help message. if (help) { dctool_command_showhelp (&dctool_timesync); return EXIT_SUCCESS; } // Get the system time. dc_datetime_t datetime = {0}; dc_ticks_t now = dc_datetime_now (); if (!dc_datetime_localtime(&datetime, now)) { message ("ERROR: Failed to get the system time.\n"); exitcode = EXIT_FAILURE; goto cleanup; } // Synchronize the device clock. status = do_timesync (context, descriptor, argv[0], &datetime); if (status != DC_STATUS_SUCCESS) { message ("ERROR: %s\n", dctool_errmsg (status)); exitcode = EXIT_FAILURE; goto cleanup; } cleanup: return exitcode; } const dctool_command_t dctool_timesync = { dctool_timesync_run, DCTOOL_CONFIG_DESCRIPTOR, "timesync", "Synchronize the device clock", "Usage:\n" " dctool timesync [options]\n" "\n" "Options:\n" #ifdef HAVE_GETOPT_LONG " -h, --help Show help message\n" #else " -h Show help message\n" #endif };
libdc-for-dirk-Subsurface-branch
examples/dctool_timesync.c
/* * libdivecomputer * * Copyright (C) 2015 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <unistd.h> #include <stdio.h> #ifdef HAVE_GETOPT_H #include <getopt.h> #endif #include <libdivecomputer/context.h> #include <libdivecomputer/descriptor.h> #include <libdivecomputer/version.h> #include "dctool.h" static int dctool_version_run (int argc, char *argv[], dc_context_t *context, dc_descriptor_t *descriptor) { // Default option values. unsigned int help = 0; // Parse the command-line options. int opt = 0; const char *optstring = "h"; #ifdef HAVE_GETOPT_LONG struct option options[] = { {"help", no_argument, 0, 'h'}, {0, 0, 0, 0 } }; while ((opt = getopt_long (argc, argv, optstring, options, NULL)) != -1) { #else while ((opt = getopt (argc, argv, optstring)) != -1) { #endif switch (opt) { case 'h': help = 1; break; default: return EXIT_FAILURE; } } argc -= optind; argv += optind; // Show help message. if (help) { dctool_command_showhelp (&dctool_version); return EXIT_SUCCESS; } printf ("libdivecomputer version %s\n", dc_version (NULL)); return EXIT_SUCCESS; } const dctool_command_t dctool_version = { dctool_version_run, DCTOOL_CONFIG_NONE, "version", "Show version information", "Usage:\n" " dctool version [options]\n" "\n" "Options:\n" #ifdef HAVE_GETOPT_LONG " -h, --help Show help message\n" #else " -h Show help message\n" #endif };
libdc-for-dirk-Subsurface-branch
examples/dctool_version.c
/* * libdivecomputer * * Copyright (C) 2015 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include <signal.h> #ifdef HAVE_GETOPT_H #include <getopt.h> #endif #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #include <libdivecomputer/context.h> #include <libdivecomputer/descriptor.h> #include "common.h" #include "dctool.h" #include "utils.h" #if defined(__GLIBC__) || defined(__MINGW32__) #define RESET 0 #else #define RESET 1 #endif #if defined(__GLIBC__) || defined(__MINGW32__) || defined(BSD) #define NOPERMUTATION "+" #else #define NOPERMUTATION "" #endif static const dctool_command_t *g_commands[] = { &dctool_help, &dctool_version, &dctool_list, &dctool_download, &dctool_dump, &dctool_parse, &dctool_read, &dctool_write, &dctool_timesync, &dctool_fwupdate, NULL }; static volatile sig_atomic_t g_cancel = 0; const dctool_command_t * dctool_command_find (const char *name) { if (name == NULL) return NULL; size_t i = 0; while (g_commands[i] != NULL) { if (strcmp(g_commands[i]->name, name) == 0) { break; } i++; } return g_commands[i]; } void dctool_command_showhelp (const dctool_command_t *command) { if (command == NULL) { unsigned int maxlength = 0; for (size_t i = 0; g_commands[i] != NULL; ++i) { unsigned int length = strlen (g_commands[i]->name); if (length > maxlength) maxlength = length; } printf ( "A simple command line interface for the libdivecomputer library\n" "\n" "Usage:\n" " dctool [options] <command> [<args>]\n" "\n" "Options:\n" #ifdef HAVE_GETOPT_LONG " -h, --help Show help message\n" " -d, --device <device> Device name\n" " -f, --family <family> Device family type\n" " -m, --model <model> Device model number\n" " -l, --logfile <logfile> Logfile\n" " -q, --quiet Quiet mode\n" " -v, --verbose Verbose mode\n" #else " -h Show help message\n" " -d <device> Device name\n" " -f <family> Family type\n" " -m <model> Model number\n" " -l <logfile> Logfile\n" " -q Quiet mode\n" " -v Verbose mode\n" #endif "\n" "Available commands:\n"); for (size_t i = 0; g_commands[i] != NULL; ++i) { printf (" %-*s%s\n", maxlength + 3, g_commands[i]->name, g_commands[i]->description); } printf ("\nSee 'dctool help <command>' for more information on a specific command.\n\n"); } else { printf ("%s\n\n%s\n", command->description, command->usage); } } int dctool_cancel_cb (void *userdata) { return g_cancel; } static void sighandler (int signum) { #ifndef _WIN32 // Restore the default signal handler. signal (signum, SIG_DFL); #endif g_cancel = 1; } static void logfunc (dc_context_t *context, dc_loglevel_t loglevel, const char *file, unsigned int line, const char *function, const char *msg, void *userdata) { const char *loglevels[] = {"NONE", "ERROR", "WARNING", "INFO", "DEBUG", "ALL"}; if (loglevel == DC_LOGLEVEL_ERROR || loglevel == DC_LOGLEVEL_WARNING) { message ("%s: %s [in %s:%d (%s)]\n", loglevels[loglevel], msg, file, line, function); } else { message ("%s: %s\n", loglevels[loglevel], msg); } } int main (int argc, char *argv[]) { int exitcode = EXIT_SUCCESS; dc_status_t status = DC_STATUS_SUCCESS; dc_context_t *context = NULL; dc_descriptor_t *descriptor = NULL; // Default option values. unsigned int help = 0; dc_loglevel_t loglevel = DC_LOGLEVEL_WARNING; const char *logfile = NULL; const char *device = NULL; dc_family_t family = DC_FAMILY_NULL; unsigned int model = 0; unsigned int have_family = 0, have_model = 0; // Parse the command-line options. int opt = 0; const char *optstring = NOPERMUTATION "hd:f:m:l:qv"; #ifdef HAVE_GETOPT_LONG struct option options[] = { {"help", no_argument, 0, 'h'}, {"device", required_argument, 0, 'd'}, {"family", required_argument, 0, 'f'}, {"model", required_argument, 0, 'm'}, {"logfile", required_argument, 0, 'l'}, {"quiet", no_argument, 0, 'q'}, {"verbose", no_argument, 0, 'v'}, {0, 0, 0, 0 } }; while ((opt = getopt_long (argc, argv, optstring, options, NULL)) != -1) { #else while ((opt = getopt (argc, argv, optstring)) != -1) { #endif switch (opt) { case 'h': help = 1; break; case 'd': device = optarg; break; case 'f': family = dctool_family_type (optarg); have_family = 1; break; case 'm': model = strtoul (optarg, NULL, 0); have_model = 1; break; case 'l': logfile = optarg; break; case 'q': loglevel = DC_LOGLEVEL_NONE; break; case 'v': loglevel++; break; default: return EXIT_FAILURE; } } // Skip the processed arguments. argc -= optind; argv += optind; optind = RESET; #if defined(HAVE_DECL_OPTRESET) && HAVE_DECL_OPTRESET optreset = 1; #endif // Set the default model number. if (have_family && !have_model) { model = dctool_family_model (family); } // Translate the help option into a command. char *argv_help[] = {(char *) "help", NULL, NULL}; if (help || argv[0] == NULL) { if (argv[0]) { argv_help[1] = argv[0]; argv = argv_help; argc = 2; } else { argv = argv_help; argc = 1; } } // Try to find the command. const dctool_command_t *command = dctool_command_find (argv[0]); if (command == NULL) { message ("Unknown command %s.\n", argv[0]); return EXIT_FAILURE; } // Setup the cancel signal handler. signal (SIGINT, sighandler); // Initialize the logfile. message_set_logfile (logfile); // Initialize a library context. status = dc_context_new (&context); if (status != DC_STATUS_SUCCESS) { exitcode = EXIT_FAILURE; goto cleanup; } // Setup the logging. dc_context_set_loglevel (context, loglevel); dc_context_set_logfunc (context, logfunc, NULL); if (command->config & DCTOOL_CONFIG_DESCRIPTOR) { // Check mandatory arguments. if (device == NULL && family == DC_FAMILY_NULL) { message ("No device name or family type specified.\n"); exitcode = EXIT_FAILURE; goto cleanup; } // Search for a matching device descriptor. status = dctool_descriptor_search (&descriptor, device, family, model); if (status != DC_STATUS_SUCCESS) { exitcode = EXIT_FAILURE; goto cleanup; } // Fail if no device descriptor found. if (descriptor == NULL) { if (device) { message ("No supported device found: %s\n", device); } else { message ("No supported device found: %s, 0x%X\n", dctool_family_name (family), model); } exitcode = EXIT_FAILURE; goto cleanup; } } // Execute the command. exitcode = command->run (argc, argv, context, descriptor); cleanup: dc_descriptor_free (descriptor); dc_context_free (context); message_set_logfile (NULL); return exitcode; }
libdc-for-dirk-Subsurface-branch
examples/dctool.c
/* * libdivecomputer * * Copyright (C) 2016 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <assert.h> #include "output-private.h" dctool_output_t * dctool_output_allocate (const dctool_output_vtable_t *vtable) { dctool_output_t *output = NULL; assert(vtable != NULL); assert(vtable->size >= sizeof(dctool_output_t)); // Allocate memory. output = (dctool_output_t *) malloc (vtable->size); if (output == NULL) { return output; } output->vtable = vtable; output->number = 0; return output; } void dctool_output_deallocate (dctool_output_t *output) { free (output); } dc_status_t dctool_output_write (dctool_output_t *output, dc_parser_t *parser, const unsigned char data[], unsigned int size, const unsigned char fingerprint[], unsigned int fsize) { if (output == NULL || output->vtable->write == NULL) return DC_STATUS_SUCCESS; output->number++; return output->vtable->write (output, parser, data, size, fingerprint, fsize); } dc_status_t dctool_output_free (dctool_output_t *output) { dc_status_t status = DC_STATUS_SUCCESS; if (output == NULL) return DC_STATUS_SUCCESS; if (output->vtable->free) { status = output->vtable->free (output); } dctool_output_deallocate (output); return status; }
libdc-for-dirk-Subsurface-branch
examples/output.c
/* * libdivecomputer * * Copyright (C) 2014 Linus Torvalds * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <ctype.h> #include <math.h> #include <stdarg.h> /* Wow. MSC is truly crap */ #ifdef _MSC_VER #define snprintf _snprintf #define vsnprintf _vsnprintf #endif #include "suunto_eonsteel.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #include "platform.h" #define C_ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a))) enum eon_sample { ES_none = 0, ES_dtime, // duint16,precision=3 (time delta in ms) ES_depth, // uint16,precision=2,nillable=65535 (depth in cm) ES_temp, // int16,precision=2,nillable=-3000 (temp in deci-Celsius) ES_ndl, // int16,nillable=-1 (ndl in minutes) ES_ceiling, // uint16,precision=2,nillable=65535 (ceiling in cm) ES_tts, // uint16,nillable=65535 (time to surface) ES_heading, // uint16,precision=4,nillable=65535 (heading in degrees) ES_abspressure, // uint16,precision=0,nillable=65535 (abs presure in centibar) ES_gastime, // int16,nillable=-1 (remaining gas time in minutes) ES_ventilation, // uint16,precision=6,nillable=65535 ("x/6000000,x"? No idea) ES_gasnr, // uint8 ES_pressure, // uint16,nillable=65535 (cylinder pressure in centibar) ES_state, // enum:0=Wet Outside,1=Below Wet Activation Depth,2=Below Surface,3=Dive Active,4=Surface Calculation,5=Tank pressure available,6=Closed Circuit Mode ES_state_active, // bool ES_notify, // enum:0=NoFly Time,1=Depth,2=Surface Time,3=Tissue Level,4=Deco,5=Deco Window,6=Safety Stop Ahead,7=Safety Stop,8=Safety Stop Broken,9=Deep Stop Ahead,10=Deep Stop,11=Dive Time,12=Gas Available,13=SetPoint Switch,14=Diluent Hypoxia,15=Air Time,16=Tank Pressure ES_notify_active, // bool ES_warning, // enum:0=ICD Penalty,1=Deep Stop Penalty,2=Mandatory Safety Stop,3=OTU250,4=OTU300,5=CNS80%,6=CNS100%,7=Max.Depth,8=Air Time,9=Tank Pressure,10=Safety Stop Broken,11=Deep Stop Broken,12=Ceiling Broken,13=PO2 High ES_warning_active, // bool ES_alarm, ES_alarm_active, ES_gasswitch, // uint16 ES_setpoint_type, // enum:0=Low,1=High,2=Custom ES_setpoint_po2, // uint32 ES_setpoint_automatic, // bool ES_bookmark, }; #define EON_MAX_GROUP 16 struct type_desc { const char *desc, *format, *mod; unsigned int size; enum eon_sample type[EON_MAX_GROUP]; }; #define MAXTYPE 512 #define MAXGASES 16 #define MAXSTRINGS 32 typedef struct suunto_eonsteel_parser_t { dc_parser_t base; struct type_desc type_desc[MAXTYPE]; // field cache struct { unsigned int initialized; unsigned int divetime; double maxdepth; double avgdepth; unsigned int ngases; dc_gasmix_t gasmix[MAXGASES]; dc_salinity_t salinity; double surface_pressure; dc_divemode_t divemode; double lowsetpoint; double highsetpoint; double customsetpoint; dc_field_string_t strings[MAXSTRINGS]; dc_tankinfo_t tankinfo[MAXGASES]; double tanksize[MAXGASES]; double tankworkingpressure[MAXGASES]; } cache; } suunto_eonsteel_parser_t; typedef int (*eon_data_cb_t)(unsigned short type, const struct type_desc *desc, const unsigned char *data, int len, void *user); static const struct { const char *name; enum eon_sample type; } type_translation[] = { { "+Time", ES_dtime }, { "Depth", ES_depth }, { "Temperature", ES_temp }, { "NoDecTime", ES_ndl }, { "Ceiling", ES_ceiling }, { "TimeToSurface", ES_tts }, { "Heading", ES_heading }, { "DeviceInternalAbsPressure", ES_abspressure }, { "GasTime", ES_gastime }, { "Ventilation", ES_ventilation }, { "Cylinders+Cylinder.GasNumber", ES_gasnr }, { "Cylinders.Cylinder.Pressure", ES_pressure }, { "Events+State.Type", ES_state }, { "Events.State.Active", ES_state_active }, { "Events+Notify.Type", ES_notify }, { "Events.Notify.Active", ES_notify_active }, { "Events+Warning.Type", ES_warning }, { "Events.Warning.Active", ES_warning_active }, { "Events+Alarm.Type", ES_alarm }, { "Events.Alarm.Active", ES_alarm_active }, { "Events.Bookmark.Name", ES_bookmark }, { "Events.GasSwitch.GasNumber", ES_gasswitch }, { "Events.SetPoint.Type", ES_setpoint_type }, { "Events.Events.SetPoint.PO2", ES_setpoint_po2 }, { "Events.SetPoint.Automatic", ES_setpoint_automatic }, { "Events.DiveTimer.Active", ES_none }, { "Events.DiveTimer.Time", ES_none }, }; static enum eon_sample lookup_descriptor_type(suunto_eonsteel_parser_t *eon, struct type_desc *desc) { int i; const char *name = desc->desc; // Not a sample type? Skip it if (strncmp(name, "sml.DeviceLog.Samples", 21)) return ES_none; // Skip the common base name += 21; // We have a "+Sample.Time", which starts a new // sample and contains the time delta if (!strcmp(name, "+Sample.Time")) return ES_dtime; // .. the rest should start with ".Sample." if (strncmp(name, ".Sample.", 8)) return ES_none; // Skip the ".Sample." name += 8; // .. and look it up in the table of sample type strings for (i = 0; i < C_ARRAY_SIZE(type_translation); i++) { if (!strcmp(name, type_translation[i].name)) return type_translation[i].type; } return ES_none; } static const char *desc_type_name(enum eon_sample type) { int i; for (i = 0; i < C_ARRAY_SIZE(type_translation); i++) { if (type == type_translation[i].type) return type_translation[i].name; } return "Unknown"; } static int lookup_descriptor_size(suunto_eonsteel_parser_t *eon, struct type_desc *desc) { const char *format = desc->format; unsigned char c; if (!format) return 0; if (!strncmp(format, "bool", 4)) return 1; if (!strncmp(format, "enum", 4)) return 1; if (!strncmp(format, "utf8", 4)) return 0; // find the byte size (eg "float32" -> 4 bytes) while ((c = *format) != 0) { if (isdigit(c)) return atoi(format)/8; format++; } return 0; } static int fill_in_group_details(suunto_eonsteel_parser_t *eon, struct type_desc *desc) { int subtype = 0; const char *grp = desc->desc; for (;;) { struct type_desc *base; char *end; long index; index = strtol(grp, &end, 10); if (index < 0 || index >= MAXTYPE || end == grp) { ERROR(eon->base.context, "Group type descriptor '%s' does not parse", desc->desc); break; } base = eon->type_desc + index; if (!base->desc) { ERROR(eon->base.context, "Group type descriptor '%s' has undescribed index %ld", desc->desc, index); break; } if (!base->size) { ERROR(eon->base.context, "Group type descriptor '%s' uses unsized sub-entry '%s'", desc->desc, base->desc); break; } if (!base->type[0]) { ERROR(eon->base.context, "Group type descriptor '%s' has non-enumerated sub-entry '%s'", desc->desc, base->desc); break; } if (base->type[1]) { ERROR(eon->base.context, "Group type descriptor '%s' has a recursive group sub-entry '%s'", desc->desc, base->desc); break; } if (subtype >= EON_MAX_GROUP-1) { ERROR(eon->base.context, "Group type descriptor '%s' has too many sub-entries", desc->desc); break; } desc->size += base->size; desc->type[subtype++] = base->type[0]; switch (*end) { case 0: return 0; case ',': grp = end+1; continue; default: ERROR(eon->base.context, "Group type descriptor '%s' has unparseable index %ld", desc->desc, index); return -1; } } return -1; } /* * Here we cache descriptor data so that we don't have * to re-parse the string all the time. That way we can * do it just once per type. * * Right now we only bother with the sample descriptors, * which all start with "sml.DeviceLog.Samples" (for the * base types) or are "GRP" types that are a group of said * types and are a set of numbers. */ static int fill_in_desc_details(suunto_eonsteel_parser_t *eon, struct type_desc *desc) { if (!desc->desc) return 0; if (isdigit(desc->desc[0])) return fill_in_group_details(eon, desc); desc->size = lookup_descriptor_size(eon, desc); desc->type[0] = lookup_descriptor_type(eon, desc); return 0; } static void desc_free (struct type_desc desc[], unsigned int count) { for (unsigned int i = 0; i < count; ++i) { free((void *)desc[i].desc); free((void *)desc[i].format); free((void *)desc[i].mod); } } static int record_type(suunto_eonsteel_parser_t *eon, unsigned short type, const char *name, int namelen) { struct type_desc desc; const char *next; memset(&desc, 0, sizeof(desc)); do { int len; char *p; next = strchr(name, '\n'); if (next) { len = next - name; next++; } else { len = strlen(name); if (!len) break; } if (len < 5 || name[0] != '<' || name[4] != '>') { ERROR(eon->base.context, "Unexpected type description: %.*s", len, name); return -1; } p = (char *) malloc(len-4); if (!p) { ERROR(eon->base.context, "out of memory"); desc_free(&desc, 1); return -1; } memcpy(p, name+5, len-5); p[len-5] = 0; // PTH, GRP, FRM, MOD switch (name[1]) { case 'P': case 'G': desc.desc = p; break; case 'F': desc.format = p; break; case 'M': desc.mod = p; break; default: ERROR(eon->base.context, "Unknown type descriptor: %.*s", len, name); desc_free(&desc, 1); free(p); return -1; } } while ((name = next) != NULL); if (type >= MAXTYPE) { ERROR(eon->base.context, "Type out of range (%04x: '%s' '%s' '%s')", type, desc.desc ? desc.desc : "", desc.format ? desc.format : "", desc.mod ? desc.mod : ""); desc_free(&desc, 1); return -1; } fill_in_desc_details(eon, &desc); desc_free(eon->type_desc + type, 1); eon->type_desc[type] = desc; return 0; } static int traverse_entry(suunto_eonsteel_parser_t *eon, const unsigned char *p, int len, eon_data_cb_t callback, void *user) { const unsigned char *name, *data, *end, *last, *one_past_end = p + len; int textlen, type; int rc; // First two bytes: zero and text length if (p[0]) { HEXDUMP(eon->base.context, DC_LOGLEVEL_DEBUG, "next", p, 8); ERROR(eon->base.context, "Bad dive entry (%02x)", p[0]); return -1; } textlen = p[1]; name = p + 2; if (textlen == 0xff) { textlen = array_uint32_le(name); name += 4; } // Two bytes of 'type' followed by the name/descriptor, followed by the data data = name + textlen; type = array_uint16_le(name); name += 2; if (*name != '<') { HEXDUMP(eon->base.context, DC_LOGLEVEL_DEBUG, "bad", p, 16); return -1; } record_type(eon, type, (const char *) name, textlen-3); end = data; last = data; while (end < one_past_end && *end) { const unsigned char *begin = end; unsigned int type = *end++; unsigned int len; if (type == 0xff) { type = array_uint16_le(end); end += 2; } len = *end++; // I've never actually seen this case yet.. // Just assuming from the other cases. if (len == 0xff) { HEXDUMP(eon->base.context, DC_LOGLEVEL_DEBUG, "len-ff", end, 8); len = array_uint32_le(end); end += 4; } if (type >= MAXTYPE || !eon->type_desc[type].desc) { HEXDUMP(eon->base.context, DC_LOGLEVEL_DEBUG, "last", last, 16); HEXDUMP(eon->base.context, DC_LOGLEVEL_DEBUG, "this", begin, 16); } else { rc = callback(type, eon->type_desc+type, end, len, user); if (rc < 0) return rc; } last = begin; end += len; } return end - p; } static int traverse_data(suunto_eonsteel_parser_t *eon, eon_data_cb_t callback, void *user) { const unsigned char *data = eon->base.data; int len = eon->base.size; // Dive files start with "SBEM" and four NUL characters // Additionally, we've prepended the time as an extra // 4-byte pre-header if (len < 12 || memcmp(data+4, "SBEM", 4)) return 0; data += 12; len -= 12; while (len > 4) { int i = traverse_entry(eon, data, len, callback, user); if (i < 0) return 1; len -= i; data += i; } return 0; } struct sample_data { suunto_eonsteel_parser_t *eon; dc_sample_callback_t callback; void *userdata; unsigned int time; const char *state_type, *notify_type; const char *warning_type, *alarm_type; /* We gather up deco and cylinder pressure information */ int gasnr; int tts, ndl; double ceiling; }; static void sample_time(struct sample_data *info, unsigned short time_delta) { dc_sample_value_t sample = {0}; info->time += time_delta; sample.time = info->time / 1000; if (info->callback) info->callback(DC_SAMPLE_TIME, sample, info->userdata); } static void sample_depth(struct sample_data *info, unsigned short depth) { dc_sample_value_t sample = {0}; if (depth == 0xffff) return; sample.depth = depth / 100.0; if (info->callback) info->callback(DC_SAMPLE_DEPTH, sample, info->userdata); } static void sample_temp(struct sample_data *info, short temp) { dc_sample_value_t sample = {0}; if (temp < -3000) return; sample.temperature = temp / 10.0; if (info->callback) info->callback(DC_SAMPLE_TEMPERATURE, sample, info->userdata); } static void sample_ndl(struct sample_data *info, short ndl) { dc_sample_value_t sample = {0}; info->ndl = ndl; if (ndl < 0) return; sample.deco.type = DC_DECO_NDL; sample.deco.time = ndl; if (info->callback) info->callback(DC_SAMPLE_DECO, sample, info->userdata); } static void sample_tts(struct sample_data *info, unsigned short tts) { if (tts != 0xffff) info->tts = tts; } static void sample_ceiling(struct sample_data *info, unsigned short ceiling) { if (ceiling != 0xffff) info->ceiling = ceiling / 100.0; } static void sample_heading(struct sample_data *info, unsigned short heading) { dc_sample_value_t sample = {0}; if (heading == 0xffff) return; sample.event.type = SAMPLE_EVENT_HEADING; sample.event.value = heading; if (info->callback) info->callback(DC_SAMPLE_EVENT, sample, info->userdata); } static void sample_abspressure(struct sample_data *info, unsigned short pressure) { } static void sample_gastime(struct sample_data *info, short gastime) { dc_sample_value_t sample = {0}; if (gastime < 0) return; // Hmm. We have no good way to report airtime remaining } /* * Per-sample "ventilation" data. * * It's described as: * - "uint16,precision=6,nillable=65535" * - "x/6000000,x" */ static void sample_ventilation(struct sample_data *info, unsigned short unk) { } static void sample_gasnr(struct sample_data *info, unsigned char idx) { info->gasnr = idx; } static void sample_pressure(struct sample_data *info, unsigned short pressure) { dc_sample_value_t sample = {0}; if (pressure == 0xffff) return; sample.pressure.tank = info->gasnr-1; sample.pressure.value = pressure / 100.0; if (info->callback) info->callback(DC_SAMPLE_PRESSURE, sample, info->userdata); } static void sample_bookmark_event(struct sample_data *info, unsigned short idx) { dc_sample_value_t sample = {0}; sample.event.type = SAMPLE_EVENT_BOOKMARK; sample.event.value = idx; if (info->callback) info->callback(DC_SAMPLE_EVENT, sample, info->userdata); } static void sample_gas_switch_event(struct sample_data *info, unsigned short idx) { suunto_eonsteel_parser_t *eon = info->eon; dc_sample_value_t sample = {0}; if (idx < 1 || idx > eon->cache.ngases) return; sample.gasmix = idx - 1; if (info->callback) info->callback(DC_SAMPLE_GASMIX, sample, info->userdata); } /* * Look up the string from an enumeration. * * Enumerations have the enum values in the "format" string, * and all start with "enum:" followed by a comma-separated list * of enumeration values and strings. Example: * * "enum:0=NoFly Time,1=Depth,2=Surface Time,3=..." */ static const char *lookup_enum(const struct type_desc *desc, unsigned char value) { const char *str = desc->format; unsigned char c; if (!str) return NULL; if (strncmp(str, "enum:", 5)) return NULL; str += 5; while ((c = *str) != 0) { unsigned char n; const char *begin, *end; char *ret; str++; if (!isdigit(c)) continue; n = c - '0'; // We only handle one or two digits if (isdigit(*str)) { n = n*10 + *str - '0'; str++; } begin = end = str; while ((c = *str) != 0) { str++; if (c == ',') break; end = str; } // Verify that it has the 'n=string' format and skip the equals sign if (*begin != '=') continue; begin++; // Is it the value we're looking for? if (n != value) continue; ret = (char *)malloc(end - begin + 1); if (!ret) break; memcpy(ret, begin, end-begin); ret[end-begin] = 0; return ret; } return NULL; } /* * The EON Steel has four different sample events: "state", "notification", * "warning" and "alarm". All end up having two fields: type and a boolean value. */ static void sample_event_state_type(const struct type_desc *desc, struct sample_data *info, unsigned char type) { info->state_type = lookup_enum(desc, type); } static void sample_event_state_value(const struct type_desc *desc, struct sample_data *info, unsigned char value) { dc_sample_value_t sample = {0}; const char *name; name = info->state_type; if (!name) return; sample.event.type = SAMPLE_EVENT_STRING; sample.event.name = name; sample.event.flags = value ? SAMPLE_FLAGS_BEGIN : SAMPLE_FLAGS_END; sample.event.flags |= 1 << SAMPLE_FLAGS_SEVERITY_SHIFT; if (info->callback) info->callback(DC_SAMPLE_EVENT, sample, info->userdata); } static void sample_event_notify_type(const struct type_desc *desc, struct sample_data *info, unsigned char type) { info->notify_type = lookup_enum(desc, type); } static void sample_event_notify_value(const struct type_desc *desc, struct sample_data *info, unsigned char value) { dc_sample_value_t sample = {0}; const char *name; name = info->notify_type; if (!name) return; sample.event.type = SAMPLE_EVENT_STRING; sample.event.name = name; sample.event.flags = value ? SAMPLE_FLAGS_BEGIN : SAMPLE_FLAGS_END; sample.event.flags |= 2 << SAMPLE_FLAGS_SEVERITY_SHIFT; if (info->callback) info->callback(DC_SAMPLE_EVENT, sample, info->userdata); } static void sample_event_warning_type(const struct type_desc *desc, struct sample_data *info, unsigned char type) { info->warning_type = lookup_enum(desc, type); } static void sample_event_warning_value(const struct type_desc *desc, struct sample_data *info, unsigned char value) { dc_sample_value_t sample = {0}; const char *name; name = info->warning_type; if (!name) return; sample.event.type = SAMPLE_EVENT_STRING; sample.event.name = name; sample.event.flags = value ? SAMPLE_FLAGS_BEGIN : SAMPLE_FLAGS_END; sample.event.flags |= 3 << SAMPLE_FLAGS_SEVERITY_SHIFT; if (info->callback) info->callback(DC_SAMPLE_EVENT, sample, info->userdata); } static void sample_event_alarm_type(const struct type_desc *desc, struct sample_data *info, unsigned char type) { info->alarm_type = lookup_enum(desc, type); } static void sample_event_alarm_value(const struct type_desc *desc, struct sample_data *info, unsigned char value) { const char *name; dc_sample_value_t sample = {0}; name = info->alarm_type; if (!name) return; sample.event.type = SAMPLE_EVENT_STRING; sample.event.name = name; sample.event.flags = value ? SAMPLE_FLAGS_BEGIN : SAMPLE_FLAGS_END; sample.event.flags |= 4 << SAMPLE_FLAGS_SEVERITY_SHIFT; if (info->callback) info->callback(DC_SAMPLE_EVENT, sample, info->userdata); } // enum:0=Low,1=High,2=Custom static void sample_setpoint_type(const struct type_desc *desc, struct sample_data *info, unsigned char value) { dc_sample_value_t sample = {0}; const char *type = lookup_enum(desc, value); if (!type) { DEBUG(info->eon->base.context, "sample_setpoint_type(%u) did not match anything in %s", value, desc->format); return; } if (!strcasecmp(type, "Low")) sample.ppo2 = info->eon->cache.lowsetpoint; else if (!strcasecmp(type, "High")) sample.ppo2 = info->eon->cache.highsetpoint; else if (!strcasecmp(type, "Custom")) sample.ppo2 = info->eon->cache.customsetpoint; else { DEBUG(info->eon->base.context, "sample_setpoint_type(%u) unknown type '%s'", value, type); free((void *)type); return; } if (info->callback) info->callback(DC_SAMPLE_SETPOINT, sample, info->userdata); free((void *)type); } // uint32 static void sample_setpoint_po2(struct sample_data *info, unsigned int pressure) { // I *think* this just sets the custom SP, and then // we'll get a setpoint_type(2) later. info->eon->cache.customsetpoint = pressure / 100000.0; // Pascal to bar } static void sample_setpoint_automatic(struct sample_data *info, unsigned char value) { DEBUG(info->eon->base.context, "sample_setpoint_automatic(%u)", value); } static int handle_sample_type(const struct type_desc *desc, struct sample_data *info, enum eon_sample type, const unsigned char *data) { switch (type) { case ES_dtime: sample_time(info, array_uint16_le(data)); return 2; case ES_depth: sample_depth(info, array_uint16_le(data)); return 2; case ES_temp: sample_temp(info, array_uint16_le(data)); return 2; case ES_ndl: sample_ndl(info, array_uint16_le(data)); return 2; case ES_ceiling: sample_ceiling(info, array_uint16_le(data)); return 2; case ES_tts: sample_tts(info, array_uint16_le(data)); return 2; case ES_heading: sample_heading(info, array_uint16_le(data)); return 2; case ES_abspressure: sample_abspressure(info, array_uint16_le(data)); return 2; case ES_gastime: sample_gastime(info, array_uint16_le(data)); return 2; case ES_ventilation: sample_ventilation(info, array_uint16_le(data)); return 2; case ES_gasnr: sample_gasnr(info, *data); return 1; case ES_pressure: sample_pressure(info, array_uint16_le(data)); return 2; case ES_state: sample_event_state_type(desc, info, data[0]); return 1; case ES_state_active: sample_event_state_value(desc, info, data[0]); return 1; case ES_notify: sample_event_notify_type(desc, info, data[0]); return 1; case ES_notify_active: sample_event_notify_value(desc, info, data[0]); return 1; case ES_warning: sample_event_warning_type(desc, info, data[0]); return 1; case ES_warning_active: sample_event_warning_value(desc, info, data[0]); return 1; case ES_alarm: sample_event_alarm_type(desc, info, data[0]); return 1; case ES_alarm_active: sample_event_alarm_value(desc, info, data[0]); return 1; case ES_bookmark: sample_bookmark_event(info, array_uint16_le(data)); return 2; case ES_gasswitch: sample_gas_switch_event(info, array_uint16_le(data)); return 2; case ES_setpoint_type: sample_setpoint_type(desc, info, data[0]); return 1; case ES_setpoint_po2: sample_setpoint_po2(info, array_uint32_le(data)); return 4; case ES_setpoint_automatic: // bool sample_setpoint_automatic(info, data[0]); return 1; default: return 0; } } static int traverse_samples(unsigned short type, const struct type_desc *desc, const unsigned char *data, int len, void *user) { struct sample_data *info = (struct sample_data *) user; suunto_eonsteel_parser_t *eon = info->eon; int i, used = 0; if (desc->size > len) ERROR(eon->base.context, "Got %d bytes of data for '%s' that wants %d bytes", len, desc->desc, desc->size); info->ndl = -1; info->tts = 0; info->ceiling = 0.0; for (i = 0; i < EON_MAX_GROUP; i++) { enum eon_sample type = desc->type[i]; int bytes = handle_sample_type(desc, info, type, data); if (!bytes) break; if (bytes > len) { ERROR(eon->base.context, "Wanted %d bytes of data, only had %d bytes ('%s' idx %d)", bytes, len, desc->desc, i); break; } data += bytes; len -= bytes; used += bytes; } if (info->ndl < 0 && (info->tts || info->ceiling)) { dc_sample_value_t sample = {0}; sample.deco.type = DC_DECO_DECOSTOP; sample.deco.time = info->tts; sample.deco.depth = info->ceiling; if (info->callback) info->callback(DC_SAMPLE_DECO, sample, info->userdata); } // Warn if there are left-over bytes for something we did use part of if (used && len) ERROR(eon->base.context, "Entry for '%s' had %d bytes, only used %d", desc->desc, len+used, used); return 0; } static dc_status_t suunto_eonsteel_parser_samples_foreach(dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { suunto_eonsteel_parser_t *eon = (suunto_eonsteel_parser_t *) abstract; struct sample_data data = { eon, callback, userdata, 0 }; traverse_data(eon, traverse_samples, &data); return DC_STATUS_SUCCESS; } static dc_status_t get_string_field(suunto_eonsteel_parser_t *eon, unsigned idx, dc_field_string_t *value) { if (idx < MAXSTRINGS) { dc_field_string_t *res = eon->cache.strings+idx; if (res->desc && res->value) { *value = *res; return DC_STATUS_SUCCESS; } } return DC_STATUS_UNSUPPORTED; } // Ugly define thing makes the code much easier to read // I'd love to use __typeof__, but that's a gcc'ism #define field_value(p, set) \ memcpy((p), &(set), sizeof(set)) static dc_status_t suunto_eonsteel_parser_get_field(dc_parser_t *parser, dc_field_type_t type, unsigned int flags, void *value) { dc_tank_t *tank = (dc_tank_t *) value; suunto_eonsteel_parser_t *eon = (suunto_eonsteel_parser_t *)parser; if (!(eon->cache.initialized & (1 << type))) return DC_STATUS_UNSUPPORTED; switch (type) { case DC_FIELD_DIVETIME: field_value(value, eon->cache.divetime); break; case DC_FIELD_MAXDEPTH: field_value(value, eon->cache.maxdepth); break; case DC_FIELD_AVGDEPTH: field_value(value, eon->cache.avgdepth); break; case DC_FIELD_GASMIX_COUNT: case DC_FIELD_TANK_COUNT: field_value(value, eon->cache.ngases); break; case DC_FIELD_GASMIX: if (flags >= MAXGASES) return DC_STATUS_UNSUPPORTED; field_value(value, eon->cache.gasmix[flags]); break; case DC_FIELD_SALINITY: field_value(value, eon->cache.salinity); break; case DC_FIELD_ATMOSPHERIC: field_value(value, eon->cache.surface_pressure); break; case DC_FIELD_DIVEMODE: field_value(value, eon->cache.divemode); break; case DC_FIELD_TANK: /* * Sadly it seems that the EON Steel doesn't tell us whether * we get imperial or metric data - the only indication is * that metric is (at least so far) always whole liters */ tank->volume = eon->cache.tanksize[flags]; tank->gasmix = flags; /* * The pressure reported is NOT the pressure the user enters. * * So 3000psi turns into 206.700 bar instead of 206.843 bar; * We report it as we get it and let the application figure out * what to do with that */ tank->workpressure = eon->cache.tankworkingpressure[flags]; tank->type = eon->cache.tankinfo[flags]; /* * See if we should call this imperial instead. * * We need to have workpressure and a valid tank. In that case, * a fractional tank size implies imperial. */ if (tank->workpressure && (tank->type & DC_TANKINFO_METRIC)) { if (fabs(tank->volume - rint(tank->volume)) > 0.001) tank->type += DC_TANKINFO_IMPERIAL - DC_TANKINFO_METRIC; } break; case DC_FIELD_STRING: return get_string_field(eon, flags, (dc_field_string_t *)value); default: return DC_STATUS_UNSUPPORTED; } return DC_STATUS_SUCCESS; } /* * The time of the dive is encoded in the filename, * and we've saved it off as the four first bytes * of the dive data (in little-endian format). */ static dc_status_t suunto_eonsteel_parser_get_datetime(dc_parser_t *parser, dc_datetime_t *datetime) { if (parser->size < 4) return DC_STATUS_UNSUPPORTED; if (!dc_datetime_gmtime(datetime, array_uint32_le(parser->data))) return DC_STATUS_DATAFORMAT; datetime->timezone = DC_TIMEZONE_NONE; return DC_STATUS_SUCCESS; } // time in ms static void add_time_field(suunto_eonsteel_parser_t *eon, unsigned short time_delta_ms) { eon->cache.divetime += time_delta_ms; } // depth in cm static void set_depth_field(suunto_eonsteel_parser_t *eon, unsigned short d) { if (d != 0xffff) { double depth = d / 100.0; if (depth > eon->cache.maxdepth) eon->cache.maxdepth = depth; eon->cache.initialized |= 1 << DC_FIELD_MAXDEPTH; } } // new gas: // "sml.DeviceLog.Header.Diving.Gases+Gas.State" // // We eventually need to parse the descriptor for that 'enum type'. // Two versions so far: // "enum:0=Off,1=Primary,2=?,3=Diluent" // "enum:0=Off,1=Primary,3=Diluent,4=Oxygen" // // We turn that into the DC_TANKINFO data here, but // initially consider all non-off tanks to me METRIC. // // We may later turn the METRIC tank size into IMPERIAL if we // get a working pressure and non-integral size static int add_gas_type(suunto_eonsteel_parser_t *eon, const struct type_desc *desc, unsigned char type) { int idx = eon->cache.ngases; dc_tankinfo_t tankinfo = DC_TANKINFO_METRIC; const char *name; if (idx >= MAXGASES) return 0; eon->cache.ngases = idx+1; name = lookup_enum(desc, type); if (!name) DEBUG(eon->base.context, "Unable to look up gas type %u in %s", type, desc->format); else if (!strcasecmp(name, "Diluent")) tankinfo |= DC_TANKINFO_CC_DILUENT; else if (!strcasecmp(name, "Oxygen")) tankinfo |= DC_TANKINFO_CC_O2; else if (!strcasecmp(name, "None")) tankinfo = DC_TANKVOLUME_NONE; else if (strcasecmp(name, "Primary")) DEBUG(eon->base.context, "Unknown gas type %u (%s)", type, name); eon->cache.tankinfo[idx] = tankinfo; eon->cache.initialized |= 1 << DC_FIELD_GASMIX_COUNT; eon->cache.initialized |= 1 << DC_FIELD_TANK_COUNT; free((void *)name); return 0; } // "sml.DeviceLog.Header.Diving.Gases.Gas.Oxygen" // O2 percentage as a byte static int add_gas_o2(suunto_eonsteel_parser_t *eon, unsigned char o2) { int idx = eon->cache.ngases-1; if (idx >= 0) eon->cache.gasmix[idx].oxygen = o2 / 100.0; eon->cache.initialized |= 1 << DC_FIELD_GASMIX; return 0; } // "sml.DeviceLog.Header.Diving.Gases.Gas.Helium" // He percentage as a byte static int add_gas_he(suunto_eonsteel_parser_t *eon, unsigned char he) { int idx = eon->cache.ngases-1; if (idx >= 0) eon->cache.gasmix[idx].helium = he / 100.0; eon->cache.initialized |= 1 << DC_FIELD_GASMIX; return 0; } static int add_gas_size(suunto_eonsteel_parser_t *eon, float l) { int idx = eon->cache.ngases-1; if (idx >= 0) eon->cache.tanksize[idx] = l; eon->cache.initialized |= 1 << DC_FIELD_TANK; return 0; } static int add_gas_workpressure(suunto_eonsteel_parser_t *eon, float wp) { int idx = eon->cache.ngases-1; if (idx >= 0) eon->cache.tankworkingpressure[idx] = wp; return 0; } static int add_string(suunto_eonsteel_parser_t *eon, const char *desc, const char *value) { int i; eon->cache.initialized |= 1 << DC_FIELD_STRING; for (i = 0; i < MAXSTRINGS; i++) { dc_field_string_t *str = eon->cache.strings+i; if (str->desc) continue; str->desc = desc; str->value = strdup(value); break; } return 0; } static int add_string_fmt(suunto_eonsteel_parser_t *eon, const char *desc, const char *fmt, ...) { char buffer[256]; va_list ap; /* * We ignore the return value from vsnprintf, and we * always NUL-terminate the destination buffer ourselves. * * That way we don't have to worry about random bad legacy * implementations. */ va_start(ap, fmt); buffer[sizeof(buffer)-1] = 0; (void) vsnprintf(buffer, sizeof(buffer)-1, fmt, ap); va_end(ap); return add_string(eon, desc, buffer); } static float get_le32_float(const unsigned char *src) { union { unsigned int val; float result; } u; u.val = array_uint32_le(src); return u.result; } // "Device" fields are all utf8: // Info.BatteryAtEnd // Info.BatteryAtStart // Info.BSL // Info.HW // Info.SW // Name // SerialNumber static int traverse_device_fields(suunto_eonsteel_parser_t *eon, const struct type_desc *desc, const unsigned char *data, int len) { const char *name = desc->desc + strlen("sml.DeviceLog.Device."); if (!strcmp(name, "SerialNumber")) return add_string(eon, "Serial", data); if (!strcmp(name, "Info.HW")) return add_string(eon, "HW Version", data); if (!strcmp(name, "Info.SW")) return add_string(eon, "FW Version", data); if (!strcmp(name, "Info.BatteryAtStart")) return add_string(eon, "Battery at start", data); if (!strcmp(name, "Info.BatteryAtEnd")) return add_string(eon, "Battery at end", data); return 0; } // "sml.DeviceLog.Header.Diving.Gases" // // +Gas.State (enum:0=Off,1=Primary,3=Diluent,4=Oxygen) // .Gas.Oxygen (uint8,precision=2) // .Gas.Helium (uint8,precision=2) // .Gas.PO2 (uint32) // .Gas.TransmitterID (utf8) // .Gas.TankSize (float32,precision=5) // .Gas.TankFillPressure (float32,precision=0) // .Gas.StartPressure (float32,precision=0) // .Gas.EndPressure (float32,precision=0) // .Gas.TransmitterStartBatteryCharge (int8,precision=2) // .Gas.TransmitterEndBatteryCharge (int8,precision=2) static int traverse_gas_fields(suunto_eonsteel_parser_t *eon, const struct type_desc *desc, const unsigned char *data, int len) { const char *name = desc->desc + strlen("sml.DeviceLog.Header.Diving.Gases"); if (!strcmp(name, "+Gas.State")) return add_gas_type(eon, desc, data[0]); if (!strcmp(name, ".Gas.Oxygen")) return add_gas_o2(eon, data[0]); if (!strcmp(name, ".Gas.Helium")) return add_gas_he(eon, data[0]); if (!strcmp(name, ".Gas.TransmitterID")) return add_string(eon, "Transmitter ID", data); if (!strcmp(name, ".Gas.TankSize")) return add_gas_size(eon, get_le32_float(data)); if (!strcmp(name, ".Gas.TankFillPressure")) return add_gas_workpressure(eon, get_le32_float(data)); // There is a bug with older transmitters, where the transmitter // battery charge returns zero. Rather than returning that bogus // data, just don't return any battery charge information at all. // // Make sure to add all non-battery-charge field checks above this // test, so that it doesn't trigger for anything else. if (!data[0]) return 0; if (!strcmp(name, ".Gas.TransmitterStartBatteryCharge")) return add_string_fmt(eon, "Transmitter Battery at start", "%d %%", data[0]); if (!strcmp(name, ".Gas.TransmitterEndBatteryCharge")) return add_string_fmt(eon, "Transmitter Battery at end", "%d %%", data[0]); return 0; } // "sml.DeviceLog.Header.Diving." // // SurfaceTime (uint32) // NumberInSeries (uint32) // Algorithm (utf8) // SurfacePressure (uint32) // Conservatism (int8) // Altitude (uint16) // AlgorithmTransitionDepth (uint8) // DaysInSeries (uint32) // PreviousDiveDepth (float32,precision=2) // LowSetPoint (uint32) // HighSetPoint (uint32) // SwitchHighSetPoint.Enabled (bool) // SwitchHighSetPoint.Depth (float32,precision=1) // SwitchLowSetPoint.Enabled (bool) // SwitchLowSetPoint.Depth (float32,precision=1) // StartTissue.CNS (float32,precision=3) // StartTissue.OTU (float32) // StartTissue.OLF (float32,precision=3) // StartTissue.Nitrogen+Pressure (uint32) // StartTissue.Helium+Pressure (uint32) // StartTissue.RgbmNitrogen (float32,precision=3) // StartTissue.RgbmHelium (float32,precision=3) // DiveMode (utf8) // AlgorithmBottomTime (uint32) // AlgorithmAscentTime (uint32) // AlgorithmBottomMixture.Oxygen (uint8,precision=2) // AlgorithmBottomMixture.Helium (uint8,precision=2) // DesaturationTime (uint32) // EndTissue.CNS (float32,precision=3) // EndTissue.OTU (float32) // EndTissue.OLF (float32,precision=3) // EndTissue.Nitrogen+Pressure (uint32) // EndTissue.Helium+Pressure (uint32) // EndTissue.RgbmNitrogen (float32,precision=3) // EndTissue.RgbmHelium (float32,precision=3) static int traverse_diving_fields(suunto_eonsteel_parser_t *eon, const struct type_desc *desc, const unsigned char *data, int len) { const char *name = desc->desc + strlen("sml.DeviceLog.Header.Diving."); if (!strncmp(name, "Gases", 5)) return traverse_gas_fields(eon, desc, data, len); if (!strcmp(name, "SurfacePressure")) { unsigned int pressure = array_uint32_le(data); // in SI units - Pascal eon->cache.surface_pressure = pressure / 100000.0; // bar eon->cache.initialized |= 1 << DC_FIELD_ATMOSPHERIC; return 0; } if (!strcmp(name, "Algorithm")) return add_string(eon, "Deco algorithm", data); if (!strcmp(name, "DiveMode")) { if (!strncmp((const char *)data, "CCR", 3)) { eon->cache.divemode = DC_DIVEMODE_CCR; eon->cache.initialized |= 1 << DC_FIELD_DIVEMODE; } return add_string(eon, "Dive Mode", data); } /* Signed byte of conservatism (-2 .. +2) */ if (!strcmp(name, "Conservatism")) { int val = *(signed char *)data; return add_string_fmt(eon, "Personal Adjustment", "P%d", val); } if (!strcmp(name, "LowSetPoint")) { unsigned int pressure = array_uint32_le(data); // in SI units - Pascal eon->cache.lowsetpoint = pressure / 100000.0; // bar return 0; } if (!strcmp(name, "HighSetPoint")) { unsigned int pressure = array_uint32_le(data); // in SI units - Pascal eon->cache.highsetpoint = pressure / 100000.0; // bar return 0; } // Time recoded in seconds. // Let's just agree to ignore seconds if (!strcmp(name, "DesaturationTime")) { unsigned int time = array_uint32_le(data) / 60; return add_string_fmt(eon, "Desaturation Time", "%d:%02d", time / 60, time % 60); } if (!strcmp(name, "SurfaceTime")) { unsigned int time = array_uint32_le(data) / 60; return add_string_fmt(eon, "Surface Time", "%d:%02d", time / 60, time % 60); } return 0; } // "Header" fields are: // Activity (utf8) // DateTime (utf8) // Depth.Avg (float32,precision=2) // Depth.Max (float32,precision=2) // Diving.* // Duration (uint32) // PauseDuration (uint32) // SampleInterval (uint8) static int traverse_header_fields(suunto_eonsteel_parser_t *eon, const struct type_desc *desc, const unsigned char *data, int len) { const char *name = desc->desc + strlen("sml.DeviceLog.Header."); if (!strncmp(name, "Diving.", 7)) return traverse_diving_fields(eon, desc, data, len); if (!strcmp(name, "Depth.Max")) { double d = get_le32_float(data); if (d > eon->cache.maxdepth) eon->cache.maxdepth = d; return 0; } if (!strcmp(name, "DateTime")) return add_string(eon, "Dive ID", data); return 0; } static int traverse_dynamic_fields(suunto_eonsteel_parser_t *eon, const struct type_desc *desc, const unsigned char *data, int len) { const char *name = desc->desc; if (!strncmp(name, "sml.", 4)) { name += 4; if (!strncmp(name, "DeviceLog.", 10)) { name += 10; if (!strncmp(name, "Device.", 7)) return traverse_device_fields(eon, desc, data, len); if (!strncmp(name, "Header.", 7)) { return traverse_header_fields(eon, desc, data, len); } } } return 0; } /* * This is a simplified sample parser that only parses the depth and time * samples. It also depends on the GRP entries always starting with time/depth, * and just stops on anything else. */ static int traverse_sample_fields(suunto_eonsteel_parser_t *eon, const struct type_desc *desc, const unsigned char *data, int len) { int i; for (i = 0; i < EON_MAX_GROUP; i++) { enum eon_sample type = desc->type[i]; switch (type) { case ES_dtime: add_time_field(eon, array_uint16_le(data)); data += 2; continue; case ES_depth: set_depth_field(eon, array_uint16_le(data)); data += 2; continue; default: break; } break; } return 0; } static int traverse_fields(unsigned short type, const struct type_desc *desc, const unsigned char *data, int len, void *user) { suunto_eonsteel_parser_t *eon = (suunto_eonsteel_parser_t *) user; // Sample type? Do basic maxdepth and time parsing if (desc->type[0]) traverse_sample_fields(eon, desc, data, len); else traverse_dynamic_fields(eon, desc, data, len); return 0; } static void initialize_field_caches(suunto_eonsteel_parser_t *eon) { memset(&eon->cache, 0, sizeof(eon->cache)); eon->cache.initialized = 1 << DC_FIELD_DIVETIME; traverse_data(eon, traverse_fields, eon); // The internal time fields are in ms and have to be added up // like that. At the end, we translate it back to seconds. eon->cache.divetime /= 1000; } static void show_descriptor(suunto_eonsteel_parser_t *eon, int nr, struct type_desc *desc) { int i; if (!desc->desc) return; DEBUG(eon->base.context, "Descriptor %d: '%s', size %d bytes", nr, desc->desc, desc->size); if (desc->format) DEBUG(eon->base.context, " format '%s'", desc->format); if (desc->mod) DEBUG(eon->base.context, " mod '%s'", desc->mod); for (i = 0; i < EON_MAX_GROUP; i++) { enum eon_sample type = desc->type[i]; if (!type) continue; DEBUG(eon->base.context, " %d: %d (%s)", i, type, desc_type_name(type)); } } static void show_all_descriptors(suunto_eonsteel_parser_t *eon) { for (unsigned int i = 0; i < MAXTYPE; ++i) show_descriptor(eon, i, eon->type_desc+i); } static dc_status_t suunto_eonsteel_parser_set_data(dc_parser_t *parser, const unsigned char *data, unsigned int size) { suunto_eonsteel_parser_t *eon = (suunto_eonsteel_parser_t *) parser; desc_free(eon->type_desc, MAXTYPE); memset(eon->type_desc, 0, sizeof(eon->type_desc)); initialize_field_caches(eon); show_all_descriptors(eon); return DC_STATUS_SUCCESS; } static dc_status_t suunto_eonsteel_parser_destroy(dc_parser_t *parser) { suunto_eonsteel_parser_t *eon = (suunto_eonsteel_parser_t *) parser; desc_free(eon->type_desc, MAXTYPE); return DC_STATUS_SUCCESS; } static const dc_parser_vtable_t suunto_eonsteel_parser_vtable = { sizeof(suunto_eonsteel_parser_t), DC_FAMILY_SUUNTO_EONSTEEL, suunto_eonsteel_parser_set_data, /* set_data */ suunto_eonsteel_parser_get_datetime, /* datetime */ suunto_eonsteel_parser_get_field, /* fields */ suunto_eonsteel_parser_samples_foreach, /* samples_foreach */ suunto_eonsteel_parser_destroy /* destroy */ }; dc_status_t suunto_eonsteel_parser_create(dc_parser_t **out, dc_context_t *context, unsigned int model) { suunto_eonsteel_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; parser = (suunto_eonsteel_parser_t *) dc_parser_allocate (context, &suunto_eonsteel_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } memset(&parser->type_desc, 0, sizeof(parser->type_desc)); memset(&parser->cache, 0, sizeof(parser->cache)); *out = (dc_parser_t *) parser; return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/suunto_eonsteel_parser.c
/* * libdivecomputer * * Copyright (C) 2014 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcmp, memcpy #include <stdlib.h> // malloc, free #include "citizen_aqualand.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "checksum.h" #include "ringbuffer.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &citizen_aqualand_device_vtable) typedef struct citizen_aqualand_device_t { dc_device_t base; dc_iostream_t *iostream; unsigned char fingerprint[8]; } citizen_aqualand_device_t; static dc_status_t citizen_aqualand_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t citizen_aqualand_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t citizen_aqualand_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t citizen_aqualand_device_close (dc_device_t *abstract); static const dc_device_vtable_t citizen_aqualand_device_vtable = { sizeof(citizen_aqualand_device_t), DC_FAMILY_CITIZEN_AQUALAND, citizen_aqualand_device_set_fingerprint, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ citizen_aqualand_device_dump, /* dump */ citizen_aqualand_device_foreach, /* foreach */ NULL, /* timesync */ citizen_aqualand_device_close /* close */ }; dc_status_t citizen_aqualand_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; citizen_aqualand_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (citizen_aqualand_device_t *) dc_device_allocate (context, &citizen_aqualand_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; memset (device->fingerprint, 0, sizeof (device->fingerprint)); // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (4800 8N1). status = dc_iostream_configure (device->iostream, 4800, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (1000ms). status = dc_iostream_set_timeout (device->iostream, 1000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Make sure everything is in a sane state. dc_iostream_sleep (device->iostream, 300); dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); *out = (dc_device_t *) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t citizen_aqualand_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; citizen_aqualand_device_t *device = (citizen_aqualand_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t citizen_aqualand_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { citizen_aqualand_device_t *device = (citizen_aqualand_device_t *) abstract; if (size && size != sizeof (device->fingerprint)) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, sizeof (device->fingerprint)); else memset (device->fingerprint, 0, sizeof (device->fingerprint)); return DC_STATUS_SUCCESS; } static dc_status_t citizen_aqualand_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { dc_status_t status = DC_STATUS_SUCCESS; citizen_aqualand_device_t *device = (citizen_aqualand_device_t *) abstract; status = dc_iostream_set_dtr (device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to set the DTR line."); return status; } // Send the init byte. const unsigned char init[] = {0x7F}; status = dc_iostream_write (device->iostream, init, sizeof (init), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } dc_iostream_sleep(device->iostream, 1200); // Send the command. const unsigned char command[] = {0xFF}; status = dc_iostream_write (device->iostream, command, sizeof (command), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } while (1) { // Receive the response packet. unsigned char answer[32] = {0}; status = dc_iostream_read (device->iostream, answer, sizeof (answer), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } if (!dc_buffer_append(buffer, answer, sizeof (answer))) { ERROR (abstract->context, "Insufficient buffer space available."); return status; } // Send the command. status = dc_iostream_write (device->iostream, command, sizeof (command), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } if (answer[sizeof(answer) - 1] == 0xFF) break; } status = dc_iostream_set_dtr (device->iostream, 0); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to clear the DTR line."); return status; } return DC_STATUS_SUCCESS; } static dc_status_t citizen_aqualand_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { citizen_aqualand_device_t *device = (citizen_aqualand_device_t *) abstract; dc_buffer_t *buffer = dc_buffer_new (0); if (buffer == NULL) return DC_STATUS_NOMEMORY; dc_status_t rc = citizen_aqualand_device_dump (abstract, buffer); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } unsigned char *data = dc_buffer_get_data (buffer); unsigned int size = dc_buffer_get_size (buffer); if (callback && memcmp (data + 0x05, device->fingerprint, sizeof (device->fingerprint)) != 0) { callback (data, size, data + 0x05, sizeof (device->fingerprint), userdata); } dc_buffer_free (buffer); return rc; }
libdc-for-dirk-Subsurface-branch
src/citizen_aqualand.c
/* This is an implementation of the AES128 algorithm, specifically ECB and CBC mode. The implementation is verified against the test vectors in: National Institute of Standards and Technology Special Publication 800-38A 2001 ED ECB-AES128 ---------- plain-text: 6bc1bee22e409f96e93d7e117393172a ae2d8a571e03ac9c9eb76fac45af8e51 30c81c46a35ce411e5fbc1191a0a52ef f69f2445df4f9b17ad2b417be66c3710 key: 2b7e151628aed2a6abf7158809cf4f3c resulting cipher 3ad77bb40d7a3660a89ecaf32466ef97 f5d3d58503b9699de785895a96fdbaaf 43b1cd7f598ece23881b00e3ed030688 7b0c785e27e8ad3f8223207104725dd4 NOTE: String length must be evenly divisible by 16byte (str_len % 16 == 0) You should pad the end of the string with zeros if this is not the case. */ /*****************************************************************************/ /* Includes: */ /*****************************************************************************/ #include <string.h> // CBC mode, for memset #include "aes.h" /*****************************************************************************/ /* Defines: */ /*****************************************************************************/ // The number of columns comprising a state in AES. This is a constant in AES. Value=4 #define Nb 4 // The number of 32 bit words in a key. #define Nk 4 // Key length in bytes [128 bit] #define KEYLEN 16 // The number of rounds in AES Cipher. #define Nr 10 // jcallan@github points out that declaring Multiply as a function // reduces code size considerably with the Keil ARM compiler. // See this link for more information: https://github.com/kokke/tiny-AES128-C/pull/3 #ifndef MULTIPLY_AS_A_FUNCTION #define MULTIPLY_AS_A_FUNCTION 0 #endif /*****************************************************************************/ /* Private variables: */ /*****************************************************************************/ // state - array holding the intermediate results during decryption. typedef uint8_t state_t[4][4]; typedef struct aes_state_t { state_t* state; // The array that stores the round keys. uint8_t RoundKey[176]; // The Key input to the AES Program const uint8_t* Key; #if defined(CBC) && CBC // Initial Vector used only for CBC mode uint8_t* Iv; #endif } aes_state_t; // The lookup-tables are marked const so they can be placed in read-only storage instead of RAM // The numbers below can be computed dynamically trading ROM for RAM - // This can be useful in (embedded) bootloader applications, where ROM is often limited. static const uint8_t sbox[256] = { //0 1 2 3 4 5 6 7 8 9 A B C D E F 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 }; static const uint8_t rsbox[256] = { 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d }; // The round constant word array, Rcon[i], contains the values given by // x to th e power (i-1) being powers of x (x is denoted as {02}) in the field GF(2^8) // Note that i starts at 1, not 0). static const uint8_t Rcon[255] = { 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb }; /*****************************************************************************/ /* Private functions: */ /*****************************************************************************/ static uint8_t getSBoxValue(uint8_t num) { return sbox[num]; } static uint8_t getSBoxInvert(uint8_t num) { return rsbox[num]; } // This function produces Nb(Nr+1) round keys. The round keys are used in each round to decrypt the states. static void KeyExpansion(aes_state_t *state) { uint32_t i, j, k; uint8_t tempa[4]; // Used for the column/row operations // The first round key is the key itself. for(i = 0; i < Nk; ++i) { state->RoundKey[(i * 4) + 0] = state->Key[(i * 4) + 0]; state->RoundKey[(i * 4) + 1] = state->Key[(i * 4) + 1]; state->RoundKey[(i * 4) + 2] = state->Key[(i * 4) + 2]; state->RoundKey[(i * 4) + 3] = state->Key[(i * 4) + 3]; } // All other round keys are found from the previous round keys. for(; (i < (Nb * (Nr + 1))); ++i) { for(j = 0; j < 4; ++j) { tempa[j]=state->RoundKey[(i-1) * 4 + j]; } if (i % Nk == 0) { // This function rotates the 4 bytes in a word to the left once. // [a0,a1,a2,a3] becomes [a1,a2,a3,a0] // Function RotWord() { k = tempa[0]; tempa[0] = tempa[1]; tempa[1] = tempa[2]; tempa[2] = tempa[3]; tempa[3] = k; } // SubWord() is a function that takes a four-byte input word and // applies the S-box to each of the four bytes to produce an output word. // Function Subword() { tempa[0] = getSBoxValue(tempa[0]); tempa[1] = getSBoxValue(tempa[1]); tempa[2] = getSBoxValue(tempa[2]); tempa[3] = getSBoxValue(tempa[3]); } tempa[0] = tempa[0] ^ Rcon[i/Nk]; } else if (Nk > 6 && i % Nk == 4) { // Function Subword() { tempa[0] = getSBoxValue(tempa[0]); tempa[1] = getSBoxValue(tempa[1]); tempa[2] = getSBoxValue(tempa[2]); tempa[3] = getSBoxValue(tempa[3]); } } state->RoundKey[i * 4 + 0] = state->RoundKey[(i - Nk) * 4 + 0] ^ tempa[0]; state->RoundKey[i * 4 + 1] = state->RoundKey[(i - Nk) * 4 + 1] ^ tempa[1]; state->RoundKey[i * 4 + 2] = state->RoundKey[(i - Nk) * 4 + 2] ^ tempa[2]; state->RoundKey[i * 4 + 3] = state->RoundKey[(i - Nk) * 4 + 3] ^ tempa[3]; } } // This function adds the round key to state. // The round key is added to the state by an XOR function. static void AddRoundKey(aes_state_t *state, uint8_t round) { uint8_t i,j; for(i=0;i<4;++i) { for(j = 0; j < 4; ++j) { (*state->state)[i][j] ^= state->RoundKey[round * Nb * 4 + i * Nb + j]; } } } // The SubBytes Function Substitutes the values in the // state matrix with values in an S-box. static void SubBytes(aes_state_t *state) { uint8_t i, j; for(i = 0; i < 4; ++i) { for(j = 0; j < 4; ++j) { (*state->state)[j][i] = getSBoxValue((*state->state)[j][i]); } } } // The ShiftRows() function shifts the rows in the state to the left. // Each row is shifted with different offset. // Offset = Row number. So the first row is not shifted. static void ShiftRows(aes_state_t *state) { uint8_t temp; // Rotate first row 1 columns to left temp = (*state->state)[0][1]; (*state->state)[0][1] = (*state->state)[1][1]; (*state->state)[1][1] = (*state->state)[2][1]; (*state->state)[2][1] = (*state->state)[3][1]; (*state->state)[3][1] = temp; // Rotate second row 2 columns to left temp = (*state->state)[0][2]; (*state->state)[0][2] = (*state->state)[2][2]; (*state->state)[2][2] = temp; temp = (*state->state)[1][2]; (*state->state)[1][2] = (*state->state)[3][2]; (*state->state)[3][2] = temp; // Rotate third row 3 columns to left temp = (*state->state)[0][3]; (*state->state)[0][3] = (*state->state)[3][3]; (*state->state)[3][3] = (*state->state)[2][3]; (*state->state)[2][3] = (*state->state)[1][3]; (*state->state)[1][3] = temp; } static uint8_t xtime(uint8_t x) { return ((x<<1) ^ (((x>>7) & 1) * 0x1b)); } // MixColumns function mixes the columns of the state matrix static void MixColumns(aes_state_t *state) { uint8_t i; uint8_t Tmp,Tm,t; for(i = 0; i < 4; ++i) { t = (*state->state)[i][0]; Tmp = (*state->state)[i][0] ^ (*state->state)[i][1] ^ (*state->state)[i][2] ^ (*state->state)[i][3] ; Tm = (*state->state)[i][0] ^ (*state->state)[i][1] ; Tm = xtime(Tm); (*state->state)[i][0] ^= Tm ^ Tmp ; Tm = (*state->state)[i][1] ^ (*state->state)[i][2] ; Tm = xtime(Tm); (*state->state)[i][1] ^= Tm ^ Tmp ; Tm = (*state->state)[i][2] ^ (*state->state)[i][3] ; Tm = xtime(Tm); (*state->state)[i][2] ^= Tm ^ Tmp ; Tm = (*state->state)[i][3] ^ t ; Tm = xtime(Tm); (*state->state)[i][3] ^= Tm ^ Tmp ; } } // Multiply is used to multiply numbers in the field GF(2^8) #if MULTIPLY_AS_A_FUNCTION static uint8_t Multiply(uint8_t x, uint8_t y) { return (((y & 1) * x) ^ ((y>>1 & 1) * xtime(x)) ^ ((y>>2 & 1) * xtime(xtime(x))) ^ ((y>>3 & 1) * xtime(xtime(xtime(x)))) ^ ((y>>4 & 1) * xtime(xtime(xtime(xtime(x)))))); } #else #define Multiply(x, y) \ ( ((y & 1) * x) ^ \ ((y>>1 & 1) * xtime(x)) ^ \ ((y>>2 & 1) * xtime(xtime(x))) ^ \ ((y>>3 & 1) * xtime(xtime(xtime(x)))) ^ \ ((y>>4 & 1) * xtime(xtime(xtime(xtime(x)))))) \ #endif // MixColumns function mixes the columns of the state matrix. // The method used to multiply may be difficult to understand for the inexperienced. // Please use the references to gain more information. static void InvMixColumns(aes_state_t *state) { int i; uint8_t a,b,c,d; for(i=0;i<4;++i) { a = (*state->state)[i][0]; b = (*state->state)[i][1]; c = (*state->state)[i][2]; d = (*state->state)[i][3]; (*state->state)[i][0] = Multiply(a, 0x0e) ^ Multiply(b, 0x0b) ^ Multiply(c, 0x0d) ^ Multiply(d, 0x09); (*state->state)[i][1] = Multiply(a, 0x09) ^ Multiply(b, 0x0e) ^ Multiply(c, 0x0b) ^ Multiply(d, 0x0d); (*state->state)[i][2] = Multiply(a, 0x0d) ^ Multiply(b, 0x09) ^ Multiply(c, 0x0e) ^ Multiply(d, 0x0b); (*state->state)[i][3] = Multiply(a, 0x0b) ^ Multiply(b, 0x0d) ^ Multiply(c, 0x09) ^ Multiply(d, 0x0e); } } // The SubBytes Function Substitutes the values in the // state matrix with values in an S-box. static void InvSubBytes(aes_state_t *state) { uint8_t i,j; for(i=0;i<4;++i) { for(j=0;j<4;++j) { (*state->state)[j][i] = getSBoxInvert((*state->state)[j][i]); } } } static void InvShiftRows(aes_state_t *state) { uint8_t temp; // Rotate first row 1 columns to right temp=(*state->state)[3][1]; (*state->state)[3][1]=(*state->state)[2][1]; (*state->state)[2][1]=(*state->state)[1][1]; (*state->state)[1][1]=(*state->state)[0][1]; (*state->state)[0][1]=temp; // Rotate second row 2 columns to right temp=(*state->state)[0][2]; (*state->state)[0][2]=(*state->state)[2][2]; (*state->state)[2][2]=temp; temp=(*state->state)[1][2]; (*state->state)[1][2]=(*state->state)[3][2]; (*state->state)[3][2]=temp; // Rotate third row 3 columns to right temp=(*state->state)[0][3]; (*state->state)[0][3]=(*state->state)[1][3]; (*state->state)[1][3]=(*state->state)[2][3]; (*state->state)[2][3]=(*state->state)[3][3]; (*state->state)[3][3]=temp; } // Cipher is the main function that encrypts the PlainText. static void Cipher(aes_state_t *state) { uint8_t round = 0; // Add the First round key to the state before starting the rounds. AddRoundKey(state, 0); // There will be Nr rounds. // The first Nr-1 rounds are identical. // These Nr-1 rounds are executed in the loop below. for(round = 1; round < Nr; ++round) { SubBytes(state); ShiftRows(state); MixColumns(state); AddRoundKey(state, round); } // The last round is given below. // The MixColumns function is not here in the last round. SubBytes(state); ShiftRows(state); AddRoundKey(state, Nr); } static void InvCipher(aes_state_t *state) { uint8_t round=0; // Add the First round key to the state before starting the rounds. AddRoundKey(state, Nr); // There will be Nr rounds. // The first Nr-1 rounds are identical. // These Nr-1 rounds are executed in the loop below. for(round=Nr-1;round>0;round--) { InvShiftRows(state); InvSubBytes(state); AddRoundKey(state, round); InvMixColumns(state); } // The last round is given below. // The MixColumns function is not here in the last round. InvShiftRows(state); InvSubBytes(state); AddRoundKey(state, 0); } static void BlockCopy(uint8_t* output, uint8_t* input) { uint8_t i; for (i=0;i<KEYLEN;++i) { output[i] = input[i]; } } /*****************************************************************************/ /* Public functions: */ /*****************************************************************************/ #if defined(ECB) && ECB void AES128_ECB_encrypt(uint8_t* input, const uint8_t* key, uint8_t* output) { aes_state_t state; // Copy input to output, and work in-memory on output BlockCopy(output, input); state.state = (state_t*)output; state.Key = key; KeyExpansion(&state); // The next function call encrypts the PlainText with the Key using AES algorithm. Cipher(&state); } void AES128_ECB_decrypt(uint8_t* input, const uint8_t* key, uint8_t *output) { aes_state_t state; // Copy input to output, and work in-memory on output BlockCopy(output, input); state.state = (state_t*)output; // The KeyExpansion routine must be called before encryption. state.Key = key; KeyExpansion(&state); InvCipher(&state); } #endif // #if defined(ECB) && ECB #if defined(CBC) && CBC static void XorWithIv(aes_state_t *state, uint8_t* buf) { uint8_t i; for(i = 0; i < KEYLEN; ++i) { buf[i] ^= state->Iv[i]; } } void AES128_CBC_encrypt_buffer(uint8_t* output, uint8_t* input, uint32_t length, const uint8_t* key, const uint8_t* iv) { intptr_t i; uint8_t remainders = length % KEYLEN; /* Remaining bytes in the last non-full block */ aes_state_t state; BlockCopy(output, input); state.state = (state_t*)output; // Skip the key expansion if key is passed as 0 if(0 != key) { state.Key = key; KeyExpansion(&state); } if(iv != 0) { state.Iv = (uint8_t*)iv; } for(i = 0; i < length; i += KEYLEN) { XorWithIv(&state, input); BlockCopy(output, input); state.state = (state_t*)output; Cipher(&state); state.Iv = output; input += KEYLEN; output += KEYLEN; } if(remainders) { BlockCopy(output, input); memset(output + remainders, 0, KEYLEN - remainders); /* add 0-padding */ state.state = (state_t*)output; Cipher(&state); } } void AES128_CBC_decrypt_buffer(uint8_t* output, uint8_t* input, uint32_t length, const uint8_t* key, const uint8_t* iv) { intptr_t i; uint8_t remainders = length % KEYLEN; /* Remaining bytes in the last non-full block */ aes_state_t state; BlockCopy(output, input); state.state = (state_t*)output; // Skip the key expansion if key is passed as 0 if(0 != key) { state.Key = key; KeyExpansion(&state); } // If iv is passed as 0, we continue to encrypt without re-setting the Iv if(iv != 0) { state.Iv = (uint8_t*)iv; } for(i = 0; i < length; i += KEYLEN) { BlockCopy(output, input); state.state = (state_t*)output; InvCipher(&state); XorWithIv(&state, output); state.Iv = input; input += KEYLEN; output += KEYLEN; } if(remainders) { BlockCopy(output, input); memset(output+remainders, 0, KEYLEN - remainders); /* add 0-padding */ state.state = (state_t*)output; InvCipher(&state); } } #endif // #if defined(CBC) && CBC
libdc-for-dirk-Subsurface-branch
src/aes.c
/* * libdivecomputer * * Copyright (C) 2009 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcpy, memcmp #include <stdlib.h> // malloc, free #include <assert.h> // assert #include "mares_puck.h" #include "mares_common.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "checksum.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &mares_puck_device_vtable) #define NEMOWIDE 1 #define NEMOAIR 4 #define PUCK 7 #define PUCKAIR 19 typedef struct mares_puck_device_t { mares_common_device_t base; const mares_common_layout_t *layout; unsigned char fingerprint[5]; } mares_puck_device_t; static dc_status_t mares_puck_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t mares_puck_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t mares_puck_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t mares_puck_device_close (dc_device_t *abstract); static const dc_device_vtable_t mares_puck_device_vtable = { sizeof(mares_puck_device_t), DC_FAMILY_MARES_PUCK, mares_puck_device_set_fingerprint, /* set_fingerprint */ mares_common_device_read, /* read */ NULL, /* write */ mares_puck_device_dump, /* dump */ mares_puck_device_foreach, /* foreach */ NULL, /* timesync */ mares_puck_device_close /* close */ }; static const mares_common_layout_t mares_puck_layout = { 0x4000, /* memsize */ 0x0070, /* rb_profile_begin */ 0x4000, /* rb_profile_end */ 0x4000, /* rb_freedives_begin */ 0x4000 /* rb_freedives_end */ }; static const mares_common_layout_t mares_nemoair_layout = { 0x8000, /* memsize */ 0x0070, /* rb_profile_begin */ 0x8000, /* rb_profile_end */ 0x8000, /* rb_freedives_begin */ 0x8000 /* rb_freedives_end */ }; static const mares_common_layout_t mares_nemowide_layout = { 0x4000, /* memsize */ 0x0070, /* rb_profile_begin */ 0x3400, /* rb_profile_end */ 0x3400, /* rb_freedives_begin */ 0x4000 /* rb_freedives_end */ }; dc_status_t mares_puck_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; mares_puck_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (mares_puck_device_t *) dc_device_allocate (context, &mares_puck_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Initialize the base class. mares_common_device_init (&device->base); // Set the default values. device->layout = NULL; memset (device->fingerprint, 0, sizeof (device->fingerprint)); // Open the device. status = dc_serial_open (&device->base.iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (38400 8N1). status = dc_iostream_configure (device->base.iostream, 38400, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (1000 ms). status = dc_iostream_set_timeout (device->base.iostream, 1000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Clear the DTR line. status = dc_iostream_set_dtr (device->base.iostream, 0); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to clear the DTR line."); goto error_close; } // Clear the RTS line. status = dc_iostream_set_rts (device->base.iostream, 0); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to clear the RTS line."); goto error_close; } // Make sure everything is in a sane state. dc_iostream_purge (device->base.iostream, DC_DIRECTION_ALL); // Identify the model number. unsigned char header[PACKETSIZE] = {0}; status = mares_common_device_read ((dc_device_t *) device, 0, header, sizeof (header)); if (status != DC_STATUS_SUCCESS) { goto error_close; } // Override the base class values. switch (header[1]) { case NEMOWIDE: device->layout = &mares_nemowide_layout; break; case NEMOAIR: case PUCKAIR: device->layout = &mares_nemoair_layout; break; case PUCK: device->layout = &mares_puck_layout; break; default: // Unknown, try puck device->layout = &mares_puck_layout; break; } *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->base.iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t mares_puck_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; mares_puck_device_t *device = (mares_puck_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Close the device. rc = dc_iostream_close (device->base.iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t mares_puck_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { mares_puck_device_t *device = (mares_puck_device_t *) abstract; if (size && size != sizeof (device->fingerprint)) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, sizeof (device->fingerprint)); else memset (device->fingerprint, 0, sizeof (device->fingerprint)); return DC_STATUS_SUCCESS; } static dc_status_t mares_puck_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { mares_puck_device_t *device = (mares_puck_device_t *) abstract; assert (device->layout != NULL); // Allocate the required amount of memory. if (!dc_buffer_resize (buffer, device->layout->memsize)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } return device_dump_read (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), PACKETSIZE); } static dc_status_t mares_puck_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { mares_puck_device_t *device = (mares_puck_device_t *) abstract; assert (device->layout != NULL); dc_buffer_t *buffer = dc_buffer_new (device->layout->memsize); if (buffer == NULL) return DC_STATUS_NOMEMORY; dc_status_t rc = mares_puck_device_dump (abstract, buffer); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } // Emit a device info event. unsigned char *data = dc_buffer_get_data (buffer); dc_event_devinfo_t devinfo; devinfo.model = data[1]; devinfo.firmware = 0; devinfo.serial = array_uint16_be (data + 8); device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); rc = mares_common_extract_dives (abstract->context, device->layout, device->fingerprint, data, callback, userdata); dc_buffer_free (buffer); return rc; }
libdc-for-dirk-Subsurface-branch
src/mares_puck.c
/* * libdivecomputer * * Copyright (C) 2015 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <assert.h> #include "common-private.h" void dc_status_set_error (dc_status_t *status, dc_status_t error) { assert (status != NULL); if (*status == DC_STATUS_SUCCESS) *status = error; }
libdc-for-dirk-Subsurface-branch
src/common.c
/* * libdivecomputer * * Copyright (C) 2009 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> // malloc, realloc, free #include <string.h> // memcpy, memmove #include <libdivecomputer/buffer.h> struct dc_buffer_t { unsigned char *data; size_t capacity, offset, size; }; dc_buffer_t * dc_buffer_new (size_t capacity) { dc_buffer_t *buffer = (dc_buffer_t *) malloc (sizeof (dc_buffer_t)); if (buffer == NULL) return NULL; if (capacity) { buffer->data = (unsigned char *) malloc (capacity); if (buffer->data == NULL) { free (buffer); return NULL; } } else { buffer->data = NULL; } buffer->capacity = capacity; buffer->offset = 0; buffer->size = 0; return buffer; } void dc_buffer_free (dc_buffer_t *buffer) { if (buffer == NULL) return; if (buffer->data) free (buffer->data); free (buffer); } int dc_buffer_clear (dc_buffer_t *buffer) { if (buffer == NULL) return 0; buffer->offset = 0; buffer->size = 0; return 1; } static size_t dc_buffer_expand_calc (dc_buffer_t *buffer, size_t n) { size_t oldsize = buffer->capacity; size_t newsize = (oldsize ? oldsize : n); while (newsize < n) newsize *= 2; return newsize; } static int dc_buffer_expand_append (dc_buffer_t *buffer, size_t n) { if (n > buffer->capacity - buffer->offset) { if (n > buffer->capacity) { size_t capacity = dc_buffer_expand_calc (buffer, n); unsigned char *data = (unsigned char *) malloc (capacity); if (data == NULL) return 0; if (buffer->size) memcpy (data, buffer->data + buffer->offset, buffer->size); free (buffer->data); buffer->data = data; buffer->capacity = capacity; buffer->offset = 0; } else { if (buffer->size) memmove (buffer->data, buffer->data + buffer->offset, buffer->size); buffer->offset = 0; } } return 1; } static int dc_buffer_expand_prepend (dc_buffer_t *buffer, size_t n) { size_t available = buffer->capacity - buffer->size; if (n > buffer->offset + buffer->size) { if (n > buffer->capacity) { size_t capacity = dc_buffer_expand_calc (buffer, n); unsigned char *data = (unsigned char *) malloc (capacity); if (data == NULL) return 0; if (buffer->size) memcpy (data + capacity - buffer->size, buffer->data + buffer->offset, buffer->size); free (buffer->data); buffer->data = data; buffer->capacity = capacity; buffer->offset = capacity - buffer->size; } else { if (buffer->size) memmove (buffer->data + available, buffer->data + buffer->offset, buffer->size); buffer->offset = available; } } return 1; } int dc_buffer_reserve (dc_buffer_t *buffer, size_t capacity) { if (buffer == NULL) return 0; if (capacity <= buffer->capacity) return 1; unsigned char *data = (unsigned char *) realloc (buffer->data, capacity); if (data == NULL) return 0; buffer->data = data; buffer->capacity = capacity; return 1; } int dc_buffer_resize (dc_buffer_t *buffer, size_t size) { if (buffer == NULL) return 0; if (!dc_buffer_expand_append (buffer, size)) return 0; if (size > buffer->size) memset (buffer->data + buffer->offset + buffer->size, 0, size - buffer->size); buffer->size = size; return 1; } int dc_buffer_append (dc_buffer_t *buffer, const unsigned char data[], size_t size) { if (buffer == NULL) return 0; if (!dc_buffer_expand_append (buffer, buffer->size + size)) return 0; if (size) memcpy (buffer->data + buffer->offset + buffer->size, data, size); buffer->size += size; return 1; } int dc_buffer_prepend (dc_buffer_t *buffer, const unsigned char data[], size_t size) { if (buffer == NULL) return 0; if (!dc_buffer_expand_prepend (buffer, buffer->size + size)) return 0; if (size) memcpy (buffer->data + buffer->offset - size, data, size); buffer->size += size; buffer->offset -= size; return 1; } int dc_buffer_slice (dc_buffer_t *buffer, size_t offset, size_t size) { if (buffer == NULL) return 0; if (offset + size > buffer->size) return 0; buffer->offset += offset; buffer->size = size; return 1; } size_t dc_buffer_get_size (dc_buffer_t *buffer) { if (buffer == NULL) return 0; return buffer->size; } unsigned char * dc_buffer_get_data (dc_buffer_t *buffer) { if (buffer == NULL) return NULL; return buffer->size ? buffer->data + buffer->offset : NULL; }
libdc-for-dirk-Subsurface-branch
src/buffer.c
/* * libdivecomputer * * Copyright (C) 2018 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #ifdef _WIN32 #define NOGDI #include <windows.h> #else #include <time.h> #include <sys/time.h> #ifdef HAVE_MACH_MACH_TIME_H #include <mach/mach_time.h> #endif #endif #include "timer.h" struct dc_timer_t { #if defined (_WIN32) LARGE_INTEGER timestamp; LARGE_INTEGER frequency; #elif defined (HAVE_CLOCK_GETTIME) struct timespec timestamp; #elif defined (HAVE_MACH_ABSOLUTE_TIME) uint64_t timestamp; mach_timebase_info_data_t info; #else struct timeval timestamp; #endif }; dc_status_t dc_timer_new (dc_timer_t **out) { dc_timer_t *timer = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; timer = (dc_timer_t *) malloc (sizeof (dc_timer_t)); if (timer == NULL) { return DC_STATUS_NOMEMORY; } #if defined (_WIN32) if (!QueryPerformanceFrequency(&timer->frequency) || !QueryPerformanceCounter(&timer->timestamp)) { free(timer); return DC_STATUS_IO; } #elif defined (HAVE_CLOCK_GETTIME) if (clock_gettime(CLOCK_MONOTONIC, &timer->timestamp) != 0) { free(timer); return DC_STATUS_IO; } #elif defined (HAVE_MACH_ABSOLUTE_TIME) if (mach_timebase_info(&timer->info) != KERN_SUCCESS) { free(timer); return DC_STATUS_IO; } timer->timestamp = mach_absolute_time(); #else if (gettimeofday (&timer->timestamp, NULL) != 0) { free(timer); return DC_STATUS_IO; } #endif *out = timer; return DC_STATUS_SUCCESS; } dc_status_t dc_timer_now (dc_timer_t *timer, dc_usecs_t *usecs) { dc_status_t status = DC_STATUS_SUCCESS; dc_usecs_t value = 0; if (timer == NULL) { status = DC_STATUS_INVALIDARGS; goto out; } #if defined (_WIN32) LARGE_INTEGER now; if (!QueryPerformanceCounter(&now)) { status = DC_STATUS_IO; goto out; } value = (now.QuadPart - timer->timestamp.QuadPart) * 1000000 / timer->frequency.QuadPart; #elif defined (HAVE_CLOCK_GETTIME) struct timespec now, delta; if (clock_gettime(CLOCK_MONOTONIC, &now) != 0) { status = DC_STATUS_IO; goto out; } if (now.tv_nsec < timer->timestamp.tv_nsec) { delta.tv_nsec = 1000000000 + now.tv_nsec - timer->timestamp.tv_nsec; delta.tv_sec = now.tv_sec - timer->timestamp.tv_sec - 1; } else { delta.tv_nsec = now.tv_nsec - timer->timestamp.tv_nsec; delta.tv_sec = now.tv_sec - timer->timestamp.tv_sec; } value = (dc_usecs_t) delta.tv_sec * 1000000 + delta.tv_nsec / 1000; #elif defined (HAVE_MACH_ABSOLUTE_TIME) uint64_t now = mach_absolute_time(); value = (now - timer->timestamp) * timer->info.numer / timer->info.denom; #else struct timeval now, delta; if (gettimeofday (&now, NULL) != 0) { status = DC_STATUS_IO; goto out; } timersub (&now, &timer->timestamp, &delta); value = (dc_usecs_t) delta.tv_sec * 1000000 + delta.tv_usec; #endif out: if (usecs) *usecs = value; return status; } dc_status_t dc_timer_free (dc_timer_t *timer) { free (timer); return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/timer.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcpy, memcmp #include <stdlib.h> // malloc, free #include "mares_nemo.h" #include "mares_common.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "checksum.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &mares_nemo_device_vtable) #ifdef PACKETSIZE #undef PACKETSIZE /* Override the common value. */ #endif #define MEMORYSIZE 0x4000 #define PACKETSIZE 0x20 #define NEMO 0 #define NEMOEXCEL 17 #define NEMOAPNEIST 18 typedef struct mares_nemo_device_t { dc_device_t base; dc_iostream_t *iostream; unsigned char fingerprint[5]; } mares_nemo_device_t; static dc_status_t mares_nemo_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t mares_nemo_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t mares_nemo_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t mares_nemo_device_close (dc_device_t *abstract); static const dc_device_vtable_t mares_nemo_device_vtable = { sizeof(mares_nemo_device_t), DC_FAMILY_MARES_NEMO, mares_nemo_device_set_fingerprint, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ mares_nemo_device_dump, /* dump */ mares_nemo_device_foreach, /* foreach */ NULL, /* timesync */ mares_nemo_device_close /* close */ }; static const mares_common_layout_t mares_nemo_layout = { MEMORYSIZE, /* memsize */ 0x0070, /* rb_profile_begin */ 0x3400, /* rb_profile_end */ 0x3400, /* rb_freedives_begin */ 0x4000 /* rb_freedives_end */ }; static const mares_common_layout_t mares_nemo_apneist_layout = { MEMORYSIZE, /* memsize */ 0x0070, /* rb_profile_begin */ 0x0800, /* rb_profile_end */ 0x0800, /* rb_freedives_begin */ 0x4000 /* rb_freedives_end */ }; dc_status_t mares_nemo_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; mares_nemo_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (mares_nemo_device_t *) dc_device_allocate (context, &mares_nemo_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; memset (device->fingerprint, 0, sizeof (device->fingerprint)); // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (9600 8N1). status = dc_iostream_configure (device->iostream, 9600, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (1000 ms). status = dc_iostream_set_timeout (device->iostream, 1000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Set the DTR line. status = dc_iostream_set_dtr (device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the DTR line."); goto error_close; } // Set the RTS line. status = dc_iostream_set_rts (device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the RTS line."); goto error_close; } // Make sure everything is in a sane state. dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t mares_nemo_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; mares_nemo_device_t *device = (mares_nemo_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t mares_nemo_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { mares_nemo_device_t *device = (mares_nemo_device_t *) abstract; if (size && size != sizeof (device->fingerprint)) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, sizeof (device->fingerprint)); else memset (device->fingerprint, 0, sizeof (device->fingerprint)); return DC_STATUS_SUCCESS; } static dc_status_t mares_nemo_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { dc_status_t status = DC_STATUS_SUCCESS; mares_nemo_device_t *device = (mares_nemo_device_t *) abstract; // Pre-allocate the required amount of memory. if (!dc_buffer_reserve (buffer, MEMORYSIZE)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = MEMORYSIZE + 20; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Wait until some data arrives. size_t available = 0; while (dc_iostream_get_available (device->iostream, &available) == DC_STATUS_SUCCESS && available == 0) { if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; device_event_emit (abstract, DC_EVENT_WAITING, NULL); dc_iostream_sleep (device->iostream, 100); } // Receive the header of the package. unsigned char header = 0x00; for (unsigned int i = 0; i < 20;) { status = dc_iostream_read (device->iostream, &header, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the header."); return status; } if (header == 0xEE) { i++; // Continue. } else { i = 0; // Reset. } } // Update and emit a progress event. progress.current += 20; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); unsigned int nbytes = 0; while (nbytes < MEMORYSIZE) { // Read the packet. unsigned char packet[(PACKETSIZE + 1) * 2] = {0}; status = dc_iostream_read (device->iostream, packet, sizeof (packet), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Verify the checksums of the packet. unsigned char crc1 = packet[PACKETSIZE]; unsigned char crc2 = packet[PACKETSIZE * 2 + 1]; unsigned char ccrc1 = checksum_add_uint8 (packet, PACKETSIZE, 0x00); unsigned char ccrc2 = checksum_add_uint8 (packet + PACKETSIZE + 1, PACKETSIZE, 0x00); if (crc1 == ccrc1 && crc2 == ccrc2) { // Both packets have a correct checksum. if (memcmp (packet, packet + PACKETSIZE + 1, PACKETSIZE) != 0) { ERROR (abstract->context, "Both packets are not equal."); return DC_STATUS_PROTOCOL; } dc_buffer_append (buffer, packet, PACKETSIZE); } else if (crc1 == ccrc1) { // Only the first packet has a correct checksum. WARNING (abstract->context, "Only the first packet has a correct checksum."); dc_buffer_append (buffer, packet, PACKETSIZE); } else if (crc2 == ccrc2) { // Only the second packet has a correct checksum. WARNING (abstract->context, "Only the second packet has a correct checksum."); dc_buffer_append (buffer, packet + PACKETSIZE + 1, PACKETSIZE); } else { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } // Update and emit a progress event. progress.current += PACKETSIZE; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); nbytes += PACKETSIZE; } return DC_STATUS_SUCCESS; } static dc_status_t mares_nemo_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { mares_nemo_device_t *device = (mares_nemo_device_t *) abstract; dc_buffer_t *buffer = dc_buffer_new (MEMORYSIZE); if (buffer == NULL) return DC_STATUS_NOMEMORY; dc_status_t rc = mares_nemo_device_dump (abstract, buffer); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } // Emit a device info event. unsigned char *data = dc_buffer_get_data (buffer); dc_event_devinfo_t devinfo; devinfo.model = data[1]; devinfo.firmware = 0; devinfo.serial = array_uint16_be (data + 8); device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); const mares_common_layout_t *layout = NULL; switch (data[1]) { case NEMO: case NEMOEXCEL: layout = &mares_nemo_layout; break; case NEMOAPNEIST: layout = &mares_nemo_apneist_layout; break; default: // Unknown, try nemo WARNING (abstract->context, "Unsupported model %02x detected!", data[1]); layout = &mares_nemo_layout; break; } rc = mares_common_extract_dives (abstract->context, layout, device->fingerprint, data, callback, userdata); dc_buffer_free (buffer); return rc; }
libdc-for-dirk-Subsurface-branch
src/mares_nemo.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <libdivecomputer/units.h> #include "suunto_solution.h" #include "context-private.h" #include "parser-private.h" #define ISINSTANCE(parser) dc_parser_isinstance((parser), &suunto_solution_parser_vtable) typedef struct suunto_solution_parser_t suunto_solution_parser_t; struct suunto_solution_parser_t { dc_parser_t base; // Cached fields. unsigned int cached; unsigned int divetime; unsigned int maxdepth; }; static dc_status_t suunto_solution_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t suunto_solution_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t suunto_solution_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t suunto_solution_parser_vtable = { sizeof(suunto_solution_parser_t), DC_FAMILY_SUUNTO_SOLUTION, suunto_solution_parser_set_data, /* set_data */ NULL, /* datetime */ suunto_solution_parser_get_field, /* fields */ suunto_solution_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; dc_status_t suunto_solution_parser_create (dc_parser_t **out, dc_context_t *context) { suunto_solution_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (suunto_solution_parser_t *) dc_parser_allocate (context, &suunto_solution_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. parser->cached = 0; parser->divetime = 0; parser->maxdepth = 0; *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; } static dc_status_t suunto_solution_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { suunto_solution_parser_t *parser = (suunto_solution_parser_t *) abstract; // Reset the cache. parser->cached = 0; parser->divetime = 0; parser->maxdepth = 0; return DC_STATUS_SUCCESS; } static dc_status_t suunto_solution_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { suunto_solution_parser_t *parser = (suunto_solution_parser_t *) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; if (size < 4) return DC_STATUS_DATAFORMAT; if (!parser->cached) { unsigned int nsamples = 0; unsigned int depth = 0, maxdepth = 0; unsigned int offset = 3; while (offset < size && data[offset] != 0x80) { unsigned char value = data[offset++]; if (value < 0x7e || value > 0x82) { depth += (signed char) value; if (value == 0x7D || value == 0x83) { if (offset + 1 > size) return DC_STATUS_DATAFORMAT; depth += (signed char) data[offset++]; } if (depth > maxdepth) maxdepth = depth; nsamples++; } } // Store the offset to the end marker. unsigned int marker = offset; if (marker + 1 >= size || data[marker] != 0x80) return DC_STATUS_DATAFORMAT; parser->cached = 1; parser->divetime = (nsamples * 3 + data[marker + 1]) * 60; parser->maxdepth = maxdepth; } dc_gasmix_t *gasmix = (dc_gasmix_t *) value; if (value) { switch (type) { case DC_FIELD_DIVETIME: *((unsigned int *) value) = parser->divetime; break; case DC_FIELD_MAXDEPTH: *((double *) value) = parser->maxdepth * FEET; break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = 1; break; case DC_FIELD_GASMIX: gasmix->helium = 0.0; gasmix->oxygen = 0.21; gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium; break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t suunto_solution_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { const unsigned char *data = abstract->data; unsigned int size = abstract->size; if (size < 4) return DC_STATUS_DATAFORMAT; unsigned int time = 0, depth = 0; unsigned int gasmix_previous = 0xFFFFFFFF; unsigned int gasmix = 0; unsigned int offset = 3; while (offset < size && data[offset] != 0x80) { dc_sample_value_t sample = {0}; unsigned char value = data[offset++]; if (value < 0x7e || value > 0x82) { // Time (minutes). time += 3 * 60; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Depth (ft). depth += (signed char) value; if (value == 0x7D || value == 0x83) { // A value of 0x7D (125) or 0x83 (-125) indicates a descent // or ascent greater than 124 feet. The remaining part of // the total delta value is stored in the next byte. if (offset + 1 > size) return DC_STATUS_DATAFORMAT; depth += (signed char) data[offset++]; } sample.depth = depth * FEET; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); // Gas change. if (gasmix != gasmix_previous) { sample.gasmix = gasmix; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); gasmix_previous = gasmix; } } else { // Event. sample.event.type = SAMPLE_EVENT_NONE; sample.event.time = 0; sample.event.flags = 0; sample.event.value = 0; switch (value) { case 0x7e: // Deco, ASC sample.event.type = SAMPLE_EVENT_DECOSTOP; break; case 0x7f: // Ceiling, ERR sample.event.type = SAMPLE_EVENT_CEILING; break; case 0x81: // Slow sample.event.type = SAMPLE_EVENT_ASCENT; break; default: // Unknown WARNING (abstract->context, "Unknown event"); break; } if (sample.event.type != SAMPLE_EVENT_NONE) { if (callback) callback (DC_SAMPLE_EVENT, sample, userdata); } } } if (data[offset] != 0x80) return DC_STATUS_DATAFORMAT; return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/suunto_solution_parser.c
/* * libdivecomputer * * Copyright (C) 2014 John Van Ostrand * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcpy, memcmp #include <stdlib.h> // malloc, free #include <assert.h> // assert #include "cochran_commander.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "array.h" #include "ringbuffer.h" #include "rbstream.h" #define C_ARRAY_SIZE(array) (sizeof (array) / sizeof *(array)) #define MAXRETRIES 2 #define COCHRAN_MODEL_COMMANDER_TM 0 #define COCHRAN_MODEL_COMMANDER_PRE21000 1 #define COCHRAN_MODEL_COMMANDER_AIR_NITROX 2 #define COCHRAN_MODEL_EMC_14 3 #define COCHRAN_MODEL_EMC_16 4 #define COCHRAN_MODEL_EMC_20 5 typedef enum cochran_endian_t { ENDIAN_LE, ENDIAN_BE, ENDIAN_WORD_BE, } cochran_endian_t; typedef struct cochran_commander_model_t { unsigned char id[3 + 1]; unsigned int model; } cochran_commander_model_t; typedef struct cochran_data_t { unsigned char config[1024]; unsigned char *logbook; unsigned short int dive_count; int fp_dive_num; int invalid_profile_dive_num; unsigned int logbook_size; } cochran_data_t; typedef struct cochran_device_layout_t { unsigned int model; unsigned int address_bits; cochran_endian_t endian; unsigned int baudrate; unsigned int rbstream_size; // Config data. unsigned int cf_dive_count; unsigned int cf_last_log; unsigned int cf_last_interdive; unsigned int cf_serial_number; // Logbook ringbuffer. unsigned int rb_logbook_begin; unsigned int rb_logbook_end; unsigned int rb_logbook_entry_size; unsigned int rb_logbook_entry_count; // Profile ringbuffer. unsigned int rb_profile_begin; unsigned int rb_profile_end; // pointers. unsigned int pt_fingerprint; unsigned int fingerprint_size; unsigned int pt_profile_pre; unsigned int pt_profile_begin; unsigned int pt_profile_end; unsigned int pt_dive_number; } cochran_device_layout_t; typedef struct cochran_commander_device_t { dc_device_t base; dc_iostream_t *iostream; const cochran_device_layout_t *layout; unsigned char id[67]; unsigned char fingerprint[6]; } cochran_commander_device_t; static dc_status_t cochran_commander_device_set_fingerprint (dc_device_t *device, const unsigned char data[], unsigned int size); static dc_status_t cochran_commander_device_read (dc_device_t *device, unsigned int address, unsigned char data[], unsigned int size); static dc_status_t cochran_commander_device_dump (dc_device_t *device, dc_buffer_t *data); static dc_status_t cochran_commander_device_foreach (dc_device_t *device, dc_dive_callback_t callback, void *userdata); static dc_status_t cochran_commander_device_close (dc_device_t *device); static const dc_device_vtable_t cochran_commander_device_vtable = { sizeof (cochran_commander_device_t), DC_FAMILY_COCHRAN_COMMANDER, cochran_commander_device_set_fingerprint,/* set_fingerprint */ cochran_commander_device_read, /* read */ NULL, /* write */ cochran_commander_device_dump, /* dump */ cochran_commander_device_foreach, /* foreach */ NULL, /* timesync */ cochran_commander_device_close /* close */ }; // Cochran Commander TM, pre-dates pre-21000 s/n static const cochran_device_layout_t cochran_cmdr_tm_device_layout = { COCHRAN_MODEL_COMMANDER_TM, // model 24, // address_bits ENDIAN_WORD_BE, // endian 9600, // baudrate 4096, // rbstream_size 0x146, // cf_dive_count 0x158, // cf_last_log 0xffffff, // cf_last_interdive 0x15c, // cf_serial_number 0x010000, // rb_logbook_begin 0x01232b, // rb_logbook_end 90, // rb_logbook_entry_size 100, // rb_logbook_entry_count 0x01232b, // rb_profile_begin 0x018000, // rb_profile_end 15, // pt_fingerprint 4, // fingerprint_size 0, // pt_profile_pre 0, // pt_profile_begin 90, // pt_profile_end (Next begin pointer is the end) 20, // pt_dive_number }; // Cochran Commander pre-21000 s/n static const cochran_device_layout_t cochran_cmdr_1_device_layout = { COCHRAN_MODEL_COMMANDER_PRE21000, // model 24, // address_bits ENDIAN_WORD_BE, // endian 115200, // baudrate 32768, // rbstream_size 0x046, // cf_dive_count 0x6c, // cf_last_log 0x70, // cf_last_interdive 0x0AA, // cf_serial_number 0x00000000, // rb_logbook_begin 0x00020000, // rb_logbook_end 256, // rb_logbook_entry_size 512, // rb_logbook_entry_count 0x00020000, // rb_profile_begin 0x00100000, // rb_profile_end 12, // pt_fingerprint 4, // fingerprint_size 28, // pt_profile_pre 0, // pt_profile_begin 128, // pt_profile_end 68, // pt_dive_number }; // Cochran Commander Nitrox static const cochran_device_layout_t cochran_cmdr_device_layout = { COCHRAN_MODEL_COMMANDER_AIR_NITROX, // model 24, // address_bits ENDIAN_WORD_BE, // endian 115200, // baudrate 32768, // rbstream_size 0x046, // cf_dive_count 0x06C, // cf_last_log 0x070, // cf_last_interdive 0x0AA, // cf_serial_number 0x00000000, // rb_logbook_begin 0x00020000, // rb_logbook_end 256, // rb_logbook_entry_size 512, // rb_logbook_entry_count 0x00020000, // rb_profile_begin 0x00100000, // rb_profile_end 0, // pt_fingerprint 6, // fingerprint_size 30, // pt_profile_pre 6, // pt_profile_begin 128, // pt_profile_end 70, // pt_dive_number }; // Cochran EMC-14 static const cochran_device_layout_t cochran_emc14_device_layout = { COCHRAN_MODEL_EMC_14, // model 32, // address_bits ENDIAN_LE, // endian 850000, // baudrate 32768, // rbstream_size 0x0D2, // cf_dive_count 0x13E, // cf_last_log 0x142, // cf_last_interdive 0x1E6, // cf_serial_number 0x00000000, // rb_logbook_begin 0x00020000, // rb_logbook_end 512, // rb_logbook_entry_size 256, // rb_logbook_entry_count 0x00022000, // rb_profile_begin 0x00200000, // rb_profile_end 0, // pt_fingerprint 6, // fingerprint_size 30, // pt_profile_pre 6, // pt_profile_begin 256, // pt_profile_end 86, // pt_dive_number }; // Cochran EMC-16 static const cochran_device_layout_t cochran_emc16_device_layout = { COCHRAN_MODEL_EMC_16, // model 32, // address_bits ENDIAN_LE, // endian 850000, // baudrate 32768, // rbstream_size 0x0D2, // cf_dive_count 0x13E, // cf_last_log 0x142, // cf_last_interdive 0x1E6, // cf_serial_number 0x00000000, // rb_logbook_begin 0x00080000, // rb_logbook_end 512, // rb_logbook_entry_size 1024, // rb_logbook_entry_count 0x00094000, // rb_profile_begin 0x00800000, // rb_profile_end 0, // pt_fingerprint 6, // fingerprint_size 30, // pt_profile_pre 6, // pt_profile_begin 256, // pt_profile_end 86, // pt_dive_number }; // Cochran EMC-20 static const cochran_device_layout_t cochran_emc20_device_layout = { COCHRAN_MODEL_EMC_20, // model 32, // address_bits ENDIAN_LE, // endian 850000, // baudrate 32768, // rbstream_size 0x0D2, // cf_dive_count 0x13E, // cf_last_log 0x142, // cf_last_interdive 0x1E6, // cf_serial_number 0x00000000, // rb_logbook_begin 0x00080000, // rb_logbook_end 512, // rb_logbook_entry_size 1024, // rb_logbook_entry_count 0x00094000, // rb_profile_begin 0x01000000, // rb_profile_end 0, // pt_fingerprint 6, // fingerprint_size 30, // pt_profile_pre 6, // pt_profile_begin 256, // pt_profile_end 86, // pt_dive_number }; // Determine model descriptor number from model string static unsigned int cochran_commander_get_model (cochran_commander_device_t *device) { const cochran_commander_model_t models[] = { {"\x0a""12", COCHRAN_MODEL_COMMANDER_TM}, {"\x11""21", COCHRAN_MODEL_COMMANDER_PRE21000}, {"\x11""22", COCHRAN_MODEL_COMMANDER_AIR_NITROX}, {"730", COCHRAN_MODEL_EMC_14}, {"731", COCHRAN_MODEL_EMC_14}, {"A30", COCHRAN_MODEL_EMC_16}, {"A31", COCHRAN_MODEL_EMC_16}, {"230", COCHRAN_MODEL_EMC_20}, {"231", COCHRAN_MODEL_EMC_20}, {"\x40""30", COCHRAN_MODEL_EMC_20}, }; unsigned int model = 0xFFFFFFFF; for (unsigned int i = 0; i < C_ARRAY_SIZE(models); ++i) { if (memcmp (device->id + 0x3D, models[i].id, sizeof(models[i].id) - 1) == 0) { model = models[i].model; break; } } return model; } static dc_status_t cochran_commander_serial_setup (cochran_commander_device_t *device) { dc_status_t status = DC_STATUS_SUCCESS; // Set the serial communication protocol (9600 8N2, no FC). status = dc_iostream_configure (device->iostream, 9600, 8, DC_PARITY_NONE, DC_STOPBITS_TWO, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (device->base.context, "Failed to set the terminal attributes."); return status; } // Set the timeout for receiving data (5000 ms). status = dc_iostream_set_timeout (device->iostream, 5000); if (status != DC_STATUS_SUCCESS) { ERROR (device->base.context, "Failed to set the timeout."); return status; } // Wake up DC and trigger heartbeat dc_iostream_set_break(device->iostream, 1); dc_iostream_sleep(device->iostream, 16); dc_iostream_set_break(device->iostream, 0); // Clear old heartbeats dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); // Wait for heartbeat byte before send unsigned char answer = 0; status = dc_iostream_read(device->iostream, &answer, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (device->base.context, "Failed to receive device heartbeat."); return status; } if (answer != 0xAA) { ERROR (device->base.context, "Received bad hearbeat byte (%02x).", answer); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } static dc_status_t cochran_commander_packet (cochran_commander_device_t *device, dc_event_progress_t *progress, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize, int high_speed) { dc_device_t *abstract = (dc_device_t *) device; dc_status_t status = DC_STATUS_SUCCESS; if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; // Send the command to the device, one byte at a time // If sent all at once the command is ignored. It's like the DC // has no buffering. for (unsigned int i = 0; i < csize; i++) { // Give the DC time to read the character. if (i) dc_iostream_sleep(device->iostream, 16); // 16 ms status = dc_iostream_write(device->iostream, command + i, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } } if (high_speed && device->layout->baudrate != 9600) { // Give the DC time to process the command. dc_iostream_sleep(device->iostream, 45); // Rates are odd, like 850400 for the EMC, 115200 for commander status = dc_iostream_configure(device->iostream, device->layout->baudrate, 8, DC_PARITY_NONE, DC_STOPBITS_TWO, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to set the high baud rate."); return status; } } // Receive the answer from the device. // Use 1024 byte "packets" so we can display progress. unsigned int nbytes = 0; while (nbytes < asize) { unsigned int len = asize - nbytes; if (len > 1024) len = 1024; status = dc_iostream_read (device->iostream, answer + nbytes, len, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive data."); return status; } nbytes += len; if (progress) { progress->current += len; device_event_emit (abstract, DC_EVENT_PROGRESS, progress); } } return DC_STATUS_SUCCESS; } static dc_status_t cochran_commander_read_id (cochran_commander_device_t *device, unsigned char id[], unsigned int size) { dc_status_t rc = DC_STATUS_SUCCESS; unsigned char command[6] = {0x05, 0x9D, 0xFF, 0x00, 0x43, 0x00}; rc = cochran_commander_packet(device, NULL, command, sizeof(command), id, size, 0); if (rc != DC_STATUS_SUCCESS) return rc; if (memcmp(id, "(C)", 3) != 0) { // It's a Commander, read a different location command[1] = 0xBD; command[2] = 0x7F; rc = cochran_commander_packet(device, NULL, command, sizeof(command), id, size, 0); if (rc != DC_STATUS_SUCCESS) return rc; } return DC_STATUS_SUCCESS; } static dc_status_t cochran_commander_read_config (cochran_commander_device_t *device, dc_event_progress_t *progress, unsigned char data[], unsigned int size) { dc_device_t *abstract = (dc_device_t *) device; dc_status_t rc = DC_STATUS_SUCCESS; if ((size % 512) != 0) return DC_STATUS_INVALIDARGS; // Read two 512 byte blocks into one 1024 byte buffer unsigned int pages = size / 512; for (unsigned int i = 0; i < pages; i++) { unsigned char command[2] = {0x96, i}; unsigned int command_size = sizeof(command); if (device->layout->model == COCHRAN_MODEL_COMMANDER_TM) command_size = 1; rc = cochran_commander_packet(device, progress, command, command_size, data + i * 512, 512, 0); if (rc != DC_STATUS_SUCCESS) return rc; dc_event_vendor_t vendor; vendor.data = data + i * 512; vendor.size = 512; device_event_emit (abstract, DC_EVENT_VENDOR, &vendor); } return DC_STATUS_SUCCESS; } static dc_status_t cochran_commander_read (cochran_commander_device_t *device, dc_event_progress_t *progress, unsigned int address, unsigned char data[], unsigned int size) { dc_status_t rc = DC_STATUS_SUCCESS; // Build the command unsigned char command[10]; unsigned char command_size; switch (device->layout->address_bits) { case 32: // EMC uses 32 bit addressing command[0] = 0x15; command[1] = (address ) & 0xff; command[2] = (address >> 8) & 0xff; command[3] = (address >> 16) & 0xff; command[4] = (address >> 24) & 0xff; command[5] = (size ) & 0xff; command[6] = (size >> 8 ) & 0xff; command[7] = (size >> 16 ) & 0xff; command[8] = (size >> 24 ) & 0xff; command[9] = 0x05; command_size = 10; break; case 24: // Commander uses 24 byte addressing if (device->layout->baudrate == 9600) { // This read command will return 32K bytes if asked to read // 0 bytes. So we can allow a size of up to 0x10000 but if // the user asks for 0 bytes we should just return success // otherwise we'll end end up running past the buffer. if (size > 0x10000) return DC_STATUS_INVALIDARGS; if (size == 0) return DC_STATUS_SUCCESS; // Older commander, use low-speed read command command[0] = 0x05; command[1] = (address ) & 0xff; command[2] = (address >> 8) & 0xff; command[3] = (address >> 16) & 0xff; command[4] = (size ) & 0xff; command[5] = (size >> 8 ) & 0xff; command_size = 6; } else { // Newer commander with high-speed read command command[0] = 0x15; command[1] = (address ) & 0xff; command[2] = (address >> 8) & 0xff; command[3] = (address >> 16) & 0xff; command[4] = (size ) & 0xff; command[5] = (size >> 8 ) & 0xff; command[6] = (size >> 16 ) & 0xff; command[7] = 0x04; command_size = 8; } break; default: return DC_STATUS_UNSUPPORTED; } dc_iostream_sleep(device->iostream, 550); // set back to 9600 baud rc = cochran_commander_serial_setup(device); if (rc != DC_STATUS_SUCCESS) return rc; // Read data at high speed rc = cochran_commander_packet (device, progress, command, command_size, data, size, 1); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; } static dc_status_t cochran_commander_read_retry (cochran_commander_device_t *device, dc_event_progress_t *progress, unsigned int address, unsigned char data[], unsigned int size) { // Save the state of the progress events. unsigned int saved = 0; if (progress) { saved = progress->current; } unsigned int nretries = 0; dc_status_t rc = DC_STATUS_SUCCESS; while ((rc = cochran_commander_read (device, progress, address, data, size)) != DC_STATUS_SUCCESS) { // Automatically discard a corrupted packet, // and request a new one. if (rc != DC_STATUS_PROTOCOL && rc != DC_STATUS_TIMEOUT) return rc; // Abort if the maximum number of retries is reached. if (nretries++ >= MAXRETRIES) return rc; // Restore the state of the progress events. if (progress) { progress->current = saved; } } return rc; } /* * For corrupt dives the end-of-samples pointer is 0xFFFFFFFF * search for a reasonable size, e.g. using next dive start sample * or end-of-samples to limit searching for recoverable samples */ static unsigned int cochran_commander_guess_sample_end_address(cochran_commander_device_t *device, cochran_data_t *data, unsigned int log_num) { const unsigned char *log_entry = data->logbook + device->layout->rb_logbook_entry_size * log_num; if (log_num == data->dive_count) // Return next usable address from config page return array_uint32_le(data->config + device->layout->rb_profile_end); // Next log's start address return array_uint32_le(log_entry + device->layout->rb_logbook_entry_size + device->layout->pt_profile_begin); } static unsigned int cochran_commander_profile_size(cochran_commander_device_t *device, cochran_data_t *data, int dive_num, unsigned int sample_start_address, unsigned int sample_end_address) { // Validate addresses if (sample_start_address < device->layout->rb_profile_begin || sample_start_address > device->layout->rb_profile_end || sample_end_address < device->layout->rb_profile_begin || (sample_end_address > device->layout->rb_profile_end && sample_end_address != 0xFFFFFFFF)) { return 0; } if (sample_end_address == 0xFFFFFFFF) // Corrupt dive, guess the end address sample_end_address = cochran_commander_guess_sample_end_address(device, data, dive_num); return ringbuffer_distance(sample_start_address, sample_end_address, 0, device->layout->rb_profile_begin, device->layout->rb_profile_end); } /* * Do several things. Find the log that matches the fingerprint, * calculate the total read size for progress indicator, * Determine the most recent dive without profile data. */ static unsigned int cochran_commander_find_fingerprint(cochran_commander_device_t *device, cochran_data_t *data) { unsigned int base = device->layout->rb_logbook_begin; // We track profile ringbuffer usage to determine which dives have profile data int profile_capacity_remaining = device->layout->rb_profile_end - device->layout->rb_profile_begin; int dive_count = -1; data->fp_dive_num = -1; // Start at end of log if (data->dive_count < device->layout->rb_logbook_entry_count) dive_count = data->dive_count; else dive_count = device->layout->rb_logbook_entry_count; dive_count--; unsigned int sample_read_size = 0; data->invalid_profile_dive_num = -1; // Remove the pre-dive events that occur after the last dive unsigned int rb_head_ptr = 0; if (device->layout->model == COCHRAN_MODEL_COMMANDER_TM) // TM uses SRAM and does not need to erase pages rb_head_ptr = base + array_uint16_be(data->config + device->layout->cf_last_log); else if (device->layout->endian == ENDIAN_WORD_BE) rb_head_ptr = base + (array_uint32_word_be(data->config + device->layout->cf_last_log) & 0xfffff000) + 0x2000; else rb_head_ptr = base + (array_uint32_le(data->config + device->layout->cf_last_log) & 0xfffff000) + 0x2000; unsigned int head_dive = 0, tail_dive = 0; if (data->dive_count <= device->layout->rb_logbook_entry_count) { head_dive = data->dive_count; tail_dive = 0; } else { // Log wrapped tail_dive = data->dive_count % device->layout->rb_logbook_entry_count; head_dive = tail_dive; } unsigned int last_profile_idx = (device->layout->rb_logbook_entry_count + head_dive - 1) % device->layout->rb_logbook_entry_count; unsigned int last_profile_end = 0; if (device->layout->model == COCHRAN_MODEL_COMMANDER_TM) // There is no end pointer in this model and no inter-dive // events. We could use profile_begin from the next dive but // since this is the last dive, we'll use rb_head_ptr last_profile_end = rb_head_ptr; else last_profile_end = base + array_uint32_le(data->logbook + last_profile_idx * device->layout->rb_logbook_entry_size + device->layout->pt_profile_end); unsigned int last_profile_pre = 0xFFFFFFFF; if (device->layout->endian == ENDIAN_WORD_BE) last_profile_pre = base + array_uint32_word_be(data->config + device->layout->cf_last_log); else last_profile_pre = base + array_uint32_le(data->config + device->layout->cf_last_log); if (rb_head_ptr > last_profile_end) profile_capacity_remaining -= rb_head_ptr - last_profile_end; // Loop through dives to find FP, Accumulate profile data size, // and find the last dive with invalid profile for (unsigned int i = 0; i <= dive_count; ++i) { unsigned int idx = (device->layout->rb_logbook_entry_count + head_dive - (i + 1)) % device->layout->rb_logbook_entry_count; unsigned char *log_entry = data->logbook + idx * device->layout->rb_logbook_entry_size; // We're done if we find the fingerprint if (!memcmp(device->fingerprint, log_entry + device->layout->pt_fingerprint, device->layout->fingerprint_size)) { data->fp_dive_num = idx; break; } unsigned int profile_pre = 0; if (device->layout->model == COCHRAN_MODEL_COMMANDER_TM) profile_pre = base + array_uint16_le(log_entry + device->layout->pt_profile_pre); else profile_pre = base + array_uint32_le(log_entry + device->layout->pt_profile_pre); unsigned int sample_size = cochran_commander_profile_size(device, data, idx, profile_pre, last_profile_pre); last_profile_pre = profile_pre; // Determine if sample exists if (profile_capacity_remaining > 0) { // Subtract this dive's profile size including post-dive events profile_capacity_remaining -= sample_size; if (profile_capacity_remaining < 0) { // Save the last dive that is missing profile data data->invalid_profile_dive_num = idx; } // Accumulate read size for progress bar sample_read_size += sample_size; } } return sample_read_size; } dc_status_t cochran_commander_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; cochran_commander_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (cochran_commander_device_t *) dc_device_allocate (context, &cochran_commander_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; cochran_commander_device_set_fingerprint((dc_device_t *) device, NULL, 0); // Open the device. status = dc_serial_open (&device->iostream, device->base.context, name); if (status != DC_STATUS_SUCCESS) { ERROR (device->base.context, "Failed to open the serial port."); goto error_free; } status = cochran_commander_serial_setup(device); if (status != DC_STATUS_SUCCESS) { goto error_close; } // Read ID from the device status = cochran_commander_read_id (device, device->id, sizeof(device->id)); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Device not responding."); goto error_close; } unsigned int model = cochran_commander_get_model(device); switch (model) { case COCHRAN_MODEL_COMMANDER_TM: device->layout = &cochran_cmdr_tm_device_layout; break; case COCHRAN_MODEL_COMMANDER_PRE21000: device->layout = &cochran_cmdr_1_device_layout; break; case COCHRAN_MODEL_COMMANDER_AIR_NITROX: device->layout = &cochran_cmdr_device_layout; break; case COCHRAN_MODEL_EMC_14: device->layout = &cochran_emc14_device_layout; break; case COCHRAN_MODEL_EMC_16: device->layout = &cochran_emc16_device_layout; break; case COCHRAN_MODEL_EMC_20: device->layout = &cochran_emc20_device_layout; break; default: ERROR (context, "Unknown model"); status = DC_STATUS_UNSUPPORTED; goto error_close; } *out = (dc_device_t *) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t cochran_commander_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; cochran_commander_device_t *device = (cochran_commander_device_t *) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t cochran_commander_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { cochran_commander_device_t *device = (cochran_commander_device_t *) abstract; if (size && size != device->layout->fingerprint_size) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, device->layout->fingerprint_size); else memset (device->fingerprint, 0xFF, sizeof(device->fingerprint)); return DC_STATUS_SUCCESS; } static dc_status_t cochran_commander_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size) { cochran_commander_device_t *device = (cochran_commander_device_t *) abstract; return cochran_commander_read_retry(device, NULL, address, data, size); } static dc_status_t cochran_commander_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { cochran_commander_device_t *device = (cochran_commander_device_t *) abstract; dc_status_t rc = DC_STATUS_SUCCESS; unsigned char config[1024]; unsigned int config_size = sizeof(config); unsigned int size = device->layout->rb_profile_end - device->layout->rb_logbook_begin; // Reserve space if (!dc_buffer_resize(buffer, size)) { ERROR(abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } if (device->layout->model == COCHRAN_MODEL_COMMANDER_TM) config_size = 512; // Determine size for progress dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = config_size + size; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Emit ID block dc_event_vendor_t vendor; vendor.data = device->id; vendor.size = sizeof (device->id); device_event_emit (abstract, DC_EVENT_VENDOR, &vendor); rc = cochran_commander_read_config (device, &progress, config, config_size); if (rc != DC_STATUS_SUCCESS) return rc; // Read the sample data, logbook and sample data are contiguous rc = cochran_commander_read_retry (device, &progress, device->layout->rb_logbook_begin, dc_buffer_get_data(buffer), size); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the sample data."); return rc; } return DC_STATUS_SUCCESS; } static dc_status_t cochran_commander_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { cochran_commander_device_t *device = (cochran_commander_device_t *) abstract; const cochran_device_layout_t *layout = device->layout; dc_status_t status = DC_STATUS_SUCCESS; dc_rbstream_t *rbstream = NULL; cochran_data_t data; data.logbook = NULL; // Calculate max data sizes unsigned int max_config = sizeof(data.config); unsigned int max_logbook = layout->rb_logbook_end - layout->rb_logbook_begin; unsigned int max_sample = layout->rb_profile_end - layout->rb_profile_begin; unsigned int base = device->layout->rb_logbook_begin; if (device->layout->model == COCHRAN_MODEL_COMMANDER_TM) max_config = 512; // setup progress indication dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = max_config + max_logbook + max_sample; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Emit ID block dc_event_vendor_t vendor; vendor.data = device->id; vendor.size = sizeof (device->id); device_event_emit (abstract, DC_EVENT_VENDOR, &vendor); // Read config dc_status_t rc = DC_STATUS_SUCCESS; rc = cochran_commander_read_config(device, &progress, data.config, max_config); if (rc != DC_STATUS_SUCCESS) return rc; // Determine size of dive list to read. if (layout->endian == ENDIAN_LE) data.dive_count = array_uint16_le (data.config + layout->cf_dive_count); else data.dive_count = array_uint16_be (data.config + layout->cf_dive_count); if (data.dive_count == 0) { // No dives to read WARNING(abstract->context, "This dive computer has no recorded dives."); return DC_STATUS_SUCCESS; } if (data.dive_count > layout->rb_logbook_entry_count) { data.logbook_size = layout->rb_logbook_entry_count * layout->rb_logbook_entry_size; } else { data.logbook_size = data.dive_count * layout->rb_logbook_entry_size; } // Update progress indicator with new maximum progress.maximum -= max_logbook - data.logbook_size; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Allocate space for log book. data.logbook = (unsigned char *) malloc(data.logbook_size); if (data.logbook == NULL) { ERROR (abstract->context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Request log book rc = cochran_commander_read_retry(device, &progress, layout->rb_logbook_begin, data.logbook, data.logbook_size); if (rc != DC_STATUS_SUCCESS) { status = rc; goto error; } // Locate fingerprint, recent dive with invalid profile and calc read size unsigned int profile_read_size = cochran_commander_find_fingerprint(device, &data); // Update progress indicator with new maximum progress.maximum -= (max_sample - profile_read_size); device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Emit a device info event. dc_event_devinfo_t devinfo; devinfo.model = layout->model; devinfo.firmware = 0; // unknown if (layout->endian == ENDIAN_WORD_BE) devinfo.serial = array_uint32_word_be(data.config + layout->cf_serial_number); else devinfo.serial = array_uint32_le(data.config + layout->cf_serial_number); device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); unsigned int head_dive = 0, tail_dive = 0, dive_count = 0; if (data.dive_count <= layout->rb_logbook_entry_count) { head_dive = data.dive_count; tail_dive = 0; } else { // Log wrapped tail_dive = data.dive_count % layout->rb_logbook_entry_count; head_dive = tail_dive; } // Change tail to dive following the fingerprint dive. if (data.fp_dive_num > -1) tail_dive = (data.fp_dive_num + 1) % layout->rb_logbook_entry_count; // Number of dives to read dive_count = (layout->rb_logbook_entry_count + head_dive - tail_dive) % layout->rb_logbook_entry_count; unsigned int last_start_address = 0; if (layout->endian == ENDIAN_WORD_BE) last_start_address = base + array_uint32_word_be(data.config + layout->cf_last_log ); else last_start_address = base + array_uint32_le(data.config + layout->cf_last_log ); // Create the ringbuffer stream. status = dc_rbstream_new (&rbstream, abstract, 1, layout->rbstream_size, layout->rb_profile_begin, layout->rb_profile_end, last_start_address); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to create the ringbuffer stream."); goto error; } int invalid_profile_flag = 0; // Loop through each dive for (unsigned int i = 0; i < dive_count; ++i) { unsigned int idx = (layout->rb_logbook_entry_count + head_dive - (i + 1)) % layout->rb_logbook_entry_count; unsigned char *log_entry = data.logbook + idx * layout->rb_logbook_entry_size; unsigned int sample_start_address = 0; unsigned int sample_end_address = 0; if (layout->model == COCHRAN_MODEL_COMMANDER_TM) { sample_start_address = base + array_uint16_le (log_entry + layout->pt_profile_begin); sample_end_address = last_start_address; // Commander TM has SRAM which seems to randomize when they lose power for too long // Check for bad entries. if (sample_start_address < layout->rb_profile_begin || sample_start_address > layout->rb_profile_end || sample_end_address < layout->rb_profile_begin || sample_end_address > layout->rb_profile_end || array_uint16_le(log_entry + layout->pt_dive_number) % layout->rb_logbook_entry_count != idx) { ERROR(abstract->context, "Corrupt dive (%d).", idx); continue; } } else { sample_start_address = base + array_uint32_le (log_entry + layout->pt_profile_begin); sample_end_address = base + array_uint32_le (log_entry + layout->pt_profile_end); } int sample_size = 0, pre_size = 0; // Determine if profile exists if (idx == data.invalid_profile_dive_num) invalid_profile_flag = 1; if (!invalid_profile_flag) { sample_size = cochran_commander_profile_size(device, &data, idx, sample_start_address, sample_end_address); pre_size = cochran_commander_profile_size(device, &data, idx, sample_end_address, last_start_address); last_start_address = sample_start_address; } // Build dive blob unsigned int dive_size = layout->rb_logbook_entry_size + sample_size; unsigned char *dive = (unsigned char *) malloc(dive_size + pre_size); if (dive == NULL) { status = DC_STATUS_NOMEMORY; goto error; } memcpy(dive, log_entry, layout->rb_logbook_entry_size); // log // Read profile data if (sample_size) { rc = dc_rbstream_read(rbstream, &progress, dive + layout->rb_logbook_entry_size, sample_size + pre_size); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the sample data."); status = rc; free(dive); goto error; } } if (callback && !callback (dive, dive_size, dive + layout->pt_fingerprint, layout->fingerprint_size, userdata)) { free(dive); break; } free(dive); } error: dc_rbstream_free(rbstream); free(data.logbook); return status; }
libdc-for-dirk-Subsurface-branch
src/cochran_commander.c
/* * libdivecomputer * * Copyright (C) 2011 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <string.h> #include <assert.h> #include <libdivecomputer/units.h> #include "mares_darwin.h" #include "mares_common.h" #include "context-private.h" #include "device-private.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &mares_darwin_device_vtable) #define DARWIN 0 #define DARWINAIR 1 typedef struct mares_darwin_layout_t { // Memory size. unsigned int memsize; // Logbook ringbuffer. unsigned int rb_logbook_offset; unsigned int rb_logbook_size; unsigned int rb_logbook_count; // Profile ringbuffer unsigned int rb_profile_begin; unsigned int rb_profile_end; // Sample size unsigned int samplesize; } mares_darwin_layout_t; typedef struct mares_darwin_device_t { mares_common_device_t base; const mares_darwin_layout_t *layout; unsigned int model; unsigned char fingerprint[6]; } mares_darwin_device_t; static dc_status_t mares_darwin_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t mares_darwin_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t mares_darwin_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t mares_darwin_device_close (dc_device_t *abstract); static const dc_device_vtable_t mares_darwin_device_vtable = { sizeof(mares_darwin_device_t), DC_FAMILY_MARES_DARWIN, mares_darwin_device_set_fingerprint, /* set_fingerprint */ mares_common_device_read, /* read */ NULL, /* write */ mares_darwin_device_dump, /* dump */ mares_darwin_device_foreach, /* foreach */ NULL, /* timesync */ mares_darwin_device_close /* close */ }; static const mares_darwin_layout_t mares_darwin_layout = { 0x4000, /* memsize */ 0x0100, /* rb_logbook_offset */ 52, /* rb_logbook_size */ 50, /* rb_logbook_count */ 0x0B30, /* rb_profile_begin */ 0x4000, /* rb_profile_end */ 2 /* samplesize */ }; static const mares_darwin_layout_t mares_darwinair_layout = { 0x4000, /* memsize */ 0x0100, /* rb_logbook_offset */ 60, /* rb_logbook_size */ 50, /* rb_logbook_count */ 0x0CC0, /* rb_profile_begin */ 0x3FFF, /* rb_profile_end */ 3 /* samplesize */ }; static dc_status_t mares_darwin_extract_dives (dc_device_t *device, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata); dc_status_t mares_darwin_device_open (dc_device_t **out, dc_context_t *context, const char *name, unsigned int model) { dc_status_t status = DC_STATUS_SUCCESS; mares_darwin_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (mares_darwin_device_t *) dc_device_allocate (context, &mares_darwin_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Initialize the base class. mares_common_device_init (&device->base); // Set the default values. memset (device->fingerprint, 0, sizeof (device->fingerprint)); device->model = model; if (model == DARWINAIR) device->layout = &mares_darwinair_layout; else device->layout = &mares_darwin_layout; // Open the device. status = dc_serial_open (&device->base.iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (9600 8N1). status = dc_iostream_configure (device->base.iostream, 9600, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (1000 ms). status = dc_iostream_set_timeout (device->base.iostream, 1000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Set the DTR line. status = dc_iostream_set_dtr (device->base.iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the DTR line."); goto error_close; } // Set the RTS line. status = dc_iostream_set_rts (device->base.iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the RTS line."); goto error_close; } // Make sure everything is in a sane state. dc_iostream_sleep (device->base.iostream, 100); dc_iostream_purge (device->base.iostream, DC_DIRECTION_ALL); // Override the base class values. device->base.echo = 1; device->base.delay = 50; *out = (dc_device_t *) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->base.iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t mares_darwin_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; mares_darwin_device_t *device = (mares_darwin_device_t *) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Close the device. rc = dc_iostream_close (device->base.iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t mares_darwin_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { mares_darwin_device_t *device = (mares_darwin_device_t *) abstract; if (size && size != sizeof (device->fingerprint)) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, sizeof (device->fingerprint)); else memset (device->fingerprint, 0, sizeof (device->fingerprint)); return DC_STATUS_SUCCESS; } static dc_status_t mares_darwin_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { mares_darwin_device_t *device = (mares_darwin_device_t *) abstract; assert (device->layout != NULL); // Allocate the required amount of memory. if (!dc_buffer_resize (buffer, device->layout->memsize)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } return device_dump_read (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), PACKETSIZE); } static dc_status_t mares_darwin_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { mares_darwin_device_t *device = (mares_darwin_device_t *) abstract; assert (device->layout != NULL); dc_buffer_t *buffer = dc_buffer_new (device->layout->memsize); if (buffer == NULL) return DC_STATUS_NOMEMORY; dc_status_t rc = mares_darwin_device_dump (abstract, buffer); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } // Emit a device info event. unsigned char *data = dc_buffer_get_data (buffer); dc_event_devinfo_t devinfo; devinfo.model = device->model; devinfo.firmware = 0; devinfo.serial = array_uint16_be (data + 8); device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); rc = mares_darwin_extract_dives (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), callback, userdata); dc_buffer_free (buffer); return rc; } static dc_status_t mares_darwin_extract_dives (dc_device_t *abstract, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata) { mares_darwin_device_t *device = (mares_darwin_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; assert (device->layout != NULL); const mares_darwin_layout_t *layout = device->layout; // Get the profile pointer. unsigned int eop = array_uint16_be (data + 0x8A); if (eop < layout->rb_profile_begin || eop >= layout->rb_profile_end) { ERROR (abstract->context, "Invalid ringbuffer pointer detected (0x%04x).", eop); return DC_STATUS_DATAFORMAT; } // Get the logbook index. unsigned int last = data[0x8C]; if (last >= layout->rb_logbook_count) { ERROR (abstract->context, "Invalid ringbuffer pointer detected (0x%02x).", last); return DC_STATUS_DATAFORMAT; } // Allocate memory for the largest possible dive. unsigned char *buffer = (unsigned char *) malloc (layout->rb_logbook_size + layout->rb_profile_end - layout->rb_profile_begin); if (buffer == NULL) { ERROR (abstract->context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // The logbook ringbuffer can store a fixed amount of entries, but there // is no guarantee that the profile ringbuffer will contain a profile for // each entry. The number of remaining bytes (which is initialized to the // largest possible value) is used to detect the last valid profile. unsigned int remaining = layout->rb_profile_end - layout->rb_profile_begin; unsigned int current = eop; for (unsigned int i = 0; i < layout->rb_logbook_count; ++i) { // Get the offset to the current logbook entry in the ringbuffer. unsigned int idx = (layout->rb_logbook_count + last - i) % layout->rb_logbook_count; unsigned int offset = layout->rb_logbook_offset + idx * layout->rb_logbook_size; // Get the length of the current dive. unsigned int nsamples = array_uint16_be (data + offset + 6); unsigned int length = nsamples * layout->samplesize; if (nsamples == 0xFFFF || length > remaining) break; // Copy the logbook entry. memcpy (buffer, data + offset, layout->rb_logbook_size); // Copy the profile data. if (current < layout->rb_profile_begin + length) { unsigned int a = current - layout->rb_profile_begin; unsigned int b = length - a; memcpy (buffer + layout->rb_logbook_size, data + layout->rb_profile_end - b, b); memcpy (buffer + layout->rb_logbook_size + b, data + layout->rb_profile_begin, a); current = layout->rb_profile_end - b; } else { memcpy (buffer + layout->rb_logbook_size, data + current - length, length); current -= length; } if (memcmp (buffer, device->fingerprint, sizeof (device->fingerprint)) == 0) { free (buffer); return DC_STATUS_SUCCESS; } if (callback && !callback (buffer, layout->rb_logbook_size + length, buffer, 6, userdata)) { free (buffer); return DC_STATUS_SUCCESS; } remaining -= length; } free (buffer); return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/mares_darwin.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> #include "array.h" void array_reverse_bytes (unsigned char data[], unsigned int size) { for (unsigned int i = 0; i < size / 2; ++i) { unsigned char hlp = data[i]; data[i] = data[size - 1 - i]; data[size - 1 - i] = hlp; } } void array_reverse_bits (unsigned char data[], unsigned int size) { for (unsigned int i = 0; i < size; ++i) { unsigned char j = 0; j = (data[i] & 0x01) << 7; j += (data[i] & 0x02) << 5; j += (data[i] & 0x04) << 3; j += (data[i] & 0x08) << 1; j += (data[i] & 0x10) >> 1; j += (data[i] & 0x20) >> 3; j += (data[i] & 0x40) >> 5; j += (data[i] & 0x80) >> 7; data[i] = j; } } int array_isequal (const unsigned char data[], unsigned int size, unsigned char value) { for (unsigned int i = 0; i < size; ++i) { if (data[i] != value) return 0; } return 1; } const unsigned char * array_search_forward (const unsigned char *data, unsigned int size, const unsigned char *marker, unsigned int msize) { while (size >= msize) { if (memcmp (data, marker, msize) == 0) return data; size--; data++; } return NULL; } const unsigned char * array_search_backward (const unsigned char *data, unsigned int size, const unsigned char *marker, unsigned int msize) { data += size; while (size >= msize) { if (memcmp (data - msize, marker, msize) == 0) return data; size--; data--; } return NULL; } int array_convert_bin2hex (const unsigned char input[], unsigned int isize, unsigned char output[], unsigned int osize) { if (osize != 2 * isize) return -1; const unsigned char ascii[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; for (unsigned int i = 0; i < isize; ++i) { // Set the most-significant nibble. unsigned char msn = (input[i] >> 4) & 0x0F; output[i * 2 + 0] = ascii[msn]; // Set the least-significant nibble. unsigned char lsn = input[i] & 0x0F; output[i * 2 + 1] = ascii[lsn]; } return 0; } int array_convert_hex2bin (const unsigned char input[], unsigned int isize, unsigned char output[], unsigned int osize) { if (isize != 2 * osize) return -1; for (unsigned int i = 0; i < osize; ++i) { unsigned char value = 0; for (unsigned int j = 0; j < 2; ++j) { unsigned char number = 0; unsigned char ascii = input[i * 2 + j]; if (ascii >= '0' && ascii <= '9') number = ascii - '0'; else if (ascii >= 'A' && ascii <= 'F') number = 10 + ascii - 'A'; else if (ascii >= 'a' && ascii <= 'f') number = 10 + ascii - 'a'; else return -1; /* Invalid character */ value <<= 4; value += number; } output[i] = value; } return 0; } unsigned int array_convert_str2num (const unsigned char data[], unsigned int size) { unsigned int value = 0; for (unsigned int i = 0; i < size; ++i) { if (data[i] < '0' || data[i] > '9') break; value *= 10; value += data[i] - '0'; } return value; } unsigned int array_uint_be (const unsigned char data[], unsigned int n) { unsigned int shift = n * 8; unsigned int value = 0; for (unsigned int i = 0; i < n; ++i) { shift -= 8; value |= data[i] << shift; } return value; } unsigned int array_uint_le (const unsigned char data[], unsigned int n) { unsigned int shift = 0; unsigned int value = 0; for (unsigned int i = 0; i < n; ++i) { value |= data[i] << shift; shift += 8; } return value; } unsigned int array_uint32_be (const unsigned char data[]) { return (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]; } unsigned int array_uint32_le (const unsigned char data[]) { return data[0] + (data[1] << 8) + (data[2] << 16) + (data[3] << 24); } unsigned int array_uint32_word_be (const unsigned char data[]) { return data[1] + (data[0] << 8) + (data[3] << 16) + (data[2] << 24); } void array_uint32_le_set (unsigned char data[], const unsigned int input) { data[0] = input & 0xFF; data[1] = (input >> 8) & 0xFF; data[2] = (input >> 16) & 0xFF; data[3] = (input >> 24) & 0xFF; } unsigned int array_uint24_be (const unsigned char data[]) { return (data[0] << 16) + (data[1] << 8) + data[2]; } void array_uint24_be_set (unsigned char data[], const unsigned int input) { data[0] = (input >> 16) & 0xFF; data[1] = (input >> 8) & 0xFF; data[2] = input & 0xFF; } unsigned int array_uint24_le (const unsigned char data[]) { return data[0] + (data[1] << 8) + (data[2] << 16); } unsigned short array_uint16_be (const unsigned char data[]) { return (data[0] << 8) + data[1]; } unsigned short array_uint16_le (const unsigned char data[]) { return data[0] + (data[1] << 8); } unsigned char bcd2dec (unsigned char value) { return ((value >> 4) & 0x0f) * 10 + (value & 0x0f); }
libdc-for-dirk-Subsurface-branch
src/array.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <string.h> // memcmp #include <libdivecomputer/units.h> #include "reefnet_sensuspro.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_parser_isinstance((parser), &reefnet_sensuspro_parser_vtable) typedef struct reefnet_sensuspro_parser_t reefnet_sensuspro_parser_t; struct reefnet_sensuspro_parser_t { dc_parser_t base; // Depth calibration. double atmospheric; double hydrostatic; // Clock synchronization. unsigned int devtime; dc_ticks_t systime; // Cached fields. unsigned int cached; unsigned int divetime; unsigned int maxdepth; }; static dc_status_t reefnet_sensuspro_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t reefnet_sensuspro_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t reefnet_sensuspro_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t reefnet_sensuspro_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t reefnet_sensuspro_parser_vtable = { sizeof(reefnet_sensuspro_parser_t), DC_FAMILY_REEFNET_SENSUSPRO, reefnet_sensuspro_parser_set_data, /* set_data */ reefnet_sensuspro_parser_get_datetime, /* datetime */ reefnet_sensuspro_parser_get_field, /* fields */ reefnet_sensuspro_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; dc_status_t reefnet_sensuspro_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int devtime, dc_ticks_t systime) { reefnet_sensuspro_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (reefnet_sensuspro_parser_t *) dc_parser_allocate (context, &reefnet_sensuspro_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. parser->atmospheric = ATM; parser->hydrostatic = 1025.0 * GRAVITY; parser->devtime = devtime; parser->systime = systime; parser->cached = 0; parser->divetime = 0; parser->maxdepth = 0; *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensuspro_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { reefnet_sensuspro_parser_t *parser = (reefnet_sensuspro_parser_t*) abstract; // Reset the cache. parser->cached = 0; parser->divetime = 0; parser->maxdepth = 0; return DC_STATUS_SUCCESS; } dc_status_t reefnet_sensuspro_parser_set_calibration (dc_parser_t *abstract, double atmospheric, double hydrostatic) { reefnet_sensuspro_parser_t *parser = (reefnet_sensuspro_parser_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; parser->atmospheric = atmospheric; parser->hydrostatic = hydrostatic; return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensuspro_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { reefnet_sensuspro_parser_t *parser = (reefnet_sensuspro_parser_t *) abstract; if (abstract->size < 6 + 4) return DC_STATUS_DATAFORMAT; unsigned int timestamp = array_uint32_le (abstract->data + 6); dc_ticks_t ticks = parser->systime - (parser->devtime - timestamp); if (!dc_datetime_localtime (datetime, ticks)) return DC_STATUS_DATAFORMAT; return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensuspro_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { reefnet_sensuspro_parser_t *parser = (reefnet_sensuspro_parser_t *) abstract; if (abstract->size < 12) return DC_STATUS_DATAFORMAT; if (!parser->cached) { const unsigned char footer[2] = {0xFF, 0xFF}; const unsigned char *data = abstract->data; unsigned int size = abstract->size; unsigned int interval = array_uint16_le (data + 4); unsigned int maxdepth = 0; unsigned int nsamples = 0; unsigned int offset = 10; while (offset + sizeof (footer) <= size && memcmp (data + offset, footer, sizeof (footer)) != 0) { unsigned int value = array_uint16_le (data + offset); unsigned int depth = (value & 0x01FF); if (depth > maxdepth) maxdepth = depth; nsamples++; offset += 2; } parser->cached = 1; parser->divetime = nsamples * interval; parser->maxdepth = maxdepth; } if (value) { switch (type) { case DC_FIELD_DIVETIME: *((unsigned int *) value) = parser->divetime; break; case DC_FIELD_MAXDEPTH: *((double *) value) = (parser->maxdepth * FSW - parser->atmospheric) / parser->hydrostatic; break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = 0; break; case DC_FIELD_DIVEMODE: *((dc_divemode_t *) value) = DC_DIVEMODE_GAUGE; break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensuspro_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { reefnet_sensuspro_parser_t *parser = (reefnet_sensuspro_parser_t*) abstract; const unsigned char header[4] = {0x00, 0x00, 0x00, 0x00}; const unsigned char footer[2] = {0xFF, 0xFF}; const unsigned char *data = abstract->data; unsigned int size = abstract->size; unsigned int offset = 0; while (offset + sizeof (header) <= size) { if (memcmp (data + offset, header, sizeof (header)) == 0) { if (offset + 10 > size) return DC_STATUS_DATAFORMAT; unsigned int time = 0; unsigned int interval = array_uint16_le (data + offset + 4); offset += 10; while (offset + sizeof (footer) <= size && memcmp (data + offset, footer, sizeof (footer)) != 0) { unsigned int value = array_uint16_le (data + offset); unsigned int depth = (value & 0x01FF); unsigned int temperature = (value & 0xFE00) >> 9; dc_sample_value_t sample = {0}; // Time (seconds) time += interval; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Temperature (°F) sample.temperature = (temperature - 32.0) * (5.0 / 9.0); if (callback) callback (DC_SAMPLE_TEMPERATURE, sample, userdata); // Depth (absolute pressure in fsw) sample.depth = (depth * FSW - parser->atmospheric) / parser->hydrostatic; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); offset += 2; } break; } else { offset++; } } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/reefnet_sensuspro_parser.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcmp, memcpy #include <stdlib.h> // malloc, free #include <assert.h> // assert #include "suunto_vyper.h" #include "suunto_common.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "checksum.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &suunto_vyper_device_vtable) #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #define MAX(a,b) (((a) > (b)) ? (a) : (b)) #define SZ_MEMORY 0x2000 #define SZ_PACKET 32 #define HDR_DEVINFO_VYPER 0x24 #define HDR_DEVINFO_SPYDER 0x16 #define HDR_DEVINFO_BEGIN (HDR_DEVINFO_SPYDER) #define HDR_DEVINFO_END (HDR_DEVINFO_VYPER + 6) typedef struct suunto_vyper_device_t { suunto_common_device_t base; dc_iostream_t *iostream; } suunto_vyper_device_t; static dc_status_t suunto_vyper_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size); static dc_status_t suunto_vyper_device_write (dc_device_t *abstract, unsigned int address, const unsigned char data[], unsigned int size); static dc_status_t suunto_vyper_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t suunto_vyper_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t suunto_vyper_device_close (dc_device_t *abstract); static const dc_device_vtable_t suunto_vyper_device_vtable = { sizeof(suunto_vyper_device_t), DC_FAMILY_SUUNTO_VYPER, suunto_common_device_set_fingerprint, /* set_fingerprint */ suunto_vyper_device_read, /* read */ suunto_vyper_device_write, /* write */ suunto_vyper_device_dump, /* dump */ suunto_vyper_device_foreach, /* foreach */ NULL, /* timesync */ suunto_vyper_device_close /* close */ }; static const suunto_common_layout_t suunto_vyper_layout = { 0x51, /* eop */ 0x71, /* rb_profile_begin */ SZ_MEMORY, /* rb_profile_end */ 9, /* fp_offset */ 5 /* peek */ }; static const suunto_common_layout_t suunto_spyder_layout = { 0x1C, /* eop */ 0x4C, /* rb_profile_begin */ SZ_MEMORY, /* rb_profile_end */ 6, /* fp_offset */ 3 /* peek */ }; dc_status_t suunto_vyper_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; suunto_vyper_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (suunto_vyper_device_t *) dc_device_allocate (context, &suunto_vyper_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Initialize the base class. suunto_common_device_init (&device->base); // Set the default values. device->iostream = NULL; // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (2400 8O1). status = dc_iostream_configure (device->iostream, 2400, 8, DC_PARITY_ODD, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (1000 ms). status = dc_iostream_set_timeout (device->iostream, 1000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Set the DTR line (power supply for the interface). status = dc_iostream_set_dtr (device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the DTR line."); goto error_close; } // Give the interface 100 ms to settle and draw power up. dc_iostream_sleep (device->iostream, 100); // Make sure everything is in a sane state. dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t suunto_vyper_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; suunto_vyper_device_t *device = (suunto_vyper_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t suunto_vyper_send (suunto_vyper_device_t *device, const unsigned char command[], unsigned int csize) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; dc_iostream_sleep (device->iostream, 500); // Set RTS to send the command. status = dc_iostream_set_rts (device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to set RTS."); return status; } // Send the command to the dive computer. status = dc_iostream_write (device->iostream, command, csize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // If the interface sends an echo back (which is the case for many clone // interfaces), this echo should be removed from the input queue before // attempting to read the real reply from the dive computer. Otherwise, // the data transfer will fail. Timing is also critical here! We have to // wait at least until the echo appears (40ms), but not until the reply // from the dive computer appears (600ms). // The original suunto interface does not have this problem, because it // does not send an echo and the RTS switching makes it impossible to // receive the reply before RTS is cleared. We have to wait some time // before clearing RTS (around 30ms). But if we wait too long (> 500ms), // the reply disappears again. dc_iostream_sleep (device->iostream, 200); dc_iostream_purge (device->iostream, DC_DIRECTION_INPUT); // Clear RTS to receive the reply. status = dc_iostream_set_rts (device->iostream, 0); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to clear RTS."); return status; } return DC_STATUS_SUCCESS; } static dc_status_t suunto_vyper_transfer (suunto_vyper_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize, unsigned int size) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; assert (asize >= size + 2); if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; // Send the command to the dive computer. dc_status_t rc = suunto_vyper_send (device, command, csize); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return rc; } // Receive the answer of the dive computer. status = dc_iostream_read (device->iostream, answer, asize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Verify the header of the package. if (memcmp (command, answer, asize - size - 1) != 0) { ERROR (abstract->context, "Unexpected answer start byte(s)."); return DC_STATUS_PROTOCOL; } // Verify the checksum of the package. unsigned char crc = answer[asize - 1]; unsigned char ccrc = checksum_xor_uint8 (answer, asize - 1, 0x00); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } static dc_status_t suunto_vyper_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size) { suunto_vyper_device_t *device = (suunto_vyper_device_t*) abstract; unsigned int nbytes = 0; while (nbytes < size) { // Calculate the package size. unsigned int len = MIN (size - nbytes, SZ_PACKET); // Read the package. unsigned char answer[SZ_PACKET + 5] = {0}; unsigned char command[5] = {0x05, (address >> 8) & 0xFF, // high (address ) & 0xFF, // low len, // count 0}; // CRC command[4] = checksum_xor_uint8 (command, 4, 0x00); dc_status_t rc = suunto_vyper_transfer (device, command, sizeof (command), answer, len + 5, len); if (rc != DC_STATUS_SUCCESS) return rc; memcpy (data, answer + 4, len); nbytes += len; address += len; data += len; } return DC_STATUS_SUCCESS; } static dc_status_t suunto_vyper_device_write (dc_device_t *abstract, unsigned int address, const unsigned char data[], unsigned int size) { suunto_vyper_device_t *device = (suunto_vyper_device_t*) abstract; unsigned int nbytes = 0; while (nbytes < size) { // Calculate the package size. unsigned int len = MIN (size - nbytes, SZ_PACKET); // Prepare to write the package. unsigned char panswer[3] = {0}; unsigned char pcommand[3] = {0x07, 0xA5, 0xA2}; dc_status_t rc = suunto_vyper_transfer (device, pcommand, sizeof (pcommand), panswer, sizeof (panswer), 0); if (rc != DC_STATUS_SUCCESS) return rc; // Write the package. unsigned char wanswer[5] = {0}; unsigned char wcommand[SZ_PACKET + 5] = {0x06, (address >> 8) & 0xFF, // high (address ) & 0xFF, // low len, // count 0}; // data + CRC memcpy (wcommand + 4, data, len); wcommand[len + 4] = checksum_xor_uint8 (wcommand, len + 4, 0x00); rc = suunto_vyper_transfer (device, wcommand, len + 5, wanswer, sizeof (wanswer), 0); if (rc != DC_STATUS_SUCCESS) return rc; nbytes += len; address += len; data += len; } return DC_STATUS_SUCCESS; } static dc_status_t suunto_vyper_read_dive (dc_device_t *abstract, dc_buffer_t *buffer, int init, dc_event_progress_t *progress) { dc_status_t status = DC_STATUS_SUCCESS; suunto_vyper_device_t *device = (suunto_vyper_device_t*) abstract; if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; // Erase the current contents of the buffer. if (!dc_buffer_clear (buffer)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Send the command to the dive computer. unsigned char command[3] = {init ? 0x08 : 0x09, 0xA5, 0x00}; command[2] = checksum_xor_uint8 (command, 2, 0x00); dc_status_t rc = suunto_vyper_send (device, command, 3); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return rc; } unsigned int nbytes = 0; for (unsigned int npackages = 0;; ++npackages) { // Receive the header of the package. size_t n = 0; unsigned char answer[SZ_PACKET + 3] = {0}; status = dc_iostream_read (device->iostream, answer, 2, &n); if (status != DC_STATUS_SUCCESS) { // If no data is received because a timeout occured, we assume // the last package was already received and the transmission // can be finished. Unfortunately this is not 100% reliable, // because there is always a small chance that more data will // arrive later (especially with a short timeout). But it works // good enough in practice. // Only for the very first package, we can be sure there was // an error, because the DC always sends at least one package. if (n == 0 && npackages != 0) break; ERROR (abstract->context, "Failed to receive the answer."); return status; } // Verify the header of the package. if (answer[0] != command[0] || answer[1] > SZ_PACKET) { ERROR (abstract->context, "Unexpected answer start byte(s)."); return DC_STATUS_PROTOCOL; } // Receive the remaining part of the package. unsigned char len = answer[1]; status = dc_iostream_read (device->iostream, answer + 2, len + 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Verify the checksum of the package. unsigned char crc = answer[len + 2]; unsigned char ccrc = checksum_xor_uint8 (answer, len + 2, 0x00); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } // The DC sends a null package (a package with length zero) when it // has reached the end of its internal ring buffer. From this point on, // the current dive has been overwritten with newer data. Therefore, // we discard the current (incomplete) dive and end the transmission. if (len == 0) { dc_buffer_clear (buffer); return DC_STATUS_SUCCESS; } // Update and emit a progress event. if (progress) { progress->current += len; if (progress->current > progress->maximum) progress->current = progress->maximum; device_event_emit (abstract, DC_EVENT_PROGRESS, progress); } // Append the package to the output buffer. // Reporting of buffer errors is delayed until the entire // transfer is finished. This approach leaves no data behind in // the serial receive buffer, and if this packet is part of the // last incomplete dive, no error has to be reported at all. dc_buffer_append (buffer, answer + 2, len); nbytes += len; // If a package is smaller than $SZ_PACKET bytes, // we assume it's the last packet and the transmission can be // finished early. However, this approach does not work if the // last packet is exactly $SZ_PACKET bytes long! #if 0 if (len != SZ_PACKET) break; #endif } // Check for a buffer error. if (dc_buffer_get_size (buffer) != nbytes) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // The DC traverses its internal ring buffer backwards. The most recent // dive is send first (which allows you to download only the new dives), // but also the contents of each dive is reversed. Therefore, we reverse // the bytes again before returning them to the application. array_reverse_bytes (dc_buffer_get_data (buffer), dc_buffer_get_size (buffer)); return DC_STATUS_SUCCESS; } static dc_status_t suunto_vyper_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { // Allocate the required amount of memory. if (!dc_buffer_resize (buffer, SZ_MEMORY)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } return device_dump_read (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), SZ_PACKET); } static dc_status_t suunto_vyper_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { suunto_common_device_t *device = (suunto_common_device_t*) abstract; // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = SZ_MEMORY; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Read the device info. The Vyper and the Spyder store this data // in a different location. To minimize the number of (slow) reads, // we read a larger block of memory that always contains the data // for both devices. unsigned char header[HDR_DEVINFO_END - HDR_DEVINFO_BEGIN] = {0}; dc_status_t rc = suunto_vyper_device_read (abstract, HDR_DEVINFO_BEGIN, header, sizeof (header)); if (rc != DC_STATUS_SUCCESS) return rc; // Identify the connected device as a Vyper or a Spyder, by inspecting // the Vyper model code. For a Spyder, this value will contain the // sample interval (20, 30 or 60s) instead of the model code. unsigned int hoffset = HDR_DEVINFO_VYPER - HDR_DEVINFO_BEGIN; const suunto_common_layout_t *layout = &suunto_vyper_layout; if (header[hoffset] == 20 || header[hoffset] == 30 || header[hoffset] == 60) { hoffset = HDR_DEVINFO_SPYDER - HDR_DEVINFO_BEGIN; layout = &suunto_spyder_layout; } // Update and emit a progress event. progress.maximum = sizeof (header) + (layout->rb_profile_end - layout->rb_profile_begin); progress.current += sizeof (header); device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Emit a device info event. dc_event_devinfo_t devinfo; devinfo.model = header[hoffset + 0]; devinfo.firmware = header[hoffset + 1]; devinfo.serial = 0; for (unsigned int i = 0; i < 4; ++i) { devinfo.serial *= 100; devinfo.serial += header[hoffset + 2 + i]; } device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); // Allocate a memory buffer. dc_buffer_t *buffer = dc_buffer_new (layout->rb_profile_end - layout->rb_profile_begin); if (buffer == NULL) return DC_STATUS_NOMEMORY; unsigned int ndives = 0; unsigned int remaining = layout->rb_profile_end - layout->rb_profile_begin; while ((rc = suunto_vyper_read_dive (abstract, buffer, (ndives == 0), &progress)) == DC_STATUS_SUCCESS) { unsigned char *data = dc_buffer_get_data (buffer); unsigned int size = dc_buffer_get_size (buffer); if (size > remaining) { ERROR (abstract->context, "Unexpected number of bytes received."); dc_buffer_free (buffer); return DC_STATUS_DATAFORMAT; } if (size == 0) { dc_buffer_free (buffer); return DC_STATUS_SUCCESS; } if (memcmp (data + layout->fp_offset, device->fingerprint, sizeof (device->fingerprint)) == 0) { dc_buffer_free (buffer); return DC_STATUS_SUCCESS; } if (callback && !callback (data, size, data + layout->fp_offset, sizeof (device->fingerprint), userdata)) { dc_buffer_free (buffer); return DC_STATUS_SUCCESS; } remaining -= size; ndives++; } dc_buffer_free (buffer); return rc; }
libdc-for-dirk-Subsurface-branch
src/suunto_vyper.c
/* * libdivecomputer * * Copyright (C) 2013 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcmp, memcpy #include <stdlib.h> // malloc, free #include "shearwater_petrel.h" #include "shearwater_common.h" #include "context-private.h" #include "device-private.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &shearwater_petrel_device_vtable) #define MANIFEST_ADDR 0xE0000000 #define MANIFEST_SIZE 0x600 #define DIVE_ADDR 0xC0000000 #define DIVE_SIZE 0xFFFFFF #define RECORD_SIZE 0x20 #define RECORD_COUNT (MANIFEST_SIZE / RECORD_SIZE) typedef struct shearwater_petrel_device_t { shearwater_common_device_t base; unsigned char fingerprint[4]; } shearwater_petrel_device_t; static dc_status_t shearwater_petrel_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t shearwater_petrel_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t shearwater_petrel_device_close (dc_device_t *abstract); static const dc_device_vtable_t shearwater_petrel_device_vtable = { sizeof(shearwater_petrel_device_t), DC_FAMILY_SHEARWATER_PETREL, shearwater_petrel_device_set_fingerprint, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ NULL, /* dump */ shearwater_petrel_device_foreach, /* foreach */ NULL, /* timesync */ shearwater_petrel_device_close /* close */ }; static unsigned int str2num (unsigned char data[], unsigned int size, unsigned int offset) { unsigned int value = 0; for (unsigned int i = offset; i < size; ++i) { if (data[i] < '0' || data[i] > '9') break; value *= 10; value += data[i] - '0'; } return value; } dc_status_t shearwater_petrel_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; shearwater_petrel_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (shearwater_petrel_device_t *) dc_device_allocate (context, &shearwater_petrel_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. memset (device->fingerprint, 0, sizeof (device->fingerprint)); // Open the device. status = shearwater_common_open (&device->base, context, name); if (status != DC_STATUS_SUCCESS) { goto error_free; } *out = (dc_device_t *) device; return DC_STATUS_SUCCESS; error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t shearwater_petrel_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; shearwater_common_device_t *device = (shearwater_common_device_t *) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Shutdown the device. unsigned char request[] = {0x2E, 0x90, 0x20, 0x00}; rc = shearwater_common_transfer (device, request, sizeof (request), NULL, 0, NULL); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } // Close the device. rc = shearwater_common_close (device); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t shearwater_petrel_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { shearwater_petrel_device_t *device = (shearwater_petrel_device_t *) abstract; if (size && size != sizeof (device->fingerprint)) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, sizeof (device->fingerprint)); else memset (device->fingerprint, 0, sizeof (device->fingerprint)); return DC_STATUS_SUCCESS; } static dc_status_t shearwater_petrel_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { shearwater_petrel_device_t *device = (shearwater_petrel_device_t *) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Allocate memory buffers for the manifests. dc_buffer_t *buffer = dc_buffer_new (MANIFEST_SIZE); dc_buffer_t *manifests = dc_buffer_new (MANIFEST_SIZE); if (buffer == NULL || manifests == NULL) { ERROR (abstract->context, "Insufficient buffer space available."); dc_buffer_free (buffer); dc_buffer_free (manifests); return DC_STATUS_NOMEMORY; } // Enable progress notifications. unsigned int current = 0, maximum = 0; dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Read the serial number. rc = shearwater_common_identifier (&device->base, buffer, ID_SERIAL); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the serial number."); dc_buffer_free (buffer); dc_buffer_free (manifests); return rc; } // Convert to a number. unsigned char serial[4] = {0}; if (array_convert_hex2bin (dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), serial, sizeof (serial)) != 0 ) { ERROR (abstract->context, "Failed to convert the serial number."); dc_buffer_free (buffer); dc_buffer_free (manifests); return DC_STATUS_DATAFORMAT; } // Read the firmware version. rc = shearwater_common_identifier (&device->base, buffer, ID_FIRMWARE); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the firmware version."); dc_buffer_free (buffer); dc_buffer_free (manifests); return rc; } // Convert to a number. unsigned int firmware = str2num (dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), 1); // Read the hardware type. rc = shearwater_common_identifier (&device->base, buffer, ID_HARDWARE); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the hardware type."); dc_buffer_free (buffer); dc_buffer_free (manifests); return rc; } // Convert and map to the model number. unsigned int hardware = array_uint_be (dc_buffer_get_data (buffer), dc_buffer_get_size (buffer)); unsigned int model = 0; switch (hardware) { case 0x0101: case 0x0202: model = PREDATOR; break; case 0x0606: case 0x0A0A: // Nerd 1 model = NERD; break; case 0x0E0D: // Nerd 2 model = NERD2; break; case 0x0404: case 0x0909: // Petrel 1 case 0x0B0B: // Petrel 1 (newer hardware) model = PETREL; break; case 0x0505: case 0x0808: // Petrel 2 model = PETREL; break; case 0x0707: // documentation list 0C0D for both Perdix and Perdix AI :-( model = PERDIX; break; case 0x0C0C: case 0x0C0D: case 0x0D0D: model = PERDIXAI; break; default: model = PETREL; WARNING (abstract->context, "Unknown hardware type %04x. Assuming Petrel.", hardware); } // Emit a device info event. dc_event_devinfo_t devinfo; devinfo.model = model; devinfo.firmware = firmware; devinfo.serial = array_uint32_be (serial); device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); while (1) { // Update the progress state. // Assume the worst case scenario of a full manifest, and adjust the // value with the actual number of dives after the manifest has been // processed. maximum += 1 + RECORD_COUNT; // Download a manifest. progress.current = NSTEPS * current; progress.maximum = NSTEPS * maximum; rc = shearwater_common_download (&device->base, buffer, MANIFEST_ADDR, MANIFEST_SIZE, 0, &progress); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to download the manifest."); dc_buffer_free (buffer); dc_buffer_free (manifests); return rc; } // Cache the buffer pointer and size. unsigned char *data = dc_buffer_get_data (buffer); unsigned int size = dc_buffer_get_size (buffer); // Process the records in the manifest. unsigned int count = 0; unsigned int offset = 0; while (offset < size) { // Check for a valid dive header. unsigned int header = array_uint16_be (data + offset); if (header != 0xA5C4) break; // Check the fingerprint data. if (memcmp (data + offset + 4, device->fingerprint, sizeof (device->fingerprint)) == 0) break; offset += RECORD_SIZE; count++; } // Update the progress state. current += 1; maximum -= RECORD_COUNT - count; // Append the manifest records to the main buffer. if (!dc_buffer_append (manifests, data, count * RECORD_SIZE)) { ERROR (abstract->context, "Insufficient buffer space available."); dc_buffer_free (buffer); dc_buffer_free (manifests); return DC_STATUS_NOMEMORY; } // Stop downloading manifest if there are no more records. if (count != RECORD_COUNT) break; } // Update and emit a progress event. progress.current = NSTEPS * current; progress.maximum = NSTEPS * maximum; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Cache the buffer pointer and size. unsigned char *data = dc_buffer_get_data (manifests); unsigned int size = dc_buffer_get_size (manifests); unsigned int offset = 0; while (offset < size) { // Get the address of the dive. unsigned int address = array_uint32_be (data + offset + 20); // Download the dive. progress.current = NSTEPS * current; progress.maximum = NSTEPS * maximum; rc = shearwater_common_download (&device->base, buffer, DIVE_ADDR + address, DIVE_SIZE, 1, &progress); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to download the dive."); dc_buffer_free (buffer); dc_buffer_free (manifests); return rc; } // Update the progress state. current += 1; unsigned char *buf = dc_buffer_get_data (buffer); unsigned int len = dc_buffer_get_size (buffer); if (callback && !callback (buf, len, buf + 12, sizeof (device->fingerprint), userdata)) break; offset += RECORD_SIZE; } // Update and emit a progress event. progress.current = NSTEPS * current; progress.maximum = NSTEPS * maximum; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); dc_buffer_free (manifests); dc_buffer_free (buffer); return rc; }
libdc-for-dirk-Subsurface-branch
src/shearwater_petrel.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcpy #include <stdlib.h> // malloc, free #include "oceanic_veo250.h" #include "oceanic_common.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "ringbuffer.h" #include "checksum.h" #define ISINSTANCE(device) dc_device_isinstance((device), &oceanic_veo250_device_vtable.base) #define MAXRETRIES 2 #define MULTIPAGE 4 #define ACK 0x5A #define NAK 0xA5 typedef struct oceanic_veo250_device_t { oceanic_common_device_t base; dc_iostream_t *iostream; unsigned int last; } oceanic_veo250_device_t; static dc_status_t oceanic_veo250_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size); static dc_status_t oceanic_veo250_device_close (dc_device_t *abstract); static const oceanic_common_device_vtable_t oceanic_veo250_device_vtable = { { sizeof(oceanic_veo250_device_t), DC_FAMILY_OCEANIC_VEO250, oceanic_common_device_set_fingerprint, /* set_fingerprint */ oceanic_veo250_device_read, /* read */ NULL, /* write */ oceanic_common_device_dump, /* dump */ oceanic_common_device_foreach, /* foreach */ NULL, /* timesync */ oceanic_veo250_device_close /* close */ }, oceanic_common_device_logbook, oceanic_common_device_profile, }; static const oceanic_common_version_t oceanic_veo250_version[] = { {"GENREACT \0\0 256K"}, {"VEO 200 R\0\0 256K"}, {"VEO 250 R\0\0 256K"}, {"SEEMANN R\0\0 256K"}, {"VEO 180 R\0\0 256K"}, {"AERISXR2 \0\0 256K"}, {"INSIGHT R\0\0 256K"}, {"HO DGO2 R\0\0 256K"}, }; static const oceanic_common_layout_t oceanic_veo250_layout = { 0x8000, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x0400, /* rb_logbook_begin */ 0x0600, /* rb_logbook_end */ 8, /* rb_logbook_entry_size */ 0x0600, /* rb_profile_begin */ 0x8000, /* rb_profile_end */ 1, /* pt_mode_global */ 1, /* pt_mode_logbook */ 1, /* pt_mode_serial */ }; static dc_status_t oceanic_veo250_send (oceanic_veo250_device_t *device, const unsigned char command[], unsigned int csize) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; // Discard garbage bytes. dc_iostream_purge (device->iostream, DC_DIRECTION_INPUT); // Send the command to the dive computer. status = dc_iostream_write (device->iostream, command, csize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Receive the response (ACK/NAK) of the dive computer. unsigned char response = NAK; status = dc_iostream_read (device->iostream, &response, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Verify the response of the dive computer. if (response != ACK) { ERROR (abstract->context, "Unexpected answer start byte(s)."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } static dc_status_t oceanic_veo250_transfer (oceanic_veo250_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; // Send the command to the device. If the device responds with an // ACK byte, the command was received successfully and the answer // (if any) follows after the ACK byte. If the device responds with // a NAK byte, we try to resend the command a number of times before // returning an error. unsigned int nretries = 0; dc_status_t rc = DC_STATUS_SUCCESS; while ((rc = oceanic_veo250_send (device, command, csize)) != DC_STATUS_SUCCESS) { if (rc != DC_STATUS_TIMEOUT && rc != DC_STATUS_PROTOCOL) return rc; // Abort if the maximum number of retries is reached. if (nretries++ >= MAXRETRIES) return rc; // Delay the next attempt. dc_iostream_sleep (device->iostream, 100); } // Receive the answer of the dive computer. status = dc_iostream_read (device->iostream, answer, asize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Verify the last byte of the answer. if (answer[asize - 1] != NAK) { ERROR (abstract->context, "Unexpected answer byte."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } static dc_status_t oceanic_veo250_init (oceanic_veo250_device_t *device) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; // Send the command to the dive computer. unsigned char command[2] = {0x55, 0x00}; status = dc_iostream_write (device->iostream, command, sizeof (command), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Receive the answer of the dive computer. size_t n = 0; unsigned char answer[13] = {0}; status = dc_iostream_read (device->iostream, answer, sizeof (answer), &n); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); if (n == 0) return DC_STATUS_SUCCESS; return status; } // Verify the answer. const unsigned char response[13] = { 0x50, 0x50, 0x53, 0x2D, 0x2D, 0x4F, 0x4B, 0x5F, 0x56, 0x32, 0x2E, 0x30, 0x30}; if (memcmp (answer, response, sizeof (response)) != 0) { ERROR (abstract->context, "Unexpected answer byte(s)."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } static dc_status_t oceanic_veo250_quit (oceanic_veo250_device_t *device) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; // Send the command to the dive computer. unsigned char command[2] = {0x98, 0x00}; status = dc_iostream_write (device->iostream, command, sizeof (command), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } return DC_STATUS_SUCCESS; } dc_status_t oceanic_veo250_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; oceanic_veo250_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (oceanic_veo250_device_t *) dc_device_allocate (context, &oceanic_veo250_device_vtable.base); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Initialize the base class. oceanic_common_device_init (&device->base); // Override the base class values. device->base.multipage = MULTIPAGE; // Set the default values. device->iostream = NULL; device->last = 0; // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (9600 8N1). status = dc_iostream_configure (device->iostream, 9600, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (3000 ms). status = dc_iostream_set_timeout (device->iostream, 3000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Set the DTR line. status = dc_iostream_set_dtr (device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the DTR line."); goto error_close; } // Set the RTS line. status = dc_iostream_set_rts (device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the RTS line."); goto error_close; } // Give the interface 100 ms to settle and draw power up. dc_iostream_sleep (device->iostream, 100); // Make sure everything is in a sane state. dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); // Initialize the data cable (PPS mode). status = oceanic_veo250_init (device); if (status != DC_STATUS_SUCCESS) { goto error_close; } // Delay the sending of the version command. dc_iostream_sleep (device->iostream, 100); // Switch the device from surface mode into download mode. Before sending // this command, the device needs to be in PC mode (manually activated by // the user), or already in download mode. status = oceanic_veo250_device_version ((dc_device_t *) device, device->base.version, sizeof (device->base.version)); if (status != DC_STATUS_SUCCESS) { goto error_close; } // Override the base class values. if (OCEANIC_COMMON_MATCH (device->base.version, oceanic_veo250_version)) { device->base.layout = &oceanic_veo250_layout; } else { WARNING (context, "Unsupported device detected!"); device->base.layout = &oceanic_veo250_layout; } *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t oceanic_veo250_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; oceanic_veo250_device_t *device = (oceanic_veo250_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Switch the device back to surface mode. rc = oceanic_veo250_quit (device); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } dc_status_t oceanic_veo250_device_keepalive (dc_device_t *abstract) { oceanic_veo250_device_t *device = (oceanic_veo250_device_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; unsigned char answer[2] = {0}; unsigned char command[4] = {0x91, (device->last ) & 0xFF, // low (device->last >> 8) & 0xFF, // high 0x00}; dc_status_t rc = oceanic_veo250_transfer (device, command, sizeof (command), answer, sizeof (answer)); if (rc != DC_STATUS_SUCCESS) return rc; // Verify the answer. if (answer[0] != NAK) { ERROR (abstract->context, "Unexpected answer byte(s)."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } dc_status_t oceanic_veo250_device_version (dc_device_t *abstract, unsigned char data[], unsigned int size) { oceanic_veo250_device_t *device = (oceanic_veo250_device_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size < PAGESIZE) return DC_STATUS_INVALIDARGS; unsigned char answer[PAGESIZE + 2] = {0}; unsigned char command[2] = {0x90, 0x00}; dc_status_t rc = oceanic_veo250_transfer (device, command, sizeof (command), answer, sizeof (answer)); if (rc != DC_STATUS_SUCCESS) return rc; // Verify the checksum of the answer. unsigned char crc = answer[PAGESIZE]; unsigned char ccrc = checksum_add_uint8 (answer, PAGESIZE, 0x00); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } memcpy (data, answer, PAGESIZE); return DC_STATUS_SUCCESS; } static dc_status_t oceanic_veo250_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size) { oceanic_veo250_device_t *device = (oceanic_veo250_device_t*) abstract; if ((address % PAGESIZE != 0) || (size % PAGESIZE != 0)) return DC_STATUS_INVALIDARGS; unsigned int nbytes = 0; while (nbytes < size) { // Calculate the number of packages. unsigned int npackets = (size - nbytes) / PAGESIZE; if (npackets > MULTIPAGE) npackets = MULTIPAGE; // Read the package. unsigned int first = address / PAGESIZE; unsigned int last = first + npackets - 1; unsigned char answer[(PAGESIZE + 1) * MULTIPAGE + 1] = {0}; unsigned char command[6] = {0x20, (first ) & 0xFF, // low (first >> 8) & 0xFF, // high (last ) & 0xFF, // low (last >> 8) & 0xFF, // high 0}; dc_status_t rc = oceanic_veo250_transfer (device, command, sizeof (command), answer, (PAGESIZE + 1) * npackets + 1); if (rc != DC_STATUS_SUCCESS) return rc; device->last = last; unsigned int offset = 0; for (unsigned int i = 0; i < npackets; ++i) { // Verify the checksum of the answer. unsigned char crc = answer[offset + PAGESIZE]; unsigned char ccrc = checksum_add_uint8 (answer + offset, PAGESIZE, 0x00); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } memcpy (data, answer + offset, PAGESIZE); offset += PAGESIZE + 1; nbytes += PAGESIZE; address += PAGESIZE; data += PAGESIZE; } } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/oceanic_veo250.c
/* * libdivecomputer * * Copyright (C) 2010 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include "cressi_edy.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_parser_isinstance((parser), &cressi_edy_parser_vtable) #define IQ700 0x05 #define EDY 0x08 typedef struct cressi_edy_parser_t cressi_edy_parser_t; struct cressi_edy_parser_t { dc_parser_t base; unsigned int model; }; static dc_status_t cressi_edy_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t cressi_edy_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t cressi_edy_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t cressi_edy_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t cressi_edy_parser_vtable = { sizeof(cressi_edy_parser_t), DC_FAMILY_CRESSI_EDY, cressi_edy_parser_set_data, /* set_data */ cressi_edy_parser_get_datetime, /* datetime */ cressi_edy_parser_get_field, /* fields */ cressi_edy_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; static unsigned int cressi_edy_parser_count_gasmixes (const unsigned char *data) { // Count the number of active gas mixes. The active gas // mixes are always first, so we stop counting as soon // as the first gas marked as disabled is found. unsigned int i = 0; while (i < 3) { if (data[0x17 - i] == 0xF0) break; i++; } return i; } dc_status_t cressi_edy_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int model) { cressi_edy_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (cressi_edy_parser_t *) dc_parser_allocate (context, &cressi_edy_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. parser->model = model; *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; } static dc_status_t cressi_edy_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { return DC_STATUS_SUCCESS; } static dc_status_t cressi_edy_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { if (abstract->size < 32) return DC_STATUS_DATAFORMAT; const unsigned char *p = abstract->data; if (datetime) { datetime->year = bcd2dec (p[4]) + 2000; datetime->month = (p[5] & 0xF0) >> 4; datetime->day = (p[5] & 0x0F) * 10 + ((p[6] & 0xF0) >> 4); datetime->hour = bcd2dec (p[14]); datetime->minute = bcd2dec (p[15]); datetime->second = 0; datetime->timezone = DC_TIMEZONE_NONE; } return DC_STATUS_SUCCESS; } static dc_status_t cressi_edy_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { cressi_edy_parser_t *parser = (cressi_edy_parser_t *) abstract; if (abstract->size < 32) return DC_STATUS_DATAFORMAT; const unsigned char *p = abstract->data; dc_gasmix_t *gasmix = (dc_gasmix_t *) value; if (value) { switch (type) { case DC_FIELD_DIVETIME: if (parser->model == EDY) *((unsigned int *) value) = bcd2dec (p[0x0C] & 0x0F) * 60 + bcd2dec (p[0x0D]); else *((unsigned int *) value) = (bcd2dec (p[0x0C] & 0x0F) * 100 + bcd2dec (p[0x0D])) * 60; break; case DC_FIELD_MAXDEPTH: *((double *) value) = (bcd2dec (p[0x02] & 0x0F) * 100 + bcd2dec (p[0x03])) / 10.0; break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = cressi_edy_parser_count_gasmixes(p); break; case DC_FIELD_GASMIX: gasmix->helium = 0.0; gasmix->oxygen = bcd2dec (p[0x17 - flags]) / 100.0; gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium; break; case DC_FIELD_TEMPERATURE_MINIMUM: *((double *) value) = (bcd2dec (p[0x0B]) * 100 + bcd2dec (p[0x0C])) / 100.0; break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t cressi_edy_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { cressi_edy_parser_t *parser = (cressi_edy_parser_t *) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; unsigned int time = 0; unsigned int interval = 30; if (parser->model == EDY) { interval = 1; } else if (parser->model == IQ700) { if (data[0x07] & 0x40) interval = 15; } unsigned int ngasmixes = cressi_edy_parser_count_gasmixes(data); unsigned int gasmix = 0xFFFFFFFF; unsigned int offset = 32; while (offset + 2 <= size) { dc_sample_value_t sample = {0}; if (data[offset] == 0xFF) break; unsigned int extra = 0; if (data[offset] & 0x80) extra = 4; // Time (seconds). time += interval; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Depth (1/10 m). unsigned int depth = bcd2dec (data[offset + 0] & 0x0F) * 100 + bcd2dec (data[offset + 1]); sample.depth = depth / 10.0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); // Current gasmix if (ngasmixes) { unsigned int idx = (data[offset + 0] & 0x60) >> 5; if (parser->model == IQ700) idx = 0; /* FIXME */ if (idx >= ngasmixes) { ERROR (abstract->context, "Invalid gas mix index."); return DC_STATUS_DATAFORMAT; } if (idx != gasmix) { sample.gasmix = idx; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); gasmix = idx; } } offset += 2 + extra; } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/cressi_edy_parser.c
/* * libdivecomputer * * Copyright (C) 2010 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <libdivecomputer/units.h> #include "mares_iconhd.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_parser_isinstance((parser), &mares_iconhd_parser_vtable) #define SMART 0x000010 #define SMARTAPNEA 0x010010 #define ICONHD 0x14 #define ICONHDNET 0x15 #define QUADAIR 0x23 #define NGASMIXES 3 #define NTANKS NGASMIXES #define AIR 0 #define GAUGE 1 #define NITROX 2 #define FREEDIVE 3 typedef struct mares_iconhd_parser_t mares_iconhd_parser_t; struct mares_iconhd_parser_t { dc_parser_t base; unsigned int model; // Cached fields. unsigned int cached; unsigned int mode; unsigned int nsamples; unsigned int footer; unsigned int samplesize; unsigned int settings; unsigned int interval; unsigned int samplerate; unsigned int ntanks; unsigned int ngasmixes; unsigned int oxygen[NGASMIXES]; }; static dc_status_t mares_iconhd_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t mares_iconhd_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t mares_iconhd_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t mares_iconhd_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t mares_iconhd_parser_vtable = { sizeof(mares_iconhd_parser_t), DC_FAMILY_MARES_ICONHD, mares_iconhd_parser_set_data, /* set_data */ mares_iconhd_parser_get_datetime, /* datetime */ mares_iconhd_parser_get_field, /* fields */ mares_iconhd_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; static dc_status_t mares_iconhd_parser_cache (mares_iconhd_parser_t *parser) { dc_parser_t *abstract = (dc_parser_t *) parser; const unsigned char *data = parser->base.data; unsigned int size = parser->base.size; if (parser->cached) { return DC_STATUS_SUCCESS; } unsigned int header = 0x5C; if (parser->model == ICONHDNET) header = 0x80; else if (parser->model == QUADAIR) header = 0x84; else if (parser->model == SMART) header = 4; // Type and number of samples only! else if (parser->model == SMARTAPNEA) header = 6; // Type and number of samples only! if (size < header + 4) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } unsigned int length = array_uint32_le (data); if (length > size) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } // Get the number of samples in the profile data. unsigned int type = 0, nsamples = 0; if (parser->model == SMART || parser->model == SMARTAPNEA) { type = array_uint16_le (data + length - header + 2); nsamples = array_uint16_le (data + length - header + 0); } else { type = array_uint16_le (data + length - header + 0); nsamples = array_uint16_le (data + length - header + 2); } // Get the dive mode. unsigned int mode = type & 0x03; // Get the header and sample size. unsigned int headersize = 0x5C; unsigned int samplesize = 8; if (parser->model == ICONHDNET) { headersize = 0x80; samplesize = 12; } else if (parser->model == QUADAIR) { headersize = 0x84; samplesize = 12; } else if (parser->model == SMART) { if (mode == FREEDIVE) { headersize = 0x2E; samplesize = 6; } else { headersize = 0x5C; samplesize = 8; } } else if (parser->model == SMARTAPNEA) { headersize = 0x50; samplesize = 14; } if (length < headersize) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } const unsigned char *p = data + length - headersize; if (parser->model != SMART && parser->model != SMARTAPNEA) { p += 4; } // Get the dive settings. unsigned int settings = 0; if (parser->model == SMARTAPNEA) { settings = array_uint16_le (p + 0x1C); } else if (parser->mode == FREEDIVE) { settings = array_uint16_le (p + 0x08); } else { settings = array_uint16_le (p + 0x0C); } // Get the sample interval. unsigned int interval = 0; unsigned int samplerate = 0; if (parser->model == SMARTAPNEA) { unsigned int idx = (settings & 0x0600) >> 9; interval = 1; samplerate = 1 << idx; } else { const unsigned int intervals[] = {1, 5, 10, 20}; unsigned int idx = (settings & 0x0C00) >> 10; interval = intervals[idx]; samplerate = 1; } // Calculate the total number of bytes for this dive. unsigned int nbytes = 4 + headersize + nsamples * samplesize; if (parser->model == ICONHDNET || parser->model == QUADAIR) { nbytes += (nsamples / 4) * 8; } else if (parser->model == SMARTAPNEA) { unsigned int divetime = array_uint32_le (p + 0x24); nbytes += divetime * samplerate * 2; } if (length != nbytes) { ERROR (abstract->context, "Calculated and stored size are not equal."); return DC_STATUS_DATAFORMAT; } // Gas mixes unsigned int ngasmixes = 0; unsigned int oxygen[NGASMIXES] = {0}; if (mode == GAUGE || mode == FREEDIVE) { ngasmixes = 0; } else if (mode == AIR) { oxygen[0] = 21; ngasmixes = 1; } else { // Count the number of active gas mixes. The active gas // mixes are always first, so we stop counting as soon // as the first gas marked as disabled is found. ngasmixes = 0; while (ngasmixes < NGASMIXES) { if (p[0x10 + ngasmixes * 4 + 1] & 0x80) break; oxygen[ngasmixes] = p[0x10 + ngasmixes * 4]; ngasmixes++; } } // Tanks unsigned int ntanks = 0; if (parser->model == ICONHDNET || parser->model == QUADAIR) { unsigned int tankoffset = (parser->model == ICONHDNET) ? 0x58 : 0x5C; while (ntanks < NTANKS) { unsigned int beginpressure = array_uint16_le (p + tankoffset + ntanks * 4 + 0); unsigned int endpressure = array_uint16_le (p + tankoffset + ntanks * 4 + 2); if (beginpressure == 0 && (endpressure == 0 || endpressure == 36000)) break; ntanks++; } } // Cache the data for later use. parser->mode = mode; parser->nsamples = nsamples; parser->footer = length - headersize; parser->samplesize = samplesize; parser->settings = settings; parser->interval = interval; parser->samplerate = samplerate; parser->ntanks = ntanks; parser->ngasmixes = ngasmixes; for (unsigned int i = 0; i < ngasmixes; ++i) { parser->oxygen[i] = oxygen[i]; } parser->cached = 1; return DC_STATUS_SUCCESS; } dc_status_t mares_iconhd_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int model) { mares_iconhd_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (mares_iconhd_parser_t *) dc_parser_allocate (context, &mares_iconhd_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. parser->model = model; parser->cached = 0; parser->mode = AIR; parser->nsamples = 0; parser->footer = 0; parser->samplesize = 0; parser->settings = 0; parser->interval = 0; parser->samplerate = 0; parser->ntanks = 0; parser->ngasmixes = 0; for (unsigned int i = 0; i < NGASMIXES; ++i) { parser->oxygen[i] = 0; } *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; } static dc_status_t mares_iconhd_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { mares_iconhd_parser_t *parser = (mares_iconhd_parser_t *) abstract; // Reset the cache. parser->cached = 0; parser->mode = AIR; parser->nsamples = 0; parser->footer = 0; parser->samplesize = 0; parser->settings = 0; parser->interval = 0; parser->samplerate = 0; parser->ntanks = 0; parser->ngasmixes = 0; for (unsigned int i = 0; i < NGASMIXES; ++i) { parser->oxygen[i] = 0; } return DC_STATUS_SUCCESS; } static dc_status_t mares_iconhd_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { mares_iconhd_parser_t *parser = (mares_iconhd_parser_t *) abstract; // Cache the parser data. dc_status_t rc = mares_iconhd_parser_cache (parser); if (rc != DC_STATUS_SUCCESS) return rc; const unsigned char *p = abstract->data + parser->footer; if (parser->model == SMART) { if (parser->mode == FREEDIVE) { p += 0x20; } else { p += 2; } } else if (parser->model == SMARTAPNEA) { p += 0x40; } else { p += 6; } if (datetime) { datetime->hour = array_uint16_le (p + 0); datetime->minute = array_uint16_le (p + 2); datetime->second = 0; datetime->day = array_uint16_le (p + 4); datetime->month = array_uint16_le (p + 6) + 1; datetime->year = array_uint16_le (p + 8) + 1900; datetime->timezone = DC_TIMEZONE_NONE; } return DC_STATUS_SUCCESS; } static dc_status_t mares_iconhd_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { mares_iconhd_parser_t *parser = (mares_iconhd_parser_t *) abstract; // Cache the parser data. dc_status_t rc = mares_iconhd_parser_cache (parser); if (rc != DC_STATUS_SUCCESS) return rc; const unsigned char *p = abstract->data + parser->footer; if (parser->model != SMART && parser->model != SMARTAPNEA) { p += 4; } unsigned int volume = 0, workpressure = 0; unsigned int tankoffset = 0; dc_gasmix_t *gasmix = (dc_gasmix_t *) value; dc_tank_t *tank = (dc_tank_t *) value; dc_salinity_t *water = (dc_salinity_t *) value; if (value) { switch (type) { case DC_FIELD_DIVETIME: if (parser->model == SMARTAPNEA) { *((unsigned int *) value) = array_uint16_le (p + 0x24); } else if (parser->mode == FREEDIVE) { unsigned int divetime = 0; unsigned int offset = 4; for (unsigned int i = 0; i < parser->nsamples; ++i) { divetime += array_uint16_le (abstract->data + offset + 2); offset += parser->samplesize; } *((unsigned int *) value) = divetime; } else { *((unsigned int *) value) = parser->nsamples * parser->interval; } break; case DC_FIELD_MAXDEPTH: if (parser->model == SMARTAPNEA) *((double *) value) = array_uint16_le (p + 0x3A) / 10.0; else if (parser->mode == FREEDIVE) *((double *) value) = array_uint16_le (p + 0x1A) / 10.0; else *((double *) value) = array_uint16_le (p + 0x00) / 10.0; break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = parser->ngasmixes; break; case DC_FIELD_GASMIX: gasmix->oxygen = parser->oxygen[flags] / 100.0; gasmix->helium = 0.0; gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium; break; case DC_FIELD_TANK_COUNT: *((unsigned int *) value) = parser->ntanks; break; case DC_FIELD_TANK: tankoffset = (parser->model == ICONHDNET) ? 0x58 : 0x5C; volume = array_uint16_le (p + tankoffset + 0x0C + flags * 8 + 0); workpressure = array_uint16_le (p + tankoffset + 0x0C + flags * 8 + 2); if (parser->settings & 0x0100) { tank->type = DC_TANKVOLUME_METRIC; tank->volume = volume; tank->workpressure = workpressure; } else { if (workpressure == 0) return DC_STATUS_DATAFORMAT; tank->type = DC_TANKVOLUME_IMPERIAL; tank->volume = volume * CUFT * 1000.0; tank->volume /= workpressure * PSI / ATM; tank->workpressure = workpressure * PSI / BAR; } tank->beginpressure = array_uint16_le (p + tankoffset + flags * 4 + 0) / 100.0; tank->endpressure = array_uint16_le (p + tankoffset + flags * 4 + 2) / 100.0; if (flags < parser->ngasmixes) { tank->gasmix = flags; } else { tank->gasmix = DC_GASMIX_UNKNOWN; } break; case DC_FIELD_ATMOSPHERIC: // Pressure (1/8 millibar) if (parser->model == SMARTAPNEA) *((double *) value) = array_uint16_le (p + 0x38) / 1000.0; else if (parser->mode == FREEDIVE) *((double *) value) = array_uint16_le (p + 0x18) / 1000.0; else *((double *) value) = array_uint16_le (p + 0x22) / 8000.0; break; case DC_FIELD_SALINITY: if (parser->model == SMARTAPNEA) { unsigned int salinity = parser->settings & 0x003F; if (salinity == 0) { water->type = DC_WATER_FRESH; } else { water->type = DC_WATER_SALT; } water->density = 1000.0 + salinity; } else { if (parser->settings & 0x0010) { water->type = DC_WATER_FRESH; } else { water->type = DC_WATER_SALT; } water->density = 0.0; } break; case DC_FIELD_TEMPERATURE_MINIMUM: if (parser->model == SMARTAPNEA) *((double *) value) = (signed short) array_uint16_le (p + 0x3C) / 10.0; else if (parser->mode == FREEDIVE) *((double *) value) = (signed short) array_uint16_le (p + 0x1C) / 10.0; else *((double *) value) = (signed short) array_uint16_le (p + 0x42) / 10.0; break; case DC_FIELD_TEMPERATURE_MAXIMUM: if (parser->model == SMARTAPNEA) *((double *) value) = (signed short) array_uint16_le (p + 0x3E) / 10.0; else if (parser->mode == FREEDIVE) *((double *) value) = (signed short) array_uint16_le (p + 0x1E) / 10.0; else *((double *) value) = (signed short) array_uint16_le (p + 0x44) / 10.0; break; case DC_FIELD_DIVEMODE: switch (parser->mode) { case AIR: case NITROX: *((dc_divemode_t *) value) = DC_DIVEMODE_OC; break; case GAUGE: *((dc_divemode_t *) value) = DC_DIVEMODE_GAUGE; break; case FREEDIVE: *((dc_divemode_t *) value) = DC_DIVEMODE_FREEDIVE; break; default: return DC_STATUS_DATAFORMAT; } break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t mares_iconhd_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { mares_iconhd_parser_t *parser = (mares_iconhd_parser_t *) abstract; // Cache the parser data. dc_status_t rc = mares_iconhd_parser_cache (parser); if (rc != DC_STATUS_SUCCESS) return rc; const unsigned char *data = abstract->data; if (parser->samplerate > 1) { // The Smart Apnea supports multiple samples per second // (e.g. 2, 4 or 8). Since our smallest unit of time is one // second, we can't represent this, and the extra samples // will get dropped. WARNING(abstract->context, "Multiple samples per second are not supported!"); } // Previous gas mix - initialize with impossible value unsigned int gasmix_previous = 0xFFFFFFFF; unsigned int time = 0; unsigned int offset = 4; unsigned int nsamples = 0; while (nsamples < parser->nsamples) { dc_sample_value_t sample = {0}; if (parser->model == SMARTAPNEA) { unsigned int maxdepth = array_uint16_le (data + offset + 0); unsigned int divetime = array_uint16_le (data + offset + 2); unsigned int surftime = array_uint16_le (data + offset + 4); // Surface Time (seconds). time += surftime; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Surface Depth (0 m). sample.depth = 0.0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); offset += parser->samplesize; nsamples++; for (unsigned int i = 0; i < divetime; ++i) { // Time (seconds). time += parser->interval; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Depth (1/10 m). unsigned int depth = array_uint16_le (data + offset); sample.depth = depth / 10.0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); offset += 2 * parser->samplerate; } } else if (parser->mode == FREEDIVE) { unsigned int maxdepth = array_uint16_le (data + offset + 0); unsigned int divetime = array_uint16_le (data + offset + 2); unsigned int surftime = array_uint16_le (data + offset + 4); // Surface Time (seconds). time += surftime; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Surface Depth (0 m). sample.depth = 0.0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); // Dive Time (seconds). time += divetime; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Maximum Depth (1/10 m). sample.depth = maxdepth / 10.0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); offset += parser->samplesize; nsamples++; } else { // Time (seconds). time += parser->interval; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Depth (1/10 m). unsigned int depth = array_uint16_le (data + offset + 0); sample.depth = depth / 10.0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); // Temperature (1/10 °C). unsigned int temperature = array_uint16_le (data + offset + 2) & 0x0FFF; sample.temperature = temperature / 10.0; if (callback) callback (DC_SAMPLE_TEMPERATURE, sample, userdata); // Current gas mix unsigned int gasmix = (data[offset + 3] & 0xF0) >> 4; if (parser->ngasmixes > 0) { if (gasmix >= parser->ngasmixes) { ERROR (abstract->context, "Invalid gas mix index."); return DC_STATUS_DATAFORMAT; } if (gasmix != gasmix_previous) { sample.gasmix = gasmix; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); gasmix_previous = gasmix; } } offset += parser->samplesize; nsamples++; // Some extra data. if ((parser->model == ICONHDNET || parser->model == QUADAIR) && (nsamples % 4) == 0) { // Pressure (1/100 bar). unsigned int pressure = array_uint16_le(data + offset); if (gasmix < parser->ntanks) { sample.pressure.tank = gasmix; sample.pressure.value = pressure / 100.0; if (callback) callback (DC_SAMPLE_PRESSURE, sample, userdata); } else if (pressure != 0) { WARNING (abstract->context, "Invalid tank with non-zero pressure."); } offset += 8; } } } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/mares_iconhd_parser.c
/* * libdivecomputer * * Copyright (C) 2014 Linus Torvalds * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <zlib.h> /* For crc32() */ #include "suunto_eonsteel.h" #include "context-private.h" #include "device-private.h" #include "array.h" #include "usbhid.h" #include "platform.h" #define EONSTEEL 0 #define EONCORE 1 typedef struct suunto_eonsteel_device_t { dc_device_t base; unsigned int model; unsigned int magic; unsigned short seq; unsigned char version[0x30]; unsigned char fingerprint[4]; } suunto_eonsteel_device_t; // The EON Steel implements a small filesystem #define DIRTYPE_FILE 0x0001 #define DIRTYPE_DIR 0x0002 struct directory_entry { struct directory_entry *next; int type; int namelen; char name[1]; }; // EON Steel command numbers and other magic field values #define CMD_INIT 0x0000 #define INIT_MAGIC 0x0001 #define INIT_SEQ 0 #define CMD_READ_STRING 0x0411 #define CMD_FILE_OPEN 0x0010 #define CMD_FILE_READ 0x0110 #define CMD_FILE_STAT 0x0710 #define CMD_FILE_CLOSE 0x0510 #define CMD_DIR_OPEN 0x0810 #define CMD_DIR_READDIR 0x0910 #define CMD_DIR_CLOSE 0x0a10 #define CMD_SET_TIME 0x0003 #define CMD_GET_TIME 0x0103 #define CMD_SET_DATE 0x0203 #define CMD_GET_DATE 0x0303 static dc_status_t suunto_eonsteel_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t suunto_eonsteel_device_foreach(dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t suunto_eonsteel_device_timesync(dc_device_t *abstract, const dc_datetime_t *datetime); static dc_status_t suunto_eonsteel_device_close(dc_device_t *abstract); static const dc_device_vtable_t suunto_eonsteel_device_vtable = { sizeof(suunto_eonsteel_device_t), DC_FAMILY_SUUNTO_EONSTEEL, suunto_eonsteel_device_set_fingerprint, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ NULL, /* dump */ suunto_eonsteel_device_foreach, /* foreach */ suunto_eonsteel_device_timesync, /* timesync */ suunto_eonsteel_device_close /* close */ }; static const char dive_directory[] = "0:/dives"; static void file_list_free (struct directory_entry *de) { while (de) { struct directory_entry *next = de->next; free (de); de = next; } } static struct directory_entry *alloc_dirent(int type, int len, const char *name) { struct directory_entry *res; res = (struct directory_entry *) malloc(offsetof(struct directory_entry, name) + len + 1); if (res) { res->next = NULL; res->type = type; res->namelen = len; memcpy(res->name, name, len); res->name[len] = 0; } return res; } static void put_le16(unsigned short val, unsigned char *p) { p[0] = val; p[1] = val >> 8; } static void put_le32(unsigned int val, unsigned char *p) { p[0] = val; p[1] = val >> 8; p[2] = val >> 16; p[3] = val >> 24; } /* * Get a single 64-byte packet from the dive computer. This handles packet * logging and any obvious packet-level errors, and returns the payload of * packet. * * The two first bytes of the packet are packet-level metadata: the report * type (always 0x3f), and then the size of the valid data in the packet. * * The maximum payload is 62 bytes. */ #define PACKET_SIZE 64 static int receive_usbhid_packet(dc_custom_io_t *io, suunto_eonsteel_device_t *eon, unsigned char *buffer, int size) { unsigned char buf[64]; dc_status_t rc = DC_STATUS_SUCCESS; size_t transferred = 0; int len; rc = io->packet_read(io, buf, PACKET_SIZE, &transferred); if (rc != DC_STATUS_SUCCESS) { ERROR(eon->base.context, "read interrupt transfer failed"); return -1; } if (transferred != PACKET_SIZE) { ERROR(eon->base.context, "incomplete read interrupt transfer (got " DC_PRINTF_SIZE ", expected %d)", transferred, PACKET_SIZE); return -1; } if (buf[0] != 0x3f) { ERROR(eon->base.context, "read interrupt transfer returns wrong report type (%d)", buf[0]); return -1; } len = buf[1]; if (len > PACKET_SIZE-2) { ERROR(eon->base.context, "read interrupt transfer reports bad length (%d)", len); return -1; } if (len > size) { ERROR(eon->base.context, "receive_packet result buffer too small - truncating"); len = size; } HEXDUMP (eon->base.context, DC_LOGLEVEL_DEBUG, "rcv", buf+2, len); memcpy(buffer, buf+2, len); return len; } static int fill_ble_buffer(dc_custom_io_t *io, suunto_eonsteel_device_t *eon, unsigned char *buffer, int size) { int state = 0; int bytes = 0; unsigned int crc; for (;;) { unsigned char packet[32]; dc_status_t rc = DC_STATUS_SUCCESS; size_t transferred = 0; int i; rc = io->packet_read(io, packet, sizeof(packet), &transferred); if (rc != DC_STATUS_SUCCESS) { ERROR(eon->base.context, "BLE GATT read transfer failed"); return -1; } for (i = 0; i < transferred; i++) { unsigned char c = packet[i]; if (c == 0x7e) { if (state == 1) goto done; if (state == 2) { ERROR(eon->base.context, "BLE GATT stream has escaped 7e character"); return -1; } /* Initial 7e character - good */ state = 1; continue; } if (!state) { ERROR(eon->base.context, "BLE GATT stream did not start with 7e"); return -1; } if (c == 0x7d) { if (state == 2) { ERROR(eon->base.context, "BLE GATT stream has escaped 7d character"); return -1; } state = 2; continue; } if (state == 2) { c ^= 0x20; state = 1; } if (bytes < size) buffer[bytes] = c; bytes++; } } done: if (bytes < 4) { ERROR(eon->base.context, "did not receive BLE CRC32 data"); return -1; } if (bytes > size) { ERROR(eon->base.context, "BLE GATT stream too long (%d bytes, buffer is %d)", bytes, size); return -1; } /* Remove and check CRC */ bytes -= 4; crc = crc32(0, buffer, bytes); if (crc != array_uint32_le(buffer + bytes)) { ERROR(eon->base.context, "incorrect BLE CRC32 data"); return -1; } HEXDUMP (eon->base.context, DC_LOGLEVEL_DEBUG, "rcv", buffer, bytes); return bytes; } #define HDRSIZE 12 #define MAXDATA 2048 #define CRCSIZE 4 static struct { unsigned int len, offset; unsigned char buffer[HDRSIZE + MAXDATA + CRCSIZE]; } ble_data; static void fill_ble_data(dc_custom_io_t *io, suunto_eonsteel_device_t *eon) { int received; received = fill_ble_buffer(io, eon, ble_data.buffer, sizeof(ble_data.buffer)); if (received < 0) received = 0; ble_data.offset = 0; ble_data.len = received; } static int receive_ble_packet(dc_custom_io_t *io, suunto_eonsteel_device_t *eon, unsigned char *buffer, int size) { int maxsize; if (ble_data.offset >= ble_data.len) return 0; maxsize = ble_data.len - ble_data.offset; if (size > maxsize) size = maxsize; memcpy(buffer, ble_data.buffer + ble_data.offset, size); ble_data.offset += size; return size; } static int receive_packet(dc_custom_io_t *io, suunto_eonsteel_device_t *eon, unsigned char *buffer, int size) { if (io->packet_size < 64) return receive_ble_packet(io, eon, buffer, size); return receive_usbhid_packet(io, eon, buffer, size); } static int add_hdlc(unsigned char *dst, unsigned char val) { int chars = 1; switch (val) { case 0x7e: case 0x7d: *dst++ = 0x7d; val ^= 0x20; chars++; /* fallthrough */ default: *dst = val; } return chars; } static int hdlc_reencode(unsigned char *dst, unsigned char *src, int len) { unsigned int crc = crc32(0, src, len); int result = 0, i; *dst++ = 0x7e; result++; for (i = 0; i < len; i++) { int chars = add_hdlc(dst, src[i]); dst += chars; result += chars; } for (i = 0; i < 4; i++) { int chars = add_hdlc(dst, crc & 255); dst += chars; result += chars; crc >>= 8; } *dst++ = 0x7e; result++; return result; } static int send_cmd(suunto_eonsteel_device_t *eon, unsigned short cmd, unsigned int len, const unsigned char *buffer) { unsigned char buf[64]; unsigned short seq = eon->seq; unsigned int magic = eon->magic; dc_custom_io_t *io = _dc_context_custom_io(eon->base.context); dc_status_t rc = DC_STATUS_SUCCESS; size_t transferred = 0; // Two-byte packet header, followed by 12 bytes of extended header if (len > sizeof(buf)-2-12) { ERROR(eon->base.context, "send command with too much long"); return -1; } memset(buf, 0, sizeof(buf)); buf[0] = 0x3f; buf[1] = len + 12; // 2-byte LE command word put_le16(cmd, buf+2); // 4-byte LE magic value (starts at 1) put_le32(magic, buf+4); // 2-byte LE sequence number; put_le16(seq, buf+8); // 4-byte LE length put_le32(len, buf+10); // .. followed by actual data if (len) { memcpy(buf+14, buffer, len); } // BLE GATT protocol? if (io->packet_size < 64) { int hdlc_len; unsigned char hdlc[2+2*(62+4)]; /* start/stop + escaping*(maxbuf+crc32) */ unsigned char *ptr; hdlc_len = hdlc_reencode(hdlc, buf+2, buf[1]); ptr = hdlc; do { int len = hdlc_len; if (len > io->packet_size) len = io->packet_size; rc = io->packet_write(io, ptr, len, &transferred); if (rc != DC_STATUS_SUCCESS) break; ptr += len; hdlc_len -= len; } while (hdlc_len); } else { rc = io->packet_write(io, buf, sizeof(buf), &transferred); } if (rc != DC_STATUS_SUCCESS) { ERROR(eon->base.context, "write interrupt transfer failed"); return -1; } // dump every outgoing packet? HEXDUMP (eon->base.context, DC_LOGLEVEL_DEBUG, "cmd", buf+2, len+12); return 0; } struct eon_hdr { unsigned short cmd; unsigned int magic; unsigned short seq; unsigned int len; }; static int receive_header(suunto_eonsteel_device_t *eon, struct eon_hdr *hdr, unsigned char *buffer, int size) { int ret; unsigned char header[64]; dc_custom_io_t *io = _dc_context_custom_io(eon->base.context); if (io->packet_size < 64) fill_ble_data(io, eon); ret = receive_packet(io, eon, header, sizeof(header)); if (ret < 0) return -1; if (ret < 12) { ERROR(eon->base.context, "short reply packet (%d)", ret); return -1; } /* Unpack the 12-byte header */ hdr->cmd = array_uint16_le(header); hdr->magic = array_uint32_le(header+2); hdr->seq = array_uint16_le(header+6); hdr->len = array_uint32_le(header+8); ret -= 12; if (ret > size) { ERROR(eon->base.context, "receive_header result data buffer too small (%d vs %d)", ret, size); return -1; } memcpy(buffer, header+12, ret); return ret; } static int receive_data(suunto_eonsteel_device_t *eon, unsigned char *buffer, int size) { int ret = 0; dc_custom_io_t *io = _dc_context_custom_io(eon->base.context); while (size > 0) { int len; len = receive_packet(io, eon, buffer + ret, size); if (len < 0) return -1; size -= len; ret += len; /* Was it not a full packet of data? We're done, regardless of expectations */ if (len < PACKET_SIZE-2) break; } return ret; } /* * Send a command, receive a reply * * This carefully checks the data fields in the reply for a match * against the command, and then only returns the actual reply * data itself. * * Also note that "receive_data()" itself will have removed the * per-packet handshake bytes, so unlike "send_cmd()", this does * not see the two initial 0x3f 0x?? bytes, and this the offsets * for the cmd/magic/seq/len are off by two compared to the * send_cmd() side. The offsets are the same in the actual raw * packet. */ static int send_receive(suunto_eonsteel_device_t *eon, unsigned short cmd, unsigned int len_out, const unsigned char *out, unsigned int len_in, unsigned char *in) { int len, actual; struct eon_hdr hdr; if (send_cmd(eon, cmd, len_out, out) < 0) return -1; /* Get the header and the first part of the data */ len = receive_header(eon, &hdr, in, len_in); if (len < 0) return -1; /* Verify the header data */ if (hdr.cmd != cmd) { ERROR(eon->base.context, "command reply doesn't match command"); return -1; } if (hdr.magic != eon->magic + 5) { ERROR(eon->base.context, "command reply doesn't match magic (got %08x, expected %08x)", hdr.magic, eon->magic + 5); return -1; } if (hdr.seq != eon->seq) { ERROR(eon->base.context, "command reply doesn't match sequence number"); return -1; } actual = hdr.len; if (actual < len) { ERROR(eon->base.context, "command reply length mismatch (got %d, claimed %d)", len, actual); return -1; } if (actual > len_in) { ERROR(eon->base.context, "command reply too big for result buffer - truncating"); actual = len_in; } /* Get the rest of the data */ len += receive_data(eon, in + len, actual - len); if (len != actual) { ERROR(eon->base.context, "command reply returned unexpected amoutn of data (got %d, expected %d)", len, actual); return -1; } // Successful command - increment sequence number eon->seq++; return len; } static int read_file(suunto_eonsteel_device_t *eon, const char *filename, dc_buffer_t *buf) { unsigned char result[2560]; unsigned char cmdbuf[64]; unsigned int size, offset; int rc, len; memset(cmdbuf, 0, sizeof(cmdbuf)); len = strlen(filename) + 1; if (len + 4 > sizeof(cmdbuf)) { ERROR(eon->base.context, "too long filename: %s", filename); return -1; } memcpy(cmdbuf+4, filename, len); rc = send_receive(eon, CMD_FILE_OPEN, len+4, cmdbuf, sizeof(result), result); if (rc < 0) { ERROR(eon->base.context, "unable to look up %s", filename); return -1; } HEXDUMP (eon->base.context, DC_LOGLEVEL_DEBUG, "lookup", result, rc); rc = send_receive(eon, CMD_FILE_STAT, 0, NULL, sizeof(result), result); if (rc < 0) { ERROR(eon->base.context, "unable to stat %s", filename); return -1; } HEXDUMP (eon->base.context, DC_LOGLEVEL_DEBUG, "stat", result, rc); size = array_uint32_le(result+4); offset = 0; while (size > 0) { unsigned int ask, got, at; ask = size; if (ask > 1024) ask = 1024; put_le32(1234, cmdbuf+0); // Not file offset, after all put_le32(ask, cmdbuf+4); // Size of read rc = send_receive(eon, CMD_FILE_READ, 8, cmdbuf, sizeof(result), result); if (rc < 0) { ERROR(eon->base.context, "unable to read %s", filename); return -1; } if (rc < 8) { ERROR(eon->base.context, "got short read reply for %s", filename); return -1; } // Not file offset, just stays unmodified. at = array_uint32_le(result); if (at != 1234) { ERROR(eon->base.context, "read of %s returned different offset than asked for (%d vs %d)", filename, at, offset); return -1; } // Number of bytes actually read got = array_uint32_le(result+4); if (!got) break; if (rc < 8 + got) { ERROR(eon->base.context, "odd read size reply for offset %d of file %s", offset, filename); return -1; } if (got > size) got = size; if (!dc_buffer_append (buf, result + 8, got)) { ERROR (eon->base.context, "Insufficient buffer space available."); return -1; } offset += got; size -= got; } rc = send_receive(eon, CMD_FILE_CLOSE, 0, NULL, sizeof(result), result); if (rc < 0) { ERROR(eon->base.context, "cmd CMD_FILE_CLOSE failed"); return -1; } HEXDUMP(eon->base.context, DC_LOGLEVEL_DEBUG, "close", result, rc); return offset; } /* * NOTE! This will create the list of dirent's in reverse order, * with the last dirent first. That's intentional: for dives, * we will want to look up the last dive first. */ static struct directory_entry *add_dirent(struct directory_entry *new, struct directory_entry *list) { struct directory_entry **pp = &list, *p; /* Skip any entries that are later than the new one */ while ((p = *pp) != NULL && strcmp(p->name, new->name) > 0) pp = &p->next; /* Add the new one to that location and return the new list pointer */ new->next = p; *pp = new; return list; } static struct directory_entry *parse_dirent(suunto_eonsteel_device_t *eon, int nr, const unsigned char *p, int len, struct directory_entry *old) { while (len > 8) { unsigned int type = array_uint32_le(p); unsigned int namelen = array_uint32_le(p+4); const unsigned char *name = p+8; struct directory_entry *entry; if (namelen + 8 + 1 > len || name[namelen] != 0) { ERROR(eon->base.context, "corrupt dirent entry: len=%d namelen=%d name='%s'", len, namelen, name); break; } HEXDUMP(eon->base.context, DC_LOGLEVEL_DEBUG, "dir entry", p, 8); p += 8 + namelen + 1; len -= 8 + namelen + 1; entry = alloc_dirent(type, namelen, (const char *) name); if (!entry) { ERROR(eon->base.context, "out of memory"); break; } old = add_dirent(entry, old); } return old; } static int get_file_list(suunto_eonsteel_device_t *eon, struct directory_entry **res) { struct directory_entry *de = NULL; unsigned char cmd[64]; unsigned char result[2048]; int rc, cmdlen; *res = NULL; put_le32(0, cmd); memcpy(cmd + 4, dive_directory, sizeof(dive_directory)); cmdlen = 4 + sizeof(dive_directory); rc = send_receive(eon, CMD_DIR_OPEN, cmdlen, cmd, sizeof(result), result); if (rc < 0) { ERROR(eon->base.context, "cmd DIR_LOOKUP failed"); return -1; } HEXDUMP(eon->base.context, DC_LOGLEVEL_DEBUG, "DIR_LOOKUP", result, rc); for (;;) { unsigned int nr, last; rc = send_receive(eon, CMD_DIR_READDIR, 0, NULL, sizeof(result), result); if (rc < 0) { ERROR(eon->base.context, "readdir failed"); return -1; } if (rc < 8) { ERROR(eon->base.context, "short readdir result"); return -1; } nr = array_uint32_le(result); last = array_uint32_le(result+4); HEXDUMP(eon->base.context, DC_LOGLEVEL_DEBUG, "dir packet", result, 8); de = parse_dirent(eon, nr, result+8, rc-8, de); if (last) break; } rc = send_receive(eon, CMD_DIR_CLOSE, 0, NULL, sizeof(result), result); if (rc < 0) { ERROR(eon->base.context, "dir close failed"); } *res = de; return 0; } static int initialize_eonsteel(suunto_eonsteel_device_t *eon) { const unsigned char init[] = {0x02, 0x00, 0x2a, 0x00}; struct eon_hdr hdr; if (send_cmd(eon, CMD_INIT, sizeof(init), init)) { ERROR(eon->base.context, "Failed to send initialization command"); return -1; } if (receive_header(eon, &hdr, eon->version, sizeof(eon->version)) < 0) { ERROR(eon->base.context, "Failed to receive initial reply"); return -1; } // Don't ask eon->magic = (hdr.magic & 0xffff0000) | 0x0005; // Increment the sequence number for every command sent eon->seq++; return 0; } dc_status_t suunto_eonsteel_device_open(dc_device_t **out, dc_context_t *context, const char *name, unsigned int model) { dc_status_t status = DC_STATUS_SUCCESS; suunto_eonsteel_device_t *eon = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; eon = (suunto_eonsteel_device_t *) dc_device_allocate(context, &suunto_eonsteel_device_vtable); if (!eon) return DC_STATUS_NOMEMORY; // Set up the magic handshake fields eon->model = model; eon->magic = INIT_MAGIC; eon->seq = INIT_SEQ; memset (eon->version, 0, sizeof (eon->version)); memset (eon->fingerprint, 0, sizeof (eon->fingerprint)); dc_custom_io_t *io = _dc_context_custom_io(eon->base.context); if (io && io->packet_open) status = io->packet_open(io, context, name); else { /* We really need some way to specify USB ID's in the descriptor */ unsigned int vendor_id = 0x1493; unsigned int device_id = model ? 0x0033 : 0x0030; status = dc_usbhid_custom_io(context, vendor_id, device_id); } if (status != DC_STATUS_SUCCESS) { ERROR(context, "unable to open device"); goto error_free; } if (initialize_eonsteel(eon) < 0) { ERROR(context, "unable to initialize device"); status = DC_STATUS_IO; goto error_close; } *out = (dc_device_t *) eon; return DC_STATUS_SUCCESS; error_close: suunto_eonsteel_device_close((dc_device_t *) eon); error_free: free(eon); return status; } static int count_dir_entries(struct directory_entry *de) { int count = 0; while (de) { count++; de = de->next; } return count; } static dc_status_t suunto_eonsteel_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { suunto_eonsteel_device_t *device = (suunto_eonsteel_device_t *) abstract; if (size && size != sizeof (device->fingerprint)) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, sizeof (device->fingerprint)); else memset (device->fingerprint, 0, sizeof (device->fingerprint)); return DC_STATUS_SUCCESS; } static dc_status_t suunto_eonsteel_device_foreach(dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { int skip = 0, rc; struct directory_entry *de; suunto_eonsteel_device_t *eon = (suunto_eonsteel_device_t *) abstract; dc_buffer_t *file; char pathname[64]; unsigned int time; dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; // Emit a device info event. dc_event_devinfo_t devinfo; devinfo.model = eon->model; devinfo.firmware = array_uint32_be (eon->version + 0x20); devinfo.serial = array_convert_str2num(eon->version + 0x10, 16); device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); if (get_file_list(eon, &de) < 0) return DC_STATUS_IO; if (de == NULL) { return DC_STATUS_SUCCESS; } file = dc_buffer_new (16384); if (file == NULL) { ERROR (abstract->context, "Insufficient buffer space available."); file_list_free (de); return DC_STATUS_NOMEMORY; } progress.maximum = count_dir_entries(de); progress.current = 0; device_event_emit(abstract, DC_EVENT_PROGRESS, &progress); while (de) { int len; struct directory_entry *next = de->next; unsigned char buf[4]; const unsigned char *data = NULL; unsigned int size = 0; if (device_is_cancelled(abstract)) skip = 1; switch (de->type) { case DIRTYPE_DIR: /* Ignore subdirectories in the dive directory */ break; case DIRTYPE_FILE: if (skip) break; if (sscanf(de->name, "%x.LOG", &time) != 1) break; len = snprintf(pathname, sizeof(pathname), "%s/%s", dive_directory, de->name); if (len >= sizeof(pathname)) break; // Reset the membuffer, put the 4-byte length at the head. dc_buffer_clear(file); put_le32(time, buf); dc_buffer_append(file, buf, 4); // Then read the filename into the rest of the buffer rc = read_file(eon, pathname, file); if (rc < 0) break; data = dc_buffer_get_data(file); size = dc_buffer_get_size(file); if (memcmp (data, eon->fingerprint, sizeof (eon->fingerprint)) == 0) { skip = 1; break; } if (callback && !callback(data, size, data, sizeof(eon->fingerprint), userdata)) skip = 1; } progress.current++; device_event_emit(abstract, DC_EVENT_PROGRESS, &progress); free(de); de = next; } dc_buffer_free(file); return device_is_cancelled(abstract) ? DC_STATUS_CANCELLED : DC_STATUS_SUCCESS; } static dc_status_t suunto_eonsteel_device_timesync(dc_device_t *abstract, const dc_datetime_t *datetime) { suunto_eonsteel_device_t *eon = (suunto_eonsteel_device_t *) abstract; unsigned char result[64], cmd[8]; unsigned int year, month, day; unsigned int hour, min, msec; int rc; year = datetime->year; month = datetime->month; day = datetime->day; hour = datetime->hour; min = datetime->minute; msec = datetime->second * 1000; cmd[0] = year & 0xFF; cmd[1] = year >> 8; cmd[2] = month; cmd[3] = day; cmd[4] = hour; cmd[5] = min; cmd[6] = msec & 0xFF; cmd[7] = msec >> 8; rc = send_receive(eon, CMD_SET_TIME, sizeof(cmd), cmd, sizeof(result), result); if (rc < 0) { return DC_STATUS_IO; } rc = send_receive(eon, CMD_SET_DATE, sizeof(cmd), cmd, sizeof(result), result); if (rc < 0) { return DC_STATUS_IO; } return DC_STATUS_SUCCESS; } static dc_status_t suunto_eonsteel_device_close(dc_device_t *abstract) { dc_custom_io_t *io = _dc_context_custom_io(abstract->context); return io->packet_close(io); }
libdc-for-dirk-Subsurface-branch
src/suunto_eonsteel.c
/* * libdivecomputer * * Copyright (C) 2013 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcmp, memcpy #include <stdlib.h> // malloc, free #include "shearwater_common.h" #include "context-private.h" #include "array.h" #define SZ_PACKET 254 // SLIP special character codes #define END 0xC0 #define ESC 0xDB #define ESC_END 0xDC #define ESC_ESC 0xDD dc_status_t shearwater_common_open (shearwater_common_device_t *device, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); return status; } // Set the serial communication protocol (115200 8N1). status = dc_iostream_configure (device->iostream, 115200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (3000ms). status = dc_iostream_set_timeout (device->iostream, 3000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); status = DC_STATUS_IO; goto error_close; } // Make sure everything is in a sane state. dc_iostream_sleep (device->iostream, 300); dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); return status; } dc_status_t shearwater_common_close (shearwater_common_device_t *device) { // Close the device. return dc_iostream_close (device->iostream); } static int shearwater_common_decompress_lre (unsigned char *data, unsigned int size, dc_buffer_t *buffer, unsigned int *isfinal) { // The RLE decompression algorithm does interpret the binary data as a // stream of 9 bit values. Therefore, the total number of bits needs to be // a multiple of 9 bits. unsigned int nbits = size * 8; if (nbits % 9 != 0) return -1; unsigned int offset = 0; while (offset + 9 <= nbits) { // Extract the 9 bit value. unsigned int byte = offset / 8; unsigned int bit = offset % 8; unsigned int shift = 16 - (bit + 9); unsigned int value = (array_uint16_be (data + byte) >> shift) & 0x1FF; // The 9th bit indicates whether the remaining 8 bits represent // a run of zero bytes or not. If the bit is set, the value is // not a run and doesn’t need expansion. If the bit is not set, // the value contains the number of zero bytes in the run. A // zero-length run indicates the end of the compressed stream. if (value & 0x100) { // Append the data byte directly. unsigned char c = value & 0xFF; if (!dc_buffer_append (buffer, &c, 1)) return -1; } else if (value == 0) { // Reached the end of the compressed stream. if (isfinal) *isfinal = 1; break; } else { // Expand the run with zero bytes. if (!dc_buffer_resize (buffer, dc_buffer_get_size (buffer) + value)) return -1; } offset += 9; } return 0; } static int shearwater_common_decompress_xor (unsigned char *data, unsigned int size) { // Each block of 32 bytes is XOR'ed (in-place) with the previous block, // except for the first block, which is passed through unchanged. for (unsigned int i = 32; i < size; ++i) { data[i] ^= data[i - 32]; } return 0; } static dc_status_t shearwater_common_slip_write (shearwater_common_device_t *device, const unsigned char data[], unsigned int size) { dc_status_t status = DC_STATUS_SUCCESS; const unsigned char end[] = {END}; const unsigned char esc_end[] = {ESC, ESC_END}; const unsigned char esc_esc[] = {ESC, ESC_ESC}; unsigned char buffer[32]; unsigned int nbytes = 0; #if 0 // Send an initial END character to flush out any data that may have // accumulated in the receiver due to line noise. status = dc_iostream_write (device->iostream, end, sizeof (end), NULL); if (status != DC_STATUS_SUCCESS) { return status; } #endif for (unsigned int i = 0; i < size; ++i) { const unsigned char *seq = NULL; unsigned int len = 0; switch (data[i]) { case END: // Escape the END character. seq = esc_end; len = sizeof (esc_end); break; case ESC: // Escape the ESC character. seq = esc_esc; len = sizeof (esc_esc); break; default: // Normal character. seq = data + i; len = 1; break; } // Flush the buffer if necessary. if (nbytes + len + sizeof(end) > sizeof(buffer)) { status = dc_iostream_write (device->iostream, buffer, nbytes, NULL); if (status != DC_STATUS_SUCCESS) { return status; } nbytes = 0; } // Append the escaped character. memcpy(buffer + nbytes, seq, len); nbytes += len; } // Append the END character to indicate the end of the packet. memcpy(buffer + nbytes, end, sizeof(end)); nbytes += sizeof(end); // Flush the buffer. status = dc_iostream_write (device->iostream, buffer, nbytes, NULL); if (status != DC_STATUS_SUCCESS) { return status; } return DC_STATUS_SUCCESS; } static dc_status_t shearwater_common_slip_read (shearwater_common_device_t *device, unsigned char data[], unsigned int size, unsigned int *actual) { dc_status_t status = DC_STATUS_SUCCESS; unsigned int received = 0; // Read bytes until a complete packet has been received. If the // buffer runs out of space, bytes are dropped. The caller can // detect this condition because the return value will be larger // than the supplied buffer size. while (1) { unsigned char c = 0; // Get a single character to process. status = dc_iostream_read (device->iostream, &c, 1, NULL); if (status != DC_STATUS_SUCCESS) { return status; } switch (c) { case END: // If it's an END character then we're done. // As a minor optimization, empty packets are ignored. This // is to avoid bothering the upper layers with all the empty // packets generated by the duplicate END characters which // are sent to try to detect line noise. if (received) goto done; else break; case ESC: // If it's an ESC character, get another character and then // figure out what to store in the packet based on that. status = dc_iostream_read (device->iostream, &c, 1, NULL); if (status != DC_STATUS_SUCCESS) { return status; } // If it's not one of the two escaped characters, then we // have a protocol violation. The best bet seems to be to // leave the byte alone and just stuff it into the packet. switch (c) { case ESC_END: c = END; break; case ESC_ESC: c = ESC; break; } // Fall-through! default: if (received < size) data[received] = c; received++; } } done: if (received > size) return DC_STATUS_PROTOCOL; if (actual) *actual = received; return DC_STATUS_SUCCESS; } dc_status_t shearwater_common_transfer (shearwater_common_device_t *device, const unsigned char input[], unsigned int isize, unsigned char output[], unsigned int osize, unsigned int *actual) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; unsigned char packet[SZ_PACKET + 4]; unsigned int n = 0; if (isize > SZ_PACKET || osize > SZ_PACKET) return DC_STATUS_INVALIDARGS; if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; // Setup the request packet. packet[0] = 0xFF; packet[1] = 0x01; packet[2] = isize + 1; packet[3] = 0x00; memcpy (packet + 4, input, isize); // Send the request packet. status = shearwater_common_slip_write (device, packet, isize + 4); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the request packet."); return status; } // Return early if no response packet is requested. if (osize == 0) { if (actual) *actual = 0; return DC_STATUS_SUCCESS; } // Receive the response packet. status = shearwater_common_slip_read (device, packet, sizeof (packet), &n); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the response packet."); return status; } // Validate the packet header. if (n < 4 || packet[0] != 0x01 || packet[1] != 0xFF || packet[3] != 0x00) { ERROR (abstract->context, "Invalid packet header."); return DC_STATUS_PROTOCOL; } // Validate the packet length. unsigned int length = packet[2]; if (length < 1 || length - 1 + 4 != n || length - 1 > osize) { ERROR (abstract->context, "Invalid packet header."); return DC_STATUS_PROTOCOL; } memcpy (output, packet + 4, length - 1); if (actual) *actual = length - 1; return DC_STATUS_SUCCESS; } dc_status_t shearwater_common_download (shearwater_common_device_t *device, dc_buffer_t *buffer, unsigned int address, unsigned int size, unsigned int compression, dc_event_progress_t *progress) { dc_device_t *abstract = (dc_device_t *) device; dc_status_t rc = DC_STATUS_SUCCESS; unsigned int n = 0; unsigned char req_init[] = { 0x35, (compression ? 0x10 : 0x00), 0x34, (address >> 24) & 0xFF, (address >> 16) & 0xFF, (address >> 8) & 0xFF, (address ) & 0xFF, (size >> 16) & 0xFF, (size >> 8) & 0xFF, (size ) & 0xFF}; unsigned char req_block[] = {0x36, 0x00}; unsigned char req_quit[] = {0x37}; unsigned char response[SZ_PACKET]; // Erase the current contents of the buffer. if (!dc_buffer_clear (buffer)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Enable progress notifications. unsigned int initial = 0, current = 0, maximum = 3 + size + 1; if (progress) { initial = progress->current; device_event_emit (abstract, DC_EVENT_PROGRESS, progress); } // Transfer the init request. rc = shearwater_common_transfer (device, req_init, sizeof (req_init), response, 3, &n); if (rc != DC_STATUS_SUCCESS) { return rc; } // Verify the init response. if (n != 3 || response[0] != 0x75 || response[1] != 0x10 || response[2] > SZ_PACKET) { ERROR (abstract->context, "Unexpected response packet."); return DC_STATUS_PROTOCOL; } // Update and emit a progress event. if (progress) { current += 3; progress->current = initial + STEP (current, maximum); device_event_emit (abstract, DC_EVENT_PROGRESS, progress); } unsigned int done = 0; unsigned char block = 1; unsigned int nbytes = 0; while (nbytes < size && !done) { // Transfer the block request. req_block[1] = block; rc = shearwater_common_transfer (device, req_block, sizeof (req_block), response, sizeof (response), &n); if (rc != DC_STATUS_SUCCESS) { return rc; } // Verify the block header. if (n < 2 || response[0] != 0x76 || response[1] != block) { ERROR (abstract->context, "Unexpected response packet."); return DC_STATUS_PROTOCOL; } // Verify the block length. unsigned int length = n - 2; if (nbytes + length > size) { ERROR (abstract->context, "Unexpected packet size."); return DC_STATUS_PROTOCOL; } // Update and emit a progress event. if (progress) { current += length; progress->current = initial + STEP (current, maximum); device_event_emit (abstract, DC_EVENT_PROGRESS, progress); } if (compression) { if (shearwater_common_decompress_lre (response + 2, length, buffer, &done) != 0) { ERROR (abstract->context, "Decompression error (LRE phase)."); return DC_STATUS_PROTOCOL; } } else { if (!dc_buffer_append (buffer, response + 2, length)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_PROTOCOL; } } nbytes += length; block++; } if (compression) { if (shearwater_common_decompress_xor (dc_buffer_get_data (buffer), dc_buffer_get_size (buffer)) != 0) { ERROR (abstract->context, "Decompression error (XOR phase)."); return DC_STATUS_PROTOCOL; } } // Transfer the quit request. rc = shearwater_common_transfer (device, req_quit, sizeof (req_quit), response, 2, &n); if (rc != DC_STATUS_SUCCESS) { return rc; } // Verify the quit response. if (n != 2 || response[0] != 0x77 || response[1] != 0x00) { ERROR (abstract->context, "Unexpected response packet."); return DC_STATUS_PROTOCOL; } // Update and emit a progress event. if (progress) { current += 1; progress->current = initial + STEP (current, maximum); device_event_emit (abstract, DC_EVENT_PROGRESS, progress); } return DC_STATUS_SUCCESS; } dc_status_t shearwater_common_identifier (shearwater_common_device_t *device, dc_buffer_t *buffer, unsigned int id) { dc_device_t *abstract = (dc_device_t *) device; dc_status_t rc = DC_STATUS_SUCCESS; // Erase the buffer. if (!dc_buffer_clear (buffer)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Transfer the request. unsigned int n = 0; unsigned char request[] = {0x22, (id >> 8) & 0xFF, (id ) & 0xFF}; unsigned char response[SZ_PACKET]; rc = shearwater_common_transfer (device, request, sizeof (request), response, sizeof (response), &n); if (rc != DC_STATUS_SUCCESS) { return rc; } // Verify the response. if (n < 3 || response[0] != 0x62 || response[1] != request[1] || response[2] != request[2]) { ERROR (abstract->context, "Unexpected response packet."); return DC_STATUS_PROTOCOL; } // Append the packet to the output buffer. if (!dc_buffer_append (buffer, response + 3, n - 3)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } return rc; }
libdc-for-dirk-Subsurface-branch
src/shearwater_common.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> // malloc, free #include <string.h> // strerror #include <errno.h> // errno #include <unistd.h> // open, close, read, write #include <fcntl.h> // fcntl #include <termios.h> // tcgetattr, tcsetattr, cfsetispeed, cfsetospeed, tcflush, tcsendbreak #include <sys/ioctl.h> // ioctl #include <time.h> // nanosleep #ifdef HAVE_LINUX_SERIAL_H #include <linux/serial.h> #endif #ifdef HAVE_IOKIT_SERIAL_IOSS_H #include <IOKit/serial/ioss.h> #endif #include <stdio.h> #include <sys/types.h> #include <dirent.h> #include <fnmatch.h> #ifndef TIOCINQ #define TIOCINQ FIONREAD #endif #ifdef ENABLE_PTY #define NOPTY (errno != EINVAL && errno != ENOTTY) #else #define NOPTY 1 #endif #include "serial.h" #include "common-private.h" #include "context-private.h" #include "iostream-private.h" #include "iterator-private.h" #include "descriptor-private.h" #include "timer.h" #define DIRNAME "/dev" static dc_status_t dc_serial_iterator_next (dc_iterator_t *iterator, void *item); static dc_status_t dc_serial_iterator_free (dc_iterator_t *iterator); static dc_status_t dc_serial_set_timeout (dc_iostream_t *iostream, int timeout); static dc_status_t dc_serial_set_latency (dc_iostream_t *iostream, unsigned int value); static dc_status_t dc_serial_set_break (dc_iostream_t *iostream, unsigned int value); static dc_status_t dc_serial_set_dtr (dc_iostream_t *iostream, unsigned int value); static dc_status_t dc_serial_set_rts (dc_iostream_t *iostream, unsigned int value); static dc_status_t dc_serial_get_lines (dc_iostream_t *iostream, unsigned int *value); static dc_status_t dc_serial_get_available (dc_iostream_t *iostream, size_t *value); static dc_status_t dc_serial_configure (dc_iostream_t *iostream, unsigned int baudrate, unsigned int databits, dc_parity_t parity, dc_stopbits_t stopbits, dc_flowcontrol_t flowcontrol); static dc_status_t dc_serial_read (dc_iostream_t *iostream, void *data, size_t size, size_t *actual); static dc_status_t dc_serial_write (dc_iostream_t *iostream, const void *data, size_t size, size_t *actual); static dc_status_t dc_serial_flush (dc_iostream_t *iostream); static dc_status_t dc_serial_purge (dc_iostream_t *iostream, dc_direction_t direction); static dc_status_t dc_serial_sleep (dc_iostream_t *iostream, unsigned int milliseconds); static dc_status_t dc_serial_close (dc_iostream_t *iostream); struct dc_serial_device_t { char name[256]; }; typedef struct dc_serial_iterator_t { dc_iterator_t base; dc_filter_t filter; DIR *dp; } dc_serial_iterator_t; typedef struct dc_serial_t { dc_iostream_t base; /* * The file descriptor corresponding to the serial port. */ int fd; int timeout; dc_timer_t *timer; /* * Serial port settings are saved into this variable immediately * after the port is opened. These settings are restored when the * serial port is closed. */ struct termios tty; } dc_serial_t; static const dc_iterator_vtable_t dc_serial_iterator_vtable = { sizeof(dc_serial_iterator_t), dc_serial_iterator_next, dc_serial_iterator_free, }; static const dc_iostream_vtable_t dc_serial_vtable = { sizeof(dc_serial_t), dc_serial_set_timeout, /* set_timeout */ dc_serial_set_latency, /* set_latency */ dc_serial_set_break, /* set_break */ dc_serial_set_dtr, /* set_dtr */ dc_serial_set_rts, /* set_rts */ dc_serial_get_lines, /* get_lines */ dc_serial_get_available, /* get_received */ dc_serial_configure, /* configure */ dc_serial_read, /* read */ dc_serial_write, /* write */ dc_serial_flush, /* flush */ dc_serial_purge, /* purge */ dc_serial_sleep, /* sleep */ dc_serial_close, /* close */ }; static dc_status_t syserror(int errcode) { switch (errcode) { case EINVAL: return DC_STATUS_INVALIDARGS; case ENOMEM: return DC_STATUS_NOMEMORY; case ENOENT: return DC_STATUS_NODEVICE; case EACCES: case EBUSY: return DC_STATUS_NOACCESS; default: return DC_STATUS_IO; } } const char * dc_serial_device_get_name (dc_serial_device_t *device) { if (device == NULL || device->name[0] == '\0') return NULL; return device->name; } void dc_serial_device_free (dc_serial_device_t *device) { free (device); } dc_status_t dc_serial_iterator_new (dc_iterator_t **out, dc_context_t *context, dc_descriptor_t *descriptor) { dc_status_t status = DC_STATUS_SUCCESS; dc_serial_iterator_t *iterator = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; iterator = (dc_serial_iterator_t *) dc_iterator_allocate (context, &dc_serial_iterator_vtable); if (iterator == NULL) { SYSERROR (context, ENOMEM); return DC_STATUS_NOMEMORY; } iterator->dp = opendir (DIRNAME); if (iterator->dp == NULL) { int errcode = errno; SYSERROR (context, errcode); status = syserror (errcode); goto error_free; } iterator->filter = dc_descriptor_get_filter (descriptor); *out = (dc_iterator_t *) iterator; return DC_STATUS_SUCCESS; error_free: dc_iterator_deallocate ((dc_iterator_t *) iterator); return status; } static dc_status_t dc_serial_iterator_next (dc_iterator_t *abstract, void *out) { dc_serial_iterator_t *iterator = (dc_serial_iterator_t *) abstract; dc_serial_device_t *device = NULL; struct dirent *ep = NULL; const char *patterns[] = { #if defined (__APPLE__) "tty.*", #else "ttyS*", "ttyUSB*", "ttyACM*", "rfcomm*", #endif NULL }; while ((ep = readdir (iterator->dp)) != NULL) { for (size_t i = 0; patterns[i] != NULL; ++i) { if (fnmatch (patterns[i], ep->d_name, 0) != 0) continue; char filename[sizeof(device->name)]; int n = snprintf (filename, sizeof (filename), "%s/%s", DIRNAME, ep->d_name); if (n < 0 || (size_t) n >= sizeof (filename)) { return DC_STATUS_NOMEMORY; } if (iterator->filter && !iterator->filter (DC_TRANSPORT_SERIAL, filename)) { continue; } device = (dc_serial_device_t *) malloc (sizeof(dc_serial_device_t)); if (device == NULL) { SYSERROR (abstract->context, ENOMEM); return DC_STATUS_NOMEMORY; } strncpy(device->name, filename, sizeof(device->name)); *(dc_serial_device_t **) out = device; return DC_STATUS_SUCCESS; } } return DC_STATUS_DONE; } static dc_status_t dc_serial_iterator_free (dc_iterator_t *abstract) { dc_serial_iterator_t *iterator = (dc_serial_iterator_t *) abstract; closedir (iterator->dp); return DC_STATUS_SUCCESS; } dc_status_t dc_serial_open (dc_iostream_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; dc_serial_t *device = NULL; if (out == NULL || name == NULL) return DC_STATUS_INVALIDARGS; // Are we using custom IO? if (_dc_context_custom_io(context)) return dc_custom_io_serial_open(out, context, name); INFO (context, "Open: name=%s", name); // Allocate memory. device = (dc_serial_t *) dc_iostream_allocate (context, &dc_serial_vtable); if (device == NULL) { SYSERROR (context, ENOMEM); return DC_STATUS_NOMEMORY; } // Default to blocking reads. device->timeout = -1; // Create a high resolution timer. status = dc_timer_new (&device->timer); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to create a high resolution timer."); goto error_free; } // Open the device in non-blocking mode, to return immediately // without waiting for the modem connection to complete. device->fd = open (name, O_RDWR | O_NOCTTY | O_NONBLOCK); if (device->fd == -1) { int errcode = errno; SYSERROR (context, errcode); status = syserror (errcode); goto error_timer_free; } #ifndef ENABLE_PTY // Enable exclusive access mode. if (ioctl (device->fd, TIOCEXCL, NULL) != 0) { int errcode = errno; SYSERROR (context, errcode); status = syserror (errcode); goto error_close; } #endif // Retrieve the current terminal attributes, to // be able to restore them when closing the device. // It is also used to check if the obtained // file descriptor represents a terminal device. if (tcgetattr (device->fd, &device->tty) != 0) { int errcode = errno; SYSERROR (context, errcode); status = syserror (errcode); goto error_close; } *out = (dc_iostream_t *) device; return DC_STATUS_SUCCESS; error_close: close (device->fd); error_timer_free: dc_timer_free (device->timer); error_free: dc_iostream_deallocate ((dc_iostream_t *) device); return status; } static dc_status_t dc_serial_close (dc_iostream_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; dc_serial_t *device = (dc_serial_t *) abstract; // Restore the initial terminal attributes. if (tcsetattr (device->fd, TCSANOW, &device->tty) != 0) { int errcode = errno; SYSERROR (abstract->context, errcode); dc_status_set_error(&status, syserror (errcode)); } #ifndef ENABLE_PTY // Disable exclusive access mode. if (ioctl (device->fd, TIOCNXCL, NULL)) { int errcode = errno; SYSERROR (abstract->context, errcode); dc_status_set_error(&status, syserror (errcode)); } #endif // Close the device. if (close (device->fd) != 0) { int errcode = errno; SYSERROR (abstract->context, errcode); dc_status_set_error(&status, syserror (errcode)); } dc_timer_free (device->timer); return status; } static dc_status_t dc_serial_configure (dc_iostream_t *abstract, unsigned int baudrate, unsigned int databits, dc_parity_t parity, dc_stopbits_t stopbits, dc_flowcontrol_t flowcontrol) { dc_serial_t *device = (dc_serial_t *) abstract; // Retrieve the current settings. struct termios tty; memset (&tty, 0, sizeof (tty)); if (tcgetattr (device->fd, &tty) != 0) { int errcode = errno; SYSERROR (abstract->context, errcode); return syserror (errcode); } // Setup raw input/output mode without echo. tty.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | ICRNL); tty.c_oflag &= ~(OPOST); tty.c_lflag &= ~(ICANON | ECHO | ISIG | IEXTEN); // Enable the receiver (CREAD) and ignore modem control lines (CLOCAL). tty.c_cflag |= (CLOCAL | CREAD); // VMIN is the minimum number of characters for non-canonical read // and VTIME is the timeout in deciseconds for non-canonical read. // Setting both of these parameters to zero implies that a read // will return immediately, only giving the currently available // characters (non-blocking read behaviour). However, a non-blocking // read (or write) can also be achieved by using O_NONBLOCK. // But together with VMIN = 1, it becomes possible to recognize // the difference between a timeout and modem disconnect (EOF) // when read() returns zero. tty.c_cc[VMIN] = 1; tty.c_cc[VTIME] = 0; // Set the baud rate. int custom = 0; speed_t baud = 0; switch (baudrate) { case 0: baud = B0; break; case 50: baud = B50; break; case 75: baud = B75; break; case 110: baud = B110; break; case 134: baud = B134; break; case 150: baud = B150; break; case 200: baud = B200; break; case 300: baud = B300; break; case 600: baud = B600; break; case 1200: baud = B1200; break; case 1800: baud = B1800; break; case 2400: baud = B2400; break; case 4800: baud = B4800; break; case 9600: baud = B9600; break; case 19200: baud = B19200; break; case 38400: baud = B38400; break; #ifdef B57600 case 57600: baud = B57600; break; #endif #ifdef B115200 case 115200: baud = B115200; break; #endif #ifdef B230400 case 230400: baud = B230400; break; #endif #ifdef B460800 case 460800: baud = B460800; break; #endif #ifdef B500000 case 500000: baud = B500000; break; #endif #ifdef B576000 case 576000: baud = B576000; break; #endif #ifdef B921600 case 921600: baud = B921600; break; #endif #ifdef B1000000 case 1000000: baud = B1000000; break; #endif #ifdef B1152000 case 1152000: baud = B1152000; break; #endif #ifdef B1500000 case 1500000: baud = B1500000; break; #endif #ifdef B2000000 case 2000000: baud = B2000000; break; #endif #ifdef B2500000 case 2500000: baud = B2500000; break; #endif #ifdef B3000000 case 3000000: baud = B3000000; break; #endif #ifdef B3500000 case 3500000: baud = B3500000; break; #endif #ifdef B4000000 case 4000000: baud = B4000000; break; #endif default: baud = B38400; /* Required for custom baudrates on linux. */ custom = 1; break; } if (cfsetispeed (&tty, baud) != 0 || cfsetospeed (&tty, baud) != 0) { int errcode = errno; SYSERROR (abstract->context, errcode); return syserror (errcode); } // Set the character size. tty.c_cflag &= ~CSIZE; switch (databits) { case 5: tty.c_cflag |= CS5; break; case 6: tty.c_cflag |= CS6; break; case 7: tty.c_cflag |= CS7; break; case 8: tty.c_cflag |= CS8; break; default: return DC_STATUS_INVALIDARGS; } // Set the parity type. #ifdef CMSPAR tty.c_cflag &= ~(PARENB | PARODD | CMSPAR); #else tty.c_cflag &= ~(PARENB | PARODD); #endif tty.c_iflag &= ~(IGNPAR | PARMRK | INPCK); switch (parity) { case DC_PARITY_NONE: tty.c_iflag |= IGNPAR; break; case DC_PARITY_EVEN: tty.c_cflag |= PARENB; tty.c_iflag |= INPCK; break; case DC_PARITY_ODD: tty.c_cflag |= (PARENB | PARODD); tty.c_iflag |= INPCK; break; #ifdef CMSPAR case DC_PARITY_MARK: tty.c_cflag |= (PARENB | PARODD | CMSPAR); tty.c_iflag |= INPCK; break; case DC_PARITY_SPACE: tty.c_cflag |= (PARENB | CMSPAR); tty.c_iflag |= INPCK; break; #endif default: return DC_STATUS_INVALIDARGS; } // Set the number of stop bits. switch (stopbits) { case DC_STOPBITS_ONE: tty.c_cflag &= ~CSTOPB; break; case DC_STOPBITS_TWO: tty.c_cflag |= CSTOPB; break; default: return DC_STATUS_INVALIDARGS; } // Set the flow control. switch (flowcontrol) { case DC_FLOWCONTROL_NONE: #ifdef CRTSCTS tty.c_cflag &= ~CRTSCTS; #endif tty.c_iflag &= ~(IXON | IXOFF | IXANY); break; case DC_FLOWCONTROL_HARDWARE: #ifdef CRTSCTS tty.c_cflag |= CRTSCTS; tty.c_iflag &= ~(IXON | IXOFF | IXANY); break; #else return DC_STATUS_UNSUPPORTED; #endif case DC_FLOWCONTROL_SOFTWARE: #ifdef CRTSCTS tty.c_cflag &= ~CRTSCTS; #endif tty.c_iflag |= (IXON | IXOFF); break; default: return DC_STATUS_INVALIDARGS; } // Apply the new settings. if (tcsetattr (device->fd, TCSANOW, &tty) != 0 && NOPTY) { int errcode = errno; SYSERROR (abstract->context, errcode); return syserror (errcode); } // Configure a custom baudrate if necessary. if (custom) { #if defined(TIOCGSERIAL) && defined(TIOCSSERIAL) && !defined(__ANDROID__) // Get the current settings. struct serial_struct ss; if (ioctl (device->fd, TIOCGSERIAL, &ss) != 0 && NOPTY) { int errcode = errno; SYSERROR (abstract->context, errcode); return syserror (errcode); } // Set the custom divisor. ss.custom_divisor = ss.baud_base / baudrate; ss.flags &= ~ASYNC_SPD_MASK; ss.flags |= ASYNC_SPD_CUST; // Apply the new settings. if (ioctl (device->fd, TIOCSSERIAL, &ss) != 0 && NOPTY) { int errcode = errno; SYSERROR (abstract->context, errcode); return syserror (errcode); } #elif defined(IOSSIOSPEED) speed_t speed = baudrate; if (ioctl (device->fd, IOSSIOSPEED, &speed) != 0 && NOPTY) { int errcode = errno; SYSERROR (abstract->context, errcode); return syserror (errcode); } #else // Custom baudrates are not supported. return DC_STATUS_UNSUPPORTED; #endif } return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_set_timeout (dc_iostream_t *abstract, int timeout) { dc_serial_t *device = (dc_serial_t *) abstract; device->timeout = timeout; return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_set_latency (dc_iostream_t *abstract, unsigned int milliseconds) { dc_serial_t *device = (dc_serial_t *) abstract; #if defined(TIOCGSERIAL) && defined(TIOCSSERIAL) && !defined(__ANDROID__) // Get the current settings. struct serial_struct ss; if (ioctl (device->fd, TIOCGSERIAL, &ss) != 0 && NOPTY) { int errcode = errno; SYSERROR (abstract->context, errcode); return syserror (errcode); } // Set or clear the low latency flag. if (milliseconds == 0) { ss.flags |= ASYNC_LOW_LATENCY; } else { ss.flags &= ~ASYNC_LOW_LATENCY; } // Apply the new settings. if (ioctl (device->fd, TIOCSSERIAL, &ss) != 0 && NOPTY) { int errcode = errno; SYSERROR (abstract->context, errcode); return syserror (errcode); } #elif defined(IOSSDATALAT) // Set the receive latency in microseconds. Serial drivers use this // value to determine how often to dequeue characters received by // the hardware. A value of zero restores the default value. unsigned long usec = (milliseconds == 0 ? 1 : milliseconds * 1000); if (ioctl (device->fd, IOSSDATALAT, &usec) != 0 && NOPTY) { int errcode = errno; SYSERROR (abstract->context, errcode); return syserror (errcode); } #endif return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_read (dc_iostream_t *abstract, void *data, size_t size, size_t *actual) { dc_status_t status = DC_STATUS_SUCCESS; dc_serial_t *device = (dc_serial_t *) abstract; size_t nbytes = 0; // The absolute target time. dc_usecs_t target = 0; int init = 1; while (nbytes < size) { fd_set fds; FD_ZERO (&fds); FD_SET (device->fd, &fds); struct timeval tv, *ptv = NULL; if (device->timeout > 0) { dc_usecs_t timeout = 0; dc_usecs_t now = 0; status = dc_timer_now (device->timer, &now); if (status != DC_STATUS_SUCCESS) { goto out; } if (init) { // Calculate the initial timeout. timeout = device->timeout * 1000; // Calculate the target time. target = now + timeout; init = 0; } else { // Calculate the remaining timeout. if (now < target) { timeout = target - now; } else { timeout = 0; } } tv.tv_sec = timeout / 1000000; tv.tv_usec = timeout % 1000000; ptv = &tv; } else if (device->timeout == 0) { tv.tv_sec = 0; tv.tv_usec = 0; ptv = &tv; } int rc = select (device->fd + 1, &fds, NULL, NULL, ptv); if (rc < 0) { int errcode = errno; if (errcode == EINTR) continue; // Retry. SYSERROR (abstract->context, errcode); status = syserror (errcode); goto out; } else if (rc == 0) { break; // Timeout. } ssize_t n = read (device->fd, (char *) data + nbytes, size - nbytes); if (n < 0) { int errcode = errno; if (errcode == EINTR || errcode == EAGAIN) continue; // Retry. SYSERROR (abstract->context, errcode); status = syserror (errcode); goto out; } else if (n == 0) { break; // EOF. } nbytes += n; } if (nbytes != size) { status = DC_STATUS_TIMEOUT; } out: if (actual) *actual = nbytes; return status; } static dc_status_t dc_serial_write (dc_iostream_t *abstract, const void *data, size_t size, size_t *actual) { dc_status_t status = DC_STATUS_SUCCESS; dc_serial_t *device = (dc_serial_t *) abstract; size_t nbytes = 0; while (nbytes < size) { fd_set fds; FD_ZERO (&fds); FD_SET (device->fd, &fds); int rc = select (device->fd + 1, NULL, &fds, NULL, NULL); if (rc < 0) { int errcode = errno; if (errcode == EINTR) continue; // Retry. SYSERROR (abstract->context, errcode); status = syserror (errcode); goto out; } else if (rc == 0) { break; // Timeout. } ssize_t n = write (device->fd, (const char *) data + nbytes, size - nbytes); if (n < 0) { int errcode = errno; if (errcode == EINTR || errcode == EAGAIN) continue; // Retry. SYSERROR (abstract->context, errcode); status = syserror (errcode); goto out; } else if (n == 0) { break; // EOF. } nbytes += n; } // Wait until all data has been transmitted. #ifdef __ANDROID__ /* Android is missing tcdrain, so use ioctl version instead */ while (ioctl (device->fd, TCSBRK, 1) != 0) { #else while (tcdrain (device->fd) != 0) { #endif int errcode = errno; if (errcode != EINTR ) { SYSERROR (abstract->context, errcode); status = syserror (errcode); goto out; } } out: if (actual) *actual = nbytes; return status; } static dc_status_t dc_serial_purge (dc_iostream_t *abstract, dc_direction_t direction) { dc_serial_t *device = (dc_serial_t *) abstract; int flags = 0; switch (direction) { case DC_DIRECTION_INPUT: flags = TCIFLUSH; break; case DC_DIRECTION_OUTPUT: flags = TCOFLUSH; break; case DC_DIRECTION_ALL: flags = TCIOFLUSH; break; default: return DC_STATUS_INVALIDARGS; } if (tcflush (device->fd, flags) != 0) { int errcode = errno; SYSERROR (abstract->context, errcode); return syserror (errcode); } return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_flush (dc_iostream_t *abstract) { return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_set_break (dc_iostream_t *abstract, unsigned int level) { dc_serial_t *device = (dc_serial_t *) abstract; unsigned long action = (level ? TIOCSBRK : TIOCCBRK); if (ioctl (device->fd, action, NULL) != 0 && NOPTY) { int errcode = errno; SYSERROR (abstract->context, errcode); return syserror (errcode); } return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_set_dtr (dc_iostream_t *abstract, unsigned int level) { dc_serial_t *device = (dc_serial_t *) abstract; unsigned long action = (level ? TIOCMBIS : TIOCMBIC); int value = TIOCM_DTR; if (ioctl (device->fd, action, &value) != 0 && NOPTY) { int errcode = errno; SYSERROR (abstract->context, errcode); return syserror (errcode); } return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_set_rts (dc_iostream_t *abstract, unsigned int level) { dc_serial_t *device = (dc_serial_t *) abstract; unsigned long action = (level ? TIOCMBIS : TIOCMBIC); int value = TIOCM_RTS; if (ioctl (device->fd, action, &value) != 0 && NOPTY) { int errcode = errno; SYSERROR (abstract->context, errcode); return syserror (errcode); } return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_get_available (dc_iostream_t *abstract, size_t *value) { dc_serial_t *device = (dc_serial_t *) abstract; int bytes = 0; if (ioctl (device->fd, TIOCINQ, &bytes) != 0) { int errcode = errno; SYSERROR (abstract->context, errcode); return syserror (errcode); } if (value) *value = bytes; return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_get_lines (dc_iostream_t *abstract, unsigned int *value) { dc_serial_t *device = (dc_serial_t *) abstract; unsigned int lines = 0; int status = 0; if (ioctl (device->fd, TIOCMGET, &status) != 0) { int errcode = errno; SYSERROR (abstract->context, errcode); return syserror (errcode); } if (status & TIOCM_CAR) lines |= DC_LINE_DCD; if (status & TIOCM_CTS) lines |= DC_LINE_CTS; if (status & TIOCM_DSR) lines |= DC_LINE_DSR; if (status & TIOCM_RNG) lines |= DC_LINE_RNG; if (value) *value = lines; return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_sleep (dc_iostream_t *abstract, unsigned int timeout) { struct timespec ts; ts.tv_sec = (timeout / 1000); ts.tv_nsec = (timeout % 1000) * 1000000; while (nanosleep (&ts, &ts) != 0) { int errcode = errno; if (errcode != EINTR ) { SYSERROR (abstract->context, errcode); return syserror (errcode); } } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/serial_posix.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> // malloc, free #include <memory.h> // memcpy #include "uwatec_aladin.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "ringbuffer.h" #include "checksum.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &uwatec_aladin_device_vtable) #define SZ_MEMORY 2048 #define RB_PROFILE_BEGIN 0x000 #define RB_PROFILE_END 0x600 #define RB_PROFILE_NEXT(a) ringbuffer_increment (a, 1, RB_PROFILE_BEGIN, RB_PROFILE_END) #define RB_PROFILE_DISTANCE(a,b) ringbuffer_distance (a, b, 0, RB_PROFILE_BEGIN, RB_PROFILE_END) #define HEADER 4 typedef struct uwatec_aladin_device_t { dc_device_t base; dc_iostream_t *iostream; unsigned int timestamp; unsigned int devtime; dc_ticks_t systime; } uwatec_aladin_device_t ; static dc_status_t uwatec_aladin_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t uwatec_aladin_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t uwatec_aladin_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t uwatec_aladin_device_close (dc_device_t *abstract); static const dc_device_vtable_t uwatec_aladin_device_vtable = { sizeof(uwatec_aladin_device_t), DC_FAMILY_UWATEC_ALADIN, uwatec_aladin_device_set_fingerprint, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ uwatec_aladin_device_dump, /* dump */ uwatec_aladin_device_foreach, /* foreach */ NULL, /* timesync */ uwatec_aladin_device_close /* close */ }; static dc_status_t uwatec_aladin_extract_dives (dc_device_t *device, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata); dc_status_t uwatec_aladin_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; uwatec_aladin_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (uwatec_aladin_device_t *) dc_device_allocate (context, &uwatec_aladin_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; device->timestamp = 0; device->systime = (dc_ticks_t) -1; device->devtime = 0; // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (19200 8N1). status = dc_iostream_configure (device->iostream, 19200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (INFINITE). status = dc_iostream_set_timeout (device->iostream, -1); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Set the DTR line. status = dc_iostream_set_dtr (device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the DTR line."); goto error_close; } // Clear the RTS line. status = dc_iostream_set_rts (device->iostream, 0); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to clear the RTS line."); goto error_close; } *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t uwatec_aladin_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; uwatec_aladin_device_t *device = (uwatec_aladin_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t uwatec_aladin_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { uwatec_aladin_device_t *device = (uwatec_aladin_device_t*) abstract; if (size && size != 4) return DC_STATUS_INVALIDARGS; if (size) device->timestamp = array_uint32_le (data); else device->timestamp = 0; return DC_STATUS_SUCCESS; } static dc_status_t uwatec_aladin_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { dc_status_t status = DC_STATUS_SUCCESS; uwatec_aladin_device_t *device = (uwatec_aladin_device_t*) abstract; // Pre-allocate the required amount of memory. if (!dc_buffer_reserve (buffer, SZ_MEMORY)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = SZ_MEMORY + 2; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); unsigned char answer[SZ_MEMORY + 2] = {0}; // Receive the header of the package. for (unsigned int i = 0; i < 4;) { if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; status = dc_iostream_read (device->iostream, answer + i, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } if (answer[i] == (i < 3 ? 0x55 : 0x00)) { i++; // Continue. } else { i = 0; // Reset. device_event_emit (abstract, DC_EVENT_WAITING, NULL); } } // Fetch the current system time. dc_ticks_t now = dc_datetime_now (); // Update and emit a progress event. progress.current += 4; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Receive the remaining part of the package. status = dc_iostream_read (device->iostream, answer + 4, sizeof (answer) - 4, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Unexpected EOF in answer."); return status; } // Update and emit a progress event. progress.current += sizeof (answer) - 4; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Reverse the bit order. array_reverse_bits (answer, sizeof (answer)); // Verify the checksum of the package. unsigned short crc = array_uint16_le (answer + SZ_MEMORY); unsigned short ccrc = checksum_add_uint16 (answer, SZ_MEMORY, 0x0000); if (ccrc != crc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } // Store the clock calibration values. device->systime = now; device->devtime = array_uint32_be (answer + HEADER + 0x7f8); // Emit a clock event. dc_event_clock_t clock; clock.systime = device->systime; clock.devtime = device->devtime; device_event_emit (abstract, DC_EVENT_CLOCK, &clock); dc_buffer_append (buffer, answer, SZ_MEMORY); return DC_STATUS_SUCCESS; } static dc_status_t uwatec_aladin_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { dc_buffer_t *buffer = dc_buffer_new (SZ_MEMORY); if (buffer == NULL) return DC_STATUS_NOMEMORY; dc_status_t rc = uwatec_aladin_device_dump (abstract, buffer); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } // Emit a device info event. unsigned char *data = dc_buffer_get_data (buffer); dc_event_devinfo_t devinfo; devinfo.model = data[HEADER + 0x7bc]; devinfo.firmware = 0; devinfo.serial = array_uint24_be (data + HEADER + 0x7ed); device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); rc = uwatec_aladin_extract_dives (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), callback, userdata); dc_buffer_free (buffer); return rc; } static dc_status_t uwatec_aladin_extract_dives (dc_device_t *abstract, const unsigned char* data, unsigned int size, dc_dive_callback_t callback, void *userdata) { uwatec_aladin_device_t *device = (uwatec_aladin_device_t*) abstract; if (abstract && !ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size < SZ_MEMORY) return DC_STATUS_DATAFORMAT; // The logbook ring buffer can store up to 37 dives. But // if the total number of dives is less, not all logbook // entries contain valid data. unsigned int ndives = array_uint16_be (data + HEADER + 0x7f2); if (ndives > 37) ndives = 37; // Get the index to the newest logbook entry. This value is // normally in the range from 1 to 37 and is converted to // a zero based index, taking care not to underflow. unsigned int eol = (data[HEADER + 0x7f4] + 37 - 1) % 37; // Get the end of the profile ring buffer. This value points // to the last byte of the last profile and is incremented // one byte to point immediately after the last profile. unsigned int eop = RB_PROFILE_NEXT (data[HEADER + 0x7f6] + (((data[HEADER + 0x7f7] & 0x0F) >> 1) << 8)); // Start scanning the profile ringbuffer. int profiles = 1; // Both ring buffers are traversed backwards to retrieve the most recent // dives first. This allows you to download only the new dives and avoids // having to rely on the number of profiles in the ring buffer (which // is buggy according to the documentation). During the traversal, the // previous pointer does always point to the end of the dive data and // we move the current pointer backwards until a start marker is found. unsigned int previous = eop; unsigned int current = eop; for (unsigned int i = 0; i < ndives; ++i) { // Memory buffer to store one dive. unsigned char buffer[18 + RB_PROFILE_END - RB_PROFILE_BEGIN] = {0}; // Get the offset to the current logbook entry. unsigned int offset = ((eol + 37 - i) % 37) * 12 + RB_PROFILE_END; // Copy the serial number, type and logbook data // to the buffer and set the profile length to zero. memcpy (buffer + 0, data + HEADER + 0x07ed, 3); memcpy (buffer + 3, data + HEADER + 0x07bc, 1); memcpy (buffer + 4, data + HEADER + offset, 12); memset (buffer + 16, 0, 2); // Convert the timestamp from the Aladin (big endian) // to the Memomouse format (little endian). array_reverse_bytes (buffer + 11, 4); unsigned int len = 0; if (profiles) { // Search the profile ringbuffer for a start marker. do { if (current == RB_PROFILE_BEGIN) current = RB_PROFILE_END; current--; if (data[HEADER + current] == 0xFF) { len = RB_PROFILE_DISTANCE (current, previous); previous = current; break; } } while (current != eop); if (len >= 1) { // Skip the start marker. len--; unsigned int begin = RB_PROFILE_NEXT (current); // Set the profile length. buffer[16] = (len ) & 0xFF; buffer[17] = (len >> 8) & 0xFF; // Copy the profile data. if (begin + len > RB_PROFILE_END) { unsigned int a = RB_PROFILE_END - begin; unsigned int b = (begin + len) - RB_PROFILE_END; memcpy (buffer + 18 + 0, data + HEADER + begin, a); memcpy (buffer + 18 + a, data + HEADER, b); } else { memcpy (buffer + 18, data + HEADER + begin, len); } } // Since the size of the profile ringbuffer is limited, // not all logbook entries will have profile data. Thus, // once the end of the profile ringbuffer is reached, // there is no need to keep scanning the ringbuffer. if (current == eop) profiles = 0; } // Automatically abort when a dive is older than the provided timestamp. unsigned int timestamp = array_uint32_le (buffer + 11); if (device && timestamp <= device->timestamp) return DC_STATUS_SUCCESS; if (callback && !callback (buffer, len + 18, buffer + 11, 4, userdata)) return DC_STATUS_SUCCESS; } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/uwatec_aladin.c
/* * libdivecomputer * * Copyright (C) 2014 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include "divesystem_idive.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_device_isinstance((parser), &divesystem_idive_parser_vtable) #define IX3M_EASY 0x22 #define IX3M_DEEP 0x23 #define IX3M_TEC 0x24 #define IX3M_REB 0x25 #define SZ_HEADER_IDIVE 0x32 #define SZ_SAMPLE_IDIVE 0x2A #define SZ_HEADER_IX3M 0x36 #define SZ_SAMPLE_IX3M 0x36 #define SZ_SAMPLE_IX3M_APOS4 0x40 #define NGASMIXES 8 #define EPOCH 1199145600 /* 2008-01-01 00:00:00 */ #define OC 0 #define SCR 1 #define CCR 2 #define GAUGE 3 #define FREEDIVE 4 #define INVALID 0xFFFFFFFF typedef struct divesystem_idive_parser_t divesystem_idive_parser_t; struct divesystem_idive_parser_t { dc_parser_t base; unsigned int model; unsigned int headersize; // Cached fields. unsigned int cached; unsigned int divemode; unsigned int divetime; unsigned int maxdepth; unsigned int ngasmixes; unsigned int oxygen[NGASMIXES]; unsigned int helium[NGASMIXES]; unsigned int beginpressure; unsigned int endpressure; }; static dc_status_t divesystem_idive_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t divesystem_idive_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t divesystem_idive_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t divesystem_idive_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t divesystem_idive_parser_vtable = { sizeof(divesystem_idive_parser_t), DC_FAMILY_DIVESYSTEM_IDIVE, divesystem_idive_parser_set_data, /* set_data */ divesystem_idive_parser_get_datetime, /* datetime */ divesystem_idive_parser_get_field, /* fields */ divesystem_idive_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; dc_status_t divesystem_idive_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int model) { divesystem_idive_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (divesystem_idive_parser_t *) dc_parser_allocate (context, &divesystem_idive_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. parser->model = model; if (model >= IX3M_EASY) { parser->headersize = SZ_HEADER_IX3M; } else { parser->headersize = SZ_HEADER_IDIVE; } parser->cached = 0; parser->divemode = INVALID; parser->divetime = 0; parser->maxdepth = 0; parser->ngasmixes = 0; for (unsigned int i = 0; i < NGASMIXES; ++i) { parser->oxygen[i] = 0; parser->helium[i] = 0; } parser->beginpressure = 0; parser->endpressure = 0; *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; } static dc_status_t divesystem_idive_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { divesystem_idive_parser_t *parser = (divesystem_idive_parser_t *) abstract; // Reset the cache. parser->cached = 0; parser->divemode = INVALID; parser->divetime = 0; parser->maxdepth = 0; parser->ngasmixes = 0; for (unsigned int i = 0; i < NGASMIXES; ++i) { parser->oxygen[i] = 0; parser->helium[i] = 0; } parser->beginpressure = 0; parser->endpressure = 0; return DC_STATUS_SUCCESS; } static dc_status_t divesystem_idive_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { divesystem_idive_parser_t *parser = (divesystem_idive_parser_t *) abstract; if (abstract->size < parser->headersize) return DC_STATUS_DATAFORMAT; dc_ticks_t ticks = array_uint32_le(abstract->data + 7) + EPOCH; if (!dc_datetime_localtime (datetime, ticks)) return DC_STATUS_DATAFORMAT; return DC_STATUS_SUCCESS; } static dc_status_t divesystem_idive_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { divesystem_idive_parser_t *parser = (divesystem_idive_parser_t *) abstract; const unsigned char *data = abstract->data; if (abstract->size < parser->headersize) return DC_STATUS_DATAFORMAT; if (!parser->cached) { dc_status_t rc = divesystem_idive_parser_samples_foreach (abstract, NULL, NULL); if (rc != DC_STATUS_SUCCESS) return rc; } dc_gasmix_t *gasmix = (dc_gasmix_t *) value; dc_tank_t *tank = (dc_tank_t *) value; dc_salinity_t *water = (dc_salinity_t *) value; if (value) { switch (type) { case DC_FIELD_DIVETIME: *((unsigned int *) value) = parser->divetime; break; case DC_FIELD_MAXDEPTH: *((double *) value) = parser->maxdepth / 10.0; break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = parser->ngasmixes; break; case DC_FIELD_GASMIX: gasmix->helium = parser->helium[flags] / 100.0; gasmix->oxygen = parser->oxygen[flags] / 100.0; gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium; break; case DC_FIELD_TANK_COUNT: if (parser->beginpressure == 0 && parser->endpressure == 0) return DC_STATUS_UNSUPPORTED; *((unsigned int *) value) = 1; break; case DC_FIELD_TANK: tank->type = DC_TANKVOLUME_NONE; tank->volume = 0.0; tank->workpressure = 0.0; tank->beginpressure = parser->beginpressure; tank->endpressure = parser->endpressure; tank->gasmix = DC_GASMIX_UNKNOWN; break; case DC_FIELD_ATMOSPHERIC: if (parser->model >= IX3M_EASY) { *((double *) value) = array_uint16_le (data + 11) / 10000.0; } else { *((double *) value) = array_uint16_le (data + 11) / 1000.0; } break; case DC_FIELD_SALINITY: water->type = data[34] == 0 ? DC_WATER_SALT : DC_WATER_FRESH; water->density = 0.0; break; case DC_FIELD_DIVEMODE: if (parser->divemode == 0xFFFFFFFF) return DC_STATUS_UNSUPPORTED; switch (parser->divemode) { case OC: *((dc_divemode_t *) value) = DC_DIVEMODE_OC; break; case SCR: *((dc_divemode_t *) value) = DC_DIVEMODE_SCR; break; case CCR: *((dc_divemode_t *) value) = DC_DIVEMODE_CCR; break; case GAUGE: *((dc_divemode_t *) value) = DC_DIVEMODE_GAUGE; break; case FREEDIVE: *((dc_divemode_t *) value) = DC_DIVEMODE_FREEDIVE; break; default: ERROR (abstract->context, "Unknown dive mode %02x.", parser->divemode); return DC_STATUS_DATAFORMAT; } break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t divesystem_idive_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { divesystem_idive_parser_t *parser = (divesystem_idive_parser_t *) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; unsigned int time = 0; unsigned int maxdepth = 0; unsigned int ngasmixes = 0; unsigned int oxygen[NGASMIXES]; unsigned int helium[NGASMIXES]; unsigned int o2_previous = 0xFFFFFFFF; unsigned int he_previous = 0xFFFFFFFF; unsigned int mode_previous = INVALID; unsigned int divemode = INVALID; unsigned int beginpressure = 0; unsigned int endpressure = 0; unsigned int firmware = 0; unsigned int apos4 = 0; unsigned int nsamples = array_uint16_le (data + 1); unsigned int samplesize = SZ_SAMPLE_IDIVE; if (parser->model >= IX3M_EASY) { // Detect the APOS4 firmware. firmware = array_uint32_le(data + 0x2A); apos4 = (firmware / 10000000) >= 4; if (apos4) { // Dive downloaded and recorded with the APOS4 firmware. samplesize = SZ_SAMPLE_IX3M_APOS4; } else if (size == parser->headersize + nsamples * SZ_SAMPLE_IX3M_APOS4) { // Dive downloaded with the APOS4 firmware, but recorded // with an older firmware. samplesize = SZ_SAMPLE_IX3M_APOS4; } else { // Dive downloaded and recorded with an older firmware. samplesize = SZ_SAMPLE_IX3M; } } else { firmware = array_uint32_le(data + 0x2E); } unsigned int offset = parser->headersize; while (offset + samplesize <= size) { dc_sample_value_t sample = {0}; // Time (seconds). unsigned int timestamp = array_uint32_le (data + offset + 2); if (timestamp <= time) { ERROR (abstract->context, "Timestamp moved backwards."); return DC_STATUS_DATAFORMAT; } time = timestamp; sample.time = timestamp; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Depth (1/10 m). unsigned int depth = array_uint16_le (data + offset + 6); if (maxdepth < depth) maxdepth = depth; sample.depth = depth / 10.0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); // Temperature (Celsius). signed int temperature = (signed short) array_uint16_le (data + offset + 8); sample.temperature = temperature / 10.0; if (callback) callback (DC_SAMPLE_TEMPERATURE, sample, userdata); // Dive mode unsigned int mode = data[offset + 18]; if (mode != mode_previous) { if (mode_previous != INVALID) { WARNING (abstract->context, "Dive mode changed from %02x to %02x.", mode_previous, mode); } mode_previous = mode; } if (divemode == INVALID) { divemode = mode; } // Setpoint if (mode == SCR || mode == CCR) { unsigned int setpoint = array_uint16_le (data + offset + 19); sample.setpoint = setpoint / 1000.0; if (callback) callback (DC_SAMPLE_SETPOINT, sample, userdata); } // Gaschange. unsigned int o2 = data[offset + 10]; unsigned int he = data[offset + 11]; if (o2 != o2_previous || he != he_previous) { // Find the gasmix in the list. unsigned int i = 0; while (i < ngasmixes) { if (o2 == oxygen[i] && he == helium[i]) break; i++; } // Add it to list if not found. if (i >= ngasmixes) { if (i >= NGASMIXES) { ERROR (abstract->context, "Maximum number of gas mixes reached."); return DC_STATUS_DATAFORMAT; } oxygen[i] = o2; helium[i] = he; ngasmixes = i + 1; } sample.gasmix = i; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); o2_previous = o2; he_previous = he; } // Deco stop / NDL. unsigned int decostop = 0, decotime = 0, tts = 0; if (apos4) { decostop = array_uint16_le (data + offset + 21); decotime = array_uint16_le (data + offset + 23); tts = array_uint16_le (data + offset + 25); if (tts == 0x7FFF) { tts = INVALID; } } else { decostop = array_uint16_le (data + offset + 21); tts = array_uint16_le (data + offset + 23); if (tts == 0xFFFF) { tts = INVALID; } } if (tts != INVALID) { if (decostop) { sample.deco.type = DC_DECO_DECOSTOP; sample.deco.depth = decostop / 10.0; sample.deco.time = apos4 ? decotime : tts; } else { sample.deco.type = DC_DECO_NDL; sample.deco.depth = 0.0; sample.deco.time = tts; } if (callback) callback (DC_SAMPLE_DECO, sample, userdata); } // CNS unsigned int cns = array_uint16_le (data + offset + 29); sample.cns = cns / 100.0; if (callback) callback (DC_SAMPLE_CNS, sample, userdata); // Tank Pressure if (samplesize == SZ_SAMPLE_IX3M_APOS4) { unsigned int pressure = data[offset + 49]; if (beginpressure == 0 && pressure != 0) { beginpressure = pressure; } if (beginpressure) { sample.pressure.tank = 0; sample.pressure.value = pressure; if (callback) callback (DC_SAMPLE_PRESSURE, sample, userdata); endpressure = pressure; } } offset += samplesize; } // Cache the data for later use. parser->beginpressure = beginpressure; parser->endpressure = endpressure; for (unsigned int i = 0; i < ngasmixes; ++i) { parser->helium[i] = helium[i]; parser->oxygen[i] = oxygen[i]; } parser->ngasmixes = ngasmixes; parser->maxdepth = maxdepth; parser->divetime = time; parser->divemode = divemode; parser->cached = 1; return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/divesystem_idive_parser.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcpy #include <stdlib.h> // malloc, free #include <assert.h> #include "oceanic_vtpro.h" #include "oceanic_common.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "ringbuffer.h" #include "checksum.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &oceanic_vtpro_device_vtable.base) #define MAXRETRIES 2 #define MULTIPAGE 4 #define ACK 0x5A #define NAK 0xA5 #define END 0x51 #define AERIS500AI 0x4151 typedef enum oceanic_vtpro_protocol_t { MOD, INTR, } oceanic_vtpro_protocol_t; typedef struct oceanic_vtpro_device_t { oceanic_common_device_t base; dc_iostream_t *iostream; unsigned int model; oceanic_vtpro_protocol_t protocol; } oceanic_vtpro_device_t; static dc_status_t oceanic_vtpro_device_logbook (dc_device_t *abstract, dc_event_progress_t *progress, dc_buffer_t *logbook); static dc_status_t oceanic_vtpro_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size); static dc_status_t oceanic_vtpro_device_close (dc_device_t *abstract); static const oceanic_common_device_vtable_t oceanic_vtpro_device_vtable = { { sizeof(oceanic_vtpro_device_t), DC_FAMILY_OCEANIC_VTPRO, oceanic_common_device_set_fingerprint, /* set_fingerprint */ oceanic_vtpro_device_read, /* read */ NULL, /* write */ oceanic_common_device_dump, /* dump */ oceanic_common_device_foreach, /* foreach */ NULL, /* timesync */ oceanic_vtpro_device_close /* close */ }, oceanic_vtpro_device_logbook, oceanic_common_device_profile, }; static const oceanic_common_version_t oceanic_vtpro_version[] = { {"VERSAPRO \0\0 256K"}, {"ATMOSTWO \0\0 256K"}, {"PROPLUS2 \0\0 256K"}, {"ATMOSAIR \0\0 256K"}, {"VTPRO r\0\0 256K"}, {"ELITE r\0\0 256K"}, }; static const oceanic_common_version_t oceanic_wisdom_version[] = { {"WISDOM r\0\0 256K"}, }; static const oceanic_common_layout_t oceanic_vtpro_layout = { 0x8000, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x0240, /* rb_logbook_begin */ 0x0440, /* rb_logbook_end */ 8, /* rb_logbook_entry_size */ 0x0440, /* rb_profile_begin */ 0x8000, /* rb_profile_end */ 0, /* pt_mode_global */ 0, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static const oceanic_common_layout_t oceanic_wisdom_layout = { 0x8000, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x03D0, /* rb_logbook_begin */ 0x05D0, /* rb_logbook_end */ 8, /* rb_logbook_entry_size */ 0x05D0, /* rb_profile_begin */ 0x8000, /* rb_profile_end */ 0, /* pt_mode_global */ 0, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static const oceanic_common_layout_t aeris_500ai_layout = { 0x20000, /* memsize */ 0x0000, /* cf_devinfo */ 0x0110, /* cf_pointers */ 0x0200, /* rb_logbook_begin */ 0x0200, /* rb_logbook_end */ 8, /* rb_logbook_entry_size */ 0x00200, /* rb_profile_begin */ 0x20000, /* rb_profile_end */ 0, /* pt_mode_global */ 1, /* pt_mode_logbook */ 2, /* pt_mode_serial */ }; static dc_status_t oceanic_vtpro_send (oceanic_vtpro_device_t *device, const unsigned char command[], unsigned int csize) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; // Send the command to the dive computer. status = dc_iostream_write (device->iostream, command, csize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Receive the response (ACK/NAK) of the dive computer. unsigned char response = NAK; status = dc_iostream_read (device->iostream, &response, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Verify the response of the dive computer. if (response != ACK) { ERROR (abstract->context, "Unexpected answer start byte(s)."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } static dc_status_t oceanic_vtpro_transfer (oceanic_vtpro_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; // Send the command to the device. If the device responds with an // ACK byte, the command was received successfully and the answer // (if any) follows after the ACK byte. If the device responds with // a NAK byte, we try to resend the command a number of times before // returning an error. unsigned int nretries = 0; dc_status_t rc = DC_STATUS_SUCCESS; while ((rc = oceanic_vtpro_send (device, command, csize)) != DC_STATUS_SUCCESS) { if (rc != DC_STATUS_TIMEOUT && rc != DC_STATUS_PROTOCOL) return rc; // Abort if the maximum number of retries is reached. if (nretries++ >= MAXRETRIES) return rc; } if (asize) { // Receive the answer of the dive computer. status = dc_iostream_read (device->iostream, answer, asize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } } return DC_STATUS_SUCCESS; } static dc_status_t oceanic_vtpro_init (oceanic_vtpro_device_t *device) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; // Send the command to the dive computer. unsigned char command[2][2] = { {0xAA, 0x00}, {0x20, 0x00}}; status = dc_iostream_write (device->iostream, command[device->protocol], sizeof (command[device->protocol]), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Receive the answer of the dive computer. unsigned char answer[13] = {0}; status = dc_iostream_read (device->iostream, answer, sizeof (answer), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Verify the answer. const unsigned char response[2][13] = { {0x4D, 0x4F, 0x44, 0x2D, 0x2D, 0x4F, 0x4B, 0x5F, 0x56, 0x32, 0x2E, 0x30, 0x30}, {0x49, 0x4E, 0x54, 0x52, 0x2D, 0x4F, 0x4B, 0x5F, 0x56, 0x31, 0x2E, 0x31, 0x31}}; if (memcmp (answer, response[device->protocol], sizeof (response[device->protocol])) != 0) { ERROR (abstract->context, "Unexpected answer byte(s)."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } static dc_status_t oceanic_vtpro_quit (oceanic_vtpro_device_t *device) { dc_device_t *abstract = (dc_device_t *) device; // Send the command to the dive computer. unsigned char answer[1] = {0}; unsigned char command[4] = {0x6A, 0x05, 0xA5, 0x00}; dc_status_t rc = oceanic_vtpro_transfer (device, command, sizeof (command), answer, sizeof (answer)); if (rc != DC_STATUS_SUCCESS) return rc; // Verify the last byte of the answer. if (answer[0] != END) { ERROR (abstract->context, "Unexpected answer byte(s)."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } static dc_status_t oceanic_vtpro_calibrate (oceanic_vtpro_device_t *device) { dc_device_t *abstract = (dc_device_t *) device; // Send the command to the dive computer. // The timeout is temporary increased, because the // device needs approximately 6 seconds to respond. unsigned char answer[2] = {0}; unsigned char command[2] = {0x18, 0x00}; dc_status_t rc = dc_iostream_set_timeout (device->iostream, 9000); if (rc != DC_STATUS_SUCCESS) return rc; rc = oceanic_vtpro_transfer (device, command, sizeof (command), answer, sizeof (answer)); if (rc != DC_STATUS_SUCCESS) return rc; rc = dc_iostream_set_timeout (device->iostream, 3000); if (rc != DC_STATUS_SUCCESS) return rc; // Verify the last byte of the answer. if (answer[1] != 0x00) { ERROR (abstract->context, "Unexpected answer byte(s)."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } static dc_status_t oceanic_aeris500ai_device_logbook (dc_device_t *abstract, dc_event_progress_t *progress, dc_buffer_t *logbook) { dc_status_t rc = DC_STATUS_SUCCESS; oceanic_vtpro_device_t *device = (oceanic_vtpro_device_t *) abstract; assert (device != NULL); assert (device->base.layout != NULL); assert (device->base.layout->rb_logbook_entry_size == PAGESIZE / 2); assert (device->base.layout->rb_logbook_begin == device->base.layout->rb_logbook_end); assert (progress != NULL); const oceanic_common_layout_t *layout = device->base.layout; // Erase the buffer. if (!dc_buffer_clear (logbook)) return DC_STATUS_NOMEMORY; // Read the pointer data. unsigned char pointers[PAGESIZE] = {0}; rc = oceanic_vtpro_device_read (abstract, layout->cf_pointers, pointers, sizeof (pointers)); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the memory page."); return rc; } // Get the logbook pointers. unsigned int last = pointers[0x03]; // Update and emit a progress event. progress->current += PAGESIZE; progress->maximum += PAGESIZE + (last + 1) * PAGESIZE / 2; device_event_emit (abstract, DC_EVENT_PROGRESS, progress); // Allocate memory for the logbook entries. if (!dc_buffer_reserve (logbook, (last + 1) * PAGESIZE / 2)) return DC_STATUS_NOMEMORY; // Send the logbook index command. unsigned char command[] = {0x52, (last >> 8) & 0xFF, // high (last ) & 0xFF, // low 0x00}; rc = oceanic_vtpro_transfer (device, command, sizeof (command), NULL, 0); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the logbook index command."); return rc; } // Read the logbook index. for (unsigned int i = 0; i < last + 1; ++i) { // Receive the answer of the dive computer. unsigned char answer[PAGESIZE / 2 + 1] = {0}; rc = dc_iostream_read (device->iostream, answer, sizeof(answer), NULL); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return rc; } // Verify the checksum of the answer. unsigned char crc = answer[PAGESIZE / 2]; unsigned char ccrc = checksum_add_uint4 (answer, PAGESIZE / 2, 0x00); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } // Update and emit a progress event. progress->current += PAGESIZE / 2; device_event_emit (abstract, DC_EVENT_PROGRESS, progress); // Ignore uninitialized entries. if (array_isequal (answer, PAGESIZE / 2, 0xFF)) { WARNING (abstract->context, "Uninitialized logbook entries detected!"); continue; } // Compare the fingerprint to identify previously downloaded entries. if (memcmp (answer, device->base.fingerprint, PAGESIZE / 2) == 0) { dc_buffer_clear (logbook); } else { dc_buffer_append (logbook, answer, PAGESIZE / 2); } } return DC_STATUS_SUCCESS; } static dc_status_t oceanic_vtpro_device_logbook (dc_device_t *abstract, dc_event_progress_t *progress, dc_buffer_t *logbook) { oceanic_vtpro_device_t *device = (oceanic_vtpro_device_t *) abstract; if (device->model == AERIS500AI) { return oceanic_aeris500ai_device_logbook (abstract, progress, logbook); } else { return oceanic_common_device_logbook (abstract, progress, logbook); } } dc_status_t oceanic_vtpro_device_open (dc_device_t **out, dc_context_t *context, const char *name, unsigned int model) { dc_status_t status = DC_STATUS_SUCCESS; oceanic_vtpro_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (oceanic_vtpro_device_t *) dc_device_allocate (context, &oceanic_vtpro_device_vtable.base); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Initialize the base class. oceanic_common_device_init (&device->base); // Override the base class values. device->base.multipage = MULTIPAGE; // Set the default values. device->iostream = NULL; device->model = model; if (model == AERIS500AI) { device->protocol = INTR; } else { device->protocol = MOD; } // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (9600 8N1). status = dc_iostream_configure (device->iostream, 9600, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (3000 ms). status = dc_iostream_set_timeout (device->iostream, 3000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Set the DTR line. status = dc_iostream_set_dtr (device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the DTR line."); goto error_close; } // Set the RTS line. status = dc_iostream_set_rts (device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the RTS line."); goto error_close; } // Give the interface 100 ms to settle and draw power up. dc_iostream_sleep (device->iostream, device->protocol == MOD ? 100 : 1000); // Make sure everything is in a sane state. dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); // Initialize the data cable (MOD mode). status = oceanic_vtpro_init (device); if (status != DC_STATUS_SUCCESS) { goto error_close; } // Switch the device from surface mode into download mode. Before sending // this command, the device needs to be in PC mode (manually activated by // the user), or already in download mode. status = oceanic_vtpro_device_version ((dc_device_t *) device, device->base.version, sizeof (device->base.version)); if (status != DC_STATUS_SUCCESS) { goto error_close; } // Calibrate the device. Although calibration is optional, it's highly // recommended because it reduces the transfer time considerably, even // when processing the command itself is quite slow. status = oceanic_vtpro_calibrate (device); if (status != DC_STATUS_SUCCESS) { goto error_close; } // Override the base class values. if (model == AERIS500AI) { device->base.layout = &aeris_500ai_layout; } else if (OCEANIC_COMMON_MATCH (device->base.version, oceanic_wisdom_version)) { device->base.layout = &oceanic_wisdom_layout; } else if (OCEANIC_COMMON_MATCH (device->base.version, oceanic_vtpro_version)) { device->base.layout = &oceanic_vtpro_layout; } else { WARNING (context, "Unsupported device detected!"); device->base.layout = &oceanic_vtpro_layout; } *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t oceanic_vtpro_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; oceanic_vtpro_device_t *device = (oceanic_vtpro_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Switch the device back to surface mode. rc = oceanic_vtpro_quit (device); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } dc_status_t oceanic_vtpro_device_keepalive (dc_device_t *abstract) { oceanic_vtpro_device_t *device = (oceanic_vtpro_device_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; // Send the command to the dive computer. unsigned char answer[1] = {0}; unsigned char command[4] = {0x6A, 0x08, 0x00, 0x00}; dc_status_t rc = oceanic_vtpro_transfer (device, command, sizeof (command), answer, sizeof (answer)); if (rc != DC_STATUS_SUCCESS) return rc; // Verify the last byte of the answer. if (answer[0] != END) { ERROR (abstract->context, "Unexpected answer byte(s)."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } dc_status_t oceanic_vtpro_device_version (dc_device_t *abstract, unsigned char data[], unsigned int size) { oceanic_vtpro_device_t *device = (oceanic_vtpro_device_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size < PAGESIZE) return DC_STATUS_INVALIDARGS; // Switch the device into download mode. The response is ignored here, // since it is identical (except for the missing trailing byte) to the // response of the first part of the other command in this function. unsigned char cmd[2] = {0x88, 0x00}; unsigned char ans[PAGESIZE / 2 + 1] = {0}; dc_status_t rc = oceanic_vtpro_transfer (device, cmd, sizeof (cmd), ans, sizeof (ans)); if (rc != DC_STATUS_SUCCESS) return rc; // Verify the checksum of the answer. unsigned char crc = ans[PAGESIZE / 2]; unsigned char ccrc = checksum_add_uint4 (ans, PAGESIZE / 2, 0x00); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } if (device->protocol == MOD) { // Obtain the device identification string. This string is // split over two packets, but we join both parts again. for (unsigned int i = 0; i < 2; ++i) { unsigned char command[4] = {0x72, 0x03, i * 0x10, 0x00}; unsigned char answer[PAGESIZE / 2 + 2] = {0}; rc = oceanic_vtpro_transfer (device, command, sizeof (command), answer, sizeof (answer)); if (rc != DC_STATUS_SUCCESS) return rc; // Verify the checksum of the answer. unsigned char crc = answer[PAGESIZE / 2]; unsigned char ccrc = checksum_add_uint4 (answer, PAGESIZE / 2, 0x00); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } // Verify the last byte of the answer. if (answer[PAGESIZE / 2 + 1] != END) { ERROR (abstract->context, "Unexpected answer byte."); return DC_STATUS_PROTOCOL; } // Append the answer to the output buffer. memcpy (data + i * PAGESIZE / 2, answer, PAGESIZE / 2); } } else { // Return an empty device identification string. memset (data, 0x00, PAGESIZE); } return DC_STATUS_SUCCESS; } static dc_status_t oceanic_vtpro_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size) { oceanic_vtpro_device_t *device = (oceanic_vtpro_device_t*) abstract; if ((address % PAGESIZE != 0) || (size % PAGESIZE != 0)) return DC_STATUS_INVALIDARGS; unsigned int nbytes = 0; while (nbytes < size) { // Calculate the number of packages. unsigned int npackets = (size - nbytes) / PAGESIZE; if (npackets > MULTIPAGE) npackets = MULTIPAGE; // Read the package. unsigned int first = address / PAGESIZE; unsigned int last = first + npackets - 1; unsigned char answer[(PAGESIZE + 1) * MULTIPAGE] = {0}; unsigned char command[6] = {0x34, (first >> 8) & 0xFF, // high (first ) & 0xFF, // low (last >> 8) & 0xFF, // high (last ) & 0xFF, // low 0x00}; dc_status_t rc = oceanic_vtpro_transfer (device, command, sizeof (command), answer, (PAGESIZE + 1) * npackets); if (rc != DC_STATUS_SUCCESS) return rc; unsigned int offset = 0; for (unsigned int i = 0; i < npackets; ++i) { // Verify the checksum of the answer. unsigned char crc = answer[offset + PAGESIZE]; unsigned char ccrc = checksum_add_uint8 (answer + offset, PAGESIZE, 0x00); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } memcpy (data, answer + offset, PAGESIZE); offset += PAGESIZE + 1; nbytes += PAGESIZE; address += PAGESIZE; data += PAGESIZE; } } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/oceanic_vtpro.c
/* * libdivecomputer * * Copyright (C) 2011 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <stdio.h> #include <string.h> #ifdef _MSC_VER #define snprintf _snprintf #endif #include <libdivecomputer/units.h> #include "atomics_cobalt.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_parser_isinstance((parser), &atomics_cobalt_parser_vtable) #define SZ_HEADER 228 #define SZ_GASMIX 18 #define SZ_GASSWITCH 6 #define SZ_SEGMENT 16 typedef struct atomics_cobalt_parser_t atomics_cobalt_parser_t; struct atomics_cobalt_parser_t { dc_parser_t base; // Depth calibration. double atmospheric; double hydrostatic; }; static dc_status_t atomics_cobalt_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t atomics_cobalt_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t atomics_cobalt_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t atomics_cobalt_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t atomics_cobalt_parser_vtable = { sizeof(atomics_cobalt_parser_t), DC_FAMILY_ATOMICS_COBALT, atomics_cobalt_parser_set_data, /* set_data */ atomics_cobalt_parser_get_datetime, /* datetime */ atomics_cobalt_parser_get_field, /* fields */ atomics_cobalt_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; dc_status_t atomics_cobalt_parser_create (dc_parser_t **out, dc_context_t *context) { atomics_cobalt_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (atomics_cobalt_parser_t *) dc_parser_allocate (context, &atomics_cobalt_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. parser->atmospheric = 0.0; parser->hydrostatic = 1025.0 * GRAVITY; *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; } static dc_status_t atomics_cobalt_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { return DC_STATUS_SUCCESS; } dc_status_t atomics_cobalt_parser_set_calibration (dc_parser_t *abstract, double atmospheric, double hydrostatic) { atomics_cobalt_parser_t *parser = (atomics_cobalt_parser_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; parser->atmospheric = atmospheric; parser->hydrostatic = hydrostatic; return DC_STATUS_SUCCESS; } static dc_status_t atomics_cobalt_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { if (abstract->size < SZ_HEADER) return DC_STATUS_DATAFORMAT; const unsigned char *p = abstract->data; if (datetime) { datetime->year = array_uint16_le (p + 0x14); datetime->month = p[0x16]; datetime->day = p[0x17]; datetime->hour = p[0x18]; datetime->minute = p[0x19]; datetime->second = 0; datetime->timezone = DC_TIMEZONE_NONE; } return DC_STATUS_SUCCESS; } #define BUFLEN 16 static dc_status_t atomics_cobalt_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { atomics_cobalt_parser_t *parser = (atomics_cobalt_parser_t *) abstract; if (abstract->size < SZ_HEADER) return DC_STATUS_DATAFORMAT; const unsigned char *p = abstract->data; dc_gasmix_t *gasmix = (dc_gasmix_t *) value; dc_tank_t *tank = (dc_tank_t *) value; double atmospheric = 0.0; char buf[BUFLEN]; dc_field_string_t *string = (dc_field_string_t *) value; if (parser->atmospheric) atmospheric = parser->atmospheric; else atmospheric = array_uint16_le (p + 0x26) * BAR / 1000.0; unsigned int workpressure = 0; if (value) { switch (type) { case DC_FIELD_DIVETIME: *((unsigned int *) value) = array_uint16_le (p + 0x58) * 60; break; case DC_FIELD_MAXDEPTH: *((double *) value) = (array_uint16_le (p + 0x56) * BAR / 1000.0 - atmospheric) / parser->hydrostatic; break; case DC_FIELD_GASMIX_COUNT: case DC_FIELD_TANK_COUNT: *((unsigned int *) value) = p[0x2a]; break; case DC_FIELD_GASMIX: gasmix->helium = p[SZ_HEADER + SZ_GASMIX * flags + 5] / 100.0; gasmix->oxygen = p[SZ_HEADER + SZ_GASMIX * flags + 4] / 100.0; gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium; break; case DC_FIELD_TEMPERATURE_SURFACE: *((double *) value) = (p[0x1B] - 32.0) * (5.0 / 9.0); break; case DC_FIELD_TANK: p += SZ_HEADER + SZ_GASMIX * flags; switch (p[2]) { case 1: // Cuft at psi case 2: // Cuft at bar workpressure = array_uint16_le(p + 10); if (workpressure == 0) return DC_STATUS_DATAFORMAT; tank->type = DC_TANKVOLUME_IMPERIAL; tank->volume = array_uint16_le(p + 8) * CUFT * 1000.0; tank->volume /= workpressure * PSI / ATM; tank->workpressure = workpressure * PSI / BAR; break; case 3: // Wet volume in 1/10 liter tank->type = DC_TANKVOLUME_METRIC; tank->volume = array_uint16_le(p + 8) / 10.0; tank->workpressure = 0.0; break; default: return DC_STATUS_DATAFORMAT; } tank->gasmix = flags; tank->beginpressure = array_uint16_le(p + 6) * PSI / BAR; tank->endpressure = array_uint16_le(p + 14) * PSI / BAR; break; case DC_FIELD_DIVEMODE: switch(p[0x24]) { case 0: // Open Circuit Trimix case 2: // Open Circuit Nitrox *((dc_divemode_t *) value) = DC_DIVEMODE_OC; break; case 1: // Closed Circuit *((dc_divemode_t *) value) = DC_DIVEMODE_CCR; break; default: return DC_STATUS_DATAFORMAT; } break; case DC_FIELD_STRING: switch(flags) { case 0: // Serialnr string->desc = "Serial"; snprintf(buf, BUFLEN, "%c%c%c%c-%c%c%c%c", p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[11]); break; case 1: // Program Version string->desc = "Program Version"; snprintf(buf, BUFLEN, "%.2f", array_uint16_le(p + 30) / 100.0); break; case 2: // Boot Version string->desc = "Boot Version"; snprintf(buf, BUFLEN, "%.2f", array_uint16_le(p + 32) / 100.0); break; case 3: // Nofly string->desc = "NoFly Time"; snprintf(buf, BUFLEN, "%0u:%02u", p[0x52], p[0x53]); break; default: return DC_STATUS_UNSUPPORTED; } string->value = strdup(buf); break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t atomics_cobalt_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { atomics_cobalt_parser_t *parser = (atomics_cobalt_parser_t *) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; if (size < SZ_HEADER) return DC_STATUS_DATAFORMAT; unsigned int interval = data[0x1a]; unsigned int ngasmixes = data[0x2a]; unsigned int nswitches = data[0x2b]; unsigned int nsegments = array_uint16_le (data + 0x50); unsigned int header = SZ_HEADER + SZ_GASMIX * ngasmixes + SZ_GASSWITCH * nswitches; if (size < header + SZ_SEGMENT * nsegments) return DC_STATUS_DATAFORMAT; double atmospheric = 0.0; if (parser->atmospheric) atmospheric = parser->atmospheric; else atmospheric = array_uint16_le (data + 0x26) * BAR / 1000.0; // Previous gas mix - initialize with impossible value unsigned int gasmix_previous = 0xFFFFFFFF; // Get the primary tank. unsigned int tank = 0; while (tank < ngasmixes) { unsigned int sensor = array_uint16_le(data + SZ_HEADER + SZ_GASMIX * tank + 12); if (sensor == 1) break; tank++; } if (tank >= ngasmixes) { ERROR (abstract->context, "Invalid primary tank index."); return DC_STATUS_DATAFORMAT; } unsigned int time = 0; unsigned int in_deco = 0; unsigned int offset = header; while (offset + SZ_SEGMENT <= size) { dc_sample_value_t sample = {0}; // Time (seconds). time += interval; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Depth (1/1000 bar). unsigned int depth = array_uint16_le (data + offset + 0); sample.depth = (depth * BAR / 1000.0 - atmospheric) / parser->hydrostatic; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); // Pressure (1 psi). unsigned int pressure = array_uint16_le (data + offset + 2); sample.pressure.tank = tank; sample.pressure.value = pressure * PSI / BAR; if (callback) callback (DC_SAMPLE_PRESSURE, sample, userdata); // Current gas mix unsigned int gasmix = data[offset + 4]; if (gasmix != gasmix_previous) { unsigned int idx = 0; while (idx < ngasmixes) { if (data[SZ_HEADER + SZ_GASMIX * idx + 0] == gasmix) break; idx++; } if (idx >= ngasmixes) { ERROR (abstract->context, "Invalid gas mix index."); return DC_STATUS_DATAFORMAT; } sample.gasmix = idx; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); gasmix_previous = gasmix; } // Temperature (1 °F). unsigned int temperature = data[offset + 8]; sample.temperature = (temperature - 32.0) * (5.0 / 9.0); if (callback) callback (DC_SAMPLE_TEMPERATURE, sample, userdata); // violation status sample.event.type = 0; sample.event.time = 0; sample.event.value = 0; sample.event.flags = 0; unsigned int violation = data[offset + 11]; if (violation & 0x01) { sample.event.type = SAMPLE_EVENT_ASCENT; if (callback) callback (DC_SAMPLE_EVENT, sample, userdata); } if (violation & 0x04) { sample.event.type = SAMPLE_EVENT_CEILING; if (callback) callback (DC_SAMPLE_EVENT, sample, userdata); } if (violation & 0x08) { sample.event.type = SAMPLE_EVENT_PO2; if (callback) callback (DC_SAMPLE_EVENT, sample, userdata); } // NDL & deco unsigned int ndl = data[offset + 5] * 60; if (ndl > 0) in_deco = 0; else if (ndl == 0 && (violation & 0x02)) in_deco = 1; if (in_deco) sample.deco.type = DC_DECO_DECOSTOP; else sample.deco.type = DC_DECO_NDL; sample.deco.time = ndl; sample.deco.depth = 0.0; if (callback) callback (DC_SAMPLE_DECO, sample, userdata); offset += SZ_SEGMENT; } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/atomics_cobalt_parser.c
/* * libdivecomputer * * Copyright (C) 2009 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <libdivecomputer/units.h> #include "oceanic_veo250.h" #include "oceanic_common.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_parser_isinstance((parser), &oceanic_veo250_parser_vtable) #define REACTPRO 0x4247 #define VEO200 0x424B #define VEO250 0x424C #define INSIGHT 0x425A #define REACTPROWHITE 0x4354 typedef struct oceanic_veo250_parser_t oceanic_veo250_parser_t; struct oceanic_veo250_parser_t { dc_parser_t base; unsigned int model; // Cached fields. unsigned int cached; unsigned int divetime; double maxdepth; }; static dc_status_t oceanic_veo250_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t oceanic_veo250_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t oceanic_veo250_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t oceanic_veo250_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t oceanic_veo250_parser_vtable = { sizeof(oceanic_veo250_parser_t), DC_FAMILY_OCEANIC_VEO250, oceanic_veo250_parser_set_data, /* set_data */ oceanic_veo250_parser_get_datetime, /* datetime */ oceanic_veo250_parser_get_field, /* fields */ oceanic_veo250_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; dc_status_t oceanic_veo250_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int model) { oceanic_veo250_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (oceanic_veo250_parser_t *) dc_parser_allocate (context, &oceanic_veo250_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. parser->model = model; parser->cached = 0; parser->divetime = 0; parser->maxdepth = 0.0; *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; } static dc_status_t oceanic_veo250_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { oceanic_veo250_parser_t *parser = (oceanic_veo250_parser_t *) abstract; // Reset the cache. parser->cached = 0; parser->divetime = 0; parser->maxdepth = 0.0; return DC_STATUS_SUCCESS; } static dc_status_t oceanic_veo250_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { oceanic_veo250_parser_t *parser = (oceanic_veo250_parser_t *) abstract; if (abstract->size < 8) return DC_STATUS_DATAFORMAT; const unsigned char *p = abstract->data; if (datetime) { datetime->year = ((p[5] & 0xF0) >> 4) + ((p[1] & 0xE0) >> 1) + 2000; datetime->month = ((p[7] & 0xF0) >> 4); datetime->day = p[1] & 0x1F; datetime->hour = p[3]; datetime->minute = p[2]; datetime->second = 0; datetime->timezone = DC_TIMEZONE_NONE; if (parser->model == VEO200 || parser->model == VEO250) datetime->year += 3; else if (parser->model == REACTPRO) datetime->year += 2; } return DC_STATUS_SUCCESS; } static dc_status_t oceanic_veo250_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { oceanic_veo250_parser_t *parser = (oceanic_veo250_parser_t *) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; if (size < 7 * PAGESIZE / 2) return DC_STATUS_DATAFORMAT; if (!parser->cached) { sample_statistics_t statistics = SAMPLE_STATISTICS_INITIALIZER; dc_status_t rc = oceanic_veo250_parser_samples_foreach ( abstract, sample_statistics_cb, &statistics); if (rc != DC_STATUS_SUCCESS) return rc; parser->cached = 1; parser->divetime = statistics.divetime; parser->maxdepth = statistics.maxdepth; } unsigned int footer = size - PAGESIZE; dc_gasmix_t *gasmix = (dc_gasmix_t *) value; if (value) { switch (type) { case DC_FIELD_DIVETIME: *((unsigned int *) value) = data[footer + 3] * 60 + data[footer + 4] * 3600; break; case DC_FIELD_MAXDEPTH: *((double *) value) = parser->maxdepth; break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = 1; break; case DC_FIELD_GASMIX: gasmix->helium = 0.0; if (data[footer + 6]) gasmix->oxygen = data[footer + 6] / 100.0; else gasmix->oxygen = 0.21; gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium; break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t oceanic_veo250_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { oceanic_veo250_parser_t *parser = (oceanic_veo250_parser_t *) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; if (size < 7 * PAGESIZE / 2) return DC_STATUS_DATAFORMAT; unsigned int time = 0; unsigned int interval = 0; unsigned int interval_idx = data[0x27] & 0x03; if (parser->model == REACTPRO || parser->model == REACTPROWHITE) { interval_idx += 1; interval_idx %= 4; } switch (interval_idx) { case 0: interval = 2; break; case 1: interval = 15; break; case 2: interval = 30; break; case 3: interval = 60; break; } unsigned int offset = 5 * PAGESIZE / 2; while (offset + PAGESIZE / 2 <= size - PAGESIZE) { dc_sample_value_t sample = {0}; // Ignore empty samples. if (array_isequal (data + offset, PAGESIZE / 2, 0x00)) { offset += PAGESIZE / 2; continue; } // Time. time += interval; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Vendor specific data sample.vendor.type = SAMPLE_VENDOR_OCEANIC_VEO250; sample.vendor.size = PAGESIZE / 2; sample.vendor.data = data + offset; if (callback) callback (DC_SAMPLE_VENDOR, sample, userdata); // Depth (ft) unsigned int depth = data[offset + 2]; sample.depth = depth * FEET; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); // Temperature (°F) unsigned int temperature; if (parser->model == REACTPRO || parser->model == REACTPROWHITE || parser->model == INSIGHT) { temperature = data[offset + 6]; } else { temperature = data[offset + 7]; } sample.temperature = (temperature - 32.0) * (5.0 / 9.0); if (callback) callback (DC_SAMPLE_TEMPERATURE, sample, userdata); // NDL / Deco unsigned int have_deco = 0; unsigned int decostop = 0, decotime = 0; if (parser->model == REACTPRO || parser->model == REACTPROWHITE || parser->model == INSIGHT) { decostop = (data[offset + 7] & 0xF0) >> 4; decotime = ((data[offset + 3] & 0xC0) << 2) | data[offset + 4]; have_deco = 1; } else { decostop = (data[offset + 5] & 0xF0) >> 4; decotime = array_uint16_le(data + offset + 4) & 0x0FFF; have_deco = 1; } if (have_deco) { if (decostop) { sample.deco.type = DC_DECO_DECOSTOP; sample.deco.depth = decostop * 10 * FEET; } else { sample.deco.type = DC_DECO_NDL; sample.deco.depth = 0.0; } sample.deco.time = decotime * 60; if (callback) callback (DC_SAMPLE_DECO, sample, userdata); } offset += PAGESIZE / 2; } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/oceanic_veo250_parser.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> // malloc, free #include <stdio.h> // snprintf #include <string.h> #include "socket.h" #ifdef _WIN32 #ifdef HAVE_AF_IRDA_H #define IRDA #include <af_irda.h> #endif #else #ifdef HAVE_LINUX_IRDA_H #define IRDA #include <linux/types.h> #include <linux/irda.h> #endif #endif #include "irda.h" #include "common-private.h" #include "context-private.h" #include "iostream-private.h" #include "iterator-private.h" #include "descriptor-private.h" #include "array.h" #include "platform.h" #define ISINSTANCE(device) dc_iostream_isinstance((device), &dc_irda_vtable) #define DISCOVER_MAX_DEVICES 16 // Maximum number of devices. #define DISCOVER_MAX_RETRIES 4 // Maximum number of retries. #ifdef _WIN32 #define DISCOVER_BUFSIZE sizeof (DEVICELIST) + \ sizeof (IRDA_DEVICE_INFO) * (DISCOVER_MAX_DEVICES - 1) #else #define DISCOVER_BUFSIZE sizeof (struct irda_device_list) + \ sizeof (struct irda_device_info) * (DISCOVER_MAX_DEVICES - 1) #endif struct dc_irda_device_t { unsigned int address; unsigned int charset; unsigned int hints; char name[22]; }; #ifdef IRDA static dc_status_t dc_irda_iterator_next (dc_iterator_t *iterator, void *item); typedef struct dc_irda_iterator_t { dc_iterator_t base; dc_irda_device_t items[DISCOVER_MAX_DEVICES]; size_t count; size_t current; } dc_irda_iterator_t; static const dc_iterator_vtable_t dc_irda_iterator_vtable = { sizeof(dc_irda_iterator_t), dc_irda_iterator_next, NULL, }; static const dc_iostream_vtable_t dc_irda_vtable = { sizeof(dc_socket_t), dc_socket_set_timeout, /* set_timeout */ dc_socket_set_latency, /* set_latency */ dc_socket_set_break, /* set_break */ dc_socket_set_dtr, /* set_dtr */ dc_socket_set_rts, /* set_rts */ dc_socket_get_lines, /* get_lines */ dc_socket_get_available, /* get_received */ dc_socket_configure, /* configure */ dc_socket_read, /* read */ dc_socket_write, /* write */ dc_socket_flush, /* flush */ dc_socket_purge, /* purge */ dc_socket_sleep, /* sleep */ dc_socket_close, /* close */ }; #endif unsigned int dc_irda_device_get_address (dc_irda_device_t *device) { if (device == NULL) return 0; return device->address; } const char * dc_irda_device_get_name (dc_irda_device_t *device) { if (device == NULL || device->name[0] == '\0') return NULL; return device->name; } void dc_irda_device_free (dc_irda_device_t *device) { free (device); } dc_status_t dc_irda_iterator_new (dc_iterator_t **out, dc_context_t *context, dc_descriptor_t *descriptor) { #ifdef IRDA dc_status_t status = DC_STATUS_SUCCESS; dc_irda_iterator_t *iterator = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; iterator = (dc_irda_iterator_t *) dc_iterator_allocate (context, &dc_irda_iterator_vtable); if (iterator == NULL) { SYSERROR (context, S_ENOMEM); return DC_STATUS_NOMEMORY; } // Initialize the socket library. status = dc_socket_init (context); if (status != DC_STATUS_SUCCESS) { goto error_free; } // Open the socket. int fd = socket (AF_IRDA, SOCK_STREAM, 0); if (fd == S_INVALID) { s_errcode_t errcode = S_ERRNO; SYSERROR (context, errcode); status = dc_socket_syserror(errcode); goto error_socket_exit; } unsigned char data[DISCOVER_BUFSIZE] = {0}; #ifdef _WIN32 DEVICELIST *list = (DEVICELIST *) data; #else struct irda_device_list *list = (struct irda_device_list *) data; #endif s_socklen_t size = sizeof (data); int rc = 0; unsigned int nretries = 0; while ((rc = getsockopt (fd, SOL_IRLMP, IRLMP_ENUMDEVICES, (char *) data, &size)) != 0 || #ifdef _WIN32 list->numDevice == 0) #else list->len == 0) #endif { // Automatically retry the discovery when no devices were found. // On Linux, getsockopt fails with EAGAIN when no devices are // discovered, while on Windows it succeeds and sets the number // of devices to zero. Both situations are handled the same here. if (rc != 0) { s_errcode_t errcode = S_ERRNO; if (errcode != S_EAGAIN) { SYSERROR (context, errcode); status = dc_socket_syserror(errcode); goto error_socket_close; } } // Abort if the maximum number of retries is reached. if (nretries++ >= DISCOVER_MAX_RETRIES) { break; } // Restore the size parameter in case it was // modified by the previous getsockopt call. size = sizeof (data); #ifdef _WIN32 Sleep (1000); #else sleep (1); #endif } S_CLOSE (fd); dc_socket_exit (context); dc_filter_t filter = dc_descriptor_get_filter (descriptor); unsigned int count = 0; #ifdef _WIN32 for (size_t i = 0; i < list->numDevice; ++i) { const char *name = list->Device[i].irdaDeviceName; unsigned int address = array_uint32_le (list->Device[i].irdaDeviceID); unsigned int charset = list->Device[i].irdaCharSet; unsigned int hints = (list->Device[i].irdaDeviceHints1 << 8) + list->Device[i].irdaDeviceHints2; #else for (size_t i = 0; i < list->len; ++i) { const char *name = list->dev[i].info; unsigned int address = list->dev[i].daddr; unsigned int charset = list->dev[i].charset; unsigned int hints = array_uint16_be (list->dev[i].hints); #endif INFO (context, "Discover: address=%08x, name=%s, charset=%02x, hints=%04x", address, name, charset, hints); if (filter && !filter (DC_TRANSPORT_IRDA, name)) { continue; } strncpy(iterator->items[count].name, name, sizeof(iterator->items[count].name) - 1); iterator->items[count].name[sizeof(iterator->items[count].name) - 1] = '\0'; iterator->items[count].address = address; iterator->items[count].charset = charset; iterator->items[count].hints = hints; count++; } iterator->current = 0; iterator->count = count; *out = (dc_iterator_t *) iterator; return DC_STATUS_SUCCESS; error_socket_close: S_CLOSE (fd); error_socket_exit: dc_socket_exit (context); error_free: dc_iterator_deallocate ((dc_iterator_t *) iterator); return status; #else return DC_STATUS_UNSUPPORTED; #endif } #ifdef IRDA static dc_status_t dc_irda_iterator_next (dc_iterator_t *abstract, void *out) { dc_irda_iterator_t *iterator = (dc_irda_iterator_t *) abstract; dc_irda_device_t *device = NULL; if (iterator->current >= iterator->count) return DC_STATUS_DONE; device = (dc_irda_device_t *) malloc (sizeof(dc_irda_device_t)); if (device == NULL) { SYSERROR (abstract->context, S_ENOMEM); return DC_STATUS_NOMEMORY; } *device = iterator->items[iterator->current++]; *(dc_irda_device_t **) out = device; return DC_STATUS_SUCCESS; } #endif dc_status_t dc_irda_open (dc_iostream_t **out, dc_context_t *context, unsigned int address, unsigned int lsap) { #ifdef IRDA dc_status_t status = DC_STATUS_SUCCESS; dc_socket_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; INFO (context, "Open: address=%08x, lsap=%u", address, lsap); // Allocate memory. device = (dc_socket_t *) dc_iostream_allocate (context, &dc_irda_vtable); if (device == NULL) { SYSERROR (context, S_ENOMEM); return DC_STATUS_NOMEMORY; } // Open the socket. status = dc_socket_open (&device->base, AF_IRDA, SOCK_STREAM, 0); if (status != DC_STATUS_SUCCESS) { goto error_free; } #ifdef _WIN32 SOCKADDR_IRDA peer; peer.irdaAddressFamily = AF_IRDA; peer.irdaDeviceID[0] = (address ) & 0xFF; peer.irdaDeviceID[1] = (address >> 8) & 0xFF; peer.irdaDeviceID[2] = (address >> 16) & 0xFF; peer.irdaDeviceID[3] = (address >> 24) & 0xFF; snprintf (peer.irdaServiceName, sizeof(peer.irdaServiceName), "LSAP-SEL%u", lsap); #else struct sockaddr_irda peer; peer.sir_family = AF_IRDA; peer.sir_addr = address; peer.sir_lsap_sel = lsap; memset (peer.sir_name, 0x00, sizeof(peer.sir_name)); #endif status = dc_socket_connect (&device->base, (struct sockaddr *) &peer, sizeof (peer)); if (status != DC_STATUS_SUCCESS) { goto error_close; } *out = (dc_iostream_t *) device; return DC_STATUS_SUCCESS; error_close: dc_socket_close (&device->base); error_free: dc_iostream_deallocate ((dc_iostream_t *) device); return status; #else return DC_STATUS_UNSUPPORTED; #endif }
libdc-for-dirk-Subsurface-branch
src/irda.c
/* * libdivecomputer * * Copyright (C) 2009 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcpy, memcmp #include <stdlib.h> // malloc, free #include <assert.h> // assert #include "cressi_edy.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "checksum.h" #include "array.h" #include "ringbuffer.h" #include "rbstream.h" #define ISINSTANCE(device) dc_device_isinstance((device), &cressi_edy_device_vtable) #define MAXRETRIES 4 #define SZ_PACKET 0x80 #define SZ_PAGE (SZ_PACKET / 4) #define IQ700 0x05 #define EDY 0x08 typedef struct cressi_edy_layout_t { unsigned int memsize; unsigned int rb_profile_begin; unsigned int rb_profile_end; unsigned int rb_logbook_offset; unsigned int rb_logbook_size; unsigned int rb_logbook_begin; unsigned int rb_logbook_end; unsigned int config; } cressi_edy_layout_t; typedef struct cressi_edy_device_t { dc_device_t base; dc_iostream_t *iostream; const cressi_edy_layout_t *layout; unsigned char fingerprint[SZ_PAGE / 2]; unsigned int model; } cressi_edy_device_t; static dc_status_t cressi_edy_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t cressi_edy_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size); static dc_status_t cressi_edy_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t cressi_edy_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t cressi_edy_device_close (dc_device_t *abstract); static const dc_device_vtable_t cressi_edy_device_vtable = { sizeof(cressi_edy_device_t), DC_FAMILY_CRESSI_EDY, cressi_edy_device_set_fingerprint, /* set_fingerprint */ cressi_edy_device_read, /* read */ NULL, /* write */ cressi_edy_device_dump, /* dump */ cressi_edy_device_foreach, /* foreach */ NULL, /* timesync */ cressi_edy_device_close /* close */ }; static const cressi_edy_layout_t cressi_edy_layout = { 0x8000, /* memsize */ 0x3FE0, /* rb_profile_begin */ 0x7F80, /* rb_profile_end */ 0x7F80, /* rb_logbook_offset */ 2, /* rb_logbook_size */ 0, /* rb_logbook_begin */ 60, /* rb_logbook_end */ 0x7C, /* config */ }; static const cressi_edy_layout_t tusa_iq700_layout = { 0x2000, /* memsize */ 0x0000, /* rb_profile_begin */ 0x1F60, /* rb_profile_end */ 0x1F80, /* rb_logbook_offset */ 1, /* rb_logbook_size */ 0, /* rb_logbook_begin */ 60, /* rb_logbook_end */ 0x3C, /* config */ }; static dc_status_t cressi_edy_packet (cressi_edy_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize, int trailer) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; for (unsigned int i = 0; i < csize; ++i) { // Send the command to the device. status = dc_iostream_write (device->iostream, command + i, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Receive the echo. unsigned char echo = 0; status = dc_iostream_read (device->iostream, &echo, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the echo."); return status; } // Verify the echo. if (command[i] != echo) { ERROR (abstract->context, "Unexpected echo."); return DC_STATUS_PROTOCOL; } } if (asize) { // Receive the answer of the device. status = dc_iostream_read (device->iostream, answer, asize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Verify the trailer of the packet. if (trailer && answer[asize - 1] != 0x45) { ERROR (abstract->context, "Unexpected answer trailer byte."); return DC_STATUS_PROTOCOL; } } return DC_STATUS_SUCCESS; } static dc_status_t cressi_edy_transfer (cressi_edy_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize, int trailer) { unsigned int nretries = 0; dc_status_t rc = DC_STATUS_SUCCESS; while ((rc = cressi_edy_packet (device, command, csize, answer, asize, trailer)) != DC_STATUS_SUCCESS) { if (rc != DC_STATUS_TIMEOUT && rc != DC_STATUS_PROTOCOL) return rc; // Abort if the maximum number of retries is reached. if (nretries++ >= MAXRETRIES) return rc; // Delay the next attempt. dc_iostream_sleep (device->iostream, 300); dc_iostream_purge (device->iostream, DC_DIRECTION_INPUT); } return DC_STATUS_SUCCESS; } static dc_status_t cressi_edy_init1 (cressi_edy_device_t *device) { unsigned char command[3] = {0x41, 0x42, 0x43}; unsigned char answer[3] = {0}; return cressi_edy_transfer (device, command, sizeof (command), answer, sizeof (answer), 0); } static dc_status_t cressi_edy_init2 (cressi_edy_device_t *device) { unsigned char command[1] = {0x44}; unsigned char answer[1] = {0}; dc_status_t rc = cressi_edy_transfer (device, command, sizeof (command), answer, sizeof (answer), 0); if (rc != DC_STATUS_SUCCESS) return rc; device->model = answer[0]; return DC_STATUS_SUCCESS; } static dc_status_t cressi_edy_init3 (cressi_edy_device_t *device) { unsigned char command[1] = {0x0C}; unsigned char answer[1] = {0}; return cressi_edy_transfer (device, command, sizeof (command), answer, sizeof (answer), 1); } static dc_status_t cressi_edy_quit (cressi_edy_device_t *device) { unsigned char command[1] = {0x46}; return cressi_edy_transfer (device, command, sizeof (command), NULL, 0, 0); } dc_status_t cressi_edy_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; cressi_edy_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (cressi_edy_device_t *) dc_device_allocate (context, &cressi_edy_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; device->layout = NULL; device->model = 0; memset (device->fingerprint, 0, sizeof (device->fingerprint)); // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (1200 8N1). status = dc_iostream_configure (device->iostream, 1200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (1000 ms). status = dc_iostream_set_timeout (device->iostream, 1000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Set the DTR line. status = dc_iostream_set_dtr (device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the DTR line."); goto error_close; } // Clear the RTS line. status = dc_iostream_set_rts (device->iostream, 0); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to clear the RTS line."); goto error_close; } // Make sure everything is in a sane state. dc_iostream_sleep(device->iostream, 300); dc_iostream_purge(device->iostream, DC_DIRECTION_ALL); // Send the init commands. cressi_edy_init1 (device); cressi_edy_init2 (device); cressi_edy_init3 (device); if (device->model == IQ700) { device->layout = &tusa_iq700_layout; } else { device->layout = &cressi_edy_layout; } // Set the serial communication protocol (4800 8N1). status = dc_iostream_configure (device->iostream, 4800, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Make sure everything is in a sane state. dc_iostream_sleep(device->iostream, 300); dc_iostream_purge(device->iostream, DC_DIRECTION_ALL); *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t cressi_edy_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; cressi_edy_device_t *device = (cressi_edy_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Send the quit command. rc = cressi_edy_quit (device); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t cressi_edy_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size) { cressi_edy_device_t *device = (cressi_edy_device_t*) abstract; if ((address % SZ_PAGE != 0) || (size % SZ_PACKET != 0)) return DC_STATUS_INVALIDARGS; unsigned int nbytes = 0; while (nbytes < size) { // Read the package. unsigned int number = address / SZ_PAGE; unsigned char answer[SZ_PACKET + 1] = {0}; unsigned char command[3] = {0x52, (number >> 8) & 0xFF, // high (number ) & 0xFF}; // low dc_status_t rc = cressi_edy_transfer (device, command, sizeof (command), answer, sizeof (answer), 1); if (rc != DC_STATUS_SUCCESS) return rc; memcpy (data, answer, SZ_PACKET); nbytes += SZ_PACKET; address += SZ_PACKET; data += SZ_PACKET; } return DC_STATUS_SUCCESS; } static dc_status_t cressi_edy_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { cressi_edy_device_t *device = (cressi_edy_device_t *) abstract; if (size && size != sizeof (device->fingerprint)) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, sizeof (device->fingerprint)); else memset (device->fingerprint, 0, sizeof (device->fingerprint)); return DC_STATUS_SUCCESS; } static dc_status_t cressi_edy_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { cressi_edy_device_t *device = (cressi_edy_device_t *) abstract; // Allocate the required amount of memory. if (!dc_buffer_resize (buffer, device->layout->memsize)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } return device_dump_read (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), SZ_PACKET); } static dc_status_t cressi_edy_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { cressi_edy_device_t *device = (cressi_edy_device_t *) abstract; const cressi_edy_layout_t *layout = device->layout; // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = SZ_PACKET + (layout->rb_profile_end - layout->rb_profile_begin); device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Emit a device info event. dc_event_devinfo_t devinfo; devinfo.model = device->model; devinfo.firmware = 0; devinfo.serial = 0; device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); // Read the logbook data. unsigned char logbook[SZ_PACKET] = {0}; dc_status_t rc = cressi_edy_device_read (abstract, layout->rb_logbook_offset, logbook, sizeof (logbook)); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the logbook data."); return rc; } // Get the logbook pointers. unsigned int last = logbook[layout->config + 0]; unsigned int first = logbook[layout->config + 1]; if (first < layout->rb_logbook_begin || first >= layout->rb_logbook_end || last < layout->rb_logbook_begin || last >= layout->rb_logbook_end) { if (last == 0xFF) return DC_STATUS_SUCCESS; ERROR (abstract->context, "Invalid ringbuffer pointer detected (0x%02x 0x%02x).", first, last); return DC_STATUS_DATAFORMAT; } // Get the number of logbook items. unsigned int count = ringbuffer_distance (first, last, 0, layout->rb_logbook_begin, layout->rb_logbook_end) + 1; // Get the profile pointer. unsigned int eop = array_uint_le (logbook + layout->config + 2, layout->rb_logbook_size) * SZ_PAGE + layout->rb_profile_begin; if (eop < layout->rb_profile_begin || eop >= layout->rb_profile_end) { ERROR (abstract->context, "Invalid ringbuffer pointer detected (0x%04x).", eop); return DC_STATUS_DATAFORMAT; } // The logbook ringbuffer can store at most 60 dives, even if the profile // data could store more (e.g. many small dives). But it's also possible // that the profile ringbuffer is filled faster than the logbook ringbuffer // (e.g. many large dives). We detect this by checking the total length. unsigned int total = 0; unsigned int idx = last; unsigned int previous = eop; for (unsigned int i = 0; i < count; ++i) { // Get the pointer to the profile data. unsigned int current = array_uint_le (logbook + idx * layout->rb_logbook_size, layout->rb_logbook_size) * SZ_PAGE + layout->rb_profile_begin; if (current < layout->rb_profile_begin || current >= layout->rb_profile_end) { ERROR (abstract->context, "Invalid ringbuffer pointer detected (0x%04x).", current); return DC_STATUS_DATAFORMAT; } // Get the profile length. unsigned int length = ringbuffer_distance (current, previous, 1, layout->rb_profile_begin, layout->rb_profile_end); // Check for a ringbuffer overflow. if (total + length > layout->rb_profile_end - layout->rb_profile_begin) { count = i; break; } total += length; previous = current; if (idx == layout->rb_logbook_begin) idx = layout->rb_logbook_end; idx--; } // Update and emit a progress event. progress.current += SZ_PACKET; progress.maximum = SZ_PACKET + total; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Create the ringbuffer stream. dc_rbstream_t *rbstream = NULL; rc = dc_rbstream_new (&rbstream, abstract, SZ_PAGE, SZ_PACKET, layout->rb_profile_begin, layout->rb_profile_end, eop); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to create the ringbuffer stream."); return rc; } // Memory buffer for the profile data. unsigned char *buffer = (unsigned char *) malloc (total); if (buffer == NULL) { ERROR (abstract->context, "Failed to allocate memory."); dc_rbstream_free (rbstream); return DC_STATUS_NOMEMORY; } unsigned int offset = total; idx = last; previous = eop; for (unsigned int i = 0; i < count; ++i) { // Get the pointer to the profile data. unsigned int current = array_uint_le (logbook + idx * layout->rb_logbook_size, layout->rb_logbook_size) * SZ_PAGE + layout->rb_profile_begin; if (current < layout->rb_profile_begin || current >= layout->rb_profile_end) { ERROR (abstract->context, "Invalid ringbuffer pointer detected (0x%04x).", current); dc_rbstream_free (rbstream); free(buffer); return DC_STATUS_DATAFORMAT; } // Get the profile length. unsigned int length = ringbuffer_distance (current, previous, 1, layout->rb_profile_begin, layout->rb_profile_end); // Move to the begin of the current dive. offset -= length; // Read the dive. rc = dc_rbstream_read (rbstream, &progress, buffer + offset, length); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the dive."); dc_rbstream_free (rbstream); free (buffer); return rc; } unsigned char *p = buffer + offset; if (memcmp (p, device->fingerprint, sizeof (device->fingerprint)) == 0) break; if (callback && !callback (p, length, p, sizeof (device->fingerprint), userdata)) break; previous = current; if (idx == layout->rb_logbook_begin) idx = layout->rb_logbook_end; idx--; } dc_rbstream_free (rbstream); free(buffer); return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/cressi_edy.c
/* * libdivecomputer * * Copyright (C) 2016 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #ifdef HAVE_PTHREAD_H #include <pthread.h> #endif #ifdef _WIN32 #define NOGDI #include <windows.h> #endif #if defined(HAVE_HIDAPI) #define USE_HIDAPI #define USBHID #elif defined(HAVE_LIBUSB) && !defined(__APPLE__) #define USE_LIBUSB #define USBHID #endif #if defined(USE_LIBUSB) #ifdef _WIN32 #define NOGDI #endif #include <libusb-1.0/libusb.h> #elif defined(USE_HIDAPI) #include <hidapi/hidapi.h> #endif #include "usbhid.h" #include "common-private.h" #include "context-private.h" #include "iostream-private.h" #include "descriptor-private.h" #include "iterator-private.h" #include "platform.h" #ifdef _WIN32 typedef LONG dc_mutex_t; #define DC_MUTEX_INIT 0 #else typedef pthread_mutex_t dc_mutex_t; #define DC_MUTEX_INIT PTHREAD_MUTEX_INITIALIZER #endif #define ISINSTANCE(device) dc_iostream_isinstance((device), &dc_usbhid_vtable) struct dc_usbhid_device_t { unsigned short vid, pid; }; #ifdef USBHID static dc_status_t dc_usbhid_iterator_next (dc_iterator_t *iterator, void *item); static dc_status_t dc_usbhid_iterator_free (dc_iterator_t *iterator); static dc_status_t dc_usbhid_set_timeout (dc_iostream_t *iostream, int timeout); static dc_status_t dc_usbhid_read (dc_iostream_t *iostream, void *data, size_t size, size_t *actual); static dc_status_t dc_usbhid_write (dc_iostream_t *iostream, const void *data, size_t size, size_t *actual); static dc_status_t dc_usbhid_close (dc_iostream_t *iostream); typedef struct dc_usbhid_iterator_t { dc_iterator_t base; dc_filter_t filter; #if defined(USE_LIBUSB) struct libusb_device **devices; size_t count; size_t current; #elif defined(USE_HIDAPI) struct hid_device_info *devices, *current; #endif } dc_usbhid_iterator_t; typedef struct dc_usbhid_t { /* Base class. */ dc_iostream_t base; /* Internal state. */ #if defined(USE_LIBUSB) libusb_device_handle *handle; int interface; unsigned char endpoint_in; unsigned char endpoint_out; unsigned int timeout; #elif defined(USE_HIDAPI) hid_device *handle; int timeout; #endif } dc_usbhid_t; static const dc_iterator_vtable_t dc_usbhid_iterator_vtable = { sizeof(dc_usbhid_iterator_t), dc_usbhid_iterator_next, dc_usbhid_iterator_free, }; static const dc_iostream_vtable_t dc_usbhid_vtable = { sizeof(dc_usbhid_t), dc_usbhid_set_timeout, /* set_timeout */ NULL, /* set_latency */ NULL, /* set_break */ NULL, /* set_dtr */ NULL, /* set_rts */ NULL, /* get_lines */ NULL, /* get_received */ NULL, /* configure */ dc_usbhid_read, /* read */ dc_usbhid_write, /* write */ NULL, /* flush */ NULL, /* purge */ NULL, /* sleep */ dc_usbhid_close, /* close */ }; static dc_mutex_t g_usbhid_mutex = DC_MUTEX_INIT; static size_t g_usbhid_refcount = 0; #ifdef USE_LIBUSB static libusb_context *g_usbhid_ctx = NULL; #endif #if defined(USE_LIBUSB) static dc_status_t syserror(int errcode) { switch (errcode) { case LIBUSB_ERROR_INVALID_PARAM: return DC_STATUS_INVALIDARGS; case LIBUSB_ERROR_NO_MEM: return DC_STATUS_NOMEMORY; case LIBUSB_ERROR_NO_DEVICE: case LIBUSB_ERROR_NOT_FOUND: return DC_STATUS_NODEVICE; case LIBUSB_ERROR_ACCESS: case LIBUSB_ERROR_BUSY: return DC_STATUS_NOACCESS; case LIBUSB_ERROR_TIMEOUT: return DC_STATUS_TIMEOUT; default: return DC_STATUS_IO; } } #endif static dc_status_t usbhid_packet_close(dc_custom_io_t *io) { dc_iostream_t *usbhid = (dc_iostream_t *)io->userdata; return dc_usbhid_close(usbhid); } static dc_status_t usbhid_packet_read(dc_custom_io_t *io, void* data, size_t size, size_t *actual) { dc_iostream_t *usbhid = (dc_iostream_t *)io->userdata; return dc_usbhid_read(usbhid, data, size, actual); } /* * FIXME! The USB HID "report type" is a disaster, and there's confusion * between libusb and HIDAPI. The Scubapro G2 seems to need an explicit * report type of 0 for HIDAPI, but not for libusb. * * See commit d251b37 ("Add a zero report ID to the commands") for the * Scubapro G2 - but that doesn't actually work with the BLE case, so * I really suspect that we need to do something _here_ in the packet * IO layer, and have the USBHID registration set the report type to * use (ie an extra new argument to dc_usbhid_custom_io() to set the * report type, or something). * * The Suunto EON Steel just uses 0x3f and does that in the caller. */ static dc_status_t usbhid_packet_write(dc_custom_io_t *io, const void* data, size_t size, size_t *actual) { dc_iostream_t *usbhid = (dc_iostream_t *)io->userdata; return dc_usbhid_write(usbhid, data, size, actual); } dc_status_t dc_usbhid_custom_io (dc_context_t *context, unsigned int vid, unsigned int pid) { dc_iostream_t *usbhid; dc_status_t status; static dc_custom_io_t custom = { .packet_size = 64, .packet_close = usbhid_packet_close, .packet_read = usbhid_packet_read, .packet_write = usbhid_packet_write, }; status = dc_usbhid_open(&usbhid, context, vid, pid); if (status != DC_STATUS_SUCCESS) return status; custom.userdata = (void *)usbhid; dc_context_set_custom_io(context, &custom, NULL); dc_usbhid_set_timeout(usbhid, 10); /* Get rid of any pending stale input first */ /* NOTE! This will cause an annoying warning from dc_usbhid_read() */ for (;;) { size_t transferred = 0; unsigned char buf[64]; dc_status_t rc = dc_usbhid_read(usbhid, buf, sizeof(buf), &transferred); if (rc != DC_STATUS_SUCCESS) break; if (!transferred) break; } dc_usbhid_set_timeout(usbhid, 5000); return DC_STATUS_SUCCESS; } static void dc_mutex_lock (dc_mutex_t *mutex) { #ifdef _WIN32 while (InterlockedCompareExchange (mutex, 1, 0) == 1) { SleepEx (0, TRUE); } #else pthread_mutex_lock (mutex); #endif } static void dc_mutex_unlock (dc_mutex_t *mutex) { #ifdef _WIN32 InterlockedExchange (mutex, 0); #else pthread_mutex_unlock (mutex); #endif } static dc_status_t dc_usbhid_init (dc_context_t *context) { dc_status_t status = DC_STATUS_SUCCESS; dc_mutex_lock (&g_usbhid_mutex); if (g_usbhid_refcount == 0) { #if defined(USE_LIBUSB) int rc = libusb_init (&g_usbhid_ctx); if (rc != LIBUSB_SUCCESS) { ERROR (context, "Failed to initialize usb support (%s).", libusb_error_name (rc)); status = syserror (rc); goto error; } #elif defined(USE_HIDAPI) int rc = hid_init(); if (rc < 0) { ERROR (context, "Failed to initialize usb support."); status = DC_STATUS_IO; goto error; } #endif } g_usbhid_refcount++; error: dc_mutex_unlock (&g_usbhid_mutex); return status; } static dc_status_t dc_usbhid_exit (void) { dc_mutex_lock (&g_usbhid_mutex); if (--g_usbhid_refcount == 0) { #if defined(USE_LIBUSB) libusb_exit (g_usbhid_ctx); g_usbhid_ctx = NULL; #elif defined(USE_HIDAPI) hid_exit (); #endif } dc_mutex_unlock (&g_usbhid_mutex); return DC_STATUS_SUCCESS; } #endif unsigned int dc_usbhid_device_get_vid (dc_usbhid_device_t *device) { if (device == NULL) return 0; return device->vid; } unsigned int dc_usbhid_device_get_pid (dc_usbhid_device_t *device) { if (device == NULL) return 0; return device->pid; } void dc_usbhid_device_free(dc_usbhid_device_t *device) { free (device); } dc_status_t dc_usbhid_iterator_new (dc_iterator_t **out, dc_context_t *context, dc_descriptor_t *descriptor) { #ifdef USBHID dc_status_t status = DC_STATUS_SUCCESS; dc_usbhid_iterator_t *iterator = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; iterator = (dc_usbhid_iterator_t *) dc_iterator_allocate (context, &dc_usbhid_iterator_vtable); if (iterator == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Initialize the usb library. status = dc_usbhid_init (context); if (status != DC_STATUS_SUCCESS) { goto error_free; } #if defined(USE_LIBUSB) // Enumerate the USB devices. struct libusb_device **devices = NULL; ssize_t ndevices = libusb_get_device_list (g_usbhid_ctx, &devices); if (ndevices < 0) { ERROR (context, "Failed to enumerate the usb devices (%s).", libusb_error_name (ndevices)); status = syserror (ndevices); goto error_usb_exit; } iterator->devices = devices; iterator->count = ndevices; iterator->current = 0; #elif defined(USE_HIDAPI) struct hid_device_info *devices = hid_enumerate(0x0, 0x0); if (devices == NULL) { status = DC_STATUS_IO; goto error_usb_exit; } iterator->devices = devices; iterator->current = devices; #endif iterator->filter = dc_descriptor_get_filter (descriptor); *out = (dc_iterator_t *) iterator; return DC_STATUS_SUCCESS; error_usb_exit: dc_usbhid_exit (); error_free: dc_iterator_deallocate ((dc_iterator_t *) iterator); return status; #else return DC_STATUS_UNSUPPORTED; #endif } #ifdef USBHID static dc_status_t dc_usbhid_iterator_next (dc_iterator_t *abstract, void *out) { dc_usbhid_iterator_t *iterator = (dc_usbhid_iterator_t *) abstract; dc_usbhid_device_t *device = NULL; #if defined(USE_LIBUSB) while (iterator->current < iterator->count) { struct libusb_device *current = iterator->devices[iterator->current++]; // Get the device descriptor. struct libusb_device_descriptor dev; int rc = libusb_get_device_descriptor (current, &dev); if (rc < 0) { ERROR (abstract->context, "Failed to get the device descriptor (%s).", libusb_error_name (rc)); return syserror (rc); } dc_usb_desc_t usb = {dev.idVendor, dev.idProduct}; if (iterator->filter && !iterator->filter (DC_TRANSPORT_USBHID, &usb)) { continue; } // Get the active configuration descriptor. struct libusb_config_descriptor *config = NULL; rc = libusb_get_active_config_descriptor (current, &config); if (rc != LIBUSB_SUCCESS) { ERROR (abstract->context, "Failed to get the configuration descriptor (%s).", libusb_error_name (rc)); return syserror (rc); } // Find the first HID interface. const struct libusb_interface_descriptor *interface = NULL; for (unsigned int i = 0; i < config->bNumInterfaces; i++) { const struct libusb_interface *iface = &config->interface[i]; for (int j = 0; j < iface->num_altsetting; j++) { const struct libusb_interface_descriptor *desc = &iface->altsetting[j]; if (desc->bInterfaceClass == LIBUSB_CLASS_HID && interface == NULL) { interface = desc; } } } if (interface == NULL) { libusb_free_config_descriptor (config); continue; } // Find the first input and output interrupt endpoints. const struct libusb_endpoint_descriptor *ep_in = NULL, *ep_out = NULL; for (unsigned int i = 0; i < interface->bNumEndpoints; i++) { const struct libusb_endpoint_descriptor *desc = &interface->endpoint[i]; unsigned int type = desc->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK; unsigned int direction = desc->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK; if (type != LIBUSB_TRANSFER_TYPE_INTERRUPT) { continue; } if (direction == LIBUSB_ENDPOINT_IN && ep_in == NULL) { ep_in = desc; } if (direction == LIBUSB_ENDPOINT_OUT && ep_out == NULL) { ep_out = desc; } } if (ep_in == NULL || ep_out == NULL) { libusb_free_config_descriptor (config); continue; } device = (dc_usbhid_device_t *) malloc (sizeof(dc_usbhid_device_t)); if (device == NULL) { ERROR (abstract->context, "Failed to allocate memory."); libusb_free_config_descriptor (config); return DC_STATUS_NOMEMORY; } device->vid = dev.idVendor; device->pid = dev.idProduct; *(dc_usbhid_device_t **) out = device; libusb_free_config_descriptor (config); return DC_STATUS_SUCCESS; } #elif defined(USE_HIDAPI) while (iterator->current) { struct hid_device_info *current = iterator->current; iterator->current = current->next; dc_usb_desc_t usb = {current->vendor_id, current->product_id}; if (iterator->filter && !iterator->filter (DC_TRANSPORT_USBHID, &usb)) { continue; } device = (dc_usbhid_device_t *) malloc (sizeof(dc_usbhid_device_t)); if (device == NULL) { ERROR (abstract->context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } device->vid = current->vendor_id; device->pid = current->product_id; *(dc_usbhid_device_t **) out = device; return DC_STATUS_SUCCESS; } #endif return DC_STATUS_DONE; } static dc_status_t dc_usbhid_iterator_free (dc_iterator_t *abstract) { dc_usbhid_iterator_t *iterator = (dc_usbhid_iterator_t *) abstract; #if defined(USE_LIBUSB) libusb_free_device_list (iterator->devices, 1); #elif defined(USE_HIDAPI) hid_free_enumeration (iterator->devices); #endif dc_usbhid_exit (); return DC_STATUS_SUCCESS; } #endif dc_status_t dc_usbhid_open (dc_iostream_t **out, dc_context_t *context, unsigned int vid, unsigned int pid) { #ifdef USBHID dc_status_t status = DC_STATUS_SUCCESS; dc_usbhid_t *usbhid = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; INFO (context, "Open: vid=%04x, pid=%04x", vid, pid); // Allocate memory. usbhid = (dc_usbhid_t *) dc_iostream_allocate (context, &dc_usbhid_vtable); if (usbhid == NULL) { ERROR (context, "Out of memory."); return DC_STATUS_NOMEMORY; } // Initialize the usb library. status = dc_usbhid_init (context); if (status != DC_STATUS_SUCCESS) { goto error_free; } #if defined(USE_LIBUSB) struct libusb_device **devices = NULL; struct libusb_config_descriptor *config = NULL; int rc = 0; // Enumerate the USB devices. ssize_t ndevices = libusb_get_device_list (g_usbhid_ctx, &devices); if (ndevices < 0) { ERROR (context, "Failed to enumerate the usb devices (%s).", libusb_error_name (ndevices)); status = syserror (ndevices); goto error_usb_exit; } // Find the first device matching the VID/PID. struct libusb_device *device = NULL; for (size_t i = 0; i < ndevices; i++) { struct libusb_device_descriptor desc; rc = libusb_get_device_descriptor (devices[i], &desc); if (rc < 0) { ERROR (context, "Failed to get the device descriptor (%s).", libusb_error_name (rc)); status = syserror (rc); goto error_usb_free_list; } if (desc.idVendor == vid && desc.idProduct == pid) { device = devices[i]; break; } } if (device == NULL) { ERROR (context, "No matching USB device (%04x:%04x) found.", vid, pid); status = DC_STATUS_NODEVICE; goto error_usb_free_list; } // Get the active configuration descriptor. rc = libusb_get_active_config_descriptor (device, &config); if (rc != LIBUSB_SUCCESS) { ERROR (context, "Failed to get the configuration descriptor (%s).", libusb_error_name (rc)); status = syserror (rc); goto error_usb_free_list; } // Find the first HID interface. const struct libusb_interface_descriptor *interface = NULL; for (unsigned int i = 0; i < config->bNumInterfaces; i++) { const struct libusb_interface *iface = &config->interface[i]; for (unsigned int j = 0; j < iface->num_altsetting; j++) { const struct libusb_interface_descriptor *desc = &iface->altsetting[j]; if (desc->bInterfaceClass == LIBUSB_CLASS_HID && interface == NULL) { interface = desc; } } } if (interface == NULL) { ERROR (context, "No HID interface found."); status = DC_STATUS_IO; goto error_usb_free_config; } // Find the first input and output interrupt endpoints. const struct libusb_endpoint_descriptor *ep_in = NULL, *ep_out = NULL; for (unsigned int i = 0; i < interface->bNumEndpoints; i++) { const struct libusb_endpoint_descriptor *desc = &interface->endpoint[i]; unsigned int type = desc->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK; unsigned int direction = desc->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK; if (type != LIBUSB_TRANSFER_TYPE_INTERRUPT) continue; if (direction == LIBUSB_ENDPOINT_IN && ep_in == NULL) { ep_in = desc; } if (direction == LIBUSB_ENDPOINT_OUT && ep_out == NULL) { ep_out = desc; } } if (ep_in == NULL || ep_out == NULL) { ERROR (context, "No interrupt endpoints found."); status = DC_STATUS_IO; goto error_usb_free_config; } usbhid->interface = interface->bInterfaceNumber; usbhid->endpoint_in = ep_in->bEndpointAddress; usbhid->endpoint_out = ep_out->bEndpointAddress; usbhid->timeout = 0; INFO (context, "Open: interface=%u, endpoints=%02x,%02x", usbhid->interface, usbhid->endpoint_in, usbhid->endpoint_out); // Open the USB device. rc = libusb_open (device, &usbhid->handle); if (rc != LIBUSB_SUCCESS) { ERROR (context, "Failed to open the usb device (%s).", libusb_error_name (rc)); status = syserror (rc); goto error_usb_free_config; } #if defined(LIBUSB_API_VERSION) && (LIBUSB_API_VERSION >= 0x01000102) libusb_set_auto_detach_kernel_driver (usbhid->handle, 1); #endif // Claim the HID interface. rc = libusb_claim_interface (usbhid->handle, usbhid->interface); if (rc != LIBUSB_SUCCESS) { ERROR (context, "Failed to claim the usb interface (%s).", libusb_error_name (rc)); status = syserror (rc); goto error_usb_close; } libusb_free_config_descriptor (config); libusb_free_device_list (devices, 1); #elif defined(USE_HIDAPI) // Open the USB device. usbhid->handle = hid_open (vid, pid, NULL); if (usbhid->handle == NULL) { ERROR (context, "Failed to open the usb device."); status = DC_STATUS_IO; goto error_usb_exit; } usbhid->timeout = -1; #endif *out = (dc_iostream_t *) usbhid; return DC_STATUS_SUCCESS; #if defined(USE_LIBUSB) error_usb_close: libusb_close (usbhid->handle); error_usb_free_config: libusb_free_config_descriptor (config); error_usb_free_list: libusb_free_device_list (devices, 1); #endif error_usb_exit: dc_usbhid_exit (); error_free: dc_iostream_deallocate ((dc_iostream_t *) usbhid); return status; #else return DC_STATUS_UNSUPPORTED; #endif } #ifdef USBHID static dc_status_t dc_usbhid_close (dc_iostream_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; dc_usbhid_t *usbhid = (dc_usbhid_t *) abstract; #if defined(USE_LIBUSB) libusb_release_interface (usbhid->handle, usbhid->interface); libusb_close (usbhid->handle); #elif defined(USE_HIDAPI) hid_close(usbhid->handle); #endif dc_usbhid_exit(); return status; } static dc_status_t dc_usbhid_set_timeout (dc_iostream_t *abstract, int timeout) { dc_usbhid_t *usbhid = (dc_usbhid_t *) abstract; #if defined(USE_LIBUSB) if (timeout < 0) { usbhid->timeout = 0; } else if (timeout == 0) { return DC_STATUS_UNSUPPORTED; } else { usbhid->timeout = timeout; } #elif defined(USE_HIDAPI) if (timeout < 0) { usbhid->timeout = -1; } else { usbhid->timeout = timeout; } #endif return DC_STATUS_SUCCESS; } static dc_status_t dc_usbhid_read (dc_iostream_t *abstract, void *data, size_t size, size_t *actual) { dc_status_t status = DC_STATUS_SUCCESS; dc_usbhid_t *usbhid = (dc_usbhid_t *) abstract; int nbytes = 0; #if defined(USE_LIBUSB) int rc = libusb_interrupt_transfer (usbhid->handle, usbhid->endpoint_in, data, size, &nbytes, usbhid->timeout); if (rc != LIBUSB_SUCCESS) { ERROR (abstract->context, "Usb read interrupt transfer failed (%s).", libusb_error_name (rc)); status = syserror (rc); goto out; } #elif defined(USE_HIDAPI) nbytes = hid_read_timeout(usbhid->handle, data, size, usbhid->timeout); if (nbytes < 0) { ERROR (abstract->context, "Usb read interrupt transfer failed."); status = DC_STATUS_IO; nbytes = 0; goto out; } #endif out: if (actual) *actual = nbytes; return status; } static dc_status_t dc_usbhid_write (dc_iostream_t *abstract, const void *data, size_t size, size_t *actual) { dc_status_t status = DC_STATUS_SUCCESS; dc_usbhid_t *usbhid = (dc_usbhid_t *) abstract; int nbytes = 0; if (size == 0) { goto out; } #if defined(USE_LIBUSB) const unsigned char *buffer = (const unsigned char *) data; size_t length = size; // Skip a report id of zero. unsigned char report = buffer[0]; if (report == 0) { buffer++; length--; } int rc = libusb_interrupt_transfer (usbhid->handle, usbhid->endpoint_out, (void *) buffer, length, &nbytes, 0); if (rc != LIBUSB_SUCCESS) { ERROR (abstract->context, "Usb write interrupt transfer failed (%s).", libusb_error_name (rc)); status = syserror (rc); goto out; } if (report == 0) { nbytes++; } #elif defined(USE_HIDAPI) nbytes = hid_write(usbhid->handle, data, size); if (nbytes < 0) { ERROR (abstract->context, "Usb write interrupt transfer failed."); status = DC_STATUS_IO; nbytes = 0; goto out; } #endif out: #ifdef _WIN32 if (nbytes > size) { WARNING (abstract->context, "Number of bytes exceeds the buffer size (" DC_PRINTF_SIZE " > " DC_PRINTF_SIZE ")!", nbytes, size); nbytes = size; } #endif if (actual) *actual = nbytes; return status; } #else /* !USBHID */ dc_status_t dc_usbhid_custom_io (dc_context_t *context, unsigned int vid, unsigned int pid) { return DC_STATUS_UNSUPPORTED; } #endif
libdc-for-dirk-Subsurface-branch
src/usbhid.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <string.h> #include <libdivecomputer/units.h> #include "mares_nemo.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_parser_isinstance((parser), &mares_nemo_parser_vtable) #define NEMO 0 #define NEMOWIDE 1 #define NEMOAIR 4 #define PUCK 7 #define NEMOEXCEL 17 #define NEMOAPNEIST 18 #define PUCKAIR 19 #define AIR 0 #define NITROX 1 #define FREEDIVE 2 #define GAUGE 3 typedef struct mares_nemo_parser_t mares_nemo_parser_t; struct mares_nemo_parser_t { dc_parser_t base; unsigned int model; unsigned int freedive; /* Internal state */ unsigned int mode; unsigned int length; unsigned int sample_count; unsigned int sample_size; unsigned int header; unsigned int extra; }; static dc_status_t mares_nemo_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t mares_nemo_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t mares_nemo_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t mares_nemo_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t mares_nemo_parser_vtable = { sizeof(mares_nemo_parser_t), DC_FAMILY_MARES_NEMO, mares_nemo_parser_set_data, /* set_data */ mares_nemo_parser_get_datetime, /* datetime */ mares_nemo_parser_get_field, /* fields */ mares_nemo_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; dc_status_t mares_nemo_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int model) { mares_nemo_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (mares_nemo_parser_t *) dc_parser_allocate (context, &mares_nemo_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Get the freedive mode for this model. unsigned int freedive = FREEDIVE; if (model == NEMOWIDE || model == NEMOAIR || model == PUCK || model == PUCKAIR) freedive = GAUGE; // Set the default values. parser->model = model; parser->freedive = freedive; parser->mode = AIR; parser->length = 0; parser->sample_count = 0; parser->sample_size = 0; parser->header = 0; parser->extra = 0; *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; } static dc_status_t mares_nemo_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { mares_nemo_parser_t *parser = (mares_nemo_parser_t *) abstract; // Clear the previous state. parser->base.data = NULL; parser->base.size = 0; parser->mode = AIR; parser->length = 0; parser->sample_count = 0; parser->sample_size = 0; parser->header = 0; parser->extra = 0; if (size == 0) return DC_STATUS_SUCCESS; if (size < 2 + 3) return DC_STATUS_DATAFORMAT; unsigned int length = array_uint16_le (data); if (length > size) return DC_STATUS_DATAFORMAT; unsigned int extra = 0; const unsigned char marker[3] = {0xAA, 0xBB, 0xCC}; if (memcmp (data + length - 3, marker, sizeof (marker)) == 0) { if (parser->model == PUCKAIR) extra = 7; else extra = 12; } if (length < 2 + extra + 3) return DC_STATUS_DATAFORMAT; unsigned int mode = data[length - extra - 1]; unsigned int header_size = 53; unsigned int sample_size = 2; if (extra) { if (parser->model == PUCKAIR) sample_size = 3; else sample_size = 5; } if (mode == parser->freedive) { header_size = 28; sample_size = 6; } unsigned int nsamples = array_uint16_le (data + length - extra - 3); unsigned int nbytes = 2 + nsamples * sample_size + header_size + extra; if (length != nbytes) return DC_STATUS_DATAFORMAT; // Store the new state. parser->base.data = data; parser->base.size = size; parser->mode = mode; parser->length = length; parser->sample_count = nsamples; parser->sample_size = sample_size; parser->header = header_size; parser->extra = extra; return DC_STATUS_SUCCESS; } static dc_status_t mares_nemo_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { mares_nemo_parser_t *parser = (mares_nemo_parser_t *) abstract; if (abstract->size == 0) return DC_STATUS_DATAFORMAT; const unsigned char *p = abstract->data + parser->length - parser->extra - 8; if (datetime) { datetime->year = p[0] + 2000; datetime->month = p[1]; datetime->day = p[2]; datetime->hour = p[3]; datetime->minute = p[4]; datetime->second = 0; datetime->timezone = DC_TIMEZONE_NONE; } return DC_STATUS_SUCCESS; } static dc_status_t mares_nemo_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { mares_nemo_parser_t *parser = (mares_nemo_parser_t *) abstract; if (abstract->size == 0) return DC_STATUS_DATAFORMAT; const unsigned char *data = abstract->data; const unsigned char *p = abstract->data + 2 + parser->sample_count * parser->sample_size; if (value) { if (parser->mode != parser->freedive) { dc_gasmix_t *gasmix = (dc_gasmix_t *) value; dc_tank_t *tank = (dc_tank_t *) value; switch (type) { case DC_FIELD_DIVETIME: *((unsigned int *) value) = parser->sample_count * 20; break; case DC_FIELD_MAXDEPTH: *((double *) value) = array_uint16_le (p + 53 - 10) / 10.0; break; case DC_FIELD_GASMIX_COUNT: if (parser->mode == AIR || parser->mode == NITROX) *((unsigned int *) value) = 1; else *((unsigned int *) value) = 0; break; case DC_FIELD_GASMIX: switch (parser->mode) { case AIR: gasmix->oxygen = 0.21; break; case NITROX: gasmix->oxygen = p[53 - 43] / 100.0; break; default: return DC_STATUS_UNSUPPORTED; } gasmix->helium = 0.0; gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium; break; case DC_FIELD_TANK_COUNT: if (parser->extra) *((unsigned int *) value) = 1; else *((unsigned int *) value) = 0; break; case DC_FIELD_TANK: if (parser->extra == 12) { unsigned int volume = array_uint16_le(p + parser->header + 0); unsigned int workpressure = array_uint16_le(p + parser->header + 2); if (workpressure == 0xFFFF) { tank->type = DC_TANKVOLUME_METRIC; tank->volume = volume / 10.0; tank->workpressure = 0.0; } else { if (workpressure == 0) return DC_STATUS_DATAFORMAT; tank->type = DC_TANKVOLUME_IMPERIAL; tank->volume = volume * CUFT * 1000.0; tank->volume /= workpressure * PSI / ATM; tank->workpressure = workpressure * PSI / BAR; } tank->beginpressure = array_uint16_le(p + parser->header + 4) / 100.0; tank->endpressure = array_uint16_le(p + parser->header + 6) / 100.0; } else if (parser->extra == 7) { tank->type = DC_TANKVOLUME_NONE; tank->volume = 0.0; tank->workpressure = 0.0; tank->beginpressure = array_uint16_le(p + parser->header + 0); tank->endpressure = array_uint16_le(p + parser->header + 2); } else { return DC_STATUS_UNSUPPORTED; } if (parser->mode == AIR || parser->mode == NITROX) { tank->gasmix = 0; } else { tank->gasmix = DC_GASMIX_UNKNOWN; } break; case DC_FIELD_TEMPERATURE_MINIMUM: *((double *) value) = (signed char) p[53 - 11]; break; case DC_FIELD_DIVEMODE: switch (parser->mode) { case AIR: case NITROX: *((dc_divemode_t *) value) = DC_DIVEMODE_OC; break; case FREEDIVE: case GAUGE: *((dc_divemode_t *) value) = DC_DIVEMODE_GAUGE; break; default: return DC_STATUS_DATAFORMAT; } break; default: return DC_STATUS_UNSUPPORTED; } } else { unsigned int divetime = 0; switch (type) { case DC_FIELD_DIVETIME: for (unsigned int i = 0; i < parser->sample_count; ++i) { unsigned int idx = 2 + parser->sample_size * i; divetime += data[idx + 2] + data[idx + 3] * 60; } *((unsigned int *) value) = divetime; break; case DC_FIELD_MAXDEPTH: *((double *) value) = array_uint16_le (p + 28 - 10) / 10.0; break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = 0; break; case DC_FIELD_TEMPERATURE_MINIMUM: *((double *) value) = (signed char) p[28 - 11]; break; case DC_FIELD_DIVEMODE: *((dc_divemode_t *) value) = DC_DIVEMODE_FREEDIVE; break; default: return DC_STATUS_UNSUPPORTED; } } } return DC_STATUS_SUCCESS; } static dc_status_t mares_nemo_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { mares_nemo_parser_t *parser = (mares_nemo_parser_t *) abstract; if (abstract->size == 0) return DC_STATUS_DATAFORMAT; const unsigned char *data = abstract->data; unsigned int size = abstract->size; if (parser->mode != parser->freedive) { // Initial tank pressure. unsigned int pressure = 0; if (parser->extra == 12) { const unsigned char *p = data + 2 + parser->sample_count * parser->sample_size; pressure = array_uint16_le(p + parser->header + 4); } // Initial gas mix. unsigned int gasmix_previous = 0xFFFFFFFF; unsigned int gasmix = gasmix_previous; if (parser->mode == AIR || parser->mode == NITROX) { gasmix = 0; } unsigned int time = 0; for (unsigned int i = 0; i < parser->sample_count; ++i) { dc_sample_value_t sample = {0}; unsigned int idx = 2 + parser->sample_size * i; unsigned int value = array_uint16_le (data + idx); unsigned int depth = value & 0x07FF; unsigned int ascent = (value & 0xC000) >> 14; unsigned int violation = (value & 0x2000) >> 13; unsigned int deco = (value & 0x1000) >> 12; // Time (seconds). time += 20; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Depth (1/10 m). sample.depth = depth / 10.0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); // Gas change. if (gasmix != gasmix_previous) { sample.gasmix = gasmix; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); gasmix_previous = gasmix; } // Ascent rate if (ascent) { sample.event.type = SAMPLE_EVENT_ASCENT; sample.event.time = 0; sample.event.flags = 0; sample.event.value = ascent; if (callback) callback (DC_SAMPLE_EVENT, sample, userdata); } // Deco violation if (violation) { sample.event.type = SAMPLE_EVENT_CEILING; sample.event.time = 0; sample.event.flags = 0; sample.event.value = 0; if (callback) callback (DC_SAMPLE_EVENT, sample, userdata); } // Deco stop if (deco) { sample.deco.type = DC_DECO_DECOSTOP; } else { sample.deco.type = DC_DECO_NDL; } sample.deco.time = 0; sample.deco.depth = 0.0; if (callback) callback (DC_SAMPLE_DECO, sample, userdata); // Pressure (1 bar). if (parser->sample_size == 3) { sample.pressure.tank = 0; sample.pressure.value = data[idx + 2]; if (callback) callback (DC_SAMPLE_PRESSURE, sample, userdata); } else if (parser->sample_size == 5) { unsigned int type = (time / 20) % 3; if (type == 0) { pressure -= data[idx + 2] * 100; sample.pressure.tank = 0; sample.pressure.value = pressure / 100.0; if (callback) callback (DC_SAMPLE_PRESSURE, sample, userdata); } } } } else { // A freedive session contains only summaries for each individual // freedive. The detailed profile data (if present) is stored after // the normal dive data. We assume a freedive has a detailed profile // when the buffer contains more data than the size indicated in the // header. int profiles = (size > parser->length); unsigned int time = 0; unsigned int offset = parser->length; for (unsigned int i = 0; i < parser->sample_count; ++i) { dc_sample_value_t sample = {0}; unsigned int idx = 2 + parser->sample_size * i; unsigned int maxdepth = array_uint16_le (data + idx); unsigned int divetime = data[idx + 2] + data[idx + 3] * 60; unsigned int surftime = data[idx + 4] + data[idx + 5] * 60; // Surface Time (seconds). time += surftime; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Surface Depth (0 m). sample.depth = 0.0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); if (profiles) { // Get the freedive sample interval for this model. unsigned int interval = 4; if (parser->model == NEMOAPNEIST) interval = 1; // Calculate the number of samples that should be present // in the profile data, based on the divetime in the summary. unsigned int n = (divetime + interval - 1) / interval; // The last sample interval can be smaller than the normal // 4 seconds. We keep track of the maximum divetime, to be // able to adjust that last sample interval. unsigned int maxtime = time + divetime; // Process all depth samples. Once a zero depth sample is // reached, the current freedive profile is complete. unsigned int count = 0; while (offset + 2 <= size) { unsigned int depth = array_uint16_le (data + offset); offset += 2; if (depth == 0) break; count++; if (count > n) break; // Time (seconds). time += interval; if (time > maxtime) time = maxtime; // Adjust the last sample. sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Depth (1/10 m). sample.depth = depth / 10.0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); } // Verify that the number of samples in the profile data // equals the predicted number of samples (from the divetime // in the summary entry). If both values are different, the // the profile data is probably incorrect. if (count != n) { ERROR (abstract->context, "Unexpected number of samples."); return DC_STATUS_DATAFORMAT; } } else { // Dive Time (seconds). time += divetime; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Maximum Depth (1/10 m). sample.depth = maxdepth / 10.0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); } } } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/mares_nemo_parser.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <string.h> // memcmp, strdup #include <stdio.h> // snprintf #include "suunto_d9.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_parser_isinstance((parser), &suunto_d9_parser_vtable) #define MAXPARAMS 3 #define NGASMIXES 11 #define D9 0x0E #define D6 0x0F #define VYPER2 0x10 #define COBRA2 0x11 #define D4 0x12 #define VYPERAIR 0x13 #define COBRA3 0x14 #define HELO2 0x15 #define D4i 0x19 #define D6i 0x1A #define D9tx 0x1B #define DX 0x1C #define VYPERNOVO 0x1D #define ZOOPNOVO 0x1E #define D4F 0x20 #define ID_D6I_V1_MIX2 0x1871C062 #define ID_D6I_V1_MIX3 0x1871C063 #define ID_D6I_V2 0x18724062 #define ID_D4I_V1 ID_D6I_V1_MIX2 #define ID_D4I_V2 ID_D6I_V2 #define ID_DX_V1 0x18922062 #define ID_DX_V2 0x18924062 #define AIR 0 #define NITROX 1 #define GAUGE 2 #define FREEDIVE 3 #define MIXED 4 #define CCR 5 #define SAFETYSTOP (1 << 0) #define DECOSTOP (1 << 1) #define DEEPSTOP (1 << 2) typedef struct suunto_d9_parser_t suunto_d9_parser_t; struct suunto_d9_parser_t { dc_parser_t base; unsigned int model; unsigned int serial; // Cached fields. unsigned int cached; unsigned int mode; unsigned int ngasmixes; unsigned int oxygen[NGASMIXES]; unsigned int helium[NGASMIXES]; unsigned int gasmix; unsigned int config; }; typedef struct sample_info_t { unsigned int type; unsigned int size; unsigned int interval; unsigned int divisor; } sample_info_t; static dc_status_t suunto_d9_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t suunto_d9_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t suunto_d9_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t suunto_d9_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t suunto_d9_parser_vtable = { sizeof(suunto_d9_parser_t), DC_FAMILY_SUUNTO_D9, suunto_d9_parser_set_data, /* set_data */ suunto_d9_parser_get_datetime, /* datetime */ suunto_d9_parser_get_field, /* fields */ suunto_d9_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; static unsigned int suunto_d9_parser_find_gasmix (suunto_d9_parser_t *parser, unsigned int o2, unsigned int he) { // Find the gasmix in the list. unsigned int i = 0; while (i < parser->ngasmixes) { if (o2 == parser->oxygen[i] && he == parser->helium[i]) break; i++; } return i; } static dc_status_t suunto_d9_parser_cache (suunto_d9_parser_t *parser) { const unsigned char *data = parser->base.data; unsigned int size = parser->base.size; if (parser->cached) { return DC_STATUS_SUCCESS; } // Get the logbook id tag. unsigned int id = array_uint32_le (data + 1); // Gasmix information. unsigned int gasmode_offset = 0x19; unsigned int gasmix_offset = 0x21; unsigned int gasmix_count = 3; if (parser->model == HELO2) { gasmode_offset = 0x1F; gasmix_offset = 0x54; gasmix_count = 8; } else if (parser->model == D4i || parser->model == ZOOPNOVO || parser->model == D4F) { gasmode_offset = 0x1D; if (id == ID_D4I_V2) gasmix_offset = 0x67; else gasmix_offset = 0x5F; gasmix_count = 1; } else if (parser->model == D6i || parser->model == VYPERNOVO) { gasmode_offset = 0x1D; if (id == ID_D6I_V2) gasmix_offset = 0x67; else gasmix_offset = 0x5F; if (id == ID_D6I_V1_MIX3 || id == ID_D6I_V2) gasmix_count = 3; else gasmix_count = 2; } else if (parser->model == D9tx) { gasmode_offset = 0x1D; gasmix_offset = 0x87; gasmix_count = 8; } else if (parser->model == DX) { gasmode_offset = 0x21; if (id == ID_DX_V2) gasmix_offset = 0xC3; else gasmix_offset = 0xC1; gasmix_count = 11; } // Offset to the configuration data. unsigned int config = 0x3A; if (parser->model == D4) { config += 1; } else if (parser->model == HELO2 || parser->model == D4i || parser->model == D6i || parser->model == D9tx || parser->model == DX || parser->model == ZOOPNOVO || parser->model == VYPERNOVO || parser->model == D4F) { config = gasmix_offset + gasmix_count * 6; } if (config + 1 > size) return DC_STATUS_DATAFORMAT; // Cache the data for later use. parser->mode = data[gasmode_offset]; parser->gasmix = 0; if (parser->mode == GAUGE || parser->mode == FREEDIVE) { parser->ngasmixes = 0; } else if (parser->mode == AIR) { parser->oxygen[0] = 21; parser->helium[0] = 0; parser->ngasmixes = 1; } else { parser->ngasmixes = 0; for (unsigned int i = 0; i < gasmix_count; ++i) { if (parser->model == HELO2 || parser->model == D4i || parser->model == D6i || parser->model == D9tx || parser->model == DX || parser->model == ZOOPNOVO || parser->model == VYPERNOVO || parser->model == D4F) { parser->oxygen[i] = data[gasmix_offset + 6 * i + 1]; parser->helium[i] = data[gasmix_offset + 6 * i + 2]; } else { unsigned int oxygen = data[gasmix_offset + i]; if (oxygen == 0x00 || oxygen == 0xFF) break; parser->oxygen[i] = oxygen; parser->helium[i] = 0; } parser->ngasmixes++; } // Initial gasmix. if (parser->model == HELO2) { parser->gasmix = data[0x26]; } else if (parser->model == D4i || parser->model == D6i || parser->model == D9tx || parser->model == ZOOPNOVO || parser->model == VYPERNOVO || parser->model == D4F) { if (id == ID_D4I_V2 || id == ID_D6I_V2) { parser->gasmix = data[0x2D]; } else { parser->gasmix = data[0x28]; } } } parser->config = config; parser->cached = 1; return DC_STATUS_SUCCESS; } dc_status_t suunto_d9_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int model, unsigned int serial) { suunto_d9_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (suunto_d9_parser_t *) dc_parser_allocate (context, &suunto_d9_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. parser->model = model; parser->serial = serial; parser->cached = 0; parser->mode = AIR; parser->ngasmixes = 0; for (unsigned int i = 0; i < NGASMIXES; ++i) { parser->oxygen[i] = 0; parser->helium[i] = 0; } parser->gasmix = 0; parser->config = 0; *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; } static dc_status_t suunto_d9_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { suunto_d9_parser_t *parser = (suunto_d9_parser_t *) abstract; // Reset the cache. parser->cached = 0; parser->mode = AIR; parser->ngasmixes = 0; for (unsigned int i = 0; i < NGASMIXES; ++i) { parser->oxygen[i] = 0; parser->helium[i] = 0; } parser->gasmix = 0; parser->config = 0; return DC_STATUS_SUCCESS; } static dc_status_t suunto_d9_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { suunto_d9_parser_t *parser = (suunto_d9_parser_t*) abstract; unsigned int offset = 0x11; if (parser->model == HELO2 || parser->model == DX) offset = 0x17; else if (parser->model == D4i || parser->model == D6i || parser->model == D9tx || parser->model == ZOOPNOVO || parser->model == VYPERNOVO || parser->model == D4F) offset = 0x13; if (abstract->size < offset + 7) return DC_STATUS_DATAFORMAT; const unsigned char *p = abstract->data + offset; if (datetime) { if (parser->model == D4i || parser->model == D6i || parser->model == D9tx || parser->model == DX || parser->model == ZOOPNOVO || parser->model == VYPERNOVO || parser->model == D4F) { datetime->year = p[0] + (p[1] << 8); datetime->month = p[2]; datetime->day = p[3]; datetime->hour = p[4]; datetime->minute = p[5]; datetime->second = p[6]; } else { datetime->hour = p[0]; datetime->minute = p[1]; datetime->second = p[2]; datetime->year = p[3] + (p[4] << 8); datetime->month = p[5]; datetime->day = p[6]; } datetime->timezone = DC_TIMEZONE_NONE; } return DC_STATUS_SUCCESS; } #define BUFLEN 16 static dc_status_t suunto_d9_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { suunto_d9_parser_t *parser = (suunto_d9_parser_t*) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; // Cache the gas mix data. dc_status_t rc = suunto_d9_parser_cache (parser); if (rc != DC_STATUS_SUCCESS) return rc; dc_gasmix_t *gasmix = (dc_gasmix_t *) value; dc_field_string_t *string = (dc_field_string_t *) value; char buf[BUFLEN]; if (value) { switch (type) { case DC_FIELD_DIVETIME: if (parser->model == D4) *((unsigned int *) value) = array_uint16_le (data + 0x0B); else if (parser->model == D4i || parser->model == D6i || parser->model == D9tx || parser->model == DX || parser->model == ZOOPNOVO || parser->model == VYPERNOVO || parser->model == D4F) *((unsigned int *) value) = array_uint16_le (data + 0x0D); else if (parser->model == HELO2) *((unsigned int *) value) = array_uint16_le (data + 0x0D) * 60; else *((unsigned int *) value) = array_uint16_le (data + 0x0B) * 60; break; case DC_FIELD_MAXDEPTH: *((double *) value) = array_uint16_le (data + 0x09) / 100.0; break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = parser->ngasmixes; break; case DC_FIELD_GASMIX: gasmix->helium = parser->helium[flags] / 100.0; gasmix->oxygen = parser->oxygen[flags] / 100.0; gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium; break; case DC_FIELD_DIVEMODE: switch (parser->mode) { case AIR: case NITROX: case MIXED: *((dc_divemode_t *) value) = DC_DIVEMODE_OC; break; case GAUGE: *((dc_divemode_t *) value) = DC_DIVEMODE_GAUGE; break; case FREEDIVE: *((dc_divemode_t *) value) = DC_DIVEMODE_FREEDIVE; break; case CCR: *((dc_divemode_t *) value) = DC_DIVEMODE_CCR; break; default: return DC_STATUS_DATAFORMAT; } break; case DC_FIELD_STRING: switch (flags) { case 0: /* serial */ string->desc = "Serial"; snprintf(buf, BUFLEN, "%08u", parser->serial); break; default: return DC_STATUS_UNSUPPORTED; } string->value = strdup(buf); break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t suunto_d9_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { suunto_d9_parser_t *parser = (suunto_d9_parser_t*) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; // Cache the gas mix data. dc_status_t rc = suunto_d9_parser_cache (parser); if (rc != DC_STATUS_SUCCESS) return rc; // Number of parameters in the configuration data. unsigned int nparams = data[parser->config]; if (nparams == 0 || nparams > MAXPARAMS) { ERROR (abstract->context, "Invalid number of parameters."); return DC_STATUS_DATAFORMAT; } // Available divisor values. const unsigned int divisors[] = {1, 2, 4, 5, 10, 50, 100, 1000}; // Get the sample configuration. sample_info_t info[MAXPARAMS] = {{0}}; for (unsigned int i = 0; i < nparams; ++i) { unsigned int idx = parser->config + 2 + i * 3; info[i].type = data[idx + 0]; info[i].interval = data[idx + 1]; info[i].divisor = divisors[(data[idx + 2] & 0x1C) >> 2]; switch (info[i].type) { case 0x64: // Depth case 0x68: // Pressure info[i].size = 2; break; case 0x74: // Temperature info[i].size = 1; break; default: // Unknown sample type ERROR (abstract->context, "Unknown sample type 0x%02x.", info[i].type); return DC_STATUS_DATAFORMAT; } } // Offset to the profile data. unsigned int profile = parser->config + 2 + nparams * 3; if (profile + 5 > size) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } // HelO2 dives can have an additional data block. const unsigned char sequence[] = {0x01, 0x00, 0x00}; if (parser->model == HELO2 && memcmp (data + profile, sequence, sizeof (sequence)) != 0) profile += 12; if (profile + 5 > size) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } // Sample recording interval. unsigned int interval_sample_offset = 0x18; if (parser->model == HELO2 || parser->model == D4i || parser->model == D6i || parser->model == D9tx || parser->model == ZOOPNOVO || parser->model == VYPERNOVO || parser->model == D4F) interval_sample_offset = 0x1E; else if (parser->model == DX) interval_sample_offset = 0x22; unsigned int interval_sample = data[interval_sample_offset]; if (interval_sample == 0) { ERROR (abstract->context, "Invalid sample interval."); return DC_STATUS_DATAFORMAT; } // Offset to the first marker position. unsigned int marker = array_uint16_le (data + profile + 3); unsigned int in_deco = 0; unsigned int time = 0; unsigned int nsamples = 0; unsigned int offset = profile + 5; while (offset < size) { dc_sample_value_t sample = {0}; // Time (seconds). sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Sample data. for (unsigned int i = 0; i < nparams; ++i) { if (info[i].interval && (nsamples % info[i].interval) == 0) { if (offset + info[i].size > size) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } unsigned int value = 0; switch (info[i].type) { case 0x64: // Depth value = array_uint16_le (data + offset); sample.depth = value / (double) info[i].divisor; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); break; case 0x68: // Pressure value = array_uint16_le (data + offset); if (value != 0xFFFF) { sample.pressure.tank = 0; sample.pressure.value = value / (double) info[i].divisor; if (callback) callback (DC_SAMPLE_PRESSURE, sample, userdata); } break; case 0x74: // Temperature sample.temperature = (signed char) data[offset] / (double) info[i].divisor; if (callback) callback (DC_SAMPLE_TEMPERATURE, sample, userdata); break; default: // Unknown sample type ERROR (abstract->context, "Unknown sample type 0x%02x.", info[i].type); return DC_STATUS_DATAFORMAT; } offset += info[i].size; } } // Initial gasmix. if (time == 0 && parser->ngasmixes > 0) { if (parser->gasmix >= parser->ngasmixes) { ERROR (abstract->context, "Invalid initial gas mix."); return DC_STATUS_DATAFORMAT; } sample.gasmix = parser->gasmix; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); } // Events if ((nsamples + 1) == marker) { while (offset < size) { unsigned int event = data[offset++]; unsigned int seconds, type, unknown, heading; unsigned int current, next; unsigned int he, o2, idx; unsigned int length; sample.event.type = SAMPLE_EVENT_NONE; sample.event.time = 0; sample.event.flags = 0; sample.event.value = 0; switch (event) { case 0x01: // Next Event Marker if (offset + 4 > size) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } current = array_uint16_le (data + offset + 0); next = array_uint16_le (data + offset + 2); if (marker != current) { ERROR (abstract->context, "Unexpected event marker!"); return DC_STATUS_DATAFORMAT; } marker += next; offset += 4; break; case 0x02: // Surfaced if (offset + 2 > size) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } unknown = data[offset + 0]; seconds = data[offset + 1]; sample.event.type = SAMPLE_EVENT_SURFACE; sample.event.time = seconds; if (callback) callback (DC_SAMPLE_EVENT, sample, userdata); offset += 2; break; case 0x03: // Event if (offset + 2 > size) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } type = data[offset + 0]; seconds = data[offset + 1]; switch (type & 0x7F) { case 0x00: // Voluntary Safety Stop sample.event.type = SAMPLE_EVENT_NONE; if (type & 0x80) in_deco &= ~SAFETYSTOP; else in_deco |= SAFETYSTOP; break; case 0x01: // Mandatory Safety Stop - odd concept; model as deco stop sample.event.type = SAMPLE_EVENT_NONE; if (type & 0x80) in_deco &= ~DECOSTOP; else in_deco |= DECOSTOP; break; case 0x02: // Deep Safety Stop sample.event.type = SAMPLE_EVENT_NONE; if (type & 0x80) in_deco &= ~DEEPSTOP; else in_deco |= DEEPSTOP; break; case 0x03: // Deco sample.event.type = SAMPLE_EVENT_NONE; if (type & 0x80) in_deco &= ~DECOSTOP; else in_deco |= DECOSTOP; break; case 0x04: // Ascent Rate Warning sample.event.type = SAMPLE_EVENT_ASCENT; break; case 0x05: // Ceiling Broken sample.event.type = SAMPLE_EVENT_CEILING; break; case 0x06: // Mandatory Safety Stop Ceiling Error sample.event.type = SAMPLE_EVENT_CEILING_SAFETYSTOP; break; case 0x07: // Below Deco Floor sample.event.type = SAMPLE_EVENT_FLOOR; break; case 0x08: // Dive Time sample.event.type = SAMPLE_EVENT_DIVETIME; break; case 0x09: // Depth Alarm sample.event.type = SAMPLE_EVENT_MAXDEPTH; break; case 0x0A: // OLF 80 sample.event.type = SAMPLE_EVENT_OLF; sample.event.value = 80; break; case 0x0B: // OLF 100 sample.event.type = SAMPLE_EVENT_OLF; sample.event.value = 100; break; case 0x0C: // PO2 sample.event.type = SAMPLE_EVENT_PO2; break; case 0x0D: // Air Time Warning sample.event.type = SAMPLE_EVENT_AIRTIME; break; case 0x0E: // RGBM Warning sample.event.type = SAMPLE_EVENT_RGBM; break; case 0x0F: // PO2 High case 0x10: // PO2 Low sample.event.type = SAMPLE_EVENT_PO2; break; case 0x11: // Tissue Level Warning case 0x12: // Tissue Calc Overflow sample.event.type = SAMPLE_EVENT_TISSUELEVEL; break; case 0x13: // Deep Safety Stop sample.event.type = SAMPLE_EVENT_NONE; if (type & 0x80) in_deco &= ~DEEPSTOP; else in_deco |= DEEPSTOP; break; case 0x14: // Mandatory Safety Stop - again, model as deco stop sample.event.type = SAMPLE_EVENT_NONE; if (type & 0x80) in_deco &= ~DECOSTOP; else in_deco |= DECOSTOP; break; default: // Unknown WARNING (abstract->context, "Unknown event type 0x%02x.", type); break; } if (type & 0x80) sample.event.flags = SAMPLE_FLAGS_END; else sample.event.flags = SAMPLE_FLAGS_BEGIN; sample.event.time = seconds; if (sample.event.type != SAMPLE_EVENT_NONE) { if (callback) callback (DC_SAMPLE_EVENT, sample, userdata); } offset += 2; break; case 0x04: // Bookmark/Heading if (offset + 4 > size) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } unknown = data[offset + 0]; seconds = data[offset + 1]; heading = array_uint16_le (data + offset + 2); if (heading == 0xFFFF) { sample.event.type = SAMPLE_EVENT_BOOKMARK; sample.event.value = 0; } else { sample.event.type = SAMPLE_EVENT_HEADING; sample.event.value = heading / 2; } sample.event.time = seconds; if (callback) callback (DC_SAMPLE_EVENT, sample, userdata); offset += 4; break; case 0x05: // Gas Change if (offset + 2 > size) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } o2 = data[offset + 0]; seconds = data[offset + 1]; idx = suunto_d9_parser_find_gasmix(parser, o2, 0); if (idx >= parser->ngasmixes) { ERROR (abstract->context, "Invalid gas mix."); return DC_STATUS_DATAFORMAT; } sample.gasmix = idx; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); offset += 2; break; case 0x06: // Gas Change if (parser->model == DX || parser->model == VYPERNOVO) length = 5; else length = 4; if (offset + length > size) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } unknown = data[offset + 0]; he = data[offset + 1]; o2 = data[offset + 2]; if (parser->model == DX || parser->model == VYPERNOVO) { seconds = data[offset + 4]; } else { seconds = data[offset + 3]; } idx = suunto_d9_parser_find_gasmix(parser, o2, he); if (idx >= parser->ngasmixes) { ERROR (abstract->context, "Invalid gas mix."); return DC_STATUS_DATAFORMAT; } sample.gasmix = idx; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); offset += length; break; default: WARNING (abstract->context, "Unknown event 0x%02x.", event); break; } if (event == 0x01) break; } } if (in_deco & DEEPSTOP) { sample.deco.type = DC_DECO_DEEPSTOP; } else if (in_deco & DECOSTOP) { sample.deco.type = DC_DECO_DECOSTOP; } else if (in_deco & SAFETYSTOP) { sample.deco.type = DC_DECO_SAFETYSTOP; } else { sample.deco.type = DC_DECO_NDL; } sample.deco.time = 0; sample.deco.depth = 0.0; if (callback) callback (DC_SAMPLE_DECO, sample, userdata); time += interval_sample; nsamples++; } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/suunto_d9_parser.c
/* * libdivecomputer * * Copyright (C) 2014 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcmp, memcpy #include <stdlib.h> // malloc, free #include "divesystem_idive.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "checksum.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &divesystem_idive_device_vtable) #define IX3M_EASY 0x22 #define IX3M_DEEP 0x23 #define IX3M_TEC 0x24 #define IX3M_REB 0x25 #define MAXRETRIES 9 #define MAXPACKET 0xFF #define START 0x55 #define ACK 0x06 #define NAK 0x15 #define ERR_INVALID_CMD 0x10 #define ERR_INVALID_LENGTH 0x20 #define ERR_INVALID_DATA 0x30 #define ERR_UNSUPPORTED 0x40 #define ERR_UNAVAILABLE 0x58 #define ERR_UNREADABLE 0x5F #define ERR_BUSY 0x60 #define NSTEPS 1000 #define STEP(i,n) (NSTEPS * (i) / (n)) typedef struct divesystem_idive_command_t { unsigned char cmd; unsigned int size; } divesystem_idive_command_t; typedef struct divesystem_idive_commands_t { divesystem_idive_command_t id; divesystem_idive_command_t range; divesystem_idive_command_t header; divesystem_idive_command_t sample; unsigned int nsamples; } divesystem_idive_commands_t; typedef struct divesystem_idive_device_t { dc_device_t base; dc_iostream_t *iostream; unsigned char fingerprint[4]; unsigned int model; } divesystem_idive_device_t; static dc_status_t divesystem_idive_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t divesystem_idive_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t divesystem_idive_device_close (dc_device_t *abstract); static const dc_device_vtable_t divesystem_idive_device_vtable = { sizeof(divesystem_idive_device_t), DC_FAMILY_DIVESYSTEM_IDIVE, divesystem_idive_device_set_fingerprint, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ NULL, /* dump */ divesystem_idive_device_foreach, /* foreach */ NULL, /* timesync */ divesystem_idive_device_close /* close */ }; static const divesystem_idive_commands_t idive = { {0x10, 0x0A}, {0x98, 0x04}, {0xA0, 0x32}, {0xA8, 0x2A}, 1, }; static const divesystem_idive_commands_t ix3m = { {0x11, 0x1A}, {0x78, 0x04}, {0x79, 0x36}, {0x7A, 0x36}, 1, }; static const divesystem_idive_commands_t ix3m_apos4 = { {0x11, 0x1A}, {0x78, 0x04}, {0x79, 0x36}, {0x7A, 0x40}, 3, }; dc_status_t divesystem_idive_device_open (dc_device_t **out, dc_context_t *context, const char *name, unsigned int model) { dc_status_t status = DC_STATUS_SUCCESS; divesystem_idive_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (divesystem_idive_device_t *) dc_device_allocate (context, &divesystem_idive_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; memset (device->fingerprint, 0, sizeof (device->fingerprint)); device->model = model; // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (115200 8N1). status = dc_iostream_configure (device->iostream, 115200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (1000ms). status = dc_iostream_set_timeout (device->iostream, 1000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Make sure everything is in a sane state. dc_iostream_sleep (device->iostream, 300); dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); *out = (dc_device_t *) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t divesystem_idive_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; divesystem_idive_device_t *device = (divesystem_idive_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t divesystem_idive_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { divesystem_idive_device_t *device = (divesystem_idive_device_t *) abstract; if (size && size != sizeof (device->fingerprint)) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, sizeof (device->fingerprint)); else memset (device->fingerprint, 0, sizeof (device->fingerprint)); return DC_STATUS_SUCCESS; } static dc_status_t divesystem_idive_send (divesystem_idive_device_t *device, const unsigned char command[], unsigned int csize) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; unsigned char packet[MAXPACKET + 4]; unsigned short crc = 0; if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; if (csize < 1 || csize > MAXPACKET) return DC_STATUS_INVALIDARGS; // Setup the data packet packet[0] = START; packet[1] = csize; memcpy(packet + 2, command, csize); crc = checksum_crc_ccitt_uint16 (packet, csize + 2); packet[csize + 2] = (crc >> 8) & 0xFF; packet[csize + 3] = (crc ) & 0xFF; // Send the data packet. status = dc_iostream_write (device->iostream, packet, csize + 4, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } return DC_STATUS_SUCCESS; } static dc_status_t divesystem_idive_receive (divesystem_idive_device_t *device, unsigned char answer[], unsigned int *asize) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; unsigned char packet[MAXPACKET + 4]; if (asize == NULL || *asize < MAXPACKET) { ERROR (abstract->context, "Invalid arguments."); return DC_STATUS_INVALIDARGS; } // Read the packet start byte. while (1) { status = dc_iostream_read (device->iostream, packet + 0, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the packet start byte."); return status; } if (packet[0] == START) break; } // Read the packet length. status = dc_iostream_read (device->iostream, packet + 1, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the packet length."); return status; } unsigned int len = packet[1]; if (len < 2 || len > MAXPACKET) { ERROR (abstract->context, "Invalid packet length."); return DC_STATUS_PROTOCOL; } // Read the packet payload and checksum. status = dc_iostream_read (device->iostream, packet + 2, len + 2, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the packet payload and checksum."); return status; } // Verify the checksum. unsigned short crc = array_uint16_be (packet + len + 2); unsigned short ccrc = checksum_crc_ccitt_uint16 (packet, len + 2); if (crc != ccrc) { ERROR (abstract->context, "Unexpected packet checksum."); return DC_STATUS_PROTOCOL; } memcpy(answer, packet + 2, len); *asize = len; return DC_STATUS_SUCCESS; } static dc_status_t divesystem_idive_packet (divesystem_idive_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize, unsigned int *errorcode) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; unsigned char packet[MAXPACKET] = {0}; unsigned int length = sizeof(packet); unsigned int errcode = 0; // Send the command. status = divesystem_idive_send (device, command, csize); if (status != DC_STATUS_SUCCESS) { goto error; } // Receive the answer. status = divesystem_idive_receive (device, packet, &length); if (status != DC_STATUS_SUCCESS) { goto error; } // Verify the command byte. if (packet[0] != command[0]) { ERROR (abstract->context, "Unexpected packet header."); status = DC_STATUS_PROTOCOL; goto error; } // Verify the ACK/NAK byte. unsigned int type = packet[length - 1]; if (type != ACK && type != NAK) { ERROR (abstract->context, "Unexpected ACK/NAK byte."); status = DC_STATUS_PROTOCOL; goto error; } // Verify the length of the packet. unsigned int expected = (type == ACK ? asize : 1) + 2; if (length != expected) { ERROR (abstract->context, "Unexpected packet length."); status = DC_STATUS_PROTOCOL; goto error; } // Get the error code from a NAK packet. if (type == NAK) { errcode = packet[1]; ERROR (abstract->context, "Received NAK packet with error code %02x.", errcode); status = DC_STATUS_PROTOCOL; goto error; } memcpy(answer, packet + 1, length - 2); error: if (errorcode) { *errorcode = errcode; } return status; } static dc_status_t divesystem_idive_transfer (divesystem_idive_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize, unsigned int *errorcode) { dc_status_t status = DC_STATUS_SUCCESS; unsigned int errcode = 0; unsigned int nretries = 0; while ((status = divesystem_idive_packet (device, command, csize, answer, asize, &errcode)) != DC_STATUS_SUCCESS) { // Automatically discard a corrupted packet, // and request a new one. if (status != DC_STATUS_PROTOCOL && status != DC_STATUS_TIMEOUT) break; // Abort if the device reports a fatal error. if (errcode && errcode != ERR_BUSY) break; // Abort if the maximum number of retries is reached. if (nretries++ >= MAXRETRIES) break; // Delay the next attempt. dc_iostream_sleep (device->iostream, 100); } if (errorcode) { *errorcode = errcode; } return status; } static dc_status_t divesystem_idive_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { dc_status_t rc = DC_STATUS_SUCCESS; divesystem_idive_device_t *device = (divesystem_idive_device_t *) abstract; unsigned char packet[MAXPACKET - 2]; unsigned int errcode = 0; const divesystem_idive_commands_t *commands = &idive; if (device->model >= IX3M_EASY) { commands = &ix3m; } // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); unsigned char cmd_id[] = {commands->id.cmd, 0xED}; rc = divesystem_idive_transfer (device, cmd_id, sizeof(cmd_id), packet, commands->id.size, &errcode); if (rc != DC_STATUS_SUCCESS) return rc; // Emit a device info event. dc_event_devinfo_t devinfo; devinfo.model = array_uint16_le (packet); devinfo.firmware = array_uint32_le (packet + 2); devinfo.serial = array_uint32_le (packet + 6); device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); // Emit a vendor event. dc_event_vendor_t vendor; vendor.data = packet; vendor.size = commands->id.size; device_event_emit (abstract, DC_EVENT_VENDOR, &vendor); if (device->model >= IX3M_EASY) { // Detect the APOS4 firmware. unsigned int apos4 = (devinfo.firmware / 10000000) >= 4; if (apos4) { commands = &ix3m_apos4; } } unsigned char cmd_range[] = {commands->range.cmd, 0x8D}; rc = divesystem_idive_transfer (device, cmd_range, sizeof(cmd_range), packet, commands->range.size, &errcode); if (rc != DC_STATUS_SUCCESS) { if (errcode == ERR_UNAVAILABLE) { return DC_STATUS_SUCCESS; // No dives found. } else { return rc; } } // Get the range of the available dive numbers. unsigned int first = array_uint16_le (packet + 0); unsigned int last = array_uint16_le (packet + 2); if (first > last) { ERROR(abstract->context, "Invalid dive numbers."); return DC_STATUS_DATAFORMAT; } // Calculate the number of dives. unsigned int ndives = last - first + 1; // Update and emit a progress event. progress.maximum = ndives * NSTEPS; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); dc_buffer_t *buffer = dc_buffer_new(0); if (buffer == NULL) { return DC_STATUS_NOMEMORY; } for (unsigned int i = 0; i < ndives; ++i) { unsigned int number = last - i; unsigned char cmd_header[] = {commands->header.cmd, (number ) & 0xFF, (number >> 8) & 0xFF}; rc = divesystem_idive_transfer (device, cmd_header, sizeof(cmd_header), packet, commands->header.size, &errcode); if (rc != DC_STATUS_SUCCESS) { if (errcode == ERR_UNREADABLE) { WARNING(abstract->context, "Skipped unreadable dive!"); continue; } else { dc_buffer_free(buffer); return rc; } } if (memcmp(packet + 7, device->fingerprint, sizeof(device->fingerprint)) == 0) break; unsigned int nsamples = array_uint16_le (packet + 1); // Update and emit a progress event. progress.current = i * NSTEPS + STEP(1, nsamples + 1); device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); dc_buffer_clear(buffer); dc_buffer_reserve(buffer, commands->header.size + commands->sample.size * nsamples); if (!dc_buffer_append(buffer, packet, commands->header.size)) { ERROR (abstract->context, "Insufficient buffer space available."); dc_buffer_free(buffer); return rc; } for (unsigned int j = 0; j < nsamples; j += commands->nsamples) { unsigned int idx = j + 1; unsigned char cmd_sample[] = {commands->sample.cmd, (idx ) & 0xFF, (idx >> 8) & 0xFF}; rc = divesystem_idive_transfer (device, cmd_sample, sizeof(cmd_sample), packet, commands->sample.size * commands->nsamples, &errcode); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free(buffer); return rc; } // If the number of samples is not an exact multiple of the // number of samples per packet, then the last packet // appears to contain garbage data. Ignore those samples. unsigned int n = commands->nsamples; if (j + n > nsamples) { n = nsamples - j; } // Update and emit a progress event. progress.current = i * NSTEPS + STEP(j + n + 1, nsamples + 1); device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); if (!dc_buffer_append(buffer, packet, commands->sample.size * n)) { ERROR (abstract->context, "Insufficient buffer space available."); dc_buffer_free(buffer); return rc; } } unsigned char *data = dc_buffer_get_data(buffer); unsigned int size = dc_buffer_get_size(buffer); if (callback && !callback (data, size, data + 7, sizeof(device->fingerprint), userdata)) { dc_buffer_free (buffer); return DC_STATUS_SUCCESS; } } dc_buffer_free(buffer); return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/divesystem_idive.c
/* * libdivecomputer * * Copyright (C) 2009 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <libdivecomputer/units.h> #include "oceanic_vtpro.h" #include "oceanic_common.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_parser_isinstance((parser), &oceanic_vtpro_parser_vtable) #define AERIS500AI 0x4151 typedef struct oceanic_vtpro_parser_t oceanic_vtpro_parser_t; struct oceanic_vtpro_parser_t { dc_parser_t base; unsigned int model; // Cached fields. unsigned int cached; unsigned int divetime; double maxdepth; }; static dc_status_t oceanic_vtpro_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t oceanic_vtpro_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t oceanic_vtpro_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t oceanic_vtpro_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t oceanic_vtpro_parser_vtable = { sizeof(oceanic_vtpro_parser_t), DC_FAMILY_OCEANIC_VTPRO, oceanic_vtpro_parser_set_data, /* set_data */ oceanic_vtpro_parser_get_datetime, /* datetime */ oceanic_vtpro_parser_get_field, /* fields */ oceanic_vtpro_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; dc_status_t oceanic_vtpro_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int model) { oceanic_vtpro_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (oceanic_vtpro_parser_t *) dc_parser_allocate (context, &oceanic_vtpro_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. parser->model = model; parser->cached = 0; parser->divetime = 0; parser->maxdepth = 0.0; *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; } static dc_status_t oceanic_vtpro_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { oceanic_vtpro_parser_t *parser = (oceanic_vtpro_parser_t *) abstract; // Reset the cache. parser->cached = 0; parser->divetime = 0; parser->maxdepth = 0.0; return DC_STATUS_SUCCESS; } static dc_status_t oceanic_vtpro_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { oceanic_vtpro_parser_t *parser = (oceanic_vtpro_parser_t *) abstract; if (abstract->size < 8) return DC_STATUS_DATAFORMAT; const unsigned char *p = abstract->data; if (datetime) { // AM/PM bit of the 12-hour clock. unsigned int pm = 0; if (parser->model == AERIS500AI) { datetime->year = (p[2] & 0x0F) + 1999; datetime->month = (p[3] & 0xF0) >> 4; datetime->day = ((p[2] & 0xF0) >> 4) | ((p[3] & 0x02) << 3); datetime->hour = bcd2dec (p[1] & 0x0F) + 10 * (p[3] & 0x01); pm = p[3] & 0x08; } else { // The logbook entry can only store the last digit of the year field, // but the full year is also available in the dive header. if (abstract->size < 40) datetime->year = bcd2dec (p[4] & 0x0F) + 2000; else datetime->year = bcd2dec (((p[32 + 3] & 0xC0) >> 2) + ((p[32 + 2] & 0xF0) >> 4)) + 2000; datetime->month = (p[4] & 0xF0) >> 4; datetime->day = bcd2dec (p[3]); datetime->hour = bcd2dec (p[1] & 0x7F); pm = p[1] & 0x80; } datetime->minute = bcd2dec (p[0]); datetime->second = 0; datetime->timezone = DC_TIMEZONE_NONE; // Convert to a 24-hour clock. datetime->hour %= 12; if (pm) datetime->hour += 12; } return DC_STATUS_SUCCESS; } static dc_status_t oceanic_vtpro_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { oceanic_vtpro_parser_t *parser = (oceanic_vtpro_parser_t *) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; if (size < 7 * PAGESIZE / 2) return DC_STATUS_DATAFORMAT; if (!parser->cached) { sample_statistics_t statistics = SAMPLE_STATISTICS_INITIALIZER; dc_status_t rc = oceanic_vtpro_parser_samples_foreach ( abstract, sample_statistics_cb, &statistics); if (rc != DC_STATUS_SUCCESS) return rc; parser->cached = 1; parser->divetime = statistics.divetime; parser->maxdepth = statistics.maxdepth; } unsigned int footer = size - PAGESIZE; unsigned int oxygen = 0; unsigned int maxdepth = 0; unsigned int beginpressure = array_uint16_le(data + 0x26) & 0x0FFF; unsigned int endpressure = array_uint16_le(data + footer + 0x05) & 0x0FFF; if (parser->model == AERIS500AI) { oxygen = (array_uint16_le(data + footer + 2) & 0x0FF0) >> 4; maxdepth = data[footer + 1]; } else { oxygen = data[footer + 3]; maxdepth = array_uint16_le(data + footer + 0) & 0x0FFF; } dc_gasmix_t *gasmix = (dc_gasmix_t *) value; dc_tank_t *tank = (dc_tank_t *) value; if (value) { switch (type) { case DC_FIELD_DIVETIME: *((unsigned int *) value) = parser->divetime; break; case DC_FIELD_MAXDEPTH: *((double *) value) = maxdepth * FEET; break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = 1; break; case DC_FIELD_GASMIX: gasmix->helium = 0.0; if (oxygen) gasmix->oxygen = oxygen / 100.0; else gasmix->oxygen = 0.21; gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium; break; case DC_FIELD_TANK_COUNT: if (beginpressure == 0 && endpressure == 0) *((unsigned int *) value) = 0; else *((unsigned int *) value) = 1; break; case DC_FIELD_TANK: tank->type = DC_TANKVOLUME_NONE; tank->volume = 0.0; tank->workpressure = 0.0; tank->gasmix = flags; tank->beginpressure = beginpressure * 2 * PSI / BAR; tank->endpressure = endpressure * 2 * PSI / BAR; break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t oceanic_vtpro_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { oceanic_vtpro_parser_t *parser = (oceanic_vtpro_parser_t *) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; if (size < 7 * PAGESIZE / 2) return DC_STATUS_DATAFORMAT; unsigned int time = 0; unsigned int interval = 0; if (parser->model == AERIS500AI) { const unsigned int intervals[] = {2, 5, 10, 15, 20, 25, 30}; unsigned int samplerate = (data[0x27] >> 4); if (samplerate >= 3 && samplerate <= 9) { interval = intervals[samplerate - 3]; } } else { const unsigned int intervals[] = {2, 15, 30, 60}; unsigned int samplerate = (data[0x27] >> 4) & 0x07; if (samplerate <= 3) { interval = intervals[samplerate]; } } // Initialize the state for the timestamp processing. unsigned int timestamp = 0, count = 0, i = 0; unsigned int offset = 5 * PAGESIZE / 2; while (offset + PAGESIZE / 2 <= size - PAGESIZE) { dc_sample_value_t sample = {0}; // Ignore empty samples. if (array_isequal (data + offset, PAGESIZE / 2, 0x00) || array_isequal (data + offset, PAGESIZE / 2, 0xFF)) { offset += PAGESIZE / 2; continue; } // Get the current timestamp. unsigned int current = bcd2dec (data[offset + 1] & 0x0F) * 60 + bcd2dec (data[offset + 0]); if (current < timestamp) { ERROR (abstract->context, "Timestamp moved backwards."); return DC_STATUS_DATAFORMAT; } if (current != timestamp || count == 0) { // A sample with a new timestamp. i = 0; if (interval) { // With a time based sample interval, the maximum number // of samples for a single timestamp is always fixed. count = 60 / interval; } else { // With a depth based sample interval, the exact number // of samples for a single timestamp needs to be counted. count = 1; unsigned int idx = offset + PAGESIZE / 2 ; while (idx + PAGESIZE / 2 <= size - PAGESIZE) { // Ignore empty samples. if (array_isequal (data + idx, PAGESIZE / 2, 0x00) || array_isequal (data + idx, PAGESIZE / 2, 0xFF)) { idx += PAGESIZE / 2; continue; } unsigned int next = bcd2dec (data[idx + 1] & 0x0F) * 60 + bcd2dec (data[idx + 0]); if (next != current) break; idx += PAGESIZE / 2; count++; } } } else { // A sample with the same timestamp. i++; } if (interval) { if (current > timestamp + 1) { ERROR (abstract->context, "Unexpected timestamp jump."); return DC_STATUS_DATAFORMAT; } if (i >= count) { WARNING (abstract->context, "Unexpected sample with the same timestamp ignored."); offset += PAGESIZE / 2; continue; } } // Store the current timestamp. timestamp = current; // Time. if (interval) time = timestamp * 60 + (i + 1) * interval; else time = timestamp * 60 + (i + 1) * 60.0 / count + 0.5; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Vendor specific data sample.vendor.type = SAMPLE_VENDOR_OCEANIC_VTPRO; sample.vendor.size = PAGESIZE / 2; sample.vendor.data = data + offset; if (callback) callback (DC_SAMPLE_VENDOR, sample, userdata); // Depth (ft) unsigned int depth = 0; if (parser->model == AERIS500AI) { depth = (array_uint16_le(data + offset + 2) & 0x0FF0) >> 4; } else { depth = data[offset + 3]; } sample.depth = depth * FEET; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); // Temperature (°F) unsigned int temperature = 0; if (parser->model == AERIS500AI) { temperature = (array_uint16_le(data + offset + 6) & 0x0FF0) >> 4; } else { temperature = data[offset + 6]; } sample.temperature = (temperature - 32.0) * (5.0 / 9.0); if (callback) callback (DC_SAMPLE_TEMPERATURE, sample, userdata); offset += PAGESIZE / 2; } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/oceanic_vtpro_parser.c
/* * libdivecomputer * * Copyright (C) 2013 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <string.h> #include <assert.h> #include "uwatec_meridian.h" #include "context-private.h" #include "device-private.h" #include "checksum.h" #include "serial.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &uwatec_meridian_device_vtable) #define ACK 0x11 #define NAK 0x66 typedef struct uwatec_meridian_device_t { dc_device_t base; dc_iostream_t *iostream; unsigned int timestamp; unsigned int devtime; dc_ticks_t systime; } uwatec_meridian_device_t; static dc_status_t uwatec_meridian_device_set_fingerprint (dc_device_t *device, const unsigned char data[], unsigned int size); static dc_status_t uwatec_meridian_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t uwatec_meridian_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t uwatec_meridian_device_close (dc_device_t *abstract); static const dc_device_vtable_t uwatec_meridian_device_vtable = { sizeof(uwatec_meridian_device_t), DC_FAMILY_UWATEC_MERIDIAN, uwatec_meridian_device_set_fingerprint, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ uwatec_meridian_device_dump, /* dump */ uwatec_meridian_device_foreach, /* foreach */ NULL, /* timesync */ uwatec_meridian_device_close /* close */ }; static dc_status_t uwatec_meridian_extract_dives (dc_device_t *device, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata); static dc_status_t uwatec_meridian_transfer (uwatec_meridian_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; assert (csize > 0 && csize <= 255); // Build the packet. unsigned char packet[255 + 12] = { 0xFF, 0xFF, 0xFF, 0xA6, 0x59, 0xBD, 0xC2, 0x00, /* length */ 0x00, 0x00, 0x00, 0x00}; /* data and checksum */ memcpy (packet + 11, command, csize); packet[7] = csize; packet[11 + csize] = checksum_xor_uint8 (packet + 7, csize + 4, 0x00); // Send the packet. status = dc_iostream_write (device->iostream, packet, csize + 12, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Read the echo. unsigned char echo[sizeof(packet)]; status = dc_iostream_read (device->iostream, echo, csize + 12, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the echo."); return status; } // Verify the echo. if (memcmp (echo, packet, csize + 12) != 0) { WARNING (abstract->context, "Unexpected echo."); return DC_STATUS_PROTOCOL; } // Read the header. unsigned char header[6]; status = dc_iostream_read (device->iostream, header, sizeof (header), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the header."); return status; } // Verify the header. if (header[0] != ACK || array_uint32_le (header + 1) != asize + 1 || header[5] != packet[11]) { WARNING (abstract->context, "Unexpected header."); return DC_STATUS_PROTOCOL; } // Read the packet. status = dc_iostream_read (device->iostream, answer, asize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the packet."); return status; } // Read the checksum. unsigned char csum = 0x00; status = dc_iostream_read (device->iostream, &csum, sizeof (csum), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the checksum."); return status; } // Verify the checksum. unsigned char ccsum = 0x00; ccsum = checksum_xor_uint8 (header + 1, sizeof (header) - 1, ccsum); ccsum = checksum_xor_uint8 (answer, asize, ccsum); if (csum != ccsum) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } static dc_status_t uwatec_meridian_handshake (uwatec_meridian_device_t *device) { dc_device_t *abstract = (dc_device_t *) device; // Command template. unsigned char answer[1] = {0}; unsigned char command[5] = {0x00, 0x10, 0x27, 0, 0}; // Handshake (stage 1). command[0] = 0x1B; dc_status_t rc = uwatec_meridian_transfer (device, command, 1, answer, 1); if (rc != DC_STATUS_SUCCESS) return rc; // Verify the answer. if (answer[0] != 0x01) { ERROR (abstract->context, "Unexpected answer byte(s)."); return DC_STATUS_PROTOCOL; } // Handshake (stage 2). command[0] = 0x1C; rc = uwatec_meridian_transfer (device, command, 5, answer, 1); if (rc != DC_STATUS_SUCCESS) return rc; // Verify the answer. if (answer[0] != 0x01) { ERROR (abstract->context, "Unexpected answer byte(s)."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } dc_status_t uwatec_meridian_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; uwatec_meridian_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (uwatec_meridian_device_t *) dc_device_allocate (context, &uwatec_meridian_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; device->timestamp = 0; device->systime = (dc_ticks_t) -1; device->devtime = 0; // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (57600 8N1). status = dc_iostream_configure (device->iostream, 57600, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (3000ms). status = dc_iostream_set_timeout (device->iostream, 3000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Make sure everything is in a sane state. dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); // Perform the handshaking. status = uwatec_meridian_handshake (device); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to handshake with the device."); goto error_close; } *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t uwatec_meridian_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; uwatec_meridian_device_t *device = (uwatec_meridian_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t uwatec_meridian_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { uwatec_meridian_device_t *device = (uwatec_meridian_device_t*) abstract; if (size && size != 4) return DC_STATUS_INVALIDARGS; if (size) device->timestamp = array_uint32_le (data); else device->timestamp = 0; return DC_STATUS_SUCCESS; } static dc_status_t uwatec_meridian_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { dc_status_t status = DC_STATUS_SUCCESS; uwatec_meridian_device_t *device = (uwatec_meridian_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; device_event_emit (&device->base, DC_EVENT_PROGRESS, &progress); // Command template. unsigned char command[9] = {0x00, (device->timestamp ) & 0xFF, (device->timestamp >> 8 ) & 0xFF, (device->timestamp >> 16) & 0xFF, (device->timestamp >> 24) & 0xFF, 0x10, 0x27, 0, 0}; // Read the model number. command[0] = 0x10; unsigned char model[1] = {0}; rc = uwatec_meridian_transfer (device, command, 1, model, sizeof (model)); if (rc != DC_STATUS_SUCCESS) return rc; // Read the serial number. command[0] = 0x14; unsigned char serial[4] = {0}; rc = uwatec_meridian_transfer (device, command, 1, serial, sizeof (serial)); if (rc != DC_STATUS_SUCCESS) return rc; // Read the device clock. command[0] = 0x1A; unsigned char devtime[4] = {0}; rc = uwatec_meridian_transfer (device, command, 1, devtime, sizeof (devtime)); if (rc != DC_STATUS_SUCCESS) return rc; // Store the clock calibration values. device->systime = dc_datetime_now (); device->devtime = array_uint32_le (devtime); // Update and emit a progress event. progress.current += 9; device_event_emit (&device->base, DC_EVENT_PROGRESS, &progress); // Emit a clock event. dc_event_clock_t clock; clock.systime = device->systime; clock.devtime = device->devtime; device_event_emit (&device->base, DC_EVENT_CLOCK, &clock); // Emit a device info event. dc_event_devinfo_t devinfo; devinfo.model = model[0]; devinfo.firmware = 0; devinfo.serial = array_uint32_le (serial); device_event_emit (&device->base, DC_EVENT_DEVINFO, &devinfo); // Data Length. command[0] = 0xC6; unsigned char answer[4] = {0}; rc = uwatec_meridian_transfer (device, command, sizeof (command), answer, sizeof (answer)); if (rc != DC_STATUS_SUCCESS) return rc; unsigned int length = array_uint32_le (answer); // Update and emit a progress event. progress.maximum = 4 + 9 + (length ? length + 4 : 0); progress.current += 4; device_event_emit (&device->base, DC_EVENT_PROGRESS, &progress); if (length == 0) return DC_STATUS_SUCCESS; // Allocate the required amount of memory. if (!dc_buffer_resize (buffer, length)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } unsigned char *data = dc_buffer_get_data (buffer); // Data. command[0] = 0xC4; rc = uwatec_meridian_transfer (device, command, sizeof (command), answer, sizeof (answer)); if (rc != DC_STATUS_SUCCESS) return rc; unsigned int total = array_uint32_le (answer); // Update and emit a progress event. progress.current += 4; device_event_emit (&device->base, DC_EVENT_PROGRESS, &progress); if (total != length + 4) { ERROR (abstract->context, "Received an unexpected size."); return DC_STATUS_PROTOCOL; } unsigned int nbytes = 0; while (nbytes < length) { // Read the header. unsigned char header[5]; status = dc_iostream_read (device->iostream, header, sizeof (header), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the header."); return status; } // Get the packet size. unsigned int packetsize = array_uint32_le (header); if (packetsize < 1 || nbytes + packetsize - 1 > length) { WARNING (abstract->context, "Unexpected header."); return DC_STATUS_PROTOCOL; } // Read the packet data. status = dc_iostream_read (device->iostream, data + nbytes, packetsize - 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the packet."); return status; } // Read the checksum. unsigned char csum = 0x00; status = dc_iostream_read (device->iostream, &csum, sizeof (csum), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the checksum."); return status; } // Verify the checksum. unsigned char ccsum = 0x00; ccsum = checksum_xor_uint8 (header, sizeof (header), ccsum); ccsum = checksum_xor_uint8 (data + nbytes, packetsize - 1, ccsum); if (csum != ccsum) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } // Update and emit a progress event. progress.current += packetsize - 1; device_event_emit (&device->base, DC_EVENT_PROGRESS, &progress); nbytes += packetsize - 1; } return DC_STATUS_SUCCESS; } static dc_status_t uwatec_meridian_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { dc_buffer_t *buffer = dc_buffer_new (0); if (buffer == NULL) return DC_STATUS_NOMEMORY; dc_status_t rc = uwatec_meridian_device_dump (abstract, buffer); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } rc = uwatec_meridian_extract_dives (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), callback, userdata); dc_buffer_free (buffer); return rc; } static dc_status_t uwatec_meridian_extract_dives (dc_device_t *abstract, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata) { if (abstract && !ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; const unsigned char header[4] = {0xa5, 0xa5, 0x5a, 0x5a}; // Search the data stream for start markers. unsigned int previous = size; unsigned int current = (size >= 4 ? size - 4 : 0); while (current > 0) { current--; if (memcmp (data + current, header, sizeof (header)) == 0) { // Get the length of the profile data. unsigned int len = array_uint32_le (data + current + 4); // Check for a buffer overflow. if (current + len > previous) return DC_STATUS_DATAFORMAT; if (callback && !callback (data + current, len, data + current + 8, 4, userdata)) return DC_STATUS_SUCCESS; // Prepare for the next dive. previous = current; current = (current >= 4 ? current - 4 : 0); } } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/uwatec_meridian.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcmp, memcpy #include <stdlib.h> // malloc, free #include "reefnet_sensus.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "checksum.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &reefnet_sensus_device_vtable) #define SZ_MEMORY 32768 #define SZ_HANDSHAKE 10 typedef struct reefnet_sensus_device_t { dc_device_t base; dc_iostream_t *iostream; unsigned char handshake[SZ_HANDSHAKE]; unsigned int waiting; unsigned int timestamp; unsigned int devtime; dc_ticks_t systime; } reefnet_sensus_device_t; static dc_status_t reefnet_sensus_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t reefnet_sensus_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t reefnet_sensus_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t reefnet_sensus_device_close (dc_device_t *abstract); static const dc_device_vtable_t reefnet_sensus_device_vtable = { sizeof(reefnet_sensus_device_t), DC_FAMILY_REEFNET_SENSUS, reefnet_sensus_device_set_fingerprint, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ reefnet_sensus_device_dump, /* dump */ reefnet_sensus_device_foreach, /* foreach */ NULL, /* timesync */ reefnet_sensus_device_close /* close */ }; static dc_status_t reefnet_sensus_extract_dives (dc_device_t *device, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata); static dc_status_t reefnet_sensus_cancel (reefnet_sensus_device_t *device) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; // Send the command to the device. unsigned char command = 0x00; status = dc_iostream_write (device->iostream, &command, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // The device leaves the waiting state. device->waiting = 0; return DC_STATUS_SUCCESS; } dc_status_t reefnet_sensus_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; reefnet_sensus_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (reefnet_sensus_device_t *) dc_device_allocate (context, &reefnet_sensus_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; device->waiting = 0; device->timestamp = 0; device->systime = (dc_ticks_t) -1; device->devtime = 0; memset (device->handshake, 0, sizeof (device->handshake)); // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (19200 8N1). status = dc_iostream_configure (device->iostream, 19200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (3000 ms). status = dc_iostream_set_timeout (device->iostream, 3000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Make sure everything is in a sane state. dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t reefnet_sensus_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; reefnet_sensus_device_t *device = (reefnet_sensus_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Safely close the connection if the last handshake was // successful, but no data transfer was ever initiated. if (device->waiting) { rc = reefnet_sensus_cancel (device); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } } // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } dc_status_t reefnet_sensus_device_get_handshake (dc_device_t *abstract, unsigned char data[], unsigned int size) { reefnet_sensus_device_t *device = (reefnet_sensus_device_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size < SZ_HANDSHAKE) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_INVALIDARGS; } memcpy (data, device->handshake, SZ_HANDSHAKE); return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensus_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { reefnet_sensus_device_t *device = (reefnet_sensus_device_t*) abstract; if (size && size != 4) return DC_STATUS_INVALIDARGS; if (size) device->timestamp = array_uint32_le (data); else device->timestamp = 0; return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensus_handshake (reefnet_sensus_device_t *device) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; // Send the command to the device. unsigned char command = 0x0A; status = dc_iostream_write (device->iostream, &command, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Receive the answer from the device. unsigned char handshake[SZ_HANDSHAKE + 2] = {0}; status = dc_iostream_read (device->iostream, handshake, sizeof (handshake), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the handshake."); return status; } // Verify the header of the packet. if (handshake[0] != 'O' || handshake[1] != 'K') { ERROR (abstract->context, "Unexpected answer header."); return DC_STATUS_PROTOCOL; } // The device is now waiting for a data request. device->waiting = 1; // Store the clock calibration values. device->systime = dc_datetime_now (); device->devtime = array_uint32_le (handshake + 8); // Store the handshake packet. memcpy (device->handshake, handshake + 2, SZ_HANDSHAKE); // Emit a clock event. dc_event_clock_t clock; clock.systime = device->systime; clock.devtime = device->devtime; device_event_emit (&device->base, DC_EVENT_CLOCK, &clock); // Emit a device info event. dc_event_devinfo_t devinfo; devinfo.model = handshake[2] - '0'; devinfo.firmware = handshake[3] - '0'; devinfo.serial = array_uint16_le (handshake + 6); device_event_emit (&device->base, DC_EVENT_DEVINFO, &devinfo); // Emit a vendor event. dc_event_vendor_t vendor; vendor.data = device->handshake; vendor.size = sizeof (device->handshake); device_event_emit (abstract, DC_EVENT_VENDOR, &vendor); // Wait at least 10 ms to ensures the data line is // clear before transmission from the host begins. dc_iostream_sleep (device->iostream, 10); return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensus_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { dc_status_t status = DC_STATUS_SUCCESS; reefnet_sensus_device_t *device = (reefnet_sensus_device_t*) abstract; // Pre-allocate the required amount of memory. if (!dc_buffer_reserve (buffer, SZ_MEMORY)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = 4 + SZ_MEMORY + 2 + 3; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Wake-up the device. dc_status_t rc = reefnet_sensus_handshake (device); if (rc != DC_STATUS_SUCCESS) return rc; // Send the command to the device. unsigned char command = 0x40; status = dc_iostream_write (device->iostream, &command, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // The device leaves the waiting state. device->waiting = 0; // Receive the answer from the device. unsigned int nbytes = 0; unsigned char answer[4 + SZ_MEMORY + 2 + 3] = {0}; while (nbytes < sizeof (answer)) { unsigned int len = sizeof (answer) - nbytes; if (len > 128) len = 128; status = dc_iostream_read (device->iostream, answer + nbytes, len, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Update and emit a progress event. progress.current += len; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); nbytes += len; } // Verify the headers of the package. if (memcmp (answer, "DATA", 4) != 0 || memcmp (answer + sizeof (answer) - 3, "END", 3) != 0) { ERROR (abstract->context, "Unexpected answer start or end byte(s)."); return DC_STATUS_PROTOCOL; } // Verify the checksum of the package. unsigned short crc = array_uint16_le (answer + 4 + SZ_MEMORY); unsigned short ccrc = checksum_add_uint16 (answer + 4, SZ_MEMORY, 0x00); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } dc_buffer_append (buffer, answer + 4, SZ_MEMORY); return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensus_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { dc_buffer_t *buffer = dc_buffer_new (SZ_MEMORY); if (buffer == NULL) return DC_STATUS_NOMEMORY; dc_status_t rc = reefnet_sensus_device_dump (abstract, buffer); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } rc = reefnet_sensus_extract_dives (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), callback, userdata); dc_buffer_free (buffer); return rc; } static dc_status_t reefnet_sensus_extract_dives (dc_device_t *abstract, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata) { reefnet_sensus_device_t *device = (reefnet_sensus_device_t*) abstract; dc_context_t *context = (abstract ? abstract->context : NULL); if (abstract && !ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; // Search the entire data stream for start markers. unsigned int previous = size; unsigned int current = (size >= 7 ? size - 7 : 0); while (current > 0) { current--; if (data[current] == 0xFF && data[current + 6] == 0xFE) { // Once a start marker is found, start searching // for the end of the dive. The search is now // limited to the start of the previous dive. int found = 0; unsigned int nsamples = 0, count = 0; unsigned int offset = current + 7; // Skip non-sample data. while (offset + 1 <= previous) { // Depth (adjusted feet of seawater). unsigned char depth = data[offset++]; // Temperature (degrees Fahrenheit) if ((nsamples % 6) == 0) { if (offset + 1 > previous) break; offset++; } // Current sample is complete. nsamples++; // The end of a dive is reached when 17 consecutive // depth samples of less than 3 feet have been found. if (depth < 13 + 3) { count++; if (count == 17) { found = 1; break; } } else { count = 0; } } // Report an error if no end of dive was found. if (!found) { ERROR (context, "No end of dive found."); return DC_STATUS_DATAFORMAT; } // Automatically abort when a dive is older than the provided timestamp. unsigned int timestamp = array_uint32_le (data + current + 2); if (device && timestamp <= device->timestamp) return DC_STATUS_SUCCESS; if (callback && !callback (data + current, offset - current, data + current + 2, 4, userdata)) return DC_STATUS_SUCCESS; // Prepare for the next dive. previous = current; current = (current >= 7 ? current - 7 : 0); } } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/reefnet_sensus.c
/* * libdivecomputer * * Copyright (C) 2009 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> // malloc #include <string.h> // memcpy, memcmp #include <assert.h> // assert #include "context-private.h" #include "mares_common.h" #include "checksum.h" #include "array.h" #define MAXRETRIES 4 #define FP_OFFSET 8 #define FP_SIZE 5 #define NEMO 0 #define NEMOWIDE 1 #define NEMOAIR 4 #define PUCK 7 #define NEMOEXCEL 17 #define NEMOAPNEIST 18 #define PUCKAIR 19 #define AIR 0 #define NITROX 1 #define FREEDIVE 2 #define GAUGE 3 void mares_common_device_init (mares_common_device_t *device) { assert (device != NULL); // Set the default values. device->iostream = NULL; device->echo = 0; device->delay = 0; } static void mares_common_make_ascii (const unsigned char raw[], unsigned int rsize, unsigned char ascii[], unsigned int asize) { assert (asize == 2 * (rsize + 2)); // Header ascii[0] = '<'; // Data array_convert_bin2hex (raw, rsize, ascii + 1, 2 * rsize); // Checksum unsigned char checksum = checksum_add_uint8 (ascii + 1, 2 * rsize, 0x00); array_convert_bin2hex (&checksum, 1, ascii + 1 + 2 * rsize, 2); // Trailer ascii[asize - 1] = '>'; } static dc_status_t mares_common_packet (mares_common_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; if (device->delay) { dc_iostream_sleep (device->iostream, device->delay); } // Send the command to the device. status = dc_iostream_write (device->iostream, command, csize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } if (device->echo) { // Receive the echo of the command. unsigned char echo[PACKETSIZE] = {0}; status = dc_iostream_read (device->iostream, echo, csize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the echo."); return status; } // Verify the echo. if (memcmp (echo, command, csize) != 0) { WARNING (abstract->context, "Unexpected echo."); } } // Receive the answer of the device. status = dc_iostream_read (device->iostream, answer, asize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Verify the header and trailer of the packet. if (answer[0] != '<' || answer[asize - 1] != '>') { ERROR (abstract->context, "Unexpected answer header/trailer byte."); return DC_STATUS_PROTOCOL; } // Verify the checksum of the packet. unsigned char crc = 0; unsigned char ccrc = checksum_add_uint8 (answer + 1, asize - 4, 0x00); array_convert_hex2bin (answer + asize - 3, 2, &crc, 1); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } static dc_status_t mares_common_transfer (mares_common_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize) { unsigned int nretries = 0; dc_status_t rc = DC_STATUS_SUCCESS; while ((rc = mares_common_packet (device, command, csize, answer, asize)) != DC_STATUS_SUCCESS) { // Automatically discard a corrupted packet, // and request a new one. if (rc != DC_STATUS_PROTOCOL && rc != DC_STATUS_TIMEOUT) return rc; // Abort if the maximum number of retries is reached. if (nretries++ >= MAXRETRIES) return rc; // Discard any garbage bytes. dc_iostream_sleep (device->iostream, 100); dc_iostream_purge (device->iostream, DC_DIRECTION_INPUT); } return rc; } dc_status_t mares_common_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size) { mares_common_device_t *device = (mares_common_device_t*) abstract; unsigned int nbytes = 0; while (nbytes < size) { // Calculate the packet size. unsigned int len = size - nbytes; if (len > PACKETSIZE) len = PACKETSIZE; // Build the raw command. unsigned char raw[] = {0x51, (address ) & 0xFF, // Low (address >> 8) & 0xFF, // High len}; // Count // Build the ascii command. unsigned char command[2 * (sizeof (raw) + 2)] = {0}; mares_common_make_ascii (raw, sizeof (raw), command, sizeof (command)); // Send the command and receive the answer. unsigned char answer[2 * (PACKETSIZE + 2)] = {0}; dc_status_t rc = mares_common_transfer (device, command, sizeof (command), answer, 2 * (len + 2)); if (rc != DC_STATUS_SUCCESS) return rc; // Extract the raw data from the packet. array_convert_hex2bin (answer + 1, 2 * len, data, len); nbytes += len; address += len; data += len; } return DC_STATUS_SUCCESS; } dc_status_t mares_common_extract_dives (dc_context_t *context, const mares_common_layout_t *layout, const unsigned char fingerprint[], const unsigned char data[], dc_dive_callback_t callback, void *userdata) { assert (layout != NULL); // Get the freedive mode for this model. unsigned int model = data[1]; unsigned int freedive = FREEDIVE; if (model == NEMOWIDE || model == NEMOAIR || model == PUCK || model == PUCKAIR) freedive = GAUGE; // Get the end of the profile ring buffer. unsigned int eop = array_uint16_le (data + 0x6B); if (eop < layout->rb_profile_begin || eop >= layout->rb_profile_end) { ERROR (context, "Ringbuffer pointer out of range (0x%04x).", eop); return DC_STATUS_DATAFORMAT; } // Make the ringbuffer linear, to avoid having to deal // with the wrap point. The buffer has extra space to // store the profile data for the freedives. unsigned char *buffer = (unsigned char *) malloc ( layout->rb_profile_end - layout->rb_profile_begin + layout->rb_freedives_end - layout->rb_freedives_begin); if (buffer == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } memcpy (buffer + 0, data + eop, layout->rb_profile_end - eop); memcpy (buffer + layout->rb_profile_end - eop, data + layout->rb_profile_begin, eop - layout->rb_profile_begin); // For a freedive session, the Mares Nemo stores all the freedives of // that session in a single logbook entry, and each sample is actually // a summary for each individual freedive in the session. The profile // data is stored in a separate memory area. Since only the most recent // recent freediving session can have profile data, we keep track of the // number of freedives. unsigned int nfreedives = 0; unsigned int offset = layout->rb_profile_end - layout->rb_profile_begin; while (offset >= 3) { // Check for the presence of extra header bytes, which can be detected // by means of a three byte marker sequence. unsigned int extra = 0; const unsigned char marker[3] = {0xAA, 0xBB, 0xCC}; if (memcmp (buffer + offset - 3, marker, sizeof (marker)) == 0) { if (model == PUCKAIR) extra = 7; else extra = 12; } // Check for overflows due to incomplete dives. if (offset < extra + 3) break; // Check the dive mode of the logbook entry. Valid modes are // 0 (air), 1 (EANx), 2 (freedive) or 3 (bottom timer). // If the ringbuffer has never reached the wrap point before, // there will be "empty" memory (filled with 0xFF) and // processing should stop at this point. unsigned int mode = buffer[offset - extra - 1]; if (mode == 0xFF) break; // The header and sample size are dependant on the dive mode. Only // in freedive mode, the sizes are different from the other modes. unsigned int header_size = 53; unsigned int sample_size = 2; if (extra) { if (model == PUCKAIR) sample_size = 3; else sample_size = 5; } if (mode == freedive) { header_size = 28; sample_size = 6; nfreedives++; } // Get the number of samples in the profile data. unsigned int nsamples = array_uint16_le (buffer + offset - extra - 3); // Calculate the total number of bytes for this dive. // If the buffer does not contain that much bytes, we reached the // end of the ringbuffer. The current dive is incomplete (partially // overwritten with newer data), and processing should stop. unsigned int nbytes = 2 + nsamples * sample_size + header_size + extra; if (offset < nbytes) break; // Move to the start of the dive. offset -= nbytes; // Verify that the length that is stored in the profile data // equals the calculated length. If both values are different, // something is wrong and an error is returned. unsigned int length = array_uint16_le (buffer + offset); if (length != nbytes) { ERROR (context, "Calculated and stored size are not equal (%u %u).", length, nbytes); free (buffer); return DC_STATUS_DATAFORMAT; } // Process the profile data for the most recent freedive entry. // Since we are processing the entries backwards (newest to oldest), // this entry will always be the first one. if (mode == freedive && nfreedives == 1) { // Count the number of freedives in the profile data. unsigned int count = 0; unsigned int idx = layout->rb_freedives_begin; while (idx + 2 <= layout->rb_freedives_end && count != nsamples) { // Each freedive in the session ends with a zero sample. unsigned int sample = array_uint16_le (data + idx); if (sample == 0) count++; // Move to the next sample. idx += 2; } // Verify that the number of freedive entries in the session // equals the number of freedives in the profile data. If // both values are different, the profile data is incomplete. if (count != nsamples) { ERROR (context, "Unexpected number of freedive sessions (%u %u).", count, nsamples); free (buffer); return DC_STATUS_DATAFORMAT; } // Append the profile data to the main logbook entry. The // buffer is guaranteed to have enough space, and the dives // that will be overwritten have already been processed. memcpy (buffer + offset + nbytes, data + layout->rb_freedives_begin, idx - layout->rb_freedives_begin); nbytes += idx - layout->rb_freedives_begin; } unsigned int fp_offset = offset + length - extra - FP_OFFSET; if (fingerprint && memcmp (buffer + fp_offset, fingerprint, FP_SIZE) == 0) { free (buffer); return DC_STATUS_SUCCESS; } if (callback && !callback (buffer + offset, nbytes, buffer + fp_offset, FP_SIZE, userdata)) { free (buffer); return DC_STATUS_SUCCESS; } } free (buffer); return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/mares_common.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcmp, memcpy #include <stdlib.h> // malloc, free #include "reefnet_sensuspro.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "checksum.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &reefnet_sensuspro_device_vtable) #define SZ_MEMORY 56320 #define SZ_HANDSHAKE 10 typedef struct reefnet_sensuspro_device_t { dc_device_t base; dc_iostream_t *iostream; unsigned char handshake[SZ_HANDSHAKE]; unsigned int timestamp; unsigned int devtime; dc_ticks_t systime; } reefnet_sensuspro_device_t; static dc_status_t reefnet_sensuspro_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t reefnet_sensuspro_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t reefnet_sensuspro_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t reefnet_sensuspro_device_close (dc_device_t *abstract); static const dc_device_vtable_t reefnet_sensuspro_device_vtable = { sizeof(reefnet_sensuspro_device_t), DC_FAMILY_REEFNET_SENSUSPRO, reefnet_sensuspro_device_set_fingerprint, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ reefnet_sensuspro_device_dump, /* dump */ reefnet_sensuspro_device_foreach, /* foreach */ NULL, /* timesync */ reefnet_sensuspro_device_close /* close */ }; static dc_status_t reefnet_sensuspro_extract_dives (dc_device_t *device, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata); dc_status_t reefnet_sensuspro_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; reefnet_sensuspro_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (reefnet_sensuspro_device_t *) dc_device_allocate (context, &reefnet_sensuspro_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; device->timestamp = 0; device->systime = (dc_ticks_t) -1; device->devtime = 0; memset (device->handshake, 0, sizeof (device->handshake)); // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (19200 8N1). status = dc_iostream_configure (device->iostream, 19200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (3000ms). status = dc_iostream_set_timeout (device->iostream, 3000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Make sure everything is in a sane state. dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t reefnet_sensuspro_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; reefnet_sensuspro_device_t *device = (reefnet_sensuspro_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } dc_status_t reefnet_sensuspro_device_get_handshake (dc_device_t *abstract, unsigned char data[], unsigned int size) { reefnet_sensuspro_device_t *device = (reefnet_sensuspro_device_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size < SZ_HANDSHAKE) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_INVALIDARGS; } memcpy (data, device->handshake, SZ_HANDSHAKE); return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensuspro_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { reefnet_sensuspro_device_t *device = (reefnet_sensuspro_device_t*) abstract; if (size && size != 4) return DC_STATUS_INVALIDARGS; if (size) device->timestamp = array_uint32_le (data); else device->timestamp = 0; return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensuspro_handshake (reefnet_sensuspro_device_t *device) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; // Assert a break condition. status = dc_iostream_set_break (device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to set break."); return status; } // Receive the handshake from the dive computer. unsigned char handshake[SZ_HANDSHAKE + 2] = {0}; status = dc_iostream_read (device->iostream, handshake, sizeof (handshake), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the handshake."); return status; } // Clear the break condition again. status = dc_iostream_set_break (device->iostream, 0); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to clear break."); return status; } // Verify the checksum of the handshake packet. unsigned short crc = array_uint16_le (handshake + SZ_HANDSHAKE); unsigned short ccrc = checksum_crc_ccitt_uint16 (handshake, SZ_HANDSHAKE); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } // Store the clock calibration values. device->systime = dc_datetime_now (); device->devtime = array_uint32_le (handshake + 6); // Store the handshake packet. memcpy (device->handshake, handshake, SZ_HANDSHAKE); // Emit a clock event. dc_event_clock_t clock; clock.systime = device->systime; clock.devtime = device->devtime; device_event_emit (&device->base, DC_EVENT_CLOCK, &clock); // Emit a device info event. dc_event_devinfo_t devinfo; devinfo.model = handshake[0]; devinfo.firmware = handshake[1]; devinfo.serial = array_uint16_le (handshake + 4); device_event_emit (&device->base, DC_EVENT_DEVINFO, &devinfo); // Emit a vendor event. dc_event_vendor_t vendor; vendor.data = device->handshake; vendor.size = sizeof (device->handshake); device_event_emit (abstract, DC_EVENT_VENDOR, &vendor); dc_iostream_sleep (device->iostream, 10); return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensuspro_send (reefnet_sensuspro_device_t *device, unsigned char command) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; // Wake-up the device. dc_status_t rc = reefnet_sensuspro_handshake (device); if (rc != DC_STATUS_SUCCESS) return rc; // Send the instruction code to the device. status = dc_iostream_write (device->iostream, &command, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensuspro_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { dc_status_t status = DC_STATUS_SUCCESS; reefnet_sensuspro_device_t *device = (reefnet_sensuspro_device_t*) abstract; // Pre-allocate the required amount of memory. if (!dc_buffer_reserve (buffer, SZ_MEMORY)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = SZ_MEMORY + 2; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Wake-up the device and send the instruction code. dc_status_t rc = reefnet_sensuspro_send (device, 0xB4); if (rc != DC_STATUS_SUCCESS) return rc; unsigned int nbytes = 0; unsigned char answer[SZ_MEMORY + 2] = {0}; while (nbytes < sizeof (answer)) { unsigned int len = sizeof (answer) - nbytes; if (len > 256) len = 256; status = dc_iostream_read (device->iostream, answer + nbytes, len, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Update and emit a progress event. progress.current += len; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); nbytes += len; } unsigned short crc = array_uint16_le (answer + SZ_MEMORY); unsigned short ccrc = checksum_crc_ccitt_uint16 (answer, SZ_MEMORY); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } dc_buffer_append (buffer, answer, SZ_MEMORY); return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensuspro_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { dc_buffer_t *buffer = dc_buffer_new (SZ_MEMORY); if (buffer == NULL) return DC_STATUS_NOMEMORY; dc_status_t rc = reefnet_sensuspro_device_dump (abstract, buffer); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } rc = reefnet_sensuspro_extract_dives (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), callback, userdata); dc_buffer_free (buffer); return rc; } dc_status_t reefnet_sensuspro_device_write_interval (dc_device_t *abstract, unsigned char interval) { dc_status_t status = DC_STATUS_SUCCESS; reefnet_sensuspro_device_t *device = (reefnet_sensuspro_device_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (interval < 1 || interval > 127) return DC_STATUS_INVALIDARGS; // Wake-up the device and send the instruction code. dc_status_t rc = reefnet_sensuspro_send (device, 0xB5); if (rc != DC_STATUS_SUCCESS) return rc; dc_iostream_sleep (device->iostream, 10); status = dc_iostream_write (device->iostream, &interval, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the data packet."); return status; } return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensuspro_extract_dives (dc_device_t *abstract, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata) { reefnet_sensuspro_device_t *device = (reefnet_sensuspro_device_t*) abstract; if (abstract && !ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; const unsigned char header[4] = {0x00, 0x00, 0x00, 0x00}; const unsigned char footer[2] = {0xFF, 0xFF}; // Search the entire data stream for start markers. unsigned int previous = size; unsigned int current = (size >= 4 ? size - 4 : 0); while (current > 0) { current--; if (memcmp (data + current, header, sizeof (header)) == 0) { // Once a start marker is found, start searching // for the corresponding stop marker. The search is // now limited to the start of the previous dive. int found = 0; unsigned int offset = current + 10; // Skip non-sample data. while (offset + 2 <= previous) { if (memcmp (data + offset, footer, sizeof (footer)) == 0) { found = 1; break; } else { offset++; } } // Report an error if no stop marker was found. if (!found) return DC_STATUS_DATAFORMAT; // Automatically abort when a dive is older than the provided timestamp. unsigned int timestamp = array_uint32_le (data + current + 6); if (device && timestamp <= device->timestamp) return DC_STATUS_SUCCESS; if (callback && !callback (data + current, offset + 2 - current, data + current + 6, 4, userdata)) return DC_STATUS_SUCCESS; // Prepare for the next dive. previous = current; current = (current >= 4 ? current - 4 : 0); } } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/reefnet_sensuspro.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include "checksum.h" unsigned char checksum_add_uint4 (const unsigned char data[], unsigned int size, unsigned char init) { unsigned char crc = init; for (unsigned int i = 0; i < size; ++i) { crc += (data[i] & 0xF0) >> 4; crc += (data[i] & 0x0F); } return crc; } unsigned char checksum_add_uint8 (const unsigned char data[], unsigned int size, unsigned char init) { unsigned char crc = init; for (unsigned int i = 0; i < size; ++i) crc += data[i]; return crc; } unsigned short checksum_add_uint16 (const unsigned char data[], unsigned int size, unsigned short init) { unsigned short crc = init; for (unsigned int i = 0; i < size; ++i) crc += data[i]; return crc; } unsigned char checksum_xor_uint8 (const unsigned char data[], unsigned int size, unsigned char init) { unsigned char crc = init; for (unsigned int i = 0; i < size; ++i) crc ^= data[i]; return crc; } unsigned short checksum_crc_ccitt_uint16 (const unsigned char data[], unsigned int size) { static const unsigned short crc_ccitt_table[] = { 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 }; unsigned short crc = 0xffff; for (unsigned int i = 0; i < size; ++i) crc = (crc << 8) ^ crc_ccitt_table[(crc >> 8) ^ data[i]]; return crc; }
libdc-for-dirk-Subsurface-branch
src/checksum.c
/* * libdivecomputer * * Copyright (C) 2013 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <libdivecomputer/units.h> #include "diverite_nitekq.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_device_isinstance((parser), &diverite_nitekq_parser_vtable) #define SZ_LOGBOOK 6 #define NGASMIXES 7 typedef struct diverite_nitekq_parser_t diverite_nitekq_parser_t; struct diverite_nitekq_parser_t { dc_parser_t base; // Cached fields. unsigned int cached; unsigned int metric; unsigned int ngasmixes; unsigned int o2[NGASMIXES]; unsigned int he[NGASMIXES]; unsigned int divetime; double maxdepth; }; static dc_status_t diverite_nitekq_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t diverite_nitekq_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t diverite_nitekq_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t diverite_nitekq_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t diverite_nitekq_parser_vtable = { sizeof(diverite_nitekq_parser_t), DC_FAMILY_DIVERITE_NITEKQ, diverite_nitekq_parser_set_data, /* set_data */ diverite_nitekq_parser_get_datetime, /* datetime */ diverite_nitekq_parser_get_field, /* fields */ diverite_nitekq_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; dc_status_t diverite_nitekq_parser_create (dc_parser_t **out, dc_context_t *context) { diverite_nitekq_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (diverite_nitekq_parser_t *) dc_parser_allocate (context, &diverite_nitekq_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. parser->cached = 0; parser->metric = 0; parser->divetime = 0; parser->maxdepth = 0.0; parser->ngasmixes = 0; for (unsigned int i = 0; i < NGASMIXES; ++i) { parser->o2[i] = 0; parser->he[i] = 0; } *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; } static dc_status_t diverite_nitekq_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { return DC_STATUS_SUCCESS; } static dc_status_t diverite_nitekq_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { if (abstract->size < SZ_LOGBOOK) return DC_STATUS_DATAFORMAT; const unsigned char *p = abstract->data; if (datetime) { datetime->year = p[0] + 2000; datetime->month = p[1]; datetime->day = p[2]; datetime->hour = p[3]; datetime->minute = p[4]; datetime->second = p[5]; datetime->timezone = DC_TIMEZONE_NONE; } return DC_STATUS_SUCCESS; } static dc_status_t diverite_nitekq_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { diverite_nitekq_parser_t *parser = (diverite_nitekq_parser_t *) abstract; if (abstract->size < SZ_LOGBOOK) return DC_STATUS_DATAFORMAT; dc_gasmix_t *gasmix = (dc_gasmix_t *) value; if (!parser->cached) { dc_status_t rc = diverite_nitekq_parser_samples_foreach (abstract, NULL, NULL); if (rc != DC_STATUS_SUCCESS) return rc; } if (value) { switch (type) { case DC_FIELD_DIVETIME: *((unsigned int *) value) = parser->divetime; break; case DC_FIELD_MAXDEPTH: if (parser->metric) *((double *) value) = parser->maxdepth / 10.0; else *((double *) value) = parser->maxdepth * FEET / 10.0; break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = parser->ngasmixes; break; case DC_FIELD_GASMIX: gasmix->helium = parser->he[flags] / 100.0; gasmix->oxygen = parser->o2[flags] / 100.0; gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium; break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t diverite_nitekq_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { diverite_nitekq_parser_t *parser = (diverite_nitekq_parser_t *) abstract; if (abstract->size < SZ_LOGBOOK) return DC_STATUS_DATAFORMAT; const unsigned char *data = abstract->data + SZ_LOGBOOK; unsigned int size = abstract->size - SZ_LOGBOOK; unsigned int type = 0; unsigned int metric = 0; unsigned int interval = 0; unsigned int maxdepth = 0; unsigned int oxygen[NGASMIXES]; unsigned int helium[NGASMIXES]; unsigned int ngasmixes = 0; unsigned int gasmix = 0xFFFFFFFF; /* initialize with impossible value */ unsigned int gasmix_previous = gasmix; unsigned int time = 0; unsigned int offset = 0; while (offset + 2 <= size) { if (data[offset] == 0xFF) { unsigned int o2 = 0, he = 0; unsigned int i = 0; type = data[offset + 1]; switch (type) { case 0x01: // Settings if (offset + 27 > size) return DC_STATUS_DATAFORMAT; metric = (data[offset + 0x10] & 0x04) >> 2; interval = data[offset + 0x11]; offset += 27; break; case 0x02: // OC Samples case 0x03: // CC Samples offset += 2; break; case 0x04: // Gas Change if (offset + 7 > size) return DC_STATUS_DATAFORMAT; // Get the new gas mix. o2 = data[offset + 5]; he = data[offset + 6]; // Find the gasmix in the list. i = 0; while (i < ngasmixes) { if (o2 == oxygen[i] && he == helium[i]) break; i++; } // Add it to list if not found. if (i >= ngasmixes) { if (i >= NGASMIXES) { ERROR (abstract->context, "Maximum number of gas mixes reached."); return DC_STATUS_DATAFORMAT; } oxygen[i] = o2; helium[i] = he; ngasmixes = i + 1; } // Remember the index. gasmix = i; offset += 7; break; default: ERROR (abstract->context, "Unknown type %02x", type); return DC_STATUS_DATAFORMAT; } } else if (type == 2 || type == 3) { dc_sample_value_t sample = {0}; if (interval == 0) { ERROR (abstract->context, "No sample interval present."); return DC_STATUS_DATAFORMAT; } // Time (seconds). time += interval; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Gas change if (gasmix != gasmix_previous) { sample.gasmix = gasmix; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); gasmix_previous = gasmix; } // Depth (1/10 m or ft). unsigned int depth = array_uint16_be (data + offset); if (maxdepth < depth) maxdepth = depth; if (metric) sample.depth = depth / 10.0; else sample.depth = depth * FEET / 10.0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); offset += 2; // PPO2 if (type == 3) { if (offset + 1 > size) return DC_STATUS_DATAFORMAT; unsigned int ppo2 = data[offset]; sample.ppo2 = ppo2 / 100.0; if (callback) callback (DC_SAMPLE_PPO2, sample, userdata); offset++; } } else { ERROR (abstract->context, "Invalid sample type %02x.", type); return DC_STATUS_DATAFORMAT; } } // Cache the data for later use. for (unsigned int i = 0; i < ngasmixes; ++i) { parser->he[i] = helium[i]; parser->o2[i] = oxygen[i]; } parser->ngasmixes = ngasmixes; parser->maxdepth = maxdepth; parser->divetime = time; parser->metric = metric; parser->cached = 1; return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/diverite_nitekq_parser.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <assert.h> #include "ringbuffer.h" static unsigned int normalize (unsigned int a, unsigned int size) { return a % size; } static unsigned int distance (unsigned int a, unsigned int b, int mode, unsigned int size) { if (a < b) { return (b - a) % size; } else if (a > b) { return size - (a - b) % size; } else { return (mode == 0 ? 0 : size); } } static unsigned int increment (unsigned int a, unsigned int delta, unsigned int size) { return (a + delta) % size; } static unsigned int decrement (unsigned int a, unsigned int delta, unsigned int size) { if (delta <= a) { return (a - delta) % size; } else { return size - (delta - a) % size; } } unsigned int ringbuffer_normalize (unsigned int a, unsigned int begin, unsigned int end) { assert (end >= begin); assert (a >= begin); return normalize (a, end - begin); } unsigned int ringbuffer_distance (unsigned int a, unsigned int b, int mode, unsigned int begin, unsigned int end) { assert (end >= begin); assert (a >= begin); return distance (a, b, mode, end - begin); } unsigned int ringbuffer_increment (unsigned int a, unsigned int delta, unsigned int begin, unsigned int end) { assert (end >= begin); assert (a >= begin); return increment (a - begin, delta, end - begin) + begin; } unsigned int ringbuffer_decrement (unsigned int a, unsigned int delta, unsigned int begin, unsigned int end) { assert (end >= begin); assert (a >= begin); return decrement (a - begin, delta, end - begin) + begin; }
libdc-for-dirk-Subsurface-branch
src/ringbuffer.c
/* * libdivecomputer * * Copyright (C) 2017 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> // malloc, free #include <libdivecomputer/context.h> #include "iostream-private.h" #include "common-private.h" #include "context-private.h" /* * This is shamelessly stolen from src/custom.c, to make it * work with the subsurface custom_io model. */ typedef struct dc_custom_t { /* Base class. */ dc_iostream_t base; /* Internal state. */ dc_context_t *context; } dc_custom_t; static dc_status_t dc_custom_set_timeout (dc_iostream_t *abstract, int timeout) { dc_custom_t *custom = (dc_custom_t *) abstract; dc_custom_io_t *io = _dc_context_custom_io(custom->context); if (!io->serial_set_timeout) return DC_STATUS_SUCCESS; return io->serial_set_timeout(io, timeout); } static dc_status_t dc_custom_set_latency (dc_iostream_t *abstract, unsigned int value) { return DC_STATUS_SUCCESS; } static dc_status_t dc_custom_set_break (dc_iostream_t *abstract, unsigned int value) { dc_custom_t *custom = (dc_custom_t *) abstract; dc_custom_io_t *io = _dc_context_custom_io(custom->context); if (!io->serial_set_break) return DC_STATUS_SUCCESS; return io->serial_set_break(io, value); } static dc_status_t dc_custom_set_dtr (dc_iostream_t *abstract, unsigned int value) { dc_custom_t *custom = (dc_custom_t *) abstract; dc_custom_io_t *io = _dc_context_custom_io(custom->context); if (!io->serial_set_dtr) return DC_STATUS_SUCCESS; return io->serial_set_dtr(io, value); } static dc_status_t dc_custom_set_rts (dc_iostream_t *abstract, unsigned int value) { dc_custom_t *custom = (dc_custom_t *) abstract; dc_custom_io_t *io = _dc_context_custom_io(custom->context); if (!io->serial_set_rts) return DC_STATUS_SUCCESS; return io->serial_set_rts(io, value); } static dc_status_t dc_custom_get_lines (dc_iostream_t *abstract, unsigned int *value) { return DC_STATUS_SUCCESS; } static dc_status_t dc_custom_get_available (dc_iostream_t *abstract, size_t *value) { dc_custom_t *custom = (dc_custom_t *) abstract; dc_custom_io_t *io = _dc_context_custom_io(custom->context); if (!io->serial_get_available) return DC_STATUS_SUCCESS; return io->serial_get_available(io, value); } static dc_status_t dc_custom_configure (dc_iostream_t *abstract, unsigned int baudrate, unsigned int databits, dc_parity_t parity, dc_stopbits_t stopbits, dc_flowcontrol_t flowcontrol) { dc_custom_t *custom = (dc_custom_t *) abstract; dc_custom_io_t *io = _dc_context_custom_io(custom->context); if (!io->serial_configure) return DC_STATUS_SUCCESS; return io->serial_configure(io, baudrate, databits, parity, stopbits, flowcontrol); } static dc_status_t dc_custom_read (dc_iostream_t *abstract, void *data, size_t size, size_t *actual) { dc_custom_t *custom = (dc_custom_t *) abstract; dc_custom_io_t *io = _dc_context_custom_io(custom->context); if (!io->serial_read) return DC_STATUS_SUCCESS; return io->serial_read(io, data, size, actual); } static dc_status_t dc_custom_write (dc_iostream_t *abstract, const void *data, size_t size, size_t *actual) { dc_custom_t *custom = (dc_custom_t *) abstract; dc_custom_io_t *io = _dc_context_custom_io(custom->context); if (!io->serial_write) return DC_STATUS_SUCCESS; return io->serial_write(io, data, size, actual); } static dc_status_t dc_custom_flush (dc_iostream_t *abstract) { return DC_STATUS_SUCCESS; } static dc_status_t dc_custom_purge (dc_iostream_t *abstract, dc_direction_t direction) { dc_custom_t *custom = (dc_custom_t *) abstract; dc_custom_io_t *io = _dc_context_custom_io(custom->context); if (!io->serial_purge) return DC_STATUS_SUCCESS; return io->serial_purge(io, direction); } static dc_status_t dc_custom_sleep (dc_iostream_t *abstract, unsigned int milliseconds) { return DC_STATUS_SUCCESS; } static dc_status_t dc_custom_close (dc_iostream_t *abstract) { dc_custom_t *custom = (dc_custom_t *) abstract; dc_custom_io_t *io = _dc_context_custom_io(custom->context); if (!io->serial_close) return DC_STATUS_SUCCESS; return io->serial_close(io); } static const dc_iostream_vtable_t dc_custom_vtable = { sizeof(dc_custom_t), dc_custom_set_timeout, /* set_timeout */ dc_custom_set_latency, /* set_latency */ dc_custom_set_break, /* set_break */ dc_custom_set_dtr, /* set_dtr */ dc_custom_set_rts, /* set_rts */ dc_custom_get_lines, /* get_lines */ dc_custom_get_available, /* get_received */ dc_custom_configure, /* configure */ dc_custom_read, /* read */ dc_custom_write, /* write */ dc_custom_flush, /* flush */ dc_custom_purge, /* purge */ dc_custom_sleep, /* sleep */ dc_custom_close, /* close */ }; dc_status_t dc_custom_io_serial_open(dc_iostream_t **out, dc_context_t *context, const char *name) { dc_custom_io_t *io = _dc_context_custom_io(context); dc_custom_t *custom; custom = (dc_custom_t *) dc_iostream_allocate (context, &dc_custom_vtable); if (!custom) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } custom->context = context; *out = (dc_iostream_t *) custom; return io->serial_open(io, context, name); }
libdc-for-dirk-Subsurface-branch
src/custom_io.c
/* * libdivecomputer * * Copyright (C) 2012 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stddef.h> #include <stdlib.h> #include <assert.h> #include "context-private.h" #include "iterator-private.h" dc_iterator_t * dc_iterator_allocate (dc_context_t *context, const dc_iterator_vtable_t *vtable) { dc_iterator_t *iterator = NULL; assert(vtable != NULL); assert(vtable->size >= sizeof(dc_iterator_t)); // Allocate memory. iterator = (dc_iterator_t *) malloc (vtable->size); if (iterator == NULL) { ERROR (context, "Failed to allocate memory."); return iterator; } iterator->vtable = vtable; iterator->context = context; return iterator; } void dc_iterator_deallocate (dc_iterator_t *iterator) { free (iterator); } int dc_iterator_isinstance (dc_iterator_t *iterator, const dc_iterator_vtable_t *vtable) { if (iterator == NULL) return 0; return iterator->vtable == vtable; } dc_status_t dc_iterator_next (dc_iterator_t *iterator, void *item) { if (iterator == NULL || iterator->vtable->next == NULL) return DC_STATUS_UNSUPPORTED; if (item == NULL) return DC_STATUS_INVALIDARGS; return iterator->vtable->next (iterator, item); } dc_status_t dc_iterator_free (dc_iterator_t *iterator) { dc_status_t status = DC_STATUS_SUCCESS; if (iterator == NULL) return DC_STATUS_SUCCESS; if (iterator->vtable->free) { status = iterator->vtable->free (iterator); } dc_iterator_deallocate (iterator); return status; }
libdc-for-dirk-Subsurface-branch
src/iterator.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcmp, memcpy #include <stdlib.h> // malloc, free #include "suunto_eon.h" #include "suunto_common.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "checksum.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &suunto_eon_device_vtable) #define SZ_MEMORY 0x900 typedef struct suunto_eon_device_t { suunto_common_device_t base; dc_iostream_t *iostream; } suunto_eon_device_t; static dc_status_t suunto_eon_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t suunto_eon_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t suunto_eon_device_close (dc_device_t *abstract); static const dc_device_vtable_t suunto_eon_device_vtable = { sizeof(suunto_eon_device_t), DC_FAMILY_SUUNTO_EON, suunto_common_device_set_fingerprint, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ suunto_eon_device_dump, /* dump */ suunto_eon_device_foreach, /* foreach */ NULL, /* timesync */ suunto_eon_device_close /* close */ }; static const suunto_common_layout_t suunto_eon_layout = { 0, /* eop */ 0x100, /* rb_profile_begin */ SZ_MEMORY, /* rb_profile_end */ 6, /* fp_offset */ 3 /* peek */ }; dc_status_t suunto_eon_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; suunto_eon_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (suunto_eon_device_t *) dc_device_allocate (context, &suunto_eon_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Initialize the base class. suunto_common_device_init (&device->base); // Set the default values. device->iostream = NULL; // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (1200 8N2). status = dc_iostream_configure (device->iostream, 1200, 8, DC_PARITY_NONE, DC_STOPBITS_TWO, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (1000ms). status = dc_iostream_set_timeout (device->iostream, 1000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Clear the RTS line. status = dc_iostream_set_rts (device->iostream, 0); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the DTR/RTS line."); goto error_close; } *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t suunto_eon_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; suunto_eon_device_t *device = (suunto_eon_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t suunto_eon_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { dc_status_t status = DC_STATUS_SUCCESS; suunto_eon_device_t *device = (suunto_eon_device_t*) abstract; // Pre-allocate the required amount of memory. if (!dc_buffer_reserve (buffer, SZ_MEMORY)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = SZ_MEMORY + 1; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Send the command. unsigned char command[1] = {'P'}; status = dc_iostream_write (device->iostream, command, sizeof (command), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Receive the answer. unsigned int nbytes = 0; unsigned char answer[SZ_MEMORY + 1] = {0}; while (nbytes < sizeof(answer)) { // Set the minimum packet size. unsigned int len = 64; // Increase the packet size if more data is immediately available. size_t available = 0; status = dc_iostream_get_available (device->iostream, &available); if (status == DC_STATUS_SUCCESS && available > len) len = available; // Limit the packet size to the total size. if (nbytes + len > sizeof(answer)) len = sizeof(answer) - nbytes; // Read the packet. status = dc_iostream_read (device->iostream, answer + nbytes, len, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Update and emit a progress event. progress.current += len; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); nbytes += len; } // Verify the checksum of the package. unsigned char crc = answer[sizeof (answer) - 1]; unsigned char ccrc = checksum_add_uint8 (answer, sizeof (answer) - 1, 0x00); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } dc_buffer_append (buffer, answer, SZ_MEMORY); return DC_STATUS_SUCCESS; } static dc_status_t suunto_eon_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { suunto_common_device_t *device = (suunto_common_device_t *) abstract; dc_buffer_t *buffer = dc_buffer_new (SZ_MEMORY); if (buffer == NULL) return DC_STATUS_NOMEMORY; dc_status_t rc = suunto_eon_device_dump (abstract, buffer); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } // Emit a device info event. unsigned char *data = dc_buffer_get_data (buffer); dc_event_devinfo_t devinfo; devinfo.model = 0; devinfo.firmware = 0; devinfo.serial = 0; for (unsigned int i = 0; i < 3; ++i) { devinfo.serial *= 100; devinfo.serial += bcd2dec (data[244 + i]); } device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); rc = suunto_common_extract_dives (device, &suunto_eon_layout, data, callback, userdata); dc_buffer_free (buffer); return rc; } dc_status_t suunto_eon_device_write_name (dc_device_t *abstract, unsigned char data[], unsigned int size) { dc_status_t status = DC_STATUS_SUCCESS; suunto_eon_device_t *device = (suunto_eon_device_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size > 20) return DC_STATUS_INVALIDARGS; // Send the command. unsigned char command[21] = {'N'}; memcpy (command + 1, data, size); status = dc_iostream_write (device->iostream, command, sizeof (command), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } return DC_STATUS_SUCCESS; } dc_status_t suunto_eon_device_write_interval (dc_device_t *abstract, unsigned char interval) { dc_status_t status = DC_STATUS_SUCCESS; suunto_eon_device_t *device = (suunto_eon_device_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; // Send the command. unsigned char command[2] = {'T', interval}; status = dc_iostream_write (device->iostream, command, sizeof (command), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/suunto_eon.c
/* * libdivecomputer * * Copyright (C) 2017 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include "socket.h" #include "common-private.h" #include "context-private.h" dc_status_t dc_socket_syserror (s_errcode_t errcode) { switch (errcode) { case S_EINVAL: return DC_STATUS_INVALIDARGS; case S_ENOMEM: return DC_STATUS_NOMEMORY; case S_EACCES: return DC_STATUS_NOACCESS; case S_EAFNOSUPPORT: return DC_STATUS_UNSUPPORTED; default: return DC_STATUS_IO; } } dc_status_t dc_socket_init (dc_context_t *context) { #ifdef _WIN32 // Initialize the winsock dll. WSADATA wsaData; WORD wVersionRequested = MAKEWORD (2, 2); int rc = WSAStartup (wVersionRequested, &wsaData); if (rc != 0) { SYSERROR (context, rc); return DC_STATUS_UNSUPPORTED; } // Confirm that the winsock dll supports version 2.2. // Note that if the dll supports versions greater than 2.2 in addition to // 2.2, it will still return 2.2 since that is the version we requested. if (LOBYTE (wsaData.wVersion) != 2 || HIBYTE (wsaData.wVersion) != 2) { ERROR (context, "Incorrect winsock version."); return DC_STATUS_UNSUPPORTED; } #endif return DC_STATUS_SUCCESS; } dc_status_t dc_socket_exit (dc_context_t *context) { #ifdef _WIN32 // Terminate the winsock dll. if (WSACleanup () != 0) { s_errcode_t errcode = S_ERRNO; SYSERROR (context, errcode); return dc_socket_syserror(errcode); } #endif return DC_STATUS_SUCCESS; } dc_status_t dc_socket_open (dc_iostream_t *abstract, int family, int type, int protocol) { dc_status_t status = DC_STATUS_SUCCESS; dc_socket_t *device = (dc_socket_t *) abstract; // Default to blocking reads. device->timeout = -1; // Initialize the socket library. status = dc_socket_init (abstract->context); if (status != DC_STATUS_SUCCESS) { return status; } // Open the socket. device->fd = socket (family, type, protocol); if (device->fd == S_INVALID) { s_errcode_t errcode = S_ERRNO; SYSERROR (abstract->context, errcode); status = dc_socket_syserror(errcode); goto error; } return DC_STATUS_SUCCESS; error: dc_socket_exit (abstract->context); return status; } dc_status_t dc_socket_close (dc_iostream_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; dc_socket_t *socket = (dc_socket_t *) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Terminate all send and receive operations. shutdown (socket->fd, 0); // Close the socket. if (S_CLOSE (socket->fd) != 0) { s_errcode_t errcode = S_ERRNO; SYSERROR (abstract->context, errcode); dc_status_set_error(&status, dc_socket_syserror(errcode)); } // Terminate the socket library. rc = dc_socket_exit (abstract->context); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } dc_status_t dc_socket_connect (dc_iostream_t *abstract, const struct sockaddr *addr, s_socklen_t addrlen) { dc_socket_t *socket = (dc_socket_t *) abstract; if (connect (socket->fd, addr, addrlen) != 0) { s_errcode_t errcode = S_ERRNO; SYSERROR (abstract->context, errcode); return dc_socket_syserror(errcode); } return DC_STATUS_SUCCESS; } dc_status_t dc_socket_set_timeout (dc_iostream_t *abstract, int timeout) { dc_socket_t *socket = (dc_socket_t *) abstract; socket->timeout = timeout; return DC_STATUS_SUCCESS; } dc_status_t dc_socket_set_latency (dc_iostream_t *iostream, unsigned int value) { return DC_STATUS_SUCCESS; } dc_status_t dc_socket_set_break (dc_iostream_t *iostream, unsigned int value) { return DC_STATUS_SUCCESS; } dc_status_t dc_socket_set_dtr (dc_iostream_t *iostream, unsigned int value) { return DC_STATUS_SUCCESS; } dc_status_t dc_socket_set_rts (dc_iostream_t *iostream, unsigned int value) { return DC_STATUS_SUCCESS; } dc_status_t dc_socket_get_lines (dc_iostream_t *iostream, unsigned int *value) { if (value) *value = 0; return DC_STATUS_SUCCESS; } dc_status_t dc_socket_get_available (dc_iostream_t *abstract, size_t *value) { dc_socket_t *socket = (dc_socket_t *) abstract; #ifdef _WIN32 unsigned long bytes = 0; #else int bytes = 0; #endif if (S_IOCTL (socket->fd, FIONREAD, &bytes) != 0) { s_errcode_t errcode = S_ERRNO; SYSERROR (abstract->context, errcode); return dc_socket_syserror(errcode); } if (value) *value = bytes; return DC_STATUS_SUCCESS; } dc_status_t dc_socket_configure (dc_iostream_t *abstract, unsigned int baudrate, unsigned int databits, dc_parity_t parity, dc_stopbits_t stopbits, dc_flowcontrol_t flowcontrol) { return DC_STATUS_SUCCESS; } dc_status_t dc_socket_read (dc_iostream_t *abstract, void *data, size_t size, size_t *actual) { dc_status_t status = DC_STATUS_SUCCESS; dc_socket_t *socket = (dc_socket_t *) abstract; size_t nbytes = 0; while (nbytes < size) { fd_set fds; FD_ZERO (&fds); FD_SET (socket->fd, &fds); struct timeval tvt; if (socket->timeout > 0) { tvt.tv_sec = (socket->timeout / 1000); tvt.tv_usec = (socket->timeout % 1000) * 1000; } else if (socket->timeout == 0) { timerclear (&tvt); } int rc = select (socket->fd + 1, &fds, NULL, NULL, socket->timeout >= 0 ? &tvt : NULL); if (rc < 0) { s_errcode_t errcode = S_ERRNO; if (errcode == S_EINTR) continue; // Retry. SYSERROR (abstract->context, errcode); status = dc_socket_syserror(errcode); goto out; } else if (rc == 0) { break; // Timeout. } s_ssize_t n = recv (socket->fd, (char *) data + nbytes, size - nbytes, 0); if (n < 0) { s_errcode_t errcode = S_ERRNO; if (errcode == S_EINTR || errcode == S_EAGAIN) continue; // Retry. SYSERROR (abstract->context, errcode); status = dc_socket_syserror(errcode); goto out; } else if (n == 0) { break; // EOF reached. } nbytes += n; } if (nbytes != size) { status = DC_STATUS_TIMEOUT; } out: if (actual) *actual = nbytes; return status; } dc_status_t dc_socket_write (dc_iostream_t *abstract, const void *data, size_t size, size_t *actual) { dc_status_t status = DC_STATUS_SUCCESS; dc_socket_t *socket = (dc_socket_t *) abstract; size_t nbytes = 0; while (nbytes < size) { fd_set fds; FD_ZERO (&fds); FD_SET (socket->fd, &fds); int rc = select (socket->fd + 1, NULL, &fds, NULL, NULL); if (rc < 0) { s_errcode_t errcode = S_ERRNO; if (errcode == S_EINTR) continue; // Retry. SYSERROR (abstract->context, errcode); status = dc_socket_syserror(errcode); goto out; } else if (rc == 0) { break; // Timeout. } s_ssize_t n = send (socket->fd, (const char *) data + nbytes, size - nbytes, 0); if (n < 0) { s_errcode_t errcode = S_ERRNO; if (errcode == S_EINTR || errcode == S_EAGAIN) continue; // Retry. SYSERROR (abstract->context, errcode); status = dc_socket_syserror(errcode); goto out; } else if (n == 0) { break; // EOF. } nbytes += n; } if (nbytes != size) { status = DC_STATUS_TIMEOUT; } out: if (actual) *actual = nbytes; return status; } dc_status_t dc_socket_flush (dc_iostream_t *abstract) { return DC_STATUS_SUCCESS; } dc_status_t dc_socket_purge (dc_iostream_t *abstract, dc_direction_t direction) { return DC_STATUS_SUCCESS; } dc_status_t dc_socket_sleep (dc_iostream_t *abstract, unsigned int timeout) { return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/socket.c
/* * libdivecomputer * * Copyright (C) 2010 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <stdio.h> #include <string.h> #ifdef _MSC_VER #define snprintf _snprintf #endif #include "libdivecomputer/units.h" #include "hw_ostc.h" #include "hw_ostc3.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_parser_isinstance((parser), &hw_ostc_parser_vtable) #define MAXCONFIG 7 #define NGASMIXES 15 #define UNDEFINED 0xFFFFFFFF #define ALL 0 #define FIXED 1 #define MANUAL 2 #define HEADER 1 #define PROFILE 2 #define OSTC_ZHL16_OC 0 #define OSTC_GAUGE 1 #define OSTC_ZHL16_CC 2 #define OSTC_APNEA 3 #define OSTC_ZHL16_OC_GF 4 #define OSTC_ZHL16_CC_GF 5 #define OSTC_PSCR_GF 6 #define FROG_ZHL16 0 #define FROG_ZHL16_GF 1 #define FROG_APNEA 2 #define OSTC3_OC 0 #define OSTC3_CC 1 #define OSTC3_GAUGE 2 #define OSTC3_APNEA 3 #define OSTC3_PSCR 4 #define OSTC3_ZHL16 0 #define OSTC3_ZHL16_GF 1 #define OSTC4_VPM 2 #define OSTC4 0x3B #define UNSUPPORTED 0xFFFFFFFF typedef struct hw_ostc_sample_info_t { unsigned int type; unsigned int divisor; unsigned int size; } hw_ostc_sample_info_t; typedef struct hw_ostc_layout_t { unsigned int datetime; unsigned int maxdepth; unsigned int avgdepth; unsigned int divetime; unsigned int atmospheric; unsigned int salinity; unsigned int duration; unsigned int temperature; unsigned int battery; unsigned int desat; unsigned int firmware; unsigned int deco_info1; unsigned int deco_info2; unsigned int decomode; unsigned int battery_percentage; } hw_ostc_layout_t; typedef struct hw_ostc_gasmix_t { unsigned int oxygen; unsigned int helium; } hw_ostc_gasmix_t; typedef struct hw_ostc_parser_t { dc_parser_t base; unsigned int hwos; unsigned int model; unsigned int serial; // Cached fields. unsigned int cached; unsigned int version; unsigned int header; const hw_ostc_layout_t *layout; unsigned int ngasmixes; unsigned int nfixed; unsigned int initial; unsigned int initial_setpoint; unsigned int initial_cns; hw_ostc_gasmix_t gasmix[NGASMIXES]; } hw_ostc_parser_t; static dc_status_t hw_ostc_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t hw_ostc_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t hw_ostc_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t hw_ostc_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t hw_ostc_parser_vtable = { sizeof(hw_ostc_parser_t), DC_FAMILY_HW_OSTC, hw_ostc_parser_set_data, /* set_data */ hw_ostc_parser_get_datetime, /* datetime */ hw_ostc_parser_get_field, /* fields */ hw_ostc_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; static const hw_ostc_layout_t hw_ostc_layout_ostc = { 3, /* datetime */ 8, /* maxdepth */ 45, /* avgdepth */ 10, /* divetime */ 15, /* atmospheric */ 43, /* salinity */ 47, /* duration */ 13, /* temperature */ 34, /* battery volt after dive */ 17, /* desat */ 32, /* firmware */ 49, /* deco_info1 */ 50, /* deco_info1 */ 51, /* decomode */ 0, /* battery percentage TBD */ }; static const hw_ostc_layout_t hw_ostc_layout_frog = { 9, /* datetime */ 14, /* maxdepth */ 45, /* avgdepth */ 16, /* divetime */ 21, /* atmospheric */ 43, /* salinity */ 47, /* duration */ 19, /* temperature */ 34, /* battery volt after dive */ 23, /* desat */ 32, /* firmware */ 49, /* deco_info1 */ 50, /* deco_info2 */ 51, /* decomode */ 0, /* battery percentage TBD */ }; static const hw_ostc_layout_t hw_ostc_layout_ostc3 = { 12, /* datetime */ 17, /* maxdepth */ 73, /* avgdepth */ 19, /* divetime */ 24, /* atmospheric */ 70, /* salinity */ 75, /* duration */ 22, /* temperature */ 50, /* battery volt after dive */ 26, /* desat */ 48, /* firmware */ 77, /* deco_info1 */ 78, /* deco_info2 */ 79, /* decomode */ 59, /* battery percentage */ }; static unsigned int hw_ostc_find_gasmix (hw_ostc_parser_t *parser, unsigned int o2, unsigned int he, unsigned int type) { unsigned int offset = 0; unsigned int count = parser->ngasmixes; if (type == FIXED) { count = parser->nfixed; } else if (type == MANUAL) { offset = parser->nfixed; } unsigned int i = offset; while (i < count) { if (o2 == parser->gasmix[i].oxygen && he == parser->gasmix[i].helium) break; i++; } return i; } static dc_status_t hw_ostc_parser_cache (hw_ostc_parser_t *parser) { dc_parser_t *abstract = (dc_parser_t *) parser; const unsigned char *data = abstract->data; unsigned int size = abstract->size; if (parser->cached) { return DC_STATUS_SUCCESS; } if (size < 9) { ERROR(abstract->context, "Header too small."); return DC_STATUS_DATAFORMAT; } // Check the profile version unsigned int version = data[parser->hwos ? 8 : 2]; const hw_ostc_layout_t *layout = NULL; unsigned int header = 0; switch (version) { case 0x20: layout = &hw_ostc_layout_ostc; header = 47; break; case 0x21: layout = &hw_ostc_layout_ostc; header = 57; break; case 0x22: layout = &hw_ostc_layout_frog; header = 256; break; case 0x23: case 0x24: layout = &hw_ostc_layout_ostc3; header = 256; break; default: ERROR(abstract->context, "Unknown data format version."); return DC_STATUS_DATAFORMAT; } if (size < header) { ERROR(abstract->context, "Header too small."); return DC_STATUS_DATAFORMAT; } // Get all the gas mixes, the index of the inital mix, // the initial setpoint (used in the fixed setpoint CCR mode), // and the initial CNS from the header unsigned int initial = UNDEFINED; unsigned int initial_setpoint = UNDEFINED; unsigned int initial_cns = UNDEFINED; unsigned int ngasmixes = 0; hw_ostc_gasmix_t gasmix[NGASMIXES] = {{0}}; if (version == 0x22) { ngasmixes = 3; if (data[31] != 0xFF) { initial = data[31]; } for (unsigned int i = 0; i < ngasmixes; ++i) { gasmix[i].oxygen = data[25 + 2 * i]; gasmix[i].helium = 0; } } else if (version == 0x23 || version == 0x24) { ngasmixes = 5; for (unsigned int i = 0; i < ngasmixes; ++i) { gasmix[i].oxygen = data[28 + 4 * i + 0]; gasmix[i].helium = data[28 + 4 * i + 1]; // Find the first gas marked as the initial gas. if (initial == UNDEFINED && data[28 + 4 * i + 3] == 1) { initial = i + 1; /* One based index! */ } } // The first fixed setpoint is the initial setpoint in CCR mode. if (data[82] == OSTC3_CC) { initial_setpoint = data[60]; } // Initial CNS initial_cns = array_uint16_le (data + 53); } else { ngasmixes = 5; if (data[31] != 0xFF) { initial = data[31]; } for (unsigned int i = 0; i < ngasmixes; ++i) { gasmix[i].oxygen = data[19 + 2 * i + 0]; gasmix[i].helium = data[19 + 2 * i + 1]; } } if (initial != UNDEFINED) { if (initial < 1 || initial > ngasmixes) { ERROR(abstract->context, "Invalid initial gas mix."); return DC_STATUS_DATAFORMAT; } initial--; /* Convert to a zero based index. */ } else { WARNING(abstract->context, "No initial gas mix available."); } // Cache the data for later use. parser->version = version; parser->header = header; parser->layout = layout; parser->ngasmixes = ngasmixes; parser->nfixed = ngasmixes; parser->initial = initial; parser->initial_setpoint = initial_setpoint; parser->initial_cns = initial_cns; for (unsigned int i = 0; i < ngasmixes; ++i) { parser->gasmix[i] = gasmix[i]; } parser->cached = HEADER; return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc_parser_create_internal (dc_parser_t **out, dc_context_t *context, unsigned int serial, unsigned int hwos, unsigned int model) { hw_ostc_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (hw_ostc_parser_t *) dc_parser_allocate (context, &hw_ostc_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. parser->hwos = hwos; parser->model = model; parser->cached = 0; parser->version = 0; parser->header = 0; parser->layout = NULL; parser->ngasmixes = 0; parser->nfixed = 0; parser->initial = 0; parser->initial_setpoint = 0; parser->initial_cns = 0; for (unsigned int i = 0; i < NGASMIXES; ++i) { parser->gasmix[i].oxygen = 0; parser->gasmix[i].helium = 0; } parser->serial = serial; *out = (dc_parser_t *) parser; return DC_STATUS_SUCCESS; } dc_status_t hw_ostc_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int serial, unsigned int hwos) { return hw_ostc_parser_create_internal (out, context, serial, hwos, 0); } dc_status_t hw_ostc3_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int serial, unsigned int model) { return hw_ostc_parser_create_internal (out, context, serial, 1, model); } static dc_status_t hw_ostc_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { hw_ostc_parser_t *parser = (hw_ostc_parser_t *) abstract; // Reset the cache. parser->cached = 0; parser->version = 0; parser->header = 0; parser->layout = NULL; parser->ngasmixes = 0; parser->nfixed = 0; parser->initial = 0; parser->initial_setpoint = 0; parser->initial_cns = 0; for (unsigned int i = 0; i < NGASMIXES; ++i) { parser->gasmix[i].oxygen = 0; parser->gasmix[i].helium = 0; } return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { hw_ostc_parser_t *parser = (hw_ostc_parser_t *) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; // Cache the header data. dc_status_t rc = hw_ostc_parser_cache (parser); if (rc != DC_STATUS_SUCCESS) return rc; unsigned int version = parser->version; const hw_ostc_layout_t *layout = parser->layout; unsigned int divetime = 0; if (version > 0x20) { // Use the dive time stored in the extended header, rounded down towards // the nearest minute, to match the value displayed by the ostc. divetime = (array_uint16_le (data + layout->duration) / 60) * 60; } else { // Use the normal dive time (excluding the shallow parts of the dive). divetime = array_uint16_le (data + layout->divetime) * 60 + data[layout->divetime + 2]; } const unsigned char *p = data + layout->datetime; dc_datetime_t dt; if (version == 0x23 || version == 0x24) { dt.year = p[0] + 2000; dt.month = p[1]; dt.day = p[2]; } else { dt.year = p[2] + 2000; dt.month = p[0]; dt.day = p[1]; } dt.hour = p[3]; dt.minute = p[4]; dt.second = 0; dt.timezone = DC_TIMEZONE_NONE; if (version == 0x24) { if (datetime) *datetime = dt; } else { dc_ticks_t ticks = dc_datetime_mktime (&dt); if (ticks == (dc_ticks_t) -1) return DC_STATUS_DATAFORMAT; ticks -= divetime; if (!dc_datetime_gmtime (datetime, ticks)) return DC_STATUS_DATAFORMAT; datetime->timezone = DC_TIMEZONE_NONE; } return DC_STATUS_SUCCESS; } #define BUFLEN 32 static dc_status_t hw_ostc_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { hw_ostc_parser_t *parser = (hw_ostc_parser_t *) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; // Cache the header data. dc_status_t rc = hw_ostc_parser_cache (parser); if (rc != DC_STATUS_SUCCESS) return rc; // Cache the profile data. if (parser->cached < PROFILE) { rc = hw_ostc_parser_samples_foreach (abstract, NULL, NULL); if (rc != DC_STATUS_SUCCESS) return rc; } unsigned int version = parser->version; const hw_ostc_layout_t *layout = parser->layout; dc_gasmix_t *gasmix = (dc_gasmix_t *) value; dc_salinity_t *water = (dc_salinity_t *) value; dc_field_string_t *string = (dc_field_string_t *) value; unsigned int salinity = data[layout->salinity]; if (version == 0x23 || version == 0x24) salinity += 100; char buf[BUFLEN]; if (value) { switch (type) { case DC_FIELD_DIVETIME: *((unsigned int *) value) = array_uint16_le (data + layout->divetime) * 60 + data[layout->divetime + 2]; break; case DC_FIELD_MAXDEPTH: *((double *) value) = array_uint16_le (data + layout->maxdepth) / 100.0; break; case DC_FIELD_AVGDEPTH: *((double *) value) = array_uint16_le (data + layout->avgdepth) / 100.0; break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = parser->ngasmixes; break; case DC_FIELD_GASMIX: gasmix->oxygen = parser->gasmix[flags].oxygen / 100.0; gasmix->helium = parser->gasmix[flags].helium / 100.0; gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium; break; case DC_FIELD_SALINITY: if (salinity < 100 || salinity > 104) return DC_STATUS_UNSUPPORTED; if (salinity == 100) water->type = DC_WATER_FRESH; else water->type = DC_WATER_SALT; water->density = salinity * 10.0; break; case DC_FIELD_ATMOSPHERIC: *((double *) value) = array_uint16_le (data + layout->atmospheric) / 1000.0; break; case DC_FIELD_TEMPERATURE_MINIMUM: *((double *) value) = (signed short) array_uint16_le (data + layout->temperature) / 10.0; break; case DC_FIELD_DIVEMODE: if (version == 0x21) { switch (data[51]) { case OSTC_APNEA: *((dc_divemode_t *) value) = DC_DIVEMODE_FREEDIVE; break; case OSTC_GAUGE: *((dc_divemode_t *) value) = DC_DIVEMODE_GAUGE; break; case OSTC_ZHL16_OC: case OSTC_ZHL16_OC_GF: *((dc_divemode_t *) value) = DC_DIVEMODE_OC; break; case OSTC_ZHL16_CC: case OSTC_ZHL16_CC_GF: *((dc_divemode_t *) value) = DC_DIVEMODE_CCR; break; case OSTC_PSCR_GF: *((dc_divemode_t *) value) = DC_DIVEMODE_SCR; break; default: return DC_STATUS_DATAFORMAT; } } else if (version == 0x22) { switch (data[51]) { case FROG_ZHL16: case FROG_ZHL16_GF: *((dc_divemode_t *) value) = DC_DIVEMODE_OC; break; case FROG_APNEA: *((dc_divemode_t *) value) = DC_DIVEMODE_FREEDIVE; break; default: return DC_STATUS_DATAFORMAT; } } else if (version == 0x23 || version == 0x24) { switch (data[82]) { case OSTC3_OC: *((dc_divemode_t *) value) = DC_DIVEMODE_OC; break; case OSTC3_CC: *((dc_divemode_t *) value) = DC_DIVEMODE_CCR; break; case OSTC3_GAUGE: *((dc_divemode_t *) value) = DC_DIVEMODE_GAUGE; break; case OSTC3_APNEA: *((dc_divemode_t *) value) = DC_DIVEMODE_FREEDIVE; break; case OSTC3_PSCR: *((dc_divemode_t *) value) = DC_DIVEMODE_SCR; break; default: return DC_STATUS_DATAFORMAT; } } else { return DC_STATUS_UNSUPPORTED; } break; case DC_FIELD_STRING: switch(flags) { case 0: /* serial */ string->desc = "Serial"; snprintf(buf, BUFLEN, "%u", parser->serial); break; case 1: /* battery */ string->desc = "Battery at end"; unsigned int percentage = (unsigned int) data[layout->battery_percentage]; if (percentage != 0xFF && (version == 0x23 || version == 0x24)) { percentage = percentage>100? 100: percentage; snprintf(buf, BUFLEN, "%.2fV, %u%% remaining", array_uint16_le (data + layout->battery) / 1000.0, percentage); } else { snprintf(buf, BUFLEN, "%.2fV", array_uint16_le (data + layout->battery) / 1000.0); } break; case 2: /* desat */ string->desc = "Desat time"; snprintf(buf, BUFLEN, "%0u:%02u", array_uint16_le (data + layout->desat) / 60, array_uint16_le (data + layout->desat) % 60); break; case 3: /* firmware */ string->desc = "FW Version"; /* OSTC4 stores firmware as XXXX XYYY YYZZ ZZZB, -> X.Y.Z beta? */ if (parser->model == OSTC4) { int firmwareOnDevice = array_uint16_le (data + layout->firmware); unsigned char X = 0, Y = 0, Z = 0, beta = 0; X = (firmwareOnDevice & 0xF800) >> 11; Y = (firmwareOnDevice & 0x07C0) >> 6; Z = (firmwareOnDevice & 0x003E) >> 1; beta = firmwareOnDevice & 0x0001; snprintf(buf, BUFLEN, "%u.%u.%u%s\n", X, Y, Z, beta? "beta": ""); } else { snprintf(buf, BUFLEN, "%0u.%02u", data[layout->firmware], data[layout->firmware + 1]); } break; case 4: /* Deco model */ string->desc = "Deco model"; if (((version == 0x23 || version == 0x24) && data[layout->decomode] == OSTC3_ZHL16) || (version == 0x22 && data[layout->decomode] == FROG_ZHL16) || (version == 0x21 && (data[layout->decomode] == OSTC_ZHL16_OC || data[layout->decomode] == OSTC_ZHL16_CC))) strncpy(buf, "ZH-L16", BUFLEN); else if (((version == 0x23 || version == 0x24) && data[layout->decomode] == OSTC3_ZHL16_GF) || (version == 0x22 && data[layout->decomode] == FROG_ZHL16_GF) || (version == 0x21 && (data[layout->decomode] == OSTC_ZHL16_OC_GF || data[layout->decomode] == OSTC_ZHL16_CC_GF))) strncpy(buf, "ZH-L16-GF", BUFLEN); else if (((version == 0x24) && data[layout->decomode] == OSTC4_VPM)) strncpy(buf, "VPM", BUFLEN); else return DC_STATUS_DATAFORMAT; break; case 5: /* Deco model info */ string->desc = "Deco model info"; if (((version == 0x23 || version == 0x24) && data[layout->decomode] == OSTC3_ZHL16) || (version == 0x22 && data[layout->decomode] == FROG_ZHL16) || (version == 0x21 && (data[layout->decomode] == OSTC_ZHL16_OC || data[layout->decomode] == OSTC_ZHL16_CC))) snprintf(buf, BUFLEN, "Saturation %u, Desaturation %u", layout->deco_info1, layout->deco_info2); else if (((version == 0x23 || version == 0x24) && data[layout->decomode] == OSTC3_ZHL16_GF) || (version == 0x22 && data[layout->decomode] == FROG_ZHL16_GF) || (version == 0x21 && (data[layout->decomode] == OSTC_ZHL16_OC_GF || data[layout->decomode] == OSTC_ZHL16_CC_GF))) snprintf(buf, BUFLEN, "GF %u/%u", data[layout->deco_info1], data[layout->deco_info2]); else return DC_STATUS_DATAFORMAT; break; default: return DC_STATUS_UNSUPPORTED; } string->value = strdup(buf); break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { hw_ostc_parser_t *parser = (hw_ostc_parser_t *) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; // Cache the parser data. dc_status_t rc = hw_ostc_parser_cache (parser); if (rc != DC_STATUS_SUCCESS) return rc; unsigned int version = parser->version; unsigned int header = parser->header; const hw_ostc_layout_t *layout = parser->layout; // Exit if no profile data available. if (size == header || (size == header + 2 && data[header] == 0xFD && data[header + 1] == 0xFD)) { parser->cached = PROFILE; return DC_STATUS_SUCCESS; } // Check the header length. if (version == 0x23 || version == 0x24) { if (size < header + 5) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } } // Get the sample rate. unsigned int samplerate = 0; if (version == 0x23 || version == 0x24) samplerate = data[header + 3]; else samplerate = data[36]; // Get the salinity factor. unsigned int salinity = data[layout->salinity]; if (version == 0x23 || version == 0x24) salinity += 100; if (salinity < 100 || salinity > 104) salinity = 100; double hydrostatic = GRAVITY * salinity * 10.0; // Get the number of sample descriptors. unsigned int nconfig = 0; if (version == 0x23 || version == 0x24) nconfig = data[header + 4]; else nconfig = 6; if (nconfig > MAXCONFIG) { ERROR(abstract->context, "Too many sample descriptors."); return DC_STATUS_DATAFORMAT; } // Check the header length. if (version == 0x23 || version == 0x24) { if (size < header + 5 + 3 * nconfig) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } } // Get the extended sample configuration. hw_ostc_sample_info_t info[MAXCONFIG] = {{0}}; for (unsigned int i = 0; i < nconfig; ++i) { if (version == 0x23 || version == 0x24) { info[i].type = data[header + 5 + 3 * i + 0]; info[i].size = data[header + 5 + 3 * i + 1]; info[i].divisor = data[header + 5 + 3 * i + 2]; } else { info[i].type = i; info[i].divisor = (data[37 + i] & 0x0F); info[i].size = (data[37 + i] & 0xF0) >> 4; } if (info[i].divisor) { switch (info[i].type) { case 0: // Temperature case 1: // Deco / NDL case 6: // Tank pressure if (info[i].size != 2) { ERROR(abstract->context, "Unexpected sample size."); return DC_STATUS_DATAFORMAT; } break; case 3: // ppO2 if (info[i].size != 3 && info[i].size != 9) { ERROR(abstract->context, "Unexpected sample size."); return DC_STATUS_DATAFORMAT; } break; case 5: // CNS if (info[i].size != 1 && info[i].size != 2) { ERROR(abstract->context, "Unexpected sample size."); return DC_STATUS_DATAFORMAT; } break; default: // Not yet used. break; } } } // Get the firmware version. unsigned int firmware = 0; if (parser->model == OSTC4) { firmware = array_uint16_le (data + layout->firmware); } else { firmware = array_uint16_be (data + layout->firmware); } unsigned int time = 0; unsigned int nsamples = 0; unsigned int tank = parser->initial != UNDEFINED ? parser->initial : 0; unsigned int offset = header; if (version == 0x23 || version == 0x24) offset += 5 + 3 * nconfig; while (offset + 3 <= size) { dc_sample_value_t sample = {0}; nsamples++; // Time (seconds). time += samplerate; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Initial gas mix. if (time == samplerate && parser->initial != UNDEFINED) { sample.gasmix = parser->initial; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); } // Initial setpoint (mbar). if (time == samplerate && parser->initial_setpoint != UNDEFINED) { sample.setpoint = parser->initial_setpoint / 100.0; if (callback) callback (DC_SAMPLE_SETPOINT, sample, userdata); } // Initial CNS (%). if (time == samplerate && parser->initial_cns != UNDEFINED) { sample.cns = parser->initial_cns / 100.0; if (callback) callback (DC_SAMPLE_CNS, sample, userdata); } // Depth (mbar). unsigned int depth = array_uint16_le (data + offset); sample.depth = (depth * BAR / 1000.0) / hydrostatic; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); offset += 2; // Extended sample info. unsigned int length = data[offset] & 0x7F; offset += 1; // Check for buffer overflows. if (offset + length > size) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } // Get the event byte(s). unsigned int nbits = 0; unsigned int events = 0; while (data[offset - 1] & 0x80) { if (nbits && version != 0x23 && version != 0x24) break; if (length < 1) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } events |= data[offset] << nbits; nbits += 8; offset++; length--; } // Alarms sample.event.type = 0; sample.event.time = 0; sample.event.flags = 0; sample.event.value = 0; switch (events & 0x0F) { case 0: // No Alarm break; case 1: // Slow sample.event.type = SAMPLE_EVENT_ASCENT; break; case 2: // Deco Stop missed sample.event.type = SAMPLE_EVENT_CEILING; break; case 3: // Deep Stop missed sample.event.type = SAMPLE_EVENT_CEILING; break; case 4: // ppO2 Low Warning sample.event.type = SAMPLE_EVENT_PO2; break; case 5: // ppO2 High Warning sample.event.type = SAMPLE_EVENT_PO2; break; case 6: // Manual Marker sample.event.type = SAMPLE_EVENT_BOOKMARK; break; case 7: // Low Battery break; } if (sample.event.type && callback) callback (DC_SAMPLE_EVENT, sample, userdata); // Manual Gas Set & Change if (events & 0x10) { if (length < 2) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } unsigned int o2 = data[offset]; unsigned int he = data[offset + 1]; unsigned int idx = hw_ostc_find_gasmix (parser, o2, he, MANUAL); if (idx >= parser->ngasmixes) { if (idx >= NGASMIXES) { ERROR (abstract->context, "Maximum number of gas mixes reached."); return DC_STATUS_NOMEMORY; } parser->gasmix[idx].oxygen = o2; parser->gasmix[idx].helium = he; parser->ngasmixes = idx + 1; } sample.gasmix = idx; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); offset += 2; length -= 2; } // Gas Change if (events & 0x20) { if (length < 1) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } unsigned int idx = data[offset]; if (idx < 1 || idx > parser->ngasmixes) { ERROR(abstract->context, "Invalid gas mix."); return DC_STATUS_DATAFORMAT; } idx--; /* Convert to a zero based index. */ sample.gasmix = idx; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); tank = idx; offset++; length--; } if (version == 0x23 || version == 0x24) { // SetPoint Change if (events & 0x40) { if (length < 1) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } sample.setpoint = data[offset] / 100.0; if (callback) callback (DC_SAMPLE_SETPOINT, sample, userdata); offset++; length--; } // Bailout Event if (events & 0x0100) { if (length < 2) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } unsigned int o2 = data[offset]; unsigned int he = data[offset + 1]; unsigned int idx = hw_ostc_find_gasmix (parser, o2, he, MANUAL); if (idx >= parser->ngasmixes) { if (idx >= NGASMIXES) { ERROR (abstract->context, "Maximum number of gas mixes reached."); return DC_STATUS_NOMEMORY; } parser->gasmix[idx].oxygen = o2; parser->gasmix[idx].helium = he; parser->ngasmixes = idx + 1; } sample.gasmix = idx; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); offset += 2; length -= 2; } } // Extended sample info. for (unsigned int i = 0; i < nconfig; ++i) { if (info[i].divisor && (nsamples % info[i].divisor) == 0) { if (length < info[i].size) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } unsigned int ppo2[3] = {0}; unsigned int count = 0; unsigned int value = 0; switch (info[i].type) { case 0: // Temperature (0.1 °C). value = array_uint16_le (data + offset); sample.temperature = value / 10.0; if (callback) callback (DC_SAMPLE_TEMPERATURE, sample, userdata); break; case 1: // Deco / NDL // Due to a firmware bug, the deco/ndl info is incorrect for // all OSTC4 dives with a firmware older than version 1.0.8. if (parser->model == OSTC4 && firmware < 0x0810) break; if (data[offset]) { sample.deco.type = DC_DECO_DECOSTOP; sample.deco.depth = data[offset]; } else { sample.deco.type = DC_DECO_NDL; sample.deco.depth = 0.0; } sample.deco.time = data[offset + 1] * 60; if (callback) callback (DC_SAMPLE_DECO, sample, userdata); break; case 3: // ppO2 (0.01 bar). for (unsigned int j = 0; j < 3; ++j) { if (info[i].size == 3) { ppo2[j] = data[offset + j]; } else { ppo2[j] = data[offset + j * 3]; } if (ppo2[j] != 0) count++; } if (count) { for (unsigned int j = 0; j < 3; ++j) { sample.ppo2 = ppo2[j] / 100.0; if (callback) callback (DC_SAMPLE_PPO2, sample, userdata); } } break; case 5: // CNS if (info[i].size == 2) sample.cns = array_uint16_le (data + offset) / 100.0; else sample.cns = data[offset] / 100.0; if (callback) callback (DC_SAMPLE_CNS, sample, userdata); break; case 6: // Tank pressure value = array_uint16_le (data + offset); sample.pressure.tank = tank; sample.pressure.value = value / 10.0; if (callback) callback (DC_SAMPLE_PRESSURE, sample, userdata); break; default: // Not yet used. break; } offset += info[i].size; length -= info[i].size; } } if (version != 0x23 && version != 0x24) { // SetPoint Change if (events & 0x40) { if (length < 1) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } sample.setpoint = data[offset] / 100.0; if (callback) callback (DC_SAMPLE_SETPOINT, sample, userdata); offset++; length--; } // Bailout Event if (events & 0x80) { if (length < 2) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } unsigned int o2 = data[offset]; unsigned int he = data[offset + 1]; unsigned int idx = hw_ostc_find_gasmix (parser, o2, he, MANUAL); if (idx >= parser->ngasmixes) { if (idx >= NGASMIXES) { ERROR (abstract->context, "Maximum number of gas mixes reached."); return DC_STATUS_NOMEMORY; } parser->gasmix[idx].oxygen = o2; parser->gasmix[idx].helium = he; parser->ngasmixes = idx + 1; } sample.gasmix = idx; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); offset += 2; length -= 2; } } // Skip remaining sample bytes (if any). if (length) { WARNING (abstract->context, "Remaining %u bytes skipped.", length); } offset += length; } if (offset + 2 > size || data[offset] != 0xFD || data[offset + 1] != 0xFD) { ERROR (abstract->context, "Invalid end marker found!"); return DC_STATUS_DATAFORMAT; } parser->cached = PROFILE; return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/hw_ostc_parser.c
/* * libdivecomputer * * Copyright (C) 2013 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stddef.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include "ihex.h" #include "context-private.h" #include "checksum.h" #include "array.h" struct dc_ihex_file_t { dc_context_t *context; FILE *fp; }; dc_status_t dc_ihex_file_open (dc_ihex_file_t **result, dc_context_t *context, const char *filename) { dc_ihex_file_t *file = NULL; if (result == NULL || filename == NULL) { ERROR (context, "Invalid arguments."); return DC_STATUS_INVALIDARGS; } file = (dc_ihex_file_t *) malloc (sizeof (dc_ihex_file_t)); if (file == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } file->context = context; file->fp = fopen (filename, "rb"); if (file->fp == NULL) { ERROR (context, "Failed to open the file."); free (file); return DC_STATUS_IO; } *result = file; return DC_STATUS_SUCCESS; } dc_status_t dc_ihex_file_read (dc_ihex_file_t *file, dc_ihex_entry_t *entry) { unsigned char ascii[9 + 2 * 255 + 2] = {0}; unsigned char data[4 + 255 + 1] = {0}; unsigned int type, length, address; unsigned char csum_a, csum_b; size_t n; if (file == NULL || entry == NULL) { ERROR (file ? file->context : NULL, "Invalid arguments."); return DC_STATUS_INVALIDARGS; } /* Read the start code. */ while (1) { n = fread (ascii, 1, 1, file->fp); if (n != 1) { if (feof (file->fp)) { return DC_STATUS_DONE; } else { ERROR (file->context, "Failed to read the start code."); return DC_STATUS_IO; } } if (ascii[0] == ':') break; /* Ignore CR and LF characters. */ if (ascii[0] != '\n' && ascii[0] != '\r') { ERROR (file->context, "Unexpected character (0x%02x).", ascii[0]); return DC_STATUS_DATAFORMAT; } } /* Read the record length, address and type. */ n = fread (ascii + 1, 1, 8, file->fp); if (n != 8) { ERROR (file->context, "Failed to read the header."); return DC_STATUS_IO; } /* Convert to binary representation. */ if (array_convert_hex2bin (ascii + 1, 8, data, 4) != 0) { ERROR (file->context, "Invalid hexadecimal character."); return DC_STATUS_DATAFORMAT; } /* Get the record length. */ length = data[0]; /* Read the record payload. */ n = fread (ascii + 9, 1, 2 * length + 2, file->fp); if (n != 2 * length + 2) { ERROR (file->context, "Failed to read the data."); return DC_STATUS_IO; } /* Convert to binary representation. */ if (array_convert_hex2bin (ascii + 9, 2 * length + 2, data + 4, length + 1) != 0) { ERROR (file->context, "Invalid hexadecimal character."); return DC_STATUS_DATAFORMAT; } /* Verify the checksum. */ csum_a = data[4 + length]; csum_b = ~checksum_add_uint8 (data, 4 + length, 0x00) + 1; if (csum_a != csum_b) { ERROR (file->context, "Unexpected checksum (0x%02x, 0x%02x).", csum_a, csum_b); return DC_STATUS_DATAFORMAT; } /* Get the record address. */ address = array_uint16_be (data + 1); /* Get the record type. */ type = data[3]; if (type < 0 || type > 5) { ERROR (file->context, "Invalid record type (0x%02x).", type); return DC_STATUS_DATAFORMAT; } /* Verify the length and address. */ if (type != 0) { unsigned int len = 0; switch (type) { case 1: /* End of file record. */ len = 0; break; case 2: /* Extended segment address record. */ case 4: /* Extended linear address record. */ len = 2; break; case 3: /* Start segment address record. */ case 5: /* Start linear address record. */ len = 4; break; } if (length != len || address != 0) { ERROR (file->context, "Invalid record length or address."); return DC_STATUS_DATAFORMAT; } } /* Set the record fields. */ entry->type = type; entry->address = address; entry->length = length; /* Copy the record data. */ memcpy (entry->data, data + 4, entry->length); memset (entry->data + entry->length, 0, sizeof (entry->data) - entry->length); return DC_STATUS_SUCCESS; } dc_status_t dc_ihex_file_reset (dc_ihex_file_t *file) { if (file == NULL) { ERROR (NULL, "Invalid arguments."); return DC_STATUS_INVALIDARGS; } rewind (file->fp); return DC_STATUS_SUCCESS; } dc_status_t dc_ihex_file_close (dc_ihex_file_t *file) { if (file) { fclose (file->fp); free (file); } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/ihex.c
/* * libdivecomputer * * Copyright (C) 2011 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <string.h> #include <libdivecomputer/units.h> #include "mares_darwin.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_parser_isinstance((parser), &mares_darwin_parser_vtable) #define DARWIN 0 #define DARWINAIR 1 #define AIR 0 #define GAUGE 1 #define NITROX 2 typedef struct mares_darwin_parser_t mares_darwin_parser_t; struct mares_darwin_parser_t { dc_parser_t base; unsigned int model; unsigned int headersize; unsigned int samplesize; }; static dc_status_t mares_darwin_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t mares_darwin_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t mares_darwin_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t mares_darwin_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t mares_darwin_parser_vtable = { sizeof(mares_darwin_parser_t), DC_FAMILY_MARES_DARWIN, mares_darwin_parser_set_data, /* set_data */ mares_darwin_parser_get_datetime, /* datetime */ mares_darwin_parser_get_field, /* fields */ mares_darwin_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; dc_status_t mares_darwin_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int model) { mares_darwin_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (mares_darwin_parser_t *) dc_parser_allocate (context, &mares_darwin_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } parser->model = model; if (model == DARWINAIR) { parser->headersize = 60; parser->samplesize = 3; } else { parser->headersize = 52; parser->samplesize = 2; } *out = (dc_parser_t *) parser; return DC_STATUS_SUCCESS; } static dc_status_t mares_darwin_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { return DC_STATUS_SUCCESS; } static dc_status_t mares_darwin_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { mares_darwin_parser_t *parser = (mares_darwin_parser_t *) abstract; if (abstract->size < parser->headersize) return DC_STATUS_DATAFORMAT; const unsigned char *p = abstract->data; if (datetime) { datetime->year = array_uint16_be (p); datetime->month = p[2]; datetime->day = p[3]; datetime->hour = p[4]; datetime->minute = p[5]; datetime->second = 0; datetime->timezone = DC_TIMEZONE_NONE; } return DC_STATUS_SUCCESS; } static dc_status_t mares_darwin_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { mares_darwin_parser_t *parser = (mares_darwin_parser_t *) abstract; if (abstract->size < parser->headersize) return DC_STATUS_DATAFORMAT; const unsigned char *p = abstract->data; dc_gasmix_t *gasmix = (dc_gasmix_t *) value; dc_tank_t *tank = (dc_tank_t *) value; unsigned int mode = p[0x0C] & 0x03; if (value) { switch (type) { case DC_FIELD_DIVETIME: *((unsigned int *) value) = array_uint16_be (p + 0x06) * 20; break; case DC_FIELD_MAXDEPTH: *((double *) value) = array_uint16_be (p + 0x08) / 10.0; break; case DC_FIELD_GASMIX_COUNT: if (mode == GAUGE) { *((unsigned int *) value) = 0; } else { *((unsigned int *) value) = 1; } break; case DC_FIELD_GASMIX: gasmix->helium = 0.0; if (mode == NITROX) { gasmix->oxygen = p[0x0E] / 100.0; } else { gasmix->oxygen = 0.21; } gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium; break; case DC_FIELD_TEMPERATURE_MINIMUM: *((double *) value) = (signed char) p[0x0A]; break; case DC_FIELD_TANK_COUNT: if (parser->model == DARWINAIR) { *((unsigned int *) value) = 1; } else { *((unsigned int *) value) = 0; } break; case DC_FIELD_TANK: if (parser->model == DARWINAIR) { tank->type = DC_TANKVOLUME_METRIC; tank->volume = p[0x13] / 10.0; tank->workpressure = 0.0; tank->gasmix = 0; tank->beginpressure = array_uint16_be (p + 0x17); tank->endpressure = array_uint16_be (p + 0x19); } else { return DC_STATUS_UNSUPPORTED; } break; case DC_FIELD_DIVEMODE: switch (mode) { case AIR: case NITROX: *((dc_divemode_t *) value) = DC_DIVEMODE_OC; break; case GAUGE: *((dc_divemode_t *) value) = DC_DIVEMODE_GAUGE; break; default: return DC_STATUS_DATAFORMAT; } break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t mares_darwin_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { mares_darwin_parser_t *parser = (mares_darwin_parser_t *) abstract; if (abstract->size < parser->headersize) return DC_STATUS_DATAFORMAT; unsigned int time = 0; unsigned int mode = abstract->data[0x0C] & 0x03; unsigned int pressure = array_uint16_be (abstract->data + 0x17); unsigned int gasmix_previous = 0xFFFFFFFF; unsigned int gasmix = gasmix_previous; if (mode != GAUGE) { gasmix = 0; } unsigned int offset = parser->headersize; while (offset + parser->samplesize <= abstract->size) { dc_sample_value_t sample = {0}; unsigned int value = array_uint16_le (abstract->data + offset); unsigned int depth = value & 0x07FF; unsigned int ascent = (value & 0xE000) >> 13; unsigned int violation = (value & 0x1000) >> 12; unsigned int deco = (value & 0x0800) >> 11; // Surface Time (seconds). time += 20; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Depth (1/10 m). sample.depth = depth / 10.0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); // Gas change. if (gasmix != gasmix_previous) { sample.gasmix = gasmix; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); gasmix_previous = gasmix; } // Ascent rate if (ascent) { sample.event.type = SAMPLE_EVENT_ASCENT; sample.event.time = 0; sample.event.flags = 0; sample.event.value = ascent; if (callback) callback (DC_SAMPLE_EVENT, sample, userdata); } // Deco violation if (violation) { sample.event.type = SAMPLE_EVENT_CEILING; sample.event.time = 0; sample.event.flags = 0; sample.event.value = 0; if (callback) callback (DC_SAMPLE_EVENT, sample, userdata); } // Deco stop if (deco) { sample.deco.type = DC_DECO_DECOSTOP; } else { sample.deco.type = DC_DECO_NDL; } sample.deco.time = 0; sample.deco.depth = 0.0; if (callback) callback (DC_SAMPLE_DECO, sample, userdata); if (parser->samplesize == 3) { unsigned int type = (time / 20 + 2) % 3; if (type == 0) { // Tank Pressure (bar) pressure -= abstract->data[offset + 2]; sample.pressure.tank = 0; sample.pressure.value = pressure; if (callback) callback (DC_SAMPLE_PRESSURE, sample, userdata); } } offset += parser->samplesize; } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/mares_darwin_parser.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcmp, memcpy #include <stdlib.h> // malloc, free #include "suunto_vyper2.h" #include "suunto_common2.h" #include "context-private.h" #include "serial.h" #include "checksum.h" #include "array.h" #include "timer.h" #define ISINSTANCE(device) dc_device_isinstance((device), (const dc_device_vtable_t *) &suunto_vyper2_device_vtable) #define HELO2 0x15 typedef struct suunto_vyper2_device_t { suunto_common2_device_t base; dc_iostream_t *iostream; dc_timer_t *timer; } suunto_vyper2_device_t; static dc_status_t suunto_vyper2_device_packet (dc_device_t *abstract, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize, unsigned int size); static dc_status_t suunto_vyper2_device_close (dc_device_t *abstract); static const suunto_common2_device_vtable_t suunto_vyper2_device_vtable = { { sizeof(suunto_vyper2_device_t), DC_FAMILY_SUUNTO_VYPER2, suunto_common2_device_set_fingerprint, /* set_fingerprint */ suunto_common2_device_read, /* read */ suunto_common2_device_write, /* write */ suunto_common2_device_dump, /* dump */ suunto_common2_device_foreach, /* foreach */ NULL, /* timesync */ suunto_vyper2_device_close /* close */ }, suunto_vyper2_device_packet }; static const suunto_common2_layout_t suunto_vyper2_layout = { 0x8000, /* memsize */ 0x0011, /* fingerprint */ 0x0023, /* serial */ 0x019A, /* rb_profile_begin */ 0x7FFE /* rb_profile_end */ }; static const suunto_common2_layout_t suunto_helo2_layout = { 0x8000, /* memsize */ 0x0017, /* fingerprint */ 0x0023, /* serial */ 0x019A, /* rb_profile_begin */ 0x7FFE /* rb_profile_end */ }; dc_status_t suunto_vyper2_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; suunto_vyper2_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (suunto_vyper2_device_t *) dc_device_allocate (context, &suunto_vyper2_device_vtable.base); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Initialize the base class. suunto_common2_device_init (&device->base); // Set the default values. device->iostream = NULL; // Create a high resolution timer. status = dc_timer_new (&device->timer); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to create a high resolution timer."); goto error_free; } // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_timer_free; } // Set the serial communication protocol (9600 8N1). status = dc_iostream_configure (device->iostream, 9600, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (3000 ms). status = dc_iostream_set_timeout (device->iostream, 3000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Set the DTR line (power supply for the interface). status = dc_iostream_set_dtr (device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the DTR line."); goto error_close; } // Give the interface 100 ms to settle and draw power up. dc_iostream_sleep (device->iostream, 100); // Make sure everything is in a sane state. status = dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to reset IO state."); goto error_close; } // Read the version info. status = suunto_common2_device_version ((dc_device_t *) device, device->base.version, sizeof (device->base.version)); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to read the version info."); goto error_close; } // Override the base class values. unsigned int model = device->base.version[0]; if (model == HELO2) device->base.layout = &suunto_helo2_layout; else device->base.layout = &suunto_vyper2_layout; *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_timer_free: dc_timer_free (device->timer); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t suunto_vyper2_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; suunto_vyper2_device_t *device = (suunto_vyper2_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; dc_timer_free (device->timer); // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t suunto_vyper2_device_packet (dc_device_t *abstract, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize, unsigned int size) { dc_status_t status = DC_STATUS_SUCCESS; suunto_vyper2_device_t *device = (suunto_vyper2_device_t *) abstract; if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; dc_iostream_sleep (device->iostream, 600); // Set RTS to send the command. status = dc_iostream_set_rts (device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to set the RTS line."); return status; } // Get the current timestamp. dc_usecs_t begin = 0; status = dc_timer_now (device->timer, &begin); if (status != DC_STATUS_SUCCESS) { return status; } // Send the command to the dive computer. status = dc_iostream_write (device->iostream, command, csize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Get the current timestamp. dc_usecs_t end = 0; status = dc_timer_now (device->timer, &end); if (status != DC_STATUS_SUCCESS) { return status; } // Calculate the elapsed time. dc_usecs_t elapsed = end - begin; // Calculate the expected duration. A 2 millisecond fudge factor is added // because it improves the success rate significantly. unsigned int baudrate = 9600; unsigned int nbits = 1 + 8 /* databits */ + 1 /* stopbits */ + 0 /* parity */; dc_usecs_t expected = (dc_usecs_t) csize * 1000000 * nbits / baudrate + 2000; // Wait for the remaining time. if (elapsed < expected) { dc_usecs_t remaining = expected - elapsed; // The remaining time is rounded up to the nearest millisecond // because the sleep function doesn't support a higher // resolution on all platforms. The higher resolution is // pointless anyway, since we already added a fudge factor // above. dc_iostream_sleep (device->iostream, (remaining + 999) / 1000); } // Clear RTS to receive the reply. status = dc_iostream_set_rts (device->iostream, 0); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to set the RTS line."); return status; } // Receive the answer of the dive computer. status = dc_iostream_read (device->iostream, answer, asize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Verify the header of the package. if (answer[0] != command[0]) { ERROR (abstract->context, "Unexpected answer header."); return DC_STATUS_PROTOCOL; } // Verify the size of the package. if (array_uint16_be (answer + 1) + 4 != asize) { ERROR (abstract->context, "Unexpected answer size."); return DC_STATUS_PROTOCOL; } // Verify the parameters of the package. if (memcmp (command + 3, answer + 3, asize - size - 4) != 0) { ERROR (abstract->context, "Unexpected answer parameters."); return DC_STATUS_PROTOCOL; } // Verify the checksum of the package. unsigned char crc = answer[asize - 1]; unsigned char ccrc = checksum_xor_uint8 (answer, asize - 1, 0x00); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } dc_status_t suunto_vyper2_device_version (dc_device_t *abstract, unsigned char data[], unsigned int size) { if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; return suunto_common2_device_version (abstract, data, size); } dc_status_t suunto_vyper2_device_reset_maxdepth (dc_device_t *abstract) { if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; return suunto_common2_device_reset_maxdepth (abstract); }
libdc-for-dirk-Subsurface-branch
src/suunto_vyper2.c
/* * libdivecomputer * * Copyright (C) 2016 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <string.h> #include "rbstream.h" #include "context-private.h" #include "device-private.h" struct dc_rbstream_t { dc_device_t *device; unsigned int pagesize; unsigned int packetsize; unsigned int begin; unsigned int end; unsigned int address; unsigned int available; unsigned int skip; unsigned char cache[]; }; static unsigned int ifloor (unsigned int x, unsigned int n) { // Round down to next lower multiple. return (x / n) * n; } static unsigned int iceil (unsigned int x, unsigned int n) { // Round up to next higher multiple. return ((x + n - 1) / n) * n; } dc_status_t dc_rbstream_new (dc_rbstream_t **out, dc_device_t *device, unsigned int pagesize, unsigned int packetsize, unsigned int begin, unsigned int end, unsigned int address) { dc_rbstream_t *rbstream = NULL; if (out == NULL || device == NULL) return DC_STATUS_INVALIDARGS; // Page and packet size should be non-zero. if (pagesize == 0 || packetsize == 0) { ERROR (device->context, "Zero length page or packet size!"); return DC_STATUS_INVALIDARGS; } // Packet size should be a multiple of the page size. if (packetsize % pagesize != 0) { ERROR (device->context, "Packet size not a multiple of the page size!"); return DC_STATUS_INVALIDARGS; } // Ringbuffer boundaries should be aligned to the page size. if (begin % pagesize != 0 || end % pagesize != 0) { ERROR (device->context, "Ringbuffer not aligned to the page size!"); return DC_STATUS_INVALIDARGS; } // Address should be inside the ringbuffer. if (address < begin || address > end) { ERROR (device->context, "Address outside the ringbuffer!"); return DC_STATUS_INVALIDARGS; } // Allocate memory. rbstream = (dc_rbstream_t *) malloc (sizeof(*rbstream) + packetsize); if (rbstream == NULL) { ERROR (device->context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } rbstream->device = device; rbstream->pagesize = pagesize; rbstream->packetsize = packetsize; rbstream->begin = begin; rbstream->end = end; rbstream->address = iceil(address, pagesize); rbstream->available = 0; rbstream->skip = rbstream->address - address; *out = rbstream; return DC_STATUS_SUCCESS; } dc_status_t dc_rbstream_read (dc_rbstream_t *rbstream, dc_event_progress_t *progress, unsigned char data[], unsigned int size) { dc_status_t rc = DC_STATUS_SUCCESS; if (rbstream == NULL) return DC_STATUS_INVALIDARGS; unsigned int address = rbstream->address; unsigned int available = rbstream->available; unsigned int skip = rbstream->skip; unsigned int nbytes = 0; unsigned int offset = size; while (nbytes < size) { if (available == 0) { // Handle the ringbuffer wrap point. if (address == rbstream->begin) address = rbstream->end; // Calculate the packet size. unsigned int len = rbstream->packetsize; if (rbstream->begin + len > address) len = address - rbstream->begin; // Move to the begin of the current packet. address -= len; // Read the packet into the cache. rc = dc_device_read (rbstream->device, address, rbstream->cache, rbstream->packetsize); if (rc != DC_STATUS_SUCCESS) return rc; available = len - skip; skip = 0; } unsigned int length = available; if (nbytes + length > size) length = size - nbytes; offset -= length; available -= length; memcpy (data + offset, rbstream->cache + available, length); // Update and emit a progress event. if (progress) { progress->current += length; device_event_emit (rbstream->device, DC_EVENT_PROGRESS, progress); } nbytes += length; } rbstream->address = address; rbstream->available = available; rbstream->skip = skip; return rc; } dc_status_t dc_rbstream_free (dc_rbstream_t *rbstream) { free (rbstream); return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/rbstream.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <libdivecomputer/units.h> #include "uwatec_memomouse.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_parser_isinstance((parser), &uwatec_memomouse_parser_vtable) typedef struct uwatec_memomouse_parser_t uwatec_memomouse_parser_t; struct uwatec_memomouse_parser_t { dc_parser_t base; unsigned int devtime; dc_ticks_t systime; }; static dc_status_t uwatec_memomouse_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t uwatec_memomouse_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t uwatec_memomouse_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t uwatec_memomouse_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t uwatec_memomouse_parser_vtable = { sizeof(uwatec_memomouse_parser_t), DC_FAMILY_UWATEC_MEMOMOUSE, uwatec_memomouse_parser_set_data, /* set_data */ uwatec_memomouse_parser_get_datetime, /* datetime */ uwatec_memomouse_parser_get_field, /* fields */ uwatec_memomouse_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; dc_status_t uwatec_memomouse_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int devtime, dc_ticks_t systime) { uwatec_memomouse_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (uwatec_memomouse_parser_t *) dc_parser_allocate (context, &uwatec_memomouse_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. parser->devtime = devtime; parser->systime = systime; *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; } static dc_status_t uwatec_memomouse_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { return DC_STATUS_SUCCESS; } static dc_status_t uwatec_memomouse_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { uwatec_memomouse_parser_t *parser = (uwatec_memomouse_parser_t *) abstract; if (abstract->size < 11 + 4) return DC_STATUS_DATAFORMAT; unsigned int timestamp = array_uint32_le (abstract->data + 11); dc_ticks_t ticks = parser->systime - (parser->devtime - timestamp) / 2; if (!dc_datetime_localtime (datetime, ticks)) return DC_STATUS_DATAFORMAT; return DC_STATUS_SUCCESS; } static dc_status_t uwatec_memomouse_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { const unsigned char *data = abstract->data; unsigned int size = abstract->size; if (size < 18) return DC_STATUS_DATAFORMAT; unsigned int model = data[3]; int is_nitrox = 0, is_oxygen = 0, is_air = 0; if ((model & 0xF0) == 0xF0) is_nitrox = 1; if ((model & 0xF0) == 0xA0) is_oxygen = 1; if ((model & 0xF0) % 4 == 0) is_air = 1; unsigned int header = 22; if (is_nitrox) header += 2; if (is_oxygen) header += 3; dc_gasmix_t *gasmix = (dc_gasmix_t *) value; dc_tank_t *tank = (dc_tank_t *) value; if (value) { switch (type) { case DC_FIELD_DIVETIME: *((unsigned int *) value) = ((data[4] & 0x04 ? 100 : 0) + bcd2dec (data[5])) * 60; break; case DC_FIELD_MAXDEPTH: *((double *) value) = ((array_uint16_be (data + 6) & 0xFFC0) >> 6) * 10.0 / 64.0; break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = 1; break; case DC_FIELD_GASMIX: gasmix->helium = 0.0; if (size >= header + 18) { if (is_oxygen) gasmix->oxygen = data[18 + 23] / 100.0; else if (is_nitrox) gasmix->oxygen = (data[18 + 23] & 0x0F ? 20.0 + 2 * (data[18 + 23] & 0x0F) : 21.0) / 100.0; else gasmix->oxygen = 0.21; } else { gasmix->oxygen = 0.21; } gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium; break; case DC_FIELD_TANK_COUNT: if (data[10]) { *((unsigned int *) value) = 1; } else { *((unsigned int *) value) = 0; } break; case DC_FIELD_TANK: tank->type = DC_TANKVOLUME_NONE; tank->volume = 0.0; tank->workpressure = 0.0; if (model == 0x1C) { tank->beginpressure = data[10] * 20.0 * PSI / BAR; } else { tank->beginpressure = data[10]; } tank->endpressure = 0.0; tank->gasmix = 0; break; case DC_FIELD_TEMPERATURE_MINIMUM: *((double *) value) = (signed char) data[15] / 4.0; break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t uwatec_memomouse_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { const unsigned char *data = abstract->data; unsigned int size = abstract->size; if (size < 18) return DC_STATUS_DATAFORMAT; unsigned int model = data[3]; int is_nitrox = 0, is_oxygen = 0, is_air = 0; if ((model & 0xF0) == 0xF0) is_nitrox = 1; if ((model & 0xF0) == 0xA0) is_oxygen = 1; if ((model & 0xF0) % 4 == 0) is_air = 1; unsigned int header = 22; if (is_nitrox) header += 2; if (is_oxygen) header += 3; unsigned int time = 20; unsigned int gasmix_previous = 0xFFFFFFFF; unsigned int gasmix = 0; unsigned int offset = header + 18; while (offset + 2 <= size) { dc_sample_value_t sample = {0}; unsigned int value = array_uint16_be (data + offset); unsigned int depth = (value & 0xFFC0) >> 6; unsigned int warnings = (value & 0x3F); offset += 2; // Time (seconds) sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Depth (meters) sample.depth = depth * 10.0 / 64.0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); // Gas change. if (gasmix != gasmix_previous) { sample.gasmix = gasmix; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); gasmix_previous = gasmix; } // NDL / Deco if (warnings & 0x01) { sample.deco.type = DC_DECO_DECOSTOP; } else { sample.deco.type = DC_DECO_NDL; } sample.deco.time = 0; sample.deco.depth = 0.0; if (callback) callback (DC_SAMPLE_DECO, sample, userdata); // Warnings for (unsigned int i = 0; i < 6; ++i) { if (warnings & (1 << i)) { sample.event.time = 0; sample.event.flags = 0; sample.event.value = 0; switch (i) { case 0: // Deco stop sample.event.type = SAMPLE_EVENT_NONE; break; case 1: // Remaining bottom time too short (Air series only) sample.event.type = SAMPLE_EVENT_RBT; break; case 2: // Ascent too fast sample.event.type = SAMPLE_EVENT_ASCENT; break; case 3: // Ceiling violation of deco stop sample.event.type = SAMPLE_EVENT_CEILING; break; case 4: // Work too hard (Air series only) sample.event.type = SAMPLE_EVENT_WORKLOAD; break; case 5: // Transmit error of air pressure (always 1 unless Air series) sample.event.type = SAMPLE_EVENT_TRANSMITTER; break; } if (sample.event.type != SAMPLE_EVENT_NONE) { if (callback) callback (DC_SAMPLE_EVENT, sample, userdata); } } } if (time % 60 == 0) { sample.vendor.type = SAMPLE_VENDOR_UWATEC_ALADIN; sample.vendor.size = 0; sample.vendor.data = data + offset; // Decompression information. if (offset + 1 > size) return DC_STATUS_DATAFORMAT; sample.vendor.size++; offset++; // Oxygen percentage (O2 series only). if (is_oxygen) { if (offset + 1 > size) return DC_STATUS_DATAFORMAT; sample.vendor.size++; offset++; } if (callback) callback (DC_SAMPLE_VENDOR, sample, userdata); } time += 20; } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/uwatec_memomouse_parser.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> // malloc, free #include <libdivecomputer/units.h> #include "suunto_solution.h" #include "context-private.h" #include "device-private.h" #include "ringbuffer.h" #include "serial.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &suunto_solution_device_vtable) #define SZ_MEMORY 256 #define RB_PROFILE_BEGIN 0x020 #define RB_PROFILE_END 0x100 typedef struct suunto_solution_device_t { dc_device_t base; dc_iostream_t *iostream; } suunto_solution_device_t; static dc_status_t suunto_solution_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t suunto_solution_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t suunto_solution_device_close (dc_device_t *abstract); static const dc_device_vtable_t suunto_solution_device_vtable = { sizeof(suunto_solution_device_t), DC_FAMILY_SUUNTO_SOLUTION, NULL, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ suunto_solution_device_dump, /* dump */ suunto_solution_device_foreach, /* foreach */ NULL, /* timesync */ suunto_solution_device_close /* close */ }; static dc_status_t suunto_solution_extract_dives (dc_device_t *device, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata); dc_status_t suunto_solution_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; suunto_solution_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (suunto_solution_device_t *) dc_device_allocate (context, &suunto_solution_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (1200 8N2). status = dc_iostream_configure (device->iostream, 1200, 8, DC_PARITY_NONE, DC_STOPBITS_TWO, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (1000ms). status = dc_iostream_set_timeout (device->iostream, 1000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Clear the RTS line. status = dc_iostream_set_rts (device->iostream, 0); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the DTR/RTS line."); goto error_close; } *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t suunto_solution_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; suunto_solution_device_t *device = (suunto_solution_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t suunto_solution_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { dc_status_t status = DC_STATUS_SUCCESS; suunto_solution_device_t *device = (suunto_solution_device_t*) abstract; // Allocate the required amount of memory. if (!dc_buffer_resize (buffer, SZ_MEMORY)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } unsigned char *data = dc_buffer_get_data (buffer); // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = SZ_MEMORY - 1 + 2; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); unsigned char command[3] = {0}; unsigned char answer[3] = {0}; // Assert DTR status = dc_iostream_set_dtr(device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to set the DTR line."); return status; } // Send: 0xFF command[0] = 0xFF; dc_iostream_write (device->iostream, command, 1, NULL); // Receive: 0x3F status = dc_iostream_read (device->iostream, answer, 1, NULL); if (status != DC_STATUS_SUCCESS) return status; if (answer[0] != 0x3F) WARNING (abstract->context, "Unexpected answer byte."); // Send: 0x4D, 0x01, 0x01 command[0] = 0x4D; command[1] = 0x01; command[2] = 0x01; dc_iostream_write (device->iostream, command, 3, NULL); // Update and emit a progress event. progress.current += 1; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); data[0] = 0x00; for (unsigned int i = 1; i < SZ_MEMORY; ++i) { // Receive: 0x01, i, data[i] status = dc_iostream_read (device->iostream, answer, 3, NULL); if (status != DC_STATUS_SUCCESS) return status; if (answer[0] != 0x01 || answer[1] != i) WARNING (abstract->context, "Unexpected answer byte."); // Send: i command[0] = i; dc_iostream_write (device->iostream, command, 1, NULL); // Receive: data[i] status = dc_iostream_read (device->iostream, data + i, 1, NULL); if (status != DC_STATUS_SUCCESS) return status; if (data[i] != answer[2]) WARNING (abstract->context, "Unexpected answer byte."); // Send: 0x0D command[0] = 0x0D; dc_iostream_write (device->iostream, command, 1, NULL); // Update and emit a progress event. progress.current += 1; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); } // Receive: 0x02, 0x00, 0x80 status = dc_iostream_read (device->iostream, answer, 3, NULL); if (status != DC_STATUS_SUCCESS) return status; if (answer[0] != 0x02 || answer[1] != 0x00 || answer[2] != 0x80) WARNING (abstract->context, "Unexpected answer byte."); // Send: 0x80 command[0] = 0x80; dc_iostream_write (device->iostream, command, 1, NULL); // Receive: 0x80 status = dc_iostream_read (device->iostream, answer, 1, NULL); if (status != DC_STATUS_SUCCESS) return status; if (answer[0] != 0x80) WARNING (abstract->context, "Unexpected answer byte."); // Send: 0x20 command[0] = 0x20; dc_iostream_write (device->iostream, command, 1, NULL); // Receive: 0x3F status = dc_iostream_read (device->iostream, answer, 1, NULL); if (status != DC_STATUS_SUCCESS) return status; if (answer[0] != 0x3F) WARNING (abstract->context, "Unexpected answer byte."); // Update and emit a progress event. progress.current += 1; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); return DC_STATUS_SUCCESS; } static dc_status_t suunto_solution_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { dc_buffer_t *buffer = dc_buffer_new (SZ_MEMORY); if (buffer == NULL) return DC_STATUS_NOMEMORY; dc_status_t rc = suunto_solution_device_dump (abstract, buffer); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } // Emit a device info event. unsigned char *data = dc_buffer_get_data (buffer); dc_event_devinfo_t devinfo; devinfo.model = 0; devinfo.firmware = 0; devinfo.serial = 0; for (unsigned int i = 0; i < 3; ++i) { devinfo.serial *= 100; devinfo.serial += bcd2dec (data[0x1D + i]); } device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); rc = suunto_solution_extract_dives (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), callback, userdata); dc_buffer_free (buffer); return rc; } static dc_status_t suunto_solution_extract_dives (dc_device_t *abstract, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata) { if (abstract && !ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size < SZ_MEMORY) return DC_STATUS_DATAFORMAT; unsigned char buffer[RB_PROFILE_END - RB_PROFILE_BEGIN] = {0}; // Get the end of the profile ring buffer. unsigned int eop = data[0x18]; if (eop < RB_PROFILE_BEGIN || eop >= RB_PROFILE_END || data[eop] != 0x82) { return DC_STATUS_DATAFORMAT; } // The profile data is stored backwards in the ringbuffer. To locate // the most recent dive, we start from the end of profile marker and // traverse the ringbuffer in the opposite direction (forwards). // Since the profile data is now processed in the "wrong" direction, // it needs to be reversed again. unsigned int previous = eop; unsigned int current = eop; for (unsigned int i = 0; i < RB_PROFILE_END - RB_PROFILE_BEGIN; ++i) { // Move forwards through the ringbuffer. current++; if (current == RB_PROFILE_END) current = RB_PROFILE_BEGIN; // Check for an end of profile marker. if (data[current] == 0x82) break; // Store the current byte into the buffer. By starting at the // end of the buffer, the data is automatically reversed. unsigned int idx = RB_PROFILE_END - RB_PROFILE_BEGIN - i - 1; buffer[idx] = data[current]; // Check for an end of dive marker (of the next dive), // to find the start of the current dive. unsigned int peek = ringbuffer_increment (current, 2, RB_PROFILE_BEGIN, RB_PROFILE_END); if (data[peek] == 0x80) { unsigned int len = ringbuffer_distance (previous, current, 0, RB_PROFILE_BEGIN, RB_PROFILE_END); if (callback && !callback (buffer + idx, len, NULL, 0, userdata)) return DC_STATUS_SUCCESS; previous = current; } } if (data[current] != 0x82) return DC_STATUS_DATAFORMAT; return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/suunto_solution.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> // malloc #include <string.h> // memcpy, memcmp #include <assert.h> // assert #include "suunto_common.h" #include "ringbuffer.h" #include "array.h" #define RB_PROFILE_DISTANCE(a,b,l) ringbuffer_distance (a, b, 0, l->rb_profile_begin, l->rb_profile_end) #define RB_PROFILE_PEEK(a,l) ringbuffer_decrement (a, l->peek, l->rb_profile_begin, l->rb_profile_end) void suunto_common_device_init (suunto_common_device_t *device) { assert (device != NULL); // Set the default values. memset (device->fingerprint, 0, sizeof (device->fingerprint)); } dc_status_t suunto_common_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { suunto_common_device_t *device = (suunto_common_device_t *) abstract; assert (device != NULL); if (size && size != sizeof (device->fingerprint)) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, sizeof (device->fingerprint)); else memset (device->fingerprint, 0, sizeof (device->fingerprint)); return DC_STATUS_SUCCESS; } dc_status_t suunto_common_extract_dives (suunto_common_device_t *device, const suunto_common_layout_t *layout, const unsigned char data[], dc_dive_callback_t callback, void *userdata) { assert (layout != NULL); unsigned int eop; if (layout->eop) { // Get the end-of-profile pointer directly from the header. eop = array_uint16_be (data + layout->eop); } else { // Get the end-of-profile pointer by searching for the // end-of-profile marker in the profile ringbuffer. eop = layout->rb_profile_begin; while (eop < layout->rb_profile_end) { if (data[eop] == 0x82) break; eop++; } } // Validate the end-of-profile pointer. if (eop < layout->rb_profile_begin || eop >= layout->rb_profile_end || data[eop] != 0x82) { return DC_STATUS_DATAFORMAT; } // Memory buffer for the profile ringbuffer. unsigned int length = layout->rb_profile_end - layout->rb_profile_begin; unsigned char *buffer = (unsigned char *) malloc (length); if (buffer == NULL) return DC_STATUS_NOMEMORY; unsigned int current = eop; unsigned int previous = eop; for (unsigned int i = 0; i < length; ++i) { // Move backwards through the ringbuffer. if (current == layout->rb_profile_begin) current = layout->rb_profile_end; current--; // Check for an end of profile marker. if (data[current] == 0x82) break; // Check for an end of dive marker (of the next dive), // to find the start of the current dive. unsigned int idx = RB_PROFILE_PEEK (current, layout); if (data[idx] == 0x80) { unsigned int len = RB_PROFILE_DISTANCE (current, previous, layout); if (current + len > layout->rb_profile_end) { unsigned int a = layout->rb_profile_end - current; unsigned int b = (current + len) - layout->rb_profile_end; memcpy (buffer + 0, data + current, a); memcpy (buffer + a, data + layout->rb_profile_begin, b); } else { memcpy (buffer, data + current, len); } if (device && memcmp (buffer + layout->fp_offset, device->fingerprint, sizeof (device->fingerprint)) == 0) { free (buffer); return DC_STATUS_SUCCESS; } if (callback && !callback (buffer, len, buffer + layout->fp_offset, sizeof (device->fingerprint), userdata)) { free (buffer); return DC_STATUS_SUCCESS; } previous = current; } } free (buffer); if (data[current] != 0x82) return DC_STATUS_DATAFORMAT; return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/suunto_common.c
/* * libdivecomputer * * Copyright (C) 2017 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> // malloc, free #include "custom.h" #include "iostream-private.h" #include "common-private.h" #include "context-private.h" static dc_status_t dc_custom_set_timeout (dc_iostream_t *abstract, int timeout); static dc_status_t dc_custom_set_latency (dc_iostream_t *abstract, unsigned int value); static dc_status_t dc_custom_set_break (dc_iostream_t *abstract, unsigned int value); static dc_status_t dc_custom_set_dtr (dc_iostream_t *abstract, unsigned int value); static dc_status_t dc_custom_set_rts (dc_iostream_t *abstract, unsigned int value); static dc_status_t dc_custom_get_lines (dc_iostream_t *abstract, unsigned int *value); static dc_status_t dc_custom_get_available (dc_iostream_t *abstract, size_t *value); static dc_status_t dc_custom_configure (dc_iostream_t *abstract, unsigned int baudrate, unsigned int databits, dc_parity_t parity, dc_stopbits_t stopbits, dc_flowcontrol_t flowcontrol); static dc_status_t dc_custom_read (dc_iostream_t *abstract, void *data, size_t size, size_t *actual); static dc_status_t dc_custom_write (dc_iostream_t *abstract, const void *data, size_t size, size_t *actual); static dc_status_t dc_custom_flush (dc_iostream_t *abstract); static dc_status_t dc_custom_purge (dc_iostream_t *abstract, dc_direction_t direction); static dc_status_t dc_custom_sleep (dc_iostream_t *abstract, unsigned int milliseconds); static dc_status_t dc_custom_close (dc_iostream_t *abstract); typedef struct dc_custom_t { /* Base class. */ dc_iostream_t base; /* Internal state. */ dc_custom_cbs_t callbacks; void *userdata; } dc_custom_t; static const dc_iostream_vtable_t dc_custom_vtable = { sizeof(dc_custom_t), dc_custom_set_timeout, /* set_timeout */ dc_custom_set_latency, /* set_latency */ dc_custom_set_break, /* set_break */ dc_custom_set_dtr, /* set_dtr */ dc_custom_set_rts, /* set_rts */ dc_custom_get_lines, /* get_lines */ dc_custom_get_available, /* get_received */ dc_custom_configure, /* configure */ dc_custom_read, /* read */ dc_custom_write, /* write */ dc_custom_flush, /* flush */ dc_custom_purge, /* purge */ dc_custom_sleep, /* sleep */ dc_custom_close, /* close */ }; dc_status_t dc_custom_open (dc_iostream_t **out, dc_context_t *context, const dc_custom_cbs_t *callbacks, void *userdata) { dc_custom_t *custom = NULL; if (out == NULL || callbacks == NULL) return DC_STATUS_INVALIDARGS; INFO (context, "Open: custom"); // Allocate memory. custom = (dc_custom_t *) dc_iostream_allocate (context, &dc_custom_vtable); if (custom == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } custom->callbacks = *callbacks; custom->userdata = userdata; *out = (dc_iostream_t *) custom; return DC_STATUS_SUCCESS; } static dc_status_t dc_custom_set_timeout (dc_iostream_t *abstract, int timeout) { dc_custom_t *custom = (dc_custom_t *) abstract; if (custom->callbacks.set_timeout == NULL) return DC_STATUS_UNSUPPORTED; return custom->callbacks.set_timeout (custom->userdata, timeout); } static dc_status_t dc_custom_set_latency (dc_iostream_t *abstract, unsigned int value) { dc_custom_t *custom = (dc_custom_t *) abstract; if (custom->callbacks.set_latency == NULL) return DC_STATUS_UNSUPPORTED; return custom->callbacks.set_latency (custom->userdata, value); } static dc_status_t dc_custom_set_break (dc_iostream_t *abstract, unsigned int value) { dc_custom_t *custom = (dc_custom_t *) abstract; if (custom->callbacks.set_break == NULL) return DC_STATUS_UNSUPPORTED; return custom->callbacks.set_break (custom->userdata, value); } static dc_status_t dc_custom_set_dtr (dc_iostream_t *abstract, unsigned int value) { dc_custom_t *custom = (dc_custom_t *) abstract; if (custom->callbacks.set_dtr == NULL) return DC_STATUS_UNSUPPORTED; return custom->callbacks.set_dtr (custom->userdata, value); } static dc_status_t dc_custom_set_rts (dc_iostream_t *abstract, unsigned int value) { dc_custom_t *custom = (dc_custom_t *) abstract; if (custom->callbacks.set_rts == NULL) return DC_STATUS_UNSUPPORTED; return custom->callbacks.set_rts (custom->userdata, value); } static dc_status_t dc_custom_get_lines (dc_iostream_t *abstract, unsigned int *value) { dc_custom_t *custom = (dc_custom_t *) abstract; if (custom->callbacks.get_lines == NULL) return DC_STATUS_UNSUPPORTED; return custom->callbacks.get_lines (custom->userdata, value); } static dc_status_t dc_custom_get_available (dc_iostream_t *abstract, size_t *value) { dc_custom_t *custom = (dc_custom_t *) abstract; if (custom->callbacks.get_available == NULL) return DC_STATUS_UNSUPPORTED; return custom->callbacks.get_available (custom->userdata, value); } static dc_status_t dc_custom_configure (dc_iostream_t *abstract, unsigned int baudrate, unsigned int databits, dc_parity_t parity, dc_stopbits_t stopbits, dc_flowcontrol_t flowcontrol) { dc_custom_t *custom = (dc_custom_t *) abstract; if (custom->callbacks.configure == NULL) return DC_STATUS_UNSUPPORTED; return custom->callbacks.configure (custom->userdata, baudrate, databits, parity, stopbits, flowcontrol); } static dc_status_t dc_custom_read (dc_iostream_t *abstract, void *data, size_t size, size_t *actual) { dc_custom_t *custom = (dc_custom_t *) abstract; if (custom->callbacks.read == NULL) return DC_STATUS_UNSUPPORTED; return custom->callbacks.read (custom->userdata, data, size, actual); } static dc_status_t dc_custom_write (dc_iostream_t *abstract, const void *data, size_t size, size_t *actual) { dc_custom_t *custom = (dc_custom_t *) abstract; if (custom->callbacks.write == NULL) return DC_STATUS_UNSUPPORTED; return custom->callbacks.write (custom->userdata, data, size, actual); } static dc_status_t dc_custom_flush (dc_iostream_t *abstract) { dc_custom_t *custom = (dc_custom_t *) abstract; if (custom->callbacks.flush == NULL) return DC_STATUS_UNSUPPORTED; return custom->callbacks.flush (custom->userdata); } static dc_status_t dc_custom_purge (dc_iostream_t *abstract, dc_direction_t direction) { dc_custom_t *custom = (dc_custom_t *) abstract; if (custom->callbacks.purge == NULL) return DC_STATUS_UNSUPPORTED; return custom->callbacks.purge (custom->userdata, direction); } static dc_status_t dc_custom_sleep (dc_iostream_t *abstract, unsigned int milliseconds) { dc_custom_t *custom = (dc_custom_t *) abstract; if (custom->callbacks.sleep == NULL) return DC_STATUS_UNSUPPORTED; return custom->callbacks.sleep (custom->userdata, milliseconds); } static dc_status_t dc_custom_close (dc_iostream_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; dc_custom_t *custom = (dc_custom_t *) abstract; if (custom->callbacks.close) { status = custom->callbacks.close (custom->userdata); } return status; }
libdc-for-dirk-Subsurface-branch
src/custom.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcmp, memcpy #include <stdlib.h> // malloc, free #include <assert.h> // assert #include "uwatec_memomouse.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "checksum.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &uwatec_memomouse_device_vtable) #define PACKETSIZE 126 #define ACK 0x60 #define NAK 0xA8 typedef struct uwatec_memomouse_device_t { dc_device_t base; dc_iostream_t *iostream; unsigned int timestamp; unsigned int devtime; dc_ticks_t systime; } uwatec_memomouse_device_t; static dc_status_t uwatec_memomouse_device_set_fingerprint (dc_device_t *device, const unsigned char data[], unsigned int size); static dc_status_t uwatec_memomouse_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t uwatec_memomouse_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t uwatec_memomouse_device_close (dc_device_t *abstract); static const dc_device_vtable_t uwatec_memomouse_device_vtable = { sizeof(uwatec_memomouse_device_t), DC_FAMILY_UWATEC_MEMOMOUSE, uwatec_memomouse_device_set_fingerprint, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ uwatec_memomouse_device_dump, /* dump */ uwatec_memomouse_device_foreach, /* foreach */ NULL, /* timesync */ uwatec_memomouse_device_close /* close */ }; static dc_status_t uwatec_memomouse_extract_dives (dc_device_t *device, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata); dc_status_t uwatec_memomouse_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; uwatec_memomouse_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (uwatec_memomouse_device_t *) dc_device_allocate (context, &uwatec_memomouse_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; device->timestamp = 0; device->systime = (dc_ticks_t) -1; device->devtime = 0; // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (9600 8N1). status = dc_iostream_configure (device->iostream, 9600, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (1000 ms). status = dc_iostream_set_timeout (device->iostream, 1000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Clear the DTR line. status = dc_iostream_set_dtr (device->iostream, 0); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to clear the DTR line."); goto error_close; } // Clear the RTS line. status = dc_iostream_set_rts (device->iostream, 0); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to clear the RTS line."); goto error_close; } // Make sure everything is in a sane state. dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t uwatec_memomouse_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; uwatec_memomouse_device_t *device = (uwatec_memomouse_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t uwatec_memomouse_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { uwatec_memomouse_device_t *device = (uwatec_memomouse_device_t*) abstract; if (size && size != 4) return DC_STATUS_INVALIDARGS; if (size) device->timestamp = array_uint32_le (data); else device->timestamp = 0; return DC_STATUS_SUCCESS; } static dc_status_t uwatec_memomouse_read_packet (uwatec_memomouse_device_t *device, unsigned char data[], unsigned int size, unsigned int *result) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; assert (result != NULL); // Receive the header of the package. status = dc_iostream_read (device->iostream, data, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Reverse the bits. array_reverse_bits (data, 1); // Verify the header of the package. unsigned int len = data[0]; if (len + 2 > size) { ERROR (abstract->context, "Unexpected answer start byte(s)."); return DC_STATUS_PROTOCOL; } // Receive the remaining part of the package. status = dc_iostream_read (device->iostream, data + 1, len + 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Reverse the bits. array_reverse_bits (data + 1, len + 1); // Verify the checksum of the package. unsigned char crc = data[len + 1]; unsigned char ccrc = checksum_xor_uint8 (data, len + 1, 0x00); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } *result = len; return DC_STATUS_SUCCESS; } static dc_status_t uwatec_memomouse_read_packet_outer (uwatec_memomouse_device_t *device, unsigned char data[], unsigned int size, unsigned int *result) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; dc_status_t rc = DC_STATUS_SUCCESS; while ((rc = uwatec_memomouse_read_packet (device, data, size, result)) != DC_STATUS_SUCCESS) { // Automatically discard a corrupted packet, // and request a new one. if (rc != DC_STATUS_PROTOCOL) return rc; // Flush the input buffer. dc_iostream_purge (device->iostream, DC_DIRECTION_INPUT); // Reject the packet. unsigned char value = NAK; status = dc_iostream_write (device->iostream, &value, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to reject the packet."); return status; } } return DC_STATUS_SUCCESS; } static dc_status_t uwatec_memomouse_read_packet_inner (uwatec_memomouse_device_t *device, dc_buffer_t *buffer, dc_event_progress_t *progress) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; // Erase the current contents of the buffer. if (!dc_buffer_clear (buffer)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } unsigned int nbytes = 0; unsigned int total = PACKETSIZE; while (nbytes < total) { // Calculate the packet size. unsigned int length = total - nbytes; if (length > PACKETSIZE) length = PACKETSIZE; // Read the packet. unsigned char packet[PACKETSIZE + 2] = {0}; dc_status_t rc = uwatec_memomouse_read_packet_outer (device, packet, length + 2, &length); if (rc != DC_STATUS_SUCCESS) return rc; // Accept the packet. unsigned char value = ACK; status = dc_iostream_write (device->iostream, &value, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to accept the packet."); return status; } if (nbytes == 0) { // The first packet should contain at least // the total size of the inner packet. if (length < 2) { ERROR (abstract->context, "Data packet is too short."); return DC_STATUS_PROTOCOL; } // Calculate the total size of the inner packet. total = array_uint16_le (packet + 1) + 3; // Pre-allocate the required amount of memory. if (!dc_buffer_reserve (buffer, total)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } } // Update and emit a progress event. if (progress) { progress->maximum = total; progress->current += length; device_event_emit (&device->base, DC_EVENT_PROGRESS, progress); } // Append the packet to the buffer. dc_buffer_append (buffer, packet + 1, length); nbytes += length; } // Obtain the pointer to the buffer contents. unsigned char *data = dc_buffer_get_data (buffer); // Verify the checksum. unsigned char crc = data[total - 1]; unsigned char ccrc = checksum_xor_uint8 (data, total - 1, 0x00); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } // Discard the header and checksum bytes. dc_buffer_slice (buffer, 2, total - 3); return DC_STATUS_SUCCESS; } static dc_status_t uwatec_memomouse_dump_internal (uwatec_memomouse_device_t *device, dc_buffer_t *buffer) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; size_t available = 0; // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; device_event_emit (&device->base, DC_EVENT_PROGRESS, &progress); // Waiting for greeting message. while (dc_iostream_get_available (device->iostream, &available) == DC_STATUS_SUCCESS && available == 0) { if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; // Flush the input buffer. dc_iostream_purge (device->iostream, DC_DIRECTION_INPUT); // Reject the packet. unsigned char value = NAK; status = dc_iostream_write (device->iostream, &value, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to reject the packet."); return status; } dc_iostream_sleep (device->iostream, 300); } // Read the ID string. dc_status_t rc = uwatec_memomouse_read_packet_inner (device, buffer, NULL); if (rc != DC_STATUS_SUCCESS) return rc; // Prepare the command. unsigned char command [9] = { 0x07, // Outer packet size. 0x05, 0x00, // Inner packet size. 0x55, // Command byte. (device->timestamp ) & 0xFF, (device->timestamp >> 8) & 0xFF, (device->timestamp >> 16) & 0xFF, (device->timestamp >> 24) & 0xFF, 0x00}; // Outer packet checksum. command[8] = checksum_xor_uint8 (command, 8, 0x00); array_reverse_bits (command, sizeof (command)); // Wait a small amount of time before sending the command. // Without this delay, the transfer will fail most of the time. dc_iostream_sleep (device->iostream, 50); // Keep send the command to the device, // until the ACK answer is received. unsigned char answer = NAK; while (answer == NAK) { // Flush the input buffer. dc_iostream_purge (device->iostream, DC_DIRECTION_INPUT); // Send the command to the device. status = dc_iostream_write (device->iostream, command, sizeof (command), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Wait for the answer (ACK). status = dc_iostream_read (device->iostream, &answer, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } } // Verify the answer. if (answer != ACK) { ERROR (abstract->context, "Unexpected answer start byte(s)."); return DC_STATUS_PROTOCOL; } // Wait for the data packet. while (dc_iostream_get_available (device->iostream, &available) == DC_STATUS_SUCCESS && available == 0) { if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; device_event_emit (&device->base, DC_EVENT_WAITING, NULL); dc_iostream_sleep (device->iostream, 100); } // Fetch the current system time. dc_ticks_t now = dc_datetime_now (); // Read the data packet. rc = uwatec_memomouse_read_packet_inner (device, buffer, &progress); if (rc != DC_STATUS_SUCCESS) return rc; // Store the clock calibration values. device->systime = now; device->devtime = array_uint32_le (dc_buffer_get_data (buffer) + 1); // Emit a clock event. dc_event_clock_t clock; clock.systime = device->systime; clock.devtime = device->devtime; device_event_emit ((dc_device_t *) device, DC_EVENT_CLOCK, &clock); return DC_STATUS_SUCCESS; } static dc_status_t uwatec_memomouse_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { dc_status_t status = DC_STATUS_SUCCESS; uwatec_memomouse_device_t *device = (uwatec_memomouse_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Give the interface some time to notice the DTR // line change from a previous transfer (if any). dc_iostream_sleep (device->iostream, 500); // Set the DTR line. rc = dc_iostream_set_dtr (device->iostream, 1); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to set the RTS line."); return rc; } // Start the transfer. status = uwatec_memomouse_dump_internal (device, buffer); // Clear the DTR line again. rc = dc_iostream_set_dtr (device->iostream, 0); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to set the RTS line."); return rc; } return status; } static dc_status_t uwatec_memomouse_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { dc_buffer_t *buffer = dc_buffer_new (0); if (buffer == NULL) return DC_STATUS_NOMEMORY; dc_status_t rc = uwatec_memomouse_device_dump (abstract, buffer); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } rc = uwatec_memomouse_extract_dives (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), callback, userdata); dc_buffer_free (buffer); return rc; } static dc_status_t uwatec_memomouse_extract_dives (dc_device_t *abstract, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata) { if (abstract && !ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; // Parse the data stream to find the total number of dives. unsigned int ndives = 0; unsigned int previous = 0; unsigned int current = 5; while (current + 18 <= size) { // Memomouse sends all the data twice. The first time, it sends // the data starting from the oldest dive towards the newest dive. // Next, it send the same data in reverse order (newest to oldest). // We abort the parsing once we detect the first duplicate dive. // The second data stream contains always exactly 37 dives, and not // all dives have profile data, so it's probably data from the // connected Uwatec Aladin (converted to the memomouse format). if (previous && memcmp (data + previous, data + current, 18) == 0) break; // Get the length of the profile data. unsigned int len = array_uint16_le (data + current + 16); // Check for a buffer overflow. if (current + len + 18 > size) return DC_STATUS_DATAFORMAT; // A memomouse can store data from several dive computers, but only // the data of the connected dive computer can be transferred. // Therefore, the device info will be the same for all dives, and // only needs to be reported once. if (abstract && ndives == 0) { // Emit a device info event. dc_event_devinfo_t devinfo; devinfo.model = data[current + 3]; devinfo.firmware = 0; devinfo.serial = array_uint24_be (data + current); device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); } // Move to the next dive. previous = current; current += len + 18; ndives++; } // Parse the data stream again to return each dive in reverse order // (newest dive first). This is less efficient, since the data stream // needs to be scanned multiple times, but it makes the behaviour // consistent with the equivalent function for the Uwatec Aladin. for (unsigned int i = 0; i < ndives; ++i) { // Skip the older dives. unsigned int offset = 5; unsigned int skip = ndives - i - 1; while (skip) { // Get the length of the profile data. unsigned int len = array_uint16_le (data + offset + 16); // Move to the next dive. offset += len + 18; skip--; } // Get the length of the profile data. unsigned int length = array_uint16_le (data + offset + 16); if (callback && !callback (data + offset, length + 18, data + offset + 11, 4, userdata)) return DC_STATUS_SUCCESS; } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/uwatec_memomouse.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #define NOGDI #include <windows.h> #include "serial.h" #include "common-private.h" #include "context-private.h" #include "iostream-private.h" #include "iterator-private.h" #include "descriptor-private.h" static dc_status_t dc_serial_iterator_next (dc_iterator_t *iterator, void *item); static dc_status_t dc_serial_iterator_free (dc_iterator_t *iterator); static dc_status_t dc_serial_set_timeout (dc_iostream_t *iostream, int timeout); static dc_status_t dc_serial_set_latency (dc_iostream_t *iostream, unsigned int value); static dc_status_t dc_serial_set_break (dc_iostream_t *iostream, unsigned int value); static dc_status_t dc_serial_set_dtr (dc_iostream_t *iostream, unsigned int value); static dc_status_t dc_serial_set_rts (dc_iostream_t *iostream, unsigned int value); static dc_status_t dc_serial_get_lines (dc_iostream_t *iostream, unsigned int *value); static dc_status_t dc_serial_get_available (dc_iostream_t *iostream, size_t *value); static dc_status_t dc_serial_configure (dc_iostream_t *iostream, unsigned int baudrate, unsigned int databits, dc_parity_t parity, dc_stopbits_t stopbits, dc_flowcontrol_t flowcontrol); static dc_status_t dc_serial_read (dc_iostream_t *iostream, void *data, size_t size, size_t *actual); static dc_status_t dc_serial_write (dc_iostream_t *iostream, const void *data, size_t size, size_t *actual); static dc_status_t dc_serial_flush (dc_iostream_t *iostream); static dc_status_t dc_serial_purge (dc_iostream_t *iostream, dc_direction_t direction); static dc_status_t dc_serial_sleep (dc_iostream_t *iostream, unsigned int milliseconds); static dc_status_t dc_serial_close (dc_iostream_t *iostream); struct dc_serial_device_t { char name[256]; }; typedef struct dc_serial_iterator_t { dc_iterator_t base; dc_filter_t filter; HKEY hKey; DWORD count; DWORD current; } dc_serial_iterator_t; typedef struct dc_serial_t { dc_iostream_t base; /* * The file descriptor corresponding to the serial port. */ HANDLE hFile; /* * Serial port settings are saved into this variables immediately * after the port is opened. These settings are restored when the * serial port is closed. */ DCB dcb; COMMTIMEOUTS timeouts; } dc_serial_t; static const dc_iterator_vtable_t dc_serial_iterator_vtable = { sizeof(dc_serial_iterator_t), dc_serial_iterator_next, dc_serial_iterator_free, }; static const dc_iostream_vtable_t dc_serial_vtable = { sizeof(dc_serial_t), dc_serial_set_timeout, /* set_timeout */ dc_serial_set_latency, /* set_latency */ dc_serial_set_break, /* set_break */ dc_serial_set_dtr, /* set_dtr */ dc_serial_set_rts, /* set_rts */ dc_serial_get_lines, /* get_lines */ dc_serial_get_available, /* get_received */ dc_serial_configure, /* configure */ dc_serial_read, /* read */ dc_serial_write, /* write */ dc_serial_flush, /* flush */ dc_serial_purge, /* purge */ dc_serial_sleep, /* sleep */ dc_serial_close, /* close */ }; static dc_status_t syserror(DWORD errcode) { switch (errcode) { case ERROR_INVALID_PARAMETER: return DC_STATUS_INVALIDARGS; case ERROR_OUTOFMEMORY: return DC_STATUS_NOMEMORY; case ERROR_FILE_NOT_FOUND: return DC_STATUS_NODEVICE; case ERROR_ACCESS_DENIED: return DC_STATUS_NOACCESS; default: return DC_STATUS_IO; } } const char * dc_serial_device_get_name (dc_serial_device_t *device) { if (device == NULL || device->name[0] == '\0') return NULL; return device->name; } void dc_serial_device_free (dc_serial_device_t *device) { free (device); } dc_status_t dc_serial_iterator_new (dc_iterator_t **out, dc_context_t *context, dc_descriptor_t *descriptor) { dc_status_t status = DC_STATUS_SUCCESS; dc_serial_iterator_t *iterator = NULL; HKEY hKey = NULL; DWORD count = 0; LONG rc = 0; if (out == NULL) return DC_STATUS_INVALIDARGS; iterator = (dc_serial_iterator_t *) dc_iterator_allocate (context, &dc_serial_iterator_vtable); if (iterator == NULL) { SYSERROR (context, ERROR_OUTOFMEMORY); return DC_STATUS_NOMEMORY; } // Open the registry key. rc = RegOpenKeyExA (HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\SERIALCOMM", 0, KEY_QUERY_VALUE, &hKey); if (rc != ERROR_SUCCESS) { if (rc == ERROR_FILE_NOT_FOUND) { hKey = NULL; } else { SYSERROR (context, rc); status = syserror (rc); goto error_free; } } // Get the number of values. if (hKey) { rc = RegQueryInfoKey (hKey, NULL, NULL, NULL, NULL, NULL, NULL, &count, NULL, NULL, NULL, NULL); if (rc != ERROR_SUCCESS) { SYSERROR (context, rc); status = syserror (rc); goto error_close; } } iterator->filter = dc_descriptor_get_filter (descriptor); iterator->hKey = hKey; iterator->count = count; iterator->current = 0; *out = (dc_iterator_t *) iterator; return DC_STATUS_SUCCESS; error_close: RegCloseKey (hKey); error_free: dc_iterator_deallocate ((dc_iterator_t *) iterator); return status; } static dc_status_t dc_serial_iterator_next (dc_iterator_t *abstract, void *out) { dc_serial_iterator_t *iterator = (dc_serial_iterator_t *) abstract; dc_serial_device_t *device = NULL; while (iterator->current < iterator->count) { // Get the value name, data and type. char name[256], data[sizeof(device->name)]; DWORD name_len = sizeof (name); DWORD data_len = sizeof (data); DWORD type = 0; LONG rc = RegEnumValueA (iterator->hKey, iterator->current++, name, &name_len, NULL, &type, (LPBYTE) data, &data_len); if (rc != ERROR_SUCCESS) { SYSERROR (abstract->context, rc); return syserror (rc); } // Ignore non-string values. if (type != REG_SZ) continue; // Prevent a possible buffer overflow. if (data_len >= sizeof (data)) { return DC_STATUS_NOMEMORY; } // Null terminate the string. data[data_len] = 0; if (iterator->filter && !iterator->filter (DC_TRANSPORT_SERIAL, data)) { continue; } device = (dc_serial_device_t *) malloc (sizeof(dc_serial_device_t)); if (device == NULL) { SYSERROR (abstract->context, ERROR_OUTOFMEMORY); return DC_STATUS_NOMEMORY; } strncpy(device->name, data, sizeof(device->name)); *(dc_serial_device_t **) out = device; return DC_STATUS_SUCCESS; } return DC_STATUS_DONE; } static dc_status_t dc_serial_iterator_free (dc_iterator_t *abstract) { dc_serial_iterator_t *iterator = (dc_serial_iterator_t *) abstract; if (iterator->hKey) { RegCloseKey (iterator->hKey); } return DC_STATUS_SUCCESS; } dc_status_t dc_serial_open (dc_iostream_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; dc_serial_t *device = NULL; if (out == NULL || name == NULL) return DC_STATUS_INVALIDARGS; // Are we using custom IO? if (_dc_context_custom_io(context)) return dc_custom_io_serial_open(out, context, name); INFO (context, "Open: name=%s", name); // Build the device name. const char *devname = NULL; char buffer[MAX_PATH] = "\\\\.\\"; if (strncmp (name, buffer, 4) != 0) { size_t length = strlen (name) + 1; if (length + 4 > sizeof (buffer)) return DC_STATUS_NOMEMORY; memcpy (buffer + 4, name, length); devname = buffer; } else { devname = name; } // Allocate memory. device = (dc_serial_t *) dc_iostream_allocate (context, &dc_serial_vtable); if (device == NULL) { SYSERROR (context, ERROR_OUTOFMEMORY); return DC_STATUS_NOMEMORY; } // Open the device. device->hFile = CreateFileA (devname, GENERIC_READ | GENERIC_WRITE, 0, NULL, // No security attributes. OPEN_EXISTING, 0, // Non-overlapped I/O. NULL); if (device->hFile == INVALID_HANDLE_VALUE) { DWORD errcode = GetLastError (); SYSERROR (context, errcode); status = syserror (errcode); goto error_free; } // Retrieve the current communication settings and timeouts, // to be able to restore them when closing the device. // It is also used to check if the obtained handle // represents a serial device. if (!GetCommState (device->hFile, &device->dcb) || !GetCommTimeouts (device->hFile, &device->timeouts)) { DWORD errcode = GetLastError (); SYSERROR (context, errcode); status = syserror (errcode); goto error_close; } *out = (dc_iostream_t *) device; return DC_STATUS_SUCCESS; error_close: CloseHandle (device->hFile); error_free: dc_iostream_deallocate ((dc_iostream_t *) device); return status; } static dc_status_t dc_serial_close (dc_iostream_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; dc_serial_t *device = (dc_serial_t *) abstract; // Restore the initial communication settings and timeouts. if (!SetCommState (device->hFile, &device->dcb) || !SetCommTimeouts (device->hFile, &device->timeouts)) { DWORD errcode = GetLastError (); SYSERROR (abstract->context, errcode); dc_status_set_error(&status, syserror (errcode)); } // Close the device. if (!CloseHandle (device->hFile)) { DWORD errcode = GetLastError (); SYSERROR (abstract->context, errcode); dc_status_set_error(&status, syserror (errcode)); } return status; } static dc_status_t dc_serial_configure (dc_iostream_t *abstract, unsigned int baudrate, unsigned int databits, dc_parity_t parity, dc_stopbits_t stopbits, dc_flowcontrol_t flowcontrol) { dc_serial_t *device = (dc_serial_t *) abstract; // Retrieve the current settings. DCB dcb; if (!GetCommState (device->hFile, &dcb)) { DWORD errcode = GetLastError (); SYSERROR (abstract->context, errcode); return syserror (errcode); } dcb.fBinary = TRUE; // Enable Binary Transmission dcb.fAbortOnError = FALSE; // Baudrate. dcb.BaudRate = baudrate; // Character size. if (databits >= 5 && databits <= 8) dcb.ByteSize = databits; else return DC_STATUS_INVALIDARGS; // Parity checking. switch (parity) { case DC_PARITY_NONE: dcb.Parity = NOPARITY; dcb.fParity = FALSE; break; case DC_PARITY_EVEN: dcb.Parity = EVENPARITY; dcb.fParity = TRUE; break; case DC_PARITY_ODD: dcb.Parity = ODDPARITY; dcb.fParity = TRUE; break; case DC_PARITY_MARK: dcb.Parity = MARKPARITY; dcb.fParity = TRUE; break; case DC_PARITY_SPACE: dcb.Parity = SPACEPARITY; dcb.fParity = TRUE; break; default: return DC_STATUS_INVALIDARGS; } // Stopbits. switch (stopbits) { case DC_STOPBITS_ONE: dcb.StopBits = ONESTOPBIT; break; case DC_STOPBITS_ONEPOINTFIVE: dcb.StopBits = ONE5STOPBITS; break; case DC_STOPBITS_TWO: dcb.StopBits = TWOSTOPBITS; break; default: return DC_STATUS_INVALIDARGS; } // Flow control. switch (flowcontrol) { case DC_FLOWCONTROL_NONE: dcb.fInX = FALSE; dcb.fOutX = FALSE; dcb.fOutxCtsFlow = FALSE; dcb.fOutxDsrFlow = FALSE; dcb.fDtrControl = DTR_CONTROL_ENABLE; dcb.fRtsControl = RTS_CONTROL_ENABLE; break; case DC_FLOWCONTROL_HARDWARE: dcb.fInX = FALSE; dcb.fOutX = FALSE; dcb.fOutxCtsFlow = TRUE; dcb.fOutxDsrFlow = TRUE; dcb.fDtrControl = DTR_CONTROL_HANDSHAKE; dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; break; case DC_FLOWCONTROL_SOFTWARE: dcb.fInX = TRUE; dcb.fOutX = TRUE; dcb.fOutxCtsFlow = FALSE; dcb.fOutxDsrFlow = FALSE; dcb.fDtrControl = DTR_CONTROL_ENABLE; dcb.fRtsControl = RTS_CONTROL_ENABLE; break; default: return DC_STATUS_INVALIDARGS; } // Apply the new settings. if (!SetCommState (device->hFile, &dcb)) { DWORD errcode = GetLastError (); SYSERROR (abstract->context, errcode); return syserror (errcode); } return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_set_timeout (dc_iostream_t *abstract, int timeout) { dc_serial_t *device = (dc_serial_t *) abstract; // Retrieve the current timeouts. COMMTIMEOUTS timeouts; if (!GetCommTimeouts (device->hFile, &timeouts)) { DWORD errcode = GetLastError (); SYSERROR (abstract->context, errcode); return syserror (errcode); } // Update the settings. if (timeout < 0) { // Blocking mode. timeouts.ReadIntervalTimeout = 0; timeouts.ReadTotalTimeoutMultiplier = 0; timeouts.ReadTotalTimeoutConstant = 0; timeouts.WriteTotalTimeoutMultiplier = 0; timeouts.WriteTotalTimeoutConstant = 0; } else if (timeout == 0) { // Non-blocking mode. timeouts.ReadIntervalTimeout = MAXDWORD; timeouts.ReadTotalTimeoutMultiplier = 0; timeouts.ReadTotalTimeoutConstant = 0; timeouts.WriteTotalTimeoutMultiplier = 0; timeouts.WriteTotalTimeoutConstant = 0; } else { // Standard timeout mode. timeouts.ReadIntervalTimeout = 0; timeouts.ReadTotalTimeoutMultiplier = 0; timeouts.ReadTotalTimeoutConstant = timeout; timeouts.WriteTotalTimeoutMultiplier = 0; timeouts.WriteTotalTimeoutConstant = 0; } // Activate the new timeouts. if (!SetCommTimeouts (device->hFile, &timeouts)) { DWORD errcode = GetLastError (); SYSERROR (abstract->context, errcode); return syserror (errcode); } return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_set_latency (dc_iostream_t *abstract, unsigned int value) { return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_read (dc_iostream_t *abstract, void *data, size_t size, size_t *actual) { dc_status_t status = DC_STATUS_SUCCESS; dc_serial_t *device = (dc_serial_t *) abstract; DWORD dwRead = 0; if (!ReadFile (device->hFile, data, size, &dwRead, NULL)) { DWORD errcode = GetLastError (); SYSERROR (abstract->context, errcode); status = syserror (errcode); goto out; } if (dwRead != size) { status = DC_STATUS_TIMEOUT; } out: if (actual) *actual = dwRead; return status; } static dc_status_t dc_serial_write (dc_iostream_t *abstract, const void *data, size_t size, size_t *actual) { dc_status_t status = DC_STATUS_SUCCESS; dc_serial_t *device = (dc_serial_t *) abstract; DWORD dwWritten = 0; if (!WriteFile (device->hFile, data, size, &dwWritten, NULL)) { DWORD errcode = GetLastError (); SYSERROR (abstract->context, errcode); status = syserror (errcode); goto out; } if (dwWritten != size) { status = DC_STATUS_TIMEOUT; } out: if (actual) *actual = dwWritten; return status; } static dc_status_t dc_serial_purge (dc_iostream_t *abstract, dc_direction_t direction) { dc_serial_t *device = (dc_serial_t *) abstract; DWORD flags = 0; switch (direction) { case DC_DIRECTION_INPUT: flags = PURGE_RXABORT | PURGE_RXCLEAR; break; case DC_DIRECTION_OUTPUT: flags = PURGE_TXABORT | PURGE_TXCLEAR; break; case DC_DIRECTION_ALL: flags = PURGE_RXABORT | PURGE_RXCLEAR | PURGE_TXABORT | PURGE_TXCLEAR; break; default: return DC_STATUS_INVALIDARGS; } if (!PurgeComm (device->hFile, flags)) { DWORD errcode = GetLastError (); SYSERROR (abstract->context, errcode); return syserror (errcode); } return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_flush (dc_iostream_t *abstract) { dc_serial_t *device = (dc_serial_t *) abstract; if (!FlushFileBuffers (device->hFile)) { DWORD errcode = GetLastError (); SYSERROR (abstract->context, errcode); return syserror (errcode); } return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_set_break (dc_iostream_t *abstract, unsigned int level) { dc_serial_t *device = (dc_serial_t *) abstract; if (level) { if (!SetCommBreak (device->hFile)) { DWORD errcode = GetLastError (); SYSERROR (abstract->context, errcode); return syserror (errcode); } } else { if (!ClearCommBreak (device->hFile)) { DWORD errcode = GetLastError (); SYSERROR (abstract->context, errcode); return syserror (errcode); } } return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_set_dtr (dc_iostream_t *abstract, unsigned int level) { dc_serial_t *device = (dc_serial_t *) abstract; int status = (level ? SETDTR : CLRDTR); if (!EscapeCommFunction (device->hFile, status)) { DWORD errcode = GetLastError (); SYSERROR (abstract->context, errcode); return syserror (errcode); } return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_set_rts (dc_iostream_t *abstract, unsigned int level) { dc_serial_t *device = (dc_serial_t *) abstract; int status = (level ? SETRTS : CLRRTS); if (!EscapeCommFunction (device->hFile, status)) { DWORD errcode = GetLastError (); SYSERROR (abstract->context, errcode); return syserror (errcode); } return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_get_available (dc_iostream_t *abstract, size_t *value) { dc_serial_t *device = (dc_serial_t *) abstract; COMSTAT stats; if (!ClearCommError (device->hFile, NULL, &stats)) { DWORD errcode = GetLastError (); SYSERROR (abstract->context, errcode); return syserror (errcode); } if (value) *value = stats.cbInQue; return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_get_lines (dc_iostream_t *abstract, unsigned int *value) { dc_serial_t *device = (dc_serial_t *) abstract; unsigned int lines = 0; DWORD stats = 0; if (!GetCommModemStatus (device->hFile, &stats)) { DWORD errcode = GetLastError (); SYSERROR (abstract->context, errcode); return syserror (errcode); } if (stats & MS_RLSD_ON) lines |= DC_LINE_DCD; if (stats & MS_CTS_ON) lines |= DC_LINE_CTS; if (stats & MS_DSR_ON) lines |= DC_LINE_DSR; if (stats & MS_RING_ON) lines |= DC_LINE_RNG; if (value) *value = lines; return DC_STATUS_SUCCESS; } static dc_status_t dc_serial_sleep (dc_iostream_t *abstract, unsigned int timeout) { Sleep (timeout); return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/serial_win32.c
/* * libdivecomputer * * Copyright (C) 2012 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcmp, memcpy #include <stdlib.h> // malloc, free #include "shearwater_predator.h" #include "shearwater_common.h" #include "context-private.h" #include "device-private.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &shearwater_predator_device_vtable) #define SZ_BLOCK 0x80 #define SZ_MEMORY 0x20080 #define RB_PROFILE_BEGIN 0 #define RB_PROFILE_END 0x1F600 typedef struct shearwater_predator_device_t { shearwater_common_device_t base; unsigned char fingerprint[4]; } shearwater_predator_device_t; static dc_status_t shearwater_predator_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t shearwater_predator_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t shearwater_predator_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t shearwater_predator_device_close (dc_device_t *abstract); static const dc_device_vtable_t shearwater_predator_device_vtable = { sizeof(shearwater_predator_device_t), DC_FAMILY_SHEARWATER_PREDATOR, shearwater_predator_device_set_fingerprint, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ shearwater_predator_device_dump, /* dump */ shearwater_predator_device_foreach, /* foreach */ NULL, /* timesync */ shearwater_predator_device_close /* close */ }; static dc_status_t shearwater_predator_extract_dives (dc_device_t *device, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata); dc_status_t shearwater_predator_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; shearwater_predator_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (shearwater_predator_device_t *) dc_device_allocate (context, &shearwater_predator_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. memset (device->fingerprint, 0, sizeof (device->fingerprint)); // Open the device. status = shearwater_common_open (&device->base, context, name); if (status != DC_STATUS_SUCCESS) { goto error_free; } *out = (dc_device_t *) device; return DC_STATUS_SUCCESS; error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t shearwater_predator_device_close (dc_device_t *abstract) { shearwater_common_device_t *device = (shearwater_common_device_t *) abstract; return shearwater_common_close (device); } static dc_status_t shearwater_predator_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { shearwater_predator_device_t *device = (shearwater_predator_device_t *) abstract; if (size && size != sizeof (device->fingerprint)) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, sizeof (device->fingerprint)); else memset (device->fingerprint, 0, sizeof (device->fingerprint)); return DC_STATUS_SUCCESS; } static dc_status_t shearwater_predator_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { shearwater_common_device_t *device = (shearwater_common_device_t *) abstract; // Pre-allocate the required amount of memory. if (!dc_buffer_reserve (buffer, SZ_MEMORY)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.current = 0; progress.maximum = NSTEPS; return shearwater_common_download (device, buffer, 0xDD000000, SZ_MEMORY, 0, &progress); } static dc_status_t shearwater_predator_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { dc_buffer_t *buffer = dc_buffer_new (SZ_MEMORY); if (buffer == NULL) return DC_STATUS_NOMEMORY; dc_status_t rc = shearwater_predator_device_dump (abstract, buffer); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } // Emit a device info event. unsigned char *data = dc_buffer_get_data (buffer); dc_event_devinfo_t devinfo; devinfo.model = data[0x2000D]; devinfo.firmware = bcd2dec (data[0x2000A]); devinfo.serial = array_uint32_be (data + 0x20002); device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); rc = shearwater_predator_extract_dives (abstract, data, SZ_MEMORY, callback, userdata); dc_buffer_free (buffer); return rc; } static dc_status_t shearwater_predator_extract_predator (dc_device_t *abstract, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata) { shearwater_predator_device_t *device = (shearwater_predator_device_t*) abstract; dc_context_t *context = (abstract ? abstract->context : NULL); // Locate the most recent dive. // The device maintains an internal counter which is incremented for every // dive, and the current value at the time of the dive is stored in the // dive header. Thus the most recent dive will have the highest value. unsigned int maximum = 0; unsigned int eop = RB_PROFILE_END; // Search the ringbuffer backwards to locate matching header and // footer markers. Because the ringbuffer search algorithm starts at // some arbitrary position, which does not necessary corresponds // with a boundary between two dives, the begin position is adjusted // as soon as the first dive has been found. Without this step, // dives crossing the ringbuffer wrap point won't be detected when // searching backwards from the ringbuffer end offset. unsigned int footer = 0; unsigned int have_footer = 0; unsigned int begin = RB_PROFILE_BEGIN; unsigned int offset = RB_PROFILE_END; while (offset != begin) { // Handle the ringbuffer wrap point. if (offset == RB_PROFILE_BEGIN) offset = RB_PROFILE_END; // Move to the start of the block. offset -= SZ_BLOCK; if (array_isequal (data + offset, SZ_BLOCK, 0xFF)) { // Ignore empty blocks explicitly, because otherwise they are // incorrectly recognized as header markers. } else if (data[offset + 0] == 0xFF && data[offset + 1] == 0xFF && have_footer) { // If the first header marker is found, the begin offset is moved // after the corresponding footer marker. This is necessary to be // able to detect dives that cross the ringbuffer wrap point. if (begin == RB_PROFILE_BEGIN) begin = footer + SZ_BLOCK; // Get the internal dive number. unsigned int current = array_uint16_be (data + offset + 2); if (current > maximum) { maximum = current; eop = footer + SZ_BLOCK; } // The dive number in the header and footer should be identical. if (current != array_uint16_be (data + footer + 2)) { ERROR (context, "Unexpected dive number."); return DC_STATUS_DATAFORMAT; } // Reset the footer marker. have_footer = 0; } else if (data[offset + 0] == 0xFF && data[offset + 1] == 0xFE) { // Remember the footer marker. footer = offset; have_footer = 1; } } // Allocate memory for the profiles. unsigned char *buffer = (unsigned char *) malloc (RB_PROFILE_END - RB_PROFILE_BEGIN + SZ_BLOCK); if (buffer == NULL) { return DC_STATUS_NOMEMORY; } // Linearize the ringbuffer. memcpy (buffer + 0, data + eop, RB_PROFILE_END - eop); memcpy (buffer + RB_PROFILE_END - eop, data + RB_PROFILE_BEGIN, eop - RB_PROFILE_BEGIN); // Find the dives again in the linear buffer. footer = 0; have_footer = 0; offset = RB_PROFILE_END; while (offset != RB_PROFILE_BEGIN) { // Move to the start of the block. offset -= SZ_BLOCK; if (array_isequal (buffer + offset, SZ_BLOCK, 0xFF)) { break; } else if (buffer[offset + 0] == 0xFF && buffer[offset + 1] == 0xFF && have_footer) { // Append the final block. unsigned int length = footer + SZ_BLOCK - offset; memcpy (buffer + offset + length, data + SZ_MEMORY - SZ_BLOCK, SZ_BLOCK); // Check the fingerprint data. if (device && memcmp (buffer + offset + 12, device->fingerprint, sizeof (device->fingerprint)) == 0) break; if (callback && !callback (buffer + offset, length + SZ_BLOCK, buffer + offset + 12, sizeof (device->fingerprint), userdata)) break; have_footer = 0; } else if (buffer[offset + 0] == 0xFF && buffer[offset + 1] == 0xFE) { footer = offset; have_footer = 1; } } free (buffer); return DC_STATUS_SUCCESS; } static dc_status_t shearwater_predator_extract_petrel (dc_device_t *abstract, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata) { shearwater_predator_device_t *device = (shearwater_predator_device_t*) abstract; dc_context_t *context = (abstract ? abstract->context : NULL); // Allocate memory for the profiles. unsigned char *buffer = (unsigned char *) malloc (RB_PROFILE_END - RB_PROFILE_BEGIN + SZ_BLOCK); if (buffer == NULL) { return DC_STATUS_NOMEMORY; } // Search the ringbuffer to locate matching header and footer // markers. Because the Petrel does reorder the internal ringbuffer // before sending the data, the most recent dive is always the first // one. Therefore, there is no need to search for it, as we have to // do for the Predator. unsigned int header = 0; unsigned int have_header = 0; unsigned int offset = RB_PROFILE_BEGIN; while (offset != RB_PROFILE_END) { if (array_isequal (data + offset, SZ_BLOCK, 0xFF)) { // Ignore empty blocks explicitly, because otherwise they are // incorrectly recognized as header markers. break; } else if (data[offset + 0] == 0xFF && data[offset + 1] == 0xFF) { // Remember the header marker. header = offset; have_header = 1; } else if (data[offset + 0] == 0xFF && data[offset + 1] == 0xFE && have_header) { // The dive number in the header and footer should be identical. if (memcmp (data + header + 2, data + offset + 2, 2) != 0) { ERROR (context, "Unexpected dive number."); free (buffer); return DC_STATUS_DATAFORMAT; } // Append the final block. unsigned int length = offset + SZ_BLOCK - header; memcpy (buffer, data + header, length); memcpy (buffer + length, data + SZ_MEMORY - SZ_BLOCK, SZ_BLOCK); // Check the fingerprint data. if (device && memcmp (buffer + 12, device->fingerprint, sizeof (device->fingerprint)) == 0) break; if (callback && !callback (buffer, length + SZ_BLOCK, buffer + 12, sizeof (device->fingerprint), userdata)) break; // Reset the header marker. have_header = 0; } offset += SZ_BLOCK; } free (buffer); return DC_STATUS_SUCCESS; } static dc_status_t shearwater_predator_extract_dives (dc_device_t *abstract, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata) { if (abstract && !ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size < SZ_MEMORY) return DC_STATUS_DATAFORMAT; unsigned int model = data[0x2000D]; if (model == PETREL) { return shearwater_predator_extract_petrel (abstract, data, size, callback, userdata); } else { return shearwater_predator_extract_predator (abstract, data, size, callback, userdata); } }
libdc-for-dirk-Subsurface-branch
src/shearwater_predator.c
/* * libdivecomputer * * Copyright (C) 2009 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> // malloc, free #include <libdivecomputer/units.h> #include "reefnet_sensus.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_parser_isinstance((parser), &reefnet_sensus_parser_vtable) #define SAMPLE_DEPTH_ADJUST 13 typedef struct reefnet_sensus_parser_t reefnet_sensus_parser_t; struct reefnet_sensus_parser_t { dc_parser_t base; // Depth calibration. double atmospheric; double hydrostatic; // Clock synchronization. unsigned int devtime; dc_ticks_t systime; // Cached fields. unsigned int cached; unsigned int divetime; unsigned int maxdepth; }; static dc_status_t reefnet_sensus_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t reefnet_sensus_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t reefnet_sensus_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t reefnet_sensus_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t reefnet_sensus_parser_vtable = { sizeof(reefnet_sensus_parser_t), DC_FAMILY_REEFNET_SENSUS, reefnet_sensus_parser_set_data, /* set_data */ reefnet_sensus_parser_get_datetime, /* datetime */ reefnet_sensus_parser_get_field, /* fields */ reefnet_sensus_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; dc_status_t reefnet_sensus_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int devtime, dc_ticks_t systime) { reefnet_sensus_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (reefnet_sensus_parser_t *) dc_parser_allocate (context, &reefnet_sensus_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. parser->atmospheric = ATM; parser->hydrostatic = 1025.0 * GRAVITY; parser->devtime = devtime; parser->systime = systime; parser->cached = 0; parser->divetime = 0; parser->maxdepth = 0; *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensus_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { reefnet_sensus_parser_t *parser = (reefnet_sensus_parser_t*) abstract; // Reset the cache. parser->cached = 0; parser->divetime = 0; parser->maxdepth = 0; return DC_STATUS_SUCCESS; } dc_status_t reefnet_sensus_parser_set_calibration (dc_parser_t *abstract, double atmospheric, double hydrostatic) { reefnet_sensus_parser_t *parser = (reefnet_sensus_parser_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; parser->atmospheric = atmospheric; parser->hydrostatic = hydrostatic; return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensus_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { reefnet_sensus_parser_t *parser = (reefnet_sensus_parser_t *) abstract; if (abstract->size < 2 + 4) return DC_STATUS_DATAFORMAT; unsigned int timestamp = array_uint32_le (abstract->data + 2); dc_ticks_t ticks = parser->systime - (parser->devtime - timestamp); if (!dc_datetime_localtime (datetime, ticks)) return DC_STATUS_DATAFORMAT; return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensus_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { reefnet_sensus_parser_t *parser = (reefnet_sensus_parser_t *) abstract; if (abstract->size < 7) return DC_STATUS_DATAFORMAT; if (!parser->cached) { const unsigned char *data = abstract->data; unsigned int size = abstract->size; unsigned int maxdepth = 0; unsigned int interval = data[1]; unsigned int nsamples = 0, count = 0; unsigned int offset = 7; while (offset + 1 <= size) { // Depth. unsigned int depth = data[offset++]; if (depth > maxdepth) maxdepth = depth; // Skip temperature byte. if ((nsamples % 6) == 0) offset++; // Current sample is complete. nsamples++; // The end of a dive is reached when 17 consecutive // depth samples of less than 3 feet have been found. if (depth < SAMPLE_DEPTH_ADJUST + 3) { count++; if (count == 17) { break; } } else { count = 0; } } parser->cached = 1; parser->divetime = nsamples * interval; parser->maxdepth = maxdepth; } if (value) { switch (type) { case DC_FIELD_DIVETIME: *((unsigned int *) value) = parser->divetime; break; case DC_FIELD_MAXDEPTH: *((double *) value) = ((parser->maxdepth + 33.0 - (double) SAMPLE_DEPTH_ADJUST) * FSW - parser->atmospheric) / parser->hydrostatic; break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = 0; break; case DC_FIELD_DIVEMODE: *((dc_divemode_t *) value) = DC_DIVEMODE_GAUGE; break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensus_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { reefnet_sensus_parser_t *parser = (reefnet_sensus_parser_t*) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; unsigned int offset = 0; while (offset + 7 <= size) { if (data[offset] == 0xFF && data[offset + 6] == 0xFE) { unsigned int time = 0; unsigned int interval = data[offset + 1]; unsigned int nsamples = 0, count = 0; offset += 7; while (offset + 1 <= size) { dc_sample_value_t sample = {0}; // Time (seconds) time += interval; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Depth (adjusted feet of seawater). unsigned int depth = data[offset++]; sample.depth = ((depth + 33.0 - (double) SAMPLE_DEPTH_ADJUST) * FSW - parser->atmospheric) / parser->hydrostatic; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); // Temperature (degrees Fahrenheit) if ((nsamples % 6) == 0) { if (offset + 1 > size) return DC_STATUS_DATAFORMAT; unsigned int temperature = data[offset++]; sample.temperature = (temperature - 32.0) * (5.0 / 9.0); if (callback) callback (DC_SAMPLE_TEMPERATURE, sample, userdata); } // Current sample is complete. nsamples++; // The end of a dive is reached when 17 consecutive // depth samples of less than 3 feet have been found. if (depth < SAMPLE_DEPTH_ADJUST + 3) { count++; if (count == 17) { break; } } else { count = 0; } } break; } else { offset++; } } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/reefnet_sensus_parser.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <string.h> // memcmp #include <libdivecomputer/units.h> #include "uwatec_smart.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_parser_isinstance((parser), &uwatec_smart_parser_vtable) #define C_ARRAY_SIZE(array) (sizeof (array) / sizeof *(array)) #define NBITS 8 #define SMARTPRO 0x10 #define GALILEO 0x11 #define ALADINTEC 0x12 #define ALADINTEC2G 0x13 #define SMARTCOM 0x14 #define ALADIN2G 0x15 #define ALADINSPORTMATRIX 0x17 #define SMARTTEC 0x18 #define GALILEOTRIMIX 0x19 #define SMARTZ 0x1C #define MERIDIAN 0x20 #define ALADINSQUARE 0x22 #define CHROMIS 0x24 #define MANTIS2 0x26 #define G2 0x32 #define UNSUPPORTED 0xFFFFFFFF #define NEVENTS 3 #define NGASMIXES 10 #define HEADER 1 #define PROFILE 2 #define FRESH 1.000 #define SALT 1.025 #define FREEDIVE 0x00000080 #define GAUGE 0x00001000 #define SALINITY 0x00100000 #define EPOCH 946684800 // 2000-01-01 00:00:00 UTC typedef enum { PRESSURE_DEPTH, RBT, TEMPERATURE, PRESSURE, DEPTH, HEARTRATE, BEARING, ALARMS, TIME, APNEA, MISC, } uwatec_smart_sample_t; typedef enum { EV_WARNING, /* Warning (yellow buzzer) */ EV_ALARM, /* Alarm (red buzzer) */ EV_WORKLOAD, /* Workload */ EV_WORKLOAD_WARNING, /* Increased workload (lung symbol) */ EV_BOOKMARK, /* Bookmark / safety stop timer started */ EV_GASMIX, /* Active gasmix */ EV_UNKNOWN, } uwatec_smart_event_t; typedef struct uwatec_smart_header_info_t { unsigned int maxdepth; unsigned int divetime; unsigned int gasmix; unsigned int ngases; unsigned int temp_minimum; unsigned int temp_maximum; unsigned int temp_surface; unsigned int tankpressure; unsigned int timezone; unsigned int settings; } uwatec_smart_header_info_t; typedef struct uwatec_smart_sample_info_t { uwatec_smart_sample_t type; unsigned int absolute; unsigned int index; unsigned int ntypebits; unsigned int ignoretype; unsigned int extrabytes; } uwatec_smart_sample_info_t; typedef struct uwatec_smart_event_info_t { uwatec_smart_event_t type; unsigned int mask; unsigned int shift; } uwatec_smart_event_info_t; typedef struct uwatec_smart_gasmix_t { unsigned int id; unsigned int oxygen; unsigned int helium; } uwatec_smart_gasmix_t; typedef struct uwatec_smart_tank_t { unsigned int id; unsigned int beginpressure; unsigned int endpressure; unsigned int gasmix; } uwatec_smart_tank_t; typedef struct uwatec_smart_parser_t uwatec_smart_parser_t; struct uwatec_smart_parser_t { dc_parser_t base; unsigned int model; unsigned int devtime; dc_ticks_t systime; const uwatec_smart_sample_info_t *samples; const uwatec_smart_header_info_t *header; unsigned int headersize; unsigned int nsamples; const uwatec_smart_event_info_t *events[NEVENTS]; unsigned int nevents[NEVENTS]; unsigned int trimix; // Cached fields. unsigned int cached; unsigned int ngasmixes; uwatec_smart_gasmix_t gasmix[NGASMIXES]; unsigned int ntanks; uwatec_smart_tank_t tank[NGASMIXES]; dc_water_t watertype; dc_divemode_t divemode; }; static dc_status_t uwatec_smart_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t uwatec_smart_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t uwatec_smart_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t uwatec_smart_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static dc_status_t uwatec_smart_parse (uwatec_smart_parser_t *parser, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t uwatec_smart_parser_vtable = { sizeof(uwatec_smart_parser_t), DC_FAMILY_UWATEC_SMART, uwatec_smart_parser_set_data, /* set_data */ uwatec_smart_parser_get_datetime, /* datetime */ uwatec_smart_parser_get_field, /* fields */ uwatec_smart_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; static const uwatec_smart_header_info_t uwatec_smart_pro_header = { 18, 20, 24, 1, 22, /* temp_minimum */ UNSUPPORTED, /* temp_maximum */ UNSUPPORTED, /* temp_surface */ UNSUPPORTED, /* tankpressure */ UNSUPPORTED, /* timezone */ UNSUPPORTED, /* settings */ }; static const uwatec_smart_header_info_t uwatec_smart_galileo_header = { 22, 26, 44, 3, 30, /* temp_minimum */ 28, /* temp_maximum */ 32, /* temp_surface */ 50, /* tankpressure */ 16, /* timezone */ 92, /* settings */ }; static const uwatec_smart_header_info_t uwatec_smart_trimix_header = { 22, /* maxdepth */ 26, /* divetime */ UNSUPPORTED, 0, /* gasmixes */ 30, /* temp_minimum */ 28, /* temp_maximum */ 32, /* temp_surface */ UNSUPPORTED, /* tankpressure */ 16, /* timezone */ 68, /* settings */ }; static const uwatec_smart_header_info_t uwatec_smart_aladin_tec_header = { 22, 24, 30, 1, 26, /* temp_minimum */ 28, /* temp_maximum */ 32, /* temp_surface */ UNSUPPORTED, /* tankpressure */ 16, /* timezone */ 52, /* settings */ }; static const uwatec_smart_header_info_t uwatec_smart_aladin_tec2g_header = { 22, 26, 34, 3, 30, /* temp_minimum */ 28, /* temp_maximum */ 32, /* temp_surface */ UNSUPPORTED, /* tankpressure */ 16, /* timezone */ 60, /* settings */ }; static const uwatec_smart_header_info_t uwatec_smart_com_header = { 18, 20, 24, 1, 22, /* temp_minimum */ UNSUPPORTED, /* temp_maximum */ UNSUPPORTED, /* temp_surface */ 30, /* tankpressure */ UNSUPPORTED, /* timezone */ UNSUPPORTED, /* settings */ }; static const uwatec_smart_header_info_t uwatec_smart_tec_header = { 18, 20, 28, 3, 22, /* temp_minimum */ UNSUPPORTED, /* temp_maximum */ UNSUPPORTED, /* temp_surface */ 34, /* tankpressure */ UNSUPPORTED, /* timezone */ UNSUPPORTED, /* settings */ }; static const uwatec_smart_sample_info_t uwatec_smart_pro_samples[] = { {DEPTH, 0, 0, 1, 0, 0}, // 0ddddddd {TEMPERATURE, 0, 0, 2, 0, 0}, // 10dddddd {TIME, 1, 0, 3, 0, 0}, // 110ddddd {ALARMS, 1, 0, 4, 0, 0}, // 1110dddd {DEPTH, 0, 0, 5, 0, 1}, // 11110ddd dddddddd {TEMPERATURE, 0, 0, 6, 0, 1}, // 111110dd dddddddd {DEPTH, 1, 0, 7, 1, 2}, // 1111110d dddddddd dddddddd {TEMPERATURE, 1, 0, 8, 0, 2}, // 11111110 dddddddd dddddddd }; static const uwatec_smart_sample_info_t uwatec_smart_galileo_samples[] = { {DEPTH, 0, 0, 1, 0, 0}, // 0ddd dddd {RBT, 0, 0, 3, 0, 0}, // 100d dddd {PRESSURE, 0, 0, 4, 0, 0}, // 1010 dddd {TEMPERATURE, 0, 0, 4, 0, 0}, // 1011 dddd {TIME, 1, 0, 4, 0, 0}, // 1100 dddd {HEARTRATE, 0, 0, 4, 0, 0}, // 1101 dddd {ALARMS, 1, 0, 4, 0, 0}, // 1110 dddd {ALARMS, 1, 1, 8, 0, 1}, // 1111 0000 dddddddd {DEPTH, 1, 0, 8, 0, 2}, // 1111 0001 dddddddd dddddddd {RBT, 1, 0, 8, 0, 1}, // 1111 0010 dddddddd {TEMPERATURE, 1, 0, 8, 0, 2}, // 1111 0011 dddddddd dddddddd {PRESSURE, 1, 0, 8, 0, 2}, // 1111 0100 dddddddd dddddddd {PRESSURE, 1, 1, 8, 0, 2}, // 1111 0101 dddddddd dddddddd {PRESSURE, 1, 2, 8, 0, 2}, // 1111 0110 dddddddd dddddddd {HEARTRATE, 1, 0, 8, 0, 1}, // 1111 0111 dddddddd {BEARING, 1, 0, 8, 0, 2}, // 1111 1000 dddddddd dddddddd {ALARMS, 1, 2, 8, 0, 1}, // 1111 1001 dddddddd {APNEA, 1, 0, 8, 0, 0}, // 1111 1010 (8 bytes) {MISC, 1, 0, 8, 0, 1}, // 1111 1011 dddddddd (n-1 bytes) }; static const uwatec_smart_sample_info_t uwatec_smart_aladin_samples[] = { {DEPTH, 0, 0, 1, 0, 0}, // 0ddddddd {TEMPERATURE, 0, 0, 2, 0, 0}, // 10dddddd {TIME, 1, 0, 3, 0, 0}, // 110ddddd {ALARMS, 1, 0, 4, 0, 0}, // 1110dddd {DEPTH, 0, 0, 5, 0, 1}, // 11110ddd dddddddd {TEMPERATURE, 0, 0, 6, 0, 1}, // 111110dd dddddddd {DEPTH, 1, 0, 7, 1, 2}, // 1111110d dddddddd dddddddd {TEMPERATURE, 1, 0, 8, 0, 2}, // 11111110 dddddddd dddddddd {ALARMS, 1, 1, 9, 0, 0}, // 11111111 0ddddddd }; static const uwatec_smart_sample_info_t uwatec_smart_com_samples[] = { {PRESSURE_DEPTH, 0, 0, 1, 0, 1}, // 0ddddddd dddddddd {RBT, 0, 0, 2, 0, 0}, // 10dddddd {TEMPERATURE, 0, 0, 3, 0, 0}, // 110ddddd {PRESSURE, 0, 0, 4, 0, 1}, // 1110dddd dddddddd {DEPTH, 0, 0, 5, 0, 1}, // 11110ddd dddddddd {TEMPERATURE, 0, 0, 6, 0, 1}, // 111110dd dddddddd {ALARMS, 1, 0, 7, 1, 1}, // 1111110d dddddddd {TIME, 1, 0, 8, 0, 1}, // 11111110 dddddddd {DEPTH, 1, 0, 9, 1, 2}, // 11111111 0ddddddd dddddddd dddddddd {PRESSURE, 1, 0, 10, 1, 2}, // 11111111 10dddddd dddddddd dddddddd {TEMPERATURE, 1, 0, 11, 1, 2}, // 11111111 110ddddd dddddddd dddddddd {RBT, 1, 0, 12, 1, 1}, // 11111111 1110dddd dddddddd }; static const uwatec_smart_sample_info_t uwatec_smart_tec_samples[] = { {PRESSURE_DEPTH, 0, 0, 1, 0, 1}, // 0ddddddd dddddddd {RBT, 0, 0, 2, 0, 0}, // 10dddddd {TEMPERATURE, 0, 0, 3, 0, 0}, // 110ddddd {PRESSURE, 0, 0, 4, 0, 1}, // 1110dddd dddddddd {DEPTH, 0, 0, 5, 0, 1}, // 11110ddd dddddddd {TEMPERATURE, 0, 0, 6, 0, 1}, // 111110dd dddddddd {ALARMS, 1, 0, 7, 1, 1}, // 1111110d dddddddd {TIME, 1, 0, 8, 0, 1}, // 11111110 dddddddd {DEPTH, 1, 0, 9, 1, 2}, // 11111111 0ddddddd dddddddd dddddddd {TEMPERATURE, 1, 0, 10, 1, 2}, // 11111111 10dddddd dddddddd dddddddd {PRESSURE, 1, 0, 11, 1, 2}, // 11111111 110ddddd dddddddd dddddddd {PRESSURE, 1, 1, 12, 1, 2}, // 11111111 1110dddd dddddddd dddddddd {PRESSURE, 1, 2, 13, 1, 2}, // 11111111 11110ddd dddddddd dddddddd {RBT, 1, 0, 14, 1, 1}, // 11111111 111110dd dddddddd }; static const uwatec_smart_event_info_t uwatec_smart_tec_events_0[] = { {EV_WARNING, 0x01, 0}, {EV_ALARM, 0x02, 1}, {EV_WORKLOAD_WARNING, 0x04, 2}, {EV_WORKLOAD, 0x38, 3}, {EV_UNKNOWN, 0xC0, 6}, }; static const uwatec_smart_event_info_t uwatec_smart_aladintec_events_0[] = { {EV_WARNING, 0x01, 0}, {EV_ALARM, 0x02, 1}, {EV_BOOKMARK, 0x04, 2}, {EV_UNKNOWN, 0x08, 3}, }; static const uwatec_smart_event_info_t uwatec_smart_aladintec2g_events_0[] = { {EV_WARNING, 0x01, 0}, {EV_ALARM, 0x02, 1}, {EV_BOOKMARK, 0x04, 2}, {EV_UNKNOWN, 0x08, 3}, }; static const uwatec_smart_event_info_t uwatec_smart_aladintec2g_events_1[] = { {EV_UNKNOWN, 0x07, 0}, {EV_GASMIX, 0x18, 3}, }; static const uwatec_smart_event_info_t uwatec_smart_galileo_events_0[] = { {EV_WARNING, 0x01, 0}, {EV_ALARM, 0x02, 1}, {EV_WORKLOAD_WARNING, 0x04, 2}, {EV_BOOKMARK, 0x08, 3}, }; static const uwatec_smart_event_info_t uwatec_smart_galileo_events_1[] = { {EV_WORKLOAD, 0x07, 0}, {EV_UNKNOWN, 0x18, 3}, {EV_GASMIX, 0x60, 5}, {EV_UNKNOWN, 0x80, 7}, }; static const uwatec_smart_event_info_t uwatec_smart_galileo_events_2[] = { {EV_UNKNOWN, 0xFF, 0}, }; static const uwatec_smart_event_info_t uwatec_smart_trimix_events_2[] = { {EV_UNKNOWN, 0x0F, 0}, {EV_GASMIX, 0xF0, 4}, }; static unsigned int uwatec_smart_find_gasmix (uwatec_smart_parser_t *parser, unsigned int id) { unsigned int i = 0; while (i < parser->ngasmixes) { if (id == parser->gasmix[i].id) break; i++; } return i; } static unsigned int uwatec_smart_find_tank (uwatec_smart_parser_t *parser, unsigned int id) { unsigned int i = 0; while (i < parser->ntanks) { if (id == parser->tank[i].id) break; i++; } return i; } static dc_status_t uwatec_smart_parser_cache (uwatec_smart_parser_t *parser) { const unsigned char *data = parser->base.data; unsigned int size = parser->base.size; if (parser->cached) { return DC_STATUS_SUCCESS; } if (parser->model == GALILEO || parser->model == GALILEOTRIMIX) { if (size < 44) return DC_STATUS_DATAFORMAT; if (data[43] & 0x80) { parser->trimix = 1; parser->headersize = 84; parser->header = &uwatec_smart_trimix_header; parser->events[2] = uwatec_smart_trimix_events_2; parser->nevents[2] = C_ARRAY_SIZE (uwatec_smart_trimix_events_2); } else { parser->trimix = 0; parser->headersize = 152; parser->header = &uwatec_smart_galileo_header; parser->events[2] = uwatec_smart_galileo_events_2; parser->nevents[2] = C_ARRAY_SIZE (uwatec_smart_galileo_events_2); } } const uwatec_smart_header_info_t *header = parser->header; // Get the settings. dc_divemode_t divemode = DC_DIVEMODE_OC; dc_water_t watertype = DC_WATER_FRESH; if (header->settings != UNSUPPORTED) { unsigned int settings = array_uint32_le (data + header->settings); // Get the freedive/gauge bits. unsigned int freedive = 0; unsigned int gauge = (settings & GAUGE) != 0; if (parser->model != ALADINTEC && parser->model != ALADINTEC2G) { freedive = (settings & FREEDIVE) != 0; } // Get the dive mode. The freedive bit needs to be checked // first, because freedives have both the freedive and gauge // bits set. if (freedive) { divemode = DC_DIVEMODE_FREEDIVE; } else if (gauge) { divemode = DC_DIVEMODE_GAUGE; } else { divemode = DC_DIVEMODE_OC; } // Get the water type. if (settings & SALINITY) { watertype = DC_WATER_SALT; } } // Get the gas mixes and tanks. unsigned int ntanks = 0; unsigned int ngasmixes = 0; uwatec_smart_tank_t tank[NGASMIXES] = {{0}}; uwatec_smart_gasmix_t gasmix[NGASMIXES] = {{0}}; if (header->gasmix != UNSUPPORTED) { for (unsigned int i = 0; i < header->ngases; ++i) { unsigned int idx = DC_GASMIX_UNKNOWN; unsigned int o2 = 0; if (parser->model == ALADINTEC2G) { o2 = data[header->gasmix + i]; } else { o2 = array_uint16_le (data + header->gasmix + i * 2); } if (o2 != 0) { idx = ngasmixes; gasmix[ngasmixes].id = i; gasmix[ngasmixes].oxygen = o2; gasmix[ngasmixes].helium = 0; ngasmixes++; } unsigned int beginpressure = 0; unsigned int endpressure = 0; if (header->tankpressure != UNSUPPORTED && divemode != DC_DIVEMODE_FREEDIVE) { if (parser->model == GALILEO || parser->model == GALILEOTRIMIX || parser->model == ALADIN2G || parser->model == MERIDIAN || parser->model == CHROMIS || parser->model == MANTIS2 || parser->model == G2 || parser->model == ALADINSPORTMATRIX || parser->model == ALADINSQUARE) { unsigned int offset = header->tankpressure + 2 * i; endpressure = array_uint16_le(data + offset); beginpressure = array_uint16_le(data + offset + 2 * header->ngases); } else { unsigned int offset = header->tankpressure + 4 * i; beginpressure = array_uint16_le(data + offset); endpressure = array_uint16_le(data + offset + 2); } } if ((beginpressure != 0 || endpressure != 0) && (beginpressure != 0xFFFF) && (endpressure != 0xFFFF)) { tank[ntanks].id = i; tank[ntanks].beginpressure = beginpressure; tank[ntanks].endpressure = endpressure; tank[ntanks].gasmix = idx; ntanks++; } } } // Cache the data for later use. parser->ngasmixes = ngasmixes; for (unsigned int i = 0; i < ngasmixes; ++i) { parser->gasmix[i] = gasmix[i]; } parser->ntanks = ntanks; for (unsigned int i = 0; i < ntanks; ++i) { parser->tank[i] = tank[i]; } parser->watertype = watertype; parser->divemode = divemode; parser->cached = HEADER; return DC_STATUS_SUCCESS; } dc_status_t uwatec_smart_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int model, unsigned int devtime, dc_ticks_t systime) { dc_status_t status = DC_STATUS_SUCCESS; uwatec_smart_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (uwatec_smart_parser_t *) dc_parser_allocate (context, &uwatec_smart_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. parser->model = model; parser->devtime = devtime; parser->systime = systime; parser->trimix = 0; for (unsigned int i = 0; i < NEVENTS; ++i) { parser->events[i] = NULL; parser->nevents[i] = 0; } switch (model) { case SMARTPRO: parser->headersize = 92; parser->header = &uwatec_smart_pro_header; parser->samples = uwatec_smart_pro_samples; parser->nsamples = C_ARRAY_SIZE (uwatec_smart_pro_samples); parser->events[0] = uwatec_smart_tec_events_0; parser->nevents[0] = C_ARRAY_SIZE (uwatec_smart_tec_events_0); break; case GALILEO: case GALILEOTRIMIX: case ALADIN2G: case MERIDIAN: case CHROMIS: case MANTIS2: case ALADINSQUARE: parser->headersize = 152; parser->header = &uwatec_smart_galileo_header; parser->samples = uwatec_smart_galileo_samples; parser->nsamples = C_ARRAY_SIZE (uwatec_smart_galileo_samples); parser->events[0] = uwatec_smart_galileo_events_0; parser->events[1] = uwatec_smart_galileo_events_1; parser->events[2] = uwatec_smart_galileo_events_2; parser->nevents[0] = C_ARRAY_SIZE (uwatec_smart_galileo_events_0); parser->nevents[1] = C_ARRAY_SIZE (uwatec_smart_galileo_events_1); parser->nevents[2] = C_ARRAY_SIZE (uwatec_smart_galileo_events_2); break; case G2: case ALADINSPORTMATRIX: parser->headersize = 84; parser->header = &uwatec_smart_trimix_header; parser->samples = uwatec_smart_galileo_samples; parser->nsamples = C_ARRAY_SIZE (uwatec_smart_galileo_samples); parser->events[0] = uwatec_smart_galileo_events_0; parser->events[1] = uwatec_smart_galileo_events_1; parser->events[2] = uwatec_smart_trimix_events_2; parser->nevents[0] = C_ARRAY_SIZE (uwatec_smart_galileo_events_0); parser->nevents[1] = C_ARRAY_SIZE (uwatec_smart_galileo_events_1); parser->nevents[2] = C_ARRAY_SIZE (uwatec_smart_trimix_events_2); parser->trimix = 1; break; case ALADINTEC: parser->headersize = 108; parser->header = &uwatec_smart_aladin_tec_header; parser->samples = uwatec_smart_aladin_samples; parser->nsamples = C_ARRAY_SIZE (uwatec_smart_aladin_samples); parser->events[0] = uwatec_smart_aladintec_events_0; parser->nevents[0] = C_ARRAY_SIZE (uwatec_smart_aladintec_events_0); break; case ALADINTEC2G: parser->headersize = 116; parser->header = &uwatec_smart_aladin_tec2g_header; parser->samples = uwatec_smart_aladin_samples; parser->nsamples = C_ARRAY_SIZE (uwatec_smart_aladin_samples); parser->events[0] = uwatec_smart_aladintec2g_events_0; parser->events[1] = uwatec_smart_aladintec2g_events_1; parser->nevents[0] = C_ARRAY_SIZE (uwatec_smart_aladintec2g_events_0); parser->nevents[1] = C_ARRAY_SIZE (uwatec_smart_aladintec2g_events_1); break; case SMARTCOM: parser->headersize = 100; parser->header = &uwatec_smart_com_header; parser->samples = uwatec_smart_com_samples; parser->nsamples = C_ARRAY_SIZE (uwatec_smart_com_samples); parser->events[0] = uwatec_smart_tec_events_0; parser->nevents[0] = C_ARRAY_SIZE (uwatec_smart_tec_events_0); break; case SMARTTEC: case SMARTZ: parser->headersize = 132; parser->header = &uwatec_smart_tec_header; parser->samples = uwatec_smart_tec_samples; parser->nsamples = C_ARRAY_SIZE (uwatec_smart_tec_samples); parser->events[0] = uwatec_smart_tec_events_0; parser->nevents[0] = C_ARRAY_SIZE (uwatec_smart_tec_events_0); break; default: status = DC_STATUS_INVALIDARGS; goto error_free; } parser->cached = 0; parser->ngasmixes = 0; parser->ntanks = 0; for (unsigned int i = 0; i < NGASMIXES; ++i) { parser->gasmix[i].id = 0; parser->gasmix[i].oxygen = 0; parser->gasmix[i].helium = 0; parser->tank[i].id = 0; parser->tank[i].beginpressure = 0; parser->tank[i].endpressure = 0; parser->tank[i].gasmix = 0; } parser->watertype = DC_WATER_FRESH; parser->divemode = DC_DIVEMODE_OC; *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; error_free: dc_parser_deallocate ((dc_parser_t *) parser); return status; } static dc_status_t uwatec_smart_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { uwatec_smart_parser_t *parser = (uwatec_smart_parser_t *) abstract; // Reset the cache. parser->cached = 0; parser->ngasmixes = 0; parser->ntanks = 0; for (unsigned int i = 0; i < NGASMIXES; ++i) { parser->gasmix[i].id = 0; parser->gasmix[i].oxygen = 0; parser->gasmix[i].helium = 0; parser->tank[i].id = 0; parser->tank[i].beginpressure = 0; parser->tank[i].endpressure = 0; parser->tank[i].gasmix = 0; } parser->watertype = DC_WATER_FRESH; parser->divemode = DC_DIVEMODE_OC; return DC_STATUS_SUCCESS; } static dc_status_t uwatec_smart_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { uwatec_smart_parser_t *parser = (uwatec_smart_parser_t *) abstract; const uwatec_smart_header_info_t *table = parser->header; const unsigned char *data = abstract->data; if (abstract->size < parser->headersize) return DC_STATUS_DATAFORMAT; unsigned int timestamp = array_uint32_le (abstract->data + 8); dc_ticks_t ticks = EPOCH + timestamp / 2; if (table->timezone != UNSUPPORTED) { // For devices with timezone support, the UTC offset of the // device is used. The UTC offset is stored in units of 15 // minutes (or 900 seconds). int utc_offset = (signed char) data[table->timezone]; ticks += utc_offset * 900; if (!dc_datetime_gmtime (datetime, ticks)) return DC_STATUS_DATAFORMAT; datetime->timezone = utc_offset * 900; } else { // For devices without timezone support, the current timezone of // the host system is used. if (!dc_datetime_localtime (datetime, ticks)) return DC_STATUS_DATAFORMAT; } return DC_STATUS_SUCCESS; } static dc_status_t uwatec_smart_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { uwatec_smart_parser_t *parser = (uwatec_smart_parser_t *) abstract; // Cache the parser data. dc_status_t rc = uwatec_smart_parser_cache (parser); if (rc != DC_STATUS_SUCCESS) return rc; // Cache the profile data. if (parser->cached < PROFILE) { rc = uwatec_smart_parse (parser, NULL, NULL); if (rc != DC_STATUS_SUCCESS) return rc; } const uwatec_smart_header_info_t *table = parser->header; const unsigned char *data = abstract->data; double salinity = (parser->watertype == DC_WATER_SALT ? SALT : FRESH); dc_gasmix_t *gasmix = (dc_gasmix_t *) value; dc_tank_t *tank = (dc_tank_t *) value; dc_salinity_t *water = (dc_salinity_t *) value; if (value) { switch (type) { case DC_FIELD_DIVETIME: *((unsigned int *) value) = array_uint16_le (data + table->divetime) * 60; break; case DC_FIELD_MAXDEPTH: *((double *) value) = array_uint16_le (data + table->maxdepth) / 100.0 / salinity; break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = parser->ngasmixes; break; case DC_FIELD_GASMIX: gasmix->helium = parser->gasmix[flags].helium / 100.0; gasmix->oxygen = parser->gasmix[flags].oxygen / 100.0; gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium; break; case DC_FIELD_TANK_COUNT: *((unsigned int *) value) = parser->ntanks; break; case DC_FIELD_TANK: tank->type = DC_TANKVOLUME_NONE; tank->volume = 0.0; tank->workpressure = 0.0; tank->beginpressure = parser->tank[flags].beginpressure / 128.0; tank->endpressure = parser->tank[flags].endpressure / 128.0; tank->gasmix = parser->tank[flags].gasmix; break; case DC_FIELD_TEMPERATURE_MINIMUM: *((double *) value) = (signed short) array_uint16_le (data + table->temp_minimum) / 10.0; break; case DC_FIELD_TEMPERATURE_MAXIMUM: if (table->temp_maximum == UNSUPPORTED) return DC_STATUS_UNSUPPORTED; *((double *) value) = (signed short) array_uint16_le (data + table->temp_maximum) / 10.0; break; case DC_FIELD_TEMPERATURE_SURFACE: if (table->temp_surface == UNSUPPORTED) return DC_STATUS_UNSUPPORTED; *((double *) value) = (signed short) array_uint16_le (data + table->temp_surface) / 10.0; break; case DC_FIELD_DIVEMODE: if (table->settings == UNSUPPORTED) return DC_STATUS_UNSUPPORTED; *((dc_divemode_t *) value) = parser->divemode; break; case DC_FIELD_SALINITY: if (table->settings == UNSUPPORTED) return DC_STATUS_UNSUPPORTED; water->type = parser->watertype; water->density = salinity * 1000.0; break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static unsigned int uwatec_smart_identify (const unsigned char data[], unsigned int size) { unsigned int count = 0; for (unsigned int i = 0; i < size; ++i) { unsigned char value = data[i]; for (unsigned int j = 0; j < NBITS; ++j) { unsigned char mask = 1 << (NBITS - 1 - j); if ((value & mask) == 0) return count; count++; } } return (unsigned int) -1; } static unsigned int uwatec_galileo_identify (unsigned char value) { // Bits: 0ddd dddd if ((value & 0x80) == 0) return 0; // Bits: 100d dddd if ((value & 0xE0) == 0x80) return 1; // Bits: 1XXX dddd if ((value & 0xF0) != 0xF0) return (value & 0x70) >> 4; // Bits: 1111 XXXX return (value & 0x0F) + 7; } static unsigned int uwatec_smart_fixsignbit (unsigned int x, unsigned int n) { if (n <= 0 || n > 32) return 0; unsigned int signbit = (1 << (n - 1)); unsigned int mask = (signbit - 1); // When turning a two's-complement number with a certain number // of bits into one with more bits, the sign bit must be repeated // in all the extra bits. if ((x & signbit) == signbit) return x | ~mask; else return x & mask; } static dc_status_t uwatec_smart_parse (uwatec_smart_parser_t *parser, dc_sample_callback_t callback, void *userdata) { dc_parser_t *abstract = (dc_parser_t *) parser; const unsigned char *data = abstract->data; unsigned int size = abstract->size; const uwatec_smart_sample_info_t *table = parser->samples; unsigned int entries = parser->nsamples; // Get the maximum number of alarm bytes. unsigned int nalarms = 0; for (unsigned int i = 0; i < entries; ++i) { if (table[i].type == ALARMS && table[i].index >= nalarms) { nalarms = table[i].index + 1; } } int complete = 0; int calibrated = 0; unsigned int time = 0; unsigned int rbt = 99; unsigned int tank = 0; unsigned int gasmix = 0; double depth = 0, depth_calibration = 0; double temperature = 0; double pressure = 0; unsigned int heartrate = 0; unsigned int bearing = 0; unsigned int bookmark = 0; // Previous gas mix - initialize with impossible value unsigned int gasmix_previous = 0xFFFFFFFF; double salinity = (parser->watertype == DC_WATER_SALT ? SALT : FRESH); unsigned int interval = 4; if (parser->divemode == DC_DIVEMODE_FREEDIVE) { interval = 1; } int have_depth = 0, have_temperature = 0, have_pressure = 0, have_rbt = 0, have_heartrate = 0, have_bearing = 0; unsigned int offset = parser->headersize; while (offset < size) { dc_sample_value_t sample = {0}; // Process the type bits in the bitstream. unsigned int id = 0; if (parser->model == GALILEO || parser->model == GALILEOTRIMIX || parser->model == ALADIN2G || parser->model == MERIDIAN || parser->model == CHROMIS || parser->model == MANTIS2 || parser->model == G2 || parser->model == ALADINSPORTMATRIX || parser->model == ALADINSQUARE) { // Uwatec Galileo id = uwatec_galileo_identify (data[offset]); } else { // Uwatec Smart id = uwatec_smart_identify (data + offset, size - offset); } if (id >= entries) { ERROR (abstract->context, "Invalid type bits."); return DC_STATUS_DATAFORMAT; } // Skip the processed type bytes. offset += table[id].ntypebits / NBITS; // Process the remaining data bits. unsigned int nbits = 0; unsigned int value = 0; unsigned int n = table[id].ntypebits % NBITS; if (n > 0) { nbits = NBITS - n; value = data[offset] & (0xFF >> n); if (table[id].ignoretype) { // Ignore any data bits that are stored in // the last type byte for certain samples. nbits = 0; value = 0; } offset++; } // Check for buffer overflows. if (offset + table[id].extrabytes > size) { ERROR (abstract->context, "Incomplete sample data."); return DC_STATUS_DATAFORMAT; } // Process the extra data bytes. for (unsigned int i = 0; i < table[id].extrabytes; ++i) { nbits += NBITS; value <<= NBITS; value += data[offset]; offset++; } // Fix the sign bit. signed int svalue = uwatec_smart_fixsignbit (value, nbits); // Parse the value. unsigned int idx = 0; unsigned int subtype = 0; unsigned int nevents = 0; const uwatec_smart_event_info_t *events = NULL; switch (table[id].type) { case PRESSURE_DEPTH: pressure += ((signed char) ((svalue >> NBITS) & 0xFF)) / 4.0; depth += ((signed char) (svalue & 0xFF)) / 50.0; complete = 1; break; case RBT: if (table[id].absolute) { rbt = value; have_rbt = 1; } else { rbt += svalue; } break; case TEMPERATURE: if (table[id].absolute) { temperature = svalue / 2.5; have_temperature = 1; } else { temperature += svalue / 2.5; } break; case PRESSURE: if (table[id].absolute) { if (parser->trimix) { tank = (value & 0xF000) >> 12; pressure = (value & 0x0FFF) / 4.0; } else { tank = table[id].index; pressure = value / 4.0; } have_pressure = 1; gasmix = tank; } else { pressure += svalue / 4.0; } break; case DEPTH: if (table[id].absolute) { depth = value / 50.0; if (!calibrated) { calibrated = 1; depth_calibration = depth; } have_depth = 1; } else { depth += svalue / 50.0; } complete = 1; break; case HEARTRATE: if (table[id].absolute) { heartrate = value; have_heartrate = 1; } else { heartrate += svalue; } break; case BEARING: bearing = value; have_bearing = 1; break; case ALARMS: idx = table[id].index; if (idx >= NEVENTS || parser->events[idx] == NULL) { ERROR (abstract->context, "Unexpected event index."); return DC_STATUS_DATAFORMAT; } events = parser->events[idx]; nevents = parser->nevents[idx]; for (unsigned int i = 0; i < nevents; ++i) { uwatec_smart_event_t ev_type = events[i].type; unsigned int ev_value = (value & events[i].mask) >> events[i].shift; switch (ev_type) { case EV_BOOKMARK: bookmark = ev_value; break; case EV_GASMIX: gasmix = ev_value; break; default: break; } } break; case TIME: complete = value; break; case APNEA: if (offset + 8 > size) { ERROR (abstract->context, "Incomplete sample data."); return DC_STATUS_DATAFORMAT; } offset += 8; break; case MISC: if (value < 1 || offset + value - 1 > size) { ERROR (abstract->context, "Incomplete sample data."); return DC_STATUS_DATAFORMAT; } subtype = data[offset]; if (subtype >= 32 && subtype <= 41) { if (value < 16) { ERROR (abstract->context, "Incomplete sample data."); return DC_STATUS_DATAFORMAT; } unsigned int mixid = subtype - 32; unsigned int mixidx = DC_GASMIX_UNKNOWN; unsigned int o2 = array_uint16_le (data + offset + 1); unsigned int he = array_uint16_le (data + offset + 3); unsigned int beginpressure = array_uint16_le (data + offset + 5); unsigned int endpressure = array_uint16_le (data + offset + 7); if (o2 != 0 || he != 0) { idx = uwatec_smart_find_gasmix (parser, mixid); if (idx >= parser->ngasmixes) { if (idx >= NGASMIXES) { ERROR (abstract->context, "Maximum number of gas mixes reached."); return DC_STATUS_NOMEMORY; } parser->gasmix[idx].id = mixid; parser->gasmix[idx].oxygen = o2; parser->gasmix[idx].helium = he; parser->ngasmixes++; } mixidx = idx; } if ((beginpressure != 0 || endpressure != 0) && (beginpressure != 0xFFFF) && (endpressure != 0xFFFF)) { idx = uwatec_smart_find_tank (parser, mixid); if (idx >= parser->ntanks) { if (idx >= NGASMIXES) { ERROR (abstract->context, "Maximum number of tanks reached."); return DC_STATUS_NOMEMORY; } parser->tank[idx].id = mixid; parser->tank[idx].beginpressure = beginpressure; parser->tank[idx].endpressure = endpressure; parser->tank[idx].gasmix = mixidx; parser->ntanks++; } } } offset += value - 1; break; default: WARNING (abstract->context, "Unknown sample type."); break; } while (complete) { sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); if (parser->ngasmixes && gasmix != gasmix_previous) { idx = uwatec_smart_find_gasmix (parser, gasmix); if (idx >= parser->ngasmixes) { ERROR (abstract->context, "Invalid gas mix index."); return DC_STATUS_DATAFORMAT; } sample.gasmix = idx; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); gasmix_previous = gasmix; } if (have_temperature) { sample.temperature = temperature; if (callback) callback (DC_SAMPLE_TEMPERATURE, sample, userdata); } if (bookmark) { sample.event.type = SAMPLE_EVENT_BOOKMARK; sample.event.time = 0; sample.event.flags = 0; sample.event.value = 0; if (callback) callback (DC_SAMPLE_EVENT, sample, userdata); } if (have_rbt || have_pressure) { sample.rbt = rbt; if (callback) callback (DC_SAMPLE_RBT, sample, userdata); } if (have_pressure) { idx = uwatec_smart_find_tank(parser, tank); if (idx < parser->ntanks) { sample.pressure.tank = idx; sample.pressure.value = pressure; if (callback) callback (DC_SAMPLE_PRESSURE, sample, userdata); } } if (have_heartrate) { sample.heartbeat = heartrate; if (callback) callback (DC_SAMPLE_HEARTBEAT, sample, userdata); } if (have_bearing) { sample.bearing = bearing; if (callback) callback (DC_SAMPLE_BEARING, sample, userdata); have_bearing = 0; } if (have_depth) { sample.depth = (depth - depth_calibration) / salinity; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); } time += interval; complete--; } } parser->cached = PROFILE; return DC_STATUS_SUCCESS; } static dc_status_t uwatec_smart_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { uwatec_smart_parser_t *parser = (uwatec_smart_parser_t *) abstract; // Cache the parser data. dc_status_t rc = uwatec_smart_parser_cache (parser); if (rc != DC_STATUS_SUCCESS) return rc; // Cache the profile data. if (parser->cached < PROFILE) { rc = uwatec_smart_parse (parser, NULL, NULL); if (rc != DC_STATUS_SUCCESS) return rc; } return uwatec_smart_parse (parser, callback, userdata); }
libdc-for-dirk-Subsurface-branch
src/uwatec_smart_parser.c
/* * libdivecomputer * * Copyright (C) 2012 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcmp, memcpy #include <stdlib.h> // malloc, free #include "hw_frog.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "checksum.h" #include "ringbuffer.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &hw_frog_device_vtable) #define SZ_DISPLAY 15 #define SZ_CUSTOMTEXT 13 #define SZ_VERSION (SZ_CUSTOMTEXT + 4) #define RB_LOGBOOK_SIZE 256 #define RB_LOGBOOK_COUNT 256 #define RB_PROFILE_BEGIN 0x000000 #define RB_PROFILE_END 0x200000 #define RB_PROFILE_DISTANCE(a,b) ringbuffer_distance (a, b, 0, RB_PROFILE_BEGIN, RB_PROFILE_END) #define READY 0x4D #define HEADER 0x61 #define CLOCK 0x62 #define CUSTOMTEXT 0x63 #define DIVE 0x66 #define IDENTITY 0x69 #define DISPLAY 0x6E #define INIT 0xBB #define EXIT 0xFF typedef struct hw_frog_device_t { dc_device_t base; dc_iostream_t *iostream; unsigned char fingerprint[5]; } hw_frog_device_t; static dc_status_t hw_frog_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t hw_frog_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t hw_frog_device_timesync (dc_device_t *abstract, const dc_datetime_t *datetime); static dc_status_t hw_frog_device_close (dc_device_t *abstract); static const dc_device_vtable_t hw_frog_device_vtable = { sizeof(hw_frog_device_t), DC_FAMILY_HW_FROG, hw_frog_device_set_fingerprint, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ NULL, /* dump */ hw_frog_device_foreach, /* foreach */ hw_frog_device_timesync, /* timesync */ hw_frog_device_close /* close */ }; static int hw_frog_strncpy (unsigned char *data, unsigned int size, const char *text) { // Check the maximum length. size_t length = (text ? strlen (text) : 0); if (length > size) { return -1; } // Copy the text. if (length) memcpy (data, text, length); // Pad with spaces. memset (data + length, 0x20, size - length); return 0; } static dc_status_t hw_frog_transfer (hw_frog_device_t *device, dc_event_progress_t *progress, unsigned char cmd, const unsigned char input[], unsigned int isize, unsigned char output[], unsigned int osize) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; // Send the command. unsigned char command[1] = {cmd}; status = dc_iostream_write (device->iostream, command, sizeof (command), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } if (cmd != INIT && cmd != HEADER) { // Read the echo. unsigned char answer[1] = {0}; status = dc_iostream_read (device->iostream, answer, sizeof (answer), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the echo."); return status; } // Verify the echo. if (memcmp (answer, command, sizeof (command)) != 0) { ERROR (abstract->context, "Unexpected echo."); return DC_STATUS_PROTOCOL; } } if (input) { // Send the input data packet. status = dc_iostream_write (device->iostream, input, isize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the data packet."); return status; } } if (output) { unsigned int nbytes = 0; while (nbytes < osize) { // Set the minimum packet size. unsigned int len = 1024; // Increase the packet size if more data is immediately available. size_t available = 0; status = dc_iostream_get_available (device->iostream, &available); if (status == DC_STATUS_SUCCESS && available > len) len = available; // Limit the packet size to the total size. if (nbytes + len > osize) len = osize - nbytes; // Read the packet. status = dc_iostream_read (device->iostream, output + nbytes, len, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Update and emit a progress event. if (progress) { progress->current += len; device_event_emit ((dc_device_t *) device, DC_EVENT_PROGRESS, progress); } nbytes += len; } } if (cmd != EXIT) { // Read the ready byte. unsigned char answer[1] = {0}; status = dc_iostream_read (device->iostream, answer, sizeof (answer), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the ready byte."); return status; } // Verify the ready byte. if (answer[0] != READY) { ERROR (abstract->context, "Unexpected ready byte."); return DC_STATUS_PROTOCOL; } } return DC_STATUS_SUCCESS; } dc_status_t hw_frog_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; hw_frog_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (hw_frog_device_t *) dc_device_allocate (context, &hw_frog_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; memset (device->fingerprint, 0, sizeof (device->fingerprint)); // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (115200 8N1). status = dc_iostream_configure (device->iostream, 115200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (3000ms). status = dc_iostream_set_timeout (device->iostream, 3000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Make sure everything is in a sane state. dc_iostream_sleep (device->iostream, 300); dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); // Send the init command. status = hw_frog_transfer (device, NULL, INIT, NULL, 0, NULL, 0); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to send the command."); goto error_close; } *out = (dc_device_t *) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t hw_frog_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; hw_frog_device_t *device = (hw_frog_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Send the exit command. rc = hw_frog_transfer (device, NULL, EXIT, NULL, 0, NULL, 0); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); dc_status_set_error(&status, rc); } // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t hw_frog_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { hw_frog_device_t *device = (hw_frog_device_t *) abstract; if (size && size != sizeof (device->fingerprint)) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, sizeof (device->fingerprint)); else memset (device->fingerprint, 0, sizeof (device->fingerprint)); return DC_STATUS_SUCCESS; } dc_status_t hw_frog_device_version (dc_device_t *abstract, unsigned char data[], unsigned int size) { hw_frog_device_t *device = (hw_frog_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size != SZ_VERSION) return DC_STATUS_INVALIDARGS; // Send the command. dc_status_t rc = hw_frog_transfer (device, NULL, IDENTITY, NULL, 0, data, size); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; } static dc_status_t hw_frog_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { hw_frog_device_t *device = (hw_frog_device_t *) abstract; // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = (RB_LOGBOOK_SIZE * RB_LOGBOOK_COUNT) + (RB_PROFILE_END - RB_PROFILE_BEGIN); device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Download the version data. unsigned char id[SZ_VERSION] = {0}; dc_status_t rc = hw_frog_device_version (abstract, id, sizeof (id)); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the version."); return rc; } // Emit a device info event. dc_event_devinfo_t devinfo; devinfo.model = 0; devinfo.firmware = array_uint16_be (id + 2); devinfo.serial = array_uint16_le (id + 0); device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); // Allocate memory. unsigned char *header = (unsigned char *) malloc (RB_LOGBOOK_SIZE * RB_LOGBOOK_COUNT); if (header == NULL) { ERROR (abstract->context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Download the logbook headers. rc = hw_frog_transfer (device, &progress, HEADER, NULL, 0, header, RB_LOGBOOK_SIZE * RB_LOGBOOK_COUNT); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the header."); free (header); return rc; } // Locate the most recent dive. // The device maintains an internal counter which is incremented for every // dive, and the current value at the time of the dive is stored in the // dive header. Thus the most recent dive will have the highest value. unsigned int count = 0; unsigned int latest = 0; unsigned int maximum = 0; for (unsigned int i = 0; i < RB_LOGBOOK_COUNT; ++i) { unsigned int offset = i * RB_LOGBOOK_SIZE; // Ignore uninitialized header entries. if (array_isequal (header + offset, RB_LOGBOOK_SIZE, 0xFF)) break; // Get the internal dive number. unsigned int current = array_uint16_le (header + offset + 52); if (current > maximum) { maximum = current; latest = i; } count++; } // Calculate the total and maximum size. unsigned int ndives = 0; unsigned int size = 0; unsigned int maxsize = 0; for (unsigned int i = 0; i < count; ++i) { unsigned int idx = (latest + RB_LOGBOOK_COUNT - i) % RB_LOGBOOK_COUNT; unsigned int offset = idx * RB_LOGBOOK_SIZE; // Get the ringbuffer pointers. unsigned int begin = array_uint24_le (header + offset + 2); unsigned int end = array_uint24_le (header + offset + 5); if (begin < RB_PROFILE_BEGIN || begin >= RB_PROFILE_END || end < RB_PROFILE_BEGIN || end >= RB_PROFILE_END) { ERROR (abstract->context, "Invalid ringbuffer pointer detected (0x%06x 0x%06x).", begin, end); free (header); return DC_STATUS_DATAFORMAT; } // Calculate the profile length. unsigned int length = RB_LOGBOOK_SIZE + RB_PROFILE_DISTANCE (begin, end) - 6; // Check the fingerprint data. if (memcmp (header + offset + 9, device->fingerprint, sizeof (device->fingerprint)) == 0) break; if (length > maxsize) maxsize = length; size += length; ndives++; } // Update and emit a progress event. progress.maximum = (RB_LOGBOOK_SIZE * RB_LOGBOOK_COUNT) + size; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Finish immediately if there are no dives available. if (ndives == 0) { free (header); return DC_STATUS_SUCCESS; } // Allocate enough memory for the largest dive. unsigned char *profile = (unsigned char *) malloc (maxsize); if (profile == NULL) { ERROR (abstract->context, "Failed to allocate memory."); free (header); return DC_STATUS_NOMEMORY; } // Download the dives. for (unsigned int i = 0; i < ndives; ++i) { unsigned int idx = (latest + RB_LOGBOOK_COUNT - i) % RB_LOGBOOK_COUNT; unsigned int offset = idx * RB_LOGBOOK_SIZE; // Get the ringbuffer pointers. unsigned int begin = array_uint24_le (header + offset + 2); unsigned int end = array_uint24_le (header + offset + 5); // Calculate the profile length. unsigned int length = RB_LOGBOOK_SIZE + RB_PROFILE_DISTANCE (begin, end) - 6; // Download the dive. unsigned char number[1] = {idx}; rc = hw_frog_transfer (device, &progress, DIVE, number, sizeof (number), profile, length); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the dive."); free (profile); free (header); return rc; } // Verify the header in the logbook and profile are identical. if (memcmp (profile, header + offset, RB_LOGBOOK_SIZE) != 0) { ERROR (abstract->context, "Unexpected profile header."); free (profile); free (header); return rc; } if (callback && !callback (profile, length, profile + 9, sizeof (device->fingerprint), userdata)) break; } free (profile); free (header); return DC_STATUS_SUCCESS; } static dc_status_t hw_frog_device_timesync (dc_device_t *abstract, const dc_datetime_t *datetime) { hw_frog_device_t *device = (hw_frog_device_t *) abstract; if (datetime == NULL) { ERROR (abstract->context, "Invalid parameter specified."); return DC_STATUS_INVALIDARGS; } // Send the command. unsigned char packet[6] = { datetime->hour, datetime->minute, datetime->second, datetime->month, datetime->day, datetime->year - 2000}; dc_status_t rc = hw_frog_transfer (device, NULL, CLOCK, packet, sizeof (packet), NULL, 0); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; } dc_status_t hw_frog_device_display (dc_device_t *abstract, const char *text) { hw_frog_device_t *device = (hw_frog_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; // Pad the data packet with spaces. unsigned char packet[SZ_DISPLAY] = {0}; if (hw_frog_strncpy (packet, sizeof (packet), text) != 0) { ERROR (abstract->context, "Invalid parameter specified."); return DC_STATUS_INVALIDARGS; } // Send the command. dc_status_t rc = hw_frog_transfer (device, NULL, DISPLAY, packet, sizeof (packet), NULL, 0); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; } dc_status_t hw_frog_device_customtext (dc_device_t *abstract, const char *text) { hw_frog_device_t *device = (hw_frog_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; // Pad the data packet with spaces. unsigned char packet[SZ_CUSTOMTEXT] = {0}; if (hw_frog_strncpy (packet, sizeof (packet), text) != 0) { ERROR (abstract->context, "Invalid parameter specified."); return DC_STATUS_INVALIDARGS; } // Send the command. dc_status_t rc = hw_frog_transfer (device, NULL, CUSTOMTEXT, packet, sizeof (packet), NULL, 0); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/hw_frog.c
/* * libdivecomputer * * Copyright (C) 2009 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <libdivecomputer/units.h> #include "oceanic_atom2.h" #include "oceanic_common.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_parser_isinstance((parser), &oceanic_atom2_parser_vtable) #define ATOM1 0x4250 #define EPICA 0x4257 #define VT3 0x4258 #define T3A 0x4259 #define ATOM2 0x4342 #define GEO 0x4344 #define MANTA 0x4345 #define DATAMASK 0x4347 #define COMPUMASK 0x4348 #define OC1A 0x434E #define F10A 0x434D #define WISDOM2 0x4350 #define INSIGHT2 0x4353 #define ELEMENT2 0x4357 #define VEO20 0x4359 #define VEO30 0x435A #define ZEN 0x4441 #define ZENAIR 0x4442 #define ATMOSAI2 0x4443 #define PROPLUS21 0x4444 #define GEO20 0x4446 #define VT4 0x4447 #define OC1B 0x4449 #define VOYAGER2G 0x444B #define ATOM3 0x444C #define DG03 0x444D #define OCS 0x4450 #define OC1C 0x4451 #define VT41 0x4452 #define EPICB 0x4453 #define T3B 0x4455 #define ATOM31 0x4456 #define A300AI 0x4457 #define WISDOM3 0x4458 #define A300 0x445A #define TX1 0x4542 #define MUNDIAL2 0x4543 #define AMPHOS 0x4545 #define AMPHOSAIR 0x4546 #define PROPLUS3 0x4548 #define F11A 0x4549 #define OCI 0x454B #define A300CS 0x454C #define MUNDIAL3 0x4550 #define F10B 0x4553 #define F11B 0x4554 #define XPAIR 0x4555 #define VISION 0x4556 #define VTX 0x4557 #define I300 0x4559 #define I750TC 0x455A #define I450T 0x4641 #define I550 0x4642 #define I200 0x4646 #define NORMAL 0 #define GAUGE 1 #define FREEDIVE 2 #define NGASMIXES 6 #define HEADER 1 #define PROFILE 2 typedef struct oceanic_atom2_parser_t oceanic_atom2_parser_t; struct oceanic_atom2_parser_t { dc_parser_t base; unsigned int model; unsigned int headersize; unsigned int footersize; unsigned int serial; // Cached fields. unsigned int cached; unsigned int header; unsigned int footer; unsigned int mode; unsigned int ngasmixes; unsigned int oxygen[NGASMIXES]; unsigned int helium[NGASMIXES]; unsigned int divetime; double maxdepth; }; static dc_status_t oceanic_atom2_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t oceanic_atom2_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t oceanic_atom2_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t oceanic_atom2_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t oceanic_atom2_parser_vtable = { sizeof(oceanic_atom2_parser_t), DC_FAMILY_OCEANIC_ATOM2, oceanic_atom2_parser_set_data, /* set_data */ oceanic_atom2_parser_get_datetime, /* datetime */ oceanic_atom2_parser_get_field, /* fields */ oceanic_atom2_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; dc_status_t oceanic_atom2_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int model, unsigned int serial) { oceanic_atom2_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (oceanic_atom2_parser_t *) dc_parser_allocate (context, &oceanic_atom2_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. parser->model = model; parser->headersize = 9 * PAGESIZE / 2; parser->footersize = 2 * PAGESIZE / 2; if (model == DATAMASK || model == COMPUMASK || model == GEO || model == GEO20 || model == VEO20 || model == VEO30 || model == OCS || model == PROPLUS3 || model == A300 || model == MANTA || model == INSIGHT2 || model == ZEN || model == I300 || model == I550 || model == I200) { parser->headersize -= PAGESIZE; } else if (model == VT4 || model == VT41) { parser->headersize += PAGESIZE; } else if (model == TX1) { parser->headersize += 2 * PAGESIZE; } else if (model == ATOM1) { parser->headersize -= 2 * PAGESIZE; } else if (model == F10A || model == F10B || model == MUNDIAL2 || model == MUNDIAL3) { parser->headersize = 3 * PAGESIZE; parser->footersize = 0; } else if (model == F11A || model == F11B) { parser->headersize = 5 * PAGESIZE; parser->footersize = 0; } else if (model == A300CS || model == VTX || model == I450T || model == I750TC) { parser->headersize = 5 * PAGESIZE; } parser->serial = serial; parser->cached = 0; parser->header = 0; parser->footer = 0; parser->mode = NORMAL; parser->ngasmixes = 0; for (unsigned int i = 0; i < NGASMIXES; ++i) { parser->oxygen[i] = 0; parser->helium[i] = 0; } parser->divetime = 0; parser->maxdepth = 0.0; *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; } static dc_status_t oceanic_atom2_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { oceanic_atom2_parser_t *parser = (oceanic_atom2_parser_t *) abstract; // Reset the cache. parser->cached = 0; parser->header = 0; parser->footer = 0; parser->mode = NORMAL; parser->ngasmixes = 0; for (unsigned int i = 0; i < NGASMIXES; ++i) { parser->oxygen[i] = 0; parser->helium[i] = 0; } parser->divetime = 0; parser->maxdepth = 0.0; return DC_STATUS_SUCCESS; } static dc_status_t oceanic_atom2_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { oceanic_atom2_parser_t *parser = (oceanic_atom2_parser_t *) abstract; unsigned int header = 8; if (parser->model == F10A || parser->model == F10B || parser->model == F11A || parser->model == F11B || parser->model == MUNDIAL2 || parser->model == MUNDIAL3) header = 32; if (abstract->size < header) return DC_STATUS_DATAFORMAT; const unsigned char *p = abstract->data; if (datetime) { // AM/PM bit of the 12-hour clock. unsigned int pm = p[1] & 0x80; switch (parser->model) { case OC1A: case OC1B: case OC1C: case OCS: case VT4: case VT41: case ATOM3: case ATOM31: case A300AI: case OCI: case I550: case VISION: case XPAIR: datetime->year = ((p[5] & 0xE0) >> 5) + ((p[7] & 0xE0) >> 2) + 2000; datetime->month = (p[3] & 0x0F); datetime->day = ((p[0] & 0x80) >> 3) + ((p[3] & 0xF0) >> 4); datetime->hour = bcd2dec (p[1] & 0x1F); datetime->minute = bcd2dec (p[0] & 0x7F); break; case VT3: case VEO20: case VEO30: case DG03: case T3A: case T3B: case GEO20: case PROPLUS3: case DATAMASK: case COMPUMASK: case INSIGHT2: case I300: case I200: datetime->year = ((p[3] & 0xE0) >> 1) + (p[4] & 0x0F) + 2000; datetime->month = (p[4] & 0xF0) >> 4; datetime->day = p[3] & 0x1F; datetime->hour = bcd2dec (p[1] & 0x1F); datetime->minute = bcd2dec (p[0]); break; case ZENAIR: case AMPHOS: case AMPHOSAIR: case VOYAGER2G: datetime->year = (p[3] & 0x1F) + 2000; datetime->month = (p[7] & 0xF0) >> 4; datetime->day = ((p[3] & 0x80) >> 3) + ((p[5] & 0xF0) >> 4); datetime->hour = bcd2dec (p[1] & 0x1F); datetime->minute = bcd2dec (p[0]); break; case F10A: case F10B: case F11A: case F11B: case MUNDIAL2: case MUNDIAL3: datetime->year = bcd2dec (p[6]) + 2000; datetime->month = bcd2dec (p[7]); datetime->day = bcd2dec (p[8]); datetime->hour = bcd2dec (p[13] & 0x7F); datetime->minute = bcd2dec (p[12]); pm = p[13] & 0x80; break; case TX1: datetime->year = bcd2dec (p[13]) + 2000; datetime->month = bcd2dec (p[14]); datetime->day = bcd2dec (p[15]); datetime->hour = p[11]; datetime->minute = p[10]; break; case A300CS: case VTX: case I450T: case I750TC: datetime->year = (p[10]) + 2000; datetime->month = (p[8]); datetime->day = (p[9]); datetime->hour = bcd2dec(p[1] & 0x1F); datetime->minute = bcd2dec(p[0]); break; default: datetime->year = bcd2dec (((p[3] & 0xC0) >> 2) + (p[4] & 0x0F)) + 2000; datetime->month = (p[4] & 0xF0) >> 4; datetime->day = bcd2dec (p[3] & 0x3F); datetime->hour = bcd2dec (p[1] & 0x1F); datetime->minute = bcd2dec (p[0]); break; } datetime->second = 0; datetime->timezone = DC_TIMEZONE_NONE; // Convert to a 24-hour clock. datetime->hour %= 12; if (pm) datetime->hour += 12; /* * Workaround for the year 2010 problem. * * In theory there are more than enough bits available to store years * past 2010. Unfortunately some models do not use all those bits and * store only the last digit of the year. We try to guess the missing * information based on the current year. This should work in most * cases, except when the dive is more than 10 years old or in the * future (due to an incorrect clock on the device or the host system). * * Note that we are careful not to apply any guessing when the year is * actually stored with more bits. We don't want the code to break when * a firmware update fixes this bug. */ if (datetime->year < 2010) { // Retrieve the current year. dc_datetime_t now = {0}; if (dc_datetime_localtime (&now, dc_datetime_now ()) && now.year >= 2010) { // Guess the correct decade. int decade = (now.year / 10) * 10; if (datetime->year % 10 > now.year % 10) decade -= 10; /* Force back to the previous decade. */ // Adjust the year. datetime->year += decade - 2000; } } } return DC_STATUS_SUCCESS; } #define BUF_LEN 16 static dc_status_t oceanic_atom2_parser_cache (oceanic_atom2_parser_t *parser) { const unsigned char *data = parser->base.data; unsigned int size = parser->base.size; if (parser->cached) { return DC_STATUS_SUCCESS; } // Get the total amount of bytes before and after the profile data. unsigned int headersize = parser->headersize; unsigned int footersize = parser->footersize; if (size < headersize + footersize) return DC_STATUS_DATAFORMAT; // Get the offset to the header and footer sample. unsigned int header = headersize - PAGESIZE / 2; unsigned int footer = size - footersize; if (parser->model == VT4 || parser->model == VT41 || parser->model == A300AI || parser->model == VISION || parser->model == XPAIR) { header = 3 * PAGESIZE; } // Get the dive mode. unsigned int mode = NORMAL; if (parser->model == F10A || parser->model == F10B || parser->model == F11A || parser->model == F11B || parser->model == MUNDIAL2 || parser->model == MUNDIAL3) { mode = FREEDIVE; } else if (parser->model == T3B || parser->model == VT3 || parser->model == DG03) { mode = (data[2] & 0xC0) >> 6; } else if (parser->model == VEO20 || parser->model == VEO30 || parser->model == OCS) { mode = (data[1] & 0x60) >> 5; } // Get the gas mixes. unsigned int ngasmixes = 0; unsigned int o2_offset = 0; unsigned int he_offset = 0; if (mode == FREEDIVE) { ngasmixes = 0; } else if (parser->model == DATAMASK || parser->model == COMPUMASK) { ngasmixes = 1; o2_offset = header + 3; } else if (parser->model == VT4 || parser->model == VT41 || parser->model == A300AI || parser->model == VISION || parser->model == XPAIR) { o2_offset = header + 4; ngasmixes = 4; } else if (parser->model == OCI) { o2_offset = 0x28; ngasmixes = 4; } else if (parser->model == TX1) { o2_offset = 0x3E; he_offset = 0x48; ngasmixes = 6; } else if (parser->model == A300CS || parser->model == VTX || parser->model == I750TC) { o2_offset = 0x2A; if (data[0x39] & 0x04) { ngasmixes = 1; } else if (data[0x39] & 0x08) { ngasmixes = 2; } else if (data[0x39] & 0x10) { ngasmixes = 3; } else { ngasmixes = 4; } } else if (parser->model == I450T) { o2_offset = 0x30; ngasmixes = 3; } else if (parser->model == ZEN) { o2_offset = header + 4; ngasmixes = 2; } else { o2_offset = header + 4; ngasmixes = 3; } // Cache the data for later use. parser->header = header; parser->footer = footer; parser->mode = mode; parser->ngasmixes = ngasmixes; for (unsigned int i = 0; i < ngasmixes; ++i) { if (data[o2_offset + i]) { parser->oxygen[i] = data[o2_offset + i]; } else { parser->oxygen[i] = 21; } if (he_offset) { parser->helium[i] = data[he_offset + i]; } else { parser->helium[i] = 0; } } parser->cached = HEADER; return DC_STATUS_SUCCESS; } static dc_status_t oceanic_atom2_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { dc_status_t status = DC_STATUS_SUCCESS; oceanic_atom2_parser_t *parser = (oceanic_atom2_parser_t *) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; // Cache the header data. status = oceanic_atom2_parser_cache (parser); if (status != DC_STATUS_SUCCESS) return status; // Cache the profile data. if (parser->cached < PROFILE) { sample_statistics_t statistics = SAMPLE_STATISTICS_INITIALIZER; status = oceanic_atom2_parser_samples_foreach ( abstract, sample_statistics_cb, &statistics); if (status != DC_STATUS_SUCCESS) return status; parser->cached = PROFILE; parser->divetime = statistics.divetime; parser->maxdepth = statistics.maxdepth; } dc_gasmix_t *gasmix = (dc_gasmix_t *) value; dc_salinity_t *water = (dc_salinity_t *) value; dc_field_string_t *string = (dc_field_string_t *) value; char buf[BUF_LEN]; if (value) { switch (type) { case DC_FIELD_DIVETIME: if (parser->model == F10A || parser->model == F10B || parser->model == F11A || parser->model == F11B || parser->model == MUNDIAL2 || parser->model == MUNDIAL3) *((unsigned int *) value) = bcd2dec (data[2]) + bcd2dec (data[3]) * 60; else *((unsigned int *) value) = parser->divetime; break; case DC_FIELD_MAXDEPTH: if (parser->model == F10A || parser->model == F10B || parser->model == F11A || parser->model == F11B || parser->model == MUNDIAL2 || parser->model == MUNDIAL3) *((double *) value) = array_uint16_le (data + 4) / 16.0 * FEET; else *((double *) value) = (array_uint16_le (data + parser->footer + 4) & 0x0FFF) / 16.0 * FEET; break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = parser->ngasmixes; break; case DC_FIELD_GASMIX: gasmix->oxygen = parser->oxygen[flags] / 100.0; gasmix->helium = parser->helium[flags] / 100.0; gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium; break; case DC_FIELD_SALINITY: if (parser->model == A300CS || parser->model == VTX || parser->model == I750TC) { if (data[0x18] & 0x80) { water->type = DC_WATER_FRESH; } else { water->type = DC_WATER_SALT; } water->density = 0.0; } else { return DC_STATUS_UNSUPPORTED; } break; case DC_FIELD_DIVEMODE: switch (parser->mode) { case NORMAL: *((unsigned int *) value) = DC_DIVEMODE_OC; break; case GAUGE: *((unsigned int *) value) = DC_DIVEMODE_GAUGE; break; case FREEDIVE: *((unsigned int *) value) = DC_DIVEMODE_FREEDIVE; break; default: return DC_STATUS_DATAFORMAT; } break; case DC_FIELD_STRING: switch(flags) { case 0: /* Serial */ string->desc = "Serial"; snprintf(buf, BUF_LEN, "%06u", parser->serial); break; default: return DC_STATUS_UNSUPPORTED; } string->value = strdup(buf); break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static void oceanic_atom2_parser_vendor (oceanic_atom2_parser_t *parser, const unsigned char *data, unsigned int size, unsigned int samplesize, dc_sample_callback_t callback, void *userdata) { unsigned int offset = 0; while (offset + samplesize <= size) { dc_sample_value_t sample = {0}; // Ignore empty samples. if ((parser->mode != FREEDIVE && array_isequal (data + offset, samplesize, 0x00)) || array_isequal (data + offset, samplesize, 0xFF)) { offset += samplesize; continue; } // Get the sample type. unsigned int sampletype = data[offset + 0]; if (parser->mode == FREEDIVE) sampletype = 0; // Get the sample size. unsigned int length = samplesize; if (sampletype == 0xBB) { length = PAGESIZE; } // Vendor specific data sample.vendor.type = SAMPLE_VENDOR_OCEANIC_ATOM2; sample.vendor.size = length; sample.vendor.data = data + offset; if (callback) callback (DC_SAMPLE_VENDOR, sample, userdata); offset += length; } } static dc_status_t oceanic_atom2_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { dc_status_t status = DC_STATUS_SUCCESS; oceanic_atom2_parser_t *parser = (oceanic_atom2_parser_t *) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; // Cache the header data. status = oceanic_atom2_parser_cache (parser); if (status != DC_STATUS_SUCCESS) return status; unsigned int extratime = 0; unsigned int time = 0; unsigned int interval = 1; unsigned int samplerate = 1; if (parser->mode != FREEDIVE) { unsigned int idx = 0x17; if (parser->model == A300CS || parser->model == VTX || parser->model == I450T || parser->model == I750TC) idx = 0x1f; switch (data[idx] & 0x03) { case 0: interval = 2; break; case 1: interval = 15; break; case 2: interval = 30; break; case 3: interval = 60; break; } } else if (parser->model == F11A || parser->model == F11B) { unsigned int idx = 0x29; switch (data[idx] & 0x03) { case 0: interval = 1; samplerate = 4; break; case 1: interval = 1; samplerate = 2; break; case 2: interval = 1; break; case 3: interval = 2; break; } if (samplerate > 1) { // Some models supports multiple samples per second. // Since our smallest unit of time is one second, we can't // represent this, and the extra samples will get dropped. WARNING(abstract->context, "Multiple samples per second are not supported!"); } } unsigned int samplesize = PAGESIZE / 2; if (parser->mode == FREEDIVE) { if (parser->model == F10A || parser->model == F10B || parser->model == F11A || parser->model == F11B || parser->model == MUNDIAL2 || parser->model == MUNDIAL3) { samplesize = 2; } else { samplesize = 4; } } else if (parser->model == OC1A || parser->model == OC1B || parser->model == OC1C || parser->model == OCI || parser->model == TX1 || parser->model == A300CS || parser->model == VTX || parser->model == I450T || parser->model == I750TC) { samplesize = PAGESIZE; } unsigned int have_temperature = 1, have_pressure = 1; if (parser->mode == FREEDIVE) { have_temperature = 0; have_pressure = 0; } else if (parser->model == VEO30 || parser->model == OCS || parser->model == ELEMENT2 || parser->model == VEO20 || parser->model == A300 || parser->model == ZEN || parser->model == GEO || parser->model == GEO20 || parser->model == MANTA || parser->model == I300 || parser->model == I200) { have_pressure = 0; } // Initial temperature. unsigned int temperature = 0; if (have_temperature) { temperature = data[parser->header + 7]; } // Initial tank pressure. unsigned int tank = 0; unsigned int pressure = 0; if (have_pressure) { unsigned int idx = 2; if (parser->model == A300CS || parser->model == VTX || parser->model == I750TC) idx = 16; pressure = array_uint16_le(data + parser->header + idx); if (pressure == 10000) have_pressure = 0; } // Initial gas mix. unsigned int gasmix_previous = 0xFFFFFFFF; unsigned int count = 0; unsigned int complete = 1; unsigned int previous = 0; unsigned int offset = parser->headersize; while (offset + samplesize <= size - parser->footersize) { dc_sample_value_t sample = {0}; // Ignore empty samples. if ((parser->mode != FREEDIVE && array_isequal (data + offset, samplesize, 0x00)) || array_isequal (data + offset, samplesize, 0xFF)) { offset += samplesize; continue; } if (complete) { previous = offset; complete = 0; } // Get the sample type. unsigned int sampletype = data[offset + 0]; if (parser->mode == FREEDIVE) sampletype = 0; // The sample size is usually fixed, but some sample types have a // larger size. Check whether we have that many bytes available. unsigned int length = samplesize; if (sampletype == 0xBB) { length = PAGESIZE; if (offset + length > size - parser->footersize) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } } // Check for a tank switch sample. if (sampletype == 0xAA) { if (parser->model == DATAMASK || parser->model == COMPUMASK) { // Tank pressure (1 psi) and number tank = 0; pressure = (((data[offset + 7] << 8) + data[offset + 6]) & 0x0FFF); } else if (parser->model == A300CS || parser->model == VTX || parser->model == I750TC) { // Tank pressure (1 psi) and number (one based index) tank = (data[offset + 1] & 0x03) - 1; pressure = ((data[offset + 7] << 8) + data[offset + 6]) & 0x0FFF; } else { // Tank pressure (2 psi) and number (one based index) tank = (data[offset + 1] & 0x03) - 1; if (parser->model == ATOM2 || parser->model == EPICA || parser->model == EPICB) pressure = (((data[offset + 3] << 8) + data[offset + 4]) & 0x0FFF) * 2; else pressure = (((data[offset + 4] << 8) + data[offset + 5]) & 0x0FFF) * 2; } } else if (sampletype == 0xBB) { // The surface time is not always a nice multiple of the samplerate. // The number of inserted surface samples is therefore rounded down // to keep the timestamps aligned at multiples of the samplerate. unsigned int surftime = 60 * bcd2dec (data[offset + 1]) + bcd2dec (data[offset + 2]); unsigned int nsamples = surftime / interval; for (unsigned int i = 0; i < nsamples; ++i) { // Time time += interval; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Vendor specific data if (i == 0) { oceanic_atom2_parser_vendor (parser, data + previous, (offset - previous) + length, samplesize, callback, userdata); } // Depth sample.depth = 0.0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); complete = 1; } extratime += surftime; } else { // Skip the extra samples. if ((count % samplerate) != 0) { offset += samplesize; count++; continue; } // Time. if (parser->model == I450T) { unsigned int minute = bcd2dec(data[offset + 0]); unsigned int hour = bcd2dec(data[offset + 1] & 0x0F); unsigned int second = bcd2dec(data[offset + 2]); unsigned int timestamp = (hour * 3600) + (minute * 60 ) + second + extratime; if (timestamp < time) { ERROR (abstract->context, "Timestamp moved backwards."); return DC_STATUS_DATAFORMAT; } else if (timestamp == time) { WARNING (abstract->context, "Unexpected sample with the same timestamp ignored."); offset += length; continue; } time = timestamp; } else { time += interval; } sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Vendor specific data oceanic_atom2_parser_vendor (parser, data + previous, (offset - previous) + length, samplesize, callback, userdata); // Temperature (°F) if (have_temperature) { if (parser->model == GEO || parser->model == ATOM1 || parser->model == ELEMENT2 || parser->model == MANTA || parser->model == ZEN) { temperature = data[offset + 6]; } else if (parser->model == GEO20 || parser->model == VEO20 || parser->model == VEO30 || parser->model == OC1A || parser->model == OC1B || parser->model == OC1C || parser->model == OCI || parser->model == A300 || parser->model == I450T || parser->model == I300 || parser->model == I200) { temperature = data[offset + 3]; } else if (parser->model == OCS || parser->model == TX1) { temperature = data[offset + 1]; } else if (parser->model == VT4 || parser->model == VT41 || parser->model == ATOM3 || parser->model == ATOM31 || parser->model == A300AI || parser->model == VISION || parser->model == XPAIR) { temperature = ((data[offset + 7] & 0xF0) >> 4) | ((data[offset + 7] & 0x0C) << 2) | ((data[offset + 5] & 0x0C) << 4); } else if (parser->model == A300CS || parser->model == VTX || parser->model == I750TC) { temperature = data[offset + 11]; } else { unsigned int sign; if (parser->model == DG03 || parser->model == PROPLUS3 || parser->model == I550) sign = (~data[offset + 5] & 0x04) >> 2; else if (parser->model == VOYAGER2G || parser->model == AMPHOS || parser->model == AMPHOSAIR || parser->model == ZENAIR) sign = (data[offset + 5] & 0x04) >> 2; else if (parser->model == ATOM2 || parser->model == PROPLUS21 || parser->model == EPICA || parser->model == EPICB || parser->model == ATMOSAI2 || parser->model == WISDOM2 || parser->model == WISDOM3) sign = (data[offset + 0] & 0x80) >> 7; else sign = (~data[offset + 0] & 0x80) >> 7; if (sign) temperature -= (data[offset + 7] & 0x0C) >> 2; else temperature += (data[offset + 7] & 0x0C) >> 2; } sample.temperature = (temperature - 32.0) * (5.0 / 9.0); if (callback) callback (DC_SAMPLE_TEMPERATURE, sample, userdata); } // Tank Pressure (psi) if (have_pressure) { if (parser->model == OC1A || parser->model == OC1B || parser->model == OC1C || parser->model == OCI || parser->model == I450T) pressure = (data[offset + 10] + (data[offset + 11] << 8)) & 0x0FFF; else if (parser->model == VT4 || parser->model == VT41|| parser->model == ATOM3 || parser->model == ATOM31 || parser->model == ZENAIR ||parser->model == A300AI || parser->model == DG03 || parser->model == PROPLUS3 || parser->model == AMPHOSAIR || parser->model == I550 || parser->model == VISION || parser->model == XPAIR) pressure = (((data[offset + 0] & 0x03) << 8) + data[offset + 1]) * 5; else if (parser->model == TX1 || parser->model == A300CS || parser->model == VTX || parser->model == I750TC) pressure = array_uint16_le (data + offset + 4); else pressure -= data[offset + 1]; sample.pressure.tank = tank; sample.pressure.value = pressure * PSI / BAR; if (callback) callback (DC_SAMPLE_PRESSURE, sample, userdata); } // Depth (1/16 ft) unsigned int depth; if (parser->mode == FREEDIVE) depth = array_uint16_le (data + offset); else if (parser->model == GEO20 || parser->model == VEO20 || parser->model == VEO30 || parser->model == OC1A || parser->model == OC1B || parser->model == OC1C || parser->model == OCI || parser->model == A300 || parser->model == I450T || parser->model == I300 || parser->model == I200) depth = (data[offset + 4] + (data[offset + 5] << 8)) & 0x0FFF; else if (parser->model == ATOM1) depth = data[offset + 3] * 16; else depth = (data[offset + 2] + (data[offset + 3] << 8)) & 0x0FFF; sample.depth = depth / 16.0 * FEET; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); // Gas mix unsigned int have_gasmix = 0; unsigned int gasmix = 0; if (parser->model == TX1) { gasmix = data[offset] & 0x07; have_gasmix = 1; } if (have_gasmix && gasmix != gasmix_previous) { if (gasmix < 1 || gasmix > parser->ngasmixes) { ERROR (abstract->context, "Invalid gas mix index (%u).", gasmix); return DC_STATUS_DATAFORMAT; } sample.gasmix = gasmix - 1; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); gasmix_previous = gasmix; } // NDL / Deco unsigned int have_deco = 0; unsigned int decostop = 0, decotime = 0; if (parser->model == A300CS || parser->model == VTX || parser->model == I450T || parser->model == I750TC) { decostop = (data[offset + 15] & 0x70) >> 4; decotime = array_uint16_le(data + offset + 6) & 0x03FF; have_deco = 1; } else if (parser->model == ZEN || parser->model == DG03) { decostop = (data[offset + 5] & 0xF0) >> 4; decotime = array_uint16_le(data + offset + 4) & 0x0FFF; have_deco = 1; } else if (parser->model == TX1) { decostop = data[offset + 10]; decotime = array_uint16_le(data + offset + 6); have_deco = 1; } else if (parser->model == ATOM31 || parser->model == VISION || parser->model == XPAIR || parser->model == I550) { decostop = (data[offset + 5] & 0xF0) >> 4; decotime = array_uint16_le(data + offset + 4) & 0x03FF; have_deco = 1; } else if (parser->model == I200 || parser->model == I300 || parser->model == OC1A || parser->model == OC1B || parser->model == OC1C || parser->model == OCI) { decostop = (data[offset + 7] & 0xF0) >> 4; decotime = array_uint16_le(data + offset + 6) & 0x0FFF; have_deco = 1; } if (have_deco) { if (decostop) { sample.deco.type = DC_DECO_DECOSTOP; sample.deco.depth = decostop * 10 * FEET; } else { sample.deco.type = DC_DECO_NDL; sample.deco.depth = 0.0; } sample.deco.time = decotime * 60; if (callback) callback (DC_SAMPLE_DECO, sample, userdata); } unsigned int have_rbt = 0; unsigned int rbt = 0; if (parser->model == ATOM31) { rbt = array_uint16_le(data + offset + 6) & 0x01FF; have_rbt = 1; } else if (parser->model == I450T || parser->model == OC1A || parser->model == OC1B || parser->model == OC1C || parser->model == OCI) { rbt = array_uint16_le(data + offset + 8) & 0x01FF; have_rbt = 1; } else if (parser->model == VISION || parser->model == XPAIR || parser->model == I550) { rbt = array_uint16_le(data + offset + 6) & 0x03FF; have_rbt = 1; } if (have_rbt) { sample.rbt = rbt; if (callback) callback (DC_SAMPLE_RBT, sample, userdata); } // Bookmarks unsigned int have_bookmark = 0; if (parser->model == OC1A || parser->model == OC1B || parser->model == OC1C || parser->model == OCI) { have_bookmark = data[offset + 12] & 0x80; } if (have_bookmark) { sample.event.type = SAMPLE_EVENT_BOOKMARK; sample.event.time = 0; sample.event.flags = 0; sample.event.value = 0; if (callback) callback (DC_SAMPLE_EVENT, sample, userdata); } count++; complete = 1; } offset += length; } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/oceanic_atom2_parser.c
/* * libdivecomputer * * Copyright (C) 2014 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <libdivecomputer/units.h> #include "citizen_aqualand.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_device_isinstance((parser), &citizen_aqualand_parser_vtable) #define SZ_HEADER 32 typedef struct citizen_aqualand_parser_t { dc_parser_t base; } citizen_aqualand_parser_t; static dc_status_t citizen_aqualand_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t citizen_aqualand_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t citizen_aqualand_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t citizen_aqualand_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t citizen_aqualand_parser_vtable = { sizeof(citizen_aqualand_parser_t), DC_FAMILY_CITIZEN_AQUALAND, citizen_aqualand_parser_set_data, /* set_data */ citizen_aqualand_parser_get_datetime, /* datetime */ citizen_aqualand_parser_get_field, /* fields */ citizen_aqualand_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; dc_status_t citizen_aqualand_parser_create (dc_parser_t **out, dc_context_t *context) { citizen_aqualand_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (citizen_aqualand_parser_t *) dc_parser_allocate (context, &citizen_aqualand_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; } static dc_status_t citizen_aqualand_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { return DC_STATUS_SUCCESS; } static dc_status_t citizen_aqualand_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { if (abstract->size < SZ_HEADER) return DC_STATUS_DATAFORMAT; const unsigned char *p = abstract->data; if (datetime) { datetime->year = bcd2dec(p[0x05]) * 100 + bcd2dec(p[0x06]); datetime->month = bcd2dec(p[0x07]); datetime->day = bcd2dec(p[0x08]); datetime->hour = bcd2dec(p[0x0A]); datetime->minute = bcd2dec(p[0x0B]); datetime->second = bcd2dec(p[0x0C]); datetime->timezone = DC_TIMEZONE_NONE; } return DC_STATUS_SUCCESS; } static dc_status_t citizen_aqualand_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { if (abstract->size < SZ_HEADER) return DC_STATUS_DATAFORMAT; const unsigned char *data = abstract->data; unsigned int metric = (data[0x04] == 0xA6 ? 0 : 1); unsigned int maxdepth = bcd2dec(data[0x12]) * 10 + ((data[0x13] >> 4) & 0x0F); unsigned int divetime = (data[0x16] & 0x0F) * 100 + bcd2dec(data[0x17]); if (value) { switch (type) { case DC_FIELD_DIVETIME: *((unsigned int *) value) = divetime * 60; break; case DC_FIELD_MAXDEPTH: if (metric) *((double *) value) = maxdepth / 10.0; else *((double *) value) = maxdepth * FEET; break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = 0; break; case DC_FIELD_DIVEMODE: *((dc_divemode_t *) value) = DC_DIVEMODE_GAUGE; break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t citizen_aqualand_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { const unsigned char *data = abstract->data; unsigned int size = abstract->size; if (size < SZ_HEADER) return DC_STATUS_DATAFORMAT; // Estimate the maximum number of samples. We calculate the number of // 12 bit values that fit in the available profile data, and round the // result upwards. The actual number of samples should always be smaller // due to the presence of at least two end markers. unsigned int maxcount = (2 * (size - SZ_HEADER) + 2) / 3; // Allocate storage for the processed 16 bit samples. unsigned short *samples = (unsigned short *) malloc(maxcount * sizeof(unsigned short)); if (samples == NULL) { return DC_STATUS_NOMEMORY; } // Pre-process the depth and temperature tables. The 12 bit BCD encoded // values are converted into an array of 16 bit values, which is much // more convenient to process in the second stage. unsigned int nsamples = 0; unsigned int count[2] = {0, 0}; unsigned int offset = SZ_HEADER * 2; unsigned int length = size * 2; for (unsigned int i = 0; i < 2; ++i) { const unsigned int marker = (i == 0 ? 0xEF : 0xFF); while (offset + 3 <= length) { unsigned int value = 0; unsigned int octet = offset / 2; unsigned int nibble = offset % 2; unsigned int hi = data[octet]; unsigned int lo = data[octet + 1]; // Check for the end marker. if (hi == marker || lo == marker) { offset += nibble; break; } // Convert 12 bit BCD to decimal. if (nibble) { value = ((hi ) & 0x0F) * 100 + ((lo >> 4) & 0x0F) * 10 + ((lo ) & 0x0F); } else { value = ((hi >> 4) & 0x0F) * 100 + ((hi ) & 0x0F) * 10 + ((lo >> 4) & 0x0F); } // Store the value. samples[nsamples] = value; count[i]++; nsamples++; offset += 3; } // Verify the end marker. if (offset + 2 > length || data[offset / 2] != marker) { ERROR (abstract->context, "No end marker found."); free(samples); return DC_STATUS_DATAFORMAT; } offset += 2; } unsigned int time = 0; unsigned int interval = 5; unsigned int metric = (data[0x04] == 0xA6 ? 0 : 1); for (unsigned int i = 0; i < count[0]; ++i) { dc_sample_value_t sample = {0}; // Get the depth value. unsigned int depth = samples[i]; // Every 12th sample there is a strange sample that always contains // the value 999. This is clearly not a valid depth, but when trying // to skip these samples, the depth and temperatures go out of sync. // Therefore we replace the bogus sample with an interpolated value. if (depth == 999) { depth = 0; if (i > 0) { depth += samples[i - 1]; } if (i < count[0] - 1) { depth += samples[i + 1]; } depth /= 2; } // Time time += interval; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Depth if (metric) sample.depth = depth / 10.0; else sample.depth = depth * FEET; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); // Temperature if (time % 300 == 0) { unsigned int idx = count[0] + time / 300; if (idx < nsamples) { unsigned int temperature = samples[idx]; if (metric) sample.temperature = temperature / 10.0; else sample.temperature = (temperature - 32.0) * (5.0 / 9.0); if (callback) callback (DC_SAMPLE_TEMPERATURE, sample, userdata); } } } free(samples); return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/citizen_aqualand_parser.c
/* * libdivecomputer * * Copyright (C) 2013 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include "cressi_leonardo.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_device_isinstance((parser), &cressi_leonardo_parser_vtable) #define SZ_HEADER 82 #define DRAKE 6 typedef struct cressi_leonardo_parser_t cressi_leonardo_parser_t; struct cressi_leonardo_parser_t { dc_parser_t base; unsigned int model; }; static dc_status_t cressi_leonardo_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t cressi_leonardo_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t cressi_leonardo_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t cressi_leonardo_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t cressi_leonardo_parser_vtable = { sizeof(cressi_leonardo_parser_t), DC_FAMILY_CRESSI_LEONARDO, cressi_leonardo_parser_set_data, /* set_data */ cressi_leonardo_parser_get_datetime, /* datetime */ cressi_leonardo_parser_get_field, /* fields */ cressi_leonardo_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; dc_status_t cressi_leonardo_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int model) { cressi_leonardo_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (cressi_leonardo_parser_t *) dc_parser_allocate (context, &cressi_leonardo_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } parser->model = model; *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; } static dc_status_t cressi_leonardo_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { return DC_STATUS_SUCCESS; } static dc_status_t cressi_leonardo_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { if (abstract->size < SZ_HEADER) return DC_STATUS_DATAFORMAT; const unsigned char *p = abstract->data; if (datetime) { datetime->year = p[8] + 2000; datetime->month = p[9]; datetime->day = p[10]; datetime->hour = p[11]; datetime->minute = p[12]; datetime->second = 0; datetime->timezone = DC_TIMEZONE_NONE; } return DC_STATUS_SUCCESS; } static dc_status_t cressi_leonardo_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { cressi_leonardo_parser_t *parser = (cressi_leonardo_parser_t *) abstract; if (abstract->size < SZ_HEADER) return DC_STATUS_DATAFORMAT; const unsigned char *data = abstract->data; unsigned int interval = 20; if (parser->model == DRAKE) { interval = data[0x17]; } if (interval == 0) { ERROR(abstract->context, "Invalid sample interval"); return DC_STATUS_DATAFORMAT; } dc_gasmix_t *gasmix = (dc_gasmix_t *) value; if (value) { switch (type) { case DC_FIELD_DIVETIME: *((unsigned int *) value) = array_uint16_le (data + 0x06) * interval; break; case DC_FIELD_MAXDEPTH: *((double *) value) = array_uint16_le (data + 0x20) / 10.0; break; case DC_FIELD_GASMIX_COUNT: if (parser->model == DRAKE) { *((unsigned int *) value) = 0; } else { *((unsigned int *) value) = 1; } break; case DC_FIELD_GASMIX: gasmix->helium = 0.0; gasmix->oxygen = data[0x19] / 100.0; gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium; break; case DC_FIELD_TEMPERATURE_MINIMUM: *((double *) value) = data[0x22]; break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t cressi_leonardo_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { cressi_leonardo_parser_t *parser = (cressi_leonardo_parser_t *) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; unsigned int time = 0; unsigned int interval = 20; if (parser->model == DRAKE) { interval = data[0x17]; } if (interval == 0) { ERROR(abstract->context, "Invalid sample interval"); return DC_STATUS_DATAFORMAT; } unsigned int gasmix_previous = 0xFFFFFFFF; unsigned int gasmix = 0; unsigned int offset = SZ_HEADER; while (offset + 2 <= size) { dc_sample_value_t sample = {0}; if (offset + 4 <= size && array_uint16_le (data + offset + 2) == 0xFF00) { unsigned int surftime = data[offset] + (data[offset + 1] & 0x07) * 60; // Time (seconds). time += surftime; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Depth (1/10 m). sample.depth = 0.0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); offset += 4; } else { unsigned int value = array_uint16_le (data + offset); unsigned int depth = value & 0x07FF; unsigned int ascent = (value & 0xC000) >> 14; // Time (seconds). time += interval; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Depth (1/10 m). sample.depth = depth / 10.0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); // Gas change. if (gasmix != gasmix_previous) { sample.gasmix = gasmix; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); gasmix_previous = gasmix; } // Ascent rate if (ascent) { sample.event.type = SAMPLE_EVENT_ASCENT; sample.event.time = 0; sample.event.flags = 0; sample.event.value = ascent; if (callback) callback (DC_SAMPLE_EVENT, sample, userdata); } offset += 2; } } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/cressi_leonardo_parser.c
/* * libdivecomputer * * Copyright (C) 2014 John Van Ostrand * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <math.h> #include <libdivecomputer/units.h> #include "cochran_commander.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define C_ARRAY_SIZE(array) (sizeof (array) / sizeof *(array)) #define COCHRAN_MODEL_COMMANDER_TM 0 #define COCHRAN_MODEL_COMMANDER_PRE21000 1 #define COCHRAN_MODEL_COMMANDER_AIR_NITROX 2 #define COCHRAN_MODEL_EMC_14 3 #define COCHRAN_MODEL_EMC_16 4 #define COCHRAN_MODEL_EMC_20 5 // Cochran time stamps start at Jan 1, 1992 #define COCHRAN_EPOCH 694242000 #define UNSUPPORTED 0xFFFFFFFF typedef enum cochran_sample_format_t { SAMPLE_TM, SAMPLE_CMDR, SAMPLE_EMC, } cochran_sample_format_t; typedef enum cochran_date_encoding_t { DATE_ENCODING_MSDHYM, DATE_ENCODING_SMHDMY, DATE_ENCODING_TICKS, } cochran_date_encoding_t; typedef struct cochran_parser_layout_t { cochran_sample_format_t format; unsigned int headersize; unsigned int samplesize; unsigned int pt_sample_interval; cochran_date_encoding_t date_encoding; unsigned int datetime; unsigned int pt_profile_begin; unsigned int water_conductivity; unsigned int pt_profile_pre; unsigned int start_temp; unsigned int start_depth; unsigned int dive_number; unsigned int altitude; unsigned int pt_profile_end; unsigned int end_temp; unsigned int divetime; unsigned int max_depth; unsigned int avg_depth; unsigned int oxygen; unsigned int helium; unsigned int min_temp; unsigned int max_temp; } cochran_parser_layout_t; typedef struct cochran_events_t { unsigned char code; unsigned int data_bytes; parser_sample_event_t type; parser_sample_flags_t flag; } cochran_events_t; typedef struct event_size_t { unsigned int code; unsigned int size; } event_size_t; typedef struct cochran_commander_parser_t { dc_parser_t base; unsigned int model; const cochran_parser_layout_t *layout; const event_size_t *events; unsigned int nevents; } cochran_commander_parser_t ; static dc_status_t cochran_commander_parser_set_data (dc_parser_t *parser, const unsigned char *data, unsigned int size); static dc_status_t cochran_commander_parser_get_datetime (dc_parser_t *parser, dc_datetime_t *datetime); static dc_status_t cochran_commander_parser_get_field (dc_parser_t *parser, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t cochran_commander_parser_samples_foreach (dc_parser_t *parser, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t cochran_commander_parser_vtable = { sizeof(cochran_commander_parser_t), DC_FAMILY_COCHRAN_COMMANDER, cochran_commander_parser_set_data, /* set_data */ cochran_commander_parser_get_datetime, /* datetime */ cochran_commander_parser_get_field, /* fields */ cochran_commander_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; static const cochran_parser_layout_t cochran_cmdr_tm_parser_layout = { SAMPLE_TM, // format 90, // headersize 1, // samplesize 72, // pt_sample_interval DATE_ENCODING_TICKS, // date_encoding 15, // datetime, 4 bytes 0, // pt_profile_begin, 4 bytes UNSUPPORTED, // water_conductivity, 1 byte, 0=low(fresh), 2=high(sea) 0, // pt_profile_pre, 4 bytes 83, // start_temp, 1 byte, F UNSUPPORTED, // start_depth, 2 bytes, /4=ft 20, // dive_number, 2 bytes UNSUPPORTED, // altitude, 1 byte, /4=kilofeet UNSUPPORTED, // pt_profile_end, 4 bytes UNSUPPORTED, // end_temp, 1 byte F 57, // divetime, 2 bytes, minutes 49, // max_depth, 2 bytes, /4=ft 51, // avg_depth, 2 bytes, /4=ft 74, // oxygen, 4 bytes (2 of) 2 bytes, /256=% UNSUPPORTED, // helium, 4 bytes (2 of) 2 bytes, /256=% 82, // min_temp, 1 byte, /2+20=F UNSUPPORTED, // max_temp, 1 byte, /2+20=F }; static const cochran_parser_layout_t cochran_cmdr_1_parser_layout = { SAMPLE_CMDR, // format 256, // headersize 2, // samplesize UNSUPPORTED, // pt_sample_interval DATE_ENCODING_TICKS, // date_encoding 8, // datetime, 4 bytes 0, // pt_profile_begin, 4 bytes 24, // water_conductivity, 1 byte, 0=low(fresh), 2=high(sea) 28, // pt_profile_pre, 4 bytes 43, // start_temp, 1 byte, F 54, // start_depth, 2 bytes, /4=ft 68, // dive_number, 2 bytes 73, // altitude, 1 byte, /4=kilofeet 128, // pt_profile_end, 4 bytes 153, // end_temp, 1 byte F 166, // divetime, 2 bytes, minutes 168, // max_depth, 2 bytes, /4=ft 170, // avg_depth, 2 bytes, /4=ft 210, // oxygen, 4 bytes (2 of) 2 bytes, /256=% UNSUPPORTED, // helium, 4 bytes (2 of) 2 bytes, /256=% 232, // min_temp, 1 byte, /2+20=F 233, // max_temp, 1 byte, /2+20=F }; static const cochran_parser_layout_t cochran_cmdr_parser_layout = { SAMPLE_CMDR, // format 256, // headersize 2, // samplesize UNSUPPORTED, // pt_sample_interval DATE_ENCODING_MSDHYM, // date_encoding 0, // datetime, 6 bytes 6, // pt_profile_begin, 4 bytes 24, // water_conductivity, 1 byte, 0=low(fresh), 2=high(sea) 30, // pt_profile_pre, 4 bytes 45, // start_temp, 1 byte, F 56, // start_depth, 2 bytes, /4=ft 70, // dive_number, 2 bytes 73, // altitude, 1 byte, /4=kilofeet 128, // pt_profile_end, 4 bytes 153, // end_temp, 1 byte F 166, // divetime, 2 bytes, minutes 168, // max_depth, 2 bytes, /4=ft 170, // avg_depth, 2 bytes, /4=ft 210, // oxygen, 4 bytes (2 of) 2 bytes, /256=% UNSUPPORTED, // helium, 4 bytes (2 of) 2 bytes, /256=% 232, // min_temp, 1 byte, /2+20=F 233, // max_temp, 1 byte, /2+20=F }; static const cochran_parser_layout_t cochran_emc_parser_layout = { SAMPLE_EMC, // format 512, // headersize 3, // samplesize UNSUPPORTED, // pt_sample_interval DATE_ENCODING_SMHDMY, // date_encoding 0, // datetime, 6 bytes 6, // pt_profile_begin, 4 bytes 24, // water_conductivity, 1 byte 0=low(fresh), 2=high(sea) 30, // pt_profile_pre, 4 bytes 55, // start_temp, 1 byte, F 42, // start_depth, 2 bytes, /256=ft 86, // dive_number, 2 bytes, 89, // altitude, 1 byte /4=kilofeet 256, // pt_profile_end, 4 bytes 293, // end_temp, 1 byte, F 304, // divetime, 2 bytes, minutes 306, // max_depth, 2 bytes, /4=ft 310, // avg_depth, 2 bytes, /4=ft 144, // oxygen, 6 bytes (3 of) 2 bytes, /256=% 164, // helium, 6 bytes (3 of) 2 bytes, /256=% 403, // min_temp, 1 byte, /2+20=F 407, // max_temp, 1 byte, /2+20=F }; static const cochran_events_t cochran_events[] = { {0xA8, 1, SAMPLE_EVENT_SURFACE, SAMPLE_FLAGS_BEGIN}, // Entered PDI mode {0xA9, 1, SAMPLE_EVENT_SURFACE, SAMPLE_FLAGS_END}, // Exited PDI mode {0xAB, 5, SAMPLE_EVENT_NONE, SAMPLE_FLAGS_NONE}, // Ceiling decrease {0xAD, 5, SAMPLE_EVENT_NONE, SAMPLE_FLAGS_NONE}, // Ceiling increase {0xB5, 1, SAMPLE_EVENT_AIRTIME, SAMPLE_FLAGS_BEGIN}, // Air < 5 mins deco {0xBD, 1, SAMPLE_EVENT_NONE, SAMPLE_FLAGS_NONE}, // Switched to nomal PO2 setting {0xBE, 1, SAMPLE_EVENT_NONE, SAMPLE_FLAGS_NONE}, // Ceiling > 60 ft {0xC0, 1, SAMPLE_EVENT_NONE, SAMPLE_FLAGS_NONE}, // Switched to FO2 21% mode {0xC1, 1, SAMPLE_EVENT_ASCENT, SAMPLE_FLAGS_BEGIN}, // Ascent rate greater than limit {0xC2, 1, SAMPLE_EVENT_NONE, SAMPLE_FLAGS_NONE}, // Low battery warning {0xC3, 1, SAMPLE_EVENT_OLF, SAMPLE_FLAGS_NONE}, // CNS Oxygen toxicity warning {0xC4, 1, SAMPLE_EVENT_MAXDEPTH, SAMPLE_FLAGS_NONE}, // Depth exceeds user set point {0xC5, 1, SAMPLE_EVENT_NONE, SAMPLE_FLAGS_BEGIN}, // Entered decompression mode {0xC7, 1, SAMPLE_EVENT_VIOLATION,SAMPLE_FLAGS_BEGIN}, // Entered Gauge mode (e.g. locked out) {0xC8, 1, SAMPLE_EVENT_PO2, SAMPLE_FLAGS_BEGIN}, // PO2 too high {0xCC, 1, SAMPLE_EVENT_NONE, SAMPLE_FLAGS_BEGIN}, // Low Cylinder 1 pressure {0xCE, 1, SAMPLE_EVENT_NONE, SAMPLE_FLAGS_BEGIN}, // Non-decompression warning {0xCF, 1, SAMPLE_EVENT_OLF, SAMPLE_FLAGS_BEGIN}, // O2 Toxicity {0xCD, 1, SAMPLE_EVENT_NONE, SAMPLE_FLAGS_NONE}, // Switched to deco blend {0xD0, 1, SAMPLE_EVENT_WORKLOAD, SAMPLE_FLAGS_BEGIN}, // Breathing rate alarm {0xD3, 1, SAMPLE_EVENT_NONE, SAMPLE_FLAGS_NONE}, // Low gas 1 flow rate {0xD6, 1, SAMPLE_EVENT_CEILING, SAMPLE_FLAGS_BEGIN}, // Depth is less than ceiling {0xD8, 1, SAMPLE_EVENT_NONE, SAMPLE_FLAGS_END}, // End decompression mode {0xE1, 1, SAMPLE_EVENT_ASCENT, SAMPLE_FLAGS_END}, // End ascent rate warning {0xE2, 1, SAMPLE_EVENT_NONE, SAMPLE_FLAGS_NONE}, // Low SBAT battery warning {0xE3, 1, SAMPLE_EVENT_NONE, SAMPLE_FLAGS_NONE}, // Switched to FO2 mode {0xE5, 1, SAMPLE_EVENT_NONE, SAMPLE_FLAGS_NONE}, // Switched to PO2 mode {0xEE, 1, SAMPLE_EVENT_NONE, SAMPLE_FLAGS_END}, // End non-decompresison warning {0xEF, 1, SAMPLE_EVENT_NONE, SAMPLE_FLAGS_NONE}, // Switch to blend 2 {0xF0, 1, SAMPLE_EVENT_WORKLOAD, SAMPLE_FLAGS_END}, // Breathing rate alarm {0xF3, 1, SAMPLE_EVENT_NONE, SAMPLE_FLAGS_NONE}, // Switch to blend 1 {0xF6, 1, SAMPLE_EVENT_CEILING, SAMPLE_FLAGS_END}, // End Depth is less than ceiling }; static const event_size_t cochran_cmdr_event_bytes[] = { {0x00, 17}, {0x01, 21}, {0x02, 18}, {0x03, 17}, {0x06, 19}, {0x07, 19}, {0x08, 19}, {0x09, 19}, {0x0a, 19}, {0x0b, 21}, {0x0c, 19}, {0x0d, 19}, {0x0e, 19}, {0x10, 21}, }; static const event_size_t cochran_emc_event_bytes[] = { {0x00, 19}, {0x01, 23}, {0x02, 20}, {0x03, 19}, {0x06, 21}, {0x07, 21}, {0x0a, 21}, {0x0b, 21}, {0x0f, 19}, {0x10, 21}, }; static unsigned int cochran_commander_handle_event (cochran_commander_parser_t *parser, unsigned char code, dc_sample_callback_t callback, void *userdata) { dc_parser_t *abstract = (dc_parser_t *) parser; const cochran_events_t *event = NULL; for (unsigned int i = 0; i < C_ARRAY_SIZE(cochran_events); ++i) { if (cochran_events[i].code == code) { event = cochran_events + i; break; } } if (event == NULL) { // Unknown event, send warning so we know we missed something WARNING(abstract->context, "Unknown event 0x%02x", code); return 1; } switch (code) { case 0xAB: // Ceiling decrease // Indicated to lower ceiling by 10 ft (deeper) // Bytes 1-2: first stop duration (min) // Bytes 3-4: total stop duration (min) // Handled in calling function break; case 0xAD: // Ceiling increase // Indicates to raise ceiling by 10 ft (shallower) // Handled in calling function break; case 0xC0: // Switched to FO2 21% mode (surface) // Event seen upon surfacing // handled in calling function break; case 0xCD: // Switched to deco blend case 0xEF: // Switched to gas blend 2 case 0xF3: // Switched to gas blend 1 // handled in calling function break; default: // Don't send known events of type NONE if (event->type != SAMPLE_EVENT_NONE) { dc_sample_value_t sample = {0}; sample.event.type = event->type; sample.event.time = 0; sample.event.value = 0; sample.event.flags = event->flag; if (callback) callback (DC_SAMPLE_EVENT, sample, userdata); } } return event->data_bytes; } /* * Used to find the end of a dive that has an incomplete dive-end * block. It parses backwards past inter-dive events. */ static int cochran_commander_backparse(cochran_commander_parser_t *parser, const unsigned char *samples, int size) { int result = size, best_result = size; for (unsigned int i = 0; i < parser->nevents; i++) { int ptr = size - parser->events[i].size; if (ptr > 0 && samples[ptr] == parser->events[i].code) { // Recurse to find the largest match. Because we are parsing backwards // and the events vary in size we can't be sure the byte that matches // the event code is an event code or data from inside a longer or shorter // event. result = cochran_commander_backparse(parser, samples, ptr); } if (result < best_result) { best_result = result; } } return best_result; } dc_status_t cochran_commander_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int model) { cochran_commander_parser_t *parser = NULL; dc_status_t status = DC_STATUS_SUCCESS; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (cochran_commander_parser_t *) dc_parser_allocate (context, &cochran_commander_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } parser->model = model; switch (model) { case COCHRAN_MODEL_COMMANDER_TM: parser->layout = &cochran_cmdr_tm_parser_layout; parser->events = NULL; // No inter-dive events on this model parser->nevents = 0; break; case COCHRAN_MODEL_COMMANDER_PRE21000: parser->layout = &cochran_cmdr_1_parser_layout; parser->events = cochran_cmdr_event_bytes; parser->nevents = C_ARRAY_SIZE(cochran_cmdr_event_bytes); break; case COCHRAN_MODEL_COMMANDER_AIR_NITROX: parser->layout = &cochran_cmdr_parser_layout; parser->events = cochran_cmdr_event_bytes; parser->nevents = C_ARRAY_SIZE(cochran_cmdr_event_bytes); break; case COCHRAN_MODEL_EMC_14: case COCHRAN_MODEL_EMC_16: case COCHRAN_MODEL_EMC_20: parser->layout = &cochran_emc_parser_layout; parser->events = cochran_emc_event_bytes; parser->nevents = C_ARRAY_SIZE(cochran_emc_event_bytes); break; default: status = DC_STATUS_UNSUPPORTED; goto error_free; } *out = (dc_parser_t *) parser; return DC_STATUS_SUCCESS; error_free: dc_parser_deallocate ((dc_parser_t *) parser); return status; } static dc_status_t cochran_commander_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { return DC_STATUS_SUCCESS; } static dc_status_t cochran_commander_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { cochran_commander_parser_t *parser = (cochran_commander_parser_t *) abstract; const cochran_parser_layout_t *layout = parser->layout; const unsigned char *data = abstract->data; if (abstract->size < layout->headersize) return DC_STATUS_DATAFORMAT; dc_ticks_t ts = 0; if (datetime) { switch (layout->date_encoding) { case DATE_ENCODING_MSDHYM: datetime->second = data[layout->datetime + 1]; datetime->minute = data[layout->datetime + 0]; datetime->hour = data[layout->datetime + 3]; datetime->day = data[layout->datetime + 2]; datetime->month = data[layout->datetime + 5]; datetime->year = data[layout->datetime + 4] + (data[layout->datetime + 4] > 91 ? 1900 : 2000); datetime->timezone = DC_TIMEZONE_NONE; break; case DATE_ENCODING_SMHDMY: datetime->second = data[layout->datetime + 0]; datetime->minute = data[layout->datetime + 1]; datetime->hour = data[layout->datetime + 2]; datetime->day = data[layout->datetime + 3]; datetime->month = data[layout->datetime + 4]; datetime->year = data[layout->datetime + 5] + (data[layout->datetime + 5] > 91 ? 1900 : 2000); datetime->timezone = DC_TIMEZONE_NONE; break; case DATE_ENCODING_TICKS: ts = array_uint32_le(data + layout->datetime) + COCHRAN_EPOCH; dc_datetime_localtime(datetime, ts); break; } } return DC_STATUS_SUCCESS; } static dc_status_t cochran_commander_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { const cochran_commander_parser_t *parser = (cochran_commander_parser_t *) abstract; const cochran_parser_layout_t *layout = parser->layout; const unsigned char *data = abstract->data; unsigned int minutes = 0, qfeet = 0; dc_gasmix_t *gasmix = (dc_gasmix_t *) value; dc_salinity_t *water = (dc_salinity_t *) value; if (abstract->size < layout->headersize) return DC_STATUS_DATAFORMAT; if (value) { switch (type) { case DC_FIELD_TEMPERATURE_SURFACE: *((double *) value) = (data[layout->start_temp] - 32.0) / 1.8; break; case DC_FIELD_TEMPERATURE_MINIMUM: if (data[layout->min_temp] == 0xFF) return DC_STATUS_UNSUPPORTED; *((double *) value) = (data[layout->min_temp] / 2.0 + 20 - 32) / 1.8; break; case DC_FIELD_TEMPERATURE_MAXIMUM: if (layout->max_temp == UNSUPPORTED) return DC_STATUS_UNSUPPORTED; if (data[layout->max_temp] == 0xFF) return DC_STATUS_UNSUPPORTED; *((double *) value) = (data[layout->max_temp] / 2.0 + 20 - 32) / 1.8; break; case DC_FIELD_DIVETIME: minutes = array_uint16_le(data + layout->divetime); if (minutes == 0xFFFF) return DC_STATUS_UNSUPPORTED; *((unsigned int *) value) = minutes * 60; break; case DC_FIELD_MAXDEPTH: qfeet = array_uint16_le(data + layout->max_depth); if (qfeet == 0xFFFF) return DC_STATUS_UNSUPPORTED; *((double *) value) = qfeet / 4.0 * FEET; break; case DC_FIELD_AVGDEPTH: qfeet = array_uint16_le(data + layout->avg_depth); if (qfeet == 0xFFFF) return DC_STATUS_UNSUPPORTED; *((double *) value) = qfeet / 4.0 * FEET; break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = 2; break; case DC_FIELD_GASMIX: // Gas percentages are decimal and encoded as // highbyte = integer portion // lowbyte = decimal portion, divide by 256 to get decimal value gasmix->oxygen = array_uint16_le (data + layout->oxygen + 2 * flags) / 256.0 / 100; if (layout->helium == UNSUPPORTED) { gasmix->helium = 0; } else { gasmix->helium = array_uint16_le (data + layout->helium + 2 * flags) / 256.0 / 100; } gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium; break; case DC_FIELD_SALINITY: // 0x00 = low conductivity, 0x10 = high, maybe there's a 0x01 and 0x11? // Assume Cochran's conductivity ranges from 0 to 3 // 0 is fresh water, anything else is sea water // for density assume // 0 = 1000kg/m³, 2 = 1025kg/m³ // and other values are linear if (layout->water_conductivity == UNSUPPORTED) return DC_STATUS_UNSUPPORTED; if ((data[layout->water_conductivity] & 0x3) == 0) water->type = DC_WATER_FRESH; else water->type = DC_WATER_SALT; water->density = 1000.0 + 12.5 * (data[layout->water_conductivity] & 0x3); break; case DC_FIELD_ATMOSPHERIC: // Cochran measures air pressure and stores it as altitude. // Convert altitude (measured in 1/4 kilofeet) back to pressure. if (layout->altitude == UNSUPPORTED) return DC_STATUS_UNSUPPORTED; *(double *) value = ATM / BAR * pow(1 - 0.0000225577 * data[layout->altitude] * 250.0 * FEET, 5.25588); break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } /* * Parse early Commander computers */ static dc_status_t cochran_commander_parser_samples_foreach_tm (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { cochran_commander_parser_t *parser = (cochran_commander_parser_t *) abstract; const cochran_parser_layout_t *layout = parser->layout; const unsigned char *data = abstract->data; const unsigned char *samples = data + layout->headersize; if (abstract->size < layout->headersize) return DC_STATUS_DATAFORMAT; unsigned int size = abstract->size - layout->headersize; unsigned int sample_interval = data[layout->pt_sample_interval]; dc_sample_value_t sample = {0}; unsigned int time = 0, last_sample_time = 0; unsigned int offset = 2; unsigned int deco_ceiling = 0; unsigned int temp = samples[0]; // Half degrees F unsigned int depth = samples[1]; // Half feet last_sample_time = sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); sample.depth = (depth / 2.0) * FEET; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); sample.temperature = (temp / 2.0 - 32.0) / 1.8; if (callback) callback (DC_SAMPLE_TEMPERATURE, sample, userdata); sample.gasmix = 0; if (callback) callback(DC_SAMPLE_GASMIX, sample, userdata); while (offset < size) { const unsigned char *s = samples + offset; sample.time = time; if (last_sample_time != sample.time) { // We haven't issued this time yet. last_sample_time = sample.time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); } if (*s & 0x80) { // Event or temperate change byte if (*s & 0x60) { // Event byte switch (*s) { case 0xC5: // Deco obligation begins break; case 0xD8: // Deco obligation ends break; case 0xAB: // Decrement ceiling (deeper) deco_ceiling += 10; // feet sample.deco.type = DC_DECO_DECOSTOP; sample.deco.time = 60; // We don't know the duration sample.deco.depth = deco_ceiling * FEET; if (callback) callback(DC_SAMPLE_DECO, sample, userdata); break; case 0xAD: // Increment ceiling (shallower) deco_ceiling -= 10; // feet sample.deco.type = DC_DECO_DECOSTOP; sample.deco.depth = deco_ceiling * FEET; sample.deco.time = 60; // We don't know the duration if (callback) callback(DC_SAMPLE_DECO, sample, userdata); break; default: cochran_commander_handle_event(parser, s[0], callback, userdata); break; } } else { // Temp change if (*s & 0x10) temp -= (*s & 0x0f); else temp += (*s & 0x0f); sample.temperature = (temp / 2.0 - 32.0) / 1.8; if (callback) callback (DC_SAMPLE_TEMPERATURE, sample, userdata); } offset++; continue; } // Depth sample if (s[0] & 0x40) depth -= s[0] & 0x3f; else depth += s[0] & 0x3f; sample.depth = (depth / 2.0) * FEET; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); offset++; time += sample_interval; } return DC_STATUS_SUCCESS; } /* * Parse Commander I (Pre-21000 s/n), II and EMC computers */ static dc_status_t cochran_commander_parser_samples_foreach_emc (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { cochran_commander_parser_t *parser = (cochran_commander_parser_t *) abstract; const cochran_parser_layout_t *layout = parser->layout; const unsigned char *data = abstract->data; const unsigned char *samples = data + layout->headersize; const unsigned char *last_sample = NULL; if (abstract->size < layout->headersize) return DC_STATUS_DATAFORMAT; unsigned int size = abstract->size - layout->headersize; dc_sample_value_t sample = {0}; unsigned int time = 0, last_sample_time = 0; unsigned int offset = 0; double start_depth = 0; int depth = 0; unsigned int deco_obligation = 0; unsigned int deco_ceiling = 0; unsigned int corrupt_dive = 0; // In rare circumstances Cochran computers won't record the end-of-dive // log entry block. When the end-sample pointer is 0xFFFFFFFF it's corrupt. // That means we don't really know where the dive samples end and we don't // know what the dive summary values are (i.e. max depth, min temp) if (array_uint32_le(data + layout->pt_profile_end) == 0xFFFFFFFF) { corrupt_dive = 1; dc_datetime_t d; cochran_commander_parser_get_datetime(abstract, &d); WARNING(abstract->context, "Incomplete dive on %02d/%02d/%02d at %02d:%02d:%02d, trying to parse samples", d.year, d.month, d.day, d.hour, d.minute, d.second); // Eliminate inter-dive events size = cochran_commander_backparse(parser, samples, size); } // Cochran samples depth every second and varies between ascent rate // and temp every other second. // Prime values from the dive log section if (parser->model == COCHRAN_MODEL_COMMANDER_AIR_NITROX || parser->model == COCHRAN_MODEL_COMMANDER_PRE21000) { // Commander stores start depth in quarter-feet start_depth = array_uint16_le (data + layout->start_depth) / 4.0; } else { // EMC stores start depth in 256ths of a foot. start_depth = array_uint16_le (data + layout->start_depth) / 256.0; } last_sample_time = sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); sample.depth = start_depth * FEET; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); sample.temperature = (data[layout->start_temp] - 32.0) / 1.8; if (callback) callback (DC_SAMPLE_TEMPERATURE, sample, userdata); sample.gasmix = 0; if (callback) callback(DC_SAMPLE_GASMIX, sample, userdata); unsigned int last_gasmix = sample.gasmix; while (offset < size) { const unsigned char *s = samples + offset; sample.time = time; if (last_sample_time != sample.time) { // We haven't issued this time yet. last_sample_time = sample.time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); } // If corrupt_dive end before offset if (corrupt_dive) { // When we aren't sure where the sample data ends we can // look for events that shouldn't be in the sample data. // 0xFF is unwritten memory // 0xA8 indicates start of post-dive interval // 0xE3 (switch to FO2 mode) and 0xF3 (switch to blend 1) occur // at dive start so when we see them after the first second we // found the beginning of the next dive. if (s[0] == 0xFF || s[0] == 0xA8) { DEBUG(abstract->context, "Used corrupt dive breakout 1 on event %02x", s[0]); break; } if (time > 1 && (s[0] == 0xE3 || s[0] == 0xF3)) { DEBUG(abstract->context, "Used corrupt dive breakout 2 on event %02x", s[0]); break; } } // Check for event if (s[0] & 0x80) { offset += cochran_commander_handle_event(parser, s[0], callback, userdata); // Events indicating change in deco status switch (s[0]) { case 0xC5: // Deco obligation begins deco_obligation = 1; break; case 0xD8: // Deco obligation ends deco_obligation = 0; break; case 0xAB: // Decrement ceiling (deeper) deco_ceiling += 10; // feet sample.deco.type = DC_DECO_DECOSTOP; sample.deco.time = (array_uint16_le(s + 3) + 1) * 60; sample.deco.depth = deco_ceiling * FEET; if (callback) callback(DC_SAMPLE_DECO, sample, userdata); break; case 0xAD: // Increment ceiling (shallower) deco_ceiling -= 10; // feet sample.deco.type = DC_DECO_DECOSTOP; sample.deco.depth = deco_ceiling * FEET; sample.deco.time = (array_uint16_le(s + 3) + 1) * 60; if (callback) callback(DC_SAMPLE_DECO, sample, userdata); break; case 0xC0: // Switched to FO2 21% mode (surface) // Event seen upon surfacing break; case 0xCD: // Switched to deco blend case 0xEF: // Switched to gas blend 2 if (last_gasmix != 1) { sample.gasmix = 1; if (callback) callback(DC_SAMPLE_GASMIX, sample, userdata); last_gasmix = sample.gasmix; } break; case 0xF3: // Switched to gas blend 1 if (last_gasmix != 0) { sample.gasmix = 0; if (callback) callback(DC_SAMPLE_GASMIX, sample, userdata); last_gasmix = sample.gasmix; } break; } continue; } // Make sure we have a full sample if (offset + layout->samplesize > size) break; // Depth is logged as change in feet, bit 0x40 means negative depth if (s[0] & 0x40) depth -= (s[0] & 0x3f); else depth += (s[0] & 0x3f); sample.depth = (start_depth + depth / 4.0) * FEET; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); // Ascent rate is logged in the 0th sample, temp in the 1st, repeat. if (time % 2 == 0) { // Ascent rate double ascent_rate = 0.0; if (s[1] & 0x80) ascent_rate = (s[1] & 0x7f); else ascent_rate = -(s[1] & 0x7f); ascent_rate *= FEET / 4.0; } else { // Temperature logged in half degrees F above 20 double temperature = s[1] / 2.0 + 20.0; sample.temperature = (temperature - 32.0) / 1.8; if (callback) callback (DC_SAMPLE_TEMPERATURE, sample, userdata); } // Cochran EMC models store NDL and deco stop time // in the 20th to 23rd sample if (layout->format == SAMPLE_EMC) { // Tissue load is recorded across 20 samples, we ignore them // NDL and deco stop time is recorded across the next 4 samples // The first 2 are either NDL or stop time at deepest stop (if in deco) // The next 2 are total deco stop time. unsigned int deco_time = 0; switch (time % 24) { case 21: deco_time = last_sample[2] + s[2] * 256 + 1; if (deco_obligation) { /* Deco time for deepest stop, unused */ } else { /* Send deco NDL sample */ sample.deco.type = DC_DECO_NDL; sample.deco.time = deco_time * 60; sample.deco.depth = 0; if (callback) callback (DC_SAMPLE_DECO, sample, userdata); } break; case 23: /* Deco time, total obligation */ deco_time = last_sample[2] + s[2] * 256 + 1; if (deco_obligation) { sample.deco.type = DC_DECO_DECOSTOP; sample.deco.depth = deco_ceiling * FEET; sample.deco.time = deco_time * 60; if (callback) callback (DC_SAMPLE_DECO, sample, userdata); } break; } last_sample = s; } time++; offset += layout->samplesize; } return DC_STATUS_SUCCESS; } static dc_status_t cochran_commander_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { cochran_commander_parser_t *parser = (cochran_commander_parser_t *) abstract; if (parser->model == COCHRAN_MODEL_COMMANDER_TM) return cochran_commander_parser_samples_foreach_tm (abstract, callback, userdata); else return cochran_commander_parser_samples_foreach_emc (abstract, callback, userdata); }
libdc-for-dirk-Subsurface-branch
src/cochran_commander_parser.c
/* * libdivecomputer * * Copyright (C) 2016 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stddef.h> #include <stdlib.h> #include <assert.h> #include "iostream-private.h" #include "context-private.h" dc_iostream_t * dc_iostream_allocate (dc_context_t *context, const dc_iostream_vtable_t *vtable) { dc_iostream_t *iostream = NULL; assert(vtable != NULL); assert(vtable->size >= sizeof(dc_iostream_t)); // Allocate memory. iostream = (dc_iostream_t *) malloc (vtable->size); if (iostream == NULL) { ERROR (context, "Failed to allocate memory."); return iostream; } // Initialize the base class. iostream->vtable = vtable; iostream->context = context; return iostream; } void dc_iostream_deallocate (dc_iostream_t *iostream) { free (iostream); } int dc_iostream_isinstance (dc_iostream_t *iostream, const dc_iostream_vtable_t *vtable) { if (iostream == NULL) return 0; return iostream->vtable == vtable; } dc_status_t dc_iostream_set_timeout (dc_iostream_t *iostream, int timeout) { if (iostream == NULL || iostream->vtable->set_timeout == NULL) return DC_STATUS_UNSUPPORTED; INFO (iostream->context, "Timeout: value=%i", timeout); return iostream->vtable->set_timeout (iostream, timeout); } dc_status_t dc_iostream_set_latency (dc_iostream_t *iostream, unsigned int value) { if (iostream == NULL || iostream->vtable->set_latency == NULL) return DC_STATUS_UNSUPPORTED; INFO (iostream->context, "Latency: value=%i", value); return iostream->vtable->set_latency (iostream, value); } dc_status_t dc_iostream_set_break (dc_iostream_t *iostream, unsigned int value) { if (iostream == NULL || iostream->vtable->set_break == NULL) return DC_STATUS_UNSUPPORTED; INFO (iostream->context, "Break: value=%i", value); return iostream->vtable->set_break (iostream, value); } dc_status_t dc_iostream_set_dtr (dc_iostream_t *iostream, unsigned int value) { if (iostream == NULL || iostream->vtable->set_dtr == NULL) return DC_STATUS_UNSUPPORTED; INFO (iostream->context, "DTR: value=%i", value); return iostream->vtable->set_dtr (iostream, value); } dc_status_t dc_iostream_set_rts (dc_iostream_t *iostream, unsigned int value) { if (iostream == NULL || iostream->vtable->set_rts == NULL) return DC_STATUS_UNSUPPORTED; INFO (iostream->context, "RTS: value=%i", value); return iostream->vtable->set_rts (iostream, value); } dc_status_t dc_iostream_get_lines (dc_iostream_t *iostream, unsigned int *value) { if (iostream == NULL || iostream->vtable->get_lines == NULL) return DC_STATUS_UNSUPPORTED; return iostream->vtable->get_lines (iostream, value); } dc_status_t dc_iostream_get_available (dc_iostream_t *iostream, size_t *value) { if (iostream == NULL || iostream->vtable->get_available == NULL) return DC_STATUS_UNSUPPORTED; return iostream->vtable->get_available (iostream, value); } dc_status_t dc_iostream_configure (dc_iostream_t *iostream, unsigned int baudrate, unsigned int databits, dc_parity_t parity, dc_stopbits_t stopbits, dc_flowcontrol_t flowcontrol) { if (iostream == NULL || iostream->vtable->configure == NULL) return DC_STATUS_UNSUPPORTED; INFO (iostream->context, "Configure: baudrate=%i, databits=%i, parity=%i, stopbits=%i, flowcontrol=%i", baudrate, databits, parity, stopbits, flowcontrol); return iostream->vtable->configure (iostream, baudrate, databits, parity, stopbits, flowcontrol); } dc_status_t dc_iostream_read (dc_iostream_t *iostream, void *data, size_t size, size_t *actual) { dc_status_t status = DC_STATUS_SUCCESS; size_t nbytes = 0; if (iostream == NULL || iostream->vtable->read == NULL) { status = DC_STATUS_UNSUPPORTED; goto out; } status = iostream->vtable->read (iostream, data, size, &nbytes); HEXDUMP (iostream->context, DC_LOGLEVEL_INFO, "Read", (unsigned char *) data, nbytes); out: if (actual) *actual = nbytes; return status; } dc_status_t dc_iostream_write (dc_iostream_t *iostream, const void *data, size_t size, size_t *actual) { dc_status_t status = DC_STATUS_SUCCESS; size_t nbytes = 0; if (iostream == NULL || iostream->vtable->read == NULL) { status = DC_STATUS_UNSUPPORTED; goto out; } status = iostream->vtable->write (iostream, data, size, &nbytes); HEXDUMP (iostream->context, DC_LOGLEVEL_INFO, "Write", (const unsigned char *) data, nbytes); out: if (actual) *actual = nbytes; return status; } dc_status_t dc_iostream_flush (dc_iostream_t *iostream) { if (iostream == NULL || iostream->vtable->flush == NULL) return DC_STATUS_UNSUPPORTED; INFO (iostream->context, "Flush: none"); return iostream->vtable->flush (iostream); } dc_status_t dc_iostream_purge (dc_iostream_t *iostream, dc_direction_t direction) { if (iostream == NULL || iostream->vtable->purge == NULL) return DC_STATUS_UNSUPPORTED; INFO (iostream->context, "Purge: direction=%u", direction); return iostream->vtable->purge (iostream, direction); } dc_status_t dc_iostream_sleep (dc_iostream_t *iostream, unsigned int milliseconds) { if (iostream == NULL || iostream->vtable->sleep == NULL) return DC_STATUS_UNSUPPORTED; INFO (iostream->context, "Sleep: value=%u", milliseconds); return iostream->vtable->sleep (iostream, milliseconds); } dc_status_t dc_iostream_close (dc_iostream_t *iostream) { dc_status_t status = DC_STATUS_SUCCESS; if (iostream == NULL) return DC_STATUS_SUCCESS; if (iostream->vtable->close) { status = iostream->vtable->close (iostream); } dc_iostream_deallocate (iostream); return status; }
libdc-for-dirk-Subsurface-branch
src/iostream.c
/* * libdivecomputer * * Copyright (C) 2010 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcpy, memcmp #include <stdlib.h> // malloc, free #include <assert.h> // assert #include "zeagle_n2ition3.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "checksum.h" #include "array.h" #include "ringbuffer.h" #include "rbstream.h" #define ISINSTANCE(device) dc_device_isinstance((device), &zeagle_n2ition3_device_vtable) #define SZ_MEMORY 0x8000 #define SZ_PACKET 64 #define RB_PROFILE_BEGIN 0x3FA0 #define RB_PROFILE_END 0x7EC0 #define RB_LOGBOOK_OFFSET 0x7EC0 #define RB_LOGBOOK_BEGIN 0 #define RB_LOGBOOK_END 60 typedef struct zeagle_n2ition3_device_t { dc_device_t base; dc_iostream_t *iostream; unsigned char fingerprint[16]; } zeagle_n2ition3_device_t; static dc_status_t zeagle_n2ition3_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t zeagle_n2ition3_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size); static dc_status_t zeagle_n2ition3_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t zeagle_n2ition3_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t zeagle_n2ition3_device_close (dc_device_t *abstract); static const dc_device_vtable_t zeagle_n2ition3_device_vtable = { sizeof(zeagle_n2ition3_device_t), DC_FAMILY_ZEAGLE_N2ITION3, zeagle_n2ition3_device_set_fingerprint, /* set_fingerprint */ zeagle_n2ition3_device_read, /* read */ NULL, /* write */ zeagle_n2ition3_device_dump, /* dump */ zeagle_n2ition3_device_foreach, /* foreach */ NULL, /* timesync */ zeagle_n2ition3_device_close /* close */ }; static dc_status_t zeagle_n2ition3_packet (zeagle_n2ition3_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; assert (asize >= csize + 5); if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; // Send the command to the device. status = dc_iostream_write (device->iostream, command, csize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Receive the answer of the device. status = dc_iostream_read (device->iostream, answer, asize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Verify the echo. if (memcmp (answer, command, csize) != 0) { ERROR (abstract->context, "Unexpected echo."); return DC_STATUS_PROTOCOL; } // Verify the header and trailer of the packet. if (answer[csize] != 0x02 && answer[asize - 1] != 0x03) { ERROR (abstract->context, "Unexpected answer header/trailer byte."); return DC_STATUS_PROTOCOL; } // Verify the size of the packet. if (array_uint16_le (answer + csize + 1) + csize + 5 != asize) { ERROR (abstract->context, "Unexpected answer size."); return DC_STATUS_PROTOCOL; } // Verify the checksum of the packet. unsigned char crc = answer[asize - 2]; unsigned char ccrc = ~checksum_add_uint8 (answer + csize + 3, asize - csize - 5, 0x00) + 1; if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } static dc_status_t zeagle_n2ition3_init (zeagle_n2ition3_device_t *device) { unsigned char answer[6 + 13] = {0}; unsigned char command[6] = {0x02, 0x01, 0x00, 0x41, 0xBF, 0x03}; return zeagle_n2ition3_packet (device, command, sizeof (command), answer, sizeof (answer)); } dc_status_t zeagle_n2ition3_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; zeagle_n2ition3_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (zeagle_n2ition3_device_t *) dc_device_allocate (context, &zeagle_n2ition3_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; memset (device->fingerprint, 0, sizeof (device->fingerprint)); // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (4800 8N1). status = dc_iostream_configure (device->iostream, 4800, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (1000 ms). status = dc_iostream_set_timeout (device->iostream, 1000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Make sure everything is in a sane state. dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); // Send the init commands. zeagle_n2ition3_init (device); *out = (dc_device_t *) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t zeagle_n2ition3_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; zeagle_n2ition3_device_t *device = (zeagle_n2ition3_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t zeagle_n2ition3_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { zeagle_n2ition3_device_t *device = (zeagle_n2ition3_device_t *) abstract; if (size && size != sizeof (device->fingerprint)) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, sizeof (device->fingerprint)); else memset (device->fingerprint, 0, sizeof (device->fingerprint)); return DC_STATUS_SUCCESS; } static dc_status_t zeagle_n2ition3_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size) { zeagle_n2ition3_device_t *device = (zeagle_n2ition3_device_t*) abstract; unsigned int nbytes = 0; while (nbytes < size) { // Calculate the package size. unsigned int len = size - nbytes; if (len > SZ_PACKET) len = SZ_PACKET; // Read the package. unsigned char answer[13 + SZ_PACKET + 6] = {0}; unsigned char command[13] = {0x02, 0x08, 0x00, 0x4D, (address ) & 0xFF, // low (address >> 8) & 0xFF, // high len, // count 0x00, 0x00, 0x00, 0x00, 0x00, 0x03}; command[11] = ~checksum_add_uint8 (command + 3, 8, 0x00) + 1; dc_status_t rc = zeagle_n2ition3_packet (device, command, sizeof (command), answer, 13 + len + 6); if (rc != DC_STATUS_SUCCESS) return rc; memcpy (data, answer + 17, len); nbytes += len; address += len; data += len; } return DC_STATUS_SUCCESS; } static dc_status_t zeagle_n2ition3_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { // Allocate the required amount of memory. if (!dc_buffer_resize (buffer, SZ_MEMORY)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } return device_dump_read (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), SZ_PACKET); } static dc_status_t zeagle_n2ition3_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { zeagle_n2ition3_device_t *device = (zeagle_n2ition3_device_t *) abstract; // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = (RB_LOGBOOK_END - RB_LOGBOOK_BEGIN) * 2 + 8 + (RB_PROFILE_END - RB_PROFILE_BEGIN); device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Read the configuration data. unsigned char config[(RB_LOGBOOK_END - RB_LOGBOOK_BEGIN) * 2 + 8] = {0}; dc_status_t rc = zeagle_n2ition3_device_read (abstract, RB_LOGBOOK_OFFSET, config, sizeof (config)); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the configuration data."); return rc; } // Get the logbook pointers. unsigned int last = config[0x7C]; unsigned int first = config[0x7D]; if (first < RB_LOGBOOK_BEGIN || first >= RB_LOGBOOK_END || last < RB_LOGBOOK_BEGIN || last >= RB_LOGBOOK_END) { if (last == 0xFF) return DC_STATUS_SUCCESS; ERROR (abstract->context, "Invalid ringbuffer pointer detected (0x%02x 0x%02x).", first, last); return DC_STATUS_DATAFORMAT; } // Get the number of logbook items. unsigned int count = ringbuffer_distance (first, last, 0, RB_LOGBOOK_BEGIN, RB_LOGBOOK_END) + 1; // Get the profile pointer. unsigned int eop = array_uint16_le (config + 0x7E); if (eop < RB_PROFILE_BEGIN || eop >= RB_PROFILE_END) { ERROR (abstract->context, "Invalid ringbuffer pointer detected (0x%04x).", eop); return DC_STATUS_DATAFORMAT; } // The logbook ringbuffer can store at most 60 dives, even if the profile // data could store more (e.g. many small dives). But it's also possible // that the profile ringbuffer is filled faster than the logbook ringbuffer // (e.g. many large dives). We detect this by checking the total length. unsigned int total = 0; unsigned int idx = last; unsigned int previous = eop; for (unsigned int i = 0; i < count; ++i) { // Get the pointer to the profile data. unsigned int current = array_uint16_le (config + 2 * idx); if (current < RB_PROFILE_BEGIN || current >= RB_PROFILE_END) { ERROR (abstract->context, "Invalid ringbuffer pointer detected (0x%04x).", current); return DC_STATUS_DATAFORMAT; } // Get the profile length. unsigned int length = ringbuffer_distance (current, previous, 1, RB_PROFILE_BEGIN, RB_PROFILE_END); // Check for a ringbuffer overflow. if (total + length > RB_PROFILE_END - RB_PROFILE_BEGIN) { count = i; break; } total += length; previous = current; if (idx == RB_LOGBOOK_BEGIN) idx = RB_LOGBOOK_END; idx--; } // Update and emit a progress event. progress.current += sizeof (config); progress.maximum = (RB_LOGBOOK_END - RB_LOGBOOK_BEGIN) * 2 + 8 + total; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Create the ringbuffer stream. dc_rbstream_t *rbstream = NULL; rc = dc_rbstream_new (&rbstream, abstract, 1, SZ_PACKET, RB_PROFILE_BEGIN, RB_PROFILE_END, eop); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to create the ringbuffer stream."); return rc; } // Memory buffer for the profile data. unsigned char buffer[RB_PROFILE_END - RB_PROFILE_BEGIN] = {0}; unsigned int offset = RB_PROFILE_END - RB_PROFILE_BEGIN; idx = last; previous = eop; for (unsigned int i = 0; i < count; ++i) { // Get the pointer to the profile data. unsigned int current = array_uint16_le (config + 2 * idx); // Get the profile length. unsigned int length = ringbuffer_distance (current, previous, 1, RB_PROFILE_BEGIN, RB_PROFILE_END); // Move to the begin of the current dive. offset -= length; // Read the dive. rc = dc_rbstream_read (rbstream, &progress, buffer + offset, length); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the dive."); dc_rbstream_free (rbstream); return rc; } unsigned char *p = buffer + offset; if (memcmp (p, device->fingerprint, sizeof (device->fingerprint)) == 0) { dc_rbstream_free (rbstream); return DC_STATUS_SUCCESS; } if (callback && !callback (p, length, p, sizeof (device->fingerprint), userdata)) { dc_rbstream_free (rbstream); return DC_STATUS_SUCCESS; } previous = current; if (idx == RB_LOGBOOK_BEGIN) idx = RB_LOGBOOK_END; idx--; } dc_rbstream_free (rbstream); return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/zeagle_n2ition3.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> // malloc, free #include <string.h> // strncmp, strstr #include "uwatec_smart.h" #include "context-private.h" #include "device-private.h" #include "irda.h" #include "array.h" #include "platform.h" #define ISINSTANCE(device) dc_device_isinstance((device), &uwatec_smart_device_vtable) #define C_ARRAY_SIZE(array) (sizeof (array) / sizeof *(array)) typedef struct uwatec_smart_device_t { dc_device_t base; dc_iostream_t *iostream; unsigned int timestamp; unsigned int devtime; dc_ticks_t systime; } uwatec_smart_device_t; static dc_status_t uwatec_smart_device_set_fingerprint (dc_device_t *device, const unsigned char data[], unsigned int size); static dc_status_t uwatec_smart_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t uwatec_smart_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t uwatec_smart_device_close (dc_device_t *abstract); static const dc_device_vtable_t uwatec_smart_device_vtable = { sizeof(uwatec_smart_device_t), DC_FAMILY_UWATEC_SMART, uwatec_smart_device_set_fingerprint, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ uwatec_smart_device_dump, /* dump */ uwatec_smart_device_foreach, /* foreach */ NULL, /* timesync */ uwatec_smart_device_close /* close */ }; static dc_status_t uwatec_smart_extract_dives (dc_device_t *device, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata); static int uwatec_smart_filter (const char *name) { static const char *names[] = { "Aladin Smart Com", "Aladin Smart Pro", "Aladin Smart Tec", "Aladin Smart Z", "Uwatec Aladin", "UWATEC Galileo", "UWATEC Galileo Sol", }; if (name == NULL) return 0; for (size_t i = 0; i < C_ARRAY_SIZE(names); ++i) { if (strcasecmp(name, names[i]) == 0) { return 1; } } return 0; } static dc_status_t uwatec_smart_transfer (uwatec_smart_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; status = dc_iostream_write (device->iostream, command, csize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } status = dc_iostream_read (device->iostream, answer, asize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } return DC_STATUS_SUCCESS; } static dc_status_t uwatec_smart_handshake (uwatec_smart_device_t *device) { dc_device_t *abstract = (dc_device_t *) device; // Command template. unsigned char answer[1] = {0}; unsigned char command[5] = {0x00, 0x10, 0x27, 0, 0}; // Handshake (stage 1). command[0] = 0x1B; dc_status_t rc = uwatec_smart_transfer (device, command, 1, answer, 1); if (rc != DC_STATUS_SUCCESS) return rc; // Verify the answer. if (answer[0] != 0x01) { ERROR (abstract->context, "Unexpected answer byte(s)."); return DC_STATUS_PROTOCOL; } // Handshake (stage 2). command[0] = 0x1C; rc = uwatec_smart_transfer (device, command, 5, answer, 1); if (rc != DC_STATUS_SUCCESS) return rc; // Verify the answer. if (answer[0] != 0x01) { ERROR (abstract->context, "Unexpected answer byte(s)."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } dc_status_t uwatec_smart_device_open (dc_device_t **out, dc_context_t *context) { dc_status_t status = DC_STATUS_SUCCESS; uwatec_smart_device_t *device = NULL; dc_iterator_t *iterator = NULL; dc_irda_device_t *dev = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (uwatec_smart_device_t *) dc_device_allocate (context, &uwatec_smart_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; device->timestamp = 0; device->systime = (dc_ticks_t) -1; device->devtime = 0; // Create the irda device iterator. status = dc_irda_iterator_new (&iterator, context, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to create the irda iterator."); goto error_free; } // Enumerate the irda devices. while (1) { dc_irda_device_t *current = NULL; status = dc_iterator_next (iterator, &current); if (status != DC_STATUS_SUCCESS) { if (status == DC_STATUS_DONE) { ERROR (context, "No dive computer found."); status = DC_STATUS_NODEVICE; } else { ERROR (context, "Failed to enumerate the irda devices."); } goto error_iterator_free; } if (uwatec_smart_filter (dc_irda_device_get_name (current))) { dev = current; break; } dc_irda_device_free (current); } // Open the irda socket. status = dc_irda_open (&device->iostream, context, dc_irda_device_get_address (dev), 1); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the irda socket."); goto error_device_free; } // Perform the handshaking. status = uwatec_smart_handshake (device); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to handshake with the device."); goto error_close; } *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_device_free: dc_irda_device_free (dev); error_iterator_free: dc_iterator_free (iterator); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t uwatec_smart_device_close (dc_device_t *abstract) { uwatec_smart_device_t *device = (uwatec_smart_device_t*) abstract; // Close the device and pass up the return code. return dc_iostream_close (device->iostream); } static dc_status_t uwatec_smart_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { uwatec_smart_device_t *device = (uwatec_smart_device_t*) abstract; if (size && size != 4) return DC_STATUS_INVALIDARGS; if (size) device->timestamp = array_uint32_le (data); else device->timestamp = 0; return DC_STATUS_SUCCESS; } static dc_status_t uwatec_smart_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { uwatec_smart_device_t *device = (uwatec_smart_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; device_event_emit (&device->base, DC_EVENT_PROGRESS, &progress); // Read the model number. unsigned char cmd_model[1] = {0x10}; unsigned char model[1] = {0}; rc = uwatec_smart_transfer (device, cmd_model, sizeof (cmd_model), model, sizeof (model)); if (rc != DC_STATUS_SUCCESS) return rc; // Read the serial number. unsigned char cmd_serial[1] = {0x14}; unsigned char serial[4] = {0}; rc = uwatec_smart_transfer (device, cmd_serial, sizeof (cmd_serial), serial, sizeof (serial)); if (rc != DC_STATUS_SUCCESS) return rc; // Read the device clock. unsigned char cmd_devtime[1] = {0x1A}; unsigned char devtime[4] = {0}; rc = uwatec_smart_transfer (device, cmd_devtime, sizeof (cmd_devtime), devtime, sizeof (devtime)); if (rc != DC_STATUS_SUCCESS) return rc; // Store the clock calibration values. device->systime = dc_datetime_now (); device->devtime = array_uint32_le (devtime); // Update and emit a progress event. progress.current += 9; device_event_emit (&device->base, DC_EVENT_PROGRESS, &progress); // Emit a clock event. dc_event_clock_t clock; clock.systime = device->systime; clock.devtime = device->devtime; device_event_emit (&device->base, DC_EVENT_CLOCK, &clock); // Emit a device info event. dc_event_devinfo_t devinfo; devinfo.model = model[0]; devinfo.firmware = 0; devinfo.serial = array_uint32_le (serial); device_event_emit (&device->base, DC_EVENT_DEVINFO, &devinfo); // Command template. unsigned char command[9] = {0x00, (device->timestamp ) & 0xFF, (device->timestamp >> 8 ) & 0xFF, (device->timestamp >> 16) & 0xFF, (device->timestamp >> 24) & 0xFF, 0x10, 0x27, 0, 0}; // Data Length. command[0] = 0xC6; unsigned char answer[4] = {0}; rc = uwatec_smart_transfer (device, command, sizeof (command), answer, sizeof (answer)); if (rc != DC_STATUS_SUCCESS) return rc; unsigned int length = array_uint32_le (answer); // Update and emit a progress event. progress.maximum = 4 + 9 + (length ? length + 4 : 0); progress.current += 4; device_event_emit (&device->base, DC_EVENT_PROGRESS, &progress); if (length == 0) return DC_STATUS_SUCCESS; // Allocate the required amount of memory. if (!dc_buffer_resize (buffer, length)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } unsigned char *data = dc_buffer_get_data (buffer); // Data. command[0] = 0xC4; rc = uwatec_smart_transfer (device, command, sizeof (command), answer, sizeof (answer)); if (rc != DC_STATUS_SUCCESS) return rc; unsigned int total = array_uint32_le (answer); // Update and emit a progress event. progress.current += 4; device_event_emit (&device->base, DC_EVENT_PROGRESS, &progress); if (total != length + 4) { ERROR (abstract->context, "Received an unexpected size."); return DC_STATUS_PROTOCOL; } unsigned int nbytes = 0; while (nbytes < length) { // Set the minimum packet size. unsigned int len = 32; // Increase the packet size if more data is immediately available. size_t available = 0; rc = dc_iostream_get_available (device->iostream, &available); if (rc == DC_STATUS_SUCCESS && available > len) len = available; // Limit the packet size to the total size. if (nbytes + len > length) len = length - nbytes; rc = dc_iostream_read (device->iostream, data + nbytes, len, NULL); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return rc; } // Update and emit a progress event. progress.current += len; device_event_emit (&device->base, DC_EVENT_PROGRESS, &progress); nbytes += len; } return DC_STATUS_SUCCESS; } static dc_status_t uwatec_smart_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { dc_buffer_t *buffer = dc_buffer_new (0); if (buffer == NULL) return DC_STATUS_NOMEMORY; dc_status_t rc = uwatec_smart_device_dump (abstract, buffer); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } rc = uwatec_smart_extract_dives (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), callback, userdata); dc_buffer_free (buffer); return rc; } static dc_status_t uwatec_smart_extract_dives (dc_device_t *abstract, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata) { if (abstract && !ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; const unsigned char header[4] = {0xa5, 0xa5, 0x5a, 0x5a}; // Search the data stream for start markers. unsigned int previous = size; unsigned int current = (size >= 4 ? size - 4 : 0); while (current > 0) { current--; if (memcmp (data + current, header, sizeof (header)) == 0) { // Get the length of the profile data. unsigned int len = array_uint32_le (data + current + 4); // Check for a buffer overflow. if (current + len > previous) return DC_STATUS_DATAFORMAT; if (callback && !callback (data + current, len, data + current + 8, 4, userdata)) return DC_STATUS_SUCCESS; // Prepare for the next dive. previous = current; current = (current >= 4 ? current - 4 : 0); } } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/uwatec_smart.c
/* * libdivecomputer * * Copyright (C) 2010 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <libdivecomputer/version.h> #ifdef HAVE_VERSION_SUFFIX #include "revision.h" #endif const char * dc_version (dc_version_t *version) { if (version) { version->major = DC_VERSION_MAJOR; version->minor = DC_VERSION_MINOR; version->micro = DC_VERSION_MICRO; } #ifdef HAVE_VERSION_SUFFIX return DC_VERSION " (" DC_VERSION_REVISION ")"; #else return DC_VERSION; #endif } int dc_version_check (unsigned int major, unsigned int minor, unsigned int micro) { return DC_VERSION_CHECK (major,minor,micro); }
libdc-for-dirk-Subsurface-branch
src/version.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <assert.h> #include <stdlib.h> #include <string.h> #include "suunto_d9.h" #include "suunto_eon.h" #include "suunto_eonsteel.h" #include "suunto_solution.h" #include "suunto_vyper2.h" #include "suunto_vyper.h" #include "reefnet_sensus.h" #include "reefnet_sensuspro.h" #include "reefnet_sensusultra.h" #include "uwatec_aladin.h" #include "uwatec_memomouse.h" #include "uwatec_meridian.h" #include "uwatec_smart.h" #include "oceanic_atom2.h" #include "oceanic_veo250.h" #include "oceanic_vtpro.h" #include "mares_darwin.h" #include "mares_iconhd.h" #include "mares_nemo.h" #include "mares_puck.h" #include "hw_frog.h" #include "hw_ostc.h" #include "hw_ostc3.h" #include "cressi_edy.h" #include "cressi_leonardo.h" #include "zeagle_n2ition3.h" #include "atomics_cobalt.h" #include "scubapro_g2.h" #include "shearwater_petrel.h" #include "shearwater_predator.h" #include "diverite_nitekq.h" #include "citizen_aqualand.h" #include "divesystem_idive.h" #include "cochran_commander.h" #include "device-private.h" #include "context-private.h" dc_device_t * dc_device_allocate (dc_context_t *context, const dc_device_vtable_t *vtable) { dc_device_t *device = NULL; assert(vtable != NULL); assert(vtable->size >= sizeof(dc_device_t)); // Allocate memory. device = (dc_device_t *) malloc (vtable->size); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return device; } device->vtable = vtable; device->context = context; device->event_mask = 0; device->event_callback = NULL; device->event_userdata = NULL; device->cancel_callback = NULL; device->cancel_userdata = NULL; memset (&device->devinfo, 0, sizeof (device->devinfo)); memset (&device->clock, 0, sizeof (device->clock)); return device; } void dc_device_deallocate (dc_device_t *device) { free (device); } dc_status_t dc_device_open (dc_device_t **out, dc_context_t *context, dc_descriptor_t *descriptor, const char *name) { dc_status_t rc = DC_STATUS_SUCCESS; dc_device_t *device = NULL; if (out == NULL || descriptor == NULL) return DC_STATUS_INVALIDARGS; switch (dc_descriptor_get_type (descriptor)) { case DC_FAMILY_SUUNTO_SOLUTION: rc = suunto_solution_device_open (&device, context, name); break; case DC_FAMILY_SUUNTO_EON: rc = suunto_eon_device_open (&device, context, name); break; case DC_FAMILY_SUUNTO_VYPER: rc = suunto_vyper_device_open (&device, context, name); break; case DC_FAMILY_SUUNTO_VYPER2: rc = suunto_vyper2_device_open (&device, context, name); break; case DC_FAMILY_SUUNTO_D9: rc = suunto_d9_device_open (&device, context, name, dc_descriptor_get_model (descriptor)); break; case DC_FAMILY_SUUNTO_EONSTEEL: rc = suunto_eonsteel_device_open (&device, context, name, dc_descriptor_get_model(descriptor)); break; case DC_FAMILY_UWATEC_ALADIN: rc = uwatec_aladin_device_open (&device, context, name); break; case DC_FAMILY_UWATEC_MEMOMOUSE: rc = uwatec_memomouse_device_open (&device, context, name); break; case DC_FAMILY_UWATEC_SMART: rc = uwatec_smart_device_open (&device, context); break; case DC_FAMILY_UWATEC_MERIDIAN: rc = uwatec_meridian_device_open (&device, context, name); break; case DC_FAMILY_UWATEC_G2: rc = scubapro_g2_device_open (&device, context, name, dc_descriptor_get_model (descriptor)); break; case DC_FAMILY_REEFNET_SENSUS: rc = reefnet_sensus_device_open (&device, context, name); break; case DC_FAMILY_REEFNET_SENSUSPRO: rc = reefnet_sensuspro_device_open (&device, context, name); break; case DC_FAMILY_REEFNET_SENSUSULTRA: rc = reefnet_sensusultra_device_open (&device, context, name); break; case DC_FAMILY_OCEANIC_VTPRO: rc = oceanic_vtpro_device_open (&device, context, name, dc_descriptor_get_model (descriptor)); break; case DC_FAMILY_OCEANIC_VEO250: rc = oceanic_veo250_device_open (&device, context, name); break; case DC_FAMILY_OCEANIC_ATOM2: rc = oceanic_atom2_device_open (&device, context, name, dc_descriptor_get_model (descriptor)); break; case DC_FAMILY_MARES_NEMO: rc = mares_nemo_device_open (&device, context, name); break; case DC_FAMILY_MARES_PUCK: rc = mares_puck_device_open (&device, context, name); break; case DC_FAMILY_MARES_DARWIN: rc = mares_darwin_device_open (&device, context, name, dc_descriptor_get_model (descriptor)); break; case DC_FAMILY_MARES_ICONHD: rc = mares_iconhd_device_open (&device, context, name); break; case DC_FAMILY_HW_OSTC: rc = hw_ostc_device_open (&device, context, name); break; case DC_FAMILY_HW_FROG: rc = hw_frog_device_open (&device, context, name); break; case DC_FAMILY_HW_OSTC3: rc = hw_ostc3_device_open (&device, context, name); break; case DC_FAMILY_CRESSI_EDY: rc = cressi_edy_device_open (&device, context, name); break; case DC_FAMILY_CRESSI_LEONARDO: rc = cressi_leonardo_device_open (&device, context, name); break; case DC_FAMILY_ZEAGLE_N2ITION3: rc = zeagle_n2ition3_device_open (&device, context, name); break; case DC_FAMILY_ATOMICS_COBALT: rc = atomics_cobalt_device_open (&device, context); break; case DC_FAMILY_SHEARWATER_PREDATOR: rc = shearwater_predator_device_open (&device, context, name); break; case DC_FAMILY_SHEARWATER_PETREL: rc = shearwater_petrel_device_open (&device, context, name); break; case DC_FAMILY_DIVERITE_NITEKQ: rc = diverite_nitekq_device_open (&device, context, name); break; case DC_FAMILY_CITIZEN_AQUALAND: rc = citizen_aqualand_device_open (&device, context, name); break; case DC_FAMILY_DIVESYSTEM_IDIVE: rc = divesystem_idive_device_open (&device, context, name, dc_descriptor_get_model (descriptor)); break; case DC_FAMILY_COCHRAN_COMMANDER: rc = cochran_commander_device_open (&device, context, name); break; default: return DC_STATUS_INVALIDARGS; } *out = device; return rc; } int dc_device_isinstance (dc_device_t *device, const dc_device_vtable_t *vtable) { if (device == NULL) return 0; return device->vtable == vtable; } dc_family_t dc_device_get_type (dc_device_t *device) { if (device == NULL) return DC_FAMILY_NULL; return device->vtable->type; } dc_status_t dc_device_set_cancel (dc_device_t *device, dc_cancel_callback_t callback, void *userdata) { if (device == NULL) return DC_STATUS_UNSUPPORTED; device->cancel_callback = callback; device->cancel_userdata = userdata; return DC_STATUS_SUCCESS; } dc_status_t dc_device_set_events (dc_device_t *device, unsigned int events, dc_event_callback_t callback, void *userdata) { if (device == NULL) return DC_STATUS_UNSUPPORTED; device->event_mask = events; device->event_callback = callback; device->event_userdata = userdata; return DC_STATUS_SUCCESS; } dc_status_t dc_device_set_fingerprint (dc_device_t *device, const unsigned char data[], unsigned int size) { if (device == NULL) return DC_STATUS_UNSUPPORTED; if (device->vtable->set_fingerprint == NULL) return DC_STATUS_UNSUPPORTED; return device->vtable->set_fingerprint (device, data, size); } dc_status_t dc_device_read (dc_device_t *device, unsigned int address, unsigned char data[], unsigned int size) { if (device == NULL) return DC_STATUS_UNSUPPORTED; if (device->vtable->read == NULL) return DC_STATUS_UNSUPPORTED; return device->vtable->read (device, address, data, size); } dc_status_t dc_device_write (dc_device_t *device, unsigned int address, const unsigned char data[], unsigned int size) { if (device == NULL) return DC_STATUS_UNSUPPORTED; if (device->vtable->write == NULL) return DC_STATUS_UNSUPPORTED; return device->vtable->write (device, address, data, size); } dc_status_t dc_device_dump (dc_device_t *device, dc_buffer_t *buffer) { if (device == NULL) return DC_STATUS_UNSUPPORTED; if (device->vtable->dump == NULL) return DC_STATUS_UNSUPPORTED; if (buffer == NULL) return DC_STATUS_INVALIDARGS; dc_buffer_clear (buffer); return device->vtable->dump (device, buffer); } dc_status_t device_dump_read (dc_device_t *device, unsigned char data[], unsigned int size, unsigned int blocksize) { if (device == NULL) return DC_STATUS_UNSUPPORTED; if (device->vtable->read == NULL) return DC_STATUS_UNSUPPORTED; // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = size; device_event_emit (device, DC_EVENT_PROGRESS, &progress); unsigned int nbytes = 0; while (nbytes < size) { // Calculate the packet size. unsigned int len = size - nbytes; if (len > blocksize) len = blocksize; // Read the packet. dc_status_t rc = device->vtable->read (device, nbytes, data + nbytes, len); if (rc != DC_STATUS_SUCCESS) return rc; // Update and emit a progress event. progress.current += len; device_event_emit (device, DC_EVENT_PROGRESS, &progress); nbytes += len; } return DC_STATUS_SUCCESS; } dc_status_t dc_device_foreach (dc_device_t *device, dc_dive_callback_t callback, void *userdata) { if (device == NULL) return DC_STATUS_UNSUPPORTED; if (device->vtable->foreach == NULL) return DC_STATUS_UNSUPPORTED; return device->vtable->foreach (device, callback, userdata); } dc_status_t dc_device_timesync (dc_device_t *device, const dc_datetime_t *datetime) { if (device == NULL) return DC_STATUS_UNSUPPORTED; if (device->vtable->timesync == NULL) return DC_STATUS_UNSUPPORTED; return device->vtable->timesync (device, datetime); } dc_status_t dc_device_close (dc_device_t *device) { dc_status_t status = DC_STATUS_SUCCESS; if (device == NULL) return DC_STATUS_SUCCESS; // Disable the cancellation callback. device->cancel_callback = NULL; device->cancel_userdata = NULL; if (device->vtable->close) { status = device->vtable->close (device); } dc_device_deallocate (device); return status; } void device_event_emit (dc_device_t *device, dc_event_type_t event, const void *data) { const dc_event_progress_t *progress = (const dc_event_progress_t *) data; // Check the event data for errors. switch (event) { case DC_EVENT_WAITING: assert (data == NULL); break; case DC_EVENT_PROGRESS: assert (progress != NULL); assert (progress->maximum != 0); assert (progress->maximum >= progress->current); break; case DC_EVENT_DEVINFO: assert (data != NULL); break; case DC_EVENT_CLOCK: assert (data != NULL); break; default: break; } if (device == NULL) return; // Cache the event data. switch (event) { case DC_EVENT_DEVINFO: device->devinfo = *(const dc_event_devinfo_t *) data; break; case DC_EVENT_CLOCK: device->clock = *(const dc_event_clock_t *) data; break; default: break; } // Check if there is a callback function registered. if (device->event_callback == NULL) return; // Check the event mask. if ((event & device->event_mask) == 0) return; device->event_callback (device, event, data, device->event_userdata); } int device_is_cancelled (dc_device_t *device) { if (device == NULL) return 0; if (device->cancel_callback == NULL) return 0; return device->cancel_callback (device->cancel_userdata); }
libdc-for-dirk-Subsurface-branch
src/device.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcmp, memcpy #include <stdlib.h> // malloc, free #include <assert.h> // assert #include "suunto_d9.h" #include "suunto_common2.h" #include "context-private.h" #include "serial.h" #include "checksum.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), (const dc_device_vtable_t *) &suunto_d9_device_vtable) #define C_ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a))) #define D4i 0x19 #define D6i 0x1A #define D9tx 0x1B #define DX 0x1C #define VYPERNOVO 0x1D #define ZOOPNOVO 0x1E #define D4F 0x20 typedef struct suunto_d9_device_t { suunto_common2_device_t base; dc_iostream_t *iostream; } suunto_d9_device_t; static dc_status_t suunto_d9_device_packet (dc_device_t *abstract, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize, unsigned int size); static dc_status_t suunto_d9_device_close (dc_device_t *abstract); static const suunto_common2_device_vtable_t suunto_d9_device_vtable = { { sizeof(suunto_d9_device_t), DC_FAMILY_SUUNTO_D9, suunto_common2_device_set_fingerprint, /* set_fingerprint */ suunto_common2_device_read, /* read */ suunto_common2_device_write, /* write */ suunto_common2_device_dump, /* dump */ suunto_common2_device_foreach, /* foreach */ NULL, /* timesync */ suunto_d9_device_close /* close */ }, suunto_d9_device_packet }; static const suunto_common2_layout_t suunto_d9_layout = { 0x8000, /* memsize */ 0x0011, /* fingerprint */ 0x0023, /* serial */ 0x019A, /* rb_profile_begin */ 0x7FFE /* rb_profile_end */ }; static const suunto_common2_layout_t suunto_d9tx_layout = { 0x10000, /* memsize */ 0x0013, /* fingerprint */ 0x0024, /* serial */ 0x019A, /* rb_profile_begin */ 0xEBF0 /* rb_profile_end */ }; static const suunto_common2_layout_t suunto_dx_layout = { 0x10000, /* memsize */ 0x0017, /* fingerprint */ 0x0024, /* serial */ 0x019A, /* rb_profile_begin */ 0xEBF0 /* rb_profile_end */ }; static dc_status_t suunto_d9_device_autodetect (suunto_d9_device_t *device, unsigned int model) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; // The list with possible baudrates. const int baudrates[] = {9600, 115200}; // Use the model number as a hint to speedup the detection. unsigned int hint = 0; if (model == D4i || model == D6i || model == D9tx || model == DX || model == VYPERNOVO || model == ZOOPNOVO || model == D4F) hint = 1; for (unsigned int i = 0; i < C_ARRAY_SIZE(baudrates); ++i) { // Use the baudrate array as circular array, starting from the hint. unsigned int idx = (hint + i) % C_ARRAY_SIZE(baudrates); // Adjust the baudrate. status = dc_iostream_configure (device->iostream, baudrates[idx], 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to set the terminal attributes."); return status; } // Try reading the version info. status = suunto_common2_device_version ((dc_device_t *) device, device->base.version, sizeof (device->base.version)); if (status == DC_STATUS_SUCCESS) break; } return status; } dc_status_t suunto_d9_device_open (dc_device_t **out, dc_context_t *context, const char *name, unsigned int model) { dc_status_t status = DC_STATUS_SUCCESS; suunto_d9_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (suunto_d9_device_t *) dc_device_allocate (context, &suunto_d9_device_vtable.base); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Initialize the base class. suunto_common2_device_init (&device->base); // Set the default values. device->iostream = NULL; // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (9600 8N1). status = dc_iostream_configure (device->iostream, 9600, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (3000 ms). status = dc_iostream_set_timeout (device->iostream, 3000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Set the DTR line (power supply for the interface). status = dc_iostream_set_dtr (device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the DTR line."); goto error_close; } // Give the interface 100 ms to settle and draw power up. dc_iostream_sleep (device->iostream, 100); // Make sure everything is in a sane state. dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); // Try to autodetect the protocol variant. status = suunto_d9_device_autodetect (device, model); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to identify the protocol variant."); goto error_close; } // Override the base class values. model = device->base.version[0]; if (model == D4i || model == D6i || model == D9tx || model == VYPERNOVO || model == ZOOPNOVO || model == D4F) device->base.layout = &suunto_d9tx_layout; else if (model == DX) device->base.layout = &suunto_dx_layout; else device->base.layout = &suunto_d9_layout; *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t suunto_d9_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; suunto_d9_device_t *device = (suunto_d9_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t suunto_d9_device_packet (dc_device_t *abstract, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize, unsigned int size) { dc_status_t status = DC_STATUS_SUCCESS; suunto_d9_device_t *device = (suunto_d9_device_t *) abstract; if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; // Clear RTS to send the command. status = dc_iostream_set_rts (device->iostream, 0); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to clear RTS."); return status; } // Send the command to the dive computer. status = dc_iostream_write (device->iostream, command, csize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Receive the echo. unsigned char echo[128] = {0}; assert (sizeof (echo) >= csize); status = dc_iostream_read (device->iostream, echo, csize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the echo."); return status; } // Verify the echo. if (memcmp (command, echo, csize) != 0) { ERROR (abstract->context, "Unexpected echo."); return DC_STATUS_PROTOCOL; } // Set RTS to receive the reply. status = dc_iostream_set_rts (device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to set RTS."); return status; } // Receive the answer of the dive computer. status = dc_iostream_read (device->iostream, answer, asize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Verify the header of the package. if (answer[0] != command[0]) { ERROR (abstract->context, "Unexpected answer header."); return DC_STATUS_PROTOCOL; } // Verify the size of the package. if (array_uint16_be (answer + 1) + 4 != asize) { ERROR (abstract->context, "Unexpected answer size."); return DC_STATUS_PROTOCOL; } // Verify the parameters of the package. if (memcmp (command + 3, answer + 3, asize - size - 4) != 0) { ERROR (abstract->context, "Unexpected answer parameters."); return DC_STATUS_PROTOCOL; } // Verify the checksum of the package. unsigned char crc = answer[asize - 1]; unsigned char ccrc = checksum_xor_uint8 (answer, asize - 1, 0x00); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } dc_status_t suunto_d9_device_version (dc_device_t *abstract, unsigned char data[], unsigned int size) { if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; return suunto_common2_device_version (abstract, data, size); } dc_status_t suunto_d9_device_reset_maxdepth (dc_device_t *abstract) { if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; return suunto_common2_device_reset_maxdepth (abstract); }
libdc-for-dirk-Subsurface-branch
src/suunto_d9.c
/* * libdivecomputer * * Copyright (C) 2012 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #ifdef _MSC_VER #define snprintf _snprintf #endif #include <libdivecomputer/units.h> #include "shearwater_predator.h" #include "shearwater_petrel.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) ( \ dc_parser_isinstance((parser), &shearwater_predator_parser_vtable) || \ dc_parser_isinstance((parser), &shearwater_petrel_parser_vtable)) #define SZ_BLOCK 0x80 #define SZ_SAMPLE_PREDATOR 0x10 #define SZ_SAMPLE_PETREL 0x20 #define GASSWITCH 0x01 #define PPO2_EXTERNAL 0x02 #define SETPOINT_HIGH 0x04 #define SC 0x08 #define OC 0x10 #define METRIC 0 #define IMPERIAL 1 #define NGASMIXES 10 #define MAXSTRINGS 32 #define PREDATOR 2 #define PETREL 3 typedef struct shearwater_predator_parser_t shearwater_predator_parser_t; struct shearwater_predator_parser_t { dc_parser_t base; unsigned int model; unsigned int petrel; unsigned int samplesize; // Cached fields. unsigned int cached; unsigned int logversion; unsigned int headersize; unsigned int footersize; unsigned int ngasmixes; unsigned int oxygen[NGASMIXES]; unsigned int helium[NGASMIXES]; unsigned int calibrated; double calibration[3]; unsigned int serial; dc_divemode_t mode; /* String fields */ dc_field_string_t strings[MAXSTRINGS]; }; static dc_status_t shearwater_predator_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t shearwater_predator_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t shearwater_predator_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t shearwater_predator_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t shearwater_predator_parser_vtable = { sizeof(shearwater_predator_parser_t), DC_FAMILY_SHEARWATER_PREDATOR, shearwater_predator_parser_set_data, /* set_data */ shearwater_predator_parser_get_datetime, /* datetime */ shearwater_predator_parser_get_field, /* fields */ shearwater_predator_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; static const dc_parser_vtable_t shearwater_petrel_parser_vtable = { sizeof(shearwater_predator_parser_t), DC_FAMILY_SHEARWATER_PETREL, shearwater_predator_parser_set_data, /* set_data */ shearwater_predator_parser_get_datetime, /* datetime */ shearwater_predator_parser_get_field, /* fields */ shearwater_predator_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; static unsigned int shearwater_predator_find_gasmix (shearwater_predator_parser_t *parser, unsigned int o2, unsigned int he) { unsigned int i = 0; while (i < parser->ngasmixes) { if (o2 == parser->oxygen[i] && he == parser->helium[i]) break; i++; } return i; } static dc_status_t shearwater_common_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int model, unsigned int serial, unsigned int petrel) { shearwater_predator_parser_t *parser = NULL; const dc_parser_vtable_t *vtable = NULL; unsigned int samplesize = 0; if (out == NULL) return DC_STATUS_INVALIDARGS; if (petrel) { vtable = &shearwater_petrel_parser_vtable; samplesize = SZ_SAMPLE_PETREL; } else { vtable = &shearwater_predator_parser_vtable; samplesize = SZ_SAMPLE_PREDATOR; } // Allocate memory. parser = (shearwater_predator_parser_t *) dc_parser_allocate (context, vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. parser->model = model; parser->petrel = petrel; parser->samplesize = samplesize; parser->serial = serial; // Set the default values. parser->cached = 0; parser->logversion = 0; parser->headersize = 0; parser->footersize = 0; parser->ngasmixes = 0; for (unsigned int i = 0; i < NGASMIXES; ++i) { parser->oxygen[i] = 0; parser->helium[i] = 0; } parser->calibrated = 0; for (unsigned int i = 0; i < 3; ++i) { parser->calibration[i] = 0.0; } parser->mode = DC_DIVEMODE_OC; *out = (dc_parser_t *) parser; return DC_STATUS_SUCCESS; } dc_status_t shearwater_predator_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int model, unsigned int serial) { return shearwater_common_parser_create (out, context, model, serial, 0); } dc_status_t shearwater_petrel_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int model, unsigned int serial) { return shearwater_common_parser_create (out, context, model, serial, 1); } static dc_status_t shearwater_predator_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { shearwater_predator_parser_t *parser = (shearwater_predator_parser_t *) abstract; // Reset the cache. parser->cached = 0; parser->logversion = 0; parser->headersize = 0; parser->footersize = 0; parser->ngasmixes = 0; for (unsigned int i = 0; i < NGASMIXES; ++i) { parser->oxygen[i] = 0; parser->helium[i] = 0; } parser->calibrated = 0; for (unsigned int i = 0; i < 3; ++i) { parser->calibration[i] = 0.0; } parser->mode = DC_DIVEMODE_OC; return DC_STATUS_SUCCESS; } static dc_status_t shearwater_predator_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { const unsigned char *data = abstract->data; unsigned int size = abstract->size; if (size < 2 * SZ_BLOCK) return DC_STATUS_DATAFORMAT; unsigned int ticks = array_uint32_be (data + 12); if (!dc_datetime_gmtime (datetime, ticks)) return DC_STATUS_DATAFORMAT; datetime->timezone = DC_TIMEZONE_NONE; return DC_STATUS_SUCCESS; } /* * These string cache interfaces should be some generic * library rather than copied for all the dive computers. * * This is just copied from the EON Steel code. */ static void add_string(shearwater_predator_parser_t *parser, const char *desc, const char *value) { int i; for (i = 0; i < MAXSTRINGS; i++) { dc_field_string_t *str = parser->strings+i; if (str->desc) continue; str->desc = desc; str->value = strdup(value); break; } } static void add_string_fmt(shearwater_predator_parser_t *parser, const char *desc, const char *fmt, ...) { char buffer[256]; va_list ap; /* * We ignore the return value from vsnprintf, and we * always NUL-terminate the destination buffer ourselves. * * That way we don't have to worry about random bad legacy * implementations. */ va_start(ap, fmt); buffer[sizeof(buffer)-1] = 0; (void) vsnprintf(buffer, sizeof(buffer)-1, fmt, ap); va_end(ap); return add_string(parser, desc, buffer); } // The Battery state is a big-endian word: // // ffff = not paired / no comms for 90 s // fffe = no comms for 30 s // // Otherwise: // - top four bits are battery state (0 - normal, 1 - critical, 2 - warning) // - bottom 12 bits are pressure in 2 psi increments (0..8k psi) // // This returns the state as a bitmask (so you can see all states it had // during the dive). Note that we currently do not report pairing and // communication lapses. Todo? static unsigned int battery_state(const unsigned char *data) { unsigned int pressure = array_uint16_be(data); unsigned int state; if ((pressure & 0xFFF0) == 0xFFF0) return 0; state = pressure >> 12; if (state > 2) return 0; return 1u << state; } // Show the battery state // // NOTE! Right now it only shows the most serious bit // but the code is set up so that we could perhaps // indicate that the battery is on the edge (ie it // reported both "normal" _and_ "warning" during the // dive - maybe that would be a "starting to warn") // // We could also report unpaired and comm errors. static void add_battery_info(shearwater_predator_parser_t *parser, const char *desc, unsigned int state) { if (state >= 1 && state <= 7) { static const char *states[8] = { "", // 000 - No state bits, not used "normal", // 001 - only normal "critical", // 010 - only critical "critical", // 011 - both normal and critical "warning", // 100 - only warning "warning", // 101 - normal and warning "critical", // 110 - warning and critical "critical", // 111 - normal, warning and critical }; add_string(parser, desc, states[state]); } } static void add_deco_model(shearwater_predator_parser_t *parser, const unsigned char *data) { switch (data[67]) { case 0: add_string_fmt(parser, "Deco model", "GF %u/%u", data[4], data[5]); break; case 1: add_string_fmt(parser, "Deco model", "VPM-B +%u", data[68]); break; case 2: add_string_fmt(parser, "Deco model", "VPM-B/GFS +%u %u%%", data[68], data[85]); break; default: add_string_fmt(parser, "Deco model", "Unknown model %d", data[67]); } } static void add_battery_type(shearwater_predator_parser_t *parser, const unsigned char *data) { if (parser->logversion < 7) return; switch (data[120]) { case 1: add_string(parser, "Battery type", "1.5V Alkaline"); break; case 2: add_string(parser, "Battery type", "1.5V Lithium"); break; case 3: add_string(parser, "Battery type", "1.2V NiMH"); break; case 4: add_string(parser, "Battery type", "3.6V Saft"); break; case 5: add_string(parser, "Battery type", "3.7V Li-Ion"); break; default: add_string_fmt(parser, "Battery type", "unknown type %d", data[120]); break; } } static dc_status_t shearwater_predator_parser_cache (shearwater_predator_parser_t *parser) { dc_parser_t *abstract = (dc_parser_t *) parser; const unsigned char *data = parser->base.data; unsigned int size = parser->base.size; if (parser->cached) { return DC_STATUS_SUCCESS; } unsigned int headersize = SZ_BLOCK; unsigned int footersize = SZ_BLOCK; if (size < headersize + footersize) { ERROR (abstract->context, "Invalid data length."); return DC_STATUS_DATAFORMAT; } // Log versions before 6 weren't reliably stored in the data, but // 6 is also the oldest version that we assume in our code unsigned int logversion = 6; if (data[127] > 6) logversion = data[127]; INFO(abstract->context, "Shearwater log version %u\n", logversion); memset(parser->strings, 0, sizeof(parser->strings)); // Adjust the footersize for the final block. if (parser->petrel || array_uint16_be (data + size - footersize) == 0xFFFD) { footersize += SZ_BLOCK; if (size < headersize + footersize) { ERROR (abstract->context, "Invalid data length."); return DC_STATUS_DATAFORMAT; } } // Default dive mode. dc_divemode_t mode = DC_DIVEMODE_OC; // Get the gas mixes. unsigned int ngasmixes = 0; unsigned int oxygen[NGASMIXES] = {0}; unsigned int helium[NGASMIXES] = {0}; unsigned int o2_previous = 0, he_previous = 0; // Transmitter battery levels unsigned int t1_battery = 0, t2_battery = 0; unsigned int offset = headersize; unsigned int length = size - footersize; while (offset < length) { // Ignore empty samples. if (array_isequal (data + offset, parser->samplesize, 0x00)) { offset += parser->samplesize; continue; } // Status flags. unsigned int status = data[offset + 11]; if ((status & OC) == 0) { mode = DC_DIVEMODE_CCR; } // Gaschange. unsigned int o2 = data[offset + 7]; unsigned int he = data[offset + 8]; if (o2 != o2_previous || he != he_previous) { // Find the gasmix in the list. unsigned int idx = 0; while (idx < ngasmixes) { if (o2 == oxygen[idx] && he == helium[idx]) break; idx++; } // Add it to list if not found. if (idx >= ngasmixes) { if (idx >= NGASMIXES) { ERROR (abstract->context, "Maximum number of gas mixes reached."); return DC_STATUS_NOMEMORY; } oxygen[idx] = o2; helium[idx] = he; ngasmixes = idx + 1; } o2_previous = o2; he_previous = he; } // Transmitter battery levels if (logversion >= 7) { // T1 at offset 27, T2 at offset 19 t1_battery |= battery_state(data + offset + 27); t2_battery |= battery_state(data + offset + 19); } offset += parser->samplesize; } // Cache sensor calibration for later use unsigned int nsensors = 0, ndefaults = 0; for (size_t i = 0; i < 3; ++i) { unsigned int calibration = array_uint16_be(data + 87 + i * 2); parser->calibration[i] = calibration / 100000.0; if (parser->model == PREDATOR) { // The Predator expects the mV output of the cells to be // within 30mV to 70mV in 100% O2 at 1 atmosphere. If the // calibration value is scaled with a factor 2.2, then the // sensors lines up and matches the average. parser->calibration[i] *= 2.2; } if (data[86] & (1 << i)) { if (calibration == 2100) { ndefaults++; } nsensors++; } } if (nsensors && nsensors == ndefaults) { // If all (calibrated) sensors still have their factory default // calibration values (2100), they are probably not calibrated // properly. To avoid returning incorrect ppO2 values to the // application, they are manually disabled (e.g. marked as // uncalibrated). WARNING (abstract->context, "Disabled all O2 sensors due to a default calibration value."); parser->calibrated = 0; } else { parser->calibrated = data[86]; } // Cache the data for later use. parser->logversion = logversion; parser->headersize = headersize; parser->footersize = footersize; parser->ngasmixes = ngasmixes; for (unsigned int i = 0; i < ngasmixes; ++i) { parser->oxygen[i] = oxygen[i]; parser->helium[i] = helium[i]; } parser->mode = mode; add_string_fmt(parser, "Serial", "%08x", parser->serial); add_string_fmt(parser, "FW Version", "%2x", data[19]); add_deco_model(parser, data); add_battery_type(parser, data); add_string_fmt(parser, "Battery at end", "%.1f V", data[9] / 10.0); add_battery_info(parser, "T1 battery", t1_battery); add_battery_info(parser, "T2 battery", t2_battery); parser->cached = 1; return DC_STATUS_SUCCESS; } static dc_status_t shearwater_predator_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { shearwater_predator_parser_t *parser = (shearwater_predator_parser_t *) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; // Cache the parser data. dc_status_t rc = shearwater_predator_parser_cache (parser); if (rc != DC_STATUS_SUCCESS) return rc; // Get the offset to the footer record. unsigned int footer = size - parser->footersize; // Get the unit system. unsigned int units = data[8]; dc_gasmix_t *gasmix = (dc_gasmix_t *) value; dc_salinity_t *water = (dc_salinity_t *) value; dc_field_string_t *string = (dc_field_string_t *) value; unsigned int density = 0; if (value) { switch (type) { case DC_FIELD_DIVETIME: *((unsigned int *) value) = array_uint16_be (data + footer + 6) * 60; break; case DC_FIELD_MAXDEPTH: if (units == IMPERIAL) *((double *) value) = array_uint16_be (data + footer + 4) * FEET; else *((double *) value) = array_uint16_be (data + footer + 4); break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = parser->ngasmixes; break; case DC_FIELD_GASMIX: gasmix->oxygen = parser->oxygen[flags] / 100.0; gasmix->helium = parser->helium[flags] / 100.0; gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium; break; case DC_FIELD_SALINITY: density = array_uint16_be (data + 83); if (density == 1000) water->type = DC_WATER_FRESH; else water->type = DC_WATER_SALT; water->density = density; break; case DC_FIELD_ATMOSPHERIC: *((double *) value) = array_uint16_be (data + 47) / 1000.0; break; case DC_FIELD_DIVEMODE: *((dc_divemode_t *) value) = parser->mode; break; case DC_FIELD_STRING: if (flags < MAXSTRINGS) { dc_field_string_t *p = parser->strings + flags; if (p->desc) { *string = *p; break; } } return DC_STATUS_UNSUPPORTED; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t shearwater_predator_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { shearwater_predator_parser_t *parser = (shearwater_predator_parser_t *) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; // Cache the parser data. dc_status_t rc = shearwater_predator_parser_cache (parser); if (rc != DC_STATUS_SUCCESS) return rc; // Get the unit system. unsigned int units = data[8]; // Previous gas mix. unsigned int o2_previous = 0, he_previous = 0; unsigned int time = 0; unsigned int offset = parser->headersize; unsigned int length = size - parser->footersize; while (offset < length) { dc_sample_value_t sample = {0}; // Ignore empty samples. if (array_isequal (data + offset, parser->samplesize, 0x00)) { offset += parser->samplesize; continue; } // Time (seconds). time += 10; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Depth (1/10 m or ft). unsigned int depth = array_uint16_be (data + offset); if (units == IMPERIAL) sample.depth = depth * FEET / 10.0; else sample.depth = depth / 10.0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); // Temperature (°C or °F). int temperature = (signed char) data[offset + 13]; if (temperature < 0) { // Fix negative temperatures. temperature += 102; if (temperature > 0) { temperature = 0; } } if (units == IMPERIAL) sample.temperature = (temperature - 32.0) * (5.0 / 9.0); else sample.temperature = temperature; if (callback) callback (DC_SAMPLE_TEMPERATURE, sample, userdata); // Status flags. unsigned int status = data[offset + 11]; if ((status & OC) == 0) { // PPO2 if ((status & PPO2_EXTERNAL) == 0) { #ifdef SENSOR_AVERAGE sample.ppo2 = data[offset + 6] / 100.0; if (callback) callback (DC_SAMPLE_PPO2, sample, userdata); #else sample.ppo2 = data[offset + 12] * parser->calibration[0]; if (callback && (parser->calibrated & 0x01)) callback (DC_SAMPLE_PPO2, sample, userdata); sample.ppo2 = data[offset + 14] * parser->calibration[1]; if (callback && (parser->calibrated & 0x02)) callback (DC_SAMPLE_PPO2, sample, userdata); sample.ppo2 = data[offset + 15] * parser->calibration[2]; if (callback && (parser->calibrated & 0x04)) callback (DC_SAMPLE_PPO2, sample, userdata); #endif } // Setpoint if (parser->petrel) { sample.setpoint = data[offset + 18] / 100.0; } else { if (status & SETPOINT_HIGH) { sample.setpoint = data[18] / 100.0; } else { sample.setpoint = data[17] / 100.0; } } if (callback) callback (DC_SAMPLE_SETPOINT, sample, userdata); } // CNS if (parser->petrel) { sample.cns = data[offset + 22] / 100.0; if (callback) callback (DC_SAMPLE_CNS, sample, userdata); } // Gaschange. unsigned int o2 = data[offset + 7]; unsigned int he = data[offset + 8]; if (o2 != o2_previous || he != he_previous) { unsigned int idx = shearwater_predator_find_gasmix (parser, o2, he); if (idx >= parser->ngasmixes) { ERROR (abstract->context, "Invalid gas mix."); return DC_STATUS_DATAFORMAT; } sample.gasmix = idx; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); o2_previous = o2; he_previous = he; } // Deco stop / NDL. unsigned int decostop = array_uint16_be (data + offset + 2); if (decostop) { sample.deco.type = DC_DECO_DECOSTOP; if (units == IMPERIAL) sample.deco.depth = decostop * FEET; else sample.deco.depth = decostop; } else { sample.deco.type = DC_DECO_NDL; sample.deco.depth = 0.0; } sample.deco.time = data[offset + 9] * 60; if (callback) callback (DC_SAMPLE_DECO, sample, userdata); // for logversion 7 and newer (introduced for Perdix AI) // detect tank pressure if (parser->logversion >= 7) { // Tank pressure // Values above 0xFFF0 are special codes: // 0xFFFF AI is off // 0xFFFE No comms for 90 seconds+ // 0xFFFD No comms for 30 seconds // 0xFFFC Transmitter not paired // For regular values, the top 4 bits contain the battery // level (0=normal, 1=critical, 2=warning), and the lower 12 // bits the tank pressure in units of 2 psi. unsigned int pressure = array_uint16_be (data + offset + 27); if (pressure < 0xFFF0) { pressure &= 0x0FFF; sample.pressure.tank = 0; sample.pressure.value = pressure * 2 * PSI / BAR; if (callback) callback (DC_SAMPLE_PRESSURE, sample, userdata); } pressure = array_uint16_be (data + offset + 19); if (pressure < 0xFFF0) { pressure &= 0x0FFF; sample.pressure.tank = 1; sample.pressure.value = pressure * 2 * PSI / BAR; if (callback) callback (DC_SAMPLE_PRESSURE, sample, userdata); } // Gas time remaining in minutes // Values above 0xF0 are special codes: // 0xFF Not paired // 0xFE No communication // 0xFD Not available in current mode // 0xFC Not available because of DECO // 0xFB Tank size or max pressure haven’t been set up if (data[offset + 21] < 0xF0) { sample.rbt = data[offset + 21]; if (callback) callback (DC_SAMPLE_RBT, sample, userdata); } } offset += parser->samplesize; } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/shearwater_predator_parser.c
/* * libdivecomputer * * Copyright (C) 2012 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #ifdef _WIN32 #define NOGDI #include <windows.h> #endif #include "context-private.h" #include "timer.h" #include <libdivecomputer/custom_io.h> struct dc_context_t { dc_loglevel_t loglevel; dc_logfunc_t logfunc; void *userdata; #ifdef ENABLE_LOGGING char msg[8192 + 32]; dc_timer_t *timer; #endif dc_custom_io_t *custom_io; dc_user_device_t *user_device; }; #ifdef ENABLE_LOGGING /* * A wrapper for the vsnprintf function, which will always null terminate the * string and returns a negative value if the destination buffer is too small. */ static int l_vsnprintf (char *str, size_t size, const char *format, va_list ap) { int n; if (size == 0) return -1; #ifdef _MSC_VER /* * The non-standard vsnprintf implementation provided by MSVC doesn't null * terminate the string and returns a negative value if the destination * buffer is too small. */ n = _vsnprintf (str, size - 1, format, ap); if (n == size - 1 || n < 0) str[size - 1] = 0; #else /* * The C99 vsnprintf function will always null terminate the string. If the * destination buffer is too small, the return value is the number of * characters that would have been written if the buffer had been large * enough. */ n = vsnprintf (str, size, format, ap); if (n >= size) n = -1; #endif return n; } static int l_snprintf (char *str, size_t size, const char *format, ...) { va_list ap; int n; va_start (ap, format); n = l_vsnprintf (str, size, format, ap); va_end (ap); return n; } static int l_hexdump (char *str, size_t size, const unsigned char data[], size_t n) { const unsigned char ascii[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; if (size == 0) return -1; /* The maximum number of bytes. */ size_t maxlength = (size - 1) / 2; /* The actual number of bytes. */ size_t length = (n > maxlength ? maxlength : n); for (size_t i = 0; i < length; ++i) { /* Set the most-significant nibble. */ unsigned char msn = (data[i] >> 4) & 0x0F; str[i * 2 + 0] = ascii[msn]; /* Set the least-significant nibble. */ unsigned char lsn = data[i] & 0x0F; str[i * 2 + 1] = ascii[lsn]; } /* Null terminate the hex string. */ str[length * 2] = 0; return (n > maxlength ? -1 : length * 2); } static void logfunc (dc_context_t *context, dc_loglevel_t loglevel, const char *file, unsigned int line, const char *function, const char *msg, void *userdata) { const char *loglevels[] = {"NONE", "ERROR", "WARNING", "INFO", "DEBUG", "ALL"}; dc_usecs_t now = 0; dc_timer_now (context->timer, &now); unsigned long seconds = now / 1000000; unsigned long microseconds = now % 1000000; if (loglevel == DC_LOGLEVEL_ERROR || loglevel == DC_LOGLEVEL_WARNING) { fprintf (stderr, "[%li.%06li] %s: %s [in %s:%d (%s)]\n", seconds, microseconds, loglevels[loglevel], msg, file, line, function); } else { fprintf (stderr, "[%li.%06li] %s: %s\n", seconds, microseconds, loglevels[loglevel], msg); } } #endif dc_status_t dc_context_new (dc_context_t **out) { dc_context_t *context = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; context = (dc_context_t *) malloc (sizeof (dc_context_t)); if (context == NULL) return DC_STATUS_NOMEMORY; #ifdef ENABLE_LOGGING context->loglevel = DC_LOGLEVEL_WARNING; context->logfunc = logfunc; #else context->loglevel = DC_LOGLEVEL_NONE; context->logfunc = NULL; #endif context->userdata = NULL; #ifdef ENABLE_LOGGING memset (context->msg, 0, sizeof (context->msg)); context->timer = NULL; dc_timer_new (&context->timer); #endif context->custom_io = NULL; *out = context; return DC_STATUS_SUCCESS; } dc_status_t dc_context_free (dc_context_t *context) { if (context == NULL) return DC_STATUS_SUCCESS; dc_timer_free (context->timer); free (context); return DC_STATUS_SUCCESS; } dc_status_t dc_context_set_custom_io (dc_context_t *context, dc_custom_io_t *custom_io, dc_user_device_t *user_device) { if (context == NULL) return DC_STATUS_INVALIDARGS; context->custom_io = custom_io; custom_io->user_device = user_device; return DC_STATUS_SUCCESS; } dc_custom_io_t* _dc_context_custom_io (dc_context_t *context) { return context->custom_io; } dc_status_t dc_context_set_loglevel (dc_context_t *context, dc_loglevel_t loglevel) { if (context == NULL) return DC_STATUS_INVALIDARGS; #ifdef ENABLE_LOGGING context->loglevel = loglevel; #endif return DC_STATUS_SUCCESS; } dc_status_t dc_context_set_logfunc (dc_context_t *context, dc_logfunc_t logfunc, void *userdata) { if (context == NULL) return DC_STATUS_INVALIDARGS; #ifdef ENABLE_LOGGING context->logfunc = logfunc; context->userdata = userdata; #endif return DC_STATUS_SUCCESS; } dc_status_t dc_context_log (dc_context_t *context, dc_loglevel_t loglevel, const char *file, unsigned int line, const char *function, const char *format, ...) { #ifdef ENABLE_LOGGING va_list ap; #endif if (context == NULL) return DC_STATUS_INVALIDARGS; #ifdef ENABLE_LOGGING if (loglevel > context->loglevel) return DC_STATUS_SUCCESS; if (context->logfunc == NULL) return DC_STATUS_SUCCESS; va_start (ap, format); l_vsnprintf (context->msg, sizeof (context->msg), format, ap); va_end (ap); context->logfunc (context, loglevel, file, line, function, context->msg, context->userdata); #endif return DC_STATUS_SUCCESS; } dc_status_t dc_context_syserror (dc_context_t *context, dc_loglevel_t loglevel, const char *file, unsigned int line, const char *function, int errcode) { const char *errmsg = NULL; #ifdef _WIN32 char buffer[256]; DWORD rc = FormatMessageA (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errcode, 0, buffer, sizeof (buffer), NULL); /* Remove the CRLF and period at the end of the error message. */ while (rc > 0 && ( buffer[rc - 1] == '\n' || buffer[rc - 1] == '\r' || buffer[rc - 1] == '.')) { buffer[rc - 1] = '\0'; rc--; } if (rc > 0) errmsg = buffer; #elif defined (HAVE_STRERROR_R) char buffer[256]; int rc = strerror_r (errcode, buffer, sizeof (buffer)); if (rc == 0) errmsg = buffer; #else /* Fallback to the non-threadsafe function. */ errmsg = strerror (errcode); #endif if (errmsg == NULL) errmsg = "Unknown system error"; return dc_context_log (context, loglevel, file, line, function, "%s (%d)", errmsg, errcode); } dc_status_t dc_context_hexdump (dc_context_t *context, dc_loglevel_t loglevel, const char *file, unsigned int line, const char *function, const char *prefix, const unsigned char data[], unsigned int size) { #ifdef ENABLE_LOGGING int n; #endif if (context == NULL || prefix == NULL) return DC_STATUS_INVALIDARGS; #ifdef ENABLE_LOGGING if (loglevel > context->loglevel) return DC_STATUS_SUCCESS; if (context->logfunc == NULL) return DC_STATUS_SUCCESS; n = l_snprintf (context->msg, sizeof (context->msg), "%s: size=%u, data=", prefix, size); if (n >= 0) { n = l_hexdump (context->msg + n, sizeof (context->msg) - n, data, size); } context->logfunc (context, loglevel, file, line, function, context->msg, context->userdata); #endif return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/context.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <libdivecomputer/units.h> #include "suunto_vyper.h" #include "context-private.h" #include "parser-private.h" #define ISINSTANCE(parser) dc_parser_isinstance((parser), &suunto_vyper_parser_vtable) #define NGASMIXES 3 typedef struct suunto_vyper_parser_t suunto_vyper_parser_t; struct suunto_vyper_parser_t { dc_parser_t base; // Cached fields. unsigned int cached; unsigned int divetime; unsigned int maxdepth; unsigned int marker; unsigned int ngasmixes; unsigned int oxygen[NGASMIXES]; }; static dc_status_t suunto_vyper_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t suunto_vyper_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t suunto_vyper_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t suunto_vyper_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t suunto_vyper_parser_vtable = { sizeof(suunto_vyper_parser_t), DC_FAMILY_SUUNTO_VYPER, suunto_vyper_parser_set_data, /* set_data */ suunto_vyper_parser_get_datetime, /* datetime */ suunto_vyper_parser_get_field, /* fields */ suunto_vyper_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; static unsigned int suunto_vyper_parser_find_gasmix (suunto_vyper_parser_t *parser, unsigned int o2) { unsigned int i = 0; while (i < parser->ngasmixes) { if (o2 == parser->oxygen[i]) break; i++; } return i; } static dc_status_t suunto_vyper_parser_cache (suunto_vyper_parser_t *parser) { dc_parser_t *abstract = (dc_parser_t *) parser; const unsigned char *data = parser->base.data; unsigned int size = parser->base.size; if (parser->cached) { return DC_STATUS_SUCCESS; } if (size < 18) { return DC_STATUS_DATAFORMAT; } unsigned int ngasmixes = 1; unsigned int oxygen[NGASMIXES] = {0}; if (data[6]) oxygen[0] = data[6]; else oxygen[0] = 21; // Parse the samples. unsigned int interval = data[3]; unsigned int nsamples = 0; unsigned int depth = 0, maxdepth = 0; unsigned int offset = 14; while (offset < size && data[offset] != 0x80) { unsigned char value = data[offset++]; if (value < 0x79 || value > 0x87) { // Delta depth. depth += (signed char) value; if (depth > maxdepth) maxdepth = depth; nsamples++; } else if (value == 0x87) { // Gas change event. if (offset + 1 > size) { ERROR (abstract->context, "Buffer overflow detected!"); return DC_STATUS_DATAFORMAT; } // Get the new gas mix. unsigned int o2 = data[offset++]; // Find the gasmix in the list. unsigned int i = 0; while (i < ngasmixes) { if (o2 == oxygen[i]) break; i++; } // Add it to list if not found. if (i >= ngasmixes) { if (i >= NGASMIXES) { ERROR (abstract->context, "Maximum number of gas mixes reached."); return DC_STATUS_DATAFORMAT; } oxygen[i] = o2; ngasmixes = i + 1; } } } // Check the end marker. unsigned int marker = offset; if (marker + 4 >= size || data[marker] != 0x80) { ERROR (abstract->context, "No valid end marker found!"); return DC_STATUS_DATAFORMAT; } // Cache the data for later use. parser->divetime = nsamples * interval; parser->maxdepth = maxdepth; parser->marker = marker; parser->ngasmixes = ngasmixes; for (unsigned int i = 0; i < ngasmixes; ++i) { parser->oxygen[i] = oxygen[i]; } parser->cached = 1; return DC_STATUS_SUCCESS; } dc_status_t suunto_vyper_parser_create (dc_parser_t **out, dc_context_t *context) { suunto_vyper_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (suunto_vyper_parser_t *) dc_parser_allocate (context, &suunto_vyper_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. parser->cached = 0; parser->divetime = 0; parser->maxdepth = 0; parser->marker = 0; parser->ngasmixes = 0; for (unsigned int i = 0; i < NGASMIXES; ++i) { parser->oxygen[i] = 0; } *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; } static dc_status_t suunto_vyper_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { suunto_vyper_parser_t *parser = (suunto_vyper_parser_t *) abstract; // Reset the cache. parser->cached = 0; parser->divetime = 0; parser->maxdepth = 0; parser->marker = 0; parser->ngasmixes = 0; for (unsigned int i = 0; i < NGASMIXES; ++i) { parser->oxygen[i] = 0; } return DC_STATUS_SUCCESS; } static dc_status_t suunto_vyper_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { if (abstract->size < 9 + 5) return DC_STATUS_DATAFORMAT; const unsigned char *p = abstract->data + 9; if (datetime) { datetime->year = p[0] + (p[0] < 90 ? 2000 : 1900); datetime->month = p[1]; datetime->day = p[2]; datetime->hour = p[3]; datetime->minute = p[4]; datetime->second = 0; datetime->timezone = DC_TIMEZONE_NONE; } return DC_STATUS_SUCCESS; } static dc_status_t suunto_vyper_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { suunto_vyper_parser_t *parser = (suunto_vyper_parser_t *) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; dc_gasmix_t *gas = (dc_gasmix_t *) value; dc_tank_t *tank = (dc_tank_t *) value; // Cache the data. dc_status_t rc = suunto_vyper_parser_cache (parser); if (rc != DC_STATUS_SUCCESS) return rc; unsigned int gauge = data[4] & 0x40; unsigned int beginpressure = data[5] * 2; unsigned int endpressure = data[parser->marker + 3] * 2; if (value) { switch (type) { case DC_FIELD_DIVETIME: *((unsigned int *) value) = parser->divetime; break; case DC_FIELD_MAXDEPTH: *((double *) value) = parser->maxdepth * FEET; break; case DC_FIELD_GASMIX_COUNT: if (gauge) *((unsigned int *) value) = 0; else *((unsigned int *) value) = parser->ngasmixes; break; case DC_FIELD_GASMIX: gas->helium = 0.0; gas->oxygen = parser->oxygen[flags] / 100.0; gas->nitrogen = 1.0 - gas->oxygen - gas->helium; break; case DC_FIELD_TANK_COUNT: if (beginpressure == 0 && endpressure == 0) *((unsigned int *) value) = 0; else *((unsigned int *) value) = 1; break; case DC_FIELD_TANK: tank->type = DC_TANKVOLUME_NONE; tank->volume = 0.0; tank->workpressure = 0.0; if (gauge) tank->gasmix = DC_GASMIX_UNKNOWN; else tank->gasmix = 0; tank->beginpressure = beginpressure; tank->endpressure = endpressure; break; case DC_FIELD_TEMPERATURE_SURFACE: *((double *) value) = (signed char) data[8]; break; case DC_FIELD_TEMPERATURE_MINIMUM: *((double *) value) = (signed char) data[parser->marker + 1]; break; case DC_FIELD_DIVEMODE: if (gauge) { *((dc_divemode_t *) value) = DC_DIVEMODE_GAUGE; } else { *((dc_divemode_t *) value) = DC_DIVEMODE_OC; } break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t suunto_vyper_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { suunto_vyper_parser_t *parser = (suunto_vyper_parser_t *) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; dc_sample_value_t sample = {0}; // Cache the data. dc_status_t rc = suunto_vyper_parser_cache (parser); if (rc != DC_STATUS_SUCCESS) return rc; unsigned int gauge = data[4] & 0x40; // Time sample.time = 0; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Depth (0 ft) sample.depth = 0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); // Initial gas mix if (!gauge) { sample.gasmix = 0; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); } unsigned int depth = 0; unsigned int time = 0; unsigned int interval = data[3]; unsigned int complete = 1; unsigned int offset = 14; while (offset < size && data[offset] != 0x80) { unsigned char value = data[offset++]; if (complete) { // Time (seconds). time += interval; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); complete = 0; } if (value < 0x79 || value > 0x87) { // Delta depth. depth += (signed char) value; // Depth (ft). sample.depth = depth * FEET; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); complete = 1; } else { // Event. unsigned int o2 = 0, idx = 0; sample.event.type = SAMPLE_EVENT_NONE; sample.event.time = 0; sample.event.flags = 0; sample.event.value = 0; switch (value) { case 0x7a: // Slow sample.event.type = SAMPLE_EVENT_ASCENT; break; case 0x7b: // Violation sample.event.type = SAMPLE_EVENT_VIOLATION; break; case 0x7c: // Bookmark sample.event.type = SAMPLE_EVENT_BOOKMARK; break; case 0x7d: // Surface sample.event.type = SAMPLE_EVENT_SURFACE; break; case 0x7e: // Deco sample.event.type = SAMPLE_EVENT_DECOSTOP; break; case 0x7f: // Ceiling (Deco Violation) sample.event.type = SAMPLE_EVENT_CEILING; break; case 0x81: // Safety Stop sample.event.type = SAMPLE_EVENT_SAFETYSTOP; break; case 0x87: // Gas Change if (offset + 1 > size) return DC_STATUS_DATAFORMAT; o2 = data[offset++]; idx = suunto_vyper_parser_find_gasmix (parser, o2); if (idx >= parser->ngasmixes) { ERROR (abstract->context, "Maximum number of gas mixes reached."); return DC_STATUS_DATAFORMAT; } sample.gasmix = idx; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); sample.event.type = SAMPLE_EVENT_NONE; break; default: // Unknown WARNING (abstract->context, "Unknown event"); break; } if (sample.event.type != SAMPLE_EVENT_NONE) { if (callback) callback (DC_SAMPLE_EVENT, sample, userdata); } } } // Time if (complete) { time += interval; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); } // Depth (0 ft) sample.depth = 0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/suunto_vyper_parser.c
/* * libdivecomputer * * Copyright (C) 2012 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #if defined(HAVE_HIDAPI) #define USBHID #elif defined(HAVE_LIBUSB) && !defined(__APPLE__) #define USBHID #endif #ifdef _WIN32 #ifdef HAVE_AF_IRDA_H #define IRDA #endif #else #ifdef HAVE_LINUX_IRDA_H #define IRDA #endif #endif #include <stddef.h> #include <stdlib.h> #include <string.h> #include "descriptor-private.h" #include "iterator-private.h" #include "platform.h" #define C_ARRAY_SIZE(array) (sizeof (array) / sizeof *(array)) static int dc_filter_uwatec (dc_transport_t transport, const void *userdata); static int dc_filter_suunto (dc_transport_t transport, const void *userdata); static int dc_filter_shearwater (dc_transport_t transport, const void *userdata); static int dc_filter_hw (dc_transport_t transport, const void *userdata); static dc_status_t dc_descriptor_iterator_next (dc_iterator_t *iterator, void *item); struct dc_descriptor_t { const char *vendor; const char *product; dc_family_t type; unsigned int model; dc_filter_t filter; }; typedef struct dc_descriptor_iterator_t { dc_iterator_t base; size_t current; } dc_descriptor_iterator_t; static const dc_iterator_vtable_t dc_descriptor_iterator_vtable = { sizeof(dc_descriptor_iterator_t), dc_descriptor_iterator_next, NULL, }; /* * The model numbers in the table are the actual model numbers reported by the * device. For devices where there is no model number available (or known), an * artifical number (starting at zero) is assigned. If the model number isn't * actually used to identify individual models, identical values are assigned. */ static const dc_descriptor_t g_descriptors[] = { /* Suunto Solution */ {"Suunto", "Solution", DC_FAMILY_SUUNTO_SOLUTION, 0, NULL}, /* Suunto Eon */ {"Suunto", "Eon", DC_FAMILY_SUUNTO_EON, 0, NULL}, {"Suunto", "Solution Alpha", DC_FAMILY_SUUNTO_EON, 0, NULL}, {"Suunto", "Solution Nitrox", DC_FAMILY_SUUNTO_EON, 0, NULL}, /* Suunto Vyper */ {"Suunto", "Spyder", DC_FAMILY_SUUNTO_VYPER, 0x01, NULL}, {"Suunto", "Stinger", DC_FAMILY_SUUNTO_VYPER, 0x03, NULL}, {"Suunto", "Mosquito", DC_FAMILY_SUUNTO_VYPER, 0x04, NULL}, {"Suunto", "D3", DC_FAMILY_SUUNTO_VYPER, 0x05, NULL}, {"Suunto", "Vyper", DC_FAMILY_SUUNTO_VYPER, 0x0A, NULL}, {"Suunto", "Vytec", DC_FAMILY_SUUNTO_VYPER, 0X0B, NULL}, {"Suunto", "Cobra", DC_FAMILY_SUUNTO_VYPER, 0X0C, NULL}, {"Suunto", "Gekko", DC_FAMILY_SUUNTO_VYPER, 0X0D, NULL}, {"Suunto", "Zoop", DC_FAMILY_SUUNTO_VYPER, 0x16, NULL}, /* Suunto Vyper 2 */ {"Suunto", "Vyper 2", DC_FAMILY_SUUNTO_VYPER2, 0x10, NULL}, {"Suunto", "Cobra 2", DC_FAMILY_SUUNTO_VYPER2, 0x11, NULL}, {"Suunto", "Vyper Air", DC_FAMILY_SUUNTO_VYPER2, 0x13, NULL}, {"Suunto", "Cobra 3", DC_FAMILY_SUUNTO_VYPER2, 0x14, NULL}, {"Suunto", "HelO2", DC_FAMILY_SUUNTO_VYPER2, 0x15, NULL}, /* Suunto D9 */ {"Suunto", "D9", DC_FAMILY_SUUNTO_D9, 0x0E, NULL}, {"Suunto", "D6", DC_FAMILY_SUUNTO_D9, 0x0F, NULL}, {"Suunto", "D4", DC_FAMILY_SUUNTO_D9, 0x12, NULL}, {"Suunto", "D4i", DC_FAMILY_SUUNTO_D9, 0x19, NULL}, {"Suunto", "D6i", DC_FAMILY_SUUNTO_D9, 0x1A, NULL}, {"Suunto", "D9tx", DC_FAMILY_SUUNTO_D9, 0x1B, NULL}, {"Suunto", "DX", DC_FAMILY_SUUNTO_D9, 0x1C, NULL}, {"Suunto", "Vyper Novo", DC_FAMILY_SUUNTO_D9, 0x1D, NULL}, {"Suunto", "Zoop Novo", DC_FAMILY_SUUNTO_D9, 0x1E, NULL}, {"Suunto", "D4f", DC_FAMILY_SUUNTO_D9, 0x20, NULL}, /* Suunto EON Steel */ #if defined(USBHID) || defined(ENABLE_BLE) {"Suunto", "EON Steel", DC_FAMILY_SUUNTO_EONSTEEL, 0, dc_filter_suunto}, {"Suunto", "EON Core", DC_FAMILY_SUUNTO_EONSTEEL, 1, dc_filter_suunto}, #endif /* Uwatec Aladin */ {"Uwatec", "Aladin Air Twin", DC_FAMILY_UWATEC_ALADIN, 0x1C, NULL}, {"Uwatec", "Aladin Sport Plus", DC_FAMILY_UWATEC_ALADIN, 0x3E, NULL}, {"Uwatec", "Aladin Pro", DC_FAMILY_UWATEC_ALADIN, 0x3F, NULL}, {"Uwatec", "Aladin Air Z", DC_FAMILY_UWATEC_ALADIN, 0x44, NULL}, {"Uwatec", "Aladin Air Z O2", DC_FAMILY_UWATEC_ALADIN, 0xA4, NULL}, {"Uwatec", "Aladin Air Z Nitrox", DC_FAMILY_UWATEC_ALADIN, 0xF4, NULL}, {"Uwatec", "Aladin Pro Ultra", DC_FAMILY_UWATEC_ALADIN, 0xFF, NULL}, /* Uwatec Memomouse */ {"Uwatec", "Memomouse", DC_FAMILY_UWATEC_MEMOMOUSE, 0, NULL}, /* Uwatec Smart */ #ifdef IRDA {"Uwatec", "Smart Pro", DC_FAMILY_UWATEC_SMART, 0x10, dc_filter_uwatec}, {"Uwatec", "Galileo Sol", DC_FAMILY_UWATEC_SMART, 0x11, dc_filter_uwatec}, {"Uwatec", "Galileo Luna", DC_FAMILY_UWATEC_SMART, 0x11, dc_filter_uwatec}, {"Uwatec", "Galileo Terra", DC_FAMILY_UWATEC_SMART, 0x11, dc_filter_uwatec}, {"Uwatec", "Aladin Tec", DC_FAMILY_UWATEC_SMART, 0x12, dc_filter_uwatec}, {"Uwatec", "Aladin Prime", DC_FAMILY_UWATEC_SMART, 0x12, dc_filter_uwatec}, {"Uwatec", "Aladin Tec 2G", DC_FAMILY_UWATEC_SMART, 0x13, dc_filter_uwatec}, {"Uwatec", "Aladin 2G", DC_FAMILY_UWATEC_SMART, 0x13, dc_filter_uwatec}, {"Subgear","XP-10", DC_FAMILY_UWATEC_SMART, 0x13, dc_filter_uwatec}, {"Uwatec", "Smart Com", DC_FAMILY_UWATEC_SMART, 0x14, dc_filter_uwatec}, {"Uwatec", "Aladin 2G", DC_FAMILY_UWATEC_SMART, 0x15, dc_filter_uwatec}, {"Uwatec", "Aladin Tec 3G", DC_FAMILY_UWATEC_SMART, 0x15, dc_filter_uwatec}, {"Uwatec", "Aladin Sport", DC_FAMILY_UWATEC_SMART, 0x15, dc_filter_uwatec}, {"Subgear","XP-3G", DC_FAMILY_UWATEC_SMART, 0x15, dc_filter_uwatec}, {"Uwatec", "Smart Tec", DC_FAMILY_UWATEC_SMART, 0x18, dc_filter_uwatec}, {"Uwatec", "Galileo Trimix",DC_FAMILY_UWATEC_SMART, 0x19, dc_filter_uwatec}, {"Uwatec", "Smart Z", DC_FAMILY_UWATEC_SMART, 0x1C, dc_filter_uwatec}, {"Subgear","XP Air", DC_FAMILY_UWATEC_SMART, 0x1C, dc_filter_uwatec}, #endif /* Scubapro/Uwatec Meridian */ {"Scubapro", "Meridian", DC_FAMILY_UWATEC_MERIDIAN, 0x20, NULL}, {"Scubapro", "Mantis", DC_FAMILY_UWATEC_MERIDIAN, 0x20, NULL}, {"Scubapro", "Chromis", DC_FAMILY_UWATEC_MERIDIAN, 0x24, NULL}, {"Scubapro", "Mantis 2", DC_FAMILY_UWATEC_MERIDIAN, 0x26, NULL}, /* Scubapro G2 */ #if defined(USBHID) || defined(ENABLE_BLE) {"Scubapro", "Aladin Sport Matrix", DC_FAMILY_UWATEC_G2, 0x17, dc_filter_uwatec}, {"Scubapro", "Aladin Square", DC_FAMILY_UWATEC_G2, 0x22, dc_filter_uwatec}, {"Scubapro", "G2", DC_FAMILY_UWATEC_G2, 0x32, dc_filter_uwatec}, #endif /* Reefnet */ {"Reefnet", "Sensus", DC_FAMILY_REEFNET_SENSUS, 1, NULL}, {"Reefnet", "Sensus Pro", DC_FAMILY_REEFNET_SENSUSPRO, 2, NULL}, {"Reefnet", "Sensus Ultra", DC_FAMILY_REEFNET_SENSUSULTRA, 3, NULL}, /* Oceanic VT Pro */ {"Aeris", "500 AI", DC_FAMILY_OCEANIC_VTPRO, 0x4151, NULL}, {"Oceanic", "Versa Pro", DC_FAMILY_OCEANIC_VTPRO, 0x4155, NULL}, {"Aeris", "Atmos 2", DC_FAMILY_OCEANIC_VTPRO, 0x4158, NULL}, {"Oceanic", "Pro Plus 2", DC_FAMILY_OCEANIC_VTPRO, 0x4159, NULL}, {"Aeris", "Atmos AI", DC_FAMILY_OCEANIC_VTPRO, 0x4244, NULL}, {"Oceanic", "VT Pro", DC_FAMILY_OCEANIC_VTPRO, 0x4245, NULL}, {"Sherwood", "Wisdom", DC_FAMILY_OCEANIC_VTPRO, 0x4246, NULL}, {"Aeris", "Elite", DC_FAMILY_OCEANIC_VTPRO, 0x424F, NULL}, /* Oceanic Veo 250 */ {"Genesis", "React Pro", DC_FAMILY_OCEANIC_VEO250, 0x4247, NULL}, {"Oceanic", "Veo 200", DC_FAMILY_OCEANIC_VEO250, 0x424B, NULL}, {"Oceanic", "Veo 250", DC_FAMILY_OCEANIC_VEO250, 0x424C, NULL}, {"Seemann", "XP5", DC_FAMILY_OCEANIC_VEO250, 0x4251, NULL}, {"Oceanic", "Veo 180", DC_FAMILY_OCEANIC_VEO250, 0x4252, NULL}, {"Aeris", "XR-2", DC_FAMILY_OCEANIC_VEO250, 0x4255, NULL}, {"Sherwood", "Insight", DC_FAMILY_OCEANIC_VEO250, 0x425A, NULL}, {"Hollis", "DG02", DC_FAMILY_OCEANIC_VEO250, 0x4352, NULL}, /* Oceanic Atom 2.0 */ {"Oceanic", "Atom 1.0", DC_FAMILY_OCEANIC_ATOM2, 0x4250, NULL}, {"Aeris", "Epic", DC_FAMILY_OCEANIC_ATOM2, 0x4257, NULL}, {"Oceanic", "VT3", DC_FAMILY_OCEANIC_ATOM2, 0x4258, NULL}, {"Aeris", "Elite T3", DC_FAMILY_OCEANIC_ATOM2, 0x4259, NULL}, {"Oceanic", "Atom 2.0", DC_FAMILY_OCEANIC_ATOM2, 0x4342, NULL}, {"Oceanic", "Geo", DC_FAMILY_OCEANIC_ATOM2, 0x4344, NULL}, {"Aeris", "Manta", DC_FAMILY_OCEANIC_ATOM2, 0x4345, NULL}, {"Aeris", "XR-1 NX", DC_FAMILY_OCEANIC_ATOM2, 0x4346, NULL}, {"Oceanic", "Datamask", DC_FAMILY_OCEANIC_ATOM2, 0x4347, NULL}, {"Aeris", "Compumask", DC_FAMILY_OCEANIC_ATOM2, 0x4348, NULL}, {"Aeris", "F10", DC_FAMILY_OCEANIC_ATOM2, 0x434D, NULL}, {"Oceanic", "OC1", DC_FAMILY_OCEANIC_ATOM2, 0x434E, NULL}, {"Sherwood", "Wisdom 2", DC_FAMILY_OCEANIC_ATOM2, 0x4350, NULL}, {"Sherwood", "Insight 2", DC_FAMILY_OCEANIC_ATOM2, 0x4353, NULL}, {"Genesis", "React Pro White", DC_FAMILY_OCEANIC_ATOM2, 0x4354, NULL}, {"Tusa", "Element II (IQ-750)", DC_FAMILY_OCEANIC_ATOM2, 0x4357, NULL}, {"Oceanic", "Veo 1.0", DC_FAMILY_OCEANIC_ATOM2, 0x4358, NULL}, {"Oceanic", "Veo 2.0", DC_FAMILY_OCEANIC_ATOM2, 0x4359, NULL}, {"Oceanic", "Veo 3.0", DC_FAMILY_OCEANIC_ATOM2, 0x435A, NULL}, {"Tusa", "Zen (IQ-900)", DC_FAMILY_OCEANIC_ATOM2, 0x4441, NULL}, {"Tusa", "Zen Air (IQ-950)", DC_FAMILY_OCEANIC_ATOM2, 0x4442, NULL}, {"Aeris", "Atmos AI 2", DC_FAMILY_OCEANIC_ATOM2, 0x4443, NULL}, {"Oceanic", "Pro Plus 2.1", DC_FAMILY_OCEANIC_ATOM2, 0x4444, NULL}, {"Oceanic", "Geo 2.0", DC_FAMILY_OCEANIC_ATOM2, 0x4446, NULL}, {"Oceanic", "VT4", DC_FAMILY_OCEANIC_ATOM2, 0x4447, NULL}, {"Oceanic", "OC1", DC_FAMILY_OCEANIC_ATOM2, 0x4449, NULL}, {"Beuchat", "Voyager 2G", DC_FAMILY_OCEANIC_ATOM2, 0x444B, NULL}, {"Oceanic", "Atom 3.0", DC_FAMILY_OCEANIC_ATOM2, 0x444C, NULL}, {"Hollis", "DG03", DC_FAMILY_OCEANIC_ATOM2, 0x444D, NULL}, {"Oceanic", "OCS", DC_FAMILY_OCEANIC_ATOM2, 0x4450, NULL}, {"Oceanic", "OC1", DC_FAMILY_OCEANIC_ATOM2, 0x4451, NULL}, {"Oceanic", "VT 4.1", DC_FAMILY_OCEANIC_ATOM2, 0x4452, NULL}, {"Aeris", "Epic", DC_FAMILY_OCEANIC_ATOM2, 0x4453, NULL}, {"Aeris", "Elite T3", DC_FAMILY_OCEANIC_ATOM2, 0x4455, NULL}, {"Oceanic", "Atom 3.1", DC_FAMILY_OCEANIC_ATOM2, 0x4456, NULL}, {"Aeris", "A300 AI", DC_FAMILY_OCEANIC_ATOM2, 0x4457, NULL}, {"Sherwood", "Wisdom 3", DC_FAMILY_OCEANIC_ATOM2, 0x4458, NULL}, {"Aeris", "A300", DC_FAMILY_OCEANIC_ATOM2, 0x445A, NULL}, {"Hollis", "TX1", DC_FAMILY_OCEANIC_ATOM2, 0x4542, NULL}, {"Beuchat", "Mundial 2", DC_FAMILY_OCEANIC_ATOM2, 0x4543, NULL}, {"Sherwood", "Amphos", DC_FAMILY_OCEANIC_ATOM2, 0x4545, NULL}, {"Sherwood", "Amphos Air", DC_FAMILY_OCEANIC_ATOM2, 0x4546, NULL}, {"Oceanic", "Pro Plus 3", DC_FAMILY_OCEANIC_ATOM2, 0x4548, NULL}, {"Aeris", "F11", DC_FAMILY_OCEANIC_ATOM2, 0x4549, NULL}, {"Oceanic", "OCi", DC_FAMILY_OCEANIC_ATOM2, 0x454B, NULL}, {"Aeris", "A300CS", DC_FAMILY_OCEANIC_ATOM2, 0x454C, NULL}, {"Beuchat", "Mundial 3", DC_FAMILY_OCEANIC_ATOM2, 0x4550, NULL}, {"Oceanic", "F10", DC_FAMILY_OCEANIC_ATOM2, 0x4553, NULL}, {"Oceanic", "F11", DC_FAMILY_OCEANIC_ATOM2, 0x4554, NULL}, {"Subgear", "XP-Air", DC_FAMILY_OCEANIC_ATOM2, 0x4555, NULL}, {"Sherwood", "Vision", DC_FAMILY_OCEANIC_ATOM2, 0x4556, NULL}, {"Oceanic", "VTX", DC_FAMILY_OCEANIC_ATOM2, 0x4557, NULL}, {"Aqualung", "i300", DC_FAMILY_OCEANIC_ATOM2, 0x4559, NULL}, {"Aqualung", "i750TC", DC_FAMILY_OCEANIC_ATOM2, 0x455A, NULL}, {"Aqualung", "i450T", DC_FAMILY_OCEANIC_ATOM2, 0x4641, NULL}, {"Aqualung", "i550", DC_FAMILY_OCEANIC_ATOM2, 0x4642, NULL}, {"Aqualung", "i200", DC_FAMILY_OCEANIC_ATOM2, 0x4646, NULL}, /* Mares Nemo */ {"Mares", "Nemo", DC_FAMILY_MARES_NEMO, 0, NULL}, {"Mares", "Nemo Steel", DC_FAMILY_MARES_NEMO, 0, NULL}, {"Mares", "Nemo Titanium",DC_FAMILY_MARES_NEMO, 0, NULL}, {"Mares", "Nemo Excel", DC_FAMILY_MARES_NEMO, 17, NULL}, {"Mares", "Nemo Apneist", DC_FAMILY_MARES_NEMO, 18, NULL}, /* Mares Puck */ {"Mares", "Puck", DC_FAMILY_MARES_PUCK, 7, NULL}, {"Mares", "Puck Air", DC_FAMILY_MARES_PUCK, 19, NULL}, {"Mares", "Nemo Air", DC_FAMILY_MARES_PUCK, 4, NULL}, {"Mares", "Nemo Wide", DC_FAMILY_MARES_PUCK, 1, NULL}, /* Mares Darwin */ {"Mares", "Darwin", DC_FAMILY_MARES_DARWIN , 0, NULL}, {"Mares", "M1", DC_FAMILY_MARES_DARWIN , 0, NULL}, {"Mares", "M2", DC_FAMILY_MARES_DARWIN , 0, NULL}, {"Mares", "Darwin Air", DC_FAMILY_MARES_DARWIN , 1, NULL}, {"Mares", "Airlab", DC_FAMILY_MARES_DARWIN , 1, NULL}, /* Mares Icon HD */ {"Mares", "Matrix", DC_FAMILY_MARES_ICONHD , 0x0F, NULL}, {"Mares", "Smart", DC_FAMILY_MARES_ICONHD , 0x000010, NULL}, {"Mares", "Smart Apnea", DC_FAMILY_MARES_ICONHD , 0x010010, NULL}, {"Mares", "Icon HD", DC_FAMILY_MARES_ICONHD , 0x14, NULL}, {"Mares", "Icon HD Net Ready", DC_FAMILY_MARES_ICONHD , 0x15, NULL}, {"Mares", "Puck Pro", DC_FAMILY_MARES_ICONHD , 0x18, NULL}, {"Mares", "Nemo Wide 2", DC_FAMILY_MARES_ICONHD , 0x19, NULL}, {"Mares", "Puck 2", DC_FAMILY_MARES_ICONHD , 0x1F, NULL}, {"Mares", "Quad Air", DC_FAMILY_MARES_ICONHD , 0x23, NULL}, {"Mares", "Quad", DC_FAMILY_MARES_ICONHD , 0x29, NULL}, /* Heinrichs Weikamp */ {"Heinrichs Weikamp", "OSTC", DC_FAMILY_HW_OSTC, 0, NULL}, {"Heinrichs Weikamp", "OSTC Mk2", DC_FAMILY_HW_OSTC, 1, NULL}, {"Heinrichs Weikamp", "OSTC 2N", DC_FAMILY_HW_OSTC, 2, NULL}, {"Heinrichs Weikamp", "OSTC 2C", DC_FAMILY_HW_OSTC, 3, NULL}, {"Heinrichs Weikamp", "Frog", DC_FAMILY_HW_FROG, 0, dc_filter_hw}, {"Heinrichs Weikamp", "OSTC 2", DC_FAMILY_HW_OSTC3, 0x11, dc_filter_hw}, {"Heinrichs Weikamp", "OSTC 2", DC_FAMILY_HW_OSTC3, 0x13, dc_filter_hw}, {"Heinrichs Weikamp", "OSTC 2", DC_FAMILY_HW_OSTC3, 0x1B, dc_filter_hw}, {"Heinrichs Weikamp", "OSTC 3", DC_FAMILY_HW_OSTC3, 0x0A, dc_filter_hw}, {"Heinrichs Weikamp", "OSTC Plus", DC_FAMILY_HW_OSTC3, 0x13, dc_filter_hw}, {"Heinrichs Weikamp", "OSTC Plus", DC_FAMILY_HW_OSTC3, 0x1A, dc_filter_hw}, {"Heinrichs Weikamp", "OSTC 4", DC_FAMILY_HW_OSTC3, 0x3B, dc_filter_hw}, {"Heinrichs Weikamp", "OSTC cR", DC_FAMILY_HW_OSTC3, 0x05, dc_filter_hw}, {"Heinrichs Weikamp", "OSTC cR", DC_FAMILY_HW_OSTC3, 0x07, dc_filter_hw}, {"Heinrichs Weikamp", "OSTC Sport", DC_FAMILY_HW_OSTC3, 0x12, dc_filter_hw}, {"Heinrichs Weikamp", "OSTC Sport", DC_FAMILY_HW_OSTC3, 0x13, dc_filter_hw}, {"Heinrichs Weikamp", "OSTC 2 TR", DC_FAMILY_HW_OSTC3, 0x33, dc_filter_hw}, /* Cressi Edy */ {"Tusa", "IQ-700", DC_FAMILY_CRESSI_EDY, 0x05, NULL}, {"Cressi", "Edy", DC_FAMILY_CRESSI_EDY, 0x08, NULL}, /* Cressi Leonardo */ {"Cressi", "Leonardo", DC_FAMILY_CRESSI_LEONARDO, 1, NULL}, {"Cressi", "Giotto", DC_FAMILY_CRESSI_LEONARDO, 4, NULL}, {"Cressi", "Newton", DC_FAMILY_CRESSI_LEONARDO, 5, NULL}, {"Cressi", "Drake", DC_FAMILY_CRESSI_LEONARDO, 6, NULL}, /* Zeagle N2iTiON3 */ {"Zeagle", "N2iTiON3", DC_FAMILY_ZEAGLE_N2ITION3, 0, NULL}, {"Apeks", "Quantum X", DC_FAMILY_ZEAGLE_N2ITION3, 0, NULL}, {"Dive Rite", "NiTek Trio", DC_FAMILY_ZEAGLE_N2ITION3, 0, NULL}, {"Scubapro", "XTender 5", DC_FAMILY_ZEAGLE_N2ITION3, 0, NULL}, /* Atomic Aquatics Cobalt */ #ifdef HAVE_LIBUSB {"Atomic Aquatics", "Cobalt", DC_FAMILY_ATOMICS_COBALT, 0, NULL}, {"Atomic Aquatics", "Cobalt 2", DC_FAMILY_ATOMICS_COBALT, 2, NULL}, #endif /* Shearwater Predator */ {"Shearwater", "Predator", DC_FAMILY_SHEARWATER_PREDATOR, 2, dc_filter_shearwater}, /* Shearwater Petrel */ {"Shearwater", "Petrel", DC_FAMILY_SHEARWATER_PETREL, 3, dc_filter_shearwater}, {"Shearwater", "Petrel 2", DC_FAMILY_SHEARWATER_PETREL, 3, dc_filter_shearwater}, {"Shearwater", "Nerd", DC_FAMILY_SHEARWATER_PETREL, 4, dc_filter_shearwater}, {"Shearwater", "Perdix", DC_FAMILY_SHEARWATER_PETREL, 5, dc_filter_shearwater}, {"Shearwater", "Perdix AI", DC_FAMILY_SHEARWATER_PETREL, 6, dc_filter_shearwater}, {"Shearwater", "Nerd 2", DC_FAMILY_SHEARWATER_PETREL, 7, dc_filter_shearwater}, /* Dive Rite NiTek Q */ {"Dive Rite", "NiTek Q", DC_FAMILY_DIVERITE_NITEKQ, 0, NULL}, /* Citizen Hyper Aqualand */ {"Citizen", "Hyper Aqualand", DC_FAMILY_CITIZEN_AQUALAND, 0, NULL}, /* DiveSystem/Ratio iDive */ {"DiveSystem", "Orca", DC_FAMILY_DIVESYSTEM_IDIVE, 0x02, NULL}, {"DiveSystem", "iDive Pro", DC_FAMILY_DIVESYSTEM_IDIVE, 0x03, NULL}, {"DiveSystem", "iDive DAN", DC_FAMILY_DIVESYSTEM_IDIVE, 0x04, NULL}, {"DiveSystem", "iDive Tech", DC_FAMILY_DIVESYSTEM_IDIVE, 0x05, NULL}, {"DiveSystem", "iDive Reb", DC_FAMILY_DIVESYSTEM_IDIVE, 0x06, NULL}, {"DiveSystem", "iDive Stealth", DC_FAMILY_DIVESYSTEM_IDIVE, 0x07, NULL}, {"DiveSystem", "iDive Free", DC_FAMILY_DIVESYSTEM_IDIVE, 0x08, NULL}, {"DiveSystem", "iDive Easy", DC_FAMILY_DIVESYSTEM_IDIVE, 0x09, NULL}, {"DiveSystem", "iDive X3M", DC_FAMILY_DIVESYSTEM_IDIVE, 0x0A, NULL}, {"DiveSystem", "iDive Deep", DC_FAMILY_DIVESYSTEM_IDIVE, 0x0B, NULL}, {"Ratio", "iX3M Easy", DC_FAMILY_DIVESYSTEM_IDIVE, 0x22, NULL}, {"Ratio", "iX3M Deep", DC_FAMILY_DIVESYSTEM_IDIVE, 0x23, NULL}, {"Ratio", "iX3M Tech+", DC_FAMILY_DIVESYSTEM_IDIVE, 0x24, NULL}, {"Ratio", "iX3M Reb", DC_FAMILY_DIVESYSTEM_IDIVE, 0x25, NULL}, {"Ratio", "iX3M Pro Easy", DC_FAMILY_DIVESYSTEM_IDIVE, 0x32, NULL}, {"Ratio", "iX3M Pro Deep", DC_FAMILY_DIVESYSTEM_IDIVE, 0x34, NULL}, {"Ratio", "iX3M Pro Tech+",DC_FAMILY_DIVESYSTEM_IDIVE, 0x35, NULL}, {"Ratio", "iDive Free", DC_FAMILY_DIVESYSTEM_IDIVE, 0x40, NULL}, {"Ratio", "iDive Easy", DC_FAMILY_DIVESYSTEM_IDIVE, 0x42, NULL}, {"Ratio", "iDive Deep", DC_FAMILY_DIVESYSTEM_IDIVE, 0x44, NULL}, {"Ratio", "iDive Tech+", DC_FAMILY_DIVESYSTEM_IDIVE, 0x45, NULL}, {"Seac", "Jack", DC_FAMILY_DIVESYSTEM_IDIVE, 0x1000, NULL}, /* Cochran Commander */ {"Cochran", "Commander TM", DC_FAMILY_COCHRAN_COMMANDER, 0, NULL}, {"Cochran", "Commander I", DC_FAMILY_COCHRAN_COMMANDER, 1, NULL}, {"Cochran", "Commander II", DC_FAMILY_COCHRAN_COMMANDER, 2, NULL}, {"Cochran", "EMC-14", DC_FAMILY_COCHRAN_COMMANDER, 3, NULL}, {"Cochran", "EMC-16", DC_FAMILY_COCHRAN_COMMANDER, 4, NULL}, {"Cochran", "EMC-20H", DC_FAMILY_COCHRAN_COMMANDER, 5, NULL}, }; static int dc_filter_internal_name (const char *name, const char *values[], size_t count) { if (name == NULL) return 0; for (size_t i = 0; i < count; ++i) { if (strcasecmp (name, values[i]) == 0) { return 1; } } return 0; } static int dc_filter_internal_usb (const dc_usb_desc_t *desc, const dc_usb_desc_t values[], size_t count) { if (desc == NULL) return 0; for (size_t i = 0; i < count; ++i) { if (desc->vid == values[i].vid && desc->pid == values[i].pid) { return 1; } } return 0; } static int dc_filter_uwatec (dc_transport_t transport, const void *userdata) { static const char *irda[] = { "Aladin Smart Com", "Aladin Smart Pro", "Aladin Smart Tec", "Aladin Smart Z", "Uwatec Aladin", "UWATEC Galileo", "UWATEC Galileo Sol", }; static const dc_usb_desc_t usbhid[] = { {0x2e6c, 0x3201}, // G2 {0xc251, 0x2006}, // Aladin Square }; if (transport == DC_TRANSPORT_IRDA) { return dc_filter_internal_name ((const char *) userdata, irda, C_ARRAY_SIZE(irda)); } else if (transport == DC_TRANSPORT_USBHID) { return dc_filter_internal_usb ((const dc_usb_desc_t *) userdata, usbhid, C_ARRAY_SIZE(usbhid)); } return 1; } static int dc_filter_suunto (dc_transport_t transport, const void *userdata) { static const dc_usb_desc_t usbhid[] = { {0x1493, 0x0030}, // Eon Steel {0x1493, 0x0033}, // Eon Core }; if (transport == DC_TRANSPORT_USBHID) { return dc_filter_internal_usb ((const dc_usb_desc_t *) userdata, usbhid, C_ARRAY_SIZE(usbhid)); } return 1; } static int dc_filter_hw (dc_transport_t transport, const void *userdata) { if (transport == DC_TRANSPORT_BLUETOOTH) { return strncasecmp ((const char *) userdata, "OSTC", 4) == 0 || strncasecmp ((const char *) userdata, "FROG", 4) == 0; } return 1; } static int dc_filter_shearwater (dc_transport_t transport, const void *userdata) { static const char *bluetooth[] = { "Predator", "Petrel", "Nerd", "Perdix", }; if (transport == DC_TRANSPORT_BLUETOOTH) { return dc_filter_internal_name ((const char *) userdata, bluetooth, C_ARRAY_SIZE(bluetooth)); } return 1; } dc_status_t dc_descriptor_iterator (dc_iterator_t **out) { dc_descriptor_iterator_t *iterator = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; iterator = (dc_descriptor_iterator_t *) dc_iterator_allocate (NULL, &dc_descriptor_iterator_vtable); if (iterator == NULL) return DC_STATUS_NOMEMORY; iterator->current = 0; *out = (dc_iterator_t *) iterator; return DC_STATUS_SUCCESS; } static dc_status_t dc_descriptor_iterator_next (dc_iterator_t *abstract, void *out) { dc_descriptor_iterator_t *iterator = (dc_descriptor_iterator_t *) abstract; dc_descriptor_t **item = (dc_descriptor_t **) out; if (iterator->current >= C_ARRAY_SIZE (g_descriptors)) return DC_STATUS_DONE; /* * The explicit cast from a const to a non-const pointer is safe here. The * public interface doesn't support write access, and therefore descriptor * objects are always read-only. However, the cast allows to return a direct * reference to the entries in the table, avoiding the overhead of * allocating (and freeing) memory for a deep copy. */ *item = (dc_descriptor_t *) &g_descriptors[iterator->current++]; return DC_STATUS_SUCCESS; } void dc_descriptor_free (dc_descriptor_t *descriptor) { return; } const char * dc_descriptor_get_vendor (dc_descriptor_t *descriptor) { if (descriptor == NULL) return NULL; return descriptor->vendor; } const char * dc_descriptor_get_product (dc_descriptor_t *descriptor) { if (descriptor == NULL) return NULL; return descriptor->product; } dc_family_t dc_descriptor_get_type (dc_descriptor_t *descriptor) { if (descriptor == NULL) return DC_FAMILY_NULL; return descriptor->type; } unsigned int dc_descriptor_get_model (dc_descriptor_t *descriptor) { if (descriptor == NULL) return 0; return descriptor->model; } dc_transport_t dc_descriptor_get_transport (dc_descriptor_t *descriptor) { if (descriptor == NULL) return DC_TRANSPORT_NONE; if (descriptor->type == DC_FAMILY_ATOMICS_COBALT) return DC_TRANSPORT_USB; else if (descriptor->type == DC_FAMILY_SUUNTO_EONSTEEL) return DC_TRANSPORT_USBHID; else if (descriptor->type == DC_FAMILY_UWATEC_G2) return DC_TRANSPORT_USBHID; else if (descriptor->type == DC_FAMILY_UWATEC_SMART) return DC_TRANSPORT_IRDA; else return DC_TRANSPORT_SERIAL; } dc_filter_t dc_descriptor_get_filter (dc_descriptor_t *descriptor) { if (descriptor == NULL) return NULL; return descriptor->filter; }
libdc-for-dirk-Subsurface-branch
src/descriptor.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcmp, memcpy #include <stdlib.h> // malloc, free #include <assert.h> // assert #include "reefnet_sensusultra.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "checksum.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &reefnet_sensusultra_device_vtable) #define SZ_PACKET 512 #define SZ_MEMORY 2080768 #define SZ_USER 16384 #define SZ_HANDSHAKE 24 #define SZ_SENSE 6 #define MAXRETRIES 2 #define PROMPT 0xA5 #define ACCEPT PROMPT #define REJECT 0x00 typedef struct reefnet_sensusultra_device_t { dc_device_t base; dc_iostream_t *iostream; unsigned char handshake[SZ_HANDSHAKE]; unsigned int timestamp; unsigned int devtime; dc_ticks_t systime; } reefnet_sensusultra_device_t; static dc_status_t reefnet_sensusultra_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t reefnet_sensusultra_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t reefnet_sensusultra_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t reefnet_sensusultra_device_close (dc_device_t *abstract); static const dc_device_vtable_t reefnet_sensusultra_device_vtable = { sizeof(reefnet_sensusultra_device_t), DC_FAMILY_REEFNET_SENSUSULTRA, reefnet_sensusultra_device_set_fingerprint, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ reefnet_sensusultra_device_dump, /* dump */ reefnet_sensusultra_device_foreach, /* foreach */ NULL, /* timesync */ reefnet_sensusultra_device_close /* close */ }; dc_status_t reefnet_sensusultra_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; reefnet_sensusultra_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (reefnet_sensusultra_device_t *) dc_device_allocate (context, &reefnet_sensusultra_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; device->timestamp = 0; device->systime = (dc_ticks_t) -1; device->devtime = 0; memset (device->handshake, 0, sizeof (device->handshake)); // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (115200 8N1). status = dc_iostream_configure (device->iostream, 115200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (3000ms). status = dc_iostream_set_timeout (device->iostream, 3000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Make sure everything is in a sane state. dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t reefnet_sensusultra_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; reefnet_sensusultra_device_t *device = (reefnet_sensusultra_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } dc_status_t reefnet_sensusultra_device_get_handshake (dc_device_t *abstract, unsigned char data[], unsigned int size) { reefnet_sensusultra_device_t *device = (reefnet_sensusultra_device_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size < SZ_HANDSHAKE) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_INVALIDARGS; } memcpy (data, device->handshake, SZ_HANDSHAKE); return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensusultra_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { reefnet_sensusultra_device_t *device = (reefnet_sensusultra_device_t*) abstract; if (size && size != 4) return DC_STATUS_INVALIDARGS; if (size) device->timestamp = array_uint32_le (data); else device->timestamp = 0; return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensusultra_send_uchar (reefnet_sensusultra_device_t *device, unsigned char value) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; // Wait for the prompt byte. unsigned char prompt = 0; status = dc_iostream_read (device->iostream, &prompt, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the prompt byte"); return status; } // Verify the prompt byte. if (prompt != PROMPT) { ERROR (abstract->context, "Unexpected answer data."); return DC_STATUS_PROTOCOL; } // Send the value to the device. status = dc_iostream_write (device->iostream, &value, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the value."); return status; } return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensusultra_send_ushort (reefnet_sensusultra_device_t *device, unsigned short value) { // Send the least-significant byte. unsigned char lsb = value & 0xFF; dc_status_t rc = reefnet_sensusultra_send_uchar (device, lsb); if (rc != DC_STATUS_SUCCESS) return rc; // Send the most-significant byte. unsigned char msb = (value >> 8) & 0xFF; rc = reefnet_sensusultra_send_uchar (device, msb); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensusultra_packet (reefnet_sensusultra_device_t *device, unsigned char *data, unsigned int size, unsigned int header) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; assert (size >= header + 2); if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; // Receive the data packet. status = dc_iostream_read (device->iostream, data, size, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the packet."); return status; } // Verify the checksum of the packet. unsigned short crc = array_uint16_le (data + size - 2); unsigned short ccrc = checksum_crc_ccitt_uint16 (data + header, size - header - 2); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensusultra_handshake (reefnet_sensusultra_device_t *device, unsigned short value) { // Wake-up the device. unsigned char handshake[SZ_HANDSHAKE + 2] = {0}; dc_status_t rc = reefnet_sensusultra_packet (device, handshake, sizeof (handshake), 0); if (rc != DC_STATUS_SUCCESS) return rc; // Store the clock calibration values. device->systime = dc_datetime_now (); device->devtime = array_uint32_le (handshake + 4); // Store the handshake packet. memcpy (device->handshake, handshake, SZ_HANDSHAKE); // Emit a clock event. dc_event_clock_t clock; clock.systime = device->systime; clock.devtime = device->devtime; device_event_emit (&device->base, DC_EVENT_CLOCK, &clock); // Emit a device info event. dc_event_devinfo_t devinfo; devinfo.model = handshake[1]; devinfo.firmware = handshake[0]; devinfo.serial = array_uint16_le (handshake + 2); device_event_emit (&device->base, DC_EVENT_DEVINFO, &devinfo); // Emit a vendor event. dc_event_vendor_t vendor; vendor.data = device->handshake; vendor.size = sizeof (device->handshake); device_event_emit (&device->base, DC_EVENT_VENDOR, &vendor); // Send the instruction code to the device. rc = reefnet_sensusultra_send_ushort (device, value); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensusultra_page (reefnet_sensusultra_device_t *device, unsigned char *data, unsigned int size, unsigned int pagenum) { dc_device_t *abstract = (dc_device_t *) device; assert (size >= SZ_PACKET + 4); unsigned int nretries = 0; dc_status_t rc = DC_STATUS_SUCCESS; while ((rc = reefnet_sensusultra_packet (device, data, size, 2)) != DC_STATUS_SUCCESS) { // Automatically discard a corrupted packet, // and request a new one. if (rc != DC_STATUS_PROTOCOL) return rc; // Abort if the maximum number of retries is reached. if (nretries++ >= MAXRETRIES) return rc; // Reject the packet. rc = reefnet_sensusultra_send_uchar (device, REJECT); if (rc != DC_STATUS_SUCCESS) return rc; } // Verify the page number. unsigned int page = array_uint16_le (data); if (page != pagenum) { ERROR (abstract->context, "Unexpected page number."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensusultra_send (reefnet_sensusultra_device_t *device, unsigned short command) { // Flush the input and output buffers. dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); // Wake-up the device and send the instruction code. unsigned int nretries = 0; dc_status_t rc = DC_STATUS_SUCCESS; while ((rc = reefnet_sensusultra_handshake (device, command)) != DC_STATUS_SUCCESS) { // Automatically discard a corrupted handshake packet, // and wait for the next one. if (rc != DC_STATUS_PROTOCOL && rc != DC_STATUS_TIMEOUT) return rc; // Abort if the maximum number of retries is reached. if (nretries++ >= MAXRETRIES) return rc; // According to the developers guide, a 250 ms delay is suggested to // guarantee that the prompt byte sent after the handshake packet is // not accidentally buffered by the host and (mis)interpreted as part // of the next packet. dc_iostream_sleep (device->iostream, 250); dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); } return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensusultra_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { reefnet_sensusultra_device_t *device = (reefnet_sensusultra_device_t*) abstract; // Pre-allocate the required amount of memory. if (!dc_buffer_reserve (buffer, SZ_MEMORY)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = SZ_MEMORY; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Wake-up the device and send the instruction code. dc_status_t rc = reefnet_sensusultra_send (device, 0xB421); if (rc != DC_STATUS_SUCCESS) return rc; unsigned int nbytes = 0; unsigned int npages = 0; while (nbytes < SZ_MEMORY) { // Receive the packet. unsigned char packet[SZ_PACKET + 4] = {0}; rc = reefnet_sensusultra_page (device, packet, sizeof (packet), npages); if (rc != DC_STATUS_SUCCESS) return rc; // Update and emit a progress event. progress.current += SZ_PACKET; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Prepend the packet to the buffer. if (!dc_buffer_prepend (buffer, packet + 2, SZ_PACKET)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Accept the packet. rc = reefnet_sensusultra_send_uchar (device, ACCEPT); if (rc != DC_STATUS_SUCCESS) return rc; nbytes += SZ_PACKET; npages++; } return DC_STATUS_SUCCESS; } dc_status_t reefnet_sensusultra_device_read_user (dc_device_t *abstract, unsigned char *data, unsigned int size) { reefnet_sensusultra_device_t *device = (reefnet_sensusultra_device_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size < SZ_USER) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_INVALIDARGS; } // Wake-up the device and send the instruction code. dc_status_t rc = reefnet_sensusultra_send (device, 0xB420); if (rc != DC_STATUS_SUCCESS) return rc; unsigned int nbytes = 0; unsigned int npages = 0; while (nbytes < SZ_USER) { // Receive the packet. unsigned char packet[SZ_PACKET + 4] = {0}; rc = reefnet_sensusultra_page (device, packet, sizeof (packet), npages); if (rc != DC_STATUS_SUCCESS) return rc; // Append the packet to the buffer. memcpy (data + nbytes, packet + 2, SZ_PACKET); // Accept the packet. rc = reefnet_sensusultra_send_uchar (device, ACCEPT); if (rc != DC_STATUS_SUCCESS) return rc; nbytes += SZ_PACKET; npages++; } return DC_STATUS_SUCCESS; } dc_status_t reefnet_sensusultra_device_write_user (dc_device_t *abstract, const unsigned char *data, unsigned int size) { reefnet_sensusultra_device_t *device = (reefnet_sensusultra_device_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size < SZ_USER) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_INVALIDARGS; } // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = SZ_USER + 2; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Wake-up the device and send the instruction code. dc_status_t rc = reefnet_sensusultra_send (device, 0xB430); if (rc != DC_STATUS_SUCCESS) return rc; // Send the data to the device. for (unsigned int i = 0; i < SZ_USER; ++i) { rc = reefnet_sensusultra_send_uchar (device, data[i]); if (rc != DC_STATUS_SUCCESS) return rc; // Update and emit a progress event. progress.current += 1; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); } // Send the checksum to the device. unsigned short crc = checksum_crc_ccitt_uint16 (data, SZ_USER); rc = reefnet_sensusultra_send_ushort (device, crc); if (rc != DC_STATUS_SUCCESS) return rc; // Update and emit a progress event. progress.current += 2; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); return DC_STATUS_SUCCESS; } dc_status_t reefnet_sensusultra_device_write_parameter (dc_device_t *abstract, reefnet_sensusultra_parameter_t parameter, unsigned int value) { reefnet_sensusultra_device_t *device = (reefnet_sensusultra_device_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; // Set the instruction code and validate the new value. unsigned short code = 0; switch (parameter) { case REEFNET_SENSUSULTRA_PARAMETER_INTERVAL: code = 0xB410; if (value < 1 || value > 65535) return DC_STATUS_INVALIDARGS; break; case REEFNET_SENSUSULTRA_PARAMETER_THRESHOLD: code = 0xB411; if (value < 1 || value > 65535) return DC_STATUS_INVALIDARGS; break; case REEFNET_SENSUSULTRA_PARAMETER_ENDCOUNT: code = 0xB412; if (value < 1 || value > 65535) return DC_STATUS_INVALIDARGS; break; case REEFNET_SENSUSULTRA_PARAMETER_AVERAGING: code = 0xB413; if (value != 1 && value != 2 && value != 4) return DC_STATUS_INVALIDARGS; break; default: return DC_STATUS_INVALIDARGS; } // Wake-up the device and send the instruction code. dc_status_t rc = reefnet_sensusultra_send (device, code); if (rc != DC_STATUS_SUCCESS) return rc; // Send the new value to the device. rc = reefnet_sensusultra_send_ushort (device, value); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; } dc_status_t reefnet_sensusultra_device_sense (dc_device_t *abstract, unsigned char *data, unsigned int size) { reefnet_sensusultra_device_t *device = (reefnet_sensusultra_device_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size < SZ_SENSE) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_INVALIDARGS; } // Wake-up the device and send the instruction code. dc_status_t rc = reefnet_sensusultra_send (device, 0xB440); if (rc != DC_STATUS_SUCCESS) return rc; // Receive the packet. unsigned char package[SZ_SENSE + 2] = {0}; rc = reefnet_sensusultra_packet (device, package, sizeof (package), 0); if (rc != DC_STATUS_SUCCESS) return rc; memcpy (data, package, SZ_SENSE); return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensusultra_parse (reefnet_sensusultra_device_t *device, const unsigned char data[], unsigned int *premaining, unsigned int *pprevious, int *aborted, dc_dive_callback_t callback, void *userdata) { const unsigned char header[4] = {0x00, 0x00, 0x00, 0x00}; const unsigned char footer[4] = {0xFF, 0xFF, 0xFF, 0xFF}; // Initialize the data stream pointers. const unsigned char *current = data + *premaining; const unsigned char *previous = data + *pprevious; // Search the data stream for header markers. while ((current = array_search_backward (data, current - data, header, sizeof (header))) != NULL) { // Move the pointer to the begin of the header. current -= sizeof (header); // If there is a sequence of more than 4 zero bytes present, the header // marker is located at the start of this sequence, not the end. while (current > data && current[-1] == 0x00) current--; // Once a header marker is found, start searching // for the corresponding footer marker. The search is // now limited to the start of the previous dive. if (previous - current >= 16) { previous = array_search_forward (current + 16, previous - current - 16, footer, sizeof (footer)); } else { previous = NULL; } // Skip dives without a footer marker. if (previous) { // Move the pointer to the end of the footer. previous += sizeof (footer); // Automatically abort when a dive is older than the provided timestamp. unsigned int timestamp = array_uint32_le (current + 4); if (device && timestamp <= device->timestamp) { if (aborted) *aborted = 1; return DC_STATUS_SUCCESS; } if (callback && !callback (current, previous - current, current + 4, 4, userdata)) { if (aborted) *aborted = 1; return DC_STATUS_SUCCESS; } } // Prepare for the next iteration. previous = current; // Return the current state. *premaining = *pprevious = current - data; } // Return the current state. *premaining = sizeof (header) - 1; if (*premaining > *pprevious) *premaining = *pprevious; if (aborted) *aborted = 0; return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensusultra_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { reefnet_sensusultra_device_t *device = (reefnet_sensusultra_device_t*) abstract; dc_buffer_t *buffer = dc_buffer_new (SZ_MEMORY); if (buffer == NULL) { ERROR (abstract->context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = SZ_MEMORY; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Wake-up the device and send the instruction code. dc_status_t rc = reefnet_sensusultra_send (device, 0xB421); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } // Initialize the state for the incremental parser. unsigned int remaining = 0; unsigned int previous = 0; unsigned int nbytes = 0; unsigned int npages = 0; while (nbytes < SZ_MEMORY) { // Receive the packet. unsigned char packet[SZ_PACKET + 4] = {0}; rc = reefnet_sensusultra_page (device, packet, sizeof (packet), npages); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } // Update and emit a progress event. progress.current += SZ_PACKET; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Abort the transfer if the page contains no useful data. if (array_isequal (packet + 2, SZ_PACKET, 0xFF) && nbytes != 0) break; // Prepend the packet to the buffer. if (!dc_buffer_prepend (buffer, packet + 2, SZ_PACKET)) { dc_buffer_free (buffer); ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Update the parser state. remaining += SZ_PACKET; previous += SZ_PACKET; // Parse the page data. int aborted = 0; rc = reefnet_sensusultra_parse (device, dc_buffer_get_data (buffer), &remaining, &previous, &aborted, callback, userdata); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } if (aborted) break; // Accept the packet. rc = reefnet_sensusultra_send_uchar (device, ACCEPT); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } nbytes += SZ_PACKET; npages++; } dc_buffer_free (buffer); return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/reefnet_sensusultra.c
/* * libdivecomputer * * Copyright (C) 2009 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcmp, memcpy #include <stdlib.h> // malloc, free #include "hw_ostc.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "checksum.h" #include "array.h" #include "ihex.h" #define ISINSTANCE(device) dc_device_isinstance((device), &hw_ostc_device_vtable) #define C_ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a))) #define MAXRETRIES 9 #define FW_190 0x015A #define SZ_MD2HASH 18 #define SZ_EEPROM 256 #define SZ_HEADER 266 #define SZ_FW_190 0x8000 #define SZ_FW_NEW 0x10000 #define SZ_FIRMWARE 0x17F40 #define SZ_BLOCK 0x40 #define ACK 0x4B /* "K" for ok */ #define NAK 0x4E /* "N" for not ok */ #define PICTYPE 0x57 /* PIC type (18F4685) */ #define WIDTH 320 #define HEIGHT 240 #define BLACK 0x00 #define WHITE 0xFF typedef struct hw_ostc_device_t { dc_device_t base; dc_iostream_t *iostream; unsigned char fingerprint[5]; } hw_ostc_device_t; typedef struct hw_ostc_firmware_t { unsigned char data[SZ_FIRMWARE]; unsigned char bitmap[SZ_FIRMWARE / SZ_BLOCK]; } hw_ostc_firmware_t; static dc_status_t hw_ostc_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t hw_ostc_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t hw_ostc_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t hw_ostc_device_timesync (dc_device_t *abstract, const dc_datetime_t *datetime); static dc_status_t hw_ostc_device_close (dc_device_t *abstract); static const dc_device_vtable_t hw_ostc_device_vtable = { sizeof(hw_ostc_device_t), DC_FAMILY_HW_OSTC, hw_ostc_device_set_fingerprint, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ hw_ostc_device_dump, /* dump */ hw_ostc_device_foreach, /* foreach */ hw_ostc_device_timesync, /* timesync */ hw_ostc_device_close /* close */ }; static dc_status_t hw_ostc_extract_dives (dc_device_t *device, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata); static dc_status_t hw_ostc_send (hw_ostc_device_t *device, unsigned char cmd, unsigned int echo) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; // Send the command. unsigned char command[1] = {cmd}; status = dc_iostream_write (device->iostream, command, sizeof (command), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } if (echo) { // Read the echo. unsigned char answer[1] = {0}; status = dc_iostream_read (device->iostream, answer, sizeof (answer), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the echo."); return status; } // Verify the echo. if (memcmp (answer, command, sizeof (command)) != 0) { ERROR (abstract->context, "Unexpected echo."); return DC_STATUS_PROTOCOL; } } return DC_STATUS_SUCCESS; } dc_status_t hw_ostc_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; hw_ostc_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (hw_ostc_device_t *) dc_device_allocate (context, &hw_ostc_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; memset (device->fingerprint, 0, sizeof (device->fingerprint)); // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (115200 8N1). status = dc_iostream_configure (device->iostream, 115200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data. status = dc_iostream_set_timeout (device->iostream, 4000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Make sure everything is in a sane state. dc_iostream_sleep (device->iostream, 100); dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t hw_ostc_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; hw_ostc_device_t *device = (hw_ostc_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t hw_ostc_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { hw_ostc_device_t *device = (hw_ostc_device_t *) abstract; if (size && size != sizeof (device->fingerprint)) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, sizeof (device->fingerprint)); else memset (device->fingerprint, 0, sizeof (device->fingerprint)); return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { dc_status_t status = DC_STATUS_SUCCESS; hw_ostc_device_t *device = (hw_ostc_device_t*) abstract; // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = SZ_HEADER + SZ_FW_NEW; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Send the command. unsigned char command[1] = {'a'}; status = dc_iostream_write (device->iostream, command, sizeof (command), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Read the header. unsigned char header[SZ_HEADER] = {0}; status = dc_iostream_read (device->iostream, header, sizeof (header), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the header."); return status; } // Verify the header. unsigned char preamble[] = {0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x55}; if (memcmp (header, preamble, sizeof (preamble)) != 0) { ERROR (abstract->context, "Unexpected answer header."); return DC_STATUS_DATAFORMAT; } // Get the firmware version. unsigned int firmware = array_uint16_be (header + 264); // Get the amount of profile data. unsigned int size = sizeof (header); if (firmware > FW_190) size += SZ_FW_NEW; else size += SZ_FW_190; // Update and emit a progress event. progress.current = sizeof (header); progress.maximum = size; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Allocate the required amount of memory. if (!dc_buffer_resize (buffer, size)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } unsigned char *data = dc_buffer_get_data (buffer); // Copy the header to the output buffer. memcpy (data, header, sizeof (header)); unsigned int nbytes = sizeof (header); while (nbytes < size) { // Set the minimum packet size. unsigned int len = 1024; // Increase the packet size if more data is immediately available. size_t available = 0; status = dc_iostream_get_available (device->iostream, &available); if (status == DC_STATUS_SUCCESS && available > len) len = available; // Limit the packet size to the total size. if (nbytes + len > size) len = size - nbytes; // Read the packet. status = dc_iostream_read (device->iostream, data + nbytes, len, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Update and emit a progress event. progress.current += len; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); nbytes += len; } return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { dc_buffer_t *buffer = dc_buffer_new (0); if (buffer == NULL) return DC_STATUS_NOMEMORY; dc_status_t rc = hw_ostc_device_dump (abstract, buffer); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } // Emit a device info event. unsigned char *data = dc_buffer_get_data (buffer); dc_event_devinfo_t devinfo; devinfo.firmware = array_uint16_be (data + 264); devinfo.serial = array_uint16_le (data + 6); if (devinfo.serial > 7000) devinfo.model = 3; // OSTC 2C else if (devinfo.serial > 2048) devinfo.model = 2; // OSTC 2N else if (devinfo.serial > 300) devinfo.model = 1; // OSTC Mk2 else devinfo.model = 0; // OSTC device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); rc = hw_ostc_extract_dives (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), callback, userdata); dc_buffer_free (buffer); return rc; } dc_status_t hw_ostc_device_md2hash (dc_device_t *abstract, unsigned char data[], unsigned int size) { dc_status_t status = DC_STATUS_SUCCESS; hw_ostc_device_t *device = (hw_ostc_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size < SZ_MD2HASH) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_INVALIDARGS; } // Send the command. dc_status_t rc = hw_ostc_send (device, 'e', 0); if (rc != DC_STATUS_SUCCESS) return rc; // Read the answer. status = dc_iostream_read (device->iostream, data, SZ_MD2HASH, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc_device_timesync (dc_device_t *abstract, const dc_datetime_t *datetime) { dc_status_t status = DC_STATUS_SUCCESS; hw_ostc_device_t *device = (hw_ostc_device_t *) abstract; if (datetime == NULL) { ERROR (abstract->context, "Invalid parameter specified."); return DC_STATUS_INVALIDARGS; } // Send the command. dc_status_t rc = hw_ostc_send (device, 'b', 1); if (rc != DC_STATUS_SUCCESS) return rc; // Send the data packet. unsigned char packet[6] = { datetime->hour, datetime->minute, datetime->second, datetime->month, datetime->day, datetime->year - 2000}; status = dc_iostream_write (device->iostream, packet, sizeof (packet), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the data packet."); return status; } return DC_STATUS_SUCCESS; } dc_status_t hw_ostc_device_eeprom_read (dc_device_t *abstract, unsigned int bank, unsigned char data[], unsigned int size) { dc_status_t status = DC_STATUS_SUCCESS; hw_ostc_device_t *device = (hw_ostc_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (bank > 2) { ERROR (abstract->context, "Invalid eeprom bank specified."); return DC_STATUS_INVALIDARGS; } if (size < SZ_EEPROM) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_INVALIDARGS; } // Send the command. const unsigned char command[] = {'g', 'j', 'm'}; dc_status_t rc = hw_ostc_send (device, command[bank], 0); if (rc != DC_STATUS_SUCCESS) return rc; // Read the answer. status = dc_iostream_read (device->iostream, data, SZ_EEPROM, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } return DC_STATUS_SUCCESS; } dc_status_t hw_ostc_device_eeprom_write (dc_device_t *abstract, unsigned int bank, const unsigned char data[], unsigned int size) { hw_ostc_device_t *device = (hw_ostc_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (bank > 2) { ERROR (abstract->context, "Invalid eeprom bank specified."); return DC_STATUS_INVALIDARGS; } if (size != SZ_EEPROM) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_INVALIDARGS; } // Send the command. const unsigned char command[] = {'d', 'i', 'n'}; dc_status_t rc = hw_ostc_send (device, command[bank], 1); if (rc != DC_STATUS_SUCCESS) return rc; for (unsigned int i = 4; i < SZ_EEPROM; ++i) { // Send the data byte. rc = hw_ostc_send (device, data[i], 1); if (rc != DC_STATUS_SUCCESS) return rc; } return DC_STATUS_SUCCESS; } dc_status_t hw_ostc_device_reset (dc_device_t *abstract) { hw_ostc_device_t *device = (hw_ostc_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; // Send the command. dc_status_t rc = hw_ostc_send (device, 'h', 1); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; } dc_status_t hw_ostc_device_screenshot (dc_device_t *abstract, dc_buffer_t *buffer, hw_ostc_format_t format) { dc_status_t status = DC_STATUS_SUCCESS; hw_ostc_device_t *device = (hw_ostc_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; // Erase the current contents of the buffer. if (!dc_buffer_clear (buffer)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Bytes per pixel (RGB formats only). unsigned int bpp = 0; if (format == HW_OSTC_FORMAT_RAW) { // The RAW format has a variable size, depending on the actual image // content. Usually the total size is around 4K, which is used as an // initial guess and expanded when necessary. if (!dc_buffer_reserve (buffer, 4096)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } } else { // The RGB formats have a fixed size, depending only on the dimensions // and the number of bytes per pixel. The required amount of memory is // allocated immediately. bpp = (format == HW_OSTC_FORMAT_RGB16) ? 2 : 3; if (!dc_buffer_resize (buffer, WIDTH * HEIGHT * bpp)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } } // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = WIDTH * HEIGHT; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Send the command. dc_status_t rc = hw_ostc_send (device, 'l', 1); if (rc != DC_STATUS_SUCCESS) return rc; // Cache the pointer to the image data (RGB formats only). unsigned char *image = dc_buffer_get_data (buffer); // The OSTC sends the image data in a column by column layout, which is // converted on the fly to a more convenient row by row layout as used // in the majority of image formats. This conversions requires knowledge // of the pixel coordinates. unsigned int x = 0, y = 0; unsigned int npixels = 0; while (npixels < WIDTH * HEIGHT) { unsigned char raw[3] = {0}; status = dc_iostream_read (device->iostream, raw, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the packet."); return status; } unsigned int nbytes = 1; unsigned int count = raw[0]; if ((count & 0x80) == 0x00) { // Black pixel. raw[1] = raw[2] = BLACK; count &= 0x7F; } else if ((count & 0xC0) == 0xC0) { // White pixel. raw[1] = raw[2] = WHITE; count &= 0x3F; } else { // Color pixel. status = dc_iostream_read (device->iostream, raw + 1, 2, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the packet."); return status; } nbytes += 2; count &= 0x3F; } count++; // Check for buffer overflows. if (npixels + count > WIDTH * HEIGHT) { ERROR (abstract->context, "Unexpected number of pixels received."); return DC_STATUS_DATAFORMAT; } if (format == HW_OSTC_FORMAT_RAW) { // Append the raw data to the output buffer. if (!dc_buffer_append (buffer, raw, nbytes)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } } else { // Store the decompressed data in the output buffer. for (unsigned int i = 0; i < count; ++i) { // Calculate the offset to the current pixel (row layout) unsigned int offset = (y * WIDTH + x) * bpp; if (format == HW_OSTC_FORMAT_RGB16) { image[offset + 0] = raw[1]; image[offset + 1] = raw[2]; } else { unsigned int value = (raw[1] << 8) + raw[2]; unsigned char r = (value & 0xF800) >> 11; unsigned char g = (value & 0x07E0) >> 5; unsigned char b = (value & 0x001F); image[offset + 0] = 255 * r / 31; image[offset + 1] = 255 * g / 63; image[offset + 2] = 255 * b / 31; } // Move to the next pixel coordinate (column layout). y++; if (y == HEIGHT) { y = 0; x++; } } } // Update and emit a progress event. progress.current += count; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); npixels += count; } return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc_extract_dives (dc_device_t *abstract, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata) { hw_ostc_device_t *device = (hw_ostc_device_t *) abstract; if (abstract && !ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; const unsigned char header[2] = {0xFA, 0xFA}; const unsigned char footer[2] = {0xFD, 0xFD}; // Initialize the data stream pointers. const unsigned char *current = data + size; const unsigned char *previous = data + size; // Search the data stream for header markers. while ((current = array_search_backward (data + 266, current - data - 266, header, sizeof (header))) != NULL) { // Move the pointer to the begin of the header. current -= sizeof (header); // Once a header marker is found, start searching // for the corresponding footer marker. The search is // now limited to the start of the previous dive. previous = array_search_forward (current, previous - current, footer, sizeof (footer)); if (previous) { // Move the pointer to the end of the footer. previous += sizeof (footer); if (device && memcmp (current + 3, device->fingerprint, sizeof (device->fingerprint)) == 0) return DC_STATUS_SUCCESS; if (callback && !callback (current, previous - current, current + 3, 5, userdata)) return DC_STATUS_SUCCESS; } // Prepare for the next iteration. previous = current; } return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc_firmware_readfile (hw_ostc_firmware_t *firmware, dc_context_t *context, const char *filename) { dc_status_t rc = DC_STATUS_SUCCESS; if (firmware == NULL) { ERROR (context, "Invalid arguments."); return DC_STATUS_INVALIDARGS; } // Initialize the buffers. memset (firmware->data, 0xFF, sizeof (firmware->data)); memset (firmware->bitmap, 0x00, sizeof (firmware->bitmap)); // Open the hex file. dc_ihex_file_t *file = NULL; rc = dc_ihex_file_open (&file, context, filename); if (rc != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the hex file."); return rc; } // Read the hex file. unsigned int lba = 0; dc_ihex_entry_t entry; while ((rc = dc_ihex_file_read (file, &entry)) == DC_STATUS_SUCCESS) { if (entry.type == 0) { // Data record. unsigned int address = (lba << 16) + entry.address; if (address + entry.length > SZ_FIRMWARE) { WARNING (context, "Ignoring out of range record (0x%08x,%u).", address, entry.length); continue; } // Copy the record to the buffer. memcpy (firmware->data + address, entry.data, entry.length); // Mark the corresponding blocks in the bitmap. unsigned int begin = address / SZ_BLOCK; unsigned int end = (address + entry.length + SZ_BLOCK - 1) / SZ_BLOCK; for (unsigned int i = begin; i < end; ++i) { firmware->bitmap[i] = 1; } } else if (entry.type == 1) { // End of file record. break; } else if (entry.type == 4) { // Extended linear address record. lba = array_uint16_be (entry.data); } else { ERROR (context, "Unexpected record type."); dc_ihex_file_close (file); return DC_STATUS_DATAFORMAT; } } if (rc != DC_STATUS_SUCCESS && rc != DC_STATUS_DONE) { ERROR (context, "Failed to read the record."); dc_ihex_file_close (file); return rc; } // Close the file. dc_ihex_file_close (file); // Verify the presence of the first block. if (firmware->bitmap[0] == 0) { ERROR (context, "No first data block."); return DC_STATUS_DATAFORMAT; } // Setup the last block. // Copy the "goto main" instruction, stored in the first 8 bytes of the hex // file, to the end of the last block at address 0x17F38. This last block // needs to be present, regardless of whether it's included in the hex file // or not! memset (firmware->data + SZ_FIRMWARE - SZ_BLOCK, 0xFF, SZ_BLOCK - 8); memcpy (firmware->data + SZ_FIRMWARE - 8, firmware->data, 8); firmware->bitmap[C_ARRAY_SIZE(firmware->bitmap) - 1] = 1; // Setup the first block. // Copy the hardcoded "goto 0x17F40" instruction to the start of the first // block at address 0x00000. const unsigned char header[] = {0xA0, 0xEF, 0xBF, 0xF0}; memcpy (firmware->data, header, sizeof (header)); return rc; } static dc_status_t hw_ostc_firmware_setup_internal (hw_ostc_device_t *device) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; // Send the command. unsigned char command[1] = {0xC1}; status = dc_iostream_write (device->iostream, command, sizeof (command), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Read the response. unsigned char answer[2] = {0}; status = dc_iostream_read (device->iostream, answer, sizeof (answer), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the response."); return status; } // Verify the response. const unsigned char expected[2] = {PICTYPE, ACK}; if (memcmp (answer, expected, sizeof (expected)) != 0) { ERROR (abstract->context, "Unexpected response."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc_firmware_setup (hw_ostc_device_t *device, unsigned int maxretries) { dc_status_t rc = DC_STATUS_SUCCESS; unsigned int nretries = 0; while ((rc = hw_ostc_firmware_setup_internal (device)) != DC_STATUS_SUCCESS) { if (rc != DC_STATUS_TIMEOUT && rc != DC_STATUS_PROTOCOL) break; // Abort if the maximum number of retries is reached. if (nretries++ >= maxretries) break; } return rc; } static dc_status_t hw_ostc_firmware_write_internal (hw_ostc_device_t *device, unsigned char *data, unsigned int size) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; // Send the packet. status = dc_iostream_write (device->iostream, data, size, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the packet."); return status; } // Read the response. unsigned char answer[1] = {0}; status = dc_iostream_read (device->iostream, answer, sizeof (answer), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the response."); return status; } // Verify the response. const unsigned char expected[] = {ACK}; if (memcmp (answer, expected, sizeof (expected)) != 0) { ERROR (abstract->context, "Unexpected response."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc_firmware_write (hw_ostc_device_t *device, unsigned char *data, unsigned int size) { dc_status_t rc = DC_STATUS_SUCCESS; unsigned int nretries = 0; while ((rc = hw_ostc_firmware_write_internal (device, data, size)) != DC_STATUS_SUCCESS) { if (rc != DC_STATUS_TIMEOUT && rc != DC_STATUS_PROTOCOL) break; // Abort if the maximum number of retries is reached. if (nretries++ >= MAXRETRIES) break; } return rc; } /* * Think twice before modifying the code for updating the ostc firmware! * It has been carefully developed and tested with assistance from * Heinrichs-Weikamp, using a special development unit. If you start * experimenting with a normal unit and accidentally screw up, you might * brick the device permanently and turn it into an expensive * paperweight. You have been warned! */ dc_status_t hw_ostc_device_fwupdate (dc_device_t *abstract, const char *filename) { dc_status_t rc = DC_STATUS_SUCCESS; hw_ostc_device_t *device = (hw_ostc_device_t *) abstract; dc_context_t *context = (abstract ? abstract->context : NULL); if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; // Allocate memory for the firmware data. hw_ostc_firmware_t *firmware = (hw_ostc_firmware_t *) malloc (sizeof (hw_ostc_firmware_t)); if (firmware == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Read the hex file. rc = hw_ostc_firmware_readfile (firmware, context, filename); if (rc != DC_STATUS_SUCCESS) { ERROR (context, "Failed to read the firmware file."); free (firmware); return rc; } // Temporary set a relative short timeout. The command to setup the // bootloader needs to be send repeatedly, until the response packet is // received. Thus the time between each two attempts is directly controlled // by the timeout value. rc = dc_iostream_set_timeout (device->iostream, 300); if (rc != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); free (firmware); return rc; } // Setup the bootloader. const unsigned int baudrates[] = {19200, 115200}; for (unsigned int i = 0; i < C_ARRAY_SIZE(baudrates); ++i) { // Adjust the baudrate. rc = dc_iostream_configure (device->iostream, baudrates[i], 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to set the terminal attributes."); free (firmware); return rc; } // Try to setup the bootloader. unsigned int maxretries = (i == 0 ? 1 : MAXRETRIES); rc = hw_ostc_firmware_setup (device, maxretries); if (rc == DC_STATUS_SUCCESS) break; } if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to setup the bootloader."); free (firmware); return rc; } // Increase the timeout again. rc = dc_iostream_set_timeout (device->iostream, 1000); if (rc != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); free (firmware); return rc; } // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = C_ARRAY_SIZE(firmware->bitmap); device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); for (unsigned int i = 0; i < C_ARRAY_SIZE(firmware->bitmap); ++i) { // Skip empty blocks. if (firmware->bitmap[i] == 0) continue; // Create the packet. unsigned int address = i * SZ_BLOCK; unsigned char packet[4 + SZ_BLOCK + 1] = { (address >> 16) & 0xFF, (address >> 8) & 0xFF, (address ) & 0xFF, SZ_BLOCK }; memcpy (packet + 4, firmware->data + address, SZ_BLOCK); packet[sizeof (packet) - 1] = ~checksum_add_uint8 (packet, 4 + SZ_BLOCK, 0x00) + 1; // Send the packet. rc = hw_ostc_firmware_write (device, packet, sizeof (packet)); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the packet."); free (firmware); return rc; } // Update and emit a progress event. progress.current = i + 1; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); } free (firmware); return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/hw_ostc.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <assert.h> #include "suunto_d9.h" #include "suunto_eon.h" #include "suunto_eonsteel.h" #include "suunto_solution.h" #include "suunto_vyper2.h" #include "suunto_vyper.h" #include "reefnet_sensus.h" #include "reefnet_sensuspro.h" #include "reefnet_sensusultra.h" #include "uwatec_aladin.h" #include "uwatec_memomouse.h" #include "uwatec_meridian.h" #include "uwatec_smart.h" #include "oceanic_atom2.h" #include "oceanic_atom2.h" #include "oceanic_veo250.h" #include "oceanic_vtpro.h" #include "mares_darwin.h" #include "mares_iconhd.h" #include "mares_nemo.h" #include "mares_puck.h" #include "hw_frog.h" #include "hw_ostc.h" #include "hw_ostc3.h" #include "cressi_edy.h" #include "cressi_leonardo.h" #include "zeagle_n2ition3.h" #include "atomics_cobalt.h" #include "shearwater_petrel.h" #include "shearwater_predator.h" #include "diverite_nitekq.h" #include "citizen_aqualand.h" #include "divesystem_idive.h" #include "cochran_commander.h" #include "context-private.h" #include "parser-private.h" #include "device-private.h" #define REACTPROWHITE 0x4354 static dc_status_t dc_parser_new_internal (dc_parser_t **out, dc_context_t *context, dc_family_t family, unsigned int model, unsigned int serial, unsigned int devtime, dc_ticks_t systime) { dc_status_t rc = DC_STATUS_SUCCESS; dc_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; switch (family) { case DC_FAMILY_SUUNTO_SOLUTION: rc = suunto_solution_parser_create (&parser, context); break; case DC_FAMILY_SUUNTO_EON: rc = suunto_eon_parser_create (&parser, context, 0); break; case DC_FAMILY_SUUNTO_VYPER: if (model == 0x01) rc = suunto_eon_parser_create (&parser, context, 1); else rc = suunto_vyper_parser_create (&parser, context); break; case DC_FAMILY_SUUNTO_VYPER2: case DC_FAMILY_SUUNTO_D9: rc = suunto_d9_parser_create (&parser, context, model, serial); break; case DC_FAMILY_SUUNTO_EONSTEEL: rc = suunto_eonsteel_parser_create(&parser, context, model); break; case DC_FAMILY_UWATEC_ALADIN: case DC_FAMILY_UWATEC_MEMOMOUSE: rc = uwatec_memomouse_parser_create (&parser, context, devtime, systime); break; case DC_FAMILY_UWATEC_SMART: case DC_FAMILY_UWATEC_MERIDIAN: case DC_FAMILY_UWATEC_G2: rc = uwatec_smart_parser_create (&parser, context, model, devtime, systime); break; case DC_FAMILY_REEFNET_SENSUS: rc = reefnet_sensus_parser_create (&parser, context, devtime, systime); break; case DC_FAMILY_REEFNET_SENSUSPRO: rc = reefnet_sensuspro_parser_create (&parser, context, devtime, systime); break; case DC_FAMILY_REEFNET_SENSUSULTRA: rc = reefnet_sensusultra_parser_create (&parser, context, devtime, systime); break; case DC_FAMILY_OCEANIC_VTPRO: rc = oceanic_vtpro_parser_create (&parser, context, model); break; case DC_FAMILY_OCEANIC_VEO250: rc = oceanic_veo250_parser_create (&parser, context, model); break; case DC_FAMILY_OCEANIC_ATOM2: if (model == REACTPROWHITE) rc = oceanic_veo250_parser_create (&parser, context, model); else rc = oceanic_atom2_parser_create (&parser, context, model, serial); break; case DC_FAMILY_MARES_NEMO: case DC_FAMILY_MARES_PUCK: rc = mares_nemo_parser_create (&parser, context, model); break; case DC_FAMILY_MARES_DARWIN: rc = mares_darwin_parser_create (&parser, context, model); break; case DC_FAMILY_MARES_ICONHD: rc = mares_iconhd_parser_create (&parser, context, model); break; case DC_FAMILY_HW_OSTC: rc = hw_ostc_parser_create (&parser, context, serial, 0); break; case DC_FAMILY_HW_FROG: case DC_FAMILY_HW_OSTC3: rc = hw_ostc3_parser_create (&parser, context, serial, model); break; case DC_FAMILY_CRESSI_EDY: case DC_FAMILY_ZEAGLE_N2ITION3: rc = cressi_edy_parser_create (&parser, context, model); break; case DC_FAMILY_CRESSI_LEONARDO: rc = cressi_leonardo_parser_create (&parser, context, model); break; case DC_FAMILY_ATOMICS_COBALT: rc = atomics_cobalt_parser_create (&parser, context); break; case DC_FAMILY_SHEARWATER_PREDATOR: rc = shearwater_predator_parser_create (&parser, context, model, serial); break; case DC_FAMILY_SHEARWATER_PETREL: rc = shearwater_petrel_parser_create (&parser, context, model, serial); break; case DC_FAMILY_DIVERITE_NITEKQ: rc = diverite_nitekq_parser_create (&parser, context); break; case DC_FAMILY_CITIZEN_AQUALAND: rc = citizen_aqualand_parser_create (&parser, context); break; case DC_FAMILY_DIVESYSTEM_IDIVE: rc = divesystem_idive_parser_create (&parser, context, model); break; case DC_FAMILY_COCHRAN_COMMANDER: rc = cochran_commander_parser_create (&parser, context, model); break; default: return DC_STATUS_INVALIDARGS; } *out = parser; return rc; } dc_status_t dc_parser_new (dc_parser_t **out, dc_device_t *device) { if (device == NULL) return DC_STATUS_INVALIDARGS; return dc_parser_new_internal (out, device->context, dc_device_get_type (device), device->devinfo.model, device->devinfo.serial, device->clock.devtime, device->clock.systime); } dc_status_t dc_parser_new2 (dc_parser_t **out, dc_context_t *context, dc_descriptor_t *descriptor, unsigned int devtime, dc_ticks_t systime) { return dc_parser_new_internal (out, context, dc_descriptor_get_type (descriptor), dc_descriptor_get_model (descriptor), 0, devtime, systime); } dc_parser_t * dc_parser_allocate (dc_context_t *context, const dc_parser_vtable_t *vtable) { dc_parser_t *parser = NULL; assert(vtable != NULL); assert(vtable->size >= sizeof(dc_parser_t)); // Allocate memory. parser = (dc_parser_t *) malloc (vtable->size); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return parser; } // Initialize the base class. parser->vtable = vtable; parser->context = context; parser->data = NULL; parser->size = 0; return parser; } void dc_parser_deallocate (dc_parser_t *parser) { free (parser); } int dc_parser_isinstance (dc_parser_t *parser, const dc_parser_vtable_t *vtable) { if (parser == NULL) return 0; return parser->vtable == vtable; } dc_family_t dc_parser_get_type (dc_parser_t *parser) { if (parser == NULL) return DC_FAMILY_NULL; return parser->vtable->type; } dc_status_t dc_parser_set_data (dc_parser_t *parser, const unsigned char *data, unsigned int size) { if (parser == NULL) return DC_STATUS_UNSUPPORTED; if (parser->vtable->set_data == NULL) return DC_STATUS_UNSUPPORTED; parser->data = data; parser->size = size; return parser->vtable->set_data (parser, data, size); } dc_status_t dc_parser_get_datetime (dc_parser_t *parser, dc_datetime_t *datetime) { if (parser == NULL) return DC_STATUS_UNSUPPORTED; if (parser->vtable->datetime == NULL) return DC_STATUS_UNSUPPORTED; return parser->vtable->datetime (parser, datetime); } dc_status_t dc_parser_get_field (dc_parser_t *parser, dc_field_type_t type, unsigned int flags, void *value) { if (parser == NULL) return DC_STATUS_UNSUPPORTED; if (parser->vtable->field == NULL) return DC_STATUS_UNSUPPORTED; return parser->vtable->field (parser, type, flags, value); } dc_status_t dc_parser_samples_foreach (dc_parser_t *parser, dc_sample_callback_t callback, void *userdata) { if (parser == NULL) return DC_STATUS_UNSUPPORTED; if (parser->vtable->samples_foreach == NULL) return DC_STATUS_UNSUPPORTED; return parser->vtable->samples_foreach (parser, callback, userdata); } dc_status_t dc_parser_destroy (dc_parser_t *parser) { dc_status_t status = DC_STATUS_SUCCESS; if (parser == NULL) return DC_STATUS_SUCCESS; if (parser->vtable->destroy) { status = parser->vtable->destroy (parser); } dc_parser_deallocate (parser); return status; } void sample_statistics_cb (dc_sample_type_t type, dc_sample_value_t value, void *userdata) { sample_statistics_t *statistics = (sample_statistics_t *) userdata; switch (type) { case DC_SAMPLE_TIME: statistics->divetime = value.time; break; case DC_SAMPLE_DEPTH: if (statistics->maxdepth < value.depth) statistics->maxdepth = value.depth; break; default: break; } }
libdc-for-dirk-Subsurface-branch
src/parser.c
/* * libdivecomputer * * Copyright (C) 2013 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcpy, memcmp #include <stdlib.h> // malloc, free #include <assert.h> // assert #include "cressi_leonardo.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "checksum.h" #include "array.h" #include "ringbuffer.h" #define ISINSTANCE(device) dc_device_isinstance((device), &cressi_leonardo_device_vtable) #define SZ_MEMORY 32000 #define RB_LOGBOOK_BEGIN 0x0100 #define RB_LOGBOOK_END 0x1438 #define RB_LOGBOOK_SIZE 0x52 #define RB_LOGBOOK_COUNT ((RB_LOGBOOK_END - RB_LOGBOOK_BEGIN) / RB_LOGBOOK_SIZE) #define RB_PROFILE_BEGIN 0x1438 #define RB_PROFILE_END SZ_MEMORY #define RB_PROFILE_DISTANCE(a,b) ringbuffer_distance (a, b, 0, RB_PROFILE_BEGIN, RB_PROFILE_END) #define MAXRETRIES 4 #define PACKETSIZE 32 typedef struct cressi_leonardo_device_t { dc_device_t base; dc_iostream_t *iostream; unsigned char fingerprint[5]; } cressi_leonardo_device_t; static dc_status_t cressi_leonardo_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t cressi_leonardo_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size); static dc_status_t cressi_leonardo_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t cressi_leonardo_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t cressi_leonardo_device_close (dc_device_t *abstract); static const dc_device_vtable_t cressi_leonardo_device_vtable = { sizeof(cressi_leonardo_device_t), DC_FAMILY_CRESSI_LEONARDO, cressi_leonardo_device_set_fingerprint, /* set_fingerprint */ cressi_leonardo_device_read, /* read */ NULL, /* write */ cressi_leonardo_device_dump, /* dump */ cressi_leonardo_device_foreach, /* foreach */ NULL, /* timesync */ cressi_leonardo_device_close /* close */ }; static dc_status_t cressi_leonardo_extract_dives (dc_device_t *abstract, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata); static void cressi_leonardo_make_ascii (const unsigned char raw[], unsigned int rsize, unsigned char ascii[], unsigned int asize) { assert (asize == 2 * (rsize + 3)); // Header ascii[0] = '{'; // Data array_convert_bin2hex (raw, rsize, ascii + 1, 2 * rsize); // Checksum unsigned short crc = checksum_crc_ccitt_uint16 (ascii + 1, 2 * rsize); unsigned char checksum[] = { (crc >> 8) & 0xFF, // High (crc ) & 0xFF}; // Low array_convert_bin2hex (checksum, sizeof(checksum), ascii + 1 + 2 * rsize, 4); // Trailer ascii[asize - 1] = '}'; } static dc_status_t cressi_leonardo_packet (cressi_leonardo_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; // Send the command to the device. status = dc_iostream_write (device->iostream, command, csize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Receive the answer of the device. status = dc_iostream_read (device->iostream, answer, asize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Verify the header and trailer of the packet. if (answer[0] != '{' || answer[asize - 1] != '}') { ERROR (abstract->context, "Unexpected answer header/trailer byte."); return DC_STATUS_PROTOCOL; } // Convert the checksum of the packet. unsigned char checksum[2] = {0}; array_convert_hex2bin (answer + asize - 5, 4, checksum, sizeof(checksum)); // Verify the checksum of the packet. unsigned short crc = array_uint16_be (checksum); unsigned short ccrc = checksum_crc_ccitt_uint16 (answer + 1, asize - 6); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } static dc_status_t cressi_leonardo_transfer (cressi_leonardo_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize) { unsigned int nretries = 0; dc_status_t rc = DC_STATUS_SUCCESS; while ((rc = cressi_leonardo_packet (device, command, csize, answer, asize)) != DC_STATUS_SUCCESS) { // Automatically discard a corrupted packet, // and request a new one. if (rc != DC_STATUS_PROTOCOL && rc != DC_STATUS_TIMEOUT) return rc; // Abort if the maximum number of retries is reached. if (nretries++ >= MAXRETRIES) return rc; // Discard any garbage bytes. dc_iostream_sleep (device->iostream, 100); dc_iostream_purge (device->iostream, DC_DIRECTION_INPUT); } return rc; } dc_status_t cressi_leonardo_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; cressi_leonardo_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (cressi_leonardo_device_t *) dc_device_allocate (context, &cressi_leonardo_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; memset (device->fingerprint, 0, sizeof (device->fingerprint)); // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (115200 8N1). status = dc_iostream_configure (device->iostream, 115200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (1000 ms). status = dc_iostream_set_timeout (device->iostream, 1000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Set the RTS line. status = dc_iostream_set_rts (device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the RTS line."); goto error_close; } // Set the DTR line. status = dc_iostream_set_dtr (device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the DTR line."); goto error_close; } dc_iostream_sleep (device->iostream, 200); // Clear the DTR line. status = dc_iostream_set_dtr (device->iostream, 0); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to clear the DTR line."); goto error_close; } dc_iostream_sleep (device->iostream, 100); dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); *out = (dc_device_t *) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t cressi_leonardo_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; cressi_leonardo_device_t *device = (cressi_leonardo_device_t *) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t cressi_leonardo_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { cressi_leonardo_device_t *device = (cressi_leonardo_device_t *) abstract; if (size && size != sizeof (device->fingerprint)) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, sizeof (device->fingerprint)); else memset (device->fingerprint, 0, sizeof (device->fingerprint)); return DC_STATUS_SUCCESS; } static dc_status_t cressi_leonardo_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size) { dc_status_t rc = DC_STATUS_SUCCESS; cressi_leonardo_device_t *device = (cressi_leonardo_device_t *) abstract; unsigned int nbytes = 0; while (nbytes < size) { // Calculate the packet size. unsigned int len = size - nbytes; if (len > PACKETSIZE) len = PACKETSIZE; // Build the raw command. unsigned char raw[] = { (address >> 8) & 0xFF, // High (address ) & 0xFF, // Low (len >> 8) & 0xFF, // High (len ) & 0xFF}; // Low // Build the ascii command. unsigned char command[2 * (sizeof (raw) + 3)] = {0}; cressi_leonardo_make_ascii (raw, sizeof (raw), command, sizeof (command)); // Send the command and receive the answer. unsigned char answer[2 * (PACKETSIZE + 3)] = {0}; rc = cressi_leonardo_transfer (device, command, sizeof (command), answer, 2 * (len + 3)); if (rc != DC_STATUS_SUCCESS) return rc; // Extract the raw data from the packet. array_convert_hex2bin (answer + 1, 2 * len, data, len); nbytes += len; address += len; data += len; } return rc; } static dc_status_t cressi_leonardo_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { dc_status_t status = DC_STATUS_SUCCESS; cressi_leonardo_device_t *device = (cressi_leonardo_device_t *) abstract; // Allocate the required amount of memory. if (!dc_buffer_resize (buffer, SZ_MEMORY)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = SZ_MEMORY; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Send the command header to the dive computer. const unsigned char command[] = {0x7B, 0x31, 0x32, 0x33, 0x44, 0x42, 0x41, 0x7d}; status = dc_iostream_write (device->iostream, command, sizeof (command), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Receive the header packet. unsigned char header[7] = {0}; status = dc_iostream_read (device->iostream, header, sizeof (header), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Verify the header packet. const unsigned char expected[] = {0x7B, 0x21, 0x44, 0x35, 0x42, 0x33, 0x7d}; if (memcmp (header, expected, sizeof (expected)) != 0) { ERROR (abstract->context, "Unexpected answer byte."); return DC_STATUS_PROTOCOL; } unsigned char *data = dc_buffer_get_data (buffer); unsigned int nbytes = 0; while (nbytes < SZ_MEMORY) { // Set the minimum packet size. unsigned int len = 1024; // Increase the packet size if more data is immediately available. size_t available = 0; status = dc_iostream_get_available (device->iostream, &available); if (status == DC_STATUS_SUCCESS && available > len) len = available; // Limit the packet size to the total size. if (nbytes + len > SZ_MEMORY) len = SZ_MEMORY - nbytes; // Read the packet. status = dc_iostream_read (device->iostream, data + nbytes, len, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Update and emit a progress event. progress.current += len; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); nbytes += len; } // Receive the trailer packet. unsigned char trailer[4] = {0}; status = dc_iostream_read (device->iostream, trailer, sizeof (trailer), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Convert to a binary checksum. unsigned char checksum[2] = {0}; array_convert_hex2bin (trailer, sizeof (trailer), checksum, sizeof (checksum)); // Verify the checksum. unsigned int csum1 = array_uint16_be (checksum); unsigned int csum2 = checksum_crc_ccitt_uint16 (data, SZ_MEMORY); if (csum1 != csum2) { ERROR (abstract->context, "Unexpected answer bytes."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } static dc_status_t cressi_leonardo_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { dc_buffer_t *buffer = dc_buffer_new (SZ_MEMORY); if (buffer == NULL) return DC_STATUS_NOMEMORY; dc_status_t rc = cressi_leonardo_device_dump (abstract, buffer); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } unsigned char *data = dc_buffer_get_data (buffer); dc_event_devinfo_t devinfo; devinfo.model = data[0]; devinfo.firmware = 0; devinfo.serial = array_uint24_le (data + 1); device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); rc = cressi_leonardo_extract_dives (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), callback, userdata); dc_buffer_free (buffer); return rc; } static dc_status_t cressi_leonardo_extract_dives (dc_device_t *abstract, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata) { cressi_leonardo_device_t *device = (cressi_leonardo_device_t *) abstract; dc_context_t *context = (abstract ? abstract->context : NULL); if (abstract && !ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size < SZ_MEMORY) return DC_STATUS_DATAFORMAT; // Get the number of dives. //unsigned int ndives = array_uint16_le(data + 0x62); // Get the logbook pointer. unsigned int last = array_uint16_le(data + 0x64); if (last < RB_LOGBOOK_BEGIN || last > RB_LOGBOOK_END || ((last - RB_LOGBOOK_BEGIN) % RB_LOGBOOK_SIZE) != 0) { ERROR (context, "Invalid logbook pointer (0x%04x).", last); return DC_STATUS_DATAFORMAT; } // Convert to an index. unsigned int latest = (last - RB_LOGBOOK_BEGIN) / RB_LOGBOOK_SIZE; // Get the profile pointer. unsigned int eop = array_uint16_le(data + 0x66); if (eop < RB_PROFILE_BEGIN || last > RB_PROFILE_END) { ERROR (context, "Invalid profile pointer (0x%04x).", eop); return DC_STATUS_DATAFORMAT; } unsigned char *buffer = (unsigned char *) malloc (RB_LOGBOOK_SIZE + RB_PROFILE_END - RB_PROFILE_BEGIN); if (buffer == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } unsigned int previous = eop; unsigned int remaining = RB_PROFILE_END - RB_PROFILE_BEGIN; for (unsigned int i = 0; i < RB_LOGBOOK_COUNT; ++i) { unsigned int idx = (latest + RB_LOGBOOK_COUNT - i) % RB_LOGBOOK_COUNT; unsigned int offset = RB_LOGBOOK_BEGIN + idx * RB_LOGBOOK_SIZE; // Ignore uninitialized header entries. if (array_isequal (data + offset, RB_LOGBOOK_SIZE, 0xFF)) break; // Get the ringbuffer pointers. unsigned int header = array_uint16_le (data + offset + 2); unsigned int footer = array_uint16_le (data + offset + 4); if (header < RB_PROFILE_BEGIN || header + 2 > RB_PROFILE_END || footer < RB_PROFILE_BEGIN || footer + 2 > RB_PROFILE_END) { ERROR (context, "Invalid ringbuffer pointer detected (0x%04x 0x%04x).", header, footer); free (buffer); return DC_STATUS_DATAFORMAT; } if (previous && previous != footer + 2) { ERROR (context, "Profiles are not continuous (0x%04x 0x%04x 0x%04x).", header, footer, previous); free (buffer); return DC_STATUS_DATAFORMAT; } // Check the fingerprint data. if (device && memcmp (data + offset + 8, device->fingerprint, sizeof (device->fingerprint)) == 0) break; // Copy the logbook entry. memcpy (buffer, data + offset, RB_LOGBOOK_SIZE); // Calculate the profile address and length. unsigned int address = header + 2; unsigned int length = RB_PROFILE_DISTANCE (header, footer) - 2; if (remaining && remaining >= length + 4) { // Get the same pointers from the profile. unsigned int header2 = array_uint16_le (data + footer); unsigned int footer2 = array_uint16_le (data + header); if (header2 != header || footer2 != footer) { ERROR (context, "Invalid ringbuffer pointer detected (0x%04x 0x%04x).", header2, footer2); free (buffer); return DC_STATUS_DATAFORMAT; } // Copy the profile data. if (address + length > RB_PROFILE_END) { unsigned int len_a = RB_PROFILE_END - address; unsigned int len_b = length - len_a; memcpy (buffer + RB_LOGBOOK_SIZE, data + address, len_a); memcpy (buffer + RB_LOGBOOK_SIZE + len_a, data + RB_PROFILE_BEGIN, len_b); } else { memcpy (buffer + RB_LOGBOOK_SIZE, data + address, length); } remaining -= length + 4; } else { // No more profile data available! remaining = 0; length = 0; } if (callback && !callback (buffer, RB_LOGBOOK_SIZE + length, buffer + 8, sizeof (device->fingerprint), userdata)) { break; } previous = header; } free (buffer); return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/cressi_leonardo.c
/* * libdivecomputer * * Copyright (C) 2013 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> // malloc, free #include <stdio.h> #include "socket.h" #ifdef _WIN32 #ifdef HAVE_WS2BTH_H #define BLUETOOTH #include <initguid.h> #include <ws2bth.h> #endif #else #ifdef HAVE_BLUEZ #define BLUETOOTH #include <bluetooth/bluetooth.h> #include <bluetooth/rfcomm.h> #include <bluetooth/hci.h> #include <bluetooth/hci_lib.h> #include <bluetooth/sdp.h> #include <bluetooth/sdp_lib.h> #endif #endif #include "bluetooth.h" #include "common-private.h" #include "context-private.h" #include "iostream-private.h" #include "iterator-private.h" #include "descriptor-private.h" #ifdef _WIN32 #define DC_ADDRESS_FORMAT "%012I64X" #else #define DC_ADDRESS_FORMAT "%012llX" #endif #define C_ARRAY_SIZE(array) (sizeof (array) / sizeof *(array)) #define MAX_DEVICES 255 #define MAX_PERIODS 8 #define ISINSTANCE(device) dc_iostream_isinstance((device), &dc_bluetooth_vtable) struct dc_bluetooth_device_t { dc_bluetooth_address_t address; char name[248]; }; #ifdef BLUETOOTH static dc_status_t dc_bluetooth_iterator_next (dc_iterator_t *iterator, void *item); static dc_status_t dc_bluetooth_iterator_free (dc_iterator_t *iterator); typedef struct dc_bluetooth_iterator_t { dc_iterator_t base; dc_filter_t filter; #ifdef _WIN32 HANDLE hLookup; #else int fd; inquiry_info *devices; size_t count; size_t current; #endif } dc_bluetooth_iterator_t; static const dc_iterator_vtable_t dc_bluetooth_iterator_vtable = { sizeof(dc_bluetooth_iterator_t), dc_bluetooth_iterator_next, dc_bluetooth_iterator_free, }; static const dc_iostream_vtable_t dc_bluetooth_vtable = { sizeof(dc_socket_t), dc_socket_set_timeout, /* set_timeout */ dc_socket_set_latency, /* set_latency */ dc_socket_set_break, /* set_break */ dc_socket_set_dtr, /* set_dtr */ dc_socket_set_rts, /* set_rts */ dc_socket_get_lines, /* get_lines */ dc_socket_get_available, /* get_received */ dc_socket_configure, /* configure */ dc_socket_read, /* read */ dc_socket_write, /* write */ dc_socket_flush, /* flush */ dc_socket_purge, /* purge */ dc_socket_sleep, /* sleep */ dc_socket_close, /* close */ }; #ifdef HAVE_BLUEZ static dc_bluetooth_address_t dc_address_get (const bdaddr_t *ba) { dc_bluetooth_address_t address = 0; size_t shift = 0; for (size_t i = 0; i < C_ARRAY_SIZE(ba->b); ++i) { address |= (dc_bluetooth_address_t) ba->b[i] << shift; shift += 8; } return address; } static void dc_address_set (bdaddr_t *ba, dc_bluetooth_address_t address) { size_t shift = 0; for (size_t i = 0; i < C_ARRAY_SIZE(ba->b); ++i) { ba->b[i] = (address >> shift) & 0xFF; shift += 8; } } static dc_status_t dc_bluetooth_sdp (uint8_t *port, dc_context_t *context, const bdaddr_t *ba) { dc_status_t status = DC_STATUS_SUCCESS; sdp_session_t *session = NULL; sdp_list_t *search = NULL, *attrid = NULL; sdp_list_t *records = NULL; uint8_t channel = 0; // Connect to the SDP server on the remote device. session = sdp_connect (BDADDR_ANY, ba, SDP_RETRY_IF_BUSY); if (session == NULL) { s_errcode_t errcode = S_ERRNO; SYSERROR (context, errcode); status = dc_socket_syserror(errcode); goto error; } // Specify the UUID of the serial port service with all attributes. uuid_t uuid = {0}; uint32_t range = 0x0000FFFF; sdp_uuid16_create (&uuid, SERIAL_PORT_SVCLASS_ID); search = sdp_list_append (NULL, &uuid); attrid = sdp_list_append (NULL, &range); if (search == NULL || attrid == NULL) { s_errcode_t errcode = S_ERRNO; SYSERROR (context, errcode); status = dc_socket_syserror(errcode); goto error; } // Get a list of the service records with their attributes. if (sdp_service_search_attr_req (session, search, SDP_ATTR_REQ_RANGE, attrid, &records) != 0) { s_errcode_t errcode = S_ERRNO; SYSERROR (context, errcode); status = dc_socket_syserror(errcode); goto error; } // Go through each of the service records. for (sdp_list_t *r = records; r; r = r->next ) { sdp_record_t *record = (sdp_record_t *) r->data; // Get a list of the protocol sequences. sdp_list_t *protos = NULL; if (sdp_get_access_protos (record, &protos) != 0 ) { s_errcode_t errcode = S_ERRNO; SYSERROR (context, errcode); status = dc_socket_syserror(errcode); goto error; } // Get the rfcomm port number. int ch = sdp_get_proto_port (protos, RFCOMM_UUID); sdp_list_foreach (protos, (sdp_list_func_t) sdp_list_free, NULL); sdp_list_free (protos, NULL); if (ch > 0) { channel = ch; break; } } if (channel == 0) { ERROR (context, "No serial port service found!"); status = DC_STATUS_IO; goto error; } INFO (context, "SDP: channel=%u", channel); *port = channel; error: sdp_list_free (records, (sdp_free_func_t) sdp_record_free); sdp_list_free (attrid, NULL); sdp_list_free (search, NULL); sdp_close (session); return status; } #endif #endif char * dc_bluetooth_addr2str(dc_bluetooth_address_t address, char *str, size_t size) { if (str == NULL || size < DC_BLUETOOTH_SIZE) return NULL; int n = snprintf(str, size, "%02X:%02X:%02X:%02X:%02X:%02X", (unsigned char)((address >> 40) & 0xFF), (unsigned char)((address >> 32) & 0xFF), (unsigned char)((address >> 24) & 0xFF), (unsigned char)((address >> 16) & 0xFF), (unsigned char)((address >> 8) & 0xFF), (unsigned char)((address >> 0) & 0xFF)); if (n < 0 || (size_t) n >= size) return NULL; return str; } dc_bluetooth_address_t dc_bluetooth_str2addr(const char *str) { dc_bluetooth_address_t address = 0; if (str == NULL) return 0; unsigned char c = 0; while ((c = *str++) != '\0') { if (c == ':') { continue; } else if (c >= '0' && c <= '9') { c -= '0'; } else if (c >= 'A' && c <= 'F') { c -= 'A' - 10; } else if (c >= 'a' && c <= 'f') { c -= 'a' - 10; } else { return 0; /* Invalid character! */ } address <<= 4; address |= c; } return address; } dc_bluetooth_address_t dc_bluetooth_device_get_address (dc_bluetooth_device_t *device) { if (device == NULL) return 0; return device->address; } const char * dc_bluetooth_device_get_name (dc_bluetooth_device_t *device) { if (device == NULL || device->name[0] == '\0') return NULL; return device->name; } void dc_bluetooth_device_free (dc_bluetooth_device_t *device) { free (device); } dc_status_t dc_bluetooth_iterator_new (dc_iterator_t **out, dc_context_t *context, dc_descriptor_t *descriptor) { #ifdef BLUETOOTH dc_status_t status = DC_STATUS_SUCCESS; dc_bluetooth_iterator_t *iterator = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; iterator = (dc_bluetooth_iterator_t *) dc_iterator_allocate (context, &dc_bluetooth_iterator_vtable); if (iterator == NULL) { SYSERROR (context, S_ENOMEM); return DC_STATUS_NOMEMORY; } #ifdef _WIN32 WSAQUERYSET wsaq; memset(&wsaq, 0, sizeof (wsaq)); wsaq.dwSize = sizeof (wsaq); wsaq.dwNameSpace = NS_BTH; wsaq.lpcsaBuffer = NULL; HANDLE hLookup = NULL; if (WSALookupServiceBegin(&wsaq, LUP_CONTAINERS | LUP_FLUSHCACHE, &hLookup) != 0) { s_errcode_t errcode = S_ERRNO; if (errcode == WSASERVICE_NOT_FOUND) { // No remote bluetooth devices found. hLookup = NULL; } else { SYSERROR (context, errcode); status = dc_socket_syserror(errcode); goto error_free; } } iterator->hLookup = hLookup; #else // Get the resource number for the first available bluetooth adapter. int dev = hci_get_route (NULL); if (dev < 0) { s_errcode_t errcode = S_ERRNO; SYSERROR (context, errcode); status = dc_socket_syserror(errcode); goto error_free; } // Open a socket to the bluetooth adapter. int fd = hci_open_dev (dev); if (fd < 0) { s_errcode_t errcode = S_ERRNO; SYSERROR (context, errcode); status = dc_socket_syserror(errcode); goto error_free; } // Perform the bluetooth device discovery. The inquiry lasts for at // most MAX_PERIODS * 1.28 seconds, and at most MAX_DEVICES devices // will be returned. inquiry_info *devices = NULL; int ndevices = hci_inquiry (dev, MAX_PERIODS, MAX_DEVICES, NULL, &devices, IREQ_CACHE_FLUSH); if (ndevices < 0) { s_errcode_t errcode = S_ERRNO; SYSERROR (context, errcode); status = dc_socket_syserror(errcode); goto error_close; } iterator->fd = fd; iterator->devices = devices; iterator->count = ndevices; iterator->current = 0; #endif iterator->filter = dc_descriptor_get_filter (descriptor); *out = (dc_iterator_t *) iterator; return DC_STATUS_SUCCESS; #ifndef _WIN32 error_close: hci_close_dev(fd); #endif error_free: dc_iterator_deallocate ((dc_iterator_t *) iterator); return status; #else return DC_STATUS_UNSUPPORTED; #endif } #ifdef BLUETOOTH static dc_status_t dc_bluetooth_iterator_next (dc_iterator_t *abstract, void *out) { dc_bluetooth_iterator_t *iterator = (dc_bluetooth_iterator_t *) abstract; dc_bluetooth_device_t *device = NULL; #ifdef _WIN32 if (iterator->hLookup == NULL) { return DC_STATUS_DONE; } unsigned char buf[4096]; LPWSAQUERYSET pwsaResults = (LPWSAQUERYSET) buf; memset(pwsaResults, 0, sizeof(WSAQUERYSET)); pwsaResults->dwSize = sizeof(WSAQUERYSET); pwsaResults->dwNameSpace = NS_BTH; pwsaResults->lpBlob = NULL; while (1) { DWORD dwSize = sizeof(buf); if (WSALookupServiceNext (iterator->hLookup, LUP_RETURN_NAME | LUP_RETURN_ADDR, &dwSize, pwsaResults) != 0) { s_errcode_t errcode = S_ERRNO; if (errcode == WSA_E_NO_MORE || errcode == WSAENOMORE) { break; // No more results. } SYSERROR (abstract->context, errcode); return dc_socket_syserror(errcode); } if (pwsaResults->dwNumberOfCsAddrs == 0 || pwsaResults->lpcsaBuffer == NULL || pwsaResults->lpcsaBuffer->RemoteAddr.lpSockaddr == NULL) { ERROR (abstract->context, "Invalid results returned"); return DC_STATUS_IO; } SOCKADDR_BTH *sa = (SOCKADDR_BTH *) pwsaResults->lpcsaBuffer->RemoteAddr.lpSockaddr; dc_bluetooth_address_t address = sa->btAddr; const char *name = (char *) pwsaResults->lpszServiceInstanceName; #else while (iterator->current < iterator->count) { inquiry_info *dev = &iterator->devices[iterator->current++]; dc_bluetooth_address_t address = dc_address_get (&dev->bdaddr); // Get the user friendly name. char buf[HCI_MAX_NAME_LENGTH], *name = buf; int rc = hci_read_remote_name (iterator->fd, &dev->bdaddr, sizeof(buf), buf, 0); if (rc < 0) { name = NULL; } // Null terminate the string. buf[sizeof(buf) - 1] = '\0'; #endif INFO (abstract->context, "Discover: address=" DC_ADDRESS_FORMAT ", name=%s", address, name ? name : ""); if (iterator->filter && !iterator->filter (DC_TRANSPORT_BLUETOOTH, name)) { continue; } device = (dc_bluetooth_device_t *) malloc (sizeof(dc_bluetooth_device_t)); if (device == NULL) { SYSERROR (abstract->context, S_ENOMEM); return DC_STATUS_NOMEMORY; } device->address = address; if (name) { strncpy(device->name, name, sizeof(device->name) - 1); device->name[sizeof(device->name) - 1] = '\0'; } else { memset(device->name, 0, sizeof(device->name)); } *(dc_bluetooth_device_t **) out = device; return DC_STATUS_SUCCESS; } return DC_STATUS_DONE; } static dc_status_t dc_bluetooth_iterator_free (dc_iterator_t *abstract) { dc_bluetooth_iterator_t *iterator = (dc_bluetooth_iterator_t *) abstract; #ifdef _WIN32 if (iterator->hLookup) { WSALookupServiceEnd (iterator->hLookup); } #else bt_free(iterator->devices); hci_close_dev(iterator->fd); #endif return DC_STATUS_SUCCESS; } #endif dc_status_t dc_bluetooth_open (dc_iostream_t **out, dc_context_t *context, dc_bluetooth_address_t address, unsigned int port) { #ifdef BLUETOOTH dc_status_t status = DC_STATUS_SUCCESS; dc_socket_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; INFO (context, "Open: address=" DC_ADDRESS_FORMAT ", port=%u", address, port); // Allocate memory. device = (dc_socket_t *) dc_iostream_allocate (context, &dc_bluetooth_vtable); if (device == NULL) { SYSERROR (context, S_ENOMEM); return DC_STATUS_NOMEMORY; } // Open the socket. #ifdef _WIN32 status = dc_socket_open (&device->base, AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM); #else status = dc_socket_open (&device->base, AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM); #endif if (status != DC_STATUS_SUCCESS) { goto error_free; } #ifdef _WIN32 SOCKADDR_BTH sa; sa.addressFamily = AF_BTH; sa.btAddr = address; sa.port = port; if (port == 0) { sa.serviceClassId = SerialPortServiceClass_UUID; } else { memset(&sa.serviceClassId, 0, sizeof(sa.serviceClassId)); } #else struct sockaddr_rc sa; sa.rc_family = AF_BLUETOOTH; dc_address_set (&sa.rc_bdaddr, address); if (port == 0) { status = dc_bluetooth_sdp (&sa.rc_channel, context, &sa.rc_bdaddr); if (status != DC_STATUS_SUCCESS) { goto error_close; } } else { sa.rc_channel = port; } #endif status = dc_socket_connect (&device->base, (struct sockaddr *) &sa, sizeof (sa)); if (status != DC_STATUS_SUCCESS) { goto error_close; } *out = (dc_iostream_t *) device; return DC_STATUS_SUCCESS; error_close: dc_socket_close (&device->base); error_free: dc_iostream_deallocate ((dc_iostream_t *) device); return status; #else return DC_STATUS_UNSUPPORTED; #endif }
libdc-for-dirk-Subsurface-branch
src/bluetooth.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * (C) 2017 Linus Torvalds * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> // malloc, free #include <string.h> // strncmp, strstr #include "scubapro_g2.h" #include "context-private.h" #include "device-private.h" #include "usbhid.h" #include "array.h" #include "platform.h" #define ISINSTANCE(device) dc_device_isinstance((device), &scubapro_g2_device_vtable) #define RX_PACKET_SIZE 64 #define TX_PACKET_SIZE 32 #define ALADINSPORTMATRIX 0x17 #define ALADINSQUARE 0x22 #define G2 0x32 typedef struct scubapro_g2_device_t { dc_device_t base; unsigned int timestamp; unsigned int devtime; dc_ticks_t systime; } scubapro_g2_device_t; static dc_status_t scubapro_g2_device_set_fingerprint (dc_device_t *device, const unsigned char data[], unsigned int size); static dc_status_t scubapro_g2_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t scubapro_g2_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t scubapro_g2_device_close (dc_device_t *abstract); static const dc_device_vtable_t scubapro_g2_device_vtable = { sizeof(scubapro_g2_device_t), DC_FAMILY_UWATEC_G2, scubapro_g2_device_set_fingerprint, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ scubapro_g2_device_dump, /* dump */ scubapro_g2_device_foreach, /* foreach */ NULL, /* timesync */ scubapro_g2_device_close /* close */ }; static dc_status_t scubapro_g2_extract_dives (dc_device_t *device, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata); static int receive_data(scubapro_g2_device_t *g2, unsigned char *buffer, int size, dc_event_progress_t *progress) { dc_custom_io_t *io = _dc_context_custom_io(g2->base.context); while (size) { unsigned char buf[RX_PACKET_SIZE] = { 0 }; size_t transferred = 0; dc_status_t rc; int len; rc = io->packet_read(io, buf, sizeof(buf), &transferred); if (rc != DC_STATUS_SUCCESS) { ERROR(g2->base.context, "read interrupt transfer failed"); return -1; } if (transferred < 1) { ERROR(g2->base.context, "incomplete read interrupt transfer (got empty packet)"); return -1; } len = buf[0]; if (transferred < len + 1) { ERROR(g2->base.context, "small packet read (got %zu, expected at least %d)", transferred, len + 1); return -1; } if (len >= sizeof(buf)) { ERROR(g2->base.context, "read interrupt transfer returns impossible packet size (%d)", len); return -1; } HEXDUMP (g2->base.context, DC_LOGLEVEL_DEBUG, "rcv", buf+1, len); if (len > size) { ERROR(g2->base.context, "receive result buffer too small - truncating"); len = size; } memcpy(buffer, buf+1, len); size -= len; buffer += len; // Update and emit a progress event? if (progress) { progress->current += len; device_event_emit(&g2->base, DC_EVENT_PROGRESS, progress); } } return 0; } static dc_status_t scubapro_g2_transfer(scubapro_g2_device_t *g2, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize) { dc_custom_io_t *io = _dc_context_custom_io(g2->base.context); unsigned char buf[TX_PACKET_SIZE+1] = { 0 }; // the +1 is for the report type byte dc_status_t status = DC_STATUS_SUCCESS; size_t transferred = 0; if (csize > sizeof(buf)-2) { ERROR(g2->base.context, "command too big (%d)", csize); return DC_STATUS_INVALIDARGS; } HEXDUMP (g2->base.context, DC_LOGLEVEL_DEBUG, "cmd", command, csize); buf[0] = 0; // USBHID report type buf[1] = csize; // command size memcpy(buf+2, command, csize); // command bytes // BLE GATT protocol? if (io->packet_size < 64) { // No report type byte status = io->packet_write(io, buf+1, csize+1, &transferred); } else { status = io->packet_write(io, buf, sizeof(buf), &transferred); } if (status != DC_STATUS_SUCCESS) { ERROR(g2->base.context, "Failed to send the command."); return status; } if (receive_data(g2, answer, asize, NULL) < 0) { ERROR(g2->base.context, "Failed to receive the answer."); return DC_STATUS_IO; } return DC_STATUS_SUCCESS; } static dc_status_t scubapro_g2_handshake (scubapro_g2_device_t *device, unsigned int model) { dc_device_t *abstract = (dc_device_t *) device; // Command template. unsigned char answer[1] = {0}; unsigned char command[5] = {0x00, 0x10, 0x27, 0, 0}; // The vendor software does not do a handshake for the Aladin Sport Matrix, // so let's not do any either. if (model == ALADINSPORTMATRIX) return DC_STATUS_SUCCESS; // Handshake (stage 1). command[0] = 0x1B; dc_status_t rc = scubapro_g2_transfer (device, command, 1, answer, 1); if (rc != DC_STATUS_SUCCESS) return rc; // Verify the answer. if (answer[0] != 0x01) { ERROR (abstract->context, "Unexpected answer byte(s)."); return DC_STATUS_PROTOCOL; } // Handshake (stage 2). command[0] = 0x1C; rc = scubapro_g2_transfer (device, command, 5, answer, 1); if (rc != DC_STATUS_SUCCESS) return rc; // Verify the answer. if (answer[0] != 0x01) { ERROR (abstract->context, "Unexpected answer byte(s)."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } struct usb_id { unsigned int model; unsigned short vendor, device; }; #define C_ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a))) static const struct usb_id *get_usb_id(unsigned int model) { int i; static const struct usb_id model_to_usb[] = { { G2, 0x2e6c, 0x3201 }, // Scubapro G2 { ALADINSQUARE, 0xc251, 0x2006 }, // Scubapro Aladin Square }; for (i = 0; i < C_ARRAY_SIZE(model_to_usb); i++) { const struct usb_id *id = model_to_usb+i; if (id->model == model) return id; } return NULL; }; dc_status_t scubapro_g2_device_open(dc_device_t **out, dc_context_t *context, const char *name, unsigned int model) { dc_status_t status = DC_STATUS_SUCCESS; scubapro_g2_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (scubapro_g2_device_t *) dc_device_allocate (context, &scubapro_g2_device_vtable); if (device == NULL) { ERROR(context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->timestamp = 0; device->systime = (dc_ticks_t) -1; device->devtime = 0; dc_custom_io_t *io = _dc_context_custom_io(context); if (io && io->packet_open) status = io->packet_open(io, context, name); else { const struct usb_id *id = get_usb_id(model); if (!id) { ERROR(context, "Unknown USB ID for Scubapro model %#04x", model); status = DC_STATUS_IO; goto error_free; } status = dc_usbhid_custom_io(context, id->vendor, id->device); } if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open Scubapro G2 device"); goto error_free; } // Perform the handshaking. status = scubapro_g2_handshake(device, model); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to handshake with the device."); goto error_close; } *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: scubapro_g2_device_close((dc_device_t *) device); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t scubapro_g2_device_close (dc_device_t *abstract) { dc_custom_io_t *io = _dc_context_custom_io(abstract->context); return io->packet_close(io); } static dc_status_t scubapro_g2_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { scubapro_g2_device_t *device = (scubapro_g2_device_t*) abstract; if (size && size != 4) return DC_STATUS_INVALIDARGS; if (size) device->timestamp = array_uint32_le (data); else device->timestamp = 0; return DC_STATUS_SUCCESS; } static dc_status_t scubapro_g2_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { scubapro_g2_device_t *device = (scubapro_g2_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; device_event_emit (&device->base, DC_EVENT_PROGRESS, &progress); // Read the model number. unsigned char cmd_model[1] = {0x10}; unsigned char model[1] = {0}; rc = scubapro_g2_transfer (device, cmd_model, sizeof (cmd_model), model, sizeof (model)); if (rc != DC_STATUS_SUCCESS) return rc; // Read the serial number. unsigned char cmd_serial[1] = {0x14}; unsigned char serial[4] = {0}; rc = scubapro_g2_transfer (device, cmd_serial, sizeof (cmd_serial), serial, sizeof (serial)); if (rc != DC_STATUS_SUCCESS) return rc; // Read the device clock. unsigned char cmd_devtime[1] = {0x1A}; unsigned char devtime[4] = {0}; rc = scubapro_g2_transfer (device, cmd_devtime, sizeof (cmd_devtime), devtime, sizeof (devtime)); if (rc != DC_STATUS_SUCCESS) return rc; // Store the clock calibration values. device->systime = dc_datetime_now (); device->devtime = array_uint32_le (devtime); // Update and emit a progress event. progress.current += 9; device_event_emit (&device->base, DC_EVENT_PROGRESS, &progress); // Emit a clock event. dc_event_clock_t clock; clock.systime = device->systime; clock.devtime = device->devtime; device_event_emit (&device->base, DC_EVENT_CLOCK, &clock); // Emit a device info event. dc_event_devinfo_t devinfo; devinfo.model = model[0]; devinfo.firmware = 0; devinfo.serial = array_uint32_le (serial); device_event_emit (&device->base, DC_EVENT_DEVINFO, &devinfo); // Command template. unsigned char command[9] = {0x00, (device->timestamp ) & 0xFF, (device->timestamp >> 8 ) & 0xFF, (device->timestamp >> 16) & 0xFF, (device->timestamp >> 24) & 0xFF, 0x10, 0x27, 0, 0}; // Data Length. command[0] = 0xC6; unsigned char answer[4] = {0}; rc = scubapro_g2_transfer (device, command, sizeof (command), answer, sizeof (answer)); if (rc != DC_STATUS_SUCCESS) return rc; unsigned int length = array_uint32_le (answer); // Update and emit a progress event. progress.maximum = 4 + 9 + (length ? length + 4 : 0); progress.current += 4; device_event_emit (&device->base, DC_EVENT_PROGRESS, &progress); if (length == 0) return DC_STATUS_SUCCESS; // Allocate the required amount of memory. if (!dc_buffer_resize (buffer, length)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } unsigned char *data = dc_buffer_get_data (buffer); // Data. command[0] = 0xC4; rc = scubapro_g2_transfer (device, command, sizeof (command), answer, sizeof (answer)); if (rc != DC_STATUS_SUCCESS) return rc; unsigned int total = array_uint32_le (answer); // Update and emit a progress event. progress.current += 4; device_event_emit (&device->base, DC_EVENT_PROGRESS, &progress); if (total != length + 4) { ERROR (abstract->context, "Received an unexpected size."); return DC_STATUS_PROTOCOL; } if (receive_data(device, data, length, &progress)) { ERROR (abstract->context, "Received an unexpected size."); return DC_STATUS_IO; } return DC_STATUS_SUCCESS; } static dc_status_t scubapro_g2_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { dc_buffer_t *buffer = dc_buffer_new (0); if (buffer == NULL) return DC_STATUS_NOMEMORY; dc_status_t rc = scubapro_g2_device_dump (abstract, buffer); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } rc = scubapro_g2_extract_dives (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), callback, userdata); dc_buffer_free (buffer); return rc; } static dc_status_t scubapro_g2_extract_dives (dc_device_t *abstract, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata) { if (abstract && !ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; const unsigned char header[4] = {0xa5, 0xa5, 0x5a, 0x5a}; // Search the data stream for start markers. unsigned int previous = size; unsigned int current = (size >= 4 ? size - 4 : 0); while (current > 0) { current--; if (memcmp (data + current, header, sizeof (header)) == 0) { // Get the length of the profile data. unsigned int len = array_uint32_le (data + current + 4); // Check for a buffer overflow. if (current + len > previous) return DC_STATUS_DATAFORMAT; if (callback && !callback (data + current, len, data + current + 8, 4, userdata)) return DC_STATUS_SUCCESS; // Prepare for the next dive. previous = current; current = (current >= 4 ? current - 4 : 0); } } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/scubapro_g2.c
/* * libdivecomputer * * Copyright (C) 2013 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <string.h> #include <assert.h> #include "diverite_nitekq.h" #include "context-private.h" #include "device-private.h" #include "checksum.h" #include "serial.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &diverite_nitekq_device_vtable) #define KEEPALIVE 0x3E // '<' #define BLOCK 0x42 // 'B' #define DISCONNECT 0x44 // 'D' #define HANDSHAKE 0x48 // 'H' #define RESET 0x52 // 'R' #define UPLOAD 0x55 // 'U' #define SZ_PACKET 256 #define SZ_MEMORY (128 * SZ_PACKET) #define SZ_LOGBOOK 6 #define LOGBOOK 0x0320 #define ADDRESS 0x0384 #define EOP 0x03E6 #define RB_PROFILE_BEGIN 0x03E8 #define RB_PROFILE_END SZ_MEMORY typedef struct diverite_nitekq_device_t { dc_device_t base; dc_iostream_t *iostream; unsigned char version[32]; unsigned char fingerprint[SZ_LOGBOOK]; } diverite_nitekq_device_t; static dc_status_t diverite_nitekq_device_set_fingerprint (dc_device_t *device, const unsigned char data[], unsigned int size); static dc_status_t diverite_nitekq_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t diverite_nitekq_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t diverite_nitekq_device_close (dc_device_t *abstract); static const dc_device_vtable_t diverite_nitekq_device_vtable = { sizeof(diverite_nitekq_device_t), DC_FAMILY_DIVERITE_NITEKQ, diverite_nitekq_device_set_fingerprint, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ diverite_nitekq_device_dump, /* dump */ diverite_nitekq_device_foreach, /* foreach */ NULL, /* timesync */ diverite_nitekq_device_close /* close */ }; static dc_status_t diverite_nitekq_extract_dives (dc_device_t *device, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata); static dc_status_t diverite_nitekq_send (diverite_nitekq_device_t *device, unsigned char cmd) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; // Send the command. unsigned char command[] = {cmd}; status = dc_iostream_write (device->iostream, command, sizeof (command), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } return DC_STATUS_SUCCESS; } static dc_status_t diverite_nitekq_receive (diverite_nitekq_device_t *device, unsigned char data[], unsigned int size) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; // Read the answer. status = dc_iostream_read (device->iostream, data, size, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Read the checksum. unsigned char checksum[2] = {0}; status = dc_iostream_read (device->iostream, checksum, sizeof (checksum), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the checksum."); return status; } return DC_STATUS_SUCCESS; } static dc_status_t diverite_nitekq_handshake (diverite_nitekq_device_t *device) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; // Send the command. unsigned char command[] = {HANDSHAKE}; status = dc_iostream_write (device->iostream, command, sizeof (command), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Read the answer. status = dc_iostream_read (device->iostream, device->version, sizeof (device->version), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } return DC_STATUS_SUCCESS; } dc_status_t diverite_nitekq_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; diverite_nitekq_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (diverite_nitekq_device_t *) dc_device_allocate (context, &diverite_nitekq_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; memset (device->fingerprint, 0, sizeof (device->fingerprint)); // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (9600 8N1). status = dc_iostream_configure (device->iostream, 9600, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (1000ms). status = dc_iostream_set_timeout (device->iostream, 1000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Make sure everything is in a sane state. dc_iostream_sleep (device->iostream, 100); dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); // Perform the handshaking. status = diverite_nitekq_handshake (device); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to handshake."); goto error_close; } *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t diverite_nitekq_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; diverite_nitekq_device_t *device = (diverite_nitekq_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Disconnect. rc = diverite_nitekq_send (device, DISCONNECT); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t diverite_nitekq_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { diverite_nitekq_device_t *device = (diverite_nitekq_device_t*) abstract; if (size && size != sizeof (device->fingerprint)) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, sizeof (device->fingerprint)); else memset (device->fingerprint, 0, sizeof (device->fingerprint)); return DC_STATUS_SUCCESS; } static dc_status_t diverite_nitekq_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { diverite_nitekq_device_t *device = (diverite_nitekq_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; unsigned char packet[256] = {0}; // Pre-allocate the required amount of memory. if (!dc_buffer_reserve (buffer, SZ_PACKET + SZ_MEMORY)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = SZ_PACKET + SZ_MEMORY; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Emit a vendor event. dc_event_vendor_t vendor; vendor.data = device->version; vendor.size = sizeof (device->version); device_event_emit (abstract, DC_EVENT_VENDOR, &vendor); // Emit a device info event. dc_event_devinfo_t devinfo; devinfo.model = 0; devinfo.firmware = 0; devinfo.serial = array_uint32_be (device->version + 0x0A); device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); // Send the upload request. It's not clear whether this request is // actually needed, but let's send it anyway. rc = diverite_nitekq_send (device, UPLOAD); if (rc != DC_STATUS_SUCCESS) { return rc; } // Receive the response packet. It's currently not used (or needed) // for anything, but we prepend it to the main data anyway, in case // we ever need it in the future. rc = diverite_nitekq_receive (device, packet, sizeof (packet)); if (rc != DC_STATUS_SUCCESS) { return rc; } dc_buffer_append (buffer, packet, sizeof (packet)); // Update and emit a progress event. progress.current += SZ_PACKET; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Send the request to initiate downloading memory blocks. rc = diverite_nitekq_send (device, RESET); if (rc != DC_STATUS_SUCCESS) { return rc; } for (unsigned int i = 0; i < 128; ++i) { // Request the next memory block. rc = diverite_nitekq_send (device, BLOCK); if (rc != DC_STATUS_SUCCESS) { return rc; } // Receive the memory block. rc = diverite_nitekq_receive (device, packet, sizeof (packet)); if (rc != DC_STATUS_SUCCESS) { return rc; } dc_buffer_append (buffer, packet, sizeof (packet)); // Update and emit a progress event. progress.current += SZ_PACKET; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); } return DC_STATUS_SUCCESS; } static dc_status_t diverite_nitekq_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { dc_buffer_t *buffer = dc_buffer_new (0); if (buffer == NULL) return DC_STATUS_NOMEMORY; dc_status_t rc = diverite_nitekq_device_dump (abstract, buffer); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (buffer); return rc; } rc = diverite_nitekq_extract_dives (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), callback, userdata); dc_buffer_free (buffer); return rc; } static dc_status_t diverite_nitekq_extract_dives (dc_device_t *abstract, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata) { diverite_nitekq_device_t *device = (diverite_nitekq_device_t *) abstract; dc_context_t *context = (abstract ? abstract->context : NULL); if (abstract && !ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size < SZ_PACKET + SZ_MEMORY) return DC_STATUS_DATAFORMAT; // Skip the first packet. We don't need it for anything. It also // makes the logic easier because all offsets in the data are // relative to the real start of the memory (e.g. excluding this // artificial first block). data += SZ_PACKET; // Allocate memory. unsigned char *buffer = (unsigned char *) malloc (SZ_LOGBOOK + RB_PROFILE_END - RB_PROFILE_BEGIN); if (buffer == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Get the end of profile pointer. unsigned int eop = array_uint16_be(data + EOP); if (eop < RB_PROFILE_BEGIN || eop >= RB_PROFILE_END) { ERROR (context, "Invalid ringbuffer pointer detected (0x%04x).", eop); free (buffer); return DC_STATUS_DATAFORMAT; } // When a new dive is added, the device moves all existing logbook // and address entries towards the end, such that the most recent // one is always the first one. This is not the case for the profile // data, which is added at the end. unsigned int previous = eop; for (unsigned int i = 0; i < 10; ++i) { // Get the pointer to the logbook entry. const unsigned char *p = data + LOGBOOK + i * SZ_LOGBOOK; // Abort if an empty logbook is found. if (array_isequal (p, SZ_LOGBOOK, 0x00)) break; // Get the address of the profile data. unsigned int address = array_uint16_be(data + ADDRESS + i * 2); if (address < RB_PROFILE_BEGIN || address >= RB_PROFILE_END) { ERROR (context, "Invalid ringbuffer pointer detected (0x%04x).", address); free (buffer); return DC_STATUS_DATAFORMAT; } // Check the fingerprint data. if (device && memcmp (p, device->fingerprint, sizeof (device->fingerprint)) == 0) break; // Copy the logbook entry. memcpy (buffer, p, SZ_LOGBOOK); // Copy the profile data. unsigned int length = 0; if (previous > address) { length = previous - address; memcpy (buffer + SZ_LOGBOOK, data + address, length); } else { unsigned int len_a = RB_PROFILE_END - address; unsigned int len_b = previous - RB_PROFILE_BEGIN; length = len_a + len_b; memcpy (buffer + SZ_LOGBOOK, data + address, len_a); memcpy (buffer + SZ_LOGBOOK + len_a, data + RB_PROFILE_BEGIN, len_b); } if (callback && !callback (buffer, length + SZ_LOGBOOK, buffer, SZ_LOGBOOK, userdata)) { break; } previous = address; } free (buffer); return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/diverite_nitekq.c
/* * libdivecomputer * * Copyright (C) 2010 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcpy, memcmp #include <stdlib.h> // malloc, free #include <assert.h> // assert #include "mares_iconhd.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "array.h" #include "rbstream.h" #define C_ARRAY_SIZE(array) (sizeof (array) / sizeof *(array)) #define ISINSTANCE(device) dc_device_isinstance((device), &mares_iconhd_device_vtable) #define MATRIX 0x0F #define SMART 0x000010 #define SMARTAPNEA 0x010010 #define ICONHD 0x14 #define ICONHDNET 0x15 #define PUCKPRO 0x18 #define NEMOWIDE2 0x19 #define PUCK2 0x1F #define QUADAIR 0x23 #define QUAD 0x29 #define ACK 0xAA #define EOF 0xEA #define AIR 0 #define GAUGE 1 #define NITROX 2 #define FREEDIVE 3 typedef struct mares_iconhd_layout_t { unsigned int memsize; unsigned int rb_profile_begin; unsigned int rb_profile_end; } mares_iconhd_layout_t; typedef struct mares_iconhd_model_t { unsigned char name[16 + 1]; unsigned int id; } mares_iconhd_model_t; typedef struct mares_iconhd_device_t { dc_device_t base; dc_iostream_t *iostream; const mares_iconhd_layout_t *layout; unsigned char fingerprint[10]; unsigned char version[140]; unsigned int model; unsigned int packetsize; } mares_iconhd_device_t; static dc_status_t mares_iconhd_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t mares_iconhd_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size); static dc_status_t mares_iconhd_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t mares_iconhd_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t mares_iconhd_device_close (dc_device_t *abstract); static const dc_device_vtable_t mares_iconhd_device_vtable = { sizeof(mares_iconhd_device_t), DC_FAMILY_MARES_ICONHD, mares_iconhd_device_set_fingerprint, /* set_fingerprint */ mares_iconhd_device_read, /* read */ NULL, /* write */ mares_iconhd_device_dump, /* dump */ mares_iconhd_device_foreach, /* foreach */ NULL, /* timesync */ mares_iconhd_device_close /* close */ }; static const mares_iconhd_layout_t mares_iconhd_layout = { 0x100000, /* memsize */ 0x00A000, /* rb_profile_begin */ 0x100000, /* rb_profile_end */ }; static const mares_iconhd_layout_t mares_iconhdnet_layout = { 0x100000, /* memsize */ 0x00E000, /* rb_profile_begin */ 0x100000, /* rb_profile_end */ }; static const mares_iconhd_layout_t mares_matrix_layout = { 0x40000, /* memsize */ 0x0A000, /* rb_profile_begin */ 0x3E000, /* rb_profile_end */ }; static const mares_iconhd_layout_t mares_nemowide2_layout = { 0x40000, /* memsize */ 0x0A000, /* rb_profile_begin */ 0x40000, /* rb_profile_end */ }; static unsigned int mares_iconhd_get_model (mares_iconhd_device_t *device) { const mares_iconhd_model_t models[] = { {"Matrix", MATRIX}, {"Smart", SMART}, {"Smart Apnea", SMARTAPNEA}, {"Icon HD", ICONHD}, {"Icon AIR", ICONHDNET}, {"Puck Pro", PUCKPRO}, {"Nemo Wide 2", NEMOWIDE2}, {"Puck 2", PUCK2}, {"Quad Air", QUADAIR}, {"Quad", QUAD}, }; // Check the product name in the version packet against the list // with valid names, and return the corresponding model number. unsigned int model = 0; for (unsigned int i = 0; i < C_ARRAY_SIZE(models); ++i) { if (memcmp (device->version + 0x46, models[i].name, sizeof (models[i].name) - 1) == 0) { model = models[i].id; break; } } return model; } static dc_status_t mares_iconhd_transfer (mares_iconhd_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; assert (csize >= 2); if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; // Send the command header to the dive computer. status = dc_iostream_write (device->iostream, command, 2, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Receive the header byte. unsigned char header[1] = {0}; status = dc_iostream_read (device->iostream, header, sizeof (header), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Verify the header byte. if (header[0] != ACK) { ERROR (abstract->context, "Unexpected answer byte."); return DC_STATUS_PROTOCOL; } // Send the command payload to the dive computer. if (csize > 2) { status = dc_iostream_write (device->iostream, command + 2, csize - 2, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } } // Read the packet. status = dc_iostream_read (device->iostream, answer, asize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Receive the trailer byte. unsigned char trailer[1] = {0}; status = dc_iostream_read (device->iostream, trailer, sizeof (trailer), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Verify the trailer byte. if (trailer[0] != EOF) { ERROR (abstract->context, "Unexpected answer byte."); return DC_STATUS_PROTOCOL; } return DC_STATUS_SUCCESS; } dc_status_t mares_iconhd_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; mares_iconhd_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (mares_iconhd_device_t *) dc_device_allocate (context, &mares_iconhd_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; device->layout = NULL; memset (device->fingerprint, 0, sizeof (device->fingerprint)); memset (device->version, 0, sizeof (device->version)); device->model = 0; device->packetsize = 0; // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (115200 8E1). status = dc_iostream_configure (device->iostream, 115200, 8, DC_PARITY_EVEN, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (1000 ms). status = dc_iostream_set_timeout (device->iostream, 1000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Clear the DTR line. status = dc_iostream_set_dtr (device->iostream, 0); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to clear the DTR line."); goto error_close; } // Clear the RTS line. status = dc_iostream_set_rts (device->iostream, 0); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to clear the RTS line."); goto error_close; } // Make sure everything is in a sane state. dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); // Send the version command. unsigned char command[] = {0xC2, 0x67}; status = mares_iconhd_transfer (device, command, sizeof (command), device->version, sizeof (device->version)); if (status != DC_STATUS_SUCCESS) { goto error_close; } // Autodetect the model using the version packet. device->model = mares_iconhd_get_model (device); // Load the correct memory layout. switch (device->model) { case MATRIX: device->layout = &mares_matrix_layout; device->packetsize = 256; break; case PUCKPRO: case PUCK2: case NEMOWIDE2: case SMART: case SMARTAPNEA: case QUAD: device->layout = &mares_nemowide2_layout; device->packetsize = 256; break; case QUADAIR: device->layout = &mares_iconhdnet_layout; device->packetsize = 256; break; case ICONHDNET: device->layout = &mares_iconhdnet_layout; device->packetsize = 4096; break; case ICONHD: default: device->layout = &mares_iconhd_layout; device->packetsize = 4096; break; } *out = (dc_device_t *) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t mares_iconhd_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; mares_iconhd_device_t *device = (mares_iconhd_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t mares_iconhd_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { mares_iconhd_device_t *device = (mares_iconhd_device_t *) abstract; if (size && size != sizeof (device->fingerprint)) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, sizeof (device->fingerprint)); else memset (device->fingerprint, 0, sizeof (device->fingerprint)); return DC_STATUS_SUCCESS; } static dc_status_t mares_iconhd_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size) { dc_status_t rc = DC_STATUS_SUCCESS; mares_iconhd_device_t *device = (mares_iconhd_device_t *) abstract; unsigned int nbytes = 0; while (nbytes < size) { // Calculate the packet size. unsigned int len = size - nbytes; if (len > device->packetsize) len = device->packetsize; // Read the packet. unsigned char command[] = {0xE7, 0x42, (address ) & 0xFF, (address >> 8) & 0xFF, (address >> 16) & 0xFF, (address >> 24) & 0xFF, (len ) & 0xFF, (len >> 8) & 0xFF, (len >> 16) & 0xFF, (len >> 24) & 0xFF}; rc = mares_iconhd_transfer (device, command, sizeof (command), data, len); if (rc != DC_STATUS_SUCCESS) return rc; nbytes += len; address += len; data += len; } return rc; } static dc_status_t mares_iconhd_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { mares_iconhd_device_t *device = (mares_iconhd_device_t *) abstract; // Allocate the required amount of memory. if (!dc_buffer_resize (buffer, device->layout->memsize)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Emit a vendor event. dc_event_vendor_t vendor; vendor.data = device->version; vendor.size = sizeof (device->version); device_event_emit (abstract, DC_EVENT_VENDOR, &vendor); return device_dump_read (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), device->packetsize); } static dc_status_t mares_iconhd_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { dc_status_t rc = DC_STATUS_SUCCESS; mares_iconhd_device_t *device = (mares_iconhd_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; const mares_iconhd_layout_t *layout = device->layout; // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = layout->rb_profile_end - layout->rb_profile_begin + 4; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Emit a vendor event. dc_event_vendor_t vendor; vendor.data = device->version; vendor.size = sizeof (device->version); device_event_emit (abstract, DC_EVENT_VENDOR, &vendor); // Read the serial number. unsigned char serial[4] = {0}; rc = mares_iconhd_device_read (abstract, 0x0C, serial, sizeof (serial)); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the memory."); return rc; } // Update and emit a progress event. progress.current += sizeof (serial); device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Emit a device info event. dc_event_devinfo_t devinfo; devinfo.model = device->model; devinfo.firmware = 0; devinfo.serial = array_uint32_le (serial); device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); // Get the model code. unsigned int model = device->model; // Get the corresponding dive header size. unsigned int header = 0x5C; if (model == ICONHDNET) header = 0x80; else if (model == QUADAIR) header = 0x84; else if (model == SMART) header = 4; // Type and number of samples only! else if (model == SMARTAPNEA) header = 6; // Type and number of samples only! // Get the end of the profile ring buffer. unsigned int eop = 0; const unsigned int config[] = {0x2001, 0x3001}; for (unsigned int i = 0; i < sizeof (config) / sizeof (*config); ++i) { // Read the pointer. unsigned char pointer[4] = {0}; rc = mares_iconhd_device_read (abstract, config[i], pointer, sizeof (pointer)); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the memory."); return rc; } // Update and emit a progress event. progress.maximum += sizeof (pointer); progress.current += sizeof (pointer); device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); eop = array_uint32_le (pointer); if (eop != 0xFFFFFFFF) break; } if (eop < layout->rb_profile_begin || eop >= layout->rb_profile_end) { if (eop == 0xFFFFFFFF) return DC_STATUS_SUCCESS; // No dives available. ERROR (abstract->context, "Ringbuffer pointer out of range (0x%08x).", eop); return DC_STATUS_DATAFORMAT; } // Create the ringbuffer stream. dc_rbstream_t *rbstream = NULL; rc = dc_rbstream_new (&rbstream, abstract, 1, device->packetsize, layout->rb_profile_begin, layout->rb_profile_end, eop); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to create the ringbuffer stream."); return rc; } // Allocate memory for the dives. unsigned char *buffer = (unsigned char *) malloc (layout->rb_profile_end - layout->rb_profile_begin); if (buffer == NULL) { ERROR (abstract->context, "Failed to allocate memory."); dc_rbstream_free (rbstream); return DC_STATUS_NOMEMORY; } unsigned int offset = layout->rb_profile_end - layout->rb_profile_begin; while (offset >= header + 4) { // Read the first part of the dive header. rc = dc_rbstream_read (rbstream, &progress, buffer + offset - header, header); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the dive."); dc_rbstream_free (rbstream); free (buffer); return rc; } // Get the number of samples in the profile data. unsigned int type = 0, nsamples = 0; if (model == SMART || model == SMARTAPNEA) { type = array_uint16_le (buffer + offset - header + 2); nsamples = array_uint16_le (buffer + offset - header + 0); } else { type = array_uint16_le (buffer + offset - header + 0); nsamples = array_uint16_le (buffer + offset - header + 2); } if (nsamples == 0xFFFF || type == 0xFFFF) break; // Get the dive mode. unsigned int mode = type & 0x03; // Get the header/sample size and fingerprint offset. unsigned int headersize = 0x5C; unsigned int samplesize = 8; unsigned int fingerprint = 6; if (model == ICONHDNET) { headersize = 0x80; samplesize = 12; } else if (model == QUADAIR) { headersize = 0x84; samplesize = 12; } else if (model == SMART) { if (mode == FREEDIVE) { headersize = 0x2E; samplesize = 6; fingerprint = 0x20; } else { headersize = 0x5C; samplesize = 8; fingerprint = 2; } } else if (model == SMARTAPNEA) { headersize = 0x50; samplesize = 14; fingerprint = 0x40; } if (offset < headersize) break; // Read the second part of the dive header. rc = dc_rbstream_read (rbstream, &progress, buffer + offset - headersize, headersize - header); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the dive."); dc_rbstream_free (rbstream); free (buffer); return rc; } // Calculate the total number of bytes for this dive. // If the buffer does not contain that much bytes, we reached the // end of the ringbuffer. The current dive is incomplete (partially // overwritten with newer data), and processing should stop. unsigned int nbytes = 4 + headersize + nsamples * samplesize; if (model == ICONHDNET || model == QUADAIR) { nbytes += (nsamples / 4) * 8; } else if (model == SMARTAPNEA) { unsigned int settings = array_uint16_le (buffer + offset - headersize + 0x1C); unsigned int divetime = array_uint32_le (buffer + offset - headersize + 0x24); unsigned int samplerate = 1 << ((settings >> 9) & 0x03); nbytes += divetime * samplerate * 2; } if (offset < nbytes) break; // Read the remainder of the dive. rc = dc_rbstream_read (rbstream, &progress, buffer + offset - nbytes, nbytes - headersize); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the dive."); dc_rbstream_free (rbstream); free (buffer); return rc; } // Move to the start of the dive. offset -= nbytes; // Verify that the length that is stored in the profile data // equals the calculated length. If both values are different, // we assume we reached the last dive. unsigned int length = array_uint32_le (buffer + offset); if (length != nbytes) break; unsigned char *fp = buffer + offset + length - headersize + fingerprint; if (memcmp (fp, device->fingerprint, sizeof (device->fingerprint)) == 0) { break; } if (callback && !callback (buffer + offset, length, fp, sizeof (device->fingerprint), userdata)) { break; } } dc_rbstream_free (rbstream); free (buffer); return rc; }
libdc-for-dirk-Subsurface-branch
src/mares_iconhd.c
/* * libdivecomputer * * Copyright (C) 2009 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> // malloc #include <string.h> // memcmp, memcpy #include <assert.h> // assert #include "context-private.h" #include "suunto_common2.h" #include "ringbuffer.h" #include "rbstream.h" #include "checksum.h" #include "array.h" #define MAXRETRIES 2 #define SZ_VERSION 0x04 #define SZ_PACKET 0x78 #define SZ_MINIMUM 8 #define RB_PROFILE_DISTANCE(l,a,b,m) ringbuffer_distance (a, b, m, l->rb_profile_begin, l->rb_profile_end) #define VTABLE(abstract) ((const suunto_common2_device_vtable_t *) abstract->vtable) void suunto_common2_device_init (suunto_common2_device_t *device) { assert (device != NULL); // Set the default values. device->layout = NULL; memset (device->version, 0, sizeof (device->version)); memset (device->fingerprint, 0, sizeof (device->fingerprint)); } static dc_status_t suunto_common2_transfer (dc_device_t *abstract, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize, unsigned int size) { assert (asize >= size + 4); if (VTABLE (abstract)->packet == NULL) return DC_STATUS_UNSUPPORTED; // Occasionally, the dive computer does not respond to a command. // In that case we retry the command a number of times before // returning an error. Usually the dive computer will respond // again during one of the retries. unsigned int nretries = 0; dc_status_t rc = DC_STATUS_SUCCESS; while ((rc = VTABLE (abstract)->packet (abstract, command, csize, answer, asize, size)) != DC_STATUS_SUCCESS) { // Automatically discard a corrupted packet, // and request a new one. if (rc != DC_STATUS_TIMEOUT && rc != DC_STATUS_PROTOCOL) return rc; // Abort if the maximum number of retries is reached. if (nretries++ >= MAXRETRIES) return rc; } return rc; } dc_status_t suunto_common2_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { suunto_common2_device_t *device = (suunto_common2_device_t*) abstract; if (size && size != sizeof (device->fingerprint)) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, sizeof (device->fingerprint)); else memset (device->fingerprint, 0, sizeof (device->fingerprint)); return DC_STATUS_SUCCESS; } dc_status_t suunto_common2_device_version (dc_device_t *abstract, unsigned char data[], unsigned int size) { if (size < SZ_VERSION) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_INVALIDARGS; } unsigned char answer[SZ_VERSION + 4] = {0}; unsigned char command[4] = {0x0F, 0x00, 0x00, 0x0F}; dc_status_t rc = suunto_common2_transfer (abstract, command, sizeof (command), answer, sizeof (answer), 4); if (rc != DC_STATUS_SUCCESS) return rc; memcpy (data, answer + 3, SZ_VERSION); return DC_STATUS_SUCCESS; } dc_status_t suunto_common2_device_reset_maxdepth (dc_device_t *abstract) { unsigned char answer[4] = {0}; unsigned char command[4] = {0x20, 0x00, 0x00, 0x20}; dc_status_t rc = suunto_common2_transfer (abstract, command, sizeof (command), answer, sizeof (answer), 0); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; } dc_status_t suunto_common2_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size) { unsigned int nbytes = 0; while (nbytes < size) { // Calculate the package size. unsigned int len = size - nbytes; if (len > SZ_PACKET) len = SZ_PACKET; // Read the package. unsigned char answer[SZ_PACKET + 7] = {0}; unsigned char command[7] = {0x05, 0x00, 0x03, (address >> 8) & 0xFF, // high (address ) & 0xFF, // low len, // count 0}; // CRC command[6] = checksum_xor_uint8 (command, 6, 0x00); dc_status_t rc = suunto_common2_transfer (abstract, command, sizeof (command), answer, len + 7, len); if (rc != DC_STATUS_SUCCESS) return rc; memcpy (data, answer + 6, len); nbytes += len; address += len; data += len; } return DC_STATUS_SUCCESS; } dc_status_t suunto_common2_device_write (dc_device_t *abstract, unsigned int address, const unsigned char data[], unsigned int size) { unsigned int nbytes = 0; while (nbytes < size) { // Calculate the package size. unsigned int len = size - nbytes; if (len > SZ_PACKET) len = SZ_PACKET; // Write the package. unsigned char answer[7] = {0}; unsigned char command[SZ_PACKET + 7] = {0x06, 0x00, len + 3, (address >> 8) & 0xFF, // high (address ) & 0xFF, // low len, // count 0}; // data + CRC memcpy (command + 6, data, len); command[len + 6] = checksum_xor_uint8 (command, len + 6, 0x00); dc_status_t rc = suunto_common2_transfer (abstract, command, len + 7, answer, sizeof (answer), 0); if (rc != DC_STATUS_SUCCESS) return rc; nbytes += len; address += len; data += len; } return DC_STATUS_SUCCESS; } dc_status_t suunto_common2_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { suunto_common2_device_t *device = (suunto_common2_device_t *) abstract; assert (device != NULL); assert (device->layout != NULL); // Erase the current contents of the buffer and // allocate the required amount of memory. if (!dc_buffer_clear (buffer) || !dc_buffer_resize (buffer, device->layout->memsize)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Emit a vendor event. dc_event_vendor_t vendor; vendor.data = device->version; vendor.size = sizeof (device->version); device_event_emit (abstract, DC_EVENT_VENDOR, &vendor); return device_dump_read (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), SZ_PACKET); } dc_status_t suunto_common2_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { suunto_common2_device_t *device = (suunto_common2_device_t*) abstract; assert (device != NULL); assert (device->layout != NULL); const suunto_common2_layout_t *layout = device->layout; // Error status for delayed errors. dc_status_t status = DC_STATUS_SUCCESS; // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = layout->rb_profile_end - layout->rb_profile_begin + 8 + (SZ_MINIMUM > 4 ? SZ_MINIMUM : 4); device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Emit a vendor event. dc_event_vendor_t vendor; vendor.data = device->version; vendor.size = sizeof (device->version); device_event_emit (abstract, DC_EVENT_VENDOR, &vendor); // Read the serial number. unsigned char serial[SZ_MINIMUM > 4 ? SZ_MINIMUM : 4] = {0}; dc_status_t rc = suunto_common2_device_read (abstract, layout->serial, serial, sizeof (serial)); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the memory header."); return rc; } // Update and emit a progress event. progress.current += sizeof (serial); device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Emit a device info event. dc_event_devinfo_t devinfo; devinfo.model = device->version[0]; devinfo.firmware = array_uint24_be (device->version + 1); devinfo.serial = 0; for (unsigned int i = 0; i < 4; ++i) { devinfo.serial *= 100; devinfo.serial += serial[i]; } device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); // Read the header bytes. unsigned char header[8] = {0}; rc = suunto_common2_device_read (abstract, 0x0190, header, sizeof (header)); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the memory header."); return rc; } // Obtain the pointers from the header. unsigned int last = array_uint16_le (header + 0); unsigned int count = array_uint16_le (header + 2); unsigned int end = array_uint16_le (header + 4); unsigned int begin = array_uint16_le (header + 6); if (last < layout->rb_profile_begin || last >= layout->rb_profile_end || end < layout->rb_profile_begin || end >= layout->rb_profile_end || begin < layout->rb_profile_begin || begin >= layout->rb_profile_end) { ERROR (abstract->context, "Invalid ringbuffer pointer detected (0x%04x 0x%04x 0x%04x %u).", begin, last, end, count); return DC_STATUS_DATAFORMAT; } // Calculate the total amount of bytes. unsigned int remaining = RB_PROFILE_DISTANCE (layout, begin, end, count != 0); // Update and emit a progress event. progress.maximum -= (layout->rb_profile_end - layout->rb_profile_begin) - remaining; progress.current += sizeof (header); device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Create the ringbuffer stream. dc_rbstream_t *rbstream = NULL; rc = dc_rbstream_new (&rbstream, abstract, 1, SZ_PACKET, layout->rb_profile_begin, layout->rb_profile_end, end); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to create the ringbuffer stream."); return rc; } // Memory buffer to store all the dives. unsigned char *data = (unsigned char *) malloc (layout->rb_profile_end - layout->rb_profile_begin); if (data == NULL) { ERROR (abstract->context, "Failed to allocate memory."); dc_rbstream_free (rbstream); return DC_STATUS_NOMEMORY; } // The ring buffer is traversed backwards to retrieve the most recent // dives first. This allows us to download only the new dives. unsigned int current = last; unsigned int previous = end; unsigned int offset = remaining; while (offset) { // Calculate the size of the current dive. unsigned int size = RB_PROFILE_DISTANCE (layout, current, previous, 1); if (size < 4 || size > offset) { ERROR (abstract->context, "Unexpected profile size (%u %u).", size, offset); dc_rbstream_free (rbstream); free (data); return DC_STATUS_DATAFORMAT; } // Move to the begin of the current dive. offset -= size; // Read the dive. rc = dc_rbstream_read (rbstream, &progress, data + offset, size); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the dive."); dc_rbstream_free (rbstream); free (data); return rc; } unsigned char *p = data + offset; unsigned int prev = array_uint16_le (p + 0); unsigned int next = array_uint16_le (p + 2); if (prev < layout->rb_profile_begin || prev >= layout->rb_profile_end || next < layout->rb_profile_begin || next >= layout->rb_profile_end) { ERROR (abstract->context, "Invalid ringbuffer pointer detected (0x%04x 0x%04x).", prev, next); dc_rbstream_free (rbstream); free (data); return DC_STATUS_DATAFORMAT; } if (next != previous && next != current) { ERROR (abstract->context, "Profiles are not continuous (0x%04x 0x%04x 0x%04x).", current, next, previous); dc_rbstream_free (rbstream); free (data); return DC_STATUS_DATAFORMAT; } if (next != current) { unsigned int fp_offset = layout->fingerprint + 4; if (memcmp (p + fp_offset, device->fingerprint, sizeof (device->fingerprint)) == 0) { dc_rbstream_free (rbstream); free (data); return DC_STATUS_SUCCESS; } if (callback && !callback (p + 4, size - 4, p + fp_offset, sizeof (device->fingerprint), userdata)) { dc_rbstream_free (rbstream); free (data); return DC_STATUS_SUCCESS; } } else { ERROR (abstract->context, "Skipping incomplete dive (0x%04x 0x%04x 0x%04x).", current, next, previous); status = DC_STATUS_DATAFORMAT; } // Next dive. previous = current; current = prev; } dc_rbstream_free (rbstream); free (data); return status; }
libdc-for-dirk-Subsurface-branch
src/suunto_common2.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcpy #include <stdlib.h> // malloc, free #include "oceanic_atom2.h" #include "oceanic_common.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "array.h" #include "ringbuffer.h" #include "checksum.h" #define ISINSTANCE(device) dc_device_isinstance((device), &oceanic_atom2_device_vtable.base) #define VTX 0x4557 #define I750TC 0x455A #define MAXRETRIES 2 #define MAXDELAY 16 #define INVALID 0xFFFFFFFF #define CMD_INIT 0xA8 #define CMD_VERSION 0x84 #define CMD_READ1 0xB1 #define CMD_READ8 0xB4 #define CMD_READ16 0xB8 #define CMD_WRITE 0xB2 #define CMD_KEEPALIVE 0x91 #define CMD_QUIT 0x6A #define ACK 0x5A #define NAK 0xA5 typedef struct oceanic_atom2_device_t { oceanic_common_device_t base; dc_iostream_t *iostream; unsigned int delay; unsigned int bigpage; unsigned char cache[256]; unsigned int cached; } oceanic_atom2_device_t; static dc_status_t oceanic_atom2_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size); static dc_status_t oceanic_atom2_device_write (dc_device_t *abstract, unsigned int address, const unsigned char data[], unsigned int size); static dc_status_t oceanic_atom2_device_close (dc_device_t *abstract); static const oceanic_common_device_vtable_t oceanic_atom2_device_vtable = { { sizeof(oceanic_atom2_device_t), DC_FAMILY_OCEANIC_ATOM2, oceanic_common_device_set_fingerprint, /* set_fingerprint */ oceanic_atom2_device_read, /* read */ oceanic_atom2_device_write, /* write */ oceanic_common_device_dump, /* dump */ oceanic_common_device_foreach, /* foreach */ NULL, /* timesync */ oceanic_atom2_device_close /* close */ }, oceanic_common_device_logbook, oceanic_common_device_profile, }; static const oceanic_common_version_t aeris_f10_version[] = { {"FREEWAER \0\0 512K"}, {"OCEANF10 \0\0 512K"}, {"MUNDIAL R\0\0 512K"}, }; static const oceanic_common_version_t aeris_f11_version[] = { {"AERISF11 \0\0 1024"}, {"OCEANF11 \0\0 1024"}, }; static const oceanic_common_version_t oceanic_atom1_version[] = { {"ATOM rev\0\0 256K"}, }; static const oceanic_common_version_t oceanic_atom2_version[] = { {"2M ATOM r\0\0 512K"}, }; static const oceanic_common_version_t oceanic_atom2a_version[] = { {"MANTA R\0\0 512K"}, {"INSIGHT2 \0\0 512K"}, {"OCEVEO30 \0\0 512K"}, {"ATMOSAI R\0\0 512K"}, {"PROPLUS2 \0\0 512K"}, {"OCEGEO20 \0\0 512K"}, {"OCE GEO R\0\0 512K"}, {"AQUAI200 \0\0 512K"}, }; static const oceanic_common_version_t oceanic_atom2b_version[] = { {"ELEMENT2 \0\0 512K"}, {"OCEVEO20 \0\0 512K"}, {"TUSAZEN \0\0 512K"}, {"AQUAI300 \0\0 512K"}, {"HOLLDG03 \0\0 512K"}, }; static const oceanic_common_version_t oceanic_atom2c_version[] = { {"2M EPIC r\0\0 512K"}, {"EPIC1 R\0\0 512K"}, {"AERIA300 \0\0 512K"}, }; static const oceanic_common_version_t oceanic_default_version[] = { {"OCE VT3 R\0\0 512K"}, {"ELITET3 R\0\0 512K"}, {"ELITET31 \0\0 512K"}, {"DATAMASK \0\0 512K"}, {"COMPMASK \0\0 512K"}, }; static const oceanic_common_version_t sherwood_wisdom_version[] = { {"WISDOM R\0\0 512K"}, }; static const oceanic_common_version_t oceanic_proplus3_version[] = { {"PROPLUS3 \0\0 512K"}, }; static const oceanic_common_version_t tusa_zenair_version[] = { {"TUZENAIR \0\0 512K"}, {"AMPHOSSW \0\0 512K"}, {"AMPHOAIR \0\0 512K"}, {"VOYAGE2G \0\0 512K"}, }; static const oceanic_common_version_t oceanic_oc1_version[] = { {"OCWATCH R\0\0 1024"}, {"OC1WATCH \0\0 1024"}, {"OCSWATCH \0\0 1024"}, {"AQUAI550 \0\0 1024"}, }; static const oceanic_common_version_t oceanic_oci_version[] = { {"OCEANOCI \0\0 1024"}, }; static const oceanic_common_version_t oceanic_atom3_version[] = { {"OCEATOM3 \0\0 1024"}, {"ATOM31 \0\0 1024"}, }; static const oceanic_common_version_t oceanic_vt4_version[] = { {"OCEANVT4 \0\0 1024"}, {"OCEAVT41 \0\0 1024"}, {"AERISAIR \0\0 1024"}, {"SWVISION \0\0 1024"}, {"XPSUBAIR \0\0 1024"}, }; static const oceanic_common_version_t hollis_tx1_version[] = { {"HOLLDG04 \0\0 2048"}, }; static const oceanic_common_version_t oceanic_veo1_version[] = { {"OCEVEO10 \0\0 8K"}, {"AERIS XR1 NX R\0\0"}, }; static const oceanic_common_version_t oceanic_reactpro_version[] = { {"REACPRO2 \0\0 512K"}, }; static const oceanic_common_version_t aeris_a300cs_version[] = { {"AER300CS \0\0 2048"}, {"OCEANVTX \0\0 2048"}, {"AQUAI750 \0\0 2048"}, }; static const oceanic_common_version_t aqualung_i450t_version[] = { {"AQUAI450 \0\0 2048"}, }; static const oceanic_common_layout_t aeris_f10_layout = { 0x10000, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x0100, /* rb_logbook_begin */ 0x0D80, /* rb_logbook_end */ 32, /* rb_logbook_entry_size */ 0x0D80, /* rb_profile_begin */ 0x10000, /* rb_profile_end */ 0, /* pt_mode_global */ 2, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static const oceanic_common_layout_t aeris_f11_layout = { 0x20000, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x0100, /* rb_logbook_begin */ 0x0D80, /* rb_logbook_end */ 32, /* rb_logbook_entry_size */ 0x0D80, /* rb_profile_begin */ 0x20000, /* rb_profile_end */ 0, /* pt_mode_global */ 3, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static const oceanic_common_layout_t oceanic_default_layout = { 0x10000, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x0240, /* rb_logbook_begin */ 0x0A40, /* rb_logbook_end */ 8, /* rb_logbook_entry_size */ 0x0A40, /* rb_profile_begin */ 0x10000, /* rb_profile_end */ 0, /* pt_mode_global */ 0, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static const oceanic_common_layout_t oceanic_atom1_layout = { 0x8000, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x0240, /* rb_logbook_begin */ 0x0440, /* rb_logbook_end */ 8, /* rb_logbook_entry_size */ 0x0440, /* rb_profile_begin */ 0x8000, /* rb_profile_end */ 0, /* pt_mode_global */ 0, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static const oceanic_common_layout_t oceanic_atom2a_layout = { 0xFFF0, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x0240, /* rb_logbook_begin */ 0x0A40, /* rb_logbook_end */ 8, /* rb_logbook_entry_size */ 0x0A40, /* rb_profile_begin */ 0xFE00, /* rb_profile_end */ 0, /* pt_mode_global */ 0, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static const oceanic_common_layout_t oceanic_atom2b_layout = { 0x10000, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x0240, /* rb_logbook_begin */ 0x0A40, /* rb_logbook_end */ 8, /* rb_logbook_entry_size */ 0x0A40, /* rb_profile_begin */ 0xFE00, /* rb_profile_end */ 0, /* pt_mode_global */ 0, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static const oceanic_common_layout_t oceanic_atom2c_layout = { 0xFFF0, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x0240, /* rb_logbook_begin */ 0x0A40, /* rb_logbook_end */ 8, /* rb_logbook_entry_size */ 0x0A40, /* rb_profile_begin */ 0xFFF0, /* rb_profile_end */ 0, /* pt_mode_global */ 0, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static const oceanic_common_layout_t sherwood_wisdom_layout = { 0xFFF0, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x03D0, /* rb_logbook_begin */ 0x0A40, /* rb_logbook_end */ 8, /* rb_logbook_entry_size */ 0x0A40, /* rb_profile_begin */ 0xFE00, /* rb_profile_end */ 0, /* pt_mode_global */ 0, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static const oceanic_common_layout_t oceanic_proplus3_layout = { 0x10000, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x03E0, /* rb_logbook_begin */ 0x0A40, /* rb_logbook_end */ 8, /* rb_logbook_entry_size */ 0x0A40, /* rb_profile_begin */ 0xFE00, /* rb_profile_end */ 0, /* pt_mode_global */ 0, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static const oceanic_common_layout_t tusa_zenair_layout = { 0xFFF0, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x0240, /* rb_logbook_begin */ 0x0A40, /* rb_logbook_end */ 8, /* rb_logbook_entry_size */ 0x0A40, /* rb_profile_begin */ 0xFE00, /* rb_profile_end */ 0, /* pt_mode_global */ 1, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static const oceanic_common_layout_t oceanic_oc1_layout = { 0x20000, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x0240, /* rb_logbook_begin */ 0x0A40, /* rb_logbook_end */ 8, /* rb_logbook_entry_size */ 0x0A40, /* rb_profile_begin */ 0x1FE00, /* rb_profile_end */ 0, /* pt_mode_global */ 1, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static const oceanic_common_layout_t oceanic_oci_layout = { 0x20000, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x10C0, /* rb_logbook_begin */ 0x1400, /* rb_logbook_end */ 8, /* rb_logbook_entry_size */ 0x1400, /* rb_profile_begin */ 0x1FE00, /* rb_profile_end */ 0, /* pt_mode_global */ 1, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static const oceanic_common_layout_t oceanic_atom3_layout = { 0x20000, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x0400, /* rb_logbook_begin */ 0x0A40, /* rb_logbook_end */ 8, /* rb_logbook_entry_size */ 0x0A40, /* rb_profile_begin */ 0x1FE00, /* rb_profile_end */ 0, /* pt_mode_global */ 1, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static const oceanic_common_layout_t oceanic_vt4_layout = { 0x20000, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x0420, /* rb_logbook_begin */ 0x0A40, /* rb_logbook_end */ 8, /* rb_logbook_entry_size */ 0x0A40, /* rb_profile_begin */ 0x1FE00, /* rb_profile_end */ 0, /* pt_mode_global */ 1, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static const oceanic_common_layout_t hollis_tx1_layout = { 0x40000, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x0780, /* rb_logbook_begin */ 0x1000, /* rb_logbook_end */ 8, /* rb_logbook_entry_size */ 0x1000, /* rb_profile_begin */ 0x40000, /* rb_profile_end */ 0, /* pt_mode_global */ 1, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static const oceanic_common_layout_t oceanic_veo1_layout = { 0x0400, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x0400, /* rb_logbook_begin */ 0x0400, /* rb_logbook_end */ 8, /* rb_logbook_entry_size */ 0x0400, /* rb_profile_begin */ 0x0400, /* rb_profile_end */ 0, /* pt_mode_global */ 0, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static const oceanic_common_layout_t oceanic_reactpro_layout = { 0xFFF0, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x0400, /* rb_logbook_begin */ 0x0600, /* rb_logbook_end */ 8, /* rb_logbook_entry_size */ 0x0600, /* rb_profile_begin */ 0xFFF0, /* rb_profile_end */ 1, /* pt_mode_global */ 1, /* pt_mode_logbook */ 1, /* pt_mode_serial */ }; static const oceanic_common_layout_t aeris_a300cs_layout = { 0x40000, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x0900, /* rb_logbook_begin */ 0x1000, /* rb_logbook_end */ 16, /* rb_logbook_entry_size */ 0x1000, /* rb_profile_begin */ 0x3FE00, /* rb_profile_end */ 0, /* pt_mode_global */ 1, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static const oceanic_common_layout_t aqualung_i450t_layout = { 0x40000, /* memsize */ 0x0000, /* cf_devinfo */ 0x0040, /* cf_pointers */ 0x10C0, /* rb_logbook_begin */ 0x1400, /* rb_logbook_end */ 16, /* rb_logbook_entry_size */ 0x1400, /* rb_profile_begin */ 0x3FE00, /* rb_profile_end */ 0, /* pt_mode_global */ 1, /* pt_mode_logbook */ 0, /* pt_mode_serial */ }; static dc_status_t oceanic_atom2_packet (oceanic_atom2_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize, unsigned int crc_size) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; if (device->delay) { dc_iostream_sleep (device->iostream, device->delay); } // Send the command to the dive computer. status = dc_iostream_write (device->iostream, command, csize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Get the correct ACK byte. unsigned int ack = ACK; if (command[0] == CMD_INIT || command[0] == CMD_QUIT) { ack = NAK; } // Receive the response (ACK/NAK) of the dive computer. unsigned char response = 0; status = dc_iostream_read (device->iostream, &response, 1, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Verify the response of the dive computer. if (response != ack) { ERROR (abstract->context, "Unexpected answer start byte(s)."); return DC_STATUS_PROTOCOL; } if (asize) { // Receive the answer of the dive computer. status = dc_iostream_read (device->iostream, answer, asize, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Verify the checksum of the answer. unsigned short crc, ccrc; if (crc_size == 2) { crc = array_uint16_le (answer + asize - 2); ccrc = checksum_add_uint16 (answer, asize - 2, 0x0000); } else { crc = answer[asize - 1]; ccrc = checksum_add_uint8 (answer, asize - 1, 0x00); } if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } } return DC_STATUS_SUCCESS; } static dc_status_t oceanic_atom2_transfer (oceanic_atom2_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize, unsigned int crc_size) { // Send the command to the device. If the device responds with an // ACK byte, the command was received successfully and the answer // (if any) follows after the ACK byte. If the device responds with // a NAK byte, we try to resend the command a number of times before // returning an error. unsigned int nretries = 0; dc_status_t rc = DC_STATUS_SUCCESS; while ((rc = oceanic_atom2_packet (device, command, csize, answer, asize, crc_size)) != DC_STATUS_SUCCESS) { if (rc != DC_STATUS_TIMEOUT && rc != DC_STATUS_PROTOCOL) return rc; // Abort if the maximum number of retries is reached. if (nretries++ >= MAXRETRIES) return rc; // Increase the inter packet delay. if (device->delay < MAXDELAY) device->delay++; // Delay the next attempt. dc_iostream_sleep (device->iostream, 100); dc_iostream_purge (device->iostream, DC_DIRECTION_INPUT); } return DC_STATUS_SUCCESS; } static dc_status_t oceanic_atom2_quit (oceanic_atom2_device_t *device) { // Send the command to the dive computer. unsigned char command[4] = {CMD_QUIT, 0x05, 0xA5, 0x00}; dc_status_t rc = oceanic_atom2_transfer (device, command, sizeof (command), NULL, 0, 0); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; } dc_status_t oceanic_atom2_device_open (dc_device_t **out, dc_context_t *context, const char *name, unsigned int model) { dc_status_t status = DC_STATUS_SUCCESS; oceanic_atom2_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (oceanic_atom2_device_t *) dc_device_allocate (context, &oceanic_atom2_device_vtable.base); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Initialize the base class. oceanic_common_device_init (&device->base); // Set the default values. device->iostream = NULL; device->delay = 0; device->bigpage = 1; // no big pages device->cached = INVALID; memset(device->cache, 0, sizeof(device->cache)); // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Get the correct baudrate. unsigned int baudrate = 38400; if (model == VTX || model == I750TC) { baudrate = 115200; } // Set the serial communication protocol (38400 8N1). status = dc_iostream_configure (device->iostream, baudrate, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (1000 ms). status = dc_iostream_set_timeout (device->iostream, 1000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Give the interface 100 ms to settle and draw power up. dc_iostream_sleep (device->iostream, 100); // Set the DTR/RTS lines. status = dc_iostream_set_dtr(device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the DTR line."); return status; } status = dc_iostream_set_rts(device->iostream, 1); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the DTR line."); return status; } // Make sure everything is in a sane state. dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); // Switch the device from surface mode into download mode. Before sending // this command, the device needs to be in PC mode (automatically activated // by connecting the device), or already in download mode. status = oceanic_atom2_device_version ((dc_device_t *) device, device->base.version, sizeof (device->base.version)); if (status != DC_STATUS_SUCCESS) { goto error_close; } // Override the base class values. if (OCEANIC_COMMON_MATCH (device->base.version, aeris_f10_version)) { device->base.layout = &aeris_f10_layout; } else if (OCEANIC_COMMON_MATCH (device->base.version, aeris_f11_version)) { device->base.layout = &aeris_f11_layout; device->bigpage = 8; } else if (OCEANIC_COMMON_MATCH (device->base.version, oceanic_atom1_version)) { device->base.layout = &oceanic_atom1_layout; } else if (OCEANIC_COMMON_MATCH (device->base.version, oceanic_atom2_version)) { if (array_uint16_be (device->base.version + 0x09) >= 0x3349) { device->base.layout = &oceanic_atom2a_layout; } else { device->base.layout = &oceanic_atom2c_layout; } } else if (OCEANIC_COMMON_MATCH (device->base.version, oceanic_atom2a_version)) { device->base.layout = &oceanic_atom2a_layout; } else if (OCEANIC_COMMON_MATCH (device->base.version, oceanic_atom2b_version)) { device->base.layout = &oceanic_atom2b_layout; } else if (OCEANIC_COMMON_MATCH (device->base.version, oceanic_atom2c_version)) { device->base.layout = &oceanic_atom2c_layout; } else if (OCEANIC_COMMON_MATCH (device->base.version, sherwood_wisdom_version)) { device->base.layout = &sherwood_wisdom_layout; } else if (OCEANIC_COMMON_MATCH (device->base.version, oceanic_proplus3_version)) { device->base.layout = &oceanic_proplus3_layout; } else if (OCEANIC_COMMON_MATCH (device->base.version, tusa_zenair_version)) { device->base.layout = &tusa_zenair_layout; } else if (OCEANIC_COMMON_MATCH (device->base.version, oceanic_oc1_version)) { device->base.layout = &oceanic_oc1_layout; } else if (OCEANIC_COMMON_MATCH (device->base.version, oceanic_oci_version)) { device->base.layout = &oceanic_oci_layout; } else if (OCEANIC_COMMON_MATCH (device->base.version, oceanic_atom3_version)) { device->base.layout = &oceanic_atom3_layout; } else if (OCEANIC_COMMON_MATCH (device->base.version, oceanic_vt4_version)) { device->base.layout = &oceanic_vt4_layout; } else if (OCEANIC_COMMON_MATCH (device->base.version, hollis_tx1_version)) { device->base.layout = &hollis_tx1_layout; } else if (OCEANIC_COMMON_MATCH (device->base.version, oceanic_veo1_version)) { device->base.layout = &oceanic_veo1_layout; } else if (OCEANIC_COMMON_MATCH (device->base.version, oceanic_reactpro_version)) { device->base.layout = &oceanic_reactpro_layout; } else if (OCEANIC_COMMON_MATCH (device->base.version, aeris_a300cs_version)) { device->base.layout = &aeris_a300cs_layout; device->bigpage = 16; } else if (OCEANIC_COMMON_MATCH (device->base.version, aqualung_i450t_version)) { device->base.layout = &aqualung_i450t_layout; } else if (OCEANIC_COMMON_MATCH (device->base.version, oceanic_default_version)) { device->base.layout = &oceanic_default_layout; } else { WARNING (context, "Unsupported device detected!"); device->base.layout = &oceanic_default_layout; if (memcmp(device->base.version + 12, "256K", 4) == 0) { device->base.layout = &oceanic_atom1_layout; } else if (memcmp(device->base.version + 12, "512K", 4) == 0) { device->base.layout = &oceanic_default_layout; } else if (memcmp(device->base.version + 12, "1024", 4) == 0) { device->base.layout = &oceanic_oc1_layout; } else if (memcmp(device->base.version + 12, "2048", 4) == 0) { device->base.layout = &hollis_tx1_layout; } else { device->base.layout = &oceanic_default_layout; } } *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t oceanic_atom2_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; oceanic_atom2_device_t *device = (oceanic_atom2_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Send the quit command. rc = oceanic_atom2_quit (device); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } dc_status_t oceanic_atom2_device_keepalive (dc_device_t *abstract) { oceanic_atom2_device_t *device = (oceanic_atom2_device_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; // Send the command to the dive computer. unsigned char command[4] = {CMD_KEEPALIVE, 0x05, 0xA5, 0x00}; dc_status_t rc = oceanic_atom2_transfer (device, command, sizeof (command), NULL, 0, 0); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; } dc_status_t oceanic_atom2_device_version (dc_device_t *abstract, unsigned char data[], unsigned int size) { oceanic_atom2_device_t *device = (oceanic_atom2_device_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size < PAGESIZE) return DC_STATUS_INVALIDARGS; unsigned char answer[PAGESIZE + 1] = {0}; unsigned char command[2] = {CMD_VERSION, 0x00}; dc_status_t rc = oceanic_atom2_transfer (device, command, sizeof (command), answer, sizeof (answer), 1); if (rc != DC_STATUS_SUCCESS) return rc; memcpy (data, answer, PAGESIZE); return DC_STATUS_SUCCESS; } static dc_status_t oceanic_atom2_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size) { oceanic_atom2_device_t *device = (oceanic_atom2_device_t*) abstract; if ((address % PAGESIZE != 0) || (size % PAGESIZE != 0)) return DC_STATUS_INVALIDARGS; // Pick the correct read command and number of checksum bytes. unsigned char read_cmd = 0x00; unsigned int crc_size = 0; switch (device->bigpage) { case 1: read_cmd = CMD_READ1; crc_size = 1; break; case 8: read_cmd = CMD_READ8; crc_size = 1; break; case 16: read_cmd = CMD_READ16; crc_size = 2; break; default: return DC_STATUS_INVALIDARGS; } // Pick the best pagesize to use. unsigned int pagesize = device->bigpage * PAGESIZE; unsigned int nbytes = 0; while (nbytes < size) { unsigned int page = address / pagesize; if (page != device->cached) { // Read the package. unsigned int number = page * device->bigpage; // This is always PAGESIZE, even in big page mode. unsigned char answer[256 + 2] = {0}; // Maximum we support for the known commands. unsigned char command[4] = {read_cmd, (number >> 8) & 0xFF, // high (number ) & 0xFF, // low 0}; dc_status_t rc = oceanic_atom2_transfer (device, command, sizeof (command), answer, pagesize + crc_size, crc_size); if (rc != DC_STATUS_SUCCESS) return rc; // Cache the page. memcpy (device->cache, answer, pagesize); device->cached = page; } unsigned int offset = address % pagesize; unsigned int length = pagesize - offset; if (nbytes + length > size) length = size - nbytes; memcpy (data, device->cache + offset, length); nbytes += length; address += length; data += length; } return DC_STATUS_SUCCESS; } static dc_status_t oceanic_atom2_device_write (dc_device_t *abstract, unsigned int address, const unsigned char data[], unsigned int size) { oceanic_atom2_device_t *device = (oceanic_atom2_device_t*) abstract; if ((address % PAGESIZE != 0) || (size % PAGESIZE != 0)) return DC_STATUS_INVALIDARGS; // Invalidate the cache. device->cached = INVALID; unsigned int nbytes = 0; while (nbytes < size) { // Prepare to write the package. unsigned int number = address / PAGESIZE; unsigned char prepare[4] = {CMD_WRITE, (number >> 8) & 0xFF, // high (number ) & 0xFF, // low 0x00}; dc_status_t rc = oceanic_atom2_transfer (device, prepare, sizeof (prepare), NULL, 0, 0); if (rc != DC_STATUS_SUCCESS) return rc; // Write the package. unsigned char command[PAGESIZE + 2] = {0}; memcpy (command, data, PAGESIZE); command[PAGESIZE] = checksum_add_uint8 (command, PAGESIZE, 0x00); rc = oceanic_atom2_transfer (device, command, sizeof (command), NULL, 0, 0); if (rc != DC_STATUS_SUCCESS) return rc; nbytes += PAGESIZE; address += PAGESIZE; data += PAGESIZE; } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/oceanic_atom2.c
/* * libdivecomputer * * Copyright (C) 2009 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcpy, memmove #include <stdlib.h> // malloc, free #include <assert.h> // assert #include "oceanic_common.h" #include "context-private.h" #include "device-private.h" #include "ringbuffer.h" #include "rbstream.h" #include "array.h" #define VTABLE(abstract) ((const oceanic_common_device_vtable_t *) abstract->vtable) #define RB_LOGBOOK_DISTANCE(a,b,l) ringbuffer_distance (a, b, 1, l->rb_logbook_begin, l->rb_logbook_end) #define RB_LOGBOOK_INCR(a,b,l) ringbuffer_increment (a, b, l->rb_logbook_begin, l->rb_logbook_end) #define RB_PROFILE_DISTANCE(a,b,l) ringbuffer_distance (a, b, 0, l->rb_profile_begin, l->rb_profile_end) #define RB_PROFILE_INCR(a,b,l) ringbuffer_increment (a, b, l->rb_profile_begin, l->rb_profile_end) #define INVALID 0 static unsigned int get_profile_first (const unsigned char data[], const oceanic_common_layout_t *layout) { unsigned int value; if (layout->pt_mode_logbook == 0) { value = array_uint16_le (data + 5); } else if (layout->pt_mode_logbook == 1) { value = array_uint16_le (data + 4); } else if (layout->pt_mode_logbook == 3) { value = array_uint16_le (data + 16); } else { return array_uint16_le (data + 16); } if (layout->memsize > 0x20000) return (value & 0x3FFF) * PAGESIZE; else if (layout->memsize > 0x10000) return (value & 0x1FFF) * PAGESIZE; else return (value & 0x0FFF) * PAGESIZE; } static unsigned int get_profile_last (const unsigned char data[], const oceanic_common_layout_t *layout) { unsigned int value; if (layout->pt_mode_logbook == 0) { value = array_uint16_le (data + 6) >> 4; } else if (layout->pt_mode_logbook == 1) { value = array_uint16_le (data + 6); } else if (layout->pt_mode_logbook == 3) { value = array_uint16_le (data + 18); } else { return array_uint16_le(data + 18); } if (layout->memsize > 0x20000) return (value & 0x3FFF) * PAGESIZE; else if (layout->memsize > 0x10000) return (value & 0x1FFF) * PAGESIZE; else return (value & 0x0FFF) * PAGESIZE; } static int oceanic_common_match_pattern (const unsigned char *string, const unsigned char *pattern) { for (unsigned int i = 0; i < PAGESIZE; ++i, ++pattern, ++string) { if (*pattern != '\0' && *pattern != *string) return 0; } return 1; } int oceanic_common_match (const unsigned char *version, const oceanic_common_version_t patterns[], unsigned int n) { for (unsigned int i = 0; i < n; ++i) { if (oceanic_common_match_pattern (version, patterns[i])) return 1; } return 0; } void oceanic_common_device_init (oceanic_common_device_t *device) { assert (device != NULL); // Set the default values. memset (device->version, 0, sizeof (device->version)); memset (device->fingerprint, 0, sizeof (device->fingerprint)); device->layout = NULL; device->multipage = 1; } dc_status_t oceanic_common_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { oceanic_common_device_t *device = (oceanic_common_device_t *) abstract; assert (device != NULL); assert (device->layout != NULL); assert (device->layout->rb_logbook_entry_size <= sizeof (device->fingerprint)); unsigned int fpsize = device->layout->rb_logbook_entry_size; if (size && size != fpsize) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, fpsize); else memset (device->fingerprint, 0, fpsize); return DC_STATUS_SUCCESS; } dc_status_t oceanic_common_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { oceanic_common_device_t *device = (oceanic_common_device_t *) abstract; assert (device != NULL); assert (device->layout != NULL); // Allocate the required amount of memory. if (!dc_buffer_resize (buffer, device->layout->memsize)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Emit a vendor event. dc_event_vendor_t vendor; vendor.data = device->version; vendor.size = sizeof (device->version); device_event_emit (abstract, DC_EVENT_VENDOR, &vendor); return device_dump_read (abstract, dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), PAGESIZE * device->multipage); } dc_status_t oceanic_common_device_logbook (dc_device_t *abstract, dc_event_progress_t *progress, dc_buffer_t *logbook) { oceanic_common_device_t *device = (oceanic_common_device_t *) abstract; dc_status_t rc = DC_STATUS_SUCCESS; assert (device != NULL); assert (device->layout != NULL); assert (device->layout->rb_logbook_entry_size <= sizeof (device->fingerprint)); assert (progress != NULL); const oceanic_common_layout_t *layout = device->layout; // Erase the buffer. if (!dc_buffer_clear (logbook)) return DC_STATUS_NOMEMORY; // For devices without a logbook ringbuffer, downloading dives isn't // possible. This is not considered a fatal error, but handled as if there // are no dives present. if (layout->rb_logbook_begin == layout->rb_logbook_end) { return DC_STATUS_SUCCESS; } // Read the pointer data. unsigned char pointers[PAGESIZE] = {0}; rc = dc_device_read (abstract, layout->cf_pointers, pointers, sizeof (pointers)); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the memory page."); return rc; } // Get the logbook pointers. unsigned int rb_logbook_first = array_uint16_le (pointers + 4); unsigned int rb_logbook_last = array_uint16_le (pointers + 6); if (rb_logbook_last < layout->rb_logbook_begin || rb_logbook_last >= layout->rb_logbook_end) { ERROR (abstract->context, "Invalid logbook end pointer detected (0x%04x).", rb_logbook_last); return DC_STATUS_DATAFORMAT; } // Calculate the end pointer. unsigned int rb_logbook_end = 0; if (layout->pt_mode_global == 0) { rb_logbook_end = RB_LOGBOOK_INCR (rb_logbook_last, layout->rb_logbook_entry_size, layout); } else { rb_logbook_end = rb_logbook_last; } // Calculate the number of bytes. // In a typical ringbuffer implementation with only two begin/end // pointers, there is no distinction possible between an empty and a // full ringbuffer. We always consider the ringbuffer full in that // case, because an empty ringbuffer can be detected by inspecting // the logbook entries once they are downloaded. unsigned int rb_logbook_size = 0; if (rb_logbook_first < layout->rb_logbook_begin || rb_logbook_first >= layout->rb_logbook_end) { // Fall back to downloading the entire logbook ringbuffer as // workaround for an invalid logbook begin pointer! ERROR (abstract->context, "Invalid logbook begin pointer detected (0x%04x).", rb_logbook_first); rb_logbook_size = layout->rb_logbook_end - layout->rb_logbook_begin; } else { rb_logbook_size = RB_LOGBOOK_DISTANCE (rb_logbook_first, rb_logbook_end, layout); } // Update and emit a progress event. progress->current += PAGESIZE; progress->maximum += PAGESIZE; progress->maximum -= (layout->rb_logbook_end - layout->rb_logbook_begin) - rb_logbook_size; device_event_emit (abstract, DC_EVENT_PROGRESS, progress); // Exit if there are no dives. if (rb_logbook_size == 0) { return DC_STATUS_SUCCESS; } // Allocate memory for the logbook entries. if (!dc_buffer_resize (logbook, rb_logbook_size)) return DC_STATUS_NOMEMORY; // Cache the logbook pointer. unsigned char *logbooks = dc_buffer_get_data (logbook); // Create the ringbuffer stream. dc_rbstream_t *rbstream = NULL; rc = dc_rbstream_new (&rbstream, abstract, PAGESIZE, PAGESIZE * device->multipage, layout->rb_logbook_begin, layout->rb_logbook_end, rb_logbook_end); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to create the ringbuffer stream."); return rc; } // The logbook ringbuffer is read backwards to retrieve the most recent // entries first. If an already downloaded entry is identified (by means // of its fingerprint), the transfer is aborted immediately to reduce // the transfer time. unsigned int nbytes = 0; unsigned int offset = rb_logbook_size; while (nbytes < rb_logbook_size) { // Move to the start of the current entry. offset -= layout->rb_logbook_entry_size; // Read the logbook entry. rc = dc_rbstream_read (rbstream, progress, logbooks + offset, layout->rb_logbook_entry_size); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the memory."); dc_rbstream_free (rbstream); return rc; } nbytes += layout->rb_logbook_entry_size; // Check for uninitialized entries. Normally, such entries are // never present, except when the ringbuffer is actually empty, // but the ringbuffer pointers are not set to their empty values. // This appears to happen on some devices, and we attempt to // fix this here. if (array_isequal (logbooks + offset, layout->rb_logbook_entry_size, 0xFF)) { WARNING (abstract->context, "Uninitialized logbook entries detected!"); offset += layout->rb_logbook_entry_size; break; } // Compare the fingerprint to identify previously downloaded entries. if (memcmp (logbooks + offset, device->fingerprint, layout->rb_logbook_entry_size) == 0) { offset += layout->rb_logbook_entry_size; break; } } // Update and emit a progress event. progress->maximum -= rb_logbook_size - nbytes; device_event_emit (abstract, DC_EVENT_PROGRESS, progress); dc_buffer_slice (logbook, offset, rb_logbook_size - offset); dc_rbstream_free (rbstream); return DC_STATUS_SUCCESS; } dc_status_t oceanic_common_device_profile (dc_device_t *abstract, dc_event_progress_t *progress, dc_buffer_t *logbook, dc_dive_callback_t callback, void *userdata) { oceanic_common_device_t *device = (oceanic_common_device_t *) abstract; dc_status_t rc = DC_STATUS_SUCCESS; assert (device != NULL); assert (device->layout != NULL); assert (device->layout->rb_logbook_entry_size <= sizeof (device->fingerprint)); assert (progress != NULL); const oceanic_common_layout_t *layout = device->layout; // Cache the logbook pointer and size. const unsigned char *logbooks = dc_buffer_get_data (logbook); unsigned int rb_logbook_size = dc_buffer_get_size (logbook); // Go through the logbook entries a first time, to get the end of // profile pointer and calculate the total amount of bytes in the // profile ringbuffer. unsigned int rb_profile_end = INVALID; unsigned int rb_profile_size = 0; // Traverse the logbook ringbuffer backwards to retrieve the most recent // dives first. The logbook ringbuffer is linearized at this point, so // we do not have to take into account any memory wrapping near the end // of the memory buffer. unsigned int remaining = layout->rb_profile_end - layout->rb_profile_begin; unsigned int previous = rb_profile_end; unsigned int entry = rb_logbook_size; while (entry) { // Move to the start of the current entry. entry -= layout->rb_logbook_entry_size; // Get the profile pointers. unsigned int rb_entry_first = get_profile_first (logbooks + entry, layout); unsigned int rb_entry_last = get_profile_last (logbooks + entry, layout); if (rb_entry_first < layout->rb_profile_begin || rb_entry_first >= layout->rb_profile_end || rb_entry_last < layout->rb_profile_begin || rb_entry_last >= layout->rb_profile_end) { ERROR (abstract->context, "Invalid ringbuffer pointer detected (0x%06x 0x%06x).", rb_entry_first, rb_entry_last); break; } // Calculate the end pointer and the number of bytes. unsigned int rb_entry_end = RB_PROFILE_INCR (rb_entry_last, PAGESIZE, layout); unsigned int rb_entry_size = RB_PROFILE_DISTANCE (rb_entry_first, rb_entry_last, layout) + PAGESIZE; // Take the end pointer of the most recent logbook entry as the // end of profile pointer. if (rb_profile_end == INVALID) { rb_profile_end = previous = rb_entry_end; } // Skip gaps between the profiles. unsigned int gap = 0; if (rb_entry_end != previous) { WARNING (abstract->context, "Profiles are not continuous."); gap = RB_PROFILE_DISTANCE (rb_entry_end, previous, layout); } // Make sure the profile size is valid. if (rb_entry_size + gap > remaining) { WARNING (abstract->context, "Unexpected profile size."); break; } // Update the total profile size. rb_profile_size += rb_entry_size + gap; remaining -= rb_entry_size + gap; previous = rb_entry_first; } // At this point, we know the exact amount of data // that needs to be transfered for the profiles. progress->maximum -= (layout->rb_profile_end - layout->rb_profile_begin) - rb_profile_size; device_event_emit (abstract, DC_EVENT_PROGRESS, progress); // Create the ringbuffer stream. dc_rbstream_t *rbstream = NULL; rc = dc_rbstream_new (&rbstream, abstract, PAGESIZE, PAGESIZE * device->multipage, layout->rb_profile_begin, layout->rb_profile_end, rb_profile_end); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to create the ringbuffer stream."); return rc; } // Memory buffer for the profile data. unsigned char *profiles = (unsigned char *) malloc (rb_profile_size + rb_logbook_size); if (profiles == NULL) { ERROR (abstract->context, "Failed to allocate memory."); dc_rbstream_free (rbstream); return DC_STATUS_NOMEMORY; } // Keep track of the current position. unsigned int offset = rb_profile_size + rb_logbook_size; // Traverse the logbook ringbuffer backwards to retrieve the most recent // dives first. The logbook ringbuffer is linearized at this point, so // we do not have to take into account any memory wrapping near the end // of the memory buffer. remaining = rb_profile_size; previous = rb_profile_end; entry = rb_logbook_size; while (entry) { // Move to the start of the current entry. entry -= layout->rb_logbook_entry_size; // Get the profile pointers. unsigned int rb_entry_first = get_profile_first (logbooks + entry, layout); unsigned int rb_entry_last = get_profile_last (logbooks + entry, layout); if (rb_entry_first < layout->rb_profile_begin || rb_entry_first >= layout->rb_profile_end || rb_entry_last < layout->rb_profile_begin || rb_entry_last >= layout->rb_profile_end) { ERROR (abstract->context, "Invalid ringbuffer pointer detected (0x%06x 0x%06x).", rb_entry_first, rb_entry_last); dc_rbstream_free (rbstream); free (profiles); return DC_STATUS_DATAFORMAT; } // Calculate the end pointer and the number of bytes. unsigned int rb_entry_end = RB_PROFILE_INCR (rb_entry_last, PAGESIZE, layout); unsigned int rb_entry_size = RB_PROFILE_DISTANCE (rb_entry_first, rb_entry_last, layout) + PAGESIZE; // Skip gaps between the profiles. unsigned int gap = 0; if (rb_entry_end != previous) { WARNING (abstract->context, "Profiles are not continuous."); gap = RB_PROFILE_DISTANCE (rb_entry_end, previous, layout); } // Make sure the profile size is valid. if (rb_entry_size + gap > remaining) { WARNING (abstract->context, "Unexpected profile size."); break; } // Move to the start of the current dive. offset -= rb_entry_size + gap; // Read the dive. rc = dc_rbstream_read (rbstream, progress, profiles + offset, rb_entry_size + gap); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the dive."); dc_rbstream_free (rbstream); free (profiles); return rc; } remaining -= rb_entry_size + gap; previous = rb_entry_first; // Prepend the logbook entry to the profile data. The memory buffer is // large enough to store this entry. offset -= layout->rb_logbook_entry_size; memcpy (profiles + offset, logbooks + entry, layout->rb_logbook_entry_size); unsigned char *p = profiles + offset; if (callback && !callback (p, rb_entry_size + layout->rb_logbook_entry_size, p, layout->rb_logbook_entry_size, userdata)) { break; } } dc_rbstream_free (rbstream); free (profiles); return DC_STATUS_SUCCESS; } dc_status_t oceanic_common_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { oceanic_common_device_t *device = (oceanic_common_device_t *) abstract; assert (device != NULL); assert (device->layout != NULL); const oceanic_common_layout_t *layout = device->layout; // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = PAGESIZE + (layout->rb_logbook_end - layout->rb_logbook_begin) + (layout->rb_profile_end - layout->rb_profile_begin); device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Emit a vendor event. dc_event_vendor_t vendor; vendor.data = device->version; vendor.size = sizeof (device->version); device_event_emit (abstract, DC_EVENT_VENDOR, &vendor); // Read the device id. unsigned char id[PAGESIZE] = {0}; dc_status_t rc = dc_device_read (abstract, layout->cf_devinfo, id, sizeof (id)); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the memory page."); return rc; } // Update and emit a progress event. progress.current += PAGESIZE; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Emit a device info event. dc_event_devinfo_t devinfo; devinfo.model = array_uint16_be (id + 8); devinfo.firmware = 0; if (layout->pt_mode_serial == 0) devinfo.serial = bcd2dec (id[10]) * 10000 + bcd2dec (id[11]) * 100 + bcd2dec (id[12]); else if (layout->pt_mode_serial == 1) devinfo.serial = id[11] * 10000 + id[12] * 100 + id[13]; else devinfo.serial = (id[11] & 0x0F) * 100000 + ((id[11] & 0xF0) >> 4) * 10000 + (id[12] & 0x0F) * 1000 + ((id[12] & 0xF0) >> 4) * 100 + (id[13] & 0x0F) * 10 + ((id[13] & 0xF0) >> 4) * 1; device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); // Memory buffer for the logbook data. dc_buffer_t *logbook = dc_buffer_new (0); if (logbook == NULL) { return DC_STATUS_NOMEMORY; } // Download the logbook ringbuffer. rc = VTABLE(abstract)->logbook (abstract, &progress, logbook); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (logbook); return rc; } // Exit if there are no (new) dives. if (dc_buffer_get_size (logbook) == 0) { dc_buffer_free (logbook); return DC_STATUS_SUCCESS; } // Download the profile ringbuffer. rc = VTABLE(abstract)->profile (abstract, &progress, logbook, callback, userdata); if (rc != DC_STATUS_SUCCESS) { dc_buffer_free (logbook); return rc; } dc_buffer_free (logbook); return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/oceanic_common.c