Please note: the web server plugin requires Chipmunk AV Controller version 1.0.21.0 or later.
The Web Server Plugin offers:
The Web Server plugin enables you to serve HTML web pages, and execute server side Lua script pages (.lsp). The plugin also enables you to control Windows Media Player, and a full working example is provided. You can also send events to the Chipmunk AV Controller via GET and POST (querystring and forms). Furthermore, the web server can be configured to automatically detect an eventstring in a querystring and/or form and send the event without you having to worrry about server side scripting. The plugin also supports AJAX. A sample web remote control is provided which uses this technique to communicate with the web server without the web page having to refresh each time you click on an HTML button. The web server exposes three objects to Lua (Response, Request, and HttpUtility) which you can use to create powerful server-side scripts. Additionally, a set of Windows Media Player objects can be accessed by Lua - the working examples show how to use all these objects.

10.b.i. HTTP Settings Tab
The first time you install the web server plugin, you will need to access the settings dialog (Tools | Plugin Manager | Plugin Settings | Web Server Plugin) to configure and start your web server. The HTTP settings tab is used to specify IP address and Port number. The web server defaults to port 8001 for HTTP. It is customary to use port 443 for HTTPS. If you have multiple IP addresses be sure to set the IP address correctly. Use 0.0.0.0 to listen on all IP addresses (including http://localhost:8001). You can normally access the web site either by computer name or by IP address (depending on how your network is set up), or if you are accessing the site from the same computer, you can use http://localhost:8001/. You will need to experiment.
http://localhost:8001/ (this will only work from the same computer the web server is running on)
http://<ipaddress>:<port>/
http://<computername>:<port>/
If you are using Windows XP Firewall, when you click on the "Start Server" button a dialog may warn you that Chipmunk is trying to connect to the network/internet and has been blocked. Click on the unblock button to allow the connection:

By default, the plugin sets the root directory to Documents and Settings\[User]\Home Cinema Solutions\Chipmunk AV Controller\2.0\Plugins\Web\Root. The samples can be found in this folder. If you change the root directory you will need to move the samples to the new location.
The "Default Document" field can be used to specify a default document for each web folder, so for example http://localhost:8001 will point to http://localhost:8001/index.html.
You can password protect your web site by enabling Basic Authentication. If you enable this option you must specify a user name and password (both are case-sensitive). If you change this option be sure to restart the server. The first time you request a web page from an authentication enabled site, you will be prompted to enter a user name and password before continuing. A user will remain logged in until the end of the session when the browser is closed.
EventString Processing Settings
EventString Processing Settings determine how the web server will respond to eventstring variables found in the querystring or HTML forms.
When "Auto Execute EventString in QueryString" is switched ON, web pages or scripts are not required. Simply typing the URL "http://localhost:8001/?eventstring=Cinema.DVD.On" in the web browser address bar will send "Cinema.DVD.On" to the controller as an event (and an automatically generated response is returned to the browser indicating if the event was successfully dispatched). When set to OFF, this feature is disabled. You might want to disable this feature for security reasons.
You can have Chipmunk learn this event by placing the Controller in learn mode and requesting the URL in your web browser. Alternatively you can use the Web Server Plugin Event Filter option and manually enter the eventstring to be learned.
When "Auto Execute EventString in Forms" is switched ON, events can be sent from a standard HTML (.html) web page containing a form. For example:
<form method="post">
<input type="Submit" name="eventstring" value="Cinema On">
<input type="Submit" name="eventstring" value="Cinema Off">
</form>
The server takes care of extracting the eventstring variable and sending it as an event to the controller. Again, an automatically generated confirmation is returned. The eventstring.html web page found in the root web directory contains examples and a basic tutorial on auto eventstring processing: http://localhost:8001/eventstring.html.
When switched to "OFF" this feature is disabled. A Lua Server Page script is then required to parse the form data. For example:
<% if Request.Forms["eventstring"] ~= nil then Chipmunk.Controller:SendEvent(Chipmunk.Payload(6, Request.Forms["eventstring"])) end %> <html> <body> <h2>Remote Control</h2> <form method="post"> <input type="Submit" name="eventstring" value="Cinema On"> <input type="Submit" name="eventstring" value="Cinema Off"> </form> </body> </html>
The advantage of this approach is that you have control over what response is returned to the web browser. In the above example, the page is simply reloaded. See http://localhost:8001/eventstring.lsp for details. Open the script in notepad to see how it works. A Lua script demonstrating HTML Form processing is available at http://localhost:8001/form.lsp. This script also shows you how to get and return cookies to the client.
Logging
By default, the Web Server Plugin will log HTTP requests to [Documents and Settings]\[User]\Home Cinema solutions\AV Controller\2.0\Plugins\Web\Log. You can change this using the logging settings and browse for an alternative location. Verbose logging will append the client's HTTP headers to the HTTP log entry. Use "None" to turn off logging. You can turn off logging on a page by page basis by appending a Response Header to an .lsp page:
Response:SetHeader('Logging', 'Omit');
You can also use the activity monitor at the bottom of the HTTP Settings tab to monitor current activity. It shows the 50 most recent requests, and any error messages due to configuration changes.
10.b.ii. HTTPS Settings Tab

The web server plugin supports secure HTTPS (ie., the content is encrypted during transfer between the server and client). Obtaining a server authentication certificate is not for the faint-hearted though. A test .pfx certificate is included: Documents and Settings\[User]\Home Cinema Solution\Chipmunk AV Controller\2.0\Plugins\Web\server.pfx for testing only. You will need to obtain your own certificate from one of the certificate authorities such as Thawte or Verisign (unless you already have your own). If your certificate is installed in the certificate store check the "Load from Certificate Store" option. If the certificate is contained in a PFX or .CER file, indicate the relevant format and specify the file location. If the .CER file requires a PVK file and password use the optional PVK settings. Use the following procedure to test SSL using the supplied PFX file:
If the certificate successfully loads, the current activity text box will give details of the certificate and will indicate if the server successfully restarted. Note that if you restart Chipmunk, the latest settings will be reloaded. If the web server plugin was last using SSL and a certificate, then the certificate will be reloaded and used when Chipmunk is restarted.
10.b.iii. Mime Types Tab

Some of the more common Mime Types have been mapped for you. Mime types enable web browsers to know how to display different content types. By default, if a content type is not explicitly listed the web server will use the .* type which maps to application/octet-stream. This means that if an unknown file type is requested the user will be prompted to download the file. Use the Mime Types Tab to edit or add new entries.
If you use the "Save Changes" button, the web server plugin will save your custom settings to [Documents and Settings]\[User]\Home Cinema Solutions\Chipmunk AV Controller\2.0\Plugins\Web\mime.config. The web server plugin will use these settings rather than its default settings. If you need to restore default settings click on the "Restore Defaults" button. This will delete the mime.config file and once again use its own built-in settings. In most cases you should not have to use this tab.

Web server plugin events can be learned in two ways. The simple way is to select the All option from the Learn Event Filter drop-down (next to the Learn Event button), and then click on the Learn Event button on the Controller's main window. Either request a web page with the eventstring in the url, or click on a button/image that sends an eventstring variable. The event will automatically attach to the command or macro. The second way is to select the Web Server Plugin option form the Learn Event Filter drop down list (next to the Learn Event button). Clicking on the Learn Event button will launch the "Enter Event String" Dialog (shown above). Enter the event string to be learned. To edit a previously learned event, double-click on the event to launch the "Enter Event String" dialog.
10.d. Web Enabled Windows Media Player

The web server plugin offers web-based control for Windows Media Player (versions 9 and 10). The web pages have been designed to work on Internet Explorer (Desktop and Pocket PC versions) and Firefox. You can navigate through your WMP library by Artist, Album or Playlist. You can play all tracks on all albums by an artist; all tracks on an album or playlist; or individual tracks from an album or playlist. The following sample pages are available:
Here is a screen grab of the web-enabled player. Please note that when you have finished using the web-enabled player, be sure to click on "Off". This turns off WMP and unloads it from memory.

Using AJAX, the player displays realtime information for the currently playing track. By default the player retrieves data every 3 seconds. You can reduce this to 1 second if you have a fast network by altering the Ajax.Interval property found in the javascript load() function at the top of the controls.lsp script.
MP3 files often have album art embedded in them. If your MP3 track has an embedded image, the web server plugin will extract the image and copy it to the wmp/images folder, where it can be served as a standard jpg image. If no image is present the player displays a small transparent graphic instead. By learning a little HTML you can modify these example scripts and customise the look and feel of your player.

The web-enabled Lua script console is similar to Chipmunk's Luascript editor. You can write and run Lua scripts from within your web browser. The script is located at http://localhost:8001/lua.lsp. This Lua server page uses AJAX to communicate with the web server plugin and return the result of the script without the web page having to refresh. If you plan to run your web server on the world wide web you should exercise extreme caution with this script! At the very least you should enable basic authentication and ideally enable SSL. The above example shows an event being sent to Chipmunk to turn on the DVD player and set the DVD to chapter 1. The server-side Lua script makes use of a specially registered function DoString() which returns the Lua script result.
10.f.i. AJAX Enabled Remote Control

A sample remote control is available at http://localhost:8001/ or [Documents and Settings]\[User]\Home Cinema Solutions\Chipmunk AV Controller\2.0\Plugins\Web\Root. The sample will help you develop your own remote controls using AJAX. Most of the time you will simply be able to copy and paste existing code and modify the event strings sent by the HTML buttons. If you have Flash experience why not incorporate that into your remote?
If your web browser does not support the xmlhttprequest object used by AJAX, there is a sample remote control using an alternative but equally effective javascript approach that also offers dyamic feedback without the page having to refresh. It is located at http://localhost:8001/noajax.html. It uses the noajax.js javascript located in the scripts directory.
A final note on AJAX: the javascript include that supports the use of AJAX in the sample remote controls is called ajax.js and is located in the scripts directory http://localhost:8001/scripts. Windows Media Player scripts use the wmp.js javscript.
10.f.ii. AJAX Enabled Controller
A web-enabled controller is available at http://localhost:8001/controller.html or [Documents and Settings]\[User]\Home Cinema Solutions\Chipmunk AV Controller\2.0\Plugins\Web\Root\controller.html. The web-enabled controller loads the command tree currently loaded in Chipmunk AV Controller. Once the command tree has loaded, execute a command or macro by clicking on the appropriate item in the command tree. A command tree item's notes can be viewed by hovering over the appropriate item. Status messages are displayed at the bottom of the tree.

Please note that the web-enabled controller has been tested with IE6/7 and Firefox. Pocket IE for PPC 2003 is not currently supported.
Lua server pages have the extension .lsp. When a request comes in for an lsp page the web server parses the page for script blocks. If you are familiar with Microsoft's Active Server Pages you will know that script blocks are contained within script delimiters. Any text found between the <% and %> delimiters is treated as Lua script and each script block is executed as a Lua chunk.
<html> <body> <h1><% Response:Write('Hello World') %></h1> </body> </html>
You can have Lua output large blocks of HTML using the following technique:
<html> <body> <% Response:WriteLine('<p>Hello World</p>') Response:WriteLine([[ <h2>Sub-heading</h2> <p>Some text here...</p> ]]) %> </body> </html>
Response:WriteLine() appends a new line to the output. This helps to make the HTML output more readable. Response:Write() and Response:WriteLine() are 2 methods belonging to the Response object. The Request and Response objects are the two main objects available to Lua script blocks. They relate to the current HTTP request and contain various collections such as Headers, QueryStrings, Forms, and Cookies.
10.g.i. The Request Object
The web server script parser creates a local Request variable for each Lua script block. The Request object has four properties and four methods.
Request.Headers
public System.Collections.Specialized.NameValueCollection Headers {get;}
As a .NET NameValueCollection you have access to all of the methods and properties of the .NET NameValueCollection class. Please refer to the .NET SDK documentation for a full listing.
--Lua Example:
local host = Request.Headers["host"]
Request.Forms
As a .NET NameValueCollection you have access to all of the methods and properties of the .NET NameValueCollection class. Please refer to the .NET SDK documentation for a full listing.
public System.Collections.Specialized.NameValueCollection Forms {get;}
--Lua Example:
local postback = Request.Forms["postback"]
Request.QueryString
public System.Collections.Specialized.NameValueCollection QueryString {get;}
As a .NET NameValueCollection you have access to all of the methods and properties of the .NET NameValueCollection class. Please refer to the .NET SDK documentation for a full listing.
--Lua Example:
local id = Request.QueryString["id"]
Request.Cookies
public Chipmunk.Plugins.WebServer.HttpCookiesCollection Cookies {get;}
Cookies are a little more complex as they can contain sub-keys. You can access these sub-keys from Lua as follows:
1 -- Test to see if cookie1 exists 2 if Request.Cookies["cookie1"] ~= nil then 3 -- You can determine if a cookie has subkeys by examining the Values.Count property 4 -- If it is greater than zero, the cookie consists of subkeys. Loop through collection... 5 if(Request.Cookies["cookie1"].Values.Count > 0) then 6 local name = Request.Cookies["cookie1"].Name; 7 Response:WriteLine("Cookie Name: "..name.."<br>"); 8 local i=0; 9 while i < Request.Cookies["cookie1"].Values.Count do 10 name = Request.Cookies["cookie1"].Values.AllKeys[i]; 11 local value = Request.Cookies["cookie1"].Values[name]; 12 Response:WriteLine("SubKey Name: "..name.."; Value: "..value.."<br>"); 13 i = i+1; 14 end 15 else 16 local name = Request.Cookies["cookie1"].Name; 17 local value = Request.Cookies["cookie1"].Value; 18 Response:WriteLine("Cookie Name: "..name.."; Value: "..value.."<br>"); 19 end 20 Response:WriteLine("<br>"); 21 end
Request Methods
These four methods are simply shortcut access methods to the above properties. Request:GetCookie(cookiename) returns an HttpCookie object. The other methods return a string:
Request:GetHeader("host")
Request:GetQueryString("id")
Request:GetForm("postback")
Request:GetCookie("cookiename")
10.g.ii. Response Object
The web server script parser creates a local Response variable for each Lua script block. The Response object contains two properties:
Response.Headers
public System.Collections.Specialized.HybridDictionary Headers {set;}
As a .NET HybridDictionary you have access to all of the methods and properties of the .NET HybridDictionary class. Please refer to the .NET SDK documentation for a full listing.
--Lua Example:
Response.Headers:set_Item("CustomHeaderName", "CustomHeaderValue")
Response.Cookies
public Chipmunk.Plugins.WebServer.HttpCookiesCollection Cookies {set;}
Lua Examples:
--Add a cookie called cookie1 which has 2 subkeys (name1, and name2) local cookie = Chipmunk.Plugins.WebServer.HttpCookie("cookie1"); cookie.Values:Add("name1", "value1"); cookie.Values:Add("name2", "value2"); Response.Cookies:Add(cookie); --Add a cookie called cookie2 with a value of value2 which expires in 3 days local cookie = Chipmunk.Plugins.WebServer.HttpCookie("cookie2"); cookie.Value = "value2"; cookie.Expires = Chipmunk.Plugins.WebServer.DataTime.Now:AddDays(3); Response.Cookies:Set(cookie); --Make a previously sent cookie expire: Response.Cookies:MakeCookieExpire("cookie3", "/");
Response Methods
The following Response methods are available:
Response:Write("<h1>Hello World</h1>") Response:WriteLine("<h1>Hello World</h1>") Response:SetHeader("name", "value") Response:SetCookie("name", "value") -- Set a cookie with an expiry date Response:SetCookie("name", "value", Chipmunk.Plugins.WebServer.DataTime.Now:AddDays(3))
See Microsoft's .NET SDK documentation for details on the System.DateTime structure. In terms of cookie expiration you will need to know how to set a future date:
Chipmunk.Plugins.WebServer.DataTime(2006, 12, 31) - Set the expiry date to 2006-12-31.
Chipmunk.Plugins.WebServer.DataTime.Now.AddDays(3) - Set the expiry date to 3 days from today
Chipmunk.Plugins.WebServer.DataTime.Now.AddHours(2) - Set the expiry date to 2 hours from now
Chipmunk.Plugins.WebServer.DataTime.Now.AddMonths(1) - Set the expiry date to 1 month from today etc...
-- Lua Example: Response:SetCookie("Name", "Bob", Chipmunk.Plugins.WebServer.DataTime(2006, 12, 31)) Response:SetCookie("Name", "Bob", Chipmunk.Plugins.WebServer.DataTime.Now:AddMonths(1))
10.g.iii. Chipmunk.Plugins.WebServer.HttpUtility Object
The web server script parser creates a local HTTPUtility variable for each script block which helps shorten the namespace for this class. The static Chipmunk.Plugins.WebServer.HttpUtility class contains useful methods for HTML and URL parsing, encoding and decoding. It is a re-implementation of Microsoft's .NET System.Web.HttpUtility. See Microsoft's SDK documentation for details. Please note that whereas Microsoft's HttpUtility class is only available to Windows 2000 and XP, Chipmunk Web Server's implementation is available to older platforms as well.
string Chipmunk.Plugins.WebServer.HttpUtility.UrlEncode(string url)
string Chipmunk.Plugins.WebServer.HttpUtility.UrlDecode(string url)
string Chipmunk.Plugins.WebServer.HttpUtility.HTMLEncode(string html)
string Chipmunk.Plugins.WebServer.HttpUtility.HTMLDecode(string html)
string Chipmunk.Plugins.WebServer.HttpUtility.HTMLAttributeEncode(string htmlAttr)
-- Example of how to use methods from the Chipmunk.Plugins.WebServer.HttpUtility Class local html = HttpUtility.HtmlEncode("This <h1>text</h1> is HTML encoded"); Response:WriteLine(html.."<br>"); local url = HttpUtility.UrlEncode("Name 1=#value 1#"); Response:WriteLine(url.."<br>");
The Chipmun.Plugins.WebServer.HttpUtility.WebRoot property returns the current web root path:
print(Chipmunk.Plugins.WebServer.HttpUtility.WebRoot)
--> C:\Documents and Settings\[user]\Application Data\Home Cinema Solutions\Chipmunk AV Controller\2.0\Plugins\Web\Root
10.h. Windows Media Player Objects
10.h.i. Chipmunk.Plugins.WebServer.WMP.MediaInformation Object
All Windows Media Player functionality is contained within the Chipmunk.Plugins.WebServer.WMP namepsace. The web server script parser creates a local WMP variable for each executing script block. The longer namespace must be used when accessing the player from non Lua Server Page scripts.
Where methods return arrays use the array's Length property to loop through the collection:
local authors = WMP.MediaInformation.GetAuthors() if(authors.Length > 0) then for i=0, authors.Length-1 do Response:Write(HttpUtility.UrlEncode(authors[i])); end end
C#: public static string[] GetAuthors()
local authors = WMP.MediaInformation.GetAuthors()
C#: public static string[] GetAlbums()
local albums = WMP.MediaInformation.GetAlbums()
C#: public static string[] GetPlaylists()
local playlists = WMP.MediaInformation.GetPlaylists()
C#: public static string GetArtistFromAlbum(string album)
local artist = WMP.MediaInformation.GetArtistFromAlbum("Voulez-Vous")
C#: public static string[] GetAlbumsByArtist(string artist)
local albums = WMP.MediaInformation.GetAlbumsByArtist("ABBA")
C#: public static Song[] GetSongsByAlbum(string album)
local songs = WMP.MediaInformation.GetSongsByAlbum("Voulez-Vous")
C#: public static Song[] GetSongsByPlaylist(string playlist)
local songs = WMP.MediaInformation.GetSongsByPlaylist("MyPlaylist")
C#: public static Song[] GetSongsByArtist(string artist)
local songs = WMP.MediaInformation.GetSongsByArtist("ABBA")
C#: public static Song CurrentItem()
local song = WMP.MediaInformation.CurrentItem()
C#: public static Status GetCurrentStatus()
local status = WMP.MediaInformation.GetCurrentStatus()
C#: public static string GetImagePath(string sourceURL)
local imageURL = WMP.MediaInformation.GetImagePath("e:\\medialibrary\\mp3\\song.mp3");
10.h.ii. Chipmunk.Plugins.WebServer.WMP.NavigationControls
WMP.NavigationControls.VolumeUp()
WMP.NavigationControls.VolumeDown()
WMP.NavigationControls.Mute()
WMP.NavigationControls.Next()
WMP.NavigationControls.Previous()
WMP.NavigationControls.Play()
WMP.NavigationControls.Pause()
WMP.NavigationControls.Stop()
WMP.NavigationControls.Close()
10.h.iii. Chipmunk.Plugins.WebServer.WMP.PlayItems
WMP.PlayItems.PlayItem("e:\\medialibrary\\mp3\\song.mp3")
WMP.PlayItems.PlayAlbum("Voulez-Vous")
WMP.PlayItems.PlayArtist("ABBA")
WMP.PlayItems.PlayPlaylist("MyPlayList");
10.h.iv. Chipmunk.Plugins.WebServer.WMP.Song
C#:
public class Song {
public string Authors;
public string Title;
public string Duration;
public string Album;
public string SourceURL;
public string CollectionID;
public string TrackNumber;
}
--Lua example: local song = WMP.MediaInformation.CurrentItem() local artist = song.Authors local track = song.Title local duration = song.Duration local album = song.Album
10.h.v. Chipmunk.Plugins.WebServer.WMP.Status
C#:
public class Status {
public string Duration;
public string Elapsed;
public string State;
public string ImagePath;
public Song song;
}
--Lua example: local status = WMP.MediaInformation.GetCurrentStatus(); local duration = status.Duration local elapsed = status.Elapsed local state = status.State local imagePath = status.ImagePath local artist = status.Song.Authors local track = status.Song.Title
10.i. Windows Media Player Events
Windows Media Player raises two events: OnPlayStateChange and OnCurrentItemChange. OnPlayStateChange occurs when the Windows Media Player play state changes. The payload has one variable called "NewState". Its value contains the new play state:
[Payload DeviceID=6; EventString=OnPlayStateChange]
[Variable Name=NewState; Value=Playing]
NewState can have the following values:
| State | Description |
|---|---|
| Undefined | Windows Media Player is in an undefined state. |
| Stopped | Playback of the current media clip is stopped. |
| Paused | Playback of the current media clip is paused. When media is paused, resuming playback begins from the same location. |
| Playing | The current media clip is playing. |
| Fast Forward | The current media clip is fast forwarding. |
| Fast Rewind | The current media clip is fast rewinding. |
| Buffering | The current media clip is getting additional data from the server. |
| Waiting | Connection is established, however the server is not sending bits. Waiting for session to begin. |
| Finished | Media has completed playback and is at its end. |
| Transitioning | Preparing new media. |
| Ready | Ready to begin playing. |
| Reconnecting | Reconnecting to stream. |
OnCurrentItemChange occurs when an album or playlist transitions from one song to the next. The payload contains information relating to the new song. The payload has numerous variables:
[Payload DeviceID=6; EventString=OnCurrentItemChange]
[Variable Name=Album; Value=Cass Elliot]
[Variable Name=Authors; Value=Mama Cass]
[Variable Name=SourceURL; Value=F:\music\Cass Elliot\Cass Elliot\I'll Be Home.mp3]
[Variable Name=Duration; Value=03:37]
[Variable Name=Title; Value=I'll Be Home]
[Variable Name=TrackNumber; Value=1]
By learning these events, you can execute a Lua script and process the data. This will be particularly useful for sending the data to a VFD/LCD panel for example (or possibly displaying the data via the On Screen Display plugin).
The web server plugin consists of the following files and folders:
< Section 9: How to Use the Time Scheduler | Section 11: How to Use the RedRat3 Plugin >