[Pkg-running-devel] [openambit] 02/02: Imported Upstream version 0.2
Christian Perrier
bubulle at moszumanska.debian.org
Sun Jul 13 21:51:33 UTC 2014
This is an automated email from the git hooks/post-receive script.
bubulle pushed a commit to branch upstream
in repository openambit.
commit 2f999749ad40e3c5ec50909a283c04cdd5f37bb1
Author: Christian Perrier <bubulle at debian.org>
Date: Sun Jul 13 23:21:57 2014 +0200
Imported Upstream version 0.2
---
.gitignore | 6 +
README | 91 +
build.sh | 27 +
debian/changelog | 5 -
debian/compat | 1 -
debian/control | 18 -
debian/copyright | 39 -
debian/docs | 0
debian/rules | 13 -
debian/source/format | 1 -
install.sh | 3 +
openambit_0.2.orig.tar.gz | Bin 45 -> 0 bytes
run.sh | 8 +
src/example/CMakeLists.txt | 15 +
src/example/ambitconsole.c | 80 +
src/libambit/CMakeLists.txt | 48 +
COPYING => src/libambit/COPYING | 0
{cmake => src/libambit/cmake}/FindUDev.cmake | 9 +-
src/libambit/cmake/Findlibusb.cmake | 40 +
src/libambit/crc16.c | 77 +
src/libambit/debug.c | 71 +
src/libambit/hid-libusb.c | 1427 ++++++++++++++
src/libambit/hid.c | 795 ++++++++
src/libambit/hidapi/hidapi.h | 387 ++++
src/libambit/libambit.c | 551 ++++++
src/libambit/libambit.h | 469 +++++
src/libambit/libambit_int.h | 157 ++
src/libambit/personal.c | 122 ++
src/libambit/pmem20.c | 912 +++++++++
src/libambit/protocol.c | 212 +++
CMakeLists.txt => src/openambit/CMakeLists.txt | 0
COPYING => src/openambit/COPYING | 0
{cmake => src/openambit/cmake}/FindUDev.cmake | 0
{cmake => src/openambit/cmake}/Findlibambit.cmake | 0
.../openambit/confirmbetadialog.cpp | 0
.../openambit/confirmbetadialog.h | 0
.../openambit/confirmbetadialog.ui | 0
.../openambit/deployment}/99-suunto-ambit.rules | 0
.../openambit/deployment}/openambit.desktop | 0
.../openambit/devicemanager.cpp | 0
devicemanager.h => src/openambit/devicemanager.h | 0
{icons => src/openambit/icons}/icon_connected.png | Bin
.../openambit/icons}/icon_disconnected.png | Bin
{icons => src/openambit/icons}/icon_sync.png | Bin
logentry.cpp => src/openambit/logentry.cpp | 0
logentry.h => src/openambit/logentry.h | 0
logstore.cpp => src/openambit/logstore.cpp | 0
logstore.h => src/openambit/logstore.h | 0
main.cpp => src/openambit/main.cpp | 0
mainwindow.cpp => src/openambit/mainwindow.cpp | 0
mainwindow.h => src/openambit/mainwindow.h | 0
mainwindow.ui => src/openambit/mainwindow.ui | 0
.../openambit/movescount}/CMakeLists.txt | 0
.../openambit/movescount}/include.pri | 0
.../openambit/movescount}/movescount.cpp | 0
.../openambit/movescount}/movescount.h | 0
.../openambit/movescount}/movescountjson.cpp | 0
.../openambit/movescount}/movescountjson.h | 0
.../movescount}/movescountlogdirentry.cpp | 0
.../openambit/movescount}/movescountlogdirentry.h | 0
.../openambit/movescount}/movescountxml.cpp | 0
.../openambit/movescount}/movescountxml.h | 0
resources.qrc => src/openambit/resources.qrc | 0
settings.cpp => src/openambit/settings.cpp | 0
settings.h => src/openambit/settings.h | 0
.../openambit/settingsdialog.cpp | 0
settingsdialog.h => src/openambit/settingsdialog.h | 0
.../openambit/settingsdialog.ui | 0
.../openambit/single_application.cpp | 0
.../openambit/single_application.h | 0
udevlistener.cpp => src/openambit/udevlistener.cpp | 0
udevlistener.h => src/openambit/udevlistener.h | 0
tools/movescountXmlDiff.pl | 178 ++
wireshark_dissector/AUTHORS | 2 +
wireshark_dissector/CMakeLists.txt | 84 +
wireshark_dissector/COPYING | 22 +
wireshark_dissector/ChangeLog | 2 +
wireshark_dissector/INSTALL | 9 +
wireshark_dissector/ambit-dissector.c | 1981 ++++++++++++++++++++
wireshark_dissector/cmake/COPYING-CMAKE-SCRIPTS | 27 +
wireshark_dissector/cmake/FindGLIB2.cmake | 238 +++
wireshark_dissector/cmake/FindWireshark.cmake | 28 +
.../cmake/UseMakeDissectorReg.cmake | 33 +
wireshark_dissector/moduleinfo.h | 17 +
wireshark_dissector/tools/make-dissector-reg | 186 ++
wireshark_dissector/tools/make-dissector-reg.py | 305 +++
86 files changed, 8612 insertions(+), 84 deletions(-)
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..44bdc73
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,6 @@
+# Ignore build directories
+*build*/
+
+# Ignore temporary and user files
+*~
+*.user
diff --git a/README b/README
new file mode 100644
index 0000000..0f45808
--- /dev/null
+++ b/README
@@ -0,0 +1,91 @@
+OPENAMBIT
+=========
+
+The openambit source repository contains of several parts.
+Each part is briefly described below.
+Most people would like to use both the device communication
+library (libambit) and the GUI (openambit). The build / install
+scripts described below makes your life easier if you are
+like most people.
+You can choose to run the GUI from the build folder or install
+it to your system.
+
+BUILD SCRIPT
+============
+Builds libambit and openambit in one command
+> cd YOUR/git/REPO/loaction
+> ./build.sh
+
+
+BUILD AND INSTALL SCRIPT
+========================
+Builds and install libambit and openambit in one command.
+Note that the script will try to run sudo to install things.
+> cd YOUR/git/REPO/loaction
+> ./install.sh
+
+
+DEPENDENCIES
+============
+To be able to build libambit and openambit the following libraries
+(and their header files) needs to be available:
+ - libudev
+ - libusb
+ - libqjson
+
+For debian-based systems:
+> sudo apt-get install libudev-dev libusb-1.0-0-dev libqjson-dev
+
+
+src/libambit
+============
+The "driver" library as a shared object. Written in C.
+
+Build instructions:
+> mkdir libambit-build
+> cd libambit-build
+> cmake ../src/libambit
+> make
+Optionally:
+> sudo make install
+
+
+src/openambit
+=============
+The GUI application. Uses the libambit library.
+
+Build instructions:
+First build libambit as instructed above
+> mkdir openambit-build
+> cd openambit-build
+> cmake ../src/openambit
+> make
+Optionally:
+> sudo make install
+
+Run the application without installing:
+> cd openambit-build
+> LD_LIBRARY_PATH=../libambit-build ./openambit
+
+
+tools/movescountXmlDiff.pl
+==========================
+Small Perl-script to compare XML-files generated by
+openambit and Suuntos Moveslink. Basically a diff with
+added floating point round errors ignored.
+
+
+wireshark_dissector
+===================
+To ease the parsing of the protocol a wireshark dissector
+is maintained. This dissector parses pcap-files made with
+usbpcap. The parts of the protocol that is known atm
+should be present in the latest dissector.
+
+Build instructions:
+> mkdir build
+> cd build
+> cmake ..
+> make
+> cp ambit.so ~/.wireshark/plugins
+
diff --git a/build.sh b/build.sh
new file mode 100755
index 0000000..50245c7
--- /dev/null
+++ b/build.sh
@@ -0,0 +1,27 @@
+SOURCE_LOCATION="`dirname \"$0\"`"
+SOURCE_LOCATION="`( cd \"$SOURCE_LOCATION\" && pwd )`"
+
+CORES=$(cat /proc/cpuinfo | grep processor | wc -l)
+
+cd $SOURCE_LOCATION
+
+echo "------building libambit------"
+mkdir -p libambit-build
+cd libambit-build
+cmake -DCMAKE_INSTALL_PREFIX:PATH=/usr ../src/libambit
+make -j$CORES
+if [ "$DO_INSTALL" == "1" ]; then
+ echo "------installing libambit------"
+ sudo make install
+fi
+
+cd $SOURCE_LOCATION
+echo "------building openambit------"
+mkdir -p openambit-build
+cd openambit-build
+cmake -DCMAKE_INSTALL_PREFIX:PATH=/usr ../src/openambit
+make -j$CORES
+if [ "$DO_INSTALL" == "1" ]; then
+ echo "------installing openambit------"
+ sudo make install
+fi
diff --git a/debian/changelog b/debian/changelog
deleted file mode 100644
index 16dc2c9..0000000
--- a/debian/changelog
+++ /dev/null
@@ -1,5 +0,0 @@
-openambit (0.2-1) saucy; urgency=low
-
- * Initial release
-
- -- Emil Ljungdahl <emil at kratern.se> Thu, 30 Jan 2014 16:21:42 +0100
diff --git a/debian/compat b/debian/compat
deleted file mode 100644
index 45a4fb7..0000000
--- a/debian/compat
+++ /dev/null
@@ -1 +0,0 @@
-8
diff --git a/debian/control b/debian/control
deleted file mode 100644
index e3994f6..0000000
--- a/debian/control
+++ /dev/null
@@ -1,18 +0,0 @@
-Source: openambit
-Priority: extra
-Maintainer: Emil Ljungdahl <emil at kratern.se>
-Build-Depends: debhelper (>= 9), cmake (>= 2.8.5), libudev-dev, libqjson-dev, zlib1g-dev,
- libambit-dev (= 0.2-1), libqt4-dev
-Standards-Version: 3.9.4
-Section: utils
-Homepage: https://sourceforge.net/projects/openambit/
-#Vcs-Git: git://git.debian.org/collab-maint/openambit.git
-#Vcs-Browser: http://git.debian.org/?p=collab-maint/openambit.git;a=summary
-
-Package: openambit
-Architecture: any
-Depends: libudev1, libqjson0, zlib1g, libambit0 (= 0.2-1),
- libqt4-core, libqt4-gui, libqt4-network, ${shlibs:Depends}, ${misc:Depends}
-Description: Synchronize your Suunto Ambit series device
- Openambit is GUI application for synchronizing the Suunto Ambit series
- of devices with your PC and Suuntos cloudservice movescount.com
diff --git a/debian/copyright b/debian/copyright
deleted file mode 100644
index 9d08945..0000000
--- a/debian/copyright
+++ /dev/null
@@ -1,39 +0,0 @@
-Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
-Upstream-Name: openambit
-Source: https://sourceforge.net/projects/openambit/
-
-Files: *
-Copyright: 2014 Emil Ljungdahl <emil at kratern.se>
-License: GPL-3
- libambit is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
- .
- This program 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 General Public License for more details.
- .
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-Files: debian/*
-Copyright: 2014 Emil Ljungdahl <emil at kratern.se>
-License: GPL-2+
- This package is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
- .
- This package 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 General Public License for more details.
- .
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>
- .
- On Debian systems, the complete text of the GNU General
- Public License version 2 can be found in "/usr/share/common-licenses/GPL-2".
-
diff --git a/debian/docs b/debian/docs
deleted file mode 100644
index e69de29..0000000
diff --git a/debian/rules b/debian/rules
deleted file mode 100755
index b760bee..0000000
--- a/debian/rules
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/usr/bin/make -f
-# -*- makefile -*-
-# Sample debian/rules that uses debhelper.
-# This file was originally written by Joey Hess and Craig Small.
-# As a special exception, when this file is copied by dh-make into a
-# dh-make output file, you may use that output file without restriction.
-# This special exception was added by Craig Small in version 0.37 of dh-make.
-
-# Uncomment this to turn on verbose mode.
-#export DH_VERBOSE=1
-
-%:
- dh $@
diff --git a/debian/source/format b/debian/source/format
deleted file mode 100644
index 163aaf8..0000000
--- a/debian/source/format
+++ /dev/null
@@ -1 +0,0 @@
-3.0 (quilt)
diff --git a/install.sh b/install.sh
new file mode 100755
index 0000000..d88ce43
--- /dev/null
+++ b/install.sh
@@ -0,0 +1,3 @@
+export DO_INSTALL=1
+
+./build.sh
diff --git a/openambit_0.2.orig.tar.gz b/openambit_0.2.orig.tar.gz
deleted file mode 100644
index 5583a32..0000000
Binary files a/openambit_0.2.orig.tar.gz and /dev/null differ
diff --git a/run.sh b/run.sh
new file mode 100755
index 0000000..7d3ec6c
--- /dev/null
+++ b/run.sh
@@ -0,0 +1,8 @@
+SOURCE_LOCATION="`dirname \"$0\"`"
+SOURCE_LOCATION="`( cd \"$SOURCE_LOCATION\" && pwd )`"
+
+cd $SOURCE_LOCATION
+echo "------running openambit------"
+LD_LIBRARY_PATH=./libambit-build ./openambit-build/openambit
+
+
diff --git a/src/example/CMakeLists.txt b/src/example/CMakeLists.txt
new file mode 100644
index 0000000..f639da0
--- /dev/null
+++ b/src/example/CMakeLists.txt
@@ -0,0 +1,15 @@
+include_directories(
+ ${OPENAMBIT_SOURCE_DIR}/libambit
+)
+
+link_directories(
+ ${OPENAMBIT_BINARY_DIR}/libambit
+)
+
+add_executable(
+ ambitconsole ambitconsole.c
+)
+
+target_link_libraries(
+ ambitconsole ambit
+)
diff --git a/src/example/ambitconsole.c b/src/example/ambitconsole.c
new file mode 100644
index 0000000..4fb6bd0
--- /dev/null
+++ b/src/example/ambitconsole.c
@@ -0,0 +1,80 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <libambit.h>
+
+static int log_skip_cb(void *ambit_object, ambit_log_header_t *log_header);
+static void log_data_cb(void *object, ambit_log_entry_t *log_entry);
+
+int main(int argc, char *argv[])
+{
+ ambit_object_t *ambit_object;
+ ambit_device_info_t info;
+ ambit_device_status_t status;
+ ambit_personal_settings_t settings;
+ time_t current_time;
+ struct tm *local_time;
+
+ if ((ambit_object = libambit_detect()) != NULL) {
+ libambit_device_info_get(ambit_object, &info);
+
+ if (libambit_device_supported(ambit_object)) {
+ printf("Device: %s, serial: %s, FW version: %d.%d.%d\n", info.name, info.serial, info.fw_version[0], info.fw_version[1], info.fw_version[2]);
+
+ if (libambit_device_status_get(ambit_object, &status) == 0) {
+ printf("Current charge: %d%%\n", status.charge);
+ }
+ else {
+ printf("Failed to read status\n");
+ }
+
+ if (libambit_personal_settings_get(ambit_object, &settings) == 0) {
+ }
+ else {
+ printf("Failed to read status\n");
+ }
+
+ current_time = time(NULL);
+ local_time = localtime(¤t_time);
+ //if (libambit_date_time_set(ambit_object, local_time) == 0) {
+ //}
+ //else {
+ // printf("Failed to set date and time\n");
+ //}
+
+ libambit_log_read(ambit_object, log_skip_cb, log_data_cb, NULL, ambit_object);
+ }
+ else {
+ printf("Device: %s (fw_version: %d.%d.%d) is not supported yet!\n", info.name, info.fw_version[0], info.fw_version[1], info.fw_version[2]);
+ }
+
+ libambit_close(ambit_object);
+ }
+ else {
+ printf("No clock found, exiting\n");
+ }
+
+ return 0;
+}
+
+static int log_skip_cb(void *ambit_object, ambit_log_header_t *log_header)
+{
+ static int log_count = 0;
+
+ printf("Got log header \"%s\" %d-%02d-%02d %02d:%02d:%02d\n", log_header->activity_name, log_header->date_time.year, log_header->date_time.month, log_header->date_time.day, log_header->date_time.hour, log_header->date_time.minute, log_header->date_time.msec/1000);
+
+ if (log_count++ > 1) {
+ return 0;
+ }
+
+ return 1;
+}
+
+static void log_data_cb(void *object, ambit_log_entry_t *log_entry)
+{
+ printf("Got log entry \"%s\" %d-%02d-%02d %02d:%02d:%02d\n", log_entry->header.activity_name, log_entry->header.date_time.year, log_entry->header.date_time.month, log_entry->header.date_time.day, log_entry->header.date_time.hour, log_entry->header.date_time.minute, log_entry->header.date_time.msec/1000);
+
+ int i;
+ for (i=0; i<log_entry->header.samples_count; i++) {
+ printf("Sample #%d, type: %d, time: %04u-%02u-%02u %02u:%02u:%2.3f\n", i, log_entry->samples[i].type, log_entry->samples[i].utc_time.year, log_entry->samples[i].utc_time.month, log_entry->samples[i].utc_time.day, log_entry->samples[i].utc_time.hour, log_entry->samples[i].utc_time.minute, (1.0*log_entry->samples[i].utc_time.msec)/1000);
+ }
+}
diff --git a/src/libambit/CMakeLists.txt b/src/libambit/CMakeLists.txt
new file mode 100644
index 0000000..e8283b8
--- /dev/null
+++ b/src/libambit/CMakeLists.txt
@@ -0,0 +1,48 @@
+cmake_minimum_required (VERSION 2.8.5)
+project (LIBAMBIT)
+
+# Where to lookup modules
+set(CMAKE_MODULE_PATH "${LIBAMBIT_SOURCE_DIR}/cmake")
+
+set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall")
+
+# Debug defines
+set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -DDEBUG_PRINT_ERROR -DDEBUG_PRINT_WARNING")
+IF (DEFINED DEBUG_PRINT_INFO)
+ set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -DDEBUG_PRINT_INFO=${DEBUG_PRINT_INFO}")
+ENDIF()
+IF (DEFINED DEBUG_PRINT_FILE_LINE)
+ set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -DDEBUG_PRINT_FILE_LINE=${DEBUG_PRINT_FILE_LINE}")
+ENDIF()
+
+find_package(libusb REQUIRED)
+find_package(UDev REQUIRED)
+include(GNUInstallDirs)
+
+add_library (
+ ambit
+ SHARED
+ crc16.c
+ debug.c
+ hid.c
+ libambit.c
+ personal.c
+ pmem20.c
+ protocol.c
+)
+
+target_link_libraries(
+ ambit
+ ${UDEV_LIBS}
+ ${LIBUSB_LIBRARIES}
+ m
+)
+
+set_target_properties(ambit PROPERTIES VERSION 0.2.0 SOVERSION 0)
+
+include_directories(
+ hidapi
+)
+
+install(TARGETS ambit DESTINATION ${CMAKE_INSTALL_LIBDIR})
+install(FILES libambit.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
diff --git a/COPYING b/src/libambit/COPYING
similarity index 100%
copy from COPYING
copy to src/libambit/COPYING
diff --git a/cmake/FindUDev.cmake b/src/libambit/cmake/FindUDev.cmake
similarity index 75%
copy from cmake/FindUDev.cmake
copy to src/libambit/cmake/FindUDev.cmake
index 6febceb..08e4f39 100644
--- a/cmake/FindUDev.cmake
+++ b/src/libambit/cmake/FindUDev.cmake
@@ -12,13 +12,8 @@
find_path(UDEV_INCLUDE_DIR libudev.h)
find_library(UDEV_LIBS udev)
-find_path(UDEV_RULES_PATH udev/rules.d
- PATHS
- /lib
- /usr/lib
-)
include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(UDev DEFAULT_MSG UDEV_INCLUDE_DIR UDEV_LIBS UDEV_RULES_PATH)
+find_package_handle_standard_args(UDev DEFAULT_MSG UDEV_INCLUDE_DIR UDEV_LIBS)
-mark_as_advanced(UDEV_INCLUDE_DIR UDEV_LIBS UDEV_RULES_PATH)
+mark_as_advanced(UDEV_INCLUDE_DIR UDEV_LIBS)
diff --git a/src/libambit/cmake/Findlibusb.cmake b/src/libambit/cmake/Findlibusb.cmake
new file mode 100644
index 0000000..a478853
--- /dev/null
+++ b/src/libambit/cmake/Findlibusb.cmake
@@ -0,0 +1,40 @@
+# - Find libusb-1.0 library
+# This module defines
+# LIBUSB_INCLUDE_DIR, where to find bluetooth.h
+# LIBUSB_LIBRARIES, the libraries needed to use libusb-1.0.
+# LIBUSB_FOUND, If false, do not try to use libusb-1.0.
+#
+# Copyright (c) 2009, Michal Cihar, <michal at cihar.com>
+#
+# vim: expandtab sw=4 ts=4 sts=4:
+
+if (NOT LIBUSB_FOUND)
+ find_package(PkgConfig)
+ pkg_check_modules (LIBUSB_PKG libusb-1.0)
+
+ find_path(LIBUSB_INCLUDE_DIR NAMES libusb.h
+ PATHS
+ ${LIBUSB_PKG_INCLUDE_DIRS}
+ /usr/include/libusb-1.0
+ /usr/include
+ /usr/local/include
+ )
+
+ find_library(LIBUSB_LIBRARIES NAMES usb-1.0
+ PATHS
+ ${LIBUSB_PKG_LIBRARY_DIRS}
+ /usr/lib
+ /usr/local/lib
+ )
+
+ if(LIBUSB_INCLUDE_DIR AND LIBUSB_LIBRARIES)
+ set(LIBUSB_FOUND TRUE CACHE INTERNAL "libusb-1.0 found")
+ message(STATUS "Found libusb-1.0: ${LIBUSB_INCLUDE_DIR}, ${LIBUSB_LIBRARIES}")
+ else(LIBUSB_INCLUDE_DIR AND LIBUSB_LIBRARIES)
+ set(LIBUSB_FOUND FALSE CACHE INTERNAL "libusb-1.0 found")
+ message(STATUS "libusb-1.0 not found.")
+ endif(LIBUSB_INCLUDE_DIR AND LIBUSB_LIBRARIES)
+
+ mark_as_advanced(LIBUSB_INCLUDE_DIR LIBUSB_LIBRARIES)
+endif (NOT LIBUSB_FOUND)
+
diff --git a/src/libambit/crc16.c b/src/libambit/crc16.c
new file mode 100644
index 0000000..ce1db5f
--- /dev/null
+++ b/src/libambit/crc16.c
@@ -0,0 +1,77 @@
+/*****************************************************************/
+/* */
+/* CRC LOOKUP TABLE */
+/* ================ */
+/* The following CRC lookup table was generated automagically */
+/* by the Rocksoft^tm Model CRC Algorithm Table Generation */
+/* Program V1.0 using the following model parameters: */
+/* */
+/* Width : 2 bytes. */
+/* Poly : 0x1021 */
+/* Reverse : FALSE. */
+/* */
+/* For more information on the Rocksoft^tm Model CRC Algorithm, */
+/* see the document titled "A Painless Guide to CRC Error */
+/* Detection Algorithms" by Ross Williams */
+/* (ross at guest.adelaide.edu.au.). This document is likely to be */
+/* in the FTP archive "ftp.adelaide.edu.au/pub/rocksoft". */
+/* */
+/*****************************************************************/
+
+#include "libambit_int.h"
+
+static uint16_t crctable[256] =
+{
+ 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
+ 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
+ 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
+ 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
+ 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
+ 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
+ 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
+ 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
+ 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
+ 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
+ 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
+ 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
+ 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
+ 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
+ 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
+ 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
+ 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
+ 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
+ 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
+ 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
+ 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
+ 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
+ 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
+ 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
+ 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
+ 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
+ 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
+ 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
+ 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
+ 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
+ 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
+ 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0
+};
+
+#define CRC16_CCITT_FALSE_INIT 0xffff
+#define CRC16_CCITT_FALSE_XOROT 0x0000
+
+/*****************************************************************/
+/* End of CRC Lookup Table */
+/*****************************************************************/
+
+uint16_t crc16_ccitt_false(unsigned char *buf, size_t buflen)
+{
+ return crc16_ccitt_false_init(buf, buflen, CRC16_CCITT_FALSE_INIT);
+}
+
+uint16_t crc16_ccitt_false_init(unsigned char *buf, size_t buflen, uint16_t crc)
+{
+ while (buflen--) {
+ crc = crctable[((crc>>8) ^ *buf++) & 0xFFL] ^ (crc << 8);
+ }
+ return crc ^ CRC16_CCITT_FALSE_XOROT;
+}
diff --git a/src/libambit/debug.c b/src/libambit/debug.c
new file mode 100644
index 0000000..bd30f68
--- /dev/null
+++ b/src/libambit/debug.c
@@ -0,0 +1,71 @@
+/*
+ * (C) Copyright 2014 Emil Ljungdahl
+ *
+ * This file is part of libambit.
+ *
+ * libambit is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * Contributors:
+ *
+ */
+#include "libambit.h"
+#include "libambit_int.h"
+
+#include <stdarg.h>
+#include <stdio.h>
+
+/*
+ * Local variables
+ */
+static char debug_err_text[] = "ERROR";
+static char debug_warn_text[] = "WARNING";
+static char debug_info_text[] = "INFO";
+
+void debug_printf(debug_level_t level, const char *file, int line, const char *func, const char *fmt, ...)
+{
+ FILE *output;
+ const char *leveltxt;
+ va_list ap;
+
+ if (level == debug_level_err) {
+ output = stderr;
+ leveltxt = debug_err_text;
+ }
+ else if (level == debug_level_warn) {
+ output = stderr;
+ leveltxt = debug_warn_text;
+ }
+ else {
+ output = stdout;
+ leveltxt = debug_info_text;
+ }
+
+ fprintf(output, "libambit %s: ", leveltxt);
+#ifdef DEBUG_PRINT_FILE_LINE
+ fprintf(output, "%s:%d ", file, line);
+#else
+ // Remove compiler warning
+ file = NULL;
+ line = 0;
+#endif
+ fprintf(output, "%s(): ", func);
+
+ va_start(ap, fmt);
+ vfprintf(output, fmt, ap);
+ va_end(ap);
+
+ fprintf(output, "\n");
+
+ fflush(output);
+}
diff --git a/src/libambit/hid-libusb.c b/src/libambit/hid-libusb.c
new file mode 100644
index 0000000..6c1d247
--- /dev/null
+++ b/src/libambit/hid-libusb.c
@@ -0,0 +1,1427 @@
+/*******************************************************
+ HIDAPI - Multi-Platform library for
+ communication with HID devices.
+
+ Alan Ott
+ Signal 11 Software
+
+ 8/22/2009
+ Linux Version - 6/2/2010
+ Libusb Version - 8/13/2010
+ FreeBSD Version - 11/1/2011
+
+ Copyright 2009, All Rights Reserved.
+
+ At the discretion of the user of this library,
+ this software may be licensed under the terms of the
+ GNU General Public License v3, a BSD-Style license, or the
+ original HIDAPI license as outlined in the LICENSE.txt,
+ LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
+ files located at the root of the source distribution.
+ These files may also be found in the public source
+ code repository located at:
+ http://github.com/signal11/hidapi .
+********************************************************/
+
+#define _GNU_SOURCE /* needed for wcsdup() before glibc 2.10 */
+
+/* C */
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <ctype.h>
+#include <locale.h>
+#include <errno.h>
+
+/* Unix */
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/ioctl.h>
+#include <sys/utsname.h>
+#include <fcntl.h>
+#include <pthread.h>
+#include <wchar.h>
+
+/* GNU / LibUSB */
+#include "libusb.h"
+#include "iconv.h"
+
+#include "hidapi.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef DEBUG_PRINTF
+#define LOG(...) fprintf(stderr, __VA_ARGS__)
+#else
+#define LOG(...) do {} while (0)
+#endif
+
+#ifndef __FreeBSD__
+#define DETACH_KERNEL_DRIVER
+#endif
+
+/* Uncomment to enable the retrieval of Usage and Usage Page in
+hid_enumerate(). Warning, on platforms different from FreeBSD
+this is very invasive as it requires the detach
+and re-attach of the kernel driver. See comments inside hid_enumerate().
+libusb HIDAPI programs are encouraged to use the interface number
+instead to differentiate between interfaces on a composite HID device. */
+/*#define INVASIVE_GET_USAGE*/
+
+/* Linked List of input reports received from the device. */
+struct input_report {
+ uint8_t *data;
+ size_t len;
+ struct input_report *next;
+};
+
+
+struct hid_device_ {
+ /* Handle to the actual device. */
+ libusb_device_handle *device_handle;
+
+ /* Endpoint information */
+ int input_endpoint;
+ int output_endpoint;
+ int input_ep_max_packet_size;
+
+ /* The interface number of the HID */
+ int interface;
+
+ /* Indexes of Strings */
+ int manufacturer_index;
+ int product_index;
+ int serial_index;
+
+ /* Whether blocking reads are used */
+ int blocking; /* boolean */
+
+ /* Read thread objects */
+ pthread_t thread;
+ pthread_mutex_t mutex; /* Protects input_reports */
+ pthread_cond_t condition;
+ pthread_barrier_t barrier; /* Ensures correct startup sequence */
+ int shutdown_thread;
+ int cancelled;
+ struct libusb_transfer *transfer;
+
+ /* List of received input reports. */
+ struct input_report *input_reports;
+};
+
+static libusb_context *usb_context = NULL;
+
+uint16_t get_usb_code_for_current_locale(void);
+static int return_data(hid_device *dev, unsigned char *data, size_t length);
+
+static hid_device *new_hid_device(void)
+{
+ hid_device *dev = calloc(1, sizeof(hid_device));
+ dev->blocking = 1;
+
+ pthread_mutex_init(&dev->mutex, NULL);
+ pthread_cond_init(&dev->condition, NULL);
+ pthread_barrier_init(&dev->barrier, NULL, 2);
+
+ return dev;
+}
+
+static void free_hid_device(hid_device *dev)
+{
+ /* Clean up the thread objects */
+ pthread_barrier_destroy(&dev->barrier);
+ pthread_cond_destroy(&dev->condition);
+ pthread_mutex_destroy(&dev->mutex);
+
+ /* Free the device itself */
+ free(dev);
+}
+
+#if 0
+/*TODO: Implement this funciton on hidapi/libusb.. */
+static void register_error(hid_device *device, const char *op)
+{
+
+}
+#endif
+
+#ifdef INVASIVE_GET_USAGE
+/* Get bytes from a HID Report Descriptor.
+ Only call with a num_bytes of 0, 1, 2, or 4. */
+static uint32_t get_bytes(uint8_t *rpt, size_t len, size_t num_bytes, size_t cur)
+{
+ /* Return if there aren't enough bytes. */
+ if (cur + num_bytes >= len)
+ return 0;
+
+ if (num_bytes == 0)
+ return 0;
+ else if (num_bytes == 1) {
+ return rpt[cur+1];
+ }
+ else if (num_bytes == 2) {
+ return (rpt[cur+2] * 256 + rpt[cur+1]);
+ }
+ else if (num_bytes == 4) {
+ return (rpt[cur+4] * 0x01000000 +
+ rpt[cur+3] * 0x00010000 +
+ rpt[cur+2] * 0x00000100 +
+ rpt[cur+1] * 0x00000001);
+ }
+ else
+ return 0;
+}
+
+/* Retrieves the device's Usage Page and Usage from the report
+ descriptor. The algorithm is simple, as it just returns the first
+ Usage and Usage Page that it finds in the descriptor.
+ The return value is 0 on success and -1 on failure. */
+static int get_usage(uint8_t *report_descriptor, size_t size,
+ unsigned short *usage_page, unsigned short *usage)
+{
+ unsigned int i = 0;
+ int size_code;
+ int data_len, key_size;
+ int usage_found = 0, usage_page_found = 0;
+
+ while (i < size) {
+ int key = report_descriptor[i];
+ int key_cmd = key & 0xfc;
+
+ //printf("key: %02hhx\n", key);
+
+ if ((key & 0xf0) == 0xf0) {
+ /* This is a Long Item. The next byte contains the
+ length of the data section (value) for this key.
+ See the HID specification, version 1.11, section
+ 6.2.2.3, titled "Long Items." */
+ if (i+1 < size)
+ data_len = report_descriptor[i+1];
+ else
+ data_len = 0; /* malformed report */
+ key_size = 3;
+ }
+ else {
+ /* This is a Short Item. The bottom two bits of the
+ key contain the size code for the data section
+ (value) for this key. Refer to the HID
+ specification, version 1.11, section 6.2.2.2,
+ titled "Short Items." */
+ size_code = key & 0x3;
+ switch (size_code) {
+ case 0:
+ case 1:
+ case 2:
+ data_len = size_code;
+ break;
+ case 3:
+ data_len = 4;
+ break;
+ default:
+ /* Can't ever happen since size_code is & 0x3 */
+ data_len = 0;
+ break;
+ };
+ key_size = 1;
+ }
+
+ if (key_cmd == 0x4) {
+ *usage_page = get_bytes(report_descriptor, size, data_len, i);
+ usage_page_found = 1;
+ //printf("Usage Page: %x\n", (uint32_t)*usage_page);
+ }
+ if (key_cmd == 0x8) {
+ *usage = get_bytes(report_descriptor, size, data_len, i);
+ usage_found = 1;
+ //printf("Usage: %x\n", (uint32_t)*usage);
+ }
+
+ if (usage_page_found && usage_found)
+ return 0; /* success */
+
+ /* Skip over this key and it's associated data */
+ i += data_len + key_size;
+ }
+
+ return -1; /* failure */
+}
+#endif /* INVASIVE_GET_USAGE */
+
+#ifdef __FreeBSD__
+/* The FreeBSD version of libusb doesn't have this funciton. In mainline
+ libusb, it's inlined in libusb.h. This function will bear a striking
+ resemblence to that one, because there's about one way to code it.
+
+ Note that the data parameter is Unicode in UTF-16LE encoding.
+ Return value is the number of bytes in data, or LIBUSB_ERROR_*.
+ */
+static inline int libusb_get_string_descriptor(libusb_device_handle *dev,
+ uint8_t descriptor_index, uint16_t lang_id,
+ unsigned char *data, int length)
+{
+ return libusb_control_transfer(dev,
+ LIBUSB_ENDPOINT_IN | 0x0, /* Endpoint 0 IN */
+ LIBUSB_REQUEST_GET_DESCRIPTOR,
+ (LIBUSB_DT_STRING << 8) | descriptor_index,
+ lang_id, data, (uint16_t) length, 1000);
+}
+
+#endif
+
+
+/* Get the first language the device says it reports. This comes from
+ USB string #0. */
+static uint16_t get_first_language(libusb_device_handle *dev)
+{
+ uint16_t buf[32];
+ int len;
+
+ /* Get the string from libusb. */
+ len = libusb_get_string_descriptor(dev,
+ 0x0, /* String ID */
+ 0x0, /* Language */
+ (unsigned char*)buf,
+ sizeof(buf));
+ if (len < 4)
+ return 0x0;
+
+ return buf[1]; /* First two bytes are len and descriptor type. */
+}
+
+static int is_language_supported(libusb_device_handle *dev, uint16_t lang)
+{
+ uint16_t buf[32];
+ int len;
+ int i;
+
+ /* Get the string from libusb. */
+ len = libusb_get_string_descriptor(dev,
+ 0x0, /* String ID */
+ 0x0, /* Language */
+ (unsigned char*)buf,
+ sizeof(buf));
+ if (len < 4)
+ return 0x0;
+
+
+ len /= 2; /* language IDs are two-bytes each. */
+ /* Start at index 1 because there are two bytes of protocol data. */
+ for (i = 1; i < len; i++) {
+ if (buf[i] == lang)
+ return 1;
+ }
+
+ return 0;
+}
+
+
+/* This function returns a newly allocated wide string containing the USB
+ device string numbered by the index. The returned string must be freed
+ by using free(). */
+static wchar_t *get_usb_string(libusb_device_handle *dev, uint8_t idx)
+{
+ char buf[512];
+ int len;
+ wchar_t *str = NULL;
+ wchar_t wbuf[256];
+
+ /* iconv variables */
+ iconv_t ic;
+ size_t inbytes;
+ size_t outbytes;
+ size_t res;
+#ifdef __FreeBSD__
+ const char *inptr;
+#else
+ char *inptr;
+#endif
+ char *outptr;
+
+ /* Determine which language to use. */
+ uint16_t lang;
+ lang = get_usb_code_for_current_locale();
+ if (!is_language_supported(dev, lang))
+ lang = get_first_language(dev);
+
+ /* Get the string from libusb. */
+ len = libusb_get_string_descriptor(dev,
+ idx,
+ lang,
+ (unsigned char*)buf,
+ sizeof(buf));
+ if (len < 0)
+ return NULL;
+
+ /* buf does not need to be explicitly NULL-terminated because
+ it is only passed into iconv() which does not need it. */
+
+ /* Initialize iconv. */
+ ic = iconv_open("WCHAR_T", "UTF-16LE");
+ if (ic == (iconv_t)-1) {
+ LOG("iconv_open() failed\n");
+ return NULL;
+ }
+
+ /* Convert to native wchar_t (UTF-32 on glibc/BSD systems).
+ Skip the first character (2-bytes). */
+ inptr = buf+2;
+ inbytes = len-2;
+ outptr = (char*) wbuf;
+ outbytes = sizeof(wbuf);
+ res = iconv(ic, &inptr, &inbytes, &outptr, &outbytes);
+ if (res == (size_t)-1) {
+ LOG("iconv() failed\n");
+ goto err;
+ }
+
+ /* Write the terminating NULL. */
+ wbuf[sizeof(wbuf)/sizeof(wbuf[0])-1] = 0x00000000;
+ if (outbytes >= sizeof(wbuf[0]))
+ *((wchar_t*)outptr) = 0x00000000;
+
+ /* Allocate and copy the string. */
+ str = wcsdup(wbuf);
+
+err:
+ iconv_close(ic);
+
+ return str;
+}
+
+static char *make_path(libusb_device *dev, int interface_number)
+{
+ char str[64];
+ snprintf(str, sizeof(str), "%04x:%04x:%02x",
+ libusb_get_bus_number(dev),
+ libusb_get_device_address(dev),
+ interface_number);
+ str[sizeof(str)-1] = '\0';
+
+ return strdup(str);
+}
+
+
+int HID_API_EXPORT hid_init(void)
+{
+ if (!usb_context) {
+ const char *locale;
+
+ /* Init Libusb */
+ if (libusb_init(&usb_context))
+ return -1;
+
+ /* Set the locale if it's not set. */
+ locale = setlocale(LC_CTYPE, NULL);
+ if (!locale)
+ setlocale(LC_CTYPE, "");
+ }
+
+ return 0;
+}
+
+int HID_API_EXPORT hid_exit(void)
+{
+ if (usb_context) {
+ libusb_exit(usb_context);
+ usb_context = NULL;
+ }
+
+ return 0;
+}
+
+struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
+{
+ libusb_device **devs;
+ libusb_device *dev;
+ libusb_device_handle *handle;
+ ssize_t num_devs;
+ int i = 0;
+
+ struct hid_device_info *root = NULL; /* return object */
+ struct hid_device_info *cur_dev = NULL;
+
+ if(hid_init() < 0)
+ return NULL;
+
+ num_devs = libusb_get_device_list(usb_context, &devs);
+ if (num_devs < 0)
+ return NULL;
+ while ((dev = devs[i++]) != NULL) {
+ struct libusb_device_descriptor desc;
+ struct libusb_config_descriptor *conf_desc = NULL;
+ int j, k;
+ int interface_num = 0;
+
+ int res = libusb_get_device_descriptor(dev, &desc);
+ unsigned short dev_vid = desc.idVendor;
+ unsigned short dev_pid = desc.idProduct;
+
+ res = libusb_get_active_config_descriptor(dev, &conf_desc);
+ if (res < 0)
+ libusb_get_config_descriptor(dev, 0, &conf_desc);
+ if (conf_desc) {
+ for (j = 0; j < conf_desc->bNumInterfaces; j++) {
+ const struct libusb_interface *intf = &conf_desc->interface[j];
+ for (k = 0; k < intf->num_altsetting; k++) {
+ const struct libusb_interface_descriptor *intf_desc;
+ intf_desc = &intf->altsetting[k];
+ if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) {
+ interface_num = intf_desc->bInterfaceNumber;
+
+ /* Check the VID/PID against the arguments */
+ if ((vendor_id == 0x0 || vendor_id == dev_vid) &&
+ (product_id == 0x0 || product_id == dev_pid)) {
+ struct hid_device_info *tmp;
+
+ /* VID/PID match. Create the record. */
+ tmp = calloc(1, sizeof(struct hid_device_info));
+ if (cur_dev) {
+ cur_dev->next = tmp;
+ }
+ else {
+ root = tmp;
+ }
+ cur_dev = tmp;
+
+ /* Fill out the record */
+ cur_dev->next = NULL;
+ cur_dev->path = make_path(dev, interface_num);
+
+ res = libusb_open(dev, &handle);
+
+ if (res >= 0) {
+ /* Serial Number */
+ if (desc.iSerialNumber > 0)
+ cur_dev->serial_number =
+ get_usb_string(handle, desc.iSerialNumber);
+
+ /* Manufacturer and Product strings */
+ if (desc.iManufacturer > 0)
+ cur_dev->manufacturer_string =
+ get_usb_string(handle, desc.iManufacturer);
+ if (desc.iProduct > 0)
+ cur_dev->product_string =
+ get_usb_string(handle, desc.iProduct);
+
+#ifdef INVASIVE_GET_USAGE
+{
+ /*
+ This section is removed because it is too
+ invasive on the system. Getting a Usage Page
+ and Usage requires parsing the HID Report
+ descriptor. Getting a HID Report descriptor
+ involves claiming the interface. Claiming the
+ interface involves detaching the kernel driver.
+ Detaching the kernel driver is hard on the system
+ because it will unclaim interfaces (if another
+ app has them claimed) and the re-attachment of
+ the driver will sometimes change /dev entry names.
+ It is for these reasons that this section is
+ #if 0. For composite devices, use the interface
+ field in the hid_device_info struct to distinguish
+ between interfaces. */
+ unsigned char data[256];
+#ifdef DETACH_KERNEL_DRIVER
+ int detached = 0;
+ /* Usage Page and Usage */
+ res = libusb_kernel_driver_active(handle, interface_num);
+ if (res == 1) {
+ res = libusb_detach_kernel_driver(handle, interface_num);
+ if (res < 0)
+ LOG("Couldn't detach kernel driver, even though a kernel driver was attached.");
+ else
+ detached = 1;
+ }
+#endif
+ res = libusb_claim_interface(handle, interface_num);
+ if (res >= 0) {
+ /* Get the HID Report Descriptor. */
+ res = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_INTERFACE, LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_REPORT << 8)|interface_num, 0, data, sizeof(data), 5000);
+ if (res >= 0) {
+ unsigned short page=0, usage=0;
+ /* Parse the usage and usage page
+ out of the report descriptor. */
+ get_usage(data, res, &page, &usage);
+ cur_dev->usage_page = page;
+ cur_dev->usage = usage;
+ }
+ else
+ LOG("libusb_control_transfer() for getting the HID report failed with %d\n", res);
+
+ /* Release the interface */
+ res = libusb_release_interface(handle, interface_num);
+ if (res < 0)
+ LOG("Can't release the interface.\n");
+ }
+ else
+ LOG("Can't claim interface %d\n", res);
+#ifdef DETACH_KERNEL_DRIVER
+ /* Re-attach kernel driver if necessary. */
+ if (detached) {
+ res = libusb_attach_kernel_driver(handle, interface_num);
+ if (res < 0)
+ LOG("Couldn't re-attach kernel driver.\n");
+ }
+#endif
+}
+#endif /* INVASIVE_GET_USAGE */
+
+ libusb_close(handle);
+ }
+ /* VID/PID */
+ cur_dev->vendor_id = dev_vid;
+ cur_dev->product_id = dev_pid;
+
+ /* Release Number */
+ cur_dev->release_number = desc.bcdDevice;
+
+ /* Interface Number */
+ cur_dev->interface_number = interface_num;
+ }
+ }
+ } /* altsettings */
+ } /* interfaces */
+ libusb_free_config_descriptor(conf_desc);
+ }
+ }
+
+ libusb_free_device_list(devs, 1);
+
+ return root;
+}
+
+void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
+{
+ struct hid_device_info *d = devs;
+ while (d) {
+ struct hid_device_info *next = d->next;
+ free(d->path);
+ free(d->serial_number);
+ free(d->manufacturer_string);
+ free(d->product_string);
+ free(d);
+ d = next;
+ }
+}
+
+hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
+{
+ struct hid_device_info *devs, *cur_dev;
+ const char *path_to_open = NULL;
+ hid_device *handle = NULL;
+
+ devs = hid_enumerate(vendor_id, product_id);
+ cur_dev = devs;
+ while (cur_dev) {
+ if (cur_dev->vendor_id == vendor_id &&
+ cur_dev->product_id == product_id) {
+ if (serial_number) {
+ if (wcscmp(serial_number, cur_dev->serial_number) == 0) {
+ path_to_open = cur_dev->path;
+ break;
+ }
+ }
+ else {
+ path_to_open = cur_dev->path;
+ break;
+ }
+ }
+ cur_dev = cur_dev->next;
+ }
+
+ if (path_to_open) {
+ /* Open the device */
+ handle = hid_open_path(path_to_open);
+ }
+
+ hid_free_enumeration(devs);
+
+ return handle;
+}
+
+static void read_callback(struct libusb_transfer *transfer)
+{
+ hid_device *dev = transfer->user_data;
+ int res;
+
+ if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
+
+ struct input_report *rpt = malloc(sizeof(*rpt));
+ rpt->data = malloc(transfer->actual_length);
+ memcpy(rpt->data, transfer->buffer, transfer->actual_length);
+ rpt->len = transfer->actual_length;
+ rpt->next = NULL;
+
+ pthread_mutex_lock(&dev->mutex);
+
+ /* Attach the new report object to the end of the list. */
+ if (dev->input_reports == NULL) {
+ /* The list is empty. Put it at the root. */
+ dev->input_reports = rpt;
+ pthread_cond_signal(&dev->condition);
+ }
+ else {
+ /* Find the end of the list and attach. */
+ struct input_report *cur = dev->input_reports;
+ int num_queued = 0;
+ while (cur->next != NULL) {
+ cur = cur->next;
+ num_queued++;
+ }
+ cur->next = rpt;
+
+ /* Pop one off if we've reached 30 in the queue. This
+ way we don't grow forever if the user never reads
+ anything from the device. */
+ if (num_queued > 30) {
+ return_data(dev, NULL, 0);
+ }
+ }
+ pthread_mutex_unlock(&dev->mutex);
+ }
+ else if (transfer->status == LIBUSB_TRANSFER_CANCELLED) {
+ dev->shutdown_thread = 1;
+ dev->cancelled = 1;
+ return;
+ }
+ else if (transfer->status == LIBUSB_TRANSFER_NO_DEVICE) {
+ dev->shutdown_thread = 1;
+ dev->cancelled = 1;
+ return;
+ }
+ else if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) {
+ //LOG("Timeout (normal)\n");
+ }
+ else {
+ LOG("Unknown transfer code: %d\n", transfer->status);
+ }
+
+ /* Re-submit the transfer object. */
+ res = libusb_submit_transfer(transfer);
+ if (res != 0) {
+ LOG("Unable to submit URB. libusb error code: %d\n", res);
+ dev->shutdown_thread = 1;
+ dev->cancelled = 1;
+ }
+}
+
+
+static void *read_thread(void *param)
+{
+ hid_device *dev = param;
+ unsigned char *buf;
+ const size_t length = dev->input_ep_max_packet_size;
+
+ /* Set up the transfer object. */
+ buf = malloc(length);
+ dev->transfer = libusb_alloc_transfer(0);
+ libusb_fill_interrupt_transfer(dev->transfer,
+ dev->device_handle,
+ dev->input_endpoint,
+ buf,
+ length,
+ read_callback,
+ dev,
+ 5000/*timeout*/);
+
+ /* Make the first submission. Further submissions are made
+ from inside read_callback() */
+ libusb_submit_transfer(dev->transfer);
+
+ /* Notify the main thread that the read thread is up and running. */
+ pthread_barrier_wait(&dev->barrier);
+
+ /* Handle all the events. */
+ while (!dev->shutdown_thread) {
+ int res;
+ res = libusb_handle_events(usb_context);
+ if (res < 0) {
+ /* There was an error. */
+ LOG("read_thread(): libusb reports error # %d\n", res);
+
+ /* Break out of this loop only on fatal error.*/
+ if (res != LIBUSB_ERROR_BUSY &&
+ res != LIBUSB_ERROR_TIMEOUT &&
+ res != LIBUSB_ERROR_OVERFLOW &&
+ res != LIBUSB_ERROR_INTERRUPTED) {
+ break;
+ }
+ }
+ }
+
+ /* Cancel any transfer that may be pending. This call will fail
+ if no transfers are pending, but that's OK. */
+ libusb_cancel_transfer(dev->transfer);
+
+ while (!dev->cancelled)
+ libusb_handle_events_completed(usb_context, &dev->cancelled);
+
+ /* Now that the read thread is stopping, Wake any threads which are
+ waiting on data (in hid_read_timeout()). Do this under a mutex to
+ make sure that a thread which is about to go to sleep waiting on
+ the condition acutally will go to sleep before the condition is
+ signaled. */
+ pthread_mutex_lock(&dev->mutex);
+ pthread_cond_broadcast(&dev->condition);
+ pthread_mutex_unlock(&dev->mutex);
+
+ /* The dev->transfer->buffer and dev->transfer objects are cleaned up
+ in hid_close(). They are not cleaned up here because this thread
+ could end either due to a disconnect or due to a user
+ call to hid_close(). In both cases the objects can be safely
+ cleaned up after the call to pthread_join() (in hid_close()), but
+ since hid_close() calls libusb_cancel_transfer(), on these objects,
+ they can not be cleaned up here. */
+
+ return NULL;
+}
+
+
+hid_device * HID_API_EXPORT hid_open_path(const char *path)
+{
+ hid_device *dev = NULL;
+
+ libusb_device **devs;
+ libusb_device *usb_dev;
+ int res;
+ int d = 0;
+ int good_open = 0;
+
+ if(hid_init() < 0)
+ return NULL;
+
+ dev = new_hid_device();
+
+ libusb_get_device_list(usb_context, &devs);
+ while ((usb_dev = devs[d++]) != NULL) {
+ struct libusb_device_descriptor desc;
+ struct libusb_config_descriptor *conf_desc = NULL;
+ int i,j,k;
+ libusb_get_device_descriptor(usb_dev, &desc);
+
+ if (libusb_get_active_config_descriptor(usb_dev, &conf_desc) < 0)
+ continue;
+ for (j = 0; j < conf_desc->bNumInterfaces; j++) {
+ const struct libusb_interface *intf = &conf_desc->interface[j];
+ for (k = 0; k < intf->num_altsetting; k++) {
+ const struct libusb_interface_descriptor *intf_desc;
+ intf_desc = &intf->altsetting[k];
+ if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) {
+ char *dev_path = make_path(usb_dev, intf_desc->bInterfaceNumber);
+ if (!strcmp(dev_path, path)) {
+ /* Matched Paths. Open this device */
+
+ /* OPEN HERE */
+ res = libusb_open(usb_dev, &dev->device_handle);
+ if (res < 0) {
+ LOG("can't open device\n");
+ free(dev_path);
+ break;
+ }
+ good_open = 1;
+#ifdef DETACH_KERNEL_DRIVER
+ /* Detach the kernel driver, but only if the
+ device is managed by the kernel */
+ if (libusb_kernel_driver_active(dev->device_handle, intf_desc->bInterfaceNumber) == 1) {
+ res = libusb_detach_kernel_driver(dev->device_handle, intf_desc->bInterfaceNumber);
+ if (res < 0) {
+ libusb_close(dev->device_handle);
+ LOG("Unable to detach Kernel Driver\n");
+ free(dev_path);
+ good_open = 0;
+ break;
+ }
+ }
+#endif
+ res = libusb_claim_interface(dev->device_handle, intf_desc->bInterfaceNumber);
+ if (res < 0) {
+ LOG("can't claim interface %d: %d\n", intf_desc->bInterfaceNumber, res);
+ free(dev_path);
+ libusb_close(dev->device_handle);
+ good_open = 0;
+ break;
+ }
+
+ /* Store off the string descriptor indexes */
+ dev->manufacturer_index = desc.iManufacturer;
+ dev->product_index = desc.iProduct;
+ dev->serial_index = desc.iSerialNumber;
+
+ /* Store off the interface number */
+ dev->interface = intf_desc->bInterfaceNumber;
+
+ /* Find the INPUT and OUTPUT endpoints. An
+ OUTPUT endpoint is not required. */
+ for (i = 0; i < intf_desc->bNumEndpoints; i++) {
+ const struct libusb_endpoint_descriptor *ep
+ = &intf_desc->endpoint[i];
+
+ /* Determine the type and direction of this
+ endpoint. */
+ int is_interrupt =
+ (ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
+ == LIBUSB_TRANSFER_TYPE_INTERRUPT;
+ int is_output =
+ (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
+ == LIBUSB_ENDPOINT_OUT;
+ int is_input =
+ (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
+ == LIBUSB_ENDPOINT_IN;
+
+ /* Decide whether to use it for intput or output. */
+ if (dev->input_endpoint == 0 &&
+ is_interrupt && is_input) {
+ /* Use this endpoint for INPUT */
+ dev->input_endpoint = ep->bEndpointAddress;
+ dev->input_ep_max_packet_size = ep->wMaxPacketSize;
+ }
+ if (dev->output_endpoint == 0 &&
+ is_interrupt && is_output) {
+ /* Use this endpoint for OUTPUT */
+ dev->output_endpoint = ep->bEndpointAddress;
+ }
+ }
+
+ pthread_create(&dev->thread, NULL, read_thread, dev);
+
+ /* Wait here for the read thread to be initialized. */
+ pthread_barrier_wait(&dev->barrier);
+
+ }
+ free(dev_path);
+ }
+ }
+ }
+ libusb_free_config_descriptor(conf_desc);
+
+ }
+
+ libusb_free_device_list(devs, 1);
+
+ /* If we have a good handle, return it. */
+ if (good_open) {
+ return dev;
+ }
+ else {
+ /* Unable to open any devices. */
+ free_hid_device(dev);
+ return NULL;
+ }
+}
+
+
+int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
+{
+ int res;
+ int report_number = data[0];
+ int skipped_report_id = 0;
+
+ if (report_number == 0x0) {
+ data++;
+ length--;
+ skipped_report_id = 1;
+ }
+
+
+ if (dev->output_endpoint <= 0) {
+ /* No interrput out endpoint. Use the Control Endpoint */
+ res = libusb_control_transfer(dev->device_handle,
+ LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT,
+ 0x09/*HID Set_Report*/,
+ (2/*HID output*/ << 8) | report_number,
+ dev->interface,
+ (unsigned char *)data, length,
+ 1000/*timeout millis*/);
+
+ if (res < 0)
+ return -1;
+
+ if (skipped_report_id)
+ length++;
+
+ return length;
+ }
+ else {
+ /* Use the interrupt out endpoint */
+ int actual_length;
+ res = libusb_interrupt_transfer(dev->device_handle,
+ dev->output_endpoint,
+ (unsigned char*)data,
+ length,
+ &actual_length, 1000);
+
+ if (res < 0)
+ return -1;
+
+ if (skipped_report_id)
+ actual_length++;
+
+ return actual_length;
+ }
+}
+
+/* Helper function, to simplify hid_read().
+ This should be called with dev->mutex locked. */
+static int return_data(hid_device *dev, unsigned char *data, size_t length)
+{
+ /* Copy the data out of the linked list item (rpt) into the
+ return buffer (data), and delete the liked list item. */
+ struct input_report *rpt = dev->input_reports;
+ size_t len = (length < rpt->len)? length: rpt->len;
+ if (len > 0)
+ memcpy(data, rpt->data, len);
+ dev->input_reports = rpt->next;
+ free(rpt->data);
+ free(rpt);
+ return len;
+}
+
+static void cleanup_mutex(void *param)
+{
+ hid_device *dev = param;
+ pthread_mutex_unlock(&dev->mutex);
+}
+
+
+int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
+{
+ int bytes_read = -1;
+
+#if 0
+ int transferred;
+ int res = libusb_interrupt_transfer(dev->device_handle, dev->input_endpoint, data, length, &transferred, 5000);
+ LOG("transferred: %d\n", transferred);
+ return transferred;
+#endif
+
+ pthread_mutex_lock(&dev->mutex);
+ pthread_cleanup_push(&cleanup_mutex, dev);
+
+ /* There's an input report queued up. Return it. */
+ if (dev->input_reports) {
+ /* Return the first one */
+ bytes_read = return_data(dev, data, length);
+ goto ret;
+ }
+
+ if (dev->shutdown_thread) {
+ /* This means the device has been disconnected.
+ An error code of -1 should be returned. */
+ bytes_read = -1;
+ goto ret;
+ }
+
+ if (milliseconds == -1) {
+ /* Blocking */
+ while (!dev->input_reports && !dev->shutdown_thread) {
+ pthread_cond_wait(&dev->condition, &dev->mutex);
+ }
+ if (dev->input_reports) {
+ bytes_read = return_data(dev, data, length);
+ }
+ }
+ else if (milliseconds > 0) {
+ /* Non-blocking, but called with timeout. */
+ int res;
+ struct timespec ts;
+ clock_gettime(CLOCK_REALTIME, &ts);
+ ts.tv_sec += milliseconds / 1000;
+ ts.tv_nsec += (milliseconds % 1000) * 1000000;
+ if (ts.tv_nsec >= 1000000000L) {
+ ts.tv_sec++;
+ ts.tv_nsec -= 1000000000L;
+ }
+
+ while (!dev->input_reports && !dev->shutdown_thread) {
+ res = pthread_cond_timedwait(&dev->condition, &dev->mutex, &ts);
+ if (res == 0) {
+ if (dev->input_reports) {
+ bytes_read = return_data(dev, data, length);
+ break;
+ }
+
+ /* If we're here, there was a spurious wake up
+ or the read thread was shutdown. Run the
+ loop again (ie: don't break). */
+ }
+ else if (res == ETIMEDOUT) {
+ /* Timed out. */
+ bytes_read = 0;
+ break;
+ }
+ else {
+ /* Error. */
+ bytes_read = -1;
+ break;
+ }
+ }
+ }
+ else {
+ /* Purely non-blocking */
+ bytes_read = 0;
+ }
+
+ret:
+ pthread_mutex_unlock(&dev->mutex);
+ pthread_cleanup_pop(0);
+
+ return bytes_read;
+}
+
+int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
+{
+ return hid_read_timeout(dev, data, length, dev->blocking ? -1 : 0);
+}
+
+int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
+{
+ dev->blocking = !nonblock;
+
+ return 0;
+}
+
+
+int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
+{
+ int res = -1;
+ int skipped_report_id = 0;
+ int report_number = data[0];
+
+ if (report_number == 0x0) {
+ data++;
+ length--;
+ skipped_report_id = 1;
+ }
+
+ res = libusb_control_transfer(dev->device_handle,
+ LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT,
+ 0x09/*HID set_report*/,
+ (3/*HID feature*/ << 8) | report_number,
+ dev->interface,
+ (unsigned char *)data, length,
+ 1000/*timeout millis*/);
+
+ if (res < 0)
+ return -1;
+
+ /* Account for the report ID */
+ if (skipped_report_id)
+ length++;
+
+ return length;
+}
+
+int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
+{
+ int res = -1;
+ int skipped_report_id = 0;
+ int report_number = data[0];
+
+ if (report_number == 0x0) {
+ /* Offset the return buffer by 1, so that the report ID
+ will remain in byte 0. */
+ data++;
+ length--;
+ skipped_report_id = 1;
+ }
+ res = libusb_control_transfer(dev->device_handle,
+ LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_IN,
+ 0x01/*HID get_report*/,
+ (3/*HID feature*/ << 8) | report_number,
+ dev->interface,
+ (unsigned char *)data, length,
+ 1000/*timeout millis*/);
+
+ if (res < 0)
+ return -1;
+
+ if (skipped_report_id)
+ res++;
+
+ return res;
+}
+
+
+void HID_API_EXPORT hid_close(hid_device *dev)
+{
+ if (!dev)
+ return;
+
+ /* Cause read_thread() to stop. */
+ dev->shutdown_thread = 1;
+ libusb_cancel_transfer(dev->transfer);
+
+ /* Wait for read_thread() to end. */
+ pthread_join(dev->thread, NULL);
+
+ /* Clean up the Transfer objects allocated in read_thread(). */
+ free(dev->transfer->buffer);
+ libusb_free_transfer(dev->transfer);
+
+ /* release the interface */
+ libusb_release_interface(dev->device_handle, dev->interface);
+
+ /* Close the handle */
+ libusb_close(dev->device_handle);
+
+ /* Clear out the queue of received reports. */
+ pthread_mutex_lock(&dev->mutex);
+ while (dev->input_reports) {
+ return_data(dev, NULL, 0);
+ }
+ pthread_mutex_unlock(&dev->mutex);
+
+ free_hid_device(dev);
+}
+
+
+int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
+{
+ return hid_get_indexed_string(dev, dev->manufacturer_index, string, maxlen);
+}
+
+int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
+{
+ return hid_get_indexed_string(dev, dev->product_index, string, maxlen);
+}
+
+int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
+{
+ return hid_get_indexed_string(dev, dev->serial_index, string, maxlen);
+}
+
+int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
+{
+ wchar_t *str;
+
+ str = get_usb_string(dev->device_handle, string_index);
+ if (str) {
+ wcsncpy(string, str, maxlen);
+ string[maxlen-1] = L'\0';
+ free(str);
+ return 0;
+ }
+ else
+ return -1;
+}
+
+
+HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
+{
+ return NULL;
+}
+
+
+struct lang_map_entry {
+ const char *name;
+ const char *string_code;
+ uint16_t usb_code;
+};
+
+#define LANG(name,code,usb_code) { name, code, usb_code }
+static struct lang_map_entry lang_map[] = {
+ LANG("Afrikaans", "af", 0x0436),
+ LANG("Albanian", "sq", 0x041C),
+ LANG("Arabic - United Arab Emirates", "ar_ae", 0x3801),
+ LANG("Arabic - Bahrain", "ar_bh", 0x3C01),
+ LANG("Arabic - Algeria", "ar_dz", 0x1401),
+ LANG("Arabic - Egypt", "ar_eg", 0x0C01),
+ LANG("Arabic - Iraq", "ar_iq", 0x0801),
+ LANG("Arabic - Jordan", "ar_jo", 0x2C01),
+ LANG("Arabic - Kuwait", "ar_kw", 0x3401),
+ LANG("Arabic - Lebanon", "ar_lb", 0x3001),
+ LANG("Arabic - Libya", "ar_ly", 0x1001),
+ LANG("Arabic - Morocco", "ar_ma", 0x1801),
+ LANG("Arabic - Oman", "ar_om", 0x2001),
+ LANG("Arabic - Qatar", "ar_qa", 0x4001),
+ LANG("Arabic - Saudi Arabia", "ar_sa", 0x0401),
+ LANG("Arabic - Syria", "ar_sy", 0x2801),
+ LANG("Arabic - Tunisia", "ar_tn", 0x1C01),
+ LANG("Arabic - Yemen", "ar_ye", 0x2401),
+ LANG("Armenian", "hy", 0x042B),
+ LANG("Azeri - Latin", "az_az", 0x042C),
+ LANG("Azeri - Cyrillic", "az_az", 0x082C),
+ LANG("Basque", "eu", 0x042D),
+ LANG("Belarusian", "be", 0x0423),
+ LANG("Bulgarian", "bg", 0x0402),
+ LANG("Catalan", "ca", 0x0403),
+ LANG("Chinese - China", "zh_cn", 0x0804),
+ LANG("Chinese - Hong Kong SAR", "zh_hk", 0x0C04),
+ LANG("Chinese - Macau SAR", "zh_mo", 0x1404),
+ LANG("Chinese - Singapore", "zh_sg", 0x1004),
+ LANG("Chinese - Taiwan", "zh_tw", 0x0404),
+ LANG("Croatian", "hr", 0x041A),
+ LANG("Czech", "cs", 0x0405),
+ LANG("Danish", "da", 0x0406),
+ LANG("Dutch - Netherlands", "nl_nl", 0x0413),
+ LANG("Dutch - Belgium", "nl_be", 0x0813),
+ LANG("English - Australia", "en_au", 0x0C09),
+ LANG("English - Belize", "en_bz", 0x2809),
+ LANG("English - Canada", "en_ca", 0x1009),
+ LANG("English - Caribbean", "en_cb", 0x2409),
+ LANG("English - Ireland", "en_ie", 0x1809),
+ LANG("English - Jamaica", "en_jm", 0x2009),
+ LANG("English - New Zealand", "en_nz", 0x1409),
+ LANG("English - Phillippines", "en_ph", 0x3409),
+ LANG("English - Southern Africa", "en_za", 0x1C09),
+ LANG("English - Trinidad", "en_tt", 0x2C09),
+ LANG("English - Great Britain", "en_gb", 0x0809),
+ LANG("English - United States", "en_us", 0x0409),
+ LANG("Estonian", "et", 0x0425),
+ LANG("Farsi", "fa", 0x0429),
+ LANG("Finnish", "fi", 0x040B),
+ LANG("Faroese", "fo", 0x0438),
+ LANG("French - France", "fr_fr", 0x040C),
+ LANG("French - Belgium", "fr_be", 0x080C),
+ LANG("French - Canada", "fr_ca", 0x0C0C),
+ LANG("French - Luxembourg", "fr_lu", 0x140C),
+ LANG("French - Switzerland", "fr_ch", 0x100C),
+ LANG("Gaelic - Ireland", "gd_ie", 0x083C),
+ LANG("Gaelic - Scotland", "gd", 0x043C),
+ LANG("German - Germany", "de_de", 0x0407),
+ LANG("German - Austria", "de_at", 0x0C07),
+ LANG("German - Liechtenstein", "de_li", 0x1407),
+ LANG("German - Luxembourg", "de_lu", 0x1007),
+ LANG("German - Switzerland", "de_ch", 0x0807),
+ LANG("Greek", "el", 0x0408),
+ LANG("Hebrew", "he", 0x040D),
+ LANG("Hindi", "hi", 0x0439),
+ LANG("Hungarian", "hu", 0x040E),
+ LANG("Icelandic", "is", 0x040F),
+ LANG("Indonesian", "id", 0x0421),
+ LANG("Italian - Italy", "it_it", 0x0410),
+ LANG("Italian - Switzerland", "it_ch", 0x0810),
+ LANG("Japanese", "ja", 0x0411),
+ LANG("Korean", "ko", 0x0412),
+ LANG("Latvian", "lv", 0x0426),
+ LANG("Lithuanian", "lt", 0x0427),
+ LANG("F.Y.R.O. Macedonia", "mk", 0x042F),
+ LANG("Malay - Malaysia", "ms_my", 0x043E),
+ LANG("Malay – Brunei", "ms_bn", 0x083E),
+ LANG("Maltese", "mt", 0x043A),
+ LANG("Marathi", "mr", 0x044E),
+ LANG("Norwegian - Bokml", "no_no", 0x0414),
+ LANG("Norwegian - Nynorsk", "no_no", 0x0814),
+ LANG("Polish", "pl", 0x0415),
+ LANG("Portuguese - Portugal", "pt_pt", 0x0816),
+ LANG("Portuguese - Brazil", "pt_br", 0x0416),
+ LANG("Raeto-Romance", "rm", 0x0417),
+ LANG("Romanian - Romania", "ro", 0x0418),
+ LANG("Romanian - Republic of Moldova", "ro_mo", 0x0818),
+ LANG("Russian", "ru", 0x0419),
+ LANG("Russian - Republic of Moldova", "ru_mo", 0x0819),
+ LANG("Sanskrit", "sa", 0x044F),
+ LANG("Serbian - Cyrillic", "sr_sp", 0x0C1A),
+ LANG("Serbian - Latin", "sr_sp", 0x081A),
+ LANG("Setsuana", "tn", 0x0432),
+ LANG("Slovenian", "sl", 0x0424),
+ LANG("Slovak", "sk", 0x041B),
+ LANG("Sorbian", "sb", 0x042E),
+ LANG("Spanish - Spain (Traditional)", "es_es", 0x040A),
+ LANG("Spanish - Argentina", "es_ar", 0x2C0A),
+ LANG("Spanish - Bolivia", "es_bo", 0x400A),
+ LANG("Spanish - Chile", "es_cl", 0x340A),
+ LANG("Spanish - Colombia", "es_co", 0x240A),
+ LANG("Spanish - Costa Rica", "es_cr", 0x140A),
+ LANG("Spanish - Dominican Republic", "es_do", 0x1C0A),
+ LANG("Spanish - Ecuador", "es_ec", 0x300A),
+ LANG("Spanish - Guatemala", "es_gt", 0x100A),
+ LANG("Spanish - Honduras", "es_hn", 0x480A),
+ LANG("Spanish - Mexico", "es_mx", 0x080A),
+ LANG("Spanish - Nicaragua", "es_ni", 0x4C0A),
+ LANG("Spanish - Panama", "es_pa", 0x180A),
+ LANG("Spanish - Peru", "es_pe", 0x280A),
+ LANG("Spanish - Puerto Rico", "es_pr", 0x500A),
+ LANG("Spanish - Paraguay", "es_py", 0x3C0A),
+ LANG("Spanish - El Salvador", "es_sv", 0x440A),
+ LANG("Spanish - Uruguay", "es_uy", 0x380A),
+ LANG("Spanish - Venezuela", "es_ve", 0x200A),
+ LANG("Southern Sotho", "st", 0x0430),
+ LANG("Swahili", "sw", 0x0441),
+ LANG("Swedish - Sweden", "sv_se", 0x041D),
+ LANG("Swedish - Finland", "sv_fi", 0x081D),
+ LANG("Tamil", "ta", 0x0449),
+ LANG("Tatar", "tt", 0X0444),
+ LANG("Thai", "th", 0x041E),
+ LANG("Turkish", "tr", 0x041F),
+ LANG("Tsonga", "ts", 0x0431),
+ LANG("Ukrainian", "uk", 0x0422),
+ LANG("Urdu", "ur", 0x0420),
+ LANG("Uzbek - Cyrillic", "uz_uz", 0x0843),
+ LANG("Uzbek – Latin", "uz_uz", 0x0443),
+ LANG("Vietnamese", "vi", 0x042A),
+ LANG("Xhosa", "xh", 0x0434),
+ LANG("Yiddish", "yi", 0x043D),
+ LANG("Zulu", "zu", 0x0435),
+ LANG(NULL, NULL, 0x0),
+};
+
+uint16_t get_usb_code_for_current_locale(void)
+{
+ char *locale;
+ char search_string[64];
+ char *ptr;
+ struct lang_map_entry *lang;
+
+ /* Get the current locale. */
+ locale = setlocale(0, NULL);
+ if (!locale)
+ return 0x0;
+
+ /* Make a copy of the current locale string. */
+ strncpy(search_string, locale, sizeof(search_string));
+ search_string[sizeof(search_string)-1] = '\0';
+
+ /* Chop off the encoding part, and make it lower case. */
+ ptr = search_string;
+ while (*ptr) {
+ *ptr = tolower(*ptr);
+ if (*ptr == '.') {
+ *ptr = '\0';
+ break;
+ }
+ ptr++;
+ }
+
+ /* Find the entry which matches the string code of our locale. */
+ lang = lang_map;
+ while (lang->string_code) {
+ if (!strcmp(lang->string_code, search_string)) {
+ return lang->usb_code;
+ }
+ lang++;
+ }
+
+ /* There was no match. Find with just the language only. */
+ /* Chop off the variant. Chop it off at the '_'. */
+ ptr = search_string;
+ while (*ptr) {
+ *ptr = tolower(*ptr);
+ if (*ptr == '_') {
+ *ptr = '\0';
+ break;
+ }
+ ptr++;
+ }
+
+#if 0 /* TODO: Do we need this? */
+ /* Find the entry which matches the string code of our language. */
+ lang = lang_map;
+ while (lang->string_code) {
+ if (!strcmp(lang->string_code, search_string)) {
+ return lang->usb_code;
+ }
+ lang++;
+ }
+#endif
+
+ /* Found nothing. */
+ return 0x0;
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/src/libambit/hid.c b/src/libambit/hid.c
new file mode 100644
index 0000000..bb206e8
--- /dev/null
+++ b/src/libambit/hid.c
@@ -0,0 +1,795 @@
+/*******************************************************
+ HIDAPI - Multi-Platform library for
+ communication with HID devices.
+
+ Alan Ott
+ Signal 11 Software
+
+ 8/22/2009
+ Linux Version - 6/2/2009
+
+ Copyright 2009, All Rights Reserved.
+
+ At the discretion of the user of this library,
+ this software may be licensed under the terms of the
+ GNU General Public License v3, a BSD-Style license, or the
+ original HIDAPI license as outlined in the LICENSE.txt,
+ LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
+ files located at the root of the source distribution.
+ These files may also be found in the public source
+ code repository located at:
+ http://github.com/signal11/hidapi .
+********************************************************/
+
+/* C */
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <locale.h>
+#include <errno.h>
+
+/* Unix */
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/ioctl.h>
+#include <sys/utsname.h>
+#include <fcntl.h>
+#include <poll.h>
+
+/* Linux */
+#include <linux/hidraw.h>
+#include <linux/version.h>
+#include <linux/input.h>
+#include <libudev.h>
+
+#include "hidapi.h"
+
+/* Definitions from linux/hidraw.h. Since these are new, some distros
+ may not have header files which contain them. */
+#ifndef HIDIOCSFEATURE
+#define HIDIOCSFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x06, len)
+#endif
+#ifndef HIDIOCGFEATURE
+#define HIDIOCGFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x07, len)
+#endif
+
+
+/* USB HID device property names */
+const char *device_string_names[] = {
+ "manufacturer",
+ "product",
+ "serial",
+};
+
+/* Symbolic names for the properties above */
+enum device_string_id {
+ DEVICE_STRING_MANUFACTURER,
+ DEVICE_STRING_PRODUCT,
+ DEVICE_STRING_SERIAL,
+
+ DEVICE_STRING_COUNT,
+};
+
+struct hid_device_ {
+ int device_handle;
+ int blocking;
+ int uses_numbered_reports;
+};
+
+
+static __u32 kernel_version = 0;
+
+static __u32 detect_kernel_version(void)
+{
+ struct utsname name;
+ int major, minor, release;
+ int ret;
+
+ uname(&name);
+ ret = sscanf(name.release, "%d.%d.%d", &major, &minor, &release);
+ if (ret == 3) {
+ return KERNEL_VERSION(major, minor, release);
+ }
+
+ ret = sscanf(name.release, "%d.%d", &major, &minor);
+ if (ret == 2) {
+ return KERNEL_VERSION(major, minor, 0);
+ }
+
+ printf("Couldn't determine kernel version from version string \"%s\"\n", name.release);
+ return 0;
+}
+
+static hid_device *new_hid_device(void)
+{
+ hid_device *dev = calloc(1, sizeof(hid_device));
+ dev->device_handle = -1;
+ dev->blocking = 1;
+ dev->uses_numbered_reports = 0;
+
+ return dev;
+}
+
+
+/* The caller must free the returned string with free(). */
+static wchar_t *utf8_to_wchar_t(const char *utf8)
+{
+ wchar_t *ret = NULL;
+
+ if (utf8) {
+ size_t wlen = mbstowcs(NULL, utf8, 0);
+ if ((size_t) -1 == wlen) {
+ return wcsdup(L"");
+ }
+ ret = calloc(wlen+1, sizeof(wchar_t));
+ mbstowcs(ret, utf8, wlen+1);
+ ret[wlen] = 0x0000;
+ }
+
+ return ret;
+}
+
+/* Get an attribute value from a udev_device and return it as a whar_t
+ string. The returned string must be freed with free() when done.*/
+static wchar_t *copy_udev_string(struct udev_device *dev, const char *udev_name)
+{
+ return utf8_to_wchar_t(udev_device_get_sysattr_value(dev, udev_name));
+}
+
+/* uses_numbered_reports() returns 1 if report_descriptor describes a device
+ which contains numbered reports. */
+static int uses_numbered_reports(__u8 *report_descriptor, __u32 size) {
+ unsigned int i = 0;
+ int size_code;
+ int data_len, key_size;
+
+ while (i < size) {
+ int key = report_descriptor[i];
+
+ /* Check for the Report ID key */
+ if (key == 0x85/*Report ID*/) {
+ /* This device has a Report ID, which means it uses
+ numbered reports. */
+ return 1;
+ }
+
+ //printf("key: %02hhx\n", key);
+
+ if ((key & 0xf0) == 0xf0) {
+ /* This is a Long Item. The next byte contains the
+ length of the data section (value) for this key.
+ See the HID specification, version 1.11, section
+ 6.2.2.3, titled "Long Items." */
+ if (i+1 < size)
+ data_len = report_descriptor[i+1];
+ else
+ data_len = 0; /* malformed report */
+ key_size = 3;
+ }
+ else {
+ /* This is a Short Item. The bottom two bits of the
+ key contain the size code for the data section
+ (value) for this key. Refer to the HID
+ specification, version 1.11, section 6.2.2.2,
+ titled "Short Items." */
+ size_code = key & 0x3;
+ switch (size_code) {
+ case 0:
+ case 1:
+ case 2:
+ data_len = size_code;
+ break;
+ case 3:
+ data_len = 4;
+ break;
+ default:
+ /* Can't ever happen since size_code is & 0x3 */
+ data_len = 0;
+ break;
+ };
+ key_size = 1;
+ }
+
+ /* Skip over this key and it's associated data */
+ i += data_len + key_size;
+ }
+
+ /* Didn't find a Report ID key. Device doesn't use numbered reports. */
+ return 0;
+}
+
+/*
+ * The caller is responsible for free()ing the (newly-allocated) character
+ * strings pointed to by serial_number_utf8 and product_name_utf8 after use.
+ */
+static int
+parse_uevent_info(const char *uevent, int *bus_type,
+ unsigned short *vendor_id, unsigned short *product_id,
+ char **serial_number_utf8, char **product_name_utf8)
+{
+ char *tmp = strdup(uevent);
+ char *saveptr = NULL;
+ char *line;
+ char *key;
+ char *value;
+
+ int found_id = 0;
+ int found_serial = 0;
+ int found_name = 0;
+
+ line = strtok_r(tmp, "\n", &saveptr);
+ while (line != NULL) {
+ /* line: "KEY=value" */
+ key = line;
+ value = strchr(line, '=');
+ if (!value) {
+ goto next_line;
+ }
+ *value = '\0';
+ value++;
+
+ if (strcmp(key, "HID_ID") == 0) {
+ /**
+ * type vendor product
+ * HID_ID=0003:000005AC:00008242
+ **/
+ int ret = sscanf(value, "%x:%hx:%hx", bus_type, vendor_id, product_id);
+ if (ret == 3) {
+ found_id = 1;
+ }
+ } else if (strcmp(key, "HID_NAME") == 0) {
+ /* The caller has to free the product name */
+ *product_name_utf8 = strdup(value);
+ found_name = 1;
+ } else if (strcmp(key, "HID_UNIQ") == 0) {
+ /* The caller has to free the serial number */
+ *serial_number_utf8 = strdup(value);
+ found_serial = 1;
+ }
+
+next_line:
+ line = strtok_r(NULL, "\n", &saveptr);
+ }
+
+ free(tmp);
+ return (found_id && found_name && found_serial);
+}
+
+
+static int get_device_string(hid_device *dev, enum device_string_id key, wchar_t *string, size_t maxlen)
+{
+ struct udev *udev;
+ struct udev_device *udev_dev, *parent, *hid_dev;
+ struct stat s;
+ int ret = -1;
+ char *serial_number_utf8 = NULL;
+ char *product_name_utf8 = NULL;
+
+ /* Create the udev object */
+ udev = udev_new();
+ if (!udev) {
+ printf("Can't create udev\n");
+ return -1;
+ }
+
+ /* Get the dev_t (major/minor numbers) from the file handle. */
+ fstat(dev->device_handle, &s);
+ /* Open a udev device from the dev_t. 'c' means character device. */
+ udev_dev = udev_device_new_from_devnum(udev, 'c', s.st_rdev);
+ if (udev_dev) {
+ hid_dev = udev_device_get_parent_with_subsystem_devtype(
+ udev_dev,
+ "hid",
+ NULL);
+ if (hid_dev) {
+ unsigned short dev_vid;
+ unsigned short dev_pid;
+ int bus_type;
+ size_t retm;
+
+ ret = parse_uevent_info(
+ udev_device_get_sysattr_value(hid_dev, "uevent"),
+ &bus_type,
+ &dev_vid,
+ &dev_pid,
+ &serial_number_utf8,
+ &product_name_utf8);
+
+ if (bus_type == BUS_BLUETOOTH) {
+ switch (key) {
+ case DEVICE_STRING_MANUFACTURER:
+ wcsncpy(string, L"", maxlen);
+ ret = 0;
+ break;
+ case DEVICE_STRING_PRODUCT:
+ retm = mbstowcs(string, product_name_utf8, maxlen);
+ ret = (retm == (size_t)-1)? -1: 0;
+ break;
+ case DEVICE_STRING_SERIAL:
+ retm = mbstowcs(string, serial_number_utf8, maxlen);
+ ret = (retm == (size_t)-1)? -1: 0;
+ break;
+ case DEVICE_STRING_COUNT:
+ default:
+ ret = -1;
+ break;
+ }
+ }
+ else {
+ /* This is a USB device. Find its parent USB Device node. */
+ parent = udev_device_get_parent_with_subsystem_devtype(
+ udev_dev,
+ "usb",
+ "usb_device");
+ if (parent) {
+ const char *str;
+ const char *key_str = NULL;
+
+ if (key >= 0 && key < DEVICE_STRING_COUNT) {
+ key_str = device_string_names[key];
+ } else {
+ ret = -1;
+ goto end;
+ }
+
+ str = udev_device_get_sysattr_value(parent, key_str);
+ if (str) {
+ /* Convert the string from UTF-8 to wchar_t */
+ retm = mbstowcs(string, str, maxlen);
+ ret = (retm == (size_t)-1)? -1: 0;
+ goto end;
+ }
+ }
+ }
+ }
+ }
+
+end:
+ free(serial_number_utf8);
+ free(product_name_utf8);
+
+ udev_device_unref(udev_dev);
+ /* parent and hid_dev don't need to be (and can't be) unref'd.
+ I'm not sure why, but they'll throw double-free() errors. */
+ udev_unref(udev);
+
+ return ret;
+}
+
+int HID_API_EXPORT hid_init(void)
+{
+ const char *locale;
+
+ /* Set the locale if it's not set. */
+ locale = setlocale(LC_CTYPE, NULL);
+ if (!locale)
+ setlocale(LC_CTYPE, "");
+
+ kernel_version = detect_kernel_version();
+
+ return 0;
+}
+
+int HID_API_EXPORT hid_exit(void)
+{
+ /* Nothing to do for this in the Linux/hidraw implementation. */
+ return 0;
+}
+
+
+struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
+{
+ struct udev *udev;
+ struct udev_enumerate *enumerate;
+ struct udev_list_entry *devices, *dev_list_entry;
+
+ struct hid_device_info *root = NULL; /* return object */
+ struct hid_device_info *cur_dev = NULL;
+ struct hid_device_info *prev_dev = NULL; /* previous device */
+
+ hid_init();
+
+ /* Create the udev object */
+ udev = udev_new();
+ if (!udev) {
+ printf("Can't create udev\n");
+ return NULL;
+ }
+
+ /* Create a list of the devices in the 'hidraw' subsystem. */
+ enumerate = udev_enumerate_new(udev);
+ udev_enumerate_add_match_subsystem(enumerate, "hidraw");
+ udev_enumerate_scan_devices(enumerate);
+ devices = udev_enumerate_get_list_entry(enumerate);
+ /* For each item, see if it matches the vid/pid, and if so
+ create a udev_device record for it */
+ udev_list_entry_foreach(dev_list_entry, devices) {
+ const char *sysfs_path;
+ const char *dev_path;
+ const char *str;
+ struct udev_device *raw_dev; /* The device's hidraw udev node. */
+ struct udev_device *hid_dev; /* The device's HID udev node. */
+ struct udev_device *usb_dev; /* The device's USB udev node. */
+ struct udev_device *intf_dev; /* The device's interface (in the USB sense). */
+ unsigned short dev_vid;
+ unsigned short dev_pid;
+ char *serial_number_utf8 = NULL;
+ char *product_name_utf8 = NULL;
+ int bus_type;
+ int result;
+
+ /* Get the filename of the /sys entry for the device
+ and create a udev_device object (dev) representing it */
+ sysfs_path = udev_list_entry_get_name(dev_list_entry);
+ raw_dev = udev_device_new_from_syspath(udev, sysfs_path);
+ dev_path = udev_device_get_devnode(raw_dev);
+
+ hid_dev = udev_device_get_parent_with_subsystem_devtype(
+ raw_dev,
+ "hid",
+ NULL);
+
+ if (!hid_dev) {
+ /* Unable to find parent hid device. */
+ goto next;
+ }
+
+ result = parse_uevent_info(
+ udev_device_get_sysattr_value(hid_dev, "uevent"),
+ &bus_type,
+ &dev_vid,
+ &dev_pid,
+ &serial_number_utf8,
+ &product_name_utf8);
+
+ if (!result) {
+ /* parse_uevent_info() failed for at least one field. */
+ goto next;
+ }
+
+ if (bus_type != BUS_USB && bus_type != BUS_BLUETOOTH) {
+ /* We only know how to handle USB and BT devices. */
+ goto next;
+ }
+
+ /* Check the VID/PID against the arguments */
+ if ((vendor_id == 0x0 || vendor_id == dev_vid) &&
+ (product_id == 0x0 || product_id == dev_pid)) {
+ struct hid_device_info *tmp;
+
+ /* VID/PID match. Create the record. */
+ tmp = malloc(sizeof(struct hid_device_info));
+ if (cur_dev) {
+ cur_dev->next = tmp;
+ }
+ else {
+ root = tmp;
+ }
+ prev_dev = cur_dev;
+ cur_dev = tmp;
+
+ /* Fill out the record */
+ cur_dev->next = NULL;
+ cur_dev->path = dev_path? strdup(dev_path): NULL;
+
+ /* VID/PID */
+ cur_dev->vendor_id = dev_vid;
+ cur_dev->product_id = dev_pid;
+
+ /* Serial Number */
+ cur_dev->serial_number = utf8_to_wchar_t(serial_number_utf8);
+
+ /* Release Number */
+ cur_dev->release_number = 0x0;
+
+ /* Interface Number */
+ cur_dev->interface_number = -1;
+
+ switch (bus_type) {
+ case BUS_USB:
+ /* The device pointed to by raw_dev contains information about
+ the hidraw device. In order to get information about the
+ USB device, get the parent device with the
+ subsystem/devtype pair of "usb"/"usb_device". This will
+ be several levels up the tree, but the function will find
+ it. */
+ usb_dev = udev_device_get_parent_with_subsystem_devtype(
+ raw_dev,
+ "usb",
+ "usb_device");
+
+ if (!usb_dev) {
+ /* Free this device */
+ free(cur_dev->serial_number);
+ free(cur_dev->path);
+ free(cur_dev);
+
+ /* Take it off the device list. */
+ if (prev_dev) {
+ prev_dev->next = NULL;
+ cur_dev = prev_dev;
+ }
+ else {
+ cur_dev = root = NULL;
+ }
+
+ goto next;
+ }
+
+ /* Manufacturer and Product strings */
+ cur_dev->manufacturer_string = copy_udev_string(usb_dev, device_string_names[DEVICE_STRING_MANUFACTURER]);
+ cur_dev->product_string = copy_udev_string(usb_dev, device_string_names[DEVICE_STRING_PRODUCT]);
+
+ /* Release Number */
+ str = udev_device_get_sysattr_value(usb_dev, "bcdDevice");
+ cur_dev->release_number = (str)? strtol(str, NULL, 16): 0x0;
+
+ /* Get a handle to the interface's udev node. */
+ intf_dev = udev_device_get_parent_with_subsystem_devtype(
+ raw_dev,
+ "usb",
+ "usb_interface");
+ if (intf_dev) {
+ str = udev_device_get_sysattr_value(intf_dev, "bInterfaceNumber");
+ cur_dev->interface_number = (str)? strtol(str, NULL, 16): -1;
+ }
+
+ break;
+
+ case BUS_BLUETOOTH:
+ /* Manufacturer and Product strings */
+ cur_dev->manufacturer_string = wcsdup(L"");
+ cur_dev->product_string = utf8_to_wchar_t(product_name_utf8);
+
+ break;
+
+ default:
+ /* Unknown device type - this should never happen, as we
+ * check for USB and Bluetooth devices above */
+ break;
+ }
+ }
+
+ next:
+ free(serial_number_utf8);
+ free(product_name_utf8);
+ udev_device_unref(raw_dev);
+ /* hid_dev, usb_dev and intf_dev don't need to be (and can't be)
+ unref()d. It will cause a double-free() error. I'm not
+ sure why. */
+ }
+ /* Free the enumerator and udev objects. */
+ udev_enumerate_unref(enumerate);
+ udev_unref(udev);
+
+ return root;
+}
+
+void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
+{
+ struct hid_device_info *d = devs;
+ while (d) {
+ struct hid_device_info *next = d->next;
+ free(d->path);
+ free(d->serial_number);
+ free(d->manufacturer_string);
+ free(d->product_string);
+ free(d);
+ d = next;
+ }
+}
+
+hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
+{
+ struct hid_device_info *devs, *cur_dev;
+ const char *path_to_open = NULL;
+ hid_device *handle = NULL;
+
+ devs = hid_enumerate(vendor_id, product_id);
+ cur_dev = devs;
+ while (cur_dev) {
+ if (cur_dev->vendor_id == vendor_id &&
+ cur_dev->product_id == product_id) {
+ if (serial_number) {
+ if (wcscmp(serial_number, cur_dev->serial_number) == 0) {
+ path_to_open = cur_dev->path;
+ break;
+ }
+ }
+ else {
+ path_to_open = cur_dev->path;
+ break;
+ }
+ }
+ cur_dev = cur_dev->next;
+ }
+
+ if (path_to_open) {
+ /* Open the device */
+ handle = hid_open_path(path_to_open);
+ }
+
+ hid_free_enumeration(devs);
+
+ return handle;
+}
+
+hid_device * HID_API_EXPORT hid_open_path(const char *path)
+{
+ hid_device *dev = NULL;
+
+ hid_init();
+
+ dev = new_hid_device();
+
+ /* OPEN HERE */
+ dev->device_handle = open(path, O_RDWR);
+
+ /* If we have a good handle, return it. */
+ if (dev->device_handle > 0) {
+
+ /* Get the report descriptor */
+ int res, desc_size = 0;
+ struct hidraw_report_descriptor rpt_desc;
+
+ memset(&rpt_desc, 0x0, sizeof(rpt_desc));
+
+ /* Get Report Descriptor Size */
+ res = ioctl(dev->device_handle, HIDIOCGRDESCSIZE, &desc_size);
+ if (res < 0)
+ perror("HIDIOCGRDESCSIZE");
+
+
+ /* Get Report Descriptor */
+ rpt_desc.size = desc_size;
+ res = ioctl(dev->device_handle, HIDIOCGRDESC, &rpt_desc);
+ if (res < 0) {
+ perror("HIDIOCGRDESC");
+ } else {
+ /* Determine if this device uses numbered reports. */
+ dev->uses_numbered_reports =
+ uses_numbered_reports(rpt_desc.value,
+ rpt_desc.size);
+ }
+
+ return dev;
+ }
+ else {
+ /* Unable to open any devices. */
+ free(dev);
+ return NULL;
+ }
+}
+
+
+int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
+{
+ int bytes_written;
+
+ bytes_written = write(dev->device_handle, data, length);
+
+ return bytes_written;
+}
+
+
+int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
+{
+ int bytes_read;
+
+ if (milliseconds >= 0) {
+ /* Milliseconds is either 0 (non-blocking) or > 0 (contains
+ a valid timeout). In both cases we want to call poll()
+ and wait for data to arrive. Don't rely on non-blocking
+ operation (O_NONBLOCK) since some kernels don't seem to
+ properly report device disconnection through read() when
+ in non-blocking mode. */
+ int ret;
+ struct pollfd fds;
+
+ fds.fd = dev->device_handle;
+ fds.events = POLLIN;
+ fds.revents = 0;
+ ret = poll(&fds, 1, milliseconds);
+ if (ret == -1 || ret == 0) {
+ /* Error or timeout */
+ return ret;
+ }
+ else {
+ /* Check for errors on the file descriptor. This will
+ indicate a device disconnection. */
+ if (fds.revents & (POLLERR | POLLHUP | POLLNVAL))
+ return -1;
+ }
+ }
+
+ bytes_read = read(dev->device_handle, data, length);
+ if (bytes_read < 0 && (errno == EAGAIN || errno == EINPROGRESS))
+ bytes_read = 0;
+
+ if (bytes_read >= 0 &&
+ kernel_version != 0 &&
+ kernel_version < KERNEL_VERSION(2,6,34) &&
+ dev->uses_numbered_reports) {
+ /* Work around a kernel bug. Chop off the first byte. */
+ memmove(data, data+1, bytes_read);
+ bytes_read--;
+ }
+
+ return bytes_read;
+}
+
+int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
+{
+ return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0);
+}
+
+int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
+{
+ /* Do all non-blocking in userspace using poll(), since it looks
+ like there's a bug in the kernel in some versions where
+ read() will not return -1 on disconnection of the USB device */
+
+ dev->blocking = !nonblock;
+ return 0; /* Success */
+}
+
+
+int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
+{
+ int res;
+
+ res = ioctl(dev->device_handle, HIDIOCSFEATURE(length), data);
+ if (res < 0)
+ perror("ioctl (SFEATURE)");
+
+ return res;
+}
+
+int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
+{
+ int res;
+
+ res = ioctl(dev->device_handle, HIDIOCGFEATURE(length), data);
+ if (res < 0)
+ perror("ioctl (GFEATURE)");
+
+
+ return res;
+}
+
+
+void HID_API_EXPORT hid_close(hid_device *dev)
+{
+ if (!dev)
+ return;
+ close(dev->device_handle);
+ free(dev);
+}
+
+
+int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
+{
+ return get_device_string(dev, DEVICE_STRING_MANUFACTURER, string, maxlen);
+}
+
+int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
+{
+ return get_device_string(dev, DEVICE_STRING_PRODUCT, string, maxlen);
+}
+
+int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
+{
+ return get_device_string(dev, DEVICE_STRING_SERIAL, string, maxlen);
+}
+
+int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
+{
+ return -1;
+}
+
+
+HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
+{
+ return NULL;
+}
diff --git a/src/libambit/hidapi/hidapi.h b/src/libambit/hidapi/hidapi.h
new file mode 100644
index 0000000..5730f86
--- /dev/null
+++ b/src/libambit/hidapi/hidapi.h
@@ -0,0 +1,387 @@
+/*******************************************************
+ HIDAPI - Multi-Platform library for
+ communication with HID devices.
+
+ Alan Ott
+ Signal 11 Software
+
+ 8/22/2009
+
+ Copyright 2009, All Rights Reserved.
+
+ At the discretion of the user of this library,
+ this software may be licensed under the terms of the
+ GNU General Public License v3, a BSD-Style license, or the
+ original HIDAPI license as outlined in the LICENSE.txt,
+ LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
+ files located at the root of the source distribution.
+ These files may also be found in the public source
+ code repository located at:
+ http://github.com/signal11/hidapi .
+********************************************************/
+
+/** @file
+ * @defgroup API hidapi API
+ */
+
+#ifndef HIDAPI_H__
+#define HIDAPI_H__
+
+#include <wchar.h>
+
+#ifdef _WIN32
+ #define HID_API_EXPORT __declspec(dllexport)
+ #define HID_API_CALL
+#else
+ #define HID_API_EXPORT /**< API export macro */
+ #define HID_API_CALL /**< API call macro */
+#endif
+
+#define HID_API_EXPORT_CALL HID_API_EXPORT HID_API_CALL /**< API export and call macro*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ struct hid_device_;
+ typedef struct hid_device_ hid_device; /**< opaque hidapi structure */
+
+ /** hidapi info structure */
+ struct hid_device_info {
+ /** Platform-specific device path */
+ char *path;
+ /** Device Vendor ID */
+ unsigned short vendor_id;
+ /** Device Product ID */
+ unsigned short product_id;
+ /** Serial Number */
+ wchar_t *serial_number;
+ /** Device Release Number in binary-coded decimal,
+ also known as Device Version Number */
+ unsigned short release_number;
+ /** Manufacturer String */
+ wchar_t *manufacturer_string;
+ /** Product string */
+ wchar_t *product_string;
+ /** Usage Page for this Device/Interface
+ (Windows/Mac only). */
+ unsigned short usage_page;
+ /** Usage for this Device/Interface
+ (Windows/Mac only).*/
+ unsigned short usage;
+ /** The USB interface which this logical device
+ represents. Valid on both Linux implementations
+ in all cases, and valid on the Windows implementation
+ only if the device contains more than one interface. */
+ int interface_number;
+
+ /** Pointer to the next device */
+ struct hid_device_info *next;
+ };
+
+
+ /** @brief Initialize the HIDAPI library.
+
+ This function initializes the HIDAPI library. Calling it is not
+ strictly necessary, as it will be called automatically by
+ hid_enumerate() and any of the hid_open_*() functions if it is
+ needed. This function should be called at the beginning of
+ execution however, if there is a chance of HIDAPI handles
+ being opened by different threads simultaneously.
+
+ @ingroup API
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_init(void);
+
+ /** @brief Finalize the HIDAPI library.
+
+ This function frees all of the static data associated with
+ HIDAPI. It should be called at the end of execution to avoid
+ memory leaks.
+
+ @ingroup API
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_exit(void);
+
+ /** @brief Enumerate the HID Devices.
+
+ This function returns a linked list of all the HID devices
+ attached to the system which match vendor_id and product_id.
+ If @p vendor_id is set to 0 then any vendor matches.
+ If @p product_id is set to 0 then any product matches.
+ If @p vendor_id and @p product_id are both set to 0, then
+ all HID devices will be returned.
+
+ @ingroup API
+ @param vendor_id The Vendor ID (VID) of the types of device
+ to open.
+ @param product_id The Product ID (PID) of the types of
+ device to open.
+
+ @returns
+ This function returns a pointer to a linked list of type
+ struct #hid_device, containing information about the HID devices
+ attached to the system, or NULL in the case of failure. Free
+ this linked list by calling hid_free_enumeration().
+ */
+ struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id);
+
+ /** @brief Free an enumeration Linked List
+
+ This function frees a linked list created by hid_enumerate().
+
+ @ingroup API
+ @param devs Pointer to a list of struct_device returned from
+ hid_enumerate().
+ */
+ void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs);
+
+ /** @brief Open a HID device using a Vendor ID (VID), Product ID
+ (PID) and optionally a serial number.
+
+ If @p serial_number is NULL, the first device with the
+ specified VID and PID is opened.
+
+ @ingroup API
+ @param vendor_id The Vendor ID (VID) of the device to open.
+ @param product_id The Product ID (PID) of the device to open.
+ @param serial_number The Serial Number of the device to open
+ (Optionally NULL).
+
+ @returns
+ This function returns a pointer to a #hid_device object on
+ success or NULL on failure.
+ */
+ HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number);
+
+ /** @brief Open a HID device by its path name.
+
+ The path name be determined by calling hid_enumerate(), or a
+ platform-specific path name can be used (eg: /dev/hidraw0 on
+ Linux).
+
+ @ingroup API
+ @param path The path name of the device to open
+
+ @returns
+ This function returns a pointer to a #hid_device object on
+ success or NULL on failure.
+ */
+ HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path);
+
+ /** @brief Write an Output report to a HID device.
+
+ The first byte of @p data[] must contain the Report ID. For
+ devices which only support a single report, this must be set
+ to 0x0. The remaining bytes contain the report data. Since
+ the Report ID is mandatory, calls to hid_write() will always
+ contain one more byte than the report contains. For example,
+ if a hid report is 16 bytes long, 17 bytes must be passed to
+ hid_write(), the Report ID (or 0x0, for devices with a
+ single report), followed by the report data (16 bytes). In
+ this example, the length passed in would be 17.
+
+ hid_write() will send the data on the first OUT endpoint, if
+ one exists. If it does not, it will send the data through
+ the Control Endpoint (Endpoint 0).
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param data The data to send, including the report number as
+ the first byte.
+ @param length The length in bytes of the data to send.
+
+ @returns
+ This function returns the actual number of bytes written and
+ -1 on error.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_write(hid_device *device, const unsigned char *data, size_t length);
+
+ /** @brief Read an Input report from a HID device with timeout.
+
+ Input reports are returned
+ to the host through the INTERRUPT IN endpoint. The first byte will
+ contain the Report number if the device uses numbered reports.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param data A buffer to put the read data into.
+ @param length The number of bytes to read. For devices with
+ multiple reports, make sure to read an extra byte for
+ the report number.
+ @param milliseconds timeout in milliseconds or -1 for blocking wait.
+
+ @returns
+ This function returns the actual number of bytes read and
+ -1 on error. If no packet was available to be read within
+ the timeout period, this function returns 0.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds);
+
+ /** @brief Read an Input report from a HID device.
+
+ Input reports are returned
+ to the host through the INTERRUPT IN endpoint. The first byte will
+ contain the Report number if the device uses numbered reports.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param data A buffer to put the read data into.
+ @param length The number of bytes to read. For devices with
+ multiple reports, make sure to read an extra byte for
+ the report number.
+
+ @returns
+ This function returns the actual number of bytes read and
+ -1 on error. If no packet was available to be read and
+ the handle is in non-blocking mode, this function returns 0.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_read(hid_device *device, unsigned char *data, size_t length);
+
+ /** @brief Set the device handle to be non-blocking.
+
+ In non-blocking mode calls to hid_read() will return
+ immediately with a value of 0 if there is no data to be
+ read. In blocking mode, hid_read() will wait (block) until
+ there is data to read before returning.
+
+ Nonblocking can be turned on and off at any time.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param nonblock enable or not the nonblocking reads
+ - 1 to enable nonblocking
+ - 0 to disable nonblocking.
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *device, int nonblock);
+
+ /** @brief Send a Feature report to the device.
+
+ Feature reports are sent over the Control endpoint as a
+ Set_Report transfer. The first byte of @p data[] must
+ contain the Report ID. For devices which only support a
+ single report, this must be set to 0x0. The remaining bytes
+ contain the report data. Since the Report ID is mandatory,
+ calls to hid_send_feature_report() will always contain one
+ more byte than the report contains. For example, if a hid
+ report is 16 bytes long, 17 bytes must be passed to
+ hid_send_feature_report(): the Report ID (or 0x0, for
+ devices which do not use numbered reports), followed by the
+ report data (16 bytes). In this example, the length passed
+ in would be 17.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param data The data to send, including the report number as
+ the first byte.
+ @param length The length in bytes of the data to send, including
+ the report number.
+
+ @returns
+ This function returns the actual number of bytes written and
+ -1 on error.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *device, const unsigned char *data, size_t length);
+
+ /** @brief Get a feature report from a HID device.
+
+ Make sure to set the first byte of @p data[] to the Report
+ ID of the report to be read. Make sure to allow space for
+ this extra byte in @p data[].
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param data A buffer to put the read data into, including
+ the Report ID. Set the first byte of @p data[] to the
+ Report ID of the report to be read.
+ @param length The number of bytes to read, including an
+ extra byte for the report ID. The buffer can be longer
+ than the actual report.
+
+ @returns
+ This function returns the number of bytes read and
+ -1 on error.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *device, unsigned char *data, size_t length);
+
+ /** @brief Close a HID device.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ */
+ void HID_API_EXPORT HID_API_CALL hid_close(hid_device *device);
+
+ /** @brief Get The Manufacturer String from a HID device.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param string A wide string buffer to put the data into.
+ @param maxlen The length of the buffer in multiples of wchar_t.
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *device, wchar_t *string, size_t maxlen);
+
+ /** @brief Get The Product String from a HID device.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param string A wide string buffer to put the data into.
+ @param maxlen The length of the buffer in multiples of wchar_t.
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT_CALL hid_get_product_string(hid_device *device, wchar_t *string, size_t maxlen);
+
+ /** @brief Get The Serial Number String from a HID device.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param string A wide string buffer to put the data into.
+ @param maxlen The length of the buffer in multiples of wchar_t.
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *device, wchar_t *string, size_t maxlen);
+
+ /** @brief Get a string from a HID device, based on its string index.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param string_index The index of the string to get.
+ @param string A wide string buffer to put the data into.
+ @param maxlen The length of the buffer in multiples of wchar_t.
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *device, int string_index, wchar_t *string, size_t maxlen);
+
+ /** @brief Get a string describing the last error which occurred.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+
+ @returns
+ This function returns a string containing the last error
+ which occurred or NULL if none has occurred.
+ */
+ HID_API_EXPORT const wchar_t* HID_API_CALL hid_error(hid_device *device);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/src/libambit/libambit.c b/src/libambit/libambit.c
new file mode 100644
index 0000000..b16a77c
--- /dev/null
+++ b/src/libambit/libambit.c
@@ -0,0 +1,551 @@
+/*
+ * (C) Copyright 2014 Emil Ljungdahl
+ *
+ * This file is part of libambit.
+ *
+ * libambit is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * Contributors:
+ *
+ */
+#include "libambit.h"
+#include "libambit_int.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+/*
+ * Local definitions
+ */
+#define SUUNTO_USB_VENDOR_ID 0x1493
+
+struct ambit_supported_device_s {
+ uint16_t vid;
+ uint16_t pid;
+ char *model;
+ uint8_t min_sw_version[4];
+ char *name;
+ bool supported;
+ uint16_t pmem20_chunksize;
+};
+
+/*
+ * Static functions
+ */
+static int device_info_get(ambit_object_t *object, ambit_device_info_t *info);
+static int lock_log(ambit_object_t *object, bool lock);
+
+/*
+ * Static variables
+ */
+static ambit_supported_device_t supported_devices[] = {
+ { SUUNTO_USB_VENDOR_ID, 0x001a, "Colibri", {0x01,0x01,0x02,0x00}, "Suunto Ambit2 S", true, 0x0400 },
+ { SUUNTO_USB_VENDOR_ID, 0x0019, "Duck", {0x01,0x01,0x02,0x00}, "Suunto Ambit2", true, 0x0400 },
+ { SUUNTO_USB_VENDOR_ID, 0x001a, "Colibri", {0x00,0x02,0x03,0x00}, "Suunto Ambit2 S", false, 0x0400 },
+ { SUUNTO_USB_VENDOR_ID, 0x0019, "Duck", {0x00,0x02,0x03,0x00}, "Suunto Ambit2", false, 0x0400 },
+ { SUUNTO_USB_VENDOR_ID, 0x001a, "Colibri", {0x00,0x02,0x02,0x00}, "Suunto Ambit2 S (up to 0.2.2)", false, 0x0200 },
+ { SUUNTO_USB_VENDOR_ID, 0x0019, "Duck", {0x00,0x02,0x02,0x00}, "Suunto Ambit2 (up to 0.2.2)", false, 0x0200 },
+ { SUUNTO_USB_VENDOR_ID, 0x0010, "Bluebird", {0x02,0x01,0x00,0x00}, "Suunto Ambit", true, 0x0200 },
+ { SUUNTO_USB_VENDOR_ID, 0x0010, "Bluebird", {0x01,0x09,0x00,0x00}, "Suunto Ambit", false, 0x0200 }, /* First with PMEM 2.0!? */
+ { SUUNTO_USB_VENDOR_ID, 0x0010, "Bluebird", {0x01,0x06,0x00,0x00}, "Suunto Ambit", false, 0 },
+ { SUUNTO_USB_VENDOR_ID, 0x0010, "Bluebird", {0x01,0x01,0x00,0x00}, "Suunto Ambit", false, 0 },
+ { SUUNTO_USB_VENDOR_ID, 0x0010, "Bluebird", {0x00,0x00,0x00,0x00}, "Suunto Ambit", false, 0 },
+ { 0x0000, 0x0000, NULL, {0x00,0x00,0x00,0x00}, NULL, false }
+};
+
+/*
+ * Public functions
+ */
+ambit_object_t *libambit_detect(void)
+{
+ hid_device *handle;
+ struct hid_device_info *devs, *cur_dev;
+ ambit_object_t *ret_object = NULL;
+ int i;
+ ambit_supported_device_t *device = NULL;
+
+ LOG_INFO("Searching devices");
+
+ devs = hid_enumerate(0x0, 0x0);
+ cur_dev = devs;
+ while (cur_dev) {
+ for (i=0; i<sizeof(supported_devices)/sizeof(supported_devices[0]); i++) {
+ LOG_INFO("vendor_id=%04x, product_id=%04x", cur_dev->vendor_id, cur_dev->product_id);
+ if (cur_dev->vendor_id == supported_devices[i].vid && cur_dev->product_id == supported_devices[i].pid) {
+ LOG_INFO("match!");
+ // Found at least one supported row, lets remember that!
+ device = &supported_devices[i];
+ break;
+ }
+ }
+ if (device != NULL) {
+ // Devcice was found, we can stop looping through devices now...
+ break;
+ }
+ cur_dev = cur_dev->next;
+ }
+ hid_free_enumeration(devs);
+
+ if (device != NULL) {
+ LOG_INFO("Trying to open device");
+ handle = hid_open(device->vid, device->pid, NULL);
+ if (handle != NULL) {
+ // Setup hid device correctly
+ hid_set_nonblocking(handle, 1);
+
+ ret_object = malloc(sizeof(ambit_object_t));
+ memset(ret_object, 0, sizeof(ambit_object_t));
+ ret_object->handle = handle;
+ ret_object->vendor_id = device->vid;
+ ret_object->product_id = device->pid;
+
+ // Get device info to resolve supported functionality
+ if (device_info_get(ret_object, &ret_object->device_info) == 0) {
+ // Let's resolve the correct device
+ for (i=0; i<sizeof(supported_devices)/sizeof(supported_devices[0]); i++) {
+ if (device->vid == supported_devices[i].vid &&
+ device->pid == supported_devices[i].pid &&
+ strncmp(device->model, ret_object->device_info.model, LIBAMBIT_MODEL_NAME_LENGTH) == 0 &&
+ (ret_object->device_info.fw_version[0] > device->min_sw_version[0] ||
+ (ret_object->device_info.fw_version[0] == device->min_sw_version[0] &&
+ (ret_object->device_info.fw_version[1] > device->min_sw_version[1] ||
+ (ret_object->device_info.fw_version[1] == device->min_sw_version[1] &&
+ (ret_object->device_info.fw_version[2] > device->min_sw_version[2] ||
+ (ret_object->device_info.fw_version[2] == device->min_sw_version[2] &&
+ (ret_object->device_info.fw_version[3] >= device->min_sw_version[3])))))))) {
+ // Found matching entry, reset to this one!
+ device = &supported_devices[i];
+ break;
+ }
+ }
+ ret_object->device = device;
+ strncpy(ret_object->device_info.name, device->name, LIBAMBIT_PRODUCT_NAME_LENGTH);
+
+ // Initialize pmem
+ libambit_pmem20_init(ret_object, device->pmem20_chunksize);
+
+ LOG_INFO("Successfully opened device \"%s (%s)\" SW: %d.%d.%d, Supported: %s", device->name, device->model, ret_object->device_info.fw_version[0], ret_object->device_info.fw_version[1], ret_object->device_info.fw_version[3] << 8 | ret_object->device_info.fw_version[2], device->supported ? "YES" : "NO");
+ }
+ else {
+ free(ret_object);
+ ret_object = NULL;
+ LOG_ERROR("Failed to get device info from \"%s (%s)\"", device->name, device->model);
+ }
+ }
+ else {
+ LOG_ERROR("Failed to open device \"%s (%s)\"", device->name, device->model);
+ }
+ }
+
+ return ret_object;
+}
+
+void libambit_close(ambit_object_t *object)
+{
+ LOG_INFO("Closing");
+ if (object != NULL) {
+ if (object->handle != NULL) {
+ // Make sure to clear log lock (if possible)
+ lock_log(object, false);
+ hid_close(object->handle);
+ }
+
+ libambit_pmem20_deinit(object);
+ free(object);
+ }
+}
+
+bool libambit_device_supported(ambit_object_t *object)
+{
+ bool ret = false;
+
+ if (object != NULL && object->device != NULL) {
+ ret = object->device->supported;
+ }
+
+ return ret;
+}
+
+int libambit_device_info_get(ambit_object_t *object, ambit_device_info_t *info)
+{
+ int ret = -1;
+
+ if (object != NULL && object->device != NULL) {
+ if (info != NULL) {
+ memcpy(info, &object->device_info, sizeof(ambit_device_info_t));
+ }
+ ret = 0;
+ }
+
+ return ret;
+}
+
+void libambit_sync_display_show(ambit_object_t *object)
+{
+ lock_log(object, true);
+}
+
+void libambit_sync_display_clear(ambit_object_t *object)
+{
+ lock_log(object, false);
+}
+
+int libambit_date_time_set(ambit_object_t *object, struct tm *tm)
+{
+ uint8_t date_data[8];
+ uint8_t time_data[8] = { 0x09, 0x00, 0x01, 0x00 };
+ int ret = -1;
+
+ LOG_INFO("Writing date and time to clock");
+
+ // Set date
+ *(uint16_t*)(&date_data[0]) = htole16(1900 + tm->tm_year);
+ date_data[2] = 1 + tm->tm_mon;
+ date_data[3] = tm->tm_mday;
+ memset(&date_data[4], 0, 4); // ????? Unknown data
+
+ // Set time
+ time_data[4] = tm->tm_hour;
+ time_data[5] = tm->tm_min;
+ *(uint16_t*)(&time_data[6]) = htole16(1000*tm->tm_sec);
+
+ if (libambit_protocol_command(object, ambit_command_date, date_data, sizeof(date_data), NULL, NULL, 0) == 0 &&
+ libambit_protocol_command(object, ambit_command_time, time_data, sizeof(time_data), NULL, NULL, 0) == 0) {
+
+ ret = 0;
+ }
+ else {
+ LOG_WARNING("Failed to write date and time");
+ }
+
+ return ret;
+}
+
+int libambit_device_status_get(ambit_object_t *object, ambit_device_status_t *status)
+{
+ uint8_t *reply_data = NULL;
+ size_t replylen;
+ int ret = -1;
+
+ LOG_INFO("Reading device status");
+
+ if (libambit_protocol_command(object, ambit_command_status, NULL, 0, &reply_data, &replylen, 0) == 0) {
+ if (status != NULL) {
+ status->charge = reply_data[1];
+ }
+ ret = 0;
+ }
+ else {
+ LOG_WARNING("Failed to read device status");
+ }
+
+ libambit_protocol_free(reply_data);
+
+ return ret;
+}
+
+int libambit_personal_settings_get(ambit_object_t *object, ambit_personal_settings_t *settings)
+{
+ uint8_t *reply_data = NULL;
+ size_t replylen = 0;
+ int ret = -1;
+
+ LOG_INFO("Reading personal settings");
+
+ if (libambit_protocol_command(object, ambit_command_personal_settings, NULL, 0, &reply_data, &replylen, 0) == 0) {
+ ret = libambit_personal_settings_parse(reply_data, replylen, settings);
+ libambit_protocol_free(reply_data);
+ }
+ else {
+ LOG_WARNING("Failed to read personal settings");
+ }
+
+ return ret;
+}
+
+int libambit_gps_orbit_header_read(ambit_object_t *object, uint8_t data[8])
+{
+ uint8_t *reply_data = NULL;
+ size_t replylen = 0;
+ int ret = -1;
+
+ if (libambit_protocol_command(object, ambit_command_gps_orbit_head, NULL, 0, &reply_data, &replylen, 0) == 0 && replylen == 9) {
+ memcpy(data, &reply_data[1], 8);
+ libambit_protocol_free(reply_data);
+
+ ret = 0;
+ }
+ else {
+ LOG_WARNING("Failed to read GPS orbit header");
+ }
+
+ return ret;
+}
+
+int libambit_gps_orbit_write(ambit_object_t *object, uint8_t *data, size_t datalen)
+{
+ uint8_t header[8], cmpheader[8];
+ int ret = -1;
+
+ LOG_INFO("Writing GPS orbit data");
+
+ libambit_protocol_command(object, ambit_command_write_start, NULL, 0, NULL, NULL, 0);
+
+ if (libambit_gps_orbit_header_read(object, header) == 0) {
+ cmpheader[0] = data[7]; // Year, swap bytes
+ cmpheader[1] = data[6];
+ cmpheader[2] = data[8];
+ cmpheader[3] = data[9];
+ cmpheader[4] = data[13]; // 4 byte swap
+ cmpheader[5] = data[12];
+ cmpheader[6] = data[11];
+ cmpheader[7] = data[10];
+
+ // Check if new data differs
+ if (memcmp(header, cmpheader, 8) != 0) {
+ ret = libambit_pmem20_gps_orbit_write(object, data, datalen);
+ }
+ else {
+ LOG_INFO("Current GPS orbit data is already up to date, skipping");
+ ret = 0;
+ }
+ }
+
+ return ret;
+}
+
+int libambit_log_read(ambit_object_t *object, ambit_log_skip_cb skip_cb, ambit_log_push_cb push_cb, ambit_log_progress_cb progress_cb, void *userref)
+{
+ int entries_read = 0;
+
+ uint8_t *reply_data = NULL;
+ size_t replylen = 0;
+ uint16_t log_entries_total = 0;
+ uint16_t log_entries_walked = 0;
+
+ uint32_t more = 0x00000400;
+
+ bool read_pmem = false;
+
+ ambit_log_header_t log_header;
+ ambit_log_entry_t *log_entry;
+
+ LOG_INFO("Reading number of logs");
+
+ /*
+ * Read number of log entries
+ */
+ if (libambit_protocol_command(object, ambit_command_log_count, NULL, 0, &reply_data, &replylen, 0) != 0) {
+ LOG_WARNING("Failed to read number of log entries");
+ return -1;
+ }
+ log_entries_total = le16toh(*(uint16_t*)(reply_data + 2));
+ libambit_protocol_free(reply_data);
+
+ LOG_INFO("Number of logs=%d", log_entries_total);
+
+ /*
+ * First part walks through headers to check if there is any point in start
+ * reading the PMEM content. If no skip callback is defined, there is no
+ * point in checking the headers, because no one can tell us to not include
+ * the logs...
+ */
+
+ if (skip_cb != NULL) {
+ LOG_INFO("Look in headers for new logs");
+ // Rewind
+ if (libambit_protocol_command(object, ambit_command_log_head_first, NULL, 0, &reply_data, &replylen, 0) != 0) {
+ LOG_WARNING("Failed to rewind header pointer");
+ return -1;
+ }
+ more = le32toh(*(uint32_t*)reply_data);
+ libambit_protocol_free(reply_data);
+
+ // Loop through logs while more entries exists
+ while (more == 0x00000400) {
+ LOG_INFO("Reading next header");
+ // Go to next entry
+ if (libambit_protocol_command(object, ambit_command_log_head_step, NULL, 0, &reply_data, &replylen, 0) != 0) {
+ LOG_WARNING("Failed to walk to next header");
+ return -1;
+ }
+ libambit_protocol_free(reply_data);
+
+ // Assume every header is composited by 2 parts, where only the
+ // second is of interrest right now
+ if (libambit_protocol_command(object, ambit_command_log_head, NULL, 0, &reply_data, &replylen, 0) != 0) {
+ LOG_WARNING("Failed to read first part of header");
+ return -1;
+ }
+ libambit_protocol_free(reply_data);
+
+ if (libambit_protocol_command(object, ambit_command_log_head, NULL, 0, &reply_data, &replylen, 0) == 0) {
+ if (replylen > 8 && libambit_pmem20_log_parse_header(reply_data + 8, replylen - 8, &log_header) == 0) {
+ if (skip_cb(userref, &log_header) != 0) {
+ // Header was NOT skipped, break out!
+ read_pmem = true;
+ LOG_INFO("Found new entry, start reading log data");
+ break;
+ }
+ }
+ else {
+ LOG_ERROR("Failed to parse log header");
+ return -1;
+ }
+ libambit_protocol_free(reply_data);
+ }
+ else {
+ LOG_WARNING("Failed to read second part of header");
+ return -1;
+ }
+
+ // Is there more entries to read?
+ if (libambit_protocol_command(object, ambit_command_log_head_peek, NULL, 0, &reply_data, &replylen, 0) != 0) {
+ LOG_WARNING("Failed to check for more headers");
+ return -1;
+ }
+ more = le32toh(*(uint32_t*)reply_data);
+ libambit_protocol_free(reply_data);
+ }
+ }
+ else {
+ LOG_INFO("No skip callback defined, reading log data");
+ read_pmem = true;
+ }
+
+ if (read_pmem) {
+ if (libambit_pmem20_log_init(object) != 0) {
+ return -1;
+ }
+
+ // Loop through all log entries, first check headers
+ while (log_entries_walked < log_entries_total && libambit_pmem20_log_next_header(object, &log_header) == 1) {
+ LOG_INFO("Reading header of log %d of %d", log_entries_walked + 1, log_entries_total);
+ if (progress_cb != NULL) {
+ progress_cb(userref, log_entries_total, log_entries_walked+1, 100*log_entries_walked/log_entries_total);
+ }
+ // Check if this entry needs to be read
+ if (skip_cb == NULL || skip_cb(userref, &log_header) != 0) {
+ LOG_INFO("Reading data of log %d of %d", log_entries_walked + 1, log_entries_total);
+ log_entry = libambit_pmem20_log_read_entry(object);
+ if (log_entry != NULL) {
+ if (push_cb != NULL) {
+ push_cb(userref, log_entry);
+ }
+ entries_read++;
+ }
+ }
+ else {
+ LOG_INFO("Log %d of %d already exists, skip reading data", log_entries_walked + 1, log_entries_total);
+ }
+ log_entries_walked++;
+ if (progress_cb != NULL) {
+ progress_cb(userref, log_entries_total, log_entries_walked, 100*log_entries_walked/log_entries_total);
+ }
+ }
+ }
+
+ LOG_INFO("%d entries read", entries_read);
+
+ return entries_read;
+}
+
+void libambit_log_entry_free(ambit_log_entry_t *log_entry)
+{
+ int i;
+
+ if (log_entry != NULL) {
+ if (log_entry->samples != NULL) {
+ for (i=0; i<log_entry->samples_count; i++) {
+ if (log_entry->samples[i].type == ambit_log_sample_type_periodic) {
+ if (log_entry->samples[i].u.periodic.values != NULL) {
+ free(log_entry->samples[i].u.periodic.values);
+ }
+ }
+ if (log_entry->samples[i].type == ambit_log_sample_type_gps_base) {
+ if (log_entry->samples[i].u.gps_base.satellites != NULL) {
+ free(log_entry->samples[i].u.gps_base.satellites);
+ }
+ }
+ if (log_entry->samples[i].type == ambit_log_sample_type_unknown) {
+ if (log_entry->samples[i].u.unknown.data != NULL) {
+ free(log_entry->samples[i].u.unknown.data);
+ }
+ }
+ }
+ free(log_entry->samples);
+ }
+ free(log_entry);
+ }
+}
+
+static int device_info_get(ambit_object_t *object, ambit_device_info_t *info)
+{
+ uint8_t send_data[] = { 0x01, 0x06, 0x14, 0x00 };
+ uint8_t *reply_data = NULL;
+ size_t replylen;
+ int ret = -1;
+
+ LOG_INFO("Reading device info");
+
+ if (libambit_protocol_command(object, ambit_command_device_info, send_data, sizeof(send_data), &reply_data, &replylen, 1) == 0) {
+ if (info != NULL) {
+ memcpy(info->model, reply_data, 16);
+ info->model[16] = 0;
+ memcpy(info->serial, &reply_data[16], 16);
+ info->serial[16] = 0;
+ memcpy(info->fw_version, &reply_data[32], 4);
+ memcpy(info->hw_version, &reply_data[36], 4);
+ }
+ ret = 0;
+ }
+ else {
+ LOG_WARNING("Failed to read log info");
+ }
+
+ libambit_protocol_free(reply_data);
+
+ return ret;
+}
+
+static int lock_log(ambit_object_t *object, bool lock)
+{
+ int ret = -1;
+ uint8_t send_data[] = { 0x00, 0x00, 0x00, 0x00 };
+ uint8_t *reply_data = NULL;
+ size_t replylen;
+
+ uint32_t current_lock = 0xffffffff;
+
+ if ((ret = libambit_protocol_command(object, ambit_command_lock_check, NULL, 0, &reply_data, &replylen, 0)) == 0) {
+ current_lock = le32toh(*(uint32_t*)reply_data);
+ libambit_protocol_free(reply_data);
+ }
+
+ if (lock && current_lock == 0) {
+ LOG_INFO("Setting Sync message to device display");
+ send_data[0] = 1;
+ ret = libambit_protocol_command(object, ambit_command_lock_set, send_data, sizeof(send_data), &reply_data, &replylen, 0);
+ libambit_protocol_free(reply_data);
+ }
+ else if (!lock && current_lock == 1) {
+ LOG_INFO("Clearing Sync message to device display");
+ send_data[0] = 0;
+ ret = libambit_protocol_command(object, ambit_command_lock_set, send_data, sizeof(send_data), &reply_data, &replylen, 0);
+ libambit_protocol_free(reply_data);
+ }
+
+ return ret;
+}
+
diff --git a/src/libambit/libambit.h b/src/libambit/libambit.h
new file mode 100644
index 0000000..570c0a3
--- /dev/null
+++ b/src/libambit/libambit.h
@@ -0,0 +1,469 @@
+/*
+ * (C) Copyright 2014 Emil Ljungdahl
+ *
+ * This file is part of libambit.
+ *
+ * libambit is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * Contributors:
+ *
+ */
+#ifndef __LIBAMBIT_H__
+#define __LIBAMBIT_H__
+
+#ifdef __cplusplus /* If this is a C++ compiler, use C linkage */
+extern "C" {
+#endif
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <time.h>
+
+#define LIBAMBIT_MODEL_NAME_LENGTH 16
+#define LIBAMBIT_SERIAL_LENGTH 16
+#define LIBAMBIT_PRODUCT_NAME_LENGTH 32
+
+typedef struct ambit_object_s ambit_object_t;
+
+typedef struct ambit_device_info_s {
+ char name[LIBAMBIT_PRODUCT_NAME_LENGTH+1];
+ char model[LIBAMBIT_MODEL_NAME_LENGTH+1];
+ char serial[LIBAMBIT_SERIAL_LENGTH+1];
+ uint8_t fw_version[4];
+ uint8_t hw_version[4];
+} ambit_device_info_t;
+
+typedef struct ambit_device_status_s {
+ uint8_t charge;
+} ambit_device_status_t;
+
+typedef struct ambit_personal_settings_s {
+ uint8_t sportmode_button_lock;
+ uint8_t timemode_button_lock;
+ uint16_t compass_declination;
+ uint8_t units_mode;
+ struct {
+ uint8_t pressure;
+ uint8_t altitude;
+ uint8_t distance;
+ uint8_t height;
+ uint8_t temperature;
+ uint8_t verticalspeed;
+ uint8_t weight;
+ uint8_t compass;
+ uint8_t heartrate;
+ uint8_t speed;
+ } units;
+ uint8_t gps_position_format;
+ uint8_t language;
+ uint8_t navigation_style;
+ uint8_t sync_time_w_gps;
+ uint8_t time_format;
+ struct {
+ uint8_t hour;
+ uint8_t minute;
+ } alarm;
+ uint8_t alarm_enable;
+ struct {
+ uint8_t hour;
+ uint8_t minute;
+ } dual_time;
+ uint8_t date_format;
+ uint8_t tones_mode;
+ uint8_t backlight_mode;
+ uint8_t backlight_brightness;
+ uint8_t display_brightness;
+ uint8_t display_is_negative;
+ uint16_t weight; /* kg scale 0.01 */
+ uint16_t birthyear;
+ uint8_t max_hr;
+ uint8_t rest_hr;
+ uint8_t fitness_level;
+ uint8_t is_male;
+ uint8_t length;
+ uint8_t alti_baro_mode;
+ uint8_t fused_alti_disabled;
+ uint16_t bikepod_calibration; /* scale 0.0001 */
+ uint16_t bikepod_calibration2; /* scale 0.0001 */
+ uint16_t bikepod_calibration3; /* scale 0.0001 */
+ uint16_t footpod_calibration; /* scale 0.0001 */
+ uint8_t automatic_bikepower_calib;
+} ambit_personal_settings_t;
+
+typedef struct ambit_log_date_time_s {
+ uint16_t year;
+ uint8_t month;
+ uint8_t day;
+ uint8_t hour;
+ uint8_t minute;
+ uint16_t msec;
+} ambit_date_time_t;
+
+typedef enum ambit_log_sample_type_e {
+ ambit_log_sample_type_periodic = 0x0200,
+ ambit_log_sample_type_logpause = 0x0304,
+ ambit_log_sample_type_logrestart = 0x0305,
+ ambit_log_sample_type_ibi = 0x0306,
+ ambit_log_sample_type_ttff = 0x0307,
+ ambit_log_sample_type_distance_source = 0x0308,
+ ambit_log_sample_type_lapinfo = 0x0309,
+ ambit_log_sample_type_altitude_source = 0x030d,
+ ambit_log_sample_type_gps_base = 0x030f,
+ ambit_log_sample_type_gps_small = 0x0310,
+ ambit_log_sample_type_gps_tiny = 0x0311,
+ ambit_log_sample_type_time = 0x0312,
+ ambit_log_sample_type_activity = 0x0318,
+ ambit_log_sample_type_position = 0x031b,
+ ambit_log_sample_type_unknown = 0xf000
+} ambit_log_sample_type_t;
+
+typedef enum ambit_log_sample_periodic_type_e {
+ ambit_log_sample_periodic_type_latitude = 0x01,
+ ambit_log_sample_periodic_type_longitude = 0x02,
+ ambit_log_sample_periodic_type_distance = 0x03,
+ ambit_log_sample_periodic_type_speed = 0x04,
+ ambit_log_sample_periodic_type_hr = 0x05,
+ ambit_log_sample_periodic_type_time = 0x06,
+ ambit_log_sample_periodic_type_gpsspeed = 0x07,
+ ambit_log_sample_periodic_type_wristaccspeed = 0x08,
+ ambit_log_sample_periodic_type_bikepodspeed = 0x09,
+ ambit_log_sample_periodic_type_ehpe = 0x0a,
+ ambit_log_sample_periodic_type_evpe = 0x0b,
+ ambit_log_sample_periodic_type_altitude = 0x0c,
+ ambit_log_sample_periodic_type_abspressure = 0x0d,
+ ambit_log_sample_periodic_type_energy = 0x0e,
+ ambit_log_sample_periodic_type_temperature = 0x0f,
+ ambit_log_sample_periodic_type_charge = 0x10,
+ ambit_log_sample_periodic_type_gpsaltitude = 0x11,
+ ambit_log_sample_periodic_type_gpsheading = 0x12,
+ ambit_log_sample_periodic_type_gpshdop = 0x13,
+ ambit_log_sample_periodic_type_gpsvdop = 0x14,
+ ambit_log_sample_periodic_type_wristcadence = 0x15,
+ ambit_log_sample_periodic_type_snr = 0x16,
+ ambit_log_sample_periodic_type_noofsatellites = 0x17,
+ ambit_log_sample_periodic_type_sealevelpressure = 0x18,
+ ambit_log_sample_periodic_type_verticalspeed = 0x19,
+ ambit_log_sample_periodic_type_cadence = 0x1a,
+ ambit_log_sample_periodic_type_bikepower = 0x1f,
+ ambit_log_sample_periodic_type_swimingstrokecnt = 0x20,
+ ambit_log_sample_periodic_type_ruleoutput1 = 0x64,
+ ambit_log_sample_periodic_type_ruleoutput2 = 0x65,
+ ambit_log_sample_periodic_type_ruleoutput3 = 0x66,
+ ambit_log_sample_periodic_type_ruleoutput4 = 0x67,
+ ambit_log_sample_periodic_type_ruleoutput5 = 0x68
+} ambit_log_sample_periodic_type_t;
+
+typedef struct ambit_log_sample_periodic_value_s {
+ ambit_log_sample_periodic_type_t type;
+ union {
+ int32_t latitude; /* degree, scale: 0.0000001, -90 <= latitude <= 90 */
+ int32_t longitude; /* degree, scale: 0.0000001, -180 <= latitude <= 180 */
+ uint32_t distance; /* meter, scale: 1 */
+ uint16_t speed; /* m/s scale: 0.01, ignore if 0xffff */
+ uint8_t hr; /* bpm, ignore if 0xff */
+ uint32_t time; /* msec */
+ uint16_t gpsspeed; /* m/s scale: 0.01 */
+ uint16_t wristaccspeed; /* m/s scale: 0.01 */
+ uint16_t bikepodspeed; /* m/s scale: 0.01 */
+ uint32_t ehpe; /* meters scale: 0.01 */
+ uint32_t evpe; /* meters scale: 0.01 */
+ int16_t altitude; /* meters, -1000 <= altitude <= 10000 */
+ uint16_t abspressure; /* hpa scale 0.1 */
+ uint16_t energy; /* hcal/min */
+ int16_t temperature; /* celsius scale 0.1, -100 <= temp <= 100 */
+ uint8_t charge; /* percent */
+ int32_t gpsaltitude; /* meters scale: 0.01, -1000 <= altitude <= 10000 */
+ uint16_t gpsheading; /* degrees, scale: 0.01, 0 <= heading <= 360 */
+ uint8_t gpshdop; /* ? */
+ uint8_t gpsvdop; /* ? */
+ uint16_t wristcadence; /* rpm, ignore if 0xffff */
+ uint8_t snr[16]; /* ? */
+ uint8_t noofsatellites; /* ignore if 0xff */
+ int16_t sealevelpressure; /* hpa scale: 0.1 */
+ int16_t verticalspeed; /* m/s scale: 0.01 */
+ uint8_t cadence; /* rpm, ignore if 0xff */
+ uint16_t bikepower; /* watt */
+ uint32_t swimingstrokecnt; /* counter */
+ int32_t ruleoutput1; /* ignore if 0x80000000 */
+ int32_t ruleoutput2; /* ignore if 0x80000000 */
+ int32_t ruleoutput3; /* ignore if 0x80000000 */
+ int32_t ruleoutput4; /* ignore if 0x80000000 */
+ int32_t ruleoutput5; /* ignore if 0x80000000 */
+ } u;
+} ambit_log_sample_periodic_value_t;
+
+typedef struct ambit_log_gps_satellite_s {
+ uint8_t sv;
+ uint8_t snr;
+ uint8_t state;
+} ambit_log_gps_satellite_t;
+
+typedef struct ambit_log_sample_s {
+ ambit_log_sample_type_t type; /* type of sample */
+ uint32_t time; /* time from zero */
+ ambit_date_time_t utc_time;
+ union {
+ struct {
+ uint8_t value_count;
+ ambit_log_sample_periodic_value_t *values;
+ } periodic;
+ struct {
+ uint8_t ibi_count;
+ uint16_t ibi[32];
+ } ibi;
+ uint16_t ttff;
+ uint8_t distance_source; /* 2 = GPS, 3 = Wrist */
+ struct {
+ uint8_t event_type; /* 0x01 = manual lap,
+ 0x14 = high interval end,
+ 0x15 = low interval end,
+ 0x16 = interval start,
+ 0x1e = pause,
+ 0x1f = start */
+ ambit_date_time_t date_time;
+ uint32_t duration; /* ms */
+ uint32_t distance; /* meters */
+ } lapinfo;
+ struct {
+ uint8_t source_type; /* 0x04 = pressure */
+ int16_t altitude_offset;
+ int16_t pressure_offset;
+ } altitude_source;
+ struct {
+ uint16_t navvalid;
+ uint16_t navtype;
+ ambit_date_time_t utc_base_time;
+ int32_t latitude; /* degree, scale: 0.0000001, -90 <= latitude <= 90 */
+ int32_t longitude; /* degree, scale: 0.0000001, -180 <= latitude <= 180 */
+ int32_t altitude; /* meters scale: 0.01, -1000 <= altitude <= 10000 */
+ uint16_t speed; /* m/s scale: 0.01 */
+ uint16_t heading; /* degrees, scale: 0.01, 0 <= heading <= 360 */
+ uint32_t ehpe; /* meters scale: 0.01 */
+ uint8_t noofsatellites; /* */
+ uint8_t hdop; /* ? scale: 0.2 */
+ uint8_t satellites_count;
+ ambit_log_gps_satellite_t *satellites;
+ } gps_base;
+ struct {
+ uint8_t noofsatellites; /* */
+ int32_t latitude; /* degree, scale: 0.0000001, -90 <= latitude <= 90 */
+ int32_t longitude; /* degree, scale: 0.0000001, -180 <= latitude <= 180 */
+ uint32_t ehpe; /* meters scale: 0.01 */
+ } gps_small;
+ struct {
+ int32_t latitude; /* degree, scale: 0.0000001, -90 <= latitude <= 90 */
+ int32_t longitude; /* degree, scale: 0.0000001, -180 <= latitude <= 180 */
+ uint32_t ehpe; /* meters scale: 0.01 */
+ uint8_t unknown; /* Unknown data */
+ } gps_tiny;
+ struct {
+ uint8_t hour;
+ uint8_t minute;
+ uint8_t second;
+ } time;
+ struct {
+ uint16_t activitytype;
+ uint32_t custommode;
+ } activity;
+ struct {
+ int32_t latitude; /* degree, scale: 0.0000001, -90 <= latitude <= 90 */
+ int32_t longitude; /* degree, scale: 0.0000001, -180 <= latitude <= 180 */
+ } position;
+ struct {
+ size_t datalen;
+ uint8_t *data;
+ } unknown;
+ } u;
+} ambit_log_sample_t;
+
+typedef struct ambit_log_header_s {
+ ambit_date_time_t date_time;
+ uint32_t duration; /* ms */
+ uint16_t ascent; /* m */
+ uint16_t descent; /* m */
+ uint32_t ascent_time; /* ms */
+ uint32_t descent_time; /* ms */
+ uint32_t recovery_time; /* ms */
+ uint16_t speed_avg; /* m/h */
+ uint16_t speed_max; /* m/h */
+ uint32_t speed_max_time; /* ms */
+ int16_t altitude_max; /* m */
+ int16_t altitude_min; /* m */
+ uint32_t altitude_max_time; /* ms */
+ uint32_t altitude_min_time; /* ms */
+ uint8_t heartrate_avg; /* bpm */
+ uint8_t heartrate_max; /* bpm */
+ uint8_t heartrate_min; /* bpm */
+ uint32_t heartrate_max_time; /* ms */
+ uint32_t heartrate_min_time; /* ms */
+ uint8_t peak_training_effect; /* effect scale 0.1 */
+ uint8_t activity_type;
+ char activity_name[16];
+ int16_t temperature_max; /* degree celsius scale 0.1 */
+ int16_t temperature_min; /* degree celsius scale 0.1 */
+ uint32_t temperature_max_time; /* ms */
+ uint32_t temperature_min_time; /* ms */
+ uint32_t distance; /* m */
+ uint32_t samples_count; /* number of samples in log */
+ uint16_t energy_consumption; /* kcal */
+ uint32_t first_fix_time; /* ms */
+ uint8_t battery_start; /* percent */
+ uint8_t battery_end; /* percent */
+ uint32_t distance_before_calib; /* m */
+
+ uint8_t unknown1[5];
+ uint8_t unknown2;
+ uint8_t unknown3[6];
+ uint8_t unknown4[8];
+ uint8_t unknown5[4];
+ uint8_t unknown6[24];
+} ambit_log_header_t;
+
+typedef struct ambit_log_entry_s {
+ ambit_log_header_t header;
+ uint32_t samples_count;
+ ambit_log_sample_t *samples;
+} ambit_log_entry_t;
+
+/**
+ * Try to detect clock
+ * If clock detected, object handle is returned
+ * \return object handle if clock found, else NULL
+ */
+ambit_object_t *libambit_detect(void);
+
+/**
+ * Close open Ambit object
+ * \param object Object to close
+ */
+void libambit_close(ambit_object_t *object);
+
+/**
+ * Check if detected device is currently supported
+ * \param object Object to check
+ * \return true if device supported, else false
+ */
+bool libambit_device_supported(ambit_object_t *object);
+
+/**
+ * Get device info on connected dev
+ * \param object Object to get info from
+ * \param status Status object to be filled
+ * \return 0 on success, else -1
+ */
+int libambit_device_info_get(ambit_object_t *object, ambit_device_info_t *status);
+
+/**
+ * Set sync message to device display
+ * \param object Object to set display on
+ */
+void libambit_sync_display_show(ambit_object_t *object);
+
+/**
+ * Clear sync message from device display
+ * \param object Object to clear display on
+ */
+void libambit_sync_display_clear(ambit_object_t *object);
+
+/**
+ * Set current date and time to clock
+ * \param object Object to write to
+ * \param date_time Date and time to set
+ * \return 0 on success, else -1
+ */
+int libambit_date_time_set(ambit_object_t *object, struct tm *date_time);
+
+/**
+ * Get status info from device
+ * \param object Object to get status from
+ * \param status Status object to be filled
+ * \return 0 on success, else -1
+ */
+int libambit_device_status_get(ambit_object_t *object, ambit_device_status_t *status);
+
+/**
+ * Get settings from device
+ * \param object Object to get settings from
+ * \param settings Settings object to be filled
+ * \return 0 on success, else -1
+ */
+int libambit_personal_settings_get(ambit_object_t *object, ambit_personal_settings_t *settings);
+
+/**
+ * Read GPS orbit header, useful to check if new write is needed.
+ * NOTE! Reversed byte order compared to the data that is written.
+ * \param object Object to get settings from
+ * \param data Header data (date + !?)
+ * \return 0 on success, else -1
+ */
+int libambit_gps_orbit_header_read(ambit_object_t *object, uint8_t data[8]);
+
+/**
+ * Write GPS orbit data
+ * \param object Object to get settings from
+ * \param data Data to be written
+ * \param datalen Length of data
+ * \return 0 on success, else -1
+ */
+int libambit_gps_orbit_write(ambit_object_t *object, uint8_t *data, size_t datalen);
+
+/**
+ * Callback function for checking if a specific log entry should be read out or
+ * skipped during log readouts
+ * \param object Object reference
+ * \param log_header Pointer to log header that is about to be read out
+ * \return Should return 0 to skip entry, else -1
+ */
+typedef int (*ambit_log_skip_cb)(void *userref, ambit_log_header_t *log_header);
+
+/**
+ * Callback function to push log entry to calling application
+ * \param object Object reference
+ * \param log_entry Complete log entry. NOTE! Caller is responsible of freeing
+ * allocated memory with lib_ambit_log_entry_free()
+ */
+typedef void (*ambit_log_push_cb)(void *userref, ambit_log_entry_t *log_entry);
+
+/**
+ * Callback function to notify about progress
+ * \param object Object reference
+ * \param log_count Number of available logs
+ * \param log_current Current log number in progress
+ * \param progress_percent Total progress in percent
+ */
+typedef void (*ambit_log_progress_cb)(void *userref, uint16_t log_count, uint16_t log_current, uint8_t progress_percent);
+
+/**
+ * Read complete log of all excercises from device (filtered by skip_cb
+ * \param object Object reference
+ * \param skip_cb Callback to be used to check if a specific entry should read
+ * or skipped. Use NULL to get all entries.
+ * \param push_cb Callback to use for pushing read out entry to caller.
+ * \return Number of entries read, or -1 on error
+ * \note Caller is responsible of freeing log entries with
+ * libambit_log_entry_free()
+ */
+int libambit_log_read(ambit_object_t *object, ambit_log_skip_cb skip_cb, ambit_log_push_cb push_cb, ambit_log_progress_cb progress_cb, void *userref);
+
+/**
+ * Free log entry allocated by libambit_log_read
+ * \param log_entry Log entry to free
+ */
+void libambit_log_entry_free(ambit_log_entry_t *log_entry);
+
+#ifdef __cplusplus /* If this is a C++ compiler, end C linkage */
+}
+#endif
+
+#endif /* __LIBAMBIT_H__ */
diff --git a/src/libambit/libambit_int.h b/src/libambit/libambit_int.h
new file mode 100644
index 0000000..4286859
--- /dev/null
+++ b/src/libambit/libambit_int.h
@@ -0,0 +1,157 @@
+/*
+ * (C) Copyright 2014 Emil Ljungdahl
+ *
+ * This file is part of libambit.
+ *
+ * libambit is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * Contributors:
+ *
+ */
+#ifndef __LIBAMBIT_INT_H__
+#define __LIBAMBIT_INT_H__
+
+#include <stdint.h>
+#include "hidapi/hidapi.h"
+#include "libambit.h"
+
+typedef struct ambit_supported_device_s ambit_supported_device_t;
+
+struct ambit_object_s {
+ hid_device *handle;
+ uint16_t vendor_id;
+ uint16_t product_id;
+ uint16_t sequence_no;
+ ambit_supported_device_t *device;
+ ambit_device_info_t device_info;
+
+ struct {
+ uint16_t chunk_size;
+ struct {
+ bool initialized;
+ uint32_t first_entry;
+ uint32_t last_entry;
+ uint32_t entries;
+ uint32_t next_free_address;
+ struct {
+ uint32_t current;
+ uint32_t next;
+ uint32_t prev;
+ } current;
+ uint8_t *buffer;
+ uint8_t *chunks_read;
+ } log;
+ } pmem20;
+};
+
+enum ambit_commands_e {
+ ambit_command_device_info = 0x0000,
+ ambit_command_time = 0x0300,
+ ambit_command_date = 0x0302,
+ ambit_command_status = 0x0306,
+ ambit_command_personal_settings = 0x0b00,
+ ambit_command_unknown1 = 0x0b04,
+ ambit_command_log_count = 0x0b06,
+ ambit_command_log_head_first = 0x0b07,
+ ambit_command_log_head_peek = 0x0b08,
+ ambit_command_log_head_step = 0x0b0a,
+ ambit_command_log_head = 0x0b0b,
+ ambit_command_gps_orbit_head = 0x0b15,
+ ambit_command_data_write = 0x0b16,
+ ambit_command_log_read = 0x0b17,
+ ambit_command_data_tail_len = 0x0b18,
+ ambit_command_lock_check = 0x0b19,
+ ambit_command_lock_set = 0x0b1a,
+ ambit_command_write_start = 0x0b1b // Really!? Just a guess...
+};
+
+// crc16.c
+uint16_t crc16_ccitt_false(unsigned char *buf, size_t buflen);
+uint16_t crc16_ccitt_false_init(unsigned char *buf, size_t buflen, uint16_t crc);
+
+// personal.c
+int libambit_personal_settings_parse(uint8_t *data, size_t datalen, ambit_personal_settings_t *settings);
+
+// pmem20.c
+int libambit_pmem20_init(ambit_object_t *object, uint16_t chunk_size);
+int libambit_pmem20_deinit(ambit_object_t *object);
+int libambit_pmem20_log_init(ambit_object_t *object);
+int libambit_pmem20_log_deinit(ambit_object_t *object);
+int libambit_pmem20_log_next_header(ambit_object_t *object, ambit_log_header_t *log_header);
+ambit_log_entry_t *libambit_pmem20_log_read_entry(ambit_object_t *object);
+int libambit_pmem20_log_parse_header(uint8_t *data, size_t datalen, ambit_log_header_t *log_header);
+int libambit_pmem20_gps_orbit_write(ambit_object_t *object, uint8_t *data, size_t datalen);
+
+// protocol.c
+int libambit_protocol_command(ambit_object_t *object, uint16_t command, uint8_t *data, size_t datalen, uint8_t **reply_data, size_t *replylen, uint8_t legacy_format);
+void libambit_protocol_free(uint8_t *data);
+
+// debug.c
+typedef enum debug_level_e {
+ debug_level_err,
+ debug_level_warn,
+ debug_level_info
+} debug_level_t;
+void debug_printf(debug_level_t level, const char *file, int line, const char *func, const char *fmt, ...);
+#ifdef DEBUG_PRINT_ERROR
+#define LOG_ERROR(fmt, ...) debug_printf(debug_level_err, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
+#else
+#define LOG_ERROR(fmt, ...)
+#endif
+#ifdef DEBUG_PRINT_WARNING
+#define LOG_WARNING(fmt, ...) debug_printf(debug_level_warn, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
+#else
+#define LOG_WARNING(fmt, ...)
+#endif
+#ifdef DEBUG_PRINT_INFO
+#define LOG_INFO(fmt, ...) debug_printf(debug_level_info, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
+#else
+#define LOG_INFO(fmt, ...)
+#endif
+
+// static helpers
+static inline uint8_t read8(uint8_t *buf, size_t offset)
+{
+ return buf[offset];
+}
+
+static inline uint16_t read16(uint8_t *buf, size_t offset)
+{
+ return (buf[offset] | (buf[offset+1] << 8));
+}
+
+static inline uint32_t read32(uint8_t *buf, size_t offset)
+{
+ return (buf[offset] | (buf[offset+1] << 8) | (buf[offset+2] << 16) | (buf[offset+3] << 24));
+}
+
+static inline uint8_t read8inc(uint8_t *buf, size_t *offset)
+{
+ *offset += 1;
+ return buf[(*offset)-1];
+}
+
+static inline uint16_t read16inc(uint8_t *buf, size_t *offset)
+{
+ *offset += 2;
+ return (buf[(*offset)-2] | (buf[(*offset)-1] << 8));
+}
+
+static inline uint32_t read32inc(uint8_t *buf, size_t *offset)
+{
+ *offset += 4;
+ return (buf[(*offset)-4] | (buf[(*offset)-3] << 8) | (buf[(*offset)-2] << 16) | (buf[(*offset)-1] << 24));
+}
+
+#endif /* __LIBAMBIT_INT_H__ */
diff --git a/src/libambit/personal.c b/src/libambit/personal.c
new file mode 100644
index 0000000..9cfb66c
--- /dev/null
+++ b/src/libambit/personal.c
@@ -0,0 +1,122 @@
+/*
+ * (C) Copyright 2014 Emil Ljungdahl
+ *
+ * This file is part of libambit.
+ *
+ * libambit is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * Contributors:
+ *
+ */
+#include "libambit.h"
+#include "libambit_int.h"
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+
+/*
+ * Local definitions
+ */
+
+/*
+ * Public functions
+ */
+int libambit_personal_settings_parse(uint8_t *data, size_t datalen, ambit_personal_settings_t *settings)
+{
+ size_t offset = 0;
+
+ // Check that data is long enough
+ if (datalen < 132) {
+ return -1;
+ }
+
+ offset = 1;
+ settings->sportmode_button_lock = read8inc(data, &offset);
+ settings->timemode_button_lock = read8inc(data, &offset);
+ offset += 1;
+ settings->compass_declination = read16inc(data, &offset);
+ offset += 2;
+ settings->units_mode = read8inc(data, &offset);
+
+ settings->units.pressure = read8inc(data, &offset);
+ settings->units.altitude = read8inc(data, &offset);
+ settings->units.distance = read8inc(data, &offset);
+ settings->units.height = read8inc(data, &offset);
+ settings->units.temperature = read8inc(data, &offset);
+ settings->units.verticalspeed = read8inc(data, &offset);
+ settings->units.weight = read8inc(data, &offset);
+ settings->units.compass = read8inc(data, &offset);
+ settings->units.heartrate = read8inc(data, &offset);
+ settings->units.speed = read8inc(data, &offset);
+
+ settings->gps_position_format = read8inc(data, &offset);
+ settings->language = read8inc(data, &offset);
+ settings->navigation_style = read8inc(data, &offset);
+ offset += 2;
+ settings->sync_time_w_gps = read8inc(data, &offset);
+ settings->time_format = read8inc(data, &offset);
+
+ settings->alarm.hour = read8inc(data, &offset);
+ settings->alarm.minute = read8inc(data, &offset);
+
+ settings->alarm_enable = read8inc(data, &offset);
+
+ offset += 2;
+ settings->dual_time.hour = read8inc(data, &offset);
+ settings->dual_time.minute = read8inc(data, &offset);
+
+ offset += 3;
+
+ settings->date_format = read8inc(data, &offset);
+
+ offset += 3;
+
+ settings->tones_mode = read8inc(data, &offset);
+
+ offset += 3;
+
+ settings->backlight_mode = read8inc(data, &offset);
+ settings->backlight_brightness = read8inc(data, &offset);
+ settings->display_brightness = read8inc(data, &offset);
+ settings->display_is_negative = read8inc(data, &offset);
+ settings->weight = read16inc(data, &offset);
+ settings->birthyear = read16inc(data, &offset);
+ settings->max_hr = read8inc(data, &offset);
+ settings->rest_hr = read8inc(data, &offset);
+ settings->fitness_level = read8inc(data, &offset);
+ settings->is_male = read8inc(data, &offset);
+ settings->length = read8inc(data, &offset);
+
+ offset += 3;
+
+ settings->alti_baro_mode = read8inc(data, &offset);
+
+ offset += 1;
+
+ settings->fused_alti_disabled = read8inc(data, &offset);
+
+ offset = 0x80;
+ settings->bikepod_calibration = read16inc(data, &offset);
+ settings->bikepod_calibration2 = read16inc(data, &offset);
+
+ if (datalen >= 137) {
+ // Only Ambit 2 got this!
+ settings->bikepod_calibration3 = read16inc(data, &offset);
+ settings->footpod_calibration = read16inc(data, &offset);
+ settings->automatic_bikepower_calib = read8inc(data, &offset);
+ }
+
+ return 0;
+}
diff --git a/src/libambit/pmem20.c b/src/libambit/pmem20.c
new file mode 100644
index 0000000..b3646ea
--- /dev/null
+++ b/src/libambit/pmem20.c
@@ -0,0 +1,912 @@
+/*
+ * (C) Copyright 2014 Emil Ljungdahl
+ *
+ * This file is part of libambit.
+ *
+ * libambit is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * Contributors:
+ *
+ */
+#include "libambit.h"
+#include "libambit_int.h"
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+
+/*
+ * Local definitions
+ */
+#define PMEM20_LOG_START 0x000f4240
+#define PMEM20_LOG_SIZE 0x0029f630 /* 2 750 000 */
+#define PMEM20_LOG_WRAP_START_OFFSET 0x00000012
+#define PMEM20_LOG_WRAP_BUFFER_MARGIN 0x00010000 /* Max theoretical size of sample */
+#define PMEM20_LOG_HEADER_MIN_LEN 512 /* Header actually longer, but not interesting*/
+
+#define PMEM20_GPS_ORBIT_START 0x000704e0
+
+typedef struct __attribute__((__packed__)) periodic_sample_spec_s {
+ uint16_t type;
+ uint16_t offset;
+ uint16_t length;
+} periodic_sample_spec_t;
+
+/*
+ * Static functions
+ */
+static int parse_sample(uint8_t *buf, size_t offset, uint8_t **spec, ambit_log_entry_t *log_entry, size_t *sample_count);
+static int read_upto(ambit_object_t *object, uint32_t address, uint32_t length);
+static int read_log_chunk(ambit_object_t *object, uint32_t address);
+static int write_data_chunk(ambit_object_t *object, uint32_t address, size_t buffer_count, uint8_t **buffers, size_t *buffer_sizes);
+static void add_time(ambit_date_time_t *intime, int32_t offset, ambit_date_time_t *outtime);
+static int is_leap(unsigned int y);
+static void to_timeval(ambit_date_time_t *ambit_time, struct timeval *timeval);
+
+/*
+ * Static variables
+ */
+
+
+
+/*
+ * Public functions
+ */
+int libambit_pmem20_init(ambit_object_t *object, uint16_t chunk_size)
+{
+ object->pmem20.chunk_size = chunk_size;
+
+ return 0;
+}
+
+int libambit_pmem20_log_init(ambit_object_t *object)
+{
+ int ret = -1;
+ size_t offset;
+
+ // Allocate buffer for complete memory
+ if (object->pmem20.log.buffer != NULL) {
+ free(object->pmem20.log.buffer);
+ }
+ if (object->pmem20.log.chunks_read != NULL) {
+ free(object->pmem20.log.chunks_read);
+ }
+ memset(&object->pmem20.log, 0, sizeof(object->pmem20.log));
+
+ object->pmem20.log.buffer = malloc(PMEM20_LOG_SIZE + PMEM20_LOG_WRAP_BUFFER_MARGIN);
+ object->pmem20.log.chunks_read = malloc((PMEM20_LOG_SIZE/object->pmem20.chunk_size)+1);
+
+ if (object->pmem20.log.buffer != NULL && object->pmem20.log.chunks_read != NULL) {
+ // Set all chunks to NOT read
+ memset(object->pmem20.log.chunks_read, 0, (PMEM20_LOG_SIZE/object->pmem20.chunk_size)+1);
+
+ // Read initial log header
+ LOG_INFO("Reading first log data chunk");
+ ret = read_log_chunk(object, PMEM20_LOG_START);
+
+ if (ret == 0) {
+ // Parse PMEM header
+ offset = 0;
+ object->pmem20.log.last_entry = read32inc(object->pmem20.log.buffer, &offset);
+ object->pmem20.log.first_entry = read32inc(object->pmem20.log.buffer, &offset);
+ object->pmem20.log.entries = read32inc(object->pmem20.log.buffer, &offset);
+ object->pmem20.log.next_free_address = read32inc(object->pmem20.log.buffer, &offset);
+ object->pmem20.log.current.current = PMEM20_LOG_START;
+ object->pmem20.log.current.next = object->pmem20.log.first_entry;
+ object->pmem20.log.current.prev = PMEM20_LOG_START;
+
+ LOG_INFO("log data header read, entries=%d, first_entry=%08x, last_entry=%08x, next_free_address=%08x", object->pmem20.log.entries, object->pmem20.log.first_entry, object->pmem20.log.last_entry, object->pmem20.log.next_free_address);
+
+ // Set initialized
+ object->pmem20.log.initialized = true;
+ }
+ else {
+ LOG_WARNING("Failed to read first data chunk");
+ }
+ }
+
+ return ret;
+}
+
+int libambit_pmem20_deinit(ambit_object_t *object)
+{
+ if (object->pmem20.log.buffer != NULL) {
+ free(object->pmem20.log.buffer);
+ }
+ if (object->pmem20.log.chunks_read != NULL) {
+ free(object->pmem20.log.chunks_read);
+ }
+ memset(&object->pmem20.log, 0, sizeof(object->pmem20.log));
+
+ return 0;
+}
+
+int libambit_pmem20_log_next_header(ambit_object_t *object, ambit_log_header_t *log_header)
+{
+ int ret = -1;
+ size_t buffer_offset;
+ uint16_t tmp_len;
+
+ LOG_INFO("Reading header of next log entry");
+
+ if (!object->pmem20.log.initialized) {
+ LOG_ERROR("Trying to get next log without initialization");
+ return -1;
+ }
+
+ // Check if we reached end of entries
+ if (object->pmem20.log.current.current == object->pmem20.log.current.next) {
+ LOG_INFO("No more entries to read");
+ return 0;
+ }
+
+ if (read_upto(object, object->pmem20.log.current.next, PMEM20_LOG_HEADER_MIN_LEN) == 0) {
+ buffer_offset = (object->pmem20.log.current.next - PMEM20_LOG_START);
+ // First check that header seems to be correctly present
+ if (strncmp((char*)object->pmem20.log.buffer + buffer_offset, "PMEM", 4) == 0) {
+ object->pmem20.log.current.current = object->pmem20.log.current.next;
+ buffer_offset += 4;
+ object->pmem20.log.current.next = read32inc(object->pmem20.log.buffer, &buffer_offset);
+ object->pmem20.log.current.prev = read32inc(object->pmem20.log.buffer, &buffer_offset);
+ tmp_len = read16inc(object->pmem20.log.buffer, &buffer_offset);
+ buffer_offset += tmp_len;
+ tmp_len = read16inc(object->pmem20.log.buffer, &buffer_offset);
+ if (libambit_pmem20_log_parse_header(object->pmem20.log.buffer + buffer_offset, tmp_len, log_header) == 0) {
+ LOG_INFO("Log entry header parsed");
+ ret = 1;
+ }
+ else {
+ LOG_ERROR("Failed to parse log entry header correctly");
+ }
+ }
+ else {
+ LOG_ERROR("Failed to find valid log entry header start");
+ }
+ }
+ else {
+ LOG_WARNING("Failed to read log entry header");
+ }
+
+ // Unset initialized of something went wrong
+ if (ret < 0) {
+ object->pmem20.log.initialized = false;
+ }
+
+ return ret;
+}
+
+ambit_log_entry_t *libambit_pmem20_log_read_entry(ambit_object_t *object)
+{
+ // Note! We assume that the caller has called libambit_pmem20_log_next_header just before
+ uint8_t *periodic_sample_spec;
+ uint16_t tmp_len, sample_len;
+ size_t buffer_offset, sample_count = 0, i;
+ ambit_log_entry_t *log_entry;
+ ambit_log_sample_t *last_periodic = NULL, *utcsource = NULL, *altisource = NULL;
+ ambit_date_time_t utcbase;
+ uint32_t altisource_index = 0;
+ uint32_t last_base_lat = 0, last_base_long = 0;
+ uint32_t last_small_lat = 0, last_small_long = 0;
+ uint32_t last_ehpe = 0;
+
+ if (!object->pmem20.log.initialized) {
+ LOG_ERROR("Trying to get log entry without initialization");
+ return NULL;
+ }
+
+ // Allocate log entry
+ if ((log_entry = calloc(1, sizeof(ambit_log_entry_t))) == NULL) {
+ object->pmem20.log.initialized = false;
+ return NULL;
+ }
+
+ LOG_INFO("Reading log entry from address=%08x", object->pmem20.log.current.current);
+
+ buffer_offset = (object->pmem20.log.current.current - PMEM20_LOG_START);
+ buffer_offset += 12;
+ // Read samples content definition
+ tmp_len = read16inc(object->pmem20.log.buffer, &buffer_offset);
+ periodic_sample_spec = object->pmem20.log.buffer + buffer_offset;
+ buffer_offset += tmp_len;
+ // Parse header
+ tmp_len = read16inc(object->pmem20.log.buffer, &buffer_offset);
+ if (libambit_pmem20_log_parse_header(object->pmem20.log.buffer + buffer_offset, tmp_len, &log_entry->header) != 0) {
+ LOG_ERROR("Failed to parse log entry header correctly");
+ free(log_entry);
+ object->pmem20.log.initialized = false;
+ return NULL;
+ }
+ buffer_offset += tmp_len;
+ // Now that we know number of samples, allocate space for them!
+ if ((log_entry->samples = calloc(log_entry->header.samples_count, sizeof(ambit_log_sample_t))) == NULL) {
+ free(log_entry);
+ object->pmem20.log.initialized = false;
+ return NULL;
+ }
+ log_entry->samples_count = log_entry->header.samples_count;
+
+ LOG_INFO("Log entry got %d samples, reading", log_entry->samples_count);
+
+ // OK, so we are at start of samples, get them all!
+ while (sample_count < log_entry->samples_count) {
+ /* NOTE! The double reads below seems a bit unoptimized,
+ but if we need optimization, we should optimize read_upto
+ instead...
+ To ease the pain on wraparound we simply duplicate the sample
+ to the end of the buffer. */
+
+ // First check for log area wrap
+ if (buffer_offset >= PMEM20_LOG_SIZE - 1) {
+ read_upto(object, PMEM20_LOG_START + PMEM20_LOG_WRAP_START_OFFSET, 2);
+ sample_len = read16(object->pmem20.log.buffer, PMEM20_LOG_WRAP_START_OFFSET);
+ }
+ else if (buffer_offset == PMEM20_LOG_SIZE - 2) {
+ read_upto(object, PMEM20_LOG_START + PMEM20_LOG_WRAP_START_OFFSET, 1);
+ sample_len = object->pmem20.log.buffer[buffer_offset] | (object->pmem20.log.buffer[PMEM20_LOG_WRAP_START_OFFSET] << 8);
+ }
+ else {
+ read_upto(object, PMEM20_LOG_START + buffer_offset, 2);
+ sample_len = read16(object->pmem20.log.buffer, buffer_offset);
+ }
+
+ // Read all data
+ if (buffer_offset + 2 < (PMEM20_LOG_SIZE-1)) {
+ read_upto(object, PMEM20_LOG_START + buffer_offset + 2, sample_len);
+ }
+ if (buffer_offset + 2 + sample_len > PMEM20_LOG_SIZE) {
+ read_upto(object, PMEM20_LOG_START + PMEM20_LOG_WRAP_START_OFFSET, (buffer_offset + 2 + sample_len) - PMEM20_LOG_SIZE);
+ memcpy(object->pmem20.log.buffer + PMEM20_LOG_SIZE, object->pmem20.log.buffer + PMEM20_LOG_WRAP_START_OFFSET, (buffer_offset + 2 + sample_len) - PMEM20_LOG_SIZE);
+ }
+
+ if (parse_sample(object->pmem20.log.buffer, buffer_offset, &periodic_sample_spec, log_entry, &sample_count) == 1) {
+ // Calculate times
+ if (log_entry->samples[sample_count-1].type == ambit_log_sample_type_periodic) {
+ last_periodic = &log_entry->samples[sample_count-1];
+ }
+ else if (last_periodic != NULL) {
+ log_entry->samples[sample_count-1].time += last_periodic->time;
+ }
+ else {
+ log_entry->samples[sample_count-1].time = 0;
+ }
+
+ if (utcsource == NULL && log_entry->samples[sample_count-1].type == ambit_log_sample_type_gps_base) {
+ utcsource = &log_entry->samples[sample_count-1];
+ // Calculate UTC base time
+ add_time(&utcsource->u.gps_base.utc_base_time, 0-utcsource->time, &utcbase);
+ }
+
+ // Calculate positions
+ if (log_entry->samples[sample_count-1].type == ambit_log_sample_type_gps_base) {
+ last_base_lat = log_entry->samples[sample_count-1].u.gps_base.latitude;
+ last_base_long = log_entry->samples[sample_count-1].u.gps_base.longitude;
+ last_small_lat = log_entry->samples[sample_count-1].u.gps_base.latitude;
+ last_small_long = log_entry->samples[sample_count-1].u.gps_base.longitude;
+ last_ehpe = log_entry->samples[sample_count-1].u.gps_base.ehpe;
+ }
+ else if (log_entry->samples[sample_count-1].type == ambit_log_sample_type_gps_small) {
+ log_entry->samples[sample_count-1].u.gps_small.latitude = last_base_lat + log_entry->samples[sample_count-1].u.gps_small.latitude*10;
+ log_entry->samples[sample_count-1].u.gps_small.longitude = last_base_long + log_entry->samples[sample_count-1].u.gps_small.longitude*10;
+ last_small_lat = log_entry->samples[sample_count-1].u.gps_small.latitude;
+ last_small_long = log_entry->samples[sample_count-1].u.gps_small.longitude;
+ last_ehpe = log_entry->samples[sample_count-1].u.gps_small.ehpe;
+ }
+ else if (log_entry->samples[sample_count-1].type == ambit_log_sample_type_gps_tiny) {
+ log_entry->samples[sample_count-1].u.gps_tiny.latitude = last_small_lat + log_entry->samples[sample_count-1].u.gps_tiny.latitude*10;
+ log_entry->samples[sample_count-1].u.gps_tiny.longitude = last_small_long + log_entry->samples[sample_count-1].u.gps_tiny.longitude*10;
+ log_entry->samples[sample_count-1].u.gps_tiny.ehpe = (last_ehpe > 700 ? 700 : last_ehpe);
+ last_small_lat = log_entry->samples[sample_count-1].u.gps_tiny.latitude;
+ last_small_long = log_entry->samples[sample_count-1].u.gps_tiny.longitude;
+ }
+
+ if (altisource == NULL && log_entry->samples[sample_count-1].type == ambit_log_sample_type_altitude_source) {
+ altisource = &log_entry->samples[sample_count-1];
+ altisource_index = sample_count-1;
+ }
+ }
+ buffer_offset += 2 + sample_len;
+ // Wrap
+ if (buffer_offset >= PMEM20_LOG_SIZE) {
+ buffer_offset = PMEM20_LOG_WRAP_START_OFFSET + (buffer_offset - PMEM20_LOG_SIZE);
+ }
+ }
+
+ // Loop through samples again and correct times etc
+ for (sample_count = 0; sample_count < log_entry->header.samples_count; sample_count++) {
+ // Set UTC times (if UTC source found)
+ if (utcsource != NULL) {
+ add_time(&utcbase, log_entry->samples[sample_count].time, &log_entry->samples[sample_count].utc_time);
+ }
+ // Correct altitude based on altitude offset in altitude source
+ if (altisource != NULL && log_entry->samples[sample_count].type == ambit_log_sample_type_periodic && sample_count < altisource_index) {
+ for (i=0; i<log_entry->samples[sample_count].u.periodic.value_count; i++) {
+ if (log_entry->samples[sample_count].u.periodic.values[i].type == ambit_log_sample_periodic_type_sealevelpressure) {
+ log_entry->samples[sample_count].u.periodic.values[i].u.sealevelpressure += altisource->u.altitude_source.pressure_offset;
+ }
+ if (log_entry->samples[sample_count].u.periodic.values[i].type == ambit_log_sample_periodic_type_altitude) {
+ log_entry->samples[sample_count].u.periodic.values[i].u.altitude += altisource->u.altitude_source.altitude_offset;
+ }
+ }
+ }
+ }
+
+ return log_entry;
+}
+
+int libambit_pmem20_log_parse_header(uint8_t *data, size_t datalen, ambit_log_header_t *log_header)
+{
+ size_t offset = 0;
+
+ // Check that header is long enough to be parsed correctly
+ if (datalen < 129) {
+ return -1;
+ }
+
+ offset = 1;
+ log_header->date_time.year = read16inc(data, &offset);
+ log_header->date_time.month = read8inc(data, &offset);
+ log_header->date_time.day = read8inc(data, &offset);
+ log_header->date_time.hour = read8inc(data, &offset);
+ log_header->date_time.minute = read8inc(data, &offset);
+ log_header->date_time.msec = read8inc(data, &offset)*1000;
+
+ memcpy(log_header->unknown1, data+offset, 5);
+ offset += 5;
+
+ log_header->duration = read32inc(data, &offset)*100; // seconds 0.1
+ log_header->ascent = read16inc(data, &offset);
+ log_header->descent = read16inc(data, &offset);
+ log_header->ascent_time = read32inc(data, &offset)*1000;
+ log_header->descent_time = read32inc(data, &offset)*1000;
+ log_header->recovery_time = read16inc(data, &offset)*60*1000;
+ log_header->speed_avg = read16inc(data, &offset)*10; // 10 m/h
+ log_header->speed_max = read16inc(data, &offset)*10; // 10 m/h
+ log_header->altitude_max = read16inc(data, &offset);
+ log_header->altitude_min = read16inc(data, &offset);
+ log_header->heartrate_avg = read8inc(data, &offset);
+ log_header->heartrate_max = read8inc(data, &offset);
+ log_header->peak_training_effect = read8inc(data, &offset);
+ log_header->activity_type = read8inc(data, &offset);
+ memcpy(log_header->activity_name, data + offset, 16);
+ offset += 16;
+ log_header->heartrate_min = read8inc(data, &offset);
+
+ log_header->unknown2 = read8inc(data, &offset);
+
+ log_header->temperature_max = read16inc(data, &offset);
+ log_header->temperature_min = read16inc(data, &offset);
+ log_header->distance = read32inc(data, &offset);
+ log_header->samples_count = read32inc(data, &offset);
+ log_header->energy_consumption = read16inc(data, &offset);
+
+ memcpy(log_header->unknown3, data+offset, 6);
+ offset += 6;
+
+ log_header->speed_max_time = read32inc(data, &offset);
+ log_header->altitude_max_time = read32inc(data, &offset);
+ log_header->altitude_min_time = read32inc(data, &offset);
+ log_header->heartrate_max_time = read32inc(data, &offset);
+ log_header->heartrate_min_time = read32inc(data, &offset);
+ log_header->temperature_max_time = read32inc(data, &offset);
+ log_header->temperature_min_time = read32inc(data, &offset);
+
+ memcpy(log_header->unknown4, data+offset, 8);
+ offset += 8;
+
+ log_header->first_fix_time = read16inc(data, &offset)*1000;
+ log_header->battery_start = read8inc(data, &offset);
+ log_header->battery_end = read8inc(data, &offset);
+
+ memcpy(log_header->unknown5, data+offset, 4);
+ offset += 4;
+
+ log_header->distance_before_calib = read32inc(data, &offset);
+
+ if (datalen >= offset + 24) {
+ memcpy(log_header->unknown6, data+offset, 24);
+ offset += 24;
+ }
+
+ return 0;
+}
+
+int libambit_pmem20_gps_orbit_write(ambit_object_t *object, uint8_t *data, size_t datalen)
+{
+ int ret = -1;
+ uint8_t *bufptrs[2];
+ size_t bufsizes[2];
+ uint8_t startheader[4];
+ uint8_t tailbuf[8];
+ uint32_t *_sizeptr = (uint32_t*)&startheader[0];
+ uint32_t address = PMEM20_GPS_ORBIT_START;
+ size_t offset = 0;
+
+ *_sizeptr = htole32(datalen);
+ bufptrs[0] = startheader;
+ bufsizes[0] = 4;
+ bufptrs[1] = data;
+ bufsizes[1] = object->pmem20.chunk_size - 4; // We assume that data is
+ // always > chunk_size
+
+ // Write first chunk (including length)
+ ret = write_data_chunk(object, address, 2, bufptrs, bufsizes);
+ offset += bufsizes[1];
+ address += object->pmem20.chunk_size;
+
+ // Write rest of the chunks
+ while (ret == 0 && offset < datalen) {
+ bufptrs[0] = data + offset;
+ bufsizes[0] = (datalen - offset > object->pmem20.chunk_size ? object->pmem20.chunk_size : datalen - offset);
+
+ ret = write_data_chunk(object, address, 1, bufptrs, bufsizes);
+ offset += bufsizes[0];
+ address += bufsizes[0];
+ }
+
+ // Write tail length (or what is really!?)
+ if (ret == 0) {
+ *((uint32_t*)(&tailbuf[0])) = htole32(PMEM20_GPS_ORBIT_START);
+ *((uint32_t*)(&tailbuf[4])) = htole32(bufsizes[0]);
+ ret = libambit_protocol_command(object, ambit_command_data_tail_len, tailbuf, sizeof(tailbuf), NULL, NULL, 0);
+ }
+
+ return ret;
+}
+
+/**
+ * Parse the given sample
+ * \return number of samples added (1 or 0)
+ */
+static int parse_sample(uint8_t *buf, size_t offset, uint8_t **spec, ambit_log_entry_t *log_entry, size_t *sample_count)
+{
+ int ret = 0;
+ size_t int_offset = offset;
+ uint16_t sample_len = read16inc(buf, &int_offset);
+ uint8_t sample_type = read8inc(buf, &int_offset);
+ uint8_t episodic_type;
+ uint16_t spec_count, spec_type, spec_offset;
+ periodic_sample_spec_t *spec_entry;
+ int i;
+
+ switch (sample_type) {
+ case 0: /* periodic sample specifier */
+ // Update specifier on input
+ *spec = buf + offset + 2;
+ break;
+ case 2: /* periodic sample */
+ log_entry->samples[*sample_count].type = ambit_log_sample_type_periodic;
+ log_entry->samples[*sample_count].time = read32(buf, offset + sample_len - 2);
+
+ // Loop through specifier and set corresponding fields
+ spec_count = read16(*spec, 1);
+ log_entry->samples[*sample_count].u.periodic.value_count = spec_count;
+ log_entry->samples[*sample_count].u.periodic.values = calloc(spec_count, sizeof(ambit_log_sample_periodic_value_t));
+ for (i=0, spec_entry = (periodic_sample_spec_t*)(*spec + 3); i<spec_count; i++, spec_entry++) {
+ spec_type = le16toh(spec_entry->type);
+ spec_offset = le16toh(spec_entry->offset);
+ switch(spec_type) {
+ case ambit_log_sample_periodic_type_latitude:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_latitude;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.latitude = read32(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_longitude:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_longitude;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.longitude = read32(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_distance:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_distance;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.distance = read32(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_speed:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_speed;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.speed = read16(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_hr:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_hr;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.hr = read8(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_time:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_time;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.time = read32(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_gpsspeed:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_gpsspeed;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.gpsspeed = read16(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_wristaccspeed:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_wristaccspeed;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.wristaccspeed = read16(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_bikepodspeed:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_bikepodspeed;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.bikepodspeed = read16(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_ehpe:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_ehpe;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.ehpe = read32(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_evpe:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_evpe;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.evpe = read32(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_altitude:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_altitude;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.altitude = read16(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_abspressure:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_abspressure;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.abspressure = read32(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_energy:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_energy;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.energy = read16(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_temperature:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_temperature;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.temperature = read16(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_charge:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_charge;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.charge = read8(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_gpsaltitude:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_gpsaltitude;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.gpsaltitude = read32(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_gpsheading:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_gpsheading;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.gpsheading = read16(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_gpshdop:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_gpshdop;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.gpshdop = read8(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_gpsvdop:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_gpsvdop;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.gpsvdop = read8(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_wristcadence:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_wristcadence;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.wristcadence = read16(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_snr:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_snr;
+ memcpy(log_entry->samples[*sample_count].u.periodic.values[i].u.snr, buf + int_offset + spec_offset, 16);
+ break;
+ case ambit_log_sample_periodic_type_noofsatellites:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_noofsatellites;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.noofsatellites = read8(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_sealevelpressure:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_sealevelpressure;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.sealevelpressure = read16(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_verticalspeed:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_verticalspeed;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.verticalspeed = read16(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_cadence:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_cadence;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.cadence = read8(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_bikepower:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_bikepower;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.bikepower = read16(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_swimingstrokecnt:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_swimingstrokecnt;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.swimingstrokecnt = read32(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_ruleoutput1:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_ruleoutput1;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.ruleoutput1 = read32(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_ruleoutput2:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_ruleoutput2;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.ruleoutput2 = read32(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_ruleoutput3:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_ruleoutput3;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.ruleoutput3 = read32(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_ruleoutput4:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_ruleoutput4;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.ruleoutput4 = read32(buf, int_offset + spec_offset);
+ break;
+ case ambit_log_sample_periodic_type_ruleoutput5:
+ log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_ruleoutput5;
+ log_entry->samples[*sample_count].u.periodic.values[i].u.ruleoutput5 = read32(buf, int_offset + spec_offset);
+ break;
+ }
+ }
+ ret = 1;
+ break;
+ case 3:
+ // First parameter is relative time
+ log_entry->samples[*sample_count].time = read32inc(buf, &int_offset);
+ episodic_type = read8inc(buf, &int_offset);
+ switch (episodic_type) {
+ case 0x04:
+ log_entry->samples[*sample_count].type = ambit_log_sample_type_logpause;
+ break;
+ case 0x05:
+ log_entry->samples[*sample_count].type = ambit_log_sample_type_logrestart;
+ break;
+ case 0x06:
+ log_entry->samples[*sample_count].type = ambit_log_sample_type_ibi;
+ for (i=0; i<(sample_len - 6)/2; i++) {
+ log_entry->samples[*sample_count].u.ibi.ibi[i] = read16inc(buf, &int_offset);
+ }
+ log_entry->samples[*sample_count].u.ibi.ibi_count = (sample_len - 6)/2;
+ break;
+ case 0x07:
+ log_entry->samples[*sample_count].type = ambit_log_sample_type_ttff;
+ log_entry->samples[*sample_count].u.ttff = read16inc(buf, &int_offset);
+ break;
+ case 0x08:
+ log_entry->samples[*sample_count].type = ambit_log_sample_type_distance_source;
+ log_entry->samples[*sample_count].u.distance_source = read8inc(buf, &int_offset);
+ break;
+ case 0x09:
+ log_entry->samples[*sample_count].type = ambit_log_sample_type_lapinfo;
+ log_entry->samples[*sample_count].u.lapinfo.event_type = read8inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.lapinfo.date_time.year = read16inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.lapinfo.date_time.month = read8inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.lapinfo.date_time.day = read8inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.lapinfo.date_time.hour = read8inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.lapinfo.date_time.minute = read8inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.lapinfo.date_time.msec = read8inc(buf, &int_offset)*1000;
+ log_entry->samples[*sample_count].u.lapinfo.duration = read32inc(buf, &int_offset)*100;
+ log_entry->samples[*sample_count].u.lapinfo.distance = read32inc(buf, &int_offset);
+ break;
+ case 0x0d:
+ log_entry->samples[*sample_count].type = ambit_log_sample_type_altitude_source;
+ log_entry->samples[*sample_count].u.altitude_source.source_type = read8inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.altitude_source.altitude_offset = read16inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.altitude_source.pressure_offset = read16inc(buf, &int_offset);
+ break;
+ case 0x0f:
+ log_entry->samples[*sample_count].type = ambit_log_sample_type_gps_base;
+ log_entry->samples[*sample_count].u.gps_base.navvalid = read16inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_base.navtype = read16inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_base.utc_base_time.year = read16inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_base.utc_base_time.month = read8inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_base.utc_base_time.day = read8inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_base.utc_base_time.hour = read8inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_base.utc_base_time.minute = read8inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_base.utc_base_time.msec = read16inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_base.latitude = read32inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_base.longitude = read32inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_base.altitude = read32inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_base.speed = read16inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_base.heading = read16inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_base.ehpe = read32inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_base.noofsatellites = read8inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_base.hdop = read8inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_base.satellites = calloc((sample_len - 40)/4, sizeof(ambit_log_gps_satellite_t));
+ for (i=0; i<(sample_len - 40)/4; i++) {
+ log_entry->samples[*sample_count].u.gps_base.satellites[i].sv = read8inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_base.satellites[i].state = read8inc(buf, &int_offset);
+ int_offset += 1;
+ log_entry->samples[*sample_count].u.gps_base.satellites[i].snr = read8inc(buf, &int_offset);
+ }
+ log_entry->samples[*sample_count].u.gps_base.satellites_count = (sample_len - 40)/4;
+ break;
+ case 0x10:
+ log_entry->samples[*sample_count].type = ambit_log_sample_type_gps_small;
+ log_entry->samples[*sample_count].u.gps_small.latitude = (int16_t)read16inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_small.longitude = (int16_t)read16inc(buf, &int_offset);
+ int_offset += 2; // Time (seconds)
+ log_entry->samples[*sample_count].u.gps_small.ehpe = read8inc(buf, &int_offset)*100;
+ log_entry->samples[*sample_count].u.gps_small.noofsatellites = read8inc(buf, &int_offset);
+ break;
+ case 0x11:
+ log_entry->samples[*sample_count].type = ambit_log_sample_type_gps_tiny;
+ log_entry->samples[*sample_count].u.gps_tiny.latitude = (int8_t)read8inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_tiny.longitude = (int8_t)read8inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.gps_tiny.unknown = read8inc(buf, &int_offset);
+ break;
+ case 0x12:
+ log_entry->samples[*sample_count].type = ambit_log_sample_type_time;
+ log_entry->samples[*sample_count].u.time.hour = read8inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.time.minute = read8inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.time.second = read8inc(buf, &int_offset);
+ break;
+ case 0x18:
+ log_entry->samples[*sample_count].type = ambit_log_sample_type_activity;
+ log_entry->samples[*sample_count].u.activity.activitytype = read16inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.activity.custommode = read32inc(buf, &int_offset);
+ break;
+ case 0x1b:
+ log_entry->samples[*sample_count].type = ambit_log_sample_type_position;
+ log_entry->samples[*sample_count].u.position.latitude = read32inc(buf, &int_offset);
+ log_entry->samples[*sample_count].u.position.longitude = read32inc(buf, &int_offset);
+ break;
+ default:
+ LOG_WARNING("Found unknown episodic sample type (0x%02x)", episodic_type);
+ log_entry->samples[*sample_count].type = ambit_log_sample_type_unknown;
+ log_entry->samples[*sample_count].u.unknown.datalen = sample_len;
+ log_entry->samples[*sample_count].u.unknown.data = malloc(sample_len);
+ memcpy(log_entry->samples[*sample_count].u.unknown.data, buf + offset + 2, sample_len);
+ break;
+ }
+ ret = 1;
+ break;
+ default:
+ LOG_WARNING("Found unknown sample type (0x%02x)", sample_type);
+ log_entry->samples[*sample_count].type = ambit_log_sample_type_unknown;
+ log_entry->samples[*sample_count].u.unknown.datalen = sample_len;
+ log_entry->samples[*sample_count].u.unknown.data = malloc(sample_len);
+ memcpy(log_entry->samples[*sample_count].u.unknown.data, buf + offset + 2, sample_len);
+ ret = 1;
+ break;
+ }
+
+ *sample_count += ret;
+
+ return ret;
+}
+
+static int read_upto(ambit_object_t *object, uint32_t address, uint32_t length)
+{
+ uint32_t start_address = address - ((address - PMEM20_LOG_START) % object->pmem20.chunk_size);
+
+ while (start_address < address + length) {
+ if (object->pmem20.log.chunks_read[(start_address - PMEM20_LOG_START)/object->pmem20.chunk_size] == 0) {
+ if (read_log_chunk(object, start_address) != 0) {
+ return -1;
+ }
+ object->pmem20.log.chunks_read[(start_address - PMEM20_LOG_START)/object->pmem20.chunk_size] = 1;
+ }
+ start_address += object->pmem20.chunk_size;
+ }
+
+ return 0;
+}
+
+static int read_log_chunk(ambit_object_t *object, uint32_t address)
+{
+ int ret = -1;
+
+ uint8_t *buffer = object->pmem20.log.buffer + (address - PMEM20_LOG_START);
+ uint32_t length = object->pmem20.chunk_size;
+
+ uint8_t *reply = NULL;
+ size_t replylen = 0;
+
+ uint8_t send_data[8];
+ uint32_t *_address = (uint32_t*)&send_data[0];
+ uint32_t *_length = (uint32_t*)&send_data[4];
+
+ if ((address + object->pmem20.chunk_size) > (PMEM20_LOG_START + PMEM20_LOG_SIZE)) {
+ length = PMEM20_LOG_START + PMEM20_LOG_SIZE - address;
+ }
+
+ *_address = htole32(address);
+ *_length = htole32(length);
+
+ if (libambit_protocol_command(object, ambit_command_log_read, send_data, sizeof(send_data), &reply, &replylen, 0) == 0 &&
+ replylen == length + 8) {
+ memcpy(buffer, reply + 8, length);
+ ret = 0;
+ }
+
+ libambit_protocol_free(reply);
+
+ return ret;
+}
+
+static int write_data_chunk(ambit_object_t *object, uint32_t address, size_t buffer_count, uint8_t **buffers, size_t *buffer_sizes)
+{
+ int ret = -1;
+
+ uint8_t *reply = NULL;
+ size_t replylen = 0;
+
+ uint8_t *send_data;
+ size_t send_data_len = 8;
+
+ int i;
+ for (i=0; i<buffer_count; i++) {
+ send_data_len += buffer_sizes[i];
+ }
+ send_data = malloc(send_data_len);
+
+ if (send_data != NULL) {
+ uint32_t *_address = (uint32_t*)&send_data[0];
+ uint32_t *_length = (uint32_t*)&send_data[4];
+ uint8_t *send_data_ptr = &send_data[8];
+
+ *_address = htole32(address);
+ *_length = htole32(send_data_len - 8);
+
+ for (i=0; i<buffer_count; i++) {
+ memcpy(send_data_ptr, buffers[i], buffer_sizes[i]);
+ send_data_ptr += buffer_sizes[i];
+ }
+
+ if (libambit_protocol_command(object, ambit_command_data_write, send_data, send_data_len, &reply, &replylen, 0) == 0) {
+ ret = 0;
+ }
+
+ free(send_data);
+ libambit_protocol_free(reply);
+ }
+
+ return ret;
+}
+
+static void add_time(ambit_date_time_t *intime, int32_t offset, ambit_date_time_t *outtime)
+{
+ struct timeval timeval;
+ struct tm *tm;
+
+ to_timeval(intime, &timeval);
+
+ if (offset >= 0) {
+ timeval.tv_sec += offset / 1000;
+ timeval.tv_usec += (offset % 1000)*1000;
+ }
+ else {
+ timeval.tv_sec += offset / 1000;
+ timeval.tv_usec -= (abs(offset) % 1000)*1000;
+ }
+ if (timeval.tv_usec >= 1000000) {
+ timeval.tv_sec++;
+ timeval.tv_usec -= 1000000;
+ }
+ if(timeval.tv_usec < 0) {
+ timeval.tv_sec--;
+ timeval.tv_usec += 1000000;
+ }
+
+ tm = gmtime(&timeval.tv_sec);
+ outtime->msec = tm->tm_sec * 1000 + (timeval.tv_usec / 1000);
+ outtime->minute = tm->tm_min;
+ outtime->hour = tm->tm_hour;
+ outtime->day = tm->tm_mday;
+ outtime->month = tm->tm_mon;
+ outtime->year = tm->tm_year;
+}
+
+static int is_leap(unsigned int y) {
+ y += 1900;
+ return (y % 4) == 0 && ((y % 100) != 0 || (y % 400) == 0);
+}
+
+static void to_timeval(ambit_date_time_t *ambit_time, struct timeval *timeval) {
+ static const unsigned ndays[2][12] = {
+ {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
+ {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
+ };
+ timeval->tv_sec = 0;
+ timeval->tv_usec = 0;
+ int i;
+
+ for (i = 70; i < ambit_time->year; ++i) {
+ timeval->tv_sec += is_leap(i) ? 366 : 365;
+ }
+
+ for (i = 0; i < ambit_time->month; ++i) {
+ timeval->tv_sec += ndays[is_leap(ambit_time->year)][i];
+ }
+ timeval->tv_sec += ambit_time->day - 1;
+ timeval->tv_sec *= 24;
+ timeval->tv_sec += ambit_time->hour;
+ timeval->tv_sec *= 60;
+ timeval->tv_sec += ambit_time->minute;
+ timeval->tv_sec *= 60;
+ timeval->tv_sec += ambit_time->msec / 1000;
+ timeval->tv_usec = (ambit_time->msec % 1000)*1000;
+}
diff --git a/src/libambit/protocol.c b/src/libambit/protocol.c
new file mode 100644
index 0000000..192d29a
--- /dev/null
+++ b/src/libambit/protocol.c
@@ -0,0 +1,212 @@
+/*
+ * (C) Copyright 2014 Emil Ljungdahl
+ *
+ * This file is part of libambit.
+ *
+ * libambit is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * Contributors:
+ *
+ */
+#include "libambit.h"
+#include "libambit_int.h"
+#include "hidapi/hidapi.h"
+
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+#include <unistd.h>
+#include <stdio.h>
+
+/*
+ * Local definitions
+ */
+#define READ_TIMEOUT 20000 // ms
+#define READ_POLL_INTERVAL 100 // ms
+#define READ_POLL_RETRY (READ_TIMEOUT / READ_POLL_INTERVAL)
+
+typedef struct __attribute__((__packed__)) ambit_msg_header_s {
+ uint8_t UId;
+ uint8_t UL;
+ uint8_t MP;
+ uint8_t ML;
+ uint16_t parts_seq;
+ uint16_t checksum;
+ uint16_t command;
+ uint16_t send_recv;
+ uint16_t format;
+ uint16_t sequence;
+ uint32_t payload_len;
+} ambit_msg_header_t;
+
+/*
+ * Static functions
+ */
+/**
+ * Write packet to bus. The data buffer should include space for headers
+ * which is automatically filled in.
+ * \param object Connection object
+ * \param data Data buffer to write (64 byte)
+ * \return 0 on success, else -1
+ */
+static int protocol_write_packet(ambit_object_t *object, uint8_t *data);
+
+/**
+ * Read packet from bus.
+ * \param object Connection object
+ * \param data Data buffer to write (64 byte)
+ * \return 0 on success, else -1
+ */
+static int protocol_read_packet(ambit_object_t *object, uint8_t *data);
+
+/**
+ * Finalize packet. Add lengths and calculate checksums
+ * \param data Data buffer
+ * \param payload_len Length of payload
+ */
+static void finalize_packet(uint8_t *data, uint8_t payload_len);
+
+/*
+ * Static variables
+ */
+
+/*
+ * Public functions
+ */
+int libambit_protocol_command(ambit_object_t *object, uint16_t command, uint8_t *data, size_t datalen, uint8_t **reply_data, size_t *replylen, uint8_t legacy_format)
+{
+ int ret = 0;
+ uint8_t buf[64];
+ int packet_count = 1;
+ ambit_msg_header_t *msg = (ambit_msg_header_t *)buf;
+ uint8_t packet_payload_len;
+ int i;
+ uint32_t dataoffset = 0, reply_data_len;
+ uint16_t msg_parts;
+
+ // Calculate number of packets
+ if (datalen > 42) {
+ packet_count = 2 + (datalen - 42)/54;
+ }
+
+ // Create first packet
+ msg->MP = 0x5d;
+ msg->parts_seq = htole16(packet_count);
+ msg->command = htobe16(command);
+ msg->send_recv = htole16(legacy_format ? 1 : 5);
+ msg->format = htole16(legacy_format ? 0 : 9); // TODO!!!
+ msg->sequence = htole16(object->sequence_no);
+ msg->payload_len = htole32(datalen);
+ packet_payload_len = fmin(42, datalen);
+ memcpy(&buf[20], &data[dataoffset], packet_payload_len);
+ finalize_packet(buf, packet_payload_len + 12);
+ protocol_write_packet(object, buf);
+
+ datalen -= packet_payload_len;
+ dataoffset += packet_payload_len;
+
+ // Send additional packets
+ for(i=1; i<packet_count; i++) {
+ msg->MP = 0x5e;
+ msg->parts_seq = htole16(i);
+ packet_payload_len = fmin(54, datalen);
+ memcpy(&buf[8], &data[dataoffset], packet_payload_len);
+ finalize_packet(buf, packet_payload_len);
+ protocol_write_packet(object, buf);
+
+ datalen -= packet_payload_len;
+ dataoffset += packet_payload_len;
+ }
+
+ // Retrieve reply packets
+ if (protocol_read_packet(object, buf) == 0 &&
+ msg->MP == 0x5d && le16toh(msg->sequence) == object->sequence_no) {
+ reply_data_len = le32toh(msg->payload_len);
+ dataoffset = 0;
+ packet_payload_len = fmin(42, reply_data_len);
+ if (reply_data != NULL && replylen != NULL) {
+ *replylen = reply_data_len;
+ *reply_data = malloc(reply_data_len);
+ memcpy(&(*reply_data)[dataoffset], &buf[20], packet_payload_len);
+ }
+ dataoffset += packet_payload_len;
+ reply_data_len -= packet_payload_len;
+
+ msg_parts = le16toh(msg->parts_seq);
+
+ for (i=2; ret == 0 && i<=msg_parts; i++) {
+ if (protocol_read_packet(object, buf) == 0 && msg->MP == 0x5e && le16toh(msg->parts_seq) < msg_parts) {
+ packet_payload_len = fmin(54, reply_data_len);
+ if (reply_data != NULL) {
+ memcpy(&(*reply_data)[42+(le16toh(msg->parts_seq)-1)*54], &buf[8], packet_payload_len);
+ }
+ dataoffset += packet_payload_len;
+ reply_data_len -= packet_payload_len;
+ }
+ else {
+ ret = -1;
+ }
+ }
+ }
+ else {
+ ret = -1;
+ }
+
+ // Increment sequence number for next run
+ object->sequence_no++;
+
+ return ret;
+}
+
+void libambit_protocol_free(uint8_t *data)
+{
+ if (data != NULL) {
+ free(data);
+ }
+}
+
+static int protocol_write_packet(ambit_object_t *object, uint8_t *data)
+{
+ hid_write(object->handle, data, 64);
+
+ return 0;
+}
+
+static int protocol_read_packet(ambit_object_t *object, uint8_t *data)
+{
+ int i, res = -1;
+ for (i=0; i<READ_POLL_RETRY; i++) {
+ res = hid_read(object->handle, data, 64);
+ if (res != 0) {
+ break;
+ }
+ usleep(READ_POLL_INTERVAL * 1000);
+ }
+
+ return (res > 0 ? 0 : -1);
+}
+
+static void finalize_packet(uint8_t *data, uint8_t payload_len)
+{
+ ambit_msg_header_t *msg = (ambit_msg_header_t *)data;
+ uint16_t *payload_crc, tmpcrc;
+
+ msg->UId = 0x3f;
+ msg->UL = payload_len + 8;
+ msg->ML = payload_len;
+ tmpcrc = crc16_ccitt_false(&data[2], 4);
+ msg->checksum = htole16(tmpcrc);
+ payload_crc = (uint16_t *)&data[msg->UL];
+ *payload_crc = htole16(crc16_ccitt_false_init(&data[8], payload_len, tmpcrc));
+}
diff --git a/CMakeLists.txt b/src/openambit/CMakeLists.txt
similarity index 100%
rename from CMakeLists.txt
rename to src/openambit/CMakeLists.txt
diff --git a/COPYING b/src/openambit/COPYING
similarity index 100%
rename from COPYING
rename to src/openambit/COPYING
diff --git a/cmake/FindUDev.cmake b/src/openambit/cmake/FindUDev.cmake
similarity index 100%
rename from cmake/FindUDev.cmake
rename to src/openambit/cmake/FindUDev.cmake
diff --git a/cmake/Findlibambit.cmake b/src/openambit/cmake/Findlibambit.cmake
similarity index 100%
rename from cmake/Findlibambit.cmake
rename to src/openambit/cmake/Findlibambit.cmake
diff --git a/confirmbetadialog.cpp b/src/openambit/confirmbetadialog.cpp
similarity index 100%
rename from confirmbetadialog.cpp
rename to src/openambit/confirmbetadialog.cpp
diff --git a/confirmbetadialog.h b/src/openambit/confirmbetadialog.h
similarity index 100%
rename from confirmbetadialog.h
rename to src/openambit/confirmbetadialog.h
diff --git a/confirmbetadialog.ui b/src/openambit/confirmbetadialog.ui
similarity index 100%
rename from confirmbetadialog.ui
rename to src/openambit/confirmbetadialog.ui
diff --git a/deployment/99-suunto-ambit.rules b/src/openambit/deployment/99-suunto-ambit.rules
similarity index 100%
rename from deployment/99-suunto-ambit.rules
rename to src/openambit/deployment/99-suunto-ambit.rules
diff --git a/deployment/openambit.desktop b/src/openambit/deployment/openambit.desktop
similarity index 100%
rename from deployment/openambit.desktop
rename to src/openambit/deployment/openambit.desktop
diff --git a/devicemanager.cpp b/src/openambit/devicemanager.cpp
similarity index 100%
rename from devicemanager.cpp
rename to src/openambit/devicemanager.cpp
diff --git a/devicemanager.h b/src/openambit/devicemanager.h
similarity index 100%
rename from devicemanager.h
rename to src/openambit/devicemanager.h
diff --git a/icons/icon_connected.png b/src/openambit/icons/icon_connected.png
similarity index 100%
rename from icons/icon_connected.png
rename to src/openambit/icons/icon_connected.png
diff --git a/icons/icon_disconnected.png b/src/openambit/icons/icon_disconnected.png
similarity index 100%
rename from icons/icon_disconnected.png
rename to src/openambit/icons/icon_disconnected.png
diff --git a/icons/icon_sync.png b/src/openambit/icons/icon_sync.png
similarity index 100%
rename from icons/icon_sync.png
rename to src/openambit/icons/icon_sync.png
diff --git a/logentry.cpp b/src/openambit/logentry.cpp
similarity index 100%
rename from logentry.cpp
rename to src/openambit/logentry.cpp
diff --git a/logentry.h b/src/openambit/logentry.h
similarity index 100%
rename from logentry.h
rename to src/openambit/logentry.h
diff --git a/logstore.cpp b/src/openambit/logstore.cpp
similarity index 100%
rename from logstore.cpp
rename to src/openambit/logstore.cpp
diff --git a/logstore.h b/src/openambit/logstore.h
similarity index 100%
rename from logstore.h
rename to src/openambit/logstore.h
diff --git a/main.cpp b/src/openambit/main.cpp
similarity index 100%
rename from main.cpp
rename to src/openambit/main.cpp
diff --git a/mainwindow.cpp b/src/openambit/mainwindow.cpp
similarity index 100%
rename from mainwindow.cpp
rename to src/openambit/mainwindow.cpp
diff --git a/mainwindow.h b/src/openambit/mainwindow.h
similarity index 100%
rename from mainwindow.h
rename to src/openambit/mainwindow.h
diff --git a/mainwindow.ui b/src/openambit/mainwindow.ui
similarity index 100%
rename from mainwindow.ui
rename to src/openambit/mainwindow.ui
diff --git a/movescount/CMakeLists.txt b/src/openambit/movescount/CMakeLists.txt
similarity index 100%
rename from movescount/CMakeLists.txt
rename to src/openambit/movescount/CMakeLists.txt
diff --git a/movescount/include.pri b/src/openambit/movescount/include.pri
similarity index 100%
rename from movescount/include.pri
rename to src/openambit/movescount/include.pri
diff --git a/movescount/movescount.cpp b/src/openambit/movescount/movescount.cpp
similarity index 100%
rename from movescount/movescount.cpp
rename to src/openambit/movescount/movescount.cpp
diff --git a/movescount/movescount.h b/src/openambit/movescount/movescount.h
similarity index 100%
rename from movescount/movescount.h
rename to src/openambit/movescount/movescount.h
diff --git a/movescount/movescountjson.cpp b/src/openambit/movescount/movescountjson.cpp
similarity index 100%
rename from movescount/movescountjson.cpp
rename to src/openambit/movescount/movescountjson.cpp
diff --git a/movescount/movescountjson.h b/src/openambit/movescount/movescountjson.h
similarity index 100%
rename from movescount/movescountjson.h
rename to src/openambit/movescount/movescountjson.h
diff --git a/movescount/movescountlogdirentry.cpp b/src/openambit/movescount/movescountlogdirentry.cpp
similarity index 100%
rename from movescount/movescountlogdirentry.cpp
rename to src/openambit/movescount/movescountlogdirentry.cpp
diff --git a/movescount/movescountlogdirentry.h b/src/openambit/movescount/movescountlogdirentry.h
similarity index 100%
rename from movescount/movescountlogdirentry.h
rename to src/openambit/movescount/movescountlogdirentry.h
diff --git a/movescount/movescountxml.cpp b/src/openambit/movescount/movescountxml.cpp
similarity index 100%
rename from movescount/movescountxml.cpp
rename to src/openambit/movescount/movescountxml.cpp
diff --git a/movescount/movescountxml.h b/src/openambit/movescount/movescountxml.h
similarity index 100%
rename from movescount/movescountxml.h
rename to src/openambit/movescount/movescountxml.h
diff --git a/resources.qrc b/src/openambit/resources.qrc
similarity index 100%
rename from resources.qrc
rename to src/openambit/resources.qrc
diff --git a/settings.cpp b/src/openambit/settings.cpp
similarity index 100%
rename from settings.cpp
rename to src/openambit/settings.cpp
diff --git a/settings.h b/src/openambit/settings.h
similarity index 100%
rename from settings.h
rename to src/openambit/settings.h
diff --git a/settingsdialog.cpp b/src/openambit/settingsdialog.cpp
similarity index 100%
rename from settingsdialog.cpp
rename to src/openambit/settingsdialog.cpp
diff --git a/settingsdialog.h b/src/openambit/settingsdialog.h
similarity index 100%
rename from settingsdialog.h
rename to src/openambit/settingsdialog.h
diff --git a/settingsdialog.ui b/src/openambit/settingsdialog.ui
similarity index 100%
rename from settingsdialog.ui
rename to src/openambit/settingsdialog.ui
diff --git a/single_application.cpp b/src/openambit/single_application.cpp
similarity index 100%
rename from single_application.cpp
rename to src/openambit/single_application.cpp
diff --git a/single_application.h b/src/openambit/single_application.h
similarity index 100%
rename from single_application.h
rename to src/openambit/single_application.h
diff --git a/udevlistener.cpp b/src/openambit/udevlistener.cpp
similarity index 100%
rename from udevlistener.cpp
rename to src/openambit/udevlistener.cpp
diff --git a/udevlistener.h b/src/openambit/udevlistener.h
similarity index 100%
rename from udevlistener.h
rename to src/openambit/udevlistener.h
diff --git a/tools/movescountXmlDiff.pl b/tools/movescountXmlDiff.pl
new file mode 100755
index 0000000..0548b7d
--- /dev/null
+++ b/tools/movescountXmlDiff.pl
@@ -0,0 +1,178 @@
+#!/usr/bin/perl
+
+#use strict;
+#use warnings;
+
+my $diffText = `diff -w $ARGV[0] $ARGV[1]`;
+
+my @lines = split /\n/, $diffText;
+
+my @records;
+my $currentRecordLine;
+my $currentRecordRemoveLines;
+my $currentRecordAddLines;
+my $currentRecordStarted = 0;
+
+foreach my $line (@lines) {
+ if ($line =~ m/[0-9,\-]+[c|d|a][0-9,\-]+/g) {
+ if ($currentRecordStarted == 1) {
+ my %currentRecord = ( "LinesText" => $currentRecordLine,
+ "RemoveLines" => $currentRecordRemoveLines,
+ "AddLines" => $currentRecordAddLines
+ );
+ push(@records, \%currentRecord);
+ }
+ $currentRecordLine = $line;
+ $currentRecordRemoveLines = [];
+ $currentRecordAddLines = [];
+ $currentRecordStarted = 1;
+ }
+ elsif ($line =~ m/^</g) {
+ push(@{$currentRecordRemoveLines}, $line);
+ }
+ elsif ($line =~ m/^>/g) {
+ push(@{$currentRecordAddLines}, $line);
+ }
+}
+
+foreach my $entry (@records) {
+ my $printDiff = 1;
+
+ if (scalar @{$entry->{"RemoveLines"}} == scalar @{$entry->{"AddLines"}}) {
+ my $diffFound = scalar @{$entry->{"RemoveLines"}};
+ for ($i = 0; $i < scalar @{$entry->{"RemoveLines"}}; $i++) {
+ if ((@matchRemove = (@{$entry->{"RemoveLines"}}[$i] =~ m/<HR>([0-9\.]+)<\/HR>/g)) && (@matchAdd = (@{$entry->{"AddLines"}}[$i] =~ m/<HR>([0-9\.]+)<\/HR>/g))) {
+ if ((@matchRemove[0] - @matchAdd[0]) < 0.00000000000005 &&
+ (@matchRemove[0] - @matchAdd[0]) > -0.00000000000005) {
+ $diffFound--;
+ }
+ }
+ elsif ((@matchRemove = (@{$entry->{"RemoveLines"}}[$i] =~ m/<Latitude>([\-0-9\.]+)<\/Latitude>/g)) && (@matchAdd = (@{$entry->{"AddLines"}}[$i] =~ m/<Latitude>([\-0-9\.]+)<\/Latitude>/g))) {
+ if ((@matchRemove[0] - @matchAdd[0]) < 0.000000000000005 &&
+ (@matchRemove[0] - @matchAdd[0]) > -0.000000000000005) {
+ $diffFound--;
+ }
+ }
+ elsif ((@matchRemove = (@{$entry->{"RemoveLines"}}[$i] =~ m/<Longitude>([\-0-9\.]+)<\/Longitude>/g)) && (@matchAdd = (@{$entry->{"AddLines"}}[$i] =~ m/<Longitude>([\-0-9\.]+)<\/Longitude>/g))) {
+ if ((@matchRemove[0] - @matchAdd[0]) < 0.000000000000005 &&
+ (@matchRemove[0] - @matchAdd[0]) > -0.000000000000005) {
+ $diffFound--;
+ }
+ }
+ elsif ((@matchRemove = (@{$entry->{"RemoveLines"}}[$i] =~ m/<Speed>([0-9\.]+)<\/Speed>/g)) && (@matchAdd = (@{$entry->{"AddLines"}}[$i] =~ m/<Speed>([0-9\.]+)<\/Speed>/g))) {
+ if ((@matchRemove[0] - @matchAdd[0]) < 0.00000000000005 &&
+ (@matchRemove[0] - @matchAdd[0]) > -0.00000000000005) {
+ $diffFound--;
+ }
+ }
+ elsif ((@matchRemove = (@{$entry->{"RemoveLines"}}[$i] =~ m/<VerticalSpeed>([\-0-9\.]+)<\/VerticalSpeed>/g)) && (@matchAdd = (@{$entry->{"AddLines"}}[$i] =~ m/<VerticalSpeed>([\-0-9\.]+)<\/VerticalSpeed>/g))) {
+ if ((@matchRemove[0] - @matchAdd[0]) < 0.00000000000005 &&
+ (@matchRemove[0] - @matchAdd[0]) > -0.00000000000005) {
+ $diffFound--;
+ }
+ }
+ elsif ((@matchRemove = (@{$entry->{"RemoveLines"}}[$i] =~ m/<GPSHeading>([\-0-9\.]+)<\/GPSHeading>/g)) && (@matchAdd = (@{$entry->{"AddLines"}}[$i] =~ m/<GPSHeading>([\-0-9\.]+)<\/GPSHeading>/g))) {
+ if ((@matchRemove[0] - @matchAdd[0]) < 0.00000000000005 &&
+ (@matchRemove[0] - @matchAdd[0]) > -0.00000000000005) {
+ $diffFound--;
+ }
+ }
+ elsif ((@matchRemove = (@{$entry->{"RemoveLines"}}[$i] =~ m/<GPSSpeed>([0-9\.]+)<\/GPSSpeed>/g)) && (@matchAdd = (@{$entry->{"AddLines"}}[$i] =~ m/<GPSSpeed>([0-9\.]+)<\/GPSSpeed>/g))) {
+ if ((@matchRemove[0] - @matchAdd[0]) < 0.00000000000005 &&
+ (@matchRemove[0] - @matchAdd[0]) > -0.00000000000005) {
+ $diffFound--;
+ }
+ }
+ elsif ((@matchRemove = (@{$entry->{"RemoveLines"}}[$i] =~ m/<GPSAltitude>([0-9\.]+)<\/GPSAltitude>/g)) && (@matchAdd = (@{$entry->{"AddLines"}}[$i] =~ m/<GPSAltitude>([0-9\.]+)<\/GPSAltitude>/g))) {
+ if ((@matchRemove[0] - @matchAdd[0]) < 0.00000000000005 &&
+ (@matchRemove[0] - @matchAdd[0]) > -0.00000000000005) {
+ $diffFound--;
+ }
+ }
+ elsif ((@matchRemove = (@{$entry->{"RemoveLines"}}[$i] =~ m/<EHPE>([0-9\.]+)<\/EHPE>/g)) && (@matchAdd = (@{$entry->{"AddLines"}}[$i] =~ m/<EHPE>([0-9\.]+)<\/EHPE>/g))) {
+ if ((@matchRemove[0] - @matchAdd[0]) < 0.00000000000005 &&
+ (@matchRemove[0] - @matchAdd[0]) > -0.00000000000005) {
+ $diffFound--;
+ }
+ }
+ elsif ((@matchRemove = (@{$entry->{"RemoveLines"}}[$i] =~ m/<Duration>([0-9\.]+)<\/Duration>/g)) && (@matchAdd = (@{$entry->{"AddLines"}}[$i] =~ m/<Duration>([0-9\.]+)<\/Duration>/g))) {
+ if ((@matchRemove[0] - @matchAdd[0]) < 0.000000000005 &&
+ (@matchRemove[0] - @matchAdd[0]) > -0.000000000005) {
+ $diffFound--;
+ }
+ }
+ elsif ((@matchRemove = (@{$entry->{"RemoveLines"}}[$i] =~ m/<Time>([0-9\.]+)<\/Time>/g)) && (@matchAdd = (@{$entry->{"AddLines"}}[$i] =~ m/<Time>([0-9\.]+)<\/Time>/g))) {
+ if ((@matchRemove[0] - @matchAdd[0]) < 0.000000000005 &&
+ (@matchRemove[0] - @matchAdd[0]) > -0.000000000005) {
+ $diffFound--;
+ }
+ }
+ elsif ((@matchRemove = (@{$entry->{"RemoveLines"}}[$i] =~ m/<EnergyConsumption>([0-9\.]+)<\/EnergyConsumption>/g)) && (@matchAdd = (@{$entry->{"AddLines"}}[$i] =~ m/<EnergyConsumption>([0-9\.]+)<\/EnergyConsumption>/g))) {
+ if ((@matchRemove[0] - @matchAdd[0]) < 0.00000000000005 &&
+ (@matchRemove[0] - @matchAdd[0]) > -0.00000000000005) {
+ $diffFound--;
+ }
+ }
+ elsif ((@matchRemove = (@{$entry->{"RemoveLines"}}[$i] =~ m/<PeakTrainingEffect>([0-9\.]+)<\/PeakTrainingEffect>/g)) && (@matchAdd = (@{$entry->{"AddLines"}}[$i] =~ m/<PeakTrainingEffect>([0-9\.]+)<\/PeakTrainingEffect>/g))) {
+ if ((@matchRemove[0] - @matchAdd[0]) < 0.00000000000005 &&
+ (@matchRemove[0] - @matchAdd[0]) > -0.00000000000005) {
+ $diffFound--;
+ }
+ }
+ elsif ((@matchRemove = (@{$entry->{"RemoveLines"}}[$i] =~ m/<BatteryCharge>([0-9\.]+)<\/BatteryCharge>/g)) && (@matchAdd = (@{$entry->{"AddLines"}}[$i] =~ m/<BatteryCharge>([0-9\.]+)<\/BatteryCharge>/g))) {
+ if ((@matchRemove[0] - @matchAdd[0]) < 0.00000000000005 &&
+ (@matchRemove[0] - @matchAdd[0]) > -0.00000000000005) {
+ $diffFound--;
+ }
+ }
+ elsif ((@matchRemove = (@{$entry->{"RemoveLines"}}[$i] =~ m/<BatteryChargeAtStart>([0-9\.]+)<\/BatteryChargeAtStart>/g)) && (@matchAdd = (@{$entry->{"AddLines"}}[$i] =~ m/<BatteryChargeAtStart>([0-9\.]+)<\/BatteryChargeAtStart>/g))) {
+ if ((@matchRemove[0] - @matchAdd[0]) < 0.00000000000005 &&
+ (@matchRemove[0] - @matchAdd[0]) > -0.00000000000005) {
+ $diffFound--;
+ }
+ }
+ elsif ((@matchRemove = (@{$entry->{"RemoveLines"}}[$i] =~ m/<Avg>([0-9\.]+)<\/Avg>/g)) && (@matchAdd = (@{$entry->{"AddLines"}}[$i] =~ m/<Avg>([0-9\.]+)<\/Avg>/g))) {
+ if ((@matchRemove[0] - @matchAdd[0]) < 0.00000000000005 &&
+ (@matchRemove[0] - @matchAdd[0]) > -0.00000000000005) {
+ $diffFound--;
+ }
+ }
+ elsif ((@matchRemove = (@{$entry->{"RemoveLines"}}[$i] =~ m/<Max>([0-9\.]+)<\/Max>/g)) && (@matchAdd = (@{$entry->{"AddLines"}}[$i] =~ m/<Max>([0-9\.]+)<\/Max>/g))) {
+ if ((@matchRemove[0] - @matchAdd[0]) < 0.00000000000005 &&
+ (@matchRemove[0] - @matchAdd[0]) > -0.00000000000005) {
+ $diffFound--;
+ }
+ }
+ #elsif ((@matchRemove = (@{$entry->{"RemoveLines"}}[$i] =~ m/<UTC>[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:([0-9]{2})Z<\/UTC>/g)) && (@matchAdd = (@{$entry->{"AddLines"}}[$i] =~ m/<UTC>[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:([0-9]{2})Z<\/UTC>/g))) {
+ # if ((@matchRemove[0] - @matchAdd[0]) <= 1 &&
+ # (@matchRemove[0] - @matchAdd[0]) >= -1) {
+ # $diffFound--;
+ # }
+ #}
+ elsif ((@matchRemove = (@{$entry->{"RemoveLines"}}[$i] =~ m/<UTC>[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:([0-9]{2}\.[0-9]{3})Z<\/UTC>/g)) && (@matchAdd = (@{$entry->{"AddLines"}}[$i] =~ m/<UTC>[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:([0-9]{2}\.[0-9]{3})Z<\/UTC>/g))) {
+ if ((@matchRemove[0] - @matchAdd[0]) < 0.002 &&
+ (@matchRemove[0] - @matchAdd[0]) > -0.002) {
+ $diffFound--;
+ }
+ }
+ }
+ if ($diffFound == 0) {
+ $printDiff = 0;
+ }
+ }
+
+ if ($printDiff == 1) {
+ print $entry->{"LinesText"}, "\n";
+ foreach my $remLine (@{$entry->{"RemoveLines"}}) {
+ print $remLine, "\n";
+ }
+ if (scalar @{$entry->{"RemoveLines"}} > 0 && scalar @{$entry->{"AddLines"}} > 0) {
+ print "---\n";
+ }
+ foreach my $remLine (@{$entry->{"AddLines"}}) {
+ print $remLine, "\n";
+ }
+ }
+}
+
+
diff --git a/wireshark_dissector/AUTHORS b/wireshark_dissector/AUTHORS
new file mode 100644
index 0000000..c6b30e1
--- /dev/null
+++ b/wireshark_dissector/AUTHORS
@@ -0,0 +1,2 @@
+Author:
+Emil Ljungdahl <emil at kratern.se>
diff --git a/wireshark_dissector/CMakeLists.txt b/wireshark_dissector/CMakeLists.txt
new file mode 100644
index 0000000..d6061aa
--- /dev/null
+++ b/wireshark_dissector/CMakeLists.txt
@@ -0,0 +1,84 @@
+# CMakeLists.txt
+#
+# $Id: CMakeLists.txt 31995 2010-02-24 22:32:10Z jmayer $
+#
+# Wireshark - Network traffic analyzer
+# By Gerald Combs <gerald at wireshark.org>
+# Copyright 1998 Gerald Combs
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program 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 General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+
+project(ambit-wireshark-plugin C)
+
+cmake_minimum_required(VERSION 2.6)
+set(CMAKE_BACKWARDS_COMPATIBILITY 2.6)
+set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake)
+set(CMAKE_INSTALL_LIBDIR ~/.wireshark)
+
+INCLUDE(UseMakeDissectorReg)
+
+set(GLIB2_MIN_VERSION 2.4.0)
+
+find_package(GLIB2)
+include_directories (${GLIB2_INCLUDE_DIRS})
+
+find_package(Wireshark)
+include_directories (${WIRESHARK_INCLUDE_DIRS})
+
+set(LINK_MODE_LIB SHARED)
+set(LINK_MODE_MODULE MODULE)
+
+
+set(DISSECTOR_SRC
+ ambit-dissector.c
+)
+
+set(PLUGIN_FILES
+ plugin.c
+ ${DISSECTOR_SRC}
+)
+
+set(CLEAN_FILES
+ ${PLUGIN_FILES}
+)
+
+if (WERROR)
+ set_source_files_properties(
+ ${CLEAN_FILES}
+ PROPERTIES
+ COMPILE_FLAGS -Werror
+ )
+endif()
+
+include_directories(${CMAKE_CURRENT_SOURCE_DIR})
+
+register_dissector_files(plugin.c
+ plugin
+ ${DISSECTOR_SRC}
+)
+
+add_library(ambit ${LINK_MODE_MODULE}
+ ${PLUGIN_FILES}
+)
+set_target_properties(ambit PROPERTIES PREFIX "")
+set_target_properties(ambit PROPERTIES LINK_FLAGS "${WS_LINK_FLAGS}")
+
+target_link_libraries(ambit ${WIRESHARK_LIBRARIES})
+
+install(TARGETS ambit
+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/plugins NAMELINK_SKIP
+)
+
diff --git a/wireshark_dissector/COPYING b/wireshark_dissector/COPYING
new file mode 100644
index 0000000..53b6b71
--- /dev/null
+++ b/wireshark_dissector/COPYING
@@ -0,0 +1,22 @@
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+1. Redistributions of source code must retain the copyright
+ notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+3. The name of the author may not be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/wireshark_dissector/ChangeLog b/wireshark_dissector/ChangeLog
new file mode 100644
index 0000000..429dc64
--- /dev/null
+++ b/wireshark_dissector/ChangeLog
@@ -0,0 +1,2 @@
+2013-11-04
+First version of the (Suunto Ambit 2) dissector plugin for wireshark
diff --git a/wireshark_dissector/INSTALL b/wireshark_dissector/INSTALL
new file mode 100644
index 0000000..ff62ac2
--- /dev/null
+++ b/wireshark_dissector/INSTALL
@@ -0,0 +1,9 @@
+This wireshark plugin is built with cmake (in a separate build/ directory):
+ mkdir build
+ cd build
+ cmake ..
+ make
+ make install
+
+This will build the .so plugin for wireshark and install it into the user's
+~/.wireshark/plugins/ directory, where wireshark will load plugins from.
diff --git a/wireshark_dissector/ambit-dissector.c b/wireshark_dissector/ambit-dissector.c
new file mode 100644
index 0000000..712ccb2
--- /dev/null
+++ b/wireshark_dissector/ambit-dissector.c
@@ -0,0 +1,1981 @@
+#include "config.h"
+
+#include <glib.h>
+#include <epan/conversation.h>
+#include <epan/expert.h>
+#include <epan/packet.h>
+#include <epan/reassemble.h>
+#include <epan/dissectors/packet-usb.h>
+
+typedef struct ambit_reassembly_entry {
+ guint8 valid;
+ guint32 command;
+ guint32 start_frame;
+ guint32 frame_count;
+ guint32 size;
+ unsigned char *data;
+ guint32 log_entry_size;
+ unsigned char *log_entry;
+ guint32 log_start_frame;
+} ambit_reassembly_entry_t;
+
+typedef struct ambit_protocol_type {
+ guint32 command;
+ char *name;
+ gint (*dissector)(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+} ambit_protocol_type_t;
+
+static const ambit_protocol_type_t *find_subdissector(guint32 command);
+static gint dissect_ambit_date_write(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_date_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_time_write(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_time_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_status_get(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_status_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_device_info_get(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_device_info_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_personal_settings_get(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_personal_settings_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_log_header_get(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_log_header_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_log_header_unwind_get(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_log_header_unwind_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_log_header_peek_get(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_log_header_peek_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_log_header_step_get(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_log_header_step_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_log_count_get(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_log_count_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_log_data_get(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_log_data_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_);
+static gint dissect_ambit_log_data_content(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_, guint32 offset, guint32 length);
+static gint dissect_ambit_log_data_sample(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_, guint32 offset, guint32 length, guint32 *sampleno, guint32 *periodic_sample_specifier);
+
+/* protocols and header fields */
+#define D_AMBIT_USBID 0x3f
+static int proto_ambit = -1;
+static int hf_ambit_usbid = -1;
+static int hf_ambit_usblength = -1;
+static int hf_ambit_msgpart = -1;
+static int hf_ambit_msglength = -1;
+static int hf_ambit_msgsegs = -1;
+static int hf_ambit_msgseg = -1;
+static int hf_ambit_msgheaderchksum = -1;
+static int hf_ambit_requestcmd = -1;
+static int hf_ambit_pktseqno = -1;
+static int hf_ambit_pktlen = -1;
+static int hf_ambit_payloadchksum = -1;
+
+static int hf_ambit_unknown = -1;
+
+static int hf_ambit_date = -1;
+static int hf_ambit_time = -1;
+static int hf_ambit_charge = -1;
+static int hf_ambit_model = -1;
+static int hf_ambit_serial = -1;
+static int hf_ambit_fw_version = -1;
+static int hf_ambit_hw_version = -1;
+static int hf_ambit_personal_compass_declination = -1;
+static int hf_ambit_personal_map_orientation = -1;
+static int hf_ambit_personal_date_format = -1;
+static int hf_ambit_personal_time_format = -1;
+static int hf_ambit_personal_coordinate_system = -1;
+static int hf_ambit_personal_unit_system = -1;
+static int hf_ambit_personal_alarm_enable = -1;
+static int hf_ambit_personal_alarm_time = -1;
+static int hf_ambit_personal_dual_time = -1;
+static int hf_ambit_personal_gps_sync_time = -1;
+static int hf_ambit_personal_weight = -1;
+static int hf_ambit_personal_max_hb = -1;
+static int hf_ambit_personal_rest_hb = -1;
+static int hf_ambit_personal_birthyear = -1;
+static int hf_ambit_personal_length = -1;
+static int hf_ambit_personal_sex = -1;
+static int hf_ambit_personal_fitness_level = -1;
+static int hf_ambit_personal_alti_baro_fused_alti = -1;
+static int hf_ambit_personal_alti_baro_profile = -1;
+static int hf_ambit_personal_backlight_brightness = -1;
+static int hf_ambit_personal_backlight_mode = -1;
+static int hf_ambit_personal_display_contrast = -1;
+static int hf_ambit_personal_invert_display = -1;
+static int hf_ambit_personal_lock_sports_mode = -1;
+static int hf_ambit_personal_lock_time_mode = -1;
+static int hf_ambit_personal_tones = -1;
+
+static int hf_ambit_log_header_seq = -1;
+static int hf_ambit_log_header_length = -1;
+static int hf_ambit_log_header_sample_desc = -1;
+static int hf_ambit_log_header_date = -1;
+static int hf_ambit_log_header_time = -1;
+static int hf_ambit_log_header_duration = -1;
+static int hf_ambit_log_header_ascent = -1;
+static int hf_ambit_log_header_descent = -1;
+static int hf_ambit_log_header_ascent_time = -1;
+static int hf_ambit_log_header_descent_time = -1;
+static int hf_ambit_log_header_recovery = -1;
+static int hf_ambit_log_header_avg_speed = -1;
+static int hf_ambit_log_header_max_speed = -1;
+static int hf_ambit_log_header_altitude_max = -1;
+static int hf_ambit_log_header_altitude_min = -1;
+static int hf_ambit_log_header_hr_avg = -1;
+static int hf_ambit_log_header_hr_max = -1;
+static int hf_ambit_log_header_peak_effect = -1;
+static int hf_ambit_log_header_activity_type = -1;
+static int hf_ambit_log_header_activity_name = -1;
+static int hf_ambit_log_header_hr_min = -1;
+static int hf_ambit_log_header_temp_max = -1;
+static int hf_ambit_log_header_temp_min = -1;
+static int hf_ambit_log_header_distance = -1;
+static int hf_ambit_log_header_sample_count = -1;
+static int hf_ambit_log_header_energy = -1;
+static int hf_ambit_log_header_speed_max_time = -1;
+static int hf_ambit_log_header_alt_max_time = -1;
+static int hf_ambit_log_header_alt_min_time = -1;
+static int hf_ambit_log_header_hr_max_time = -1;
+static int hf_ambit_log_header_hr_min_time = -1;
+static int hf_ambit_log_header_temp_max_time = -1;
+static int hf_ambit_log_header_temp_min_time = -1;
+static int hf_ambit_log_header_time_first_fix = -1;
+static int hf_ambit_log_header_battery_start = -1;
+static int hf_ambit_log_header_battery_stop = -1;
+static int hf_ambit_log_header_distance_before_calib = -1;
+
+static int hf_ambit_log_header_more = -1;
+
+static int hf_ambit_log_count = -1;
+
+static int hf_ambit_log_data_addr_frame_ref = -1;
+static int hf_ambit_log_data_address = -1;
+static int hf_ambit_log_data_length = -1;
+static int hf_ambit_log_data_sof = -1;
+static int hf_ambit_log_data_first_addr = -1;
+static int hf_ambit_log_data_last_addr = -1;
+static int hf_ambit_log_data_entry_count = -1;
+static int hf_ambit_log_data_next_free_addr = -1;
+static int hf_ambit_log_data_next_addr = -1;
+static int hf_ambit_log_data_prev_addr = -1;
+
+static int hf_ambit_log_sample_length = -1;
+static int hf_ambit_log_sample_peri_spec_count = -1;
+static int hf_ambit_log_sample_type = -1;
+static int hf_ambit_log_sample_peri_spec_id = -1;
+static int hf_ambit_log_sample_peri_spec_offset = -1;
+static int hf_ambit_log_sample_peri_spec_length = -1;
+static int hf_ambit_log_sample_periodic_distance = -1;
+static int hf_ambit_log_sample_periodic_speed = -1;
+static int hf_ambit_log_sample_periodic_hr = -1;
+static int hf_ambit_log_sample_periodic_time = -1;
+static int hf_ambit_log_sample_periodic_altitude = -1;
+static int hf_ambit_log_sample_periodic_energy = -1;
+static int hf_ambit_log_sample_periodic_temp = -1;
+static int hf_ambit_log_sample_periodic_preassure = -1;
+static int hf_ambit_log_sample_periodic_vert_speed = -1;
+
+static int hf_ambit_log_other_time_offset = -1;
+static int hf_ambit_log_other_type = -1;
+static int hf_ambit_log_activity_type = -1;
+static int hf_ambit_log_activity_custom_mode_id = -1;
+static int hf_ambit_log_time_event_type = -1;
+static int hf_ambit_log_time_event_date = -1;
+static int hf_ambit_log_time_event_time = -1;
+static int hf_ambit_log_time_event_duration = -1;
+static int hf_ambit_log_time_event_distance = -1;
+
+static int hf_ambit_log_gps_base_navtype = -1;
+static int hf_ambit_log_gps_base_date = -1;
+static int hf_ambit_log_gps_base_time = -1;
+static int hf_ambit_log_gps_base_latitude = -1;
+static int hf_ambit_log_gps_base_longitude = -1;
+static int hf_ambit_log_gps_base_altitude = -1;
+static int hf_ambit_log_gps_base_speed = -1;
+static int hf_ambit_log_gps_base_heading = -1;
+static int hf_ambit_log_gps_base_ehpe = -1;
+static int hf_ambit_log_gps_base_satelite_no = -1;
+static int hf_ambit_log_gps_base_hdop = -1;
+static int hf_ambit_log_gps_base_sv = -1;
+static int hf_ambit_log_gps_base_state = -1;
+static int hf_ambit_log_gps_base_snr = -1;
+
+static int hf_ambit_log_gps_small_time = -1;
+static int hf_ambit_log_gps_small_latitude = -1;
+static int hf_ambit_log_gps_small_longitude = -1;
+static int hf_ambit_log_gps_small_ehpe = -1;
+static int hf_ambit_log_gps_small_satelite_no = -1;
+
+static int hf_ambit_log_gps_tiny_time = -1;
+static int hf_ambit_log_gps_tiny_latitude = -1;
+static int hf_ambit_log_gps_tiny_longitude = -1;
+
+static int hf_ambit_log_distance_source_type = -1;
+
+static int hf_ambit_log_altitude_source_type = -1;
+static int hf_ambit_log_altitude_source_altitude_offset = -1;
+static int hf_ambit_log_altitude_source_preassure_offset = -1;
+
+static int hf_ambit_log_ibi = -1;
+
+static gint ett_ambit = -1;
+static gint ett_ambit_data = -1;
+static gint ett_ambit_log_data = -1;
+static gint ett_ambit_log_samples = -1;
+static gint ett_ambit_log_sample = -1;
+
+static ambit_reassembly_entry_t *reassembly_entries = NULL;
+static guint32 reassembly_entries_alloc = 0;
+
+static guint32 address_to_frame_lookup[4096];
+
+static const value_string msgpart_index_vals[] = {
+ { 0x5d, "First part" },
+ { 0x5e, "Following part" },
+ { 0, NULL }
+};
+
+static const value_string log_header_more_vals[] = {
+ { 0x00000400, "More entries" },
+ { 0x00000c00, "No more entries" },
+ { 0, NULL }
+};
+
+static const value_string log_samples_type_vals[] = {
+ { 0x00, "Periodic sample specifier" },
+ { 0x02, "Periodic sample" },
+ { 0x03, "Other sample" },
+ { 0, NULL }
+};
+
+static const value_string log_samples_spec_type_vals[] = {
+ { 0x03, "Distance" },
+ { 0x04, "Speed" },
+ { 0x05, "HR" },
+ { 0x06, "Time" },
+ { 0x0c, "Altitude" },
+ { 0x0e, "Energy consumption" },
+ { 0x0f, "Temperature" },
+ { 0x18, "Preassure" },
+ { 0x19, "Vertical speed" },
+ { 0, NULL }
+};
+
+static const value_string log_samples_time_event_type_vals[] = {
+ { 0x01, "Manual lap" },
+ { 0x14, "High interval end" },
+ { 0x15, "Low interval end" },
+ { 0x16, "Interval start" },
+ { 0x1e, "Pause" },
+ { 0x1f, "Start" },
+ { 0, NULL }
+};
+
+static const value_string log_samples_distance_source_type_vals[] = {
+ { 0x02, "GPS" },
+ { 0x03, "Wrist" },
+ { 0, NULL }
+};
+
+static const value_string log_samples_altitude_source_type_vals[] = {
+ { 0x04, "Preassure" },
+ { 0, NULL }
+};
+
+static const ambit_protocol_type_t subdissectors[] = {
+ { 0x03000500, "Set time", dissect_ambit_time_write },
+ { 0x03000a00, "Time reply", dissect_ambit_time_reply },
+ { 0x03020500, "Set date", dissect_ambit_date_write },
+ { 0x03020a00, "Date reply", dissect_ambit_date_reply },
+ { 0x03060500, "Get device status", dissect_ambit_status_get },
+ { 0x03060a00, "Device status reply", dissect_ambit_status_reply },
+ { 0x00000100, "Get device info", dissect_ambit_device_info_get },
+ { 0x00020200, "Device info reply", dissect_ambit_device_info_reply },
+ { 0x0b000500, "Get personal settings", dissect_ambit_personal_settings_get },
+ { 0x0b000a00, "Personal settings reply", dissect_ambit_personal_settings_reply },
+ { 0x0b010500, "Write personal settings", dissect_ambit_personal_settings_reply },
+ { 0x0b010a00, "Personal settings write reply", dissect_ambit_personal_settings_get },
+ { 0x0b060500, "Get log count", dissect_ambit_log_count_get },
+ { 0x0b060a00, "Log count reply", dissect_ambit_log_count_reply },
+ { 0x0b070500, "Log header unwind request", dissect_ambit_log_header_unwind_get },
+ { 0x0b070a00, "Log header unwind reply", dissect_ambit_log_header_unwind_reply },
+ { 0x0b080500, "Log header peek request", dissect_ambit_log_header_peek_get },
+ { 0x0b080a00, "Log header peek reply", dissect_ambit_log_header_peek_reply },
+ { 0x0b0a0500, "Log header step request", dissect_ambit_log_header_step_get },
+ { 0x0b0a0a00, "Log header step reply", dissect_ambit_log_header_step_reply },
+ { 0x0b0b0500, "Get log header", dissect_ambit_log_header_get },
+ { 0x0b0b0a00, "Log header reply", dissect_ambit_log_header_reply },
+ { 0x0b170500, "Get log data", dissect_ambit_log_data_get },
+ { 0x0b170a00, "Log data reply", dissect_ambit_log_data_reply },
+ { 0, NULL, NULL }
+};
+
+static const ambit_protocol_type_t *find_subdissector(guint32 command)
+{
+ int i = 0;
+ const ambit_protocol_type_t *entry = &subdissectors[i++];
+
+ while (entry->command != 0) {
+ if (entry->command == command) {
+ return entry;
+ }
+ entry = &subdissectors[i++];
+ }
+
+ return NULL;
+}
+
+static void dissect_ambit_add_unknown(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gint offset, gint len)
+{
+ proto_item *unknown_item = NULL;
+ unknown_item = proto_tree_add_item(tree, hf_ambit_unknown, tvb, offset, len, ENC_LITTLE_ENDIAN);
+ expert_add_info_format(pinfo, unknown_item, PI_UNDECODED, PI_WARN, "Not dissected yet");
+}
+
+static gint dissect_ambit_date_write(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+ gint offset = 0;
+ guint16 year = tvb_get_letohs(tvb, 0);
+ guint8 month = tvb_get_guint8(tvb, 2);
+ guint8 day = tvb_get_guint8(tvb, 3);
+ proto_tree_add_string_format_value(tree, hf_ambit_date, tvb, offset, 4, "Date", "%04d-%02d-%02d", year, month, day);
+ offset += 4;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 4);
+ offset += 4;
+}
+
+static gint dissect_ambit_date_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+}
+
+static gint dissect_ambit_time_write(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+ gint offset = 0;
+ guint8 hour = tvb_get_guint8(tvb, 4);
+ guint8 minute = tvb_get_guint8(tvb, 5);
+ guint16 seconds = tvb_get_letohs(tvb, 6) / 1000;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 4);
+ offset += 4;
+ proto_tree_add_string_format_value(tree, hf_ambit_time, tvb, offset, 4, "Time", "%02d:%02d:%02d", hour, minute, seconds);
+ offset += 4;
+}
+
+static gint dissect_ambit_time_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+}
+
+static gint dissect_ambit_status_get(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+}
+
+static gint dissect_ambit_status_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+ gint offset = 0;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 1);
+ offset += 1;
+ proto_tree_add_item(tree, hf_ambit_charge, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 1);
+ offset += 1;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 1);
+ offset += 1;
+}
+
+static gint dissect_ambit_device_info_get(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+}
+
+static gint dissect_ambit_device_info_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+ guint8 fw1,fw2,fw3;
+ guint8 hw1,hw2;
+ guint16 hw3;
+ gint offset = 0;
+ proto_tree_add_item(tree, hf_ambit_model, tvb, offset, 16, ENC_LITTLE_ENDIAN);
+ offset += 16;
+ proto_tree_add_item(tree, hf_ambit_serial, tvb, offset, 16, ENC_LITTLE_ENDIAN);
+ offset += 16;
+ fw1 = tvb_get_guint8(tvb, offset);
+ fw2 = tvb_get_guint8(tvb, offset+1);
+ fw3 = tvb_get_guint8(tvb, offset+2);
+ proto_tree_add_string_format_value(tree, hf_ambit_fw_version, tvb, offset, 3, "FW version", "%d.%d.%d", fw1, fw2, fw3);
+ offset += 3;
+ offset += 1;
+ hw1 = tvb_get_guint8(tvb, offset);
+ hw2 = tvb_get_guint8(tvb, offset+1);
+ hw3 = tvb_get_letohs(tvb, offset+2);
+ proto_tree_add_string_format_value(tree, hf_ambit_hw_version, tvb, offset, 4, "HW version", "%d.%d.%d", hw1, hw2, hw3);
+ offset += 4;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 8);
+ offset += 8;
+}
+
+static gint dissect_ambit_personal_settings_get(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+}
+
+static gint dissect_ambit_personal_settings_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+ gint offset = 1;
+ proto_tree_add_item(tree, hf_ambit_personal_lock_sports_mode, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset = 2;
+ proto_tree_add_item(tree, hf_ambit_personal_lock_time_mode, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset = 4;
+ guint8 declination_direction = tvb_get_guint8(tvb, offset);
+ guint8 declination_deg = tvb_get_guint8(tvb, offset + 1);
+ if (declination_direction == 0) {
+ proto_tree_add_string_format_value(tree, hf_ambit_personal_compass_declination, tvb, offset, 2, "Compass declination", "None");
+ }
+ else {
+ proto_tree_add_string_format_value(tree, hf_ambit_personal_compass_declination, tvb, offset, 2, "Compass declination", "%s %f", declination_direction == 1 ? "E" : "W", 0.5*declination_deg);
+ }
+ offset = 8;
+ proto_tree_add_item(tree, hf_ambit_personal_unit_system, tvb, offset, 8, ENC_LITTLE_ENDIAN);
+ offset = 19;
+ proto_tree_add_item(tree, hf_ambit_personal_coordinate_system, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset = 21;
+ proto_tree_add_item(tree, hf_ambit_personal_map_orientation, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset = 24;
+ proto_tree_add_item(tree, hf_ambit_personal_gps_sync_time, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset = 25;
+ proto_tree_add_item(tree, hf_ambit_personal_time_format, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset = 26;
+ guint8 alarm_hour = tvb_get_guint8(tvb, offset);
+ guint8 alarm_minute = tvb_get_guint8(tvb, offset + 1);
+ proto_tree_add_string_format_value(tree, hf_ambit_personal_alarm_time, tvb, offset, 2, "Alarm time", "%d:%d", alarm_hour, alarm_minute);
+ offset = 28;
+ proto_tree_add_item(tree, hf_ambit_personal_alarm_enable, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset = 31;
+ guint8 dual_hour = tvb_get_guint8(tvb, offset);
+ guint8 dual_minute = tvb_get_guint8(tvb, offset + 1);
+ proto_tree_add_string_format_value(tree, hf_ambit_personal_dual_time, tvb, offset, 2, "Dual time", "%d:%d", dual_hour, dual_minute);
+ offset = 36;
+ proto_tree_add_item(tree, hf_ambit_personal_date_format, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset = 40;
+ proto_tree_add_item(tree, hf_ambit_personal_tones, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset = 44;
+ proto_tree_add_item(tree, hf_ambit_personal_backlight_mode, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset = 45;
+ proto_tree_add_item(tree, hf_ambit_personal_backlight_brightness, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset = 46;
+ proto_tree_add_item(tree, hf_ambit_personal_display_contrast, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset = 47;
+ proto_tree_add_item(tree, hf_ambit_personal_invert_display, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset = 48;
+ guint16 weight = tvb_get_letohs(tvb, offset);
+ proto_tree_add_float(tree, hf_ambit_personal_weight, tvb, offset, 2, ((float)weight)/100);
+ offset = 50;
+ proto_tree_add_item(tree, hf_ambit_personal_birthyear, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset = 52;
+ proto_tree_add_item(tree, hf_ambit_personal_max_hb, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset = 53;
+ proto_tree_add_item(tree, hf_ambit_personal_rest_hb, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset = 54;
+ proto_tree_add_item(tree, hf_ambit_personal_fitness_level, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset = 55;
+ guint8 sex = tvb_get_guint8(tvb, offset);
+ proto_tree_add_string_format_value(tree, hf_ambit_personal_sex, tvb, offset, 1, "Is male", "%s", sex == 1 ? "true" : "false");
+ offset = 56;
+ proto_tree_add_item(tree, hf_ambit_personal_length, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset = 60;
+ proto_tree_add_item(tree, hf_ambit_personal_alti_baro_profile, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset = 62;
+ proto_tree_add_item(tree, hf_ambit_personal_alti_baro_fused_alti, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+}
+
+static gint dissect_ambit_log_header_get(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+}
+
+static gint dissect_ambit_log_header_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+ gint offset = 0;
+ guint16 msg_id = tvb_get_letohs(tvb, 2);
+ guint32 datalen = tvb_get_letohl(tvb, 4);
+ guint32 header_1_len;
+
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 2);
+ offset += 2;
+ proto_tree_add_item(tree, hf_ambit_log_header_seq, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ header_1_len = tvb_get_letohl(tvb, offset);
+ proto_tree_add_item(tree, hf_ambit_log_header_length, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ if (msg_id == 1) {
+ proto_tree_add_item(tree, hf_ambit_log_header_sample_desc, tvb, offset, datalen, ENC_LITTLE_ENDIAN);
+ }
+ else if (msg_id == 2) {
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 1);
+ offset += 1;
+ guint16 year = tvb_get_letohs(tvb, offset);
+ guint8 month = tvb_get_guint8(tvb, offset + 2);
+ guint8 day = tvb_get_guint8(tvb, offset + 3);
+ proto_tree_add_string_format_value(tree, hf_ambit_log_header_date, tvb, offset, 4, "Date", "%04d-%02d-%02d", year, month, day);
+ offset += 4;
+ guint8 hour = tvb_get_guint8(tvb, offset);
+ guint8 minute = tvb_get_guint8(tvb, offset + 1);
+ guint16 seconds = tvb_get_guint8(tvb, offset + 2);
+ proto_tree_add_string_format_value(tree, hf_ambit_log_header_time, tvb, offset, 3, "Time", "%02d:%02d:%02d", hour, minute, seconds);
+ offset += 3;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 5);
+ offset += 5;
+ proto_tree_add_item(tree, hf_ambit_log_header_duration, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_header_ascent, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(tree, hf_ambit_log_header_descent, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(tree, hf_ambit_log_header_ascent_time, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_header_descent_time, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_header_recovery, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(tree, hf_ambit_log_header_avg_speed, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(tree, hf_ambit_log_header_max_speed, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(tree, hf_ambit_log_header_altitude_max, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(tree, hf_ambit_log_header_altitude_min, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(tree, hf_ambit_log_header_hr_avg, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(tree, hf_ambit_log_header_hr_max, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(tree, hf_ambit_log_header_peak_effect, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(tree, hf_ambit_log_header_activity_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(tree, hf_ambit_log_header_activity_name, tvb, offset, 16, ENC_LITTLE_ENDIAN);
+ offset += 16;
+ proto_tree_add_item(tree, hf_ambit_log_header_hr_min, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 1);
+ offset += 1;
+ proto_tree_add_item(tree, hf_ambit_log_header_temp_max, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(tree, hf_ambit_log_header_temp_min, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(tree, hf_ambit_log_header_distance, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_header_sample_count, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_header_energy, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 6);
+ offset += 6;
+ proto_tree_add_item(tree, hf_ambit_log_header_speed_max_time, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_header_alt_max_time, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_header_alt_min_time, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_header_hr_max_time, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_header_hr_min_time, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_header_temp_max_time, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_header_temp_min_time, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 8);
+ offset += 8;
+ proto_tree_add_item(tree, hf_ambit_log_header_time_first_fix, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(tree, hf_ambit_log_header_battery_start, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(tree, hf_ambit_log_header_battery_stop, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 4);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_header_distance_before_calib, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ if (datalen > offset) {
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 24);
+ offset += 24;
+ proto_tree_add_item(tree, hf_ambit_log_header_activity_name, tvb, offset, 16, ENC_LITTLE_ENDIAN);
+ offset += 16;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 4);
+ offset += 4;
+ year = tvb_get_letohs(tvb, offset);
+ month = tvb_get_guint8(tvb, offset + 2);
+ day = tvb_get_guint8(tvb, offset + 3);
+ proto_tree_add_string_format_value(tree, hf_ambit_log_header_date, tvb, offset, 4, "Date", "%04d-%02d-%02d", year, month, day);
+ offset += 4;
+ hour = tvb_get_guint8(tvb, offset);
+ minute = tvb_get_guint8(tvb, offset + 1);
+ seconds = tvb_get_guint8(tvb, offset + 2);
+ proto_tree_add_string_format_value(tree, hf_ambit_log_header_time, tvb, offset, 3, "Time", "%02d:%02d:%02d", hour, minute, seconds);
+ offset += 3;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 1);
+ offset += 1;
+ proto_tree_add_item(tree, hf_ambit_log_header_distance, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_header_duration, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_header_max_speed, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 2);
+ offset += 2;
+ proto_tree_add_item(tree, hf_ambit_log_header_ascent, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(tree, hf_ambit_log_header_descent, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 2);
+ offset += 2;
+ proto_tree_add_item(tree, hf_ambit_log_header_hr_avg, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(tree, hf_ambit_log_header_hr_max, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 4);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_header_recovery, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(tree, hf_ambit_log_header_energy, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(tree, hf_ambit_log_header_peak_effect, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(tree, hf_ambit_log_header_activity_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, (header_1_len - 211));
+ offset += (header_1_len - 211);
+ }
+ }
+}
+
+static gint dissect_ambit_log_count_get(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+}
+
+static gint dissect_ambit_log_count_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+ dissect_ambit_add_unknown(tvb, pinfo, tree, 0, 2);
+ proto_tree_add_item(tree, hf_ambit_log_count, tvb, 2, 2, ENC_LITTLE_ENDIAN);
+}
+
+static gint dissect_ambit_log_header_unwind_get(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+}
+
+static gint dissect_ambit_log_header_unwind_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+ proto_tree_add_item(tree, hf_ambit_log_header_more, tvb, 0, 4, ENC_LITTLE_ENDIAN);
+}
+
+static gint dissect_ambit_log_header_peek_get(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+}
+
+static gint dissect_ambit_log_header_peek_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+ proto_tree_add_item(tree, hf_ambit_log_header_more, tvb, 0, 4, ENC_LITTLE_ENDIAN);
+}
+
+static gint dissect_ambit_log_header_step_get(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+}
+
+static gint dissect_ambit_log_header_step_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+ proto_tree_add_item(tree, hf_ambit_log_header_more, tvb, 0, 4, ENC_LITTLE_ENDIAN);
+}
+
+static gint dissect_ambit_log_data_get(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+ gint offset = 0;
+ proto_tree_add_item(tree, hf_ambit_log_data_address, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_data_length, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+}
+
+static gint dissect_ambit_log_data_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+ gint offset = 0;
+ guint32 address = tvb_get_letohl(tvb, 0);
+ guint32 length = tvb_get_letohl(tvb, 4);
+
+ guint32 link_addr;
+ proto_item *pi;
+
+ proto_tree_add_item(tree, hf_ambit_log_data_address, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_data_length, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+
+ if (address == 0x000f4240) {
+ /* Known start address, then we know a bit about the header... */
+ proto_tree_add_item(tree, hf_ambit_log_data_last_addr, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ link_addr = tvb_get_letohl(tvb, offset);
+ pi = proto_tree_add_uint(tree, hf_ambit_log_data_addr_frame_ref, tvb, 0, 0, address_to_frame_lookup[(link_addr - 0x000f4240) / 0x400]);
+ PROTO_ITEM_SET_GENERATED(pi);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_data_first_addr, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ link_addr = tvb_get_letohl(tvb, offset);
+ pi = proto_tree_add_uint(tree, hf_ambit_log_data_addr_frame_ref, tvb, 0, 0, address_to_frame_lookup[(link_addr - 0x000f4240) / 0x400]);
+ PROTO_ITEM_SET_GENERATED(pi);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_data_entry_count, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(tree, hf_ambit_log_data_next_free_addr, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ link_addr = tvb_get_letohl(tvb, offset);
+ pi = proto_tree_add_uint(tree, hf_ambit_log_data_addr_frame_ref, tvb, 0, 0, address_to_frame_lookup[(link_addr - 0x000f4240) / 0x400]);
+ PROTO_ITEM_SET_GENERATED(pi);
+ offset += 4;
+ }
+
+ // Loop through data to find PEM start
+ int i;
+ guint8 a,b,c,d;
+ for(i=0; i<length; i++) {
+ if((a = tvb_get_guint8(tvb, i)) == 'P') {
+ b = tvb_get_guint8(tvb, i+1);
+ c = tvb_get_guint8(tvb, i+2);
+ d = tvb_get_guint8(tvb, i+3);
+
+ if (b == 'M' && c == 'E' && d == 'M') {
+ offset = i;
+ i = dissect_ambit_log_data_content(tvb, pinfo, tree, data, offset, length);
+ }
+ }
+ }
+}
+
+static gint dissect_ambit_log_data_content(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_, guint32 offset, guint32 length)
+{
+ guint16 header_1_len;
+ guint32 link_addr;
+ guint32 sample_count = 0;
+ proto_item *pi;
+ proto_item *sample_ti = NULL;
+ proto_tree *samples_tree = NULL;
+ guint32 period_sample_spec;
+
+ proto_tree_add_item(tree, hf_ambit_log_data_sof, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ if (offset + 4 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_data_next_addr, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ link_addr = tvb_get_letohl(tvb, offset);
+ pi = proto_tree_add_uint(tree, hf_ambit_log_data_addr_frame_ref, tvb, 0, 0, address_to_frame_lookup[(link_addr - 0x000f4240) / 0x400]);
+ PROTO_ITEM_SET_GENERATED(pi);
+ offset += 4;
+ if (offset + 4 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_data_prev_addr, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ link_addr = tvb_get_letohl(tvb, offset);
+ pi = proto_tree_add_uint(tree, hf_ambit_log_data_addr_frame_ref, tvb, 0, 0, address_to_frame_lookup[(link_addr - 0x000f4240) / 0x400]);
+ PROTO_ITEM_SET_GENERATED(pi);
+ offset += 4;
+ if (offset + 2 >= length) return offset;
+ header_1_len = tvb_get_letohs(tvb, offset);
+ proto_tree_add_item(tree, hf_ambit_log_header_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ if (offset + header_1_len >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_sample_desc, tvb, offset, header_1_len, ENC_LITTLE_ENDIAN);
+ period_sample_spec = offset - 2; // Include length as well
+ offset += header_1_len;
+ if (offset + 2 >= length) return offset;
+ header_1_len = tvb_get_letohs(tvb, offset);
+ proto_tree_add_item(tree, hf_ambit_log_header_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+
+ if (offset + 1 >= length) return offset;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 1);
+ offset += 1;
+ if (offset + 4 >= length) return offset;
+ guint16 year = tvb_get_letohs(tvb, offset);
+ guint8 month = tvb_get_guint8(tvb, offset + 2);
+ guint8 day = tvb_get_guint8(tvb, offset + 3);
+ proto_tree_add_string_format_value(tree, hf_ambit_log_header_date, tvb, offset, 4, "Date", "%04d-%02d-%02d", year, month, day);
+ offset += 4;
+ if (offset + 3 >= length) return offset;
+ guint8 hour = tvb_get_guint8(tvb, offset);
+ guint8 minute = tvb_get_guint8(tvb, offset + 1);
+ guint16 seconds = tvb_get_guint8(tvb, offset + 2);
+ proto_tree_add_string_format_value(tree, hf_ambit_log_header_time, tvb, offset, 3, "Time", "%02d:%02d:%02d", hour, minute, seconds);
+ offset += 3;
+ if (offset + 5 >= length) return offset;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 5);
+ offset += 5;
+ if (offset + 4 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_duration, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ if (offset + 2 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_ascent, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ if (offset + 2 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_descent, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ if (offset + 4 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_ascent_time, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ if (offset + 4 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_descent_time, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ if (offset + 2 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_recovery, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ if (offset + 2 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_avg_speed, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ if (offset + 2 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_max_speed, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ if (offset + 2 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_altitude_max, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ if (offset + 2 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_altitude_min, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ if (offset + 1 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_hr_avg, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ if (offset + 1 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_hr_max, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ if (offset + 1 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_peak_effect, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ if (offset + 1 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_activity_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ if (offset + 16 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_activity_name, tvb, offset, 16, ENC_LITTLE_ENDIAN);
+ offset += 16;
+ if (offset + 1 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_hr_min, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ if (offset + 1 >= length) return offset;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 1);
+ offset += 1;
+ if (offset + 2 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_temp_max, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ if (offset + 2 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_temp_min, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ if (offset + 4 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_distance, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ if (offset + 4 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_sample_count, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ sample_count = tvb_get_letohl(tvb, offset);
+ offset += 4;
+ if (offset + 2 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_energy, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ if (offset + 6 >= length) return offset;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 6);
+ offset += 6;
+ if (offset + 4 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_speed_max_time, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ if (offset + 4 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_alt_max_time, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ if (offset + 4 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_alt_min_time, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ if (offset + 4 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_hr_max_time, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ if (offset + 4 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_hr_min_time, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ if (offset + 4 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_temp_max_time, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ if (offset + 4 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_temp_min_time, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ if (offset + 8 >= length) return offset;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 8);
+ offset += 8;
+ if (offset + 2 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_time_first_fix, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ if (offset + 1 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_battery_start, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ if (offset + 1 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_battery_stop, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ if (offset + 4 >= length) return offset;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 4);
+ offset += 4;
+ if (offset + 4 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_distance_before_calib, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ if (header_1_len == 913) { /* Long header */
+ if (offset + 24 >= length) return offset;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 24);
+ offset += 24;
+ if (offset + 16 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_activity_name, tvb, offset, 16, ENC_LITTLE_ENDIAN);
+ offset += 16;
+ if (offset + 4 >= length) return offset;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 4);
+ offset += 4;
+ if (offset + 4 >= length) return offset;
+ year = tvb_get_letohs(tvb, offset);
+ month = tvb_get_guint8(tvb, offset + 2);
+ day = tvb_get_guint8(tvb, offset + 3);
+ proto_tree_add_string_format_value(tree, hf_ambit_log_header_date, tvb, offset, 4, "Date", "%04d-%02d-%02d", year, month, day);
+ offset += 4;
+ if (offset + 3 >= length) return offset;
+ hour = tvb_get_guint8(tvb, offset);
+ minute = tvb_get_guint8(tvb, offset + 1);
+ seconds = tvb_get_guint8(tvb, offset + 2);
+ proto_tree_add_string_format_value(tree, hf_ambit_log_header_time, tvb, offset, 3, "Time", "%02d:%02d:%02d", hour, minute, seconds);
+ offset += 3;
+ if (offset + 1 >= length) return offset;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 1);
+ offset += 1;
+ if (offset + 4 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_distance, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ if (offset + 4 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_duration, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ if (offset + 2 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_max_speed, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ if (offset + 2 >= length) return offset;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 2);
+ offset += 2;
+ if (offset + 2 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_ascent, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ if (offset + 2 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_descent, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ if (offset + 2 >= length) return offset;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 2);
+ offset += 2;
+ if (offset + 1 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_hr_avg, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ if (offset + 1 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_hr_max, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ if (offset + 4 >= length) return offset;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, 4);
+ offset += 4;
+ if (offset + 2 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_recovery, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ if (offset + 2 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_energy, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ if (offset + 1 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_peak_effect, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ if (offset + 1 >= length) return offset;
+ proto_tree_add_item(tree, hf_ambit_log_header_activity_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ if (offset + (header_1_len - 211) >= length) return offset;
+ dissect_ambit_add_unknown(tvb, pinfo, tree, offset, (header_1_len - 211));
+ offset += (header_1_len - 211);
+ }
+
+ sample_ti = proto_tree_add_text(tree, tvb, 0, 0, "Samples");
+ samples_tree = proto_item_add_subtree(sample_ti, ett_ambit_log_samples);
+
+ guint16 sample_len;
+ guint32 sample_num = 1;
+
+ while (offset + 2 < length) {
+ sample_len = tvb_get_letohs(tvb, offset);
+ if (offset + 2 + sample_len <= length) {
+ dissect_ambit_log_data_sample(tvb, pinfo, samples_tree, data, offset, length, &sample_num, &period_sample_spec);
+ }
+ offset += sample_len + 2;
+ }
+
+ return offset;
+}
+
+static gint dissect_ambit_log_data_sample(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_, guint32 offset, guint32 length, guint32 *sampleno, guint32 *periodic_sample_specifier)
+{
+ gint ret = 0, i;
+ proto_tree *sample_tree = NULL;
+ proto_tree *subtree = NULL, *subsubtree = NULL;
+ proto_item *sample_ti = NULL;
+ guint16 sample_len;
+ guint8 sample_type;
+ guint8 inner_type;
+ guint16 count;
+ guint16 type;
+ guint16 spec_offset;
+ guint16 spec_len;
+
+ sample_len = tvb_get_letohs(tvb, offset);
+ sample_type = tvb_get_guint8(tvb, offset + 2);
+
+ switch(sample_type) {
+ case 0:
+ *periodic_sample_specifier = offset;
+ sample_ti = proto_tree_add_text(tree, tvb, offset, sample_len + 2, "Period sample specifier");
+ sample_tree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_peri_spec_count, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ count = tvb_get_letohs(tvb, offset);
+ offset += 2;
+ sample_ti = proto_tree_add_text(sample_tree, tvb, offset, count*6, "Values");
+ subtree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ for (i=0; i<count; i++) {
+ sample_ti = proto_tree_add_text(subtree, tvb, offset, 6, "Value %d", i+1);
+ subsubtree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ proto_tree_add_item(subsubtree, hf_ambit_log_sample_peri_spec_id, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(subsubtree, hf_ambit_log_sample_peri_spec_offset, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(subsubtree, hf_ambit_log_sample_peri_spec_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ }
+ break;
+ case 2:
+ sample_ti = proto_tree_add_text(tree, tvb, offset, sample_len + 2, "Sample #%u (Periodic sample)", (*sampleno)++);
+ sample_tree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ // Loop through specification
+ count = tvb_get_letohs(tvb, (*periodic_sample_specifier) + 3);
+ for (i=0; i<count; i++) {
+ type = tvb_get_letohs(tvb, (*periodic_sample_specifier) + 5 + i*6);
+ spec_offset = tvb_get_letohs(tvb, (*periodic_sample_specifier) + 7 + i*6);
+ spec_len = tvb_get_letohs(tvb, (*periodic_sample_specifier) + 9 + i*6);
+ switch(type) {
+ case 0x03:
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_periodic_distance, tvb, offset + spec_offset, spec_len, ENC_LITTLE_ENDIAN);
+ break;
+ case 0x04:
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_periodic_speed, tvb, offset + spec_offset, spec_len, ENC_LITTLE_ENDIAN);
+ break;
+ case 0x05:
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_periodic_hr, tvb, offset + spec_offset, spec_len, ENC_LITTLE_ENDIAN);
+ break;
+ case 0x06:
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_periodic_time, tvb, offset + spec_offset, spec_len, ENC_LITTLE_ENDIAN);
+ break;
+ case 0x0c:
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_periodic_altitude, tvb, offset + spec_offset, spec_len, ENC_LITTLE_ENDIAN);
+ break;
+ case 0x0e:
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_periodic_energy, tvb, offset + spec_offset, spec_len, ENC_LITTLE_ENDIAN);
+ break;
+ case 0x0f:
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_periodic_temp, tvb, offset + spec_offset, spec_len, ENC_LITTLE_ENDIAN);
+ break;
+ case 0x18:
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_periodic_preassure, tvb, offset + spec_offset, spec_len, ENC_LITTLE_ENDIAN);
+ break;
+ case 0x19:
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_periodic_vert_speed, tvb, offset + spec_offset, spec_len, ENC_LITTLE_ENDIAN);
+ break;
+ }
+ }
+ break;
+ case 3:
+ inner_type = tvb_get_guint8(tvb, offset + 7);
+ switch(inner_type) {
+ case 0x04:
+ sample_ti = proto_tree_add_text(tree, tvb, offset, sample_len + 2, "Sample #%u (Pause)", (*sampleno)++);
+ sample_tree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_time_offset, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ break;
+ case 0x05:
+ sample_ti = proto_tree_add_text(tree, tvb, offset, sample_len + 2, "Sample #%u (Restart)", (*sampleno)++);
+ sample_tree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_time_offset, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ break;
+ break;
+ case 0x06:
+ sample_ti = proto_tree_add_text(tree, tvb, offset, sample_len + 2, "Sample #%u (IBI)", (*sampleno)++);
+ sample_tree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_time_offset, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ for(i=0; i<sample_len-6; i+=2) {
+ proto_tree_add_item(sample_tree, hf_ambit_log_ibi, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ }
+ break;
+ case 0x07:
+ sample_ti = proto_tree_add_text(tree, tvb, offset, sample_len + 2, "Sample #%u (TTFF)", (*sampleno)++);
+ sample_tree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_time_offset, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ dissect_ambit_add_unknown(tvb, pinfo, sample_tree, offset, 2);
+ offset += 2;
+ break;
+ case 0x08:
+ sample_ti = proto_tree_add_text(tree, tvb, offset, sample_len + 2, "Sample #%u (Distance source)", (*sampleno)++);
+ sample_tree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_time_offset, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_distance_source_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ if (offset < sample_len - 2) {
+ dissect_ambit_add_unknown(tvb, pinfo, sample_tree, offset, sample_len - 7);
+ }
+ break;
+ case 0x09:
+ sample_ti = proto_tree_add_text(tree, tvb, offset, sample_len + 2, "Sample #%u (Time event)", (*sampleno)++);
+ sample_tree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_time_offset, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_time_event_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ {
+ guint16 year = tvb_get_letohs(tvb, offset);
+ guint8 month = tvb_get_guint8(tvb, offset + 2);
+ guint8 day = tvb_get_guint8(tvb, offset + 3);
+ proto_tree_add_string_format_value(sample_tree, hf_ambit_log_time_event_date, tvb, offset, 4, "Date", "%04d-%02d-%02d", year, month, day);
+ offset += 4;
+ guint8 hour = tvb_get_guint8(tvb, offset);
+ guint8 minute = tvb_get_guint8(tvb, offset + 1);
+ guint16 seconds = tvb_get_guint8(tvb, offset + 2);
+ proto_tree_add_string_format_value(sample_tree, hf_ambit_log_time_event_time, tvb, offset, 3, "Time", "%02d:%02d:%02d", hour, minute, seconds);
+ offset += 3;
+ }
+ proto_tree_add_item(sample_tree, hf_ambit_log_time_event_duration, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(sample_tree, hf_ambit_log_time_event_distance, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ dissect_ambit_add_unknown(tvb, pinfo, sample_tree, offset, sample_len - 22);
+ break;
+ case 0x0d:
+ sample_ti = proto_tree_add_text(tree, tvb, offset, sample_len + 2, "Sample #%u (Altitude source)", (*sampleno)++);
+ sample_tree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_time_offset, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_altitude_source_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_altitude_source_altitude_offset, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_altitude_source_preassure_offset, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ if (offset < sample_len - 2) {
+ dissect_ambit_add_unknown(tvb, pinfo, sample_tree, offset, sample_len - 11);
+ }
+ break;
+ case 0x0f:
+ sample_ti = proto_tree_add_text(tree, tvb, offset, sample_len + 2, "Sample #%u (gps-base)", (*sampleno)++);
+ sample_tree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_time_offset, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ dissect_ambit_add_unknown(tvb, pinfo, sample_tree, offset, 2);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_gps_base_navtype, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ {
+ guint16 year = tvb_get_letohs(tvb, offset);
+ guint8 month = tvb_get_guint8(tvb, offset + 2);
+ guint8 day = tvb_get_guint8(tvb, offset + 3);
+ proto_tree_add_string_format_value(sample_tree, hf_ambit_log_gps_base_date, tvb, offset, 4, "Date", "%04d-%02d-%02d", year, month, day);
+ offset += 4;
+ guint8 hour = tvb_get_guint8(tvb, offset);
+ guint8 minute = tvb_get_guint8(tvb, offset + 1);
+ guint16 seconds = tvb_get_letohs(tvb, offset + 2);
+ proto_tree_add_string_format_value(sample_tree, hf_ambit_log_gps_base_time, tvb, offset, 4, "Time", "%02d:%02d:%2.3f", hour, minute, ((float)seconds/1000.0));
+ offset += 4;
+ }
+ {
+ guint32 latlong = tvb_get_letohl(tvb, offset);
+ proto_tree_add_string_format_value(sample_tree, hf_ambit_log_gps_base_latitude, tvb, offset, 4, "Latitude", "%f", (float)latlong/10000000);
+ offset += 4;
+ latlong = tvb_get_letohl(tvb, offset);
+ proto_tree_add_string_format_value(sample_tree, hf_ambit_log_gps_base_longitude, tvb, offset, 4, "Longitude", "%f", (float)latlong/10000000);
+ offset += 4;
+ }
+ proto_tree_add_item(sample_tree, hf_ambit_log_gps_base_altitude, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(sample_tree, hf_ambit_log_gps_base_speed, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_gps_base_heading, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_gps_base_ehpe, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(sample_tree, hf_ambit_log_gps_base_satelite_no, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_gps_base_hdop, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ sample_ti = proto_tree_add_text(sample_tree, tvb, offset, sample_len-40, "Satellites");
+ subtree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ for(i=0; i<sample_len-40; i+=6) {
+ sample_ti = proto_tree_add_text(subtree, tvb, offset, 6, "Satellite");
+ subsubtree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ proto_tree_add_item(subsubtree, hf_ambit_log_gps_base_sv, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(subsubtree, hf_ambit_log_gps_base_state, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ dissect_ambit_add_unknown(tvb, pinfo, subsubtree, offset, 1);
+ offset += 1;
+ proto_tree_add_item(subsubtree, hf_ambit_log_gps_base_snr, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ }
+ break;
+ case 0x10:
+ sample_ti = proto_tree_add_text(tree, tvb, offset, sample_len + 2, "Sample #%u (gps-small)", (*sampleno)++);
+ sample_tree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_time_offset, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ {
+ gint16 latlong_offset = tvb_get_letohs(tvb, offset);
+ proto_tree_add_string_format_value(sample_tree, hf_ambit_log_gps_small_latitude, tvb, offset, 2, "Latitude offset", "%d (%f)", latlong_offset, (float)latlong_offset/1000000);
+ offset += 2;
+ latlong_offset = tvb_get_letohs(tvb, offset);
+ proto_tree_add_string_format_value(sample_tree, hf_ambit_log_gps_small_longitude, tvb, offset, 2, "Longitude offset", "%d (%f)", latlong_offset, (float)latlong_offset/1000000);
+ offset += 2;
+ }
+ proto_tree_add_item(sample_tree, hf_ambit_log_gps_small_time, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_gps_small_ehpe, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_gps_small_satelite_no, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ if (offset < sample_len - 2) {
+ dissect_ambit_add_unknown(tvb, pinfo, sample_tree, offset, sample_len - 14);
+ }
+ break;
+ case 0x11:
+ sample_ti = proto_tree_add_text(tree, tvb, offset, sample_len + 2, "Sample #%u (gps-tiny)", (*sampleno)++);
+ sample_tree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_time_offset, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ {
+ gint8 latlong_offset = tvb_get_guint8(tvb, offset);
+ proto_tree_add_string_format_value(sample_tree, hf_ambit_log_gps_tiny_latitude, tvb, offset, 1, "Latitude offset", "%d (%f)", latlong_offset, (float)latlong_offset/1000000);
+ offset += 1;
+ latlong_offset = tvb_get_guint8(tvb, offset);
+ proto_tree_add_string_format_value(sample_tree, hf_ambit_log_gps_tiny_longitude, tvb, offset, 1, "Longitude offset", "%d (%f)", latlong_offset, (float)latlong_offset/1000000);
+ offset += 1;
+ }
+ {
+ guint8 time = tvb_get_guint8(tvb, offset);
+ proto_tree_add_string_format_value(sample_tree, hf_ambit_log_gps_tiny_time, tvb, offset, 1, "Time", "%d", time & 0x3f);
+ // Unknown bits
+ dissect_ambit_add_unknown(tvb, pinfo, sample_tree, offset, 1);
+ offset += 1;
+ }
+ if (offset < sample_len - 2) {
+ dissect_ambit_add_unknown(tvb, pinfo, sample_tree, offset, sample_len - 9);
+ }
+ break;
+ case 0x12:
+ sample_ti = proto_tree_add_text(tree, tvb, offset, sample_len + 2, "Sample #%u (Time)", (*sampleno)++);
+ sample_tree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_time_offset, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ {
+ guint8 hour = tvb_get_guint8(tvb, offset);
+ guint8 minute = tvb_get_guint8(tvb, offset + 1);
+ guint16 seconds = tvb_get_guint8(tvb, offset + 2);
+ proto_tree_add_string_format_value(sample_tree, hf_ambit_log_time_event_time, tvb, offset, 3, "Time", "%02d:%02d:%02d", hour, minute, seconds);
+ offset += 3;
+ }
+ if (offset < sample_len - 2) {
+ dissect_ambit_add_unknown(tvb, pinfo, sample_tree, offset, sample_len - 9);
+ }
+ break;
+ case 0x18:
+ sample_ti = proto_tree_add_text(tree, tvb, offset, sample_len + 2, "Sample #%u (Activity)", (*sampleno)++);
+ sample_tree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_time_offset, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_activity_type, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_activity_custom_mode_id, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ if (offset < sample_len - 2) {
+ dissect_ambit_add_unknown(tvb, pinfo, sample_tree, offset, sample_len - 12);
+ }
+ break;
+ case 0x1b:
+ sample_ti = proto_tree_add_text(tree, tvb, offset, sample_len + 2, "Sample #%u (lat-long)", (*sampleno)++);
+ sample_tree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_time_offset, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ {
+ guint32 latlong = tvb_get_letohl(tvb, offset);
+ proto_tree_add_string_format_value(sample_tree, hf_ambit_log_gps_base_latitude, tvb, offset, 4, "Latitude", "%f", (float)latlong/10000000);
+ offset += 4;
+ latlong = tvb_get_letohl(tvb, offset);
+ proto_tree_add_string_format_value(sample_tree, hf_ambit_log_gps_base_longitude, tvb, offset, 4, "Longitude", "%f", (float)latlong/10000000);
+ offset += 4;
+ }
+ if (offset < sample_len - 2) {
+ dissect_ambit_add_unknown(tvb, pinfo, sample_tree, offset, sample_len - 14);
+ }
+ break;
+ default:
+ sample_ti = proto_tree_add_text(tree, tvb, offset, sample_len + 2, "Sample #%u (Unknown)", (*sampleno)++);
+ sample_tree = proto_item_add_subtree(sample_ti, ett_ambit_log_sample);
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_length, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(sample_tree, hf_ambit_log_sample_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_time_offset, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ proto_tree_add_item(sample_tree, hf_ambit_log_other_type, tvb, offset, 1, ENC_LITTLE_ENDIAN);
+ offset += 1;
+ dissect_ambit_add_unknown(tvb, pinfo, sample_tree, offset, sample_len - 6);
+ break;
+ }
+ break;
+ default:
+ break;
+ }
+
+ return 0;
+}
+
+static gint
+dissect_ambit(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
+{
+ gint offset = 0;
+ guint8 usbid = tvb_get_guint8(tvb, 0);
+ guint8 len = tvb_get_guint8(tvb, 1) + 2;
+ guint8 msg_part = tvb_get_guint8(tvb, 2);
+ guint8 data_header_len = tvb_get_guint8(tvb, 3);
+ guint16 msg_count = tvb_get_letohs(tvb, 4);
+ guint32 command = tvb_get_ntohl(tvb, 8);
+ guint32 pkt_len = tvb_get_letohl(tvb, 16);
+ tvbuff_t *new_tvb = NULL, *next_tvb = NULL, *log_tvb = NULL;
+ static guint32 fragments_start_frame;
+ static guint16 fragments_offset;
+ static guint16 fragments_data_len;
+ int data_len = 0;
+ int data_offset = 0;
+ const ambit_protocol_type_t *subdissector;
+
+ static guint32 current_log_start_frame = 0xffffffff;
+ static guint32 log_after_end_of_use = 0xffffffff;
+ static guint32 log_last_known_address;
+
+ if (usbid == D_AMBIT_USBID) {
+ if (msg_part == 0x5d) {
+ data_len = data_header_len - 12;
+ data_offset = 20;
+ }
+ else {
+ data_len = data_header_len;
+ data_offset = 8;
+ }
+
+ while (pinfo->fd->num + 1 > reassembly_entries_alloc) {
+ reassembly_entries = g_realloc(reassembly_entries, sizeof(ambit_reassembly_entry_t)*(reassembly_entries_alloc + 10000));
+ memset(reassembly_entries+reassembly_entries_alloc, 0, sizeof(ambit_reassembly_entry_t)*10000);
+ reassembly_entries_alloc += 10000;
+ }
+ if (!pinfo->fd->flags.visited) {
+ if (msg_part == 0x5d && msg_count > 1) {
+ reassembly_entries[pinfo->fd->num].valid = 2;
+ reassembly_entries[pinfo->fd->num].command = command;
+ reassembly_entries[pinfo->fd->num].start_frame = pinfo->fd->num;
+ reassembly_entries[pinfo->fd->num].frame_count = msg_count;
+ reassembly_entries[pinfo->fd->num].size = pkt_len;
+ reassembly_entries[pinfo->fd->num].data = (unsigned char*)g_malloc(pkt_len);
+ fragments_start_frame = pinfo->fd->num;
+ fragments_offset = data_len;
+ fragments_data_len = pkt_len;
+
+ tvb_memcpy(tvb, reassembly_entries[pinfo->fd->num].data, data_offset, data_len);
+ }
+ else if (msg_part == 0x5e) {
+ if (fragments_data_len >= fragments_offset + data_len) {
+ //fragments_start_frame = pinfo->fd->num-msg_count;
+ reassembly_entries[pinfo->fd->num].valid = 2;
+ reassembly_entries[pinfo->fd->num].command = reassembly_entries[fragments_start_frame].command;
+ reassembly_entries[pinfo->fd->num].start_frame = fragments_start_frame;
+ reassembly_entries[pinfo->fd->num].frame_count = reassembly_entries[fragments_start_frame].frame_count;
+ reassembly_entries[pinfo->fd->num].size = fragments_data_len;
+ reassembly_entries[pinfo->fd->num].data = reassembly_entries[fragments_start_frame].data;
+ tvb_memcpy(tvb, &(reassembly_entries[fragments_start_frame].data[fragments_offset]), data_offset, data_len);
+ fragments_offset += data_len;
+
+ command = reassembly_entries[fragments_start_frame].command;
+ }
+ else {
+ }
+ }
+ else {
+ reassembly_entries[pinfo->fd->num].valid = 1;
+ reassembly_entries[pinfo->fd->num].command = command;
+ }
+
+ // Handle dissection of logs
+ if (command == 0x0b170a00) {
+ // First check for initial known header
+ if (msg_part == 0x5d) {
+ guint32 address = tvb_get_letohl(tvb, data_offset);
+ guint32 length = tvb_get_letohl(tvb, data_offset + 4);
+
+ log_last_known_address = address;
+ if (address == 0x000f4240) {
+ log_after_end_of_use = tvb_get_letohl(tvb, data_offset + 20);
+ }
+ // Set address to lookup table
+ address_to_frame_lookup[(log_last_known_address - 0x000f4240) / 0x400] = pinfo->fd->num + 19;
+
+ // Adjust data pointers for extra address and length fields
+ data_offset += 8;
+ data_len -= 8;
+ }
+
+ // Loop through entry to find PMEM
+ int i;
+ guint8 a,b,c,d;
+ for(i=0; i<data_len; i++) {
+ if((a = tvb_get_guint8(tvb, data_offset+i)) == 'P' && i+3<data_len) {
+ b = tvb_get_guint8(tvb, data_offset+i+1);
+ c = tvb_get_guint8(tvb, data_offset+i+2);
+ d = tvb_get_guint8(tvb, data_offset+i+3);
+
+ if (b == 'M' && c == 'E' && d == 'M') {
+ if (current_log_start_frame != 0xffffffff) {
+ reassembly_entries[current_log_start_frame].log_entry = g_realloc(reassembly_entries[current_log_start_frame].log_entry, reassembly_entries[current_log_start_frame].log_entry_size + i);
+ tvb_memcpy(tvb, &reassembly_entries[current_log_start_frame].log_entry[reassembly_entries[current_log_start_frame].log_entry_size], data_offset, i);
+ reassembly_entries[current_log_start_frame].log_entry_size += i;
+ }
+ reassembly_entries[pinfo->fd->num].log_entry = (unsigned char*)g_malloc(data_len-i);
+ tvb_memcpy(tvb, reassembly_entries[pinfo->fd->num].log_entry, data_offset+i, data_len-i);
+ reassembly_entries[pinfo->fd->num].log_entry_size = data_len-i;
+ current_log_start_frame = pinfo->fd->num;
+ break;
+ }
+ }
+ }
+
+ if (i == data_len && current_log_start_frame != 0xffffffff) {
+ // No new PMEM found
+ reassembly_entries[current_log_start_frame].log_entry = g_realloc(reassembly_entries[current_log_start_frame].log_entry, reassembly_entries[current_log_start_frame].log_entry_size + data_len);
+ tvb_memcpy(tvb, &reassembly_entries[current_log_start_frame].log_entry[reassembly_entries[current_log_start_frame].log_entry_size], data_offset, data_len);
+
+ reassembly_entries[current_log_start_frame].log_entry_size += data_len;
+ }
+
+ // Increment address
+ log_last_known_address += data_len;
+
+ reassembly_entries[pinfo->fd->num].log_start_frame = current_log_start_frame;
+
+ if (log_last_known_address >= log_after_end_of_use) {
+ // If we are after end of file, reset log entry!
+ current_log_start_frame = 0xffffffff;
+ }
+ }
+ }
+
+ if (tree) { /* we are being asked for details */
+ proto_item *ti = NULL;
+ proto_tree *ambit_tree = NULL;
+ proto_item *data_ti = NULL;
+ proto_tree *data_tree = NULL;
+
+ col_set_str(pinfo->cinfo, COL_PROTOCOL, "Ambit");
+
+ ti = proto_tree_add_item(tree, proto_ambit, tvb, 0, len, ENC_NA);
+ ambit_tree = proto_item_add_subtree(ti, ett_ambit);
+ offset = 2;
+ proto_tree_add_item(ambit_tree, hf_ambit_msgpart, tvb, offset, 1, ENC_BIG_ENDIAN);
+ offset += 1;
+ proto_tree_add_item(ambit_tree, hf_ambit_msglength, tvb, offset, 1, ENC_BIG_ENDIAN);
+ offset += 1;
+ if (msg_part == 0x5d) {
+ proto_tree_add_item(ambit_tree, hf_ambit_msgsegs, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ }
+ else if (msg_part == 0x5e) {
+ proto_tree_add_item(ambit_tree, hf_ambit_msgseg, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ }
+ offset += 2;
+ proto_tree_add_item(ambit_tree, hf_ambit_msgheaderchksum, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ if (msg_part == 0x5d) {
+ proto_tree_add_item(ambit_tree, hf_ambit_requestcmd, tvb, offset, 4, ENC_BIG_ENDIAN);
+ offset += 4;
+ offset += 2;
+ proto_tree_add_item(ambit_tree, hf_ambit_pktseqno, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ proto_tree_add_item(ambit_tree, hf_ambit_pktlen, tvb, offset, 4, ENC_LITTLE_ENDIAN);
+ offset += 4;
+ }
+
+ if (reassembly_entries[pinfo->fd->num].valid == 1) {
+ new_tvb = tvb_new_subset_remaining(tvb, offset);
+ pkt_len = data_len;
+ col_set_str(pinfo->cinfo, COL_INFO, "");
+ }
+ else if (reassembly_entries[pinfo->fd->num].start_frame + reassembly_entries[pinfo->fd->num].frame_count - 1 == pinfo->fd->num) {
+ new_tvb = tvb_new_real_data(reassembly_entries[pinfo->fd->num].data, reassembly_entries[pinfo->fd->num].size, reassembly_entries[pinfo->fd->num].size);
+ //tvb_set_child_real_data_tvbuff(tvb, new_tvb);
+ add_new_data_source(pinfo, new_tvb, "Reassembled");
+ pkt_len = reassembly_entries[pinfo->fd->num].size;
+
+ col_add_fstr(pinfo->cinfo, COL_INFO, " (#%u of #%u) Reassembled", pinfo->fd->num-reassembly_entries[pinfo->fd->num].start_frame + 1, reassembly_entries[pinfo->fd->num].frame_count);
+
+ if (reassembly_entries[pinfo->fd->num].log_start_frame != 0xffffffff &&
+ reassembly_entries[reassembly_entries[pinfo->fd->num].log_start_frame].log_entry != NULL) {
+ log_tvb = tvb_new_real_data(reassembly_entries[reassembly_entries[pinfo->fd->num].log_start_frame].log_entry, reassembly_entries[reassembly_entries[pinfo->fd->num].log_start_frame].log_entry_size, reassembly_entries[reassembly_entries[pinfo->fd->num].log_start_frame].log_entry_size);
+ add_new_data_source(pinfo, log_tvb, "Log");
+ }
+ }
+ else {
+ col_add_fstr(pinfo->cinfo, COL_INFO, " (#%u of #%u)", pinfo->fd->num-reassembly_entries[pinfo->fd->num].start_frame + 1, reassembly_entries[pinfo->fd->num].frame_count);
+ }
+
+ subdissector = find_subdissector(reassembly_entries[pinfo->fd->num].command);
+ if (subdissector != NULL) {
+ col_prepend_fstr(pinfo->cinfo, COL_INFO, "%s", subdissector->name);
+ }
+
+ if (new_tvb != NULL) {
+ if (subdissector != NULL) {
+ data_ti = proto_tree_add_text(ambit_tree, new_tvb, 0, pkt_len, "%s", subdissector->name);
+ }
+ else {
+ data_ti = proto_tree_add_text(ambit_tree, new_tvb, 0, pkt_len, "Payload");
+ }
+ data_tree = proto_item_add_subtree(data_ti, ett_ambit_data);
+
+ if (subdissector != NULL) {
+ subdissector->dissector(new_tvb, pinfo, data_tree, data);
+ }
+ }
+
+ if (log_tvb != NULL) {
+ data_ti = proto_tree_add_text(ambit_tree, new_tvb, 0, pkt_len, "Full log entry");
+ data_tree = proto_item_add_subtree(data_ti, ett_ambit_log_data);
+ dissect_ambit_log_data_content(log_tvb, pinfo, data_tree, data, 0, reassembly_entries[reassembly_entries[pinfo->fd->num].log_start_frame].log_entry_size);
+ }
+
+ offset += data_len;
+ proto_tree_add_item(ambit_tree, hf_ambit_payloadchksum, tvb, offset, 2, ENC_LITTLE_ENDIAN);
+ offset += 2;
+ }
+
+ return len;
+ }
+
+ return 0;
+}
+
+void
+proto_register_ambit(void)
+{
+ static hf_register_info hf[] = {
+ { &hf_ambit_unknown,
+ { "Unknown", "ambit.unknown", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL } },
+ { &hf_ambit_usbid,
+ { "USB-ID", "ambit.usbid", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL } },
+ { &hf_ambit_usblength,
+ { "USB length", "ambit.usblen", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } },
+ { &hf_ambit_msgpart,
+ { "msg part", "ambit.msgpart", FT_UINT8, BASE_HEX, VALS(msgpart_index_vals), 0, NULL, HFILL } },
+ { &hf_ambit_msglength,
+ { "msg length", "ambit.msglen", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } },
+ { &hf_ambit_msgsegs,
+ { "msg parts", "ambit.msgsegs", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } },
+ { &hf_ambit_msgseg,
+ { "msg part", "ambit.msgseg", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } },
+ { &hf_ambit_msgheaderchksum,
+ { "msg header checksum", "ambit.msgheaderchksum", FT_UINT16, BASE_HEX, NULL, 0x0, NULL, HFILL } },
+ { &hf_ambit_requestcmd,
+ { "Command", "ambit.command", FT_UINT32, BASE_HEX, NULL, 0x0, NULL, HFILL } },
+ { &hf_ambit_pktseqno,
+ { "Packet sequence no", "ambit.pktseqno", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } },
+ { &hf_ambit_pktlen,
+ { "Packet length", "ambit.pktlen", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_payloadchksum,
+ { "Paypload checksum", "ambit.payloadchksum", FT_UINT16, BASE_HEX, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_date,
+ { "Date", "ambit.date", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_time,
+ { "Time", "ambit.time", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_charge,
+ { "Charge", "ambit.charge", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_model,
+ { "Model", "ambit.model", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_serial,
+ { "Serial", "ambit.serial", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_fw_version,
+ { "FW version", "ambit.fwversion", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_hw_version,
+ { "HW version", "ambit.hwversion", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_compass_declination,
+ { "Compass declination", "ambit.personal.compass_declination", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_map_orientation,
+ { "Map orientation", "ambit.personal.map_orientation", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_weight,
+ { "Weight", "ambit.personal.weight", FT_FLOAT, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_date_format,
+ { "Date format", "ambit.personal.date_format", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_time_format,
+ { "Time format", "ambit.personal.time_format", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_coordinate_system,
+ { "Coordinate system", "ambit.personal.coordinate_system", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_unit_system,
+ { "Units", "ambit.personal.units", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL } },
+ { &hf_ambit_personal_alarm_enable,
+ { "Alarm enable", "ambit.personal.alarm_enable", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_alarm_time,
+ { "Alarm time", "ambit.personal.alarm_time", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_dual_time,
+ { "Dual time", "ambit.personal.dual_time", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_gps_sync_time,
+ { "Sync time w. GPS", "ambit.personal.gps_sync_time", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_alti_baro_fused_alti,
+ { "Fused altitude", "ambit.personal.fused_alti", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_alti_baro_profile,
+ { "Baro profile", "ambit.personal.baro_profile", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_max_hb,
+ { "Max heart beat", "ambit.personal.maxhb", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_rest_hb,
+ { "Rest heart rate", "ambit.personal.resthb", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_birthyear,
+ { "Birthyear", "ambit.personal.birthyear", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } },
+ { &hf_ambit_personal_length,
+ { "Length", "ambit.personal.length", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_sex,
+ { "IsMale", "ambit.personal.ismale", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_fitness_level,
+ { "Fitness level", "ambit.personal.fitness_level", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_backlight_brightness,
+ { "Backlight brightness", "ambit.personal.backlight_brightness", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_backlight_mode,
+ { "Backlight mode", "ambit.personal.backlight_mode", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_display_contrast,
+ { "Display contrast", "ambit.personal.display_contrast", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_invert_display,
+ { "Invert display", "ambit.personal.invert_display", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_lock_sports_mode,
+ { "Button lock, sports", "ambit.personal.lock_sportsmode", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_lock_time_mode,
+ { "Button lock, time", "ambit.personal.lock_timemode", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_personal_tones,
+ { "Tones", "ambit.personal.tones", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+
+ { &hf_ambit_log_header_seq,
+ { "Header part", "ambit.log_header.header_part", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_length,
+ { "Length", "ambit.log_header.length", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_sample_desc,
+ { "Samples description???", "ambit.log_header.samples_desc", FT_BYTES, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_date,
+ { "Date", "ambit.log_header.date", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_time,
+ { "Time", "ambit.log_header.time", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_duration,
+ { "Duration (1/10 sec)", "ambit.log_header.duration", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_ascent,
+ { "Ascent", "ambit.log_header.ascent", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_descent,
+ { "Descent", "ambit.log_header.descent", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_ascent_time,
+ { "Ascent time (sec)", "ambit.log_header.ascent_time", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_descent_time,
+ { "Descent time (sec)", "ambit.log_header.descent_time", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_recovery,
+ { "Recovery time (minutes)", "ambit.log_header.recovery", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_avg_speed,
+ { "Avg speed (10 m/h)", "ambit.log_header.avg_speed", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_max_speed,
+ { "Max speed (10 m/h)", "ambit.log_header.max_speed", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_altitude_max,
+ { "Altitude max", "ambit.log_header.alt_max", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_altitude_min,
+ { "Altitude min", "ambit.log_header.alt_min", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_hr_avg,
+ { "Heartrate avg", "ambit.log_header.hr_avg", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_hr_max,
+ { "Heartrate max", "ambit.log_header.hr_max", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_peak_effect,
+ { "Peak training effect (1/10)", "ambit.log_header.peak_effect", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_activity_type,
+ { "Activity type", "ambit.log_header.activity_type", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_activity_name,
+ { "Activity name", "ambit.log_header.activity_name", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_hr_min,
+ { "Heartrate min", "ambit.log_header.hr_min", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_temp_max,
+ { "Temperature max (1/10 Celsius)", "ambit.log_header.temp_max", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_temp_min,
+ { "Temperature min (1/10 Celsius)", "ambit.log_header.temp_min", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_distance,
+ { "Distance (m)", "ambit.log_header.distance", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_sample_count,
+ { "Sample count", "ambit.log_header.sample_count", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_energy,
+ { "Energy consumption (kcal)", "ambit.log_header.energy_consumption", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_speed_max_time,
+ { "Time max speed (ms)", "ambit.log_header.speed_maxtime", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_alt_max_time,
+ { "Time max altitude (ms)", "ambit.log_header.alt_maxtime", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_alt_min_time,
+ { "Time min altitude (ms)", "ambit.log_header.alt_mintime", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_hr_max_time,
+ { "Time max HR (ms)", "ambit.log_header.hr_maxtime", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_hr_min_time,
+ { "Time min HR (ms)", "ambit.log_header.hr_mintime", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_temp_max_time,
+ { "Time max temperature (ms)", "ambit.log_header.temp_maxtime", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_temp_min_time,
+ { "Time min temperature (ms)", "ambit.log_header.temp_mintime", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_time_first_fix,
+ { "Time of first fix", "ambit.log_header.time_first_fix", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_battery_start,
+ { "Battery at start", "ambit.log_header.battery_start", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_battery_stop,
+ { "Battery at end", "ambit.log_header.battery_stop", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_header_distance_before_calib,
+ { "Distance before calibration", "ambit.log_header.distance_before_calib", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+
+ { &hf_ambit_log_header_more,
+ { "More values", "ambit.log_header.more", FT_UINT32, BASE_HEX, VALS(log_header_more_vals), 0, NULL, HFILL } },
+
+ { &hf_ambit_log_count,
+ { "Log count", "ambit.log.count", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+
+ { &hf_ambit_log_data_addr_frame_ref,
+ { "In frame", "ambit.log_data.inframe", FT_FRAMENUM, BASE_NONE, NULL, 0, NULL, HFILL } },
+ { &hf_ambit_log_data_address,
+ { "Address", "ambit.log_data.address", FT_UINT32, BASE_HEX, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_data_length,
+ { "Length", "ambit.log_data.length", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_data_sof,
+ { "Start of entry", "ambit.log_data.start_of_entry", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_data_first_addr,
+ { "First entry address", "ambit.log_data.first_addr", FT_UINT32, BASE_HEX, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_data_last_addr,
+ { "Last entry address", "ambit.log_data.last_addr", FT_UINT32, BASE_HEX, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_data_entry_count,
+ { "Number of entries", "ambit.log_data.entry_count", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_data_next_free_addr,
+ { "Next free address", "ambit.log_data.next_free_addr", FT_UINT32, BASE_HEX, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_data_next_addr,
+ { "Next entry address", "ambit.log_data.next_addr", FT_UINT32, BASE_HEX, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_data_prev_addr,
+ { "Previous entry address", "ambit.log_data.prev_addr", FT_UINT32, BASE_HEX, NULL, 0x0,NULL, HFILL } },
+
+
+ { &hf_ambit_log_sample_length,
+ { "Sample length", "ambit.log_sample.length", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_sample_type,
+ { "Sample type", "ambit.log_sample.type", FT_UINT8, BASE_HEX, VALS(log_samples_type_vals), 0x0,NULL, HFILL } },
+ { &hf_ambit_log_sample_peri_spec_count,
+ { "Value count", "ambit.log_sample.spec.count", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_sample_peri_spec_id,
+ { "Type", "ambit.log_sample.spec.type", FT_UINT16, BASE_DEC, VALS(log_samples_spec_type_vals), 0x0,NULL, HFILL } },
+ { &hf_ambit_log_sample_peri_spec_offset,
+ { "Offset", "ambit.log_sample.spec.offset", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_sample_peri_spec_length,
+ { "Length", "ambit.log_sample.spec.length", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_sample_periodic_distance,
+ { "Distance", "ambit.log_sample.periodic.distance", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_sample_periodic_speed,
+ { "Speed", "ambit.log_sample.periodic.speed", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_sample_periodic_hr,
+ { "HR", "ambit.log_sample.periodic.hr", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_sample_periodic_time,
+ { "Time", "ambit.log_sample.periodic.time", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_sample_periodic_altitude,
+ { "Altitude", "ambit.log_sample.periodic.altitude", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_sample_periodic_energy,
+ { "Energy consumption", "ambit.log_sample.periodic.energy", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_sample_periodic_temp,
+ { "Temperature", "ambit.log_sample.periodic.temp", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_sample_periodic_preassure,
+ { "Preassure", "ambit.log_sample.periodic.preassure", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_sample_periodic_vert_speed,
+ { "Vertical speed", "ambit.log_sample.periodic.vert_speed", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+
+ { &hf_ambit_log_other_time_offset,
+ { "Time offset (from last periodic sample)", "ambit.log_sample.other.time", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_other_type,
+ { "Other log type", "ambit.log_sample.other.type", FT_UINT8, BASE_HEX, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_activity_type,
+ { "Activity type", "ambit.log_sample.activity.type", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_activity_custom_mode_id,
+ { "Custom mode ID", "ambit.log_sample.activity.custom_mode_id", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_time_event_type,
+ { "Time event type", "ambit.log_sample.time_event.type", FT_UINT8, BASE_HEX, VALS(log_samples_time_event_type_vals), 0x0,NULL, HFILL } },
+ { &hf_ambit_log_time_event_date,
+ { "Date", "ambit.log_sample.time_event.date", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_time_event_time,
+ { "Time", "ambit.log_sample.time_event.time", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_time_event_duration,
+ { "Duration (1/10 s)", "ambit.log_sample.time_event.duration", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_time_event_distance,
+ { "Distance (m)", "ambit.log_sample.time_event.distance", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+
+ { &hf_ambit_log_gps_base_navtype,
+ { "NavType", "ambit.log_sample.gps_base.navtype", FT_UINT16, BASE_HEX, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_gps_base_date,
+ { "Date (UTC)", "ambit.log_sample.gps_base.date", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_gps_base_time,
+ { "Time (UTC)", "ambit.log_sample.gps_base.time", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_gps_base_latitude,
+ { "Latitude", "ambit.log_sample.gps_base.latitude", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_gps_base_longitude,
+ { "Longitude", "ambit.log_sample.gps_base.longitude", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_gps_base_altitude,
+ { "Altitude (1/100 m)", "ambit.log_sample.gps_base.altitude", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_gps_base_speed,
+ { "Speed", "ambit.log_sample.gps_base.speed", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_gps_base_heading,
+ { "Direction (1/100 degree)", "ambit.log_sample.gps_base.direction", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_gps_base_ehpe,
+ { "EHPE", "ambit.log_sample.gps_base.ehpe", FT_UINT32, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_gps_base_satelite_no,
+ { "No of satellites", "ambit.log_sample.gps_base.satellite_no", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_gps_base_hdop,
+ { "HDOP (1/5)", "ambit.log_sample.gps_base.hdop", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_gps_base_sv,
+ { "SV", "ambit.log_sample.gps_base.sv", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_gps_base_state,
+ { "State", "ambit.log_sample.gps_base.state", FT_UINT8, BASE_HEX, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_gps_base_snr,
+ { "SNR", "ambit.log_sample.gps_base.snr", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+
+ { &hf_ambit_log_gps_small_time,
+ { "Time (only seconds, ms)", "ambit.log_sample.gps_small.time", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_gps_small_latitude,
+ { "Latitude (offset from gps-base)", "ambit.log_sample.gps_small.latitude", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_gps_small_longitude,
+ { "Longitude (offset from gps-base)", "ambit.log_sample.gps_small.longitude", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_gps_small_ehpe,
+ { "EHPE", "ambit.log_sample.gps_small.ehpe", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_gps_small_satelite_no,
+ { "No of satellites", "ambit.log_sample.gps_small.satellite_no", FT_UINT8, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+
+ { &hf_ambit_log_gps_tiny_time,
+ { "Time (only seconds, s)", "ambit.log_sample.gps_tiny.time", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_gps_tiny_latitude,
+ { "Latitude (offset from gps-base/gps-small)", "ambit.log_sample.gps_tiny.latitude", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_gps_tiny_longitude,
+ { "Longitude (offset from gps-base/gps-small)", "ambit.log_sample.gps_tiny.longitude", FT_STRING, BASE_NONE, NULL, 0x0,NULL, HFILL } },
+
+ { &hf_ambit_log_distance_source_type,
+ { "Type", "ambit.log_sample.distance_source.type", FT_UINT8, BASE_HEX, VALS(log_samples_distance_source_type_vals), 0x0,NULL, HFILL } },
+
+ { &hf_ambit_log_altitude_source_type,
+ { "Type", "ambit.log_sample.altitude_source.type", FT_UINT8, BASE_HEX, VALS(log_samples_altitude_source_type_vals), 0x0,NULL, HFILL } },
+ { &hf_ambit_log_altitude_source_altitude_offset,
+ { "Altitude offset", "ambit.log_sample.altitude_source.alt_offset", FT_INT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ { &hf_ambit_log_altitude_source_preassure_offset,
+ { "Preassure", "ambit.log_sample.altitude_source.preas_offset", FT_INT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+
+ { &hf_ambit_log_ibi,
+ { "IBI entry", "ambit.log_sample.ibi", FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL } },
+ };
+
+ static gint *ett[] = {
+ &ett_ambit,
+ &ett_ambit_data,
+ &ett_ambit_log_data,
+ &ett_ambit_log_samples,
+ &ett_ambit_log_sample,
+ };
+
+ proto_ambit = proto_register_protocol (
+ "Suunto Ambit USB Protocol",
+ "Ambit",
+ "ambit"
+ );
+
+ proto_register_field_array(proto_ambit, hf, array_length(hf));
+ proto_register_subtree_array(ett, array_length(ett));
+ //register_dissector("ambit", dissect_ambit, proto_ambit);
+}
+
+void
+proto_reg_handoff_ambit(void)
+{
+ static dissector_handle_t ambit_handle;
+
+ //ambit_handle = find_dissector("ambit");
+ ambit_handle = new_create_dissector_handle(dissect_ambit, proto_ambit);
+ dissector_add_uint("usb.interrupt", IF_CLASS_UNKNOWN, ambit_handle);
+ dissector_add_uint("usb.interrupt", IF_CLASS_HID, ambit_handle);
+}
diff --git a/wireshark_dissector/cmake/COPYING-CMAKE-SCRIPTS b/wireshark_dissector/cmake/COPYING-CMAKE-SCRIPTS
new file mode 100644
index 0000000..280ed6c
--- /dev/null
+++ b/wireshark_dissector/cmake/COPYING-CMAKE-SCRIPTS
@@ -0,0 +1,27 @@
+Copyright notice for the files copied from
+http://www.opensync.org/browser/branches/3rd-party-cmake-modules/modules
+
+$Id: COPYING-CMAKE-SCRIPTS 34248 2010-09-25 15:38:12Z jmayer $
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+1. Redistributions of source code must retain the copyright
+ notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+3. The name of the author may not be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/wireshark_dissector/cmake/FindGLIB2.cmake b/wireshark_dissector/cmake/FindGLIB2.cmake
new file mode 100644
index 0000000..ae7badd
--- /dev/null
+++ b/wireshark_dissector/cmake/FindGLIB2.cmake
@@ -0,0 +1,238 @@
+#
+# $Id: FindGLIB2.cmake 34248 2010-09-25 15:38:12Z jmayer $
+#
+# - Try to find GLib2
+# Once done this will define
+#
+# GLIB2_FOUND - system has GLib2
+# GLIB2_INCLUDE_DIRS - the GLib2 include directory
+# GLIB2_LIBRARIES - Link these to use GLib2
+#
+# HAVE_GLIB_GREGEX_H glib has gregex.h header and
+# supports g_regex_match_simple
+#
+# Copyright (c) 2006 Andreas Schneider <mail at cynapses.org>
+# Copyright (c) 2006 Philippe Bernery <philippe.bernery at gmail.com>
+# Copyright (c) 2007 Daniel Gollub <gollub at b1-systems.de>
+# Copyright (c) 2007 Alban Browaeys <prahal at yahoo.com>
+# Copyright (c) 2008 Michael Bell <michael.bell at web.de>
+# Copyright (c) 2008-2009 Bjoern Ricks <bjoern.ricks at googlemail.com>
+#
+# Redistribution and use is allowed according to the terms of the New
+# BSD license.
+# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
+#
+
+
+IF (GLIB2_LIBRARIES AND GLIB2_INCLUDE_DIRS )
+ # in cache already
+ SET(GLIB2_FOUND TRUE)
+ELSE (GLIB2_LIBRARIES AND GLIB2_INCLUDE_DIRS )
+
+ INCLUDE(FindPkgConfig)
+
+ ## Glib
+ IF ( GLIB2_FIND_REQUIRED )
+ SET( _pkgconfig_REQUIRED "REQUIRED" )
+ ELSE ( GLIB2_FIND_REQUIRED )
+ SET( _pkgconfig_REQUIRED "" )
+ ENDIF ( GLIB2_FIND_REQUIRED )
+
+ IF ( GLIB2_MIN_VERSION )
+ PKG_SEARCH_MODULE( GLIB2 ${_pkgconfig_REQUIRED} glib-2.0>=${GLIB2_MIN_VERSION} )
+ ELSE ( GLIB2_MIN_VERSION )
+ PKG_SEARCH_MODULE( GLIB2 ${_pkgconfig_REQUIRED} glib-2.0 )
+ ENDIF ( GLIB2_MIN_VERSION )
+ IF ( PKG_CONFIG_FOUND )
+ IF ( GLIB2_FOUND )
+ SET ( GLIB2_CORE_FOUND TRUE )
+ ELSE ( GLIB2_FOUND )
+ SET ( GLIB2_CORE_FOUND FALSE )
+ ENDIF ( GLIB2_FOUND )
+ ENDIF ( PKG_CONFIG_FOUND )
+
+ # Look for glib2 include dir and libraries w/o pkgconfig
+ IF ( NOT GLIB2_FOUND AND NOT PKG_CONFIG_FOUND )
+ FIND_PATH(
+ _glibconfig_include_DIR
+ NAMES
+ glibconfig.h
+ PATHS
+ /opt/gnome/lib64
+ /opt/gnome/lib
+ /opt/lib/
+ /opt/local/lib
+ /sw/lib/
+ /usr/lib64
+ /usr/lib
+ /usr/local/include
+ ${CMAKE_LIBRARY_PATH}
+ PATH_SUFFIXES
+ glib-2.0/include
+ )
+
+ FIND_PATH(
+ _glib2_include_DIR
+ NAMES
+ glib.h
+ PATHS
+ /opt/gnome/include
+ /opt/local/include
+ /sw/include
+ /usr/include
+ /usr/local/include
+ PATH_SUFFIXES
+ glib-2.0
+ )
+
+ #MESSAGE(STATUS "Glib headers: ${_glib2_include_DIR}")
+
+ FIND_LIBRARY(
+ _glib2_link_DIR
+ NAMES
+ glib-2.0
+ glib
+ PATHS
+ /opt/gnome/lib
+ /opt/local/lib
+ /sw/lib
+ /usr/lib
+ /usr/local/lib
+ )
+ IF ( _glib2_include_DIR AND _glib2_link_DIR )
+ SET ( _glib2_FOUND TRUE )
+ ENDIF ( _glib2_include_DIR AND _glib2_link_DIR )
+
+
+ IF ( _glib2_FOUND )
+ SET ( GLIB2_INCLUDE_DIRS ${_glib2_include_DIR} ${_glibconfig_include_DIR} )
+ SET ( GLIB2_LIBRARIES ${_glib2_link_DIR} )
+ SET ( GLIB2_CORE_FOUND TRUE )
+ ELSE ( _glib2_FOUND )
+ SET ( GLIB2_CORE_FOUND FALSE )
+ ENDIF ( _glib2_FOUND )
+
+ # Handle dependencies
+ # libintl
+ IF ( NOT LIBINTL_FOUND )
+ FIND_PATH(LIBINTL_INCLUDE_DIR
+ NAMES
+ libintl.h
+ PATHS
+ /opt/gnome/include
+ /opt/local/include
+ /sw/include
+ /usr/include
+ /usr/local/include
+ )
+
+ FIND_LIBRARY(LIBINTL_LIBRARY
+ NAMES
+ intl
+ PATHS
+ /opt/gnome/lib
+ /opt/local/lib
+ /sw/lib
+ /usr/local/lib
+ /usr/lib
+ )
+
+ IF (LIBINTL_LIBRARY AND LIBINTL_INCLUDE_DIR)
+ SET (LIBINTL_FOUND TRUE)
+ ENDIF (LIBINTL_LIBRARY AND LIBINTL_INCLUDE_DIR)
+ ENDIF ( NOT LIBINTL_FOUND )
+
+ # libiconv
+ IF ( NOT LIBICONV_FOUND )
+ FIND_PATH(LIBICONV_INCLUDE_DIR
+ NAMES
+ iconv.h
+ PATHS
+ /opt/gnome/include
+ /opt/local/include
+ /opt/local/include
+ /sw/include
+ /sw/include
+ /usr/local/include
+ /usr/include
+ PATH_SUFFIXES
+ glib-2.0
+ )
+
+ FIND_LIBRARY(LIBICONV_LIBRARY
+ NAMES
+ iconv
+ PATHS
+ /opt/gnome/lib
+ /opt/local/lib
+ /sw/lib
+ /usr/lib
+ /usr/local/lib
+ )
+
+ IF (LIBICONV_LIBRARY AND LIBICONV_INCLUDE_DIR)
+ SET (LIBICONV_FOUND TRUE)
+ ENDIF (LIBICONV_LIBRARY AND LIBICONV_INCLUDE_DIR)
+ ENDIF ( NOT LIBICONV_FOUND )
+
+ IF (LIBINTL_FOUND)
+ SET (GLIB2_LIBRARIES ${GLIB2_LIBRARIES} ${LIBINTL_LIBRARY})
+ SET (GLIB2_INCLUDE_DIRS ${GLIB2_INCLUDE_DIRS} ${LIBINTL_INCLUDE_DIR})
+ ENDIF (LIBINTL_FOUND)
+
+ IF (LIBICONV_FOUND)
+ SET (GLIB2_LIBRARIES ${GLIB2_LIBRARIES} ${LIBICONV_LIBRARY})
+ SET (GLIB2_INCLUDE_DIRS ${GLIB2_INCLUDE_DIRS} ${LIBICONV_INCLUDE_DIR})
+ ENDIF (LIBICONV_FOUND)
+
+ ENDIF ( NOT GLIB2_FOUND AND NOT PKG_CONFIG_FOUND )
+ ##
+
+ IF (GLIB2_CORE_FOUND AND GLIB2_INCLUDE_DIRS AND GLIB2_LIBRARIES)
+ SET (GLIB2_FOUND TRUE)
+ ENDIF (GLIB2_CORE_FOUND AND GLIB2_INCLUDE_DIRS AND GLIB2_LIBRARIES)
+
+ IF (GLIB2_FOUND)
+ IF (NOT GLIB2_FIND_QUIETLY)
+ MESSAGE (STATUS "Found GLib2: ${GLIB2_LIBRARIES} ${GLIB2_INCLUDE_DIRS}")
+ ENDIF (NOT GLIB2_FIND_QUIETLY)
+ ELSE (GLIB2_FOUND)
+ IF (GLIB2_FIND_REQUIRED)
+ MESSAGE (SEND_ERROR "Could not find GLib2")
+ ENDIF (GLIB2_FIND_REQUIRED)
+ ENDIF (GLIB2_FOUND)
+
+ # show the GLIB2_INCLUDE_DIRS and GLIB2_LIBRARIES variables only in the advanced view
+ MARK_AS_ADVANCED(GLIB2_INCLUDE_DIRS GLIB2_LIBRARIES)
+ MARK_AS_ADVANCED(LIBICONV_INCLUDE_DIR LIBICONV_LIBRARY)
+ MARK_AS_ADVANCED(LIBINTL_INCLUDE_DIR LIBINTL_LIBRARY)
+
+ENDIF (GLIB2_LIBRARIES AND GLIB2_INCLUDE_DIRS)
+
+IF ( WIN32 )
+ # include libiconv for win32
+ IF ( NOT LIBICONV_FOUND )
+ FIND_PATH(LIBICONV_INCLUDE_DIR iconv.h PATH_SUFFIXES glib-2.0)
+
+ FIND_LIBRARY(LIBICONV_LIBRARY NAMES iconv)
+
+ IF (LIBICONV_LIBRARY AND LIBICONV_INCLUDE_DIR)
+ SET (LIBICONV_FOUND TRUE)
+ ENDIF (LIBICONV_LIBRARY AND LIBICONV_INCLUDE_DIR)
+ ENDIF ( NOT LIBICONV_FOUND )
+ IF (LIBICONV_FOUND)
+ SET (GLIB2_LIBRARIES ${GLIB2_LIBRARIES} ${LIBICONV_LIBRARY})
+ SET (GLIB2_INCLUDE_DIRS ${GLIB2_INCLUDE_DIRS} ${LIBICONV_INCLUDE_DIR})
+ ENDIF (LIBICONV_FOUND)
+ENDIF ( WIN32 )
+
+IF ( GLIB2_FOUND )
+ # Check if system has a newer version of glib
+ # which supports g_regex_match_simple
+ INCLUDE( CheckIncludeFiles )
+ SET( CMAKE_REQUIRED_INCLUDES ${GLIB2_INCLUDE_DIRS} )
+ CHECK_INCLUDE_FILES ( glib/gregex.h HAVE_GLIB_GREGEX_H )
+ CHECK_INCLUDE_FILES ( glib/gchecksum.h HAVE_GLIB_GCHECKSUM_H )
+ # Reset CMAKE_REQUIRED_INCLUDES
+ SET( CMAKE_REQUIRED_INCLUDES "" )
+ENDIF( GLIB2_FOUND )
diff --git a/wireshark_dissector/cmake/FindWireshark.cmake b/wireshark_dissector/cmake/FindWireshark.cmake
new file mode 100644
index 0000000..2cfae6e
--- /dev/null
+++ b/wireshark_dissector/cmake/FindWireshark.cmake
@@ -0,0 +1,28 @@
+#
+# Try to find the wireshark library and its includes
+#
+# This snippet sets the following variables:
+# WIRESHARK_FOUND True if wireshark library got found
+# WIRESHARK_INCLUDE_DIRS Location of the wireshark headers
+# WIRESHARK_LIBRARIES List of libraries to use wireshark
+#
+# Copyright (c) 2011 Reinhold Kainhofer <reinhold at kainhofer.com>
+#
+# Redistribution and use is allowed according to the terms of the New
+# BSD license.
+# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
+#
+
+# wireshark does not install its library with pkg-config information,
+# so we need to manually find the libraries and headers
+
+FIND_PATH( WIRESHARK_INCLUDE_DIRS epan/column_info.h PATH_SUFFIXES wireshark )
+FIND_LIBRARY( WIRESHARK_LIBRARIES wireshark PATH_SUFFIXES wireshark )
+
+# Report results
+IF ( WIRESHARK_LIBRARIES AND WIRESHARK_INCLUDE_DIRS )
+ SET( WIRESHARK_FOUND 1 )
+ELSE ( WIRESHARK_LIBRARIES AND WIRESHARK_INCLUDE_DIRS )
+ MESSAGE( SEND_ERROR "Could NOT find the wireshark library and headers" )
+ENDIF ( WIRESHARK_LIBRARIES AND WIRESHARK_INCLUDE_DIRS )
+
diff --git a/wireshark_dissector/cmake/UseMakeDissectorReg.cmake b/wireshark_dissector/cmake/UseMakeDissectorReg.cmake
new file mode 100644
index 0000000..e7e1a73
--- /dev/null
+++ b/wireshark_dissector/cmake/UseMakeDissectorReg.cmake
@@ -0,0 +1,33 @@
+#
+# $Id: UseMakeDissectorReg.cmake 33616 2010-07-22 12:18:36Z stig $
+#
+MACRO(REGISTER_DISSECTOR_FILES _outputfile _registertype )
+ # FIXME: Only the Python stuff has been implemented
+ # Make this into a MACRO, to avoid duplication with plugins/.../
+ #register.c: $(plugin_src) $(ALL_DISSECTORS_SRC) $(top_srcdir)/tools/make-dissector-reg \
+ # $(top_srcdir)/tools/make-dissector-reg.py
+ # @if test -n "$(PYTHON)"; then \
+ # echo Making register.c with python ; \
+ # $(PYTHON) $(top_srcdir)/tools/make-dissector-reg.py $(srcdir) \
+ # dissectors $(ALL_DISSECTORS_SRC) ; \
+ # else \
+ # echo Making register.c with shell script ; \
+ # $(top_srcdir)/tools/make-dissector-reg $(srcdir) \
+ # dissectors $(plugin_src) $(ALL_DISSECTORS_SRC) ; \
+ # fi
+ set( _sources ${ARGN} )
+ ADD_CUSTOM_COMMAND(
+ OUTPUT
+ ${_outputfile}
+ COMMAND ${PYTHON_EXECUTABLE}
+ ${CMAKE_SOURCE_DIR}/tools/make-dissector-reg.py
+ ${CMAKE_CURRENT_SOURCE_DIR}
+ ${_registertype}
+ ${_sources}
+ DEPENDS
+ ${_sources}
+ ${CMAKE_SOURCE_DIR}/tools/make-dissector-reg
+ ${CMAKE_SOURCE_DIR}/tools/make-dissector-reg.py
+ )
+ENDMACRO(REGISTER_DISSECTOR_FILES)
+
diff --git a/wireshark_dissector/moduleinfo.h b/wireshark_dissector/moduleinfo.h
new file mode 100644
index 0000000..3bc54c2
--- /dev/null
+++ b/wireshark_dissector/moduleinfo.h
@@ -0,0 +1,17 @@
+/* Included *after* config.h, in order to re-define these macros */
+
+#ifdef PACKAGE
+#undef PACKAGE
+#endif
+
+/* Name of package */
+#define PACKAGE "ambit-usb"
+
+
+#ifdef VERSION
+#undef VERSION
+#endif
+
+/* Version number of package */
+#define VERSION "0.0.1"
+
diff --git a/wireshark_dissector/tools/make-dissector-reg b/wireshark_dissector/tools/make-dissector-reg
new file mode 100755
index 0000000..d2efa7c
--- /dev/null
+++ b/wireshark_dissector/tools/make-dissector-reg
@@ -0,0 +1,186 @@
+#! /bin/sh
+
+#
+# $Id: make-dissector-reg 21716 2007-05-07 17:55:42Z gal $
+#
+
+#
+# The first argument is the directory in which the source files live.
+#
+srcdir="$1"
+shift
+
+#
+# The second argument is either "plugin" or "dissectors"; if it's
+# "plugin", we build a plugin.c for a plugin, and if it's
+# "dissectors", we build a register.c for libwireshark.
+#
+registertype="$1"
+shift
+if [ "$registertype" = plugin ]
+then
+ outfile="plugin.c"
+elif [ "$registertype" = dissectors ]
+then
+ outfile="register.c"
+else
+ echo "Unknown output type '$registertype'" 1>&2
+ exit 1
+fi
+
+#
+# All subsequent arguments are the files to scan.
+#
+rm -f ${outfile}-tmp
+echo '/* Do not modify this file. */' >${outfile}-tmp
+echo '/* It is created automatically by the Makefile. */'>>${outfile}-tmp
+if [ "$registertype" = plugin ]
+then
+ cat <<"EOF" >>${outfile}-tmp
+#ifdef HAVE_CONFIG_H
+# include "config.h"
+#endif
+
+#include <gmodule.h>
+
+#include "moduleinfo.h"
+
+#ifndef ENABLE_STATIC
+G_MODULE_EXPORT const gchar version[] = VERSION;
+
+/* Start the functions we need for the plugin stuff */
+
+G_MODULE_EXPORT void
+plugin_register (void)
+{
+EOF
+#
+# Build code to call all the protocol registration routines.
+#
+for f in "$@"
+do
+ if [ -f $f ]
+ then
+ srcfile=$f
+ else
+ srcfile=$srcdir/$f
+ fi
+ grep '^proto_register_[a-z_0-9A-Z]* *(' $srcfile 2>/dev/null | grep -v ';'
+done | sed -e 's/^.*://' -e 's/^\([a-z_0-9A-Z]*\).*/ {extern void \1 (void); \1 ();}/' >>${outfile}-tmp
+for f in "$@"
+do
+ if [ -f $f ]
+ then
+ srcfile=$f
+ else
+ srcfile=$srcdir/$f
+ fi
+ grep '^void proto_register_[a-z_0-9A-Z]* *(' $srcfile 2>/dev/null | grep -v ';'
+done | sed -e 's/^.*://' -e 's/^void \([a-z_0-9A-Z]*\).*/ {extern void \1 (void); \1 ();}/' >>${outfile}-tmp
+else
+ cat <<"EOF" >>${outfile}-tmp
+#include "register.h"
+void
+register_all_protocols(register_cb cb, gpointer client_data)
+{
+EOF
+#
+# Build code to call all the protocol registration routines.
+#
+for f in "$@"
+do
+ if [ -f $f ]
+ then
+ srcfile=$f
+ else
+ srcfile=$srcdir/$f
+ fi
+ grep '^proto_register_[a-z_0-9A-Z]* *(' $srcfile 2>/dev/null | grep -v ';'
+done | sed -e 's/^.*://' -e 's/^\([a-z_0-9A-Z]*\).*/ {extern void \1 (void); if(cb) (*cb)(RA_REGISTER, \"\1\", client_data); \1 ();}/' >>${outfile}-tmp
+for f in "$@"
+do
+ if [ -f $f ]
+ then
+ srcfile=$f
+ else
+ srcfile=$srcdir/$f
+ fi
+ grep '^void proto_register_[a-z_0-9A-Z]* *(' $srcfile 2>/dev/null | grep -v ';'
+done | sed -e 's/^.*://' -e 's/^void \([a-z_0-9A-Z]*\).*/ {extern void \1 (void); if(cb) (*cb)(RA_REGISTER, \"\1\", client_data); \1 ();}/' >>${outfile}-tmp
+
+fi
+echo '}' >>${outfile}-tmp
+
+
+#
+# Build code to call all the protocol handoff registration routines.
+#
+if [ "$registertype" = plugin ]
+then
+ cat <<"EOF" >>${outfile}-tmp
+G_MODULE_EXPORT void
+plugin_reg_handoff(void)
+{
+EOF
+for f in "$@"
+do
+ if [ -f $f ]
+ then
+ srcfile=$f
+ else
+ srcfile=$srcdir/$f
+ fi
+ grep '^proto_reg_handoff_[a-z_0-9A-Z]* *(' $srcfile 2>/dev/null | grep -v ';'
+done | sed -e 's/^.*://' -e 's/^\([a-z_0-9A-Z]*\).*/ {extern void \1 (void); \1 ();}/' >>${outfile}-tmp
+for f in "$@"
+do
+ if [ -f $f ]
+ then
+ srcfile=$f
+ else
+ srcfile=$srcdir/$f
+ fi
+ grep '^void proto_reg_handoff_[a-z_0-9A-Z]* *(' $srcfile 2>/dev/null | grep -v ';'
+done | sed -e 's/^.*://' -e 's/^void \([a-z_0-9A-Z]*\).*/ {extern void \1 (void); \1 ();}/' >>${outfile}-tmp
+else
+ cat <<"EOF" >>${outfile}-tmp
+void
+register_all_protocol_handoffs(register_cb cb, gpointer client_data)
+{
+EOF
+for f in "$@"
+do
+ if [ -f $f ]
+ then
+ srcfile=$f
+ else
+ srcfile=$srcdir/$f
+ fi
+ grep '^proto_reg_handoff_[a-z_0-9A-Z]* *(' $srcfile 2>/dev/null | grep -v ';'
+done | sed -e 's/^.*://' -e 's/^\([a-z_0-9A-Z]*\).*/ {extern void \1 (void); if(cb) (*cb)(RA_HANDOFF, \"\1\", client_data); \1 ();}/' >>${outfile}-tmp
+for f in "$@"
+do
+ if [ -f $f ]
+ then
+ srcfile=$f
+ else
+ srcfile=$srcdir/$f
+ fi
+ grep '^void proto_reg_handoff_[a-z_0-9A-Z]* *(' $srcfile 2>/dev/null | grep -v ';'
+done | sed -e 's/^.*://' -e 's/^void \([a-z_0-9A-Z]*\).*/ {extern void \1 (void); if(cb) (*cb)(RA_HANDOFF, \"\1\", client_data); \1 ();}/' >>${outfile}-tmp
+fi
+echo '}' >>${outfile}-tmp
+if [ "$registertype" = plugin ]
+then
+ echo '#endif' >>${outfile}-tmp
+else
+ cat <<"EOF" >>${outfile}-tmp
+gulong register_count(void)
+{
+EOF
+ proto_regs=`grep RA_REGISTER ${outfile}-tmp | wc -l`
+ handoff_regs=`grep RA_HANDOFF ${outfile}-tmp | wc -l`
+ echo " return $proto_regs + $handoff_regs;" >>${outfile}-tmp
+ echo '}' >>${outfile}-tmp
+fi
+mv ${outfile}-tmp ${outfile}
diff --git a/wireshark_dissector/tools/make-dissector-reg.py b/wireshark_dissector/tools/make-dissector-reg.py
new file mode 100755
index 0000000..4497290
--- /dev/null
+++ b/wireshark_dissector/tools/make-dissector-reg.py
@@ -0,0 +1,305 @@
+#!/usr/bin/env python
+#
+# Looks for registration routines in the protocol dissectors,
+# and assembles C code to call all the routines.
+#
+# This is a Python version of the make-reg-dotc shell script.
+# Running the shell script on Win32 is very very slow because of
+# all the process-launching that goes on --- multiple greps and
+# seds for each input file. I wrote this python version so that
+# less processes would have to be started.
+#
+# $Id: make-dissector-reg.py 30447 2009-10-09 20:47:18Z krj $
+
+import os
+import sys
+import re
+import pickle
+from stat import *
+
+VERSION_KEY = '_VERSION'
+CUR_VERSION = '$Id: make-dissector-reg.py 30447 2009-10-09 20:47:18Z krj $'
+
+#
+# The first argument is the directory in which the source files live.
+#
+srcdir = sys.argv[1]
+
+#
+# The second argument is either "plugin" or "dissectors"; if it's
+# "plugin", we build a plugin.c for a plugin, and if it's
+# "dissectors", we build a register.c for libwireshark.
+#
+registertype = sys.argv[2]
+if registertype == "plugin" or registertype == "plugin_wtap":
+ tmp_filename = "plugin.c-tmp"
+ final_filename = "plugin.c"
+ cache_filename = None
+ preamble = """\
+/*
+ * Do not modify this file.
+ *
+ * It is created automatically by Makefile or Makefile.nmake.
+ */
+"""
+elif registertype == "dissectors":
+ tmp_filename = "register.c-tmp"
+ final_filename = "register.c"
+ cache_filename = "register-cache.pkl"
+ preamble = """\
+/*
+ * Do not modify this file.
+ *
+ * It is created automatically by the "register.c" target in
+ * epan/dissectors/Makefile or Makefile.nmake using information in
+ * epan/dissectors/register-cache.pkl.
+ *
+ * You can force this file to be regenerated completely by deleting
+ * it along with epan/dissectors/register-cache.pkl.
+ */
+"""
+else:
+ print "Unknown output type '%s'" % registertype
+ sys.exit(1)
+
+
+#
+# All subsequent arguments are the files to scan.
+#
+files = sys.argv[3:]
+
+# Create the proper list of filenames
+filenames = []
+for file in files:
+ if os.path.isfile(file):
+ filenames.append(file)
+ else:
+ filenames.append(os.path.join(srcdir, file))
+
+if len(filenames) < 1:
+ print "No files found"
+ sys.exit(1)
+
+
+# Look through all files, applying the regex to each line.
+# If the pattern matches, save the "symbol" section to the
+# appropriate array.
+regs = {
+ 'proto_reg': [],
+ 'handoff_reg': [],
+ 'wtap_register': [],
+ }
+
+# For those that don't know Python, r"" indicates a raw string,
+# devoid of Python escapes.
+proto_regex0 = r"^(?P<symbol>proto_register_[_A-Za-z0-9]+)\s*\([^;]+$"
+proto_regex1 = r"void\s+(?P<symbol>proto_register_[_A-Za-z0-9]+)\s*\([^;]+$"
+
+handoff_regex0 = r"^(?P<symbol>proto_reg_handoff_[_A-Za-z0-9]+)\s*\([^;]+$"
+handoff_regex1 = r"void\s+(?P<symbol>proto_reg_handoff_[_A-Za-z0-9]+)\s*\([^;]+$"
+
+wtap_reg_regex0 = r"^(?P<symbol>wtap_register_[_A-Za-z0-9]+)\s*\([^;]+$"
+wtap_reg_regex1 = r"void\s+(?P<symbol>wtap_register_[_A-Za-z0-9]+)\s*\([^;]+$"
+
+# This table drives the pattern-matching and symbol-harvesting
+patterns = [
+ ( 'proto_reg', re.compile(proto_regex0) ),
+ ( 'proto_reg', re.compile(proto_regex1) ),
+ ( 'handoff_reg', re.compile(handoff_regex0) ),
+ ( 'handoff_reg', re.compile(handoff_regex1) ),
+ ( 'wtap_register', re.compile(wtap_reg_regex0) ),
+ ( 'wtap_register', re.compile(wtap_reg_regex1) ),
+ ]
+
+# Open our registration symbol cache
+cache = None
+if cache_filename:
+ try:
+ cache_file = open(cache_filename, 'rb')
+ cache = pickle.load(cache_file)
+ cache_file.close()
+ if not cache.has_key(VERSION_KEY) or cache[VERSION_KEY] != CUR_VERSION:
+ cache = {VERSION_KEY: CUR_VERSION}
+ except:
+ cache = {VERSION_KEY: CUR_VERSION}
+
+# Grep
+for filename in filenames:
+ file = open(filename)
+ cur_mtime = os.fstat(file.fileno())[ST_MTIME]
+ if cache and cache.has_key(filename):
+ cdict = cache[filename]
+ if cur_mtime == cdict['mtime']:
+# print "Pulling %s from cache" % (filename)
+ regs['proto_reg'].extend(cdict['proto_reg'])
+ regs['handoff_reg'].extend(cdict['handoff_reg'])
+ regs['wtap_register'].extend(cdict['wtap_register'])
+ file.close()
+ continue
+ # We don't have a cache entry
+ if cache is not None:
+ cache[filename] = {
+ 'mtime': cur_mtime,
+ 'proto_reg': [],
+ 'handoff_reg': [],
+ 'wtap_register': [],
+ }
+# print "Searching %s" % (filename)
+ for line in file.readlines():
+ for action in patterns:
+ regex = action[1]
+ match = regex.search(line)
+ if match:
+ symbol = match.group("symbol")
+ sym_type = action[0]
+ regs[sym_type].append(symbol)
+ if cache is not None:
+# print "Caching %s for %s: %s" % (sym_type, filename, symbol)
+ cache[filename][sym_type].append(symbol)
+ file.close()
+
+if cache is not None and cache_filename is not None:
+ cache_file = open(cache_filename, 'wb')
+ pickle.dump(cache, cache_file)
+ cache_file.close()
+
+# Make sure we actually processed something
+if len(regs['proto_reg']) < 1:
+ print "No protocol registrations found"
+ sys.exit(1)
+
+# Sort the lists to make them pretty
+regs['proto_reg'].sort()
+regs['handoff_reg'].sort()
+regs['wtap_register'].sort()
+
+reg_code = open(tmp_filename, "w")
+
+reg_code.write(preamble)
+
+# Make the routine to register all protocols
+if registertype == "plugin" or registertype == "plugin_wtap":
+ reg_code.write("""
+#ifdef HAVE_CONFIG_H
+# include "config.h"
+#endif
+
+#include <gmodule.h>
+
+#include "moduleinfo.h"
+
+#ifndef ENABLE_STATIC
+G_MODULE_EXPORT const gchar version[] = VERSION;
+
+/* Start the functions we need for the plugin stuff */
+
+G_MODULE_EXPORT void
+plugin_register (void)
+{
+""");
+else:
+ reg_code.write("""
+#include "register.h"
+void
+register_all_protocols(register_cb cb, gpointer client_data)
+{
+""");
+
+for symbol in regs['proto_reg']:
+ if registertype == "plugin" or registertype == "plugin_wtap":
+ line = " {extern void %s (void); %s ();}\n" % (symbol, symbol)
+ else:
+ line = " {extern void %s (void); if(cb) (*cb)(RA_REGISTER, \"%s\", client_data); %s ();}\n" % (symbol, symbol, symbol)
+ reg_code.write(line)
+
+reg_code.write("}\n")
+
+
+# Make the routine to register all protocol handoffs
+if registertype == "plugin" or registertype == "plugin_wtap":
+ reg_code.write("""
+G_MODULE_EXPORT void
+plugin_reg_handoff(void)
+{
+""");
+else:
+ reg_code.write("""
+void
+register_all_protocol_handoffs(register_cb cb, gpointer client_data)
+{
+""");
+
+for symbol in regs['handoff_reg']:
+ if registertype == "plugin" or registertype == "plugin_wtap":
+ line = " {extern void %s (void); %s ();}\n" % (symbol, symbol)
+ else:
+ line = " {extern void %s (void); if(cb) (*cb)(RA_HANDOFF, \"%s\", client_data); %s ();}\n" % (symbol, symbol, symbol)
+ reg_code.write(line)
+
+reg_code.write("}\n")
+
+if registertype == "plugin":
+ reg_code.write("#endif\n");
+elif registertype == "plugin_wtap":
+ reg_code.write("""
+G_MODULE_EXPORT void
+register_wtap_module(void)
+{
+""");
+
+ for symbol in regs['wtap_register']:
+ line = " {extern void %s (void); %s ();}\n" % (symbol, symbol)
+ reg_code.write(line)
+
+ reg_code.write("}\n");
+ reg_code.write("#endif\n");
+else:
+ reg_code.write("""
+static gulong proto_reg_count(void)
+{
+""");
+
+ line = " return %d;\n" % len(regs['proto_reg'])
+ reg_code.write(line)
+
+ reg_code.write("""
+}
+""");
+ reg_code.write("""
+static gulong handoff_reg_count(void)
+{
+""");
+
+ line = " return %d;\n" % len(regs['handoff_reg'])
+ reg_code.write(line)
+
+ reg_code.write("""
+}
+""");
+ reg_code.write("""
+gulong register_count(void)
+{
+""");
+
+ line = " return proto_reg_count() + handoff_reg_count();"
+ reg_code.write(line)
+
+ reg_code.write("""
+}\n
+""");
+
+
+# Close the file
+reg_code.close()
+
+# Remove the old final_file if it exists.
+try:
+ os.stat(final_filename)
+ os.remove(final_filename)
+except OSError:
+ pass
+
+# Move from tmp file to final file
+os.rename(tmp_filename, final_filename)
+
+
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-running/openambit.git
More information about the Pkg-running-devel
mailing list