How to use your RS232 or IRDA port for Remote Control
=====================================================
Blank Frank (veg@mindless.com) December 1999

Document version 1.0, 4th December, 1999

Contents
========
Introduction
WINSAMP.EXE
	What is it
	The user display and controls
	Command line options
MANYBUTT.EXE
	What is it
	The user display
	User controls
Code examples for Windows interfacing
Remote control protocols / known issues
Making WINSAMP work from Windows desktop when you can't run MANTBYUTT


Introduction
============
This document (README.TXT) is a companion to the html file (REMOTE.HTM)
available on my web page (www.veg.nildram.co.uk/remote.htm). It attempts
to explain the user interface and command line options for the dos-based IR
sampler program WINSAMP.EXE, the use of the Windows95/98 VB5 front-end
program MANYBUTT.EXE, and the methods it uses to interface to the dos
program, give some explanation of remote control protocols and deal with
some known issues surrounding some particular types of remote.

WINSAMP.EXE
===========
	What is it
	----------
WINSAMP.EXE is a dos-based program to sample and play back IR remote
controls used for TVs etc, using either a PC RS232 port + simple
hardware interface (schematic on web page) or an IRDA port (play back
only). The method employed (explained on web page) is, as far as I
know, novel, largely processor speed independent, and able to be
implemented on many different platforms (hand-held etc) so long as they
have similar serial capabilities. The samples obtained can be used on
other speeds of PC and on other platforms, without modification. They are
compact, easy to edit, print, import into other applications and send by
email.

WINSAMP evolved from my original experimental software, and contains a
number of little-used and/or obscure features and functions which were
really intended to help me develop the idea rather than provide extra
functionality for users in the long term. I have tested the program with
a selection of remotes from different devices and manufacturers, and
have tweaked or added features to cope with all the ones I've tested. At
present, I would expect the system to work as a replacement for the
majority of the controls out there, but there are some situations where
it is necessary to have some understanding of what's going on, and there
is a known issue with 'flash' controls. WINSAMP is a useful tool for
investigating how remotes work and for diagnosing problems.

Why bother? Well, my own situation is a real-life example. My main Pc is
in one room and my Satellite receiver and Video recorder are in the room
next door. The PC has a WinTV card for video grabbing and watching TV
while playing with the PC, and there is a coax feed from the boxes in
the other room. My sampler hardware is set up with a long 2-wire lead
for the IR led which reaches the next room, and a short lead to the
detector circuit beside the PC for grabbing samples. I have made a
composite remote on the PC by sampling the important buttons from both
the Sat and Vid remotes, and now I can channel-surf and play videos from
the comfort of the Windows desktop on my PC while doing other stuff. To
prove the point, I can put the same samples on the laptop and use the
IRDA port to control Sat and Vid so long as it has line-of-sight, though
it's easier just to pick up the actual remotes in this case. OK, hardly
a world-shattering application of technology, but it suits me. Perhaps
you can find other uses.

A word of warning before you get started. This should be obvious from
all the theory etc, but if you built the hardware illustrated on the web
page, make sure the IR detector circuit can't see your IR transmitter
led (if you have one) during sampling, otherwise the sample will
certainly be junk.

	The user display and controls
	-----------------------------
When you start WINSAMP as a stand-alone app with screen output, you are
presented with a horribly-cluttered 80*50 text-based display covered in
stuff. Starting from top to botton, left to right, here is a description
of what you should see, what it does and how to interact with it.

Top line banner - tells you how to exit (alt-x) and version number.

COM port currently in use (defaults to COM2 because this suits my
machine).

Line telling you how to get help (WINSAMP ?).

Current silence method (0xfe silence combs by default [see html file],
or real silence based on timing loop, in which case it shows a value
for the timing loop which is a tight loop taking approximately the same
length of time that it takes to transmit one character - this is
determined by experiment, you really need a scope to get it right, and
I do not recommend you use it; it depends on processor speed so is
outwith the spirit of what I'm trying to achieve, and is a remnant of
some early tests I did; if you insist, 't' toggles the mode, but there
is no way of changing it from the command line, so forget it).

