<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Ian Mercer</title>
	<atom:link href="http://blog.abodit.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.abodit.com</link>
	<description>Living in the World&#039;s Smartest House</description>
	<lastBuildDate>Sat, 21 Apr 2012 15:41:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>My first programme [sic]</title>
		<link>http://blog.abodit.com/2012/04/my-first-programme-sic/</link>
		<comments>http://blog.abodit.com/2012/04/my-first-programme-sic/#comments</comments>
		<pubDate>Sat, 21 Apr 2012 15:38:09 +0000</pubDate>
		<dc:creator>Ian Mercer</dc:creator>
				<category><![CDATA[My News]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=1728</guid>
		<description><![CDATA[At the risk of looking seriously old, here&#8217;s something found on a paper tape bearing the title &#8220;Ian&#8217;s First Programme&#8221; &#8230; Can you identify the language and the computer it ran on?]]></description>
			<content:encoded><![CDATA[<p>At the risk of looking seriously old, here&#8217;s something found on a paper tape bearing the title &#8220;Ian&#8217;s First Programme&#8221; &#8230;</p>
<pre class="brush: plain; title: ; notranslate">
BEGIN INTEGER A,B,C,D,E,F,G,ANS'
READ A,B,C,D,E,F,G'
ANS:=(A+B+C+D+E+F+G)/7'
PRINT ANS'
END'
</pre>
<p>Can you identify the language <em>and </em> the computer it ran on?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2012/04/my-first-programme-sic/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Building a better .NET State Machine</title>
		<link>http://blog.abodit.com/2012/04/building-a-better-net-state-machine/</link>
		<comments>http://blog.abodit.com/2012/04/building-a-better-net-state-machine/#comments</comments>
		<pubDate>Sun, 15 Apr 2012 07:38:27 +0000</pubDate>
		<dc:creator>Ian Mercer</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Nuget]]></category>
		<category><![CDATA[State Machine]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=1723</guid>
		<description><![CDATA[There are several state machine implementations for .NET out there but, sadly, none of them met all of the requirements I have for a state machine. These are:- 1) Well written using encapsulation and other good practices 2) Able to be easily serialized to disk 3) Able to handle temporal events easily (After &#8230; At <a href="http://blog.abodit.com/2012/04/building-a-better-net-state-machine/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>There are several state machine implementations for .NET out there but, sadly, none of them met all of the requirements I have for a state machine.  These are:-</p>
<p>1) Well written using encapsulation and other good practices<br />
2) Able to be easily serialized to disk<br />
3) Able to handle temporal events easily (After &#8230; At &#8230; Every &#8230;)<br />
4) Disk serialized form must expose a property saying when it next needs to be fetched from disk to run<br />
5) Implements hierarchical states with entry and exit actions</p>
<p>So I built one, and have made the source code available on Nuget so you can add it to any project easily without any extra DLLs.</p>
<p>Look for &#8220;<a href="https://nuget.org/packages/AboditStateMachine/0.1.1353" title="Abodit State Machine on Nuget">AboditStateMachine</a>&#8221; on Nuget to download it.  The download includes a sample state machine documented to show off some of its capabilities.</p>
<p>Defining states is easy, just give them a name and specify their parent state if any:-</p>
<pre class="brush: csharp; title: ; notranslate">
        public static readonly State UnVerified = AddState(&quot;UnVerified&quot;);

        public static readonly State Verified = AddState(&quot;Verified&quot;);

        // States are hierarchical.  If you are in state VerifiedRecently you are also in is parent state Verified.

        public static readonly State VerifiedRecently = AddState(&quot;Verified recently&quot;, parent: Verified);
        public static readonly State VerifiedAWhileAgo = AddState(&quot;Verified a while ago&quot;, parent: Verified);
</pre>
<p>You can use any other type that&#8217;s <strong>IEquatable<T></strong> as an Event type or you can use the provided Event class:</p>
<pre class="brush: csharp; title: ; notranslate">
        private static Event eUserVerifiedEmail = new Event(&quot;User verified email&quot;);
        private static Event eScheduledCheck = new Event(&quot;Scheduled Check&quot;);
        private static Event eBeenHereAWhile = new Event(&quot;Been here a while&quot;);
