Exemplo n.º 1
0
        public async Task <int> AddEvent(CommandContext ctx, EventType type, string message, DateTime eventTime,
                                         ulong channelId = 0)
        {
            List <ulong> mentionedUserIds = new List <ulong>();
            List <ulong> mentionedRoleIds = new List <ulong>();

            ctx.Message.MentionedUsers.ToList().ForEach(user => mentionedUserIds.Add(user.Id));
            ctx.Message.MentionedRoles.ToList().ForEach(user => mentionedRoleIds.Add(user.Id));
            TimedEvent tEvent = new TimedEvent
            {
                Type              = type,
                Message           = message,
                EventTime         = eventTime,
                UserId            = ctx.User.Id,
                ChannelId         = channelId > 0 ? channelId : ctx.Channel.Id,
                MentionUserIdList = mentionedUserIds.ToArray(),
                MentionRoleIdList = mentionedRoleIds.ToArray()
            };

            tEvent.Id = (await ShimakazeBot.DbCtx.TimedEvents.AddAsync(tEvent)).Entity.Id;
            try
            {
                await ShimakazeBot.DbCtx.SaveChangesAsync();
            }
            catch (Exception e)
            {
                await ctx.RespondAsync(e.Message);
            }

            return(AddAndStartEvent(EventInTimer.MakeTimer(tEvent), tEvent.Id) ? tEvent.Id : -1);
        }
Exemplo n.º 2
0
        public Form(int x, int y)
        {
            Ready       = false;
            Controls    = new List <IFormControl>();
            Position    = new Vector2(x, y);
            ReveilEvent = new TimedEvent(200,
                                         () =>
            {
                if (Reveiling)
                {
                    Controls[ReveilIndex].Visible = true;
                    ContentHandler.Sounds["Swoosh"].Play();

                    if (ReveilIndex < Controls.Count - 1)
                    {
                        ReveilIndex++;
                    }
                    else
                    {
                        Reveiling = false;
                        Ready     = true;
                    }
                }
            }, -1);
        }
Exemplo n.º 3
0
 private void Blank_OnExecute(TimedEvent timedEvent)
 {
     if (timedEvent.FirstExecution)
     {
         destinationSlot.SetVisible(false);
     }
 }
Exemplo n.º 4
0
        public int schedule(TimedEvent task, DateTime time)
        {
            long t = time.Ticks - DateTime.Now.Ticks;

            t = Math.Abs(t);
            return(schedulemms(task, t));
        }
Exemplo n.º 5
0
        private static PlaybackEvent GetPlaybackEventWithNoteMetadata(TimedEvent timedEvent, TempoMap tempoMap, NotePlaybackEventMetadata noteMetadata)
        {
            var playbackEvent = new PlaybackEvent(timedEvent.Event, timedEvent.TimeAs <MetricTimeSpan>(tempoMap), timedEvent.Time);

            playbackEvent.Metadata.Note = noteMetadata;
            return(playbackEvent);
        }
Exemplo n.º 6
0
        public void GenerateSpan()
        {
            ZipkinEndpoint localEndpoint = new ZipkinEndpoint()
            {
                ServiceName = "tweetiebird"
            };

            var traceId  = "d239036e7d5cec116b562147388b35bf";
            var spanId   = "9cc1e3049173be09";
            var parentId = "8b03ab423da481c5";

            Dictionary <string, IAttributeValue> attributes    = new Dictionary <string, IAttributeValue>();
            IList <ITimedEvent <IAnnotation> >   annotations   = new List <ITimedEvent <IAnnotation> >();
            List <ITimedEvent <IMessageEvent> >  networkEvents = new List <ITimedEvent <IMessageEvent> >()
            {
                TimedEvent <IMessageEvent> .Create(Timestamp.Create(EPOCH_SECONDS + 1505855799, 433901068), new MessageEventBuilder(MessageEventType.RECEIVED, 0, 0, 0).SetCompressedMessageSize(7).Build()),
                TimedEvent <IMessageEvent> .Create(Timestamp.Create(EPOCH_SECONDS + 1505855799, 459486280), new MessageEventBuilder(MessageEventType.SENT, 0, 0, 0).SetCompressedMessageSize(13).Build())
            };

            ISpanData data = SpanData.Create(
                SpanContext.Create(
                    TraceId.FromBytes(Arrays.StringToByteArray(traceId)),
                    SpanId.FromBytes(Arrays.StringToByteArray(spanId)),
                    TraceOptions.FromBytes(new byte[] { 1 })),
                SpanId.FromBytes(Arrays.StringToByteArray(parentId)),
                true,                               /* hasRemoteParent */
                "Recv.helloworld.Greeter.SayHello", /* name */
                Timestamp.Create(EPOCH_SECONDS + 1505855794, 194009601) /* startTimestamp */,
                Attributes.Create(attributes, 0 /* droppedAttributesCount */),
                TimedEvents <IAnnotation> .Create(annotations, 0 /* droppedEventsCount */),
                TimedEvents <IMessageEvent> .Create(networkEvents, 0 /* droppedEventsCount */),
                LinkList.Create(new List <ILink>(), 0 /* droppedLinksCount */),
                null, /* childSpanCount */
                Status.OK,
                Timestamp.Create(EPOCH_SECONDS + 1505855799, 465726528) /* endTimestamp */);

            var handler = new TraceExporterHandler(new TraceExporterOptions()
            {
                UseShortTraceIds = false
            });
            var result = handler.GenerateSpan(data, localEndpoint);

            var zspan = ZipkinSpan.NewBuilder()
                        .TraceId(traceId)
                        .ParentId(parentId)
                        .Id(spanId)
                        .Kind(ZipkinSpanKind.SERVER)
                        .Name(data.Name)
                        .Timestamp(1505855794000000L + (194009601L / 1000))
                        .Duration(
                (1505855799000000L + (465726528L / 1000))
                - (1505855794000000L + (194009601L / 1000)))
                        .LocalEndpoint(localEndpoint)
                        .AddAnnotation(1505855799000000L + (433901068L / 1000), "RECEIVED")
                        .AddAnnotation(1505855799000000L + (459486280L / 1000), "SENT")
                        .PutTag("census.status_code", "OK")
                        .Build();

            Assert.Equal(zspan, result);
        }
