From b78033ff7992903343242c247b8782f27fa1b769 Mon Sep 17 00:00:00 2001 From: JackCarterSmith Date: Sun, 27 Jun 2021 18:23:33 +0200 Subject: [PATCH] Finish serial JSON decoding --- Programmer.cs | 194 +++++++++++------------ SerialController.cs | 284 ++++++++++++++++++---------------- TinyFPGA-VisualProgrammer.sln | 50 +++--- TinyProg.cs | 77 ++++++--- 4 files changed, 328 insertions(+), 277 deletions(-) diff --git a/Programmer.cs b/Programmer.cs index d2c92a5..86f9954 100644 --- a/Programmer.cs +++ b/Programmer.cs @@ -1,97 +1,97 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; -using System.IO; - -namespace TinyFPGA_VisualProgrammer -{ - public partial class Programmer : Form - { - SerialController sController = null; - TinyProg TProg = null; - - public Programmer() - { - InitializeComponent(); - fileSelectDialog.InitialDirectory = Path.GetDirectoryName(Application.ExecutablePath); - this.AllowDrop = true; - this.DragEnter += new DragEventHandler(Programmer_DragEnter); - this.DragDrop += new DragEventHandler(Programmer_DragDrop); - - sController = new SerialController(); - TProg = new TinyProg(sController); - if (sController.sPortsList != null && sController.sPortsList.Count > 0) - { - foreach (string s in sController.sPortsList) - serialPortList.Items.Add(s); - - serialPortList.SelectedIndex = serialPortList.Items.Count - 1; - } - } - - void Programmer_DragEnter(object sender, DragEventArgs e) - { - if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; - } - - 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; - } - - private void fileExpSelect_Click(object sender, EventArgs e) - { - fileSelectDialog.ShowDialog(); - } - - private void fileSelectDialog_FileOk(object sender, CancelEventArgs e) - { - fileLocationTextBox.Text = fileSelectDialog.FileName; - launchProgramBtn.Enabled = true; - } - - private void connectBtn_Click(object sender, EventArgs e) - { - connectBtn.Enabled = false; - - if (sController.GetPortOpened()) - { - sController.ClosePort(); - connectBtn.Text = "Connect"; - statusLabel.Text = "--"; - } - else - { - sController.comPortName = serialPortList.SelectedItem.ToString(); - sController.OpenPort(); - if (sController.GetPortOpened()) - TProg.CheckTinyPresence(); - if (TProg.TinyFPGAIsConnected) - statusLabel.Text = TProg.GetBoardData().name + " v" + TProg.GetBoardData().hver + " found."; - else - statusLabel.Text = "No TinyFPGA found."; - connectBtn.Text = "Disconnect"; - } - - connectBtn.Enabled = true; - } - - private void serialPortList_SelectedIndexChanged(object sender, EventArgs e) - { - if (serialPortList.SelectedItem.ToString().Length > 0) - connectBtn.Enabled = true; - else - connectBtn.Enabled = false; - } - } -} +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using System.IO; + +namespace TinyFPGA_VisualProgrammer +{ + public partial class Programmer : Form + { + SerialController sController = null; + TinyProg TProg = null; + + public Programmer() + { + InitializeComponent(); + fileSelectDialog.InitialDirectory = Path.GetDirectoryName(Application.ExecutablePath); + this.AllowDrop = true; + this.DragEnter += new DragEventHandler(Programmer_DragEnter); + this.DragDrop += new DragEventHandler(Programmer_DragDrop); + + sController = new SerialController(); + TProg = new TinyProg(sController); + if (sController.sPortsList != null && sController.sPortsList.Count > 0) + { + foreach (string s in sController.sPortsList) + serialPortList.Items.Add(s); + + serialPortList.SelectedIndex = serialPortList.Items.Count - 1; + } + } + + void Programmer_DragEnter(object sender, DragEventArgs e) + { + if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; + } + + 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; + } + + private void fileExpSelect_Click(object sender, EventArgs e) + { + fileSelectDialog.ShowDialog(); + } + + private void fileSelectDialog_FileOk(object sender, CancelEventArgs e) + { + fileLocationTextBox.Text = fileSelectDialog.FileName; + launchProgramBtn.Enabled = true; + } + + private void connectBtn_Click(object sender, EventArgs e) + { + connectBtn.Enabled = false; + + if (sController.GetPortOpened()) + { + sController.ClosePort(); + connectBtn.Text = "Connect"; + statusLabel.Text = "--"; + } + else + { + sController.comPortName = serialPortList.SelectedItem.ToString(); + sController.OpenPort(); + if (sController.GetPortOpened()) + TProg.CheckTinyPresence(); + if (TProg.TinyFPGAIsConnected) + statusLabel.Text = TProg.GetBoardData().Name + " v" + TProg.GetBoardData().HVer + " found."; + else + statusLabel.Text = "No TinyFPGA found."; + connectBtn.Text = "Disconnect"; + } + + connectBtn.Enabled = true; + } + + private void serialPortList_SelectedIndexChanged(object sender, EventArgs e) + { + if (serialPortList.SelectedItem.ToString().Length > 0) + connectBtn.Enabled = true; + else + connectBtn.Enabled = false; + } + } +} diff --git a/SerialController.cs b/SerialController.cs index 586d90c..847221c 100644 --- a/SerialController.cs +++ b/SerialController.cs @@ -1,137 +1,147 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.IO.Ports; -using System.Text.RegularExpressions; -using Microsoft.Win32; - -namespace TinyFPGA_VisualProgrammer -{ - public class SerialController - { - SerialPort mainSerial = new SerialPort(); - public List sPortsList { get; private set; } - public string comPortName { get; set; } - - public SerialController() - { - mainSerial.BaudRate = 9600; - mainSerial.ReceivedBytesThreshold = 1; - mainSerial.ReadBufferSize = 4096; - mainSerial.WriteBufferSize = 4096; - mainSerial.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); - List usbPorts = ComPortNames("1D50", "6130"); - if (usbPorts.Count > 0) - { - sPortsList = new List(); - foreach (string s in SerialPort.GetPortNames()) - { - if (usbPorts.Contains(s)) - sPortsList.Add(s); - } - } - } - - private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) - { - SerialPort sp = (SerialPort)sender; - string indata = sp.ReadExisting(); - Console.WriteLine("Data Received:"); - Console.Write(indata); - } - - public void OpenPort() - { - mainSerial.PortName = comPortName; - mainSerial.ReadTimeout = 1000; - mainSerial.WriteTimeout = 1000; - try - { - mainSerial.Open(); - } - catch { } - } - - public void ClosePort() - { - try - { - mainSerial.Close(); - } - catch { } - } - - public bool GetPortOpened() - { - return mainSerial.IsOpen; - } - - public void clearBuffer() { - mainSerial.DiscardInBuffer(); - mainSerial.DiscardOutBuffer(); - } - - public void SendBytes(byte[] db, int dc) - { - try - { - mainSerial.Write(db, 0, dc); - } - catch { } - - //while (mainSerial.BytesToWrite >= 0) { } - //mainSerial.DiscardOutBuffer(); - } - - public byte[] WaitForBytes(int dc) - { - byte[] result = new byte[dc]; - - try - { - mainSerial.Read(result, 0, dc); - } - catch { } - - //while (mainSerial.BytesToRead >= 0) { } - //mainSerial.DiscardOutBuffer(); - - return result; - } - - /// - /// Compile an array of COM port names associated with given VID and PID - /// - /// - /// - /// - List ComPortNames(String VID, String PID) - { - String pattern = String.Format("^VID_{0}.PID_{1}", VID, PID); - Regex _rx = new Regex(pattern, RegexOptions.IgnoreCase); - List comports = new List(); - RegistryKey rk1 = Registry.LocalMachine; - RegistryKey rk2 = rk1.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum"); - foreach (String s3 in rk2.GetSubKeyNames()) - { - RegistryKey rk3 = rk2.OpenSubKey(s3); - foreach (String s in rk3.GetSubKeyNames()) - { - if (_rx.Match(s).Success) - { - RegistryKey rk4 = rk3.OpenSubKey(s); - foreach (String s2 in rk4.GetSubKeyNames()) - { - RegistryKey rk5 = rk4.OpenSubKey(s2); - RegistryKey rk6 = rk5.OpenSubKey("Device Parameters"); - comports.Add((string)rk6.GetValue("PortName")); - } - } - } - } - return comports; - } - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.IO.Ports; +using System.Text.RegularExpressions; +using Microsoft.Win32; + +namespace TinyFPGA_VisualProgrammer +{ + public class SerialController + { + SerialPort mainSerial = new SerialPort(); + public List sPortsList { get; private set; } + public string comPortName { get; set; } + + public SerialController() + { + mainSerial.BaudRate = 9600; + mainSerial.ReceivedBytesThreshold = 1; + mainSerial.ReadBufferSize = 4096; + mainSerial.WriteBufferSize = 4096; + //mainSerial.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); + List usbPorts = ComPortNames("1D50", "6130"); + if (usbPorts.Count > 0) + { + sPortsList = new List(); + foreach (string s in SerialPort.GetPortNames()) + { + if (usbPorts.Contains(s)) + sPortsList.Add(s); + } + } + } + + /* + private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) + { + SerialPort sp = (SerialPort)sender; + string indata = sp.ReadExisting(); + Console.WriteLine("Data Received:"); + Console.Write(indata); + } + */ + + public void OpenPort() + { + mainSerial.PortName = comPortName; + mainSerial.ReadTimeout = 1000; + mainSerial.WriteTimeout = 1000; + try + { + mainSerial.Open(); + } + catch { } + } + + public void ClosePort() + { + try + { + mainSerial.Close(); + } + catch { } + } + + public bool GetPortOpened() + { + return mainSerial.IsOpen; + } + + public void clearBuffer() { + mainSerial.DiscardInBuffer(); + mainSerial.DiscardOutBuffer(); + } + + public void SendBytes(byte[] db, int dc) + { + try + { + mainSerial.Write(db, 0, dc); + } + catch (Exception ex) + { + Console.WriteLine("Failed to push new data into serial bus. (" + ex.Message + ")"); + } + + mainSerial.DiscardOutBuffer(); + } + + public byte[] WaitForBytes(int dc) + { + byte[] result = new byte[dc]; + int countdown = 0; + + do + { + try + { + countdown += mainSerial.Read(result, countdown, dc - countdown); + } + catch (Exception ex) + { + Console.WriteLine("Failed to fetch new data from serial bus. (" + ex.Message + ")"); + } + } + while (countdown < dc); + mainSerial.DiscardInBuffer(); + + return result; + } + + /// + /// Compile an array of COM port names associated with given VID and PID + /// + /// + /// + /// + List ComPortNames(String VID, String PID) + { + String pattern = String.Format("^VID_{0}.PID_{1}", VID, PID); + Regex _rx = new Regex(pattern, RegexOptions.IgnoreCase); + List comports = new List(); + RegistryKey rk1 = Registry.LocalMachine; + RegistryKey rk2 = rk1.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum"); + foreach (String s3 in rk2.GetSubKeyNames()) + { + RegistryKey rk3 = rk2.OpenSubKey(s3); + foreach (String s in rk3.GetSubKeyNames()) + { + if (_rx.Match(s).Success) + { + RegistryKey rk4 = rk3.OpenSubKey(s); + foreach (String s2 in rk4.GetSubKeyNames()) + { + RegistryKey rk5 = rk4.OpenSubKey(s2); + RegistryKey rk6 = rk5.OpenSubKey("Device Parameters"); + comports.Add((string)rk6.GetValue("PortName")); + } + } + } + } + return comports; + } + } +} diff --git a/TinyFPGA-VisualProgrammer.sln b/TinyFPGA-VisualProgrammer.sln index 835eb77..4f28723 100644 --- a/TinyFPGA-VisualProgrammer.sln +++ b/TinyFPGA-VisualProgrammer.sln @@ -1,25 +1,25 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.30907.101 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TinyFPGA-VisualProgrammer", "TinyFPGA-VisualProgrammer.csproj", "{6917BC1D-EB8A-4DCD-89AF-BE183A82BA39}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {6917BC1D-EB8A-4DCD-89AF-BE183A82BA39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6917BC1D-EB8A-4DCD-89AF-BE183A82BA39}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6917BC1D-EB8A-4DCD-89AF-BE183A82BA39}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6917BC1D-EB8A-4DCD-89AF-BE183A82BA39}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {8FF556F6-777A-4303-BD2F-6C9543C14057} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30907.101 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TinyFPGA-VisualProgrammer", "TinyFPGA-VisualProgrammer.csproj", "{6917BC1D-EB8A-4DCD-89AF-BE183A82BA39}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {6917BC1D-EB8A-4DCD-89AF-BE183A82BA39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6917BC1D-EB8A-4DCD-89AF-BE183A82BA39}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6917BC1D-EB8A-4DCD-89AF-BE183A82BA39}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6917BC1D-EB8A-4DCD-89AF-BE183A82BA39}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {8FF556F6-777A-4303-BD2F-6C9543C14057} + EndGlobalSection +EndGlobal diff --git a/TinyProg.cs b/TinyProg.cs index 75d4699..449ef9a 100644 --- a/TinyProg.cs +++ b/TinyProg.cs @@ -11,25 +11,44 @@ namespace TinyFPGA_VisualProgrammer { public class JSON_BoardMeta { - public string name { get; set; } - public string fpga { get; set; } - public string hver { get; set; } - public string uuid { get; set; } + [JsonProperty("name")] + public string Name { get; set; } + + [JsonProperty("fpga")] + public string FPGA { get; set; } + + [JsonProperty("hver")] + public string HVer { get; set; } + + [JsonProperty("uuid")] + public string UUID { get; set; } } public class JSON_BootMeta { - public string bootloader { get; set; } - public string bver { get; set; } - public string update { get; set; } - public JSON_AddrMap addrmap { get; set; } + [JsonProperty("bootloader")] + public string BootLoader { get; set; } + + [JsonProperty("bver")] + public string BVer { get; set; } + + [JsonProperty("update")] + public string Update { get; set; } + + [JsonProperty("addrmap")] + public JSON_AddrMap AddrMap { get; set; } } public class JSON_AddrMap { - public string bootloader { get; set; } - public string userimage { get; set; } - public string userdata { get; set; } + [JsonProperty("bootloader")] + public string BootLoader { get; set; } + + [JsonProperty("userimage")] + public string UserImage { get; set; } + + [JsonProperty("userdata")] + public string UserData { get; set; } } public class TinyProg @@ -126,7 +145,7 @@ namespace TinyFPGA_VisualProgrammer /* * Send datas container through serial line */ - //pPort.clearBuffer(); + pPort.clearBuffer(); pPort.SendBytes(cmdSequence, cmdSequence.Length); if (read_len > 0) @@ -181,13 +200,17 @@ namespace TinyFPGA_VisualProgrammer public string ReadSecureRegPage(uint page) { - return Encoding.UTF8.GetString(SendCommand(SecurePage_readCmd, BitConverter.GetBytes((page & 0xFFFF) << 8 + SecurePage_bitOffset), new byte[] { 0x00 }, 255)).Insert(0, "{"); + 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 { - TinyProg tProg; + readonly TinyProg tProg; //JSONRoot JSON_root; public JSON_BoardMeta BoardMeta { get; private set; } public JSON_BootMeta BootMeta { get; private set; } @@ -203,12 +226,30 @@ namespace TinyFPGA_VisualProgrammer { string rawJSON; - rawJSON = tProg.ReadSecureRegPage(1).Substring(13, 107); - BoardMeta = JsonConvert.DeserializeObject(rawJSON); // Read 1st register, contain boardmeta + rawJSON = tProg.ReadSecureRegPage(1).Substring(12); + rawJSON = rawJSON.Remove(rawJSON.Length - 2); + 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(12, 209); - BootMeta = JsonConvert.DeserializeObject(rawJSON); // Read 2nd register, contain bootmeta + rawJSON = tProg.ReadSecureRegPage(2).Substring(11); + rawJSON = rawJSON.Remove(rawJSON.Length - 2); + 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 }