Exemplo n.º 1
0
        private void getServerTime_ResponseReceived(HttpRequest sender, HttpResponse response)
        {
            Debug.Print("Response received:\n");
            Debug.Print("- response status = " + response.StatusCode);
            Debug.Print("- response content =\n" + response.Text);
            if (response.StatusCode == "200")
            {
                DateTime dt;

                String timestamp = response.Text.Substring(24, 14);
                Debug.Print("timestamp acquired: " + timestamp);
                int yyyy = Int32.Parse(timestamp.Substring(0, 4));
                int MM   = Int32.Parse(timestamp.Substring(4, 2));
                int dd   = Int32.Parse(timestamp.Substring(6, 2));
                int hh   = Int32.Parse(timestamp.Substring(8, 2));
                int mm   = Int32.Parse(timestamp.Substring(10, 2));
                int ss   = Int32.Parse(timestamp.Substring(12, 2));

                dt = new DateTime(yyyy, MM, dd, hh, mm, ss);
                //Utility.SetLocalTime(dt);

                if (dt.Year < 2011)
                {
                    return;
                }

                RealTimeClock.SetDateTime(dt);
            }
        }
Exemplo n.º 2
0
        private static void DevicePoll_Received(List <C4UFX.CANMessage> responses)
        {
            StatusUpdate?.Invoke("Querying names (1/3)...");


            foreach (C4UFX.CANMessage response in responses)
            {
                FndTnd address = CANInterface.IdToFndTnd(response.ID);
                if (address.FromDevice > 0)
                {
                    Node   currentNode = allResponses.First(x => x.NodeId == address.FromNode);
                    byte   fromNode    = CANInterface.IdToFndTnd(response.ID).FromNode;
                    byte   fromDevice  = CANInterface.IdToFndTnd(response.ID).FromDevice;
                    Device newDevice;
                    switch ((Signatures)response.Data[2])
                    {
                    case Signatures.MechanicalSwitch: newDevice = new MechanicalSwitch(fromNode, fromDevice); break;

                    case Signatures.StatusLED: newDevice = new StatusLED(fromNode, fromDevice); break;

                    case Signatures.InfraredInput: newDevice = new InfraredInput(fromNode, fromDevice); break;

                    case Signatures.DimmerOut: newDevice = new DimmerOut(fromNode, fromDevice); break;

                    case Signatures.LatLong: newDevice = new LatLong(fromNode, fromDevice); break;

                    case Signatures.TimerEvent: newDevice = new TimerEvent(fromNode, fromDevice); break;

                    case Signatures.Scene: newDevice = new Scene(fromNode, fromDevice); break;

                    case Signatures.RealTimeClock: newDevice = new RealTimeClock(fromNode, fromDevice); break;

                    default: newDevice = new UnknownDevice(fromNode, fromDevice); break;
                    }

                    currentNode.Devices.Add(newDevice);
                }
            }

            Dictionary <byte, List <byte> > sendList = new Dictionary <byte, List <byte> >();

            foreach (Node node in allResponses)
            {
                if (sendList.Keys.Contains(node.NodeId))
                {
                    break;
                }
                sendList.Add(node.NodeId, new List <byte>());
                for (byte i = 1; i < 127; i++)
                {
                    sendList[node.NodeId].Add(i);
                }
            }

            CANPing poll = new CANPing(Commands.CmdSysEName1, sendList);

            poll.ResponseReceived += Name1Poll_Received;
            PongsReceived?.Invoke(allResponses, false);
        }
