Compare commits

...

No commits in common. "master" and "github/win64" have entirely different histories.

19 changed files with 952 additions and 365 deletions

2
.gitignore vendored
View File

@ -326,4 +326,4 @@ ASALocalRun/
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
.mfractor/

3
.gitmodules vendored
View File

@ -1,3 +0,0 @@
[submodule "spacenav-driver"]
path = spacenav-driver
url = https://github.com/thib8956/spacenav-driver.git

36
Makefile Normal file
View File

@ -0,0 +1,36 @@
TARGET = spnav
TARGET_LIB = libspnavhdi.so # target lib
CC = gcc
#CFLAGS = -Wall -Wextra -fPIC -pedantic -O2 # C flags for building library
CFLAGS = -Wall -Wextra -pedantic -g -DDEBUG # C flags for developpement
LDFLAGS = -Wall -Wextra -O2
LIBS = -Llib -lhidapi-libusb
RM = rm -f # rm command
.PHONY: all default
default: $(TARGET)
all: default
OBJECTS = $(patsubst %.c, %.o, $(wildcard *.c))
HEADERS = $(wildcard *.h)
%.o: %.c $(HEADERS)
$(CC) $(CFLAGS) -c $< -o $@
.PRECIOUS: $(TARGET) $(OBJECTS)
$(TARGET): $(OBJECTS)
$(CC) $(OBJECTS) -Wall -o $@ $(LIBS)
# Shared Libs
$(TARGET_LIB): $(OBJECTS)
$(CC) $(LDFLAGS) -shared -fpic -Wl,--no-undefined -o $@ $^ $(LIBS)
.PHONY: clean
clean:
-${RM} ${TARGET}
-${RM} ${TARGET_LIB} ${OBJECTS} $(SRCS:.c=.d)

View File

@ -1,40 +0,0 @@
using System;
namespace SpaceNavWrapper
{
class Program
{
static void Main(string[] args)
{
//spnavwrapper.SpaceNav.Instance.Threshold = 5;
//spnavwrapper.SpaceNav.Instance.Sensitivity = 0.1;
//for (; ; )
//{
// var ev = spnavwrapper.SpaceNav.Instance.WaitEvent(100);
// Console.WriteLine(ev);
//}
SpaceNav navDriver = new SpaceNav();
navDriver.InitDevice();
navDriver.Button += delegate (object sender, ButtonEventArgs e)
{
navDriver.Nonblocking = !navDriver.Nonblocking;
};
navDriver.Motion += OnMotion;
Console.CancelKeyPress += delegate {
navDriver.Dispose();
};
for (; ; )
{
navDriver.WaitEvent();
Console.WriteLine("AA");
}
}
private static void OnMotion(object sender, MotionEventArgs e)
{
Console.WriteLine(e);
}
}
}

View File

@ -1,3 +1,2 @@
# spnav-csharp-wrapper
Simple C# wrapper for the [HID spacenavigator driver](https://github.com/thib8956/spacenav-driver.git)
# Spacenav HDI driver
Simple driver for the spacenavigator 3d mice using HDI api

View File