Exemplo n.º 7
0
        public void Clone()
        {
            var timedEvent = new TimedEvent(new NoteOnEvent((SevenBitNumber)100, (SevenBitNumber)50));

            Assert.IsTrue(TimedEventEquality.AreEqual(timedEvent, timedEvent.Clone(), true),
                          "Clone of a timed event doesn't equal to the original one.");
        }
 public void AdvertiseCallback(TimedEvent timer)
 {
     foreach (string arg in BroadcastMessage)
     {
         Server.Broadcast(arg);
     }
 }
Exemplo n.º 9
0
        void bs_times_CurrentItemChanged(object sender, EventArgs e)
        {
            var selection = grid.SelectedCells.Cast <DataGridViewCell>().Select(fn => fn.RowIndex).Distinct().ToArray();
            var adding    = TimeSpan.Zero;

            foreach (var index in selection)
            {
                var ev = (TimedEvent)grid.Rows[index].DataBoundItem;
                adding += ev.ComputeDuration();
            }
            string msg = "";

            if (selection.Length > 1)
            {
                msg = $" Selection: {(int)adding.TotalHours}:{adding.Minutes:00}";
            }
            var time = TimedEvent.ComputeDuration(Times(), true);

            lblHours.Text = $"Time: {(int)time.TotalHours}:{time.Minutes:00}{msg}";
            if (Started() != null)
            {
                btnStartStop.Text = "Stop Timing";
            }
            else
            {
                btnStartStop.Text = "Start Timing";
            }
        }
Exemplo n.º 10
0
 public void OnTimerCB(TimedEvent evt)
 {
     if (Globals.Contains(evt.Name + "Callback"))
     {
         Invoke(evt.Name + "Callback", evt);
     }
 }
Exemplo n.º 11
0
        public LLUDPServer(LLUDP udp, IScene scene, IPAddress bindAddress, int port, IConfigSource configSource, IScheduler scheduler)
            : base(bindAddress, port)
        {
            m_udp     = udp;
            Scene     = scene;
            Scheduler = scheduler;

            IConfig throttleConfig = configSource.Configs["LLUDP"];

            m_throttleRates = new ThrottleRates(LLUDPServer.MTU, throttleConfig);

            m_resendTimer = new TimedEvent(100);
            m_ackTimer    = new TimedEvent(500);
            m_pingTimer   = new TimedEvent(5000);

            m_httpServer = Scene.Simian.GetAppModule <IHttpServer>();

            IConfig config = configSource.Configs["LLUDP"];

            if (config != null)
            {
                m_asyncPacketHandling = config.GetBoolean("AsyncPacketHandling", true);
                m_recvBufferSize      = config.GetInt("SocketReceiveBufferSize", 0);
            }

            m_throttle = new TokenBucket(null, m_throttleRates.SceneTotalLimit, m_throttleRates.SceneTotal);

            PacketEvents = new PacketEventDictionary(Scheduler);

            Scene.OnPresenceRemove += PresenceRemoveHandler;
        }
Exemplo n.º 12
0
        //
        // Interface Contracts
        //

        /// <summary>
        ///		Called by the TimedEvent holding this animation
        /// </summary>
        public void ExecuteCommand()
        {
            this.Animate();
            this.UpdateIntervalTime();
            this.currentEvent = null;
            this.ProgressToNextUnit();
        }
Exemplo n.º 13
0
        /// <summary>
        /// Initialize scene.
        /// </summary>
        public override void Init()
        {
            // Call base init.
            base.Init();

            // Set texture of the scene.
            Texture2D texture = Game.Content.Load <Texture2D>("Images/Screens/GameOver");

            // Load the nintendo logo.
            MonoSprite logo = new MonoSprite(texture, new Rectangle(0, 0, SuperPlatformerGame.RESOLUTION_X, SuperPlatformerGame.RESOLUTION_Y), Vector2.Zero, SuperPlatformerGame.RESOLUTION_X, SuperPlatformerGame.RESOLUTION_Y);

            // Add the logo to the drawlist.
            Children.Add(logo);

            _sound = Game.Content.Load <SoundEffect>("Audio/smw_gameover");

            if (_sound != null)
            {
                _sound.Play();
            }

            // Set and start the timer.
            _durationTimer = new TimedEvent(OnTimerElapsed, _duration);
            _durationTimer.Enable();
        }
        /// <inheritdoc/>
        public void AddEvent(string name, IDictionary <string, object> eventAttributes)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (eventAttributes == null)
            {
                throw new ArgumentNullException(nameof(eventAttributes));
            }

            if (!this.IsRecordingEvents)
            {
                return;
            }

            lock (this.@lock)
            {
                if (this.HasEnded)
                {
                    // logger.log(Level.FINE, "Calling AddEvent() on an ended Span.");
                    return;
                }

                this.InitializedEvents.AddEvent(TimedEvent <IEvent> .Create(PreciseTimestamp.GetUtcNow(), Event.Create(name, eventAttributes)));
            }
        }
