RobotViewModel.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.ComponentModel.Composition;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using ELog;
  6. using Microsoft.Practices.Prism.ViewModel;
  7. using ENet;
  8. namespace Modules.Robot
  9. {
  10. [Export(contractType: typeof (RobotViewModel)), PartCreationPolicy(creationPolicy: CreationPolicy.NonShared)]
  11. internal class RobotViewModel : NotificationObject
  12. {
  13. private Host host = null;
  14. private string logText = "";
  15. public string LogText
  16. {
  17. get
  18. {
  19. return this.logText;
  20. }
  21. set
  22. {
  23. if (this.logText == value)
  24. {
  25. return;
  26. }
  27. this.logText = value;
  28. this.RaisePropertyChanged("LogText");
  29. }
  30. }
  31. public RobotViewModel()
  32. {
  33. Library.Initialize();
  34. host = new Host(null, Native.ENET_PROTOCOL_MAXIMUM_PEER_ID);
  35. Task.Factory.StartNew(() =>
  36. {
  37. while (host.Service(10) >= 0)
  38. {
  39. Event e;
  40. while (host.CheckEvents(out e) > 0)
  41. {
  42. switch (e.Type)
  43. {
  44. case EventType.Receive:
  45. {
  46. LogText += "Receive OK\r\n";
  47. Log.Debug("receive ok");
  48. break;
  49. }
  50. case EventType.Disconnect:
  51. {
  52. e.Peer.Dispose();
  53. break;
  54. }
  55. }
  56. }
  57. }
  58. });
  59. }
  60. public async Task<Peer> StartClient()
  61. {
  62. return await Task.Factory.StartNew<Peer>(() =>
  63. {
  64. var address = new Address {Host = "192.168.10.246", Port = 8901};
  65. var peer = this.host.Connect(address, 2, 1);
  66. return peer;
  67. });
  68. }
  69. public void Start()
  70. {
  71. var peer = StartClient().Result;
  72. if (peer.State == PeerState.Connected)
  73. {
  74. Log.Debug("11111111111");
  75. }
  76. }
  77. }
  78. }