Last key was xxx - this is the code associated with the most recent
keyboard button - left it in because it can remind you what you just
did, but mainly because it makes it easier for me to add features to the
program (remember, this is basically my experimental test bed).

Timeout cursor xxxx - this is fundamental and complex. It is a value
(default 1500) used in the post-grab phase to process the results.
Remembering that sampling is timed by transmitting a stream of chars at
115200 baud (ie in approx 104 usec chunks), this value is the number of
characters that have to have been sent before the software will begin to
look for a timeout. The actual sampling blasts out 2560 chars (by
default, can be mofified in 'silent' mode only) in a continuous stream
once IR is detected and gathers the results in an array, without
attempting to process the samples at all. Once the grab is complete, the
array is examined to produce counts for silent and comb periods. Once
the point determined by the timeout cursor has been passed, the software
will look to see if it is currently in a silent period which is longer
than the value for timeout, or keeps processing the array until it has
found such a silent period. This system makes sure that whole remote
packets are stored, and makes sure that there is at least a minimum
number of packets in the sample. A typical remote might send a packet
lasting 50 ms every 100 ms for as long as the button is held down -
moving the timeout cursor up and down allows control over how exactly
how much data is collected. The cursor is represented by a red
background character on the sillyscope (see below), and can be moved
using PgUp, PgDn, Home and End keys.

Chars for timeout - (default 100) - this is the number of consecutive
silent character chunks necessary to assume that this is a gap between
packets rather than within a packet. The longest silence I've seen so
far within a packet is about 43 chars, and the shortest silence between
packets is about 93 chars, but typically inter-packet silent periods run
around several hundred. If you have a remote with a silent time which is
shorter than the timeout value and you keep the button pressed until the
2560 char sample window has expired, the array will fail to decode
because it couldn't figure out a good place to stop. This situation is
easy to diagnose and fix - you need to change your chars for timeout
value using the '7' and '8' keys.

The sillyscope is 32 lines of 80 characters (=2560 chars) representing
the most recent sample. You can tell at a glance what the data from the
remote looks like. Character periods during which IR activity was
detected are shown as 'W', and silent periods are '.'. What you would
expect to see are alternating blocks of 'W's and '.'s, and the a red
character showing the current position of the timeout cursor. This makes
it easy to reposition the timeout to get the number of packets you want.
The sillyscope shows the raw data before any corrections for rounding up
or down etc are applied. You should get familiar with the characteristic
patterns of different buttons from the same remote, and different
remotes, because it will make it easier to diagnose problems with
samples if you ever encounter any.

The next thing is a grid of 40 buttons as text fields numbered 1 to 40.
You navigate around the grid using the arrow keys, and the one
highlighted is the button currently selected for sampling or playback.
Initially, all the text fields are white, changing to magenta once a
sample has been stored for that button. To grab a sample, select the
button field you want then hit the SPACE BAR. Previously set buttons are
overwritten by new samples, and new buttons will change colour when
sampled. Squirt an IR packet at the detector circuit (make sure the COM
port is correct) and you should see the sample appear on the sillyscope
and the button should indicate that it has been set. If you want to
transmit a sample, it must first show that it is set. Select the one you
want then hit ENTER. If you want to save all your samples as one text
file, hit 'W' - note that only the buttons which have been set will be
written to the file, and that there is no way of directly loading this
file into the program at a later time. This file is called REMOTE.TXT,
and can be handy outwith the program. If you want to build up a set of
buttons which can be reloaded, use 'S' to write a binary file REMOTE.BIN
which is a snapshot of the entire sample memory and has a fixed 16000
byte length. If you want to load a previous snapshot, use 'L'. All the
buttons which were set when the previous snapshot was taken will change
colour to magenta to show they are set. If you want to remove a button
sample from the current group, select it and use 'E' to erase it - the
button text will return to white - the not-set condition. The file name
REMOTE.BIN is fixed - if you wish to build up a collection of different
sample snapshots, you will have to take care of copying, renaming etc,
but this should be simple to do in a batch file. Files are read from and
written to the current directory.