Exemplo n.º 15
0
    public void handleMouseInput()
    {
        // if the mouse is in the range of the player and the player is
        // not frozen
        if (!freeze)
        {
            // if you are clicking left the tell playerToWorld to delete the block
            // if they are clicking right then try and add a block
            if (Input.GetButtonDown("Fire1") && isMouseClickInRange())
            {
                // create a timed event for the left click that must be complete to do again
                Vector3Int mousePos = getMousePositionAsInt();
                TimedEvent.create(() => removeTile(mousePos), 1f, "leftClick");
            }
            else if (Input.GetButtonDown("Fire2") && isMouseClickInRange() && !isMouseOverPlayer())
            {
                placeTile(getMousePositionAsInt());
            }
        }

        // if the player is scrolling at all then change the selected item
        if ((int)Input.mouseScrollDelta.y != 0)
        {
            playerToWorld.changeSelectedItem((int)Input.mouseScrollDelta.y);
        }
    }
Exemplo n.º 16
0
        public PatternActionResult Invoke(long time, PatternContext context)
        {
            var programEvent = Program.GetProgramEvent(context.Channel);
            var timedEvent   = new TimedEvent(programEvent, time);

            return(new PatternActionResult(time, new[] { timedEvent }));
        }
        public PatternActionResult Invoke(long time, PatternContext context)
        {
            var textEvent  = (BaseTextEvent)Activator.CreateInstance(typeof(TEvent), Text);
            var timedEvent = new TimedEvent(textEvent, time);

            return(new PatternActionResult(time, new[] { timedEvent }));
        }
Exemplo n.º 18
0
 public void KillTimer(TimedEvent timer)
 {
     if (timer != null)
     {
         timer.Kill();
         Timers.Remove(timer.Name);
     }
 }
Exemplo n.º 19
0
 public void KillParallelTimer(TimedEvent timer)
 {
     if (timer != null)
     {
         timer.Kill();
         ParallelTimers.Remove(timer);
     }
 }
Exemplo n.º 20
0
 public ProcedimentosAdmin()
 {
     InitializeComponent();
     Fill();
     ControlsH.CreateColumns(ProcedimentosDG, typeof(Procedimento_Table));
     TimedEvent = new TimedEvent(1, 2, true, UpdateProcedimentos);
     TimedEvent.TriggerNow();
 }
Exemplo n.º 21
0
        /// <summary>
        /// Add an event to the map
        /// </summary>
        /// <param name="ev"></param>
        /// <returns>unique id of the added event, negative if the adding the event failed</returns>
        public int AddEvent(TimedEvent ev)
        {
            // assign and return the unique id
            int eventId = ++idCounter;
            eventMap.Add(eventId, ev);

            return eventId;
        }
        //
        // Constructor
        //

        public PlayerRespawner()
        {
            // DATA SET
            this.respawnWait = 2.5f;

            // Add self to timer
            this.timedEvent = TimedEventManager.Active.Create(this, this.respawnWait);
        }
Exemplo n.º 23
0
        public EventTimer AddTimer(float duration, TimedEvent callbackFunction)
        {
            EventTimer newTimer = new EventTimer(duration, callbackFunction);

            currentTimers.Add(newTimer);

            return(newTimer);
        }
Exemplo n.º 24
0
 public void goToStage(int stage)
 {
     _currentEventSet = retrieveStage(stage);
     StopAllCoroutines();
     currentStage = stage;
     startTime    = Time.time;
     _nextEvent   = null;
 }
Exemplo n.º 25
0
        //
        // Constructor
        //

        public Animation() : base()
        {
            this.currentUnit              = null;
            this.currentEvent             = null;
            this.intervalTime             = 1.0f;
            this.requestedNewIntervalTime = this.intervalTime;
            this.isLooping = false;
        }
Exemplo n.º 26
0
 public PesquisaPessoas()
 {
     InitializeComponent();
     ControlsH.CreateColumns(PessoasDG, typeof(Table1));
     ControlsH.CreateColumns(EnderecoDG, typeof(Table2));
     TimedEvent = new TimedEvent(1, 3, true, UpdatePessoas);
     TimedEvent.TriggerNow();
 }
Exemplo n.º 27
0
        public HttpResponseMessage Put(TimedEvent timedEvent)
        {
            HeatingService.UpdateEvent(timedEvent);

            var response = Request.CreateResponse<TimedEvent>(System.Net.HttpStatusCode.OK, timedEvent);

            return response;
        }
Exemplo n.º 28
0
        public void _handleIncentives(IMessageBase message)
        {
            //Logger.Debug("handle incentives");
            Incentives incentives = (Incentives)message;

            List <RevokeEvent> revokeEvents    = new List <RevokeEvent>();
            List <TimedEvent>  actuationEvents = new List <TimedEvent>();

            foreach (TimedEvent newEvent in incentives.Events)
            {
                var newTimedEvent = (TimedEvent)newEvent;
                if (newEvent is RevokeEvent)
                {
                    revokeEvents.Add((RevokeEvent)newTimedEvent);
                }
                else
                {
                    actuationEvents.Add(newTimedEvent);
                }
            }

            lock (_events)
            {
                _events.RemoveAll(event_ =>
                                  revokeEvents.TrueForOne(
                                      revokeEvent => revokeEvent.Id == event_.Id
                                      )
                                  );

                foreach (TimedEvent newEvent in actuationEvents)
                {
                    TimedEvent eventToOverwrite = _events.Find(existingEvent => newEvent.StrategyId == existingEvent.StrategyId && newEvent.Id == existingEvent.Id);
                    if (eventToOverwrite == null)
                    {
                        _events.Add(newEvent);
                    }
                    else
                    {
                        eventToOverwrite.OverrideWith(newEvent);
                    }
                }
            }

            //double minDistance = double.MaxValue;
            //Vector minPosition = null;
            //Vector currentPosition = CurrentPosition;
            //foreach (Vector position in positions)
            //{
            //    double distance = (currentPosition - position).SqrMagnitude;
            //    if (distance < minDistance)
            //    {
            //        minDistance = distance;
            //        minPosition = position;
            //    }
            //}

            // _recommendedPosition = minPosition;
        }
