May 16 2016

Turning on a led from powershell over wi-fi, i2c

Category: C# | Hardware | IoT | PIC | PowerShell | Raspberry | Robot — Duke @ 16:44

It is a couple of week i’ve started a new project, something i’ve always wanted to do, but i’ve never had time or resources or… the real will to complete it.

I’m not saying i will make it this time but certainly it is progressing.

Today i’ve reached a critic mass, something interesting and usefull enough to post about it, what the hispter and the millennials calls “minumum viable product”, it will be part of somthing bigger but i want to blog it to not forget it and, as i’ve found difficulties in it, maybe help someone else, who knows?

My project is very “hardware” oriented, something in the real “maker” area. I’m not an hardware guy, but i’ve the minimal skill required to play whit the modern electronics, that at my eyes looks like logo bricks for grown-up (while you treat them as black box).

So here is what i want to do:

I’ve a Raspberry Pi 2, a wi-fi dongle TP-link TL-WN725 (i also have the EDIMAX EW-7811Un but doesn’t work well with Win 10 IoT yet)  and the latest build of Windows 10 IoT (v.10.0.14328.1000, apparently, longer version are better….)

Then i’ve a breadboard, a bounch of headed cables, resistors and a led, plus a PIC16F18325 (in a PDIP14 package)

To complete this mini-lab i’ve a mini dso 203 oscilloscope and of course a PicKit3 programmer for the PIC

I want to type a command in my computer (any of the my computers) and have a led turned on or off, but not by the raspberry, on the PIC microcontroller instead.this because i’ll later need some of the advanced capabilities on the PIC, but for now for educational and demonstrative purposes, the led is well enough.

so my setup is the following:


So from wherever am i, i want to turn on that led with a command on my shell

that’s a lot of protocols and OS and software and languages together, from the very high level powershell to the closest possible to the metal +vcc signal,

I know, i know, it is called Internet Of Things, and it has already been invented by someone else, but who cares? I want to make my very own IoT.

so, first thing first:

Today we will cover how to connect from my pc to a raspberry who has in turn Win 10 iot on. If you are intereste on how to install Windows 10 Iot, the excellent Scott Hanselman has a blog post for this.

so i want to open powershell a type a command to connect to my raspberry, Win 10 IoT is already configured to receive powershell session (WinRM is turned on by default) all you need to know is your raspberry name and the root user’s credential

i’ve then a module called Connect-Raspberry.psm1 which loads automatically any time i open a PS session (thanks to an import-module in my $psprofile)

the code of the module is the following

$knownRaspberry = @{Jeeg=@{Username="Administrator";Password="mysecretpassword"}}

