Compare commits

..

3 Commits

Author SHA1 Message Date
453a99fdb2
Yeah something finish! 2025-04-09 12:25:52 +02:00
b78033ff79
Finish serial JSON decoding 2021-06-27 18:23:33 +02:00
c398bc2df8
Finish JSON parser prototype
Need to better organize serial management, some bytes are truncated
2021-03-06 01:10:30 +01:00
12 changed files with 1013 additions and 467 deletions

3
.gitignore vendored
View File

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

View File

@ -1,7 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Globalization;
using System.Linq; using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
namespace TinyFPGA_VisualProgrammer namespace TinyFPGA_VisualProgrammer

48
Programmer.Designer.cs generated
View File

@ -1,4 +1,7 @@
 
using System;
using System.ComponentModel;
namespace TinyFPGA_VisualProgrammer namespace TinyFPGA_VisualProgrammer
{ {
partial class Programmer partial class Programmer
@ -33,7 +36,7 @@ namespace TinyFPGA_VisualProgrammer
this.serialPortList = new System.Windows.Forms.ComboBox(); this.serialPortList = new System.Windows.Forms.ComboBox();
this.fileExpSelect = new System.Windows.Forms.Button(); this.fileExpSelect = new System.Windows.Forms.Button();
this.launchProgramBtn = 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.fileLocationTextBox = new System.Windows.Forms.TextBox();
this.programStatusBar = new System.Windows.Forms.ProgressBar(); this.programStatusBar = new System.Windows.Forms.ProgressBar();
this.groupBox1 = new System.Windows.Forms.GroupBox(); this.groupBox1 = new System.Windows.Forms.GroupBox();
@ -44,6 +47,8 @@ namespace TinyFPGA_VisualProgrammer
this.bgWorker = new System.ComponentModel.BackgroundWorker(); this.bgWorker = new System.ComponentModel.BackgroundWorker();
this.fileSelectDialog = new System.Windows.Forms.OpenFileDialog(); this.fileSelectDialog = new System.Windows.Forms.OpenFileDialog();
this.connectBtn = new System.Windows.Forms.Button(); this.connectBtn = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.modeList = new System.Windows.Forms.ComboBox();
this.groupBox1.SuspendLayout(); this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout(); this.SuspendLayout();
@ -68,12 +73,14 @@ namespace TinyFPGA_VisualProgrammer
resources.ApplyResources(this.launchProgramBtn, "launchProgramBtn"); resources.ApplyResources(this.launchProgramBtn, "launchProgramBtn");
this.launchProgramBtn.Name = "launchProgramBtn"; this.launchProgramBtn.Name = "launchProgramBtn";
this.launchProgramBtn.UseVisualStyleBackColor = true; this.launchProgramBtn.UseVisualStyleBackColor = true;
this.launchProgramBtn.Click += new System.EventHandler(this.launchProgramBtn_Click);
// //
// button3 // ResetBtn
// //
resources.ApplyResources(this.button3, "button3"); resources.ApplyResources(this.ResetBtn, "ResetBtn");
this.button3.Name = "button3"; this.ResetBtn.Name = "ResetBtn";
this.button3.UseVisualStyleBackColor = true; this.ResetBtn.UseVisualStyleBackColor = true;
this.ResetBtn.Click += new System.EventHandler(this.ResetBtn_Click);
// //
// fileLocationTextBox // fileLocationTextBox
// //
@ -84,6 +91,7 @@ namespace TinyFPGA_VisualProgrammer
// programStatusBar // programStatusBar
// //
resources.ApplyResources(this.programStatusBar, "programStatusBar"); resources.ApplyResources(this.programStatusBar, "programStatusBar");
this.programStatusBar.Maximum = 1000;
this.programStatusBar.Name = "programStatusBar"; this.programStatusBar.Name = "programStatusBar";
// //
// groupBox1 // groupBox1
@ -119,11 +127,14 @@ namespace TinyFPGA_VisualProgrammer
// bgWorker // bgWorker
// //
this.bgWorker.WorkerReportsProgress = true; 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 // fileSelectDialog
// //
this.fileSelectDialog.DefaultExt = "hex"; this.fileSelectDialog.DefaultExt = "hex";
this.fileSelectDialog.FileName = "bitmap.hex"; this.fileSelectDialog.FileName = "top_bitmap.bin";
resources.ApplyResources(this.fileSelectDialog, "fileSelectDialog"); resources.ApplyResources(this.fileSelectDialog, "fileSelectDialog");
this.fileSelectDialog.FileOk += new System.ComponentModel.CancelEventHandler(this.fileSelectDialog_FileOk); this.fileSelectDialog.FileOk += new System.ComponentModel.CancelEventHandler(this.fileSelectDialog_FileOk);
// //
@ -134,17 +145,35 @@ namespace TinyFPGA_VisualProgrammer
this.connectBtn.UseVisualStyleBackColor = true; this.connectBtn.UseVisualStyleBackColor = true;
this.connectBtn.Click += new System.EventHandler(this.connectBtn_Click); 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 // Programmer
// //
resources.ApplyResources(this, "$this"); resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 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.connectBtn);
this.Controls.Add(this.label2); this.Controls.Add(this.label2);
this.Controls.Add(this.pictureBox1); this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.label1); this.Controls.Add(this.label1);
this.Controls.Add(this.fileLocationTextBox); this.Controls.Add(this.fileLocationTextBox);
this.Controls.Add(this.serialPortList); this.Controls.Add(this.serialPortList);
this.Controls.Add(this.button3); this.Controls.Add(this.ResetBtn);
this.Controls.Add(this.fileExpSelect); this.Controls.Add(this.fileExpSelect);
this.Controls.Add(this.programStatusBar); this.Controls.Add(this.programStatusBar);
this.Controls.Add(this.launchProgramBtn); this.Controls.Add(this.launchProgramBtn);
@ -152,6 +181,7 @@ namespace TinyFPGA_VisualProgrammer
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.MaximizeBox = false; this.MaximizeBox = false;
this.Name = "Programmer"; this.Name = "Programmer";
this.Load += new System.EventHandler(this.Programmer_Load);
this.groupBox1.ResumeLayout(false); this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout(); this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
@ -165,7 +195,7 @@ namespace TinyFPGA_VisualProgrammer
private System.Windows.Forms.ComboBox serialPortList; private System.Windows.Forms.ComboBox serialPortList;
private System.Windows.Forms.Button fileExpSelect; private System.Windows.Forms.Button fileExpSelect;
private System.Windows.Forms.Button launchProgramBtn; 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.TextBox fileLocationTextBox;
private System.Windows.Forms.ProgressBar programStatusBar; private System.Windows.Forms.ProgressBar programStatusBar;
private System.ComponentModel.BackgroundWorker bgWorker; private System.ComponentModel.BackgroundWorker bgWorker;
@ -176,6 +206,8 @@ namespace TinyFPGA_VisualProgrammer
private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button connectBtn; private System.Windows.Forms.Button connectBtn;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ComboBox modeList;
} }
} }

