using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Data.SQLite;
using TwinCAT.Ads;
namespace SQLiteDataloggerCE
{
public partial class DataLogger : Form
{
// Software version
private const string sSQL_Version = "HCP_2013-02_v1.0";
// SQL database connections string
private DbConnection db = new SQLiteConnection(@"Data Source = \Hard Disk2\SQLData.db3");
// Create table SQL string
string SQLText =
@"pragma foreign_keys = off;
begin transaction;
pragma auto_vacuum=0;
pragma default_cache_size=2000;
pragma encoding='UTF-8';
pragma page_size=1024;
create table if not exists [tblLogData] (
[ID] INTEGER PRIMARY KEY AUTOINCREMENT,
[DateTime] TIMESTAMP,
[TankNr] INTEGER,
[BatchNr] INTEGER,
[Temperatur] FLOAT,
[Volume] FLOAT,
[ErrorCode] VARCHAR(8),
[Approved] BOOL(1));
commit transaction;
pragma foreign_keys = on;";
// TwinCAT Ads client
private TcAdsClient AdsClient;
private TcAdsSymbolInfoLoader AdsSymbolInfoLoader;
private TcAdsSymbolInfo SqlDataAdsSymbolInfo;
private int hWrite;
private int hDone;
private int hWatchDog;
public DataLogger()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
AdsClientOpen();
}
catch (Exception err)
{
MessageBox.Show("Form1_Load() - " + err.Message);
}
}
private void Form1_Closing(object sender, CancelEventArgs e)
{
try
{
AdsClientClose();
db.Close();
db.Dispose();
}
catch (Exception err)
{
MessageBox.Show("Form1_FormClosing() - " + err.Message);
}
}
private void AdsClientOpen()
{
try
{
AdsClient = new TcAdsClient();
AdsClient.Connect("", 801);
AdsSymbolInfoLoader = AdsClient.CreateSymbolInfoLoader();
SqlDataAdsSymbolInfo = AdsSymbolInfoLoader.FindSymbol(("P_Datalogger.stSQLData").ToUpper());
hWatchDog = AdsClient.CreateVariableHandle("P_Datalogger.bWatchDog");
hDone = AdsClient.CreateVariableHandle("P_Datalogger.bDone");
AdsClient.AdsNotificationEx += new AdsNotificationExEventHandler(AdsClient_AdsNotificationEx);
hWrite = AdsClient.AddDeviceNotificationEx("P_Datalogger.bWrite", AdsTransMode.OnChange, 10, 0, null, typeof(bool));
}
catch
{
// MessageBox.Show("AdsClientOpen() - " + err.Message);
}
}
private void AdsClientClose()
{
try
{
// Close db
if (db.State == ConnectionState.Open)
db.Close();
AdsClient.DeleteVariableHandle(hWatchDog);
AdsClient.DeleteVariableHandle(hDone);
AdsClient.DeleteDeviceNotification(hWrite);
}
catch
{
// MessageBox.Show("AdsClientClose() - " + err.Message);
}
finally
{
AdsClient.Dispose();
}
}
private void AdsClient_AdsNotificationEx(object sender, AdsNotificationExEventArgs e)
{
try
{
if (e.NotificationHandle == hWrite)
{
if (Convert.ToBoolean(e.Value) == false)
AdsClient.WriteAny(hDone, Convert.ToBoolean(false));
else
if (SqlWriteData() == true)
AdsClient.WriteAny(hDone, Convert.ToBoolean(true));
}
}
catch (Exception err)
{
MessageBox.Show("AdsClient_AdsNotificationEx() - " + err.Message);
}
}
private void CheckIfSQLTableExist()
{
try
{
// Check db state
if (db.State != ConnectionState.Open)
db.Open();
using (DbCommand cmd = db.CreateCommand())
{
cmd.CommandText = SQLText;
cmd.ExecuteNonQuery();
cmd.Dispose();
}
// Clean up
if (db.State == ConnectionState.Open)
db.Close();
if (SqlWriteData() == true)
AdsClient.WriteAny(hDone, Convert.ToBoolean(true));
}
catch (Exception err)
{
MessageBox.Show("CheckSQLTable() - " + err.Message);
}
}
private Boolean SqlWriteData()
{
try
{
// Check symbol info
if (SqlDataAdsSymbolInfo != null)
{
AdsStream DataStream = new AdsStream(SqlDataAdsSymbolInfo.Size);
AdsBinaryReader BinReader = new AdsBinaryReader(DataStream);
StringBuilder sb = new StringBuilder("", 100);
// Read ADS logData variabels
AdsClient.Read(SqlDataAdsSymbolInfo.IndexGroup, SqlDataAdsSymbolInfo.IndexOffset, DataStream);
// Check db state
if (db.State != ConnectionState.Open)
db.Open();
if (db.State == ConnectionState.Open)
{
// Write data to SQL file
using (DbTransaction dbTrans = db.BeginTransaction())
{
using (DbCommand cmd = db.CreateCommand())
{
try
{
// Struct values
TcAdsSymbolInfo subSymbol = SqlDataAdsSymbolInfo.FirstSubSymbol;
cmd.Transaction = dbTrans;
sb.Append(string.Format("INSERT INTO tblLogData VALUES(null,"));
if (SqlDataAdsSymbolInfo.SubSymbolCount > 0)
{
for (int i = 1; i <= SqlDataAdsSymbolInfo.SubSymbolCount; i++)
{
sb.Append(string.Format("{0}", GetBinReadValues(subSymbol, BinReader)));
sb.Append(",");
subSymbol = subSymbol.NextSymbol;
}
// Remove last ","
sb.Remove(sb.Length - 1, 1);
sb.Append(");");
cmd.CommandText = sb.ToString();
cmd.ExecuteNonQuery();
dbTrans.Commit();
cmd.Dispose();
}
}
catch
{
dbTrans.Rollback();
// Close db
if (db.State == ConnectionState.Open)
db.Close();
CheckIfSQLTableExist();
return (false);
}
}
}
}
// Close db
if (db.State == ConnectionState.Open)
db.Close();
return (true);
}
else
return (false);
}
catch
{
CheckIfSQLTableExist();
return (false);
}
}
private string GetBinReadValues(TcAdsSymbolInfo AdsSymbolInfo, AdsBinaryReader BinReader)
{
try
{
switch (AdsSymbolInfo.Datatype)
{
case AdsDatatypeId.ADST_BIT: return BinReader.ReadBoolean().ToString();
case AdsDatatypeId.ADST_INT16: return BinReader.ReadInt16().ToString();
case AdsDatatypeId.ADST_INT32: return BinReader.ReadInt32().ToString();
case AdsDatatypeId.ADST_INT64: return BinReader.ReadInt64().ToString();
case AdsDatatypeId.ADST_INT8: return BinReader.ReadSByte().ToString();
case AdsDatatypeId.ADST_REAL32: return BinReader.ReadSingle().ToString().Replace(",", ".");
case AdsDatatypeId.ADST_REAL64: return BinReader.ReadDouble().ToString().Replace(",", ".");
case AdsDatatypeId.ADST_STRING: return "'" + BinReader.ReadPlcString(AdsSymbolInfo.Size).ToString() + "'";
case AdsDatatypeId.ADST_UINT16: return BinReader.ReadUInt16().ToString();
case AdsDatatypeId.ADST_UINT32: return BinReader.ReadUInt32().ToString();
case AdsDatatypeId.ADST_UINT64: return BinReader.ReadUInt64().ToString();
case AdsDatatypeId.ADST_UINT8: return BinReader.ReadByte().ToString();
case AdsDatatypeId.ADST_WSTRING: return "'" + BinReader.ReadPlcString(AdsSymbolInfo.Size).ToString() + "'";
default: return "'" + BinReader.ReadPlcString(AdsSymbolInfo.Size).ToString() + "'";
}
}
catch (Exception err)
{
MessageBox.Show("GetBinReadValues() - " + err.Message);
}
return ("");
}
private void WatchDog_Tick(object sender, EventArgs e)
{
try
{
// Check watchdog
if ((bool)(AdsClient.ReadAny(hWatchDog, typeof(bool))) == false)
{
AdsClientClose();
AdsClientOpen();
}
// Set watchdog false
AdsClient.WriteAny(hWatchDog, Convert.ToBoolean(false));
}
catch
{
AdsClientClose();
AdsClientOpen();
}
}
}
}