function Get-CredentialObject([string] $username, [string] $password){ 
    $encryptedPass = ConvertTo-SecureString $password -AsPlainText -Force 
    return new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $encryptedPass 

function Connect-Raspberry([string] $machine, [string] $username, [string] $password){    

    $trustedHosts = get-item  "WSMan:\localhost\Client\TrustedHosts" 
    if(!($trustedHosts.value -contains $machine)){ 
        Set-Item WSMan:\localhost\Client\TrustedHosts -Value $machine -Force 

    if($machine -eq $null){ throw throw [System.IO.Exception] "Please specify Machine"} 
    if($knownRaspberry.ContainsKey($machine) -and (!$username) -and (!$password)) 
        $password = $knownRaspberry[$machine].password; 
        $username = $knownRaspberry[$machine].Username;        
    if($username) { 
        $username = "Administrator" 
        $cred = get-credential -Message "enter password" -UserName "$machine\$username" 
        $cred = get-CredentialObject -username "$machine\$username" -password $password 
    #the following line is an hack to workaround a bug, maybe in the future will not be required 
    #remove-module psreadline -force 
    Enter-PSSession -ComputerName $machine -Credential $cred 


if it is the first time you run it you may need to run as administrator as it will set the trustedhosts for the WSMan\client to trust the raspberry

given that i can connect to my  raspberry (it is called Jeeg as all the machine in my network have name of Gō Nagai’s robots)


of course the script can take username and password but you can map in the $knownRaspberry variables all your frequently accessed raspberry

Obviously Jeeg is powered up and connecte to my Wi-Fi lan by the TP-Link Usb dongle

Now i have a shell on my Pc (Grendizer) that is actually a remote session on Jeeg and i can ask Jeeg to do anything it knows.

but now i want Jeeg to write a message on it’s I2C bus. Windows 10 IoT has the drivers, but powershell knows nothing about them.

The good thing is that Powershell understand .Net very well and that Windows 10 IoT can run .Net Universal Windows App!

so my idea was to write a simplified wrapper around the .Net API for the I2C to use as base for a Powershell Module

to do this you need Visual Studio 2015 Update 2 with the Windows 10 IoT SDK that match at best possible the version of Windows 10 IoT oon the raspberry. I’ve found that the SDK are usually a couple of versions behind the Raspberry Build but fortunately it doesn’t seems to be a problem!

so File>New>Project and select Universal Windows (dll)


you should have these references.

the wrapper’s code is the following:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using Windows.Devices.Enumeration; 
using Windows.Devices.I2c;

namespace Bus 
    public enum Speed 
        Standard = 0, 
        Fast = 1, 

    public class I2CControllerAddressException : Exception 
        public I2CControllerAddressException(int address, string deviceId) 
            : base(string.Format("The address {0} on I2C Controller {1} is currently in use.", address, deviceId)) 
        { } 

    public class I2CControllerFoundException : Exception 
        public I2CControllerFoundException() 
            : base("Could not find the I2C controller") 
        { } 

    public class I2c 
        private static I2cDevice Open(int targetAddress, Speed speed) 

            var advancedQuerySyntaxString = I2cDevice.GetDeviceSelector(); 
            var controllerDeviceIds = DeviceInformation.FindAllAsync(advancedQuerySyntaxString).GetAwaiter().GetResult(); 
            if (controllerDeviceIds == null || controllerDeviceIds.Count == 0) 
                throw new I2CControllerFoundException(); 
            var i2cControllerDeviceId = controllerDeviceIds[0].Id;

            var i2cSettings = new I2cConnectionSettings(targetAddress); 
            i2cSettings.BusSpeed = (I2cBusSpeed)speed;

            // Create an I2cDevice with our selected bus controller ID and I2C settings 
            var I2cSalve = I2cDevice.FromIdAsync(i2cControllerDeviceId, i2cSettings).GetAwaiter().GetResult();

            return I2cSalve; 

        public static void Send(int targetAddress, Speed speed, byte[] message) 
            var device = Open(targetAddress, speed); 

        public static byte[] Receive(int targetAddress, Speed speed, byte[] message, int expectedReplyLenght) 
            var device = Open(targetAddress, speed); 
            var reply = new byte[expectedReplyLenght]; 
            device.WriteRead(message, reply); 
            return reply; 



complie it and you will have a nice i2c.dll file

that is almost enough to play with the i2c bus from the command line.

why almost? because this file reference the System.Runtime.WindowsRuntime that you have to find out where it is, it will not copyed in the same folder of your dll, it is not the same mechanism of the old projects where you can specify “copy local”

the best way i’ve find is to make an universal windows app (.exe) wich refers this assembly and compile it, in the binary folder you’ll find also the the System.Runtime.WindowsRuntime.dll you need


now open the file explorer and type \\Jeeg\C$

you’ll see the “Jeeg” C disk, copy both the assembly in the path

\\jeeg\c$\Program Files\WindowsPowerShell\Modules\i2c

(you need to create the I2C folder of course)

so you will have the following


and you are ready!

from your remoted session on Powershell just type

Import-module i2c

to load the module and be able to send and receive date on i2c using powershell

and this ishow you send a command on the i2c bus


this command for example sends (master write on server, in the i2c terminology) on the address 8 the byte 0xAA, using the standatd speed (100KHz)

Raspberry is also able to use the fast mode (400KHz)

I2C has also two speed,Full Speed 1MHz and High Speed 3,2MHz but Raspberry is not able (at the moment at least) to use these speed, in any case the PIC16F series doesn’t have enough processing power to handle these clocks, i think it is necessary at least 16bit PIC to work with these speed, but i’ve not investigated.


next time i'll talk about the PIC firmware, that's the most interesting part to me and there are many tricks that may be useful to any hobbist that may face these topics for the first time :)


Jul 24 2013

Null safe accessor

Category: C# | Visual Studio — Duke @ 06:54

It is happened to me many time to have to accesso a long hierarchi of object just to display a value to the user, and possibly this hierarchy contains null values

So the case is a.B.C.D.E.F where a is my object reference B, C, D, E are child of a in a long hierarchy of property accessor, and finally F is a simple integer o a string that i don't care about but the user want to see (if present)


It turns out that some languages have the so called  Groovy's safe dereferencing operator  (see

but C# have not :(


Stack overwlow is full of smart solutions, some very elegant (see some here but allof these are in someway suboptimal


the one i like more is


bossName =Employee.NullSafe( e => e.Supervisor).NullSafe( s => s.Boss).NullSafe( b => b.Name);


but is too verbose :(


so i've ended up with an alternate solution (that cames in two flavours to tell the true)



Jan 22 2013

Many news!

Category: C# | General — Duke @ 16:55

Wow! these are busy days! full of news and awesomeness!

First things first! finally i managed to get hold of a new domain name for my site

Thanks to everyone who have supported me, expecially Lilla <3


Second: i've published a new project on codeplex about setting the precision of decimal numbers. It is quite Amazing to me how many people have downloaded it in 4 days... SyncWcf was much more slower...

probably people prefer simple project?

Anyway i'm happy, i've also started working on a new electronic project and i'm Learning lot of things (a nice way to say that nowthing works as intended for now... but it is proceeding quite well, i've to say!)

Stay tuned probably i'll post something in the near future about this project!


Busy days... i love these!



Aug 5 2012

I’m on the clouds

Category: C# | Virtual Machines | ASP.NET | Cloud | Azure — Duke @ 17:47

Great! the blog is online again! finally it is persistent! I mean.. it will stay online 24/7,because it is on azure!

I’ve tried several solution but at the end I’ve found the most suitable for me.

A virtual machine instance with IIS installed on it. then an endpoint opened on the port 80, and finally  my lovely DynDNS that routes my domain name with an A record on the VIP address of the Virtual Machine.

I’m happy

it works

and the database is hosted on a separate instance of SqlServer!

some may ask why to not use the web instances (shared or reserved) available in azure, they should be ideal to host a simple blog

yes they are but….

shared instances doesn’t allow custom DNS (still wondering why)

reserved instances have a price that is too higher

and last but not least. a virtual machine allows you to do what you want on it… that is not exactly what one need in case of production website (because it force you to do all the maintenance, antivirusing, patching etc…) but it is ideal for a small experimental site.

Azure is amazing, especially the new HTML portal, I’ve done everything in 3 hours without no training at all, and I’ve tried several solution (also the shared sites, yes….)

great job MS, now lover the price of the reserved site instances or allow custom dns on the shared ones.


Dec 30 2011

Simple ASP.NET MVC script manager

Category: ASP.NET | C# | MVC3 — Duke @ 15:57

I remember that some months ago I’ve found a beauty video of a beauty component that allows to manage .js and .css files from an MVC application.

Unfortunately I’ve lost the link and I don’t remember the name of the component.

I’ve searched the seven seas of the internet but… nothing. Things went worst today when I realized I need a script manager.

I’ve searched, browsed and digged the internet again but the best I’ve found is the “Simple script manager” on codeplex, that is well far from being “beauty”

So, I’ve started my own simple script manager. for now it is very basic. it does almost nothing but at least it is in full “MVC” style, by using and respecting the existing design of MVC3, differently from the other things I’ve found.


so: here is the code More...

Tags: , ,

Dec 22 2011

Compare two objects’ hierarchy

Category: C# | Linq — Duke @ 17:47

I think that everyone sometime is in the situation to understand which are the difference between two objects.

Sometime it is easy but sometime is not. Imagine that you have to prepare for your user a log of all the difference and changes that has been applied on a complex document object model.

I’m in this situation: I have NHibenrate that maps a database. As usual the principal entity of the domain have dozens and dozens of sub entities.

This complex structure is subject to revision from the user. There is a workflow to generate and approve a newer version of the object graph, but as the graph is complex, the user want to have a report of what is changed. from the last approved version. ok: now I have an graph of objects that represent the current situation, and a graph of objects that represent the last approved version.

How to solve this issue? Next: once you have discovered where the objects differs, you maybe want to see which is the actual value and understand which was the old value and which is the new one. Finally, maybe you want to revert some of the difference…. how you can do it in an efficient and powerful way? the reply is EXPRESSIONS From linq on, .NET have gained one of the best thing I ever seen in a programming language, the ability to manipulate code as it is data.

This possibility is SIMPLY AMAZING. I’ve already used this in SyncWcf and now I’ve another clue that makes me love expression more and more. so what I’ve done? give a look at the code below: More...

Tags: , , , ,

Oct 30 2011 MVC3: entity framework 4.1 UniqueValue attribute validator

Category: ASP.NET | C# | Linq | MVC3 — Duke @ 15:28

I’m playing with MVC3 and EF4.1 (magic unicorn version) for a nice project I’m working on, and I’ve found myself in the situation to validate some fields against value duplication

(think about username, or other things that must be unique).

Unfortunately we don't have [Unique] constraint attribute in EF4.1 yet, so I’ve thought to leverage on the validation infrastructure of MVC3 to ensure uniqueness of the values.

I like the simplicity and expressiveness of the attributes then I’ve implemented my UniqueValueAttribute class.

this is remarkable because now I have a simple way to decorate every model attribute I want to be unique

(lot of fun code follows) More...


Sep 22 2011

Visual Studio 2010 Expression Tree Debugger Visualizer: how to make it work.

Category: C# | Visual Studio — Duke @ 19:21

I’m developing a quite complicated (it is always complicated when you have to manage big trees) project.

As in the project there are a lot of trees that are moving around (never seen a tree walking down the streets?)  and transforming themselves I’ve thought that it could be nice to use a Debug Visualizer to have a clearer view of the structure of these expression trees.

I know, the visual studio 2010 have the new DebugView property that makes it inspect the tree.. but it is still complicated to read when you have kilometric long namespace names that ends in generic object that in turn uses generic parameters with (again) long names.

it is a mess Triste

so I’ve decided to use the old but still good Expression tree visualizer available from the Visual studio 2008 C# code samples.

Downloaded, changed the reference to the Microsoft.VisualStudio.DebuggerVisualizers.dll library so to reference the newest one (C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.VisualStudio.DebuggerVisualizers.dll) and then compiled.

But here starts the problem:

My configuration is Windows 7 64 bit Ultimate and Visual studio 2010 Ultimate (with latest service packs and everything)

My projects are all in .Net 4.0 at the moment I'm writing.

I’ve compiled the visualizer, put it in the right folder

C:\Users\Duke\Documents\Visual Studio 2010\Visualizers

and BAM! …. nothing Triste

nothing appear, no magnifier  when I hover an expression reference.

I’ve tried to moving the visualizer in all the possible valid location (also considering the 64 bit architecture) but noting!

Binged and Googled… I’ve found that many people have had the same issue.

So I’ve started looking inside the actual code, and here it is!


[assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizer), typeof(ExpressionTreeVisualizerObjectSource), Target = typeof(Expression), Description = "Expression Tree Visualizer")]

Sooooo wrong! I’ve fixed it this way


[assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizer), typeof(ExpressionTreeVisualizerObjectSource), Target = typeof(Expression<>), Description = "Expression Tree Visualizer")]

