diff --git a/Program.cs b/Program.cs index ea62e2e..ded3263 100644 --- a/Program.cs +++ b/Program.cs @@ -1,7 +1,6 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; +using System.Globalization; +using System.Reflection; using System.Windows.Forms; namespace TinyFPGA_VisualProgrammer diff --git a/Programmer.Designer.cs b/Programmer.Designer.cs index 6fa17f8..765e1da 100644 --- a/Programmer.Designer.cs +++ b/Programmer.Designer.cs @@ -1,4 +1,7 @@  +using System; +using System.ComponentModel; + namespace TinyFPGA_VisualProgrammer { partial class Programmer @@ -33,7 +36,7 @@ namespace TinyFPGA_VisualProgrammer this.serialPortList = new System.Windows.Forms.ComboBox(); this.fileExpSelect = new System.Windows.Forms.Button(); this.launchProgramBtn = new System.Windows.Forms.Button(); - this.button3 = new System.Windows.Forms.Button(); + this.ResetBtn = new System.Windows.Forms.Button(); this.fileLocationTextBox = new System.Windows.Forms.TextBox(); this.programStatusBar = new System.Windows.Forms.ProgressBar(); this.groupBox1 = new System.Windows.Forms.GroupBox(); @@ -44,6 +47,8 @@ namespace TinyFPGA_VisualProgrammer this.bgWorker = new System.ComponentModel.BackgroundWorker(); this.fileSelectDialog = new System.Windows.Forms.OpenFileDialog(); this.connectBtn = new System.Windows.Forms.Button(); + this.label3 = new System.Windows.Forms.Label(); + this.modeList = new System.Windows.Forms.ComboBox(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); @@ -68,12 +73,14 @@ namespace TinyFPGA_VisualProgrammer resources.ApplyResources(this.launchProgramBtn, "launchProgramBtn"); this.launchProgramBtn.Name = "launchProgramBtn"; this.launchProgramBtn.UseVisualStyleBackColor = true; + this.launchProgramBtn.Click += new System.EventHandler(this.launchProgramBtn_Click); // - // button3 + // ResetBtn // - resources.ApplyResources(this.button3, "button3"); - this.button3.Name = "button3"; - this.button3.UseVisualStyleBackColor = true; + resources.ApplyResources(this.ResetBtn, "ResetBtn"); + this.ResetBtn.Name = "ResetBtn"; + this.ResetBtn.UseVisualStyleBackColor = true; + this.ResetBtn.Click += new System.EventHandler(this.ResetBtn_Click); // // fileLocationTextBox // @@ -84,6 +91,7 @@ namespace TinyFPGA_VisualProgrammer // programStatusBar // resources.ApplyResources(this.programStatusBar, "programStatusBar"); + this.programStatusBar.Maximum = 1000; this.programStatusBar.Name = "programStatusBar"; // // groupBox1 @@ -119,11 +127,14 @@ namespace TinyFPGA_VisualProgrammer // bgWorker // this.bgWorker.WorkerReportsProgress = true; + this.bgWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bgWorker_DoWork); + this.bgWorker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.bgWorker_ProgressChanged); + this.bgWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bgWorker_RunWorkerCompleted); // // fileSelectDialog // this.fileSelectDialog.DefaultExt = "hex"; - this.fileSelectDialog.FileName = "bitmap.hex"; + this.fileSelectDialog.FileName = "top_bitmap.bin"; resources.ApplyResources(this.fileSelectDialog, "fileSelectDialog"); this.fileSelectDialog.FileOk += new System.ComponentModel.CancelEventHandler(this.fileSelectDialog_FileOk); // @@ -134,17 +145,35 @@ namespace TinyFPGA_VisualProgrammer this.connectBtn.UseVisualStyleBackColor = true; this.connectBtn.Click += new System.EventHandler(this.connectBtn_Click); // + // label3 + // + resources.ApplyResources(this.label3, "label3"); + this.label3.Name = "label3"; + // + // modeList + // + this.modeList.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + resources.ApplyResources(this.modeList, "modeList"); + this.modeList.FormattingEnabled = true; + this.modeList.Items.AddRange(new object[] { + resources.GetString("modeList.Items"), + resources.GetString("modeList.Items1"), + resources.GetString("modeList.Items2")}); + this.modeList.Name = "modeList"; + // // Programmer // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.Controls.Add(this.modeList); + this.Controls.Add(this.label3); this.Controls.Add(this.connectBtn); this.Controls.Add(this.label2); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.label1); this.Controls.Add(this.fileLocationTextBox); this.Controls.Add(this.serialPortList); - this.Controls.Add(this.button3); + this.Controls.Add(this.ResetBtn); this.Controls.Add(this.fileExpSelect); this.Controls.Add(this.programStatusBar); this.Controls.Add(this.launchProgramBtn); @@ -152,6 +181,7 @@ namespace TinyFPGA_VisualProgrammer this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.MaximizeBox = false; this.Name = "Programmer"; + this.Load += new System.EventHandler(this.Programmer_Load); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); @@ -165,7 +195,7 @@ namespace TinyFPGA_VisualProgrammer private System.Windows.Forms.ComboBox serialPortList; private System.Windows.Forms.Button fileExpSelect; private System.Windows.Forms.Button launchProgramBtn; - private System.Windows.Forms.Button button3; + private System.Windows.Forms.Button ResetBtn; private System.Windows.Forms.TextBox fileLocationTextBox; private System.Windows.Forms.ProgressBar programStatusBar; private System.ComponentModel.BackgroundWorker bgWorker; @@ -176,6 +206,8 @@ namespace TinyFPGA_VisualProgrammer private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button connectBtn; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.ComboBox modeList; } } diff --git a/Programmer.cs b/Programmer.cs index 86f9954..8d35750 100644 --- a/Programmer.cs +++ b/Programmer.cs @@ -8,6 +8,8 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; +using System.Threading; + namespace TinyFPGA_VisualProgrammer { @@ -25,7 +27,7 @@ namespace TinyFPGA_VisualProgrammer this.DragDrop += new DragEventHandler(Programmer_DragDrop); sController = new SerialController(); - TProg = new TinyProg(sController); + TProg = new TinyProg(sController, statusLabel, bgWorker); if (sController.sPortsList != null && sController.sPortsList.Count > 0) { foreach (string s in sController.sPortsList) @@ -43,10 +45,9 @@ namespace TinyFPGA_VisualProgrammer void Programmer_DragDrop(object sender, DragEventArgs e) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); - //if(Path.GetExtension(files.First()) == "hex") fileLocationTextBox.Text = files.First(); fileSelectDialog.FileName = files.First(); - launchProgramBtn.Enabled = true; + RefreshProgramBtnStatus(); } private void fileExpSelect_Click(object sender, EventArgs e) @@ -57,12 +58,13 @@ namespace TinyFPGA_VisualProgrammer private void fileSelectDialog_FileOk(object sender, CancelEventArgs e) { fileLocationTextBox.Text = fileSelectDialog.FileName; - launchProgramBtn.Enabled = true; + RefreshProgramBtnStatus(); } private void connectBtn_Click(object sender, EventArgs e) { connectBtn.Enabled = false; + UseWaitCursor = true; if (sController.GetPortOpened()) { @@ -76,14 +78,24 @@ namespace TinyFPGA_VisualProgrammer sController.OpenPort(); if (sController.GetPortOpened()) TProg.CheckTinyPresence(); + if (TProg.TinyFPGAIsConnected) + { statusLabel.Text = TProg.GetBoardData().Name + " v" + TProg.GetBoardData().HVer + " found."; + ResetBtn.Enabled = true; + } else + { statusLabel.Text = "No TinyFPGA found."; - connectBtn.Text = "Disconnect"; + ResetBtn.Enabled = false; + } + + connectBtn.Text = "Disconnect"; } connectBtn.Enabled = true; + UseWaitCursor = false; + RefreshProgramBtnStatus(); } private void serialPortList_SelectedIndexChanged(object sender, EventArgs e) @@ -93,5 +105,71 @@ namespace TinyFPGA_VisualProgrammer else connectBtn.Enabled = false; } + + private void Programmer_Load(object sender, EventArgs e) + { + modeList.SelectedIndex = 0; + } + + private void ResetBtn_Click(object sender, EventArgs e) + { + if (TProg.TinyFPGAIsConnected) + { + TProg.ResetCmd(); + statusLabel.Text = "Board has been reset."; + connectBtn.PerformClick(); + } + } + + private void RefreshProgramBtnStatus() + { + if (TProg.TinyFPGAIsConnected && (fileLocationTextBox.Text.Length > 0)) + launchProgramBtn.Enabled = true; + else + launchProgramBtn.Enabled = false; + } + + private void launchProgramBtn_Click(object sender, EventArgs e) + { + launchProgramBtn.Enabled = false; + ResetBtn.Enabled = false; + bgWorker.RunWorkerAsync(); + } + + private void bgWorker_DoWork(object sender, DoWorkEventArgs e) + { + byte[] bitstream = null; + + // Read bitstream file - unknown extensions will be considered as binary + using (FileStream fs = new FileStream(fileLocationTextBox.Text, FileMode.Open, FileAccess.Read)) + { + bitstream = new byte[fs.Length]; + fs.Read(bitstream, 0, (int)fs.Length); + } + + if (fileLocationTextBox.Text.EndsWith(".hex")) + { + string hexString = System.Text.Encoding.ASCII.GetString(bitstream); + bitstream = hexString.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) + .Select(i => (byte)Convert.ToInt32(i, 16)) + .ToArray(); + } + + // Do the programming + statusLabel.Invoke((MethodInvoker)(() => statusLabel.Text = bitstream.Length.ToString() + " bytes to program.")); + if (TProg.Program(ref bitstream, ref bgWorker)) + statusLabel.Invoke((MethodInvoker)(() => statusLabel.Text = "SUCCESS!")); + } + + private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) + { + programStatusBar.Value = e.ProgressPercentage; + } + + private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) + { + launchProgramBtn.Enabled = true; + ResetBtn.Enabled = true; + } } } diff --git a/Programmer.resx b/Programmer.resx index 37d9708..d03114f 100644 --- a/Programmer.resx +++ b/Programmer.resx @@ -119,10 +119,10 @@ - 124, 86 + 71, 86 - 78, 21 + 73, 21 @@ -138,7 +138,7 @@ $this - 5 + 7 321, 116 @@ -162,16 +162,16 @@ $this - 7 + 9 False - 71, 187 + 180, 187 - 215, 34 + 158, 34 2 @@ -189,31 +189,34 @@ $this - 9 + 11 - + + False + + 108, 247 - + 137, 21 - + 3 - + Exit Bootloader/Reset - - button3 + + ResetBtn - + System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - + $this - - 6 + + 8 44, 116 @@ -237,10 +240,10 @@ $this - 4 + 6 - 10, 227 + 12, 227 333, 14 @@ -258,7 +261,7 @@ $this - 8 + 10 True @@ -315,7 +318,7 @@ $this - 10 + 12 True @@ -324,13 +327,13 @@ 12, 89 - 106, 13 + 57, 13 8 - TinyFPGA COM port: + Serial port: label1 @@ -342,7 +345,7 @@ $this - 3 + 5 12, 12 @@ -367,7 +370,7 @@ $this - 2 + 4 True @@ -394,7 +397,7 @@ $this - 1 + 3 180, 22 @@ -403,16 +406,16 @@ 17, 23 - FPGA bitmap|*.hex,*.bin,*.jed|Tous les fichiers|*.* + FPGA bitmap|*.bin;*.hex|Tous les fichiers|*.* False - 211, 86 + 21, 187 - 104, 21 + 153, 34 11 @@ -430,6 +433,66 @@ $this + 2 + + + True + + + 177, 89 + + + 37, 13 + + + 12 + + + Mode: + + + label3 + + + System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 1 + + + False + + + user_image + + + user_data + + + bootloader + + + 220, 86 + + + 118, 21 + + + 13 + + + modeList + + + System.Windows.Forms.ComboBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + 0 diff --git a/Properties/Resources.Designer.cs b/Properties/Resources.Designer.cs index f086478..5fe8c6c 100644 --- a/Properties/Resources.Designer.cs +++ b/Properties/Resources.Designer.cs @@ -1,10 +1,10 @@ //------------------------------------------------------------------------------ // -// Ce code a été généré par un outil. -// Version du runtime :4.0.30319.42000 +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 // -// Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si -// le code est régénéré. +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. // //------------------------------------------------------------------------------ @@ -13,13 +13,13 @@ namespace TinyFPGA_VisualProgrammer.Properties { /// - /// Une classe de ressource fortement typée destinée, entre autres, à la consultation des chaînes localisées. + /// A strongly-typed resource class, for looking up localized strings, etc. /// - // Cette classe a été générée automatiquement par la classe StronglyTypedResourceBuilder - // à l'aide d'un outil, tel que ResGen ou Visual Studio. - // Pour ajouter ou supprimer un membre, modifiez votre fichier .ResX, puis réexécutez ResGen - // avec l'option /str ou régénérez votre projet VS. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { @@ -33,7 +33,7 @@ namespace TinyFPGA_VisualProgrammer.Properties { } /// - /// Retourne l'instance ResourceManager mise en cache utilisée par cette classe. + /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { @@ -47,8 +47,8 @@ namespace TinyFPGA_VisualProgrammer.Properties { } /// - /// Remplace la propriété CurrentUICulture du thread actuel pour toutes - /// les recherches de ressources à l'aide de cette classe de ressource fortement typée. + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { @@ -61,7 +61,7 @@ namespace TinyFPGA_VisualProgrammer.Properties { } /// - /// Recherche une ressource localisée de type System.Drawing.Bitmap. + /// Looks up a localized resource of type System.Drawing.Bitmap. /// internal static System.Drawing.Bitmap softBanner { get { @@ -71,7 +71,7 @@ namespace TinyFPGA_VisualProgrammer.Properties { } /// - /// Recherche une ressource localisée de type System.Drawing.Icon semblable à (Icône). + /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// internal static System.Drawing.Icon tinyfpga_icon { get { diff --git a/SerialController.cs b/SerialController.cs index 847221c..cf79003 100644 --- a/SerialController.cs +++ b/SerialController.cs @@ -17,7 +17,7 @@ namespace TinyFPGA_VisualProgrammer public SerialController() { - mainSerial.BaudRate = 9600; + mainSerial.BaudRate = 115200; mainSerial.ReceivedBytesThreshold = 1; mainSerial.ReadBufferSize = 4096; mainSerial.WriteBufferSize = 4096; @@ -86,7 +86,7 @@ namespace TinyFPGA_VisualProgrammer Console.WriteLine("Failed to push new data into serial bus. (" + ex.Message + ")"); } - mainSerial.DiscardOutBuffer(); + //mainSerial.DiscardOutBuffer(); } public byte[] WaitForBytes(int dc) diff --git a/TinyFPGA-VisualProgrammer.csproj b/TinyFPGA-VisualProgrammer.csproj index 24fd587..0f64046 100644 --- a/TinyFPGA-VisualProgrammer.csproj +++ b/TinyFPGA-VisualProgrammer.csproj @@ -27,6 +27,8 @@ false false true + + AnyCPU @@ -35,6 +37,7 @@ false bin\Debug\ DEBUG;TRACE + 8.0 prompt 4 true @@ -46,6 +49,7 @@ bin\Release\ + 8.0 prompt 4 true @@ -60,8 +64,9 @@ true - - packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll + + packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll + True diff --git a/TinyProg.cs b/TinyProg.cs index 449ef9a..b06c0ae 100644 --- a/TinyProg.cs +++ b/TinyProg.cs @@ -1,16 +1,22 @@ -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.IO.Ports; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace TinyFPGA_VisualProgrammer -{ - public class JSON_BoardMeta - { +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.Design; +using System.Data; +using System.IO.Ports; +using System.Linq; +using System.Runtime.InteropServices.ComTypes; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace TinyFPGA_VisualProgrammer +{ + public class JSON_BoardMeta + { [JsonProperty("name")] public string Name { get; set; } @@ -21,11 +27,11 @@ namespace TinyFPGA_VisualProgrammer public string HVer { get; set; } [JsonProperty("uuid")] - public string UUID { get; set; } - } - - public class JSON_BootMeta - { + public string UUID { get; set; } + } + + public class JSON_BootMeta + { [JsonProperty("bootloader")] public string BootLoader { get; set; } @@ -35,12 +41,12 @@ namespace TinyFPGA_VisualProgrammer [JsonProperty("update")] public string Update { get; set; } - [JsonProperty("addrmap")] - public JSON_AddrMap AddrMap { get; set; } - } - - public class JSON_AddrMap - { + [JsonProperty("addrmap")] + public JSON_AddrMap AddrMap { get; set; } + } + + public class JSON_AddrMap + { [JsonProperty("bootloader")] public string BootLoader { get; set; } @@ -48,210 +54,402 @@ namespace TinyFPGA_VisualProgrammer public string UserImage { get; set; } [JsonProperty("userdata")] - public string UserData { get; set; } - } - - public class TinyProg - { - SerialController pPort = null; - byte SecurePage_bitOffset = 0x00; - byte SecurePage_writeCmd = 0x00; - byte SecurePage_readCmd = 0x00; - byte SecurePage_eraseCmd = 0x00; - TinyMeta tinyMeta = null; - - public bool TinyFPGAIsConnected { get; private set; } - - public TinyProg(SerialController p) - { - TinyFPGAIsConnected = false; - if (p != null) - pPort = p; - } - - - public void CheckTinyPresence() - { - WakeCmd(); - byte[] flash_id = RetrieveFlashID(); - if (flash_id.Length >= 3) - { - if (flash_id[0] == 0x9D && flash_id[2] == 0x60) - { - // ISSI - SecurePage_bitOffset = 4; - SecurePage_writeCmd = 0x62; - SecurePage_readCmd = 0x68; - SecurePage_eraseCmd = 0x64; - } - else - { - // Adesto - SecurePage_bitOffset = 0; - SecurePage_writeCmd = 0x42; - SecurePage_readCmd = 0x48; - SecurePage_eraseCmd = 0x44; - } - } - - tinyMeta = new TinyMeta(this); - if (tinyMeta.BoardMeta != null) - TinyFPGAIsConnected = true; - else - TinyFPGAIsConnected = false; - } - - public JSON_BoardMeta GetBoardData() - { - return tinyMeta.BoardMeta; - } - - public JSON_BootMeta GetBootData() - { - return tinyMeta.BootMeta; - } - - byte[] SendCommand(byte opcode, byte[] addr, byte[] datas, uint read_len = 0) - { - if (addr == null) - addr = new byte[] { }; - if (datas == null) - datas = new byte[] { }; - - byte[] _ret = new byte[read_len]; - byte[] cmdSequence = new byte[sizeof(byte) + sizeof(ushort) + sizeof(ushort) + sizeof(byte) + addr.Length + datas.Length]; - int i; - - /* - * Prepare datas container - */ - cmdSequence[0] = 0x01; - - ushort seqSize = (ushort)(1 + addr.Length + datas.Length); - cmdSequence[1] = (byte)(seqSize & 0xFF); // LSB - cmdSequence[2] = (byte)((seqSize >> 8) & 0xFF); - - cmdSequence[3] = (byte)(read_len & 0xFF); // LSB - cmdSequence[4] = (byte)((read_len >> 8) & 0xFF); - - cmdSequence[5] = opcode; - i = 6; - foreach (byte ab in addr) - cmdSequence[i++] = ab; - i = 6 + addr.Length; - foreach (byte d in datas) - cmdSequence[i++] = d; - - /* - * Send datas container through serial line - */ - pPort.clearBuffer(); - pPort.SendBytes(cmdSequence, cmdSequence.Length); - - if (read_len > 0) - _ret = pPort.WaitForBytes((int)read_len); - - return _ret; - } - - public void WakeCmd() - { - SendCommand(0xab, null, null); - } - - byte[] RetrieveFlashID() - { - return SendCommand(0x9f, null, null, 3); - } - - void FlashWriteEnable() - { - SendCommand(0x06, null, null); - } - - void FlashWriteDisable() - { - SendCommand(0x04, null, null); - } - - byte RetrieveStatus() - { - return SendCommand(0x05, null, null, 1)[0]; - } - - void WaitWhileBusy() - { - while ((RetrieveStatus() & 1) == 1) { } - } - - void EraseSecureRegPage(uint page) - { - FlashWriteEnable(); - SendCommand(SecurePage_eraseCmd, BitConverter.GetBytes((page & 0xFFFF) << 8 + SecurePage_bitOffset), null); - WaitWhileBusy(); - } - - void ProgramSecureRegPage(uint page, byte[] data) - { - FlashWriteEnable(); - SendCommand(SecurePage_writeCmd, BitConverter.GetBytes((page & 0xFFFF) << 8 + SecurePage_bitOffset), data); - WaitWhileBusy(); - } - - public string ReadSecureRegPage(uint page) - { - string extractedData; - byte[] cmdResult = SendCommand(SecurePage_readCmd, BitConverter.GetBytes((page & 0xFFFF) << 8 + SecurePage_bitOffset), new byte[] { 0x00 }, 255); - extractedData = Encoding.UTF8.GetString(cmdResult).Trim(); // Need trimming to clear string from dirty bytes from the casting process. - - return extractedData; - } - } - - public class TinyMeta - { - readonly TinyProg tProg; - //JSONRoot JSON_root; - public JSON_BoardMeta BoardMeta { get; private set; } - public JSON_BootMeta BootMeta { get; private set; } - - public TinyMeta(TinyProg tProg) - { - this.tProg = tProg; - tProg.WakeCmd(); - ReadMetadata(); - } - - void ReadMetadata() - { - string rawJSON; - - rawJSON = tProg.ReadSecureRegPage(1).Substring(12); - rawJSON = rawJSON.Remove(rawJSON.Length - 2); + public string UserData { get; set; } + } + + public class TinyProg + { + SerialController pPort = null; + BackgroundWorker bw = null; + Label status = null; + byte SecurePage_bitOffset = 0x00; + byte SecurePage_writeCmd = 0x00; + byte SecurePage_readCmd = 0x00; + byte SecurePage_eraseCmd = 0x00; + TinyMeta tinyMeta = null; + short step_prog = 0; + + public bool TinyFPGAIsConnected { get; private set; } + + public TinyProg(SerialController p, Label sl, BackgroundWorker _bw) + { + TinyFPGAIsConnected = false; + if (p != null) + pPort = p; + if (sl != null) + status = sl; + if (_bw != null) + bw = _bw; + } + + + public void CheckTinyPresence() + { + WakeCmd(); + byte[] flash_id = RetrieveFlashID(); + if (flash_id.Length >= 3) + { + if (flash_id[0] == 0x9D && flash_id[2] == 0x60) + { + // ISSI + SecurePage_bitOffset = 4; + SecurePage_writeCmd = 0x62; + SecurePage_readCmd = 0x68; + SecurePage_eraseCmd = 0x64; + } + else + { + // Adesto + SecurePage_bitOffset = 0; + SecurePage_writeCmd = 0x42; + SecurePage_readCmd = 0x48; + SecurePage_eraseCmd = 0x44; + } + } + + tinyMeta = new TinyMeta(this); + if (tinyMeta.BoardMeta != null) + TinyFPGAIsConnected = true; + else + TinyFPGAIsConnected = false; + } + + public JSON_BoardMeta GetBoardData() + { + return tinyMeta.BoardMeta; + } + + public JSON_BootMeta GetBootData() + { + return tinyMeta.BootMeta; + } + + byte[] SendCommand(byte opcode, byte[] addr, byte[] datas, uint read_len = 0) + { + if (addr == null) + addr = new byte[] { }; + else + addr = addr.Take(3).Reverse().ToArray(); // Drop the unused MSB 8b + + if (datas == null) + datas = new byte[] { }; + + byte[] _ret = new byte[read_len]; + byte[] cmdSequence = new byte[sizeof(byte) + sizeof(ushort) + sizeof(ushort) + sizeof(byte) + addr.Length + datas.Length]; + int i; + + /* + * Prepare datas container + */ + cmdSequence[0] = 0x01; + + ushort seqSize = (ushort)(1 + addr.Length + datas.Length); + cmdSequence[1] = (byte)(seqSize & 0xFF); // LSB - Little-endian + cmdSequence[2] = (byte)((seqSize >> 8) & 0xFF); + + cmdSequence[3] = (byte)(read_len & 0xFF); // LSB - Little-endian + cmdSequence[4] = (byte)((read_len >> 8) & 0xFF); + + cmdSequence[5] = opcode; + i = 6; + foreach (byte ab in addr) + cmdSequence[i++] = ab; // Caution - this write in reverse order (big-endian) + i = 6 + addr.Length; + foreach (byte d in datas) + cmdSequence[i++] = d; // Caution - this write in reverse order (big-endian) + + /* + * Send datas container through serial line + */ + //pPort.clearBuffer(); + pPort.SendBytes(cmdSequence, cmdSequence.Length); + + if (read_len > 0) + _ret = pPort.WaitForBytes((int)read_len); + + return _ret; + } + + public void WakeCmd() + { + SendCommand(0xab, null, null); + } + + public void ResetCmd() + { + pPort.SendBytes(new byte[] { 0x00 }, 1); + } + + byte[] RetrieveFlashID() + { + return SendCommand(0x9f, null, null, 3); + } + + void FlashWriteEnable() + { + SendCommand(0x06, null, null); + } + + void FlashWriteDisable() + { + SendCommand(0x04, null, null); + } + + byte RetrieveStatus() + { + return SendCommand(0x05, null, null, 1)[0]; + } + + void WaitWhileBusy() + { + while ((RetrieveStatus() & 1) == 1) { } + } + + void EraseSecureRegPage(uint page) + { + FlashWriteEnable(); + SendCommand(SecurePage_eraseCmd, BitConverter.GetBytes((page & 0xFFFF) << 8 + SecurePage_bitOffset), null); + WaitWhileBusy(); + } + + void ProgramSecureRegPage(uint page, byte[] data) + { + FlashWriteEnable(); + SendCommand(SecurePage_writeCmd, BitConverter.GetBytes((page & 0xFFFF) << 8 + SecurePage_bitOffset), data); + WaitWhileBusy(); + } + + public string ReadSecureRegPage(uint page) + { + byte[] cmdResult = SendCommand(SecurePage_readCmd, BitConverter.GetBytes((page & 0xFFFF) << 8 + SecurePage_bitOffset), new byte[] { 0x00 }, 255); + return Encoding.ASCII.GetString(cmdResult).Trim(); // Need trimming to clear string from dirty bytes from the casting process. + } + + internal byte[] FlashRead(uint addr, uint length, bool progress = false) + { + byte[] datas = null; + uint initial_length = length; + uint readen_bytes = 0; + string default_status = status.Text; + + while (length > 0) + { + uint readLength = Math.Min(255, length); + if (datas == null) + datas = SendCommand(0x0B, BitConverter.GetBytes(addr + readen_bytes), new byte[] {0x00}, readLength); + else + datas = datas.Concat(SendCommand(0x0B, BitConverter.GetBytes(addr + readen_bytes), new byte[] { 0x00 }, readLength)).ToArray(); + + readen_bytes += readLength; + length -= readLength; + if (step_prog == 3) + { + status.Invoke((MethodInvoker)(() => status.Text = "Verifying " + readen_bytes.ToString() + " of " + initial_length + " bytes...")); + bw.ReportProgress(850 + Convert.ToInt32((float)readen_bytes / initial_length * 150)); + } + } + + return datas; + } + + internal void FlashWrite(uint addr, byte[] datas) + { + uint initial_length = Convert.ToUInt32(datas.Length); + uint written_bytes = 0; + //string default_status = status.Text; + + while (written_bytes < datas.Length) + { + uint Addr256bBoundary = 256 - ((addr + written_bytes) & 0xFF); + uint writeLength = Math.Min(256, Math.Min(Convert.ToUInt32(datas.Length) - written_bytes, Addr256bBoundary)); + + SendCommand(0x06, null, null); // Write enable + SendCommand(0x02, BitConverter.GetBytes(addr + written_bytes), datas.Skip(Convert.ToInt32(written_bytes)).Take(Convert.ToInt32(writeLength)).ToArray()); + WaitWhenBusy(); + + written_bytes += writeLength; + if (step_prog == 2) { + status.Invoke((MethodInvoker)(() => status.Text = "Writing " + written_bytes.ToString() + " of " + initial_length + " bytes...")); + bw.ReportProgress(150 + Convert.ToInt32((float)written_bytes / initial_length * 700)); + } + } + } + + private void WaitWhenBusy() + { + //Thread.Sleep(1); + while ((SendCommand(0x05, null, null, 1)[0] & 1) != 0) + //Thread.Sleep(1); + continue; + } + + private void FlashErase(uint addr, uint length) + { + byte OpCode; + switch (length) + { + default: + case 4 * 1024: + OpCode = 0x20; + break; + case 32 * 1024: + OpCode = 0x52; + break; + case 64 * 1024: + OpCode = 0xD8; + break; + } + + SendCommand(0x06, null, null); // Write enable + SendCommand(OpCode, BitConverter.GetBytes(addr), null); + WaitWhenBusy(); + } + + internal void Erase(uint addr, uint length) + { + //uint initial_length = length; + uint[] validLength = {1, 4 * 1024, 32 * 1024, 64 * 1024}; + uint erase_length = 0; + byte[] start_read_data = null; + byte[] end_read_data = null; + + while (length > 0) + { + erase_length = validLength.Where(p => p <= length && addr % p == 0).Max(); + + if (erase_length == 1) + { + // start_addr end_addr + // v v + // +------------------+------------------+----------------+ + // | keep | erase | keep | + // +------------------+------------------+----------------+ + // <- start_length -> <- erase_length -> <- end_length -> + + uint start_addr = addr & 0xFFF000; + uint start_length = addr & 0xFFF; + erase_length = Math.Min(0x1000 - start_length, length); + uint end_addr = start_addr + start_length + erase_length; + uint end_length = start_addr + 0x1000 - end_addr; + + // Readback data that should be rewritten + if (start_length > 0) + start_read_data = FlashRead(start_addr, start_length); + if (end_length > 0) + end_read_data = FlashRead(end_addr, end_length); + + FlashErase(start_addr, 0x1000); + + // Rewrite data + if (start_length > 0) + FlashWrite(start_addr, start_read_data); + if (end_length > 0) + FlashWrite(end_addr, end_read_data); + } + else + FlashErase(addr, erase_length); + + length -= erase_length; + addr += erase_length; + /*if (step_prog == 1) + { + uint a = Convert.ToUInt32(initial_length - (-initial_length + length)); + status.Invoke((MethodInvoker)(() => status.Text = "Erasing " + a.ToString() + " of " + initial_length + " bytes...")); + bw.ReportProgress(Convert.ToInt32((float)1 / initial_length * 15)); + }*/ + } + } + + internal bool Program(ref byte[] bitstream, ref BackgroundWorker bw) + { + GroupCollection usrimg_addrs = Regex.Match(GetBootData().AddrMap.UserImage, @"^\s*(?0x[A-Fa-f0-9]+)\s*-\s*(?0x[A-Fa-f0-9]+)\s*$").Groups; + uint[] usrimg_boundings = { Convert.ToUInt32(usrimg_addrs["start"].Value, 16), Convert.ToUInt32(usrimg_addrs["end"].Value, 16) }; + + if (bitstream.Length > (usrimg_boundings[1] - usrimg_boundings[0])) + { + status.Invoke((MethodInvoker)(() => status.Text = "Bitstream is too large for the target!")); + return false; + } + + // Erase the flash + step_prog = 1; + status.Invoke((MethodInvoker)(() => status.Text = "Erasing...")); + Erase(usrimg_boundings[0], Convert.ToUInt32(bitstream.Length)); + + // Program the bitstream + step_prog = 2; + FlashWrite(usrimg_boundings[0], bitstream); + //SendCommand(0x04, null, null); // Write disable + + // Check the flash datas + step_prog = 3; + byte[] readback = FlashRead(usrimg_boundings[0], Convert.ToUInt32(bitstream.Length)); + + step_prog = 0; + bw.ReportProgress(1000); + if (bitstream.SequenceEqual(bitstream)) + { + ResetCmd(); + return true; + } + return false; + } + } + + public class TinyMeta + { + readonly TinyProg tProg; + //JSONRoot JSON_root; + public JSON_BoardMeta BoardMeta { get; private set; } + public JSON_BootMeta BootMeta { get; private set; } + + public TinyMeta(TinyProg tProg) + { + this.tProg = tProg; + tProg.WakeCmd(); + ReadMetadata(); + } + + void ReadMetadata() + { + string rawJSON; + + //rawJSON = tProg.ReadSecureRegPage(1).Substring(12); + //rawJSON = rawJSON.Remove(rawJSON.Length - 2); + rawJSON = tProg.ReadSecureRegPage(1); + rawJSON = Regex.Replace(rawJSON, @"\x00", string.Empty); + rawJSON = Regex.Replace(rawJSON, @"{\x22boardmeta\x22:", string.Empty); + rawJSON = Regex.Replace(rawJSON, @"\}(?!.*\})", string.Empty); try { BoardMeta = JsonConvert.DeserializeObject(rawJSON); // Read 1st register, contain boardmeta - } + } catch (JsonReaderException _jex) { Console.WriteLine(_jex.Message); Console.WriteLine(rawJSON); - } - Thread.Sleep(200); - - rawJSON = tProg.ReadSecureRegPage(2).Substring(11); - rawJSON = rawJSON.Remove(rawJSON.Length - 2); + } + Thread.Sleep(200); + + //rawJSON = tProg.ReadSecureRegPage(2).Substring(11); + //rawJSON = rawJSON.Remove(rawJSON.Length - 2); + rawJSON = tProg.ReadSecureRegPage(2); + rawJSON = Regex.Replace(rawJSON, @"\x00", string.Empty); + rawJSON = Regex.Replace(rawJSON, @"{\x22bootmeta\x22:", string.Empty); + rawJSON = Regex.Replace(rawJSON, @"\}(?!.*\})", string.Empty); try { BootMeta = JsonConvert.DeserializeObject(rawJSON); // Read 2nd register, contain bootmeta - } + } catch (JsonReaderException _jex) { Console.WriteLine(_jex.Message); Console.WriteLine(rawJSON); - } - Thread.Sleep(200); - //tProg.ReadSecureRegPage(3); // Read 3rd register, contain nothing - } - } -} + } + Thread.Sleep(200); + //tProg.ReadSecureRegPage(3); // Read 3rd register, contain nothing + + //TODO: Read from internal memory ([17, 18, 19, 20, 21, 22, 23, 24]) + } + } +} diff --git a/packages.config b/packages.config index a9de8b5..e46d5a8 100644 --- a/packages.config +++ b/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file