Archive for September, 2009

Automated web-visit

September 19th, 2009

I have a webservice that I need to visit to get it to catch new stuff from RSS-feeds. But since it is hosted on a server where I cant run a cron-job I made a small script that i run from Eventghost.

On Error Resume Next

Set oXml = CreateObject("Microsoft.XMLHTTP")
oXml.Open "GET", "http://lifestream.ronnkvist.nu/cron/blaha/blaha", False
oXml.Send ""

'Remove comment to output the response
'wscript.echo oXml.ResponseText

Send text to Squeezecenter

September 18th, 2009

This VBScript will send a text to your squeezecenter and the text will be displayed on your Squeezebox.

I use it to show who is calling.

It uses w3Sockets from http://www.dimac.com/default3.asp?M=FreeDownloads/Menu.asp&P=FreeDownloads/FreeDownloadsstart.asp, so download and register it before trying this out.

Option Explicit
Dim i, oTelnet, outString, slimHost, slimPort, txtDuration, sendStop, headString, maxLengthHead, headPaddingChar, headPadding

slimHost = "192.168.100.50"	' IP-address to Squeezecenter
slimPort = "9090" ' Portnumber on the Squeezecenter (Standard is 9090)
txtDuration = "120" ' Seconds to show the text
sendStop = False ' Stop music?

headString = "Incoming call" ' Text to show on top row
maxLengthHead = 44 ' Max-length on top row
headPaddingChar = "*" ' On the sides of the text

Dim playerMac(1) ' Se example below
playerMac(0) = "00:04:20:00:aa:bb"	' Kitchen
playerMac(1) = "4d:22:6a:00:aa:bb"	' Soft squeeze
' ------------------------------------------------------------------------------------------------
' Example for 1 player
' Dim playerMac(0)
' playerMac(0) = "11:22:33:44:55:66"
'
' Example for 3 players
' Dim playerMac(2)
' playerMac(0) = "11:22:33:44:55:66"
' playerMac(1) = "aa:bb:cc:dd:ee:ff"
' playerMac(2) = "77:88:99:00:aa:bb"
' ------------------------------------------------------------------------------------------------

' Create top row
headString = " " & headString & " "
headPadding = ""
For i = 0 to (Round((maxLengthHead-Len(headString)) / 2))
	headPadding = headPadding & headPaddingChar
Next
outString = Replace(headPadding & headString & headPadding, " ", "%20") & " "

' Create row to show
if wScript.Arguments.Count <> 0 then
	For i = 0 to (wScript.Arguments.Count-1)
		outString = outString & wScript.Arguments(i) & "%20"
	Next
Else
	outString = outString & "Saknar%20parametrar%20till%20scriptet"
End if

set oTelnet = CreateObject("Socket.TCP")
With oTelnet
	.DoTelnetEmulation = True
	.TelnetEmulation = "TTY"
	.Host = slimHost & ":" & slimPort
	.Open

	' Loop thru all players
	For i = 0 to uBound(playerMac)
		' Skickar stop-kommandot
		if sendStop then
			' Stop the music
			.SendLine playerMac(i) & " button stop"
		end if

		' Send display-command
		.SendLine playerMac(i) & " display " & outString & " " & txtDuration

	Next

	.SendLine "exit"
	.Close
End With
Set oTelnet = Nothing

Dynamic thermometer-image

September 18th, 2009

If you want to create a dynamic thermometer for your webpage PHP has some capability to create and modify images.

The script below can be called with http://domotica.ronnkvist.nu/temperature-scripts/termometer.php?temp=22 to create an image like this:
22