Note typeof(Expression) transformed in typeof(Expression<>)

The type to visualize should be the generic one to work with the last version of the framework.

Recompiled, dropped in the right folder and this time IT WORKS!

Ok! now it works like a charm I hope this could help also other people with the same issue Sorriso


Jan 6 2011

Running VirtualBox as 64 Bit windows service

Category: C# | Virtual Machines — Duke @ 13:19
It is some time that I’m interested in virtualization: I think it is a nice way to keep my machine healty and clean, and in the same time it allows me to experiment and do “distruptive” things.
I love the possibility to take snapshots and recover a previous state in a moment!
Probably some of you have noticed that “” is not always online(there is a reason for this you’ll discover in a moment), right? I know it is boring and frustrating when a resource is not available when you need it, and for this I’m really sorry.
So… I’ve started thinking on how to improve the thing. First of all: my favorite virtualization environment is VirtualBox (too bad Oracle have bought it, I hope it will not ruine all this good work) I like it because is free, is fast (in my opinion far better than VMWare) and it is supported by an opensource community… and having the source code in your hands you can do great things.
Anyway… my site is not always available: that’s because it is hosted on a virtual machine on my real machine! ANd this because I always like to know the internals and from time to time I had some crazy ideas: like streaming the town fest in the square in front of my windows using my HD camera ( LOL, usually I did this on xmas night) or connect some netduino robots and drive it from a web interface… this requires me to have a host where I really can do everything. and these host services are not cheap, unfortunately Triste 
But hey! VirtualBox really saves the day! So I  have this virtualmachine “Bear” that runs my site… the one you are reading now. And it is hosted on my real machine… and my machine is housed in my bedroom… and at night I like to sleep A bocca aperta 
It is natural that I shut id down at night… and therefore the site becomes unavailable….
Again, my pc is setup to start up at about 14.00 CET every day (that’s because it have to record my favorite tv series…. but this is another story) and since I’m forgetful, I usually don’t remember to turn the VM on, so I’ve tough to improve the situation… I’ve started searching for a tool that allows me to automatically starts my VM up when the pc starts.
I’ve found VirtualBox headless mode… nice! but… I have not found a way to use it… expecially because for the shutd down part… I want my VM freezes its state when the pc is shutted down.. I don’t want to loose the last change on the site, nor to wait minutes for the virtualized machine shut down…
I’ve serched for days but nothing appears to be a strong solution…. there are some services that tries to emulate this but at the end they open a shell and invokes the command line version ov VBOX and “do things”
this have the bad behavior (in the major part of the occasions) to open console windows for some seconds, or to leave consoles opened…. and if you close the console .. the VM dies Triste
this is ugly and completely unprofessional.
But fortunately VirtualBox is opensource! and there are SDKs!!

