Rss 2.0 via FEED

About...

cc128-large_01 I recently bought a device to monitor our household energy consumption. After looking at a few I lumped for a CurrentCost Envi. this is a great little device that comes in two parts – a transmitter with jaws that wrap around the main power cable coming into your home and a desktop display unit. The communication is all wireless and I have found that it works okay through two thick brick walls.

the reason for going with this particular unit was that it has a data port that can connect to a USB port and feed it’s readings to a PC – I wanted to be able to monitor the readings on my PC and chart/analyse them at will.

imageThe communication to the PC is basically via USB, but emulating a serial port COM connection – the CurrentCost website has links to the drivers you’ll need for this.

I wanted to, not only, record the readings but to chart them (on my website), get regular updates via various notification methods and a few other bits. Unfortunately, none of the software applications listed on their website covered all the items that I wanted – so I set about writing something myself…

My initial thoughts were around just sending the data to Google PowerMeter, but at that stage the API was not public and their forums/groups were not very active (6 posts in about 18 months), so I abandoned that and decided a ‘DIY’ approach was needed. 
UPDATE: It looks like there may be some substance to it now, so that is another area to look at (another plugin)…

imageThe requirements were pretty simple – I wanted a service that grabbed the readings as they came in, decoded them into something intelligible and then pushed them out to a number of ‘modules’ that would do something with the reading. the ‘modules’ would be self contained and new modules could be added at any time. The initial modules would be :-

  • Tweet the reading at a regular interval
  • Record the reading (in a database, Xml file or the like)
  • Send the reading to a website / webservice

It seemed a simple Windows Service with a COM port would be enough to grab the reading, the readings are all in Xml so another class to parse the Xml would be needed and then for the ‘modules’ a ‘plugin’ type architecture was called for. I came up with an interface that all plugins would implement and a method of loading them in dynamically.

Each plugin would inherit from the IPowerMonitorPlugin interface and to load the plugins, each one would be specified in the app.config file with a filename and classname. The service would look at each plugin entry, load the DLL and create an instance of the plugin class :-

    private void LoadPlugins()
    {
        plugins = new ArrayList();

        NameValueCollection appSettings = ConfigurationManager.AppSettings;
        foreach (string key in appSettings.AllKeys)
        {
            if(key.ToLower().StartsWith("plugin"))
            {
                string path = AppDomain.CurrentDomain.BaseDirectory;
                string[] config = appSettings.Get(key).Split(':');
                Assembly ass = Assembly.LoadFile(path + config[0]);
                IPowerMonitorPlugin plugin = (IPowerMonitorPlugin)ass.CreateInstance(config[1]);
                if (null == plugins)
                {
                    plugins = new ArrayList();
                }
                if (!plugins.Contains(plugin))
                {
                    plugin.Init();
                    plugins.Add(plugin);
                }

            }
        }
    }

When the service was working and decoding the readings correctly, I started adding plugins – first was a simple ‘RawXmlWriterPlugin’ – this simple wrote the raw Xml reading data (Reading.RawXml) out to a text file – just to make sure it was working and we were decoding the Xml correctly.

imageThe next service was posting the data to a website – I found this great website (pachube.com) which allows you to track environmental data measurements, have multiple feeds, multiple measurements and has a lot of options for getting data in and out. The API that they provide is pretty simple to push data into and their website allows plenty of ways to visualize the data – for example here is a link to my last 24 hours energy consumption in a chart format, here is my latest temperature reading and here is an archive of all the energy data I have ever posted. there are also mash up to things like iGoogle widgets, Google’s Visualization API, Google Sketchup, iPhone Apps, Android Apps and this rather neat gauge.

From there I started the Twitter service….

 imagePachubePosterPlugin

The plugin for posting to Pachube requires that you have already create a feed with two datastreams (datastream 0 is energy and datastream 1 is temperature). You will need an API Key and the feed id. Both these items are configured in the app.config file also.

 TwitterPlugin

The plugin for ‘tweeting’ to twitter is also pretty simple – all you need is an account (username and password) and the ‘handle’ of the person/account you want to send the message to (if you want to send a direct message). You also specify the message text you wish to send (with placeholders for the energy and temperature values) an the interval (in minutes) of how frequently you wish to send the tweets.

SQL / Xml Storage Plugin

Watch this space … ;-)

Source and Package

For the time being either send me an email or post in the comments if you’d like access to the source code.

If you want to run this software yourself then here is a link to a zip file containing the full package. To get it installed, do the following :

  • imageUnzip the package contents into a folder (“C:\Program Files\PowerMonitorService\” would be good)
  • Open a command prompt and change to the folder above
  • Run the following command line…

