public async Task RunAsync(CancellationToken cancellationToken) { var externalTemperatureDevice = new ExternalTemperatureDevice(_droneId); var internalTemperatureDevice = new InternalTemperatureDevice( _droneId, _snapInternalTemperatureLikelihood); var gpsDevice = new GpsDevice(_droneId, GetCurrentLocation); var devices = new Device[] { externalTemperatureDevice, internalTemperatureDevice, gpsDevice }; foreach (var d in devices) { // Bubble up d.NewEvent += (sender, eventData) => NewEvent?.Invoke(sender, eventData); } var deviceTasks = from d in devices select d.RunAsync(cancellationToken); var moveTask = MoveAsync(cancellationToken); await Task.WhenAll(deviceTasks.Prepend(moveTask)); }
private void EnsureBlockSubscribed() { if (_eventsSubscription != null) { return; } this.MakeCallWithReconnect(app => { var storageKey = app.GetKeys("System", "Events"); _eventsSubscription = app.SubscribeStorage(storageKey, change => { if (change == null) { return; } try { var events = GetApplication().Serializer .DeserializeAssertReadAll <EventList>(change.HexToByteArray()).Events; foreach (var eventRecord in events) { NewEvent?.Invoke(this, eventRecord.Event); } } catch (Exception ex) { Settings.Logger.Error($"Failed to deserialize events: {ex}"); OnError?.Invoke(this, ex); throw; } }); }, Settings.MaxReconnectCount); }
private async Task GetEventsAsync() { using (ClientWebSocket ws = new ClientWebSocket()) { string url = API.BaseUrl.AbsoluteUri.Replace("http", "ws") + $"{Version}/events"; await ws.ConnectAsync(new Uri(url), CancellationToken.None); while (ws.State == WebSocketState.Open) { StringBuilder msg = new StringBuilder(); byte[] buffer = new byte[1024]; WebSocketReceiveResult receiveResult; do { receiveResult = await ws.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); msg.Append(Encoding.UTF8.GetString(buffer, 0, receiveResult.Count)); } while (!receiveResult.EndOfMessage); Console.WriteLine(msg); // NewEvent?.Invoke(wsEvent, msg); NewEvent?.Invoke(ws, EventArgs.Empty); } } }
public void OnContainerClick() { if (DragDropHelper.Items.FindAll(x => x.Event.Start == Start).Count == 0) { NewEvent?.Invoke(Start); } }
/// <summary> /// Creates a new instance /// </summary> /// <param name="timeProvider">The time provider to use</param> public RealTimeScheduleEventService(ITimeProvider timeProvider) { _nextUtcScheduledEvent = Ref.Create(new ReferenceWrapper <DateTime>(DateTime.MinValue)); _timer = new Timer( async state => { var nextUtcScheduledEvent = ((Ref <ReferenceWrapper <DateTime> >)state).Value.Value; var diff = nextUtcScheduledEvent - timeProvider.GetUtcNow(); // we need to guarantee we trigger the event after the requested due time // has past, if we got called earlier lets wait until time is right while (diff.Ticks > 0) { if (diff.Milliseconds >= 1) { Thread.Sleep(diff); } else { Thread.SpinWait(1000); } // testing has shown that it sometimes requires more than one loop diff = nextUtcScheduledEvent - timeProvider.GetUtcNow(); } NewEvent?.Invoke(this, EventArgs.Empty); }, _nextUtcScheduledEvent, // Due time is never, has to be scheduled Timeout.InfiniteTimeSpan, // Do not trigger periodically Timeout.InfiniteTimeSpan); }
private void Append(string name, DateTime date, byte[] data, long expectedVersion) { var @event = DesserializeEvent(data); @event.Version = expectedVersion; @event.Date = date; NewEvent?.Invoke(@event); }
/// <summary> /// Creates a new instance /// </summary> /// <param name="timeProvider">The time provider to use</param> public RealTimeScheduleEventService(ITimeProvider timeProvider) { _tokenSource = new CancellationTokenSource(); _event = new ManualResetEvent(false); _work = new Queue <DateTime>(); _pulseThread = new Thread(() => { while (!_tokenSource.Token.IsCancellationRequested) { DateTime nextUtcScheduledEvent; lock (_work) { _work.TryDequeue(out nextUtcScheduledEvent); } if (nextUtcScheduledEvent == default) { _event.WaitOne(_tokenSource.Token); _event.Reset(); if (_tokenSource.Token.IsCancellationRequested) { return; } continue; } // testing has shown that it sometimes requires more than one loop var diff = nextUtcScheduledEvent - timeProvider.GetUtcNow(); while (diff.Ticks > 0) { _tokenSource.Token.WaitHandle.WaitOne(diff); diff = nextUtcScheduledEvent - timeProvider.GetUtcNow(); if (_tokenSource.Token.IsCancellationRequested) { return; } } NewEvent?.Invoke(this, EventArgs.Empty); } }) { IsBackground = true, Name = "RealTimeScheduleEventService" }; _pulseThread.Start(); }
private void ProcessPacket(byte[] packet) { if (packet == null || packet.Length < 8) { return; } if ((packet[3] & 1) == 0) //Request { string methodName = ""; List <RPCVariable> parameters = _rpcDecoder.DecodeRequest(packet, ref methodName); RPCVariable response = new RPCVariable(RPCVariableType.rpcVoid); if (methodName == "") { response = RPCVariable.CreateError(-1, "Packet is not well formed: " + BitConverter.ToString(packet)); } else if (methodName == "system.listMethods") { response = new RPCVariable(RPCVariableType.rpcArray); response.ArrayValue.Add(new RPCVariable("system.multicall")); response.ArrayValue.Add(new RPCVariable("error")); response.ArrayValue.Add(new RPCVariable("event")); response.ArrayValue.Add(new RPCVariable("newDevices")); response.ArrayValue.Add(new RPCVariable("updateDevice")); response.ArrayValue.Add(new RPCVariable("deleteDevices")); response.ArrayValue.Add(new RPCVariable("newEvent")); response.ArrayValue.Add(new RPCVariable("deleteEvent")); response.ArrayValue.Add(new RPCVariable("updateEvent")); } else if (methodName == "system.multicall" && parameters.Any()) { foreach (RPCVariable method in parameters[0].ArrayValue) { if (method.Type != RPCVariableType.rpcStruct || method.StructValue.Count() != 2) { continue; } if (method.StructValue["methodName"].StringValue != "event") { continue; } List <RPCVariable> eventParams = method.StructValue["params"].ArrayValue; if (eventParams.Count() != 5 || eventParams[0].Type != RPCVariableType.rpcString || eventParams[1].Type != RPCVariableType.rpcInteger || eventParams[2].Type != RPCVariableType.rpcInteger || eventParams[3].Type != RPCVariableType.rpcString) { continue; } RPCEvent?.Invoke(this, eventParams[1].IntegerValue, eventParams[2].IntegerValue, eventParams[3].StringValue, eventParams[4], eventParams[0].StringValue); } } else if (methodName == "error" && parameters.Count() == 3 && parameters[1].Type == RPCVariableType.rpcInteger && parameters[2].Type == RPCVariableType.rpcString) { HomegearError?.Invoke(this, parameters[1].IntegerValue, parameters[2].StringValue); } else if (methodName == "newDevices") { NewDevices?.Invoke(this); } else if (methodName == "deleteDevices") { DevicesDeleted?.Invoke(this); } else if (methodName == "updateDevice") { if (parameters.Count == 4 && parameters[0].Type == RPCVariableType.rpcString && parameters[1].Type == RPCVariableType.rpcInteger && parameters[2].Type == RPCVariableType.rpcInteger && parameters[3].Type == RPCVariableType.rpcInteger) { UpdateDevice?.Invoke(this, parameters[1].IntegerValue, parameters[2].IntegerValue, parameters[3].IntegerValue); } } else if (methodName == "newEvent") { if (parameters.Count == 2 && parameters[1].Type == RPCVariableType.rpcStruct) { string id = ""; long type = -1; long peerId = 0; long channel = -1; string variable = ""; if (parameters[1].StructValue.ContainsKey("ID")) { id = parameters[1].StructValue["ID"].StringValue; } if (parameters[1].StructValue.ContainsKey("TYPE")) { type = parameters[1].StructValue["TYPE"].IntegerValue; } if (parameters[1].StructValue.ContainsKey("PEERID")) { peerId = parameters[1].StructValue["PEERID"].IntegerValue; } if (parameters[1].StructValue.ContainsKey("PEERCHANNEL")) { channel = parameters[1].StructValue["PEERCHANNEL"].IntegerValue; } if (parameters[1].StructValue.ContainsKey("VARIABLE")) { variable = parameters[1].StructValue["VARIABLE"].StringValue; } NewEvent?.Invoke(this, id, type, peerId, channel, variable); } } else if (methodName == "deleteEvent") { if (parameters.Count == 6) { EventDeleted?.Invoke(this, parameters[1].StringValue, parameters[2].IntegerValue, parameters[3].IntegerValue, parameters[4].IntegerValue, parameters[5].StringValue); } } else if (methodName == "updateEvent") { if (parameters.Count == 6) { UpdateEvent?.Invoke(this, parameters[1].StringValue, parameters[2].IntegerValue, parameters[3].IntegerValue, parameters[4].IntegerValue, parameters[5].StringValue); } } byte[] responsePacket = _rpcEncoder.EncodeResponse(response).ToArray(); SendPacket(responsePacket); } else //Response { _rpcResponse = _rpcDecoder.DecodeResponse(packet); _responseReceived.Set(); } }
/// <summary> /// Raises NewEvent event. /// </summary> public void OnNewEvent(LogEventArgs logEventArgs) { NewEvent?.Invoke(this, logEventArgs); }
private void newToolStripMenuItem_Click(object sender, EventArgs e) => NewEvent?.Invoke();
public void PushEvent(IActorInteractionEvent interactionEvent) { var eventArgs = new NewActorInteractionEventArgs(interactionEvent); NewEvent?.Invoke(this, eventArgs); }
protected void OnNewEvent(DroneEvent data) { NewEvent?.Invoke(this, data); }
public void Start() { if (includeEvents != null && includeEvents.Count() > 0) { foreach (var eventName in includeEvents) { var pollingUrl = new PollingUrl(apiKey, eventName); pollingUrl.OnNewEvent += (object sender, Events.HoistEvent hoistEvent) => { NewEvent.Invoke(this, hoistEvent); }; pollingUrl.Start(); pollingUrls.Add(pollingUrl); } } else { var pollingUrl = new PollingUrl(apiKey); pollingUrl.OnNewEvent += (object sender, Events.HoistEvent hoistEvent) => { NewEvent.Invoke(this, hoistEvent); }; pollingUrl.Start(); pollingUrls.Add(pollingUrl); } }
protected virtual void AddEvent(Event e) { NewEvent?.Invoke(e); }
protected virtual void OnNewEvent(object sender, NewEventArgs e) { NewEvent?.Invoke(sender, e); }