Exemplo n.º 29
0
        public void SetTime_NonZero()
        {
            var tempoMap          = TempoMap.Default;
            var timedEvent        = new TimedEvent(new NoteOnEvent(), 1000);
            var changedTimedEvent = timedEvent.SetTime(new MetricTimeSpan(0, 0, 2), tempoMap);

            Assert.AreSame(timedEvent, changedTimedEvent, "Changed timed event is not the original one.");
            Assert.AreEqual(changedTimedEvent.TimeAs <MetricTimeSpan>(tempoMap), new MetricTimeSpan(0, 0, 2), "Time is invalid.");
        }
Exemplo n.º 30
0
        public void SetTime_Zero()
        {
            var tempoMap          = TempoMap.Default;
            var timedEvent        = new TimedEvent(new NoteOnEvent(), 1000);
            var changedTimedEvent = timedEvent.SetTime(new MetricTimeSpan(), tempoMap);

            Assert.AreSame(timedEvent, changedTimedEvent, "Changed timed event is not the original one.");
            Assert.AreEqual(0, changedTimedEvent.Time, "Time is not zero.");
        }
 // Start is called before the first frame update
 void Start()
 {
     StartCoroutine(BeatGroupInitializer());
     if (events.Length > 0)
     {
         Array.Sort(events);
         _nextEvent = events[_eventIndex];
     }
 }
Exemplo n.º 32
0
        public Player(Vector2 position)
        {
            _position        = position;
            _initialPosition = Position;
            _state           = PlayerState.Idle;

            _timedEventInvinsible = new TimedEvent(2000, () => IsInvinsible = false);
            _isVisible            = true;
        }
Exemplo n.º 33
0
        public static void AddEvent(TimedEvent timedEvent)
        {
            if (timedEvent.Id == 0)
            {
                highestEventId++;
                timedEvent.Id = highestEventId;
            }
            else if (timedEvent.Id > highestEventId) highestEventId = timedEvent.Id;

            Events.Add(timedEvent);
        }
Exemplo n.º 34
0
        public IEnumerable<TimedEvent> GetRange(DateTime RangeStart, DateTime RangeEnd)
        {
            // Handle zero interval condition
             if (_Interval == TimeSpan.Zero) yield break;

             // Check event intersection with range
             TimeSpan RangeDuration = RangeEnd - RangeStart;
             DateTime IterateStart = SynchronizeTime(RangeStart);
             DateTime IterateEnd = RangeEnd;

             // Check first event
             // EEEE EEEE
             //   WWWWWWW
             TimedEvent FirstEvt = new TimedEvent(
            (IterateStart.Ticks >= _Interval.Ticks ? // Handle when IterateStart is near DateTime.MinValue
            IterateStart.Subtract(_Interval) :
            DateTime.MinValue),
            _Duration);
             if (FirstEvt.StartTime != IterateStart && FirstEvt.Intersects(new TimedEvent(RangeStart, RangeEnd)))
            yield return FirstEvt;

             if (DateTime.MaxValue - IterateEnd >= _Interval) {
            for (DateTime dt = IterateStart; dt < IterateEnd; dt = dt.Add(_Interval))
               yield return new TimedEvent(dt, dt.Add(_Duration));
             }
             else {
            // Special case when end of iteration is very close to DateTime.MaxValue
            // IterateEnd must be at least > Interval time to match any events
            if (IterateEnd.Ticks >= _Interval.Ticks) {
               DateTime IterateEnd2 = IterateEnd.Subtract(_Interval);
               for (DateTime dt = IterateStart; ; dt = dt.Add(_Interval)) {
                  yield return new TimedEvent(dt, dt.Add(_Duration));
                  if (dt >= IterateEnd2) break;
               }
            }
             }

             yield break;
        }
Exemplo n.º 35
0
        public IEnumerable<TimedEvent> GetRange(DateTime RangeStart, DateTime RangeEnd)
        {
            TimedEvent RangeEvent = new TimedEvent(RangeStart, RangeEnd);
             IEnumerable<TimedEvent> Enum1 = _OffsetTime.Ticks >= 0 ?
            _Schedule.GetRange(SafeDateTimeAdd(RangeStart, _OffsetTime.Negate()), DateTime.MaxValue) :
            _Schedule.GetRange(SafeDateTimeAdd(RangeStart, _OffsetTime), DateTime.MaxValue);

             foreach (TimedEvent Evt in Enum1) {
            TimedEvent OffsetEvt;
            try {
               OffsetEvt = new TimedEvent(Evt.StartTime + _OffsetTime, Evt.EndTime + _OffsetTime);
            }
            catch (ArgumentOutOfRangeException) {
               // This occurs when _OffsetTime is added to StartTime or EndTime and causes an overflow or underflow.
               // In this case, we ignore this event, since it can't be represented.
               continue;
            }
            if (OffsetEvt.StartTime >= RangeEnd) break;
            if (OffsetEvt.Intersects(RangeEvent))
               yield return OffsetEvt;
             }

             yield break;
        }
Exemplo n.º 36
0
    /// <summary>.
    /// Insert a timer event in the queue. Timer values are
    /// recursively defined by the summation of preceding timer values.
    /// So inserting a timeEvent with a value of 7 seconds may look as follows:
    /// 
    /// Q before:   2 -> 3 -> 1 -> 5 -> ...
    ///
    /// Insert(7):  2 -> 3 -> 1 -> 1 -> 4 -> ...
    ///                            ^ seven inserted here. 1 + summation of preceding timers is 7. 
    /// </summary>
    public void Insert(TimedEvent timedEvent)
    {
      int i = 0;

      Console.WriteLine("insert " + timedEvent.Timer_ms);

      //spool to proximity-based index for this event 
      while (timedEvent.Timer_ms > 0 && i < _Q.Count)
      {
        timedEvent.Timer_ms -= _Q[i].Timer_ms;
        if (timedEvent.Timer_ms > 0)
        {
          i++;
        }
      }

      //insert and decrement right neighbor
      if (i < _Q.Count)
      {
        //There's some pencil work here to adjust the timerVals, and the neighbor.
        timedEvent.Timer_ms += _Q[i].Timer_ms;
        _Q[i].Timer_ms -= timedEvent.Timer_ms;
        _Q.Insert(i, timedEvent);
      }
      //degenerate case: end of list, just insert at the end
      else
      {
        _Q.Add(timedEvent);
      }
      //Console.WriteLine("Inserted event with tmr: "+timedEvent._timer_ms);
    }