View File

@ -1,98 +1,175 @@
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;
using System.IO.Ports; using System.Threading;
namespace TinyFPGA_VisualProgrammer
{ namespace TinyFPGA_VisualProgrammer
public partial class Programmer : Form {
{ public partial class Programmer : Form
SerialController sController = null; {
TinyProg TProg = null; SerialController sController = null;
TinyProg TProg = null;
public Programmer()
{ public Programmer()
InitializeComponent(); {
fileSelectDialog.InitialDirectory = Path.GetDirectoryName(Application.ExecutablePath); InitializeComponent();
this.AllowDrop = true; fileSelectDialog.InitialDirectory = Path.GetDirectoryName(Application.ExecutablePath);
this.DragEnter += new DragEventHandler(Programmer_DragEnter); this.AllowDrop = true;
this.DragDrop += new DragEventHandler(Programmer_DragDrop); this.DragEnter += new DragEventHandler(Programmer_DragEnter);
this.DragDrop += new DragEventHandler(Programmer_DragDrop);
sController = new SerialController();
TProg = new TinyProg(sController); sController = new SerialController();
if (sController.sPortsList != null && sController.sPortsList.Count > 0) TProg = new TinyProg(sController, statusLabel, bgWorker);
{ if (sController.sPortsList != null && sController.sPortsList.Count > 0)
foreach (string s in sController.sPortsList) {
serialPortList.Items.Add(s); foreach (string s in sController.sPortsList)
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); {
//if(Path.GetExtension(files.First()) == "hex") string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
fileLocationTextBox.Text = files.First(); fileLocationTextBox.Text = files.First();
fileSelectDialog.FileName = files.First(); fileSelectDialog.FileName = files.First();
launchProgramBtn.Enabled = true; RefreshProgramBtnStatus();
} }
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; RefreshProgramBtnStatus();
} }
private void connectBtn_Click(object sender, EventArgs e) private void connectBtn_Click(object sender, EventArgs e)
{ {
connectBtn.Enabled = false; connectBtn.Enabled = false;
UseWaitCursor = true;
if (sController.GetPortOpened())
{ if (sController.GetPortOpened())
sController.ClosePort(); {
connectBtn.Text = "Connect"; sController.ClosePort();
statusLabel.Text = "--"; connectBtn.Text = "Connect";
} statusLabel.Text = "--";
else }
{ else
sController.comPortName = serialPortList.SelectedItem.ToString(); {
sController.OpenPort(); sController.comPortName = serialPortList.SelectedItem.ToString();
if (sController.GetPortOpened()) sController.OpenPort();
TProg.CheckTinyPresence(); if (sController.GetPortOpened())
if (TProg.TinyFPGAIsConnected) TProg.CheckTinyPresence();
statusLabel.Text = "XXXX found.";
else if (TProg.TinyFPGAIsConnected)
statusLabel.Text = "No TinyFPGA found."; {
connectBtn.Text = "Disconnect"; statusLabel.Text = TProg.GetBoardData().Name + " v" + TProg.GetBoardData().HVer + " found.";
} ResetBtn.Enabled = true;
}
connectBtn.Enabled = true; else
} {
statusLabel.Text = "No TinyFPGA found.";
private void serialPortList_SelectedIndexChanged(object sender, EventArgs e) ResetBtn.Enabled = false;
{ }
if (serialPortList.SelectedItem.ToString().Length > 0)
connectBtn.Enabled = true; connectBtn.Text = "Disconnect";
else }
connectBtn.Enabled = false;
} connectBtn.Enabled = true;
} UseWaitCursor = false;
} RefreshProgramBtnStatus();
}
private void serialPortList_SelectedIndexChanged(object sender, EventArgs e)
{
if (serialPortList.SelectedItem.ToString().Length > 0)
connectBtn.Enabled = true;
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;
}
}
}

View File

@ -119,10 +119,10 @@
</resheader> </resheader>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> <assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="serialPortList.Location" type="System.Drawing.Point, System.Drawing"> <data name="serialPortList.Location" type="System.Drawing.Point, System.Drawing">
<value>124, 86</value> <value>71, 86</value>
</data> </data>
<data name="serialPortList.Size" type="System.Drawing.Size, System.Drawing"> <data name="serialPortList.Size" type="System.Drawing.Size, System.Drawing">
<value>78, 21</value> <value>73, 21</value>
</data> </data>
<assembly alias="mscorlib" name="mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <assembly alias="mscorlib" name="mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="serialPortList.TabIndex" type="System.Int32, mscorlib"> <data name="serialPortList.TabIndex" type="System.Int32, mscorlib">
@ -138,7 +138,7 @@
<value>$this</value> <value>$this</value>
</data> </data>
<data name="&gt;&gt;serialPortList.ZOrder" xml:space="preserve"> <data name="&gt;&gt;serialPortList.ZOrder" xml:space="preserve">
<value>5</value> <value>7</value>
</data> </data>
<data name="fileExpSelect.Location" type="System.Drawing.Point, System.Drawing"> <data name="fileExpSelect.Location" type="System.Drawing.Point, System.Drawing">
<value>321, 116</value> <value>321, 116</value>
@ -162,16 +162,16 @@
<value>$this</value> <value>$this</value>
</data> </data>
<data name="&gt;&gt;fileExpSelect.ZOrder" xml:space="preserve"> <data name="&gt;&gt;fileExpSelect.ZOrder" xml:space="preserve">
<value>7</value> <value>9</value>
</data> </data>
<data name="launchProgramBtn.Enabled" type="System.Boolean, mscorlib"> <data name="launchProgramBtn.Enabled" type="System.Boolean, mscorlib">
<value>False</value> <value>False</value>
</data> </data>
<data name="launchProgramBtn.Location" type="System.Drawing.Point, System.Drawing"> <data name="launchProgramBtn.Location" type="System.Drawing.Point, System.Drawing">
<value>71, 187</value> <value>180, 187</value>
</data> </data>
<data name="launchProgramBtn.Size" type="System.Drawing.Size, System.Drawing"> <data name="launchProgramBtn.Size" type="System.Drawing.Size, System.Drawing">
<value>215, 34</value> <value>158, 34</value>
</data> </data>
<data name="launchProgramBtn.TabIndex" type="System.Int32, mscorlib"> <data name="launchProgramBtn.TabIndex" type="System.Int32, mscorlib">
<value>2</value> <value>2</value>
@ -189,31 +189,34 @@
<value>$this</value> <value>$this</value>
</data> </data>
<data name="&gt;&gt;launchProgramBtn.ZOrder" xml:space="preserve"> <data name="&gt;&gt;launchProgramBtn.ZOrder" xml:space="preserve">
<value>9</value> <value>11</value>
</data> </data>
<data name="button3.Location" type="System.Drawing.Point, System.Drawing"> <data name="ResetBtn.Enabled" type="System.Boolean, mscorlib">
<value>False</value>
</data>
<data name="ResetBtn.Location" type="System.Drawing.Point, System.Drawing">
<value>108, 247</value> <value>108, 247</value>
</data> </data>
<data name="button3.Size" type="System.Drawing.Size, System.Drawing"> <data name="ResetBtn.Size" type="System.Drawing.Size, System.Drawing">
<value>137, 21</value> <value>137, 21</value>
</data> </data>
<data name="button3.TabIndex" type="System.Int32, mscorlib"> <data name="ResetBtn.TabIndex" type="System.Int32, mscorlib">
<value>3</value> <value>3</value>
</data> </data>
<data name="button3.Text" xml:space="preserve"> <data name="ResetBtn.Text" xml:space="preserve">
<value>Exit Bootloader/Reset</value> <value>Exit Bootloader/Reset</value>
</data> </data>
<data name="&gt;&gt;button3.Name" xml:space="preserve"> <data name="&gt;&gt;ResetBtn.Name" xml:space="preserve">
<value>button3</value> <value>ResetBtn</value>
</data> </data>
<data name="&gt;&gt;button3.Type" xml:space="preserve"> <data name="&gt;&gt;ResetBtn.Type" xml:space="preserve">
<value>System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data> </data>
<data name="&gt;&gt;button3.Parent" xml:space="preserve"> <data name="&gt;&gt;ResetBtn.Parent" xml:space="preserve">
<value>$this</value> <value>$this</value>
</data> </data>
<data name="&gt;&gt;button3.ZOrder" xml:space="preserve"> <data name="&gt;&gt;ResetBtn.ZOrder" xml:space="preserve">
<value>6</value> <value>8</value>
</data> </data>
<data name="fileLocationTextBox.Location" type="System.Drawing.Point, System.Drawing"> <data name="fileLocationTextBox.Location" type="System.Drawing.Point, System.Drawing">
<value>44, 116</value> <value>44, 116</value>
@ -237,10 +240,10 @@
<value>$this</value> <value>$this</value>
</data> </data>
<data name="&gt;&gt;fileLocationTextBox.ZOrder" xml:space="preserve"> <data name="&gt;&gt;fileLocationTextBox.ZOrder" xml:space="preserve">
<value>4</value> <value>6</value>
</data> </data>
<data name="programStatusBar.Location" type="System.Drawing.Point, System.Drawing"> <data name="programStatusBar.Location" type="System.Drawing.Point, System.Drawing">
<value>10, 227</value> <value>12, 227</value>
</data> </data>
<data name="programStatusBar.Size" type="System.Drawing.Size, System.Drawing"> <data name="programStatusBar.Size" type="System.Drawing.Size, System.Drawing">
<value>333, 14</value> <value>333, 14</value>
@ -258,7 +261,7 @@
<value>$this</value> <value>$this</value>
</data> </data>
<data name="&gt;&gt;programStatusBar.ZOrder" xml:space="preserve"> <data name="&gt;&gt;programStatusBar.ZOrder" xml:space="preserve">
<value>8</value> <value>10</value>
</data> </data>
<data name="statusLabel.AutoSize" type="System.Boolean, mscorlib"> <data name="statusLabel.AutoSize" type="System.Boolean, mscorlib">
<value>True</value> <value>True</value>
@ -315,7 +318,7 @@
<value>$this</value> <value>$this</value>
</data> </data>
<data name="&gt;&gt;groupBox1.ZOrder" xml:space="preserve"> <data name="&gt;&gt;groupBox1.ZOrder" xml:space="preserve">
<value>10</value> <value>12</value>
</data> </data>
<data name="label1.AutoSize" type="System.Boolean, mscorlib"> <data name="label1.AutoSize" type="System.Boolean, mscorlib">
<value>True</value> <value>True</value>
@ -324,13 +327,13 @@
<value>12, 89</value> <value>12, 89</value>
</data> </data>
<data name="label1.Size" type="System.Drawing.Size, System.Drawing"> <data name="label1.Size" type="System.Drawing.Size, System.Drawing">
<value>106, 13</value> <value>57, 13</value>
</data> </data>
<data name="label1.TabIndex" type="System.Int32, mscorlib"> <data name="label1.TabIndex" type="System.Int32, mscorlib">
<value>8</value> <value>8</value>
</data> </data>
<data name="label1.Text" xml:space="preserve"> <data name="label1.Text" xml:space="preserve">
<value>TinyFPGA COM port:</value> <value>Serial port:</value>
</data> </data>
<data name="&gt;&gt;label1.Name" xml:space="preserve"> <data name="&gt;&gt;label1.Name" xml:space="preserve">
<value>label1</value> <value>label1</value>
@ -342,7 +345,7 @@
<value>$this</value> <value>$this</value>
</data> </data>
<data name="&gt;&gt;label1.ZOrder" xml:space="preserve"> <data name="&gt;&gt;label1.ZOrder" xml:space="preserve">
<value>3</value> <value>5</value>
</data> </data>
<data name="pictureBox1.Location" type="System.Drawing.Point, System.Drawing"> <data name="pictureBox1.Location" type="System.Drawing.Point, System.Drawing">
<value>12, 12</value> <value>12, 12</value>
@ -367,7 +370,7 @@
<value>$this</value> <value>$this</value>
</data> </data>
<data name="&gt;&gt;pictureBox1.ZOrder" xml:space="preserve"> <data name="&gt;&gt;pictureBox1.ZOrder" xml:space="preserve">
<value>2</value> <value>4</value>
</data> </data>
<data name="label2.AutoSize" type="System.Boolean, mscorlib"> <data name="label2.AutoSize" type="System.Boolean, mscorlib">
<value>True</value> <value>True</value>
@ -394,7 +397,7 @@
<value>$this</value> <value>$this</value>
</data> </data>
<data name="&gt;&gt;label2.ZOrder" xml:space="preserve"> <data name="&gt;&gt;label2.ZOrder" xml:space="preserve">
<value>1</value> <value>3</value>
</data> </data>
<metadata name="bgWorker.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="bgWorker.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>180, 22</value> <value>180, 22</value>
@ -403,16 +406,16 @@
<value>17, 23</value> <value>17, 23</value>
</metadata> </metadata>
<data name="fileSelectDialog.Filter" xml:space="preserve"> <data name="fileSelectDialog.Filter" xml:space="preserve">
<value>FPGA bitmap|*.hex,*.bin,*.jed|Tous les fichiers|*.*</value> <value>FPGA bitmap|*.bin;*.hex|Tous les fichiers|*.*</value>
</data> </data>
<data name="connectBtn.Enabled" type="System.Boolean, mscorlib"> <data name="connectBtn.Enabled" type="System.Boolean, mscorlib">
<value>False</value> <value>False</value>
</data> </data>
<data name="connectBtn.Location" type="System.Drawing.Point, System.Drawing"> <data name="connectBtn.Location" type="System.Drawing.Point, System.Drawing">
<value>211, 86</value> <value>21, 187</value>
</data> </data>
<data name="connectBtn.Size" type="System.Drawing.Size, System.Drawing"> <data name="connectBtn.Size" type="System.Drawing.Size, System.Drawing">
<value>104, 21</value> <value>153, 34</value>
</data> </data>
<data name="connectBtn.TabIndex" type="System.Int32, mscorlib"> <data name="connectBtn.TabIndex" type="System.Int32, mscorlib">
<value>11</value> <value>11</value>
@ -430,6 +433,66 @@
<value>$this</value> <value>$this</value>
</data> </data>
<data name="&gt;&gt;connectBtn.ZOrder" xml:space="preserve"> <data name="&gt;&gt;connectBtn.ZOrder" xml:space="preserve">
<value>2</value>
</data>
<data name="label3.AutoSize" type="System.Boolean, mscorlib">
<value>True</value>
</data>
<data name="label3.Location" type="System.Drawing.Point, System.Drawing">
<value>177, 89</value>
</data>
<data name="label3.Size" type="System.Drawing.Size, System.Drawing">
<value>37, 13</value>
</data>
<data name="label3.TabIndex" type="System.Int32, mscorlib">
<value>12</value>
</data>
<data name="label3.Text" xml:space="preserve">
<value>Mode:</value>
</data>
<data name="&gt;&gt;label3.Name" xml:space="preserve">
<value>label3</value>
</data>
<data name="&gt;&gt;label3.Type" xml:space="preserve">
<value>System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
<data name="&gt;&gt;label3.Parent" xml:space="preserve">
<value>$this</value>
</data>
<data name="&gt;&gt;label3.ZOrder" xml:space="preserve">
<value>1</value>
</data>
<data name="modeList.Enabled" type="System.Boolean, mscorlib">
<value>False</value>
</data>
<data name="modeList.Items" xml:space="preserve">
<value>user_image</value>
</data>
<data name="modeList.Items1" xml:space="preserve">
<value>user_data</value>
</data>
<data name="modeList.Items2" xml:space="preserve">
<value>bootloader</value>
</data>
<data name="modeList.Location" type="System.Drawing.Point, System.Drawing">
<value>220, 86</value>
</data>
<data name="modeList.Size" type="System.Drawing.Size, System.Drawing">
<value>118, 21</value>
</data>
<data name="modeList.TabIndex" type="System.Int32, mscorlib">
<value>13</value>
</data>
<data name="&gt;&gt;modeList.Name" xml:space="preserve">
<value>modeList</value>
</data>
<data name="&gt;&gt;modeList.Type" xml:space="preserve">
<value>System.Windows.Forms.ComboBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
<data name="&gt;&gt;modeList.Parent" xml:space="preserve">
<value>$this</value>
</data>
<data name="&gt;&gt;modeList.ZOrder" xml:space="preserve">
<value>0</value> <value>0</value>
</data> </data>
<metadata name="$this.Localizable" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <metadata name="$this.Localizable" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">

