Compare commits

...

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

16 changed files with 692 additions and 742 deletions

330
.gitignore vendored
View File

@ -1,3 +1,329 @@
.vscode/*
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
*.o
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/

3
.gitmodules vendored Normal file
View File

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

View File

@ -1,36 +0,0 @@
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)

40
Program.cs Normal file
View File

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

165
SpaceNav.cs Normal file
View File

@ -0,0 +1,165 @@
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;
}
}
}

100
SpaceNavEvent.cs Normal file
View File

@ -0,0 +1,100 @@
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
View File

@ -1,391 +0,0 @@
/*******************************************************
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

View File

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

Binary file not shown.

47
main.c
View File

@ -1,47 +0,0 @@
#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
spacenav-driver Submodule

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

View File

@ -0,0 +1,35 @@
<?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>

17
spnav-csharp-wrapper.sln Normal file
View File

@ -0,0 +1,17 @@
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
View File

@ -1,204 +0,0 @@
#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
View File

@ -1,59 +0,0 @@
#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__ */