Thinktank

Ridiculous Laws

Here’s some humourous food for thought.  Those of you in front of a Linux/Unix system, install fortune-mod and have a squiz at /usr/share/fortune/law — or just view this file that I have compiled.  Looking around, I found some more from elsewhere.

After you’ve stopped laughing… a query… How many of these laws are actually true?  I’m curious to know.

One theory that was proposed to me, is that there may not be a law as such prohibiting some act mentioned, but that someone was charged whilst doing an act mentioned in that document.  (e.g. shooting off a policeman’s tie… shoot anywhere near a policeman, and I’ll bet you’ll get busted!)

So, a query… how many of these are urban myth, and how many are actual laws?  And what law enforcement agency would have the audacity to enforce them?

Antennas and Baluns

Well, I spent much of my weekend fooling around with antennas in one form or another.

I had taken down my HF rig to bring to the Brisbane Amateur Radio Club social — to sort out why it wouldn’t tune up on 10m… the problem turned out to be my power supply. I was using an old 250W AT computer PSU capable of supplying 9A at 12V. My radio, a Kenwood TS-120S is a 100W radio, and draws 20A when running full power. Now I had assumed since the mic gain was turned down to comply with my 10W limit, so the limited power wouldn’t be a problem… not so… it turns out that although I turned the mic gain down, the radio still wants its 20A for voice peaks. This causes the voltage to drop, and of course, instability.

Well, BuyEquip had some 600W ATX power supplies, that advertised a 52A 12V output rail, brand new for $60, so I snapped one up. A few more bits and pieces, and now my radio is much happier on 10m. Interestingly, the box says 52A, the unit itself says 20A… either way, I’ve met my requirements. 😉

Earlier when I had my HF rig set up, I had taken the balun out since I noticed it seemed to be shorting out the feedline (measured with an Ohmmeter), and I couldn’t even pick up commercial SW stations (I used to hear Radio New Zealand quite strong around 7.145MHz).

I later discovered that it’s quite normal for a 1:1 balun to appear as a DC short… my balun uses ~10 turns of not-very-thin copper enamel wire and I guess I’m used to transformers for other applications where one sees a much higher resistance. Transformer Baluns are typically almost purely reactive — remember the reactance of an inductor is Xl=2(pi)fL — at DC, f=0, thus my ohmmeter sees Xl=0.

However, I knew I had done something wrong when wiring it up as when I disconnected the shield — I received Radio NZ S9+10dB, connecting the shield back dropped that to S2.

In the meantime, I used a 5cm piece of RG58, soldered straight to some 300ohm ladder line (surplus from my sim jim antenna).

I wasn’t sure that I had wired the balun correctly — and had lost the plans, so I set about locating some on the ‘net. A quick search revealed this page from the Antrim & District Amateur Radio Society. Well… what a difference it made… my noise floor on 80m went from S7 down to S3!

I spent the evening chatting on the Australia Wide Night Owl Insomnia Net (Friday evenings after 10:00PM at 3.6MHz LSB) — talking with stations as far away as Coffs Harbour, and even heard a feint amateur contact from New Zealand (ZL1?? callsign).

The other issue, was with my handheld. I’ve got two portable antennas for it, neither of them are particularly efficient on 2m, both are brilliant 70cm band antennas. One is the antenna that Kenwood supplied with the radio, the other was a Comet SMA3 antenna that I had bought at BARCfest. Not bad for portable use — but I wondered if I could do better.

People might remember my old project, the Hat-lamp, where I set out to homebrew a headlamp using a hard hat. Two radio amateurs suggested that I add an antenna mount to that — one suggested I could have a SMA-SMA socket adapter there and use my handheld’s existing antenna, the other suggested a SO239 socket on the top with a mobile antenna.

Well I gave the idea some thought… The big issue with this is two-fold: clearance (the antenna would have to incorporate a spring to absorb being whacked against low objects) and the social aspect (what would people think after seeing it). Neither of the handheld antennas were particularly good on the former part — I managed to bend the newer antenna once just sitting down — it’s mostly bent back into shape now, but I didn’t want to risk it. Both would be rather conspicuous though. A mobile antenna would be a rather heavy thing to have sitting on one’s head, so I gave that idea a miss.

I found some stainless steel fencing wire that was quite stiff, and cut off about 60cm of it. The idea was I’d wind the bottom of it into a spring, and a SMA plug would be soldered to the end (using some copper enamel wire to make the connection). Well, I built that Saturday Night, and using it directly on the handheld, noticed an immediate improvement in performance — I was hitting repeaters I normally don’t hit unless I’m plugged into the roof antenna. It is shown below… click on the photo for a larger view.

Homebrew portable whip

Last night, I set out to attach the antenna mount to the hat. One hole and a bit of elbow grease later, I had screwed the SMA-SMA adapter into the hole. The antenna neatly screws onto the fitting around the back of the hat, and a length of coax screws in underneath running to the radio. I haven’t tried walking around outside with it, but indoor performance is good.  The photos below show the socket views on top and underneath the hat’s brim…

Antenna mount/socket topAntenna mount/socket underside

