-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.cs
More file actions
1056 lines (947 loc) · 39.9 KB
/
MainWindow.cs
File metadata and controls
1056 lines (947 loc) · 39.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-------------------------------------------------------------------
// Copyright © 2012 Kindel Systems, LLC
// http://www.kindel.com
// charlie@kindel.com
//
// Published under the MIT License.
// Source control on SourceForge
// http://sourceforge.net/projects/mcecontroller/
//-------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Resources;
using System.Windows.Forms;
using MCEControl.Properties;
using Microsoft.Win32.Security;
using log4net;
using log4net.Repository.Hierarchy;
using log4net.Core;
using log4net.Appender;
using log4net.Layout;
namespace MCEControl
{
/// <summary>
/// Summary description for MainWindow.
/// </summary>
public class MainWindow : Form
{
// Used to enabled access to AddLogEntry
public static MainWindow MainWnd;
public CommandTable CmdTable;
private log4net.ILog _log4;
// Persisted application settings
public AppSettings Settings;
// Protocol objects
private SocketServer _server;
private SocketClient _client;
private SerialServer _serialServer;
// Indicates whether user hit the close box (minimize)
// or the app is exiting
private bool _shuttingDown;
private CommandWindow _cmdWindow;
// Window controls
private MainMenu _mainMenu;
private MenuItem _menuItemFileMenu;
private MenuItem _menuItemExit;
private MenuItem _menuItemHelpMenu;
private MenuItem _menuItemAbout;
private StatusBar _statusBar;
private NotifyIcon _notifyIcon;
private TextBox _log;
private ContextMenu _notifyMenu;
private MenuItem _notifyMenuItemExit;
private IContainer components;
private MenuItem _menuItemSendAwake;
private MenuItem _menuSeparator2;
private MenuItem _menuSeparator1;
private MenuItem _menuSettings;
private MenuItem _menuSeparator5;
private MenuItem _notifyMenuItemSettings;
private MenuItem _menuSeparator4;
private MenuItem _notifyMenuViewStatus;
private MenuItem _menuItemHelp;
private MenuItem _menuItemSupport;
private MenuItem _menuItemEditCommands;
private MenuItem menuItem2;
private MenuItem menuItem1;
private MenuItem _menuItemCheckVersion;
public SocketClient Client
{
get { return _client; }
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
public static void Main(string[] args)
{
if (!IsNet45OrNewer())
{
MessageBox.Show(
"MCE Controller requires .NET Framework 4.5 or newer.\r\n\r\nDownload and install from http://www.microsoft.com/net/");
return;
}
MainWnd = new MainWindow();
Application.Run(MainWnd);
}
public static bool IsNet45OrNewer()
{
// Class "ReflectionContext" exists from .NET 4.5 onwards.
return Type.GetType("System.Reflection.ReflectionContext", false) != null;
}
public MainWindow()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
_notifyIcon.Icon = Icon;
// Load AppSettings
Settings = AppSettings.Deserialize(AppSettings.GetSettingsPath());
ShowInTaskbar = true;
SetStatusBar("");
_menuItemSendAwake.Enabled = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
// When the app exits we need to un-shift any modify keys that might
// have been pressed or they'll still be stuck after exit
SendInputCommand.ShiftKey("shift", false);
SendInputCommand.ShiftKey("ctrl", false);
SendInputCommand.ShiftKey("alt", false);
SendInputCommand.ShiftKey("lwin", false);
SendInputCommand.ShiftKey("rwin", false);
if (components != null)
{
components.Dispose();
}
if (_server != null)
{
// remove our notification handler
_server.Notifications -= HandleSocketServerCallbacks;
_server.Dispose();
}
if (_client != null)
{
// remove our notification handler
_client.Notifications -= HandleClientNotifications;
_client.Dispose();
}
if (_serialServer != null)
{
_serialServer.Notifications -= HandleSerialServerNotifications;
_serialServer.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainWindow));
this._mainMenu = new System.Windows.Forms.MainMenu(this.components);
this._menuItemFileMenu = new System.Windows.Forms.MenuItem();
this._menuItemSendAwake = new System.Windows.Forms.MenuItem();
this._menuSeparator1 = new System.Windows.Forms.MenuItem();
this._menuItemEditCommands = new System.Windows.Forms.MenuItem();
this._menuSeparator2 = new System.Windows.Forms.MenuItem();
this._menuItemExit = new System.Windows.Forms.MenuItem();
this._menuSettings = new System.Windows.Forms.MenuItem();
this._menuItemHelpMenu = new System.Windows.Forms.MenuItem();
this._menuItemHelp = new System.Windows.Forms.MenuItem();
this._menuItemSupport = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this._menuItemCheckVersion = new System.Windows.Forms.MenuItem();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this._menuItemAbout = new System.Windows.Forms.MenuItem();
this._statusBar = new System.Windows.Forms.StatusBar();
this._notifyIcon = new System.Windows.Forms.NotifyIcon(this.components);
this._notifyMenu = new System.Windows.Forms.ContextMenu();
this._notifyMenuViewStatus = new System.Windows.Forms.MenuItem();
this._menuSeparator4 = new System.Windows.Forms.MenuItem();
this._notifyMenuItemSettings = new System.Windows.Forms.MenuItem();
this._menuSeparator5 = new System.Windows.Forms.MenuItem();
this._notifyMenuItemExit = new System.Windows.Forms.MenuItem();
this._log = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// _mainMenu
//
this._mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this._menuItemFileMenu,
this._menuSettings,
this._menuItemHelpMenu});
//
// _menuItemFileMenu
//
this._menuItemFileMenu.Index = 0;
this._menuItemFileMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this._menuItemSendAwake,
this._menuSeparator1,
this._menuItemEditCommands,
this._menuSeparator2,
this._menuItemExit});
this._menuItemFileMenu.Text = "&File";
//
// _menuItemSendAwake
//
this._menuItemSendAwake.Index = 0;
this._menuItemSendAwake.Text = "Send &Awake Signal";
this._menuItemSendAwake.Click += new System.EventHandler(this.MenuItemSendAwakeClick);
//
// _menuSeparator1
//
this._menuSeparator1.Index = 1;
this._menuSeparator1.Text = "-";
//
// _menuItemEditCommands
//
this._menuItemEditCommands.Index = 2;
this._menuItemEditCommands.Text = "&Open .commands file location...";
this._menuItemEditCommands.Click += new System.EventHandler(this.MenuItemEditCommandsClick);
//
// _menuSeparator2
//
this._menuSeparator2.Index = 3;
this._menuSeparator2.Text = "-";
//
// _menuItemExit
//
this._menuItemExit.Index = 4;
this._menuItemExit.Text = "E&xit";
this._menuItemExit.Click += new System.EventHandler(this.MenuItemExitClick);
//
// _menuSettings
//
this._menuSettings.Index = 1;
this._menuSettings.Text = "&Settings";
this._menuSettings.Click += new System.EventHandler(this.MenuSettingsClick);
//
// _menuItemHelpMenu
//
this._menuItemHelpMenu.Index = 2;
this._menuItemHelpMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this._menuItemHelp,
this._menuItemSupport,
this.menuItem2,
this._menuItemCheckVersion,
this.menuItem1,
this._menuItemAbout});
this._menuItemHelpMenu.Text = "&Help";
//
// _menuItemHelp
//
this._menuItemHelp.Index = 0;
this._menuItemHelp.Shortcut = System.Windows.Forms.Shortcut.F1;
this._menuItemHelp.Text = "&Documentation...";
this._menuItemHelp.Click += new System.EventHandler(this.MenuItemHelpClick);
//
// _menuItemSupport
//
this._menuItemSupport.Index = 1;
this._menuItemSupport.Text = "&Get Support...";
this._menuItemSupport.Click += new System.EventHandler(this.MenuItemSupportClick);
//
// menuItem2
//
this.menuItem2.Index = 2;
this.menuItem2.Text = "-";
//
// _menuItemCheckVersion
//
this._menuItemCheckVersion.Index = 3;
this._menuItemCheckVersion.Text = "&Check for a newer version";
this._menuItemCheckVersion.Click += new System.EventHandler(this.menuItemCheckVersion_Click);
//
// menuItem1
//
this.menuItem1.Index = 4;
this.menuItem1.Text = "-";
//
// _menuItemAbout
//
this._menuItemAbout.Index = 5;
this._menuItemAbout.Text = "&About MCE Controller";
this._menuItemAbout.Click += new System.EventHandler(this.MenuItemAboutClick);
//
// _statusBar
//
this._statusBar.Location = new System.Drawing.Point(0, 85);
this._statusBar.Name = "_statusBar";
this._statusBar.Size = new System.Drawing.Size(368, 29);
this._statusBar.TabIndex = 0;
//
// _notifyIcon
//
this._notifyIcon.ContextMenu = this._notifyMenu;
this._notifyIcon.Text = global::MCEControl.Properties.Resources.App_FullName;
this._notifyIcon.Visible = true;
this._notifyIcon.DoubleClick += new System.EventHandler(this.NotifyIconDoubleClick);
//
// _notifyMenu
//
this._notifyMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this._notifyMenuViewStatus,
this._menuSeparator4,
this._notifyMenuItemSettings,
this._menuSeparator5,
this._notifyMenuItemExit});
//
// _notifyMenuViewStatus
//
this._notifyMenuViewStatus.Index = 0;
this._notifyMenuViewStatus.Text = "&View Status...";
this._notifyMenuViewStatus.Click += new System.EventHandler(this.NotifyIconDoubleClick);
//
// _menuSeparator4
//
this._menuSeparator4.Index = 1;
this._menuSeparator4.Text = "-";
//
// _notifyMenuItemSettings
//
this._notifyMenuItemSettings.Index = 2;
this._notifyMenuItemSettings.Text = "&Settings...";
this._notifyMenuItemSettings.Click += new System.EventHandler(this.MenuSettingsClick);
//
// _menuSeparator5
//
this._menuSeparator5.Index = 3;
this._menuSeparator5.Text = "-";
//
// _notifyMenuItemExit
//
this._notifyMenuItemExit.Index = 4;
this._notifyMenuItemExit.Text = "&Exit";
this._notifyMenuItemExit.Click += new System.EventHandler(this.MenuItemExitClick);
//
// _log
//
this._log.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._log.Font = new System.Drawing.Font("Lucida Console", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this._log.Location = new System.Drawing.Point(0, 0);
this._log.Multiline = true;
this._log.Name = "_log";
this._log.Size = new System.Drawing.Size(368, 89);
this._log.TabIndex = 1;
this._log.WordWrap = false;
this._log.TextChanged += new System.EventHandler(this.LogTextChanged);
this._log.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.LogKeyPress);
//
// MainWindow
//
this.AutoScaleBaseSize = new System.Drawing.Size(8, 19);
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(368, 114);
this.Controls.Add(this._log);
this.Controls.Add(this._statusBar);
this.HelpButton = true;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Menu = this._mainMenu;
this.MinimizeBox = false;
this.Name = "MainWindow";
this.Text = "MCE Controller";
this.HelpButtonClicked += new System.ComponentModel.CancelEventHandler(this.MainWindow_HelpButtonClicked);
this.Closing += new System.ComponentModel.CancelEventHandler(this.MainWindowClosing);
this.Load += new System.EventHandler(this.MainWindowLoad);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
protected override void WndProc(ref Message m)
{
// If the session is being logged off, or the machine is shutting
// down...
if (m.Msg == 0x11) // WM_QUERYENDSESSION
{
// Allow shut down (m.Result may already be non-zero, but I set it
// just in case)
m.Result = (IntPtr)1;
// Indicate to MainWindow_Closing() that we are shutting down;
// otherwise it will just minimize to the tray
_shuttingDown = true;
}
base.WndProc(ref m);
}
private void MainWindowLoad(object sender, EventArgs e)
{
CheckVersion();
// Location can not be changed in constructor, has to be done here
Location = Settings.WindowLocation;
Size = Settings.WindowSize;
CmdTable = CommandTable.Deserialize(Settings.DisableInternalCommands);
if (CmdTable == null)
{
MessageBox.Show(this, Resources.MCEController_commands_read_error, Resources.App_FullName);
_notifyIcon.Visible = false;
Opacity = 100;
}
else
{
AddLogEntry("MCEC: " + CmdTable.CommandCount + " commands available.");
Opacity = (double)Settings.Opacity / 100;
if (Settings.HideOnStartup)
{
Opacity = 0;
Win32.PostMessage(Handle, (UInt32)WM.SYSCOMMAND, (UInt32)SC.CLOSE, 0);
}
}
if (_cmdWindow == null)
_cmdWindow = new CommandWindow();
//_cmdWindow.Visible = Settings.ShowCommandWindow;
//var t = new System.Timers.Timer() {
// AutoReset = false,
// Interval = 2000
//};
//t.Elapsed += (sender, args) => Start();
//AddLogEntry("Starting services...");
//t.Start();
Start();
}
private void MainWindowClosing(object sender, CancelEventArgs e)
{
if (!_shuttingDown)
{
// If we're NOT shutting down (the user hit the close button or pressed
// CTRL-F4) minimize to tray.
e.Cancel = true;
// Hide the form and make sure the taskbar icon is visible
_notifyIcon.Visible = true;
Hide();
}
}
private void CheckVersion()
{
AddLogEntry(string.Format("MCEC: Version: {0}", Application.ProductVersion));
var lv = new LatestVersion();
lv.GetLatestStableVersionAsync((o, version) =>
{
if (version == null && !string.IsNullOrWhiteSpace(lv.ErrorMessage))
{
AddLogEntry(
string.Format(
"MCEC: Could not access mcec.codeplex.com to see if a newer version is available. {0}",
lv.ErrorMessage));
}
else if (lv.CompareVersions() < 0)
{
AddLogEntry(
string.Format(
"MCEC: A newer version of MCE Controller ({0}) is available at mcec.codeplex.com.", version));
}
else if (lv.CompareVersions() > 0)
{
AddLogEntry(
string.Format(
"MCEC: You are are running a MORE recent version than can be found at mcec.codeplex.com ({0}).",
version));
}
else
{
AddLogEntry("MCEC: You are running the most recent version of MCE Controller.");
}
});
}
private void Start()
{
if (Settings.ActAsServer)
StartServer();
if (Settings.ActAsSerialServer)
StartSerialServer();
if (Settings.ActAsClient)
StartClient();
}
public void ShutDown()
{
AddLogEntry("ShutDown");
_shuttingDown = true;
// hide icon from the systray
_notifyIcon.Visible = false;
StopServer();
StopClient();
StopSerialServer();
// Prevent access to the static MainWnd
MainWnd = null;
// Save the window size/location
Settings.WindowLocation = Location;
Settings.WindowSize = Size;
Settings.Serialize();
Close();
Application.Exit();
}
private void StartServer()
{
if (_server == null)
{
_server = new SocketServer();
_server.Notifications += HandleSocketServerCallbacks;
_server.Start(Settings.ServerPort);
_menuItemSendAwake.Enabled = Settings.WakeupEnabled;
}
else
AddLogEntry("MCEC: Attempt to StartServer() while an instance already exists!");
}
private void StopServer()
{
if (_server != null)
{
// remove our notification handler
_server.Stop();
_server = null;
_menuItemSendAwake.Enabled = false;
}
}
private void StartSerialServer()
{
if (_serialServer == null)
{
_serialServer = new SerialServer();
_serialServer.Notifications += HandleSerialServerNotifications;
_serialServer.Start(Settings.SerialServerPortName,
Settings.SerialServerBaudRate,
Settings.SerialServerParity,
Settings.SerialServerDataBits,
Settings.SerialServerStopBits,
Settings.SerialServerHandshake);
}
else
AddLogEntry("MCEC: Attempt to StartSerialServer() while an instance already exists!");
}
private void StopSerialServer()
{
if (_serialServer != null)
{
// remove our notification handler
_serialServer.Stop();
_serialServer = null;
}
}
private void StartClient(bool delay = false)
{
if (_client == null)
{
_client = new SocketClient(Settings);
_client.Notifications += HandleClientNotifications;
_client.Start(delay);
}
}
private void StopClient()
{
if (_client != null)
{
_cmdWindow.Visible = false;
AddLogEntry("Client: Stopping...");
_client.Stop();
_client = null;
}
}
private delegate void RestartClientCallback();
private void RestartClient()
{
if (_cmdWindow != null)
{
if (this.InvokeRequired)
this.BeginInvoke((RestartClientCallback)RestartClient);
else
{
StopClient();
if (!_shuttingDown && Settings.ActAsClient)
{
AddLogEntry("Client: Reconnecting...");
StartClient(true);
}
}
}
}
private delegate void ShowCommandWindowCallback();
private void ShowCommandWindow()
{
if (this.InvokeRequired)
this.BeginInvoke((ShowCommandWindowCallback)ShowCommandWindow);
else
{
_cmdWindow.Visible = Settings.ShowCommandWindow;
}
}
private delegate void HideCommandWindowCallback();
private void HideCommandWindow()
{
if (this.InvokeRequired)
this.BeginInvoke((HideCommandWindowCallback)HideCommandWindow);
else
{
_cmdWindow.Visible = false;
}
}
private void ReceivedData(Reply reply, string cmd)
{
try
{
CmdTable.Execute(reply, cmd);
}
catch (Exception e)
{
AddLogEntry(string.Format("Command: ({0}) error: {1}", cmd, e));
}
}
private delegate void SetStatusBarCallback(string text);
private void SetStatusBar(string text)
{
if (_statusBar.InvokeRequired)
{
_statusBar.BeginInvoke((SetStatusBarCallback)SetStatusBar, new object[] { text });
}
else
{
_statusBar.Text = text;
_notifyIcon.Text = text;
}
}
//
// Notify callback for the TCP/IP Server
//
public void HandleSocketServerCallbacks(ServiceNotification notification, ServiceStatus status, Reply reply, string msg)
{
if (notification == ServiceNotification.StatusChange)
HandleSocketServerStatusChange(status);
else
HandleSocketServerNotification(notification, status, (SocketServer.ServerReplyContext)reply, msg);
}
private void HandleSocketServerNotification(ServiceNotification notification, ServiceStatus status,
SocketServer.ServerReplyContext serverReplyContext, string msg)
{
string s = "";
switch (notification)
{
case ServiceNotification.ReceivedData:
Debug.Assert(serverReplyContext.Socket.RemoteEndPoint != null, notification.ToString());
s = string.Format("Server: Received from Client #{0} at {1}: {2}",
serverReplyContext.ClientNumber, serverReplyContext.Socket.RemoteEndPoint, msg);
AddLogEntry(s);
ReceivedData(serverReplyContext, msg);
return;
case ServiceNotification.Write:
Debug.Assert(serverReplyContext.Socket.RemoteEndPoint != null, notification.ToString());
s = string.Format("Wrote to Client #{0} at {1}: {2}",
serverReplyContext.ClientNumber, serverReplyContext.Socket.RemoteEndPoint, msg);
break;
case ServiceNotification.WriteFailed:
Debug.Assert(serverReplyContext.Socket.RemoteEndPoint != null, notification.ToString());
s = string.Format("Write failed to Client #{0} at {1}: {2}",
serverReplyContext.ClientNumber, serverReplyContext.Socket.RemoteEndPoint, msg);
break;
case ServiceNotification.ClientConnected:
Debug.Assert(serverReplyContext.Socket.RemoteEndPoint != null, notification.ToString());
s = string.Format("Client #{0} at {1} connected.",
serverReplyContext.ClientNumber, serverReplyContext.Socket.RemoteEndPoint);
break;
case ServiceNotification.ClientDisconnected:
Debug.Assert(serverReplyContext.Socket.RemoteEndPoint != null, notification.ToString());
s = string.Format("Client #{0} at {1} has disconnected.",
serverReplyContext.ClientNumber, serverReplyContext.Socket.RemoteEndPoint);
break;
case ServiceNotification.Wakeup:
s = "Wakeup: " + (string)msg;
break;
case ServiceNotification.Error:
switch (status)
{
case ServiceStatus.Waiting:
case ServiceStatus.Stopped:
case ServiceStatus.Sleeping:
s = string.Format("{0}: {1}", status, msg);
break;
case ServiceStatus.Connected:
if (serverReplyContext != null)
{
Debug.Assert(serverReplyContext.Socket != null);
Debug.Assert(serverReplyContext.Socket.RemoteEndPoint != null);
s = string.Format("(Client #{0} at {1}): {2}",
serverReplyContext.ClientNumber,
serverReplyContext.Socket == null
? "n/a"
: serverReplyContext.Socket.RemoteEndPoint.ToString(),
msg);
}
else
s = msg;
break;
}
s = "Error " + s;
break;
default:
s = "Unknown notification: " + notification;
break;
}
AddLogEntry("Server: " + s);
}
private void HandleSocketServerStatusChange(ServiceStatus status)
{
string s = "";
switch (status)
{
case ServiceStatus.Started:
s = "Starting TCP/IP Server on port " + Settings.ServerPort;
SetStatusBar(s);
if (Settings.WakeupEnabled)
_server.SendAwakeCommand(Settings.WakeupCommand, Settings.WakeupHost,
Settings.WakeupPort);
break;
case ServiceStatus.Waiting:
s = "Waiting for a client to connect";
break;
case ServiceStatus.Connected:
SetStatusBar("Clients connected, waiting for commands...");
return;
case ServiceStatus.Stopped:
s = "Stopped.";
SetStatusBar("Client/Sever Not Active");
if (Settings.WakeupEnabled)
_server.SendAwakeCommand(Settings.ClosingCommand, Settings.WakeupHost,
Settings.WakeupPort);
break;
}
AddLogEntry("Server: " + s);
}
//
// Notify callback for the TCP/IP Client
//
public void HandleClientNotifications(ServiceNotification notify, ServiceStatus status, Reply reply, string msg)
{
string s = null;
switch (notify)
{
case ServiceNotification.StatusChange:
if (status == ServiceStatus.Started)
{
s = "Connecting to " + Settings.ClientHost + ":" + Settings.ClientPort;
SetStatusBar(s);
HideCommandWindow();
}
else if (status == ServiceStatus.Connected)
{
s = "Connected to " + Settings.ClientHost + ":" + Settings.ClientPort;
SetStatusBar(s);
ShowCommandWindow();
}
else if (status == ServiceStatus.Stopped)
{
s = "Stopped.";
SetStatusBar("Client/Sever Not Active");
HideCommandWindow();
}
else if (status == ServiceStatus.Sleeping)
{
s = "Waiting " + (Settings.ClientDelayTime / 1000) +
" seconds to connect.";
SetStatusBar(s);
HideCommandWindow();
}
break;
case ServiceNotification.ReceivedData:
AddLogEntry(string.Format("Client: Received; {0}", msg));
ReceivedData(reply, (string)msg);
return;
case ServiceNotification.Error:
AddLogEntry("Client: Error; " + (string)msg);
RestartClient();
return;
default:
s = "Unknown notification";
break;
}
AddLogEntry("Client: " + s);
}
//
// Notify callback for the Serial Server
//
public void HandleSerialServerNotifications(ServiceNotification notify, ServiceStatus status, Reply reply, string msg)
{
string s = null;
switch (notify)
{
case ServiceNotification.StatusChange:
switch (status)
{
case ServiceStatus.Started:
s = string.Format("SerialServer: Opening port: {0}", msg);
break;
case ServiceStatus.Waiting:
s = string.Format("SerialServer: Waiting for commands on {0}...", msg);
SetStatusBar("Waiting for Serial commands...");
break;
case ServiceStatus.Stopped:
s = "SerialServer: Stopped.";
SetStatusBar("Serial Server Not Active");
break;
}
break;
case ServiceNotification.ReceivedData:
AddLogEntry(string.Format("SerialServer: Received: {0}", msg));
ReceivedData(reply, (string)msg);
return;
case ServiceNotification.Error:
s = string.Format("SerialServer: Error: {0}", msg);
break;
default:
s = "SerialServer: Unknown notification";
break;
}
AddLogEntry(s);
}
public static void AddLogEntry(string text)
{
if (MainWnd == null) return;
if (MainWnd._log4 == null)
{
string logFile = Environment.CurrentDirectory + @"\MCEControl.log";
if (Environment.CurrentDirectory.Contains("Program Files (x86)"))
logFile = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Kindel Systems\MCE Controller\MCEControl.log";
Logger.Setup(logFile);
MainWnd._log4 = log4net.LogManager.GetLogger("MCEControl");
AddLogEntry("MCEC: Log file being written to " + logFile);
}
MainWnd._log4.Info(text);
// Can only update the log in the main window when on the UI thread
if (MainWnd.InvokeRequired || MainWnd._log.InvokeRequired)
MainWnd.BeginInvoke((AddLogEntryUiThreadCallback)AddLogEntryUiThread, new object[] { text });
else
{
AddLogEntryUiThread(text);
}
}
private delegate void AddLogEntryUiThreadCallback(string text);
private static void AddLogEntryUiThread(string text)
{
MainWnd._log.AppendText("[" + DateTime.Now.ToString("yy'-'MM'-'dd' 'HH':'mm':'ss") + "] " + text +
Environment.NewLine);
}
private void MenuItemExitClick(object sender, EventArgs e)
{
ShutDown();
}
private void NotifyIconDoubleClick(object sender, EventArgs e)
{
// Show the form when the user double clicks on the notify icon.
// Set the WindowState to normal if the form is minimized.
if (WindowState == FormWindowState.Minimized)
WindowState = FormWindowState.Normal;
// Activate the form.
_notifyIcon.Visible = false;
Activate();
Show();
Opacity = (double)Settings.Opacity / 100;
}
private void MenuItemAboutClick(object sender, EventArgs e)
{
var a = new AboutBox();
a.ShowDialog(this);
}
private void MenuSettingsClick(object sender, EventArgs e)
{
var d = new SettingsDialog(Settings);
if (d.ShowDialog(this) == DialogResult.OK)
{
Settings = d.Settings;
Opacity = (double)Settings.Opacity / 100;
RestartClient();
StopServer();
StopSerialServer();
if (Settings.ActAsServer)
StartServer();
if (Settings.ActAsSerialServer)
StartSerialServer();
if (Settings.ActAsClient)
{
StartClient();
}
}
}
// Prevent input into the edit box
private void LogKeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
// Keep the end of the log visible and prevent it from overflowing
private void LogTextChanged(object sender, EventArgs e)
{
// We don't want to overrun the size a textbox can handle
// limit to 16k
if (_log.TextLength > (16 * 1024))
{
_log.Text = _log.Text.Remove(0, _log.Text.IndexOf("\r\n", StringComparison.Ordinal) + 2);
_log.Select(_log.TextLength, 0);
}
_log.ScrollToCaret();
}
private void MenuItemSendAwakeClick(object sender, EventArgs e)
{
_server.SendAwakeCommand(Settings.WakeupCommand, Settings.WakeupHost, Settings.WakeupPort);
}
private void MenuItemHelpClick(object sender, EventArgs e)
{
Process.Start("http://mcec.codeplex.com/documentation/");
}
private void MenuItemSupportClick(object sender, EventArgs e)
{