I can't get GameController class working with my joystick. However I found a simple library https://github.com/suzukiplan/gamepad-osx using IOKit written is C, and got it working in swift command line app using the following code for main.swift:
import Foundation
func callback(_ type: Int32, _ page: Int32, _ usage: Int32, _ value: Int32) -> Void {
print("Type: \(type); page: \(page), usage: \(usage), value: \(value)")
}
let ctx = gamepad_init(1, 1, 0)
if ctx == nil {
print("Init failed")
exit(4)
}
gamepad_set_callback(ctx, callback(_:_:_:_:))
CFRunLoopRun()
exit(0)
Console messages:
attched device: Controller
attched device: 2.4G RX
attched device: VirtualHIDKeyboard
Type: 2; page: 7, usage: 227, value: 1
Type: 2; page: 7, usage: -1, value: 6
....
Since I am actually targeting MacOS app, I created a single-view Cocoa app with the following (very similar) code in Main View:
import AppKit
class MainView: NSView {
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
print("Init started")
let ctx = gamepad_init(1, 1, 0)
if ctx == nil {
print("Init failed")
return
}
print("Init succeeded")
gamepad_set_callback(ctx, callback(_:_:_:_:))
print("Callback attached")
}
}
func callback(_ type: Int32, _ page: Int32, _ usage: Int32, _ value: Int32) -> Void {
print("Type: \(type); page: \(page), usage: \(usage), value: \(value)")
}
The window appears, but console output has only that:
Initialising started
Initialising succeeded
Callback attached
No attachment messages, and quite obviously no callback from device
Also tried an running and additional thread (DispatchQueue) in Main view and in AppDelegate
func applicationDidFinishLaunching(_ aNotification: Notification) {
DispatchQueue(label: "Joy").async {
print("Initialising started")
let ctx = gamepad_init(1, 1, 0)
if ctx == nil {
print("Init failed")
return
}
print("Initialising succeeded")
gamepad_set_callback(ctx, callback(_:_:_:_:))
CFRunLoopRun()
}
}
Again, no attachment messages
Any ideas?