Git Product home page Git Product logo

dualsense-ts's Introduction

dualsense-ts

This module provides a natural interface for your DualSense controller.

Getting started

Installation

This package is distributed via npm. Install it the usual way:

  • npm add dualsense-ts

In the browser, dualsense-ts has zero dependencies and relies on the WebHID API. At this time, only Chrome, Edge, and Opera are compatible.

In node.js, dualsense-ts relies on node-hid as a peer dependency, so you'll need to add it as well:

  • npm add node-hid

Connecting

When you construct a new Dualsense(), it will begin searching for a controller. If it finds one, it will connect automatically.

import { Dualsense } from "dualsense-ts";

// Grab a controller connected via USB or Bluetooth
const controller = new Dualsense();

If the device disconnects, dualsense-ts will quietly wait for it to come back. You can monitor the connection status with controller.connection using any of the Input APIs listed in the next section.

const connected = controller.connection.active

controller.connection.on("change", ({ active }) = > {
  console.log(`controller ${active ? '' : 'dis'}connected`)
});

Input APIs

dualsense-ts provides several interfaces for reading input:

  • Synchronous: It's safe to read the current input state at any time
// Buttons
controller.circle.state; // false
controller.left.bumper.state; // true

// Triggers
controller.right.trigger.active; // true
controller.right.trigger.pressure; // 0.72, 0 - 1

// Analog Sticks - represented as a position on a unit circle
controller.left.analog.x.active; // true, when away from center
controller.left.analog.x.state; // 0.51, -1 to 1
controller.left.analog.direction; // 4.32, radians
controller.left.analog.magnitude; // 0.23, 0 to 1

// Touchpad - each touch point works like an analog input
controller.touchpad.right.contact.state; // false
+controller.touchpad.right.x; // -0.44, -1 to 1
  • Callbacks: Each input is an EventEmitter or EventTarget that provides input, press, release, and change events
// Change events are triggered only when an input's value changes
controller.triangle.on("change", (input) =>
  console.log(`${input} changed: ${input.active}`)
);
// ▲ changed: true
// ▲ changed: false

// The callback provides two arguments, so you can monitor nested inputs
// You'll get a reference to your original input, and the one that changed
controller.dpad.on("press", (dpad, input) =>
  assert(dpad === controller.dpad)
  console.log(`${input} pressed`)
);
// ↑ pressed
// → pressed
// ↑ pressed

// `input` events are triggered whenever there is new information from the controller
// Your Dualsense may provide over 250 `input` events per second, so use this sparingly
// These events are not available for nested inputs, like the example above
controller.left.analog.x.on("input", console.log)
  • Promises: Wait for one-off inputs using await
// Resolves next time `dpad up` is released
const { active } = await controller.dpad.up.promise("release");

// Wait for the next press of any dpad button
const { left, up, down, right } = await controller.dpad.promise("press");

// Wait for any input at all
await controller.promise();
  • Async Iterators: Each input is an async iterator that provides state changes
for await (const { pressure } of controller.left.trigger) {
  console.log(`L2: ${Math.round(pressure * 100)}%`);
}

Other Supported Features

Motion Control

