#!/usr/bin/env php
<?php
/**
 * Convert Open Metering System manufacturer codes to acronyms and back
 *
 * 5CB0 <=> WEP
 *
 * @author Christian Weiske <weiske@mogic.com>
 */
if ($argc < 2) {
    echo "Pass manufacturer code or acronym\n";
    exit(1);
}

$param = $argv[1];

if (strlen($param) == 3) {
    //acronym like ZRI
    $bin = '0'
         . str_pad(decbin(ord($param{0}) - 64), 5, '0', STR_PAD_LEFT)
         . str_pad(decbin(ord($param{1}) - 64), 5, '0', STR_PAD_LEFT)
         . str_pad(decbin(ord($param{2}) - 64), 5, '0', STR_PAD_LEFT);
    echo str_pad(strtoupper(dechex(bindec($bin))), 4, '0', STR_PAD_LEFT)
        . "\n";
} else if (strlen($param) == 4) {
    // 2 bytes as 6A49
    $fb = str_pad(decbin(hexdec('5CB0')), 16, '0', STR_PAD_LEFT);
    echo chr(64 + bindec(substr($fb, 1, 5)))
        . chr(64 + bindec(substr($fb, 6, 5)))
        . chr(64 + bindec(substr($fb, 11, 5)))
        . "\n";
} else {
    echo "Wrong length; 3 or 4 characters expected\n";
    exit(2);
}

?>
