It working!!

I ended up doing it differently but the solutions posted here pointed me in the right direction.
For anybody struggling to get this to work, this is what I did (using HS3).
I run the below script every time a device value changes.
Code: Select all
'Log to Database for HS3
'WR. Muller
'08/03/2014
'Version: 1.0
'VB.Net script to write Homeseer 3 values to SQL Server Express Historical Database
'Add this line to Homeseer\Config\Settings.ini
' ScriptingReferences=System.Data;System.Data.Dll
' Add this line to Homeseer\Scipts\Startup.ini
' hs.RegisterStatusChangeCB("L2DH.vb","Main")
Imports System.Data.SqlClient
Sub Main(ByVal Parms As Object)
Dim dev_address As String
Dim device_valuenew, device_valueprv As Double
Dim cn As New SqlConnection("Server=192.168.2.25,1433;Database=HS3Test;User ID=sa;Password=rm7800;Trusted_Connection=False;")
hs.WriteLog("L2DH", "Script running")
dev_address = Parms(1) 'address of device
device_valuenew = Parms(2) 'new value of device
device_valueprv = Parms(3) 'previous value of device
Try
cn.Open()
hs.WriteLog("L2DB", "Connection is open")
Dim SQLComm As New SqlCommand("UPDATE dbo.Data SET EndValue='" & device_valuenew & "' WHERE DevID='" & dev_address & "' AND DateDiff(hh, GetDate(),TimeStamp) = 0" & _
"IF @@ROWCOUNT=0" & _
"INSERT INTO dbo.Data(DevID, StartValue, EndValue) VALUES('" & dev_address & "','" & device_valueprv & "','" & device_valuenew & "')", cn)
SQLComm.ExecuteNonQuery()
hs.WriteLog("L2DH", "Logged to Historical Database: Address: " & dev_address & ", New Value: " & device_valuenew)
cn.Close()
hs.WriteLog("L2DH", "Connection is closed")
'End If
Catch ex As Exception
hs.WriteLogEx("L2DH", "Error: " & ex.Message)
End Try
End Sub
The database is set-up in SQLServer. The structure is like this:
Code: Select all
USE [HS3Test]
GO
/****** Object: Table [dbo].[Data] Script Date: 16-3-2014 8:19:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Data](
[TimeStamp] [smalldatetime] NOT NULL,
[LastUpdate] [datetime] NULL,
[DevID] [nchar](15) NOT NULL,
[StartValue] [float] NULL,
[EndValue] [float] NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Data] ADD CONSTRAINT [DF_Data_timestamp] DEFAULT (dateadd(hour,datediff(hour,(0),getdate()),(0))) FOR [TimeStamp]
GO
The constraint at the end is used to truncate the Timestamp value to a full hour. The way I have the INSERT statement written in the script, it always adds a new record when a new hour has started, by just deleting the minutes and seconds, you end up with the hour value.
The data looks like this when everything is working well.

- 2014-03-16 08.19.29 am.png (24.65 KiB) Viewed 22878 times
There are still a few things I need to do:
1. Make the logging device specific; now every device value change is logged
2. Making interval a device value is logged device specific. Now everything is logged at an interval of an hour which is fine for energy, but other devices may require something different.