Tags: ,

Oct 13 2010

3 ways for splitting a collection into pages with Linq

Category: C# — Duke @ 18:27
There are situations when you have a collection of objects (IEnumerable<T>) and you need to split it in chunks or pages so to process these resulting pars in different moments.
There are a lot of way to achieve this but the nicer is probably using Linq (it makes also your code looks a lot more modern and cool!)
the focus of this post is to discuss some of these ways and it’s pros and cons.
Digging around the web I've found this first example ( unfortunately I've lost the link, anyway the code in this first sample is not mine)
public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> enumerable, int chunkSize) 
    var total = enumerable.Count(); 
    for (int i = 0; i * chunkSize < total; i++) 
        yield return enumerable.Skip(i * chunkSize).Take(chunkSize); 
This allows you to write code like:
foreach(var page in myCollection.Chunk(30))
    foreach(var item in page)
anyway, this work well in limited scenarios, when the amount of record are quite low. To prove it imagine to have a collection with 1 million item in it, and you want to split it in chunk of 1000 elements each.
the Chunk method will first skip zero element (hey pretty fast!) and then take 1000. the total amount of time is c, given c the size of the chunk.
but the next round the method have to skip the first 1000(as they are already taken) and then take 1000. Hum… still not so bad as the first 1000 was already taken and then we have to process the next 1000.
third round…. skip 2000 this time… and then take 1000; ok but we have skipped 0 the first time, 1000 the second time and 2000 the third time… if we continue this way at the 10th page we will have to skip 0, 1000, 2000, 3000, 4000 … 9000! oh no, this means that at the kth page we will need to skip
((k * (k-1))/2 ) * c;
Old friend Gauss appears again! plus of course (k * c) for the take part.
that’s so bad, as you can see, we have a term that grows as O(k^2) and you for sure don’t want to have such complexity if your collection have 1 million of elements… moreover, one usually want to split thinks in chunks when the number is important, so exactly our scenario… therefore this algorithm is quite poor in a general situation: we are not going to use it in our programs, isn’t it?
So, let’s move forward and try to find something better: we have to solve the problem of restarting every time from the beginning, let’s try some caching, it usually works,right?
public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> enumerable, int chunkSize) 
    var total = enumerable.Count(); 
    var current = enumerable; 

    for (int i = 0; i * chunkSize < total; i++) 
        yield return current.Take(chunkSize); 
        current = current.Skip(chunkSize);