Exemplo n.º 37
0
 public TimedEventBooleanUnitTest(string Name, TimedEvent Event, Func<TimedEvent, bool> TimedEventFunc, bool ExpectedResult)
 {
     this.Name = Name;
     this.Event = Event;
     this.TimedEventFunc = TimedEventFunc;
     this.ExpectedResult = ExpectedResult;
 }
Exemplo n.º 38
0
        private static void ProcessRelay(Heater p_Heater, TimedEvent p_Event, Boolean p_StaySame)
        {
            // if p_StaySame the relay should stay off if already off or on if already on
            bool bTooHot = false;

            for (int a = 0; a < p_Heater.Sensors.Count; a++)
            {
                if (p_Heater.Sensors[a].Reading >= p_Heater.TempMax)
                {
                    bTooHot = true;
                    break;
                }
            }

            if (!bTooHot)
            {
                bool bFound = false;
                bool bState = (p_Event.Type == (int)TimedEvent.EventType.Heat);

                for (int k = 0; k < m_oProcessedRelays.Count; k++)
                {
                    if (p_Heater.RelayAddress == m_oProcessedRelays[k][0])
                    {
                        if (p_Event.Id >= int.Parse(m_oProcessedRelays[k][1]))
                        {// highest event id has priority
                            RelayControl.SetupRelay(p_Heater.RelayAddress, (p_StaySame) ? RelayControl.GetRelayState(p_Heater.RelayAddress) : bState);
                            m_oProcessedRelays[k][1] = p_Event.Id.ToString();
                        }
                        bFound = true;
                    }
                }

                if (!bFound)
                {
                    RelayControl.SetupRelay(p_Heater.RelayAddress, (p_StaySame) ? RelayControl.GetRelayState(p_Heater.RelayAddress) : bState);
                    string[] saUsedRelay = new string[3];
                    saUsedRelay[0] = p_Heater.RelayAddress;
                    saUsedRelay[1] = p_Event.Id.ToString();
                    m_oProcessedRelays.Add(saUsedRelay);
                }

            }
        }
Exemplo n.º 39
0
        // Optimized 2008-07-13
        public IEnumerable<TimedEvent> GetRange(DateTime RangeStart, DateTime RangeEnd)
        {
            /* Subtraction complex example:
              * Input:
              * A: xxxx  xxxx
              * B:   xxxxxx
              *
              * Compare:
              * A: AAAA  xxxx
              * B:   BBBBBB
              *
              * Compute subtraction:
              * A: AA--  xxxx
              * A:   --BBBB
              *
              * Compare next:
              * A: RR    AAAA
              * B:     BBBB
              *
              * Compute subtraction:
              * A: RR    --AA
              * B:     BB--
              *
              * Result:
              * RR      RR
              *
              */

             // Prepare iterator A.
             var IteratorA = _ScheduleA.GetRange(RangeStart, RangeEnd).GetEnumerator();
             bool HasMoreA = IteratorA.MoveNext();

             // If no events in schedule A, quit now.
             if (!HasMoreA) yield break;

             // Prepare iterator B.
             var IteratorB = _ScheduleB.GetRange(RangeStart, RangeEnd).GetEnumerator();
             bool HasMoreB = IteratorB.MoveNext();

             List<TimedEvent> QueueA = new List<TimedEvent>();

             bool readvanceFlag;
             do {
            readvanceFlag = false;

            // Get next event for A from queue or iterator, whichever is earliest.
            TimedEvent A = default(TimedEvent);
            if (QueueA.Count > 0 && (!HasMoreA || QueueA[0] <= IteratorA.Current)) {
               // Pop event off queue A.
               A = QueueA[0];
               QueueA.RemoveAt(0);
            }
            else if (HasMoreA) {
               // If queue is empty or iterator's current value is earlier,
               // get next event from A and put it on the queue.
               QueueA.Add(IteratorA.Current);
               HasMoreA = IteratorA.MoveNext();
               readvanceFlag = true;
               continue;
            }

            bool recompareFlag;
            do {  // comparison code block.
               recompareFlag = false;

               if (!HasMoreB) {
                  // If no more events from B, return remaining events from A.
                  yield return A;
               }
               else {
                  // Compare A <=> B.
                  var B = IteratorB.Current;

                  // AAAA
                  //      BBBB
                  if (A.EndTime <= B.StartTime) {
                     // No intersection, return A.
                     yield return A;
                  }
                  // AAAA   or AAAA or   AAAA or  AA
                  //   BBBB     BB     BBBB      BBBB
                  else if (B.EndTime > A.StartTime) {
                     // AAAA   or AAAA
                     //   BBBB     BB
                     if (A.StartTime < B.StartTime) {
                        var NewA = new TimedEvent(A.StartTime, B.StartTime);
                        QueueA.Add(NewA);

                        if (B.EndTime < A.EndTime) {
                           var NewA2 = new TimedEvent(B.EndTime, A.EndTime);
                           QueueA.Add(NewA2);
                        }
                     }
                     //   AAAA or  AA
                     // BBBB      BBBB
                     else if (B.EndTime < A.EndTime) {
                        var NewA = new TimedEvent(B.EndTime, A.EndTime);
                        QueueA.Add(NewA);
                     }
                  }
                  else {
                     //      AAAA
                     // BBBB
                     // No intersection, advance schedule B and recompare.
                     HasMoreB = IteratorB.MoveNext();
                     recompareFlag = true;
                     continue;
                  }
               } // if (!HasMoreB) else
            } while (recompareFlag);

            // Continue until no more events from A.
             } while (readvanceFlag || HasMoreA || QueueA.Count > 0);

             yield break;
        }
