예제 #1
0
        static void TestWeakRef()
        {
            _ref =
                ExtendedWeakReference.RecoverOrCreate(
                    typeof(TypeUniqueToOurApp), //作为标识的类
                    0,                          //ID标识,这个比较有用
                    ExtendedWeakReference.c_SurvivePowerdown);

            //数据重要次序:OkayToThrowAway->NiceToHave->Important->Critical->System
            _ref.Priority = (Int32)ExtendedWeakReference.PriorityLevel.Important;

            //获取数据
            var numBoots = (NumBoots)_ref.Target;

            if (numBoots == null)
            {
                Debug.Print("the first time!");
                numBoots = new NumBoots(1);
            }
            else
            {
                numBoots = new NumBoots(numBoots.BootCount + 1);
                Debug.Print("This is boot #" + numBoots.BootCount);
            }

            //保存数据
            _ref.Target = numBoots;

            //延时等待保存
            Thread.Sleep(2000);
        }
예제 #2
0
            internal X509Certificate Get(string certName)
            {
                int idx = m_names.IndexOf(certName);

                if (-1 == idx)
                {
                    return(null);
                }

                ExtendedWeakReference ewr = ExtendedWeakReference.Recover(typeof(_CertStore_), (uint)m_values[idx]);

                if (ewr == null)
                {
                    return(null);
                }

                X509Certificate cert = ewr.Target as X509Certificate;

                if (cert.Issuer == null || cert.Issuer.Length == 0)
                {
                    cert.Initialize();
                }

                ewr.PushBackIntoRecoverList();

                return(cert);
            }
예제 #3
0
 private static void LoadLCDSettings()
 {
     // Grab the data
     _lcdEwrSettings          = ExtendedWeakReference.RecoverOrCreate(typeof(LcdEwr), 0, ExtendedWeakReference.c_SurvivePowerdown);
     _lcdEwrSettings.Priority = (Int32)ExtendedWeakReference.PriorityLevel.Critical;
     _lcd = (LCDSettings)_lcdEwrSettings.Target;
 }
예제 #4
0
        /// <summary>
        /// Static constructor so that we can load the certificate map from EWR prior to usage.
        /// </summary>
        static CertificateStore()
        {
            s_ewrCertLookup = ExtendedWeakReference.RecoverOrCreate(typeof(_CertLookup_), (uint)0, ExtendedWeakReference.c_SurvivePowerdown);

            if (s_ewrCertLookup.Target == null)
            {
                s_ewrCertLookup.Priority = (int)ExtendedWeakReference.PriorityLevel.Critical;

                s_personalCertData = new _CertLookup_();

                s_ewrCertLookup.Target = s_personalCertData;
            }
            else
            {
                s_personalCertData = s_ewrCertLookup.Target as _CertLookup_;
            }

            s_ewrCALookup = ExtendedWeakReference.RecoverOrCreate(typeof(_CertLookup_), (uint)1, ExtendedWeakReference.c_SurvivePowerdown);

            if (s_ewrCALookup.Target == null)
            {
                s_ewrCALookup.Priority = (int)ExtendedWeakReference.PriorityLevel.Critical;

                s_CACertData = new _CALookup_();

                s_ewrCALookup.Target = s_CACertData;
            }
            else
            {
                s_CACertData = s_ewrCALookup.Target as _CALookup_;
            }
        }
        /// <summary>
        /// The execution entry point.
        /// </summary>
        public static void Main()
        {
            // We are booting; try to retrieve the boot count.
            s_numBootsExtendedWeakReference =
                ExtendedWeakReference.RecoverOrCreate(
                    typeof(TypeUniqueToOurApp),                // The unique type that identifies the data.
                    0,                                         // The ID of the specific data item.
                    ExtendedWeakReference.c_SurvivePowerdown); // The CLR should try to persist data across a reboot.

            // Indicate how important this data is.  The CLR discards
            // OkayToThrowAway items first, then NiceToHave items, then
            // Important items, then Critical items, and finally System items.
            // In practice, System items are virtually never discarded.
            s_numBootsExtendedWeakReference.Priority =
                (Int32)ExtendedWeakReference.PriorityLevel.Important;

            // Try to get the persisted data, initializing it if it is not
            // available.  The Target property of the extended weak reference
            // must be cast to the actual type of the object.  The Target
            // property is cast to prevent the object from being
            // garbage-collected unexpectedly.
            NumBoots numBoots = (NumBoots)s_numBootsExtendedWeakReference.Target;

            if (numBoots == null)
            {
                // The object could not be found in flash memory, so create the
                // object and initialize it.
                Debug.Print(
                    "The device was booted for the first time, or the boot counter was lost. Initializing the boot counter to 1.");
                numBoots = new NumBoots(1);
            }
            else
            {
                // The object was found in flash memory; increment the boot
                // counter.
                numBoots = new NumBoots(numBoots.BootCount + 1);
                Debug.Print("Successfully read boot counter. This is boot #" +
                            numBoots.BootCount);
            }

            // Set the Target property of the extended weak reference to the
            // boot count object, triggering persistence.
            s_numBootsExtendedWeakReference.Target = numBoots;

            // The CLR needs some time to asynchronously store the data in
            // flash.  In this sample application, we use a two-second Sleep.
            // A real application would simply continue without delay.  This app
            // only needs to sleep because the application is about to end.

            // The system provides no guarantee about when the data will
            // actually be stored in flash memory.  When the data is actually
            // stored depends on the size of the object and the speed of the
            // flash memory.

            System.Threading.Thread.Sleep(2000);
        }
예제 #6
0
        /// <summary>
        /// Save addres mapping to persistent storage
        /// </summary>
        public void Save()
        {
#if MICROFRAMEWORK
            ExtendedWeakReference ewr = ExtendedWeakReference.RecoverOrCreate(typeof(Addresses), 0, ExtendedWeakReference.c_SurvivePowerdown);
            if (ewr != null)
            {
                ewr.Priority = (int)ExtendedWeakReference.PriorityLevel.System;
                ewr.Target   = _addresses;
                ewr.PushBackIntoRecoverList();
            }
#endif
        }
예제 #7
0
        /// <summary>
        /// Load address mapping from persistent storage
        /// </summary>
        public void Load()
        {
#if MICROFRAMEWORK
            ExtendedWeakReference ewr = ExtendedWeakReference.Recover(typeof(Addresses), 0);
            if (ewr != null)
            {
                Addresses addr = ewr.Target as Addresses;
                if (addr != null)
                {
                    _addresses = addr;
                }
            }
#endif
        }
예제 #8
0
        public static object LoadFromFlash(Type dataType, uint id)
        {
            ewr = ExtendedWeakReference.RecoverOrCreate(dataType, id, ExtendedWeakReference.c_SurvivePowerdown | ExtendedWeakReference.c_SurviveBoot);

            // Indicate how important this data is. The CLR discards from first to last:
            // OkayToThrowAway items
            // NiceToHave items
            // Important items
            // Critical items
            // System items.
            // In practice, System items are virtually never discarded.
            ewr.Priority = (Int32)ExtendedWeakReference.PriorityLevel.System;

            return(ewr.Target);
        }