The last thing on the screen is the decoded compact sample array
associated with a button. This appears whenever a sample is made
successfully (this does not mean that it will work, simply that it obeys
the timing rules being used at the moment) or whenever you select a
button which already has a stored sample, either from this session or
reloaded from a binary snapshot. The first number you see is a count of
all the sample elements, and should always be an odd number since there
is always one more comb than silent period. There may be an implicit
silent period following the last comb, but this should always happen
anyway because of the natural gap that exists between packets if you try
to fire out multiple packets in quick succession. The following numbers
are character counts for the combs and silent periods within the sample,
and you should find that if you repeatedly sample the same button the
numbers will be very similar if not identical - a jitter of one or
possibly two counts would be the most you should see. This decoded array
is effectively what gets put in the text file when you choose to Write a
text file - the actual format starts with a string in quotes followed by
a comma then comma-delimited data. The text string gives the button
number for each stored sample. Here is a fragment of one line from a
file - 
"button  2",47,8,9,7,9,16,8,8,8,8,8,8, . . . . . . . . . 
This button has 47 elements, and they appear to be approximately 8 or 16
chars wide (ie about 830 usec or 1660 usec), but this is only one of a
multitude of possible remotes.
The binary file REMOTE.BIN is 16000 bytes long, representing 40 arrays
of 200 words each, one for each button in ascending order. All of this
is written to disk regardless of whether or not it contains a sample.
For each 200-word block, the first word contains the count and subsequent
words contain the element widths for the button sample. Unused words
will contain 0x0000.

	Command line options
	--------------------
The program can be started with various command line options. Amongst
other things, these options enable the program to be called and
controlled by, for example, Windows95/98 applications to give much
greater apparent levels of sophistication and user friendliness. The
command line parameters are not case-sensitive (where applicable) and
can be supplied or omitted in any combination and order, though
priorities vary.

Options are supplied separated by spaces, like this -
WINSAMP opt opt opt ... (enter)

The options are -
?
Cx
Q
FILENAME
=x
+x
!x

- where x is a numeric value of the appropriate range.

What they do
-------------
?
-
This is a call for help. If it appears anywhere in the command line, it
takes priority over any other parameters (which will have no effect).
The program will start, dump a page of text about parameters onto the
display and exit.

Cx
--
This overrides the default COM port (COM2) using the value of x. Valid
numbers are 1, 2, 3 and 4. These are the only port numbers the program
can use, and they refer to the base addresses 0x03f8, 0x02f8, 0x03E8,
0x02E8 in that order, as seen by dos / bios. This parameter is relevant
in all cases except when ? is used.

Q
-
This makes the program start with no screen output. The program then
waits to grab one sample, writes it to a text file REMOTE.TXT (or other
file if FILENAME is supplied) and exits silently unless there is a
sampling or file error, in which case an error message will be left on
the screen. The string at the start of the text file will always be
"button  1", . . . .

If a file already exists, it will be overwritten without protest. If it
doesn't already exist, it will be created.

The string is really a placeholder. I do not know what the absolute
limit for the length of the string might be, but there is certainly no
problem in editing this to contain anything printable of a 'reasonable'
length, like 50 characters or something - this would provide enough
space for a verbose description giving button function and name,
manufacturer's name for the appliance etc. This method is employed in
MANYBUTT.EXE described below to set the captions for the buttons and
tooltip information, and with a bit of planning could form the basis for
an indexing system for thousands of buttons.


FILENAME
--------
This can be any legal dos filename longer than 2 characters including a
period if desired (ie 2 chars + period, or 3 chars without period,
minimum), and may include a path if the current directory is where you
don't want to find it or write it. Supplied along with the Q parameter,
this will cause a sample to be written to FILENAME rather than
REMOTE.TXT. Supplied without the Q parameter, the program will attempt
to play this back as a remote packet. All of the above will be silent,
except if there is an error, in which case a message will be left on the
screen.

*** NOTE *** Remember that if neither FILENAME nor Q is supplied, the
program will start up with a normal dos screen as described in User
Display and Controls above.

=x
--
This overrides the default sample size. It is only relevant when the Q
parameter is supplied, that is, you can only change the default sample
size from 2560 when you wish to sample with NO SCREEN OUTPUT. Clearly,
it would be meaningless for playback, and if there was screen output,
the sillyscope display would be messed up, so it is ignored except under
the particular circumstances explained in this paragraph. It would be
pretty much pointless to give it a value less than 2560. DO NOT give it
a value greater than 5000 (which is about half a second). There is no
error checking - just laziness on my part I'm afraid - maybe in the next
revision. The maximum sample array size is defined as 5000. If you go
past this something will undoubtedly break, with potentially
catastrophic results. You have been warned. So, =2561 to =5000 would be
safe limits.