Exemplo n.º 3
0
        public static void Init()
        {
            try
            {
                if (RealTimeClock.GetTime().Year < 2012)
                {
                    RealTimeClock.SetTime(new DateTime(2012, 01, 01, 12, 0, 0));
                }
                Utility.SetLocalTime(RealTimeClock.GetTime());

                bool res = InitLcd();
                res |= SetHeap();
                res |= SetBoot();
                if (res)
                {
                    PowerState.RebootDevice(false);
                }

#if USE_LED_PWM
                _ledGreen      = new PWM(PWM.Pin.PWM3);
                _ledGreenValue = 0;
                _ledGreen.Set(false);

                _ledRed      = new PWM(PWM.Pin.PWM2);
                _ledRedValue = 0;
                _ledRed.Set(false);
#else
                _ledGreen = new OutputPort(EMX.Pin.IO49, false);
                _ledRed   = new OutputPort(EMX.Pin.IO50, false);
#endif

                InitNetwork();

                LcdBacklightLevel = AppSettings.Instance.LcdBacklightLevel;

                VsDriver.Init(out _lcdInit, out _lcdSet);//Mp.App.Resources.Plugins.GetBytes(Mp.App.Resources.Plugins.BinaryResources.Flac_v140));
                if (_lcdInit.Invoke(48) != 0)
                {
                    throw new Exception("Could not init LCD backlight");                           //IO48 is for LCD backlight
                }
                if (_lcdSet.Invoke(LcdBacklightLevel) != 0)
                {
                    throw new Exception("Could not set LCD backlight level");
                }

                VsDriver.Volume  = AppSettings.Instance.Audio.Volume;
                VsDriver.Balance = AppSettings.Instance.Audio.Balance;
                VsDriver.Bass    = AppSettings.Instance.Audio.Bass;
                VsDriver.Treble  = AppSettings.Instance.Audio.Treble;

                PowerState.OnRebootEvent += (soft) =>
                {
                    AppSettings.Instance.Save();
                };
            }
            catch (Exception)
            { }
        }
Exemplo n.º 4
0
        public Engine()
        {
            var clock = new RealTimeClock();

            Clocks     = c => clock;
            Loggers    = c => c.LogFile != null ? new FileLogger(clock, c.LogFile) : null;
            Transports = c => TcpTransport.Create(clock, c.Role == Role.Acceptor, c.Host, c.Port);

            BufferSize       = 65536;
            MaxMessageLength = 4096;
            MaxMessageFields = 1024;
        }
Exemplo n.º 5
0
        public static DateTime SafeRtc()
        {
            DateTime dt;

            try
            {
                dt = RealTimeClock.GetDateTime();
            }
            catch (Exception)
            {
                dt = error;
            }

            return(dt);
        }
Exemplo n.º 6
0
        private void Timer_Gas_Tick(GT.Timer timer)
        {
            temp = s.getTemp().BinToCelsius().ToString();
            //DateTime startDate = DateTime.Now;
            DateTime startDate = RealTimeClock.GetDateTime();

            Debug.Print("Sending: " + temp + " - " + startDate.ToString("yyyyMMddHHmmss"));
            lpg = sens.MQGetGasPercentage(sens.MQRead() / sens.R0, gas_type.LPG).ToString();
            Debug.Print("Gpl: " + lpg);
            co = sens.MQGetGasPercentage(sens.MQRead() / sens.R0, gas_type.CO).ToString();
            Debug.Print("CO: " + co);
            smoke = sens.MQGetGasPercentage(sens.MQRead() / sens.R0, gas_type.SMOKE).ToString();
            Debug.Print("Smoke: " + smoke);

            server.pushData(temp, lpg, co, smoke, startDate.ToString("yyyyMMddHHmmss"));
        }
Exemplo n.º 7
0
        public Mbc3(int[] cartridge, CartridgeType type, IBattery battery, int romBanks, int ramBanks)
        {
            _cartridge = cartridge;
            _ram       = new int[0x2000 * Math.Max(ramBanks, 1)];
            for (var i = 0; i < _ram.Length; i++)
            {
                _ram[i] = 0xff;
            }

            _clock   = new RealTimeClock(Clock.SystemClock);
            _battery = battery;

            var clockData = new long[12];

            battery.LoadRamWithClock(_ram, clockData);
            _clock.Deserialize(clockData);
        }
Exemplo n.º 8
0
        public static void SetDateTime(DateTime newTime)
        {
            var buf = new byte[4];

            Utility.InsertValueIntoArray(buf, 0, 4, RtcValidMagic);
            RealTimeClock.SetTime(newTime);     // Update RTC.
            BatteryRAM.Write(0, buf, 0, 4);     // Mark it valid in BatteryRam.
            RtcIsValid = true;                  // Mark it valid in code.
            Utility.SetLocalTime(newTime);      // Don't forget to update the framework clock too!

            var evt = OnRtcUpdate;

            if (evt != null)
            {
                evt(newTime);
            }
        }
