Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.55 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using System.Threading;
  4. using System.IO.Ports;
  5. using System.Runtime.InteropServices;
  6. using System.Windows.Forms;
  7. using System.Diagnostics;
  8.  
  9. namespace External_Media_Control {
  10. public static class ComListener {
  11. private static string[] lastScannedPorts = { };
  12. private static bool hasPinged = false;
  13. private static string lastAction;
  14.  
  15. //Music-control
  16. public const int KEYEVENTF_EXTENTEDKEY = 1;
  17. public const int KEYEVENTF_KEYUP = 0;
  18. public const int VK_MEDIA_NEXT_TRACK = 0xB0; //Next track
  19. public const int VK_MEDIA_PLAY_PAUSE = 0xB3; //Play/pause
  20. public const int VK_MEDIA_PREV_TRACK = 0xB1; //Previous track
  21. [DllImport("user32.dll", SetLastError = true)]
  22. static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
  23.  
  24. public static void UpdateComPorts() {
  25. Thread.Sleep(200); //Give it a little time to update, not be busy
  26.  
  27. string[] newPortNames;
  28. try {
  29. newPortNames = SerialPort.GetPortNames();
  30. } catch (Exception e) {
  31. //Most likely "not enough space"... SerialPort needs a break, but has definitely changed
  32. //Program.Debug(e);
  33. Program.Debug(e.ToString());
  34. return;
  35. }
  36. if (!Enumerable.SequenceEqual(lastScannedPorts, newPortNames)) {
  37. //if (!Enumerable.SequenceEqual<String>(lastScannedPorts, lastScannedPorts)) {
  38. Program.Debug("Got ports");
  39. lastScannedPorts = newPortNames;
  40.  
  41. Program.Debug("COM port changed.");
  42. if (Program.paired) {
  43. int pos = Array.IndexOf(lastScannedPorts, Program.mediaController.PortName);
  44. if (pos == -1) {
  45. //Probably not needed, as if the port it's listening to is no longer connected, it can't be workin'
  46. Program.Debug("COM port removed, pinging to make sure;");
  47. PingArduino();
  48. }
  49. } else {
  50. Thread.Sleep(200);
  51. CheckPorts();
  52. }
  53. } else {
  54. Program.Debug("Test 2");
  55. }
  56. }
  57.  
  58. private static void PingArduino() {
  59. if (Program.paired && Program.mediaController != null) {
  60. /*if (Program.mediaController.IsOpen) {
  61. Program.mediaController.Write("Ping#");
  62. hasPinged = true;
  63. } else {*/
  64. Unpair();
  65. Program.Debug("Yep, port is closed... Checking again");
  66. CheckPorts();
  67. //}
  68. }
  69. }
  70.  
  71. private static void Unpair() {
  72. if (Program.mediaController != null) {
  73. Program.mediaController.Dispose();
  74. Program.mediaController.Close();
  75. Program.mediaController = null;
  76. Program.paired = false;
  77. }
  78. }
  79.  
  80. private static void SerialPinChanged(object sender, SerialPinChangedEventArgs e) {
  81. Program.Debug("Pin changed...?");
  82. }
  83.  
  84. static void CheckPorts() {
  85. Program.Debug("\nChecking port...");
  86.  
  87. if (Program.paired) {
  88. Program.Debug("Already paired");
  89. return;
  90. }
  91.  
  92. int portsChecked = 0;
  93.  
  94. foreach (string portname in lastScannedPorts) {
  95. /*if (portname == "COM1" || portname == "COM3") {
  96. //COM1 and COM3 is reserved and always present
  97. portsChecked++;
  98. continue;
  99. }*/
  100.  
  101. Thread t = new Thread(OpenTheThread);
  102. t.Start();
  103. if (!t.Join(TimeSpan.FromSeconds(4.5))) {
  104. portsChecked++;
  105. t.Abort();
  106. }
  107.  
  108. void OpenTheThread() {
  109. Program.Debug("Opened thread");
  110. Thread.CurrentThread.IsBackground = true;
  111.  
  112. Program.Debug("Opening port with portname: " + portname);
  113. SerialPort portTesting = new SerialPort {
  114. PortName = portname,
  115. //BaudRate = 230400,
  116. BaudRate = 500000,
  117. DtrEnable = true,
  118. ReadTimeout = 3500,
  119. Parity = Parity.None,
  120. DataBits = 8,
  121. StopBits = StopBits.One,
  122. //Handshake = Handshake.
  123. };
  124.  
  125. if (!OpenPort(portTesting)) {
  126. portTesting.Dispose();
  127. portTesting.Close();
  128. Thread.CurrentThread.Abort();
  129. portsChecked++;
  130. return;
  131. }
  132.  
  133. bool hasReceivedData = false;
  134.  
  135. portTesting.DataReceived += (sender, e) => onDataReceive(sender, e);
  136. void onDataReceive(object sender, SerialDataReceivedEventArgs e) {
  137. if (e.EventType == SerialData.Chars) {
  138. hasReceivedData = true;
  139. string line;
  140.  
  141. try {
  142. line = portTesting.ReadLine();
  143. } catch (Exception ex) {
  144. Program.Debug("Error reading line, most likely timeout reached.");
  145. //Console.WriteLine(ex.Message);
  146. //portTesting.DataReceived -= null;
  147. return;
  148. }
  149.  
  150. Program.Debug("Got input: " + line);
  151.  
  152. if (!Program.paired) {
  153. if (line == "Ready to pair") {
  154. Program.Debug("[Paired]\n");
  155. Program.paired = true;
  156. Program.mediaController = portTesting;
  157. return;
  158. } else {
  159. Program.Debug("Wrong input.\n\n");
  160. }
  161. } else if (Program.applicationSetUp) {
  162. if (Program.mediaController.BytesToRead > 150) {
  163. Program.mediaController.DiscardInBuffer();
  164. }
  165.  
  166. Program.Debug("Executing action; " + line);
  167. CheckInput(line);
  168. }
  169. }
  170. }
  171.  
  172. Program.Debug("Opened port");
  173. while (!hasReceivedData || portTesting != null || !Program.paired) ;
  174.  
  175. if (!Program.paired) {
  176. portTesting.Dispose();
  177. portTesting.Close();
  178. portTesting = null;
  179.  
  180. Program.Debug("Closing port\n");
  181. }
  182. portsChecked++;
  183. Thread.CurrentThread.Abort();
  184. }
  185. } //End for-loop
  186.  
  187. while (portsChecked != lastScannedPorts.Length) {
  188. Program.Debug(portsChecked.ToString() + " != " + lastScannedPorts.Length.ToString());
  189. Program.Debug((portsChecked == lastScannedPorts.Length).ToString());
  190. }
  191.  
  192. if (Program.paired && Program.mediaController != null) {
  193. if (Properties.Settings.Default.enableOverlay && Properties.Settings.Default.idleOverlay)
  194. Program.overlayForm.FadeIn(Properties.Settings.Default.idleOpacity / 100);
  195.  
  196. Program.mediaController.ErrorReceived += SerialErrorReceived;
  197. Program.mediaController.PinChanged += SerialPinChanged;
  198.  
  199. Program.Debug("COM listeners set up");
  200. } else {
  201. Program.Debug("No EMC detected...");
  202. }
  203. Program.UpdateTrayIconText();
  204. }
  205.  
  206. private static bool OpenPort(SerialPort port) {
  207. //Try to open port
  208. try {
  209. port.Open();
  210. } catch (Exception e) {
  211. Program.Debug(port.PortName + " is open somewhere else. Error;");
  212. Program.Debug(e.ToString());
  213. return false;
  214. }
  215. return true;
  216. }
  217.  
  218. private static void SerialErrorReceived(object sender, SerialErrorReceivedEventArgs e) {
  219. Program.Debug("[SERIAL ERROR]: " + e);
  220. }
  221.  
  222. static void CheckInput(string serial) {
  223. string action
  224. , parameter = "";
  225.  
  226. if (serial.Contains(":")) {
  227. //Contains a parameter
  228. action = serial.Split(':')[0];
  229. parameter = serial.Split(':')[1];
  230. } else {
  231. action = serial;
  232. }
  233.  
  234. if (lastAction != action) {
  235. Program.mediaController.DiscardInBuffer();
  236. }
  237.  
  238. switch (action) {
  239. case "previous":
  240. //keybd_event(VK_MEDIA_PREV_TRACK, 0, KEYEVENTF_EXTENTEDKEY, 0);
  241. //Program.Debug("Playing previous song");
  242. Program.SetActiveApplication(Program.ProcessState.back);
  243. break;
  244. case "next":
  245. //keybd_event(VK_MEDIA_NEXT_TRACK, 0, KEYEVENTF_EXTENTEDKEY, 0);
  246. //Program.Debug("Playing next song");
  247. Program.SetActiveApplication(Program.ProcessState.forth);
  248. break;
  249. case "play/pause":
  250. keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_EXTENTEDKEY, 0);
  251. Program.Debug("Playing/pausing");
  252. break;
  253. case "volume_down":
  254. if(Program.activeProcess is null) {
  255. //No process selected
  256. float masterVolume = AudioManager.GetMasterVolume();
  257.  
  258. int decimals = (int)Math.Floor(Math.Log10(Properties.Settings.Default.volumeStep) + 1);
  259. float toSet = masterVolume - (float)Math.Round((float)Properties.Settings.Default.volumeStep, decimals);
  260. if (toSet < 0) toSet = 0;
  261.  
  262. AudioManager.SetMasterVolume(toSet);
  263. Program.overlayForm.SetProgressValue((int)toSet);
  264. Program.Debug("Turned volume down (" + toSet + ")");
  265. } else {
  266. //Process selected
  267. float setVolume = AudioManager.GetApplicationVolume(Program.activeProcess.processes[0].Id).Value;
  268. if(setVolume - Properties.Settings.Default.volumeStep <= 0) setVolume = 0; else setVolume -= Properties.Settings.Default.volumeStep;
  269.  
  270. Program.overlayForm.SetProgressValue((int)setVolume);
  271. Console.WriteLine(setVolume);
  272.  
  273. foreach(Process p in Program.activeProcess.processes) {
  274. AudioManager.SetApplicationVolume(p.Id, setVolume);
  275. }
  276. }
  277. if (Properties.Settings.Default.showOverlayOnVolumeChange && Properties.Settings.Default.enableOverlay) {
  278. Program.overlayForm.FadeIn();
  279. }
  280. break;
  281. case "volume_up":
  282. if (Program.activeProcess is null) {
  283. //No process selected
  284. int masterVolume = (int)AudioManager.GetMasterVolume();
  285.  
  286. int decimals = (int)Math.Floor(Math.Log10(Properties.Settings.Default.volumeStep) + 1);
  287. float toSet = masterVolume + (float)Math.Round((float)Properties.Settings.Default.volumeStep, decimals);
  288. if (toSet > 100) toSet = 100;
  289.  
  290. AudioManager.SetMasterVolume(toSet);
  291. Program.overlayForm.SetProgressValue((int)toSet);
  292. Program.Debug("Turned volume up (" + toSet + ")");
  293. } else {
  294. //Process selected
  295. float setVolume = AudioManager.GetApplicationVolume(Program.activeProcess.processes[0].Id).Value;
  296. if (setVolume + Properties.Settings.Default.volumeStep >= 100) setVolume = 100; else setVolume += Properties.Settings.Default.volumeStep;
  297.  
  298. Program.overlayForm.SetProgressValue((int)setVolume);
  299. Console.WriteLine(setVolume);
  300.  
  301. foreach (Process p in Program.activeProcess.processes) {
  302. AudioManager.SetApplicationVolume(p.Id, setVolume);
  303. }
  304. }
  305. if (Properties.Settings.Default.showOverlayOnVolumeChange && Properties.Settings.Default.enableOverlay) {
  306. Program.overlayForm.FadeIn();
  307. }
  308. break;
  309. case "mute":
  310. if (Program.activeProcess is null) {
  311. AudioManager.SetMasterVolumeMute(!AudioManager.GetMasterVolumeMute());
  312. Program.Debug("Muted Windows");
  313. } else {
  314. //Process selected
  315. foreach (Process p in Program.activeProcess.processes) {
  316. AudioManager.SetApplicationMute(p.Id, (bool)!AudioManager.GetApplicationMute(p.Id));
  317. }
  318. Program.Debug("Muted active application");
  319. }
  320. break;
  321. case "prev_app":
  322. Program.SetActiveApplication(Program.ProcessState.back);
  323. break;
  324. case "next_app":
  325. Program.SetActiveApplication(Program.ProcessState.forth);
  326. break;
  327. default:
  328. Program.Debug("Unknown action \"" + action + "\"");
  329. return;
  330. }
  331. lastAction = action;
  332.  
  333. Program.Debug("");
  334. }
  335. }
  336. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement