Esempio n. 1
0
        private bool WriteOtp(byte[] data)
        {
            var       devices = DfuContext.Current.GetDevices();
            DfuDevice device  = devices[0];

            device.Upload(data, 0x1FFF7800, 2);
            return(true);
        }
Esempio n. 2
0
        byte[] ReadOtp()
        {
            var       devices = DfuContext.Current.GetDevices();
            DfuDevice device  = devices[0];

            var configuration = new byte[32];

            device.Download(configuration, 0x1FFF7800, 2);
            return(configuration);
        }
Esempio n. 3
0
        private static void Upload(DfuDevice device, string path, int address)
        {
            FileInfo fi = new FileInfo(path);

            byte[] bytes = File.ReadAllBytes(path);
            totalBytes = bytes.Length;

            Console.WriteLine($"Uploading {fi.Name}");
            uploadedByteCount = 0;
            device.Upload(bytes, (int)address);
            Console.WriteLine("\rdone                    ");
        }
        public Task EraseAndUploadDevice(int deviceIndex, int productID, string configPath, string flashPath, string bootFile)
        {
            int uploadedByteCount = 0;
            int totalBytes        = 0;


            var devices = DfuContext.Current.GetDevices();

            if (devices.Count == 0)
            {
                throw new Exception("Device not found");
            }

            DfuDevice device = devices[deviceIndex];

            device.ClaimInterface();
            device.SetInterfaceAltSetting(0);
            device.Clear();

            var deviceConfig = Globals.DeviceTypes.SingleOrDefault(x => x.ProductID == productID);

            int sectorCount = 0;

            foreach (var sector in deviceConfig.Sectors)
            {
                device.EraseSector((int)sector);
                eraseProgress = (sectorCount + 1) * 100 / deviceConfig.Sectors.Count();
                Debug.WriteLine(CurrentProgress.ToString());
                RaiseFirmwareUpdateProgress(CurrentProgress.ToString());
                sectorCount++;
            }

            // get bytes for progress

            using (System.IO.StreamReader streamReader = new System.IO.StreamReader(configPath))
            {
                string hexFileString = streamReader.ReadToEnd();
                byte[] hexFileBytes  = SrecHexEncoding.GetBytes(hexFileString, deviceConfig.ConfigBaseAddress);
                totalBytes += hexFileBytes.Length;
            }

            using (System.IO.StreamReader streamReader = new System.IO.StreamReader(flashPath))
            {
                string hexFileString = streamReader.ReadToEnd();
                byte[] hexFileBytes  = SrecHexEncoding.GetBytes(hexFileString, deviceConfig.FlashBaseAddress);
                totalBytes += hexFileBytes.Length;
            }

            // load tinybooter

            using (System.IO.StreamReader streamReader = new System.IO.StreamReader(bootFile))
            {
                string hexFileString = streamReader.ReadToEnd();
                byte[] hexFileBytes  = SrecHexEncoding.GetBytes(hexFileString, bootloaderBaseAddress);
                device.Upload(hexFileBytes, (int)bootloaderBaseAddress);
            }

            device.Uploading += (sender, e) =>
            {
                uploadedByteCount += e.BytesUploaded;
                uploadProgress     = uploadedByteCount * 100 / totalBytes;
                Debug.WriteLine(CurrentProgress.ToString());
                RaiseFirmwareUpdateProgress(CurrentProgress.ToString());
            };

            // load config

            using (System.IO.StreamReader streamReader = new System.IO.StreamReader(configPath))
            {
                string hexFileString = streamReader.ReadToEnd();
                byte[] hexFileBytes  = SrecHexEncoding.GetBytes(hexFileString, deviceConfig.ConfigBaseAddress);
                device.Upload(hexFileBytes, (int)deviceConfig.ConfigBaseAddress);
            }

            // load flash

            using (System.IO.StreamReader streamReader = new System.IO.StreamReader(flashPath))
            {
                string hexFileString = streamReader.ReadToEnd();
                byte[] hexFileBytes  = SrecHexEncoding.GetBytes(hexFileString, deviceConfig.FlashBaseAddress);
                device.Upload(hexFileBytes, (int)deviceConfig.FlashBaseAddress);
            }

            //// step 4: restart board
            device.SetAddress(0x08000001);             // NOTE: for thumb2 instructinos, we added 1 to the "base address".  Otherwise our board will not restart properly.
            RaiseFirmwareUpdateProgress("Update Complete");

            //                                    // leave DFU mode.
            ////device.LeaveDfuMode();
            return(Task.CompletedTask);
        }
        public Task EraseAndUploadDevice(int deviceIndex, byte productID)
        {
            int uploadedByteCount = 0;
            int totalBytes        = 0;

            List <Firmware> firmwares = LoadFirmwareFiles();
            Firmware        firmware  = firmwares.SingleOrDefault(x => x.ProductID == productID);


            var devices = DfuContext.Current.GetDevices();

            if (devices.Count == 0)
            {
                throw new Exception("Device not found");
            }

            DfuDevice device = devices[deviceIndex];

            device.ClaimInterface();
            device.SetInterfaceAltSetting(0);
            device.Clear();

            // TODO: make sure we are in DFU mode; if we are in app mode (runtime) then we need to detach and re-enumerate.

            // get our total sectors and block counts
            List <uint> allSectorBaseAddresses = new List <uint>();

            foreach (Firmware.FirmwareRegion region in firmware.FirmwareRegions)
            {
                allSectorBaseAddresses.AddRange(region.SectorBaseAddresses);
            }

            // erase each sector
            for (int iSector = 0; iSector < allSectorBaseAddresses.Count; iSector++)
            {
                device.EraseSector((int)allSectorBaseAddresses[iSector]);
                eraseProgress = (iSector + 1) * 100 / allSectorBaseAddresses.Count();
                Debug.WriteLine(CurrentProgress.ToString());
                RaiseFirmwareUpdateProgress(CurrentProgress.ToString());
            }

            device.Uploading += (sender, e) =>
            {
                uploadedByteCount += e.BytesUploaded;
                uploadProgress     = uploadedByteCount * 100 / totalBytes;
                Debug.WriteLine(CurrentProgress.ToString());
                RaiseFirmwareUpdateProgress(CurrentProgress.ToString());
            };

            for (int i = 0; i < firmware.FirmwareRegions.Count; i++)
            {
                var region = firmware.FirmwareRegions[i];
                if (region.Filename != null)
                {
                    using (System.IO.StreamReader streamReader = new System.IO.StreamReader(firmware.FolderPath + "/" + region.Filename))
                    {
                        string hexFileString = streamReader.ReadToEnd();
                        byte[] hexFileBytes  = SrecHexEncoding.GetBytes(hexFileString, region.BaseAddress);
                        totalBytes += hexFileBytes.Length;
                    }
                }
            }

            for (int i = 0; i < firmware.FirmwareRegions.Count; i++)
            {
                var region = firmware.FirmwareRegions[i];
                if (region.Filename != null)
                {
                    using (System.IO.StreamReader streamReader = new System.IO.StreamReader(firmware.FolderPath + "/" + region.Filename))
                    {
                        string hexFileString = streamReader.ReadToEnd();
                        byte[] hexFileBytes  = SrecHexEncoding.GetBytes(hexFileString, region.BaseAddress);
                        device.Upload(hexFileBytes, (int)region.BaseAddress);
                    }
                }
            }

            //// step 4: restart board
            device.SetAddress(0x08000001);             // NOTE: for thumb2 instructinos, we added 1 to the "base address".  Otherwise our board will not restart properly.
            RaiseFirmwareUpdateProgress("Update Complete");

            //                                    // leave DFU mode.
            ////device.LeaveDfuMode();
            return(Task.CompletedTask);
        }