Exemplo n.º 9
0
        void wifiC_WifiConnected(object sender, EventArgs e)
        {
            //QUA CI VANNO LE COSE QUANDO E CONNESSO
            Debug.Print("Evento WiFi Connesso Ricevuto");
            #region Check connection
            /*Check connection*/
            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.it");
            //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //if (response.StatusDescription == " OK")
            //{
            //    Debug.Print("Connect on internet");
            //}
            #endregion

            /*Set Data*/
            RealTimeClock.SetDateTime(Utilità.GetNetworkTime());


            /*Start Timer for syncronize time*/
            Utility.SetLocalTime(Utilità.GetNetworkTime());
            GT.Timer syncClock = new GT.Timer(1000 * 60 * 30);
            if (!syncClock.IsRunning)
            {
                syncClock.Tick += sincronizzazione_clock;
                syncClock.Start();
            }

            //solo prova perchè su mio pc non va broadcast!!!!!!!!!!!!!!!!!!!!
            client = new M2QTT_Wrapper("192.168.43.145", sqldb);
            /*Start Timer for send data*/
            GT.Timer t2min = new GT.Timer(2000 * 60);
            if (!t2min.IsRunning)
            {
                t2min.Tick += send_data;
                t2min.Start();
            }

            //FINO A QUA, DA TOGLIERE

            /*Find Broker IP*/
            //brokerIP broker = new brokerIP();
            //broker.IpObteined += b_IpObteined;
            //Thread scanIP = new Thread(broker.startListening);
            //scanIP.Start();
        }
