Showing posts with label Datalog. Show all posts
Showing posts with label Datalog. Show all posts

Monday, 17 November 2008

BCD to Binary conversion

I needed to convert some numbers received from a PLC from their original packed BCD format to binary (hex) format. The numbers to convert are split into two 16-bit halves, and need to be converted into one 32-bit number.

(Packed BCD values contain two digits for every byte.)

There is a method that exists that will convert numbers from BCD into a true hex number, by using string formatting, but this is relatively expensive in terms of performance and I required the best performance possible.

So, I came up with this function:

   1:  /// <summary>
   2:  /// Convert two PLC words in BCD format (forming 8 digit number) into single binary integer.
   3:  /// e.g. If Lower = 0x5678 and Upper = 0x1234, then Return is 12345678 decimal, or 0xbc614e.
   4:  /// </summary>
   5:  /// <param name="lower">Least significant 16 bits.</param>
   6:  /// <param name="upper">Most significant 16 bits.</param>
   7:  /// <returns>32 bit unsigned integer.</returns>
   8:  /// <remarks>If the parameters supplied are invalid, returns zero.</remarks>
   9:  private uint BCD2ToBin(uint lower, uint upper)
  10:  {
  11:      uint binVal = 0;
  12:   
  13:      if ((lower | upper) != 0)
  14:      {
  15:          int shift = 0;
  16:          uint multiplier = 1;
  17:          uint bcdVal = (upper << 16) | lower;
  18:   
  19:          for (int i = 0; i < 8; i++)
  20:          {
  21:              uint digit = (bcdVal >> shift) & 0xf;
  22:   
  23:              if (digit > 9)
  24:              {
  25:                  binVal = 0;
  26:                  break;
  27:              }
  28:              else
  29:              {
  30:                  binVal += digit * multiplier;
  31:                  shift += 4;
  32:                  multiplier *= 10;
  33:              }
  34:          }
  35:      }
  36:   
  37:      return binVal;
  38:  }


The function takes in two unsigned itegers that hold each of the 16-bit weighted BCD values, and returns a 32-bit unsigned integer.

It is important to note that the return is an unsigned integer, as this allows BCD values up to 0x99999999 to be converted correctly.

I have also taken the approach of returning zero if any of the values supplied are incorrect, i.e. contain an invalid digit. (BCD values can only contain digits ranging between 0 and 9, and not A to F.)

Of course, it may be desirable to return a different value, or to throw an exception if the parameters supplied are invalid, but for my purposes, returning a zero was sufficient.

This method proved to be around four to five times quicker than by using the string format method.

Friday, 24 October 2008

Using RowPrePaint event of a DataGridView control

To draw a row in a DataGridView control in a different style depending on a certain condition, you can use the RowPrePaint event to interrupt the painting of the rows in the grid.

You then have a choice of which parts of the row to be painted automatically and which parts to paint yourself via the PaintParts event property.

In the code below, I paint a row with a custom brush, depending on the value of a column that is named 'Error'.

   1:  /// <summary>
   2:  /// Handles the drawing of each DataGridView row depending on set log error state.
   3:  /// </summary>
   4:  /// <param name="sender"></param>
   5:  /// <param name="e"></param>
   6:  private void setLogDataGridView_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
   7:  {
   8:      // Paint all parts of row except SelectionBackground and the Focus box.
   9:      e.PaintParts = DataGridViewPaintParts.All & ~(DataGridViewPaintParts.SelectionBackground | DataGridViewPaintParts.Focus);
  10:   
  11:      // Get the value of the error column of the current row
  12:      string val = this.setLogDataGridView.Rows[e.RowIndex].Cells["Error"].Value.ToString();
  13:   
  14:      if (val != "0")
  15:      {
  16:           // Get rectangle of area to paint with custom brush.
  17:            Rectangle rowBounds = new Rectangle(
  18:             this.setLogDataGridView.RowHeadersWidth, e.RowBounds.Top,
  19:             this.setLogDataGridView.Columns.GetColumnsWidth(
  20:             DataGridViewElementStates.Visible) -
  21:             this.setLogDataGridView.HorizontalScrollingOffset + 1,
  22:             e.RowBounds.Height);
  23:   
  24:      // Disable normal painting of backgrounds.
  25:      e.PaintParts &= ~(DataGridViewPaintParts.Background | DataGridViewPaintParts.ContentBackground);
  26:   
  27:      e.PaintHeader(false);
  28:   
  29:      // Paint the custom background.
  30:      using (Brush lgb = new LinearGradientBrush(rowBounds, Color.Red,
  31:             Color.DarkRed, LinearGradientMode.Vertical))
  32:      {
  33:          e.Graphics.FillRectangle(lgb, rowBounds);
  34:      }
  35:   
  36:      // Set the text colour.
  37:      this.setLogDataGridView.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Yellow;
  38:      this.setLogDataGridView.Rows[e.RowIndex].DefaultCellStyle.SelectionForeColor =      Color.Yellow;
  39:      }
  40:  }