<?php
	// Should be in even 5's (20, 25, 30 and so on)
	$maxTemp = 30;
	$minTemp = -30;

	// Where should the bar be placed?
	$barStart = 8;
	$maxHeight = 172;
	$totalBarHeight = 164;

	// Colors and what background to use
    $tmpImg = @imagecreatefrompng("termometer.png");
	$colBar = imagecolorallocate($tmpImg, 208, 33, 33);
	$colBlack = imagecolorallocate($tmpImg, 0, 0, 0);

	// Temperature-lines
	imageline($tmpImg, 1, $barStart+(($totalBarHeight/6) * 0), 22, $barStart+(($totalBarHeight/6) * 0), $colBlack);
	imageline($tmpImg, 1, $barStart+(($totalBarHeight/6) * 1), 22, $barStart+(($totalBarHeight/6) * 1), $colBlack);
	imageline($tmpImg, 1, $barStart+(($totalBarHeight/6) * 2), 22, $barStart+(($totalBarHeight/6) * 2), $colBlack);
	imageline($tmpImg, 1, $barStart+(($totalBarHeight/6) * 3), 22, $barStart+(($totalBarHeight/6) * 3), $colBlack);
	imageline($tmpImg, 1, $barStart+(($totalBarHeight/6) * 4), 22, $barStart+(($totalBarHeight/6) * 4), $colBlack);
	imageline($tmpImg, 1, $barStart+(($totalBarHeight/6) * 5), 22, $barStart+(($totalBarHeight/6) * 5), $colBlack);
	imageline($tmpImg, 1, $barStart+(($totalBarHeight/6) * 6), 22, $barStart+(($totalBarHeight/6) * 6), $colBlack);

	// Text-strings by the lines
	imagestring($tmpImg, 1, 25, $barStart+(($totalBarHeight/6) * 0)-4, " 30", $colBlack);
	imagestring($tmpImg, 1, 25, $barStart+(($totalBarHeight/6) * 1)-4, " 20", $colBlack);
	imagestring($tmpImg, 1, 25, $barStart+(($totalBarHeight/6) * 2)-4, " 10", $colBlack);
	imagestring($tmpImg, 1, 25, $barStart+(($totalBarHeight/6) * 3)-4, "  0", $colBlack);
	imagestring($tmpImg, 1, 25, $barStart+(($totalBarHeight/6) * 4)-4, "-10", $colBlack);
	imagestring($tmpImg, 1, 25, $barStart+(($totalBarHeight/6) * 5)-4, "-20", $colBlack);
	imagestring($tmpImg, 1, 25, $barStart+(($totalBarHeight/6) * 6)-4, "-30", $colBlack);

	$temperature = trim($_GET['temp']);
	if ($temperature == "") {
		$temperature = 0;
	}

	// Calculate the bar-height
	$tempSpan = (0 - $minTemp) + $maxTemp;
	if ($temperature == 0) {
		$barHeight = ($totalBarHeight / 2);
	} elseif ($temperature > 0) {
		if ($temperature >= $maxTemp) {
			$barHeight = $totalBarHeight;
		} else {
			$barHeight = ($totalBarHeight / 2) + (($temperature / $maxTemp) * ($totalBarHeight / 2));
		}
	} else {
		if ($temperature <= $minTemp) {
			$barHeight = 0;
		} else {
			$barHeight = ($totalBarHeight / 2) - (($totalBarHeight / 2) * ((0-$temperature) / (0-$minTemp)));
		}
	}

	// Temperature-bar
	imagefilledrectangle($tmpImg, 7, $barStart+($totalBarHeight-$barHeight), 13, 172, $colBar);

	// Create the image
	header( "Content-type: image/png" );
	imagepng($tmpImg );
?>

The background image is found at http://domotica.ronnkvist.nu/temperature-scripts/termometer.png

Log diskspace

September 18th, 2009

If you want to log the usage of diskspace on a computer it’s not that hard.. you just need some place to store the data and a script that runs at given intervals.

I have a table in my SQL Server.

