Finish serial JSON decoding

This commit is contained in:
JackCarterSmith 2021-06-27 18:23:33 +02:00
parent c398bc2df8
commit b78033ff79
Signed by: JackCarterSmith
GPG Key ID: DB362B740828F843
4 changed files with 328 additions and 277 deletions

View File

@ -1,97 +1,97 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
using System.Drawing; using System.Drawing;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using System.IO; using System.IO;
namespace TinyFPGA_VisualProgrammer namespace TinyFPGA_VisualProgrammer
{ {
public partial class Programmer : Form public partial class Programmer : Form
{ {
SerialController sController = null; SerialController sController = null;
TinyProg TProg = null; TinyProg TProg = null;
public Programmer() public Programmer()
{ {
InitializeComponent(); InitializeComponent();
fileSelectDialog.InitialDirectory = Path.GetDirectoryName(Application.ExecutablePath); fileSelectDialog.InitialDirectory = Path.GetDirectoryName(Application.ExecutablePath);
this.AllowDrop = true; this.AllowDrop = true;
this.DragEnter += new DragEventHandler(Programmer_DragEnter); this.DragEnter += new DragEventHandler(Programmer_DragEnter);
this.DragDrop += new DragEventHandler(Programmer_DragDrop); this.DragDrop += new DragEventHandler(Programmer_DragDrop);
sController = new SerialController(); sController = new SerialController();
TProg = new TinyProg(sController); TProg = new TinyProg(sController);
if (sController.sPortsList != null && sController.sPortsList.Count > 0) if (sController.sPortsList != null && sController.sPortsList.Count > 0)
{ {
foreach (string s in sController.sPortsList) foreach (string s in sController.sPortsList)
serialPortList.Items.Add(s); serialPortList.Items.Add(s);
serialPortList.SelectedIndex = serialPortList.Items.Count - 1; serialPortList.SelectedIndex = serialPortList.Items.Count - 1;
} }
} }
void Programmer_DragEnter(object sender, DragEventArgs e) void Programmer_DragEnter(object sender, DragEventArgs e)
{ {
if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
} }
void Programmer_DragDrop(object sender, DragEventArgs e) void Programmer_DragDrop(object sender, DragEventArgs e)
{ {
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
//if(Path.GetExtension(files.First()) == "hex") //if(Path.GetExtension(files.First()) == "hex")
fileLocationTextBox.Text = files.First(); fileLocationTextBox.Text = files.First();
fileSelectDialog.FileName = files.First(); fileSelectDialog.FileName = files.First();
launchProgramBtn.Enabled = true; launchProgramBtn.Enabled = true;
} }
private void fileExpSelect_Click(object sender, EventArgs e) private void fileExpSelect_Click(object sender, EventArgs e)
{ {
fileSelectDialog.ShowDialog(); fileSelectDialog.ShowDialog();
} }
private void fileSelectDialog_FileOk(object sender, CancelEventArgs e) private void fileSelectDialog_FileOk(object sender, CancelEventArgs e)
{ {
fileLocationTextBox.Text = fileSelectDialog.FileName; fileLocationTextBox.Text = fileSelectDialog.FileName;
launchProgramBtn.Enabled = true; launchProgramBtn.Enabled = true;
} }
private void connectBtn_Click(object sender, EventArgs e) private void connectBtn_Click(object sender, EventArgs e)
{ {
connectBtn.Enabled = false; connectBtn.Enabled = false;
if (sController.GetPortOpened()) if (sController.GetPortOpened())
{ {
sController.ClosePort(); sController.ClosePort();
connectBtn.Text = "Connect"; connectBtn.Text = "Connect";
statusLabel.Text = "--"; statusLabel.Text = "--";
} }
else else
{ {
sController.comPortName = serialPortList.SelectedItem.ToString(); sController.comPortName = serialPortList.SelectedItem.ToString();
sController.OpenPort(); sController.OpenPort();
if (sController.GetPortOpened()) if (sController.GetPortOpened())
TProg.CheckTinyPresence(); TProg.CheckTinyPresence();
if (TProg.TinyFPGAIsConnected) if (TProg.TinyFPGAIsConnected)
statusLabel.Text = TProg.GetBoardData().name + " v" + TProg.GetBoardData().hver + " found."; statusLabel.Text = TProg.GetBoardData().Name + " v" + TProg.GetBoardData().HVer + " found.";
else else
statusLabel.Text = "No TinyFPGA found."; statusLabel.Text = "No TinyFPGA found.";
connectBtn.Text = "Disconnect"; connectBtn.Text = "Disconnect";
} }
connectBtn.Enabled = true; connectBtn.Enabled = true;
} }
private void serialPortList_SelectedIndexChanged(object sender, EventArgs e) private void serialPortList_SelectedIndexChanged(object sender, EventArgs e)
{ {
if (serialPortList.SelectedItem.ToString().Length > 0) if (serialPortList.SelectedItem.ToString().Length > 0)
connectBtn.Enabled = true; connectBtn.Enabled = true;
else else
connectBtn.Enabled = false; connectBtn.Enabled = false;
} }
} }
} }