controller.gyroscope.on("change", ({ x, y, z }) => {
  console.log(`Gyroscope: \n\t${x}\n\t${y}\n\t${z}`)
}

controller.accelerometer.on("change", ({ x, y, z }) => {
  console.log(`Accelerometer: \n\t${x}\n\t${y}\n\t${z}`)
}

controller.accelerometer.z.on("change", ({ force }) => {
  if (force > 0.3) console.log('Controller moving')
})

Rumble

Only supported in node.js over USB at this time.

controller.rumble(1.0); // 100% rumble intensity
controller.left.rumble(0.5); // 50% rumble intensity on the left
console.log(controller.left.rumble()); // Prints 0.5
console.log(controller.right.rumble()); // Prints 1
controller.rumble(0); // Stop rumbling

controller.rumble(true); // Another way to set 100% intensity
controller.rumble(false); // Another way to stop rumbling

// Control right rumble intensity with the right trigger
controller.right.trigger.on("change", (trigger) => {
  controller.right.rumble(trigger.magnitude);
});

With React

Check out the example app for more details.

// DualsenseContext.tsx
import { createContext } from "react";
import { Dualsense } from "dualsense-ts";

const controller = new Dualsense();
export const DualsenseContext = createContext(controller);
DualsenseContext.displayName = "DualsenseContext";

controller.connection.on("change", ({ state }) => {
  console.group("dualsense-ts");
  console.log(`Controller ${state ? "" : "dis"}connected`);
  console.groupEnd();
});

controller.hid.on("error", (err) => {
  console.group("dualsense-ts");
  console.log(err);
  console.groupEnd();
});

The user will need to grant permission before we can access new devices using the WebHID API. The Dualsense class provides a callback that can be used as a handler for onClick or other user-triggered events:

// PermissionComponent.tsx
import { useContext } from "react";
import { DualsenseContext } from "./DualsenseContext";

export const RequestController = () => {
  const controller = useContext(DualsenseContext);
  return (
    <button
      text="Grant Permission"
      onClick={controller.hid.provider.getRequest()}
    />
  );
};

Now components with access to this context can enjoy the shared dualsense-ts interface:

// ConnectionComponent.tsx
import { useContext, useEffect, useState } from "react";
import { DualsenseContext } from "./DualsenseContext";

export const ControllerConnection = () => {
  const controller = useContext(DualsenseContext);
  const [connected, setConnected] = useState(controller.connection.state);
  const [triangle, setTriangle] = useState(controller.triangle.state);

  useEffect(() => {
    controller.connection.on("change", ({ state }) => setConnected(state));
    controller.triangle.on("change", ({ state }) => setTriangle(state));
  }, []);

  return (
    <p dir={triangle ? "ltr" : "rtl"}>{`Controller ${
      state ? "" : "dis"
    }connected`}</p>
  );
};

It's not working

Try out the example app's debugger to look for clues. Please open an issue on Github if you have questions or something doesn't seem right.

If inputs are not working or wrong, use the debugger to view the report buffer and include this with your issue to help us reproduce the problem.

Migration Guide

dualsense-ts uses semantic versioning. For more info on breaking changes, check out the migration guide.

Credits

dualsense-ts's People

Contributors

camtosh avatar captainthrillsdev avatar daniloarcidiacono avatar dependabot[bot] avatar github-actions[bot] avatar nsfm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

dualsense-ts's Issues

Bad inputs in bluetooth mode

Describe the bug
Bluetooth almost works but inputs are incorrect

To Reproduce
yarn debug

Expected behavior
Identical to USB

Additional context
Bluetooth input buffer has 14 extra bytes

"HID write failed: {}" error shows up after connecting gamepad in browser

Describe the bug
After granting permission to connect a DualSense gamepad using controller.hid.provider.getRequest() the following error shows up:
image

To Reproduce
Package version: 5.1.8
steps:

  1. Connect gamepad with Bluetooth.
  2. Grant permission using controller.hid.provider.getRequest().

Expected behavior
Successful connection with no errors.

Additional context

  • Using in a React (18.2.0) TypeScript (5.0.2) app built with Vite (4.4.5).
  • Used ReactContext like in the documentation and zustand (4.4.4) to check if it's a problem in my end.

Touchpad & Multitouch Support

Is your feature request related to a problem? Please describe.
The controller has a feature that doesn't work with this library

Describe the solution you'd like
Support for all available features

Bumpers not working

Describe the bug
No callbacks for L1 and R1

To Reproduce
Just use them

Expected behavior
Callbacks

Additional context
L1 and R1 are available in the hid report but are not mapped.

Calling "removeAllListeners()" breaks most inputs

Describe the bug
Using "removeAllListeners()" to clear an event handler as suggested by the readme breaks inputs that relay changes from other inputs.

To Reproduce
Attempt to reuse inputs after following the steps suggested by the readme.

Expected behavior
My event handler is cleared without breaking my inputs.

Node HID check for browser error

Describe the bug
node_hid_provider is checking for window type undefined, typeof window === 'undefined' though

To Reproduce
Please provide exact package version and steps to reproduce the behavior:

  1. Try and run with node-hid

Expected behavior
Update check to correctly use 'undefined'

Multiplayer support

Is your feature request related to a problem? Please describe.
Would like to be able to use multiple controllers.

Describe the solution you'd like
A utility to list available controllers, and a way to specify which controller to link to which Dualsense instance.

Rumble support

** Is your feature request related to a problem? Please describe. **
The controller has a feature that doesn't work with this library

** Describe the solution you'd like **
Support for all available features

Gyro & Accelerometer support

Is your feature request related to a problem? Please describe.
The controller has a feature that doesn't work with this library

Describe the solution you'd like
Support for all available features

Axis values mapped to wrong range

Describe the bug
Values for analog axis are mapped from -128 to 128, rather than -1 to 1.

To Reproduce
Check the state of the input while using the analog stick.

Expected behavior
X and Y axis should be limited from -1 to 1 as documented.

Primary buttons and dpad conflict

Describe the bug
Pressing any of the primary buttons breaks dpad inputs.

To Reproduce
Hold down on the dpad and press X. The dpad state will change to 'false' until you release X.

Expected behavior
No conflicts.

Missing inputs from bumpers/triggers

Describe the bug
No feedback from bumpers or triggers

To Reproduce
Attempt to listen for inputs from the bumpers or triggers

Expected behavior
My callbacks should run when the bumpers/triggers are used

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.