Exemplo n.º 10
0
        public const UInt32 RtcValidMagic = 0x6d605ea1;        // This is set in BatteryRam when the RTC is valid.

        static WallClock()
        {
            // Establish if the RTC is valid or not based on a magic value set in battery RAM.
            var buf = new byte[4];

            BatteryRAM.Read(0, buf, 0, buf.Length);
            var batteryRamClockVal = Utility.ExtractValueFromArray(buf, 0, 4);

            RtcIsValid = batteryRamClockVal == RtcValidMagic;

            if (RtcIsValid)
            {
                Utility.SetLocalTime(RealTimeClock.GetTime());
            }
            else
            {
                Utility.SetLocalTime(new DateTime(2011, 01, 01, 0, 0, 0));      // Fake the start of 2011.
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Try to update both system and RTC time using the NTP protocol
        /// </summary>
        /// <param name="TimeServer">Time server to use, ex: pool.ntp.org</param>
        /// <param name="GmtOffset">GMT offset in minutes, ex: -240</param>
        /// <returns>Returns true if successful</returns>
        public static bool NTPTime(string TimeServer, int GmtOffset = 0)
        {
            Socket s = null;

            try
            {
                EndPoint rep = new IPEndPoint(Dns.GetHostEntry(TimeServer).AddressList[0], 123);
                s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                byte[] ntpData = new byte[48];
                Array.Clear(ntpData, 0, 48);
                ntpData[0] = 0x1B;                                   // Set protocol version
                s.SendTo(ntpData, rep);                              // Send Request
                if (s.Poll(30 * 1000 * 1000, SelectMode.SelectRead)) // Waiting an answer for 30s, if nothing: timeout
                {
                    s.ReceiveFrom(ntpData, ref rep);                 // Receive Time
                    byte  offsetTransmitTime = 40;
                    ulong intpart            = 0;
                    ulong fractpart          = 0;
                    for (int i = 0; i <= 3; i++)
                    {
                        intpart = (intpart << 8) | ntpData[offsetTransmitTime + i];
                    }
                    for (int i = 4; i <= 7; i++)
                    {
                        fractpart = (fractpart << 8) | ntpData[offsetTransmitTime + i];
                    }
                    ulong milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000L);
                    s.Close();
                    DateTime dateTime = new DateTime(1900, 1, 1) + TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
                    Utility.SetLocalTime(dateTime.AddMinutes(GmtOffset));
                    RealTimeClock.SetTime(DateTime.Now);
                    return(true);
                }
                s.Close();
            }
            catch
            {
                try { s.Close(); }
                catch { }
            }
            return(false);
        }
Exemplo n.º 12
0
        static OutputPort RS = new OutputPort(FEZSpider.Socket11.Pin4, false);               //RS de l'écran
        #endregion


        public static void Main()
        {
            InitialisationProgramme();

            #region Affichage d'une phrase qui défile //Désactivé
            //RS.Write(true);
            //AfficheChaine("");
            //while (true)
            //{
            //    FaireDefilerDroite();

            //}
            #endregion

            #region Initialisation Heure
            DT = new DateTime(2016, 11, 29, 15, 48, 0);
            RealTimeClock.SetDateTime(DT);
            DT = RealTimeClock.GetDateTime();
            #endregion
        }
Exemplo n.º 13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="force"></param>
        public void EnsureTime(bool force)
        {
            if (force || DateTime.Now.Year < 2013)
            {
                TimeService.SystemTimeChanged +=
                    (o, e) =>
                {
                    Trace.TraceInformation("SystemTimeChanged");

                    RealTimeClock.SetTime(DateTime.Now);

                    Utility.SetLocalTime(RealTimeClock.GetTime());

                    Trace.TraceInformation("Updated Date: {0}", DateTime.Now);

                    TimeService.Stop();
                };

                TimeService.TimeSyncFailed +=
                    (o, e) =>
                {
                    Trace.TraceInformation("TimeSyncFailed");
                };

                TimeService.Settings =
                    new TimeServiceSettings()
                {
                    AutoDayLightSavings = false,
                    ForceSyncAtWakeUp   = true,
                    RefreshTime         = 60,
                    PrimaryServer       = Dns.GetHostEntry("time.windows.com").AddressList[0].GetAddressBytes(),
                    AlternateServer     = Dns.GetHostEntry("time.nist.gov").AddressList[0].GetAddressBytes(),
                };

                TimeService.SetTimeZoneOffset(this.utcOffset * 60);

                TimeService.Start();
            }
        }
Exemplo n.º 14
0
        // Get current time from server
        private static bool requestTime()
        {
            string url = buildUrlFromSettings(TimeRequest);

            Remote.Result result = Remote.Get(url);

            if (result.Success)
            {
                // Request current time
                DebugOnly.Print("Requesting current time to server...");
                DateTime serverDt = result.Content.ToDateTime();

                DateTime rtcDt = Utils.SafeRtc();

                if (!serverDt.WeakCompare(rtcDt))
                {
                    // Found time mismatch
                    DebugOnly.Print("ERROR: RTC/Server time mismatch! Server: " + serverDt.ToMyString() + ", RTC: " + rtcDt.ToMyString());
                    DebugOnly.Print("Setting RTC...");
                    Log log = new Log(Log.TypeInfo, "RTC/Server time mismatch! Server: " + serverDt.ToMyString() + ", RTC: " + rtcDt.ToMyString());
                    AddLog(log);

                    RealTimeClock.SetDateTime(serverDt);
                }
                else
                {
                    DebugOnly.Print("RTC already synced with server time!");
                }

                // RTC time is now valid
                timeChecked = true;

                return(true);
            }

            return(false);
        }
Exemplo n.º 15
0
 /// <summary>
 ///
 /// </summary>
 public Time()
 {
     Utility.SetLocalTime(RealTimeClock.GetTime());
 }
 public void SetUp()
 {
     _clock = new VirtualClock();
     _rtc   = new RealTimeClock(_clock);
 }
Exemplo n.º 17
0
        public static void Main()
        {
            Initialisation();
            Utility.SetLocalTime(RealTimeClock.GetDateTime());

            firstWrite();
            while (true)
            {
                //Set l'heure du RTC
                //if (!btn1.Read())
                //{
                //    DateTime DT;
                //    DT = new DateTime(2017, 12, 05, 08, 12, 00);
                //    RealTimeClock.SetDateTime(DT);
                //}

                if (!btn1.Read())
                {
                    Rick();
                }

                updateHeureVariable();

                #region moultIf
                if (ssverif != ss)  //Test seconde
                {
                    ssverif = ss;
                    SetCursor(0, 6);
                    rs.Write(true);
                    write(ss);
                    rs.Write(false);

                    if (mmverif != mm)  //Test minute
                    {
                        mmverif = mm;
                        SetCursor(0, 3);
                        rs.Write(true);
                        write(mm + ":");
                        rs.Write(false);

                        if (HHverif != HH)  //Test heure
                        {
                            HHverif = HH;
                            SetCursor(0, 0);
                            rs.Write(true);
                            write(HH + ":");
                            rs.Write(false);

                            if (Dverif != dd)   //Test jour
                            {
                                Dverif = dd;
                                SetCursor(0, 9);
                                rs.Write(true);
                                write(ddd);
                                rs.Write(false);
                                SetCursor(1, 0);
                                rs.Write(true);
                                write(dd + "/");
                                rs.Write(false);

                                if (MMverif != MM)  //Test mois
                                {
                                    MMverif = MM;
                                    SetCursor(1, 3);
                                    rs.Write(true);
                                    write(MM + "/");
                                    rs.Write(false);

                                    if (YYverif != YY)  //Test année
                                    {
                                        YYverif = YY;
                                        SetCursor(1, 6);
                                        rs.Write(true);
                                        write(YY);
                                        rs.Write(false);
                                    } //Fin if année
                                }     //Fin if mois
                            }         //Fin if Jour
                        }             //Fin if heure
                    }                 //Fin if minute
                }                     //Fin if seconde
                #endregion

                SetCursor(1, 13);
                if (alarm)
                {
                    write("ON");
                }
                else
                {
                    write("OFF");
                }

                Thread.Sleep(1000);
            }
        }
Exemplo n.º 18
0
 public RealTimeClockTests()
 {
     clock = new VirtualClock();
     rtc   = new RealTimeClock(clock);
 }
Exemplo n.º 19
0
        private void Timer_Cross_Tick(GT.Timer timer)
        {
            count = 0;
            String[] times;
            String[] init_time;
            String[] end_time;
            Int32    ora_start;
            Int32    minuto_start;
            Int32    ora_fine;
            Int32    minuto_fine;

            times        = Program.time_sett.Split('/');
            init_time    = times[0].Split('-');
            end_time     = times[1].Split('-');
            ora_start    = Int32.Parse(init_time[0]);
            minuto_start = Int32.Parse(init_time[1]);
            ora_fine     = Int32.Parse(end_time[0]);
            minuto_fine  = Int32.Parse(end_time[1]);

            //DateTime startDate = DateTime.Now;
            DateTime startDate   = RealTimeClock.GetDateTime();
            int      ora_vera    = startDate.Hour;
            int      minuto_vero = startDate.Minute;

            if (Int32.Parse(init_time[0]) > Int32.Parse(end_time[0]))
            {
                //Ora tra init_time[0] e 23.59 e tra 00.00 e end_time[0]
                if (((ora_vera > ora_start) && (ora_vera < 23)) || (ora_fine > 0) && (ora_vera < ora_fine))
                {
                    Debug.Print("Movimento Rilevato");
                    server.PutCross(startDate.ToString("yyyyMMddHHmmss"));
                }
                else if (ora_vera == ora_start)
                {
                    if (minuto_vero > minuto_start)
                    {
                        Debug.Print("Movimento Rilevato");
                        server.PutCross(startDate.ToString("yyyyMMddHHmmss"));
                    }
                }

                else if (ora_vera == ora_fine)
                {
                    if (minuto_vero < minuto_fine)
                    {
                        Debug.Print("Movimento Rilevato");
                        server.PutCross(startDate.ToString("yyyyMMddHHmmss"));
                    }
                }
            }
            else
            {
                if (ora_vera > ora_start && ora_vera < ora_fine)
                {
                    Debug.Print("Movimento Rilevato");
                    server.PutCross(startDate.ToString("yyyyMMddHHmmss"));
                }
                else if (ora_vera == ora_start)
                {
                    if (minuto_vero > minuto_start)
                    {
                        Debug.Print("Movimento Rilevato");
                        server.PutCross(startDate.ToString("yyyyMMddHHmmss"));
                    }
                }
                else if (ora_vera == ora_fine)
                {
                    if (minuto_vero < minuto_fine)
                    {
                        Debug.Print("Movimento Rilevato");
                        server.PutCross(startDate.ToString("yyyyMMddHHmmss"));
                    }
                }
            }

            timer_cross.Stop();
        }