“C:\Windows\Microsoft.NET\Framework64\v2.0.50727\InstallUtil.exe” PowerMonitorService.exe     (if you are running a 64 bit machine… or)
“C:\Windows\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe” PowerMonitorService.exe     (if you are running a 32 bit machine… or)

  • Open the PowerMonitorService.exe.config file (in Notepad) and edit your configuration as needed – save when done.
  • Now start the service (Windows..Run..services.msc, find the one named PowerMonitorService, right click and choose “Start”)

Enjoy…

GEO 51.4043388366699:-1.2875679731369

Share/Bookmark

Posted: Tuesday, May 11, 2010 5:13:16 PM (GMT Daylight Time, UTC+01:00)  #   Comments [0]
TAGS: .NET | C Sharp | Development | Software | Technical | Twitter

Yesterday on Leon's Blog, secretGeek, I noticed they had released v3.4 of TimeSnapper. One of the features that caught my eye was the ability to develop/add plugins to it.timesnapper_screen

I love plugins, I've written plugins for Windows Live Writer, Outlook, dasBlog, and more.  Everything should have an SDK or plugin'able architecture. I championed it at work and we were one of the first Archiving Vendors with a 'real' SDK (I've built demo Vista Gadgets, integration scripts, federated search providers and PowerShell commandlets for it).

Anyway, the TimeSnapper plugin model looked really clean and easy to use. Read the one page description and your ready to go (didn't even download the sample code - it was so clear how things worked there was no need).

twitpic_logoI wanted a little play around with it, so I though upload a snapshot to TwitPic would be a good idea. Opening a new project in Visual Studio, adding a reference to the ITimeSnapperPlugin.dll, create a new inherited class from ITimeSnapperPlugin and implement the interface :

 

    #region ITimeSnapperPlugin Members

    bool ITimeSnapperPlugin.Configurable
    {
        get { return true; }
    }

    void ITimeSnapperPlugin.Configure()
    {
        System.Windows.Forms.Form frm = new TwitPicPluginConfig();
        frm.ShowDialog();
    }

    string ITimeSnapperPlugin.Description
    {
        get { return "Uploads snapshots to TwitPic"; }
    }

    string ITimeSnapperPlugin.FriendlyName
    {
        get { return "TwitPic Plugin"; }
    }

    object ITimeSnapperPlugin.HandleEvent(TimeSnapperEvent TimeSnapperEvent, EventArgs args)
    {
        switch (TimeSnapperEvent)
        {
            case TimeSnapperEvent.SnapshotSaved :
                // upload it it to TwitPic
                if (IsTimeToUpload())
                {
                    string fileName = ((TimeSnapperPluginAPI.SnapshotSavedEventArgs)(args)).Activity.Filename;
                    Debug.WriteLine("Uploading " + fileName + " to TwitPic");
                    XmlDocument xmlDoc = UploadToTwitPic(fileName);
                }
                break;

            default :
                Debug.Assert(false, "Should never occur");
                break;
        }
        return null;
    }

    TimeSnapperMenuItem[] ITimeSnapperPlugin.MenuItems()
    {
        return null;
    }

    Guid ITimeSnapperPlugin.PluginID
    {
        get { return new Guid("50744334-C5A0-44f1-BE64-5BBF32FDA79D"); }
    }

    TimeSnapperEvent[] ITimeSnapperPlugin.SubscribesTo()
    {
        return new TimeSnapperEvent[] { TimeSnapperEvent.SnapshotSaved };
    }

 

All that was required was to give it a new Guid and name/description and then subscribe to the 'SnapShotSaved' event and handle the event when it was triggered.yedda_logo
To get the image uploaded to TwitPic I used some code from the excellent Yedda Twitter C# Library (just the stuff for posting image data to a url).
That all worked a breeze, but it was sending images (and posting to my twitter account) every 10 seconds (and of course it was hard coded to my username/password) - what was needed was a bit of configuration...

Luckily the plugin model provides an excellent and easy way to do this (set the Configurable property to true, and handle the Configure event). A bit more jiggery pokery, one modal dialog and an XML config file later, it was all working (configurable username, password, twitter message and frequency of updates) - although I really should do something better than store the username/password in clear text in an XML file...

If you want the plugin, just drop this dll into your %install%\plugins folder and restart TimeSnapper.

GEO: 51.4043006896973 : -1.28754603862762

Share/Bookmark

Posted: Wednesday, March 18, 2009 12:32:14 PM (GMT Standard Time, UTC+00:00)  #   Comments [2]
TAGS: .NET | C Sharp | Development | Software | Twitter

handheldgps Apparently I am rapidly becoming 'Geo Guy'. I seem to be adding Geo / Gps support and plug-ins to everything I use...plugins

I just finished adding 'Insert GPS Link' support to PockeTwit (a great little Windows Mobile twitter client - really, go and get a copy now...)
Previously I added GeoRSS support to dasBlog for individual blog posts as well as the RSS feed, and I also added geo microformat support to Windows Live Writer with my 'InsertGeoMicroformat' plugin.

So, what's next - have you got an app that needs Geo / GPS support added ?

  PockeTwitIcon   DasBlog Reflection 640x480 Green

GEO 51.4043243116043:-1.28760516643523

Share/Bookmark

Posted: Wednesday, January 21, 2009 9:40:49 PM (GMT Standard Time, UTC+00:00)  #   Comments [0]
TAGS: .NET | ASP.NET | C Sharp | Dasblog | GPS | RSS | Software | Twitter | Windows Mobile

twitter_logo Twitter is one of those applications / services that I've had trouble getting to grips with. For me it seems it's like shouting about what you are doing right now to a huge audience that is not listening. Who really cares that @kjhughes is heading to the shops to get some Mint sauce ?? Maybe I'm just not that kind of social animal, maybe I don't have enough friends using it, maybe I should 'but in' to other peoples conversations more, maybe I'm just plain boring...

I do see a use for it though (for me). It's a pretty neat way to do some remote control stuff - like set up a Media Center recording, reboot my PC, and also it's a neat way of getting updates, like new blog comment received, TV recording completed and the like....

So, right now I need to get my Outlook addin project completed, but right afterwards I'm planning an app that interfaces to twitter and accepts direct tweets as remote control instructions, and also can update me on specific events. I am also thinking about adding twitter alerts to dasBlog (on comments, posts, errors, daily reports etc)

I can see myself getting immersed in this twitter thing...

GEO 51.4043197631836:-1.28760504722595

Share/Bookmark

Posted: Sunday, January 18, 2009 9:38:10 PM (GMT Standard Time, UTC+00:00)  #   Comments [0]
TAGS: Development | Software | Twitter | Web

twitterI have been playing with Twitter recently and thought it might be neat to see if I could post a 'tweet' from PowerShell. There is a great Google Group that discusses their API. The APIs are all REST based and really easy to use - the only complexity is that you need HTTP Basic Authentication to do anything 'real'.

One of the more simple API calls is to get the public timeline. No authentication is required for this so you can simply the url into your browser and get back the data (xml format, but json and other formats are available also). Try this :Windows_PowerShell_icon

http://twitter.com/statuses/public_timeline.xml

Now, for doing an update we need the following API:

update

Updates the authenticating user's status.  Requires the status parameter specified below.  Request must be a POST.

URL: http://twitter.com/statuses/update.format

Formats: xml, json.  Returns the posted status in requested format when successful.

Parameters:

  • status.  Required.  The text of your status update.  Be sure to URL encode as necessary.  Must not be more than 160 characters and should not be more than 140 characters to ensure optimal display.

The fact it must be a POST means we have to use a HttpWebRequest (as opposed to the easier WebClient). Anyway, here is the PowerShell function :

function Send-Tweet([string]$text, [string]$username, [string]$password)

{

     $updateurl = "http://twitter.com/statuses/update.xml"

     $result = $null

     $text = [System.Web.HttpUtility]::UrlEncode($text)

 

     [System.Net.HttpWebRequest] $request = [System.Net.HttpWebRequest] [System.Net.WebRequest]::Create($updateurl)

     $request.Credentials = new-object System.Net.NetworkCredential($username, $password)

     $request.Method = "POST"

     $request.ContentType = "application/x-www-form-urlencoded"

     $param = "status=" + $text

     $sourceParam = "&source=PowerShell"

     $request.ContentLength = $param.Length + $sourceParam.Length

 

     [System.IO.StreamWriter] $stOut = new-object System.IO.StreamWriter($request.GetRequestStream(), [System.Text.Encoding]::ASCII)

     $stOut.Write($param)

     $stOut.Write($sourceParam)

     $stOut.Close()

 

     [System.Net.HttpWebResponse] $response = [System.Net.HttpWebResponse] $request.GetResponse()

     if ($response.StatusCode -ne 200)

     {

           $result = "Error : " + $response.StatusCode + " : " + $response.StatusDescription

     }

     else

     {

           $sr = New-Object System.IO.StreamReader($response.GetResponseStream())

           [xml]$xml = [xml]$sr.ReadToEnd()

           $id = $xml.status.id

           $tweet = $xml.status.text

           if ($tweet.length -gt 50) { $tweet = $tweet.Substring(0,50) + "...(truncacted)" }

           $result = "Tweet " + $id + " added : " + $tweet

     }

    

     return $result

}

And to use it :

send-tweet "I'm sending updates from PowerShell, cool or what ??" "<your_username>" "<your_password>"

 
GEO 51.4043197631836:-1.28760504722595

Share/Bookmark

Posted: Tuesday, April 01, 2008 10:23:11 AM (GMT Daylight Time, UTC+01:00)  #   Comments [1]
TAGS: PowerShell | Twitter
Copyright © 2010 Ken Hughes. All rights reserved.

Creative Commons License
This work is licensed under a Creative Commons Attribution 2.0 UK: England & Wales License.