CREATE TABLE Diskspace(
	index bigint IDENTITY(1,1) NOT NULL,
	TimeStamp datetime NOT NULL,
	FreePercent decimal(18, 3) NOT NULL,
	DriveLetter char(1) NOT NULL,
 CONSTRAINT PK__Diskspace__49C3F6B7 PRIMARY KEY CLUSTERED
(
	index ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON PRIMARY
) ON PRIMARY

Then I have a VBScript that runs every five minutes (via Eventghost). You need to change databasename, user and password.

Set oDb = createobject("ADODB.Connection")
oDb.ConnectionString = "DRIVER={SQL Server Native Client 10.0};SERVER=localhost;DATABASE=TheDatabaseName;UID=MyUserName;PWD=SomePassword; OPTION=3"
oDb.Open

Set oWmiService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set oDisks = oWmiService.ExecQuery("Select * from Win32_LogicalDisk Where DriveType = 3")

For Each oDisk In oDisks
    sPercent = Replace(Round((oDisk.FreeSpace / oDisk.Size)*100, 1), ",", ".")
    sDisk = uCase(Replace(oDisk.DeviceID, ":", ""))

	sSql = "INSERT INTO diskspace (TimeStamp, FreePercent, DriveLetter) VALUES (GETDATE(), '" & sPercent & "', '" & sDisk & "')"
	WScript.Echo sSql
	oDb.Execute(sSql)
Next

oDb.Close

As easy as that…

Create event in EventGhost

September 13th, 2009

There are two easy ways of creating events in EventGhost.

First by commandline:

C:\Program Files\EventGhost\EventGhost.exe -E MyTestEventFromCmd
C:\Program Files\EventGhost\EventGhost.exe -E MyTestEventFromCmd WithPayload

And then via VBScript

Dim oEventGhost
Set oEventGhost = CreateObject("EventGhost")
oEventGhost.TriggerEvent "MyTestEvent"
oEventGhost.TriggerEvent "AndSomeOtherEvent", "WithPayload"
Set oEventGhost = Nothing

With that you can get EventGhost to react on loads of stuff… why not react on incoming phonecalls?
eventghostevents

Last temperature reading

September 13th, 2009

If you want to create a webpage or something similar you might want to show off the latest temperature reading.

This script will give you last reading in every table, if you want to exclude / include specific tables look at the “AND Name NOT LIKE” lines.

IF EXISTS(SELECT TABLE_NAME FROM TEMPDB.INFORMATION_SCHEMA.TABLES
      WHERE TABLE_NAME LIKE '#TemperatureLast%')
   DROP TABLE #TemperatureLast
GO

CREATE TABLE #TemperatureLast (
   MSureName SYSNAME NOT NULL,
   TimeStamp DATETIME NOT NULL,
   Temperature DECIMAL(18, 3) NOT NULL,
)

DECLARE
   @query VARCHAR(2000),
   @currTable SYSNAME

DECLARE tablesCurr CURSOR
	FOR
	SELECT Name as TableName
		FROM  sysobjects
		WHERE xtype = 'U'
			AND Name NOT LIKE '%space%'
			-- AND Name NOT LIKE '%something%'
			-- AND Name LIKE 'Temperature%'
		ORDER BY TableName
	FOR READ ONLY