Why would you want to change it? Well, you may find you get better
results with a longer sample than the default allows - some remotes
leave long gaps between packets and you may want to have more packets in
your sample. You'll need to look at the sample text file to figure out
what's happening, since you cannot change the value and have screen
output at the same time.

+x
--
This overrides the timeoutcursor default of 1500. You can increase it to
capture more packets in your sample or decrease it to zero if you want
and get only the first packet. A sensible bottom limit would be 400, and
the maximum must be at least 100 less than the sample size otherwise it
may not have the effect you want. I don't think you can break anything
by using crazy values for this parameter, the processing simply won't
work as expected, or in some cases work at all. This parameter works
both in silent and screen modes.

!x
--
This is the chars_for_timeout value (default 100). If you set it too
low, you may time out in the middle of a packet and the sample won't
work. If you set it too high, you may fail to detect a timeout where you
expect it and your sample will either be longer than you wanted or fail
to decode at all. Again, I don't think you will break anything if you
get it badly wrong, it simply won't work as planned. The default is a
reasonable compromise for all the remotes I've tested except one, where
I had to drop it to around !93 to get what I wanted. This parameter
works both in silent and screen modes.

*** NOTE *** I would suggest you leave the =x, +x and !x values alone
unless you really need to play.


MANYBUTT.EXE
============
	What is it
	----------
This is my Windows front end demo program written in VB5, which will
only run if you have the necessary runtime support files, which I can't
supply because of the pressure on my bandwidth. If someone wants to host
a full distribution package of about 1.6 meg, I'll send it and put a
link from my page. Bear in mind that this is only really a demonstration
to prove the usefulness of the technique - I have no intentions of
producing an all-singing all-dancing application myself.

MANYBUTT.EXE is copied to the same directory as WINSAMP.EXE. It provides
a convenient method for gathering and using samples while operating
under Windows95/98. The demo is actually fully working and satisfies my
requirements for controlling the Satellite / Video feed to my WinTV card
from the boxes next door. At various times, it makes use of all of the
command line options explained above. It features up to 50 remote
control buttons, but this is a purely arbitrary limit set because it was
sufficient for my needs. Each button sample is contained in a separate
text file (named BUTT1.BUT - BUTT50.BUT, again arbitrary), and settings
are maintained between sessions using a very small number of Registry
entries. It provides the facility for placing meaningful captions on the
buttons and more long-winded descriptions on associated tooltips. I
didn't feel the need to have the facility for timed functions, composite
buttons etc, but I can't think of any features offhand that could not be
achieved by building from what is already there, using the command line
features of WINSAMP.EXE that are already in place.

Button files are stored in the same directory as the programs, but this
again is simply down to my laziness. If it became a problem, it would be
easy to do something much more elaborate. As things stand, if I needed
more than 50 buttons for any reason, my first step would be to create
several directories each with a copy of the programs, with several
shortcuts each meaningfully titled to reflect the purpose. There is no
problem doing this because the dos program has only a transient presence
in normal operation, contention would only cause confusion, not
disaster, if you had multiple invocations waiting for samples
simultaneously, and all copies of the Windows program would share the
same Registry entries, which are only written to the Registry when the
program is closed.

	The user display
	----------------
The first time you run MANYBUTT.EXE, you will see a window containing 50
remote buttons, COM port selection radio buttons, some sliders for the
sampling parameters (preset to the default values - leave them alone
if you can), a long button under the first group of 20 remote buttons
which cycles the display through three different configurations, 4
buttons which do various things to the right of the sliders, and a check
box designed to prevent accidental destruction of existing samples.
There is no Windows 'Help' as such, but I have been if anything over
liberal in the use of tooltips, and explanations keep popping up
annoyingly all over the place. You can actually play with all this even
if you don't have any sample / playback hardware attached, and probably
should.