@ -1,165 +0,0 @@
using System;
using System.Runtime.InteropServices;
namespace SpaceNavWrapper
{
public class SpaceNav : IDisposable
{
const string DLL_NAME = "spnavhdi";
#region Constants
private const int SPNAV_EVENT_MOTION = 1;
private const int SPNAV_EVENT_BUTTON = 2;
private const ushort SPNAV_VENDOR_ID = 0x046d;
private const ushort SPNAV_PRODUCT_ID = 0x0c627;
#endregion
public event EventHandler<MotionEventArgs> Motion;
public event EventHandler<ButtonEventArgs> Button;
private double _sensitivity = 1.0;
private int _threshold = 5;
private bool _nonblocking;
private bool isDisposed;
#region Structures
private struct SpNavEventMotion
{
public int type;
public int x, y, z;
public int rx, ry, rz;
public uint period;
public IntPtr data;
}
private struct SpNavEventButton
{
public int type;
[MarshalAs(UnmanagedType.Bool)]
public bool press;
public int bnum;
}
[StructLayout(LayoutKind.Explicit)]
private struct SpNavEvent
{
[FieldOffset(0)] public int type;
[FieldOffset(0)] public SpNavEventMotion motion;
[FieldOffset(0)] public SpNavEventButton button;
}
#endregion
#region DLL Imports
[DllImport(DLL_NAME)]
private static extern int spnav_open(ushort vendor_id, ushort product_id);
[DllImport(DLL_NAME)]
private static extern int spnav_close();
[DllImport(DLL_NAME)]
private static extern int spnav_set_nonblocking(bool nonblock);
[DllImport(DLL_NAME)]
private static extern int spnav_wait_event(ref SpNavEvent ev);
[DllImport(DLL_NAME)]
private static extern int spnav_wait_event_timeout(ref SpNavEvent ev, int timeout);
[DllImport(DLL_NAME)]
private static extern int spnav_sensitivity(double sens);
[DllImport(DLL_NAME)]
private static extern int spnav_deadzone(int threshold);
#endregion
public void InitDevice()
{
// TODO handle retcode and errors
spnav_open(SPNAV_VENDOR_ID, SPNAV_PRODUCT_ID);
}
public void WaitEvent(int millis = -1)
{
SpNavEvent sev = new SpNavEvent();
int ev_type;
if (millis == -1)
{
ev_type = spnav_wait_event(ref sev);
}
else
{
ev_type = spnav_wait_event_timeout(ref sev, (int)millis);
}
switch (ev_type)
{
case SPNAV_EVENT_BUTTON:
var e = sev.button;
Button(this, new ButtonEventArgs(e.press, e.bnum));
break;
case SPNAV_EVENT_MOTION:
var ev = sev.motion;
Motion(this, new MotionEventArgs(ev.x, ev.y, ev.z, ev.rx, ev.ry, ev.rz));
break;
default:
break;
}
}
private void CloseDevice()
{
// TODO : handle retcode and errors
spnav_close();
}
#region Properties
public double Sensitivity
{
get
{
return _sensitivity;
}
set
{
_sensitivity = value;
spnav_sensitivity(value);
}
}
public int Threshold
{
get
{
return _threshold;
}
set
{
_threshold = value;
spnav_deadzone(value);
}
}
public bool Nonblocking
{
get
{
return _nonblocking;
}
set
{
_nonblocking = value;
spnav_set_nonblocking(value);
}
}
#endregion
public void Dispose()
{
if (!isDisposed)
{
CloseDevice();
Button = null;
Motion = null;
}
isDisposed = true;
}
}
}

View File

@ -1,100 +0,0 @@
using System;
using System.Collections.Generic;
namespace SpaceNavWrapper
{
public enum SpaceNavAxis {
X, Y, Z, Rx, Ry, Rz
}
public class MotionEventArgs : EventArgs
{
public readonly Dictionary<SpaceNavAxis, int> axisValues;
public MotionEventArgs(int x, int y, int z, int rx, int ry, int rz)
{
axisValues = new Dictionary<SpaceNavAxis, int>();
axisValues[SpaceNavAxis.X] = x;
axisValues[SpaceNavAxis.Y] = y;
axisValues[SpaceNavAxis.Z] = y;
axisValues[SpaceNavAxis.Rx] = rx;
axisValues[SpaceNavAxis.Ry] = ry;
axisValues[SpaceNavAxis.Rz] = rz;
}
public int X
{
get
{
return axisValues[SpaceNavAxis.X];
}
}
public int Y
{
get
{
return axisValues[SpaceNavAxis.Y];
}
}
public int Z
{
get
{
return axisValues[SpaceNavAxis.Z];
}
}
public int Rx
{
get
{
return axisValues[SpaceNavAxis.Rx];
}
}
public int Ry
{
get
{
return axisValues[SpaceNavAxis.Ry];
}
}
public int Rz
{
get
{
return axisValues[SpaceNavAxis.Rz];
}
}
public override string ToString()
{
return string.Format("x={0} y={1} z={2} rx={3} ry={4} rz={5}", X, Y, Z, Rx, Ry, Rz);
}
public int GetAxis(SpaceNavAxis axis)
{
return axisValues[axis];
}
}
public class ButtonEventArgs : EventArgs
{
public readonly bool Pressed;
public readonly int Button;
public ButtonEventArgs(bool pressed, int button)
{
Pressed = pressed;
Button = button;
}
public override string ToString()
{
return string.Format("button={0}, pressed={1}", Button, Pressed);
}
}
}