Exemplo n.º 40
0
 public static void UpdateEvent(TimedEvent timedEvent)
 {
     if (timedEvent.Id != 0)
     {
         if (timedEvent.Id > highestEventId) highestEventId = timedEvent.Id;
         TimedEvent anEvent = GetEventById(timedEvent.Id);
         if (anEvent != null) anEvent.setData(timedEvent);
     }
 }
Exemplo n.º 41
0
 /// <summary>
 /// Constructor for event with a start time and duration.
 /// </summary>
 /// <param name="EventTime">Date/time of event.</param>
 /// <param name="Duration">Duration of event.</param>
 public OneTimeSchedule(DateTime StartTime, TimeSpan Duration)
 {
     _Event = new TimedEvent(StartTime, Duration);
      _Notation = NotationKind.Lasting;
 }
Exemplo n.º 42
0
    /// <summary>
    /// GameModel.Initiaize() must be called before this, to make sure required objects exist.
    /// </summary>
    /// <param name="level"></param>
    void _initializeTimedEventQ(Level level)
    {
      int i, spawnTimeout_ms;

      //start by emptying the queue; it should never be full in this context
      _timerQ.Clear();

      //init five missiles as initial wave in the first few seconds, with no spawn timeout
      for (i = 0; i < 5; i++)
      {
        spawnTimeout_ms = RandomNumberGenerator.Instance.Rand() % 1500;
        EventPacket missileEvent = _eventFactory.MakeRandomSpawnMissileEventPacket(_gameModel.GetGameObjectList());
        TimedEvent timedMissile = new TimedEvent(spawnTimeout_ms, missileEvent);
        _timerQ.Insert(timedMissile);
      }

      //make 20 missiles, injected at random intervals, with a min separation of some sort
      for (i = 0; i < level.NumMissiles; i++)
      {
        spawnTimeout_ms = RandomNumberGenerator.Instance.Rand() % GameParameters.LEVEL_DURATION_MS;
        EventPacket missileEvent = _eventFactory.MakeRandomSpawnMissileEventPacket(_gameModel.GetGameObjectList());
        TimedEvent timedMissile = new TimedEvent(spawnTimeout_ms, missileEvent);
        _timerQ.Insert(timedMissile);
      }

      //the final wave of missiles at the end of the level
      for (i = 0; i < 5; i++)
      {
        spawnTimeout_ms = GameParameters.LEVEL_DURATION_MS + RandomNumberGenerator.Instance.Rand() % 1500;
        EventPacket missileEvent = _eventFactory.MakeRandomSpawnMissileEventPacket(_gameModel.GetGameObjectList());
        TimedEvent timedMissile = new TimedEvent(spawnTimeout_ms, missileEvent);
        _timerQ.Insert(timedMissile);
      }

      //some mirvs at the end
      for (i = 0; i < level.NumMirvs; i++)
      {
        spawnTimeout_ms = GameParameters.LEVEL_DURATION_MS + 1500 + RandomNumberGenerator.Instance.Rand() % 1500;
        EventPacket mirvEvent = _eventFactory.MakeRandomSpawnMirvEventPacket(_gameModel.GetGameObjectList());
        TimedEvent timedMirv = new TimedEvent(spawnTimeout_ms, mirvEvent);
        _timerQ.Insert(timedMirv);
      }

      //spawn the bombers
      for (i = 0; i < level.NumBombers; i++)
      {
        spawnTimeout_ms = RandomNumberGenerator.Instance.Rand() % GameParameters.LEVEL_DURATION_MS;
        EventPacket bomberSpawn = _eventFactory.MakeSpawnBomberEventPacket(new Position(0, GameParameters.BOMBER_ALTITUDE));
        TimedEvent timedBomber = new TimedEvent(spawnTimeout_ms, bomberSpawn);
        _timerQ.Insert(timedBomber);
      }

      //spawn the deathheads
      for (i = 0; i < level.NumDeathheads; i++)
      {
        spawnTimeout_ms = RandomNumberGenerator.Instance.Rand() % GameParameters.LEVEL_DURATION_MS;
        EventPacket deathheadSpawn = _eventFactory.MakeSpawnBomberEventPacket(new Position(0, GameParameters.BOMBER_ALTITUDE));
        TimedEvent timedDeathhead = new TimedEvent(spawnTimeout_ms, deathheadSpawn);
        _timerQ.Insert(timedDeathhead);
      }
    }
Exemplo n.º 43
0
 /// <summary>
 /// Constructor for event with a start and end time.
 /// </summary>
 /// <param name="StartTime"></param>
 /// <param name="EndTime"></param>
 public OneTimeSchedule(DateTime StartTime, DateTime EndTime)
 {
     _Event = new TimedEvent(StartTime, EndTime);
      _Notation = NotationKind.To;
 }