OPEN tablesCurr
   FETCH NEXT FROM tablesCurr INTO @currTable
   WHILE (@@FETCH_STATUS <> -1) BEGIN

		SET @Query = 'SELECT TOP 1 ''' + @currTable + ''', TimeStamp, Temperature FROM ' + @currTable + ' ORDER BY TimeStamp DESC'
		INSERT #TemperatureLast EXEC (@query)

      FETCH NEXT FROM tablesCurr INTO @currTable
   END
CLOSE tablesCurr
DEALLOCATE tablesCurr

SELECT * FROM #TemperatureLast
DROP TABLE #TemperatureLast

Spring and autumn

September 13th, 2009

According to SMHI autumn is when the average temperature of the day is falling and is between 0 and 10 degrees. And spring is when it’s rising and between 0 and 10 degrees.

Reference: http://www.smhi.se/cmp/jsp/polopoly.jsp?d=5938&l=sv

This “little” script will give you a resulting table with average temperature on UtomhusNorr calculated with the last five days.

IF EXISTS(SELECT TABLE_NAME FROM TEMPDB.INFORMATION_SCHEMA.TABLES
      WHERE TABLE_NAME LIKE '#TemperatureAvg%')
   DROP TABLE #TemperatureAvg
GO

CREATE TABLE #TemperatureAvg (
   TimeStamp DATETIME NOT NULL,
   Temperature DECIMAL(18, 3) NOT NULL,
)

DECLARE
   @query VARCHAR(2000),
   @currDate DATETIME

DECLARE dateCurr CURSOR
   FOR
   SELECT DISTINCT CAST(CONVERT(CHAR(10),TimeStamp,20) AS DATETIME) as TempDates
   FROM UtomhusNorr
   WHERE TimeStamp &gt; DATEADD(month, -1, GETDATE())
   ORDER BY TempDates DESC
   FOR READ ONLY

OPEN dateCurr
   FETCH NEXT FROM dateCurr INTO @currDate
   WHILE (@@FETCH_STATUS &lt;&gt; -1) BEGIN
      SET @Query = 'SELECT MAX(TimeStamp) AS TimeStamp, AVG(Temperature) as Temperature FROM UtomhusNorr WHERE TimeStamp &gt; DATEADD(day, -5, ''' + CONVERT(NVARCHAR(32), @currDate) + ''') AND TimeStamp &lt; ''' + CONVERT(NVARCHAR(32), @currDate) + ''''
      INSERT #TemperatureAvg EXEC (@query)

      FETCH NEXT FROM dateCurr INTO @currDate
   END
CLOSE dateCurr
DEALLOCATE dateCurr

SELECT TimeStamp, Temperature AS AvgTemp5daysBack FROM #TemperatureAvg
DROP TABLE #TemperatureAvg

Migrate data from MySQL to SQL Server

September 13th, 2009

Since I work with MS SQL Server (and have done for the last 10 years) I converted the MySQL-databases in MSure to MS SQL.
This script will copy 4 tables, easy to add more.
Remember to change the ConnectionString’s to your settings. (server, database, user and password)

Set oMySQL = createobject("ADODB.Connection")
oMySQL.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver};SERVER=localhost;DATABASE=msure;UID=msure;PWD=abc123; OPTION=3"
oMySQL.Open

Set oSql = createobject("ADODB.Connection")
oSql.ConnectionString = "DRIVER={SQL Server Native Client 10.0};SERVER=localhost;DATABASE=msure;UID=MSure;PWD=abc123; OPTION=3"
oSql.Open

CopyTable "UtomhusNorr"
CopyTable "UtomhusOster"
CopyTable "UtomhusSoder"
CopyTable "UtomhusVaster"

sub CopyTable(sTable)
  set oSource = oMySQL.Execute("SELECT * FROM " & sTable)
  do while not oSource.Eof

    sSql = "INSERT INTO " & sTable & " (TimeStamp, Temperature) VALUES ('" & oSource("TimeStamp") & "', '" & Replace(oSource("Temperature"),",", ".") & "')"

    wscript.echo sSql
    oSql.Execute sSql

    oSource.MoveNext
  Loop
End Sub

oMySQL.Close
oSql.Close

Automated web-visit

September 13th, 2009

If you have a webpage that you need to visit every xx minutes/hours to get some scripts to work, you can visit it via a VBScript…

On Error Resume Next
Dim oXml
Const cURL = "http://www.something.com/path/automate.php"

Set oXml = CreateObject("Microsoft.XMLHTTP")
oXml.Open "GET", cURL, False
oXml.Send ""

Tweet something

September 13th, 2009

It’s easy to tweet from the command-line… Google up some curl command-line application and download it.

curl --user MyTwitterUser:MyPassword --data &quot;source=haStatus&amp;status=This is what I want to tweet&quot; http://twitter.com/statuses/update.json

I have a “source” called “haStatus” (Has Status or Home Automation Status) that is registered with Twitter. If you don’t want to use that one as source, just remove source=haStatus& from the command-line.

Since it’s a quite long commandline I have a small cmd-file that does the trick for me:

@echo off
h:\scripts\bin\curl --user MyTwitterUser:MyPassword --data &quot;source=haStatus&amp;status=%*&quot; http://twitter.com/statuses/update.json

time /T &gt;H:\Scripts\Log\lastTweet.log
date /T &gt;&gt;H:\Scripts\Log\lastTweet.log
echo %* &gt;&gt;H:\Scripts\Log\lastTweet.log