Finish JSON parser prototype

Need to better organize serial management, some bytes are truncated
This commit is contained in:
JackCarterSmith 2021-03-06 01:10:30 +01:00
parent dbd0be1188
commit c398bc2df8
Signed by: JackCarterSmith
GPG Key ID: DB362B740828F843
7 changed files with 144 additions and 24 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
bin/ bin/
obj/ obj/
.vs/ .vs/
packages/

View File

@ -8,7 +8,6 @@ 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;
using System.IO.Ports;
namespace TinyFPGA_VisualProgrammer namespace TinyFPGA_VisualProgrammer
{ {
@ -78,7 +77,7 @@ namespace TinyFPGA_VisualProgrammer
if (sController.GetPortOpened()) if (sController.GetPortOpened())
TProg.CheckTinyPresence(); TProg.CheckTinyPresence();
if (TProg.TinyFPGAIsConnected) if (TProg.TinyFPGAIsConnected)
statusLabel.Text = "XXXX 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";

View File

@ -18,6 +18,10 @@ namespace TinyFPGA_VisualProgrammer
public SerialController() public SerialController()
{ {
mainSerial.BaudRate = 9600; mainSerial.BaudRate = 9600;
mainSerial.ReceivedBytesThreshold = 1;
mainSerial.ReadBufferSize = 4096;
mainSerial.WriteBufferSize = 4096;
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)
{ {
@ -30,11 +34,19 @@ namespace TinyFPGA_VisualProgrammer
} }
} }
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() public void OpenPort()
{ {
mainSerial.PortName = comPortName; mainSerial.PortName = comPortName;
mainSerial.ReadTimeout = 2000; mainSerial.ReadTimeout = 1000;
mainSerial.WriteTimeout = 5000; mainSerial.WriteTimeout = 1000;
try try
{ {
mainSerial.Open(); mainSerial.Open();
@ -56,29 +68,36 @@ namespace TinyFPGA_VisualProgrammer
return mainSerial.IsOpen; return mainSerial.IsOpen;
} }
public void clearBuffer() {
mainSerial.DiscardInBuffer();
mainSerial.DiscardOutBuffer();
}
public void SendBytes(byte[] db, int dc) public void SendBytes(byte[] db, int dc)
{ {
mainSerial.WriteTimeout = 5000;
try try
{ {
mainSerial.Write(db, 0, dc); mainSerial.Write(db, 0, dc);
} }
catch { } catch { }
//while (mainSerial.BytesToWrite >= 0) { }
//mainSerial.DiscardOutBuffer();
} }
public byte[] WaitForBytes(int dc) public byte[] WaitForBytes(int dc)
{ {
byte[] result = new byte[dc]; byte[] result = new byte[dc];
mainSerial.ReadTimeout = 2000;
try try
{ {
mainSerial.Read(result, 0, dc); mainSerial.Read(result, 0, dc);
} }
catch { } catch { }
//while (mainSerial.BytesToRead >= 0) { }
//mainSerial.DiscardOutBuffer();
return result; return result;
} }

View File

@ -12,6 +12,21 @@
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic> <Deterministic>true</Deterministic>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
@ -22,15 +37,18 @@
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath> <OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>
</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<ApplicationIcon>Resources\tinyfpga-icon.ico</ApplicationIcon> <ApplicationIcon>Resources\tinyfpga-icon.ico</ApplicationIcon>
@ -38,7 +56,13 @@
<PropertyGroup> <PropertyGroup>
<StartupObject>TinyFPGA_VisualProgrammer.Program</StartupObject> <StartupObject>TinyFPGA_VisualProgrammer.Program</StartupObject>
</PropertyGroup> </PropertyGroup>
<PropertyGroup>
<NoWin32Manifest>true</NoWin32Manifest>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />
@ -75,6 +99,7 @@
<DependentUpon>Resources.resx</DependentUpon> <DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
</Compile> </Compile>
<None Include="packages.config" />
<None Include="Properties\Settings.settings"> <None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator> <Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput> <LastGenOutput>Settings.Designer.cs</LastGenOutput>
@ -94,5 +119,17 @@
<ItemGroup> <ItemGroup>
<None Include="Resources\tinyfpga-icon.ico" /> <None Include="Resources\tinyfpga-icon.ico" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.7.2">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.7.2 %28x86 et x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project> </Project>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<PublishUrlHistory>publish\</PublishUrlHistory>
<InstallUrlHistory />
<SupportUrlHistory />
<UpdateUrlHistory />
<BootstrapperUrlHistory />
<ErrorReportUrlHistory />
<FallbackCulture>fr-FR</FallbackCulture>
<VerifyUploadedFiles>false</VerifyUploadedFiles>
</PropertyGroup>
</Project>

View File

@ -1,12 +1,37 @@
using System; using Newtonsoft.Json;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO.Ports; using System.IO.Ports;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace TinyFPGA_VisualProgrammer 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; }
}
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; }
}
public class JSON_AddrMap
{
public string bootloader { get; set; }
public string userimage { get; set; }
public string userdata { get; set; }
}
public class TinyProg public class TinyProg
{ {
SerialController pPort = null; SerialController pPort = null;
@ -14,6 +39,7 @@ namespace TinyFPGA_VisualProgrammer
byte SecurePage_writeCmd = 0x00; byte SecurePage_writeCmd = 0x00;
byte SecurePage_readCmd = 0x00; byte SecurePage_readCmd = 0x00;
byte SecurePage_eraseCmd = 0x00; byte SecurePage_eraseCmd = 0x00;
TinyMeta tinyMeta = null;
public bool TinyFPGAIsConnected { get; private set; } public bool TinyFPGAIsConnected { get; private set; }
@ -47,11 +73,23 @@ namespace TinyFPGA_VisualProgrammer
SecurePage_readCmd = 0x48; SecurePage_readCmd = 0x48;
SecurePage_eraseCmd = 0x44; SecurePage_eraseCmd = 0x44;
} }
TinyFPGAIsConnected = true;
} }
//@TODO: Add json security parser 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) byte[] SendCommand(byte opcode, byte[] addr, byte[] datas, uint read_len = 0)
@ -88,12 +126,11 @@ namespace TinyFPGA_VisualProgrammer
/* /*
* Send datas container through serial line * Send datas container through serial line
*/ */
//pPort.clearBuffer();
pPort.SendBytes(cmdSequence, cmdSequence.Length); pPort.SendBytes(cmdSequence, cmdSequence.Length);
if (read_len > 0) if (read_len > 0)
{
_ret = pPort.WaitForBytes((int)read_len); _ret = pPort.WaitForBytes((int)read_len);
}
return _ret; return _ret;
} }
@ -131,39 +168,49 @@ namespace TinyFPGA_VisualProgrammer
void EraseSecureRegPage(uint page) void EraseSecureRegPage(uint page)
{ {
FlashWriteEnable(); FlashWriteEnable();
SendCommand(SecurePage_eraseCmd, BitConverter.GetBytes(page << 8 + SecurePage_bitOffset), null); SendCommand(SecurePage_eraseCmd, BitConverter.GetBytes((page & 0xFFFF) << 8 + SecurePage_bitOffset), null);
WaitWhileBusy(); WaitWhileBusy();
} }
void ProgramSecureRegPage(uint page, byte[] data) void ProgramSecureRegPage(uint page, byte[] data)
{ {
FlashWriteEnable(); FlashWriteEnable();
SendCommand(SecurePage_writeCmd, BitConverter.GetBytes(page << 8 + SecurePage_bitOffset), data); SendCommand(SecurePage_writeCmd, BitConverter.GetBytes((page & 0xFFFF) << 8 + SecurePage_bitOffset), data);
WaitWhileBusy(); WaitWhileBusy();
} }
byte[] ReadSecureRegPage(uint page) public string ReadSecureRegPage(uint page)
{ {
return SendCommand(SecurePage_readCmd, BitConverter.GetBytes(page << 8 + SecurePage_bitOffset), new byte[] { 0x00 }, 255); return Encoding.UTF8.GetString(SendCommand(SecurePage_readCmd, BitConverter.GetBytes((page & 0xFFFF) << 8 + SecurePage_bitOffset), new byte[] { 0x00 }, 255)).Insert(0, "{");
} }
} }
public class TinyMeta public class TinyMeta
{ {
TinyProg tProg; TinyProg tProg;
//JSONRoot root; //JSONRoot JSON_root;
public JSON_BoardMeta BoardMeta { get; private set; }
public JSON_BootMeta BootMeta { get; private set; }
public TinyMeta(TinyProg tProg) public TinyMeta(TinyProg tProg)
{ {
this.tProg = tProg; this.tProg = tProg;
tProg.WakeCmd(); tProg.WakeCmd();
//this.root = ReadMetadata(); ReadMetadata();
} }
void ReadMetadata()
void ParseJSON()
{ {
string rawJSON;
rawJSON = tProg.ReadSecureRegPage(1).Substring(13, 107);
BoardMeta = JsonConvert.DeserializeObject<JSON_BoardMeta>(rawJSON); // Read 1st register, contain boardmeta
Thread.Sleep(200);
rawJSON = tProg.ReadSecureRegPage(2).Substring(12, 209);
BootMeta = JsonConvert.DeserializeObject<JSON_BootMeta>(rawJSON); // Read 2nd register, contain bootmeta
Thread.Sleep(200);
//tProg.ReadSecureRegPage(3); // Read 3rd register, contain nothing
} }
} }
} }

4
packages.config Normal file
View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="12.0.3" targetFramework="net472" />
</packages>