391
hidapi.h Normal file
View File

@ -0,0 +1,391 @@
/*******************************************************
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.
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[]. Upon return, the first byte will
still contain the Report ID, and the report data will
start in data[1].
@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, or set it to zero
if your device does not use numbered reports.
@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 plus
one for the report ID (which is still in the first
byte), or -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

1
lib/libhidapi-libusb.so Symbolic link
View File

@ -0,0 +1 @@
libhidapi-libusb.so.0.0.0

BIN
lib/libhidapi-libusb.so.0.0.0 Executable file

Binary file not shown.

47
main.c Normal file
View File

@ -0,0 +1,47 @@
#include <stdio.h>
#include <stdlib.h>
#define MAX_STR 255
#define SPNAV_VENDOR_ID 0x046d
#define SPNAV_PRODUCT_ID 0xc626
#define SPNAV_3D_EXPLORER_PRODUCT_ID 0x0c627
#include <signal.h>
#include <stdbool.h>
#include "spnav.h"
static bool INTERRUPTED = false;
void sighandler(int signo) {
if (signo == SIGINT) {
INTERRUPTED = true;
}
}
int main(int argc, char const* argv[]) {
signal(SIGINT, sighandler);
spnav_event ev;
spnav_open(SPNAV_VENDOR_ID, SPNAV_3D_EXPLORER_PRODUCT_ID);
spnav_sensitivity(0.1);
spnav_deadzone(10);
spnav_set_nonblocking(true);
for (;;) {
// spnav_wait_event_timeout(&ev, 400);
spnav_wait_event(&ev);
switch (ev.type) {
case MOTION:
printf("x=%d, y=%d, z=%d ", ev.motion.x, ev.motion.y, ev.motion.z);
printf("rx=%d, ry=%d, rz=%d\n", ev.motion.rx, ev.motion.ry, ev.motion.rz);
break;
case BUTTON:
printf("bnum=%d, pressed=%d\n", ev.button.bnum, ev.button.press);
break;
}
if (INTERRUPTED) {
break;
}
}
spnav_close();
}

@ -1 +0,0 @@
Subproject commit f654a62bdb4dbe14991fa89c2af69034587f816a

48
spacenav-driver.sln Normal file
View File

@ -0,0 +1,48 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27130.2003
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "spacenav-driver", "spacenav-driver.vcxproj", "{0264ED29-8433-48C7-A045-59AC1372DB7D}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "hidapi", "..\hidapi\windows\hidapi.vcxproj", "{A107C21C-418A-4697-BB10-20C3AA60E2E4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0264ED29-8433-48C7-A045-59AC1372DB7D}.Debug|Any CPU.ActiveCfg = Debug|Win32
{0264ED29-8433-48C7-A045-59AC1372DB7D}.Debug|x64.ActiveCfg = Debug|x64
{0264ED29-8433-48C7-A045-59AC1372DB7D}.Debug|x64.Build.0 = Debug|x64
{0264ED29-8433-48C7-A045-59AC1372DB7D}.Debug|x86.ActiveCfg = Debug|Win32
{0264ED29-8433-48C7-A045-59AC1372DB7D}.Debug|x86.Build.0 = Debug|Win32
{0264ED29-8433-48C7-A045-59AC1372DB7D}.Release|Any CPU.ActiveCfg = Release|x64
{0264ED29-8433-48C7-A045-59AC1372DB7D}.Release|x64.ActiveCfg = Release|x64
{0264ED29-8433-48C7-A045-59AC1372DB7D}.Release|x64.Build.0 = Release|x64
{0264ED29-8433-48C7-A045-59AC1372DB7D}.Release|x86.ActiveCfg = Release|Win32
{0264ED29-8433-48C7-A045-59AC1372DB7D}.Release|x86.Build.0 = Release|Win32
{A107C21C-418A-4697-BB10-20C3AA60E2E4}.Debug|Any CPU.ActiveCfg = Debug|Win32
{A107C21C-418A-4697-BB10-20C3AA60E2E4}.Debug|x64.ActiveCfg = Debug|x64
{A107C21C-418A-4697-BB10-20C3AA60E2E4}.Debug|x64.Build.0 = Debug|x64
{A107C21C-418A-4697-BB10-20C3AA60E2E4}.Debug|x86.ActiveCfg = Debug|Win32
{A107C21C-418A-4697-BB10-20C3AA60E2E4}.Debug|x86.Build.0 = Debug|Win32
{A107C21C-418A-4697-BB10-20C3AA60E2E4}.Debug|x86.Deploy.0 = Debug|Win32
{A107C21C-418A-4697-BB10-20C3AA60E2E4}.Release|Any CPU.ActiveCfg = Release|Win32
{A107C21C-418A-4697-BB10-20C3AA60E2E4}.Release|x64.ActiveCfg = Release|x64
{A107C21C-418A-4697-BB10-20C3AA60E2E4}.Release|x64.Build.0 = Release|x64
{A107C21C-418A-4697-BB10-20C3AA60E2E4}.Release|x86.ActiveCfg = Release|Win32
{A107C21C-418A-4697-BB10-20C3AA60E2E4}.Release|x86.Build.0 = Release|Win32
{A107C21C-418A-4697-BB10-20C3AA60E2E4}.Release|x86.Deploy.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {486AE857-F0BF-44F3-863E-C51A5CC1A832}
EndGlobalSection
EndGlobal

130
spacenav-driver.vcxproj Normal file
View File

@ -0,0 +1,130 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{0264ED29-8433-48C7-A045-59AC1372DB7D}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<TargetExt>.exe</TargetExt>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<TargetExt>.dll</TargetExt>
<TargetName>spnavhdi</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;SPACENAVDRIVER_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
<CompileAs>CompileAsC</CompileAs>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;SPACENAVDRIVER_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<CompileAs>CompileAsC</CompileAs>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="main.c" />
<ClCompile Include="spnav.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="hidapi.h" />
<ClInclude Include="spnav.h" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\hidapi\windows\hidapi.vcxproj">
<Project>{a107c21c-418a-4697-bb10-20c3aa60e2e4}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="spnav.c">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="hidapi.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="spnav.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -1,35 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProjectGuid>{BC0B9CC5-C678-4DBF-AA73-FD98C1D6BF60}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>spnavcsharpwrapper</RootNamespace>
<AssemblyName>spnav-csharp-wrapper</AssemblyName>
<TargetFrameworkVersion>v4.7</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<Compile Include="SpaceNavEvent.cs" />
<Compile Include="Program.cs" />
<Compile Include="SpaceNav.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -1,17 +0,0 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "spnav-csharp-wrapper", "spnav-csharp-wrapper.csproj", "{BC0B9CC5-C678-4DBF-AA73-FD98C1D6BF60}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BC0B9CC5-C678-4DBF-AA73-FD98C1D6BF60}.Debug|x86.ActiveCfg = Debug|x86
{BC0B9CC5-C678-4DBF-AA73-FD98C1D6BF60}.Debug|x86.Build.0 = Debug|x86
{BC0B9CC5-C678-4DBF-AA73-FD98C1D6BF60}.Release|x86.ActiveCfg = Release|x86
{BC0B9CC5-C678-4DBF-AA73-FD98C1D6BF60}.Release|x86.Build.0 = Release|x86
EndGlobalSection
EndGlobal

204
spnav.c Normal file
View File

@ -0,0 +1,204 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "spnav.h"
#include "hidapi.h"
#ifdef DEBUG
#define DEBUG_PRINT(...) \
do { \
fprintf(stderr, __VA_ARGS__); \
} while (false)
#else
#define DEBUG_PRINT(...) \
do { \
} while (false)
#endif
#define EVENT_BUF 64
enum {
TRANSLATION = 1,
ROTATION = 2,
BTN = 3
};
static bool IS_OPEN = false;
/* Sensitivity is multiplied with every motion (1.0 normal). */
static double SPNAV_SENS = 1.0;
static int SPNAV_DEADZONE_THRESHOLD = 5;
/* HID device for SpaceNavigator mouse */
hid_device *device = NULL;
int convert_input(int first, unsigned char val) {
switch (val) {
case 0:
return first;
case 1:
return first + 255;
case 254:
return -512 + first;
case 255:
return -255 + first;
default:
return 0;
}
}
bool in_deadzone(unsigned char *data, int threshold) {
/* data[0] is the event type */
int i;
for (i = 1; i < SPNAV_NAXIS; i++) {
if (data[i] > threshold) {
return false;
}
}
DEBUG_PRINT("in_deadzone\n");
return true;
}
int read_event(hid_device *device, spnav_event *ev, int ms) {
unsigned char buf[EVENT_BUF];
int nbytes;
if (ms == -1) {
nbytes = hid_read(device, buf, sizeof(buf));
} else {
nbytes = hid_read_timeout(device, buf, sizeof(buf), ms);
}
if (nbytes < 0) {
DEBUG_PRINT("hid_read_timeout() error");
return -1;
} else if (nbytes == 0) {
ev->type = 0;
return 0;
}
ev->type = buf[0];
// Fill spnav_event struct
switch (ev->type) {
case TRANSLATION:
if (in_deadzone(buf, SPNAV_DEADZONE_THRESHOLD)) {
ev->type = 0;
return ev->type;
}
ev->motion.type = 1;
ev->motion.x = (int)(SPNAV_SENS * convert_input((buf[1] & 0x0000ff), buf[2]));
ev->motion.z = -(int)(SPNAV_SENS * convert_input((buf[3] & 0x0000ff), buf[4]));
ev->motion.y = -(int)(SPNAV_SENS * convert_input((buf[5] & 0x0000ff), buf[6]));
// DEBUG_PRINT("Translation x=%d, y=%d, z=%d\n", ev->motion.x, ev->motion.y, ev->motion.z);
break;
case ROTATION:
if (in_deadzone(buf, SPNAV_DEADZONE_THRESHOLD)) {
ev->type = 0;
return ev->type;
}
ev->motion.type = 1;
ev->motion.rx = -(int)(SPNAV_SENS * convert_input((buf[1] & 0x0000ff), buf[2]));
ev->motion.rz = -(int)(SPNAV_SENS * convert_input((buf[3] & 0x0000ff), buf[4]));
ev->motion.ry = (int)(SPNAV_SENS * convert_input((buf[5] & 0x0000ff), buf[6]));
// DEBUG_PRINT("Rotation rx=%d, ry=%d, rz=%d\n", ev->motion.rx, ev->motion.ry, ev->motion.rz);
break;
case BTN:
ev->button.type = 2;
ev->button.press = buf[1] == 0x01;
ev->button.bnum = buf[1];
//DEBUG_PRINT("Buttons: %d %d\n", /* btn 1 */buf[1] & 0x01, /* btn 2 */ buf[1] & 0x02);
break;
}
return ev->type;
}
int set_led(hid_device *dev, char state) {
const unsigned char led_data[2] = {0x04, state};
int nbytes = hid_write(dev, led_data, sizeof(led_data));
if (nbytes != sizeof(led_data)) {
DEBUG_PRINT("set_led(): hid_write() has written %d bytes (should be %ld)\n",
nbytes, sizeof(led_data));
return -1;
}
return nbytes;
}
int spnav_open(unsigned short vendor_id, unsigned short product_id) {
DEBUG_PRINT("spnav_open()\n");
/* Connexion already opened */
if (IS_OPEN) {
DEBUG_PRINT("Connexion already opened!\n");
return -1;
}
// Initialize the hidapi library
hid_init();
// Open the device using the VID, PID,
// and optionally the Serial number.
device = hid_open(vendor_id, product_id, NULL);
if (device == NULL) {
DEBUG_PRINT("hid_open() failed!");
return -1;
}
IS_OPEN = true;
set_led(device, 1);
return 0;
}
int spnav_close() {
if (!IS_OPEN) {
DEBUG_PRINT("Device is not opened!\n");
return -1;
}
set_led(device, 0);
hid_close(device);
DEBUG_PRINT("Connection to HID device closed!\n");
hid_exit();
IS_OPEN = false;
return 0;
}
int spnav_set_nonblocking(bool nonblock) {
int ret = hid_set_nonblocking(device, nonblock);
if (ret == -1) {
DEBUG_PRINT("Call to hid_set_nonblocking() failed\n");
return -1;
}
DEBUG_PRINT("Nonblocking state is now %d\n", nonblock);
return 0;
}
int spnav_wait_event(spnav_event *event) {
if (device == NULL) {
DEBUG_PRINT("spnav_wait_event(): device not connected.\n");
return -1;
}
return read_event(device, event, -1);
}
int spnav_wait_event_timeout(spnav_event *event, int milliseconds) {
if (device == NULL) {
DEBUG_PRINT("spnav_wait_event_timeout(): device not connected.\n");
return -1;
}
return read_event(device, event, milliseconds);
}
int spnav_sensitivity(double sens) {
if (sens <= 0.0) {
DEBUG_PRINT("Invalid sensitivity value %f\n", sens);
return -1;
}
SPNAV_SENS = sens;
DEBUG_PRINT("Sensitivity set to %f\n", SPNAV_SENS);
return 0;
}
int spnav_deadzone(int value) {
if (value < 0) {
DEBUG_PRINT("Invalid deadzone value %d\n", value);
return -1;
}
SPNAV_DEADZONE_THRESHOLD = value;
DEBUG_PRINT("Deadzone threshold set to %d\n", value);
return 0;
}