예제 #9
0
            private uint GetNextFreeIndex()
            {
                uint idx = 0;

                if (m_values.Count > 0)
                {
                    idx = (uint)m_values[m_values.Count - 1] + 1;

                    // overflow - collapse indexes
                    if (idx == 0)
                    {
                        for (int i = 0; i < m_values.Count; i++)
                        {
                            // if the current index matches the lookup value then we are already in the correct position
                            if (idx == (uint)m_values[i])
                            {
                                idx++;
                            }
                            else
                            {
                                // collapse cert indexes
                                ExtendedWeakReference ewr = ExtendedWeakReference.Recover(typeof(_CertStore_), (uint)m_values[i]);

                                if (ewr != null)
                                {
                                    X509Certificate cert = ewr.Target as X509Certificate;
                                    ewr.Target = null;

                                    ewr          = new ExtendedWeakReference(cert, typeof(_CertStore_), idx, ExtendedWeakReference.c_SurvivePowerdown);
                                    ewr.Priority = (int)ExtendedWeakReference.PriorityLevel.Critical;
                                    ewr.Target   = cert;
                                    ewr.PushBackIntoRecoverList();

                                    m_values[i] = (uint)idx;

                                    // increment active index count only if we have a valid EWR certificate
                                    idx++;
                                }
                            }
                        }
                    }
                }

                return(idx);
            }
        /// <summary>
        /// Initializes the touch panel.
        /// </summary>
        public static void Initialize()
        {
            touchConnection = new TouchConnection();
            Touch.Initialize(touchConnection);

            TouchCollectorConfiguration.CollectionMode    = CollectionMode.InkAndGesture;
            TouchCollectorConfiguration.CollectionMethod  = CollectionMethod.Native;
            TouchCollectorConfiguration.SamplingFrequency = 50;

            calWeakRef          = ExtendedWeakReference.RecoverOrCreate(typeof(GlideCalibration), 0, ExtendedWeakReference.c_SurvivePowerdown);
            calWeakRef.Priority = (Int32)ExtendedWeakReference.PriorityLevel.Important;
            CalSettings         = (CalibrationSettings)calWeakRef.Target;

            if (CalSettings != null)
            {
                Touch.ActiveTouchPanel.SetCalibration(CalSettings.Points.Length, CalSettings.SX, CalSettings.SY, CalSettings.CX, CalSettings.CY);
                Calibrated = true;
            }
        }
예제 #11
0
        private static bool ValidateEWR(bool NewData)
        {
            bool success = true;

            for (uint i = 1; i < 10; i++)
            {
                ewrs[i] = ExtendedWeakReference.Recover(typeof(TestObj), i);
                if (ewrs[i] == null)
                {
                    success = false;
                    Log.Exception("Unable to recover object #" + i + " after reboot " + runTracker.RebootCount);
                    ewrs[i] = ExtendedWeakReference.RecoverOrCreate(typeof(TestObj), i,
                                                                    ExtendedWeakReference.c_SurviveBoot |
                                                                    ExtendedWeakReference.c_SurvivePowerdown);
                }
                TestObj obj = (TestObj)ewrs[i].Target;
                if (obj == null)
                {
                    success = false;
                    Log.Exception("Recovered object #" + i + " null after reboot " + runTracker.RebootCount);
                }
                if (runTracker.objHashes[i] != obj.GetHashCode())
                {
                    success = false;
                    Log.Exception("Recovered object #" + i + " hash value does not match stored hash value");
                }
                Log.Comment("Verified object #" + i);
                if (NewData)
                {
                    Log.Comment("Creating new object and setting back to ewr");
                    obj                     = new TestObj();
                    ewrs[i].Target          = obj;
                    runTracker.objHashes[i] = obj.GetHashCode();
                }
                else
                {
                    Log.Comment("Pushing object back into list");
                    ewrs[i].PushBackIntoRecoverList();
                }
            }
            return(success);
        }
예제 #12
0
        private void On()
        {
            lock (_hal)
            {
                _hal._powerPort.Write(true);
                Thread.Sleep(200);

                SWReset();
                InitRegisters();
                StartOsc();
                EnableInterrupts();
                Channel    = _channel;
                Power      = _rfPower;
                _rxEnabled = false;

                // CC2420 ext address is a random value. Recover/generate ext address from flash if needed
                {
                    CC2420Address addr = null;
                    // try to recover address
                    ExtendedWeakReference ewr = ExtendedWeakReference.Recover(typeof(CC2420Address), 0);
                    if (addr != null)
                    {
                        // address recovered from flash
                        _hal.ExtendedAddress = addr.extAddress;
                    }
                    else
                    {
                        // save current address in flash
                        ewr = ExtendedWeakReference.RecoverOrCreate(typeof(CC2420Address), 0, ExtendedWeakReference.c_SurvivePowerdown);
                        if (ewr != null)
                        {
                            addr            = new CC2420Address();
                            addr.extAddress = _hal.ExtendedAddress;
                            ewr.Priority    = (int)ExtendedWeakReference.PriorityLevel.System;
                            ewr.Target      = addr;
                            ewr.PushBackIntoRecoverList();
                        }
                    }
                }
            }
        }