</pre>
<p>The state machine itself is specified in a static constructor so it runs just once no matter how many instances of the state machine you create.  Each method is provided with an instance of the state machine &#8216;m&#8217; as well as the state &#8216;s&#8217; and the event &#8216;e&#8217; as appropriate:</p>
<pre class="brush: csharp; title: ; notranslate">
        static DemoStatemachine()
        {
            UnVerified
                    .OnEnter((m, s, e) =&gt;
                        {
                            // States can execute code when they are entered or when they are left
                            // In this case we start a timer to bug the user until they confirm their email
                            m.Every(new TimeSpan(hours: 10, minutes:0, seconds:0), eScheduledCheck);

                            // You can also set a reminder to happen at a specific time, or after a given interval just once
                            m.At(new DateTime(DateTime.Now.Year+1, 1, 1), eScheduledCheck);
                            m.After(new TimeSpan(hours: 24, minutes: 0, seconds: 0), eScheduledCheck);

                            // All necessary timing information is serialized with the state machine
                            // The serialized state machine also exposes a property showing when it next needs to be woken up
                            // External code will need to call the Tick(utc) method at that time to trigger the next temporal event
                        })
                    .When(eScheduledCheck, (m, s, e) =&gt;
                    {
                        Trace.WriteLine(&quot;Here is where we would send a message to the user asking them to verify their email&quot;);
                        // We return the current state 's' rather than 'UnVerified' in case we are in a child state of 'Unverified'
                        // This makes it easy to handle hierarchical states and to either change to a different state or stay in the same state
                        return s;
                    })
                    .When(eUserVerifiedEmail, (m, s, e) =&gt;
                    {
                        Trace.WriteLine(&quot;The user has verified their email address, we are done (almost)&quot;);
                        // Kill the scheduled check event, we no longer need it
                        m.CancelScheduledEvent(eScheduledCheck);
                        // Start a timer for one last transition
                        m.After(new TimeSpan(hours:24, minutes:0, seconds:0), eBeenHereAWhile);
                        return VerifiedRecently;
                    });

            VerifiedRecently
                    .When(eBeenHereAWhile, (m, s, e) =&gt;
                    {
                        Trace.WriteLine(&quot;User has now been a member for over 24 hours - give them additional priviledges for example&quot;);
                        // No need to cancel the eBeenHereAWhile event because it wasn't auto-repeating
                        //m.CancelScheduledEvent(eBeenHereAWhile);
                        return VerifiedAWhileAgo;
                    });

            Verified.OnEnter((m, s, e) =&gt;
                {
                    Trace.WriteLine(&quot;The user is now fully verified&quot;);
                });

            VerifiedAWhileAgo.OnEnter((m, s, e) =&gt;
                {
                    Trace.WriteLine(&quot;The user has been verified for over 24 hours&quot;);
                });

        }
</pre>
<p>With your state machine defined you can now create instances of it, trigger events on them, serialize them to disk, fetch them back, carry on eventing on them, &#8230;</p>
<pre class="brush: csharp; title: ; notranslate">
            DemoStatemachine demoStateMachine = new DemoStatemachine(DemoStatemachine.UnVerified);

            // At the time specified in demoStateMachine.NextTimedEventAt you reload the state machine from disk and call
            demoStateMachine.Tick(DateTime.UtcNow);

            // When the user verifies their email address you call ...
            demoStateMachine.VerifiesEmail();

            // At any other time you can examine the current state, act on the state changed event, ...