59
spnav.h Normal file
View File

@ -0,0 +1,59 @@
#ifndef SPNAV_H__
#define SPNAV_H__
#include <stdbool.h>
#define SPNAV_NAXIS 6
#ifdef _WIN32
#define SPNAV_API_EXPORT __declspec(dllexport)
#define SPNAV_API_CALL
#else
#define SPNAV_API_EXPORT /**< API export macro */
#define SPNAV_API_CALL /**< API call macro */
#endif
#define SPNAV_API_EXPORT_CALL SPNAV_API_EXPORT SPNAV_API_CALL /**< API export and call macro*/
enum event_type {
ANY,
MOTION,
BUTTON
};
struct event_motion {
int type;
int x, y, z;
int rx, ry, rz;
unsigned int period;
int *data;
};
struct event_button {
int type;
bool press;
int bnum;
};
typedef union spnav_event {
int type;
struct event_motion motion;
struct event_button button;
} spnav_event;
#ifdef __cplusplus
extern "C" {
#endif
int SPNAV_API_EXPORT_CALL spnav_open(unsigned short vendor_id, unsigned short product_id);
int SPNAV_API_EXPORT_CALL spnav_close(void);
int SPNAV_API_EXPORT_CALL spnav_set_nonblocking(bool nonblock);
int SPNAV_API_EXPORT_CALL spnav_wait_event(spnav_event *event);
int SPNAV_API_EXPORT_CALL spnav_wait_event_timeout(spnav_event *event, int timeout);
int SPNAV_API_EXPORT_CALL spnav_sensitivity(double sens);
int SPNAV_API_EXPORT_CALL spnav_deadzone(int value);
#ifdef __cplusplus
}
#endif
#endif /* SPNAV_H__ */