RobotViewModel.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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
  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. public async void StartClient()
  45. {
  46. try
  47. {
  48. var address = new Address { Host = "192.168.10.246", Port = 8901 };
  49. using (Peer peer = await this.host.ConnectAsync(address))
  50. {
  51. using (Packet packet = await peer.ReceiveAsync())
  52. {
  53. var builder = new StringBuilder();
  54. var bytes = packet.Bytes;
  55. for (int i = 0; i < bytes.Length; ++i)
  56. {
  57. var b = bytes[i];
  58. builder.Append(b.ToString("X2"));
  59. }
  60. var packetStream = new MemoryStream(bytes, 4, bytes.Length - 4);
  61. var smsg = Serializer.Deserialize<SMSG_Auth_Challenge>(packetStream);
  62. Logger.Debug(string.Format(
  63. "opcode: {0}\n{1}", BitConverter.ToUInt16(bytes, 0), XmlHelper.XmlSerialize(smsg)));
  64. await peer.DisconnectLaterAsync();
  65. }
  66. }
  67. }
  68. catch (Exception e)
  69. {
  70. Logger.Debug(e.Message);
  71. }
  72. }
  73. public void Start()
  74. {
  75. for (int i = 0; i < 1; ++i)
  76. {
  77. this.StartClient();
  78. }
  79. }
  80. }
  81. }