Ammeter interface

by cisterni 5. September 2011 20:39

We are using VSLab as a console to coordinate experiments for measuring energy absorbed by algorithms. We have developed a methodology that allows us to get complexity behavior from the current absorbed by a computer on the AC power. Here is the source of a "virtual" ammeter based on phidgets sensors that allows us to decide the sampling frequency and wether use a buffer or not to accumulate samples. It is a nice application of unit of measure of F#, and shows also a pitfall of the language: "open" is a keyword but also the method name of the Phidgets .NET library, thus we resorted to reflection for invocation.

open Phidgets
 
let ifkit = new InterfaceKit()
let openPhidgets() = typeof<InterfaceKit>.GetMethod("open", [| |]).Invoke(ifkit, [| |]) |> ignore
 
[<Measure>] type V // Volt unit measure
[<Measure>] type A // Ampére unit measure
[<Measure>] type Hz // Hertz
[<Measure>] type s // Seconds
[<Measure>] type ms // Seconds
 
type AmmeterSensor(id:int, kit:InterfaceKit) =
  let k = 0.04204<A>
  let mutable buffered = false
  let sensor = kit.sensors.[id]
  let mutable lastv = 0.
  let mutable samplingRate = 10.<Hz>
  let mutable accumulator = 0.
  let mutable samplescount = 0.
  let mutable maxsz = 0 // Infinite
 
  let interval() = float(1. / samplingRate) * 1000.<ms>
  let mutable startInterval = System.DateTime.Now
 
  let buffer = new System.Collections.Generic.Queue<float<A>>()
 
  do
    sensor.Sensitivity <- 1
    kit.SensorChange.Add(fun v ->
      if v.Index = id && buffered then
        let dt = interval()
        let t = System.DateTime.Now
        if (t - startInterval).TotalMilliseconds > float(dt) then
          lastv <- (accumulator / samplescount)
          if maxsz > 0 && buffer.Count = maxsz then buffer.Dequeue() |> ignore
          buffer.Enqueue(lastv * k)
          startInterval <- t
          samplescount <- 0.
          accumulator <- 0.
        accumulator <- float(v.Value) + accumulator
        samplescount <- samplescount + 1.
    )
 
  member x.Buffered
    with get() = buffered
    and set(v) = buffered <- v
 
  member x.SamplingRate
    with get() = samplingRate
    and set(v) = samplingRate <- v
 
  /// <summary>
  /// NUmber of buffered samples. 0 means no bouds, please beware out of memory!
  /// </summary>
  member x.BufferSize
    with get() = maxsz
    and set(v) = maxsz <- v
 
  member x.nextValue() =
    if not buffered then
      Some(float(sensor.Value) * k)
    else
      if buffer.Count = 0 then
        let dt = interval()
        let t = System.DateTime.Now
        if (t - startInterval).TotalMilliseconds > float(dt) then
          startInterval <- t
          samplescount <- 0.
          accumulator <- 0.
          Some(float(sensor.Value) * k)
        else
          None
      else
        Some(buffer.Dequeue())
 
  member x.ToSequence () =
    seq {
      while kit.Attached do
        if buffered then
          let t = System.DateTime.Now
          let dt = float(interval())
          let elapsed = (t - startInterval).TotalMilliseconds
          if elapsed <= dt then
            System.Threading.Thread.Sleep(int(dt - elapsed) + 1)
        yield x.nextValue()
    }
 
 
 
 
openPhidgets()
 
let sens0 = new AmmeterSensor(3, ifkit)
 
sens0.Buffered <- true
 
sens0.ToSequence() |> Seq.take 1000 |> Seq.map (fun v -> match v with Some x -> float(x) | _ -> 0.)  |> Seq.toList |> Chart.Line
 
 
let sensors = [| 0 .. 2 |] |> Array.map (fun id -> new AmmeterSensor(id, ifkit))
sensors |> Array.iter (fun s -> s.Buffered <- true)
 
let values(amount) =
  seq {
    while true do
      let e = sensors |> Array.fold (fun v s -> v + s.nextValue().Value) 0.<A>
      System.Threading.Thread.Sleep(110)
      yield e
  } |> Seq.take amount
 
 
 
open System.IO
 
let out = File.CreateText(@"enclosure-5-pwr-100.xml")
out.WriteLine(@"<? xml version=""1.1"" encoding=""utf-8"" ?>")
out.WriteLine(@"<AmmeterSamples Description=""Enclosure with 5 blade pwr 100%"" SampleRate=""10Hz"">")
 
values(1200) |> Seq.iter (fun v -> out.WriteLine(sprintf "  <Sample>%f</Sample>" (float(v))))
 
out.WriteLine(@"</AmmeterSamples>")
out.Close()
printfn "Done."
 
 
sens0.nextValue()
 
let inp0 = ifkit.sensors.[0]
 
inp0.Sensitivity <- 1
 
inp0.Value
  ifkit.close()

Currently rated 2.2 by 24 people

  • Currently 2.166666/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Design | General | F# Interactive