Exemplo n.º 44
0
        public static void LoadFromFile()
        {
            Groups.Clear();
            Rooms.Clear();
            Events.Clear();
            FloorHeats.Clear();
            TowelRads.Clear();
            RoomSensors.Clear();
            FloorSensors.Clear();

            EventGroup group;
            Room room;
            Heater heater;
            Sensor sensor;
            TimedEvent timedEvent;

            XmlTextReader reader = new XmlTextReader("initdata.xml");

            while ((reader.Read()))
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        //Display beginning of element.
                        switch (reader.Name)
                        {
                            case "group":
                                group = new EventGroup(Convert.ToInt32(reader.GetAttribute("id")), reader.GetAttribute("name"));
                                Groups.Add(group);
                                break;
                            case "room":
                                room = new Room(Convert.ToInt32(reader.GetAttribute("id")), reader.GetAttribute("name"), Convert.ToInt32(reader.GetAttribute("group")),
                                    Convert.ToInt32(reader.GetAttribute("tempmin")), Convert.ToInt32(reader.GetAttribute("tempmax")), Convert.ToInt32(reader.GetAttribute("temptarget")));
                                Rooms.Add(room);
                                break;
                            case "floorheat":
                                heater = new Heater(Convert.ToInt32(reader.GetAttribute("id")), Heater.HEATER_TYPE_FLOOR, reader.GetAttribute("name"), Convert.ToInt32(reader.GetAttribute("group")),
                                    Convert.ToInt32(reader.GetAttribute("room")), reader.GetAttribute("relay"), Convert.ToInt32(reader.GetAttribute("tempmax")));
                                FloorHeats.Add(heater);
                                break;
                            case "towelrad":
                                heater = new Heater(Convert.ToInt32(reader.GetAttribute("id")), Heater.HEATER_TYPE_TOWEL, reader.GetAttribute("name"), Convert.ToInt32(reader.GetAttribute("group")),
                                    Convert.ToInt32(reader.GetAttribute("room")), reader.GetAttribute("relay"), Convert.ToInt32(reader.GetAttribute("tempmax")));
                                TowelRads.Add(heater);
                                break;
                            case "timergroup":
                                break;
                            case "roomsensor":
                                sensor = new Sensor(Convert.ToInt32(reader.GetAttribute("id")), Sensor.SENSOR_TYPE_ROOM, reader.GetAttribute("name"), Convert.ToInt32(reader.GetAttribute("room")),
                                    reader.GetAttribute("owid"), "x");
                                RoomSensors.Add(sensor);
                                break;
                            case "floorsensor":
                                sensor = new Sensor(Convert.ToInt32(reader.GetAttribute("id")), Sensor.SENSOR_TYPE_FLOOR, reader.GetAttribute("name"), Convert.ToInt32(reader.GetAttribute("room")),
                                    reader.GetAttribute("owid"), "x");
                                FloorSensors.Add(sensor);
                                break;
                            case "event":
                                timedEvent = new TimedEvent(Convert.ToInt32(reader.GetAttribute("id")), 1, Convert.ToInt32(reader.GetAttribute("subject")),
                                    reader.GetAttribute("timestart"), reader.GetAttribute("timeend"), reader.GetAttribute("comment"));
                                if (timedEvent.Id > highestEventId) highestEventId = timedEvent.Id;
                                Events.Add(timedEvent);
                                break;
                        }
                        break;
                }
            }

            // Add heaters to rooms
            for (int i = 0; i < FloorHeats.Count; i++)
            {
                for (int j = 0; j < Rooms.Count; j++)
                {
                    if (Rooms[j].Id == FloorHeats[i].RoomId)
                    {
                        Rooms[j].Heaters.Add(FloorHeats[i]);
                        break;
                    }
                }
            }
            for (int i = 0; i < TowelRads.Count; i++)
            {
                for (int j = 0; j < Rooms.Count; j++)
                {
                    if (Rooms[j].Id == TowelRads[i].RoomId)
                    {
                        Rooms[j].Heaters.Add(TowelRads[i]);
                        break;
                    }
                }
            }

            // Add sensors to rooms and heaters
            for (int i = 0; i < RoomSensors.Count; i++)
            {
                for (int j = 0; j < Rooms.Count; j++)
                {
                    if (Rooms[j].Id == RoomSensors[i].RoomId)
                    {
                        Rooms[j].Sensors.Add(RoomSensors[i]);
                        for (int k = 0; k < Rooms[j].Heaters.Count; k++)
                        {
                            Rooms[j].Heaters[k].Sensors.Add(RoomSensors[i]);
                        }
                        break;
                    }
                }
            }
            for (int i = 0; i < FloorSensors.Count; i++)
            {
                for (int j = 0; j < Rooms.Count; j++)
                {
                    if (Rooms[j].Id == FloorSensors[i].RoomId)
                    {
                        Rooms[j].Sensors.Add(FloorSensors[i]);
                        for (int k = 0; k < Rooms[j].Heaters.Count; k++)
                        {
                            Rooms[j].Heaters[k].Sensors.Add(FloorSensors[i]);
                        }
                        break;
                    }
                }
            }

            reader.Close();
        }
Exemplo n.º 45
0
        public LLUDPServer(LLUDP udp, IScene scene, IPAddress bindAddress, int port, IConfigSource configSource, IScheduler scheduler)
            : base(bindAddress, port)
        {
            m_udp = udp;
            Scene = scene;
            Scheduler = scheduler;

            IConfig throttleConfig = configSource.Configs["LLUDP"];
            m_throttleRates = new ThrottleRates(LLUDPServer.MTU, throttleConfig);

            m_resendTimer = new TimedEvent(100);
            m_ackTimer = new TimedEvent(500);
            m_pingTimer = new TimedEvent(5000);

            m_httpServer = Scene.Simian.GetAppModule<IHttpServer>();

            IConfig config = configSource.Configs["LLUDP"];
            if (config != null)
            {
                m_asyncPacketHandling = config.GetBoolean("AsyncPacketHandling", true);
                m_recvBufferSize = config.GetInt("SocketReceiveBufferSize", 0);
            }

            m_throttle = new TokenBucket(null, m_throttleRates.SceneTotalLimit, m_throttleRates.SceneTotal);

            PacketEvents = new PacketEventDictionary(Scheduler);

            Scene.OnPresenceRemove += PresenceRemoveHandler;
        }
