-
Notifications
You must be signed in to change notification settings - Fork 1
/
MiJia.cs
3075 lines (2688 loc) · 110 KB
/
MiJia.cs
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
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Drawing;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Management;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using AutoIt;
using Elton.Aqara;
using KnownFolderPaths;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.CodeAnalysis.Scripting.Hosting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NAudio.CoreAudioApi;
namespace MiJia
{
#region Gateway Helper routines
public class DeviceInfo
{
public string Cmd { get; set; }
[JsonProperty("mac")]
public string MAC { get; set; }
[JsonProperty("password")]
public string Password { get; set; }
[JsonProperty("model")]
public string Model { get; set; }
public string Sid { get; set; }
[JsonProperty("short_id")]
public string ShortId { get; set; }
[JsonProperty("did")]
public string DeviceId { get; set; }
public string Token { get; set; }
public string Data { get; set; }
//[JsonProperty("devices")]
//public AqaraDeviceConfig[] Devices { get; set; }
//[JsonProperty("gateways")]
//public AqaraGatewayConfig[] Gateways { get; set; }
}
public class Gateway
{
public string MulticastIP { get; set; } = "224.0.0.50";
public int MulticastPort { get; set; } = 4321;
public string RemoteIP { get; set; } = "192.168.1.244";
public int RemotePort { get; set; } = 9898;
public string Token { get; set; }
internal int SendCmd(string cmd)
{
IPAddress mip = IPAddress.Parse(MulticastIP);
IPEndPoint mep = new IPEndPoint(mip, MulticastPort);
IPAddress rip = IPAddress.Parse(RemoteIP);
IPEndPoint rep = new IPEndPoint(rip, RemotePort);
UdpClient udp = new UdpClient();
udp.JoinMulticastGroup(mip);
udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udp.ExclusiveAddressUse = false;
udp.Connect("127.0.0.1", RemotePort);
byte[] bs = Encoding.Default.GetBytes(cmd);
return udp.Send(bs, bs.Length);
}
internal async Task<string> SendCmd(string cmd, string server, int port)
{
string result = string.Empty;
UdpClient udp = new UdpClient();
udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udp.ExclusiveAddressUse = false;
udp.Connect(server, port);
byte[] bs = Encoding.Default.GetBytes(cmd);
var ret = udp.Send(bs, bs.Length);
var received = await udp.ReceiveAsync();
result = Encoding.Default.GetString(received.Buffer);
return (result);
}
public async Task<List<string>> Listen()
{
List<string> result = new List<string>();
IPAddress mip = IPAddress.Parse(MulticastIP);
IPEndPoint mep = new IPEndPoint(mip, MulticastPort);
IPAddress rip = IPAddress.Parse(RemoteIP);
IPEndPoint rep = new IPEndPoint(rip, RemotePort);
UdpClient udp = new UdpClient();
udp.JoinMulticastGroup(mip);
udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udp.ExclusiveAddressUse = false;
udp.Client.Bind(new IPEndPoint(IPAddress.Any, RemotePort));
while (true)
{
var received = await udp.ReceiveAsync();
var line = Encoding.Default.GetString(received.Buffer);
if (!string.IsNullOrEmpty(line))
{
result.Add(line);
break;
}
}
return (result);
}
public async Task<IList<string>> GetDevice()
{
List<string> result = new List<string>();
//var ret = SendCmd("{\"cmd\":\"whois\"}");
var ret = await SendCmd("{\"cmd\" : \"get_id_list\"}", RemoteIP, RemotePort);
JsonSerializer serializer = new JsonSerializer();
DeviceInfo token = JsonConvert.DeserializeObject<DeviceInfo>(ret);
if (!string.IsNullOrEmpty(token.Data))
{
var data = JsonConvert.DeserializeObject<string[]>(token.Data);
foreach (var device in data)
result.Add(device);
}
return (result);
}
public async Task<IList<string>> GetDevice(string deviceId)
{
List<string> result = new List<string>();
if (!string.IsNullOrEmpty(deviceId))
{
var ret = await SendCmd($"{{\"cmd\":\"read\", \"sid\":\"{deviceId}\"}}", RemoteIP, RemotePort);
JsonSerializer serializer = new JsonSerializer();
DeviceInfo token = JsonConvert.DeserializeObject<DeviceInfo>(ret);
if (!string.IsNullOrEmpty(token.Data))
{
JToken data = JsonConvert.DeserializeObject<JToken>(token.Data);
if (data["status"] != null)
{
var status = data["status"];
}
}
}
return (result);
}
}
#endregion
public enum OpConditionMode { AND, OR, NOR, XOR };
public class OpCondition<T>
{
public OpConditionMode Mode;
public KeyValuePair<string, T> Param { get; set; }
}
public enum ActionMode { Close, Minimize, Maximize, Mute };
public class OpAction<T>
{
public string Name { get; set; }
public ActionMode Mode { get; set; }
public IList<OpCondition<T>> Conditions { get; set; }
public IList<string> Param { get; set; }
}
public static class Extensions
{
private static NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
private delegate void SetPropertyThreadSafeDelegate<TResult>(
Control @this,
Expression<Func<TResult>> property,
TResult value);
public static void SetPropertyThreadSafe<TResult>(
this Control @this,
Expression<Func<TResult>> property,
TResult value)
{
var propertyInfo = (property.Body as MemberExpression).Member as PropertyInfo;
if (propertyInfo == null ||
!@this.GetType().IsSubclassOf(propertyInfo.ReflectedType) ||
@this.GetType().GetProperty(
propertyInfo.Name,
propertyInfo.PropertyType) == null)
{
throw new ArgumentException("The lambda expression 'property' must reference a valid property on this Control.");
}
if (@this.InvokeRequired)
{
@this.Invoke(new SetPropertyThreadSafeDelegate<TResult>
(SetPropertyThreadSafe),
new object[] { @this, property, value });
}
else
{
@this.GetType().InvokeMember(
propertyInfo.Name,
BindingFlags.SetProperty,
null,
@this,
new object[] { value });
}
}
public static void Update(this Control control, string text)
{
control.Invoke((MethodInvoker)delegate
{
// Running on the UI thread
control.Text = text;
});
}
public static string PaddingLeft(this string text, int width, char paddingchar = ' ')
{
var plen = width - Encoding.GetEncoding("gbk").GetBytes(text).Length;
var padding = new string(paddingchar, plen > 0 ? plen : 0);
return ($"{padding}{text}");
}
public static string PaddingRight(this string text, int width, char paddingchar = ' ')
{
var plen = width - Encoding.GetEncoding("gbk").GetBytes(text).Length;
var padding = new string(paddingchar, plen > 0 ? plen : 0);
return ($"{text}{padding}");
}
#region MiJia Device Exts
public static bool IsOpen(this AqaraDevice device)
{
bool result = false;
if (device is AqaraDevice)
{
if (device.States.ContainsKey("state"))
{
}
}
return (result);
}
#endregion
public static IEnumerable<T> Tail<T>(this IEnumerable<T> source, int N)
{
return source.Skip(Math.Max(0, source.Count() - N));
}
public static IEnumerable<T> Head<T>(this IEnumerable<T> source, int N)
{
return source.Take(Math.Max(0, Math.Min(N, source.Count())));
}
#region Process Helper
public static void Kill(this Process process)
{
if (process is Process && process.Id > 0)
{
try
{
var result = process.CloseMainWindow();
process.Close();
result = process.WaitForExit(5000);
if (!result && process.Id > 0)
{
process.Kill();
result = process.HasExited;
}
}
catch (Exception)
{
}
}
}
public static void Restart(this Process process)
{
if (process is Process && process.Id > 0)
{
try
{
var cmd = process.StartInfo;
Kill(process);
Process.Start(cmd);
}
catch (Exception)
{
}
}
}
#endregion
#region Service Helper
public static void Start(this ServiceController service, double timeout = 30)
{
if (service is ServiceController &&
(service.Status == ServiceControllerStatus.Stopped || service.Status == ServiceControllerStatus.StopPending))
{
try
{
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(timeout));
}
#if DEBUG
catch (Exception ex)
#else
catch (Exception)
#endif
{
#if DEBUG
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif
}
}
}
public static void Start(this IEnumerable<ServiceController> services, double timeout = 30)
{
foreach (var service in services)
{
Start(service, timeout);
}
}
public static void Start(this Dictionary<string, ServiceController> services, double timeout = 30)
{
foreach (var service in services)
{
Start(service.Value, timeout);
}
}
public static void Stop(this ServiceController service, double timeout = 30)
{
if (service is ServiceController && service.CanStop &&
service.Status != ServiceControllerStatus.Stopped && service.Status != ServiceControllerStatus.StopPending)
{
try
{
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(timeout));
}
#if DEBUG
catch (Exception ex)
#else
catch (Exception)
#endif
{
#if DEBUG
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif
}
}
}
public static void Stop(this IEnumerable<ServiceController> services, double timeout = 30)
{
foreach (var service in services)
{
Stop(service, timeout);
}
}
public static void Stop(this Dictionary<string, ServiceController> services, double timeout = 30)
{
foreach (var service in services)
{
Stop(service.Value, timeout);
}
}
public static void Restart(this ServiceController service, bool force = false, double timeout = 30)
{
if (service is ServiceController && service.CanStop)
{
try
{
bool running = service.Status == ServiceControllerStatus.Running;
Stop(service, timeout);
if (running || force)
Start(service, timeout);
}
#if DEBUG
catch (Exception ex)
#else
catch (Exception)
#endif
{
#if DEBUG
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif
}
}
}
public static void Restart(this IEnumerable<ServiceController> services, bool force = false, double timeout = 30)
{
foreach (var service in services)
{
Restart(service, force, timeout);
}
}
public static void Restart(this Dictionary<string, ServiceController> services, bool force = false, double timeout = 30)
{
foreach (var service in services)
{
Restart(service.Value, force, timeout);
}
}
public static void Pause(this ServiceController service, double timeout = 30)
{
if (service is ServiceController && service.CanPauseAndContinue && service.Status == ServiceControllerStatus.Running)
{
try
{
service.Pause();
service.WaitForStatus(ServiceControllerStatus.Paused, TimeSpan.FromSeconds(timeout));
}
#if DEBUG
catch (Exception ex)
#else
catch (Exception)
#endif
{
#if DEBUG
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif
}
}
}
public static void Pause(this IEnumerable<ServiceController> services, double timeout = 30)
{
foreach (var service in services)
{
Pause(service, timeout);
}
}
public static void Pause(this Dictionary<string, ServiceController> services, double timeout = 30)
{
foreach (var service in services)
{
Pause(service.Value, timeout);
}
}
public static void Continue(this ServiceController service, double timeout = 30)
{
if (service is ServiceController && service.CanPauseAndContinue &&
(service.Status == ServiceControllerStatus.Paused || service.Status == ServiceControllerStatus.PausePending))
{
try
{
service.Continue();
service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(timeout));
}
#if DEBUG
catch (Exception ex)
#else
catch (Exception)
#endif
{
#if DEBUG
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif
}
}
}
public static void Continue(this IEnumerable<ServiceController> services, double timeout = 30)
{
foreach (var service in services)
{
Continue(service, timeout);
}
}
public static void Continue(this Dictionary<string, ServiceController> services, double timeout = 30)
{
foreach (var service in services)
{
Continue(service.Value, timeout);
}
}
#endregion
}
public class ScriptEngine : IDisposable
{
private static NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
private static string APPFOLDER = Path.GetDirectoryName(Application.ExecutablePath);
private string SKYFOLDER = Path.Combine(KnownFolders.GetPath(KnownFolder.SkyDrive), @"ApplicationData\ConnectedHome");
private string DOCFOLDER = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments), @"Elton\ConnectedHome\");
private string USERNAME = Environment.UserName;
public bool Pausing { get; set; } = false;
public TextBox Logger { get; set; } = null;
public Action<string, string, MessageBoxIcon> NotificationAction { get; set; } = null;
#region MiJiaGateway routines
private System.Windows.Forms.Timer timerRefresh = null;
private int interval = 1000;
public int Interval
{
get { return (interval); }
set
{
interval = value;
if (timerRefresh is System.Windows.Forms.Timer)
{
if (timerRefresh.Enabled) timerRefresh.Stop();
timerRefresh.Interval = value;
timerRefresh.Start();
}
}
}
private async void TimerRefresh_Tick(object sender, EventArgs e)
{
if (sciptRunning || string.IsNullOrEmpty(scriptContext))
return;
else if (!(client is AqaraClient) || client.Gateways.Count() <= 0)
return;
try
{
var gateway = client.Gateways.Values.FirstOrDefault();
if (gateway == null)
{
if (Logger is TextBox) Logger.Update(string.Empty); //Logger.Text = string.Empty;
}
else
{
var maxlen_device = 0;
foreach (var device in gateway.Devices.Values)
{
if (!Devices.ContainsKey(device.Name))
Devices[device.Name] = device;
else
Devices[device.Name].StateDuration++;
var len_device = Encoding.GetEncoding("gbk").GetBytes(device.Name).Length;
if (len_device > maxlen_device) maxlen_device = len_device;
}
if (Logger is TextBox)
{
var sb = new StringBuilder();
sb.AppendLine($"{gateway.EndPoint?.ToString()}[{gateway.Id}]]");
sb.AppendLine($"{gateway.LatestTimestamp.ToString()} : {gateway.Token}");
sb.AppendLine("".PaddingRight(72, '-'));
foreach (var device in gateway.Devices.Values)
{
List<string> psl = new List<string>();
foreach (var pair in device.States)
{
psl.Add($"{pair.Key} = {pair.Value.Value}");
}
sb.AppendLine($"{device.Name.PaddingRight(maxlen_device)}[{string.Join(",", psl)}]");
}
Logger.Update(sb.ToString());
}
}
}
catch (Exception) { }
if (!Pausing) await RunScript();
}
private Task worker = null;
private CancellationToken workerCancelToken = new System.Threading.CancellationToken();
private AqaraConfig config = null;
private AqaraClient client = null;
private Dictionary<string, dynamic> Devices = new Dictionary<string, dynamic>();
//private SortedDictionary<DateTime, StateChangedEventArgs> events = new SortedDictionary<DateTime, StateChangedEventArgs>();
private Queue<KeyValuePair<DateTime, StateChangedEventArgs>> events = new Queue<KeyValuePair<DateTime, StateChangedEventArgs>>(100);
private async void DeviceStateChanged(object sender, StateChangedEventArgs e)
{
//events.Add(DateTime.Now, e);
if (events is Queue<KeyValuePair<DateTime, StateChangedEventArgs>>)
{
events.Enqueue(new KeyValuePair<DateTime, StateChangedEventArgs>(DateTime.Now, e));
if (events.Count > 100) events.Dequeue();
}
if (Devices is Dictionary<string, dynamic>)
{
Devices[e.Device.Name] = e.Device;
if (e.Device is AqaraDevice)
{
Devices[e.Device.Name].NewStateName = e.StateName;
Devices[e.Device.Name].NewStateValue = e.NewData;
Devices[e.Device.Name].StateDuration = 0;
}
}
if (!Pausing) await RunScript();
}
internal void InitMiJiaGateway(string basepath, string configFile)
{
if (File.Exists(Path.Combine(basepath, "aqara.json")))
{
config = AqaraConfig.Parse(File.ReadAllText(configFile));
}
else if (File.Exists(configFile))
{
config = AqaraConfig.Parse(File.ReadAllText(configFile));
}
if (client is AqaraClient)
{
client.CancellationPending = true;
AutoItX.Sleep(100);
if (worker is Task) workerCancelToken.ThrowIfCancellationRequested();
AutoItX.Sleep(100);
}
client = new AqaraClient(config);
client.DeviceStateChanged += DeviceStateChanged;
worker = Task.Run(() =>
{
client.DoWork(workerCancelToken);
}, workerCancelToken);
if (timerRefresh is System.Windows.Forms.Timer) timerRefresh.Stop();
timerRefresh = new System.Windows.Forms.Timer();
timerRefresh.Tick += TimerRefresh_Tick;
timerRefresh.Interval = Interval;
timerRefresh.Start();
}
#endregion
#region CSharp Script routines
private bool sciptRunning = false;
private string scriptContext = string.Empty;
public string ScriptContext
{
get { return (scriptContext); }
set { Load(value); }
}
private string scriptFile = string.Empty;
public string ScriptFile
{
get { return (scriptFile); }
set
{
if (File.Exists(value))
{
scriptFile = value;
ScriptContext = File.ReadAllText(scriptFile);
}
}
}
private Globals globals = new Globals();
private CancellationTokenSource cancelSource = new CancellationTokenSource();
private Script script;
private InteractiveAssemblyLoader loader = new InteractiveAssemblyLoader();
private ScriptOptions scriptOptions = ScriptOptions.Default;
internal ScriptOptions InitScriptEngine()
{
scriptOptions = ScriptOptions.Default;
//options = options.AddReferences(AppDomain.CurrentDomain.GetAssemblies());
scriptOptions = scriptOptions.AddReferences(new Assembly[] {
Assembly.GetAssembly(typeof(Path)),
Assembly.GetAssembly(typeof(AutoItX)),
Assembly.GetAssembly(typeof(JsonConvert)),
Assembly.GetAssembly(typeof(AqaraDevice)),
Assembly.GetAssembly(typeof(StateChangedEventArgs)),
Assembly.GetAssembly(typeof(MessageBox)),
Assembly.GetAssembly(typeof(MessageBoxButtons)),
Assembly.GetAssembly(typeof(MessageBoxDefaultButton)),
Assembly.GetAssembly(typeof(MessageBoxIcon)),
Assembly.GetAssembly(typeof(MessageBoxOptions)),
Assembly.GetCallingAssembly(),
Assembly.GetEntryAssembly(),
Assembly.GetExecutingAssembly(),
Assembly.GetAssembly(typeof(System.Globalization.CultureInfo)),
Assembly.GetAssembly(typeof(Color)),
Assembly.GetAssembly(typeof(Math)),
Assembly.GetAssembly(typeof(Regex)),
Assembly.GetAssembly(typeof(DynamicObject)), // System.Dynamic
Assembly.GetAssembly(typeof(ExpandoObject)), // System.Dynamic
Assembly.GetAssembly(typeof(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo)), // Microsoft.CSharp
Assembly.GetAssembly(typeof(Enumerable)), // Linq
Assembly.GetAssembly(typeof(DefaultExpression)), // Linq Expression
Assembly.GetAssembly(typeof(KnownFolders)), // KnownFolderPaths
});
scriptOptions = scriptOptions.AddImports(new string[] {
"System",
"System.Collections.Generic",
"System.Collections.Specialized",
"System.Dynamic",
"System.Drawing",
"System.Globalization",
"System.IO",
"System.Linq",
"System.Linq.Expressions",
"System.Math",
"System.Text",
"System.Text.RegularExpressions",
"System.Windows.Forms",
"AutoIt",
"KnownFolderPaths",
"Newtonsoft.Json",
"Elton.Aqara",
"MiJia",
});
if (File.Exists(scriptFile))
Load(File.ReadAllText(scriptFile));
return (scriptOptions);
}
public void Load(string context = "")
{
if (!string.IsNullOrEmpty(context)) scriptContext = context;
script = CSharpScript.Create(scriptContext, scriptOptions, typeof(Globals), loader);
script.Compile();
}
internal void Init(string basepath, string configFile, TextBox logger)
{
InitMiJiaGateway(basepath, configFile);
scriptOptions = InitScriptEngine();
if (logger is TextBox) Logger = logger;
if (globals is Globals) globals.NotificationAction = NotificationAction;
}
internal async Task<ScriptState> RunScript(bool AutoReset = false, bool IsTest = false)
{
ScriptState result = null;
if (sciptRunning || string.IsNullOrEmpty(scriptContext))
return (result);
else if (!(client is AqaraClient) || client.Gateways.Count() <= 0)
return (result);
sciptRunning = true;
var gateway = client.Gateways.Values.FirstOrDefault();
if (gateway == null)
{
if (Logger is TextBox)
Logger.Update(string.Empty);
//Logger.SetPropertyThreadSafe(() => Logger.Text, string.Empty);
}
else
{
try
{
globals.Logger.Clear();
globals.isTest = IsTest;
globals.device = Devices;
globals.events = events.Tail(25).ToList();
if (!(script is Script)) Load();
if (script is Script)
{
if (!(cancelSource is CancellationTokenSource) || cancelSource.IsCancellationRequested) cancelSource = new CancellationTokenSource();
result = await script.RunAsync(globals, cancelSource.Token);
}
if (AutoReset) globals.Reset();
globals.vars.Clear();
StringBuilder sb = new StringBuilder();
if (globals.Logger.Count > 0)
{
sb.AppendLine("-- Print Out ".PaddingRight(72, '-'));
foreach (var line in globals.Logger)
{
sb.AppendLine(line);
}
}
if (result is ScriptState && result.Variables.Length > 0)
{
sb.AppendLine("-- Variables ".PaddingRight(72, '-'));
foreach (var v in result.Variables)
{
if (v.Name.Equals("Device", StringComparison.CurrentCultureIgnoreCase)) continue;
if (v.Name.Equals("EventLog", StringComparison.CurrentCultureIgnoreCase)) continue;
if (v.Name.StartsWith("_")) continue;
sb.AppendLine($"{v.Name} = {v.Value}");
globals.vars[v.Name] = v.Value;
}
}
if (Logger is TextBox)
Logger.Update(Logger.Text + sb.ToString());
//Logger.SetPropertyThreadSafe(() => Logger.Text, Logger.Text + sb.ToString());
}
catch (Exception ex)
{
if (Logger is TextBox)
Logger.Update(Logger.Text + ex.Message);
//Logger.SetPropertyThreadSafe(() => Logger.Text, Logger.Text + ex.Message);
}
}
sciptRunning = false;
return (result);
}
#region IDisposable Support
private bool disposedValue = false; // 要检测冗余调用
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: 释放托管状态(托管对象)。
if (cancelSource is CancellationTokenSource && !cancelSource.IsCancellationRequested) cancelSource.Cancel();
}
// TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。
// TODO: 将大型字段设置为 null。
disposedValue = true;
}
}
// TODO: 仅当以上 Dispose(bool disposing) 拥有用于释放未托管资源的代码时才替代终结器。
// ~ScriptEngine() {
// // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
// Dispose(false);
// }
// 添加此代码以正确实现可处置模式。
public void Dispose()
{
// 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
Dispose(true);
// TODO: 如果在以上内容中替代了终结器,则取消注释以下行。
// GC.SuppressFinalize(this);
}
#endregion
#endregion
}
public class DEVICE : IDisposable
{
private static NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
internal AqaraClient client = default(AqaraClient);
public string State { get; internal set; } = string.Empty;
public string StateName { get; internal set; } = string.Empty;
public uint StateDuration { get; set; } = 0;
public Dictionary<string, string> Properties { get; set; } = new Dictionary<string, string>();
public dynamic Info { get; set; }
public bool Open { get; }
public void SetState(string key, string value)
{
if (client is AqaraClient)
{
List<KeyValuePair<string, dynamic>> states = new List<KeyValuePair<string, dynamic>>();
KeyValuePair<string, dynamic> kv = new KeyValuePair<string, dynamic>(key, value);
states.Add(kv);
SetStates(states);
}
}
public void SetStates(IEnumerable<KeyValuePair<string, dynamic>> states)
{
if (client is AqaraClient && states is IEnumerable<KeyValuePair<string, dynamic>>)
{
client.SendWriteCommand(Info as AqaraDevice, states);
}
}
public void Reset()
{
State = string.Empty;
StateName = string.Empty;
if (Info is AqaraDevice)
{
Info.NewStateName = string.Empty;
}
}
#region IDisposable Support
private bool disposedValue = false; // 要检测冗余调用
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: 释放托管状态(托管对象)。
if (Properties is Dictionary<string, string>) { Properties.Clear(); Properties = null; }
if (client is AqaraClient) { client.CancellationPending = true; }
}
// TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。
// TODO: 将大型字段设置为 null。
disposedValue = true;
}
}
// TODO: 仅当以上 Dispose(bool disposing) 拥有用于释放未托管资源的代码时才替代终结器。
// ~DEVICE() {
// // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
// Dispose(false);
// }
// 添加此代码以正确实现可处置模式。
public void Dispose()
{
// 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
Dispose(true);
// TODO: 如果在以上内容中替代了终结器,则取消注释以下行。
// GC.SuppressFinalize(this);
}
#endregion
}
public class Globals : IDisposable
{
private static NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
public enum MUTE_MODE { Mute, UnMute, Toggle, Background }
private class ProcInfo
{
uint PID { get; set; } = 0;
uint Parent { get; set; } = 0;
string Name { get; set; } = string.Empty;
string Title { get; set; } = string.Empty;
Process Info { get; set; } = default(Process);
}
Dictionary<uint, Process> procs = null;
private ManagementEventWatcher _watcherStart;
private ManagementEventWatcher _watcherStop;
private ScreenPowerMgmt _screenMgmtPower;
private PowerMgmt _PowerStatus = PowerMgmt.On;
private void ScreenMgmtPower(object sender, ScreenPowerMgmtEventArgs e)
{
_PowerStatus = e.PowerStatus;
if (e.PowerStatus == PowerMgmt.StandBy) logger.Add("StandBy Event!");
else if (e.PowerStatus == PowerMgmt.Off) logger.Add("Off Event!");
else if (e.PowerStatus == PowerMgmt.On) logger.Add("On Event!");
}
private Hardcodet.Wpf.TaskbarNotification.TaskbarIcon tbi = null;
private void InitNotification()
{