Пример #1
0
        private async void buttonConnect_Click(object sender, EventArgs e)
        {
            this.buttonConnect.Enabled = false;

            var connectionType = (CommunicationType)this.comboBoxCommunicationType.SelectedItem;

            try
            {
                switch (connectionType)
                {
                case CommunicationType.SerialPort:
                    this.Communication = new SerialPortCommunication(this.textBoxValue.Text);
                    break;

                case CommunicationType.NetworkTcp:
                    this.Communication = new TcpNetworkCommunication(new IPEndPoint(IPAddress.Parse(this.textBoxValue.Text), 4003));
                    break;

                case CommunicationType.NetworkUdp:
                    this.Communication = new UdpNetworkCommunication(IPAddress.Parse(this.textBoxValue.Text));
                    break;

                default:
                    break;
                }

                this.DialogResult = DialogResult.OK;
            }
            catch (Exception exception)
            {
                MessageBox.Show($"Cannot connect {exception}", "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            this.buttonConnect.Enabled = true;
        }
Пример #2
0
        public async void TestSetup()
        {
            m_loggingContext = new LoggingContext(Guid.NewGuid());
            var data = TestHelper.CreateApplicationEndpoint();

            m_mockEventChannel = data.EventChannel;
            m_restfulClient    = data.RestfulClient;

            m_applicationEndpoint = data.ApplicationEndpoint;
            await m_applicationEndpoint.InitializeAsync(m_loggingContext).ConfigureAwait(false);

            await m_applicationEndpoint.InitializeApplicationAsync(m_loggingContext).ConfigureAwait(false);

            ICommunication communication = m_applicationEndpoint.Application.Communication;

            m_restfulClient.HandleRequestProcessed += (sender, args) =>
            {
                TestHelper.RaiseEventsOnHttpRequest(args, DataUrls.MessagingInvitations, HttpMethod.Post, "Event_MessagingInvitationStarted.json", m_mockEventChannel);
                TestHelper.RaiseEventsOnHttpRequest(args, DataUrls.EstablishMessagingCall, HttpMethod.Post, "Event_MessagingInvitationStarted.json", m_mockEventChannel);
            };

            // Start a messaging invitation
            m_messagingInvitation = await communication.StartMessagingWithIdentityAsync(
                "Test subject",
                "sip:[email protected]",
                "https://example.com/callback",
                "Local user",
                "sip:[email protected]",
                m_loggingContext);
        }
Пример #3
0
 public CommunicationPackage(ICommunication _communication, DataPackage _data)
 {
     Id = s_idCounter;
     s_idCounter++;
     Communication = _communication;
     Data          = _data;
 }
Пример #4
0
        //TODO: move to separate class {READY}
        public UserData GetInfoFromUser(TagType tag, Diff diff, IMp3File file, ICommunication communication)
        {
            communication.SendMessage($"File: {file.FilePath}");
            communication.SendMessage($"There is a problem with tag \"{tag}\". ");
            communication.SendMessage(
                $"You can enter tag from: \n\t1) File name (Data: \"{diff.FileNameValue}\"), \n\t2) Mp3 Tags (Data: \"{diff.TagValue}\"), \n\t3) Manual");

            while (true)
            {
                communication.SendMessage("Your choise (number): ");
                SyncActions inputData;
                var choiseCorrect = Enum.TryParse(communication.GetResponse(), out inputData);
                if (!choiseCorrect)
                {
                    communication.SendMessage("Wrong input!");
                    communication.SendMessage("You sholud enter number with action!");
                    continue;
                }

                switch (inputData)
                {
                    case SyncActions.FromFileName:
                        return new UserData(inputData, diff.FileNameValue);
                    case SyncActions.FromTags:
                        return new UserData(inputData, diff.TagValue);
                    case SyncActions.Manual:
                        communication.SendMessage("Enter text for tag \"" + tag + "\"");
                        return new UserData(inputData, communication.GetResponse());
                }
            }
        }
 public void OnStartGameAction(ICommunication communication, DataPackage data)
 {
     if (communication.IsMaster)
     {
         if (_serverInfo._lobbylist[0].IsLobbyComplete())
         {
             _gameStarted = true;
             Core.State   = StateEnum.GameRunningState;
             for (int i = 0; i < _serverInfo._communications.Count; i++)
             {
                 if (!(_serverInfo._communications[i] == communication))
                 {
                     _serverInfo._communications[i].Send(_dataPackageProvider.GetPackage("PlayerData"));
                 }
             }
             communication.Send(_dataPackageProvider.GetPackage("ServerStartingGame"));
         }
         else
         {
             communication.Send(_dataPackageProvider.GetPackage("NotEnoughInfo"));
         }
     }
     else
     {
         communication.Send(_dataPackageProvider.GetPackage("OnlyMasterStartInfo"));
     }
 }
Пример #6
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="comm">Object implementing the <see cref="ICommunication"/> interface for talking to the brick</param>
        /// <param name="alwaysSendEvents">Send events when data changes, or at every poll</param>
        public Brick(ICommunication comm, bool alwaysSendEvents)
        {
            DirectCommand = new DirectCommand(this);
            SystemCommand = new SystemCommand(this);
            BatchCommand  = new Command(this);

            Buttons = new BrickButtons();

            _alwaysSendEvents = alwaysSendEvents;

            var index = 0;

            _comm = comm;
            _comm.ReportReceived += ReportReceived;

            Ports = new Dictionary <InputPort, Port>();

            foreach (InputPort i in Enum.GetValues(typeof(InputPort)))
            {
                Ports[i] = new Port
                {
                    InputPort = i,
                    Index     = index++,
                    Name      = i.ToString(),
                };
            }
        }
 public PermissionSystem(
     ICommunication communication,
     IServiceScopeFactory scopeFactory)
 {
     this.communication = communication;
     this.scopeFactory  = scopeFactory;
 }
Пример #8
0
        public VcselDriverViewModel(ICommunication communication, IRegionManager regionManager, IEventAggregator eventAggregator)
            : base(regionManager, eventAggregator)
        {
            this.comm = communication;

            this.vcselDriver = new ConfigVcselDriver();

            ConfigVcselDriverCmd = new DelegateCommand(ConfigVcselDriver);
            eventAggregator.GetEvent <ConfigVcselDriverReplyEvent>().Subscribe(reply =>
            {
                if (reply.Ack == 0)
                {
                    this.PrintWatchLog("ConfigVcselDriver Success", LogLevel.Warning);
                }
                else
                {
                    this.PrintWatchLog("ConfigVcselDriver Fail", LogLevel.Error);
                }

                MaxIBias = (UInt32)(Math.Round(reply.MaxIBiasMicroAmp / 1000.0 / TickFrequency) * TickFrequency);
                MaxISw   = (UInt32)(Math.Round(reply.MaxISwitchMicroAmp / 1000.0 / TickFrequency) * TickFrequency);
                IBias    = (UInt32)(Math.Round(reply.IBiasMicroAmp / 1000.0 / TickFrequency) * TickFrequency);
                ISw      = (UInt32)(Math.Round(reply.ISwitchMicroAmp / 1000.0 / TickFrequency) * TickFrequency);
            }, true);
        }
Пример #9
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            // While this example uses the SerialCommunication class, any of the communication classes could be used... they all implement ICommunication.
            // For simplicity we will use 8N1 and not ask on the form.
            _comm = new SerialCommunication(txtSerialPort.Text, 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
            _comm.Logger = new Prophecy.Logger.TraceLogger(Prophecy.Logger.LoggerVerbosity.Normal); // assign the built-in TraceLogger just as an example. You could create your own logger class.
            //_comm.Delimiter = "\r"; // change the delimiter since it defaults to "\r\n".
            //_comm.CurrentEncoding = System.Text.ASCIIEncoding.ASCII;  // this is unnecessary since it defaults to ASCII
            //_comm.ReceivedDelimitedString += new EventHandler<ReceivedDelimitedStringEventArgs>(_comm_ReceivedDelimitedString); // Since our pretend protocol uses \r as the delimiter let's make life easy and subscribe to the ReceivedDelimitedString event. We could also subscribe to ReceivedString and ReceivedBytes.
            //_comm.IncludeDelimiterInRawResponse = false; // this is unnecessary since it defaults to false
            //_comm.ReadBufferEnabled = false; // this is unnecessary since it defaults to false and it since we are using the ReceivedDelimitedString event there would be no need to use a buffer.
            _comm.Delimiter = null; // set to null to disable the ReceivedDelimitedString
            _comm.CurrentEncoding = null; // do not decode strings
            //_comm.ReceivedBytes += new EventHandler<ReceivedBytesEventArgs>(_serial_DataReceived);
            _comm.ReadBufferEnabled = true; // If the ReadBufferEnabled property is true, you may

            _comm.DefaultSendDelayInterval = 0; // this is unnecessary since it defaults to 0

            _comm.DefaultSendDelayInterval = 0; // this is unnecessary since it defaults to 0

            // Start connection monitor.
            _comm.ConnectionMonitorTimeout = 60000;
            //_comm.ConnectionMonitorTestRequest = "HELLO\r"; // a pretend message to send when no data has been received for a while (note that serial connections can not detect physical disconnections so we count on this).
            _comm.ConnectionEstablished += new EventHandler<EventArgs>(_comm_ConnectionEstablished);
            _comm.ConnectionLost += new EventHandler<EventArgs>(_comm_ConnectionLost);
            _comm.StartConnectionMonitor(); // if we were not using connection monitoring we could call _comm.Open().

            txtSerialPort.Enabled = false;
            btnStart.Enabled = false;
        }
Пример #10
0
 public CommunicationAcceptEventArgs(ICommunication communication, byte[] head, Credential credential)
     : base(communication)
 {
     Head       = head;
     Handled    = false;
     Credential = credential;
 }
Пример #11
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="comm">Object implementing the <see cref="ICommunication"/> interface for talking to the brick</param>
        /// <param name="responseManager">The response manager used to get sequence numbers and create reports</param>
        /// <param name="alwaysSendEvents">Send events when data changes, or at every poll</param>
        public Brick(ICommunication comm, ResponseManager responseManager, bool alwaysSendEvents)
        {
            _subject       = new BehaviorSubject <Response>(null);
            _directCommand = new DirectCommand(this);
            _systemCommand = new SystemCommand(this);

            Buttons = new BrickButtons();

            _comm             = comm ?? throw new ArgumentNullException(nameof(comm));
            _responseManager  = responseManager ?? throw new ArgumentNullException(nameof(comm));
            _alwaysSendEvents = alwaysSendEvents;

            Ports = new Dictionary <InputPort, Port>();

            int index = 0;

            foreach (InputPort i in Enum.GetValues(typeof(InputPort)))
            {
                Ports[i] = new Port
                {
                    InputPort = i,
                    Index     = index++,
                    Name      = i.ToString(),
                };
            }
        }
 public MicrophoneHandler(
     Config.BotConfiguration botConfig,
     ICommunication communication)
 {
     this.communication = communication;
     this.botConfig     = botConfig;
 }
Пример #13
0
        private static void CircleMovementWithAbsolutePosition(ICommunication communication, bool debug)
        {
            var panTiltControl = new EneoPanTiltControl(communication, debug);

            panTiltControl.Start();
            panTiltControl.DisableLimit();

            //var random = new Random();

            for (var i = 0; i < 50; i++)
            {
                var positions = CalculatePolygon(i, new PointF(0, 0), 7);
                foreach (var position in positions)
                {
                    panTiltControl.MovePanAbsolute(position.X);
                    panTiltControl.MoveTiltAbsolute(position.Y);
                    Thread.Sleep(40);
                }

                //panTiltControl.PanTiltAbsolute(0, 0);
                //panTiltControl.ComparePosition(new PanTiltPosition(0, 0), 0.5, 20, 200);
            }

            panTiltControl.EnableLimit();
            panTiltControl.Dispose();
        }
Пример #14
0
        private static void TestPanMovementWithStartBeforeEndReached(ICommunication communication)
        {
            Console.WriteLine("Start");
            var panTiltControl  = new EneoPanTiltControl(communication);
            var positionChecker = new PositionChecker(panTiltControl);

            panTiltControl.PositionChanged += PanTiltControl_OnPositionChanged;

            while (true)
            {
                panTiltControl.PanAbsolute(0);
                positionChecker.ComparePosition(new PanTiltPosition(0, 0), 0.5, 20, 100);

                panTiltControl.PanAbsolute(40);
                positionChecker.ComparePosition(new PanTiltPosition(40, 0), 0.5, 20, 100);

                panTiltControl.PanRelative(-40);
                Thread.Sleep(500);

                panTiltControl.PanRelative(40);
                Thread.Sleep(500);

                panTiltControl.PanAbsolute(0);

                Console.WriteLine("Loop done");
            }
        }
        public static void Invoke(Command CommandType, ICommunication InvokeObject)
        {
            Type cmdResolveType = InvokeObject.GetType();

            MethodInfo[] methods = cmdResolveType.GetMethods();

            foreach (MethodInfo method in methods)
            {
                InvokeCommandAttribute attribute = null;

                object[] customAttributes = method.GetCustomAttributes(typeof(InvokeCommandAttribute), false);

                if (customAttributes != null && customAttributes.Length == 0)
                {
                    continue;
                }

                attribute = customAttributes.First() as InvokeCommandAttribute;

                if (attribute != null && attribute.CommandType.Equals(CommandType))
                {
                    method.Invoke(InvokeObject, null);
                    //CommandResolve cmdResolveObj = (CommandResolve)Activator.CreateInstance(typeof(CommandResolve), null);
                    //method.Invoke(cmdResolveObj, null);
                    break;
                }
            }
        }
        private static byte[] SecureSendReceive(ICommunication com, byte[] sndBuffer, int expectedReceiveBytes)
        {
            try
            {
                return(SendReceive(com, sndBuffer, expectedReceiveBytes));
            }
            catch (DeviceNotInitializedException)
            {
                if (TryWakeupToRetryCommand(com))
                {
                    return(SendReceive(com, sndBuffer, expectedReceiveBytes));
                }

                throw;
            }
            catch (TimeoutException)
            {
                if (TryWakeupToRetryCommand(com))
                {
                    return(SendReceive(com, sndBuffer, expectedReceiveBytes));
                }

                throw;
            }
        }
Пример #17
0
 public CommunicationReceiveEventArgs(ICommunication communication, Guid dataID, int dataLength, byte[] head) : base(communication)
 {
     this.DataID     = dataID;
     this.DataLength = dataLength;
     this.Head       = head;
     Handled         = false;
 }
Пример #18
0
        public CaptureDataViewModel(ICommunication communication, IRegionManager regionManager, IEventAggregator eventAggregator) : base(regionManager, eventAggregator)
        {
            this.comm = communication;
            foreach (CaptureDataTypeE item in Enum.GetValues(typeof(CaptureDataTypeE)))
            {
                CaptureDataTypes.Add(new ComboBoxViewMode <CaptureDataTypeE> {
                    Description = item.ToString(), SelectedModel = item, IsShow = Visibility.Visible
                });
            }

            foreach (UInt32 item in new UInt32[] { 1, 5, 10, 20, 30, 50, 100, 200, 300, 1000 })
            {
                if (item == 1000)
                {
                    CaptureDataNums.Add(new ComboBoxViewMode <UInt32> {
                        Description = "continue", SelectedModel = item, IsShow = Visibility.Visible
                    });
                }
                else
                {
                    CaptureDataNums.Add(new ComboBoxViewMode <UInt32> {
                        Description = item.ToString(), SelectedModel = item, IsShow = Visibility.Visible
                    });
                }
            }

            CaptureOkCmd     = new DelegateCommand(CaptureOK);
            CaptureCancelCmd = new DelegateCommand(CaptureCancel);
        }
Пример #19
0
        private void OnSearchAction(string obj, ICommunication communication)
        {
            if (isConnected)
            {
                _errorMsg = "Error: " + "This command does not exist or isn't enabled at this time";
                return;
            }

            _OutputWrapper.WriteOutput(0, 1, "Searching...", ConsoleColor.DarkGray);
            if (isConnected)
            {
                return;
            }

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            _UdpListener.StartListening();

            while (stopwatch.ElapsedMilliseconds < 10000)
            {
                if (_UdpListener._DataList.Count > 0)
                {
                    communication.AddPackage(_UdpListener._DataList.First());
                    _UdpListener._DataList.RemoveAt(0);
                }
            }
            stopwatch.Stop();
            _UdpListener.StopListening();
            Searched = true;
        }
Пример #20
0
 public CommunicationSendEventArgs(ICommunication communication, byte[] data, byte[] head)
     : base(communication)
 {
     DataID = Guid.NewGuid();
     Data   = data;
     Head   = head;
 }
Пример #21
0
            public static SubscriptionSetup <TMessage> SetupSubscription <TMessage>(ICommunication <TMessage> communication, IEnumerable <string> topics)
                where TMessage : IMessage
            {
                Enforce.NotNull(communication, nameof(communication));

                return(new SubscriptionSetup <TMessage>(communication, topics));
            }
Пример #22
0
 public IndexModel(ICommunication communication, ICommonResource commonResource, IUserService userService)
 {
     /* For Profile */
     _commonResource = commonResource;
     _communication  = communication;
     _userService    = userService;
 }
        public void OnAcceptInfoAction(DataPackage data, ICommunication communication)
        {
            var accept = MapProtocolToDto <AcceptDTO>(data);

            _infoOutputView.ViewEnabled = true;
            _infoOutputView.SetUpdateContent(accept._smallUpdate);
        }
Пример #24
0
        private async Task StartAgentCallAndTransferFlowAsync(ICommunication communication, string agent, string callContext)
        {
            IAudioVideoInvitation invite = await EstablishCallWithAgentAsync(communication, agent).ConfigureAwait(false);

            lock (m_syncRoot)
            {
                m_outboundAVConversations.Add(invite.RelatedConversation);
            }

            int result = Interlocked.Exchange(ref m_outboundCallTransferLock, 1);

            if (result == 0)
            {
                //Step 4: do transfer
                Logger.Instance.Information("[HuntGroupJob] Transferring call to " + agent);

                IAudioVideoCall av = invite.RelatedConversation.AudioVideoCall;

                ITransfer t = await av.TransferAsync(null, callContext, LoggingContext).ConfigureAwait(false);

                await t.WaitForTransferCompleteAsync().TimeoutAfterAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false);

                Logger.Instance.Information("[HuntGroupJob] Transfer completed successfully!");
            }
            else
            {
                // The call is already accepted and transfered by some one else
                Logger.Instance.Information("[HuntGroupJob] The call is already accepted and transfered by some one else; cancelling the transfer for " + agent);

                await invite.RelatedConversation.DeleteAsync(LoggingContext).ConfigureAwait(false);
            }
        }
Пример #25
0
 public AudioPlayer(
     Config.BotConfiguration botConfig,
     ICommunication communication)
 {
     this.communication = communication;
     defaultAudioDevice = botConfig.EffectOutputDevice;
 }
Пример #26
0
 public ChatHub(ILogger <ChatHub> logger, IMessage messageService, ICommunication communicationService, ICommonResource commonResource)
 {
     _logger               = logger;
     _messageService       = messageService;
     _communicationService = communicationService;
     _commonResource       = commonResource;
 }
 public CustomSimpleCommands(
     ICommunication communication,
     IServiceScopeFactory scopeFactory)
 {
     this.communication = communication;
     this.scopeFactory  = scopeFactory;
 }
Пример #28
0
 /// <summary>
 /// Constructor for the Twitch_Helix api helper
 /// </summary>
 public HelixHelper(
     Config.IBotConfigContainer botConfigContainer,
     ICommunication communication)
 {
     this.communication = communication;
     botConfig          = botConfigContainer.BotConfig;
 }
Пример #29
0
 private static IChannel <StringMessage> Subscribe(ICommunication <StringMessage> communication, string clientName)
 {
     return(Scenarios.PubSub.SetupSubscription(communication, new[] { "topic" })
            .UsingMessageReceivedHandler((sender, a) => { Console.WriteLine($"{clientName} received message: {a.Message}"); })
            .UsingChannelClosedHandler((sender, args) => { Interlocked.Increment(ref _closedChannels); })
            .Go());
 }
Пример #30
0
        //TODO: move to separate class {READY}
        public UserData GetInfoFromUser(TagType tag, Diff diff, IMp3File file, ICommunication communication)
        {
            communication.SendMessage($"File: {file.FilePath}");
            communication.SendMessage($"There is a problem with tag \"{tag}\". ");
            communication.SendMessage(
                $"You can enter tag from: \n\t1) File name (Data: \"{diff.FileNameValue}\"), \n\t2) Mp3 Tags (Data: \"{diff.TagValue}\"), \n\t3) Manual");

            while (true)
            {
                communication.SendMessage("Your choise (number): ");
                SyncActions inputData;
                var         choiseCorrect = Enum.TryParse(communication.GetResponse(), out inputData);
                if (!choiseCorrect)
                {
                    communication.SendMessage("Wrong input!");
                    communication.SendMessage("You sholud enter number with action!");
                    continue;
                }

                switch (inputData)
                {
                case SyncActions.FromFileName:
                    return(new UserData(inputData, diff.FileNameValue));

                case SyncActions.FromTags:
                    return(new UserData(inputData, diff.TagValue));

                case SyncActions.Manual:
                    communication.SendMessage("Enter text for tag \"" + tag + "\"");
                    return(new UserData(inputData, communication.GetResponse()));
                }
            }
        }
Пример #31
0
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="comm">Object implementing the <see cref="ICommunication"/> interface for talking to the brick</param>
		/// <param name="alwaysSendEvents">Send events when data changes, or at every poll</param>
		public Brick(ICommunication comm, bool alwaysSendEvents)
		{
			_directCommand = new DirectCommand(this);
			_systemCommand = new SystemCommand(this);
			_batchCommand = new Command(this);

			Buttons = new BrickButtons();

			_alwaysSendEvents = alwaysSendEvents;

			int index = 0;

			_comm = comm;
			_comm.ReportReceived += ReportReceived;

			Ports = new Dictionary<InputPort,Port>();

			foreach(InputPort i in Enum.GetValues(typeof(InputPort)))
			{
				Ports[i] = new Port
				{
					InputPort = i,
					Index = index++,
					Name = i.ToString(),
				};
			}
		}
Пример #32
0
        public void Initialize(ICommunication comm, IDictionary config)
        {
            _configuration = new CapiDeviceConfiguration(config);

            try
            {
                _capiApplication = new CapiApplication();
                _capiApplication.IncomingPhysicalConnection += new EventHandler<IncomingPhysicalConnectionEventArgs>(_capiApplication_IncomingPhysicalConnection);

                foreach (Controller ctrl in _capiApplication.Controllers)
                {
                    try
                    {
                        ctrl.Listen(CIPMask.Telephony | CIPMask.Telephony7KHZ | CIPMask.Audio7KHZ | CIPMask.Audio31KHZ);
                        LogInfoEntry("Listening on '{0}'", ctrl);
                    }
                    catch (Exception ex)
                    {
                        LogErrorEntry("Error listening on '{0}': {1}", ctrl, ex);
                    }
                }
            }
            catch (Exception ex)
            {
                _capiApplication = null;
                LogErrorEntry("Error on initializing: {0}", ex);
            }

            
        }
        /// <summary>
        /// 创建通讯模块
        /// </summary>
        /// <param name="communicationType">通讯方式</param>
        /// <returns></returns>
        public static ICommunication CreateCommunication(CommunicationType communicationType)
        {
            ICommunication communication = null;

            switch (communicationType)
            {
            case CommunicationType.C8962:
                communication = new C8962Communication();
                break;

            case CommunicationType.socketClient:
                communication = new SocketTcpClientCommunication();
                break;

            case CommunicationType.Http:
                communication = new HttpCommunication();
                break;

            case CommunicationType.HongDian:
                throw new NotImplementedException("CommunicationType.HongDian 通讯方式暂时未实现");

            //break;
            case CommunicationType.MAS:
                throw new NotImplementedException("CommunicationType.MAS 通讯方式暂时未实现");
            //break;

            default:
                throw new NotImplementedException("未知通讯方式");
                //break;
            }
            return(communication);
        }
Пример #34
0
 //<Constructors>
 public Client(ICommunication communication)
 {
     _communication = communication;
     _ActionHanlder = new ProtocolAction();
     _InputHandler  = new InputAction(_ActionHanlder);
     _OutputWrapper = new OutputWrapper();
 }
        public Zone(ICommunication comm, int zoneNumber, ILogger logger)
        {
            this._comm = comm;
            this.Number = zoneNumber;
            this._logger = logger;

            this._comm.ReceivedDelimitedString += new EventHandler<ReceivedDelimitedStringEventArgs>(ReceivedDelimitedString);
        }
Пример #36
0
        public PolishLinePlcLog(ICommunication client, ILogger logger)
            : base(client)
        {
            if (logger == null)
                throw new ArgumentNullException(string.Format("{0} wasn't initialized in class {1}.", typeof(ILogger).FullName, this.GetType().FullName));

            _logger = logger;
        }
Пример #37
0
 //
 //Constructors
 //
 /// <summary>
 /// Sets up a new client object communicating using the specified interface
 /// </summary>
 /// <param name="comms">The interface (implementing ICommunication) that will handle sending and recieving messages</param>
 public Client(ICommunication comms)
 {
     Logger.Log("New Client starting up.");
     Communications = comms;
     comms.Parent = this;
     comms.Recieved += RecieveMessage;
     comms.Failed += FailedMessage;
 }
Пример #38
0
        public Mp3Syncing(IEnumerable<IMp3File> files, string mask, ICommunication communication, ISaver saver)
        {
            _files = files.ToArray();
            _communication = communication;
            _mask = mask;

            _data = new List<KeyValuePair<string, KeyValuePair<string, Dictionary<TagType, string>>>>();
            _saver = saver;
        }
Пример #39
0
        private void OnTest(object sender, EventArgs e)
        {
            _comm = GetCommunication(_config.Node);

            _test = new LEDTest(2*_config.LEDsHeight + 2*_config.LEDsWidth);
            _timer.Elapsed += TimerOnElapsedTest;
            _timer.Start();


        }
Пример #40
0
        /// <summary>
        /// Constructor for Client UI object
        /// </summary>
        /// <param name="comms">The interface to bind communications to</param>
        public ClientUI(ICommunication comms)
        {
            InitializeComponent();

            _client = new Client(comms);
            _client.ActionableMessageRecieved += MessageRecieved;
            _client.Communications.Failed += MessageSendFailed;
            _client.Communications.CharacterRecieved += Communications_CharacterRecieved;
            SendMessage += _client.SendMessage;
        }
Пример #41
0
        /// <summary>
        /// Initializes a new instance of <see cref="Workspace"/> for a given <see cref="Token"/> with a given <see cref="ICommunication"/>
        /// </summary>
        /// <param name="token"><see cref="Token">Access token to use</see></param>
        /// <param name="communication"><see cref="ICommunication"/> to use</param>
        public Workspace(Token token, ICommunication communication)
        {
            _communication = communication;

            Groups = new Groups(token, communication);
            Datasets = new Datasets(token, communication);
            Tables = new Tables(token, communication);
            Rows = new Rows(token, communication);
            Dashboards = new Dashboards(token, communication);
            Reports = new Reports(token, communication);
            Tiles = new Tiles(token, communication);
        }
Пример #42
0
        private void StartService()
        {
            host = new ServiceHost(this);
            host.Open();
            channelFactory = new ChannelFactory<ICommunication>("ChatEndpoint");
            _channel = channelFactory.CreateChannel();
            
            //// Information to send to the channel
            //_channel.DisplayMessage(new SendEntity("Event", _myUserName + " has entered the conversation."));

            //// Information to display locally
            //_displayMessageDelegate(new SendEntity("Info", "To change your name, type setname: NEW_NAME"));
        }
Пример #43
0
        /// <summary>
        /// Initializes the modem
        /// </summary>
        /// <param name="comm"></param>
        /// <param name="config"></param>
        public void Initialize(ICommunication comm, IDictionary config)
        {
            _comm = comm;
            _config = config;
            _modemConfiguration = new AnalogATZModemConfiguration(config);

            _comm.OnDataReceived += new OnDataReceivedDelegate(_comm_OnDataReceived);


            if (TransmitCommand("ATZ") == false ||
             TransmitCommand(_modemConfiguration.CommandInitializeCallerId) == false)
            {
                throw new Exception("Initialization of Telecom Device failed!");
            }
        }
Пример #44
0
		public NxtBrick(ICommunication channel)
		{
			this.channel = channel;
			this.channel.ResponseReceived += Channel_ResponseReceived;
			this.context = SynchronizationContext.Current;
			this.tokenSource = new CancellationTokenSource();
			this.dataReceivedEvent = new ManualResetEvent(false);
			this.responses = new Queue<ResponseTelegram>();
			this.channelMonitor = new SemaphoreSlim(1);

			this.connectionCommands = new ConnectionCommands(this);
			this.directCommands = new DirectCommands(this);
			this.systemCommands = new SystemCommands(this);

			this.sensors = new Dictionary<SensorPort, SensorBase>();

		}
Пример #45
0
 /// <summary>
 /// Initializes an instance of <see cref="Groups"/>
 /// </summary>
 /// <param name="token"><see cref="Token">Access token</see></param>
 /// <param name="communication"><see cref="ICommunication"/> for communicating with Power BI</param>
 public Groups(Token token, ICommunication communication)
 {
     _token = token;
     _communication = communication;
 }
Пример #46
0
        private void OnStartStop(object sender, EventArgs e)
        {
            if (_timer.Enabled)
            {
                _timer.Stop();
                List<Color> black = new List<Color>(_config.LEDsHeight*2 + _config.LEDsWidth*2);
                black.ForEach(x => x = Color.Black);
                _comm.Write(black, 0);

            }
            else
            {
                _capture = new Capture(_config);
                _comm = GetCommunication(_config.Node);

                if (_comm == null)
                {
                    MessageBox.Show("Can't connect to AmbiBeam: " + _config.Node, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                _timer.Elapsed += timer_Tick;;
                _timer.Start();
            }

        }
Пример #47
0
 /// <summary>
 /// Initializes a new instance of <see cref="Reports"/>
 /// </summary>
 /// <param name="token"><see cref="Token">Access token</see></param>
 /// <param name="communication"><see cref="ICommunication"/> for communicating with Power BI</param>
 public Reports(Token token, ICommunication communication)
 {
     _token = token;
     _communication = communication;
 }
Пример #48
0
 /// <summary>
 /// Initializes a new instance of <see cref="Tiles"/>
 /// </summary>
 /// <param name="token"><see cref="Token">Access token</see></param>
 /// <param name="communication"><see cref="ICommunication"/> for communicating with Power BI</param>
 public Tiles(Token token, ICommunication communication)
 {
     _token = token;
     _communication = communication;
 }
Пример #49
0
 internal ControlAE6MC(ICommunication communication)
 {
     var enumerable = Enumerable.Range(1, AE6MC.NumberOfZones);
     this.communication = communication;
 }
Пример #50
0
		/// <summary>
		/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
		/// </summary>
		/// <param name="disposing">
		/// <c>True</c>, if the method is called directly from user code or
		/// <c>false</c>, if the method is called from inside the finalizer.
		/// </param>
		/// <remarks>
		/// This method executes in two distinct scenarios. 
		/// If <paramref name="disposing"/> equals <c>true</c>, the method has been called 
		/// directly or indirectly by a user's code. 
		/// Managed and unmanaged resources can be disposed.
		/// If <paramref name="disposing"/> equals <c>false</c>, the method has been called 
		/// by the runtime from inside the finalizer and you should not reference other objects. 
		/// Only unmanaged resources can be disposed.
		/// </remarks>
		private void Dispose(bool disposing)
		{
			if( !this.disposed )
			{
				if( disposing )
				{
					// Dispose managed resources.
					if (null != this.channel)
					{
						Task.Run(() => this.channel.DisconnectAsync());
						this.channel = null;
					}
					if(null != this.tokenSource)
					{
						this.tokenSource.Cancel();
						this.tokenSource.Dispose();
					}
					if (null != this.channelMonitor)
						this.channelMonitor.Dispose();

					if(null != this.dataReceivedEvent)
					{
						this.dataReceivedEvent.Dispose();
					}
				}

				// Free native resources here if necessary.

				// Disposing has been done.
				this.disposed = true;
			}
		}
 public ReadUntillEndRecieved(ICommunication lineReader)
 {
     _lineReader = lineReader;
 }
Пример #52
0
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="comm">Object implementing the <see cref="ICommunication"/> interface for talking to the brick</param>
		public Brick(ICommunication comm) : this(comm, false) { }
Пример #53
0
 public StockerPlc(ICommunication client)
     : base(client)
 {
 }
Пример #54
0
 public WyzComm(ICommunication comm, IAnalyzerCollection result)
 {
 }
Пример #55
0
 public PolishLinePlc(ICommunication client)
     : base(client)
 {
 }
Пример #56
0
 public void SaveClient()
 {
     //communication.username
     communication = new MysqlCommunication();
     communication.Connect("dsafdsa");
 }
Пример #57
0
 /// <summary>
 /// Initializes an instance of <see cref="Dashboards"/>
 /// </summary>
 /// <param name="token"><see cref="Token">Access token</see></param>
 /// <param name="communication"><see cref="ICommunication"/> for communicating with Power BI</param>
 public Dashboards(Token token, ICommunication communication)
 {
     _token = token;
     _communication = communication;
 }
Пример #58
0
 private void Form1_FormClosed(object sender, FormClosedEventArgs e)
 {
     if (_comm != null)
     {
         _comm.Dispose();
         _comm = null;
     }
 }
Пример #59
0
 public MountPlc(ICommunication client)
     : base(client)
 {
 }
Пример #60
0
        private void SimpleComm_Transfer(ICommunication source, ICommunication sink, string identifier)
        {

            AutoResetEvent syncSrc = new AutoResetEvent(false);
            AutoResetEvent syncSink = new AutoResetEvent(false);

            source.OnDataReceived += (OnDataReceivedDelegate)delegate(byte[] data, int length)
            {
                Console.WriteLine("{0} SOURCE received: {1}", identifier, Encoding.Default.GetString(data, 0, length));
            };

            sink.OnDataReceived += (OnDataReceivedDelegate)delegate(byte[] data, int length)
            {
                Console.WriteLine("{0} SINK received: {1}", identifier, Encoding.Default.GetString(data, 0, length));
            };

            //Src thread
            ThreadPool.QueueUserWorkItem(
                (WaitCallback)delegate(object state)
                {
                    for (int i = 0; i < 1000; i++)
                    {
                        byte[] b = Encoding.ASCII.GetBytes(string.Format("Hello from source: {0}", i));
                        source.SendData(b, 0, b.Length);
                        Thread.Sleep(20);
                    }

                    syncSrc.Set();
                });

            //Sink thread
            ThreadPool.QueueUserWorkItem(
                (WaitCallback)delegate(object state)
                {
                    for (int i = 0; i < 1000; i++)
                    {
                        byte[] b = Encoding.ASCII.GetBytes(string.Format("Hello from sink: {0}", i));
                        sink.SendData(b, 0, b.Length);
                        Thread.Sleep(30);
                    }

                    syncSink.Set();
                });

            syncSrc.WaitOne();
            syncSink.WaitOne();
        }