The plan, the whip is still rather conspicuous — and there’s the risk of doing someone an injury if I’m not careful where I point the whip. I’m now looking around for a souvenir peacock feather that I can stick the antenna up the centre of… the idea being the assembly becomes decorative as well as functional (below is what it looks like now, sans feather). Well kinda… it’ll still look weird, but hopefully people will notice the feather rather than the antenna. 😉

Antenna mounted on hat

Join the FaceBorg

Seems I’ve coined a new term tonight… “faceborg”.  Okay… seems others have come up with the same idea before me, as pointed out by others.  Not sure what to call the MySpace users… I’m sure someone will come up with a succinct term for them. 😉

Ever since social networking sites such as MySpace and FaceBook have come on the scene, the internet veterans have been under increasing pressure to join up with these sites.  Me?  I don’t see the point.  They don’t appear to offer anything new.  From what I can tell, they are centred around allowing someone to create their own identity.

The misconception out there among the non-technical people, is that you need to be part of one of these sites to have an online identity.  This is simply not true.  You can achieve much the same thing, through the use of traditional media such as email, IRC, and modern media such as blogs.

The one big “advantage” I keep hearing, is that it makes it easy to find others.  Again… you don’t need these social networking sites for that.  There are two ways you can achieve what these sites give you:

Keep your identity consistent.  If you like being known by a certain nickname, then use that nickname.  You can also put your real name up there too if you wish, and anything else that identifies you.

In my case, there are three identifying keywords that will locate me in many search engines: my full real name, my nickname, and my radio callsign.

The major thing that social networking sites offer however, is friendship lists.  Guess what… good ol’e HTML provides that already.  And blogs these days offer XFN.  You simply link to your friends’ blogs/webpages… and voila… your friendship is instantly publicised.  Many search engines also track links between sites — so they will also pick up on these links.

What are the advantages in having your own blog/site?  Well, you can have all the bells and whistles you like.  Want to post videos?  No worries, there are tools for doing exactly that, and embedding them in your blog posts.  The other big advantage, is you’re totally in control — you own the content, and you’re responsible for it.

How about messaging?  Well… you can add that to your blog… there are facilities that can accept such addons.  Or there’s a plethora of tools already out there… such as IRC, XMPP, MSN Messenger (dare I mention it), and of course, plain old email.

To those who are already on these social networking sites.  Great… you’re happy where you are… this is fine.  However, don’t be disappointed if the rest of us, who may likewise be happy with where we are on the web, don’t come rushing to join you.

Keeping things simple

I’ve been doing some thinking today.  I haven’t been in the amateur radio gig very long… I got my license in mid January, and I’ve been active mostly on the 2m and 70cm bands for the past few months.

The last month saw me acquire the parts needed for a HF station, and so lately I’ve also been poking around on 40m and 80m too.  I’ll admit I’m still very new to the scene, getting to know what bands are best in what conditions, and making a small number of contacts.

I’ve been very active lately on 70cm on the Mt. Coot-tha repeater, VK4RBC (438.525MHz), and have been on the odd occasion, tried making contact on various frequencies on HF.

At BARCfest this year, a number of commercial traders were present, showing off the latest and greatest from two of the big communications companies out there… ICom and Yaesu.  It was at BARCfest, that I picked up my current HF rig, a Kenwood TS-120S, and a few sellers had a number of older rigs on sale.

Now this particular rig is quite old… according to the eHam site, they are 1980s vintage, although the exact date my rig was manufactured is unclear.  As far as features, it’s basic… SSB and CW modes, coverage of 80m, 40m, 20m, 15m and 10m, and around 100W output.  For my needs, okay, the power output is overkill, but it’s sufficient.  In fact, the power output is good, as if there is an emergency, I have the extra power to make contact.

At BARCfest however, there were some of the very latest rigs on display.  There was one Yaesu base station monster being shown off by Kyle Communications, I can’t recall what model, but its (discounted!) price tag was around AU$8000.  This thing did just about everything except errect its own antenna and make you coffee.  SSTV, RTTY, Packet, DSP filtering, you name it, it had it.  Very impressive, but are all these gratuituous bells and whistles really needed?

One thing I like about the rig I have, is that the handbook includes full schematics of the transceiver circuitry, with explainations on how it works.  It’s all implemented using solid state components that are easily sourced.  In fact, the handbook has some hand-written notes suggesting that the thing has been serviced a couple of times before hand already.  Being basic in features, has enabled it to be serviced, and I suspect that I should have this rig for a very long time, as long as I can get replacement parts — I see no reason why it shouldn’t continue operating for years to come.

However, rigs like the one I described above, the average operator, I suspect, would be helpless to try and fix a complex beast like that.  There’s just so much that could go wrong, and loads of specialised components that are purpose built for it.  Sure, it might be off-the-shelf DSPs and microcontrollers in use… you might be able to buy replacements… but where do you go to get them reprogrammed so they perform the function for which they are intended?

Even my handheld, a Kenwood TH-F7E, is a rather complicated beast.  It has a small microcontroller in it, and a lot of integrated circuitry, that I couldn’t possibly fix if something went wrong.  I bought it because it had FM transmit capability on 2m and 70cm (the only two VHF/UHF bands I’m permitted on presently) and it could receive AM, {,W,N}FM, SSB and CW over a wide range from 100kHz through to about 1.3GHz.  Now okay, in order to minaturise the device, it was necessary for specialised components to be used here… that’s fair enough, but I can forget doing much in the ways of repairs.

I believe that base station rigs are getting overly complicated these days — we really need to get back to basics.  For someone like myself, I really only need a few basic features:

  • Coverage of all the analogue modes: CW, AM, FM and SSB
  • Reasonable output power
  • Good sensitivity/selectivity
  • Digital readout

All of this (except digital readout) can be implemented with analogue electronics.

Digital modes in my book are better implemented on a desktop PC.  Computers these days are quite capable of doing software DSP… I don’t see any reason why it is necessary for the transceiver to do all that.  A small microcontroller inside the rig to provide PC control, and memory banks, no worries… but that’s about as complicated as it needs to be in my opinion.

Heck, there’s no reason why some of this couldn’t be modular — that is, the rig works without the microcontroller.  The microcontroller would just be responsible for loading/storing VFO frequencies, and switching modes — if it’s absent, this just gets done manually by the user.  The controls on the front would just manipulate digital flip flops, that could also be driven by the microcontroller.

The upshot is, a rig like the above, could be made quite robust… and reasonably inexpensive.  Some of us don’t need the frills — or if they do, are sufficiently knowledgable enough to make them ourselves.  There are people who will demand very fancy rigs, and that’s fine… there’s plenty in the market now to cater for that group of operators, but for the rest of us, I think a lot could be gained from reducing the complexity in current transceivers.

Looking around for a practical hilbert transform implementation

I’ve been pondering this idea for a while now. When I’m at home, I like to listen to my music… and sometimes, talk to people using VoIP. One big bug-bear I have, however, is being tethered to a desk by the cord of a headset.

Now… I basically have a few options:

  • Cordless headphones (either infra-red or radio) — but these usually are receive-only. I’d need to rig up some sort of cordless microphone to transmit a signal the other way.
  • Bluetooth headset — but they’re much too expensive, and I have no idea how well Linux works with them.

I’ve heard comments that both of the above options, have somewhat lesser audio quality, than a wired set. Many cordless headphones operating on radio, use stereo wideband FM to transmit a signal with a bandwidth of approximately 15KHz/channel. This is okay for what I want, but if I can do better, I might as well aim for it. 😉

Bluetooth headsets offering the A2DP profile, may do better, but they do it through the use of lossy compression. To be honest though, I’m also concerned with compatibility — I don’t have any Bluetooth interfaces on my computers so I’m up for a dongle. My phone (a Nokia 3310… yes, I’ve had it since 2001) doesn’t support Bluetooth, thus the only device I’d be able to use it with, is my laptop. I don’t have a lot of money to experiment — and headsets of this nature cost around AU$250 or more.

So I’m looking at homebrewing a set. Looking at the ACMA radio frequency class licenses, it would seem these devices are classed under the LIPD class license. I’ll have to double check with the ACMA on this… but looking at the gory details, it would seem there are a few bands that are allocated under this license for this purpose…

  • 88MHz – 108MHz (FM broadcast band) with 180kHz bandwidth and maximum EIRP of 10µW
  • 174MHz – 230MHz (VHF television) with 330kHz bandwidth and maximum EIRP of 3mW
  • 520MHz – 820MHz (UHF television) with 330kHz bandwidth and maximum EIRP of 100mW

Now… out of these… the 520MHz-820MHz band has the most liberal power limit of the three, and is also the least populated of the three bands. The catch is… all three of these have to use FM.

There are three signals to be transmitted in two different directions for this project…

  • Two 25kHz audio channels, transmitted by base station to be received by the headset.
  • A single 25KHz audio channel, transmitted by headset back to the base station.

For the headset microphone->base station path, this is trivial… I’ll just use one frequency to transmit a 25kHz mono signal, modulated on a wideband FM carrier. Easy. The difficult bit, is the other direction.

Stereo FM is normally achieved through the use of a subcarrier technique. The left and right channels are transformed into two signals that I call the mono signal (left + right), and the differential (left – right). They’re both band-limited to 15kHz. The mono signal is sent at baseband, with the differential modulated using a DSBSC subcarrier at 38kHz. The entire modulating signal has a bandwidth of 53kHz, generated by these two 15kHz sources.

My idea… is to use single sideband to conserve the bandwidth a bit. I’m undecided as to how I’ll transmit the left and right channels, whether I transmit them separately, or using the mono+differential technique discussed earlier. However it’s done… the plan is that one signal will be transmitted at baseband, and the other… using upper-sideband at approximately 30kHz. The entire modulating signal will have a bandwidth of approximately 55kHz, generated from two 25kHz sources. By reducing the bandwidth of the modulating signal, I hope to improve the noise immunity of my system so I can rely on minimal transmission power.

I have covered the principles behind single-sideband transmission, including simulating a Hartley modulator using Matlab. But looking around, I can’t see any schematic or notes on a Hilbert transform. It should be noted that a real-world Hilbert transform is an approximation, since the theoretical one is non-causal — this is why Harley modulators have a compensating delay.

There’s notes on how to implement them using discrete signal processing techniques, but I really don’t want the complexity of a DSP in something so trivial. I know it can, and has, been implemented using analogue electronics. If anyone knows of a simple, easy-to-follow schematic or notes on the topic… I’d be greatly interested. 🙂

Looking around I’ve found these documents… but if people know of others, I’m all ears. 😉

ObsoleteToo: Gentoo for obsolete computers

I had a bit of a crazy idea today. Some would think I had a little too much spare time on my hands … but maybe there’s a point to this insanity.

Many of us have old computers laying about. Now, “old” is a subjective term. As goes the Weird Al song, “All About the Pentiums”…

You say you’ve had your PC for over a week?
Throw it away man — it’s an antique!

(Well, that’s how I remeber it… I might be paraphrasing a little.)

Not everybody needs a fancy box to do simple tasks. Pentium-class systems, and high-end i486 systems make quite decent X-terminals. As slow as early 486s and 386s are, they still are useful in situations where you just need a router or DHCP server (for example) to service a small home network.

I’m planning to put my 386 into active service. My Qube2 sits in my laundry, which is great. It’s cool, it’s a headless box with no need for direct interaction.

But interacting with the serial console is a pain, I have to get my laptop out, and plug it in. Thus I probably don’t do as much kernel testing as I should.

The 386 should be fast enough for this task — all it needs to run, is sshd and minicom. For a single user. Gentoo using uClibc sounds like an ideal platform. Why?

  • Minimum bloat: I merge what I need, and nothing more
  • uClibc is targetted at low-memory, low-processing-power computers
  • Gentoo gives me fine-grained control regarding what features I enable and disable.

Now the box is rather slow booting Gentoo. If I boot root-over-NFS, it takes about 30-35 minutes. I can reduce this to about 20 minutes when loading from a local HDD (narrow SCSI, as it happens), but I haven’t got far installing it due to problems with flakey disks. The kernel reports a BogoMIPS reading of about 3.9~4.2 when running at full-speed (33MHz), and about 1.6 with the “turbo” feature disabled.

Once I get it going however, it should simply be a matter of re-merging dropbear sshd (the default one in the Gentoo/uClibc stages dies with a SIGILL), merging minicom and a bootloader, and voila.

Any updates can be done via a chroot on a faster box, then the binaries shipped to the 386. Bootup time isn’t an issue, since the box can just sit there running — 386s don’t chew that much power.

This is quite low down in my priorities, at the moment I’m concentrating more on getting Gentoo/MIPS 2007.1 out the door, hopefully with some newer netboot images for Cobalt, and maybe some first ever boot images for Loongson.

But after that, I may look at what the Gentoo/Embedded people have (particularly GNAP) and see if that can be adapted to suit the needs of older computers.

I see no reason why this can’t be done — I’d much rather see the code in Gentoo streamlined to work better on older computers, than to see the specs increased, as this streamlining benefits all — not just those with few CPU cycles to spare. 😉

Making the internet messaging accessible — Facimile over IP

Atomic MPC forum user, freakonaleash, asked an interesting question regarding sending faxes over IP. This got me thinking.

We’ve got solutions for an internal LAN such as Hylafax for an intranet-based fax-over-IP solution. But nothing exists that could be considered similar to Voice-over-IP. I can’t use the internet for instance, to send a fax overseas — and sometimes just like the telephone, one needs to fax a document.

There’s also the situation of inexperienced people. People like my grandparents, wouldn’t have a clue how to use a computer to send an email, or maintain a PC. Linux distributions have gotten to the point where I’d be quite comfortable setting up a minimalist Gentoo or Ubuntu installation on an old PIII box — to allow basic email and web browsing, but I still need to be around to keep it updated and maintained. Even if I were to go throw Windows XP on the same machine — I’d still have to maintain it.

Email offers some very useful options for such people — e.g. the ability to send letters and other correspondence and have it arrive at the other end within a day or so. (and that’s if the mail servers are having a bad day!) These days, one can buy a hardware device that provides VoIP capability, one can purchase devices that offer limited web-browsing capability without the need of a full-blown desktop computer, why not an internet appliance for sending and receiving email?

Well, I don’t see the need for a whole new protocol. SMTP and POP3/IMAP will do just fine for the actual FoIP capability. The issue is the interface to these protocols. I’m thinking an internet facimile would offer the following:

  • Ethernet interface for connection to the internet via a router.
  • Internal ADSL and/or PSTN modem for stand-alone internet access without other hardware, and standard fax capability
  • LCD Display and keyboard for reading/composing mail and user interface (touchscreen)
  • Onboard scanner and printer
  • Handset/headset jack for voice communications (either VoIP or standard land-line)

The idea, is that someone who doesn’t have a proper understanding of computers, could send a message over the internet using this device. They would simply hit the “Compose” button, fill in the recipient’s fax number (standard fax) or email address (FoIP), a subject for the message and cover letter, then scan in whatever attached pages they wish to add (these would appear as PDF, JPEG or PNG attachments). Some models may include USB ports and card readers, to allow attaching arbitrary files from USB drives and flash cards. Once they’re happy, they get the option of either sending it right then and there, or storing it to send in a batch run.

For privacy, perhaps something like PGP could be incorporated, thus allowing messages to be encrypted. There’s scope for this device to act as an internet router, networked printer/scanner, and VoIP ATA box too, which could be add-on features.

In essence though, the box could just sit in the corner… and say, overnight, connect to the internet, download any new messages, send any unsent messages out.

I might look into something like this, as it seems in the open source world, we have pretty much all the necessary pieces — just a matter of piling the right software on a standard PC and we’ll have a proof-of-concept prototype.

PHP and templating engines

Update: Seems I should have read this page first… we were thinking on the same wavelength afterall. I’ll leave the post here, since I think my (and Brian Lozier’s) argument is still valid with respect to the overheads in various templating engines…


It has always fascinated me, with large-scale PHP projects, how people seem to flock to overly complicated templating engines. I’ve worked on a couple of such projects, and it got me thinking about why we do it.

My first real contact with a site that uses templating engines was the Asperger Services Australia site. Originally, it was a static-HTML site done in FrontPage, but after looking at a number of CMS systems, we finally chose TikiWiki to run the site. TikiWiki utilises the Smarty templating engine — a behemoth weighing in at just over 1MB.

Smarty wields a lot of power, able to do numerous transformations with strings — but it’s a big package, and takes quite a while to master. It also seems to occupy a lot of memory, and requires write access to directories to store “compiled” templates.

This year, we built a web application called Teamworker. Our implementation was written in PHP using MySQL, and basically it was a ground-up re-write of an internal QUT webapp of the same name (many QUT students probably know it well). For this project, we wound up using the bTemplate engine, a far simpler engine than Smarty, it uses simple string replacement of XML-like tags. It has quite a few limitations however — for instance, one cannot have two loops of the same name — it’ll substitute one, but not the other. It isn’t difficult to pick up, but some aspects of its syntax are … awkward.

I dare say if I look hard enough, there’s probably some poor sadistic sod trying to do it with XML and XSLTs. Yes, they have their place, but they’re massive overkill. If your data is already in XML to begin with (i.e. Gentoo’s site) then sure, go for it, but otherwise it seems to be (to me anyway) a really messy way to do things.

PHP, believe it or not, actually is a templating engine. It has all the features one needs. All the code I need goes inside tags like this: <?php ?>, and outside of these, I can have just about anything I want. I can also use conditional statements inside PHP tags, to control what gets displayed outside… e.g. suppose I define the variable $logged_in, a boolean, and the string $user… a webapp might have:

... random HTML code...
<?php if ($logged_in) { ?>
Hello <?= htmlentities($user) ?>.
<a href="profile.php">Profile</a>
<a href="logout.php">Logout</a>
<?php } else { ?>
Hello guest. Please <a href="login.php">log in</a>
<?php } ?>
... more code ...

Voila… done. To whistle up this template, a script only needs to initialise $logged_in and $user, then include("template_file.php");, and it’ll appear as they expect.

However, this requires that your templates be structured a particular way. You’re more-or-less generating things on-the-fly, rather than constructing everything in a buffer, then sending it later. This can lead to display code getting mixed up with computation code, which isn’t terrific. So in these situations, PHP needs a little helping hand. Enter, the 8-line templating engine.

PHP since version 4 supports output buffering. These allow the programmer to control when and how, data is released to the browser. In addition, it is also possible to fetch the rendered output from the buffer as a string then clear the slate. This gives us great power to create a very simple but flexible templating engine, in 8 lines of PHP code:

function doTemplate($templateFile, $data) {
extract($data);
ob_start();
include($templateFile);
$_out = ob_get_contents();
ob_end_clean();
return $_out;
}

It’s crude, but it works. A site can then be easily put together using this method. No files need to get written at runtime, there’s no special syntax required. The idea is the template files are just very trivial PHP scripts — one uses as few functions as possible to achieve the desired page output. So built-in functions such as if, foreach and similar constructs, and maybe the odd include(). A site might use an overall template like the following:

<html>
<head>
<title><?= htmlentities($page_title) ?></title>
</head>
<body>
<h1><?= htmlentities($page_title) ?></h1>
<hr />
Navigation: <?php foreach($navlinks as $link) { ?>
<a href="<= $link["target"]; ?>"><?= htmlentities($link["title"]) ?></a>
<?php } ?>
... other header stuff ...
<?= $content ?>
... rest of page

They may, for instance, have some form widgets. Suppose they wanted all these boolean values to use radio buttons with some sort of tick/cross image beside them? They can define the HTML code for them in one place…

<input type="radio" value="no" name="<?= $name ?>" id="<?= $name ?>_no" /><label for="<?= $name ?>_no"><img src="/images/cross.png" alt="No" /></label>
<input type="radio" value="yes" name="<?= $name ?>" id="<?= $name ?>_yes" /><label for="<?= $name ?>_yes"><img src="/images/tick.png" alt="Yes" /></label>

Then use that widget repeatedly in a document by simply defining some place holders (using <?= $placeholder_name >) and generating the page…

$my_page["show_email"] = doTemplate("templates/yesno.tpl.php",array( "name" => "show_email" ));
$my_page["subscribe_annouce"] = doTemplate("templates/yesno.tpl.php",array( "name" => "subscribe_announce" ));
//
// ... other definitions ...
//
$page_content = doTemplate("templates/register.tpl.php", $my_page);
echo doTemplate("templates/overall.tpl.php", array(
"page_title" => "Register for our forum!",
"content" => $page_content,
"navlinks" => $navigation // <-- This may be a global array that's manipulated in various places as needed.
));

Already, that works in much the way bTemplate does, but doesn’t have nearly as many limitations. There are some manipulations that it can’t do as easily as Smarty does them, such as inline manipulations of text, but then again, it’s a heck of a lot more lightweight. Sure, RAM is cheap these days… but still, why waste the resources if you don’t have to? What I’ve done above, could be viewed as wasteful — even the very act of using PHP in the eyes of some, but sometimes we don’t get a say in that matter, we work with the tools we have at hand. (Heck, I’ve been known to use C and Busybox ash to construct webapps — which works surprisingly well too.) But even in this age of cheap computing power, I think striving for minimalism is still worthwhile.

Re-inventing the headlamp… the Hat-lamp

This is an idea I’ve had for some time now, but only recently started doing anything about it. Anyway…

The problem:

As many of you may know, I study at university. Often the lectures and tutorials are on late at night. Thus, I frequently find myself making my way from or two university in the dark. Many of the areas I walk through are dimly lit, with sparse street lighting and quite a few road crossings. Often the footpath is an uneven surface, and therefore one needs a torch of some kind to see any hazards underfoot. The same torch does improve one’s visibility — but only for those in the torch’s beam.

Headlamps are really nifty torches… freeing both hands. The problem one has though, is that the small compact ones aren’t much good for distance vision, and the big bulky ones chew batteries like they’re going out of fashion. Then there’s the fussing over whether they’re pointed up or down, adjusting head straps…etc. They’re great when camping, and even for walking home of an evening, but the balance between light intensity and battery drain is a big problem, especially when only a limited supply of batteries is on hand. Seldom does one need a high-power beam all the time, but they’re useful to have.

Bike tail-lights are useful for improving one’s visibility to vehicles coming from behind, but they aren’t much help if they’re approaching side-on. And none of these lights will turn themselves off if there’s sufficient ambient light.

My idea:

These problems got me thinking about how I could solve the problem. Does it really need to be solved? Well, it isn’t a big one, so I guess not… but for the sake of it, I’ll try and solve it anyway. LED technology has vastly improved in the last few years, to the point now where they’re talking of using them in street lighting and car headlights (PDF; IEEE Explore subscription required). The big advantage is the high efficiency and low heat of LEDs. A few high-power LEDs should last as long, if not, longer than the incandescent bulb that my present headlamp uses.

My idea revolves around mounting 3 sets of LEDs on a hard hat of some description. Why a hard hat? Well, they’re a rigid structure that I can easily drill holes into and mount components on. Using a full-brim hard hat (rare in Brisbane), it’ll also keep the sun off during the day, thus serving a fourth purpose.

This headlamp would use 3 different LED banks:

  • High-Beam LED: Single 1W high-power White LED — mounted above the rim facing forward in the distance.
  • Low-Beam LEDs: Three high-intensity 5mm White LEDs — mounted under the rim facing downward.
  • Rim LEDs: Twelve high-intensity 5mm Red or Yellow LEDs — mounted around the rim of the hard hat facing outwards.

The high-beam LED would provide the distance lamp… acting like any high-power torch. It’d be focussed slightly below the horizon. The low-beam LEDs would be directed downwards so that they light up an area just in front of the wearer, allowing them to see what they’re doing. The Rim LEDs would be divided into two groups of 6 that flash alternately to warn approaching vehicles at any angle.

Mounted on the top of the hard hat, would be a light-dependant resistor (cadmium-sulfide cell) that detects ambient light, and just underneath, a PCB containing the controller logic for the automatic switching. Then down the side under the rim, would be the switches and threshold pot for controlling the whole circuit.

Each of the functions can be in one of three states, controlled by the user: on, automatic, or off

Controller Circuit:

The key to this headlamp design is the controller circuit. I ended up trying three different circuits before settling on this design. By far, the most simple circuit was based on a IRF630B N-channel power MOSFET.

In this configuration, the CdS cell and potentiometer were wired in a resistor-divider configuration, such that the voltage rose as the light level dropped. This drove the MOSFET’s gate pin, causing it to sink current whenever the light levels were low.

I soon discovered this circuit was no good for high-current devices such as my existing incandescent headlamp. Because the bulb was such a heavy load, it put a heavy strain on the batteries, causing the voltage potential to drop significantly. This in turn, shifted the threshold point on the voltage divider, causing the MOSFET to turn off again, causing the batteries to rise up again… ad nauseum, until the batteries were flat or the user got frustrated and switched to manual modes.
Addition of a relay helped… the ciruit was slightly more stable, increasingly so as large amounts of capacitance were added across the relay, slowing response times. It still was possible to get the whole system into a battery-guzzling oscillating state.

In the end, I turned to the humble 74HC14 Hex Inverting Schmitt Trigger. By turning my voltage divider up-side-down (so voltage rose with light level) I found I could gain the effect I needed. Due to the hysteresis provided by the Schmitt Triggers, the light doesn’t turn off until it gets significantly lighter than the threshold point, and doesn’t turn off until it gets significantly darker. This provided the stability I needed. Hard Hat headlamp controller, rev3

The final design (click image on right, or see SVG or Kicad .sch versions) works as follows. The CdS cell and pot provide the means for detecting the light level. Adjusting the pot will make the circuit more or less sensitive to light. This drives the first Schmitt-Triggered inverter.

The output of this inverter is passed through a BC547C NPN transistor which in turn, drives a small reed relay. This relay is the main switching workhorse, providing a switched 6v rail which hooks to small toggle switches for the low and high-beam LEDs.

For the Rim LEDs, the same schmitt trigger IC could be used to make the oscillators. The Phillips 74HC14 datasheet describes how. I didn’t care much about frequency, so long as it flickered just fast enough to be noticable. To get the alternate flashing action — I set one inverter up as an oscillator, and used it to drive a second inverter. The outputs of both drive individual BC547C transistors, which act as current sinks from the Rim LEDs.

The following two photos show my testing of the circuit on a breadboard.

Testing on breadboardCircuit in action

Bill of Materials

The following is the list of parts for this headlamp, and where I purchased them. Some components can be exchanged to suit one’s needs. At the moment, I haven’t yet bought the 1W LED and power supply which would form the high-beam LED.

Quantity Part Desc Supplier. Part No. Approx. Price each (at time of post)
1 Hard Hat Blackwoods 05339960 $22.00
1 74HC14 Hex Inverting Schmitt Trigger Jaycar ZC4821 $1.30
3 BC547C NPN Transistor (or similar) Jaycar ZT2152 $0.20
1 5V SPST Reed Relay Jaycar SY4036 $2.95
3 1kOhm Resistor Dick Smith Electronics R1074 $0.04
1 10kOhm Resistor Dick Smith Electronics R1098 $0.04
1 33Ohm Resistor (for low-beam LEDs) Dick Smith Electronics R1038 $0.04
1 10Ohm Resistor (for rim LEDs) Dick Smith Electronics R1026 $0.04
1 33µF Capacitor (electrolytic) Dick Smith Electronics R4340 $0.25
1 Veroboard PCB 95mm×76mm Jaycar HP9540 $3.80
1 1MOhm Potentiometer Jaycar RP8524 $2.50
1 Photoresistor (CdS Cell) Jaycar RD3480 $2.50
1 4×AA battery holder Jaycar PH9282 $2.25
1 1W Constant Current Supply Jaycar AA0582 $19.95
1 1W High-power White LED Jaycar ZD0508 $9.95
3 18000mcd White 5mm LED Jaycar ZD0195 $4.95
12 4000mcd Red 5mm LED Jaycar ZD0154 $0.80
1 Packet of Nylon bolts 12×3mm Jaycar HP0140 $2.65
1 Packet of Nylon bolts 25×3mm Jaycar HP0142 $3.00
1 Packet of Nylon nuts 3mm Jaycar HP0146 $2.50
3 DP3T Switch Dick Smith Electronics R7614 $0.98

Assembly

Underside of modded hardhatConstruction of this headlamp will require drilling holes into the shell of the hard hat. So once complete, I wouldn’t go using it on a construction site. To mount the rim LEDs, I found the best way to do it was to use a 3mm drill to make the hole, then use a screwdriver to widen the hole so it was just big enough to accomodate the LED. The LED was then forced into the hole, plugging it — friction holds it in place.

The switches were small enough to mount using double-sided tape just inside the hard hat. A small piece of PCB was used to mount the potentiometer, allowing it to be fastened to the underside of the rim using a nylon nut & bolt.

The low-beam LEDs were mounted onto a small PCB with the current-limiting resistor, and fixed to the front of the hard hat using masking tape (yeah, dodgy I know) — some cardboard prevents the light from shining into the wearer’s eyes.

The main PCB and battery pack were fitted inside the shell of the hard hat — two 25mm long bolts hold the battery pack in place, while one 12mm bolt holds the PCB in place. The actual components are placed on the PCB according to the PCB board design shown to the right (click for larger image).

Final Product (almost)

Well, I haven’t bought the high-beam LED yet, that’s for later. The end result however, works great. I first used it at Riverfire 2007 and found it very convenient. At the time I had lost the LDR, so had to buy one yesterday, which I fitted last night. The unit now automatically switches off if the light levels are sufficient. As far as appearance, it doesn’t look that different to an ordinary hard hat, until you switch the LEDs on. These show the hard hat, before modifications, after, and what it looks like in action.

Original Hard hat After modifications Hat-lamp in action

Safety & commercial considerations

It’s worth noting that although this hard hat would’ve been manufactured to meet AS/NZS 1801. I’ve destroyed this rating by drilling holes and inserting electronics. This project might still survive the double impact tests needed — but it’s never been tested, and isn’t intended to. I just wanted a hat that shaded me by day, and lit my path by night.

If this idea prooves popular, I could see it being adapted into a removable brim that sits over a hard hat/cap. The actual electronics cost over $60 … so embedding it into a hard hat on a commercial basis is not economic, since hard hats have a limited lifespan and need to be replaced every few years. So the headlamp would need to be detachable.

Update: 22nd November

Finished hard hat+headlampWell, having used it now for two months, the idea has worked great. One set of 4×AA batteries lasts about 2 months, with moderate usage — and even then everything still worked, just the light was getting a little dim. I’ve since added the high-beam 1W LED (the supply for it wound up costing about $40, but anyway) and extended the brim so that it provides additional shade during the day.

The photo on the left shows what it looks like now. There has been one minor technical problem, in that the relay occasionally sticks — I’m investigating whether I replace this with something solid-state such as a P-channel power MOSFET which should do the job nicely. The only other one is the odd social problem — of people asking if you’re expecting a disaster, but once they’re used to seeing me wear it, this usually isn’t an issue. 😉


Update 2009-06-05: I did get around to making a P-MOSFET version. See the schematic in PDF or gschem. The circuit can theoretically use any P-MOSFET rated at 1A current for Q1… this one uses the IRF9540N available from Jaycar (which is overkill). I use BC547Cs for Q2 and Q3. CONN1 connects to the adjustment pot (use a 2M? one), CONN2 connects to the LDR. R1 and R2 may be omitted, but are present to allow the circuit to operate if either the pot or LDR connections are broken. CONN3 and CONN4 connect to your low and high beam LED banks. CONN5 connect to the two warning LED banks. R4 and C1 control the rate of oscillation… any value can be used, see the NXP 74HC14 datasheet for details on how to calculate these.

Time-shifting radio

Well, right now I’m lying back, listening to the fruits of my labours.

When it comes to time-shifting, there are quite a few solutions that allows a user to time-shift television. MythTV, Tivo, Foxtel IQ… just to name three. However, I’ve looked around, and found very little for radio.

My needs are basic… I have an old stereo FM tuner plugged into the line-in socket of an old laptop. It’s in a spot where it can get good reception. The machine has a 20GB HDD, Apache web server, and enough CPU grunt to push the data. I thought it’d be nice if I could stream my radio around the house, in a manner that allowed me to time shift backwards up to a few hours or so. Therefore… if I wanted to hear a radio programme, but missed the first 15 minutes — no problem, just tell it to start playing from 15 mins ago. Done.

It’d also be nice if it could be in lossless form. I’m on a 100Mbit LAN — I don’t need compression, but some extra CPU cycles could be nice.

Icecast did the basic need of streaming radio quite well… but there were a few problems:

  1. It couldn’t timeshift
  2. I found it would frequently drop the feed mysteriously
  3. It used Vorbis — not so much a problem, but for my needs, lossless was better

So seeing few alternatives, I set about designing my own system. The concept is simple:

  • Create a capture programme, that records audio to a series of 1sec raw blockfiles, stored in a stream directory.
  • Make a CGI application that scoops up a number of these blockfiles, concatenates them, adds an appropriate header and pushes them out to the client
  • Construct a shell script that can clean up old files (to keep the disk from getting full)

After looking around at a suitable capture API, I settled on Portaudio v19. I had done some apps with v18… thus I had some familiarity with it. Doing this allowed my app to be cross-platform, should I decide to develop it further.

It was simply a case of writing a program that would write blockfiles, one for each second, identified by a Unix timestamp. As time ticks forward, it closes one block file and opens the next. My capture app is basically 137 lines of pure C code. Very tight and efficient.

For the CGI app, I again did it in pure C. It picks up its parameters from the PATH_INFO environment variable, allowing nice clean URLs, and parsing is as simple as calling getenv. I ended up writing two versions of this app.

The first version used sox in a child process, to convert the raw audio to a RIFF stream. My problem was that I used popen to execute sox. It worked well, except that disconnecting the player left loads of sox instances running, hogging the CPU. I started looking at writing my own RIFF header library, only to discover how complicated it was.

Looking around, I stumbled across the humble Sun Audio format. Apart from the minor inconvenience of having to pass everything through atonl/atons… everything works fine. I specify a URL like http://blackbox.local/cgi-bin/stream/linein/2 (the laptop, an IBM T20 is called blackbox), which gives me the stream “linein” from 2 seconds ago. I find it’s a bit glitchy any closer than that… but for maybe 6 hours coding, I’m quite happy with the result.

The problem has been clients… Amarok seems to know what to do with the stream. mplayer tries despairately to seek in the stream (why?) then drops out. And don’t even ask what Audacious does — I’m at a loss there. That said, good ol’e sox and wget or curl works fine, and is lightweight — just the interface is a tad annoying.

I’ll probably wind up writing my own client anyway — so I can time-shift somewhat more conveniently (using a slider to set the offset).

Still on the TODO list, is to make the capture app daemonise itself (it runs in the foreground for now), and to write an app that can be run from cron, and will record a radio programme for later listening (e.g. on a portable music player for instance) — perhaps optionally encoding it in a compressed format.

I’m tossing up whether to release the sources or not… if there’s demand for such a project, I’ll look into cleaning things up and releasing it. That said, if anyone knows of something that does similar to the above… I’d be interested to hear about it.