View File

@ -1,10 +1,10 @@
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// <auto-generated> // <auto-generated>
// Ce code a été généré par un outil. // This code was generated by a tool.
// Version du runtime :4.0.30319.42000 // Runtime Version:4.0.30319.42000
// //
// Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si // Changes to this file may cause incorrect behavior and will be lost if
// le code est régénéré. // the code is regenerated.
// </auto-generated> // </auto-generated>
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
@ -13,13 +13,13 @@ namespace TinyFPGA_VisualProgrammer.Properties {
/// <summary> /// <summary>
/// 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.
/// </summary> /// </summary>
// Cette classe a été générée automatiquement par la classe StronglyTypedResourceBuilder // This class was auto-generated by the StronglyTypedResourceBuilder
// à l'aide d'un outil, tel que ResGen ou Visual Studio. // class via a tool like ResGen or Visual Studio.
// Pour ajouter ou supprimer un membre, modifiez votre fichier .ResX, puis réexécutez ResGen // To add or remove a member, edit your .ResX file then rerun ResGen
// avec l'option /str ou régénérez votre projet VS. // with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources { internal class Resources {
@ -33,7 +33,7 @@ namespace TinyFPGA_VisualProgrammer.Properties {
} }
/// <summary> /// <summary>
/// Retourne l'instance ResourceManager mise en cache utilisée par cette classe. /// Returns the cached ResourceManager instance used by this class.
/// </summary> /// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager { internal static global::System.Resources.ResourceManager ResourceManager {
@ -47,8 +47,8 @@ namespace TinyFPGA_VisualProgrammer.Properties {
} }
/// <summary> /// <summary>
/// Remplace la propriété CurrentUICulture du thread actuel pour toutes /// Overrides the current thread's CurrentUICulture property for all
/// les recherches de ressources à l'aide de cette classe de ressource fortement typée. /// resource lookups using this strongly typed resource class.
/// </summary> /// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture { internal static global::System.Globalization.CultureInfo Culture {
@ -61,7 +61,7 @@ namespace TinyFPGA_VisualProgrammer.Properties {
} }
/// <summary> /// <summary>
/// Recherche une ressource localisée de type System.Drawing.Bitmap. /// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary> /// </summary>
internal static System.Drawing.Bitmap softBanner { internal static System.Drawing.Bitmap softBanner {
get { get {
@ -71,7 +71,7 @@ namespace TinyFPGA_VisualProgrammer.Properties {
} }
/// <summary> /// <summary>
/// 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).
/// </summary> /// </summary>
internal static System.Drawing.Icon tinyfpga_icon { internal static System.Drawing.Icon tinyfpga_icon {
get { get {

View File

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

View File

@ -12,6 +12,23 @@
<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>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
@ -20,17 +37,22 @@
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath> <OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
<LangVersion>8.0</LangVersion>
<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>
<LangVersion>8.0</LangVersion>
<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 +60,14 @@
<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=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</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 +104,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 +124,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,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

@ -1,169 +1,455 @@
using System; using Newtonsoft.Json;
using System.Collections.Generic; using System;
using System.IO.Ports; using System.Collections.Generic;
using System.Linq; using System.ComponentModel;
using System.Text; using System.ComponentModel.Design;
using System.Threading.Tasks; using System.Data;
using System.IO.Ports;
namespace TinyFPGA_VisualProgrammer using System.Linq;
{ using System.Runtime.InteropServices.ComTypes;
public class TinyProg using System.Text;
{ using System.Text.RegularExpressions;
SerialController pPort = null; using System.Threading;
byte SecurePage_bitOffset = 0x00; using System.Threading.Tasks;
byte SecurePage_writeCmd = 0x00; using System.Windows.Forms;
byte SecurePage_readCmd = 0x00;
byte SecurePage_eraseCmd = 0x00; namespace TinyFPGA_VisualProgrammer
{
public bool TinyFPGAIsConnected { get; private set; } public class JSON_BoardMeta
{
public TinyProg(SerialController p) [JsonProperty("name")]
{ public string Name { get; set; }
TinyFPGAIsConnected = false;
if (p != null) [JsonProperty("fpga")]
pPort = p; public string FPGA { get; set; }
}
[JsonProperty("hver")]
public string HVer { get; set; }
public void CheckTinyPresence()
{ [JsonProperty("uuid")]
WakeCmd(); public string UUID { get; set; }
byte[] flash_id = RetrieveFlashID(); }
if (flash_id.Length >= 3)
{ public class JSON_BootMeta
if (flash_id[0] == 0x9D && flash_id[2] == 0x60) {
{ [JsonProperty("bootloader")]
// ISSI public string BootLoader { get; set; }
SecurePage_bitOffset = 4;
SecurePage_writeCmd = 0x62; [JsonProperty("bver")]
SecurePage_readCmd = 0x68; public string BVer { get; set; }
SecurePage_eraseCmd = 0x64;
} [JsonProperty("update")]
else public string Update { get; set; }
{
// Adesto [JsonProperty("addrmap")]
SecurePage_bitOffset = 0; public JSON_AddrMap AddrMap { get; set; }
SecurePage_writeCmd = 0x42; }
SecurePage_readCmd = 0x48;
SecurePage_eraseCmd = 0x44; public class JSON_AddrMap
} {
[JsonProperty("bootloader")]
TinyFPGAIsConnected = true; public string BootLoader { get; set; }
}
[JsonProperty("userimage")]
//@TODO: Add json security parser public string UserImage { get; set; }
}
[JsonProperty("userdata")]
byte[] SendCommand(byte opcode, byte[] addr, byte[] datas, uint read_len = 0) public string UserData { get; set; }
{ }
if (addr == null)
addr = new byte[] { }; public class TinyProg
if (datas == null) {
datas = new byte[] { }; SerialController pPort = null;
BackgroundWorker bw = null;
byte[] _ret = new byte[read_len]; Label status = null;
byte[] cmdSequence = new byte[sizeof(byte) + sizeof(ushort) + sizeof(ushort) + sizeof(byte) + addr.Length + datas.Length]; byte SecurePage_bitOffset = 0x00;
int i; byte SecurePage_writeCmd = 0x00;
byte SecurePage_readCmd = 0x00;
/* byte SecurePage_eraseCmd = 0x00;
* Prepare datas container TinyMeta tinyMeta = null;
*/ short step_prog = 0;
cmdSequence[0] = 0x01;
public bool TinyFPGAIsConnected { get; private set; }
ushort seqSize = (ushort)(1 + addr.Length + datas.Length);
cmdSequence[1] = (byte)(seqSize & 0xFF); // LSB public TinyProg(SerialController p, Label sl, BackgroundWorker _bw)
cmdSequence[2] = (byte)((seqSize >> 8) & 0xFF); {
TinyFPGAIsConnected = false;
cmdSequence[3] = (byte)(read_len & 0xFF); // LSB if (p != null)
cmdSequence[4] = (byte)((read_len >> 8) & 0xFF); pPort = p;
if (sl != null)
cmdSequence[5] = opcode; status = sl;
i = 6; if (_bw != null)
foreach (byte ab in addr) bw = _bw;
cmdSequence[i++] = ab; }
i = 6 + addr.Length;
foreach (byte d in datas)
cmdSequence[i++] = d; public void CheckTinyPresence()
{
/* WakeCmd();
* Send datas container through serial line byte[] flash_id = RetrieveFlashID();
*/ if (flash_id.Length >= 3)
pPort.SendBytes(cmdSequence, cmdSequence.Length); {
if (flash_id[0] == 0x9D && flash_id[2] == 0x60)
if (read_len > 0) {
{ // ISSI
_ret = pPort.WaitForBytes((int)read_len); SecurePage_bitOffset = 4;
} SecurePage_writeCmd = 0x62;
SecurePage_readCmd = 0x68;
return _ret; SecurePage_eraseCmd = 0x64;
} }
else
public void WakeCmd() {
{ // Adesto
SendCommand(0xab, null, null); SecurePage_bitOffset = 0;
} SecurePage_writeCmd = 0x42;
SecurePage_readCmd = 0x48;
byte[] RetrieveFlashID() SecurePage_eraseCmd = 0x44;
{ }
return SendCommand(0x9f, null, null, 3); }
}
tinyMeta = new TinyMeta(this);
void FlashWriteEnable() if (tinyMeta.BoardMeta != null)
{ TinyFPGAIsConnected = true;
SendCommand(0x06, null, null); else
} TinyFPGAIsConnected = false;
}
void FlashWriteDisable()
{ public JSON_BoardMeta GetBoardData()
SendCommand(0x04, null, null); {
} return tinyMeta.BoardMeta;
}
byte RetrieveStatus()
{ public JSON_BootMeta GetBootData()
return SendCommand(0x05, null, null, 1)[0]; {
} return tinyMeta.BootMeta;
}
void WaitWhileBusy()
{ byte[] SendCommand(byte opcode, byte[] addr, byte[] datas, uint read_len = 0)
while ((RetrieveStatus() & 1) == 1) { } {
} if (addr == null)
addr = new byte[] { };
void EraseSecureRegPage(uint page) else
{ addr = addr.Take(3).Reverse().ToArray(); // Drop the unused MSB 8b
FlashWriteEnable();
SendCommand(SecurePage_eraseCmd, BitConverter.GetBytes(page << 8 + SecurePage_bitOffset), null); if (datas == null)
WaitWhileBusy(); datas = new byte[] { };
}
byte[] _ret = new byte[read_len];
void ProgramSecureRegPage(uint page, byte[] data) byte[] cmdSequence = new byte[sizeof(byte) + sizeof(ushort) + sizeof(ushort) + sizeof(byte) + addr.Length + datas.Length];
{ int i;
FlashWriteEnable();
SendCommand(SecurePage_writeCmd, BitConverter.GetBytes(page << 8 + SecurePage_bitOffset), data); /*
WaitWhileBusy(); * Prepare datas container
} */
cmdSequence[0] = 0x01;
byte[] ReadSecureRegPage(uint page)
{ ushort seqSize = (ushort)(1 + addr.Length + datas.Length);
return SendCommand(SecurePage_readCmd, BitConverter.GetBytes(page << 8 + SecurePage_bitOffset), new byte[] { 0x00 }, 255); cmdSequence[1] = (byte)(seqSize & 0xFF); // LSB - Little-endian
} cmdSequence[2] = (byte)((seqSize >> 8) & 0xFF);
}
cmdSequence[3] = (byte)(read_len & 0xFF); // LSB - Little-endian
public class TinyMeta cmdSequence[4] = (byte)((read_len >> 8) & 0xFF);
{
TinyProg tProg; cmdSequence[5] = opcode;
//JSONRoot root; i = 6;
foreach (byte ab in addr)
public TinyMeta(TinyProg tProg) cmdSequence[i++] = ab; // Caution - this write in reverse order (big-endian)
{ i = 6 + addr.Length;
this.tProg = tProg; foreach (byte d in datas)
tProg.WakeCmd(); cmdSequence[i++] = d; // Caution - this write in reverse order (big-endian)
//this.root = ReadMetadata();
} /*
* Send datas container through serial line
*/
void ParseJSON() //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*(?<start>0x[A-Fa-f0-9]+)\s*-\s*(?<end>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<JSON_BoardMeta>(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);
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<JSON_BootMeta>(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
//TODO: Read from internal memory ([17, 18, 19, 20, 21, 22, 23, 24])
}
}
}

4
packages.config Normal file
View File

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