cemu-DS4Windows/DS4Windows/DS4Control/ControlService.cs

1630 lines
66 KiB
C#
Raw Permalink Normal View History

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
2017-06-08 22:52:47 +02:00
using System.Threading;
using System.Diagnostics;
using static DS4Windows.Global;
//using Nefarius.ViGEm.Client;
namespace DS4Windows
{
public class ControlService
{
public X360BusDevice x360Bus = null;
//public ViGEmClient vigemTestClient = null;
public const int DS4_CONTROLLER_COUNT = 4;
public DS4Device[] DS4Controllers = new DS4Device[DS4_CONTROLLER_COUNT];
public Mouse[] touchPad = new Mouse[DS4_CONTROLLER_COUNT];
2019-12-18 22:33:23 +01:00
public bool running = false;
private DS4State[] MappedState = new DS4State[DS4_CONTROLLER_COUNT];
private DS4State[] CurrentState = new DS4State[DS4_CONTROLLER_COUNT];
private DS4State[] PreviousState = new DS4State[DS4_CONTROLLER_COUNT];
private DS4State[] TempState = new DS4State[DS4_CONTROLLER_COUNT];
public DS4StateExposed[] ExposedState = new DS4StateExposed[DS4_CONTROLLER_COUNT];
2019-12-18 22:33:23 +01:00
public ControllerSlotManager slotManager = new ControllerSlotManager();
public bool recordingMacro = false;
public event EventHandler<DebugEventArgs> Debug = null;
bool[] buttonsdown = new bool[4] { false, false, false, false };
bool[] held = new bool[DS4_CONTROLLER_COUNT];
int[] oldmouse = new int[DS4_CONTROLLER_COUNT] { -1, -1, -1, -1 };
2019-04-18 04:29:16 +02:00
public OutputDevice[] outputDevices = new OutputDevice[4] { null, null, null, null };
2017-09-06 04:28:54 +02:00
Thread tempThread;
Thread tempBusThread;
public List<string> affectedDevs = new List<string>()
{
@"HID\VID_054C&PID_05C4",
@"HID\VID_054C&PID_09CC&MI_03",
@"HID\VID_054C&PID_0BA0&MI_03",
@"HID\{00001124-0000-1000-8000-00805f9b34fb}_VID&0002054c_PID&05c4",
@"HID\{00001124-0000-1000-8000-00805f9b34fb}_VID&0002054c_PID&09cc",
};
public bool suspending;
2017-05-11 17:13:51 +02:00
//SoundPlayer sp = new SoundPlayer();
private UdpServer _udpServer;
private OutputSlotManager outputslotMan;
2019-12-18 22:33:23 +01:00
public event EventHandler ServiceStarted;
public event EventHandler PreServiceStop;
public event EventHandler ServiceStopped;
public event EventHandler RunningChanged;
//public event EventHandler HotplugFinished;
public delegate void HotplugControllerHandler(ControlService sender, DS4Device device, int index);
public event HotplugControllerHandler HotplugController;
2019-07-02 09:06:32 +02:00
private byte[][] udpOutBuffers = new byte[4][]
{
new byte[100], new byte[100],
new byte[100], new byte[100]
};
void GetPadDetailForIdx(int padIdx, ref DualShockPadMeta meta)
{
//meta = new DualShockPadMeta();
meta.PadId = (byte) padIdx;
meta.Model = DsModel.DS4;
var d = DS4Controllers[padIdx];
if (d == null)
{
meta.PadMacAddress = null;
meta.PadState = DsState.Disconnected;
meta.ConnectionType = DsConnection.None;
meta.Model = DsModel.None;
meta.BatteryStatus = 0;
meta.IsActive = false;
return;
//return meta;
}
bool isValidSerial = false;
//if (d.isValidSerial())
//{
string stringMac = d.getMacAddress();
if (!string.IsNullOrEmpty(stringMac))
{
stringMac = string.Join("", stringMac.Split(':'));
//stringMac = stringMac.Replace(":", "").Trim();
meta.PadMacAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(stringMac);
isValidSerial = d.isValidSerial();
}
//}
if (!isValidSerial)
{
//meta.PadMacAddress = null;
meta.PadState = DsState.Disconnected;
}
else
{
if (d.isSynced() || d.IsAlive())
meta.PadState = DsState.Connected;
else
meta.PadState = DsState.Reserved;
}
meta.ConnectionType = (d.getConnectionType() == ConnectionType.USB) ? DsConnection.Usb : DsConnection.Bluetooth;
meta.IsActive = !d.isDS4Idle();
if (d.isCharging() && d.getBattery() >= 100)
meta.BatteryStatus = DsBattery.Charged;
else
{
if (d.getBattery() >= 95)
meta.BatteryStatus = DsBattery.Full;
else if (d.getBattery() >= 70)
meta.BatteryStatus = DsBattery.High;
else if (d.getBattery() >= 50)
meta.BatteryStatus = DsBattery.Medium;
else if (d.getBattery() >= 20)
meta.BatteryStatus = DsBattery.Low;
else if (d.getBattery() >= 5)
meta.BatteryStatus = DsBattery.Dying;
else
meta.BatteryStatus = DsBattery.None;
}
//return meta;
}
private object busThrLck = new object();
private bool busThrRunning = false;
private Queue<Action> busEvtQueue = new Queue<Action>();
private object busEvtQueueLock = new object();
public ControlService()
{
2019-09-06 16:41:55 +02:00
Crc32Algorithm.InitializeTable(DS4Device.DefaultPolynomial);
2019-12-18 22:33:23 +01:00
//sp.Stream = DS4WinWPF.Properties.Resources.EE;
// Cause thread affinity to not be tied to main GUI thread
2020-01-26 04:22:18 +01:00
tempBusThread = new Thread(() =>
{
//_udpServer = new UdpServer(GetPadDetailForIdx);
busThrRunning = true;
while (busThrRunning)
{
lock (busEvtQueueLock)
{
Action tempAct = null;
for (int actInd = 0, actLen = busEvtQueue.Count; actInd < actLen; actInd++)
{
tempAct = busEvtQueue.Dequeue();
tempAct.Invoke();
}
}
lock (busThrLck)
Monitor.Wait(busThrLck);
}
});
tempBusThread.Priority = ThreadPriority.Normal;
tempBusThread.IsBackground = true;
tempBusThread.Start();
//while (_udpServer == null)
//{
// Thread.SpinWait(500);
//}
2020-01-26 04:22:18 +01:00
for (int i = 0, arlength = DS4Controllers.Length; i < arlength; i++)
{
MappedState[i] = new DS4State();
CurrentState[i] = new DS4State();
TempState[i] = new DS4State();
PreviousState[i] = new DS4State();
ExposedState[i] = new DS4StateExposed(CurrentState[i]);
}
outputslotMan = new OutputSlotManager();
DS4Devices.RequestElevation += DS4Devices_RequestElevation;
}
private void DS4Devices_RequestElevation(RequestElevationArgs args)
{
// Launches an elevated child process to re-enable device
2020-02-14 00:18:56 +01:00
ProcessStartInfo startInfo =
new ProcessStartInfo(Global.exelocation);
startInfo.Verb = "runas";
startInfo.Arguments = "re-enabledevice " + args.InstanceId;
try
{
Process child = Process.Start(startInfo);
if (!child.WaitForExit(30000))
{
child.Kill();
}
else
{
args.StatusCode = child.ExitCode;
}
child.Dispose();
}
catch { }
2020-01-26 04:22:18 +01:00
}
public void LaunchHidGuardHelper()
{
2020-01-26 04:02:37 +01:00
if (Global.hidguardInstalled)
{
2020-01-26 04:22:18 +01:00
LogDebug("HidGuardian in use. Launching HidGuardHelper.");
ProcessStartInfo startInfo =
2019-12-18 22:33:23 +01:00
new ProcessStartInfo(Global.exedirpath + "\\HidGuardHelper.exe");
startInfo.Verb = "runas";
startInfo.Arguments = Process.GetCurrentProcess().Id.ToString();
2019-12-18 22:33:23 +01:00
startInfo.WorkingDirectory = Global.exedirpath;
try
{ Process tempProc = Process.Start(startInfo); tempProc.Dispose(); }
catch { }
}
}
private void TestQueueBus(Action temp)
{
lock (busEvtQueueLock)
{
busEvtQueue.Enqueue(temp);
}
lock (busThrLck)
Monitor.Pulse(busThrLck);
}
public void ChangeUDPStatus(bool state, bool openPort=true)
{
if (state && _udpServer == null)
{
2018-12-01 07:58:50 +01:00
udpChangeStatus = true;
TestQueueBus(() =>
{
_udpServer = new UdpServer(GetPadDetailForIdx);
if (openPort)
{
2018-12-06 00:57:01 +01:00
// Change thread affinity of object to have normal priority
Task.Run(() =>
{
var UDP_SERVER_PORT = Global.getUDPServerPortNum();
var UDP_SERVER_LISTEN_ADDRESS = Global.getUDPServerListenAddress();
try
{
_udpServer.Start(UDP_SERVER_PORT, UDP_SERVER_LISTEN_ADDRESS);
LogDebug($"UDP server listening on address {UDP_SERVER_LISTEN_ADDRESS} port {UDP_SERVER_PORT}");
}
catch (System.Net.Sockets.SocketException ex)
{
var errMsg = String.Format("Couldn't start UDP server on address {0}:{1}, outside applications won't be able to access pad data ({2})", UDP_SERVER_LISTEN_ADDRESS, UDP_SERVER_PORT, ex.SocketErrorCode);
LogDebug(errMsg, true);
AppLogger.LogToTray(errMsg, true, true);
}
}).Wait();
}
udpChangeStatus = false;
});
}
else if (!state && _udpServer != null)
{
TestQueueBus(() =>
{
udpChangeStatus = true;
_udpServer.Stop();
_udpServer = null;
AppLogger.LogToGui("Closed UDP server", false);
udpChangeStatus = false;
});
}
}
public void ChangeMotionEventStatus(bool state)
{
IEnumerable<DS4Device> devices = DS4Devices.getDS4Controllers();
if (state)
{
foreach (DS4Device dev in devices)
{
dev.queueEvent(() =>
{
dev.Report += dev.MotionEvent;
});
}
}
else
{
foreach (DS4Device dev in devices)
{
dev.queueEvent(() =>
{
dev.Report -= dev.MotionEvent;
});
}
}
}
private bool udpChangeStatus = false;
public bool changingUDPPort = false;
public async void UseUDPPort()
{
changingUDPPort = true;
IEnumerable<DS4Device> devices = DS4Devices.getDS4Controllers();
foreach (DS4Device dev in devices)
{
dev.queueEvent(() =>
{
dev.Report -= dev.MotionEvent;
});
}
await Task.Delay(100);
2018-08-08 10:54:19 +02:00
var UDP_SERVER_PORT = Global.getUDPServerPortNum();
var UDP_SERVER_LISTEN_ADDRESS = Global.getUDPServerListenAddress();
2018-08-08 10:54:19 +02:00
try
{
_udpServer.Start(UDP_SERVER_PORT, UDP_SERVER_LISTEN_ADDRESS);
2018-08-08 10:54:19 +02:00
foreach (DS4Device dev in devices)
{
2018-08-08 10:54:19 +02:00
dev.queueEvent(() =>
{
dev.Report += dev.MotionEvent;
});
}
LogDebug($"UDP server listening on address {UDP_SERVER_LISTEN_ADDRESS} port {UDP_SERVER_PORT}");
2018-08-08 10:54:19 +02:00
}
catch (System.Net.Sockets.SocketException ex)
{
var errMsg = String.Format("Couldn't start UDP server on address {0}:{1}, outside applications won't be able to access pad data ({2})", UDP_SERVER_LISTEN_ADDRESS, UDP_SERVER_PORT, ex.SocketErrorCode);
2018-08-08 10:54:19 +02:00
LogDebug(errMsg, true);
AppLogger.LogToTray(errMsg, true, true);
}
changingUDPPort = false;
}
2017-08-25 06:08:35 +02:00
private void WarnExclusiveModeFailure(DS4Device device)
{
if (DS4Devices.isExclusiveMode && !device.isExclusive())
{
2019-12-18 22:33:23 +01:00
string message = DS4WinWPF.Properties.Resources.CouldNotOpenDS4.Replace("*Mac address*", device.getMacAddress()) + " " +
DS4WinWPF.Properties.Resources.QuitOtherPrograms;
2015-01-17 21:16:48 +01:00
LogDebug(message, true);
AppLogger.LogToTray(message, true);
}
2017-04-21 05:09:08 +02:00
}
private void startViGEm()
{
tempThread = new Thread(() => { try { x360Bus = new X360BusDevice(); } catch { } });
//tempThread = new Thread(() => { try { vigemTestClient = new ViGEmClient(); } catch { } });
tempThread.Priority = ThreadPriority.AboveNormal;
tempThread.IsBackground = true;
tempThread.Start();
while (tempThread.IsAlive)
{
Thread.SpinWait(500);
}
tempThread = null;
}
private void stopViGEm()
{
if (x360Bus != null)
{
x360Bus.UnplugAll();
x360Bus.Stop();
x360Bus = null;
}
//if (vigemTestClient != null)
//{
// vigemTestClient.Dispose();
// vigemTestClient = null;
//}
}
public void PluginOutDev(int index, DS4Device device)
{
OutContType contType = Global.OutContType[index];
if (useDInputOnly[index])
{
if (contType == OutContType.X360)
{
LogDebug("Plugging in X360 Controller for input #" + (index + 1));
activeOutDevType[index] = OutContType.X360;
//Xbox360OutDevice tempXbox = new Xbox360OutDevice(vigemTestClient);
Xbox360ScpOutDevice tempXbox = outputslotMan.AllocateController(OutContType.X360, x360Bus, index)
as Xbox360ScpOutDevice;
//outputDevices[index] = tempXbox;
int devIndex = index;
tempXbox.FeedbackReceived += (sender, small, large, slotIdx) =>
{
SetDevRumble(device, large, small, devIndex);
};
//Nefarius.ViGEm.Client.Targets.Xbox360FeedbackReceivedEventHandler p = (sender, args) =>
// {
// SetDevRumble(device, args.LargeMotor, args.SmallMotor, devIndex);
// };
//tempXbox.cont.FeedbackReceived += p;
//tempXbox.forceFeedbackCall = p;
outputslotMan.DeferredPlugin(tempXbox, index, outputDevices);
2019-12-18 22:33:23 +01:00
//tempXbox.Connect();
//LogDebug("X360 Controller #" + (index + 1) + " connected");
}
//else if (contType == OutContType.DS4)
//{
// LogDebug("Plugging in DS4 Controller for input #" + (index + 1));
// activeOutDevType[index] = OutContType.DS4;
// //DS4OutDevice tempDS4 = new DS4OutDevice(vigemTestClient);
// DS4OutDevice tempDS4 = outputslotMan.AllocateController(OutContType.DS4, vigemTestClient)
// as DS4OutDevice;
// //outputDevices[index] = tempDS4;
// int devIndex = index;
// //Nefarius.ViGEm.Client.Targets.DualShock4FeedbackReceivedEventHandler p = (sender, args) =>
// // {
// // //bool useRumble = false; bool useLight = false;
// // byte largeMotor = args.LargeMotor;
// // byte smallMotor = args.SmallMotor;
// // SetDevRumble(device, largeMotor, smallMotor, devIndex);
// // //DS4Color color = new DS4Color(args.LightbarColor.Red,
// // // args.LightbarColor.Green,
// // // args.LightbarColor.Blue);
// // ///*Console.WriteLine("IN EVENT");
// // //Console.WriteLine("Rumble ({0}, {1}) | Light ({2}, {3}, {4}) {5}",
// // // largeMotor, smallMotor, color.red, color.green, color.blue, DateTime.Now.ToLongTimeString());
// // // */
// // //if (largeMotor != 0 || smallMotor != 0)
// // //{
// // // useRumble = true;
// // //}
// // //if (color.red != 0 || color.green != 0 || color.blue != 0)
// // //{
// // // useLight = true;
// // //}
// // //if (!useRumble && !useLight)
// // //{
// // // //Console.WriteLine("Fallback");
// // // if (device.LeftHeavySlowRumble != 0 || device.RightLightFastRumble != 0)
// // // {
// // // useRumble = true;
// // // }
// // // /*else if (device.LightBarColor.red != 0 ||
// // // device.LightBarColor.green != 0 ||
// // // device.LightBarColor.blue != 0)
// // // {
// // // useLight = true;
// // // }
// // // */
// // //}
// // //if (useRumble)
// // //{
// // // //Console.WriteLine("Perform rumble");
// // // SetDevRumble(device, largeMotor, smallMotor, devIndex);
// // //}
// // //if (useLight)
// // //{
// // // //Console.WriteLine("Change lightbar color");
// // // DS4HapticState haptics = new DS4HapticState
// // // {
// // // LightBarColor = color,
// // // };
// // // device.SetHapticState(ref haptics);
// // //}
// // //Console.WriteLine();
// //};
// //tempDS4.cont.FeedbackReceived += p;
// //tempDS4.forceFeedbackCall = p;
// outputslotMan.DeferredPlugin(tempDS4, index, outputDevices);
// //tempDS4.Connect();
// //LogDebug("DS4 Controller #" + (index + 1) + " connected");
//}
}
useDInputOnly[index] = false;
}
public void UnplugOutDev(int index, DS4Device device, bool immediate = false)
{
if (!useDInputOnly[index])
{
//OutContType contType = Global.OutContType[index];
OutputDevice dev = outputDevices[index];
if (dev != null)
{
string tempType = dev.GetDeviceType();
LogDebug("Unplugging " + tempType + " Controller for input #" + (index + 1), false);
outputDevices[index] = null;
activeOutDevType[index] = OutContType.None;
outputslotMan.DeferredRemoval(dev, index, outputDevices, immediate);
//dev.Disconnect();
//LogDebug(tempType + " Controller # " + (index + 1) + " unplugged");
useDInputOnly[index] = true;
}
}
}
2019-12-18 22:33:23 +01:00
public bool Start(bool showlog = true)
{
startViGEm();
//if (vigemTestClient != null)
if (x360Bus.Open() && x360Bus.Start())
{
if (showlog)
2019-12-18 22:33:23 +01:00
LogDebug(DS4WinWPF.Properties.Resources.Starting);
2020-04-16 01:37:53 +02:00
//LogDebug($"Connection to ViGEmBus {Global.vigembusVersion} established");
LogDebug($"Connection to ScpVBus established");
DS4Devices.isExclusiveMode = getUseExclusiveMode();
2019-12-18 22:33:23 +01:00
//uiContext = tempui as SynchronizationContext;
if (showlog)
{
2019-12-18 22:33:23 +01:00
LogDebug(DS4WinWPF.Properties.Resources.SearchingController);
LogDebug(DS4Devices.isExclusiveMode ? DS4WinWPF.Properties.Resources.UsingExclusive : DS4WinWPF.Properties.Resources.UsingShared);
}
if (isUsingUDPServer() && _udpServer == null)
{
ChangeUDPStatus(true, false);
while (udpChangeStatus == true)
{
2018-12-01 07:58:50 +01:00
Thread.SpinWait(500);
}
}
try
{
DS4Devices.findControllers();
IEnumerable<DS4Device> devices = DS4Devices.getDS4Controllers();
//int ind = 0;
2017-04-22 05:01:20 +02:00
DS4LightBar.defaultLight = false;
//foreach (DS4Device device in devices)
2019-02-16 09:50:53 +01:00
//for (int i = 0, devCount = devices.Count(); i < devCount; i++)
int i = 0;
for (var devEnum = devices.GetEnumerator(); devEnum.MoveNext(); i++)
{
2019-02-16 09:50:53 +01:00
DS4Device device = devEnum.Current;
//DS4Device device = devices.ElementAt(i);
if (showlog)
2019-12-18 22:33:23 +01:00
LogDebug(DS4WinWPF.Properties.Resources.FoundController + " " + device.getMacAddress() + " (" + device.getConnectionType() + ") (" +
device.DisplayName + ")");
2017-08-25 06:08:35 +02:00
Task task = new Task(() => { Thread.Sleep(5); WarnExclusiveModeFailure(device); });
task.Start();
DS4Controllers[i] = device;
2019-12-18 22:33:23 +01:00
slotManager.AddController(device, i);
device.Removal += this.On_DS4Removal;
device.Removal += DS4Devices.On_Removal;
device.SyncChange += this.On_SyncChange;
device.SyncChange += DS4Devices.UpdateSerial;
device.SerialChange += this.On_SerialChange;
2019-12-21 03:08:27 +01:00
device.ChargingChanged += CheckQuickCharge;
touchPad[i] = new Mouse(i, device);
if (!useTempProfile[i])
{
if (device.isValidSerial() && containsLinkedProfile(device.getMacAddress()))
{
ProfilePath[i] = getLinkedProfile(device.getMacAddress());
Global.linkedProfileCheck[i] = true;
}
else
{
ProfilePath[i] = OlderProfilePath[i];
Global.linkedProfileCheck[i] = false;
}
LoadProfile(i, false, this, false, false);
}
device.LightBarColor = getMainColor(i);
if (!getDInputOnly(i) && device.isSynced())
{
2019-12-18 22:33:23 +01:00
//useDInputOnly[i] = false;
PluginOutDev(i, device);
2019-12-18 22:33:23 +01:00
}
else
{
useDInputOnly[i] = true;
Global.activeOutDevType[i] = OutContType.None;
}
int tempIdx = i;
device.Report += (sender, e) =>
{
this.On_Report(sender, e, tempIdx);
};
DS4Device.ReportHandler<EventArgs> tempEvnt = (sender, args) =>
{
DualShockPadMeta padDetail = new DualShockPadMeta();
GetPadDetailForIdx(tempIdx, ref padDetail);
2019-07-02 09:06:32 +02:00
_udpServer.NewReportIncoming(ref padDetail, CurrentState[tempIdx], udpOutBuffers[tempIdx]);
};
device.MotionEvent = tempEvnt;
if (_udpServer != null)
{
device.Report += tempEvnt;
}
TouchPadOn(i, device);
CheckProfileOptions(i, device, true);
device.StartUpdate();
//string filename = ProfilePath[ind];
//ind++;
if (showlog)
2017-04-21 05:09:08 +02:00
{
if (File.Exists(appdatapath + "\\Profiles\\" + ProfilePath[i] + ".xml"))
{
2019-12-18 22:33:23 +01:00
string prolog = DS4WinWPF.Properties.Resources.UsingProfile.Replace("*number*", (i + 1).ToString()).Replace("*Profile name*", ProfilePath[i]);
LogDebug(prolog);
AppLogger.LogToTray(prolog);
}
else
{
2019-12-18 22:33:23 +01:00
string prolog = DS4WinWPF.Properties.Resources.NotUsingProfile.Replace("*number*", (i + 1).ToString());
LogDebug(prolog);
AppLogger.LogToTray(prolog);
}
2017-04-21 05:09:08 +02:00
}
if (i >= 4) // out of Xinput devices!
break;
}
}
catch (Exception e)
{
LogDebug(e.Message, true);
AppLogger.LogToTray(e.Message, true);
}
running = true;
if (_udpServer != null)
{
//var UDP_SERVER_PORT = 26760;
var UDP_SERVER_PORT = Global.getUDPServerPortNum();
var UDP_SERVER_LISTEN_ADDRESS = Global.getUDPServerListenAddress();
try
{
_udpServer.Start(UDP_SERVER_PORT, UDP_SERVER_LISTEN_ADDRESS);
LogDebug($"UDP server listening on address {UDP_SERVER_LISTEN_ADDRESS} port {UDP_SERVER_PORT}");
}
catch (System.Net.Sockets.SocketException ex)
{
var errMsg = String.Format("Couldn't start UDP server on address {0}:{1}, outside applications won't be able to access pad data ({2})", UDP_SERVER_LISTEN_ADDRESS, UDP_SERVER_PORT, ex.SocketErrorCode);
LogDebug(errMsg, true);
AppLogger.LogToTray(errMsg, true, true);
}
}
}
2017-04-26 05:07:02 +02:00
else
{
string logMessage = string.Empty;
2020-04-16 01:37:53 +02:00
/*if (!vigemInstalled)
{
logMessage = "ViGEmBus is not installed";
}
else
{
logMessage = "Could not connect to ViGEmBus. Please check the status of the System device in Device Manager and if Visual C++ 2017 Redistributable is installed.";
2020-04-16 01:37:53 +02:00
}*/
logMessage = "Could not connect to ScpVBus";
2017-04-26 05:07:02 +02:00
LogDebug(logMessage);
AppLogger.LogToTray(logMessage);
2017-04-26 05:07:02 +02:00
}
2017-04-26 05:07:02 +02:00
runHotPlug = true;
2019-12-18 22:33:23 +01:00
ServiceStarted?.Invoke(this, EventArgs.Empty);
RunningChanged?.Invoke(this, EventArgs.Empty);
return true;
}
2019-12-21 03:08:27 +01:00
private void CheckQuickCharge(object sender, EventArgs e)
{
DS4Device device = sender as DS4Device;
if (device.ConnectionType == ConnectionType.BT && getQuickCharge() &&
device.Charging)
{
device.DisconnectBT();
}
}
public void PrepareAbort()
{
for (int i = 0, arlength = DS4Controllers.Length; i < arlength; i++)
{
DS4Device tempDevice = DS4Controllers[i];
if (tempDevice != null)
{
tempDevice.PrepareAbort();
}
}
}
public bool Stop(bool showlog = true)
{
if (running)
{
running = false;
2017-04-26 05:07:02 +02:00
runHotPlug = false;
2019-12-18 22:33:23 +01:00
PreServiceStop?.Invoke(this, EventArgs.Empty);
2017-04-26 05:07:02 +02:00
if (showlog)
2019-12-18 22:33:23 +01:00
LogDebug(DS4WinWPF.Properties.Resources.StoppingX360);
2019-03-19 07:30:54 +01:00
LogDebug("Closing connection to ViGEmBus");
2020-03-30 05:11:42 +02:00
bool anyUnplugged = false;
for (int i = 0, arlength = DS4Controllers.Length; i < arlength; i++)
{
DS4Device tempDevice = DS4Controllers[i];
if (tempDevice != null)
{
if ((DCBTatStop && !tempDevice.isCharging()) || suspending)
{
if (tempDevice.getConnectionType() == ConnectionType.BT)
{
tempDevice.StopUpdate();
tempDevice.DisconnectBT(true);
}
else if (tempDevice.getConnectionType() == ConnectionType.SONYWA)
{
tempDevice.StopUpdate();
tempDevice.DisconnectDongle(true);
}
else
{
tempDevice.StopUpdate();
}
}
else
{
DS4LightBar.forcelight[i] = false;
DS4LightBar.forcedFlash[i] = 0;
2017-04-22 05:01:20 +02:00
DS4LightBar.defaultLight = true;
DS4LightBar.updateLightBar(DS4Controllers[i], i);
tempDevice.IsRemoved = true;
tempDevice.StopUpdate();
DS4Devices.RemoveDevice(tempDevice);
2017-07-18 22:37:01 +02:00
Thread.Sleep(50);
}
CurrentState[i].Battery = PreviousState[i].Battery = 0; // Reset for the next connection's initial status change.
OutputDevice tempout = outputDevices[i];
if (tempout != null)
{
UnplugOutDev(i, tempDevice, true);
2020-03-30 05:11:42 +02:00
anyUnplugged = true;
}
//outputDevices[i] = null;
//useDInputOnly[i] = true;
//Global.activeOutDevType[i] = OutContType.None;
DS4Controllers[i] = null;
touchPad[i] = null;
lag[i] = false;
inWarnMonitor[i] = false;
}
}
if (showlog)
2019-12-18 22:33:23 +01:00
LogDebug(DS4WinWPF.Properties.Resources.StoppingDS4);
2017-04-21 05:09:08 +02:00
DS4Devices.stopControllers();
2019-12-18 22:33:23 +01:00
slotManager.ClearControllerList();
if (_udpServer != null)
ChangeUDPStatus(false);
//_udpServer.Stop();
if (showlog)
2019-12-18 22:33:23 +01:00
LogDebug(DS4WinWPF.Properties.Resources.StoppedDS4Windows);
while (outputslotMan.RunningQueue)
{
Thread.SpinWait(500);
}
2020-03-30 05:11:42 +02:00
if (anyUnplugged)
{
Thread.Sleep(OutputSlotManager.DELAY_TIME);
}
stopViGEm();
}
2017-04-26 05:07:02 +02:00
runHotPlug = false;
2019-12-18 22:33:23 +01:00
ServiceStopped?.Invoke(this, EventArgs.Empty);
RunningChanged?.Invoke(this, EventArgs.Empty);
return true;
}
public bool HotPlug()
{
if (running)
{
DS4Devices.findControllers();
IEnumerable<DS4Device> devices = DS4Devices.getDS4Controllers();
2017-04-21 05:09:08 +02:00
//foreach (DS4Device device in devices)
2019-02-16 09:50:53 +01:00
//for (int i = 0, devlen = devices.Count(); i < devlen; i++)
for (var devEnum = devices.GetEnumerator(); devEnum.MoveNext();)
{
2019-02-16 09:50:53 +01:00
DS4Device device = devEnum.Current;
//DS4Device device = devices.ElementAt(i);
if (device.isDisconnectingStatus())
continue;
if (((Func<bool>)delegate
{
for (Int32 Index = 0, arlength = DS4Controllers.Length; Index < arlength; Index++)
{
if (DS4Controllers[Index] != null &&
DS4Controllers[Index].getMacAddress() == device.getMacAddress())
return true;
}
return false;
})())
{
continue;
}
2017-04-21 05:09:08 +02:00
for (Int32 Index = 0, arlength = DS4Controllers.Length; Index < arlength; Index++)
2017-04-21 05:09:08 +02:00
{
if (DS4Controllers[Index] == null)
{
2019-12-18 22:33:23 +01:00
//LogDebug(DS4WinWPF.Properties.Resources.FoundController + device.getMacAddress() + " (" + device.getConnectionType() + ")");
LogDebug(DS4WinWPF.Properties.Resources.FoundController + " " + device.getMacAddress() + " (" + device.getConnectionType() + ") (" +
device.DisplayName + ")");
2017-08-25 06:08:35 +02:00
Task task = new Task(() => { Thread.Sleep(5); WarnExclusiveModeFailure(device); });
task.Start();
DS4Controllers[Index] = device;
2019-12-18 22:33:23 +01:00
slotManager.AddController(device, Index);
device.Removal += this.On_DS4Removal;
device.Removal += DS4Devices.On_Removal;
device.SyncChange += this.On_SyncChange;
device.SyncChange += DS4Devices.UpdateSerial;
device.SerialChange += this.On_SerialChange;
2019-12-21 03:08:27 +01:00
device.ChargingChanged += CheckQuickCharge;
touchPad[Index] = new Mouse(Index, device);
if (!useTempProfile[Index])
{
if (device.isValidSerial() && containsLinkedProfile(device.getMacAddress()))
{
ProfilePath[Index] = getLinkedProfile(device.getMacAddress());
Global.linkedProfileCheck[Index] = true;
}
else
{
ProfilePath[Index] = OlderProfilePath[Index];
Global.linkedProfileCheck[Index] = false;
}
LoadProfile(Index, false, this, false, false);
}
device.LightBarColor = getMainColor(Index);
2018-04-10 01:21:49 +02:00
int tempIdx = Index;
device.Report += (sender, e) =>
{
this.On_Report(sender, e, tempIdx);
};
DS4Device.ReportHandler<EventArgs> tempEvnt = (sender, args) =>
2018-05-06 09:10:49 +02:00
{
DualShockPadMeta padDetail = new DualShockPadMeta();
GetPadDetailForIdx(tempIdx, ref padDetail);
2019-07-02 09:06:32 +02:00
_udpServer.NewReportIncoming(ref padDetail, CurrentState[tempIdx], udpOutBuffers[tempIdx]);
};
device.MotionEvent = tempEvnt;
2018-05-06 09:10:49 +02:00
if (_udpServer != null)
{
2018-05-06 09:10:49 +02:00
device.Report += tempEvnt;
}
if (!getDInputOnly(Index) && device.isSynced())
{
2019-12-18 22:33:23 +01:00
//useDInputOnly[Index] = false;
PluginOutDev(Index, device);
}
else
{
useDInputOnly[Index] = true;
Global.activeOutDevType[Index] = OutContType.None;
}
TouchPadOn(Index, device);
CheckProfileOptions(Index, device);
device.StartUpdate();
//string filename = Path.GetFileName(ProfilePath[Index]);
if (File.Exists(appdatapath + "\\Profiles\\" + ProfilePath[Index] + ".xml"))
{
2019-12-18 22:33:23 +01:00
string prolog = DS4WinWPF.Properties.Resources.UsingProfile.Replace("*number*", (Index + 1).ToString()).Replace("*Profile name*", ProfilePath[Index]);
LogDebug(prolog);
AppLogger.LogToTray(prolog);
}
else
{
2019-12-18 22:33:23 +01:00
string prolog = DS4WinWPF.Properties.Resources.NotUsingProfile.Replace("*number*", (Index + 1).ToString());
LogDebug(prolog);
AppLogger.LogToTray(prolog);
}
2017-04-21 05:09:08 +02:00
2019-12-18 22:33:23 +01:00
HotplugController?.Invoke(this, device, Index);
break;
}
2017-04-21 05:09:08 +02:00
}
}
}
return true;
}
private void CheckProfileOptions(int ind, DS4Device device, bool startUp=false)
{
device.setIdleTimeout(getIdleDisconnectTimeout(ind));
device.setBTPollRate(getBTPollRate(ind));
touchPad[ind].ResetTrackAccel(getTrackballFriction(ind));
if (!startUp)
{
CheckLauchProfileOption(ind, device);
}
}
private void CheckLauchProfileOption(int ind, DS4Device device)
{
string programPath = LaunchProgram[ind];
if (programPath != string.Empty)
{
2017-11-07 03:17:21 +01:00
System.Diagnostics.Process[] localAll = System.Diagnostics.Process.GetProcesses();
bool procFound = false;
for (int procInd = 0, procsLen = localAll.Length; !procFound && procInd < procsLen; procInd++)
{
try
{
string temp = localAll[procInd].MainModule.FileName;
if (temp == programPath)
{
procFound = true;
}
}
// Ignore any process for which this information
// is not exposed
catch { }
}
if (!procFound)
{
Task processTask = new Task(() =>
{
2017-11-10 18:22:26 +01:00
Thread.Sleep(5000);
2017-11-07 03:17:21 +01:00
System.Diagnostics.Process tempProcess = new System.Diagnostics.Process();
tempProcess.StartInfo.FileName = programPath;
tempProcess.StartInfo.WorkingDirectory = new FileInfo(programPath).Directory.ToString();
//tempProcess.StartInfo.UseShellExecute = false;
try { tempProcess.Start(); }
catch { }
});
processTask.Start();
}
}
}
public void TouchPadOn(int ind, DS4Device device)
{
Mouse tPad = touchPad[ind];
//ITouchpadBehaviour tPad = touchPad[ind];
device.Touchpad.TouchButtonDown += tPad.touchButtonDown;
device.Touchpad.TouchButtonUp += tPad.touchButtonUp;
device.Touchpad.TouchesBegan += tPad.touchesBegan;
device.Touchpad.TouchesMoved += tPad.touchesMoved;
device.Touchpad.TouchesEnded += tPad.touchesEnded;
device.Touchpad.TouchUnchanged += tPad.touchUnchanged;
//device.Touchpad.PreTouchProcess += delegate { touchPad[ind].populatePriorButtonStates(); };
device.Touchpad.PreTouchProcess += (sender, args) => { touchPad[ind].populatePriorButtonStates(); };
device.SixAxis.SixAccelMoved += tPad.sixaxisMoved;
//LogDebug("Touchpad mode for " + device.MacAddress + " is now " + tmode.ToString());
//Log.LogToTray("Touchpad mode for " + device.MacAddress + " is now " + tmode.ToString());
}
public string getDS4ControllerInfo(int index)
{
2017-05-10 02:23:51 +02:00
DS4Device d = DS4Controllers[index];
if (d != null)
{
if (!d.IsAlive())
{
2019-12-18 22:33:23 +01:00
return DS4WinWPF.Properties.Resources.Connecting;
}
2017-04-21 05:09:08 +02:00
string battery;
2017-04-21 05:09:08 +02:00
if (d.isCharging())
{
2017-04-21 05:09:08 +02:00
if (d.getBattery() >= 100)
2019-12-18 22:33:23 +01:00
battery = DS4WinWPF.Properties.Resources.Charged;
else
2019-12-18 22:33:23 +01:00
battery = DS4WinWPF.Properties.Resources.Charging.Replace("*number*", d.getBattery().ToString());
}
else
{
2019-12-18 22:33:23 +01:00
battery = DS4WinWPF.Properties.Resources.Battery.Replace("*number*", d.getBattery().ToString());
}
2017-04-21 05:09:08 +02:00
return d.getMacAddress() + " (" + d.getConnectionType() + "), " + battery;
//return d.MacAddress + " (" + d.ConnectionType + "), Battery is " + battery + ", Touchpad in " + modeSwitcher[index].ToString();
}
else
return string.Empty;
}
public string getDS4MacAddress(int index)
{
2017-05-10 02:23:51 +02:00
DS4Device d = DS4Controllers[index];
if (d != null)
{
if (!d.IsAlive())
{
2019-12-18 22:33:23 +01:00
return DS4WinWPF.Properties.Resources.Connecting;
}
2017-05-11 17:13:51 +02:00
2017-04-21 05:09:08 +02:00
return d.getMacAddress();
}
else
return string.Empty;
}
public string getShortDS4ControllerInfo(int index)
{
2017-05-10 02:23:51 +02:00
DS4Device d = DS4Controllers[index];
if (d != null)
{
2017-05-10 02:23:51 +02:00
string battery;
if (!d.IsAlive())
battery = "...";
2017-04-21 05:09:08 +02:00
if (d.isCharging())
{
2017-04-21 05:09:08 +02:00
if (d.getBattery() >= 100)
2019-12-18 22:33:23 +01:00
battery = DS4WinWPF.Properties.Resources.Full;
else
2017-04-21 05:09:08 +02:00
battery = d.getBattery() + "%+";
}
else
{
2017-04-21 05:09:08 +02:00
battery = d.getBattery() + "%";
}
2017-04-21 05:09:08 +02:00
return (d.getConnectionType() + " " + battery);
}
else
2019-12-18 22:33:23 +01:00
return DS4WinWPF.Properties.Resources.NoneText;
}
public string getDS4Battery(int index)
{
2017-05-10 02:23:51 +02:00
DS4Device d = DS4Controllers[index];
if (d != null)
{
string battery;
if (!d.IsAlive())
battery = "...";
2017-04-21 05:09:08 +02:00
if (d.isCharging())
{
2017-04-21 05:09:08 +02:00
if (d.getBattery() >= 100)
2019-12-18 22:33:23 +01:00
battery = DS4WinWPF.Properties.Resources.Full;
else
2017-04-21 05:09:08 +02:00
battery = d.getBattery() + "%+";
}
else
{
2017-04-21 05:09:08 +02:00
battery = d.getBattery() + "%";
}
2017-04-21 05:09:08 +02:00
return battery;
}
else
2019-12-18 22:33:23 +01:00
return DS4WinWPF.Properties.Resources.NA;
}
public string getDS4Status(int index)
{
2017-05-10 02:23:51 +02:00
DS4Device d = DS4Controllers[index];
if (d != null)
{
2017-04-21 05:09:08 +02:00
return d.getConnectionType() + "";
}
else
2019-12-18 22:33:23 +01:00
return DS4WinWPF.Properties.Resources.NoneText;
}
protected void On_SerialChange(object sender, EventArgs e)
{
DS4Device device = (DS4Device)sender;
int ind = -1;
for (int i = 0, arlength = DS4_CONTROLLER_COUNT; ind == -1 && i < arlength; i++)
{
DS4Device tempDev = DS4Controllers[i];
if (tempDev != null && device == tempDev)
ind = i;
}
if (ind >= 0)
{
OnDeviceSerialChange(this, ind, device.getMacAddress());
}
}
protected void On_SyncChange(object sender, EventArgs e)
{
DS4Device device = (DS4Device)sender;
int ind = -1;
for (int i = 0, arlength = DS4_CONTROLLER_COUNT; ind == -1 && i < arlength; i++)
{
DS4Device tempDev = DS4Controllers[i];
if (tempDev != null && device == tempDev)
ind = i;
}
if (ind >= 0)
{
bool synced = device.isSynced();
if (!synced)
{
if (!useDInputOnly[ind])
{
2019-10-25 09:08:48 +02:00
Global.activeOutDevType[ind] = OutContType.None;
UnplugOutDev(ind, device);
}
}
else
{
if (!getDInputOnly(ind))
{
PluginOutDev(ind, device);
}
}
}
}
//Called when DS4 is disconnected or timed out
protected virtual void On_DS4Removal(object sender, EventArgs e)
{
DS4Device device = (DS4Device)sender;
int ind = -1;
for (int i = 0, arlength = DS4Controllers.Length; ind == -1 && i < arlength; i++)
{
2017-04-21 05:09:08 +02:00
if (DS4Controllers[i] != null && device.getMacAddress() == DS4Controllers[i].getMacAddress())
ind = i;
}
if (ind != -1)
{
bool removingStatus = false;
lock (device.removeLocker)
{
if (!device.IsRemoving)
{
removingStatus = true;
device.IsRemoving = true;
}
}
if (removingStatus)
{
CurrentState[ind].Battery = PreviousState[ind].Battery = 0; // Reset for the next connection's initial status change.
if (!useDInputOnly[ind])
{
UnplugOutDev(ind, device);
}
// Use Task to reset device synth state and commit it
Task.Run(() =>
{
Mapping.Commit(ind);
}).Wait();
2019-12-18 22:33:23 +01:00
string removed = DS4WinWPF.Properties.Resources.ControllerWasRemoved.Replace("*Mac address*", (ind + 1).ToString());
if (device.getBattery() <= 20 &&
device.getConnectionType() == ConnectionType.BT && !device.isCharging())
{
2019-12-18 22:33:23 +01:00
removed += ". " + DS4WinWPF.Properties.Resources.ChargeController;
}
LogDebug(removed);
AppLogger.LogToTray(removed);
/*Stopwatch sw = new Stopwatch();
sw.Start();
while (sw.ElapsedMilliseconds < XINPUT_UNPLUG_SETTLE_TIME)
{
// Use SpinWait to keep control of current thread. Using Sleep could potentially
// cause other events to get run out of order
System.Threading.Thread.SpinWait(500);
}
sw.Stop();
*/
device.IsRemoved = true;
device.Synced = false;
DS4Controllers[ind] = null;
2019-12-18 22:33:23 +01:00
slotManager.RemoveController(device, ind);
touchPad[ind] = null;
lag[ind] = false;
inWarnMonitor[ind] = false;
2017-06-08 22:52:47 +02:00
useDInputOnly[ind] = true;
Global.activeOutDevType[ind] = OutContType.None;
2019-12-18 22:33:23 +01:00
/*uiContext?.Post(new SendOrPostCallback((state) =>
{
OnControllerRemoved(this, ind);
}), null);
2019-12-18 22:33:23 +01:00
*/
//Thread.Sleep(XINPUT_UNPLUG_SETTLE_TIME);
}
}
}
public bool[] lag = new bool[4] { false, false, false, false };
public bool[] inWarnMonitor = new bool[4] { false, false, false, false };
private byte[] currentBattery = new byte[4] { 0, 0, 0, 0 };
private bool[] charging = new bool[4] { false, false, false, false };
2017-07-27 04:38:34 +02:00
private string[] tempStrings = new string[4] { string.Empty, string.Empty, string.Empty, string.Empty };
// Called every time a new input report has arrived
//protected virtual void On_Report(object sender, EventArgs e, int ind)
protected virtual void On_Report(DS4Device device, EventArgs e, int ind)
{
//DS4Device device = (DS4Device)sender;
if (ind != -1)
{
if (getFlushHIDQueue(ind))
device.FlushHID();
2017-04-21 05:09:08 +02:00
2017-07-27 04:38:34 +02:00
string devError = tempStrings[ind] = device.error;
if (!string.IsNullOrEmpty(devError))
{
2019-12-18 22:33:23 +01:00
LogDebug(devError);
/*uiContext?.Post(new SendOrPostCallback(delegate (object state)
2017-07-27 04:38:34 +02:00
{
LogDebug(devError);
}), null);
2019-12-18 22:33:23 +01:00
*/
}
if (inWarnMonitor[ind])
{
int flashWhenLateAt = getFlashWhenLateAt();
if (!lag[ind] && device.Latency >= flashWhenLateAt)
2017-06-08 22:52:47 +02:00
{
2017-06-29 15:16:02 +02:00
lag[ind] = true;
LagFlashWarning(device, ind, true);
2019-12-18 22:33:23 +01:00
/*uiContext?.Post(new SendOrPostCallback(delegate (object state)
2017-06-08 22:52:47 +02:00
{
LagFlashWarning(ind, true);
}), null);
2019-12-18 22:33:23 +01:00
*/
2017-06-08 22:52:47 +02:00
}
else if (lag[ind] && device.Latency < flashWhenLateAt)
2017-06-08 22:52:47 +02:00
{
2017-06-29 15:16:02 +02:00
lag[ind] = false;
LagFlashWarning(device, ind, false);
2019-12-18 22:33:23 +01:00
/*uiContext?.Post(new SendOrPostCallback(delegate (object state)
2017-06-08 22:52:47 +02:00
{
LagFlashWarning(ind, false);
}), null);
2019-12-18 22:33:23 +01:00
*/
2017-06-08 22:52:47 +02:00
}
}
else
{
if (DateTime.UtcNow - device.firstActive > TimeSpan.FromSeconds(5))
{
inWarnMonitor[ind] = true;
}
}
2017-07-16 10:30:49 +02:00
device.getCurrentState(CurrentState[ind]);
DS4State cState = CurrentState[ind];
2017-07-27 04:38:34 +02:00
DS4State pState = device.getPreviousStateRef();
//device.getPreviousState(PreviousState[ind]);
//DS4State pState = PreviousState[ind];
if (device.firstReport && device.IsAlive())
{
device.firstReport = false;
2019-12-18 22:33:23 +01:00
/*uiContext?.Post(new SendOrPostCallback(delegate (object state)
2017-06-08 22:52:47 +02:00
{
OnDeviceStatusChanged(this, ind);
}), null);
2019-12-18 22:33:23 +01:00
*/
}
2019-12-18 22:33:23 +01:00
//else if (pState.Battery != cState.Battery || device.oldCharging != device.isCharging())
//{
// byte tempBattery = currentBattery[ind] = cState.Battery;
// bool tempCharging = charging[ind] = device.isCharging();
// /*uiContext?.Post(new SendOrPostCallback(delegate (object state)
// {
// OnBatteryStatusChange(this, ind, tempBattery, tempCharging);
// }), null);
// */
//}
if (getEnableTouchToggle(ind))
CheckForTouchToggle(ind, cState, pState);
cState = Mapping.SetCurveAndDeadzone(ind, cState, TempState[ind]);
if (!recordingMacro && (useTempProfile[ind] ||
2017-04-21 05:09:08 +02:00
containsCustomAction(ind) || containsCustomExtras(ind) ||
getProfileActionCount(ind) > 0))
{
Mapping.MapCustom(ind, cState, MappedState[ind], ExposedState[ind], touchPad[ind], this);
cState = MappedState[ind];
}
2017-03-28 05:27:51 +02:00
if (!useDInputOnly[ind])
{
2019-04-18 04:29:16 +02:00
outputDevices[ind]?.ConvertandSendReport(cState, ind);
//testNewReport(ref x360reports[ind], cState, ind);
//x360controls[ind]?.SendReport(x360reports[ind]);
//x360Bus.Parse(cState, processingData[ind].Report, ind);
// We push the translated Xinput state, and simultaneously we
// pull back any possible rumble data coming from Xinput consumers.
/*if (x360Bus.Report(processingData[ind].Report, processingData[ind].Rumble))
{
byte Big = processingData[ind].Rumble[3];
byte Small = processingData[ind].Rumble[4];
if (processingData[ind].Rumble[1] == 0x08)
{
SetDevRumble(device, Big, Small, ind);
}
}
*/
}
else
{
// UseDInputOnly profile may re-map sixaxis gyro sensor values as a VJoy joystick axis (steering wheel emulation mode using VJoy output device). Handle this option because VJoy output works even in USeDInputOnly mode.
// If steering wheel emulation uses LS/RS/R2/L2 output axies then the profile should NOT use UseDInputOnly option at all because those require a virtual output device.
SASteeringWheelEmulationAxisType steeringWheelMappedAxis = Global.GetSASteeringWheelEmulationAxis(ind);
switch (steeringWheelMappedAxis)
{
case SASteeringWheelEmulationAxisType.None: break;
case SASteeringWheelEmulationAxisType.VJoy1X:
case SASteeringWheelEmulationAxisType.VJoy2X:
DS4Windows.VJoyFeeder.vJoyFeeder.FeedAxisValue(cState.SASteeringWheelEmulationUnit, ((((uint)steeringWheelMappedAxis) - ((uint)SASteeringWheelEmulationAxisType.VJoy1X)) / 3) + 1, DS4Windows.VJoyFeeder.HID_USAGES.HID_USAGE_X);
break;
case SASteeringWheelEmulationAxisType.VJoy1Y:
case SASteeringWheelEmulationAxisType.VJoy2Y:
DS4Windows.VJoyFeeder.vJoyFeeder.FeedAxisValue(cState.SASteeringWheelEmulationUnit, ((((uint)steeringWheelMappedAxis) - ((uint)SASteeringWheelEmulationAxisType.VJoy1X)) / 3) + 1, DS4Windows.VJoyFeeder.HID_USAGES.HID_USAGE_Y);
break;
case SASteeringWheelEmulationAxisType.VJoy1Z:
case SASteeringWheelEmulationAxisType.VJoy2Z:
DS4Windows.VJoyFeeder.vJoyFeeder.FeedAxisValue(cState.SASteeringWheelEmulationUnit, ((((uint)steeringWheelMappedAxis) - ((uint)SASteeringWheelEmulationAxisType.VJoy1X)) / 3) + 1, DS4Windows.VJoyFeeder.HID_USAGES.HID_USAGE_Z);
break;
}
}
// Output any synthetic events.
Mapping.Commit(ind);
// Update the GUI/whatever.
DS4LightBar.updateLightBar(device, ind);
}
}
2015-01-17 21:16:48 +01:00
public void LagFlashWarning(DS4Device device, int ind, bool on)
{
if (on)
{
lag[ind] = true;
2019-12-18 22:33:23 +01:00
LogDebug(DS4WinWPF.Properties.Resources.LatencyOverTen.Replace("*number*", (ind + 1).ToString()), true);
if (getFlashWhenLate())
{
DS4Color color = new DS4Color { red = 50, green = 0, blue = 0 };
DS4LightBar.forcedColor[ind] = color;
DS4LightBar.forcedFlash[ind] = 2;
DS4LightBar.forcelight[ind] = true;
}
}
else
{
lag[ind] = false;
2019-12-18 22:33:23 +01:00
LogDebug(DS4WinWPF.Properties.Resources.LatencyNotOverTen.Replace("*number*", (ind + 1).ToString()));
DS4LightBar.forcelight[ind] = false;
DS4LightBar.forcedFlash[ind] = 0;
device.LightBarColor = getMainColor(ind);
}
}
2015-01-17 21:16:48 +01:00
public DS4Controls GetActiveInputControl(int ind)
{
DS4State cState = CurrentState[ind];
DS4StateExposed eState = ExposedState[ind];
Mouse tp = touchPad[ind];
DS4Controls result = DS4Controls.None;
if (DS4Controllers[ind] != null)
{
if (Mapping.getBoolButtonMapping(cState.Cross))
result = DS4Controls.Cross;
else if (Mapping.getBoolButtonMapping(cState.Circle))
result = DS4Controls.Circle;
else if (Mapping.getBoolButtonMapping(cState.Triangle))
result = DS4Controls.Triangle;
else if (Mapping.getBoolButtonMapping(cState.Square))
result = DS4Controls.Square;
else if (Mapping.getBoolButtonMapping(cState.L1))
result = DS4Controls.L1;
else if (Mapping.getBoolTriggerMapping(cState.L2))
result = DS4Controls.L2;
else if (Mapping.getBoolButtonMapping(cState.L3))
result = DS4Controls.L3;
else if (Mapping.getBoolButtonMapping(cState.R1))
result = DS4Controls.R1;
else if (Mapping.getBoolTriggerMapping(cState.R2))
result = DS4Controls.R2;
else if (Mapping.getBoolButtonMapping(cState.R3))
result = DS4Controls.R3;
else if (Mapping.getBoolButtonMapping(cState.DpadUp))
result = DS4Controls.DpadUp;
else if (Mapping.getBoolButtonMapping(cState.DpadDown))
result = DS4Controls.DpadDown;
else if (Mapping.getBoolButtonMapping(cState.DpadLeft))
result = DS4Controls.DpadLeft;
else if (Mapping.getBoolButtonMapping(cState.DpadRight))
result = DS4Controls.DpadRight;
else if (Mapping.getBoolButtonMapping(cState.Share))
result = DS4Controls.Share;
else if (Mapping.getBoolButtonMapping(cState.Options))
result = DS4Controls.Options;
else if (Mapping.getBoolButtonMapping(cState.PS))
result = DS4Controls.PS;
else if (Mapping.getBoolAxisDirMapping(cState.LX, true))
result = DS4Controls.LXPos;
else if (Mapping.getBoolAxisDirMapping(cState.LX, false))
result = DS4Controls.LXNeg;
else if (Mapping.getBoolAxisDirMapping(cState.LY, true))
result = DS4Controls.LYPos;
else if (Mapping.getBoolAxisDirMapping(cState.LY, false))
result = DS4Controls.LYNeg;
else if (Mapping.getBoolAxisDirMapping(cState.RX, true))
result = DS4Controls.RXPos;
else if (Mapping.getBoolAxisDirMapping(cState.RX, false))
result = DS4Controls.RXNeg;
else if (Mapping.getBoolAxisDirMapping(cState.RY, true))
result = DS4Controls.RYPos;
else if (Mapping.getBoolAxisDirMapping(cState.RY, false))
result = DS4Controls.RYNeg;
else if (Mapping.getBoolTouchMapping(tp.leftDown))
result = DS4Controls.TouchLeft;
else if (Mapping.getBoolTouchMapping(tp.rightDown))
result = DS4Controls.TouchRight;
else if (Mapping.getBoolTouchMapping(tp.multiDown))
result = DS4Controls.TouchMulti;
else if (Mapping.getBoolTouchMapping(tp.upperDown))
result = DS4Controls.TouchUpper;
}
return result;
}
2017-07-18 22:37:01 +02:00
public bool[] touchreleased = new bool[4] { true, true, true, true },
touchslid = new bool[4] { false, false, false, false };
protected virtual void CheckForTouchToggle(int deviceID, DS4State cState, DS4State pState)
{
if (!getUseTPforControls(deviceID) && cState.Touch1 && pState.PS)
{
if (GetTouchActive(deviceID) && touchreleased[deviceID])
{
TouchActive[deviceID] = false;
2019-12-18 22:33:23 +01:00
LogDebug(DS4WinWPF.Properties.Resources.TouchpadMovementOff);
AppLogger.LogToTray(DS4WinWPF.Properties.Resources.TouchpadMovementOff);
touchreleased[deviceID] = false;
}
else if (touchreleased[deviceID])
{
TouchActive[deviceID] = true;
2019-12-18 22:33:23 +01:00
LogDebug(DS4WinWPF.Properties.Resources.TouchpadMovementOn);
AppLogger.LogToTray(DS4WinWPF.Properties.Resources.TouchpadMovementOn);
touchreleased[deviceID] = false;
}
}
else
touchreleased[deviceID] = true;
}
public virtual void StartTPOff(int deviceID)
{
if (deviceID < 4)
2015-01-17 21:16:48 +01:00
{
TouchActive[deviceID] = false;
2015-01-17 21:16:48 +01:00
}
}
public virtual string TouchpadSlide(int ind)
{
DS4State cState = CurrentState[ind];
string slidedir = "none";
2017-04-21 05:09:08 +02:00
if (DS4Controllers[ind] != null && cState.Touch2 &&
!(touchPad[ind].dragging || touchPad[ind].dragging2))
{
if (touchPad[ind].slideright && !touchslid[ind])
{
slidedir = "right";
touchslid[ind] = true;
}
else if (touchPad[ind].slideleft && !touchslid[ind])
{
slidedir = "left";
touchslid[ind] = true;
}
else if (!touchPad[ind].slideleft && !touchPad[ind].slideright)
{
slidedir = "";
touchslid[ind] = false;
}
2017-04-21 05:09:08 +02:00
}
return slidedir;
}
2015-01-17 21:16:48 +01:00
public virtual void LogDebug(String Data, bool warning = false)
{
//Console.WriteLine(System.DateTime.Now.ToString("G") + "> " + Data);
if (Debug != null)
{
2015-01-17 21:16:48 +01:00
DebugEventArgs args = new DebugEventArgs(Data, warning);
OnDebug(this, args);
}
}
public virtual void OnDebug(object sender, DebugEventArgs args)
{
if (Debug != null)
Debug(this, args);
}
// sets the rumble adjusted with rumble boost. General use method
public virtual void setRumble(byte heavyMotor, byte lightMotor, int deviceNum)
{
if (deviceNum < 4)
{
DS4Device device = DS4Controllers[deviceNum];
if (device != null)
SetDevRumble(device, heavyMotor, lightMotor, deviceNum);
//device.setRumble((byte)lightBoosted, (byte)heavyBoosted);
}
}
// sets the rumble adjusted with rumble boost. Method more used for
// report handling. Avoid constant checking for a device.
public void SetDevRumble(DS4Device device,
byte heavyMotor, byte lightMotor, int deviceNum)
{
byte boost = getRumbleBoost(deviceNum);
uint lightBoosted = ((uint)lightMotor * (uint)boost) / 100;
if (lightBoosted > 255)
lightBoosted = 255;
uint heavyBoosted = ((uint)heavyMotor * (uint)boost) / 100;
if (heavyBoosted > 255)
heavyBoosted = 255;
2017-04-21 05:09:08 +02:00
device.setRumble((byte)lightBoosted, (byte)heavyBoosted);
}
public DS4State getDS4State(int ind)
{
return CurrentState[ind];
}
2017-04-21 05:09:08 +02:00
public DS4State getDS4StateMapped(int ind)
{
return MappedState[ind];
}
public DS4State getDS4StateTemp(int ind)
{
return TempState[ind];
}
}
}