Exemplo n.º 46
0
    public void SetTimer(TimedFunction function, float delay)
    {
        TimedEvent e = new TimedEvent();
        e.function = function;
        e.delay = delay;
        e.addedTime = Time.time;

        timerList.Add(e);
    }
Exemplo n.º 47
0
 public TimedEventUnitTest(string Name, TimedEvent Event, Func<TimedEvent, IEnumerable<TimedEvent>> TimedEventFunc, IEnumerable<TimedEvent> ExpectedEvents)
 {
     this.Name = Name;
     this.Event = Event;
     this.TimedEventFunc = TimedEventFunc;
     this.ExpectedEvents = ExpectedEvents;
 }
Exemplo n.º 48
0
 public TimedEventDateUnitTest(string Name, TimedEvent Event, Func<TimedEvent, IEnumerable<DateTime>> TimedEventFunc, IEnumerable<DateTime> ExpectedDates)
 {
     this.Name = Name;
     this.Event = Event;
     this.TimedEventFunc = TimedEventFunc;
     this.ExpectedDates = ExpectedDates;
 }
Exemplo n.º 49
0
        public IEnumerable<TimedEvent> GetRange(DateTime RangeStart, DateTime RangeEnd)
        {
            // Determine start of iteration by stepping back _Duration time, then adding 1 minute (smallest increment in cron)
             TimeSpan OneMinute = new TimeSpan(0, 1, 0);
             TimeSpan StepBackTime = _Duration >= OneMinute ? _Duration.Subtract(OneMinute) : TimeSpan.Zero;
             DateTime IterateStart = RangeStart.Ticks >= StepBackTime.Ticks ? RangeStart.Subtract(StepBackTime) : DateTime.MinValue;

             // Strip seconds, ms, and ticks
             IterateStart.AddTicks(-(IterateStart.Ticks % TimeSpan.TicksPerMinute));

             // Start iteration with restricted ranges
             int? MonthStart = IterateStart.Month;
             int? DayStart = IterateStart.Day;
             int? HourStart = IterateStart.Hour;
             int? MinuteStart = IterateStart.Minute;

             for (int Year = IterateStart.Year; Year <= RangeEnd.Year; Year++) {

            var Months = _MonthLookup.PickList
               .Where(x => MonthStart.HasValue ? x >= MonthStart.Value : true);

            foreach (int Month in Months) {
               var DOWCounter = new int[] { 0, 0, 0, 0, 0, 0, 0 };
               var MonthDays = Calendar.GetMonthDays(Year, Month);
               var Days = _DayLookup.PickList
                  .Select(x => x < 0 ? MonthDays + x + 1 : x)
                  .Where(x => (DayStart.HasValue ? x >= DayStart.Value : true) && x <= MonthDays);

               if (MonthStart.HasValue && Month != MonthStart.Value)
                  MonthStart = DayStart = HourStart = MinuteStart = null;

               foreach (int DayIndex in Days) {
                  // Resolve negative Day as index from last day of the month.
                  int Day = DayIndex < 0 ? MonthDays + DayIndex + 1 : DayIndex;

                  if (DayStart.HasValue && Day != DayStart.Value)
                     DayStart = HourStart = MinuteStart = null;

                  // Compute day of week.
                  int DOW = (int)new DateTime(Year, Month, Day).DayOfWeek;

                  // Skip this day if DOW doesn't match
                  if (!_DayOfWeekLookup[DOW]) continue;
                  DOWCounter[DOW]++;
                  if (_DayOfWeekLookup.OccurranceIndex.HasValue) {
                     // Check DOW occurance index.
                     // Handle special case for last occurance (negative range).
                     int occuranceIndex = _DayOfWeekLookup.OccurranceIndex < 0 ?
                        // Compute last occurrance index.
                        ComputeLastDOWOccurance(Year, Month, DOW) + _DayOfWeekLookup.OccurranceIndex.Value + 1 :
                        _DayOfWeekLookup.OccurranceIndex.Value - 1;

                     if (occuranceIndex != DOWCounter[DOW] - 1) continue;
                  }

                  var Hours = _HourLookup.PickList
                     .Where(x => HourStart.HasValue ? x >= HourStart.Value : true);

                  foreach (int Hour in Hours) {
                     if (HourStart.HasValue && Hour != HourStart.Value)
                        HourStart = MinuteStart = null;

                     var Minutes = _MinuteLookup.PickList
                        .Where(x => MinuteStart.HasValue ? x >= MinuteStart.Value : true);

                     foreach (int Minute in Minutes) {
                        DateTime Next = new DateTime(Year, Month, Day, Hour, Minute, 0);
                        if (Next >= RangeEnd) yield break;
                        TimedEvent ReturnEvent = new TimedEvent(Next, _Duration);

                        yield return ReturnEvent;
                     }

                     MinuteStart = null;
                  }

                  HourStart = MinuteStart = null;
               }

               DayStart = HourStart = MinuteStart = null;
            }

            MonthStart = DayStart = HourStart = MinuteStart = null;
             }

             yield break;
        }
Exemplo n.º 50
0
	public int AddEvent(TimedEvent TE) {
        TE.ID = IDGenerator;
        int temp = IDGenerator;
        SyncList.Add(IDGenerator++, TE);
        return temp;
	}
Exemplo n.º 51
0
        public IDisposable CreateTimedEvent(Categories category, string variable, string description, int? value)
        {
            if (!ReportingAnalytics) return Disposable;

            var e = new TimedEvent()
            {
                Category = category.ToString(),
                VariableName = variable,
                Description = description,
                Value = value
            };
            //Timed event does not need startup tracking.
            return e;
        }
Exemplo n.º 52
0
        public void TrackTimedEvent(Categories category, string variable, TimeSpan time, string description = "")
        {
            if (!ReportingAnalytics) return;

            var e = new TimedEvent(time)
            {
                Category = category.ToString(),
                VariableName = variable,
                Description = description
            };
            e.Track();
        }