RobotViewModel.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 Helper;
  8. using Log;
  9. using Microsoft.Practices.Prism.ViewModel;
  10. using ProtoBuf;
  11. using Robot.Protos;
  12. namespace Modules.Robot
  13. {
  14. [Export(contractType: typeof (RobotViewModel)), PartCreationPolicy(creationPolicy: CreationPolicy.NonShared)]
  15. internal class RobotViewModel: NotificationObject, IDisposable
  16. {
  17. private readonly Host host;
  18. private string logText = "";
  19. private readonly DispatcherTimer timer = new DispatcherTimer(DispatcherPriority.Normal)
  20. { Interval = new TimeSpan(0, 0, 0, 0, 50) };
  21. public string LogText
  22. {
  23. get
  24. {
  25. return this.logText;
  26. }
  27. set
  28. {
  29. if (this.logText == value)
  30. {
  31. return;
  32. }
  33. this.logText = value;
  34. this.RaisePropertyChanged("LogText");
  35. }
  36. }
  37. public RobotViewModel()
  38. {
  39. Library.Initialize();
  40. this.host = new Host();
  41. this.timer.Tick += delegate { this.host.Run(); };
  42. this.timer.Start();
  43. }
  44. ~RobotViewModel()
  45. {
  46. this.Disposing(false);
  47. }
  48. public void Dispose()
  49. {
  50. this.Disposing(true);
  51. GC.SuppressFinalize(this);
  52. }
  53. protected virtual void Disposing(bool disposing)
  54. {
  55. this.host.Dispose();
  56. }
  57. public async void StartClient()
  58. {
  59. try
  60. {
  61. var address = new Address { HostName = "192.168.10.246", Port = 8901 };
  62. using (Peer peer = await this.host.ConnectAsync(address))
  63. {
  64. using (Packet packet = await peer.ReceiveAsync())
  65. {
  66. var bytes = packet.Bytes;
  67. var packetStream = new MemoryStream(bytes, 4, bytes.Length - 4);
  68. var smsg = Serializer.Deserialize<SMSG_Auth_Challenge>(packetStream);
  69. Logger.Debug(string.Format(
  70. "opcode: {0}\n{1}", BitConverter.ToUInt16(bytes, 0), XmlHelper.XmlSerialize(smsg)));
  71. await peer.DisconnectLaterAsync();
  72. }
  73. }
  74. }
  75. catch (Exception e)
  76. {
  77. Logger.Debug(e.Message);
  78. }
  79. }
  80. public void Start()
  81. {
  82. for (int i = 0; i < 1; ++i)
  83. {
  84. this.StartClient();
  85. }
  86. }
  87. }
  88. }