Create a User business object

To create a business object that represents a 'User' of my Datalog application, I have used the code shown below, and it works well for my purposes. I decided to make it a Struct instead of a Class as it is a small and lightweight object. If any readers think that it should preferably be a Class, then please leave a comment. I'm still learning this stuff, so any tips welcome!

   1:  using System;
   2:   
   3:  namespace KAS.Datalog
   4:  {
   5:      /// <summary>
   6:      /// Represents a user of the application.
   7:      /// </summary>
   8:      public struct User
   9:      {
  10:          #region Fields
  11:   
  12:          private string _strName;
  13:          private UserLevel _userLevel;
  14:   
  15:          #endregion
  16:   
  17:          #region Properties
  18:   
  19:          /// <summary>
  20:          /// Gets or sets the user name.
  21:          /// </summary>
  22:          public string Name
  23:          {
  24:              get { return this._strName; }
  25:              set { this._strName = value; }
  26:          }
  27:   
  28:          /// <summary>
  29:          /// Gets or sets the user level.
  30:          /// </summary>
  31:          public UserLevel Level
  32:          {
  33:              get { return this._userLevel; }
  34:              set { this._userLevel = value; }
  35:          }
  36:   
  37:          #endregion
  38:   
  39:          #region Constructor
  40:   
  41:          /// <summary>
  42:          /// Constructor
  43:          /// </summary>
  44:          /// <param name="name">Name of the user</param>
  45:          /// <param name="level">Secutirty level</param>
  46:          public User(string name, UserLevel level)
  47:          {
  48:              if (name != "") { this._strName = name; }
  49:              else { this._strName = "Unknown"; }
  50:   
  51:              this._userLevel = level;
  52:          }
  53:   
  54:          #endregion
  55:   
  56:          #region Overridden methods
  57:   
  58:          public override string ToString()
  59:          {
  60:              return this._strName + "," + this._userLevel.ToString();
  61:          }
  62:   
  63:          #endregion
  64:      }
  65:  }

Sunday, 6 July 2008

Filling a DataGridView from a list of structs

An easy way I have found of filling a DataGridView with data, is when you configure the data source to be a list. As part of my Datalog project, I have a struct that represents a tracked machine set. Each new tracked set is added to a List<>. When the job run is complete, it is this List<> that I make the data source.

