RobotViewModel.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.ComponentModel.Composition;
  3. using System.IO;
  4. using System.Text;
  5. using System.Windows.Threading;
  6. using ENet;
  7. using Log;
  8. using Microsoft.Practices.Prism.ViewModel;
  9. using ProtoBuf;
  10. using Robot.Protos;
  11. namespace Modules.Robot
  12. {
  13. [Export(contractType: typeof (RobotViewModel)), PartCreationPolicy(creationPolicy: CreationPolicy.NonShared)]
  14. internal class RobotViewModel: NotificationObject
  15. {
  16. private readonly Host host;
  17. private string logText = "";
  18. private readonly DispatcherTimer timer = new DispatcherTimer(DispatcherPriority.Normal)
  19. { Interval = new TimeSpan(0, 0, 0, 0, 50) };
  20. public string LogText
  21. {
  22. get
  23. {
  24. return this.logText;
  25. }
  26. set
  27. {
  28. if (this.logText == value)
  29. {
  30. return;
  31. }
  32. this.logText = value;
  33. this.RaisePropertyChanged("LogText");
  34. }
  35. }
  36. public RobotViewModel()
  37. {
  38. Library.Initialize();
  39. this.host = new Host();
  40. this.timer.Tick += delegate { this.host.Run(); };
  41. this.timer.Start();
  42. }
  43. public async void StartClient()
  44. {
  45. try
  46. {
  47. var address = new Address { Host = "192.168.10.246", Port = 8901 };
  48. using (Peer peer = await this.host.ConnectAsync(address))
  49. {
  50. using (Packet packet = await peer.ReceiveAsync())
  51. {
  52. Logger.Debug(packet.Length + " " + packet.Data);
  53. var bytes = Encoding.Default.GetBytes(packet.Data);
  54. var builder = new StringBuilder();
  55. foreach (var b in bytes)
  56. {
  57. builder.Append(b.ToString("X2"));
  58. }
  59. Logger.Debug(string.Format("HEX string: {0}", builder));
  60. var smsg = Serializer.Deserialize<SMSG_Auth_Challenge>(new MemoryStream(bytes));
  61. Logger.Debug(string.Format("{0}, {1}", smsg.Num, smsg.Seed));
  62. await peer.DisconnectLaterAsync();
  63. }
  64. }
  65. }
  66. catch (Exception e)
  67. {
  68. Logger.Debug(e.Message);
  69. }
  70. }
  71. public void Start()
  72. {
  73. for (int i = 0; i < 1; ++i)
  74. {
  75. this.StartClient();
  76. }
  77. }
  78. }
  79. }