</pre>
<p>I hope you find this new state machine implementation useful, and if you have any feedback, do please send it my way.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2012/04/building-a-better-net-state-machine/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Internet of Dogs</title>
		<link>http://blog.abodit.com/2012/03/the-internet-of-dogs/</link>
		<comments>http://blog.abodit.com/2012/03/the-internet-of-dogs/#comments</comments>
		<pubDate>Sun, 25 Mar 2012 21:14:32 +0000</pubDate>
		<dc:creator>Ian Mercer</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Home Automation]]></category>
		<category><![CDATA[My News]]></category>
		<category><![CDATA[GreenGoose]]></category>
		<category><![CDATA[IOT]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=1714</guid>
		<description><![CDATA[In my previous post about GreenGoose I described my initial experiences with this &#8220;Internet Of Things in a box&#8221; product. Recently I&#8217;ve been trying their API and have integrated it into my Home Automation System. Click image to see it all. The initial integration was easy, I used the new ASP.NET WebApi Core Libraries (from <a href="http://blog.abodit.com/2012/03/the-internet-of-dogs/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>In my <a href="/2012/03/greengoose-review/">previous post about GreenGoose</a> I described my initial experiences with this &#8220;Internet Of Things in a box&#8221; product.  Recently I&#8217;ve been trying their API and have integrated it into my Home Automation System.</p>
<p>Click image to see it all.<br />
<a href="http://blog.abodit.com/wp-content/uploads/2012/03/EllieOnLine.png"><img src="http://blog.abodit.com/wp-content/uploads/2012/03/EllieOnLine.png" alt="" title="EllieOnLine" width="1026" height="283" class="aligncenter size-full wp-image-1715" /></a></p>
<p>The initial integration was easy, I used the new ASP.NET WebApi Core Libraries (from Nuget) together with Newtonsoft Json.Net.  GreenGoose&#8217;s datetime format is somewhat quirky but hopefully they&#8217;ll move to a more standard one soon.  They are, however, also about to switch to OAuth so it&#8217;s going to require some more work when that happens.  </p>
<p>Aside from a few simple WebAPI calls and some Json parsing the rest was just a matter of connecting up the appropriate TimeSeries classes that I use to track values that vary over time, declaring a few graphs, and deciding what to log.  With that in place I can now spin up a home automation &#8216;sensor&#8217; corresponding to any GreenGoose sensor Id and my home automation system will add all of the relevant graphs and charts, triggers and more for that device.</p>
<p>What&#8217;s interesting is that a single sensor potentially serves a couple of different purposes.  The dog collar sensor for example polls regularly back to the base station so it can potentially be used to sense both how much exercise the dog has had but also simply whether the dog is at home or not which could be really handy for anyone with a dog that&#8217;s learned to ignore the invisible fence!  Each sensor can, through the TimeSeries objects also offer additional data and triggers that can be used elsewhere in the home, for example, an alert if the dog was walked less than half and hour each day.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2012/03/the-internet-of-dogs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Juvenile Red-Tailed Hawk on the fence today</title>
		<link>http://blog.abodit.com/2012/03/juvenile-red-tailed-hawk-on-the-fence-today/</link>
		<comments>http://blog.abodit.com/2012/03/juvenile-red-tailed-hawk-on-the-fence-today/#comments</comments>
		<pubDate>Sun, 18 Mar 2012 22:03:36 +0000</pubDate>
		<dc:creator>Ian Mercer</dc:creator>
				<category><![CDATA[Photography]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=1710</guid>
		<description><![CDATA[I was fortunate to find this fine young red-tailed hawk sitting on the fence today (click to enlarge):]]></description>
			<content:encoded><![CDATA[<p>I was fortunate to find this fine young red-tailed hawk sitting on the fence today (click to enlarge):</p>
<p><a href="http://blog.abodit.com/wp-content/uploads/2012/03/474632_10150612287777951_755432950_9218770_1097169115_o.jpg"><img src="http://blog.abodit.com/wp-content/uploads/2012/03/474632_10150612287777951_755432950_9218770_1097169115_o-1024x576.jpg" alt="Juvenile Red-Tailed Hawk" title="Juvenile Red-Tailed Hawk" width="1024" height="576" class="aligncenter size-large wp-image-1708" /></a></p>
<p><a href="http://blog.abodit.com/wp-content/uploads/2012/03/476434_10150612145502951_755432950_9218061_1381989489_o.jpg"><img src="http://blog.abodit.com/wp-content/uploads/2012/03/476434_10150612145502951_755432950_9218061_1381989489_o-1024x576.jpg" alt="Juvenile Red-Tailed Hawk" title="Juvenile Red-Tailed Hawk" width="1024" height="576" class="aligncenter size-large wp-image-1709" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2012/03/juvenile-red-tailed-hawk-on-the-fence-today/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>GreenGoose Review</title>
		<link>http://blog.abodit.com/2012/03/greengoose-review/</link>
		<comments>http://blog.abodit.com/2012/03/greengoose-review/#comments</comments>
		<pubDate>Wed, 14 Mar 2012 06:54:50 +0000</pubDate>
		<dc:creator>Ian Mercer</dc:creator>
				<category><![CDATA[Home Automation]]></category>
		<category><![CDATA[quantified self]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=1690</guid>
		<description><![CDATA[One of the conclusions I&#8217;ve reached from my many years experimenting with home automation is that one of the missing ingredients is affordable, wireless sensors with long battery life. One of the best solutions I&#8217;ve found so far is to use CADDX alarm sensors because they are wireless, have exceptionally long battery life and can <a href="http://blog.abodit.com/2012/03/greengoose-review/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-thumbnail wp-image-1685" title="GreenGoose Hardware" src="http://blog.abodit.com/wp-content/uploads/2012/03/Unpacking-1-150x150.jpg" alt="GreenGoose Hardware" width="150" height="150" /><br />
One of the conclusions I&#8217;ve reached from my many years experimenting with home automation is that one of the missing ingredients is affordable, wireless sensors with long battery life. One of the best solutions I&#8217;ve found so far is to use CADDX alarm sensors because they are wireless, have exceptionally long battery life and can be connected to a PC using a reliable serial connection. Proponents of the <em>Internet of Things</em> talk about every device having an IP address and recently some wifi-connected sensors have appeared. I&#8217;m skeptical of that approach: it seems unlikely however that they will get the kind of battery life you need to be practical and you really don&#8217;t need a separate IP address for every single sensor.</p>
<p>What I believe we need is a hub device that connects to the internet and then really cheap wireless sensors that communicate back through it using a connection technology that requires much less power than wifi. So when <a href="http://greengoose.com">GreenGoose</a> recently announced their sensors I was one of the first to place a pre-order and this week I received one of their first device shipments. This blog post discusses some of my initial impressions.</p>
<p>First off I have to say I don&#8217;t like the egg shape or the color of the hub. Fortunately it&#8217;s in the wiring closet next to the router so I don&#8217;t need to see it.</p>
<p><img class="alignright size-thumbnail wp-image-1686" title="GreenGoose Mounting on food container" src="http://blog.abodit.com/wp-content/uploads/2012/03/Unpacking-2-150x150.jpg" alt="GreenGoose Mounting on food container" width="150" height="150" />The sensors themselves are remarkably small considering they claim a battery life of 1.5 years and the fact that they include both a sensor, some intelligence and a wireless transmitter. Two of the sensors were stick-on devices which I stuck on the dog and cat food containers respectively even though one was labelled food and the other treats. The other two were shaped like dog tags. Here you can see one of the stick-on sensors mounted inside the lid of a dog food container.  You can view a teardown of the GreenGoose sensors and hub on <a title="GreenGoose Teardown" href="http://www.flickr.com/photos/38416248@N07/sets/72157629557903549">this Flickr page</a>.</p>
<p>Connecting the sensors up to my account took two attempts, three sensors were found on the first try and the remaining sensor on the second try. That&#8217;s apparently fairly normal. There were a few configuration problems with my account and the iPad software (actually iPhone software in 2x mode) and the web site is clearly still under development with daily bug fixes and improvements happening each time I try it. But, I have to say the folks at GreenGoose have been incredibly responsive to my every comment or bug report.</p>
<p><img class="aligncenter size-full wp-image-1691" title="GreenGoose User Interface" src="http://blog.abodit.com/wp-content/uploads/2012/03/GreenGooseUI.png" alt="GreenGoose User Interface" width="582" height="539" /><br />
So now I&#8217;m getting reports from the sensors on their web site and overall things seem to be working quite well. It&#8217;s certainly not 100% reliable yet in terms of capturing every event so I don&#8217;t think these are going to be the perfect home automation sensor that I&#8217;m still waiting and hoping for, but, in all fairness, the folks at GreenGoose aren&#8217;t selling these sensors as alarm panel sensors, but as more of a fun game tracking activity and reminding people to go walk the dog. I&#8217;ll update this blog when I have a better idea exactly how accurate they are at capturing activity.</p>
<p>The biggest gotcha however is that my original plan to use the sensors on different devices has been somewhat thwarted by the realization that <strong>each different sensor type is calibrated to detect a specific kind of motion. You cannot re-purpose them like you would a normal motion or contact sensor</strong>. So putting the <em>dog collar sensor</em> on my key chain isn&#8217;t producing the results I&#8217;d expected. We will have to wait for GreenGoose to come out with sensors to put on doors, cars, shoes, cellphones, iPads and whatever else we want to track. I&#8217;ve suggested to GreenGoose that they explain this better on their web site as many hobbyists will try to repurpose the sensors for applications other than the ones for which they were designed.</p>
<p>Another issue at the moment is that the web site forces you to assign the sensors to a specific pet and they only support one pet name. They say they&#8217;ll add multiple-pet support soon.</p>
<p>Next I plan to try their API and will report back on how that goes.</p>
<blockquote><p>Bottom line: this is remarkable technology &#8211; a mems accelerometer, some computing power, a radio transmitter and a 1.5 year battery in a package the size of a stick of gum is quite a feat of engineering. Some of the software is a bit &#8216;immature&#8217; but it&#8217;s improving daily. Overall this is a very affordable way to try out some &#8216;quantified self&#8217; ideas for yourself, it might help you walk the dog more often (our dogs wouldn&#8217;t let you forget to do that, but maybe yours would!), and the support from GreenGoose has been great.</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2012/03/greengoose-review/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A simple state machine in C#</title>
		<link>http://blog.abodit.com/2012/01/a-simple-state-machine-in-c/</link>
		<comments>http://blog.abodit.com/2012/01/a-simple-state-machine-in-c/#comments</comments>
		<pubDate>Sat, 07 Jan 2012 08:31:35 +0000</pubDate>
		<dc:creator>Ian Mercer</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=1673</guid>
		<description><![CDATA[Within the Abodit Natural Language engine there is often a need to track the state of various elements of a conversation. For example, is the user logged in or not, have they verified their email address, what instructional text have we offered them so far, &#8230; To make this easier I decided to add a <a href="http://blog.abodit.com/2012/01/a-simple-state-machine-in-c/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>Within the Abodit Natural Language engine there is often a need to track the state of various elements of a conversation.  For example, is the user logged in or not, have they verified their email address, what instructional text have we offered them so far, &#8230;</p>
<p>To make this easier I decided to add a simple state machine class to the Abodit utilities provided with my NLP Engine.  There are, of course, a plethora of existing state machines on the web.  Some of them are based on older .NET technology lacking use of generics and functional programming techniques.  Others go overboard with fluent-style interfaces when a simple inheritance-based approach from an abstract base class would actually be simpler, less code, and more powerful.  Most of them I didn&#8217;t discover until after I&#8217;d built this one.  In any case, it&#8217;s always a good learning exercise to try to build something from scratch, so here goes &#8230;</p>
<p>First let&#8217;s take a look at the result.  Here&#8217;s how you can define a state machine that derives from this new StateMachine class:</p>
<pre class="brush: csharp; title: ; notranslate">
      public class LoginOutStatemachine : StateMachine&lt;LoginOutStatemachine&gt;
    {
        public static void ReportEnter(LoginOutStatemachine m, Event e, State state)
        {
            Console.WriteLine(m.User + &quot; entered state &quot; + state + &quot; via &quot; + e);
        }

        public static void ReportLeave(LoginOutStatemachine m, State state, Event e)
        {
            Console.WriteLine(m.User + &quot; left state &quot; + state + &quot; via &quot; + e);
        }

        public static State Initial = new State(&quot;Initial&quot;, ReportEnter, ReportLeave);
        public static State LoggedIn = new State(&quot;Logged In&quot;, ReportEnter, ReportLeave);
        public static State LoggedOut = new State(&quot;Logged Out&quot;, ReportEnter, ReportLeave);
        public static State Deleted = new State(&quot;Deleted&quot;, ReportEnter, ReportLeave);

        private static Event eLogsIn = new Event(&quot;Logs In&quot;);
        private static Event eLogsOut = new Event(&quot;Logs Out&quot;);
        private static Event eDeletesAccount = new Event(&quot;Account Deleted&quot;);

        static LoginOutStatemachine()
        {
            Initial
                    .When(eLogsIn, (m, s, e) =&gt; { Console.WriteLine(&quot;Logging in &quot; + m.User); return LoggedIn; })
                    .When(eDeletesAccount, (m, s, e) =&gt; { Console.WriteLine(&quot;Deleting account &quot; + m.User); return Deleted; });
            LoggedIn
                    .When(eLogsOut, (m, s, e) =&gt; { Console.WriteLine(&quot;Logging out &quot; + m.User); return LoggedOut; })
                    .When(eDeletesAccount, (m, s, e) =&gt; { Console.WriteLine(&quot;Account deleted &quot; + m.User); return Deleted; });
            LoggedOut
                    .When(eLogsIn, (m, s, e) =&gt; { Console.WriteLine(&quot;Logging in &quot; + m.User); return LoggedIn; })
                    .When(eDeletesAccount, (m, s, e) =&gt; { Console.WriteLine(&quot;Account deleted &quot; + m.User); return Deleted; });
        }

        public User User { get; private set; }

        public LoginOutStatemachine(State initial, User user)
            : base(initial)
        {
            this.User = user;
        }

        // Expose the events as public methods

        public void LogsIn()
        {
            this.EventHappens(eLogsIn);
        }

        public void LogsOut()
        {
            this.EventHappens(eLogsOut);
        }

        public void DeletesAccount()
        {
            this.EventHappens(eDeletesAccount);
        }
    }
</pre>
<p>As you can see, you define the <i>states</i> and the <i>events</i> for the state machine using static definitions.  (Events trigger state changes and associated actions).  Typically I&#8217;ll make the States public but the events private and instead provide method calls for each event that is allowed.</p>
<p>Each state can also have an Action that fires on entering the state and an action that fires on leaving the state and each action is provided with all of the parameters it might need (the state machine instance, the state it is going to or from, and the event that caused the transition to happen).  In this case all of these entry and exit events are linked to the same method that simply reports what happened.</p>
<p>To define what happens when an given event is received by the state machine you create the static constructor as shown and then, using a fluent interface you define for each initial state, the transition to a new state by calling the <i>When</i> method passing it the event and the action to take when that event happens from the initial state specified.  At the end of the method you must return the new state:</p>
<pre class="brush: csharp; title: ; notranslate">
Initial
  .When(eLogsIn, (m, s, e) =&gt; { Console.WriteLine(&quot;Logging in &quot; + m.User); return LoggedIn; })
  .When(eDeletesAccount, (m, s, e) =&gt; { Console.WriteLine(&quot;Deleting account &quot; + m.User); return Deleted; });
</pre>
<p>The (m, s, e) parameters give you the state machine itself, the state you are coming from and the event that has been received.  By passing your method all of these values I make it easy for you to access any properties of the state machine itself (e.g. a User object) and also allow you to write a single method that handles more than one event type or more than one initial state but which can still be parameterized by those values.</p>
<p>The other minor trick is that the StateMachine class is a generic in the state machine class itself.  A small trick that allows access to `T` as the type of the inherited state machine class and thus to any additional properties you define there.</p>
<p>Note how your state machine class can have properties like `User` which allows the transition code to access any additional data it needs.  You create an instance of the state machine for each user (all the heavy lifting is done in the static definition so the state machine remains a light-weight object).</p>
<p>In the case of the NLP engine you can pass an `IListener` in to the state machine constructor also so that you can `Say` messages back to the user.  Since the state machine is such a light-weight object you can afford to create it for each message interaction with the user and the information you need to persist is just the current state (which I will soon make into a string lookup).</p>
<p>If you want to use the actual state machine in any of your own projects (gratis), here&#8217;s the current code:</p>
<pre class="brush: csharp; title: ; notranslate">
    /// &lt;summary&gt;
    /// A state machine allows you to track state and to take actions when states change
    /// This state machine provides a fluent interface for defining states and transitions
    /// &lt;/summary&gt;
    /// &lt;remarks&gt;
    /// Nasty generic of self so we can refer to the inheriting class in here
    /// &lt;/remarks&gt;
    [Serializable]
    [DebuggerDisplay(&quot;Current State = {CurrentState.Name}&quot;)]
    public abstract class StateMachine&lt;T&gt; where T:StateMachine&lt;T&gt;
    {
        public State CurrentState { get; set; }

        public StateMachine(State initial)
        {
            this.CurrentState = initial;
        }

        /// &lt;summary&gt;
        /// An event has happened, transition to next state
        /// &lt;/summary&gt;
        public void EventHappens(Event @event)
        {
            this.CurrentState = this.CurrentState.OnEvent((T)this, @event);
        }

        /// &lt;summary&gt;
        /// An event that causes the state machine to transition to a new state
        /// &lt;/summary&gt;
        /// &lt;remarks&gt;
        /// Defined as a nested class so that this state machine's events can only be used with it
        /// &lt;/remarks&gt;
        [DebuggerDisplay(&quot;Event = {Name}&quot;)]
        public class Event
        {
            public string Name { get; private set; }
            public Event(string name)
            {
                this.Name = name;
            }
            public override string ToString()
            {
                return &quot;~&quot; + this.Name + &quot;~&quot;;
            }
        }

        /// &lt;summary&gt;
        /// A state that the state machine can be in
        /// &lt;/summary&gt;
        /// &lt;remarks&gt;
        /// Defined as a nested class so that this state machine's states can only be used with it
        /// &lt;/remarks&gt;
        [DebuggerDisplay(&quot;State = {Name}&quot;)]
        public class State
        {
            /// &lt;summary&gt;
            /// The Name of this state
            /// &lt;/summary&gt;
            public string Name { get; private set; }

            public Action&lt;T, State, Event&gt; ExitAction { get; private set; }
            public Action&lt;T, Event, State&gt; EntryAction { get; private set; }

            private readonly IDictionary&lt;Event, Func&lt;T, State, Event, State&gt;&gt; transitions = new Dictionary&lt;Event, Func&lt;T, State, Event, State&gt;&gt;();

            /// &lt;summary&gt;
            /// Create a new State with a name and an optional entry and exit action
            /// &lt;/summary&gt;
            public State(string name, Action&lt;T, Event, State&gt; entryAction = null, Action&lt;T, State, Event&gt; exitAction = null)
            {
                this.Name = name;
                this.EntryAction = entryAction;
                this.ExitAction = exitAction;
            }

            public State When(Event @event, Func&lt;T, State, Event, State&gt; action)
            {
                transitions.Add(@event, action);
                return this;
            }

            public State OnEvent(T parent, Event @event)
            {
                Func&lt;T, State, Event, State&gt; transition = null;
                if (transitions.TryGetValue(@event, out transition))
                {
                    State newState = transition(parent, this, @event);
                    if (newState != this)
                    {
                        // Entry and exit actions only fire when CHANGING state
                        if (this.ExitAction != null) this.ExitAction(parent, this, @event);
                        if (newState.EntryAction != null) newState.EntryAction(parent, @event, newState);
                    }
                    return newState;
                }
                else
                    return this;        // did not change state
            }

            public override string ToString()
            {
                return &quot;*&quot; + this.Name + &quot;*&quot;;
            }
        }
    }
}
</pre>
<p>For further reading on State Machines I recommend this <a href="http://en.wikipedia.org/wiki/UML_state_machine">Wikipedia Article</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2012/01/a-simple-state-machine-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Understanding Dates and Times in Natural Language</title>
		<link>http://blog.abodit.com/2011/12/understanding-dates-and-times-in-natural-language/</link>
		<comments>http://blog.abodit.com/2011/12/understanding-dates-and-times-in-natural-language/#comments</comments>
		<pubDate>Tue, 27 Dec 2011 08:54:08 +0000</pubDate>
		<dc:creator>Ian Mercer</dc:creator>
				<category><![CDATA[My News]]></category>
		<category><![CDATA[Natural Language Processing]]></category>
		<category><![CDATA[NLP]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=1666</guid>
		<description><![CDATA[One of the more challenging aspects of understanding natural language is dealing with date and time expressions. There are many different ways a user could refer to a specific date and time. They might say &#8220;Next Tuesday at 4pm&#8221;, they might give a specific date in any of several different forms, they might refer to <a href="http://blog.abodit.com/2011/12/understanding-dates-and-times-in-natural-language/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>One of the more challenging aspects of understanding natural language is dealing with date and time expressions.  There are many different ways a user could refer to a specific date and time.  They might say &#8220;Next Tuesday at 4pm&#8221;, they might give a specific date in any of several different forms, they might refer to other time ranges &#8220;First Tuesday in January 2012 at 4pm&#8221; etc.</p>
<p>Whilst my natural language engine can&#8217;t understand every possible date time expression (e.g. the second Wednesday after the first Friday in May 2010) it does handle a huge variety.</p>
<p>Clearly the .NET provided DateTime class is wholly inadequate to express the kinds of date/time expressions your users might enter.  To deal with that I&#8217;ve created my own classes that represent items like a specific <strong>Time</strong> of day, a <strong>DateTimeRange</strong>, a <strong>DateTimeRangeCollection</strong>, &#8230;</p>
<p><strong>TemporalSets</strong> are the most general result of parsing a datetime expression since they can represent any date time expression.  Broadly they split into two categories: finite and infinite expressions.  &#8220;Tuesday at 5pm&#8221; is an infinite time expression.  &#8220;Tuesday at 5pm January 2012&#8243; is a finite time expression.  Sometimes you will want to accept an infinite expression and interpret it as a future or past finite occurrence.  For that I have a MergePreferPast and MergePreferFuture method that operate on a <strong>TemporalSetCollection</strong>.  The demonstration code on <a href="http://nlp.abodit.com/home/download">BitBucket </a>shows this in action.</p>
<p><strong>TemporalSets</strong> also have unique capabilities around both providing query expressions (for database searches) and generative expressions (for adding dates to a calendar).</p>
<p>If you&#8217;d like to try out the latest date / time expression parsing code in my <a href="http://nlp.abodit.com">Natural Language Engine</a> you can visit the <a href="http://nlp.abodit.com/home/demo">demo</a> and try typing &#8220;define&#8221; followed by a date / time expression. </p>
<p>If you find any expressions that ought to work, please feel free to email or Tweet them to me.</p>
<p>Here&#8217;s a sample session:</p>
<pre class="brush: plain; title: ; notranslate">
define june 23rd 2010
Absolute:[DATETIMERANGE 6/23/2010 at 12:00 AM to 6/23/2010 at 11:59 PM]

define January 19th
Future:[Thursday 1/19/2012], [Saturday 1/19/2013], [Sunday 1/19/2014], [Monday 1/19/2015], [Tuesday 1/19/2016], [Thursday 1/19/2017], [Friday 1/19/2018], [Saturday 1/19/2019], [Sunday 1/19/2020], [Tuesday 1/19/2021]
Past: [Wednesday 1/19/2011] ...
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2011/12/understanding-dates-and-times-in-natural-language/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Integrating Wordnet with Natural Language Processing (NLP)</title>
		<link>http://blog.abodit.com/2011/11/integrating-wordnet-with-natural-language-processing-nlp/</link>
		<comments>http://blog.abodit.com/2011/11/integrating-wordnet-with-natural-language-processing-nlp/#comments</comments>
		<pubDate>Sat, 26 Nov 2011 23:03:12 +0000</pubDate>
		<dc:creator>Ian Mercer</dc:creator>
				<category><![CDATA[Natural Language Processing]]></category>
		<category><![CDATA[Semantic Web]]></category>
		<category><![CDATA[NLP]]></category>
		<category><![CDATA[Wordnet]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=1650</guid>
		<description><![CDATA[I&#8217;ve been working to get a release of my NLP Engine out the door but wanted to boost the built in dictionary / thesaurus before release. So this weekend I integrated Wordnet into the engine. Wordnet is available in RDF as a series of triples. As well as all the word definitions grouped into synonym <a href="http://blog.abodit.com/2011/11/integrating-wordnet-with-natural-language-processing-nlp/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been working to get a release of my NLP Engine out the door but wanted to boost the built in dictionary / thesaurus before release.  So this weekend I integrated Wordnet into the engine.  Wordnet is available in RDF as a series of triples.  As well as all the word definitions grouped into synonym sets (synsets) it also includes relationships like class relationships &#8216;<a href="http://en.wikipedia.org/wiki/Hyponymy">hyponym</a>&#8216; or &#8216;isa&#8217; and part relationships &#8216;<a href="http://en.wikipedia.org/wiki/Meronym">meronym</a>&#8216; or &#8216;<a href="http://en.wikipedia.org/wiki/Holonymy">holonym</a>&#8216;.</p>
<p>By building a simple in-memory graph of all these relationships my engine can now use them to infer interface types on objects.  To define an interface corresponding to a Wordnet synset like a mammal (wn30:synset-mammal-noun-1) you simply define an interface in the namespace &#8216;Noun&#8217; having a name of &#8216;mammal1&#8242;.  Through the type inheritance specified in the Wordnet file all mammals now inherit that interface automatically and you can write natural language rules that ask for a mammal and they will get any type of mammal defined in Wordnet.</p>
<p>For example:</p>
<p><a href="http://blog.abodit.com/wp-content/uploads/2011/11/DefineAardvark.png"><img src="http://blog.abodit.com/wp-content/uploads/2011/11/DefineAardvark.png" alt="Wordnet integration with Natural Language Engine" title="Wordnet integration with Natural Language Engine" width="623" height="206" class="alignright size-full wp-image-1651" /></a>  </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2011/11/integrating-wordnet-with-natural-language-processing-nlp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MongoDB substring search with a difference</title>
		<link>http://blog.abodit.com/2011/11/mongodb-substring-search-with-a-difference/</link>
		<comments>http://blog.abodit.com/2011/11/mongodb-substring-search-with-a-difference/#comments</comments>
		<pubDate>Fri, 25 Nov 2011 19:22:50 +0000</pubDate>
		<dc:creator>Ian Mercer</dc:creator>
				<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=1643</guid>
		<description><![CDATA[It&#8217;s quite common to want to search a database for a key that starts with a given string. In SQL you have LIKE and in MongoDB you have regular expressions: But what if you want to do the inverse of this? i.e. to search the database for the keys that are themselves substrings of the <a href="http://blog.abodit.com/2011/11/mongodb-substring-search-with-a-difference/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s quite common to want to search a database for a key that starts with a given string.  In SQL you have LIKE and in MongoDB you have regular expressions:</p>
<pre class="brush: jscript; title: ; notranslate">
db.customers.find( { name : { $regex : '^acme', $options: 'i' } } );
</pre>
<p>But what if you want to do the inverse of this? i.e. to search the database for the keys that are themselves substrings of the search string?  For example, suppose you are trying to parse a block of text and you want to find phrases in the database that match the start of the current block of text.  In SQL you would be dead in the water but with MongoDB you can create a RegEx that matches either the first word, or the first two words, or the first three words, &#8230; and so on.</p>
<p>We can construct a regular expression to do this, it might look something like: <strong>^word1($| word2($| word3$))</strong></p>
<p>Here&#8217;s a C# method that can create the necessary regular expression:</p>
<pre class="brush: csharp; title: ; notranslate">
        /// &lt;summary&gt;
        /// This generates a regular expression that matches as much of the given phrase as it can from a string
        /// i.e. a reverse prefix search where you want the database to supply the prefix and match it against your query
        /// useful for matching 'as much as possible from a given input'
        /// &lt;/summary&gt;
        private string generatePrefixRegex(string phrase, bool atStart)
        {
            string[] bits = phrase.Split(' ');
            string result = bits[0];

            // At the start of a sentence, if the first character is upper cased, we should also be looking for a lowercased verson of it
            if (atStart &amp;&amp; char.IsUpper(result[0]))
            {
                result = string.Format(&quot;(%0|%1)%2&quot;, char.ToLowerInvariant(result[0]), char.ToUpperInvariant(result[0]), result.Substring(1));
            }

            // Each additional word - either we end the string before it or we must include it

            foreach (var bit in bits.Skip(1))
            {
                result = result + &quot;($| &quot; + Regex.Escape(bit);
            }

            result = result + &quot;$&quot;;                      // last word must end string

            foreach (var bit in bits.Skip(1))
            {
                result = result + &quot;)&quot;;                 // close the expression
            }
            return &quot;^&quot; + result;                        // Must start at the start of a Name
        }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2011/11/mongodb-substring-search-with-a-difference/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A traffic service that answers &#8220;which way should I go?&#8221;</title>
		<link>http://blog.abodit.com/2011/10/a-traffic-service-that-answers-which-way-should-i-go/</link>
		<comments>http://blog.abodit.com/2011/10/a-traffic-service-that-answers-which-way-should-i-go/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 06:22:28 +0000</pubDate>
		<dc:creator>Ian Mercer</dc:creator>
				<category><![CDATA[Home Automation]]></category>
		<category><![CDATA[My News]]></category>
		<category><![CDATA[Smartest House]]></category>
		<category><![CDATA[smart home]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=1632</guid>
		<description><![CDATA[Most traffic reports (on the radio or in text message alerts) are fairly useless. Like weather reports they contain lots of irrelevant information that could be eliminated with just a bit of extra context. In fact, most of the information they deliver is completely irrelevant to you as an individual located in one spot and <a href="http://blog.abodit.com/2011/10/a-traffic-service-that-answers-which-way-should-i-go/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p><img src="http://blog.abodit.com/wp-content/uploads/2011/10/TrafficWhichWay.png" alt="Which way should I go?  Traffic" title="Which way should I go?  Traffic" width="980" height="421" class="alignleft size-full wp-image-1633" /></p>
<p>Most traffic reports (on the radio or in text message alerts) are fairly useless.  Like <a href="http://blog.abodit.com/2010/07/weather-forecasting-for-home-automation/">weather reports</a> they contain lots of irrelevant information that could be eliminated with just a bit of extra context.  In fact, most of the information they deliver is completely irrelevant to you as an individual located in one spot and hoping to get to another spot.  Furthermore they aren&#8217;t actionable &#8211; telling me the traffic is slow on SR-520 and on I-90 isn&#8217;t interesting unless you can tell me which is the best way to go given where I am now and where I want to be.</p>
<p>So this weekend I added a new feature to the home automation that uses the WSDOT&#8217;s excellent traffic feed API to calculate a traffic report just for me.  Recently I&#8217;ve started driving from the north end of Bellevue to the south end of Sammamish during rush hour.  There are two very different paths I can take: SR-520 or I-405 to I-90.  If either route has a problem I should take the other.  So now I get an XMPP (chat) message from 4PM to 6PM whenever the optimal path changes from one route to the other.  It&#8217;s the absolute minimum information I need and it&#8217;s 100% actionable.</p>
<p>For the moment the calculation is fairly simple, I simply maintain a list of the FlowDataID values along each route and then calculate a total &#8216;slowness&#8217; factor based on the sum of those segments.  If one way is much better than the other it generates an alert.  If it goes back to being roughly equal the alert is cleared.</p>
<p>Since the calculation is purely relative (route A vs route B) it&#8217;s also fairly immune to day-of-week / school-holidays and other factors that have a significant impact on traffic but no impact on the only actionable decision I need to consider.</p>
<p>One other interesting point from the graph is just how spiked the traffic is on SR-520 compared to I-90.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2011/10/a-traffic-service-that-answers-which-way-should-i-go/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 0.187 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2012-05-20 13:41:54 -->