예제 #13
0
            internal bool Update(string certName, X509Certificate cert)
            {
                int idx = m_names.IndexOf(certName);

                if (-1 == idx)
                {
                    return(false);
                }

                ExtendedWeakReference ewr = ExtendedWeakReference.Recover(typeof(_CertStore_), (uint)m_values[idx]);

                if (ewr == null)
                {
                    return(false);
                }

                ewr.Target = cert;
                ewr.PushBackIntoRecoverList();

                return(true);
            }
예제 #14
0
            internal bool Remove(string certName)
            {
                int idx = m_names.IndexOf(certName);

                if (idx == -1)
                {
                    return(false);
                }

                ExtendedWeakReference ewr = ExtendedWeakReference.Recover(typeof(_CertStore_), (uint)m_values[idx]);

                if (ewr != null)
                {
                    m_names.RemoveAt(idx);
                    m_values.RemoveAt(idx);

                    ewr.Target = null;
                }

                return(true);
            }
예제 #15
0
        private TetrisApp()
        {
            // Create the object that configures the GPIO pins to buttons.
            GPIOButtonInputProvider inputProvider = new GPIOButtonInputProvider(null);

            // Create ExtendedWeakReference for high score table
            highScoreEWD = ExtendedWeakReference.RecoverOrCreate(
                typeof(TetrisApp),
                0,
                ExtendedWeakReference.c_SurvivePowerdown);
            // Set persistance priority
            highScoreEWD.Priority = (int)ExtendedWeakReference.PriorityLevel.Important;

            // Try to recover previously saved HighScore
            HighScore = (HighScoreTable)highScoreEWD.Target;

            // If nothing was recovered - create new
            if (HighScore == null)
            {
                HighScore = new HighScoreTable();
            }
        }
예제 #16
0
        private void LoadData()
        {
            ConfigEWR          = ExtendedWeakReference.RecoverOrCreate(typeof(Config), 0, ExtendedWeakReference.c_SurviveBoot | ExtendedWeakReference.c_SurvivePowerdown);
            ConfigEWR.Priority = (int)ExtendedWeakReference.PriorityLevel.Critical;

            wifiNetworks.Clear();
            if (EnableWifiSetupNetworks)
            {
                APDetails.AddSetupAPs(wifiNetworks);
            }

            Config config = ConfigEWR.Target as Config;

            if (config == null)
            {
                config          = new Config();
                config.UniqueID = "";
                var random = new Random();
                for (int i = 0; i < 20; i++)
                {
                    config.UniqueID += random.Next(10).ToString();
                }
                ConfigEWR.Target = config;
                Debug.Print("Created new configuration in flash");
            }
            else
            {
                if (config.APDetails != null)
                {
                    for (var i = 0; i < config.APDetails.Length; i++)
                    {
                        wifiNetworks.Insert(i, config.APDetails[i]);
                        Debug.Print("Loaded WiFi config for SSID " + config.APDetails[i].SSID);
                    }
                }
            }
            DeviceUniqueID = config.UniqueID;
            Debug.Print("Device unique ID is " + DeviceUniqueID);
        }
예제 #17
0
            internal bool Add(string certName, X509Certificate cert)
            {
                if (-1 != m_names.IndexOf(certName))
                {
                    return(false);
                }

                m_names.Add(certName);

                uint idx = GetNextFreeIndex();

                m_values.Add(idx);

                ExtendedWeakReference ewr = ExtendedWeakReference.RecoverOrCreate(typeof(_CertStore_), (uint)idx, ExtendedWeakReference.c_SurvivePowerdown);

                ewr.Priority = (int)ExtendedWeakReference.PriorityLevel.Critical;

                ewr.Target = cert;

                ewr.PushBackIntoRecoverList();

                return(true);
            }