View File

@ -1,137 +1,147 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.IO.Ports; using System.IO.Ports;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Microsoft.Win32; using Microsoft.Win32;
namespace TinyFPGA_VisualProgrammer namespace TinyFPGA_VisualProgrammer
{ {
public class SerialController public class SerialController
{ {
SerialPort mainSerial = new SerialPort(); SerialPort mainSerial = new SerialPort();
public List<string> sPortsList { get; private set; } public List<string> sPortsList { get; private set; }
public string comPortName { get; set; } public string comPortName { get; set; }
public SerialController() public SerialController()
{ {
mainSerial.BaudRate = 9600; mainSerial.BaudRate = 9600;
mainSerial.ReceivedBytesThreshold = 1; mainSerial.ReceivedBytesThreshold = 1;
mainSerial.ReadBufferSize = 4096; mainSerial.ReadBufferSize = 4096;
mainSerial.WriteBufferSize = 4096; mainSerial.WriteBufferSize = 4096;
mainSerial.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); //mainSerial.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
List<string> usbPorts = ComPortNames("1D50", "6130"); List<string> usbPorts = ComPortNames("1D50", "6130");
if (usbPorts.Count > 0) if (usbPorts.Count > 0)
{ {
sPortsList = new List<string>(); sPortsList = new List<string>();
foreach (string s in SerialPort.GetPortNames()) foreach (string s in SerialPort.GetPortNames())
{ {
if (usbPorts.Contains(s)) if (usbPorts.Contains(s))
sPortsList.Add(s); sPortsList.Add(s);
} }
} }
} }
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) /*
{ private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
SerialPort sp = (SerialPort)sender; {
string indata = sp.ReadExisting(); SerialPort sp = (SerialPort)sender;
Console.WriteLine("Data Received:"); string indata = sp.ReadExisting();
Console.Write(indata); Console.WriteLine("Data Received:");
} Console.Write(indata);
}
public void OpenPort() */
{
mainSerial.PortName = comPortName; public void OpenPort()
mainSerial.ReadTimeout = 1000; {
mainSerial.WriteTimeout = 1000; mainSerial.PortName = comPortName;
try mainSerial.ReadTimeout = 1000;
{ mainSerial.WriteTimeout = 1000;
mainSerial.Open(); try
} {
catch { } mainSerial.Open();
} }
catch { }
public void ClosePort() }
{
try public void ClosePort()
{ {
mainSerial.Close(); try
} {
catch { } mainSerial.Close();
} }
catch { }
public bool GetPortOpened() }
{
return mainSerial.IsOpen; public bool GetPortOpened()
} {
return mainSerial.IsOpen;
public void clearBuffer() { }
mainSerial.DiscardInBuffer();
mainSerial.DiscardOutBuffer(); public void clearBuffer() {
} mainSerial.DiscardInBuffer();
mainSerial.DiscardOutBuffer();
public void SendBytes(byte[] db, int dc) }
{
try public void SendBytes(byte[] db, int dc)
{ {
mainSerial.Write(db, 0, dc); try
} {
catch { } mainSerial.Write(db, 0, dc);
}
//while (mainSerial.BytesToWrite >= 0) { } catch (Exception ex)
//mainSerial.DiscardOutBuffer(); {
} Console.WriteLine("Failed to push new data into serial bus. (" + ex.Message + ")");
}
public byte[] WaitForBytes(int dc)
{ mainSerial.DiscardOutBuffer();
byte[] result = new byte[dc]; }
try public byte[] WaitForBytes(int dc)
{ {
mainSerial.Read(result, 0, dc); byte[] result = new byte[dc];
} int countdown = 0;
catch { }
do
//while (mainSerial.BytesToRead >= 0) { } {
//mainSerial.DiscardOutBuffer(); try
{
return result; countdown += mainSerial.Read(result, countdown, dc - countdown);
} }
catch (Exception ex)
/// <summary> {
/// Compile an array of COM port names associated with given VID and PID Console.WriteLine("Failed to fetch new data from serial bus. (" + ex.Message + ")");
/// </summary> }
/// <param name="VID"></param> }
/// <param name="PID"></param> while (countdown < dc);
/// <returns></returns> mainSerial.DiscardInBuffer();
List<string> ComPortNames(String VID, String PID)
{ return result;
String pattern = String.Format("^VID_{0}.PID_{1}", VID, PID); }
Regex _rx = new Regex(pattern, RegexOptions.IgnoreCase);
List<string> comports = new List<string>(); /// <summary>
RegistryKey rk1 = Registry.LocalMachine; /// Compile an array of COM port names associated with given VID and PID
RegistryKey rk2 = rk1.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum"); /// </summary>
foreach (String s3 in rk2.GetSubKeyNames()) /// <param name="VID"></param>
{ /// <param name="PID"></param>
RegistryKey rk3 = rk2.OpenSubKey(s3); /// <returns></returns>
foreach (String s in rk3.GetSubKeyNames()) List<string> ComPortNames(String VID, String PID)
{ {
if (_rx.Match(s).Success) String pattern = String.Format("^VID_{0}.PID_{1}", VID, PID);
{ Regex _rx = new Regex(pattern, RegexOptions.IgnoreCase);
RegistryKey rk4 = rk3.OpenSubKey(s); List<string> comports = new List<string>();
foreach (String s2 in rk4.GetSubKeyNames()) RegistryKey rk1 = Registry.LocalMachine;
{ RegistryKey rk2 = rk1.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum");
RegistryKey rk5 = rk4.OpenSubKey(s2); foreach (String s3 in rk2.GetSubKeyNames())
RegistryKey rk6 = rk5.OpenSubKey("Device Parameters"); {
comports.Add((string)rk6.GetValue("PortName")); RegistryKey rk3 = rk2.OpenSubKey(s3);
} foreach (String s in rk3.GetSubKeyNames())
} {
} if (_rx.Match(s).Success)
} {
return comports; 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;
}
}
}

View File

@ -1,25 +1,25 @@
 
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16 # Visual Studio Version 16
VisualStudioVersion = 16.0.30907.101 VisualStudioVersion = 16.0.30907.101
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TinyFPGA-VisualProgrammer", "TinyFPGA-VisualProgrammer.csproj", "{6917BC1D-EB8A-4DCD-89AF-BE183A82BA39}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TinyFPGA-VisualProgrammer", "TinyFPGA-VisualProgrammer.csproj", "{6917BC1D-EB8A-4DCD-89AF-BE183A82BA39}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU Release|Any CPU = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6917BC1D-EB8A-4DCD-89AF-BE183A82BA39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {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}.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.ActiveCfg = Release|Any CPU
{6917BC1D-EB8A-4DCD-89AF-BE183A82BA39}.Release|Any CPU.Build.0 = Release|Any CPU {6917BC1D-EB8A-4DCD-89AF-BE183A82BA39}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8FF556F6-777A-4303-BD2F-6C9543C14057} SolutionGuid = {8FF556F6-777A-4303-BD2F-6C9543C14057}
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal

View File

@ -11,25 +11,44 @@ namespace TinyFPGA_VisualProgrammer
{ {
public class JSON_BoardMeta public class JSON_BoardMeta
{ {
public string name { get; set; } [JsonProperty("name")]
public string fpga { get; set; } public string Name { get; set; }
public string hver { get; set; }
public string uuid { 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 class JSON_BootMeta
{ {
public string bootloader { get; set; } [JsonProperty("bootloader")]
public string bver { get; set; } public string BootLoader { get; set; }
public string update { get; set; }
public JSON_AddrMap addrmap { 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 class JSON_AddrMap
{ {
public string bootloader { get; set; } [JsonProperty("bootloader")]
public string userimage { get; set; } public string BootLoader { get; set; }
public string userdata { get; set; }
[JsonProperty("userimage")]
public string UserImage { get; set; }
[JsonProperty("userdata")]
public string UserData { get; set; }
} }
public class TinyProg public class TinyProg
@ -126,7 +145,7 @@ namespace TinyFPGA_VisualProgrammer
/* /*
* Send datas container through serial line * Send datas container through serial line
*/ */
//pPort.clearBuffer(); pPort.clearBuffer();
pPort.SendBytes(cmdSequence, cmdSequence.Length); pPort.SendBytes(cmdSequence, cmdSequence.Length);
if (read_len > 0) if (read_len > 0)
@ -181,13 +200,17 @@ namespace TinyFPGA_VisualProgrammer
public string ReadSecureRegPage(uint page) 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 public class TinyMeta
{ {
TinyProg tProg; readonly TinyProg tProg;
//JSONRoot JSON_root; //JSONRoot JSON_root;
public JSON_BoardMeta BoardMeta { get; private set; } public JSON_BoardMeta BoardMeta { get; private set; }
public JSON_BootMeta BootMeta { get; private set; } public JSON_BootMeta BootMeta { get; private set; }
@ -203,12 +226,30 @@ namespace TinyFPGA_VisualProgrammer
{ {
string rawJSON; string rawJSON;
rawJSON = tProg.ReadSecureRegPage(1).Substring(13, 107); rawJSON = tProg.ReadSecureRegPage(1).Substring(12);
BoardMeta = JsonConvert.DeserializeObject<JSON_BoardMeta>(rawJSON); // Read 1st register, contain boardmeta rawJSON = rawJSON.Remove(rawJSON.Length - 2);
try
{
BoardMeta = JsonConvert.DeserializeObject<JSON_BoardMeta>(rawJSON); // Read 1st register, contain boardmeta
}
catch (JsonReaderException _jex)
{
Console.WriteLine(_jex.Message);
Console.WriteLine(rawJSON);
}
Thread.Sleep(200); Thread.Sleep(200);
rawJSON = tProg.ReadSecureRegPage(2).Substring(12, 209); rawJSON = tProg.ReadSecureRegPage(2).Substring(11);
BootMeta = JsonConvert.DeserializeObject<JSON_BootMeta>(rawJSON); // Read 2nd register, contain bootmeta rawJSON = rawJSON.Remove(rawJSON.Length - 2);
try
{
BootMeta = JsonConvert.DeserializeObject<JSON_BootMeta>(rawJSON); // Read 2nd register, contain bootmeta
}
catch (JsonReaderException _jex)
{
Console.WriteLine(_jex.Message);
Console.WriteLine(rawJSON);
}
Thread.Sleep(200); Thread.Sleep(200);
//tProg.ReadSecureRegPage(3); // Read 3rd register, contain nothing //tProg.ReadSecureRegPage(3); // Read 3rd register, contain nothing
} }