Lightweight controls, VSLab and F#

by cisterni 5. January 2009 11:14

November and december have been busy months and time was short to find enough time to write about VSLab. However, things are going on and we are planning a new release of VSLab soon. The major contribution is from Giacomo Righetti, who has spent time for building a framework of lightweight controls using a former definition from me. Lightweight controls are missing from Windows Forms, and now you can have them in F# (and .NET languages). Giacomo implemented a set of predefined controls such as buttons, scrollbars, and many others so that viewlet development becomes easier. The VSLab shell project is also going on, and actually I have configured my Acer aspire one to start VSLab as a system shell :) I don't really miss Windows explorer... (ok, ok, I know I'm a little bit biased!).

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Design | General

VSLab: Call for feedback

by cisterni 23. September 2008 00:18

I'm googling to check how people is receiving VSLab and how it is used. I know that so far the project is useful only if you want to extend VS and basic packages are missing. Today I found a post about someone having problem with VSLab installation and upgrading. I wish people will contact me through the CodePlex Web site or on this blog to notify issues as well as success stories. VSLab is turning 0.25 (3 months) and 1k downloads are close!

I know I have to do doc update, but there are cool things going on under the hood, the VSLab Shell is perhaps the coolest, but we are also working to new Viewlets and samples to make VSLab more useful. If you developed a viewlet let us know, so that we can let other people know about your work and experiments. Don't hesitate also to ask for improvements, according to our resources we are willing to improve VSLab.

Antonio

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Design | General

VSLab Viewlets and lightweight controls

by cisterni 10. September 2008 21:13

Back to normal work, still fixes to do for the CTP update rush, but I'm finally able to restart the work I stopped to update the code base. A major update that is available in the current release of VSLab though not entirely defined is the support for lightweight controls. The inner working of VSLab requires (have a look to the white paper discussing the implementation) the use of Windows Form instead than WPF for developing viewlets. I hope to circumvent this limitation some day, but this is the current situation. Moreover you cannot aggregate user controls when developing viewlets, again for core reasons (essentially VSLab runs in the F# interactive process and draws in toolwindows owned by the VS process). This is the reason for implementing lightweight controls for Windows Forms: this kind of controls are available on other systems such as Java AWT and offer a mean to have logical controls without having to pay for GUI window peers.

The ViewletControls project contains the panel responsible for implementing the lightweight controls abstractions, still under definiton and debugging. The Viewlet class already inherits from this container nonetheless. We are defining basic controls to ease the implementation of viewlets, though we believe that drawing should remain the core of viewlet development since the composition is obtained through the toolwindows in Visual Studio and dialogs can be opened directly from F# without having to fill the viewlet area with controls.

Another feature recently introduced for viewlets is the Windows caret support. It is now possible to display the Windows caret at (x, y) to have input directly in the viewlet toolwindow without having to resort to textboxes.

I love this part, reimplement controls is always a good opportunity to remember the good old days.

The lightweight controls also will include a timer to express animations easily using yield expressions (continuations) using a single timer. The library has been designed after another library designed for Web applications and recalls features available in the WPF framework. Future posts will discuss with examples the usage and the implementation of this library.

 

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

Design | General

September CTP and VSLab again

by cisterni 7. September 2008 12:12

As discussed in the previous post we are working to get VSLab back on the September CTP because the VS project system has completely changed. The core mechanism used to build Viewlets do not depend on this integration, they rather rely on deeper mechanisms available on Windows. The only feature the VSLab addin used of the project system was the ability to send F# code to the F# interactive toolwindow. In the former implementation F# interactive was essentially a user control, now the system provides support for F# as a VS package, thus the toolwindow has a completely different implementation.

Although I'm talking with the F# product team I continued to look for a hack to quickly update VSLab because many people have downloaded it and I know how hateful is when a tool ceases working. Yesterday evening mostly by accident I found the solution that I quickly describe here to those interested in sending F# code to fsi.exe from VS addins. The first step is to obtain a reference to DTE2 object available from the VS automation model and here referred as appObj.

To show the F# interactive toolwindow you can simply trigger the menu command as follows:

appObj.ExecuteCommand("View.F#Interactive", "") 

The toolwindow should be loaded before you can get a reference to it: 

let tw = (appObj.ToolWindows).GetToolWindow("F# Interactive") :?> Microsoft.FSharp.VisualStudio.Session.FsiToolWindow

It is interesting to have a look to the cast, the object you are getting from GetToolWindow is not a COM wrapper but the .NET object of a type defined in the FSharp.VS.FSI.dll assembly. Now after a little bit of use of Reflector I found that the method I was interested in was executeNoHistory@182 that is clearly an inner function object and cannot be invoked directly. While I'm waiting for a public method I resorted to reflection to invoke it:

let mi = (tw.GetType()).GetMethod("executeTextNoHistory@182")

mi.Invoke(tw, [| ("2+2;;" :> obj) |]) |> ignore

