Intial commit with original files, docs and modified Linux source.

This commit is contained in:
2019-04-13 00:24:49 -04:00
commit 754b8ccb3a
111 changed files with 13099 additions and 0 deletions
BIN
View File
Binary file not shown.
+20
View File
@@ -0,0 +1,20 @@
@echo off
rem scaswr.bat - a drop target for config files
rem Change directory to the location of the batch script file (%0)...
cd /d "%~dp0"
rem Run scas with a default target filename...
echo Assembling %1...
scas %1 %1.scb
if errorlevel 1 goto end
rem Run scwr with that default filename...
echo:
echo Writing %1.scb...
scwr %1.scb
:end
rem Wait for a keypress so the output can be read...
echo:
pause
+38
View File
@@ -0,0 +1,38 @@
#OS = LINUX
#OS = MACOSX
#OS = WINDOWS
# To set up Ubuntu Linux to cross compile for Windows:
#
# apt-get install mingw32 mingw32-binutils mingw32-runtime
#
# Just edit the variable above for WINDOWS, then use "make" to build rawhid.exe
ifeq ($(OS), LINUX)
TARGET = $(PROG)
CC = gcc
STRIP = strip
CFLAGS = -Wall -O2 -DOS_$(OS) -std=c99
LIBS = -lusb
else ifeq ($(OS), MACOSX)
TARGET = $(PROG)
SDK = /Developer/SDKs/MacOSX10.6.sdk
ARCH = -mmacosx-version-min=10.6 -arch i386
CC = gcc
STRIP = strip
CFLAGS = -Wall -O2 -DOS_$(OS) -std=c99 -isysroot $(SDK) $(ARCH)
LIBS = $(ARCH) -Wl,-syslibroot,$(SDK) -framework IOKit -framework CoreFoundation
else ifeq ($(OS), WINDOWS)
TARGET = $(PROG).exe
CC = i586-mingw32msvc-gcc
STRIP = i586-mingw32msvc-strip
CFLAGS = -Wall -O2 -DOS_$(OS) -std=c99
LIBS = -lhid -lsetupapi
endif
OBJS += ../common/hid_$(OS).o
include ../build/Makefile_rules.inc
+44
View File
@@ -0,0 +1,44 @@
#OS = LINUX
#OS = MACOSX
#OS = WINDOWS
# To set up Ubuntu Linux to cross compile for Windows:
#
# apt-get install mingw32 mingw32-binutils mingw32-runtime
#
# Just edit the variable above for WINDOWS, then use "make" to build rawhid.exe
ifeq ($(OS), LINUX)
TARGET = $(PROG)
CC = g++
STRIP = strip
CFLAGS = -Wall -O2 -DOS_$(OS)
CXXFLAGS = $(CFLAGS)
LIBS =
else ifeq ($(OS), MACOSX)
TARGET = $(PROG)
SDK = /Developer/SDKs/MacOSX10.6.sdk
ARCH = -mmacosx-version-min=10.6 -arch i386
CC = g++
STRIP = strip
CFLAGS = -Wall -O2 -DOS_$(OS) -isysroot $(SDK) $(ARCH)
CXXFLAGS = $(CFLAGS)
LIBS = $(ARCH) -Wl,-syslibroot,$(SDK) -framework IOKit -framework CoreFoundation
else ifeq ($(OS), WINDOWS)
TARGET = $(PROG).exe
CC = i586-mingw32msvc-g++
CXX = i586-mingw32msvc-g++
STRIP = i586-mingw32msvc-strip
CFLAGS = -Wall -O2 -DOS_$(OS) -mwin32 -mconsole
CXXFLAGS = $(CFLAGS)
#LIBS = -lsetupapi
#LIBS = -lsetupapi -lstdc++ -lgcc -lmsvcrt
LIBS =
endif
#OBJS = $(OBJS)
include ../build/Makefile_rules.inc
+10
View File
@@ -0,0 +1,10 @@
DIRS = scas scdis scboot scinfo scrd scwr
all :
for d in $(DIRS); do (cd ../../$$d; $(MAKE) OS=$(OS) ); done
clean :
for d in $(DIRS); do (cd ../../$$d; $(MAKE) OS=$(OS) clean ); done
+26
View File
@@ -0,0 +1,26 @@
all: ../bin/$(TARGET)
$(PROG): $(OBJS)
$(CC) -o $(PROG) $(OBJS) $(LIBS)
$(STRIP) $(PROG)
$(PROG).exe: $(PROG)
cp $(PROG) $(PROG).exe
#$(PROG).dmg: $(PROG)
# mkdir tmp
# cp $(PROG) tmp
# hdiutil create -ov -volname sctools_$(PROG) -srcfolder tmp $(PROG).dmg
#hid.o: hid_$(OS).c rawhid.h
# $(CC) $(CFLAGS) -c -o $@ $<
clean:
rm -f $(OBJS) $(PROG) $(PROG).exe $(PROG).dmg ../bin/$(TARGET)
rm -rf tmp
../bin/$(TARGET): $(TARGET)
mkdir -p ../bin
cp $(TARGET) ../bin/$(TARGET)
+7
View File
@@ -0,0 +1,7 @@
# build all sctools for Linux
OS = LINUX
include ../Makefile_recurse.inc
+7
View File
@@ -0,0 +1,7 @@
# build all sctools for Mac OS-X
OS = MACOSX
include ../Makefile_recurse.inc
+7
View File
@@ -0,0 +1,7 @@
# build all sctools for Windows (mingw32)
OS = WINDOWS
include ../Makefile_recurse.inc
+3
View File
@@ -0,0 +1,3 @@
@echo off
if "%1" == "clean" devenv sctools.sln /clean Release
if "%1" != "clean" devenv sctools.sln /build Release
+61
View File
@@ -0,0 +1,61 @@
Microsoft Visual Studio Solution File, Format Version 8.00
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "scas", "..\..\scas\scas.vcproj", "{6BD9A7D9-B220-49FF-B527-45C04DBBDA9A}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "scdis", "..\..\scdis\scdis.vcproj", "{81871EED-13AF-42FF-BB7F-88F93647B45B}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "scboot", "..\..\scboot\scboot.vcproj", "{9ED4BD6A-E53F-4CB0-9057-3F45F9570B2B}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "scinfo", "..\..\scinfo\scinfo.vcproj", "{A243DB4C-FFAB-46C1-B68E-89E066EFF06E}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "scrd", "..\..\scrd\scrd.vcproj", "{262F101E-E54C-4DD7-A7BD-C5F07A7B0047}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "scwr", "..\..\scwr\scwr.vcproj", "{63366BE7-6C6E-43E0-A59B-16AFB7DDF369}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
Debug = Debug
Release = Release
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{6BD9A7D9-B220-49FF-B527-45C04DBBDA9A}.Debug.ActiveCfg = Debug|Win32
{6BD9A7D9-B220-49FF-B527-45C04DBBDA9A}.Debug.Build.0 = Debug|Win32
{6BD9A7D9-B220-49FF-B527-45C04DBBDA9A}.Release.ActiveCfg = Release|Win32
{6BD9A7D9-B220-49FF-B527-45C04DBBDA9A}.Release.Build.0 = Release|Win32
{81871EED-13AF-42FF-BB7F-88F93647B45B}.Debug.ActiveCfg = Debug|Win32
{81871EED-13AF-42FF-BB7F-88F93647B45B}.Debug.Build.0 = Debug|Win32
{81871EED-13AF-42FF-BB7F-88F93647B45B}.Release.ActiveCfg = Release|Win32
{81871EED-13AF-42FF-BB7F-88F93647B45B}.Release.Build.0 = Release|Win32
{9ED4BD6A-E53F-4CB0-9057-3F45F9570B2B}.Debug.ActiveCfg = Debug|Win32
{9ED4BD6A-E53F-4CB0-9057-3F45F9570B2B}.Debug.Build.0 = Debug|Win32
{9ED4BD6A-E53F-4CB0-9057-3F45F9570B2B}.Release.ActiveCfg = Release|Win32
{9ED4BD6A-E53F-4CB0-9057-3F45F9570B2B}.Release.Build.0 = Release|Win32
{A243DB4C-FFAB-46C1-B68E-89E066EFF06E}.Debug.ActiveCfg = Debug|Win32
{A243DB4C-FFAB-46C1-B68E-89E066EFF06E}.Debug.Build.0 = Debug|Win32
{A243DB4C-FFAB-46C1-B68E-89E066EFF06E}.Release.ActiveCfg = Release|Win32
{A243DB4C-FFAB-46C1-B68E-89E066EFF06E}.Release.Build.0 = Release|Win32
{262F101E-E54C-4DD7-A7BD-C5F07A7B0047}.Debug.ActiveCfg = Debug|Win32
{262F101E-E54C-4DD7-A7BD-C5F07A7B0047}.Debug.Build.0 = Debug|Win32
{262F101E-E54C-4DD7-A7BD-C5F07A7B0047}.Release.ActiveCfg = Release|Win32
{262F101E-E54C-4DD7-A7BD-C5F07A7B0047}.Release.Build.0 = Release|Win32
{63366BE7-6C6E-43E0-A59B-16AFB7DDF369}.Debug.ActiveCfg = Debug|Win32
{63366BE7-6C6E-43E0-A59B-16AFB7DDF369}.Debug.Build.0 = Debug|Win32
{63366BE7-6C6E-43E0-A59B-16AFB7DDF369}.Release.ActiveCfg = Release|Win32
{63366BE7-6C6E-43E0-A59B-16AFB7DDF369}.Release.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal
+22
View File
@@ -0,0 +1,22 @@
#ifndef __GLOBAL_H__
#define __GLOBAL_H__
#define INVALID_NUMBER -9999
struct token_t
{
const char* token;
int value;
};
#define BLOCK_NONE -1
#define BLOCK_LAYERDEF 0
#define BLOCK_REMAP 1
#define BLOCK_MACRO 2
#ifndef _MSC_VER
#define strnicmp strncasecmp
#define stricmp strcasecmp
#endif
#endif // __GLOBAL_H__
+381
View File
@@ -0,0 +1,381 @@
/* Simple Raw HID functions for Linux - for use with Teensy RawHID example
* http://www.pjrc.com/teensy/rawhid.html
* Copyright (c) 2009 PJRC.COM, LLC
*
* rawhid_open - open 1 or more devices
* rawhid_recv - receive a packet
* rawhid_send - send a packet
* rawhid_close - close a device
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above description, website URL and copyright notice and this permission
* notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Version 1.0: Initial Release
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/param.h>
#include <usb.h>
#include "rawhid.h"
// On Linux there are several options to access HID devices.
//
// libusb 0.1 - the only way that works well on all distributions
// libusb 1.0 - someday will become standard on most distributions
// hidraw driver - relatively new, not supported on many distributions (yet)
// hiddev driver - old, ubuntu, fedora, others dropping support
// usbfs - low level usb API: http://www.kernel.org/doc/htmldocs/usb.html#usbfs
//
// This code uses libusb 0.1, which is well supported on all linux distributions
// and very stable and widely used by many programs. libusb 0.1 only provides a
// simple synchronous interface, basically the same as this code needs. However,
// if you want non-blocking I/O, libusb 0.1 simply does not provide that. There
// is also no kernel-level buffering, so performance is poor.
//
// UPDATE: As of November 2011, hidraw support seems to be working well in all
// major linux distributions. Embedded and "small" distros, used on ARM boards,
// routers and embedded hardware stil seem to omit the hidraw driver.
//
// The hidraw driver is a great solution. However, it has only been supported
// by relatively recent (in 2009) kernels. Here is a quick survey of the status
// of hidraw support in various distributions as of Sept 2009:
//
// Fedora 11: works, kernel 2.6.29.4
// Mandiva 2009.1: works, kernel 2.6.29.1
// Ubuntu 9.10-alpha6: works, kernel 2.6.31
// Ubuntu 9.04: sysfs attrs chain broken (hidraw root only), 2.6.28 kernel
// openSUSE 11.1: sysfs attrs chain broken (hidraw root only), 2.6.27.7 kernel
// Debian Live, Lenny 5.0.2: sysfs attrs chain broken (hidraw root only), 2.6.26
// SimplyMEPIS 8.0.10: sysfs attrs chain broken (hidraw root only), 2.6.27
// Mint 7: sysfs attrs chain broken (hidraw root only), 2.6.28 kernel
// Gentoo 2008.0-r1: sysfs attrs chain broken (hidraw root only), 2.6.24 kernel
// Centos 5: no hidraw or hiddev devices, 2.6.18 kernel
// Slitaz 2.0: no hidraw devices (has hiddev), 2.6.25.5 kernel
// Puppy 4.3: no hidraw devices (has hiddev), 2.6.30.5 kernel
// Damn Small 4.4.10: (would not boot)
// Gentoo 10.0-test20090926: (would not boot)
// PCLinuxOS 2009.2: (would not boot)
// Slackware: (no live cd available? www.slackware-live.org dead)
#define printf(...) // comment this out for lots of info
// a list of all opened HID devices, so the caller can
// simply refer to them by number
typedef struct hid_struct hid_t;
static hid_t *first_hid = NULL;
static hid_t *last_hid = NULL;
struct hid_struct {
usb_dev_handle *usb;
int open;
int iface;
int ep_in;
int ep_out;
struct hid_struct *prev;
struct hid_struct *next;
};
// private functions, not intended to be used from outside this file
static void add_hid(hid_t *h);
static hid_t * get_hid(int num);
static void free_all_hid(void);
static void hid_close(hid_t *hid);
static int hid_parse_item(uint32_t *val, uint8_t **data, const uint8_t *end);
// rawhid_recv - receive a packet
// Inputs:
// num = device to receive from (zero based)
// buf = buffer to receive packet
// len = buffer's size
// timeout = time to wait, in milliseconds
// Output:
// number of bytes received, or -1 on error
//
int rawhid_recv(int num, void *buf, int len, int timeout)
{
hid_t *hid;
int r;
hid = get_hid(num);
if (!hid || !hid->open) return -1;
r = usb_interrupt_read(hid->usb, hid->ep_in, buf, len, timeout);
if (r >= 0) return r;
if (r == -110) return 0; // timeout
return -1;
}
// rawhid_send - send a packet
// Inputs:
// num = device to transmit to (zero based)
// buf = buffer containing packet to send
// len = number of bytes to transmit
// timeout = time to wait, in milliseconds
// Output:
// number of bytes sent, or -1 on error
//
int rawhid_send(int num, void *buf, int len, int timeout)
{
hid_t *hid;
hid = get_hid(num);
if (!hid || !hid->open) return -1;
if (hid->ep_out) {
return usb_interrupt_write(hid->usb, hid->ep_out, buf, len, timeout);
} else {
return usb_control_msg(hid->usb, 0x21, 9, 0, hid->iface, buf, len, timeout);
}
}
// rawhid_open - open 1 or more devices
//
// Inputs:
// max = maximum number of devices to open
// vid = Vendor ID, or -1 if any
// pid = Product ID, or -1 if any
// usage_page = top level usage page, or -1 if any
// usage = top level usage number, or -1 if any
// Output:
// actual number of devices opened
//
int rawhid_open(int max, int vid, int pid, int usage_page, int usage)
{
struct usb_bus *bus;
struct usb_device *dev;
struct usb_interface *iface;
struct usb_interface_descriptor *desc;
struct usb_endpoint_descriptor *ep;
usb_dev_handle *u;
uint8_t buf[1024], *p;
int i, n, len, tag, ep_in, ep_out, count=0, claimed;
uint32_t val=0, parsed_usage, parsed_usage_page;
hid_t *hid;
if (first_hid) free_all_hid();
printf("rawhid_open, max=%d\n", max);
if (max < 1) return 0;
usb_init();
usb_find_busses();
usb_find_devices();
for (bus = usb_get_busses(); bus; bus = bus->next) {
for (dev = bus->devices; dev; dev = dev->next) {
if (vid > 0 && dev->descriptor.idVendor != vid) continue;
if (pid > 0 && dev->descriptor.idProduct != pid) continue;
if (!dev->config) continue;
if (dev->config->bNumInterfaces < 1) continue;
printf("device: vid=%04X, pic=%04X, with %d iface\n",
dev->descriptor.idVendor,
dev->descriptor.idProduct,
dev->config->bNumInterfaces);
iface = dev->config->interface;
u = NULL;
claimed = 0;
for (i=0; i<dev->config->bNumInterfaces && iface; i++, iface++) {
desc = iface->altsetting;
if (!desc) continue;
printf(" type %d, %d, %d\n", desc->bInterfaceClass,
desc->bInterfaceSubClass, desc->bInterfaceProtocol);
if (desc->bInterfaceClass != 3) continue;
if (desc->bInterfaceSubClass != 0) continue;
if (desc->bInterfaceProtocol != 0) continue;
ep = desc->endpoint;
ep_in = ep_out = 0;
for (n = 0; n < desc->bNumEndpoints; n++, ep++) {
if (ep->bEndpointAddress & 0x80) {
if (!ep_in) ep_in = ep->bEndpointAddress & 0x7F;
printf(" IN endpoint %d\n", ep_in);
} else {
if (!ep_out) ep_out = ep->bEndpointAddress;
printf(" OUT endpoint %d\n", ep_out);
}
}
if (!ep_in) continue;
if (!u) {
u = usb_open(dev);
if (!u) {
printf(" unable to open device\n");
break;
}
}
printf(" hid interface (generic)\n");
if (usb_get_driver_np(u, i, (char *)buf, sizeof(buf)) >= 0) {
printf(" in use by driver \"%s\"\n", buf);
if (usb_detach_kernel_driver_np(u, i) < 0) {
printf(" unable to detach from kernel\n");
continue;
}
}
if (usb_claim_interface(u, i) < 0) {
printf(" unable claim interface %d\n", i);
continue;
}
len = usb_control_msg(u, 0x81, 6, 0x2200, i, (char *)buf, sizeof(buf), 250);
printf(" descriptor, len=%d\n", len);
if (len < 2) {
usb_release_interface(u, i);
continue;
}
p = buf;
parsed_usage_page = parsed_usage = 0;
while ((tag = hid_parse_item(&val, &p, buf + len)) >= 0) {
printf(" tag: %X, val %X\n", tag, val);
if (tag == 4) parsed_usage_page = val;
if (tag == 8) parsed_usage = val;
if (parsed_usage_page && parsed_usage) break;
}
if ((!parsed_usage_page) || (!parsed_usage) ||
(usage_page > 0 && parsed_usage_page != usage_page) ||
(usage > 0 && parsed_usage != usage)) {
usb_release_interface(u, i);
continue;
}
hid = (struct hid_struct *)malloc(sizeof(struct hid_struct));
if (!hid) {
usb_release_interface(u, i);
continue;
}
hid->usb = u;
hid->iface = i;
hid->ep_in = ep_in;
hid->ep_out = ep_out;
hid->open = 1;
add_hid(hid);
claimed++;
count++;
if (count >= max) return count;
}
if (u && !claimed) usb_close(u);
}
}
return count;
}
// rawhid_close - close a device
//
// Inputs:
// num = device to close (zero based)
// Output
// (nothing)
//
void rawhid_close(int num)
{
hid_t *hid;
hid = get_hid(num);
if (!hid || !hid->open) return;
hid_close(hid);
}
// Chuck Robey wrote a real HID report parser
// (chuckr@telenix.org) chuckr@chuckr.org
// http://people.freebsd.org/~chuckr/code/python/uhidParser-0.2.tbz
// this tiny thing only needs to extract the top-level usage page
// and usage, and even then is may not be truly correct, but it does
// work with the Teensy Raw HID example.
static int hid_parse_item(uint32_t *val, uint8_t **data, const uint8_t *end)
{
const uint8_t *p = *data;
uint8_t tag;
int table[4] = {0, 1, 2, 4};
int len;
if (p >= end) return -1;
if (p[0] == 0xFE) {
// long item, HID 1.11, 6.2.2.3, page 27
if (p + 5 >= end || p + p[1] >= end) return -1;
tag = p[2];
*val = 0;
len = p[1] + 5;
} else {
// short item, HID 1.11, 6.2.2.2, page 26
tag = p[0] & 0xFC;
len = table[p[0] & 0x03];
if (p + len + 1 >= end) return -1;
switch (p[0] & 0x03) {
case 3: *val = p[1] | (p[2] << 8) | (p[3] << 16) | (p[4] << 24); break;
case 2: *val = p[1] | (p[2] << 8); break;
case 1: *val = p[1]; break;
case 0: *val = 0; break;
}
}
*data += len + 1;
return tag;
}
static void add_hid(hid_t *h)
{
if (!first_hid || !last_hid) {
first_hid = last_hid = h;
h->next = h->prev = NULL;
return;
}
last_hid->next = h;
h->prev = last_hid;
h->next = NULL;
last_hid = h;
}
static hid_t * get_hid(int num)
{
hid_t *p;
for (p = first_hid; p && num > 0; p = p->next, num--) ;
return p;
}
static void free_all_hid(void)
{
hid_t *p, *q;
for (p = first_hid; p; p = p->next) {
hid_close(p);
}
p = first_hid;
while (p) {
q = p;
p = p->next;
free(q);
}
first_hid = last_hid = NULL;
}
static void hid_close(hid_t *hid)
{
hid_t *p;
int others=0;
usb_release_interface(hid->usb, hid->iface);
for (p = first_hid; p; p = p->next) {
if (p->open && p->usb == hid->usb) others++;
}
if (!others) usb_close(hid->usb);
hid->usb = NULL;
}
+409
View File
@@ -0,0 +1,409 @@
/* Simple Raw HID functions for Linux - for use with Teensy RawHID example
* http://www.pjrc.com/teensy/rawhid.html
* Copyright (c) 2009 PJRC.COM, LLC
*
* rawhid_open - open 1 or more devices
* rawhid_recv - receive a packet
* rawhid_send - send a packet
* rawhid_close - close a device
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above description, website URL and copyright notice and this permission
* notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Version 1.0: Initial Release
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/hid/IOHIDLib.h>
#include "rawhid.h"
#define BUFFER_SIZE 64
#define printf(...) // comment this out to get lots of info printed
// a list of all opened HID devices, so the caller can
// simply refer to them by number
typedef struct hid_struct hid_t;
typedef struct buffer_struct buffer_t;
static hid_t *first_hid = NULL;
static hid_t *last_hid = NULL;
struct hid_struct {
IOHIDDeviceRef ref;
int open;
uint8_t buffer[BUFFER_SIZE];
buffer_t *first_buffer;
buffer_t *last_buffer;
struct hid_struct *prev;
struct hid_struct *next;
};
struct buffer_struct {
struct buffer_struct *next;
uint32_t len;
uint8_t buf[BUFFER_SIZE];
};
// private functions, not intended to be used from outside this file
static void add_hid(hid_t *);
static hid_t * get_hid(int);
static void free_all_hid(void);
static void hid_close(hid_t *);
static void attach_callback(void *, IOReturn, void *, IOHIDDeviceRef);
static void detach_callback(void *, IOReturn, void *hid_mgr, IOHIDDeviceRef dev);
static void timeout_callback(CFRunLoopTimerRef, void *);
static void input_callback(void *, IOReturn, void *, IOHIDReportType,
uint32_t, uint8_t *, CFIndex);
// rawhid_recv - receive a packet
// Inputs:
// num = device to receive from (zero based)
// buf = buffer to receive packet
// len = buffer's size
// timeout = time to wait, in milliseconds
// Output:
// number of bytes received, or -1 on error
//
int rawhid_recv(int num, void *buf, int len, int timeout)
{
hid_t *hid;
buffer_t *b;
CFRunLoopTimerRef timer=NULL;
CFRunLoopTimerContext context;
int ret=0, timeout_occurred=0;
if (len < 1) return 0;
hid = get_hid(num);
if (!hid || !hid->open) return -1;
if ((b = hid->first_buffer) != NULL) {
if (len > b->len) len = b->len;
memcpy(buf, b->buf, len);
hid->first_buffer = b->next;
free(b);
return len;
}
memset(&context, 0, sizeof(context));
context.info = &timeout_occurred;
timer = CFRunLoopTimerCreate(NULL, CFAbsoluteTimeGetCurrent() +
(double)timeout / 1000.0, 0, 0, 0, timeout_callback, &context);
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopDefaultMode);
while (1) {
CFRunLoopRun();
if ((b = hid->first_buffer) != NULL) {
if (len > b->len) len = b->len;
memcpy(buf, b->buf, len);
hid->first_buffer = b->next;
free(b);
ret = len;
break;
}
if (!hid->open) {
printf("rawhid_recv, device not open\n");
ret = -1;
break;
}
if (timeout_occurred) break;
}
CFRunLoopTimerInvalidate(timer);
CFRelease(timer);
return ret;
}
static void input_callback(void *context, IOReturn ret, void *sender,
IOHIDReportType type, uint32_t id, uint8_t *data, CFIndex len)
{
buffer_t *n;
hid_t *hid;
printf("input_callback\n");
if (ret != kIOReturnSuccess || len < 1) return;
hid = context;
if (!hid || hid->ref != sender) return;
n = (buffer_t *)malloc(sizeof(buffer_t));
if (!n) return;
if (len > BUFFER_SIZE) len = BUFFER_SIZE;
memcpy(n->buf, data, len);
n->len = len;
n->next = NULL;
if (!hid->first_buffer || !hid->last_buffer) {
hid->first_buffer = hid->last_buffer = n;
} else {
hid->last_buffer->next = n;
hid->last_buffer = n;
}
CFRunLoopStop(CFRunLoopGetCurrent());
}
static void timeout_callback(CFRunLoopTimerRef timer, void *info)
{
printf("timeout_callback\n");
*(int *)info = 1;
CFRunLoopStop(CFRunLoopGetCurrent());
}
void output_callback(void *context, IOReturn ret, void *sender,
IOHIDReportType type, uint32_t id, uint8_t *data, CFIndex len)
{
printf("output_callback, r=%d\n", ret);
if (ret == kIOReturnSuccess) {
*(int *)context = len;
} else {
// timeout if not success?
*(int *)context = 0;
}
CFRunLoopStop(CFRunLoopGetCurrent());
}
// rawhid_send - send a packet
// Inputs:
// num = device to transmit to (zero based)
// buf = buffer containing packet to send
// len = number of bytes to transmit
// timeout = time to wait, in milliseconds
// Output:
// number of bytes sent, or -1 on error
//
int rawhid_send(int num, void *buf, int len, int timeout)
{
hid_t *hid;
int result=-100;
hid = get_hid(num);
if (!hid || !hid->open) return -1;
#if 1
#warning "Send timeout not implemented on MACOSX"
IOReturn ret = IOHIDDeviceSetReport(hid->ref, kIOHIDReportTypeOutput, 0, buf, len);
result = (ret == kIOReturnSuccess) ? len : -1;
#endif
#if 0
// No matter what I tried this never actually sends an output
// report and output_callback never gets called. Why??
// Did I miss something? This is exactly the same params as
// the sync call that works. Is it an Apple bug?
// (submitted to Apple on 22-sep-2009, problem ID 7245050)
//
IOHIDDeviceScheduleWithRunLoop(hid->ref, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
// should already be scheduled with run loop by attach_callback,
// sadly this doesn't make any difference either way
//
IOHIDDeviceSetReportWithCallback(hid->ref, kIOHIDReportTypeOutput,
0, buf, len, (double)timeout / 1000.0, output_callback, &result);
while (1) {
printf("enter run loop (send)\n");
CFRunLoopRun();
printf("leave run loop (send)\n");
if (result > -100) break;
if (!hid->open) {
result = -1;
break;
}
}
#endif
return result;
}
// rawhid_open - open 1 or more devices
//
// Inputs:
// max = maximum number of devices to open
// vid = Vendor ID, or -1 if any
// pid = Product ID, or -1 if any
// usage_page = top level usage page, or -1 if any
// usage = top level usage number, or -1 if any
// Output:
// actual number of devices opened
//
int rawhid_open(int max, int vid, int pid, int usage_page, int usage)
{
static IOHIDManagerRef hid_manager=NULL;
CFMutableDictionaryRef dict;
CFNumberRef num;
IOReturn ret;
hid_t *p;
int count=0;
if (first_hid) free_all_hid();
printf("rawhid_open, max=%d\n", max);
if (max < 1) return 0;
// Start the HID Manager
// http://developer.apple.com/technotes/tn2007/tn2187.html
if (!hid_manager) {
hid_manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
if (hid_manager == NULL || CFGetTypeID(hid_manager) != IOHIDManagerGetTypeID()) {
if (hid_manager) CFRelease(hid_manager);
return 0;
}
}
if (vid > 0 || pid > 0 || usage_page > 0 || usage > 0) {
// Tell the HID Manager what type of devices we want
dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
&kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
if (!dict) return 0;
if (vid > 0) {
num = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &vid);
CFDictionarySetValue(dict, CFSTR(kIOHIDVendorIDKey), num);
CFRelease(num);
}
if (pid > 0) {
num = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &pid);
CFDictionarySetValue(dict, CFSTR(kIOHIDProductIDKey), num);
CFRelease(num);
}
if (usage_page > 0) {
num = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage_page);
CFDictionarySetValue(dict, CFSTR(kIOHIDPrimaryUsagePageKey), num);
CFRelease(num);
}
if (usage > 0) {
num = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage);
CFDictionarySetValue(dict, CFSTR(kIOHIDPrimaryUsageKey), num);
CFRelease(num);
}
IOHIDManagerSetDeviceMatching(hid_manager, dict);
CFRelease(dict);
} else {
IOHIDManagerSetDeviceMatching(hid_manager, NULL);
}
// set up a callbacks for device attach & detach
IOHIDManagerScheduleWithRunLoop(hid_manager, CFRunLoopGetCurrent(),
kCFRunLoopDefaultMode);
IOHIDManagerRegisterDeviceMatchingCallback(hid_manager, attach_callback, NULL);
IOHIDManagerRegisterDeviceRemovalCallback(hid_manager, detach_callback, NULL);
ret = IOHIDManagerOpen(hid_manager, kIOHIDOptionsTypeNone);
if (ret != kIOReturnSuccess) {
IOHIDManagerUnscheduleFromRunLoop(hid_manager,
CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
CFRelease(hid_manager);
return 0;
}
printf("run loop\n");
// let it do the callback for all devices
while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true) == kCFRunLoopRunHandledSource) ;
// count up how many were added by the callback
for (p = first_hid; p; p = p->next) count++;
return count;
}
// rawhid_close - close a device
//
// Inputs:
// num = device to close (zero based)
// Output
// (nothing)
//
void rawhid_close(int num)
{
hid_t *hid;
hid = get_hid(num);
if (!hid || !hid->open) return;
hid_close(hid);
hid->open = 0;
}
static void add_hid(hid_t *h)
{
if (!first_hid || !last_hid) {
first_hid = last_hid = h;
h->next = h->prev = NULL;
return;
}
last_hid->next = h;
h->prev = last_hid;
h->next = NULL;
last_hid = h;
}
static hid_t * get_hid(int num)
{
hid_t *p;
for (p = first_hid; p && num > 0; p = p->next, num--) ;
return p;
}
static void free_all_hid(void)
{
hid_t *p, *q;
for (p = first_hid; p; p = p->next) {
hid_close(p);
}
p = first_hid;
while (p) {
q = p;
p = p->next;
free(q);
}
first_hid = last_hid = NULL;
}
static void hid_close(hid_t *hid)
{
if (!hid || !hid->open || !hid->ref) return;
IOHIDDeviceUnscheduleFromRunLoop(hid->ref, CFRunLoopGetCurrent( ), kCFRunLoopDefaultMode);
IOHIDDeviceClose(hid->ref, kIOHIDOptionsTypeNone);
hid->ref = NULL;
}
static void detach_callback(void *context, IOReturn r, void *hid_mgr, IOHIDDeviceRef dev)
{
hid_t *p;
printf("detach callback\n");
for (p = first_hid; p; p = p->next) {
if (p->ref == dev) {
p->open = 0;
CFRunLoopStop(CFRunLoopGetCurrent());
return;
}
}
}
static void attach_callback(void *context, IOReturn r, void *hid_mgr, IOHIDDeviceRef dev)
{
struct hid_struct *h;
printf("attach callback\n");
if (IOHIDDeviceOpen(dev, kIOHIDOptionsTypeNone) != kIOReturnSuccess) return;
h = (hid_t *)malloc(sizeof(hid_t));
if (!h) return;
memset(h, 0, sizeof(hid_t));
IOHIDDeviceScheduleWithRunLoop(dev, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
IOHIDDeviceRegisterInputReportCallback(dev, h->buffer, sizeof(h->buffer),
input_callback, h);
h->ref = dev;
h->open = 1;
add_hid(h);
}
+330
View File
@@ -0,0 +1,330 @@
/* Simple Raw HID functions for Windows - for use with Teensy RawHID example
* http://www.pjrc.com/teensy/rawhid.html
* Copyright (c) 2009 PJRC.COM, LLC
*
* rawhid_open - open 1 or more devices
* rawhid_recv - receive a packet
* rawhid_send - send a packet
* rawhid_close - close a device
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above description, website URL and copyright notice and this permission
* notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Version 1.0: Initial Release
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <windows.h>
#include <setupapi.h>
#include <ddk/hidsdi.h>
#include <ddk/hidclass.h>
#include "rawhid.h"
// a list of all opened HID devices, so the caller can
// simply refer to them by number
typedef struct hid_struct hid_t;
static hid_t *first_hid = NULL;
static hid_t *last_hid = NULL;
struct hid_struct {
HANDLE handle;
int open;
struct hid_struct *prev;
struct hid_struct *next;
};
static HANDLE rx_event=NULL;
static HANDLE tx_event=NULL;
static CRITICAL_SECTION rx_mutex;
static CRITICAL_SECTION tx_mutex;
// private functions, not intended to be used from outside this file
static void add_hid(hid_t *h);
static hid_t * get_hid(int num);
static void free_all_hid(void);
static void hid_close(hid_t *hid);
void print_win32_err(void);
// rawhid_recv - receive a packet
// Inputs:
// num = device to receive from (zero based)
// buf = buffer to receive packet
// len = buffer's size
// timeout = time to wait, in milliseconds
// Output:
// number of bytes received, or -1 on error
//
int RAWHIDFN rawhid_recv(int num, void *buf, int len, int timeout)
{
hid_t *hid;
unsigned char tmpbuf[516];
OVERLAPPED ov;
DWORD n, r;
if (sizeof(tmpbuf) < len + 1) return -1;
hid = get_hid(num);
if (!hid || !hid->open) return -1;
EnterCriticalSection(&rx_mutex);
ResetEvent(&rx_event);
memset(&ov, 0, sizeof(ov));
ov.hEvent = rx_event;
if (!ReadFile(hid->handle, tmpbuf, len + 1, NULL, &ov)) {
if (GetLastError() != ERROR_IO_PENDING) goto return_error;
r = WaitForSingleObject(rx_event, timeout);
if (r == WAIT_TIMEOUT) goto return_timeout;
if (r != WAIT_OBJECT_0) goto return_error;
}
if (!GetOverlappedResult(hid->handle, &ov, &n, FALSE)) goto return_error;
LeaveCriticalSection(&rx_mutex);
if (n <= 0) return -1;
n--;
if (n > len) n = len;
memcpy(buf, tmpbuf + 1, n);
return n;
return_timeout:
CancelIo(hid->handle);
LeaveCriticalSection(&rx_mutex);
return 0;
return_error:
print_win32_err();
LeaveCriticalSection(&rx_mutex);
return -1;
}
// rawhid_send - send a packet
// Inputs:
// num = device to transmit to (zero based)
// buf = buffer containing packet to send
// len = number of bytes to transmit
// timeout = time to wait, in milliseconds
// Output:
// number of bytes sent, or -1 on error
//
int RAWHIDFN rawhid_send(int num, void *buf, int len, int timeout)
{
hid_t *hid;
unsigned char tmpbuf[516];
OVERLAPPED ov;
DWORD n, r;
if (sizeof(tmpbuf) < len + 1) return -1;
hid = get_hid(num);
if (!hid || !hid->open) return -1;
EnterCriticalSection(&tx_mutex);
ResetEvent(&tx_event);
memset(&ov, 0, sizeof(ov));
ov.hEvent = tx_event;
tmpbuf[0] = 0;
memcpy(tmpbuf + 1, buf, len);
if (!WriteFile(hid->handle, tmpbuf, len + 1, NULL, &ov)) {
if (GetLastError() != ERROR_IO_PENDING) goto return_error;
r = WaitForSingleObject(tx_event, timeout);
if (r == WAIT_TIMEOUT) goto return_timeout;
if (r != WAIT_OBJECT_0) goto return_error;
}
if (!GetOverlappedResult(hid->handle, &ov, &n, FALSE)) goto return_error;
LeaveCriticalSection(&tx_mutex);
if (n <= 0) return -1;
return n - 1;
return_timeout:
CancelIo(hid->handle);
LeaveCriticalSection(&tx_mutex);
return 0;
return_error:
print_win32_err();
LeaveCriticalSection(&tx_mutex);
return -1;
}
// rawhid_open - open 1 or more devices
//
// Inputs:
// max = maximum number of devices to open
// vid = Vendor ID, or -1 if any
// pid = Product ID, or -1 if any
// usage_page = top level usage page, or -1 if any
// usage = top level usage number, or -1 if any
// Output:
// actual number of devices opened
//
int RAWHIDFN rawhid_open(int max, int vid, int pid, int usage_page, int usage)
{
GUID guid;
HDEVINFO info;
DWORD index=0, reqd_size;
SP_DEVICE_INTERFACE_DATA iface;
SP_DEVICE_INTERFACE_DETAIL_DATA *details;
HIDD_ATTRIBUTES attrib;
PHIDP_PREPARSED_DATA hid_data;
HIDP_CAPS capabilities;
HANDLE h;
BOOL ret;
hid_t *hid;
int count=0;
if (first_hid) free_all_hid();
if (max < 1) return 0;
if (!rx_event) {
rx_event = CreateEvent(NULL, TRUE, TRUE, NULL);
tx_event = CreateEvent(NULL, TRUE, TRUE, NULL);
InitializeCriticalSection(&rx_mutex);
InitializeCriticalSection(&tx_mutex);
}
HidD_GetHidGuid(&guid);
info = SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (info == INVALID_HANDLE_VALUE) return 0;
for (index=0; 1 ;index++) {
iface.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
ret = SetupDiEnumDeviceInterfaces(info, NULL, &guid, index, &iface);
if (!ret) return count;
SetupDiGetInterfaceDeviceDetail(info, &iface, NULL, 0, &reqd_size, NULL);
details = (SP_DEVICE_INTERFACE_DETAIL_DATA *)malloc(reqd_size);
if (details == NULL) continue;
memset(details, 0, reqd_size);
details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
ret = SetupDiGetDeviceInterfaceDetail(info, &iface, details,
reqd_size, NULL, NULL);
if (!ret) {
free(details);
continue;
}
h = CreateFile(details->DevicePath, GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
free(details);
if (h == INVALID_HANDLE_VALUE) continue;
attrib.Size = sizeof(HIDD_ATTRIBUTES);
ret = HidD_GetAttributes(h, &attrib);
//printf("vid: %4x\n", attrib.VendorID);
if (!ret || (vid > 0 && attrib.VendorID != vid) ||
(pid > 0 && attrib.ProductID != pid) ||
!HidD_GetPreparsedData(h, &hid_data)) {
CloseHandle(h);
continue;
}
if (!HidP_GetCaps(hid_data, &capabilities) ||
(usage_page > 0 && capabilities.UsagePage != usage_page) ||
(usage > 0 && capabilities.Usage != usage)) {
HidD_FreePreparsedData(hid_data);
CloseHandle(h);
continue;
}
HidD_FreePreparsedData(hid_data);
hid = (struct hid_struct *)malloc(sizeof(struct hid_struct));
if (!hid) {
CloseHandle(h);
continue;
}
hid->handle = h;
hid->open = 1;
add_hid(hid);
count++;
if (count >= max) return count;
}
return count;
}
// rawhid_close - close a device
//
// Inputs:
// num = device to close (zero based)
// Output
// (nothing)
//
void RAWHIDFN rawhid_close(int num)
{
hid_t *hid;
hid = get_hid(num);
if (!hid || !hid->open) return;
hid_close(hid);
}
static void add_hid(hid_t *h)
{
if (!first_hid || !last_hid) {
first_hid = last_hid = h;
h->next = h->prev = NULL;
return;
}
last_hid->next = h;
h->prev = last_hid;
h->next = NULL;
last_hid = h;
}
static hid_t * get_hid(int num)
{
hid_t *p;
for (p = first_hid; p && num > 0; p = p->next, num--) ;
return p;
}
static void free_all_hid(void)
{
hid_t *p, *q;
for (p = first_hid; p; p = p->next) {
hid_close(p);
}
p = first_hid;
while (p) {
q = p;
p = p->next;
free(q);
}
first_hid = last_hid = NULL;
}
static void hid_close(hid_t *hid)
{
CloseHandle(hid->handle);
hid->handle = NULL;
}
void print_win32_err(void)
{
char buf[256];
DWORD err;
err = GetLastError();
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err,
0, buf, sizeof(buf), NULL);
printf("err %ld: %s\n", err, buf);
}
+319
View File
@@ -0,0 +1,319 @@
#include "hid_tokens.h"
#include "global.h"
#include <string.h>
token_t meta_token_list[] =
{
{ "LCTRL", 0x01 }, // Left Control
{ "LSHIFT", 0x02 }, // Left Shift
{ "LALT", 0x04 }, // Left Alt
{ "LGUI", 0x08 }, // Left GUI
{ "RCTRL", 0x10 }, // Right Control
{ "RSHIFT", 0x20 }, // Right Shift
{ "RALT", 0x40 }, // Right Alt
{ "RGUI", 0x80 }, // Right GUI
{ "CTRL", 0x11 }, // Either/Both Control
{ "SHIFT", 0x22 }, // Either/Both Shift
{ "ALT", 0x44 }, // Either/Both Alt
{ "GUI", 0x88 }, // Either/Both GUI
{ "ALL", 0xFF }, // Any/All
};
token_t hid_token_list[] =
{
{ "UNASSIGNED", 0x00 }, // No Event
{ "OVERRUN_ERROR", 0x01 }, // Overrun Error
{ "POST_FAIL", 0x02 }, // POST Fail
{ "ERROR_UNDEFINED", 0x03 }, // ErrorUndefined
{ "A", 0x04 }, // a A
{ "B", 0x05 }, // b B
{ "C", 0x06 }, // c C
{ "D", 0x07 }, // d D
{ "E", 0x08 }, // e E
{ "F", 0x09 }, // f F
{ "G", 0x0A }, // g G
{ "H", 0x0B }, // h H
{ "I", 0x0C }, // i I
{ "J", 0x0D }, // j J
{ "K", 0x0E }, // k K
{ "L", 0x0F }, // l L
{ "M", 0x10 }, // m M
{ "N", 0x11 }, // n N
{ "O", 0x12 }, // o O
{ "P", 0x13 }, // p P
{ "Q", 0x14 }, // q Q
{ "R", 0x15 }, // r R
{ "S", 0x16 }, // s S
{ "T", 0x17 }, // t T
{ "U", 0x18 }, // u U
{ "V", 0x19 }, // v V
{ "W", 0x1A }, // w W
{ "X", 0x1B }, // x X
{ "Y", 0x1C }, // y Y
{ "Z", 0x1D }, // z Z
{ "1", 0x1E }, // 1 !
{ "2", 0x1F }, // 2 @
{ "3", 0x20 }, // 3 #
{ "4", 0x21 }, // 4 $
{ "5", 0x22 }, // 5 %
{ "6", 0x23 }, // 6 ^
{ "7", 0x24 }, // 7 &
{ "8", 0x25 }, // 8 *
{ "9", 0x26 }, // 9 (
{ "0", 0x27 }, // 0 )
{ "ENTER", 0x28 }, // Return
{ "ESC", 0x29 }, // Escape
{ "BACKSPACE", 0x2A }, // Backspace
{ "TAB", 0x2B }, // Tab
{ "SPACE", 0x2C }, // Space
{ "MINUS", 0x2D }, // minus _
{ "EQUAL", 0x2E }, // = +
{ "LEFT_BRACE", 0x2F }, // [ {
{ "RIGHT_BRACE", 0x30 }, // ] }
{ "BACKSLASH", 0x31 }, // \ |
{ "EUROPE_1", 0x32 }, // Europe 1
{ "SEMICOLON", 0x33 }, // ; :
{ "QUOTE", 0x34 }, // quotes
{ "BACK_QUOTE", 0x35 }, // ` ~
{ "COMMA", 0x36 }, // comma <
{ "PERIOD", 0x37 }, // . >
{ "SLASH", 0x38 }, // / ?
{ "CAPS_LOCK", 0x39 }, // Caps Lock
{ "F1", 0x3A }, // F1
{ "F2", 0x3B }, // F2
{ "F3", 0x3C }, // F3
{ "F4", 0x3D }, // F4
{ "F5", 0x3E }, // F5
{ "F6", 0x3F }, // F6
{ "F7", 0x40 }, // F7
{ "F8", 0x41 }, // F8
{ "F9", 0x42 }, // F9
{ "F10", 0x43 }, // F10
{ "F11", 0x44 }, // F11
{ "F12", 0x45 }, // F12
{ "PRINTSCREEN", 0x46 }, // Print Screen
{ "SCROLL_LOCK", 0x47 }, // Scroll Lock
{ "PAUSE", 0x48 }, // Pause
{ "INSERT", 0x49 }, // Insert
{ "HOME", 0x4A }, // Home
{ "PAGE_UP", 0x4B }, // Page Up
{ "DELETE", 0x4C }, // Delete
{ "END", 0x4D }, // End
{ "PAGE_DOWN", 0x4E }, // Page Down
{ "RIGHT", 0x4F }, // Right Arrow
{ "LEFT", 0x50 }, // Left Arrow
{ "DOWN", 0x51 }, // Down Arrow
{ "UP", 0x52 }, // Up Arrow
{ "NUM_LOCK", 0x53 }, // Num Lock
{ "PAD_SLASH", 0x54 }, // Keypad /
{ "PAD_ASTERIX", 0x55 }, // Keypad *
{ "PAD_MINUS", 0x56 }, // Keypad -
{ "PAD_PLUS", 0x57 }, // Keypad +
{ "PAD_ENTER", 0x58 }, // Keypad Enter
{ "PAD_1", 0x59 }, // Keypad 1 End
{ "PAD_2", 0x5A }, // Keypad 2 Down
{ "PAD_3", 0x5B }, // Keypad 3 PageDn
{ "PAD_4", 0x5C }, // Keypad 4 Left
{ "PAD_5", 0x5D }, // Keypad 5
{ "PAD_6", 0x5E }, // Keypad 6 Right
{ "PAD_7", 0x5F }, // Keypad 7 Home
{ "PAD_8", 0x60 }, // Keypad 8 Up
{ "PAD_9", 0x61 }, // Keypad 9 PageUp
{ "PAD_0", 0x62 }, // Keypad 0 Insert
{ "PAD_PERIOD", 0x63 }, // Keypad . Delete
{ "EUROPE_2", 0x64 }, // Europe 2
{ "APP", 0x65 }, // App
{ "POWER", 0x66 }, // Keyboard Power
{ "PAD_EQUALS", 0x67 }, // Keypad =
{ "F13", 0x68 }, // F13
{ "F14", 0x69 }, // F14
{ "F15", 0x6A }, // F15
{ "F16", 0x6B }, // F16
{ "F17", 0x6C }, // F17
{ "F18", 0x6D }, // F18
{ "F19", 0x6E }, // F19
{ "F20", 0x6F }, // F20
{ "F21", 0x70 }, // F21
{ "F22", 0x71 }, // F22
{ "F23", 0x72 }, // F23
{ "F24", 0x73 }, // F24
{ "EXECUTE", 0x74 }, // Keyboard Execute
{ "HELP", 0x75 }, // Keyboard Help
{ "MENU", 0x76 }, // Keyboard Menu
{ "SELECT", 0x77 }, // Keyboard Select
{ "STOP", 0x78 }, // Keyboard Stop
{ "AGAIN", 0x79 }, // Keyboard Again
{ "UNDO", 0x7A }, // Keyboard Undo
{ "CUT", 0x7B }, // Keyboard Cut
{ "COPY", 0x7C }, // Keyboard Copy
{ "PASTE", 0x7D }, // Keyboard Paste
{ "FIND", 0x7E }, // Keyboard Find
{ "MUTE", 0x7F }, // Keyboard Mute
{ "VOLUME_UP", 0x80 }, // Keyboard Volume Up
{ "VOLUME_DOWN", 0x81 }, // Keyboard Volume Dn
{ "LOCKING_CAPS_LOCK", 0x82 }, // Keyboard Locking Caps Lock
{ "LOCKING_NUM_LOCK", 0x83 }, // Keyboard Locking Num Lock
{ "LOCKING_SCROLL_LOCK", 0x84 }, // Keyboard Locking Scroll Lock
{ "PAD_COMMA", 0x85 }, // Keypad comma (Brazilian Keypad .)
{ "EQUAL_SIGN", 0x86 }, // Keyboard Equal Sign
{ "INTERNATIONAL_1", 0x87 }, // Keyboard Int'l 1 (Ro)
{ "INTERNATIONAL_2", 0x88 }, // Keyboard Intl'2 (Katakana/Hiragana)
{ "INTERNATIONAL_3", 0x89 }, // Keyboard Int'l 2 (Yen)
{ "INTERNATIONAL_4", 0x8A }, // Keyboard Int'l 4 (Henkan)
{ "INTERNATIONAL_5", 0x8B }, // Keyboard Int'l 5 (Muhenkan)
{ "INTERNATIONAL_6", 0x8C }, // Keyboard Int'l 6 (PC9800 Keypad comma)
{ "INTERNATIONAL_7", 0x8D }, // Keyboard Int'l 7
{ "INTERNATIONAL_8", 0x8E }, // Keyboard Int'l 8
{ "INTERNATIONAL_9", 0x8F }, // Keyboard Int'l 9
{ "LANG_1", 0x90 }, // Keyboard Lang 1 (Hanguel/English)
{ "LANG_2", 0x91 }, // Keyboard Lang 2 (Hanja)
{ "LANG_3", 0x92 }, // Keyboard Lang 3 (Katakana)
{ "LANG_4", 0x93 }, // Keyboard Lang 4 (Hiragana)
{ "LANG_5", 0x94 }, // Keyboard Lang 5 (Zenkaku/Hankaku)
{ "LANG_6", 0x95 }, // Keyboard Lang 6
{ "LANG_7", 0x96 }, // Keyboard Lang 7
{ "LANG_8", 0x97 }, // Keyboard Lang 8
{ "LANG_9", 0x98 }, // Keyboard Lang 9
{ "ALTERNATE_ERASE", 0x99 }, // Keyboard Alternate Erase
{ "SYSREQ_ATTN", 0x9A }, // Keyboard SysReq/Attention
{ "CANCEL", 0x9B }, // Keyboard Cancel
{ "CLEAR", 0x9C }, // Keyboard Clear
{ "PRIOR", 0x9D }, // Keyboard Prior
{ "RETURN", 0x9E }, // Keyboard Return
{ "SEPARATOR", 0x9F }, // Keyboard Separator
{ "OUT", 0xA0 }, // Keyboard Out
{ "OPER", 0xA1 }, // Keyboard Oper
{ "CLEAR_AGAIN", 0xA2 }, // Keyboard Clear/Again
{ "CRSEL_PROPS", 0xA3 }, // Keyboard CrSel/Props
{ "EXSEL", 0xA4 }, // Keyboard ExSel
{ "SYSTEM_POWER", 0xA8 }, // System Power
{ "SYSTEM_SLEEP", 0xA9 }, // System Sleep
{ "SYSTEM_WAKE", 0xAA }, // System Wake
{ "AUX1", 0xAB }, // Auxiliary key 1
{ "AUX2", 0xAC }, // Auxiliary key 2
{ "AUX3", 0xAD }, // Auxiliary key 3
{ "AUX4", 0xAE }, // Auxiliary key 4
{ "AUX5", 0xAF }, // Auxiliary key 5
//{ "EXTRA_UNUSED_1", 0xB0 }, // extra
{ "EXTRA_LALT", 0xB1 }, // AT-F extra pad lhs of space
{ "EXTRA_PAD_PLUS", 0xB2 }, // Term extra pad bottom of keypad +
{ "EXTRA_RALT", 0xB3 }, // AT-F extra pad rhs of space
{ "EXTRA_EUROPE_2", 0xB4 }, // AT-F extra pad lhs of enter
{ "EXTRA_BACKSLASH", 0xB5 }, // AT-F extra pad top of enter
{ "EXTRA_INSERT", 0xB6 }, // AT-F extra pad lhs of Insert
{ "EXTRA_F1", 0xB7 }, // Term F1
{ "EXTRA_F2", 0xB8 }, // Term F2
{ "EXTRA_F3", 0xB9 }, // Term F3
{ "EXTRA_F4", 0xBA }, // Term F4
{ "EXTRA_F5", 0xBB }, // Term F5
{ "EXTRA_F6", 0xBC }, // Term F6
{ "EXTRA_F7", 0xBD }, // Term F7
{ "EXTRA_F8", 0xBE }, // Term F8
{ "EXTRA_F9", 0xBF }, // Term F9
{ "EXTRA_F10", 0xC0 }, // Term F10
//{ "EXTRA_UNUSED_2", 0xC1 }, // extra
{ "EXTRA_SYSRQ", 0xC2 }, // Sys Req (AT 84-key)
{ "FAKE_01", 0xB0 }, // extra
{ "FAKE_02", 0xB1 }, // AT-F extra pad lhs of space
{ "FAKE_03", 0xB2 }, // Term extra pad bottom of keypad +
{ "FAKE_04", 0xB3 }, // AT-F extra pad rhs of space
{ "FAKE_05", 0xB4 }, // AT-F extra pad lhs of enter
{ "FAKE_06", 0xB5 }, // AT-F extra pad top of enter
{ "FAKE_07", 0xB6 }, // AT-F extra pad lhs of Insert
{ "FAKE_08", 0xB7 }, // Term F1
{ "FAKE_09", 0xB8 }, // Term F2
{ "FAKE_10", 0xB9 }, // Term F3
{ "FAKE_11", 0xBA }, // Term F4
{ "FAKE_12", 0xBB }, // Term F5
{ "FAKE_13", 0xBC }, // Term F6
{ "FAKE_14", 0xBD }, // Term F7
{ "FAKE_15", 0xBE }, // Term F8
{ "FAKE_16", 0xBF }, // Term F9
{ "FAKE_17", 0xC0 }, // Term F10
{ "FAKE_18", 0xC1 }, // extra
{ "FAKE_19", 0xC2 }, // Sys Req (AT 84-key)
{ "FN1", 0xD0 }, // Function layer key 1
{ "FN2", 0xD1 }, // Function layer key 2
{ "FN3", 0xD2 }, // Function layer key 3
{ "FN4", 0xD3 }, // Function layer key 4
{ "FN5", 0xD4 }, // Function layer key 5
{ "FN6", 0xD5 }, // Function layer key 6
{ "FN7", 0xD6 }, // Function layer key 7
{ "FN8", 0xD7 }, // Function layer key 8
{ "SELECT_0", 0xD8 }, // Select reset
{ "SELECT_1", 0xD9 }, // Select 1
{ "SELECT_2", 0xDA }, // Select 2
{ "SELECT_3", 0xDB }, // Select 3
{ "SELECT_4", 0xDC }, // Select 4
{ "SELECT_5", 0xDD }, // Select 5
{ "SELECT_6", 0xDE }, // Select 6
{ "SELECT_7", 0xDF }, // Select 7
{ "LCTRL", 0xE0 }, // Left Control
{ "LSHIFT", 0xE1 }, // Left Shift
{ "LALT", 0xE2 }, // Left Alt
{ "LGUI", 0xE3 }, // Left GUI
{ "RCTRL", 0xE4 }, // Right Control
{ "RSHIFT", 0xE5 }, // Right Shift
{ "RALT", 0xE6 }, // Right Alt
{ "RGUI", 0xE7 }, // Right GUI
{ "MEDIA_NEXT_TRACK", 0xE8 }, // Scan Next Track
{ "MEDIA_PREV_TRACK", 0xE9 }, // Scan Previous Track
{ "MEDIA_STOP", 0xEA }, // Stop
{ "MEDIA_PLAY_PAUSE", 0xEB }, // Play/ Pause
{ "MEDIA_MUTE", 0xEC }, // Mute
{ "MEDIA_BASS_BOOST", 0xED }, // Bass Boost
{ "MEDIA_LOUDNESS", 0xEE }, // Loudness
{ "MEDIA_VOLUME_UP", 0xEF }, // Volume Up
{ "MEDIA_VOLUME_DOWN", 0xF0 }, // Volume Down
{ "MEDIA_BASS_UP", 0xF1 }, // Bass Up
{ "MEDIA_BASS_DOWN", 0xF2 }, // Bass Down
{ "MEDIA_TREBLE_UP", 0xF3 }, // Treble Up
{ "MEDIA_TREBLE_DOWN", 0xF4 }, // Treble Down
{ "MEDIA_MEDIA_SELECT", 0xF5 }, // Media Select
{ "MEDIA_MAIL", 0xF6 }, // Mail
{ "MEDIA_CALCULATOR", 0xF7 }, // Calculator
{ "MEDIA_MY_COMPUTER", 0xF8 }, // My Computer
{ "MEDIA_WWW_SEARCH", 0xF9 }, // WWW Search
{ "MEDIA_WWW_HOME", 0xFA }, // WWW Home
{ "MEDIA_WWW_BACK", 0xFB }, // WWW Back
{ "MEDIA_WWW_FORWARD", 0xFC }, // WWW Forward
{ "MEDIA_WWW_STOP", 0xFD }, // WWW Stop
{ "MEDIA_WWW_REFRESH", 0xFE }, // WWW Refresh
{ "MEDIA_WWW_FAVORITES", 0xFF }, // WWW Favorites
};
const char* lookup_hid_token(int value)
{
int n = sizeof(hid_token_list) / sizeof(token_t);
for ( int i = 0; i < n; ++i ) {
if ( hid_token_list[i].value == value ) {
return hid_token_list[i].token;
}
}
return "INVALID";
}
int lookup_hid_token(const char* s)
{
int n = sizeof(hid_token_list) / sizeof(token_t);
for ( int i = 0; i < n; ++i ) {
if ( 0 == stricmp(hid_token_list[i].token, s) ) {
return hid_token_list[i].value;
}
}
return INVALID_NUMBER;
}
int lookup_meta_token(const char* s)
{
int n = sizeof(meta_token_list) / sizeof(token_t);
for ( int i = 0; i < n; ++i ) {
if ( 0 == stricmp(meta_token_list[i].token, s) ) {
return meta_token_list[i].value;
}
}
return INVALID_NUMBER;
}
+13
View File
@@ -0,0 +1,13 @@
#ifndef __HID_TOKENS_H__
#define __HID_TOKENS_H__
int lookup_hid_token(const char* s);
const char* lookup_hid_token(int value);
int lookup_meta_token(const char* s);
inline bool is_meta_handed(int meta)
{
return !(meta & (meta >> 4));
}
#endif // __HID_TOKENS_H__
+69
View File
@@ -0,0 +1,69 @@
#include "macro_tokens.h"
#include "global.h"
#include <string.h>
token_t macro_token_list[] =
{
{ "NOP", Q_NOP }, // value = ignored
{ "PRESS", Q_KEY_PRESS }, // value = hid code
{ "MAKE", Q_KEY_MAKE }, // value = hid code
{ "BREAK", Q_KEY_RELEASE }, // value = hid code
{ "ASSIGN_META", Q_ASSIGN_META }, // value = metas
{ "SET_META", Q_SET_META }, // value = metas
{ "CLEAR_META", Q_CLEAR_META }, // value = metas
{ "TOGGLE_META", Q_TOGGLE_META }, // value = metas
{ "POP_META", Q_POP_META }, // value = ignored
{ "POP_ALL_META", Q_POP_ALL_META }, // value = ignored
{ "DELAY", Q_DELAY_MS }, // value = delay count
{ "CLEAR_ALL", Q_CLEAR_ALL }, // value = ignored // internal use
{ "BOOT", Q_BOOT }, // value = ignored
{ "PUSH_META", Q_PUSH_META }, // can be combined with any other command. value = value for other command
};
const char* lookup_macro_token(int value)
{
int n = sizeof(macro_token_list) / sizeof(token_t);
for ( int i = 0; i < n; ++i ) {
if ( macro_token_list[i].value == value ) {
return macro_token_list[i].token;
}
}
return "INVALID";
}
int lookup_macro_token(const char* s)
{
int n = sizeof(macro_token_list) / sizeof(token_t);
for ( int i = 0; i < n; ++i ) {
if ( 0 == stricmp(macro_token_list[i].token, s) ) {
return macro_token_list[i].value;
}
}
return INVALID_NUMBER;
}
int get_macro_arg_type(int cmd)
{
switch ( cmd & ~Q_PUSH_META ) {
case Q_KEY_PRESS:
case Q_KEY_MAKE:
case Q_KEY_RELEASE:
return MACRO_ARG_HID;
case Q_ASSIGN_META:
case Q_SET_META:
case Q_CLEAR_META:
case Q_TOGGLE_META:
return MACRO_ARG_META;
case Q_DELAY_MS:
return MACRO_ARG_DELAY;
case Q_NOP:
case Q_POP_META:
case Q_POP_ALL_META:
case Q_CLEAR_ALL:
case Q_BOOT:
return MACRO_ARG_NONE;
default:
return INVALID_NUMBER;
}
}
+30
View File
@@ -0,0 +1,30 @@
#ifndef __MACRO_TOKENS_H__
#define __MACRO_TOKENS_H__
enum queue_command_t {
Q_NOP = 0, // value = ignored
Q_KEY_PRESS = 1, // value = hid code
Q_KEY_MAKE = 2, // value = hid code
Q_KEY_RELEASE = 3, // value = hid code
Q_ASSIGN_META = 4, // value = metas
Q_SET_META = 5, // value = metas
Q_CLEAR_META = 6, // value = metas
Q_TOGGLE_META = 7, // value = metas
Q_POP_META = 8, // value = ignored
Q_POP_ALL_META = 9, // value = ignored
Q_DELAY_MS = 10, // value = delay count
Q_CLEAR_ALL = 11, // value = ignored
Q_BOOT = 12, // value = ignored
Q_PUSH_META = 0x80, // can be or'ed with any other command
};
#define MACRO_ARG_NONE 0
#define MACRO_ARG_HID 1
#define MACRO_ARG_META 2
#define MACRO_ARG_DELAY 3
const char* lookup_macro_token(int value);
int lookup_macro_token(const char* s);
int get_macro_arg_type(int cmd);
#endif // __MACRO_TOKENS_H__
+62
View File
@@ -0,0 +1,62 @@
#ifndef __RAWHID_H__
#define __RAWHID_H__
#ifdef __cplusplus
extern "C" {
#endif
#ifdef _MSC_VER
#define RAWHIDFN __stdcall
#else
#define RAWHIDFN
#endif
// rawhid_open - open 1 or more devices
//
// Inputs:
// max = maximum number of devices to open
// vid = Vendor ID, or -1 if any
// pid = Product ID, or -1 if any
// usage_page = top level usage page, or -1 if any
// usage = top level usage number, or -1 if any
// Output:
// actual number of devices opened
//
int RAWHIDFN rawhid_open(int max, int vid, int pid, int usage_page, int usage);
// rawhid_recv - receive a packet
// Inputs:
// num = device to receive from (zero based)
// buf = buffer to receive packet
// len = buffer's size
// timeout = time to wait, in milliseconds
// Output:
// number of bytes received, or -1 on error
//
int RAWHIDFN rawhid_recv(int num, void *buf, int len, int timeout);
// rawhid_send - send a packet
// Inputs:
// num = device to transmit to (zero based)
// buf = buffer containing packet to send
// len = number of bytes to transmit
// timeout = time to wait, in milliseconds
// Output:
// number of bytes sent, or -1 on error
//
int RAWHIDFN rawhid_send(int num, void *buf, int len, int timeout);
// rawhid_close - close a device
//
// Inputs:
// num = device to close (zero based)
// Output
// (nothing)
//
void RAWHIDFN rawhid_close(int num);
#ifdef __cplusplus
};
#endif
#endif // __RAWHID_H__
+50
View File
@@ -0,0 +1,50 @@
#ifndef __RAWHID_DEFS_H__
#define __RAWHID_DEFS_H__
// enum settings_state_t {
// SS_IDLE,
// SS_WRITE_INIT,
// SS_WRITE,
// SS_WRITING,
// SS_WRITTEN,
// SS_READ,
// };
enum request_code_t {
RQ_INFO = 1,
RQ_WRITE = 2,
RQ_READ = 3,
RQ_BOOT = 4,
RQ_CONTINUATION = 0x80
};
enum response_code_t {
RC_ERROR = 1,
RC_OK = 2,
RC_READY = 3,
RC_COMPLETED = 4,
};
enum info_code_t {
IC_END = 0,
IC_CODE_VERSION = 1,
IC_CONFIG_MAX_VERSION = 2,
IC_PROTOCOL_VERSION = 3,
IC_CONFIG_VERSION = 4,
IC_RAM_SIZE = 5,
IC_EEPROM_SIZE = 6,
IC_RAM_FREE = 7,
IC_EEPROM_FREE = 8,
};
#define PACKET_LEN 64
#define SC_VID 0x16C0
#define SC_PID 0x047D
#define SC_USAGE_PAGE 0xFF99
#define SC_USAGE 0x2468
#define PROTOCOL_VERSION_MAJOR 1
#define PROTOCOL_VERSION_MINOR 0
#endif // __RAWHID_DEFS_H__
BIN
View File
Binary file not shown.
+6
View File
@@ -0,0 +1,6 @@
PJRC rawhid code, adapted to build a DLL using the Microsoft Device Driver Kit (DDK).
The DDK version used was 3790.1830, obtained from:
http://download.microsoft.com/download/9/0/f/90f019ac-8243-48d3-91cf-81fc4093ecfd/1830_usa_ddk.iso
Original PJRC code can be found in PJRC_rawhid.
+53
View File
@@ -0,0 +1,53 @@
OS = LINUX
#OS = MACOSX
#OS = WINDOWS
PROG = rawhid_test
ifeq ($(OS), LINUX)
TARGET = $(PROG)
CC = gcc
STRIP = strip
CFLAGS = -Wall -O2 -DOS_$(OS)
LIBS = -lusb
else ifeq ($(OS), MACOSX)
TARGET = $(PROG).dmg
SDK = /Developer/SDKs/MacOSX10.5.sdk
ARCH = -mmacosx-version-min=10.5 -arch ppc -arch i386
CC = gcc
STRIP = strip
CFLAGS = -Wall -O2 -DOS_$(OS) -isysroot $(SDK) $(ARCH)
LIBS = $(ARCH) -Wl,-syslibroot,$(SDK) -framework IOKit -framework CoreFoundation
else ifeq ($(OS), WINDOWS)
TARGET = $(PROG).exe
CC = i586-mingw32msvc-gcc
STRIP = i586-mingw32msvc-strip
CFLAGS = -Wall -O2 -DOS_$(OS)
LIBS = -lhid -lsetupapi
endif
OBJS = $(PROG).o hid.o
all: $(TARGET)
$(PROG): $(OBJS)
$(CC) -o $(PROG) $(OBJS) $(LIBS)
$(STRIP) $(PROG)
$(PROG).exe: $(PROG)
cp $(PROG) $(PROG).exe
$(PROG).dmg: $(PROG)
mkdir tmp
cp $(PROG) tmp
hdiutil create -ov -volname "Raw HID Test" -srcfolder tmp $(PROG).dmg
hid.o: hid_$(OS).c hid.h
$(CC) $(CFLAGS) -c -o $@ $<
clean:
rm -f *.o $(PROG) $(PROG).exe $(PROG).dmg
rm -rf tmp
+6
View File
@@ -0,0 +1,6 @@
int rawhid_open(int max, int vid, int pid, int usage_page, int usage);
int rawhid_recv(int num, void *buf, int len, int timeout);
int rawhid_send(int num, void *buf, int len, int timeout);
void rawhid_close(int num);
+340
View File
@@ -0,0 +1,340 @@
/* Simple Raw HID functions for Linux - for use with Teensy RawHID example
* http://www.pjrc.com/teensy/rawhid.html
* Copyright (c) 2009 PJRC.COM, LLC
*
* rawhid_open - open 1 or more devices
* rawhid_recv - receive a packet
* rawhid_send - send a packet
* rawhid_close - close a device
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above description, website URL and copyright notice and this permission
* notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Version 1.0: Initial Release
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <usb.h>
#include "hid.h"
#define printf(...) // comment this out for lots of info
// a list of all opened HID devices, so the caller can
// simply refer to them by number
typedef struct hid_struct hid_t;
static hid_t *first_hid = NULL;
static hid_t *last_hid = NULL;
struct hid_struct {
usb_dev_handle *usb;
int open;
int iface;
int ep_in;
int ep_out;
struct hid_struct *prev;
struct hid_struct *next;
};
// private functions, not intended to be used from outside this file
static void add_hid(hid_t *h);
static hid_t * get_hid(int num);
static void free_all_hid(void);
static void hid_close(hid_t *hid);
static int hid_parse_item(uint32_t *val, uint8_t **data, const uint8_t *end);
// rawhid_recv - receive a packet
// Inputs:
// num = device to receive from (zero based)
// buf = buffer to receive packet
// len = buffer's size
// timeout = time to wait, in milliseconds
// Output:
// number of bytes received, or -1 on error
//
int rawhid_recv(int num, void *buf, int len, int timeout)
{
hid_t *hid;
int r;
hid = get_hid(num);
if (!hid || !hid->open) return -1;
r = usb_interrupt_read(hid->usb, hid->ep_in, buf, len, timeout);
if (r >= 0) return r;
if (r == -110) return 0; // timeout
return -1;
}
// rawhid_send - send a packet
// Inputs:
// num = device to transmit to (zero based)
// buf = buffer containing packet to send
// len = number of bytes to transmit
// timeout = time to wait, in milliseconds
// Output:
// number of bytes sent, or -1 on error
//
int rawhid_send(int num, void *buf, int len, int timeout)
{
hid_t *hid;
hid = get_hid(num);
if (!hid || !hid->open) return -1;
if (hid->ep_out) {
return usb_interrupt_write(hid->usb, hid->ep_out, buf, len, timeout);
} else {
return usb_control_msg(hid->usb, 0x21, 9, 0, hid->iface, buf, len, timeout);
}
}
// rawhid_open - open 1 or more devices
//
// Inputs:
// max = maximum number of devices to open
// vid = Vendor ID, or -1 if any
// pid = Product ID, or -1 if any
// usage_page = top level usage page, or -1 if any
// usage = top level usage number, or -1 if any
// Output:
// actual number of devices opened
//
int rawhid_open(int max, int vid, int pid, int usage_page, int usage)
{
struct usb_bus *bus;
struct usb_device *dev;
struct usb_interface *iface;
struct usb_interface_descriptor *desc;
struct usb_endpoint_descriptor *ep;
usb_dev_handle *u;
uint8_t buf[1024], *p;
int i, n, len, tag, ep_in, ep_out, count=0, claimed;
uint32_t val=0, parsed_usage, parsed_usage_page;
hid_t *hid;
if (first_hid) free_all_hid();
printf("rawhid_open, max=%d\n", max);
if (max < 1) return 0;
usb_init();
usb_find_busses();
usb_find_devices();
for (bus = usb_get_busses(); bus; bus = bus->next) {
for (dev = bus->devices; dev; dev = dev->next) {
if (vid > 0 && dev->descriptor.idVendor != vid) continue;
if (pid > 0 && dev->descriptor.idProduct != pid) continue;
if (!dev->config) continue;
if (dev->config->bNumInterfaces < 1) continue;
printf("device: vid=%04X, pic=%04X, with %d iface\n",
dev->descriptor.idVendor,
dev->descriptor.idProduct,
dev->config->bNumInterfaces);
iface = dev->config->interface;
u = NULL;
claimed = 0;
for (i=0; i<dev->config->bNumInterfaces && iface; i++, iface++) {
desc = iface->altsetting;
if (!desc) continue;
printf(" type %d, %d, %d\n", desc->bInterfaceClass,
desc->bInterfaceSubClass, desc->bInterfaceProtocol);
if (desc->bInterfaceClass != 3) continue;
if (desc->bInterfaceSubClass != 0) continue;
if (desc->bInterfaceProtocol != 0) continue;
ep = desc->endpoint;
ep_in = ep_out = 0;
for (n = 0; n < desc->bNumEndpoints; n++, ep++) {
if (ep->bEndpointAddress & 0x80) {
if (!ep_in) ep_in = ep->bEndpointAddress & 0x7F;
printf(" IN endpoint %d\n", ep_in);
} else {
if (!ep_out) ep_out = ep->bEndpointAddress;
printf(" OUT endpoint %d\n", ep_out);
}
}
if (!ep_in) continue;
if (!u) {
u = usb_open(dev);
if (!u) {
printf(" unable to open device\n");
break;
}
}
printf(" hid interface (generic)\n");
if (usb_get_driver_np(u, i, (char *)buf, sizeof(buf)) >= 0) {
printf(" in use by driver \"%s\"\n", buf);
if (usb_detach_kernel_driver_np(u, i) < 0) {
printf(" unable to detach from kernel\n");
continue;
}
}
if (usb_claim_interface(u, i) < 0) {
printf(" unable claim interface %d\n", i);
continue;
}
len = usb_control_msg(u, 0x81, 6, 0x2200, i, (char *)buf, sizeof(buf), 250);
printf(" descriptor, len=%d\n", len);
if (len < 2) {
usb_release_interface(u, i);
continue;
}
p = buf;
parsed_usage_page = parsed_usage = 0;
while ((tag = hid_parse_item(&val, &p, buf + len)) >= 0) {
printf(" tag: %X, val %X\n", tag, val);
if (tag == 4) parsed_usage_page = val;
if (tag == 8) parsed_usage = val;
if (parsed_usage_page && parsed_usage) break;
}
if ((!parsed_usage_page) || (!parsed_usage) ||
(usage_page > 0 && parsed_usage_page != usage_page) ||
(usage > 0 && parsed_usage != usage)) {
usb_release_interface(u, i);
continue;
}
hid = (struct hid_struct *)malloc(sizeof(struct hid_struct));
if (!hid) {
usb_release_interface(u, i);
continue;
}
hid->usb = u;
hid->iface = i;
hid->ep_in = ep_in;
hid->ep_out = ep_out;
hid->open = 1;
add_hid(hid);
claimed++;
count++;
if (count >= max) return count;
}
if (u && !claimed) usb_close(u);
}
}
return count;
}
// rawhid_close - close a device
//
// Inputs:
// num = device to close (zero based)
// Output
// (nothing)
//
void rawhid_close(int num)
{
hid_t *hid;
hid = get_hid(num);
if (!hid || !hid->open) return;
hid_close(hid);
}
// Chuck Robey wrote a real HID report parser
// (chuckr@telenix.org) chuckr@chuckr.org
// http://people.freebsd.org/~chuckr/code/python/uhidParser-0.2.tbz
// this tiny thing only needs to extract the top-level usage page
// and usage, and even then is may not be truly correct, but it does
// work with the Teensy Raw HID example.
static int hid_parse_item(uint32_t *val, uint8_t **data, const uint8_t *end)
{
const uint8_t *p = *data;
uint8_t tag;
int table[4] = {0, 1, 2, 4};
int len;
if (p >= end) return -1;
if (p[0] == 0xFE) {
// long item, HID 1.11, 6.2.2.3, page 27
if (p + 5 >= end || p + p[1] >= end) return -1;
tag = p[2];
*val = 0;
len = p[1] + 5;
} else {
// short item, HID 1.11, 6.2.2.2, page 26
tag = p[0] & 0xFC;
len = table[p[0] & 0x03];
if (p + len + 1 >= end) return -1;
switch (p[0] & 0x03) {
case 3: *val = p[1] | (p[2] << 8) | (p[3] << 16) | (p[4] << 24); break;
case 2: *val = p[1] | (p[2] << 8); break;
case 1: *val = p[1]; break;
case 0: *val = 0; break;
}
}
*data += len + 1;
return tag;
}
static void add_hid(hid_t *h)
{
if (!first_hid || !last_hid) {
first_hid = last_hid = h;
h->next = h->prev = NULL;
return;
}
last_hid->next = h;
h->prev = last_hid;
h->next = NULL;
last_hid = h;
}
static hid_t * get_hid(int num)
{
hid_t *p;
for (p = first_hid; p && num > 0; p = p->next, num--) ;
return p;
}
static void free_all_hid(void)
{
hid_t *p, *q;
for (p = first_hid; p; p = p->next) {
hid_close(p);
}
p = first_hid;
while (p) {
q = p;
p = p->next;
free(q);
}
first_hid = last_hid = NULL;
}
static void hid_close(hid_t *hid)
{
hid_t *p;
int others=0;
usb_release_interface(hid->usb, hid->iface);
for (p = first_hid; p; p = p->next) {
if (p->open && p->usb == hid->usb) others++;
}
if (!others) usb_close(hid->usb);
hid->usb = NULL;
}
+409
View File
@@ -0,0 +1,409 @@
/* Simple Raw HID functions for Linux - for use with Teensy RawHID example
* http://www.pjrc.com/teensy/rawhid.html
* Copyright (c) 2009 PJRC.COM, LLC
*
* rawhid_open - open 1 or more devices
* rawhid_recv - receive a packet
* rawhid_send - send a packet
* rawhid_close - close a device
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above description, website URL and copyright notice and this permission
* notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Version 1.0: Initial Release
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/hid/IOHIDLib.h>
#include "hid.h"
#define BUFFER_SIZE 64
#define printf(...) // comment this out to get lots of info printed
// a list of all opened HID devices, so the caller can
// simply refer to them by number
typedef struct hid_struct hid_t;
typedef struct buffer_struct buffer_t;
static hid_t *first_hid = NULL;
static hid_t *last_hid = NULL;
struct hid_struct {
IOHIDDeviceRef ref;
int open;
uint8_t buffer[BUFFER_SIZE];
buffer_t *first_buffer;
buffer_t *last_buffer;
struct hid_struct *prev;
struct hid_struct *next;
};
struct buffer_struct {
struct buffer_struct *next;
uint32_t len;
uint8_t buf[BUFFER_SIZE];
};
// private functions, not intended to be used from outside this file
static void add_hid(hid_t *);
static hid_t * get_hid(int);
static void free_all_hid(void);
static void hid_close(hid_t *);
static void attach_callback(void *, IOReturn, void *, IOHIDDeviceRef);
static void detach_callback(void *, IOReturn, void *hid_mgr, IOHIDDeviceRef dev);
static void timeout_callback(CFRunLoopTimerRef, void *);
static void input_callback(void *, IOReturn, void *, IOHIDReportType,
uint32_t, uint8_t *, CFIndex);
// rawhid_recv - receive a packet
// Inputs:
// num = device to receive from (zero based)
// buf = buffer to receive packet
// len = buffer's size
// timeout = time to wait, in milliseconds
// Output:
// number of bytes received, or -1 on error
//
int rawhid_recv(int num, void *buf, int len, int timeout)
{
hid_t *hid;
buffer_t *b;
CFRunLoopTimerRef timer=NULL;
CFRunLoopTimerContext context;
int ret=0, timeout_occurred=0;
if (len < 1) return 0;
hid = get_hid(num);
if (!hid || !hid->open) return -1;
if ((b = hid->first_buffer) != NULL) {
if (len > b->len) len = b->len;
memcpy(buf, b->buf, len);
hid->first_buffer = b->next;
free(b);
return len;
}
memset(&context, 0, sizeof(context));
context.info = &timeout_occurred;
timer = CFRunLoopTimerCreate(NULL, CFAbsoluteTimeGetCurrent() +
(double)timeout / 1000.0, 0, 0, 0, timeout_callback, &context);
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopDefaultMode);
while (1) {
CFRunLoopRun();
if ((b = hid->first_buffer) != NULL) {
if (len > b->len) len = b->len;
memcpy(buf, b->buf, len);
hid->first_buffer = b->next;
free(b);
ret = len;
break;
}
if (!hid->open) {
printf("rawhid_recv, device not open\n");
ret = -1;
break;
}
if (timeout_occurred) break;
}
CFRunLoopTimerInvalidate(timer);
CFRelease(timer);
return ret;
}
static void input_callback(void *context, IOReturn ret, void *sender,
IOHIDReportType type, uint32_t id, uint8_t *data, CFIndex len)
{
buffer_t *n;
hid_t *hid;
printf("input_callback\n");
if (ret != kIOReturnSuccess || len < 1) return;
hid = context;
if (!hid || hid->ref != sender) return;
n = (buffer_t *)malloc(sizeof(buffer_t));
if (!n) return;
if (len > BUFFER_SIZE) len = BUFFER_SIZE;
memcpy(n->buf, data, len);
n->len = len;
n->next = NULL;
if (!hid->first_buffer || !hid->last_buffer) {
hid->first_buffer = hid->last_buffer = n;
} else {
hid->last_buffer->next = n;
hid->last_buffer = n;
}
CFRunLoopStop(CFRunLoopGetCurrent());
}
static void timeout_callback(CFRunLoopTimerRef timer, void *info)
{
printf("timeout_callback\n");
*(int *)info = 1;
CFRunLoopStop(CFRunLoopGetCurrent());
}
void output_callback(void *context, IOReturn ret, void *sender,
IOHIDReportType type, uint32_t id, uint8_t *data, CFIndex len)
{
printf("output_callback, r=%d\n", ret);
if (ret == kIOReturnSuccess) {
*(int *)context = len;
} else {
// timeout if not success?
*(int *)context = 0;
}
CFRunLoopStop(CFRunLoopGetCurrent());
}
// rawhid_send - send a packet
// Inputs:
// num = device to transmit to (zero based)
// buf = buffer containing packet to send
// len = number of bytes to transmit
// timeout = time to wait, in milliseconds
// Output:
// number of bytes sent, or -1 on error
//
int rawhid_send(int num, void *buf, int len, int timeout)
{
hid_t *hid;
int result=-100;
hid = get_hid(num);
if (!hid || !hid->open) return -1;
#if 1
#warning "Send timeout not implemented on MACOSX"
IOReturn ret = IOHIDDeviceSetReport(hid->ref, kIOHIDReportTypeOutput, 0, buf, len);
result = (ret == kIOReturnSuccess) ? len : -1;
#endif
#if 0
// No matter what I tried this never actually sends an output
// report and output_callback never gets called. Why??
// Did I miss something? This is exactly the same params as
// the sync call that works. Is it an Apple bug?
// (submitted to Apple on 22-sep-2009, problem ID 7245050)
//
IOHIDDeviceScheduleWithRunLoop(hid->ref, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
// should already be scheduled with run loop by attach_callback,
// sadly this doesn't make any difference either way
//
IOHIDDeviceSetReportWithCallback(hid->ref, kIOHIDReportTypeOutput,
0, buf, len, (double)timeout / 1000.0, output_callback, &result);
while (1) {
printf("enter run loop (send)\n");
CFRunLoopRun();
printf("leave run loop (send)\n");
if (result > -100) break;
if (!hid->open) {
result = -1;
break;
}
}
#endif
return result;
}
// rawhid_open - open 1 or more devices
//
// Inputs:
// max = maximum number of devices to open
// vid = Vendor ID, or -1 if any
// pid = Product ID, or -1 if any
// usage_page = top level usage page, or -1 if any
// usage = top level usage number, or -1 if any
// Output:
// actual number of devices opened
//
int rawhid_open(int max, int vid, int pid, int usage_page, int usage)
{
static IOHIDManagerRef hid_manager=NULL;
CFMutableDictionaryRef dict;
CFNumberRef num;
IOReturn ret;
hid_t *p;
int count=0;
if (first_hid) free_all_hid();
printf("rawhid_open, max=%d\n", max);
if (max < 1) return 0;
// Start the HID Manager
// http://developer.apple.com/technotes/tn2007/tn2187.html
if (!hid_manager) {
hid_manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
if (hid_manager == NULL || CFGetTypeID(hid_manager) != IOHIDManagerGetTypeID()) {
if (hid_manager) CFRelease(hid_manager);
return 0;
}
}
if (vid > 0 || pid > 0 || usage_page > 0 || usage > 0) {
// Tell the HID Manager what type of devices we want
dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
&kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
if (!dict) return 0;
if (vid > 0) {
num = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &vid);
CFDictionarySetValue(dict, CFSTR(kIOHIDVendorIDKey), num);
CFRelease(num);
}
if (pid > 0) {
num = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &pid);
CFDictionarySetValue(dict, CFSTR(kIOHIDProductIDKey), num);
CFRelease(num);
}
if (usage_page > 0) {
num = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage_page);
CFDictionarySetValue(dict, CFSTR(kIOHIDPrimaryUsagePageKey), num);
CFRelease(num);
}
if (usage > 0) {
num = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage);
CFDictionarySetValue(dict, CFSTR(kIOHIDPrimaryUsageKey), num);
CFRelease(num);
}
IOHIDManagerSetDeviceMatching(hid_manager, dict);
CFRelease(dict);
} else {
IOHIDManagerSetDeviceMatching(hid_manager, NULL);
}
// set up a callbacks for device attach & detach
IOHIDManagerScheduleWithRunLoop(hid_manager, CFRunLoopGetCurrent(),
kCFRunLoopDefaultMode);
IOHIDManagerRegisterDeviceMatchingCallback(hid_manager, attach_callback, NULL);
IOHIDManagerRegisterDeviceRemovalCallback(hid_manager, detach_callback, NULL);
ret = IOHIDManagerOpen(hid_manager, kIOHIDOptionsTypeNone);
if (ret != kIOReturnSuccess) {
IOHIDManagerUnscheduleFromRunLoop(hid_manager,
CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
CFRelease(hid_manager);
return 0;
}
printf("run loop\n");
// let it do the callback for all devices
while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true) == kCFRunLoopRunHandledSource) ;
// count up how many were added by the callback
for (p = first_hid; p; p = p->next) count++;
return count;
}
// rawhid_close - close a device
//
// Inputs:
// num = device to close (zero based)
// Output
// (nothing)
//
void rawhid_close(int num)
{
hid_t *hid;
hid = get_hid(num);
if (!hid || !hid->open) return;
hid_close(hid);
hid->open = 0;
}
static void add_hid(hid_t *h)
{
if (!first_hid || !last_hid) {
first_hid = last_hid = h;
h->next = h->prev = NULL;
return;
}
last_hid->next = h;
h->prev = last_hid;
h->next = NULL;
last_hid = h;
}
static hid_t * get_hid(int num)
{
hid_t *p;
for (p = first_hid; p && num > 0; p = p->next, num--) ;
return p;
}
static void free_all_hid(void)
{
hid_t *p, *q;
for (p = first_hid; p; p = p->next) {
hid_close(p);
}
p = first_hid;
while (p) {
q = p;
p = p->next;
free(q);
}
first_hid = last_hid = NULL;
}
static void hid_close(hid_t *hid)
{
if (!hid || !hid->open || !hid->ref) return;
IOHIDDeviceUnscheduleFromRunLoop(hid->ref, CFRunLoopGetCurrent( ), kCFRunLoopDefaultMode);
IOHIDDeviceClose(hid->ref, kIOHIDOptionsTypeNone);
hid->ref = NULL;
}
static void detach_callback(void *context, IOReturn r, void *hid_mgr, IOHIDDeviceRef dev)
{
hid_t *p;
printf("detach callback\n");
for (p = first_hid; p; p = p->next) {
if (p->ref == dev) {
p->open = 0;
CFRunLoopStop(CFRunLoopGetCurrent());
return;
}
}
}
static void attach_callback(void *context, IOReturn r, void *hid_mgr, IOHIDDeviceRef dev)
{
struct hid_struct *h;
printf("attach callback\n");
if (IOHIDDeviceOpen(dev, kIOHIDOptionsTypeNone) != kIOReturnSuccess) return;
h = (hid_t *)malloc(sizeof(hid_t));
if (!h) return;
memset(h, 0, sizeof(hid_t));
IOHIDDeviceScheduleWithRunLoop(dev, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
IOHIDDeviceRegisterInputReportCallback(dev, h->buffer, sizeof(h->buffer),
input_callback, h);
h->ref = dev;
h->open = 1;
add_hid(h);
}
+328
View File
@@ -0,0 +1,328 @@
/* Simple Raw HID functions for Windows - for use with Teensy RawHID example
* http://www.pjrc.com/teensy/rawhid.html
* Copyright (c) 2009 PJRC.COM, LLC
*
* rawhid_open - open 1 or more devices
* rawhid_recv - receive a packet
* rawhid_send - send a packet
* rawhid_close - close a device
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above description, website URL and copyright notice and this permission
* notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Version 1.0: Initial Release
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <windows.h>
#include <setupapi.h>
#include <ddk/hidsdi.h>
#include <ddk/hidclass.h>
#include "hid.h"
// a list of all opened HID devices, so the caller can
// simply refer to them by number
typedef struct hid_struct hid_t;
static hid_t *first_hid = NULL;
static hid_t *last_hid = NULL;
struct hid_struct {
HANDLE handle;
int open;
struct hid_struct *prev;
struct hid_struct *next;
};
static HANDLE rx_event=NULL;
static HANDLE tx_event=NULL;
static CRITICAL_SECTION rx_mutex;
static CRITICAL_SECTION tx_mutex;
// private functions, not intended to be used from outside this file
static void add_hid(hid_t *h);
static hid_t * get_hid(int num);
static void free_all_hid(void);
static void hid_close(hid_t *hid);
void print_win32_err(void);
// rawhid_recv - receive a packet
// Inputs:
// num = device to receive from (zero based)
// buf = buffer to receive packet
// len = buffer's size
// timeout = time to wait, in milliseconds
// Output:
// number of bytes received, or -1 on error
//
int rawhid_recv(int num, void *buf, int len, int timeout)
{
hid_t *hid;
unsigned char tmpbuf[516];
OVERLAPPED ov;
DWORD n, r;
if (sizeof(tmpbuf) < len + 1) return -1;
hid = get_hid(num);
if (!hid || !hid->open) return -1;
EnterCriticalSection(&rx_mutex);
ResetEvent(&rx_event);
memset(&ov, 0, sizeof(ov));
ov.hEvent = rx_event;
if (!ReadFile(hid->handle, tmpbuf, len + 1, NULL, &ov)) {
if (GetLastError() != ERROR_IO_PENDING) goto return_error;
r = WaitForSingleObject(rx_event, timeout);
if (r == WAIT_TIMEOUT) goto return_timeout;
if (r != WAIT_OBJECT_0) goto return_error;
}
if (!GetOverlappedResult(hid->handle, &ov, &n, FALSE)) goto return_error;
LeaveCriticalSection(&rx_mutex);
if (n <= 0) return -1;
n--;
if (n > len) n = len;
memcpy(buf, tmpbuf + 1, n);
return n;
return_timeout:
CancelIo(hid->handle);
LeaveCriticalSection(&rx_mutex);
return 0;
return_error:
print_win32_err();
LeaveCriticalSection(&rx_mutex);
return -1;
}
// rawhid_send - send a packet
// Inputs:
// num = device to transmit to (zero based)
// buf = buffer containing packet to send
// len = number of bytes to transmit
// timeout = time to wait, in milliseconds
// Output:
// number of bytes sent, or -1 on error
//
int rawhid_send(int num, void *buf, int len, int timeout)
{
hid_t *hid;
unsigned char tmpbuf[516];
OVERLAPPED ov;
DWORD n, r;
if (sizeof(tmpbuf) < len + 1) return -1;
hid = get_hid(num);
if (!hid || !hid->open) return -1;
EnterCriticalSection(&tx_mutex);
ResetEvent(&tx_event);
memset(&ov, 0, sizeof(ov));
ov.hEvent = tx_event;
tmpbuf[0] = 0;
memcpy(tmpbuf + 1, buf, len);
if (!WriteFile(hid->handle, tmpbuf, len + 1, NULL, &ov)) {
if (GetLastError() != ERROR_IO_PENDING) goto return_error;
r = WaitForSingleObject(tx_event, timeout);
if (r == WAIT_TIMEOUT) goto return_timeout;
if (r != WAIT_OBJECT_0) goto return_error;
}
if (!GetOverlappedResult(hid->handle, &ov, &n, FALSE)) goto return_error;
LeaveCriticalSection(&tx_mutex);
if (n <= 0) return -1;
return n - 1;
return_timeout:
CancelIo(hid->handle);
LeaveCriticalSection(&tx_mutex);
return 0;
return_error:
print_win32_err();
LeaveCriticalSection(&tx_mutex);
return -1;
}
// rawhid_open - open 1 or more devices
//
// Inputs:
// max = maximum number of devices to open
// vid = Vendor ID, or -1 if any
// pid = Product ID, or -1 if any
// usage_page = top level usage page, or -1 if any
// usage = top level usage number, or -1 if any
// Output:
// actual number of devices opened
//
int rawhid_open(int max, int vid, int pid, int usage_page, int usage)
{
GUID guid;
HDEVINFO info;
DWORD index=0, reqd_size;
SP_DEVICE_INTERFACE_DATA iface;
SP_DEVICE_INTERFACE_DETAIL_DATA *details;
HIDD_ATTRIBUTES attrib;
PHIDP_PREPARSED_DATA hid_data;
HIDP_CAPS capabilities;
HANDLE h;
BOOL ret;
hid_t *hid;
int count=0;
if (first_hid) free_all_hid();
if (max < 1) return 0;
if (!rx_event) {
rx_event = CreateEvent(NULL, TRUE, TRUE, NULL);
tx_event = CreateEvent(NULL, TRUE, TRUE, NULL);
InitializeCriticalSection(&rx_mutex);
InitializeCriticalSection(&tx_mutex);
}
HidD_GetHidGuid(&guid);
info = SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (info == INVALID_HANDLE_VALUE) return 0;
for (index=0; 1 ;index++) {
iface.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
ret = SetupDiEnumDeviceInterfaces(info, NULL, &guid, index, &iface);
if (!ret) return count;
SetupDiGetInterfaceDeviceDetail(info, &iface, NULL, 0, &reqd_size, NULL);
details = (SP_DEVICE_INTERFACE_DETAIL_DATA *)malloc(reqd_size);
if (details == NULL) continue;
memset(details, 0, reqd_size);
details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
ret = SetupDiGetDeviceInterfaceDetail(info, &iface, details,
reqd_size, NULL, NULL);
if (!ret) {
free(details);
continue;
}
h = CreateFile(details->DevicePath, GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
free(details);
if (h == INVALID_HANDLE_VALUE) continue;
attrib.Size = sizeof(HIDD_ATTRIBUTES);
ret = HidD_GetAttributes(h, &attrib);
//printf("vid: %4x\n", attrib.VendorID);
if (!ret || (vid > 0 && attrib.VendorID != vid) ||
(pid > 0 && attrib.ProductID != pid) ||
!HidD_GetPreparsedData(h, &hid_data)) {
CloseHandle(h);
continue;
}
if (!HidP_GetCaps(hid_data, &capabilities) ||
(usage_page > 0 && capabilities.UsagePage != usage_page) ||
(usage > 0 && capabilities.Usage != usage)) {
HidD_FreePreparsedData(hid_data);
CloseHandle(h);
continue;
}
HidD_FreePreparsedData(hid_data);
hid = (struct hid_struct *)malloc(sizeof(struct hid_struct));
if (!hid) {
CloseHandle(h);
continue;
}
hid->handle = h;
hid->open = 1;
add_hid(hid);
count++;
if (count >= max) return count;
}
return count;
}
// rawhid_close - close a device
//
// Inputs:
// num = device to close (zero based)
// Output
// (nothing)
//
void rawhid_close(int num)
{
hid_t *hid;
hid = get_hid(num);
if (!hid || !hid->open) return;
hid_close(hid);
}
static void add_hid(hid_t *h)
{
if (!first_hid || !last_hid) {
first_hid = last_hid = h;
h->next = h->prev = NULL;
return;
}
last_hid->next = h;
h->prev = last_hid;
h->next = NULL;
last_hid = h;
}
static hid_t * get_hid(int num)
{
hid_t *p;
for (p = first_hid; p && num > 0; p = p->next, num--) ;
return p;
}
static void free_all_hid(void)
{
hid_t *p, *q;
for (p = first_hid; p; p = p->next) {
hid_close(p);
}
p = first_hid;
while (p) {
q = p;
p = p->next;
free(q);
}
first_hid = last_hid = NULL;
}
static void hid_close(hid_t *hid)
{
CloseHandle(hid->handle);
hid->handle = NULL;
}
void print_win32_err(void)
{
char buf[256];
DWORD err;
err = GetLastError();
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err,
0, buf, sizeof(buf), NULL);
printf("err %ld: %s\n", err, buf);
}
Binary file not shown.
+95
View File
@@ -0,0 +1,95 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#if defined(OS_LINUX) || defined(OS_MACOSX)
#include <sys/ioctl.h>
#include <termios.h>
#elif defined(OS_WINDOWS)
#include <conio.h>
#endif
#include "hid.h"
static char get_keystroke(void);
int main()
{
int i, r, num;
char c, buf[64];
r = rawhid_open(1, 0x16C0, 0x0480, 0xFFAB, 0x0200);
if (r <= 0) {
printf("no rawhid device found\n");
return -1;
}
printf("found rawhid device\n");
while (1) {
// check if any Raw HID packet has arrived
num = rawhid_recv(0, buf, 64, 220);
if (num < 0) {
printf("\nerror reading, device went offline\n");
rawhid_close(0);
return 0;
}
if (num > 0) {
printf("\nrecv %d bytes:\n", num);
for (i=0; i<num; i++) {
printf("%02X ", buf[i] & 255);
if (i % 16 == 15 && i < num-1) printf("\n");
}
printf("\n");
}
// check if any input on stdin
while ((c = get_keystroke()) >= 32) {
printf("\ngot key '%c', sending...\n", c);
buf[0] = c;
for (i=1; i<64; i++) {
buf[i] = 0;
}
rawhid_send(0, buf, 64, 100);
}
}
}
#if defined(OS_LINUX) || defined(OS_MACOSX)
// Linux (POSIX) implementation of _kbhit().
// Morgan McGuire, morgan@cs.brown.edu
static int _kbhit() {
static const int STDIN = 0;
static int initialized = 0;
int bytesWaiting;
if (!initialized) {
// Use termios to turn off line buffering
struct termios term;
tcgetattr(STDIN, &term);
term.c_lflag &= ~ICANON;
tcsetattr(STDIN, TCSANOW, &term);
setbuf(stdin, NULL);
initialized = 1;
}
ioctl(STDIN, FIONREAD, &bytesWaiting);
return bytesWaiting;
}
static char _getch(void) {
char c;
if (fread(&c, 1, 1, stdin) < 1) return 0;
return c;
}
#endif
static char get_keystroke(void)
{
if (_kbhit()) {
char c = _getch();
if (c >= 32) return c;
}
return 0;
}
+70
View File
@@ -0,0 +1,70 @@
BUILD: Computing Include file dependencies:
BUILD: Examining d:\xtkbk\pjrc\usb_raw_hid\rawhid_lib directory for files to compile.
Compiling (NoSync) d:\xtkbk\pjrc\usb_raw_hid\rawhid_lib directory ********************
1>'nmake.exe /nologo BUILDMSG=Stop. -i NTTEST= UMTEST= NOLINK=1 NOPASS0=1 PASS1_NOLIB=1 386=1'
1>BUILDMSG: Processing d:\xtkbk\pjrc\usb_raw_hid\rawhid_lib
1>cl -nologo -Ii386\ -I. -IC:\WINDDK\3790~1.183\inc\mfc42 -IC:\WINDDK\3790~1.183\inc\ddk\wdm\wxp -Iobjfre_wxp_x86\i386 -IC:\WINDDK\3790~1.183\inc\wxp -IC:\WINDDK\3790~1.183\inc\wxp -IC:\WINDDK\3790~1.183\inc\crt -D_X86_=1 -Di386=1 -DSTD_CALL -DCONDITION_HANDLING=1 -DNT_INST=0 -DWIN32=100 -D_NT1X_=100 -DWINNT=1 -D_WIN32_WINNT=0x0501 /DWINVER=0x0501 -D_WIN32_IE=0x0603 -DWIN32_LEAN_AND_MEAN=1 -DDEVL=1 -D__BUILDMACHINE__=WinDDK -DFPO=0 -DNDEBUG -D_DLL=1 -D_MT=1 /c /Zl /Zp8 /Gy /Gm- /W3 /WX /WX /Gz /GX- /GR- /GF /GS /G6 /Ze /Gi- /QIfdiv- /hotpatch -Z7 /Oxs /Oy- -FIC:\WINDDK\3790~1.183\inc\wxp\warning.h .\hid_windows.c
1>hid_windows.c
1>
1>Stop.
Compiling d:\xtkbk\pjrc\usb_raw_hid\rawhid_lib directory ********************
100>'nmake.exe /nologo BUILDMSG=Stop. -i NTTEST= UMTEST= NOLINK=1 NOPASS0=1 386=1'
100>BUILDMSG: Processing d:\xtkbk\pjrc\usb_raw_hid\rawhid_lib
100> lib -out:objfre_wxp_x86\i386\rawhid.lib @C:\DOCUME~1\Jon\LOCALS~1\Temp\nm6C.tmp
100>Microsoft (R) Library Manager Version 7.10.4035
100>Copyright (C) Microsoft Corporation. All rights reserved.
100>
100>-IGNORE:4198,4010,4037,4039,4065,4070,4078,4087,4089,4221
100>/WX
100>-nodefaultlib
100>-machine:ix86
100>-def:rawhid.def
100>objfre_wxp_x86\i386\hid_windows.obj
100> Creating library objfre_wxp_x86\i386\rawhid.lib and object objfre_wxp_x86\i386\rawhid.exp
100>
100>Stop.
Linking d:\xtkbk\pjrc\usb_raw_hid\rawhid_lib directory ********************
1>'nmake.exe /nologo BUILDMSG=Stop. -i LINKONLY=1 NOPASS0=1 NTTEST= UMTEST= MAKEDLL=1 386=1'
1>BUILDMSG: Processing d:\xtkbk\pjrc\usb_raw_hid\rawhid_lib
1> link -out:objfre_wxp_x86\i386\rawhid.dll -machine:ix86 @C:\DOCUME~1\Jon\LOCALS~1\Temp\nm6D.tmp
1>Microsoft (R) Incremental Linker Version 7.10.4035
1>Copyright (C) Microsoft Corporation. All rights reserved.
1>
1>-MERGE:_PAGE=PAGE
1>-MERGE:_TEXT=.text
1>-SECTION:INIT,d
1>-OPT:REF
1>-OPT:ICF
1>-IGNORE:4198,4010,4037,4039,4065,4070,4078,4087,4089,4221
1>-INCREMENTAL:NO
1>-FULLBUILD
1>/release
1>-NODEFAULTLIB
1>/WX
1>-debug
1>-debugtype:cv
1>-version:5.1
1>-osversion:5.1
1>/functionpadmin:5
1>/safeseh
1>/opt:nowin98
1>-merge:.rdata=.text
1>/pdbcompress
1>-STACK:0x40000,0x1000
1>-dll
1>-base:@C:\WINDDK\3790~1.183\bin\coffbase.txt,rawhid
1>-subsystem:console,4.10
1>-entry:_DllMainCRTStartup@12
1>objfre_wxp_x86\i386\rawhid.exp
1>objfre_wxp_x86\i386\hid_windows.obj
1>C:\WINDDK\3790~1.183\lib\wxp\i386\BufferOverflowU.lib
1>C:\WINDDK\3790~1.183\lib\crt\i386\msvcrt.lib
1>C:\WINDDK\3790~1.183\lib\wxp\i386\ntdll.lib
1>C:\WINDDK\3790~1.183\lib\wxp\i386\hid.lib
1>C:\WINDDK\3790~1.183\lib\wxp\i386\setupapi.lib
1>C:\WINDDK\3790~1.183\lib\wxp\i386\Kernel32.lib
1>C:\WINDDK\3790~1.183\lib\wxp\i386\sehupd.lib
1> echo Skip Binplace:
1>Skip Binplace:
1>
1>Stop.
+4
View File
@@ -0,0 +1,4 @@
del /Q objfre_wxp_x86\i386\*.*
rd objfre_wxp_x86\i386
del /Q objfre_wxp_x86\*.*
rd objfre_wxp_x86
+328
View File
@@ -0,0 +1,328 @@
/* Simple Raw HID functions for Windows - for use with Teensy RawHID example
* http://www.pjrc.com/teensy/rawhid.html
* Copyright (c) 2009 PJRC.COM, LLC
*
* rawhid_open - open 1 or more devices
* rawhid_recv - receive a packet
* rawhid_send - send a packet
* rawhid_close - close a device
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above description, website URL and copyright notice and this permission
* notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Version 1.0: Initial Release
*/
#include <stdio.h>
#include <stdlib.h>
//#include <stdint.h>
#include <windows.h>
#include <setupapi.h>
#include <hidsdi.h>
#include <hidclass.h>
#include "rawhid.h"
// a list of all opened HID devices, so the caller can
// simply refer to them by number
typedef struct hid_struct hid_t;
static hid_t *first_hid = NULL;
static hid_t *last_hid = NULL;
struct hid_struct {
HANDLE handle;
int open;
struct hid_struct *prev;
struct hid_struct *next;
};
static HANDLE rx_event=NULL;
static HANDLE tx_event=NULL;
static CRITICAL_SECTION rx_mutex;
static CRITICAL_SECTION tx_mutex;
// private functions, not intended to be used from outside this file
static void add_hid(hid_t *h);
static hid_t * get_hid(int num);
static void free_all_hid(void);
static void hid_close(hid_t *hid);
void print_win32_err(void);
// rawhid_recv - receive a packet
// Inputs:
// num = device to receive from (zero based)
// buf = buffer to receive packet
// len = buffer's size
// timeout = time to wait, in milliseconds
// Output:
// number of bytes received, or -1 on error
//
int rawhid_recv(int num, void *buf, int len, int timeout)
{
hid_t *hid;
unsigned char tmpbuf[516];
OVERLAPPED ov;
DWORD n, r;
if (sizeof(tmpbuf) < len + 1) return -1;
hid = get_hid(num);
if (!hid || !hid->open) return -1;
EnterCriticalSection(&rx_mutex);
ResetEvent(&rx_event);
memset(&ov, 0, sizeof(ov));
ov.hEvent = rx_event;
if (!ReadFile(hid->handle, tmpbuf, len + 1, NULL, &ov)) {
if (GetLastError() != ERROR_IO_PENDING) goto return_error;
r = WaitForSingleObject(rx_event, timeout);
if (r == WAIT_TIMEOUT) goto return_timeout;
if (r != WAIT_OBJECT_0) goto return_error;
}
if (!GetOverlappedResult(hid->handle, &ov, &n, FALSE)) goto return_error;
LeaveCriticalSection(&rx_mutex);
if (n <= 0) return -1;
n--;
if (n > (DWORD)len) n = len;
memcpy(buf, tmpbuf + 1, n);
return n;
return_timeout:
CancelIo(hid->handle);
LeaveCriticalSection(&rx_mutex);
return 0;
return_error:
print_win32_err();
LeaveCriticalSection(&rx_mutex);
return -1;
}
// rawhid_send - send a packet
// Inputs:
// num = device to transmit to (zero based)
// buf = buffer containing packet to send
// len = number of bytes to transmit
// timeout = time to wait, in milliseconds
// Output:
// number of bytes sent, or -1 on error
//
int rawhid_send(int num, void *buf, int len, int timeout)
{
hid_t *hid;
unsigned char tmpbuf[516];
OVERLAPPED ov;
DWORD n, r;
if (sizeof(tmpbuf) < len + 1) return -1;
hid = get_hid(num);
if (!hid || !hid->open) return -1;
EnterCriticalSection(&tx_mutex);
ResetEvent(&tx_event);
memset(&ov, 0, sizeof(ov));
ov.hEvent = tx_event;
tmpbuf[0] = 0;
memcpy(tmpbuf + 1, buf, len);
if (!WriteFile(hid->handle, tmpbuf, len + 1, NULL, &ov)) {
if (GetLastError() != ERROR_IO_PENDING) goto return_error;
r = WaitForSingleObject(tx_event, timeout);
if (r == WAIT_TIMEOUT) goto return_timeout;
if (r != WAIT_OBJECT_0) goto return_error;
}
if (!GetOverlappedResult(hid->handle, &ov, &n, FALSE)) goto return_error;
LeaveCriticalSection(&tx_mutex);
if (n <= 0) return -1;
return n - 1;
return_timeout:
CancelIo(hid->handle);
LeaveCriticalSection(&tx_mutex);
return 0;
return_error:
print_win32_err();
LeaveCriticalSection(&tx_mutex);
return -1;
}
// rawhid_open - open 1 or more devices
//
// Inputs:
// max = maximum number of devices to open
// vid = Vendor ID, or -1 if any
// pid = Product ID, or -1 if any
// usage_page = top level usage page, or -1 if any
// usage = top level usage number, or -1 if any
// Output:
// actual number of devices opened
//
int rawhid_open(int max, int vid, int pid, int usage_page, int usage)
{
GUID guid;
HDEVINFO info;
DWORD index=0, reqd_size;
SP_DEVICE_INTERFACE_DATA iface;
SP_DEVICE_INTERFACE_DETAIL_DATA *details;
HIDD_ATTRIBUTES attrib;
PHIDP_PREPARSED_DATA hid_data;
HIDP_CAPS capabilities;
HANDLE h;
BOOL ret;
hid_t *hid;
int count=0;
if (first_hid) free_all_hid();
if (max < 1) return 0;
if (!rx_event) {
rx_event = CreateEvent(NULL, TRUE, TRUE, NULL);
tx_event = CreateEvent(NULL, TRUE, TRUE, NULL);
InitializeCriticalSection(&rx_mutex);
InitializeCriticalSection(&tx_mutex);
}
HidD_GetHidGuid(&guid);
info = SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (info == INVALID_HANDLE_VALUE) return 0;
for (index=0; 1 ;index++) {
iface.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
ret = SetupDiEnumDeviceInterfaces(info, NULL, &guid, index, &iface);
if (!ret) return count;
SetupDiGetInterfaceDeviceDetail(info, &iface, NULL, 0, &reqd_size, NULL);
details = (SP_DEVICE_INTERFACE_DETAIL_DATA *)malloc(reqd_size);
if (details == NULL) continue;
memset(details, 0, reqd_size);
details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
ret = SetupDiGetDeviceInterfaceDetail(info, &iface, details,
reqd_size, NULL, NULL);
if (!ret) {
free(details);
continue;
}
h = CreateFile(details->DevicePath, GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
free(details);
if (h == INVALID_HANDLE_VALUE) continue;
attrib.Size = sizeof(HIDD_ATTRIBUTES);
ret = HidD_GetAttributes(h, &attrib);
//printf("vid: %4x\n", attrib.VendorID);
if (!ret || (vid > 0 && attrib.VendorID != vid) ||
(pid > 0 && attrib.ProductID != pid) ||
!HidD_GetPreparsedData(h, &hid_data)) {
CloseHandle(h);
continue;
}
if (!HidP_GetCaps(hid_data, &capabilities) ||
(usage_page > 0 && capabilities.UsagePage != usage_page) ||
(usage > 0 && capabilities.Usage != usage)) {
HidD_FreePreparsedData(hid_data);
CloseHandle(h);
continue;
}
HidD_FreePreparsedData(hid_data);
hid = (struct hid_struct *)malloc(sizeof(struct hid_struct));
if (!hid) {
CloseHandle(h);
continue;
}
hid->handle = h;
hid->open = 1;
add_hid(hid);
count++;
if (count >= max) return count;
}
return count;
}
// rawhid_close - close a device
//
// Inputs:
// num = device to close (zero based)
// Output
// (nothing)
//
void rawhid_close(int num)
{
hid_t *hid;
hid = get_hid(num);
if (!hid || !hid->open) return;
hid_close(hid);
}
static void add_hid(hid_t *h)
{
if (!first_hid || !last_hid) {
first_hid = last_hid = h;
h->next = h->prev = NULL;
return;
}
last_hid->next = h;
h->prev = last_hid;
h->next = NULL;
last_hid = h;
}
static hid_t * get_hid(int num)
{
hid_t *p;
for (p = first_hid; p && num > 0; p = p->next, num--) ;
return p;
}
static void free_all_hid(void)
{
hid_t *p, *q;
for (p = first_hid; p; p = p->next) {
hid_close(p);
}
p = first_hid;
while (p) {
q = p;
p = p->next;
free(q);
}
first_hid = last_hid = NULL;
}
static void hid_close(hid_t *hid)
{
CloseHandle(hid->handle);
hid->handle = NULL;
}
void print_win32_err(void)
{
char buf[256];
DWORD err;
err = GetLastError();
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err,
0, buf, sizeof(buf), NULL);
printf("err %ld: %s\n", err, buf);
}
+18
View File
@@ -0,0 +1,18 @@
#############################################################################
#
# Copyright (C) Microsoft Corporation 1995 - 1998
# All Rights Reserved.
#
# MAKEFILE for HIDGAME directory
#
#############################################################################
#
# DO NOT EDIT THIS FILE!!! Edit .\sources. if you want to add a new source
# file to this component. This file merely indirects to the real make file
# that is shared by all the driver components of the Windows NT DDK
#
!INCLUDE $(NTMAKEENV)\makefile.def
+20
View File
@@ -0,0 +1,20 @@
MUI_386_OBJECTS=
386_OBJECTS= \
$(_OBJ_DIR)\i386\hid_windows.obj
MUI_IA64_OBJECTS=
IA64_OBJECTS= \
$(_OBJ_DIR)\ia64\hid_windows.obj
MUI_AMD64_OBJECTS=
AMD64_OBJECTS= \
$(_OBJ_DIR)\amd64\hid_windows.obj
MUI_ARM_OBJECTS=
ARM_OBJECTS= \
$(_OBJ_DIR)\arm\hid_windows.obj
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+5
View File
@@ -0,0 +1,5 @@
EXPORTS
rawhid_open
rawhid_recv
rawhid_send
rawhid_close
+6
View File
@@ -0,0 +1,6 @@
LIBRARY rawhid
EXPORTS
rawhid_open @1
rawhid_recv @2
rawhid_send @3
rawhid_close @4
+48
View File
@@ -0,0 +1,48 @@
#ifndef __RAWHID_H__
#define __RAWHID_H__
// rawhid_open - open 1 or more devices
//
// Inputs:
// max = maximum number of devices to open
// vid = Vendor ID, or -1 if any
// pid = Product ID, or -1 if any
// usage_page = top level usage page, or -1 if any
// usage = top level usage number, or -1 if any
// Output:
// actual number of devices opened
//
int __stdcall rawhid_open(int max, int vid, int pid, int usage_page, int usage);
// rawhid_recv - receive a packet
// Inputs:
// num = device to receive from (zero based)
// buf = buffer to receive packet
// len = buffer's size
// timeout = time to wait, in milliseconds
// Output:
// number of bytes received, or -1 on error
//
int __stdcall rawhid_recv(int num, void *buf, int len, int timeout);
// rawhid_send - send a packet
// Inputs:
// num = device to transmit to (zero based)
// buf = buffer containing packet to send
// len = number of bytes to transmit
// timeout = time to wait, in milliseconds
// Output:
// number of bytes sent, or -1 on error
//
int __stdcall rawhid_send(int num, void *buf, int len, int timeout);
// rawhid_close - close a device
//
// Inputs:
// num = device to close (zero based)
// Output
// (nothing)
//
void __stdcall rawhid_close(int num);
#endif // __RAWHID_H__
+20
View File
@@ -0,0 +1,20 @@
TARGETNAME=rawhid
TARGETTYPE=DYNLINK
TARGETPATH=obj
#UMTYPE=console
#UMENTRY=main
MSC_WARNING_LEVEL=/W3 /WX
TARGETLIBS=$(SDK_LIB_PATH)\hid.lib $(SDK_LIB_PATH)\setupapi.lib $(SDK_LIB_PATH)\Kernel32.lib
INCLUDES=$(WDM_INC_PATH)
#C_DEFINES=-DRAWHID_EXPORTS
USE_MSVCRT=1
SOURCES=hid_WINDOWS.c
i386_SOURCES=
+8
View File
@@ -0,0 +1,8 @@
PROG = scas
OBJS = $(PROG).o ../common/hid_tokens.o ../common/macro_tokens.o
include ../build/Makefile_prog.inc
+910
View File
@@ -0,0 +1,910 @@
// scas.cpp - config file assembler for Soarer's Keyboard Converter.
#include "../common/global.h"
#include "../common/hid_tokens.h"
#include "../common/macro_tokens.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <vector>
#include <utility>
#include <string>
using namespace std;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
#define SETTINGS_VERSION_MAJOR 1
#define SETTINGS_VERSION_MINOR 1
#define COMMENT_CHAR '#'
#define ERR_FILE_NOT_FOUND 1
#define ERR_INVALID_COMMAND 2
#define ERR_INVALID_ARGS 3
#define ERR_NOT_IMPLEMENTED 4
#define ERR_BLOCK_TOO_LARGE 5
#define ERR_MACRO_TOO_LONG 6
#define ERR_FILE_WRITE 7
void print_error(int err)
{
switch ( err ) {
case ERR_FILE_NOT_FOUND: fprintf(stderr, "file not found\n"); break;
case ERR_INVALID_COMMAND: fprintf(stderr, "invalid command\n"); break;
case ERR_INVALID_ARGS: fprintf(stderr, "invalid argument\n"); break;
case ERR_NOT_IMPLEMENTED: fprintf(stderr, "not implemented\n"); break;
case ERR_BLOCK_TOO_LARGE: fprintf(stderr, "block too large\n"); break;
case ERR_MACRO_TOO_LONG: fprintf(stderr, "macro too long\n"); break;
default: fprintf(stderr, "unknown error\n"); break;
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
const char* skip_whitespace(const char* p)
{
while ( isspace(*p) ) {
++p;
}
return p;
}
const char* skip_non_whitespace(const char* p)
{
while ( *p && !isspace(*p) ) {
++p;
}
return p;
}
const char* skip_digit(const char* p)
{
while ( isdigit(*p) ) {
++p;
}
return p;
}
const char* match(const char* s1, const char* s2)
{
size_t len = strlen(s1);
if ( 0 == strnicmp(s1, s2, len) ) {
return s2 + len;
}
return 0;
}
const char* skip_to_end_quote(const char* p)
{
if ( *p == '\"' ) {
return p;
}
while ( *p ) {
if ( *p == '\"' && *(p-1) != '\\' ) {
break;
}
++p;
}
return p;
}
const char* skip_token(const char* p)
{
p = skip_whitespace(p);
if ( *p == '\"' ) {
++p;
p = skip_to_end_quote(p);
if ( *p == '\"' ) {
++p;
}
} else {
p = skip_non_whitespace(p);
}
p = skip_whitespace(p);
return p;
}
string get_token(const char* p)
{
p = skip_whitespace(p);
const char* p2;
if ( *p == '\"' ) {
++p;
p2 = skip_to_end_quote(p);
} else {
p2 = skip_non_whitespace(p);
}
return string(p, p2);
}
int parse_int(const char* args)
{
args = skip_whitespace(args);
if ( isdigit(*args) ) {
return atoi(args);
}
return INVALID_NUMBER;
}
int parse_int(const char* args, int minval, int maxval)
{
int v = parse_int(args);
if ( minval <= v && v <= maxval ) {
return v;
}
return INVALID_NUMBER;
}
int parse_hid(const char* args)
{
string t = get_token(args);
return lookup_hid_token(t.c_str());
/*
const char* p2 = skip_non_whitespace(args);
char c = *p2;
if ( c ) {
*p2 = 0;
}
int hid = lookup_hid_token(args);
if ( c ) {
*p2 = c;
}
return hid;
*/
}
bool parse_meta_match(const char* args, int& desired_meta, int& matched_meta)
{
desired_meta = 0;
matched_meta = 0;
const char* p = args;
while ( *p ) {
bool inverted = false;
if ( *p == '-' ) {
inverted = true;
++p;
}
string t = get_token(p);
int meta = lookup_meta_token(t.c_str());
if ( meta == INVALID_NUMBER ) {
return false;
}
if ( inverted ) {
desired_meta &= ~meta;
matched_meta |= meta;
} else {
desired_meta |= meta;
if ( is_meta_handed(meta) ) {
matched_meta |= meta;
} else {
matched_meta |= (meta & 0x0F);
}
}
p = skip_token(p);
}
return true;
}
int parse_meta_handed(const char* p)
{
int val = 0;
while ( *p ) {
string t = get_token(p);
int meta = lookup_meta_token(t.c_str());
if ( meta == INVALID_NUMBER /*|| !is_meta_handed(meta)*/ ) {
return INVALID_NUMBER;
}
val |= meta;
p = skip_token(p);
}
return val;
}
bool parse_macro_cmd(const char* args, int& cmd, int& val)
{
string t = get_token(args);
cmd = lookup_macro_token(t.c_str());
if ( cmd == INVALID_NUMBER ) {
return false;
}
const char* p = skip_token(args);
// todo: Q_PLAY
if ( cmd == Q_PUSH_META ) {
t = get_token(p);
int q = lookup_macro_token(t.c_str());
if ( q == INVALID_NUMBER ) {
return false;
}
cmd |= q;
p = skip_token(p);
}
t = get_token(p);
//char* p2 = p;
int argtype = get_macro_arg_type(cmd);
switch ( argtype ) {
case MACRO_ARG_HID:
val = lookup_hid_token(t.c_str());
//p2 = skip_token(p);
break;
case MACRO_ARG_META:
val = parse_meta_handed(p);
////p2 = next_token(p);
break;
case MACRO_ARG_DELAY:
val = parse_int(t.c_str(), 0, 255);
//p2 = skip_token(p);
break;
case MACRO_ARG_NONE:
val = 0;
break;
}
return val != INVALID_NUMBER;
}
int lookup_set_token(const char* t)
{
if ( 0 == stricmp(t, "set1") ) {
return 1;
} else if ( 0 == stricmp(t, "set2") ) {
return 2;
} else if ( 0 == stricmp(t, "set3") ) {
return 3;
} else if ( 0 == stricmp(t, "set2ext") ) {
return 4;
} else if ( 0 == stricmp(t, "any") ) {
return 0;
}
return INVALID_NUMBER;
}
int parse_single_set(const char* p)
{
string t = get_token(p);
int s = lookup_set_token(t.c_str());
if ( s == INVALID_NUMBER ) {
return INVALID_NUMBER;
}
return s;
}
int parse_multi_set(const char* p)
{
int val = 0;
while ( *p ) {
string t = get_token(p);
int s = lookup_set_token(t.c_str());
if ( s == INVALID_NUMBER ) {
return INVALID_NUMBER;
}
if ( s ) {
val |= 1 << (s - 1);
} else {
val = 0;
}
p = skip_token(p);
}
return val;
}
int parse_function_n(const char* p)
{
if ( 0 == strnicmp("fn", p, 2) ) {
p += 2;
if ( isdigit(*p) ) {
int v = atoi(p);
if ( 1 <= v && v <= 8 ) {
return v;
}
}
}
return INVALID_NUMBER;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
typedef int (*command_fn)(const char* args);
uint8_t current_force_flags = 0;
int cmd_force(const char* args)
{
int set = parse_single_set(args);
if ( set != INVALID_NUMBER ) {
current_force_flags = (current_force_flags & 0xF0) | (uint8_t)set;
return 0;
}
// todo: XT/AT force?
return ERR_INVALID_ARGS;
}
uint8_t current_select = 0;
int cmd_select(const char* args)
{
string t = get_token(args);
int s;
if ( 0 == stricmp(t.c_str(), "any") ) {
s = 0;
} else {
s = parse_int(args, 1, 7);
}
if ( s != INVALID_NUMBER ) {
current_select = (uint8_t)s;
return 0;
}
return ERR_INVALID_ARGS;
}
uint8_t current_scanset = 0;
int cmd_scanset(const char* args)
{
int s = parse_multi_set(args);
if ( s != INVALID_NUMBER ) {
current_scanset = (uint8_t)s;
return 0;
}
return ERR_INVALID_ARGS;
}
bool is_hex(char c)
{
c = (char)toupper(c);
return isdigit(c) || ('A' <= c && c <= 'F');
}
int parse_hex(char c)
{
c = (char)toupper(c);
if ( isdigit(c) ) {
return c - '0';
} else if ( 'A' <= c && c <= 'F' ) {
return c - 'A' + 10;
} else {
return INVALID_NUMBER;
}
}
int parse_hex(const char* p)
{
p = skip_whitespace(p);
int val = 0;
int digit = parse_hex(*p++);
if ( digit == INVALID_NUMBER ) {
return INVALID_NUMBER;
}
while ( digit != INVALID_NUMBER ) {
val = (val << 4) | digit;
digit = parse_hex(*p++);
}
return val;
}
int parse_hex(const char* p, int minval, int maxval)
{
int v = parse_hex(p);
if ( minval <= v && v <= maxval ) {
return v;
}
return INVALID_NUMBER;
}
uint16_t current_keyboard_id = 0;
int cmd_keyboard_id(const char* args)
{
string t = get_token(args);
if ( 0 == stricmp(t.c_str(), "any") ) {
current_keyboard_id = 0;
} else {
int v = parse_hex(args, 0, 0xFFFF);
if ( v == INVALID_NUMBER ) {
return ERR_INVALID_ARGS;
}
current_keyboard_id = (uint16_t)v;
}
return 0;
}
uint8_t current_layer = 0;
int cmd_layer(const char* args)
{
int v = parse_int(args, 0, 255);
if ( v != INVALID_NUMBER ) {
current_layer = (uint8_t)v;
return 0;
}
return ERR_INVALID_ARGS;
}
typedef pair<uint8_t, uint8_t> layerdef_pair;
typedef vector<layerdef_pair> layerdef_list_t;
layerdef_list_t layerdef_list;
int cmd_layerdef(const char* args)
{
int fn_combo = 0;
const char* p = skip_whitespace(args);
for ( ; *p; p = skip_token(p) ) {
int fn = parse_function_n(p);
if ( fn == INVALID_NUMBER ) {
break;
}
fn_combo |= 1 << (fn - 1);
}
if ( !fn_combo ) {
return ERR_INVALID_ARGS;
}
int layer = parse_int(p, 1, 255); // layer id
if ( layer == INVALID_NUMBER ) {
return ERR_INVALID_ARGS;
}
layerdef_list.push_back(layerdef_pair((uint8_t)fn_combo, (uint8_t)layer));
return 0;
}
typedef pair<uint8_t, uint8_t> remap_pair;
typedef vector<remap_pair> remap_list_t;
remap_list_t remap_list;
int cmd_remap(const char* args)
{
args = skip_whitespace(args);
int v1 = parse_hid(args);
if ( v1 != INVALID_NUMBER ) {
args = skip_token(args);
int v2 = parse_hid(args);
if ( v2 != INVALID_NUMBER ) {
remap_list.push_back(remap_pair((uint8_t)v1, (uint8_t)v2));
return 0;
}
}
return ERR_INVALID_ARGS;
}
int current_macro_phase = -1; // -1 = invalid, 0 = make, 1 = break
uint8_t current_macro_release_meta = 1;
uint8_t current_hid_code = 0;
uint8_t current_desired_meta = 0;
uint8_t current_matched_meta = 0;
int cmd_macro(const char* args)
{
string t = get_token(args);
int hid_code = lookup_hid_token(t.c_str());
if ( hid_code == INVALID_NUMBER ) {
return ERR_INVALID_ARGS;
}
int desired_meta, matched_meta;
if ( !parse_meta_match(skip_token(args), desired_meta, matched_meta) ) {
return ERR_INVALID_ARGS;
}
current_macro_phase = 0;
current_macro_release_meta = 1;
current_hid_code = (uint8_t)hid_code;
current_desired_meta = (uint8_t)desired_meta;
current_matched_meta = (uint8_t)matched_meta;
return 0;
}
/*
int cmd_meta(char* args)
{
int v = parse_int(args, 0, 255);
if ( v != INVALID_NUMBER ) {
current_desired_meta = (uint8_t)v;
return 0;
}
return ERR_INVALID_ARGS;
}
*/
/*
int cmd_ignore(char* args)
{
int v = parse_int(args, 0, 255);
if ( v != INVALID_NUMBER ) {
current_matched_meta = (uint8_t)v;
return 0;
}
return ERR_INVALID_ARGS;
}
*/
int cmd_onbreak(const char* args)
{
if ( current_macro_phase != 0 ) {
return ERR_INVALID_COMMAND;
}
current_macro_phase = 1;
string t = get_token(args);
if ( t == "" ) {
current_macro_release_meta = 1;
} else if ( 0 == stricmp(t.c_str(), "norestoremeta") ) {
current_macro_release_meta = 0;
} else {
return ERR_INVALID_ARGS;
}
return 0;
}
typedef pair<uint8_t, uint8_t> mcommand_pair;
typedef vector<mcommand_pair> mcommand_list_t;
mcommand_list_t press_mcommand_list;
mcommand_list_t release_mcommand_list;
/*
int cmd_press(char* args)
{
int cmd, val;
if ( parse_macro_cmd(args, cmd, val) ) {
press_mcommand_list.push_back(mcommand_pair((uint8_t)cmd, (uint8_t)val));
return 0;
}
return ERR_INVALID_ARGS;
}
int cmd_release(char* args)
{
int cmd, val;
if ( parse_macro_cmd(args, cmd, val) ) {
release_mcommand_list.push_back(mcommand_pair((uint8_t)cmd, (uint8_t)val));
return 0;
}
return ERR_INVALID_ARGS;
}
*/
int cmd_macrostep(const char* args)
{
int cmd, val;
if ( parse_macro_cmd(args, cmd, val) ) {
mcommand_pair mcp((uint8_t)cmd, (uint8_t)val);
if ( current_macro_phase == 0 ) {
press_mcommand_list.push_back(mcp);
} else {
release_mcommand_list.push_back(mcp);
}
return 0;
}
return ERR_INVALID_ARGS;
}
struct macro_t
{
uint8_t hid_code;
uint8_t desired_meta;
uint8_t matched_meta;
uint8_t press_flags;
uint8_t release_flags;
mcommand_list_t commands;
};
typedef vector<macro_t> macro_list_t;
macro_list_t macro_list;
int cmd_endmacro(const char* /*args*/)
{
if ( current_macro_phase == -1 ) {
return ERR_INVALID_COMMAND;
}
current_macro_phase = -1;
macro_t macro;
macro.hid_code = current_hid_code;
macro.desired_meta = current_desired_meta;
macro.matched_meta = current_matched_meta;
macro.press_flags = (uint8_t)press_mcommand_list.size();
macro.release_flags = (uint8_t)release_mcommand_list.size();
macro.release_flags |= current_macro_release_meta << 7;
if ( press_mcommand_list.size() > 63 || release_mcommand_list.size() > 63 ) {
return ERR_MACRO_TOO_LONG;
}
//macro.commands.push_back(press_mcommand_list);
macro.commands.insert(macro.commands.end(), press_mcommand_list.begin(), press_mcommand_list.end());
//macro.commands.push_back(release_mcommand_list);
macro.commands.insert(macro.commands.end(), release_mcommand_list.begin(), release_mcommand_list.end());
macro_list.push_back(macro);
press_mcommand_list.clear();
release_mcommand_list.clear();
return 0;
}
int block_type = BLOCK_NONE;
int cmd_layerdefblock(const char* /*args*/)
{
if ( block_type != BLOCK_NONE ) {
return ERR_INVALID_COMMAND;
}
block_type = BLOCK_LAYERDEF;
return 0;
}
int cmd_remapblock(const char* /*args*/)
{
if ( block_type != BLOCK_NONE ) {
return ERR_INVALID_COMMAND;
}
block_type = BLOCK_REMAP;
return 0;
}
int cmd_macroblock(const char* /*args*/)
{
if ( block_type != BLOCK_NONE ) {
return ERR_INVALID_COMMAND;
}
block_type = BLOCK_MACRO;
return 0;
}
int cmd_invalid(const char* args)
{
switch ( block_type ) {
case BLOCK_LAYERDEF: return cmd_layerdef(args);
case BLOCK_REMAP: return cmd_remap(args);
case BLOCK_MACRO: return cmd_macrostep(args);
default: return ERR_INVALID_COMMAND;
}
}
int process_file(const char* fname);
int cmd_include(const char* args)
{
string fname = get_token(args);
return process_file(fname.c_str());
}
typedef vector<uint8_t> block_t;
typedef vector<block_t> block_list_t;
block_list_t block_list;
void fill_block_header(block_t& block)
{
// common block header stuff...
block.push_back(0); // placeholder for size
uint8_t flags = (uint8_t)block_type;
flags |= current_select << 3;
flags |= (current_scanset != 0) << 6;
flags |= (current_keyboard_id != 0) << 7;
block.push_back(flags);
if ( current_scanset ) {
block.push_back(current_scanset);
}
if ( current_keyboard_id ) {
block.push_back((uint8_t)(current_keyboard_id & 0xFF));
block.push_back((uint8_t)((current_keyboard_id >> 8) & 0xFF));
}
}
int cmd_endlayerdefblock(const char* /*args*/)
{
block_t block;
fill_block_header(block);
block.push_back((uint8_t)layerdef_list.size());
for ( int i = 0; i < (int)layerdef_list.size(); ++i ) {
block.push_back(layerdef_list[i].first);
block.push_back(layerdef_list[i].second);
}
if ( block.size() > 255 ) {
return ERR_BLOCK_TOO_LARGE;
}
block[0] = (uint8_t)block.size();
block_list.push_back(block);
layerdef_list.clear();
block_type = BLOCK_NONE;
return 0;
}
int cmd_endremapblock(const char* /*args*/)
{
block_t block;
fill_block_header(block);
block.push_back(current_layer);
block.push_back((uint8_t)remap_list.size());
for ( int i = 0; i < (int)remap_list.size(); ++i ) {
block.push_back(remap_list[i].first);
block.push_back(remap_list[i].second);
}
if ( block.size() > 255 ) {
return ERR_BLOCK_TOO_LARGE;
}
block[0] = (uint8_t)block.size();
block_list.push_back(block);
remap_list.clear();
current_layer = 0;
block_type = BLOCK_NONE;
return 0;
}
int cmd_endmacroblock(const char* /*args*/)
{
block_t block;
fill_block_header(block);
block.push_back((uint8_t)macro_list.size());
for ( int i = 0; i < (int)macro_list.size(); ++i ) {
block.push_back(macro_list[i].hid_code);
block.push_back(macro_list[i].desired_meta);
block.push_back(macro_list[i].matched_meta);
block.push_back(macro_list[i].press_flags);
block.push_back(macro_list[i].release_flags);
for ( int j = 0; j < (int)macro_list[i].commands.size(); ++j ) {
block.push_back(macro_list[i].commands[j].first);
block.push_back(macro_list[i].commands[j].second);
}
}
if ( block.size() > 255 ) {
return ERR_BLOCK_TOO_LARGE;
}
block[0] = (uint8_t)block.size();
block_list.push_back(block);
macro_list.clear();
block_type = BLOCK_NONE;
return 0;
}
int cmd_endblock(const char* args)
{
switch ( block_type ) {
case BLOCK_LAYERDEF: return cmd_endlayerdefblock(args);
case BLOCK_REMAP: return cmd_endremapblock(args);
case BLOCK_MACRO: return cmd_endmacroblock(args);
default: return ERR_INVALID_COMMAND;
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
struct command_map_t
{
const char* cmd;
command_fn fn;
};
command_map_t command_map[] =
{
{ "force", cmd_force },
{ "ifselect", cmd_select },
{ "ifset", cmd_scanset },
{ "ifkeyboard", cmd_keyboard_id },
{ "layerblock", cmd_layerdefblock },
{ "remapblock", cmd_remapblock },
{ "layer", cmd_layer },
{ "macroblock", cmd_macroblock },
{ "macro", cmd_macro },
{ "onbreak", cmd_onbreak },
{ "endmacro", cmd_endmacro },
{ "endblock", cmd_endblock },
{ "include", cmd_include },
};
command_fn find_command(const char* cmd)
{
int n = sizeof(command_map) / sizeof(command_map_t);
for ( int i = 0; i < n; ++i ) {
if ( 0 == stricmp(cmd, command_map[i].cmd) ) {
return command_map[i].fn;
}
}
return cmd_invalid;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int process_line(char* linebuf)
{
char* pcomment = strchr(linebuf, COMMENT_CHAR);
if ( pcomment ) {
*pcomment = 0;
}
string t = get_token(linebuf);
if ( t.size() ) {
const char* p;
command_fn fn = find_command(t.c_str());
if ( fn != cmd_invalid ) {
p = skip_token(linebuf);
} else {
p = linebuf;
}
if ( int err = fn(p) ) {
return err;
}
}
// p = skip_whitespace(linebuf);
// char* p2 = skip_non_whitespace(p);
// if ( *p2 ) {
// *p2++ = 0;
// p2 = skip_whitespace(p2);
// if ( int err = find_command(p)(p2) ) {
// return err;
// }
// }
return 0;
}
int process_file(FILE* f)
{
int linenum = 0;
char linebuf[256];
while ( fgets(linebuf, sizeof(linebuf), f) ) {
++linenum;
if ( int err = process_line(linebuf) ) {
fprintf(stderr, "error at line %d: ", linenum);
return err;
}
}
return 0;
}
int process_file(const char* fname)
{
FILE* f = fopen(fname, "rt");
if ( f ) {
int retval = process_file(f);
fclose(f);
return retval;
}
return ERR_FILE_NOT_FOUND;
}
int write_target(FILE* f)
{
// Header...
fputc('S', f); // signature...
fputc('C', f);
fputc(SETTINGS_VERSION_MAJOR, f);
fputc(SETTINGS_VERSION_MINOR, f);
fputc(current_force_flags, f);
fputc(0, f); // reserved
// Blocks...
for ( int i = 0; i < (int)block_list.size(); ++i ) {
if ( !fwrite(&(block_list[i][0]), block_list[i].size(), 1, f) ) {
return ERR_FILE_WRITE;
}
}
return 0;
}
int write_target(const char* fname)
{
FILE* f = fopen(fname, "wb");
if ( f ) {
int retval = write_target(f);
fclose(f);
return retval;
}
return ERR_FILE_WRITE;
}
int main(int argc, char** argv)
{
printf("scas v1.10\n");
int err = 0;
if ( argc < 3 ) {
fprintf(stderr, "usage: scas <text_config> [<text_config> ...] <binary_config>\n");
err = 1;
}
for ( int i = 1; i < argc - 1; ++i ) {
err = process_file(argv[i]);
if ( err ) {
print_error(err);
}
}
if ( !err ) {
err = write_target(argv[argc - 1]);
if ( err ) {
fprintf(stderr, "unable to write to file: %s\n", argv[argc - 1]);
}
}
if ( !err ) {
fprintf(stderr, "No errors. Wrote: %s\n", argv[argc - 1]);
}
return err ? 1 : 0;
}
+21
View File
@@ -0,0 +1,21 @@
Microsoft Visual Studio Solution File, Format Version 8.00
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "scas", "scas.vcproj", "{6BD9A7D9-B220-49FF-B527-45C04DBBDA9A}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
Debug = Debug
Release = Release
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{6BD9A7D9-B220-49FF-B527-45C04DBBDA9A}.Debug.ActiveCfg = Debug|Win32
{6BD9A7D9-B220-49FF-B527-45C04DBBDA9A}.Debug.Build.0 = Debug|Win32
{6BD9A7D9-B220-49FF-B527-45C04DBBDA9A}.Release.ActiveCfg = Release|Win32
{6BD9A7D9-B220-49FF-B527-45C04DBBDA9A}.Release.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal
+147
View File
@@ -0,0 +1,147 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="scas"
ProjectGUID="{6BD9A7D9-B220-49FF-B527-45C04DBBDA9A}"
Keyword="Win32Proj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="Debug"
IntermediateDirectory="Debug"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
MinimalRebuild="TRUE"
BasicRuntimeChecks="3"
RuntimeLibrary="5"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="4"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/scas.exe"
LinkIncremental="2"
GenerateDebugInformation="TRUE"
ProgramDatabaseFile="$(OutDir)/scas.pdb"
SubSystem="1"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="../bin"
IntermediateDirectory="Release"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
RuntimeLibrary="4"
UsePrecompiledHeader="0"
WarningLevel="4"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="3"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/scas.exe"
LinkIncremental="1"
GenerateDebugInformation="FALSE"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
<File
RelativePath="..\common\hid_tokens.cpp">
</File>
<File
RelativePath="..\common\macro_tokens.cpp">
</File>
<File
RelativePath=".\scas.cpp">
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
<File
RelativePath="..\common\global.h">
</File>
<File
RelativePath="..\common\hid_tokens.h">
</File>
<File
RelativePath="..\common\macro_tokens.h">
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}">
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
+8
View File
@@ -0,0 +1,8 @@
PROG = scboot
OBJS = $(PROG).o
include ../build/Makefile_hidprog.inc
+67
View File
@@ -0,0 +1,67 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <memory.h>
#include "../common/rawhid.h"
#include "../common/rawhid_defs.h"
typedef unsigned char u_char;
int do_boot()
{
u_char hbuf[64];
int err = 0;
if ( !err ) {
printf("scboot: sending boot request: ");
hbuf[0] = RQ_BOOT;
if ( 64 != rawhid_send(0, hbuf, 64, 100) ) {
err = 2;
printf("failed\n");
} else {
printf("ok\n");
}
}
if ( !err ) {
printf("device: ");
if ( 64 != rawhid_recv(0, hbuf, 64, 220) ) {
err = 3;
printf("failed to respond\n");
}
}
if ( !err ) {
if ( hbuf[0] != RC_OK ) {
err = 4;
printf("not ok\n");
} else {
printf("ok\n");
}
}
return err;
}
int main(int argc, char** argv)
{
printf("scboot v1.10\n");
if ( argc != 1 ) {
fprintf(stderr, "usage: scboot\n");
return 0;
}
printf("scboot: looking for Soarer\'s Converter: ");
int r = rawhid_open(1, SC_VID, SC_PID, SC_USAGE_PAGE, SC_USAGE);
if (r <= 0) {
printf("not found\n");
return -1;
}
printf("found\n");
int err = do_boot();
if ( err ) {
//printf("\nerror %d\n", err);
}
rawhid_close(0);
return 0;
}
+21
View File
@@ -0,0 +1,21 @@
Microsoft Visual Studio Solution File, Format Version 8.00
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "scboot", "scboot.vcproj", "{9ED4BD6A-E53F-4CB0-9057-3F45F9570B2B}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
Debug = Debug
Release = Release
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{9ED4BD6A-E53F-4CB0-9057-3F45F9570B2B}.Debug.ActiveCfg = Debug|Win32
{9ED4BD6A-E53F-4CB0-9057-3F45F9570B2B}.Debug.Build.0 = Debug|Win32
{9ED4BD6A-E53F-4CB0-9057-3F45F9570B2B}.Release.ActiveCfg = Release|Win32
{9ED4BD6A-E53F-4CB0-9057-3F45F9570B2B}.Release.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal
+147
View File
@@ -0,0 +1,147 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="scboot"
ProjectGUID="{9ED4BD6A-E53F-4CB0-9057-3F45F9570B2B}"
Keyword="Win32Proj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="Debug"
IntermediateDirectory="Debug"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
MinimalRebuild="TRUE"
BasicRuntimeChecks="3"
RuntimeLibrary="5"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="4"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/scboot.exe"
LinkIncremental="2"
GenerateDebugInformation="TRUE"
ProgramDatabaseFile="$(OutDir)/scboot.pdb"
SubSystem="1"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="../bin"
IntermediateDirectory="Release"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
RuntimeLibrary="4"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="3"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/scboot.exe"
LinkIncremental="1"
GenerateDebugInformation="FALSE"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
<File
RelativePath=".\scboot.c">
<FileConfiguration
Name="Debug|Win32">
<Tool
Name="VCCLCompilerTool"
CompileAs="2"/>
</FileConfiguration>
<FileConfiguration
Name="Release|Win32">
<Tool
Name="VCCLCompilerTool"
CompileAs="2"/>
</FileConfiguration>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}">
</Filter>
<File
RelativePath="..\lib\rawhid.lib">
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
+8
View File
@@ -0,0 +1,8 @@
PROG = scdis
OBJS = ../common/hid_tokens.o ../common/macro_tokens.o $(PROG).o
include ../build/Makefile_prog.inc
+376
View File
@@ -0,0 +1,376 @@
// scdis.cpp - config file disassembler for Soarer's Keyboard Converter.
#include "../common/global.h"
#include "../common/hid_tokens.h"
#include "../common/macro_tokens.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <vector>
#include <utility>
#include <string>
using namespace std;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
FILE* fout = stdout;
const char* get_force_set(uint8_t force)
{
static const char* sets[] = { "set1", "set2", "set3", "set2ext" };
uint8_t force_set = force & 0x0F;
if ( 1 <= force_set && force_set <= 4 ) {
return sets[force_set - 1];
}
return "ERROR";
}
const char* get_force_protocol(uint8_t force)
{
static const char* protocols[] = { "xt", "at" };
uint8_t force_protocol = (force & 0xF0) >> 4;
if ( 1 <= force_protocol && force_protocol <= 2 ) {
return protocols[force_protocol - 1];
}
return "ERROR";
}
const char* get_block_type(uint8_t blk_type)
{
static const char* blk_types[] = { "layerblock", "remapblock", "macroblock" };
if ( 0 <= blk_type && blk_type <= 2 ) {
return blk_types[blk_type];
}
return "ERROR";
}
string get_ifset(uint8_t ifset)
{
static const char* sets[8] = { "set1", "set2", "set3", "set2ext", "INVALIDSET", "INVALIDSET", "INVALIDSET", "INVALIDSET" };
if ( !ifset ) {
return string("any");
} else {
string s;
for ( int i = 0; i < 8; ++i ) {
if ( ifset & 1 ) {
s += sets[i];
s += " ";
}
ifset = ifset >> 1;
}
return s;
}
}
string get_macro_match_metas(uint8_t desired_meta, uint8_t matched_meta)
{
static const char* metas[4] = { "control", "shift", "alt", "gui" };
static const char* hmetas[8] = { "lcontrol", "lshift", "lalt", "lgui", "rcontrol", "rshift", "ralt", "rgui" };
uint8_t unhanded_meta = (desired_meta & ~matched_meta) & 0xF0;
string s;
for ( int i = 0; i < 4; ++i ) {
uint8_t mask = (uint8_t)((1 << (i + 4)) | (1 << i));
if ( unhanded_meta & mask ) {
s += metas[i];
s += " ";
desired_meta &= ~mask;
matched_meta &= ~mask;
}
}
for ( int i = 0; i < 8; ++i ) {
uint8_t mask = (uint8_t)(1 << i);
if ( matched_meta & mask ) {
if ( !(desired_meta & mask) ) {
s += "-";
}
s += hmetas[i];
s += " ";
}
}
return s;
}
string get_macrostep_metas(int val)
{
static const char* metas[8] = { "lcontrol", "lshift", "lalt", "lgui", "rcontrol", "rshift", "ralt", "rgui" };
string s;
for ( int i = 0; i < 8; ++i ) {
if ( val & 1 ) {
s += metas[i];
s += " ";
}
val = val >> 1;
}
return s;
}
string get_macrostep(int cmd, int val)
{
//fprintf(fout, "\t%s %d\n", lookup_macro_token(cmd), val);
string s;
if ( cmd & Q_PUSH_META ) {
s = "PUSH_META ";
}
s += lookup_macro_token(cmd & ~Q_PUSH_META);
s += " ";
int argtype = get_macro_arg_type(cmd);
char buffer[64];
switch ( argtype ) {
case MACRO_ARG_NONE:
break;
case MACRO_ARG_HID:
s += lookup_hid_token(val);
break;
case MACRO_ARG_META:
s += get_macrostep_metas(val);
break;
case MACRO_ARG_DELAY:
//s += itoa(val, buffer, 10);
sprintf(buffer, "%d", val);
s += string(buffer);
break;
default:
s += "INVALID";
break;
}
return s;
}
int process_layerblock(const uint8_t* buf, const uint8_t* bufend)
{
const uint8_t* p = buf;
fprintf(fout, "layerblock\n");
if ( bufend - p < 1 ) {
fprintf(fout, "# ERROR: block truncated\n");
return 1;
}
uint8_t n = *p++;
fprintf(fout, "# count: %d\n", n);
if ( bufend - p != (int)n * 2 ) {
fprintf(fout, "# ERROR: block size mismatch\n");
return 1;
}
for ( int i = 0; i < n; ++i ) {
uint8_t fn = *p++;
uint8_t layer = *p++;
fprintf(fout, "\t");
int b = 1;
while ( fn ) {
if ( fn & 1 ) {
fprintf(fout, "fn%d ", b);
}
++b;
fn = fn >> 1;
}
fprintf(fout, "%d\n", layer);
}
return 0;
}
int process_remapblock(const uint8_t* buf, const uint8_t* bufend)
{
const uint8_t* p = buf;
fprintf(fout, "remapblock\n");
if ( bufend - p < 2 ) {
fprintf(fout, "# ERROR: block truncated\n");
return 1;
}
uint8_t layer = *p++;
fprintf(fout, "layer %d\n", layer);
uint8_t n = *p++;
fprintf(fout, "# count: %d\n", n);
if ( bufend - p != (int)n * 2 ) {
fprintf(fout, "# ERROR: block size mismatch\n");
return 1;
}
for ( int i = 0; i < n; ++i ) {
uint8_t from_hid = *p++;
uint8_t to_hid = *p++;
fprintf(fout, "\t%s %s\n", lookup_hid_token(from_hid), lookup_hid_token(to_hid));
}
return 0;
}
int process_macro(const uint8_t* buf, const uint8_t* /*bufend*/)
{
// todo: use bufend to check length
const uint8_t* p = buf;
uint8_t hid_code = *p++;
uint8_t desired_meta = *p++;
uint8_t matched_meta = *p++;
uint8_t press_flags = *p++;
uint8_t release_flags = *p++;
size_t press_length = press_flags & 0x3F;
size_t release_length = release_flags & 0x3F;
string s = get_macro_match_metas(desired_meta, matched_meta);
fprintf(fout, "macro %s %s # %02X %02X\n", lookup_hid_token(hid_code), s.c_str(), desired_meta, matched_meta);
for ( int i = 0; i < (int)press_length; ++i ) {
uint8_t cmd = *p++;
uint8_t val = *p++;
fprintf(fout, "\t%s\n", get_macrostep(cmd, val).c_str());
}
if ( release_length ) {
fprintf(fout, "onbreak%s\n", (release_flags & 0x40) ? "" : " norestoremeta");
for ( int i = 0; i < (int)release_length; ++i ) {
uint8_t cmd = *p++;
uint8_t val = *p++;
fprintf(fout, "\t%s\n", get_macrostep(cmd, val).c_str());
}
}
fprintf(fout, "endmacro\n");
return 0;
}
int process_macroblock(const uint8_t* buf, const uint8_t* bufend)
{
const uint8_t* p = buf;
fprintf(fout, "macroblock\n");
if ( bufend - p < 1 ) {
fprintf(fout, "# ERROR: block truncated\n");
return 1;
}
uint8_t n = *p++;
fprintf(fout, "# macro count: %d\n", n);
for ( int i = 0; i < n; ++i ) {
if ( bufend - p < 5 ) {
fprintf(fout, "# ERROR: block truncated\n");
return 1;
}
int press_length = p[3] & 0x3F;
int release_length = p[4] & 0x3F;
int macro_length = 5 + 2 * (press_length + release_length);
if ( bufend - p < macro_length ) {
fprintf(fout, "# ERROR: block truncated\n");
return 1;
}
process_macro(p, p + macro_length);
p += macro_length;
}
return 0;
}
int process_block(const uint8_t* buf, size_t buflen)
{
const uint8_t* p = buf;
const uint8_t* bufend = buf + buflen;
if ( bufend - p < 2 ) {
fprintf(fout, "# ERROR: block truncated\n");
return 1;
}
fprintf(fout, "\n# block length: %d\n", *p++);
uint8_t blktype = *p & 0x07;
uint8_t blksel = (*p >> 3) & 0x07;
uint8_t has_set = (*p & 0x40) ? 1 : 0;
uint8_t has_id = (*p & 0x80) ? 2 : 0;
++p;
if ( bufend - p < has_set + has_id ) {
fprintf(fout, "# ERROR: block truncated\n");
return 1;
}
uint8_t blkset = 0;
if ( has_set ) {
blkset = *p++;
}
uint16_t blkid = 0;
if ( has_id ) {
blkid = (uint16_t)(*p++);
blkid |= ((uint16_t)(*p++) << 8);
}
fprintf(fout, "ifset %s\n", get_ifset(blkset).c_str());
if ( has_id ) {
fprintf(fout, "ifkeyboard %04X\n", blkid);
} else {
fprintf(fout, "ifkeyboard any\n");
}
if ( blksel ) {
fprintf(fout, "ifselect %d\n", blksel);
} else {
fprintf(fout, "ifselect any\n");
}
// fprintf(fout, "%s\n", get_block_type(blktype));
int retval = 1;
switch ( blktype ) {
case BLOCK_LAYERDEF: retval = process_layerblock(p, bufend); break;
case BLOCK_REMAP: retval = process_remapblock(p, bufend); break;
case BLOCK_MACRO: retval = process_macroblock(p, bufend); break;
}
fprintf(fout, "endblock\n");
return retval;
}
int process_file(const uint8_t* buf, size_t buflen)
{
const uint8_t* p = buf;
fprintf(fout, "# length: %u\n", buflen);
// header...
uint8_t sig1 = *p++;
uint8_t sig2 = *p++;
fprintf(fout, "# signature: %c %c\n", sig1, sig2);
uint8_t ver1 = *p++;
uint8_t ver2 = *p++;
fprintf(fout, "# version: %d %d\n", ver1, ver2);
if ( *p & 0x0F ) {
fprintf(fout, "force %s\n", get_force_set(*p));
}
if ( *p & 0xF0 ) {
fprintf(fout, "force %s\n", get_force_protocol(*p));
}
++p; // force
++p; // reserved
// blocks...
int err = 0;
const uint8_t* pend = buf + buflen;
while ( p < pend ) {
uint8_t blklen = *p;
if ( !blklen ) {
fprintf(fout, "ERROR: block length is zero!\n");
return 1;
}
err |= process_block(p, blklen);
p += blklen;
}
return err;
}
int main(int argc, char** argv)
{
printf("scdis v1.10\n");
if ( argc != 2 && argc != 3 ) {
fprintf(stderr, "usage: scdis <binary_config> [<text_config>]\n");
return 1;
}
const size_t bufsize = 16384;
static uint8_t buf[bufsize];
FILE* f = fopen(argv[1], "rb");
if ( !f ) {
fprintf(stderr, "error: could not open input file %s\n", argv[1]);
return 1;
}
size_t buflen = fread(buf, 1, bufsize, f);
fclose(f);
if ( argc == 3 ) {
fout = fopen(argv[2], "wt");
if ( !fout ) {
fprintf(stderr, "error: could not open output file %s\n", argv[2]);
return 1;
}
}
int err = process_file(buf, buflen);
if ( fout != stdout ) {
fclose(fout);
}
if ( err ) {
fprintf(stderr, "errors encountered, see output file\n");
return 1;
}
return 0;
}
+21
View File
@@ -0,0 +1,21 @@
Microsoft Visual Studio Solution File, Format Version 8.00
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "scdis", "scdis.vcproj", "{81871EED-13AF-42FF-BB7F-88F93647B45B}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
Debug = Debug
Release = Release
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{81871EED-13AF-42FF-BB7F-88F93647B45B}.Debug.ActiveCfg = Debug|Win32
{81871EED-13AF-42FF-BB7F-88F93647B45B}.Debug.Build.0 = Debug|Win32
{81871EED-13AF-42FF-BB7F-88F93647B45B}.Release.ActiveCfg = Release|Win32
{81871EED-13AF-42FF-BB7F-88F93647B45B}.Release.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal
+147
View File
@@ -0,0 +1,147 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="scdis"
ProjectGUID="{81871EED-13AF-42FF-BB7F-88F93647B45B}"
Keyword="Win32Proj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="Debug"
IntermediateDirectory="Debug"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
MinimalRebuild="TRUE"
BasicRuntimeChecks="3"
RuntimeLibrary="5"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="4"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/scdis.exe"
LinkIncremental="2"
GenerateDebugInformation="TRUE"
ProgramDatabaseFile="$(OutDir)/scdis.pdb"
SubSystem="1"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="../bin"
IntermediateDirectory="Release"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
RuntimeLibrary="4"
UsePrecompiledHeader="0"
WarningLevel="4"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="3"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/scdis.exe"
LinkIncremental="1"
GenerateDebugInformation="FALSE"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
<File
RelativePath="..\common\hid_tokens.cpp">
</File>
<File
RelativePath="..\common\macro_tokens.cpp">
</File>
<File
RelativePath=".\scdis.cpp">
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
<File
RelativePath="..\common\global.h">
</File>
<File
RelativePath="..\common\hid_tokens.h">
</File>
<File
RelativePath="..\common\macro_tokens.h">
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}">
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
+8
View File
@@ -0,0 +1,8 @@
PROG = scinfo
OBJS = $(PROG).o
include ../build/Makefile_hidprog.inc
+112
View File
@@ -0,0 +1,112 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <memory.h>
#include "../common/rawhid.h"
#include "../common/rawhid_defs.h"
typedef unsigned char u_char;
#define LSN(n) ((n) & 15)
#define MSN(n) (((n) >> 4) & 15)
void print_version(const char* s, u_char ver_hi, u_char ver_lo)
{
//printf("%s: v%d.%d%d%d\n", s, MSN(ver_hi), LSN(ver_hi), MSN(ver_lo), LSN(ver_lo));
printf("%s: v%d.%02d\n", s, ver_hi, ver_lo);
}
int do_info()
{
u_char hbuf[64];
int err = 0;
if ( !err ) {
printf("scinfo: sending info request: ");
hbuf[0] = RQ_INFO;
if ( 64 != rawhid_send(0, hbuf, 64, 100) ) {
err = 2;
printf("failed\n");
} else {
printf("ok\n");
}
}
if ( !err ) {
printf("device: ");
if ( 64 != rawhid_recv(0, hbuf, 64, 220) ) {
err = 3;
printf("failed to respond\n");
}
}
if ( !err ) {
if ( hbuf[0] != RC_OK ) {
err = 4;
printf("not ok\n");
} else {
printf("ok\n");
}
}
if ( !err ) {
putchar('\n');
for ( int i = 1; i < 64; i += 3 ) {
u_char ic = hbuf[i];
if ( ic == IC_END ) {
break;
}
switch ( ic ) {
case IC_CODE_VERSION:
print_version("Code Version", hbuf[i+1], hbuf[i+2]);
break;
case IC_PROTOCOL_VERSION:
print_version("Protocol Version", hbuf[i+1], hbuf[i+2]);
break;
case IC_CONFIG_MAX_VERSION:
print_version("Max Settings Version", hbuf[i+1], hbuf[i+2]);
break;
case IC_CONFIG_VERSION:
print_version("Current Settings Version", hbuf[i+1], hbuf[i+2]);
break;
case IC_RAM_SIZE:
printf("SRAM Size: %d bytes\n", hbuf[i+1] + 256 * hbuf[i+2]);
break;
case IC_RAM_FREE:
printf("SRAM Free: %d bytes\n", hbuf[i+1] + 256 * hbuf[i+2]);
break;
case IC_EEPROM_SIZE:
printf("EEPROM Size: %d bytes\n", hbuf[i+1] + 256 * hbuf[i+2]);
break;
case IC_EEPROM_FREE:
printf("EEPROM Free: %d bytes\n", hbuf[i+1] + 256 * hbuf[i+2]);
break;
}
}
}
return err;
}
int main(int argc, char** argv)
{
printf("scinfo v1.10\n");
if ( argc != 1 ) {
fprintf(stderr, "usage: scinfo\n");
return 0;
}
printf("scinfo: looking for Soarer\'s Converter: ");
int r = rawhid_open(1, SC_VID, SC_PID, SC_USAGE_PAGE, SC_USAGE);
if (r <= 0) {
printf("not found\n");
return -1;
}
printf("found\n");
int err = do_info();
if ( err ) {
//printf("\nerror %d\n", err);
}
rawhid_close(0);
return 0;
}
+21
View File
@@ -0,0 +1,21 @@
Microsoft Visual Studio Solution File, Format Version 8.00
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "scinfo", "scinfo.vcproj", "{A243DB4C-FFAB-46C1-B68E-89E066EFF06E}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
Debug = Debug
Release = Release
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{A243DB4C-FFAB-46C1-B68E-89E066EFF06E}.Debug.ActiveCfg = Debug|Win32
{A243DB4C-FFAB-46C1-B68E-89E066EFF06E}.Debug.Build.0 = Debug|Win32
{A243DB4C-FFAB-46C1-B68E-89E066EFF06E}.Release.ActiveCfg = Release|Win32
{A243DB4C-FFAB-46C1-B68E-89E066EFF06E}.Release.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal
+147
View File
@@ -0,0 +1,147 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="scinfo"
ProjectGUID="{A243DB4C-FFAB-46C1-B68E-89E066EFF06E}"
Keyword="Win32Proj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="Debug"
IntermediateDirectory="Debug"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
MinimalRebuild="TRUE"
BasicRuntimeChecks="3"
RuntimeLibrary="5"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="4"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/scinfo.exe"
LinkIncremental="2"
GenerateDebugInformation="TRUE"
ProgramDatabaseFile="$(OutDir)/scinfo.pdb"
SubSystem="1"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="../bin"
IntermediateDirectory="Release"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
RuntimeLibrary="4"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="3"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/scinfo.exe"
LinkIncremental="1"
GenerateDebugInformation="FALSE"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
<File
RelativePath=".\scinfo.c">
<FileConfiguration
Name="Debug|Win32">
<Tool
Name="VCCLCompilerTool"
CompileAs="2"/>
</FileConfiguration>
<FileConfiguration
Name="Release|Win32">
<Tool
Name="VCCLCompilerTool"
CompileAs="2"/>
</FileConfiguration>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}">
</Filter>
<File
RelativePath="..\lib\rawhid.lib">
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
+8
View File
@@ -0,0 +1,8 @@
PROG = scrd
OBJS = $(PROG).o
include ../build/Makefile_hidprog.inc
+134
View File
@@ -0,0 +1,134 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <memory.h>
#include "../common/rawhid.h"
#include "../common/rawhid_defs.h"
typedef unsigned char u_char;
int do_read(const char* fname)
{
u_char fbuf[8192];
size_t n = 0;
int err = 0;
size_t remaining = 0;
u_char hbuf[64];
if ( !err ) {
printf("scrd: sending read request: ");
hbuf[0] = RQ_READ;
if ( 64 != rawhid_send(0, hbuf, 64, 100) ) {
err = 1;
printf("failed\n");
} else {
printf("ok\n");
}
}
if ( !err ) {
printf("device: ");
if ( 64 != rawhid_recv(0, hbuf, 64, 220) ) {
err = 2;
printf("failed to respond\n");
}
}
if ( !err ) {
if ( hbuf[0] != RC_OK ) {
err = 3;
printf("not ok\n");
} else {
n = (size_t)hbuf[2] << 8 | hbuf[1];
remaining = n;
printf("has %u bytes: ok\n", n);
}
}
u_char* p = fbuf;
while ( !err && remaining ) {
if ( !err ) {
printf("scrd: ");
hbuf[0] = RC_READY;
if ( 64 != rawhid_send(0, hbuf, 64, 100) ) {
err = 4;
printf("failed to send 'ready' response\n");
} else {
printf("ready\n");
}
}
if ( !err ) {
printf("device: ");
if ( 64 != rawhid_recv(0, hbuf, 64, 2000) ) {
err = 5;
printf("failed to respond\n");
}
}
if ( !err ) {
size_t len = remaining > 64 ? 64 : remaining;
memcpy(p, hbuf, len);
remaining -= len;
p += len;
printf("sent %u bytes: ok\n", len);
}
if ( !err ) {
printf("scrd: ");
hbuf[0] = RC_OK;
if ( 64 != rawhid_send(0, hbuf, 64, 100) ) {
err = 6;
printf("failed to send 'ok' response\n");
} else {
printf("ok\n");
}
}
}
if ( !err ) {
printf("scrd: ");
hbuf[0] = RC_COMPLETED;
if ( 64 != rawhid_send(0, hbuf, 64, 100) ) {
err = 7;
printf("failed to send 'complete' response\n");
} else {
printf("complete\n");
}
}
if ( !err ) {
printf("scrd: writing file: ");
FILE* f = fopen(fname, "wb");
if ( f ) {
fputc('S', f);
fputc('C', f);
size_t n2 = fwrite(fbuf, 1, n, f);
fclose(f);
printf("%u bytes: ", n2 + 2);
printf("ok\n");
} else {
err = 8;
printf("failed\n");
}
}
return err;
}
int main(int argc, char** argv)
{
printf("scrd v1.10\n");
if ( argc != 2 ) {
fprintf(stderr, "usage: scrd <config_binary>\n");
return 0;
}
printf("scrd: looking for Soarer\'s Converter: ");
int r = rawhid_open(1, SC_VID, SC_PID, SC_USAGE_PAGE, SC_USAGE);
if (r <= 0) {
printf("not found\n");
return -1;
}
printf("found\n");
int err = do_read(argv[1]);
if ( err ) {
//printf("\nerror %d\n", err);
}
rawhid_close(0);
return 0;
}
+21
View File
@@ -0,0 +1,21 @@
Microsoft Visual Studio Solution File, Format Version 8.00
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "scrd", "scrd.vcproj", "{262F101E-E54C-4DD7-A7BD-C5F07A7B0047}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
Debug = Debug
Release = Release
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{262F101E-E54C-4DD7-A7BD-C5F07A7B0047}.Debug.ActiveCfg = Debug|Win32
{262F101E-E54C-4DD7-A7BD-C5F07A7B0047}.Debug.Build.0 = Debug|Win32
{262F101E-E54C-4DD7-A7BD-C5F07A7B0047}.Release.ActiveCfg = Release|Win32
{262F101E-E54C-4DD7-A7BD-C5F07A7B0047}.Release.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal
+147
View File
@@ -0,0 +1,147 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="scrd"
ProjectGUID="{262F101E-E54C-4DD7-A7BD-C5F07A7B0047}"
Keyword="Win32Proj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="Debug"
IntermediateDirectory="Debug"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
MinimalRebuild="TRUE"
BasicRuntimeChecks="3"
RuntimeLibrary="5"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="4"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/scrd.exe"
LinkIncremental="2"
GenerateDebugInformation="TRUE"
ProgramDatabaseFile="$(OutDir)/scrd.pdb"
SubSystem="1"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="../bin"
IntermediateDirectory="Release"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
RuntimeLibrary="4"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="3"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/scrd.exe"
LinkIncremental="1"
GenerateDebugInformation="FALSE"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
<File
RelativePath=".\scrd.c">
<FileConfiguration
Name="Debug|Win32">
<Tool
Name="VCCLCompilerTool"
CompileAs="2"/>
</FileConfiguration>
<FileConfiguration
Name="Release|Win32">
<Tool
Name="VCCLCompilerTool"
CompileAs="2"/>
</FileConfiguration>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}">
</Filter>
<File
RelativePath="..\lib\rawhid.lib">
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
+8
View File
@@ -0,0 +1,8 @@
PROG = scwr
OBJS = $(PROG).o
include ../build/Makefile_hidprog.inc
+280
View File
@@ -0,0 +1,280 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <memory.h>
#include "../common/rawhid.h"
#include "../common/rawhid_defs.h"
typedef unsigned char u_char;
#define LSB(n) (u_char)((n) & 255)
#define MSB(n) (u_char)(((n) >> 8) & 255)
#define FILE_HEADER_LEN 2
#define WRITE_PACKET_HEADER_LEN 4
#define WRITE_PACKET_DATA_LEN (PACKET_LEN - WRITE_PACKET_HEADER_LEN)
#define EEPROM_HEADER_LEN 4
#define EEPROM_FOOTER_LEN 2
#define MAX_EEPROM_SIZE 8192
#define SETTINGS_HEADER_LEN 4
#define SETTINGS_MAX_LEN (MAX_EEPROM_SIZE - EEPROM_HEADER_LEN - EEPROM_FOOTER_LEN)
#define SETTINGS_FILE_MIN_LEN (FILE_HEADER_LEN + SETTINGS_HEADER_LEN)
#define SETTINGS_FILE_MAX_LEN (SETTINGS_MAX_LEN + FILE_HEADER_LEN)
#define FILE_BUF_LEN (SETTINGS_FILE_MAX_LEN + 1)
int do_compatibility_check(u_char ver_major, u_char ver_minor, int len)
{
u_char hbuf[64];
int err = 0;
if ( !err ) {
printf("scwr: sending info request: ");
hbuf[0] = RQ_INFO;
if ( 64 != rawhid_send(0, hbuf, 64, 100) ) {
err = 2;
printf("failed\n");
} else {
printf("ok\n");
}
}
if ( !err ) {
printf("device: ");
if ( 64 != rawhid_recv(0, hbuf, 64, 220) ) {
err = 3;
printf("failed to respond\n");
}
}
if ( !err ) {
if ( hbuf[0] != RC_OK ) {
err = 4;
printf("not ok\n");
} else {
printf("ok\n");
}
}
if ( !err ) {
u_char settings_max_ver_major = 0;
u_char settings_max_ver_minor = 0;
u_char protocol_ver_major = 0;
u_char protocol_ver_minor = 0;
int max_len = 0;
for ( int i = 1; i < 64; i += 3 ) {
u_char ic = hbuf[i];
if ( ic == IC_END ) {
break;
}
switch ( ic ) {
case IC_PROTOCOL_VERSION:
protocol_ver_major = hbuf[i+1];
protocol_ver_minor = hbuf[i+2];
break;
case IC_CONFIG_MAX_VERSION:
settings_max_ver_major = hbuf[i+1];
settings_max_ver_minor = hbuf[i+2];
break;
case IC_EEPROM_SIZE:
max_len = hbuf[i+1] + 256 * hbuf[i+2] - EEPROM_HEADER_LEN - EEPROM_FOOTER_LEN;
break;
}
}
printf("protocol version check: converter=%d.%02d, scwr=%d.%02d: ", protocol_ver_major, protocol_ver_minor, PROTOCOL_VERSION_MAJOR, PROTOCOL_VERSION_MINOR);
if ( protocol_ver_major != PROTOCOL_VERSION_MAJOR || protocol_ver_minor < PROTOCOL_VERSION_MINOR ) {
err = 12;
printf("failed\n");
} else {
printf("ok\n");
}
printf("settings version check: converter=%d.%02d, file=%d.%02d: ", settings_max_ver_major, settings_max_ver_minor, ver_major, ver_minor);
if ( settings_max_ver_major != ver_major || settings_max_ver_minor < ver_minor ) {
err = 12;
printf("failed\n");
} else {
printf("ok\n");
}
printf("settings length check: max=%d, file=%d bytes: ", max_len, len);
if ( len > max_len ) {
err = 12;
printf("failed\n");
} else {
printf("ok\n");
}
}
return err;
}
int do_write(const char* fname)
{
u_char fbuf[FILE_BUF_LEN];
size_t fbuflen = 0;
int err = 0;
if ( !err ) {
printf("scwr: reading file: ");
FILE* f = fopen(fname, "rb");
if ( f ) {
fbuflen = fread(fbuf, 1, FILE_BUF_LEN, f);
fclose(f);
printf("%u bytes: ", fbuflen);
} else {
printf("failed\n");
}
}
if ( !err ) {
if ( fbuflen < SETTINGS_FILE_MIN_LEN ) {
err = 1;
printf("too short\n");
}
if ( fbuflen > SETTINGS_FILE_MAX_LEN ) {
err = 1;
printf("too long\n");
}
}
if ( !err ) {
if ( fbuf[0] != 'S' ) {
err = 11;
}
if ( fbuf[1] != 'C' ) {
err = 11;
}
if ( err ) {
printf("bad signature\n");
} else {
printf("ok\n");
}
}
size_t remaining = fbuflen - FILE_HEADER_LEN;
if ( !err ) {
err = do_compatibility_check(fbuf[2], fbuf[3], (int)remaining);
}
u_char hbuf[PACKET_LEN];
if ( !err ) {
printf("scwr: sending write request for %u bytes: ", remaining);
hbuf[0] = RQ_WRITE;
hbuf[1] = LSB(remaining);
hbuf[2] = MSB(remaining);
if ( PACKET_LEN != rawhid_send(0, hbuf, PACKET_LEN, 100) ) {
err = 2;
printf("failed\n");
} else {
printf("ok\n");
}
}
if ( !err ) {
printf("device: ");
if ( PACKET_LEN != rawhid_recv(0, hbuf, PACKET_LEN, 220) ) {
err = 3;
printf("failed to respond\n");
}
}
if ( !err ) {
if ( hbuf[0] != RC_OK ) {
err = 4;
printf("not ok\n");
} else {
printf("ok\n");
}
}
u_char* p = fbuf + FILE_HEADER_LEN;
while ( !err && remaining ) {
if ( !err ) {
printf("device: ");
if ( PACKET_LEN != rawhid_recv(0, hbuf, PACKET_LEN, 2000) ) {
err = 5;
printf("failed to respond\n");
}
}
if ( !err ) {
if ( hbuf[0] != RC_READY ) {
err = 6;
printf("not ready\n");
} else {
printf("ready\n");
}
}
if ( !err ) {
// size_t len = remaining > 64 ? 64 : remaining;
size_t len = remaining > WRITE_PACKET_DATA_LEN ? WRITE_PACKET_DATA_LEN : remaining;
hbuf[0] = RQ_CONTINUATION | RQ_WRITE;
hbuf[1] = (u_char)len;
size_t ofs = p - fbuf + FILE_HEADER_LEN;
hbuf[2] = LSB(ofs);
hbuf[3] = MSB(ofs);
for ( size_t i = 0; i < len; ++i ) {
hbuf[i + WRITE_PACKET_HEADER_LEN] = p[i];
}
printf("scwr: sending %u bytes: ", len);
// if ( 64 != rawhid_send(0, p, 64, 100) ) {
if ( PACKET_LEN != rawhid_send(0, hbuf, PACKET_LEN, 100) ) {
err = 2;
printf("failed\n");
} else {
remaining -= len;
p += len;
printf("ok\n");
}
}
if ( !err ) {
printf("device: ");
if ( PACKET_LEN != rawhid_recv(0, hbuf, PACKET_LEN, 220) ) {
err = 3;
printf("failed to respond\n");
}
}
if ( !err ) {
if ( hbuf[0] != RC_OK ) {
err = 4;
printf("not ok\n");
} else {
printf("ok\n");
}
}
}
if ( !err ) {
printf("device: ");
if ( PACKET_LEN != rawhid_recv(0, hbuf, PACKET_LEN, 2000) ) {
err = 5;
printf("failed to respond\n");
}
}
if ( !err ) {
if ( hbuf[0] != RC_COMPLETED ) {
err = 7;
printf("not complete\n");
} else {
printf("complete\n");
}
}
return err;
}
int main(int argc, char** argv)
{
printf("scwr v1.10\n");
if ( argc != 2 ) {
fprintf(stderr, "usage: scwr <config_binary>\n");
return 0;
}
printf("scwr: looking for Soarer\'s Converter: ");
int r = rawhid_open(1, SC_VID, SC_PID, SC_USAGE_PAGE, SC_USAGE);
if (r <= 0) {
printf("not found\n");
return -1;
}
printf("found\n");
int err = do_write(argv[1]);
if ( err ) {
//printf("\nerror %d\n", err);
}
rawhid_close(0);
return 0;
}
+21
View File
@@ -0,0 +1,21 @@
Microsoft Visual Studio Solution File, Format Version 8.00
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "scwr", "scwr.vcproj", "{63366BE7-6C6E-43E0-A59B-16AFB7DDF369}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
Debug = Debug
Release = Release
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{63366BE7-6C6E-43E0-A59B-16AFB7DDF369}.Debug.ActiveCfg = Debug|Win32
{63366BE7-6C6E-43E0-A59B-16AFB7DDF369}.Debug.Build.0 = Debug|Win32
{63366BE7-6C6E-43E0-A59B-16AFB7DDF369}.Release.ActiveCfg = Release|Win32
{63366BE7-6C6E-43E0-A59B-16AFB7DDF369}.Release.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal
+150
View File
@@ -0,0 +1,150 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="scwr"
ProjectGUID="{63366BE7-6C6E-43E0-A59B-16AFB7DDF369}"
Keyword="Win32Proj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="Debug"
IntermediateDirectory="Debug"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
MinimalRebuild="TRUE"
BasicRuntimeChecks="3"
RuntimeLibrary="5"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="4"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/scwr.exe"
LinkIncremental="2"
GenerateDebugInformation="TRUE"
ProgramDatabaseFile="$(OutDir)/scwr.pdb"
SubSystem="1"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="../bin"
IntermediateDirectory="Release"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
RuntimeLibrary="4"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="3"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/scwr.exe"
LinkIncremental="1"
GenerateDebugInformation="FALSE"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
<File
RelativePath=".\scwr.c">
<FileConfiguration
Name="Debug|Win32">
<Tool
Name="VCCLCompilerTool"
CompileAs="2"/>
</FileConfiguration>
<FileConfiguration
Name="Release|Win32">
<Tool
Name="VCCLCompilerTool"
CompileAs="2"/>
</FileConfiguration>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
<File
RelativePath="..\common\rawhid_defs.h">
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}">
</Filter>
<File
RelativePath="..\lib\rawhid.lib">
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>