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

Dataset Card for "all-torvalds-c-code-1"

More Information needed

Downloads last month
0
Edit dataset card