And this is the only true dependency VSLab has from the F# VS integration. Now I'm working to port project templates, but these are minor things. Hope to release the new version VSLab by wednesday.

 

Currently rated 1.5 by 2 people

  • Currently 1.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Design | General

F# September CTP and VSLab

by cisterni 6. September 2008 15:52

Hello everybody,

 while I was in holydays I received an e-mail from F# team that VSLab was not working with the new CTP of F#. I tried to recompile it for this new release finding that the VS integration has been redesigned and now I'm trying to figure out which way to go. The core of VSLab works perfectly, the only problem is that I used to send commands to F# interactive from VSLab addin and now this is not possible using the previous interface. I'm trying to figure out how this can be overcome, and at the same time I'm collaborating with the F# team in Redmond which has been really great in supporting me. Stay tuned, new information will be available ASAP.

-- Antonio

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Design | General

VSLab Shell

by cisterni 27. July 2008 17:26

I think that one of the most interesting areas of VSLab, partly unforeseen, is the project of developing a next generation system shell as a package. System shells have a long history and there is always an attempt to find the new one, but I think these are here to stay, but they also are the past. We are living in a world where the stream-based composition of software is far from satisfactory, and also the completion forms provided by shells are inadequate.

In 2001 I defined a shell called ObjShell, attempting to exploit the component-based nature of COM for software composition. At that time I realized that Unix shells are just a simpler version of this where each program was a component with a well defined interface and an associated process, and the shell was the mean by which these components were integrated. ObjShell were a very nice project and today I can say it's a pity I didn't find the time to work on it for the .NET version, otherwise the Power Shell would have arrived several years before. And in fact I was contacted by the PS team (I spoke to Jeffrey Snover when He was in charge of PS) though I didn't succeded in trying to convince on some basic design principles of the ObjShell that I would have loved to see in the PS. I'm not a PS fan, I like the object streaming metaphor, but I didn't feel need for another unreadable language full of switches and dollars.

I think that programming languages and the associated toolchain have grown enough to blur the distinction between the program and the shell, it was true for VB and COM and it is more true nowadays with .NET and languages such as F# using the interactive top level. Now with few lines you can read system counters as PerfMon does and do several other things. VSLab Shell will be a package designed to be next generation shell, where statements are highlighted to be executed and a single file may contain several scripts. Intellisense it is far better than Tab-based completion. At the moment we are working on the core functionalities of the shell, but also designing interfaces to hardware such as ILO featured by HP.

More about VSLab Shell will be available in the next release of VSLab.

Currently rated 2.3 by 7 people

  • Currently 2.285714/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

Design | Shell

VSLab R. Daneel released

by cisterni 16. July 2008 01:45

I just released the new release of VSLab codenamed R. Daneel. This release adds the package feature, an important element to build DSL and tools on top of VSLab. Packages are simply .NET assemblies with appropriate metadata used by VSLab to offer a dialog to manage them. Ok, ok you can code it, but it's handy to select which packages should be loaded, if at startup, and if you are lazy enough you can even ask for automatic namespace opening!

This is how package manager looks like:

You can load packages interactively or flag them for startup. You have two assembly caches (different from the GAC so you are not required to understand strong naming) for packages, one in the VSLab installation dir, and the other in the user profile. I managed to start the UAC dialog on Vista to have packages installed under program files.

Currently rated 2.0 by 3 people

  • Currently 2/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

Design | General

Under the hood

by cisterni 13. July 2008 20:14

I'm going crazy in refactoring and improving VSLab runtime. I'm trying to improve early design choices made while trying to find the right approach to implement it. This is important because the new package mechanism requires better design. I'm changing also core names and I've added a new VS command to be used to move as much code as possible into fsi.exe instead than into the VS addin. The FSIExec command allows F# functions to send a string to the F# interactive top-level for evaluation. This is a powerful form of meta-programming allowing F# code generating code fragments to be evaluated in the fashion of the eval function of dynamic languages.

Currently rated 2.0 by 6 people

  • Currently 2/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

Design

Package

by cisterni 7. July 2008 12:46

VSLab allows to quickly design Domain Specific Languages without having to rely on the full VS SDK. The advantage is flexibility and accessibility to programmers willing to extend VS without having to fight with the intricacies of COM that tend to surface when interacting with DTE and Visual Studio extensibility. To help defining modules easy to use we are defining an architecture for Packages that are loaded by VSLab in the easiest possible way and that can ask for dependencies without having to resort to #r #I directives explicitly. We are also planning for supporting automatic loading of packages at startup.

Original Viewlet Samples will be distributed in packages now. One significant package will be the VSLab Shell, a shell for performing System administration through Visual Studio.

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

Design

Powered by BlogEngine.NET 1.4.0.0
Theme by Mads Kristensen

VSLab blog

VSLab is a Visual Studio extension designed to support Visual Studio interaction from F# interactive. It is a Microsoft product developed at University of Pisa, by a team lead by Antonio Cisternino.

Resources

Recent comments

Comment RSS

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

© Copyright 2008