예제 #18
0
        public static void Main()
        {
            //try to recover the data or create the weak reference
            bootInfoExtendedWeakReference =
                ExtendedWeakReference.RecoverOrCreate(
                    typeof(MyUniqueSelectorType), //unique type to prevent other code from accessing our data
                    0,                            //id that refers to the data we care about
                    ExtendedWeakReference.c_SurvivePowerdown | ExtendedWeakReference.c_SurviveBoot);

            //set how important the data is
            bootInfoExtendedWeakReference.Priority = (int)ExtendedWeakReference.PriorityLevel.Important;

            //try to get the persisted data
            //if we get the data, then putting it in the field myBootInfo creates a
            //strong reference to it, preventing the GC from collecting it
            MyBootInfo myBootInfo = (MyBootInfo)bootInfoExtendedWeakReference.Target;

            if (myBootInfo == null)
            {
                //the data could not be obtained
                Debug.Print("This is the first time the device booted or the data was lost.");
                myBootInfo = new MyBootInfo(1); //first initialization
            }
            else
            {
                //the data could be obtained, display info
                Debug.Print("Number of boots = " + myBootInfo.BootCount);
                myBootInfo = new MyBootInfo(myBootInfo.BootCount + 1); //increment number of boots
            }

            //setting the Target property causes to write the data to flash memory
            bootInfoExtendedWeakReference.Target = myBootInfo;

            //give the system time to save it to flash
            System.Threading.Thread.Sleep(2000);
        }