First, the code for the struct:

   1:  /// <summary>
   2:  /// Structure representing a tracked machine set.
   3:  /// </summary>
   4:  public struct TrackedSet
   5:  {
   6:      #region Fields
   7:   
   8:      private int _id;
   9:      private string _date;
  10:      private string _time;
  11:      private string _customer;
  12:      private int _sheets;
  13:      private char _insert1;
  14:      private char _insert2;
  15:      private char _insert3;
  16:      private char _insert4;
  17:      private char _insert5;
  18:      private char _insert6;
  19:      private char _insert7;
  20:      private char _insert8;
  21:      private char _insert9;
  22:      private char _insert10;
  23:      private char _sysCtrl;
  24:      private int _weight;
  25:      private string _error;
  26:   
  27:      #endregion
  28:   
  29:      #region Properties
  30:   
  31:      // The order that the properties are defined determines the order
  32:      // of columns created in the DataGridView.
  33:      // The column names will be taken from the property name, unless overwritten.
  34:   
  35:      public int ID
  36:      { get { return this._id; } }
  37:   
  38:      public string Date
  39:      { get { return this._date; } }
  40:   
  41:      public string Time
  42:      { get { return this._time; } }
  43:   
  44:      public string Customer
  45:      { get { return this._customer; } }
  46:   
  47:      public int Sheets
  48:      { get { return this._sheets; } }
  49:          
  50:      public char Insert1
  51:      { get { return this._insert1; } }
  52:   
  53:      public char Insert2
  54:      { get { return this._insert2; } }
  55:   
  56:      public char Insert3
  57:      { get { return this._insert3; } }
  58:   
  59:      public char Insert4
  60:      { get { return this._insert4; } }
  61:   
  62:      public char Insert5
  63:      { get { return this._insert5; } }
  64:   
  65:      public char Insert6
  66:      { get { return this._insert6; } }
  67:   
  68:      public char Insert7
  69:      { get { return this._insert7; } }
  70:   
  71:      public char Insert8
  72:      { get { return this._insert8; } }
  73:   
  74:      public char Insert9
  75:      { get { return this._insert9; } }
  76:   
  77:      public char Insert10
  78:      { get { return this._insert10; } }
  79:   
  80:      public char SysCtrl
  81:      { get { return this._sysCtrl; } }
  82:   
  83:      public int Weight
  84:      { get { return this._weight; } }
  85:   
  86:      public string Error
  87:      { get { return this._error; } }
  88:   
  89:      #endregion
  90:   
  91:      #region Constructor
  92:   
  93:      /// <summary>
  94:      /// TrackedSet constructor.
  95:      /// </summary>
  96:      /// <param name="id">The ID code for the tracked set</param>
  97:      /// <param name="msg">The serial link message string decoded from job data block</param>
  98:      /// <param name="created">The creation time of the tracked set</param>
  99:      /// <param name="weight">The post weight of the tracked set.</param>
 100:      /// <param name="error">The error code of the tracked set</param>
 101:      public TrackedSet(int id, DateTime created, string msg, int weight, string error)
 102:      {
 103:          // Get ID.
 104:          this._id = id;
 105:   
 106:          // Get created date.
 107:          this._date = created.ToShortDateString();
 108:   
 109:          // Get created time.
 110:          this._time = created.ToLongTimeString();
 111:   
 112:          // Get serial link message. Correct format : 12345678901,123,abcdefghij
 113:              
 114:          string[] str = msg.Split(',');
 115:   
 116:          // Get insert requests and system control characters.
 117:          char[] c = str[0].ToCharArray();
 118:   
 119:          this._insert1 = c[0];
 120:          this._insert2 = c[1];
 121:          this._insert3 = c[2];
 122:          this._insert4 = c[3];
 123:          this._insert5 = c[4];
 124:          this._insert6 = c[5];
 125:          this._insert7 = c[6];
 126:          this._insert8 = c[7];
 127:          this._insert9 = c[8];
 128:          this._insert10 = c[9];
 129:          this._sysCtrl = c[10];
 130:   
 131:          // Get sheet count.
 132:          bool result = int.TryParse(str[1], out this._sheets);
 133:   
 134:          // Get customer code.
 135:          this._customer = str[2];
 136:   
 137:          // Get post weight.
 138:          this._weight = weight;
 139:   
 140:          // Get error code.
 141:          this._error = error;
 142:      }
 143:  }


The list is defined as...

   1:  List<TrackedSet> _trackedSetList;


...and created as...

   1:  this._trackedSetList = new List<TrackedSet>();