If for some reason you can't see all the buttons, click the long one
that is always visible one or two times and this will let you see all
available display modes. I'm sure you'll get the idea in no time, after
all, it's meant to be simple to use.

There is no Exit button - you simply close the program using the X in
the top right hand corner.

	User controls
	-------------
If all goes according to plan, the program should start up with two
remote buttons showing captions. These are derived from the sample
button files BUTT1.BUT and BUTT18.BUT. They are actually the power
buttons for my Sat and Vid. If you move the pointer over the buttons,
you will see tooltip descriptions. If you uncheck the 'samples locked'
check box, you can right-click on either of them and the corresponding
file will pop up ready for editing in notepad - this will let you see
exactly what's going on. If you choose to edit a file, remember to save
it, close notepad and hit the 'Refresh Captions' button to force a
reload. This is very important. You must ALWAYS remember to refresh the
captions after editing or sampling, otherwise you won't be able to do
anything with newly-sampled buttons or see your changes unless you close
the program and restart it. Only buttons containing samples can be
edited, so you can not make a sample 'by hand' from within the program,
though there's nothing to stop you trying this explicitly with notepad
or whatever from outside the program.

Select the radio button corresponding to the port where your hardware
lives (do it correctly, odd things might happen if you select the port
where your mouse or modem lives, for instance, and neither the Windows
nor the dos program performs any kind of sanity check on this point).

Only buttons which have been set (ie have a caption) can be transmitted.
Left-click on one of them and you should see a dos application thing
appear briefly on the taskbar. This is the dos program kicking in and
sending the associated sample file then closing itself. If the dos thing
persists on the taskbar for more than a fraction of a second, there is
a problem. The caption will probably say 'Finished'. Don't panic. Click
on the takbar app and up should pop a window which is a remnant of the
dos activity containing a meaningful error message. Study the message,
close the window using the X in the corner and try to fix the problem.
You can always use the three-finger technique to get to get rid of these
leftover dos windows too, but be careful.

If you want to grab a sample, again make sure the 'samples locked' check
box is unchecked, hold down the shift key and left click on the button
you want to use. This time one of four things can happen. Firstly, the
dos app could flash up on the taskbar for a very short time then
disappear - this most likely means there is no sampling hardware
present, or it is faulty. No harm done from the software's point of
view, but of course no sample either. Secondly, the app could appear on
the taskbar, wait for you to squirt your remote at the hardware, then
disappear - this probably means you got a good sample, or at least some
sort of sample - you'll need to test it or look at the file by right
clicking to confirm this, after refreshing the captions of course.
Thirdly, the app could appear, wait for your sample then persist on the
taskbar with the 'Finished' message - this means there was a problem and
there should be an error message waiting for you when you click on the
app to help you sort it out. Fourthly, the app could appear and just sit
there unchanged even after you fire your remote at it - this means the
IR was not detected - could be wrong COM port, remote out of range or
faulty hardware. In this case, you'll need to kill the app by right
clicking on the task bar, selecting close and clicking the Yes button
when Windows asks you if you would like to terminate it. Again, no harm
done, but you'll need to figure out what went wrong, which brings us
neatly to the next button.

The 'Sample Screen" button brings the dos app up in its normal dos
display mode. This will help you experiment, get a 'feel' for remote
control characteristics, and diagnose problems.

'Restore Defaults' puts the sliders back to their default setings.
Simple.

'Help Screen' makes the dos app dump command line help to the screen.

As previously mentioned, the 20/50/50+controls button is always visible
and cycles through the various window views. I usually run it in 20
button mode. The display always comes up in the mode it was in when you
last closed the app. Obviously, to access the sampling features, the
buttons have to be visible, because you need to uncheck the lock, which
always comes up locked, and you should need to use the Refresh Captions
button too.

To erase buttons, either delete the associated .BUT files or edit the
the contents to zero length (which you can do from within the program).

Code examples for Windows interfacing
=====================================
Here are some examples of code for interfacing VB programs with
WINSAMP.EXE.

Note that spaces contained within quotes are all significant.