예제 #19
0
        public static void Main()
        {
            // This test suite does not use the Test Runner infrastructure as it requires a
            // reboot of the physical device to verify the references have been saved.  It relies
            // on the test harness to time it out if it fails to complete because of issues with
            // EWR persistence.

            // Skip test on Emulator
            if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3)
            {
                StartTestLog("Emulator, skipping...");
                EndTestLog(0, 0, 1);
            }

            else
            {
                ewrs[0] = ExtendedWeakReference.Recover(typeof(TestRunTracker), 0);
                if (ewrs[0] == null)
                {
                    ewrs[0] = ExtendedWeakReference.RecoverOrCreate(
                        typeof(TestRunTracker),
                        0,
                        ExtendedWeakReference.c_SurviveBoot | ExtendedWeakReference.c_SurvivePowerdown);
                    runTracker = new TestRunTracker()
                    {
                        RebootCount = -1, TestState = TestRunTracker.State.Initialize
                    };
                }
                else
                {
                    runTracker = (TestRunTracker)ewrs[0].Target;
                }

                Log.Comment("State: " + runTracker.TestState + ", Reboot Count: " + runTracker.RebootCount);

                switch (runTracker.TestState)
                {
                // Initial state
                case TestRunTracker.State.Initialize:
                    if (runTracker.RebootCount == -1)
                    {
                        StartTestLog("No EWR found, initializing for first run...");
                    }
                    else
                    {
                        StartTestLog("Previous EWR found.  Re-initializing...");
                    }

                    runTracker.TestState   = TestRunTracker.State.HardReboot;
                    runTracker.RebootCount = 0;
                    runTracker.TestState   = TestRunTracker.State.HardReboot;
                    for (uint i = 1; i < 10; i++)
                    {
                        ewrs[i] = ExtendedWeakReference.RecoverOrCreate(typeof(TestObj), i,
                                                                        ExtendedWeakReference.c_SurvivePowerdown |
                                                                        ExtendedWeakReference.c_SurviveBoot);
                        TestObj obj = new TestObj();
                        ewrs[i].Target          = obj;
                        runTracker.objHashes[i] = obj.GetHashCode();
                    }
                    break;

                // HardReboot cases - Reboots 1 - 3
                case TestRunTracker.State.HardReboot:
                    Debug.Print("<TestMethod name=\"HardReboot" + runTracker.RebootCount + "\">");

                    // Validate objects
                    if (ValidateEWR(true))
                    {
                        Debug.Print("    <TestMethodResult Result=\"Pass\">");
                        runTracker.PassCount++;
                    }
                    else
                    {
                        Debug.Print("    <TestMethodResult Result=\"Fail\">");
                        runTracker.FailCount++;
                    }
                    Debug.Print("        <Text><![CDATA[TEST: HardReboot" + runTracker.RebootCount + "]]></Text>" + TimeStamp());
                    Debug.Print("    </TestMethodResult>");
                    Debug.Print("</TestMethod>");

                    // End test
                    if (runTracker.RebootCount >= 3)
                    {
                        runTracker.TestState = TestRunTracker.State.SoftReboot;
                    }

                    break;

                // SoftReboot cases - Reboots 4 - 6
                case TestRunTracker.State.SoftReboot:
                    Debug.Print("<TestMethod name=\"SoftReboot" + runTracker.RebootCount + "\">");

                    // Validate objects
                    if (ValidateEWR(true))
                    {
                        Debug.Print("    <TestMethodResult Result=\"Pass\">");
                        runTracker.PassCount++;
                    }
                    else
                    {
                        Debug.Print("    <TestMethodResult Result=\"Fail\">");
                        runTracker.FailCount++;
                    }
                    Debug.Print("        <Text><![CDATA[TEST: SoftReboot" + runTracker.RebootCount + "]]></Text>" + TimeStamp());
                    Debug.Print("    </TestMethodResult>");
                    Debug.Print("</TestMethod>");

                    // End test
                    if (runTracker.RebootCount >= 6)
                    {
                        runTracker.TestState = TestRunTracker.State.Restore;
                    }
                    break;

                // Restore cases - Reboots 7 - 8
                case TestRunTracker.State.Restore:
                    Debug.Print("<TestMethod name=\"Restore" + runTracker.RebootCount + "\">");
                    if (runTracker.RebootCount == 7)
                    {
                        Log.Comment("Restore and Pushback with Soft Reboot");
                    }
                    else
                    {
                        Log.Comment("Restore and Pushback with Hard Reboot");
                    }

                    // Validate objects
                    if (ValidateEWR(false))
                    {
                        Debug.Print("    <TestMethodResult Result=\"Pass\">");
                        runTracker.PassCount++;
                    }
                    else
                    {
                        Debug.Print("    <TestMethodResult Result=\"Fail\">");
                        runTracker.FailCount++;
                    }
                    Debug.Print("        <Text><![CDATA[TEST: SoftReboot" + runTracker.RebootCount + "]]></Text>" + TimeStamp());
                    Debug.Print("    </TestMethodResult>");
                    Debug.Print("</TestMethod>");

                    if (runTracker.RebootCount > 8)
                    {
                        runTracker.TestState = TestRunTracker.State.Complete;
                    }
                    break;

                // Tests complete
                case TestRunTracker.State.Complete:
                    runTracker.TestState = TestRunTracker.State.Initialize;
                    // Close logs
                    EndTestLog(runTracker.PassCount, runTracker.FailCount, 0);
                    break;
                }
                runTracker.RebootCount++;
                ewrs[0].Target = runTracker;
                // Need to sleep to make sure debug buffer has chance to flush before rebooting
                // This should not be needed for EWR any longer
                System.Threading.Thread.Sleep(15000);

                switch (runTracker.TestState)
                {
                case TestRunTracker.State.HardReboot:
                    PowerState.RebootDevice(false);
                    break;

                case TestRunTracker.State.SoftReboot:
                    PowerState.RebootDevice(true);
                    break;

                case TestRunTracker.State.Restore:
                    if (runTracker.RebootCount == 8)
                    {
                        PowerState.RebootDevice(true);
                    }
                    else
                    {
                        PowerState.RebootDevice(false);
                    }
                    break;
                }
                // fall through to end test suite
            }
        }
예제 #20
0
 private static void LoadCalibrationPoints()
 {
     ewrCalibrationPoints          = ExtendedWeakReference.RecoverOrCreate(typeof(CalibrationPointsID), 0, ExtendedWeakReference.c_SurvivePowerdown | ExtendedWeakReference.c_SurviveBoot);
     ewrCalibrationPoints.Priority = (int)ExtendedWeakReference.PriorityLevel.System;
     calibrationPoints             = (CalibrationPoints)ewrCalibrationPoints.Target;
 }
예제 #21
0
 public static TouchCalibrationPoints Load()
 {
     _ewr          = ExtendedWeakReference.RecoverOrCreate(typeof(TouchCalibrationPoints), 0, ExtendedWeakReference.c_SurvivePowerdown);
     _ewr.Priority = (int)ExtendedWeakReference.PriorityLevel.Important;
     return(_ewr.Target == null ? null : new TouchCalibrationPoints((TouchCalibrationData)_ewr.Target));
 }