I need to capture joystick input using C or Java (whichever is easier).
There are answers to similar questions but they all use C++ or C#.
The program only needs to get the direction and amount by which the joystick is tilted.
I'm using Windows7, so I'll probably need to use winmm.dll as is explained here.
I would appreciate if someone could explain how to do so in C or Java.
There are premade libraries for both languages. The more important question would be the language you have to use or which one you'd prefer primarily. It doesn't necessarily make sense to add C code just to add such functionality to a Java program. In a similar way, you wouldn't want to call Java from C, just to get joystick input.
First hit on Google for "java joystick" has been this one. Haven't tried it yet.
As for C++ code (and most likely C# too) you should be able to use the same code in C, assuming it's pure Windows API code (cause that one is in C too). So you shouldn't have any issues adapting these.
Edit:
Regarding the answer you linked: You should be able to use this solution 1:1 in C (in Java you'd have to write code essentially doing the same). But instead of declaring everything yourself, just #include <windows.h> and you should be ready to go (in C).
I recommend the Simple Directmedia Layer library for a pure C solution. The library is pleasant to use, and their documentation and code examples are great:
SDL_Joystick *joy;
// Initialize the joystick subsystem
SDL_InitSubSystem(SDL_INIT_JOYSTICK);
// Check for joystick
if(SDL_NumJoysticks()>0){
// Open joystick
joy=SDL_JoystickOpen(0);
...
The C# solution is indeed pure Windows API code!
In C just #include <windows.h> and instead of [DllImport("winmm.dll")]
you link to winmm.lib. The following example should make it clear:
void printJoystickData()
{
// The captured data will be written to the following struct:
//typedef struct joyinfo_tag {
// UINT wXpos;
// UINT wYpos;
// UINT wZpos;
// UINT wButtons;
//} JOYINFO,*PJOYINFO,*LPJOYINFO;
JOYINFO joystickInfo;
// The ID of the joystick you are using. If there is only one joystick use JOYSTICKID1.
UINT joystickId = JOYSTICKID1;
MMRESULT errorCode = joyGetPos(joystickId, &joystickInfo);
switch(errorCode)
{
case JOYERR_NOERROR: // No error. joystickInfo now contains contains the captured data.
{
printf("The X position (left/right tilt) is %u\n", joystickInfo.wXpos);
printf("The Y position (up/down tilt) is %u\n", joystickInfo.wYpos);
printf("The Z position (usually the throttle) is %u\n", joystickInfo.wZpos);
// These values range from 0 to 65536. 32768 is the centre position.
// Test button 1. You can do the same for JOY_BUTTON2, JOY_BUTTON3 etc.
// wButtons is a UNINT that is the OR of all pressed button flags.
if(joystickInfo.wButtons & JOY_BUTTON1)
printf("Button 1 was pressed.");
break;
}
case JOYERR_PARMS: fprintf(stderr, "Invalid parameters to joyGetPos."); break;
case JOYERR_NOCANDO: fprintf(stderr, " Failed to capture joystick input."); break;
case JOYERR_UNPLUGGED: fprintf(stderr, "The joystick identified by joystickId isn't plugged in."); break;
case MMSYSERR_NODRIVER: fprintf(stderr, "No (active) joystick driver available."); break;
}
}
The Simple Directmedia Layer library (suggested by blahdiblah) also looks promising but for what I needed to do I think the code above is simpler.
For Java use the Central Nexus Device API as suggested by Mario. The download includes documentation.
The sample you have linked to doesn't actually use anything object-oriented, which means you can quite easily port it to C.
C supports structs the same as C# (which are allocated on the stack), so that's basically copy-paste.
The one thing that might trip you up is the [DllImport] attribute. The purpose of this attribute is to p/invoke (platform invoke) an unmanaged DLL from within managed C# code. Here you would use extern to access the Windows API.
Refer this url for Gamepad.c and Gamepad.h files.
https://github.com/elanthis/gamepad
Open the joystick using
STATE.fd = open(STATE.device, O_RDWR|O_NONBLOCK);
Structure Definition:
STATE is a structure object.
//It is in Gamepad.h file
open returns -1 on failure.
Set the flag value (defined while declaring variables for joystick) if opened successfully.
Read the joystick input using
(read(STATE[gamepad].fd, &je, sizeof(je)) > 0)
Structure Definition:
je is a structure object
//It is in joystick.h
je is updated now.
je.type is one among the three things mentioned in the joystick.h header file
If a button is pressed , then je.number is an int that denotes the button number as specified by the manufacturer. If a stick is moved , then je.number denotes the axis specification by the manufacturer.
The magnitude is present in the je.value which is assigned to the stick's corresponding variable accordingly.
Related
How to send a string to a virtualbox-guest-machine?
This is my code:
public void testKeyboard() throws Exception {
IVirtualBox b = connect();
List<IMachine> machines = b.getMachines();
for (IMachine m : machines) {
MachineState d = b.getMachineStates(Arrays.asList(m)).iterator().next();
if (d == MachineState.Running) {
ISession s = manager.getSessionObject();
m.lockMachine(s, LockType.Shared);
IConsole console = s.getConsole();
IKeyboard k = console.getKeyboard();
k.putScancodes(Arrays.asList(25, 25 | 0x80)); // <- sends the character P
s.unlockMachine();
}
}
}
Microsoft say its 0x50
java.awt.event.KeyEvent also say its 0x50:
/** Constant for the "P" key. */
public static final int VK_P = 0x50;
In virtualbox its different.
P=25
2=0x50
b=0x30
Why in the world is the code of P = 25 in virtualbox?
Virtual key codes and keyboard scan codes are two different things.
Keyboards (still) talk to PCs using a really dusty old protocol. Many years ago I implemented a toy version of the protocol in an OS driver and it was quite annoying. Making it worse, keyboards can use 3 different sets of keyboard scancodes which originated with different flavors of old PCs.
Here is a reference for the 3 sets: https://www.vetra.com/scancodes.html
The constants you discovered line up with Set 1. Note that Set 1 has different codes used to press the key and release the key!
The virtual key constants used by the Java KeyEvent class and by that Windows list both seem to be based closely on ASCII characters, since 'P' = 0x50 in ASCII. But it's the job of the operating system keyboard driver to translate from keyboard scancodes to more logical sets of constants. There is no universal constant for a key.
Since VirtualBox is emulating the physical keyboard interface to the guest OS, its IKeyboard API takes raw scancodes.
For the VirtualBox GUI, it must have a function which translates from host OS key constants back to scancodes for the guest OS, which might be easier if you can use that, but IKeyboard appears to be a very low-level interface which bypasses that.
Depending on your use case, perhaps there is a different API you can also use here; or perhaps you can control your VM with guest software like SSH or VNC.
Scan codes are keyboard layout dependent mappings to key layouts. You can send codes based on the scan codes for a USB keyboard, which all modern systems are likely to understand. The codes are documented in Appendix C of the Microsoft document "Keyboard Scan Code Specification". You will see there that character P is in position 26 in the 1-indexed table of key location. This would explain a 0-indexed code of 25 producing the character P.
You will see that "key down" needs you to send 25 as the scan code (0x19) and then 0x99 for key up. This is what your (25 | 0x80) is doing. So your code at the moment sends a message meaning "Key P has been pressed (make in the table)" followed by "Key P has been released (break in the table)"
The direct link to the doc I'm referencing here is: https://download.microsoft.com/download/1/6/1/161ba512-40e2-4cc9-843a-923143f3456c/scancode.doc
N.B. These codes are quite different to ASCII codes, which are where you are getting the 0x50 from.
Sending strings via the keyboard
If you want to send a whole string via the keyboard this way, what you will need is a mapping table from ASCII codes for each character to key make and key break codes. You can then take the string character by character and work out which scan code pairs to send for each character. Note - you'll need to deal with case by adding a "Shift down" before the pair and "Shift up" afterwards. This is do-able with a fairly long mapping table, I'd use a WeakHashMap
Memory-mapped hardware
On some computing architectures, pointers can be used to directly
manipulate memory or memory-mapped devices.
Assigning addresses to pointers is an invaluable tool when programming
microcontrollers. Below is a simple example declaring a pointer of
type int and initialising it to a hexadecimal address in this example
the constant 0x7FFF:
int *hardware_address = (int *)0x7FFF;
In the mid 80s, using the BIOS to access the video capabilities of PCs
was slow. Applications that were display-intensive typically used to
access CGA video memory directly by casting the hexadecimal constant
0xB8000 to a pointer to an array of 80 unsigned 16-bit int values.
Each value consisted of an ASCII code in the low byte, and a colour in
the high byte. Thus, to put the letter 'A' at row 5, column 2 in
bright white on blue, one would write code like the following:
#define VID ((unsigned short (*)[80])0xB8000)
void foo() {
VID[4][1] = 0x1F00 | 'A';
}
is such thing possible in Java/Python in the absence of pointers?
EDIT:
is such an acces possible:
char* m_ptr=(char*)0x603920;
printf("\nm_ptr: %c",*m_ptr);
?
I'm totally uncertain of the context and thus useful application of what you're trying to do, but here goes:
The Java Native Interface should allow direct memory access within the process space. Similarly, python can load c module that would provide an access method.
Unless you've got a driver loaded by the system to do the interfacing, however, any hardware device memory will be out-of-bounds. Even then, the driver / kernel module must be the one to address non-application space memory.
If you are on an operating system with /dev/mem, you can create a MappedByteBuffer onto it and do this sort of thing.
I need to register the file association for a certain file type - in fact, I just need to launch a certain Java program with certain arguments and a name of that file.
I got as far as the following:
// in fff-assoc.cmd file:
assoc .fff=SomeFile
ftype SomeFile=java -jar some.jar <arguments1> "%%1" <arguments2>
It works properly for ASCII file names. But when I try to double-click some file with non-ASCII symbols in name, the argument passed looks like "????" (int value of each char = 63).
How can I fix those associations?
If what bobince says is accurate and you cannot reliably get the data to java directly, one alternative solution would be to write a small "shim" program in another language (e.g. C, C++ or C#).
The idea is that the program grabs the input as UNICODE, encodes it so that it's expressible using only ASCII characters (e.g. by using base64, or even something as simple as encoding every character as its numerical equivalent) and then assembles the command line argument to use and launches java itself using CreateProcess.
Your Java code could "undo" the encoding, reconstructing the UNICODE name and proceeding to use it. It's a bit of a roundabout way and requires an extra component for your software, but it should work around the restriction detailed above, if indeed that is an actual restriction.
Update: This is the basic code for the shim program. It encodes input as a sequence of integers, separated by colons. It doesn't do much in the way of error checking and you might want to improve it slightly, but it should at least get you started and going in the right direction.
You should grab Visual Studio Express (if you don't already have Visual Studio) and create a new Visual C++ project, choose "Win32" and select "Win32 Project". Choose "Win32 application". After the project is created, replace everything in the .cpp file that is displayed with this code:
#include "stdafx.h"
#include <string>
int APIENTRY _tWinMain(HINSTANCE, HINSTANCE, LPTSTR lpCmdLine, int)
{
std::string filename;
while((lpCmdLine != NULL) && (*lpCmdLine != 0))
{
if(filename.length() != 0)
filename.append(":");
char buf[32];
sprintf(buf, "%u", (unsigned int)(*lpCmdLine++));
filename.append(buf);
}
if(filename.length() == 0)
return 0;
PROCESS_INFORMATION pi;
memset(&pi, 0, sizeof(PROCESS_INFORMATION));
STARTUPINFOA si;
memset(&si, 0, sizeof(STARTUPINFOA));
si.cb = sizeof(STARTUPINFOA);
char *buf = new char[filename.length() + 256]; // ensure that 256 is enough for your extra arguments!
sprintf(buf, "java.exe -jar some.jar <arguments1> \"%s\" <arguments2>", filename.c_str());
// CHECKME: You hard-coded the path for java.exe here. While that may work on your system
// is it guaranteed that it will work on every system?
if(CreateProcessA("C:\\Program Files\\Java\\jre7\\bin\\java.exe", buf, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
{
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
delete[] buf;
return 0;
}
You should be able to figure the details on how to compile and so on fairly easily.
I just need to launch a certain Java program with certain arguments and a name of that file.
Unfortunately this 'just' is not actually possible, due to the MS implementation of the standard C library that Java uses to receive argument input (amongst other things). Unless you go straight to the native Win32 API, bypassing standard Java or C interfaces,
See this question for background.
When calling java from the command line, you can specify the encoding of the parameters (which will be used to create the strings in args[]):
java -jar -Dsun.jnu.encoding=cp1252 yourFileName
When using non-ASCII characters, the specified charset has an impact on the value of args[0]. Not sure if that would apply to file associations though.
Note: I'm not sure what other uses that parameter has - this post seems to say none.
If i have a C source file and i want to locate a specific local variable within a function and make it global - so another tool is able to process the C file (a tool i didn't write) what would be the easiest way to do this? I was thinking of using regex, but even that posses it's own problems. It's kind of like writing a mini C parser in Java.. a lot of work :S
Are there any libraries that can help make this easier?
For example, say i want to make the variable "i" into a global variable. The user will specify the function name and the variable name (but not the type the variable is - ie. "int").
I can use regex to find the function - sure. But from there i really don't know what the best approach would be?... Will CDT plugin help?
Example:
/*
* add.c
* a simple C program
*
*/
#include <stdio.h>
#define LAST 10
int main()
{
int i = 0;
int sum = 0;
for ( i = 1; i <= LAST; i++ ) {
sum += i;
} /*-for-*/
printf("sum = %d\n", sum);
return 0;
}
converted to:
/*
* add.c
* a simple C program
*
*/
#include <stdio.h>
#define LAST 10
int i = 0;
int main()
{
int sum = 0;
for ( i = 1; i <= LAST; i++ ) {
sum += i;
} /*-for-*/
printf("sum = %d\n", sum);
return 0;
}
If you do only trivial examples, you can hack this with Perl or some java regex. It won't work reliably on complex programs, because you need a real parser.
Our DMS Software Reengineering Toolkit and its C Front End could be used to to this pretty reliably.
DMS provides general purpose program analysis and transformation capability, parameterized by a programming langauge description. DMS's C Front explains to DMS what the precise syntax is for C (for a variety of dialects of C, including GCC and MS); it in effect provides a complete parser, producing Abstract Syntax trees (and the inverse: a C code generator from the ASTs) This allows DMS to read C source files accurately, including preprocessing.
With the parsed code in AST form, you can build DMS functions and/or write patterns to find function definitions and in particular your targeted variable. DMS code or alteratevely source-to-source transforms can then be used to either lift the variable out of the function, and/or insert code to track state changes of that variable so it can be seen.
So, with DMS and some custom code, you can achieve your desired effect. The example you provided is probably pretty simple to do with DMS, but the learning curve will stil be a lot; DMS is complex because the langauges it handles are complex, and you have to learn how to use it. So, this isn't an afternoon's exercise for a newbie.
Note: you will want to do this to preprocessed programs (otherwise you won't be generally able to parse them reliably). So, this should be something you do just before compilation, and shouldn't become part of the finalized code.
If you want to make permanent code changes, you'll need to parse the unpreprocessed code; that's a heckuva lot harder. DMS's C front end can do this to the extent the preprocessor directives are "structured"; about 95% of them are. So now you have a new problem: either fix the unstructured ones (a one time manual change), or reject files that can't be parsed with "tough luck".
You might use GCC instead of DMS; after all it has a very well tested C parser. It won't help you generate modified C code, though. Another alternative is Clang, which is coming up fast as a pretty good alternative. I think it will parse C++; not so sure about C or in particular the dialect of C your end user may be using (you didn't say). It has ASTs like DMS, and a kind of scheme for generating "patches" to code that might work.
The first thing I would demand is a complete specification of exactly when this is required and why, and how to identify when it is safe to do so without adversely affecting the program semantics. This is a really bad idea. Clearly those who gave you the assignment have no idea of either the implementation complexity, which is immense, or the adverse semantic effects. I am guessing that they will therefore be unable to come up with an adequate specification either, which will ultimately let you out.
I would also draw their attention to this discussion, especially Ira Baxter's comments. I used to build compilers for a living. It is not a task to learn, or ask about, on a forum.
Even if you are able to come up with a way to make such transformations, I think it's not a good idea. The program will not stay the same since you move around construction and destruction. Also, not all types are default constructable or copyable so in general the transformation is not possible.
Are you interested only in a few simple types? Then make that a part of the solution. Is the original code generated? Else, how can you trust to identify local objects by name only? The same name May also be used for different type of objects.
The facts:
When a file is moved, there's two possibilities:
The source and destination file are on the same partition and only the file system index is updated
The source and destination are on two different file system and the file need to be moved byte per byte. (aka copy on move)
The question:
How can I determine if a file will be either logically or physically moved ?
I'm transferring large files (700+ megs) and would adopt a different behaviors for each situation.
Edit:
I've already coded a moving file dialog with a worker thread that perform the blocking io call to copy the file a meg at a time. It provide information to the user like rough estimate of the remaining time and transfer rate.
The problem is: how do I know if the file can be moved logically before trying to move it physically ?
On Linux or other *nices, call stat() on the source and destination directories and compare their st_dev values. If they are the same, a logical move can be performed, otherwise a physical copy+delete must be performed.
On Windows, you can call GetFileInformationByHandle() on handles to the two directories and compare their dwVolumeSerialNumber values. Note that this requires Windows 2000 or later.
I see you're using Java -- there must be some portal through which you can access this OS-level info (perhaps JNI?)
Ok I'm on something :)
Using JNA I am able to call the Win32 API (and *nix API too) from java.
I tried calling GetFileInformationByHandle and did got a result BUT the dwVolumeSerialNumber attribute always equals 0 (tried with my C: and D: drive)
Then I saw this function on MSDN: MoveFileEx. When the flag parametter is set to 0, the copy on move feature will be disable. AND IT WORKS !!!!
So I will simply call
if (!Kernel32.INSTANCE.MoveFileEx(source.getAbsolutePath(), destination.getAbsolutePath(), 0)) {
System.out.println("logical move failed");
}
Here is the code to put in the Kernel32.java interface (this file can be found in the src.zip package in the download section of the JNA site):
boolean MoveFileEx(String lpExistingFileName, String lpNewFileName, int dwFlags);
int MOVEFILE_REPLACE_EXISTING = 0x01;
int MOVEFILE_COPY_ALLOWED = 0x02;
int MOVEFILE_CREATE_HARDLINK = 0x04;
int MOVEFILE_WRITE_THROUGH = 0x08;
int MOVEFILE_DELAY_UNTIL_REBOOT = 0x10;
int MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x20;