How the various strings are set up.
p$ = " !" + Trim(Str$(100))  'chars for timeout
s$ = " =" + Trim(Str$(2560)) 'sample size
t$ = " +" + Trim(Str$(1500)) 'timeout cursor position 
c$ = " C1" or c$ = " C2" or c$ = " C3" or c$ = " C4"
filename = "butt"+Right$(Str$(index+1),Len(Str$(index+1))-1)+".but"

This passes a filename BUTTx.BUT to WINSAMP.EXE for transmission. x is
determined by the INDEX value from the control button array, which in my
case is in the range 0 - 49. Transmission is through COM port given by
c$.
Call Shell("winsamp.exe "+filename+c$,2) '2 makes it visible on taskbar

This grabs a sample into FILENAME through COM port given by c$
Call Shell("winsamp.exe " + filename + " q" + c$ + p$ + s$ + t$, 2)

This opens a button sample file for editing.
Call Shell("notepad.exe "+filename,1) '1 means normal window with focus

This produces the dos screen dump of help information.
Call Shell("winsamp.exe ?", 3) '3 means window maximised with focus

This opens WINSAMP in full dos window, with all settings passed.
Call Shell("winsamp.exe" + c$ + p$ + s$ + t$, 3)

You can omit the sampling parameters from the command line string if you
you don't want them.

I think that more-or-less says it all.

Remote control protocols / known issues
=======================================
I'm not going to say much about protocols, because there is plenty of
general information 'out there', but there are a couple of things worth
covering.

A word about 'flash' controls. These generally use the same sorts of
protocols as more conventional remotes, the difference being that rather
than sending out combs of pulses, they send out a single pulse timed to
happen at what would be the start of a comb - this may allow them to use
greater peak IR power or simply make the batteries last longer. There is
nothing very clever about decoding them, but clearly my sampling method
as it currently stands would make the assumption that there were combs
involved when in fact there aren't, and since I also put pulses out
during the silent periods, I don't think there's any chance it will
work. You should be able to identify this type of control from the
sillyscope however, so at least you will be able to give up without
wasting much time. If the sillyscope ever shows lots of single 'W'
characters with mutli-character silent periods between them, there is a
good chance this is a 'flash' control.

One of the common control protocols actually toggles the output pattern
between consecutive pushes of the same button. The receiving device
seems to expect either a different button or the same button with its
other pattern each time it gets a packet. For example, normally a TV
'mute' button would toggle the TV between muted and not muted with each
button push, but if you sample the mute button and fire it out
repeatedly to a TV which uses the toggling protocol, only the first
button push will be recognised, unless you push other buttons in
between. This can have strange effects, not only with this software but
also with the proper remote itself. A sample which works perfectly the
first time you use it has absolutely no effect when you use it again
immediately afterwards. It is easy to spot this type of remote. You
should make two consecutive samples of the same button and compare the
decoded results - if you see two repeatable patterns rather than one,
you have this type. One way to work your way round this is to sample
both states for each button, and use the alternate set if you get stuck.
It would be easy enough to modify the Windows software to handle this
automatically, but it does complicate things a bit having to be aware of
the type of protocol if not the actual details. Another way would be to
fire out a 'neutral' button between real buttons, and this could be
manually edited into the sample text files if need be.

Making WINSAMP work from Windows desktop when you can't run MANTBYUTT
=====================================================================

You can still enjoy the benefits of a Windows interface even if you
can't get MANYBUTT to run. This requires a bit of work on your part, but
it's far from impossible.

Start WINASAMP with normal dos screen using the correct COM port. Sample
and test the buttons you want. Save the binary image ('S') so you can
reload it to make changes to your sample set. Write ('W') the text file
REMOTE.TXT as well, and edit this to give you separate files with one
line per file. These will be the filenames you put in the command lines
when you edit the properties of the shortcuts you make. In Windows,
create a new program group, and put in a shortcut to WINSAMP, with the
correct command line (give full paths for safety, and don't forget the
Cx parameter). Set it to run minimised. Then copy the shortcut to suit
the number of button files you have. Edit the Properties to give each
shortcut a meaningful name and a different button file name. You could
also change the icons etc if you want, but you get the idea. A bit of a
drag, but easy enough. The only drawbacks are that you need to double-
click each shortcut to make it fire, and you miss out on the convenience
features of the Windows program.

-------------------------- The End -----------------------------