Esempio n. 6
0
        // Write the concatonated header and configuration data to the Flash config sector
        private void WriteConfig(string configName, byte[] data, bool staticSize, bool updateConfigSector)
        {
            if (!isInitialized)
            {
                InitializeConfigData();
            }

            // updating the config
            if (cfgHash.ContainsKey(configName))
            {
                ConfigIndexData cid = (ConfigIndexData)cfgHash[configName];

                // If old and new data are different sizes
                if (cid.Size != data.Length)
                {
                    // If data comes from a well defined structure, its size cannot vary
                    //if (staticSize) throw new MFInvalidConfigurationDataException();

                    uint   newNextIndex, oldNextIndex;
                    byte[] temp;
                    int    diff = 0;

                    // Figure out where any following configuration data will start
                    newNextIndex = (uint)(cid.Index + data.Length);
                    while (0 != (newNextIndex % 4))
                    {
                        newNextIndex++;                                // Force a 4 byte boundary
                    }

                    // Figure out where any following configuration data previously started
                    oldNextIndex = (uint)(cid.Index + cid.Size);
                    while (0 != (oldNextIndex % 4))
                    {
                        oldNextIndex++;                                // Force a 4 byte boundary
                    }


                    diff = (int)newNextIndex - (int)oldNextIndex;                             // Find the adjusted difference in size between old and new config data
                    temp = new byte[lastCfgIndex + diff];                                     // Create a new byte array to contain all the configuration data

                    Array.Copy(all_cfg_data, temp, cid.Index);                                // Copy all preceding data to new array
                    Array.Copy(data, 0, temp, cid.Index, data.Length);                        // Copy new configuration to new array
                    if (oldNextIndex < lastCfgIndex)                                          // Copy all following data (if it exists) to new array
                    {
                        Array.Copy(all_cfg_data, oldNextIndex, temp, newNextIndex, (all_cfg_data.Length - oldNextIndex));
                    }

                    // Update the local copy of the configuration list
                    all_cfg_data  = temp;
                    lastCfgIndex += diff;
                }
                else
                {
                    // Copy the new configuration data on top of the old
                    Array.Copy(data, 0, all_cfg_data, cid.Index, data.Length);
                }
            }
            else                    // adding a new configuration to the end of the current list
            {
                uint newLastIndex;

                if (lastCfgIndex == -1)
                {
                    throw new OutOfMemoryException();
                }

                // Find the new size of the whole configuration list
                newLastIndex = (uint)(lastCfgIndex + data.Length);

                while (0 != (newLastIndex % 4))
                {
                    newLastIndex++;                            // Force a 4 byte boundary
                }

                byte[] temp = new byte[lastCfgIndex >= all_cfg_data.Length ? lastCfgIndex + data.Length : all_cfg_data.Length];

                Array.Copy(all_cfg_data, 0, temp, 0, all_cfg_data.Length);
                Array.Copy(data, 0, temp, lastCfgIndex, data.Length);

                // Update the local copy of the configuration list
                all_cfg_data = temp;
                lastCfgIndex = (int)newLastIndex;
            }

            if (!updateConfigSector)
            {
                return;
            }

            // Rewrite entire configuration list to Flash
            var       devices = DfuContext.Current.GetDevices();
            DfuDevice device  = devices[0];

            byte[] clear = new byte[all_cfg_data.Length];

            device.EraseSector(configAddress);
            device.Upload(all_cfg_data, configAddress);

            // Rebuild hash table
            cfgHash.Clear();
            uint hal_config_block_size = 0;

            unsafe
            {
                hal_config_block_size = (uint)sizeof(HAL_CONFIG_BLOCK);
            }
            int index = (int)staticConfig.ConfigurationLength;

            byte[]           headerData = new byte[hal_config_block_size];
            HAL_CONFIG_BLOCK cfg_header;

            while (index < lastCfgIndex)
            {
                // Read in next configuration header
                Array.Copy(all_cfg_data, index, headerData, 0, hal_config_block_size);
                cfg_header = (HAL_CONFIG_BLOCK)UnmarshalData(headerData, typeof(HAL_CONFIG_BLOCK));

                cfgHash[cfg_header.DriverNameString] = new ConfigIndexData(index, (int)(cfg_header.Size + hal_config_block_size));

                // Index of next configuration header must lie on a 4 byte boundary
                index += (int)(cfg_header.Size + hal_config_block_size);
                while (0 != (index % 4))
                {
                    index++;                            // Force a 4 byte boundary
                }
            }
        }
        // Initialize the internal structures.
        public void InitializeConfigData()
        {
            uint hal_config_block_size  = 0;
            uint hal_config_static_size = 0;
            int  index = 0;

            unsafe
            {
                hal_config_block_size  = (uint)sizeof(HAL_CONFIG_BLOCK);
                hal_config_static_size = (uint)sizeof(HAL_CONFIGURATION_SECTOR) - hal_config_block_size;
            }

            // read in the configuration data if the config sector was found
            if ((uint)configAddress != uint.MaxValue)
            {
                int hal_static_cfg_size = 0;
                unsafe
                {
                    hal_static_cfg_size = sizeof(HAL_CONFIGURATION_SECTOR);
                }

                var       devices = DfuContext.Current.GetDevices();
                DfuDevice device  = devices[0];

                m_all_cfg_data = new byte[hal_static_cfg_size];

                device.Download(m_all_cfg_data, configAddress);

                m_StaticConfig = (HAL_CONFIGURATION_SECTOR)UnmarshalData(m_all_cfg_data, typeof(HAL_CONFIGURATION_SECTOR));

                // uninitialized config sector, lets try to fix it
                if (m_StaticConfig.ConfigurationLength == 0xFFFFFFFF)
                {
                    m_StaticConfig.ConfigurationLength = (uint)hal_static_cfg_size;
                    m_StaticConfig.Version.Major       = 3;
                    m_StaticConfig.Version.Minor       = 0;
                    m_StaticConfig.Version.Extra       = 0;
                    m_StaticConfig.Version.TinyBooter  = 4;
                }

                // move to the dynamic configuration section
                index = (int)m_StaticConfig.ConfigurationLength;

                m_lastCfgIndex = index;

                while (true)
                {
                    byte[] data = new byte[hal_config_block_size];

                    // read the next configuration block
                    device.Download(data, configAddress + index);

                    HAL_CONFIG_BLOCK cfg_header = (HAL_CONFIG_BLOCK)UnmarshalData(data, typeof(HAL_CONFIG_BLOCK));

                    // out of memory or last record
                    if (cfg_header.Size > configSize)
                    {
                        // last record or bogus entry
                        m_lastCfgIndex = index;

                        // save the configuration data for later use
                        m_all_cfg_data = new byte[m_lastCfgIndex];

                        int    idx = 0;
                        byte[] tmp = null;

                        while (idx < index)
                        {
                            int size = 512;

                            if ((index - idx) < size)
                            {
                                size = index - idx;
                            }
                            tmp = new byte[size];

                            device.Download(tmp, configAddress + idx);
                            Array.Copy(tmp, 0, m_all_cfg_data, idx, tmp.Length);

                            idx += size;
                        }
                        break;                         // no more configs
                    }

                    // move to the next configuration block
                    if (cfg_header.Size + hal_config_block_size + index > configSize)
                    {
                        // end of config sector
                        break;
                    }

                    m_cfgHash[cfg_header.DriverNameString] = new ConfigIndexData(index, (int)(cfg_header.Size + hal_config_block_size));

                    index += (int)(cfg_header.Size + hal_config_block_size);

                    while (0 != (index % 4))
                    {
                        index++;
                    }
                }
            }
            m_init = true;
        }