Add new TrackedSets during a job run in this way:

   1:  // Add a new TrackedSet to the list.
   2:  this._trackedSetList.Add(new TrackedSet(this._rowCounter, 
   3:                                          DateTime.Now, 
   4:                                          this._serialLinkMessage, 
   5:                                          this._postWeightValue, 
   6:                                          this._errorCode));


Then it is simply a matter of setting the .DataSource property of the DataGridView to the list to enable it to be displayed:

   1:  this.dataGridView1.DataSource = this._trackedSetList;


This produces an output display similar to:



Click the image to see a larger view.



It is important to note thate the order that columns are created and displayed in the DataGridView is directly related to the order in which the struct properties as listed.

Thursday, 26 June 2008

Gradient border around a form

Sometimes it is nice to have a bit of extra eye candy to look at, and a good place to have some of this is on a splash screen. One effect that is very simple to achieve is a custom border around the form with a bit of colour and maybe a gradient fill, which is what this post is about.

First of all, set a few of the form properties as follows:

FormBorderstyle - None.
ControlBox - False.
MaximizeBox - False.
MinimizeBox - False.

The FormBorderStyle property is set to false because the intention is to draw a custom border of our own.
The code required to actually draw the gradient border goes in the form's Paint event. This event is fired at any time the form needs to be redrawn, or in other words - Painted.

   1:  private void SplashForm_Paint(object sender, PaintEventArgs e)
   2:  {
   3:      // Get the form bounding rectangle
   4:      Rectangle rect = new Rectangle(0, 0, this.Width, this.Height);
   5:   
   6:      // Create the brush used to paint the border
   7:      LinearGradientBrush lgb = new LinearGradientBrush(
   8:                                        rect,
   9:                                        Color.DarkBlue,
  10:                                        Color.Blue,
  11:                                        LinearGradientMode.ForwardDiagonal);
  12:    
  13:      // Draw the border with a width of 10
  14:      e.Graphics.DrawRectangle(new Pen(lgb, 10), rect);
  15:   
  16:      // Dispose of the brush
  17:      lgb.Dispose();
  18:  }


This produces the subtle gradient around the splash screen to my Datalog application:



I hope it can be seen that is easy to change the colours, change the gradient and the size of the border that is drawn. Pretty straightforward and only four lines of code.

Sunday, 29 April 2007

Datalog 3.0.0.0 release

Demo of Datalog 3.0.0.0 went well, with no last minute hitches. Only need to include a license file and it's done. I can already think of improvements to make, such as encapsulating more code into classes, and also more improvements that need to be made, such as better comms control, and reduction of the processor overhead. But for now, it has the green light to ship!

Tuesday, 17 April 2007

Eureka!

Solved the 'Failed to send Command - Write pending' error. Caused by running the Disconnect sub directly from the disconnect menu option instead of setting the 'disconnect request' flag.

Also solved the problem of getting invalid start characters when a connection is attempted after the comms lead has been removed in mid-sequence. Solved this by setting a timeout value in the PLC comms card when transmitting data. If a timeout occurs (i.e. when the lead has become disconnected and transmition is not possible) then the communications sequence is aborted and the buffers are flushed.

Monday, 16 April 2007

Test, test, test

Datalog comms test for 8+ hours without problem. Showed no sign of memory increase in Private Bytes, or in # of Bytes in All Heaps, although the latter consistantly jumped by some 300k or so, but always dropped again, as well as the regular GC cycle. The 300k jumps (increase and decrease) coincided with a GC Gen 2 collection. Error on disconnect: "Failed to send command - Write pending". This was repeated a couple of times, but not consistantly. Possibly the PLC control loop thread is being allowed to exit before a command cycle has completed?

Sunday, 15 April 2007

Concerns...

Datalog 3.0.0.0 application nearing completion, hope to present it at work very soon.

Concerns:

  • Memory use seems to rise on the IBM laptop, but not on the desktops. Can't track down why that should be.
  • Nothing to stop the app being freely copied and used on compatible equipment.
  • Limited testing has been done on different platforms.