Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using System.Threading;
- using System.IO.Ports;
- using System.Runtime.InteropServices;
- using System.Windows.Forms;
- using System.Diagnostics;
- namespace External_Media_Control {
- public static class ComListener {
- private static string[] lastScannedPorts = { };
- private static bool hasPinged = false;
- private static string lastAction;
- //Music-control
- public const int KEYEVENTF_EXTENTEDKEY = 1;
- public const int KEYEVENTF_KEYUP = 0;
- public const int VK_MEDIA_NEXT_TRACK = 0xB0; //Next track
- public const int VK_MEDIA_PLAY_PAUSE = 0xB3; //Play/pause
- public const int VK_MEDIA_PREV_TRACK = 0xB1; //Previous track
- [DllImport("user32.dll", SetLastError = true)]
- static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
- public static void UpdateComPorts() {
- Thread.Sleep(200); //Give it a little time to update, not be busy
- string[] newPortNames;
- try {
- newPortNames = SerialPort.GetPortNames();
- } catch (Exception e) {
- //Most likely "not enough space"... SerialPort needs a break, but has definitely changed
- //Program.Debug(e);
- Program.Debug(e.ToString());
- return;
- }
- if (!Enumerable.SequenceEqual(lastScannedPorts, newPortNames)) {
- //if (!Enumerable.SequenceEqual<String>(lastScannedPorts, lastScannedPorts)) {
- Program.Debug("Got ports");
- lastScannedPorts = newPortNames;
- Program.Debug("COM port changed.");
- if (Program.paired) {
- int pos = Array.IndexOf(lastScannedPorts, Program.mediaController.PortName);
- if (pos == -1) {
- //Probably not needed, as if the port it's listening to is no longer connected, it can't be workin'
- Program.Debug("COM port removed, pinging to make sure;");
- PingArduino();
- }
- } else {
- Thread.Sleep(200);
- CheckPorts();
- }
- } else {
- Program.Debug("Test 2");
- }
- }
- private static void PingArduino() {
- if (Program.paired && Program.mediaController != null) {
- /*if (Program.mediaController.IsOpen) {
- Program.mediaController.Write("Ping#");
- hasPinged = true;
- } else {*/
- Unpair();
- Program.Debug("Yep, port is closed... Checking again");
- CheckPorts();
- //}
- }
- }
- private static void Unpair() {
- if (Program.mediaController != null) {
- Program.mediaController.Dispose();
- Program.mediaController.Close();
- Program.mediaController = null;
- Program.paired = false;
- }
- }
- private static void SerialPinChanged(object sender, SerialPinChangedEventArgs e) {
- Program.Debug("Pin changed...?");
- }
- static void CheckPorts() {
- Program.Debug("\nChecking port...");
- if (Program.paired) {
- Program.Debug("Already paired");
- return;
- }
- int portsChecked = 0;
- foreach (string portname in lastScannedPorts) {
- /*if (portname == "COM1" || portname == "COM3") {
- //COM1 and COM3 is reserved and always present
- portsChecked++;
- continue;
- }*/
- Thread t = new Thread(OpenTheThread);
- t.Start();
- if (!t.Join(TimeSpan.FromSeconds(4.5))) {
- portsChecked++;
- t.Abort();
- }
- void OpenTheThread() {
- Program.Debug("Opened thread");
- Thread.CurrentThread.IsBackground = true;
- Program.Debug("Opening port with portname: " + portname);
- SerialPort portTesting = new SerialPort {
- PortName = portname,
- //BaudRate = 230400,
- BaudRate = 500000,
- DtrEnable = true,
- ReadTimeout = 3500,
- Parity = Parity.None,
- DataBits = 8,
- StopBits = StopBits.One,
- //Handshake = Handshake.
- };
- if (!OpenPort(portTesting)) {
- portTesting.Dispose();
- portTesting.Close();
- Thread.CurrentThread.Abort();
- portsChecked++;
- return;
- }
- bool hasReceivedData = false;
- portTesting.DataReceived += (sender, e) => onDataReceive(sender, e);
- void onDataReceive(object sender, SerialDataReceivedEventArgs e) {
- if (e.EventType == SerialData.Chars) {
- hasReceivedData = true;
- string line;
- try {
- line = portTesting.ReadLine();
- } catch (Exception ex) {
- Program.Debug("Error reading line, most likely timeout reached.");
- //Console.WriteLine(ex.Message);
- //portTesting.DataReceived -= null;
- return;
- }
- Program.Debug("Got input: " + line);
- if (!Program.paired) {
- if (line == "Ready to pair") {
- Program.Debug("[Paired]\n");
- Program.paired = true;
- Program.mediaController = portTesting;
- return;
- } else {
- Program.Debug("Wrong input.\n\n");
- }
- } else if (Program.applicationSetUp) {
- if (Program.mediaController.BytesToRead > 150) {
- Program.mediaController.DiscardInBuffer();
- }
- Program.Debug("Executing action; " + line);
- CheckInput(line);
- }
- }
- }
- Program.Debug("Opened port");
- while (!hasReceivedData || portTesting != null || !Program.paired) ;
- if (!Program.paired) {
- portTesting.Dispose();
- portTesting.Close();
- portTesting = null;
- Program.Debug("Closing port\n");
- }
- portsChecked++;
- Thread.CurrentThread.Abort();
- }
- } //End for-loop
- while (portsChecked != lastScannedPorts.Length) {
- Program.Debug(portsChecked.ToString() + " != " + lastScannedPorts.Length.ToString());
- Program.Debug((portsChecked == lastScannedPorts.Length).ToString());
- }
- if (Program.paired && Program.mediaController != null) {
- if (Properties.Settings.Default.enableOverlay && Properties.Settings.Default.idleOverlay)
- Program.overlayForm.FadeIn(Properties.Settings.Default.idleOpacity / 100);
- Program.mediaController.ErrorReceived += SerialErrorReceived;
- Program.mediaController.PinChanged += SerialPinChanged;
- Program.Debug("COM listeners set up");
- } else {
- Program.Debug("No EMC detected...");
- }
- Program.UpdateTrayIconText();
- }
- private static bool OpenPort(SerialPort port) {
- //Try to open port
- try {
- port.Open();
- } catch (Exception e) {
- Program.Debug(port.PortName + " is open somewhere else. Error;");
- Program.Debug(e.ToString());
- return false;
- }
- return true;
- }
- private static void SerialErrorReceived(object sender, SerialErrorReceivedEventArgs e) {
- Program.Debug("[SERIAL ERROR]: " + e);
- }
- static void CheckInput(string serial) {
- string action
- , parameter = "";
- if (serial.Contains(":")) {
- //Contains a parameter
- action = serial.Split(':')[0];
- parameter = serial.Split(':')[1];
- } else {
- action = serial;
- }
- if (lastAction != action) {
- Program.mediaController.DiscardInBuffer();
- }
- switch (action) {
- case "previous":
- //keybd_event(VK_MEDIA_PREV_TRACK, 0, KEYEVENTF_EXTENTEDKEY, 0);
- //Program.Debug("Playing previous song");
- Program.SetActiveApplication(Program.ProcessState.back);
- break;
- case "next":
- //keybd_event(VK_MEDIA_NEXT_TRACK, 0, KEYEVENTF_EXTENTEDKEY, 0);
- //Program.Debug("Playing next song");
- Program.SetActiveApplication(Program.ProcessState.forth);
- break;
- case "play/pause":
- keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_EXTENTEDKEY, 0);
- Program.Debug("Playing/pausing");
- break;
- case "volume_down":
- if(Program.activeProcess is null) {
- //No process selected
- float masterVolume = AudioManager.GetMasterVolume();
- int decimals = (int)Math.Floor(Math.Log10(Properties.Settings.Default.volumeStep) + 1);
- float toSet = masterVolume - (float)Math.Round((float)Properties.Settings.Default.volumeStep, decimals);
- if (toSet < 0) toSet = 0;
- AudioManager.SetMasterVolume(toSet);
- Program.overlayForm.SetProgressValue((int)toSet);
- Program.Debug("Turned volume down (" + toSet + ")");
- } else {
- //Process selected
- float setVolume = AudioManager.GetApplicationVolume(Program.activeProcess.processes[0].Id).Value;
- if(setVolume - Properties.Settings.Default.volumeStep <= 0) setVolume = 0; else setVolume -= Properties.Settings.Default.volumeStep;
- Program.overlayForm.SetProgressValue((int)setVolume);
- Console.WriteLine(setVolume);
- foreach(Process p in Program.activeProcess.processes) {
- AudioManager.SetApplicationVolume(p.Id, setVolume);
- }
- }
- if (Properties.Settings.Default.showOverlayOnVolumeChange && Properties.Settings.Default.enableOverlay) {
- Program.overlayForm.FadeIn();
- }
- break;
- case "volume_up":
- if (Program.activeProcess is null) {
- //No process selected
- int masterVolume = (int)AudioManager.GetMasterVolume();
- int decimals = (int)Math.Floor(Math.Log10(Properties.Settings.Default.volumeStep) + 1);
- float toSet = masterVolume + (float)Math.Round((float)Properties.Settings.Default.volumeStep, decimals);
- if (toSet > 100) toSet = 100;
- AudioManager.SetMasterVolume(toSet);
- Program.overlayForm.SetProgressValue((int)toSet);
- Program.Debug("Turned volume up (" + toSet + ")");
- } else {
- //Process selected
- float setVolume = AudioManager.GetApplicationVolume(Program.activeProcess.processes[0].Id).Value;
- if (setVolume + Properties.Settings.Default.volumeStep >= 100) setVolume = 100; else setVolume += Properties.Settings.Default.volumeStep;
- Program.overlayForm.SetProgressValue((int)setVolume);
- Console.WriteLine(setVolume);
- foreach (Process p in Program.activeProcess.processes) {
- AudioManager.SetApplicationVolume(p.Id, setVolume);
- }
- }
- if (Properties.Settings.Default.showOverlayOnVolumeChange && Properties.Settings.Default.enableOverlay) {
- Program.overlayForm.FadeIn();
- }
- break;
- case "mute":
- if (Program.activeProcess is null) {
- AudioManager.SetMasterVolumeMute(!AudioManager.GetMasterVolumeMute());
- Program.Debug("Muted Windows");
- } else {
- //Process selected
- foreach (Process p in Program.activeProcess.processes) {
- AudioManager.SetApplicationMute(p.Id, (bool)!AudioManager.GetApplicationMute(p.Id));
- }
- Program.Debug("Muted active application");
- }
- break;
- case "prev_app":
- Program.SetActiveApplication(Program.ProcessState.back);
- break;
- case "next_app":
- Program.SetActiveApplication(Program.ProcessState.forth);
- break;
- default:
- Program.Debug("Unknown action \"" + action + "\"");
- return;
- }
- lastAction = action;
- Program.Debug("");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement