Information wants to be free...

Commodore PC 30-III Repair

The Commodore PC 30-III is a AT-class 286 clone PC running at 12MHz with 1MB of RAM. My first and initial problem was the battery failure upon booting:

Commodore PC 30-III Battery Failure


For some reason, It was not possible to get past this error and continue booting anyway, so a replacement was needed. I got hold of a Glitch Works GW-12887-1 which can replace the original Dallas 1287 RTC in this machine:

Commodore PC 30-III Dallas DS1287 RTC


This is unfortunately soldered directly to the motherboard. But I cut a socket and soldered that one on instead:

Commodore PC 30-III U201 Socket Replacement


In which the replacement fits nicely:

Commodore PC 30-III GW-12887-1


This got the machine booting properly. But after a while of playing around with Compact Flash disk replacements, magic smoke suddenly appeared. Which became my second problem. I located the source; a burned ceramic capacitor:

Commodore PC 30-III Burned Ceramic Capacitor


From what I could find out online, these capacitors can fail if cracks appear in them, and moisture gets in over time. So that's most likely what happened to this 30 year old component. I got a replacement and removed the bad one, which disintegrated almost by itself:

Commodore PC 30-III Capacitor Replacement


The brand new ceramic capacitor in place:

Commodore PC 30-III New Capacitor


The machine is now up and running again:

Commodore PC 30-III Front


Topic: Repair, by Kjetil @ 08/12-2019, Article Link

Linux Distribution for 386SX

I have a Commodore PC 50-II system with a Intel 386SX CPU running at 16MHz and only 5MB of RAM, in addition, the harddrive controller and harddrive is also missing. To get around this, I have installed a 3Com 3C509B-TPO ISA Network card and have managed to boot Linux on this ancient PC over the network instead.

At first I tried to use Buildroot, but I had to give up on this in the end, as it seems that pure 386 is not supported anywhere anymore. So instead, I have gone the route of building everything from scratch, so I could pick and choose specific source versions of GCC and the Linux kernel that supports 386 with math emulation. The end result is a cross-compiling toolchain for i386, a stripped down kernel and Busybox-based rootfs mounted over NFS from another host computer.

I ended up using these specific software versions:
* linux-2.4.37.9
* gcc-3.4.6
* busybox-1.01
* uClibc-0.9.33.2
* binutils-2.32

I also had to statically link everything. I tried with dynamic linking in the beginning but the system would hang during boot, and I didn't want to troubleshoot this any further.

I have made some scripts to greatly simplify the whole process of building the cross-compiling toolchain and all the binaries. Bundled in a file here.

Unpack this into a directory and then simply run the following:

./build.sh
./rootfs.sh
          

I have used these on a Slackware 14.2 box with GCC 5.3.0
The result will be a directory with the "rootfs" and a "bzImage" located inside the kernel build tree.

The rootfs is exported over NFS in /etc/exports like this:

/home/nfs/rootfs *(rw,sync,no_root_squash,no_all_squash,no_subtree_check)
          

Also note that the legacy NFSv2 protocol needs to be actived!

To prepare the kernel is the tricky part. To load it over TFTP with Etherboot you have to use the mkelf-linux script from the mknbi package. This package is not compilable on modern Linux distributions, so I ended up compiling and using it from an old Slackware 11.0 installation running in a QEMU virtual machine.

I used the command as follows:

mkelf-linux --output=pc50linux.nb --ip="192.168.0.3:192.168.0.2:192.168.0.1:255.255.255.0:pc50" --append="root=/dev/nfs nfsroot=/home/nfs/rootfs" bzImage
          

Where .3 is the booted client PC, .2 is the NFS server and .1 is the gateway and TFTP server.

The final step is to activate the TFTP/DHCP server. I used dnsmasq for this, with the following relevant configuration:

dhcp-host=00:ff:ff:ff:ff:ff,192.168.0.3,infinite,set:pxelinux
enable-tftp
tftp-root=/var/ftpd
dhcp-boot=net:pxelinux,/var/ftpd/pc50linux.nb,boothost,192.168.0.1
          


Some additional information: I have no Boot ROM on the Ethernet card, so I used a floppy disk to actually kick-start the network booting. More specifically, the "3c509.dsk" image made from compiling parts of the "Etherboot" package. Since this also isn't compilable on modern distributions, I had to use the Slackware 11.0 QEMU virtual machine again.

Commodore PC 50-II


Topic: Configuration, by Kjetil @ 01/12-2019, Article Link

ADCQ1706 USB Oscilloscope

On a trip to Japan I bought one of these strange USB oscilloscopes. It seems it was designed for use with a Raspberry Pi, but I wanted to use it on a regular Linux desktop PC. Fortunately, the available "client" software for the RPi is written in Python, but it has several limitations. It's all in Japanese and it looks to be based around a web-server capturing still images. However, due to source code availability, I could easily create a new client.

What I present here is a Python PyGame-based solution instead, which has a graphical screen that updates in real time:

Oscilloscope


I have uploaded the code to GitLab and GitHub, but it's also presented here:

#!/usr/bin/python
import serial
import pygame
import time

class Oscilloscope(object):
    def __init__(self, tty_dev='/dev/ttyUSB0', trig_level=2048):
        self._con = serial.Serial(tty_dev, 115200, timeout=2.0)
        self._settings = {
            1 : {'hsync' : 3, 'trig' : trig_level, 'rise' : 1},
            2 : {'hsync' : 3, 'trig' : trig_level, 'rise' : 1}}

    def get_samples(self, channel):
        hsync = str(self._settings[channel]['hsync'])
        trig  = str(self._settings[channel]['trig'])
        rise  = str(self._settings[channel]['rise'])

        self._con.write('ST' + hsync + str(channel) + trig + rise + 'E')
        data = self._con.read(4003)
        if len(data) != 4003:
            return None
        if not (data[0] == 'S') and (data[1] == 'M') and (data[4002] == 'E'):
            return None

        samples = list()
        for i in range(0, 2000):
            samples.append(int((ord(data[i*2+2]) & 0x7F) + (ord(data[i*2+3]) & 0x1F) * 128))
        return samples

    def increase_hsync(self, channel):
        if self._settings[channel]['hsync'] < 6:
            self._settings[channel]['hsync'] += 1

    def decrease_hsync(self, channel):
        if self._settings[channel]['hsync'] > 0:
            self._settings[channel]['hsync'] -= 1

    def get_hsync(self, channel):
        return self._settings[channel]['hsync']

    def toggle_trig_rise(self, channel):
        if self._settings[channel]['rise'] == 1:
            self._settings[channel]['rise'] = 0
        else:
            self._settings[channel]['rise'] = 1

    def increase_trig_level(self, channel):
        if self._settings[channel]['trig'] < 3968:
            self._settings[channel]['trig'] += 256

    def decrease_trig_level(self, channel):
        if self._settings[channel]['trig'] > 128:
            self._settings[channel]['trig'] -= 256

    def get_trig_level(self, channel):
        return self._settings[channel]['trig']

class GUI(object):
    def __init__(self, oscilloscope, scale=1):
        if scale not in [1,2,4]:
            raise Exception("Invalid scale")
        self._scale = scale
        self._osc = oscilloscope
        self._ch_active = {1 : True, 2 : True}
        pygame.init()
        pygame.display.set_caption("Oscilloscope")
        self._screen = pygame.display.set_mode((500 * scale, 512 * scale))
        self._font = pygame.font.Font(pygame.font.get_default_font(), 12 * scale)

    def _toggle_channel(self, channel):
        if self._ch_active[channel] == True:
            self._ch_active[channel] = False
        else:
            self._ch_active[channel] = True 

    def _draw_samples(self, samples, color):
        prev_y = None
        for sample_no, sample in enumerate(samples):
            y = (4096 - sample) / (8 / self._scale)
            x = sample_no / (4 / self._scale)
            if prev_y == None:
                prev_y = y
            pygame.draw.line(self._screen, color, (x, prev_y), (x, y))
            prev_y = y
    
    def _draw_volt_grid(self):
        for pos, volt in [(48,1.5), (715,1), (1381,0.5), (2048,0), (2715,-0.5), (3381,-1), (4048,-1.5)]:
            y = pos / (8 / self._scale)
            pygame.draw.line(self._screen, (128, 128, 128), (0, y), ((500 * self._scale), y))
            text = self._font.render(str(volt) + "V", True, (128, 128, 128))
            if text.get_height() > y:
                self._screen.blit(text, (0, y + (1 * self._scale)))
            else:
                self._screen.blit(text, (0, y - text.get_height() + (1 * self._scale)))

    def _draw_time_grid(self, channel, color):
        hsync = self._osc.get_hsync(channel)
        if hsync == 0:
            time = [0,5,10,15,20,25,30,35,40,45]
            unit = "us"
        elif hsync == 1:
            time = [0,10,20,30,40,50,60,70,80,90]
            unit = "us"
        elif hsync == 2:
            time = [0,50,100,150,200,250,300,350,400,450]
            unit = "us"
        elif hsync == 3:
            time = [0,100,200,300,400,500,600,700,800,900]
            unit = "us"
        elif hsync == 4:
            time = [0,1,2,3,4,5,6,7,8,9]
            unit = "ms"
        elif hsync == 5:
            time = [0,2,4,6,8,10,12,14,16,18]
            unit = "ms"
        elif hsync == 6:
            time = [0,10,20,30,40,50,60,70,80,90]
            unit = "ms"

        for index in range(0, 10):
            x = index * (50 * self._scale)
            if x > 0:
                pygame.draw.line(self._screen, (128, 128, 128), (x, 0), (x, (512 * self._scale)))
            text = self._font.render(str(time[index]) + unit, True, color)
            if channel == 1:
                self._screen.blit(text, (x + (1 * self._scale), 0))
            if channel == 2:
                self._screen.blit(text, (x + (1 * self._scale), (512 * self._scale) - text.get_height()))

    def _draw_trig_line(self, channel, color):
        y = (4096 - self._osc.get_trig_level(channel)) / (8 / self._scale)
        pygame.draw.line(self._screen, color, (0, y), ((500 * self._scale), y))

    def loop(self):
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE or event.key == pygame.K_q:
                        return
                    elif event.key == pygame.K_s:
                        pygame.image.save(self._screen, "oscilloscope.png")
                        print "Screenshot saved to 'oscilloscope.png'."
                    elif event.key == pygame.K_1:
                        self._toggle_channel(1)
                    elif event.key == pygame.K_2:
                        self._toggle_channel(2)
                    elif event.key == pygame.K_3:
                        self._osc.increase_hsync(1)
                    elif event.key == pygame.K_4:
                        self._osc.decrease_hsync(1)
                    elif event.key == pygame.K_5:
                        self._osc.increase_hsync(2)
                    elif event.key == pygame.K_6:
                        self._osc.decrease_hsync(2)
                    elif event.key == pygame.K_7:
                        self._osc.toggle_trig_rise(1)
                    elif event.key == pygame.K_8:
                        self._osc.toggle_trig_rise(2)
                    elif event.key == pygame.K_e:
                        self._osc.increase_trig_level(1)
                    elif event.key == pygame.K_r:
                        self._osc.decrease_trig_level(1)
                    elif event.key == pygame.K_t:
                        self._osc.increase_trig_level(2)
                    elif event.key == pygame.K_y:
                        self._osc.decrease_trig_level(2)

            self._screen.fill((255,255,255))
            self._draw_volt_grid()

            if self._ch_active[1]:
                self._draw_time_grid(1, (255,128,128))
                self._draw_trig_line(1, (255,128,128))
                samples = self._osc.get_samples(1)
                self._draw_samples(samples, (255,0,0))

            if self._ch_active[2]:
                self._draw_time_grid(2, (128,128,255))
                self._draw_trig_line(2, (128,128,255))
                samples = self._osc.get_samples(2)
                self._draw_samples(samples, (0,0,255))

            if (not self._ch_active[1]) and (not self._ch_active[2]):
                time.sleep(0.1) # To avoid 100% CPU usage.

            pygame.display.flip()

if __name__ == "__main__":
    import sys
    import getopt

    def print_usage_and_exit():
        print "Usage: %s [options]" % (sys.argv[0])
        print "Options:"
        print "  -h         Display this help and exit."
        print "  -d DEV     Serial TTY DEV to use instead of /dev/ttyUSB0."
        print "  -s SCALE   Scale of GUI, value 1, 2 or 4."
        print " "
        sys.exit(1)

    def print_keys():
        print "Keys:"
        print "  1 = Toggle channel #1"
        print "  2 = Toggle channel #2"
        print "  3 = Increase time/div for channel #1"
        print "  4 = Decrease time/div for channel #1"
        print "  5 = Increase time/div for channel #2"
        print "  6 = Decrease time/div for channel #2"
        print "  7 = Toggle rise/fall trigging for channel #1"
        print "  8 = Toggle rise/fall trigging for channel #2"
        print "  E = Increase trig level for channel #1"
        print "  R = Decrease trig level for channel #1"
        print "  T = Increase trig level for channel #2"
        print "  Y = Decrease trig level for channel #2"
        print "  S = Screenshot"
        print "  Q = Quit"

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hd:s:")
    except getopt.GetoptError as err:
        print "Error:", str(err)
        print_usage_and_exit()

    tty_dev = None
    scale = None
    for o, a in opts:
        if o == '-h':
            print_usage_and_exit()
        elif o == '-d':
            tty_dev = a
        elif o == '-s':
            scale = int(a)

    if tty_dev:
        osc = Oscilloscope(tty_dev)
    else:
        osc = Oscilloscope()

    if scale:
        gui = GUI(osc, scale)
    else:
        gui = GUI(osc)

    print_keys()
    gui.loop()
          


Topic: Scripts and Code, by Kjetil @ 01/11-2019, Article Link

Commodore 1541-II Floppy Drive Repair

I was able to repair my Commodore 1541-II floppy drive, which is typically used together with the Commodore 64.

The first problem was that I do not have the original (external) power supply, but fortunately it uses fairly standard +5V and +12V voltages, which are also used by most PC hardware. So I made an adapter from a 4-pin molex to a 4-pin DIN connector:

Commodore 1541-II Power Adapter

The pinout of the DIN connector can be found here among other places.

When powering up the drive for the first time, it would keep the drive motor running constantly, which is apparently a known problem. Some other people online said this could be caused by a faulty PSU or bad ROM chip...

When I attempted to continue troubleshooting the next day, the situation had worsened. Now the power LED on the drive would flash a little on power on and slowly fade away. Symptoms of a short circuit or something perhaps...

With no idea on what to do about this, I decided to try to replace the electrolytic capacitors, which people often do on restoration/repair projects.

There are only three of them on the main board, all 10uF and 25V, located here:

Commodore 1541-II Capacitor Locations


Old and new replacements:

Commodore 1541-II Capacitor Replacement


To my surprise, this actually worked, and the drive is now working:

Commodore 1541-II Working


I have a theory: Two of those capacitors I changed are between the incoming 12V/5V and ground, acting as "decouping/bypass" to filter out noise. If there happened to be a short circuit or weakened resistance in the capacitors, that would explain parts of the symptoms at least.

Topic: Repair, by Kjetil @ 26/10-2019, Article Link

SSD1306 Wi-Fi Status

Here is another use of the SSD1306 miniature OLED display. Instead of loading an image like my previous project, this code contains character data and can display text. I have combined this with some simple hacks to retrieve and display Wi-Fi status information from the host. This is also meant to be connected to a Raspberry Pi 3.

Take a look:

#!/usr/bin/python
import smbus
import subprocess
import re
import time

chardata = dict()
chardata['@'] = "\x3c\x66\x6e\x6e\x60\x62\x3c\x00"
chardata['A'] = "\x18\x3c\x66\x7e\x66\x66\x66\x00"
chardata['B'] = "\x7c\x66\x66\x7c\x66\x66\x7c\x00"
chardata['C'] = "\x3c\x66\x60\x60\x60\x66\x3c\x00"
chardata['D'] = "\x78\x6c\x66\x66\x66\x6c\x78\x00"
chardata['E'] = "\x7e\x60\x60\x78\x60\x60\x7e\x00"
chardata['F'] = "\x7e\x60\x60\x78\x60\x60\x60\x00"
chardata['G'] = "\x3c\x66\x60\x6e\x66\x66\x3c\x00"
chardata['H'] = "\x66\x66\x66\x7e\x66\x66\x66\x00"
chardata['I'] = "\x3c\x18\x18\x18\x18\x18\x3c\x00"
chardata['J'] = "\x1e\x0c\x0c\x0c\x0c\x6c\x38\x00"
chardata['K'] = "\x66\x6c\x78\x70\x78\x6c\x66\x00"
chardata['L'] = "\x60\x60\x60\x60\x60\x60\x7e\x00"
chardata['M'] = "\x63\x77\x7f\x6b\x63\x63\x63\x00"
chardata['N'] = "\x66\x76\x7e\x7e\x6e\x66\x66\x00"
chardata['O'] = "\x3c\x66\x66\x66\x66\x66\x3c\x00"
chardata['P'] = "\x7c\x66\x66\x7c\x60\x60\x60\x00"
chardata['Q'] = "\x3c\x66\x66\x66\x66\x3c\x0e\x00"
chardata['R'] = "\x7c\x66\x66\x7c\x78\x6c\x66\x00"
chardata['S'] = "\x3c\x66\x60\x3c\x06\x66\x3c\x00"
chardata['T'] = "\x7e\x18\x18\x18\x18\x18\x18\x00"
chardata['U'] = "\x66\x66\x66\x66\x66\x66\x3c\x00"
chardata['V'] = "\x66\x66\x66\x66\x66\x3c\x18\x00"
chardata['W'] = "\x63\x63\x63\x6b\x7f\x77\x63\x00"
chardata['X'] = "\x66\x66\x3c\x18\x3c\x66\x66\x00"
chardata['Y'] = "\x66\x66\x66\x3c\x18\x18\x18\x00"
chardata['Z'] = "\x7e\x06\x0c\x18\x30\x60\x7e\x00"
chardata['['] = "\x3c\x30\x30\x30\x30\x30\x3c\x00"
chardata[']'] = "\x3c\x0c\x0c\x0c\x0c\x0c\x3c\x00"
chardata[' '] = "\x00\x00\x00\x00\x00\x00\x00\x00"
chardata['!'] = "\x18\x18\x18\x18\x00\x00\x18\x00"
chardata['"'] = "\x66\x66\x66\x00\x00\x00\x00\x00"
chardata['#'] = "\x66\x66\xff\x66\xff\x66\x66\x00"
chardata['$'] = "\x18\x3e\x60\x3c\x06\x7c\x18\x00"
chardata['%'] = "\x62\x66\x0c\x18\x30\x66\x46\x00"
chardata['&'] = "\x3c\x66\x3c\x38\x67\x66\x3f\x00"
chardata['\''] = "\x06\x0c\x18\x00\x00\x00\x00\x00"
chardata['('] = "\x0c\x18\x30\x30\x30\x18\x0c\x00"
chardata[')'] = "\x30\x18\x0c\x0c\x0c\x18\x30\x00"
chardata['*'] = "\x00\x66\x3c\xff\x3c\x66\x00\x00"
chardata['+'] = "\x00\x18\x18\x7e\x18\x18\x00\x00"
chardata[','] = "\x00\x00\x00\x00\x00\x18\x18\x30"
chardata['-'] = "\x00\x00\x00\x7e\x00\x00\x00\x00"
chardata['.'] = "\x00\x00\x00\x00\x00\x18\x18\x00"
chardata['/'] = "\x00\x03\x06\x0c\x18\x30\x60\x00"
chardata['0'] = "\x3c\x66\x6e\x76\x66\x66\x3c\x00"
chardata['1'] = "\x18\x18\x38\x18\x18\x18\x7e\x00"
chardata['2'] = "\x3c\x66\x06\x0c\x30\x60\x7e\x00"
chardata['3'] = "\x3c\x66\x06\x1c\x06\x66\x3c\x00"
chardata['4'] = "\x06\x0e\x1e\x66\x7f\x06\x06\x00"
chardata['5'] = "\x7e\x60\x7c\x06\x06\x66\x3c\x00"
chardata['6'] = "\x3c\x66\x60\x7c\x66\x66\x3c\x00"
chardata['7'] = "\x7e\x66\x0c\x18\x18\x18\x18\x00"
chardata['8'] = "\x3c\x66\x66\x3c\x66\x66\x3c\x00"
chardata['9'] = "\x3c\x66\x66\x3e\x06\x66\x3c\x00"
chardata[':'] = "\x00\x00\x18\x00\x00\x18\x00\x00"
chardata[';'] = "\x00\x00\x18\x00\x00\x18\x18\x30"
chardata['<'] = "\x0e\x18\x30\x60\x30\x18\x0e\x00"
chardata['='] = "\x00\x00\x7e\x00\x7e\x00\x00\x00"
chardata['>'] = "\x70\x18\x0c\x06\x0c\x18\x70\x00"
chardata['?'] = "\x3c\x66\x06\x0c\x18\x00\x18\x00"
chardata['a'] = "\x00\x00\x3c\x06\x3e\x66\x3e\x00"
chardata['b'] = "\x00\x60\x60\x7c\x66\x66\x7c\x00"
chardata['c'] = "\x00\x00\x3c\x60\x60\x60\x3c\x00"
chardata['d'] = "\x00\x06\x06\x3e\x66\x66\x3e\x00"
chardata['e'] = "\x00\x00\x3c\x66\x7e\x60\x3c\x00"
chardata['f'] = "\x00\x0e\x18\x3e\x18\x18\x18\x00"
chardata['g'] = "\x00\x00\x3e\x66\x66\x3e\x06\x7c"
chardata['h'] = "\x00\x60\x60\x7c\x66\x66\x66\x00"
chardata['i'] = "\x00\x18\x00\x38\x18\x18\x3c\x00"
chardata['j'] = "\x00\x06\x00\x06\x06\x06\x06\x3c"
chardata['k'] = "\x00\x60\x60\x6c\x78\x6c\x66\x00"
chardata['l'] = "\x00\x38\x18\x18\x18\x18\x3c\x00"
chardata['m'] = "\x00\x00\x66\x7f\x7f\x6b\x63\x00"
chardata['n'] = "\x00\x00\x7c\x66\x66\x66\x66\x00"
chardata['o'] = "\x00\x00\x3c\x66\x66\x66\x3c\x00"
chardata['p'] = "\x00\x00\x7c\x66\x66\x7c\x60\x60"
chardata['q'] = "\x00\x00\x3e\x66\x66\x3e\x06\x06"
chardata['r'] = "\x00\x00\x7c\x66\x60\x60\x60\x00"
chardata['s'] = "\x00\x00\x3e\x60\x3c\x06\x7c\x00"
chardata['t'] = "\x00\x18\x7e\x18\x18\x18\x0e\x00"
chardata['u'] = "\x00\x00\x66\x66\x66\x66\x3e\x00"
chardata['v'] = "\x00\x00\x66\x66\x66\x3c\x18\x00"
chardata['w'] = "\x00\x00\x63\x6b\x7f\x3e\x36\x00"
chardata['x'] = "\x00\x00\x66\x3c\x18\x3c\x66\x00"
chardata['y'] = "\x00\x00\x66\x66\x66\x3e\x0c\x78"
chardata['z'] = "\x00\x00\x7e\x0c\x18\x30\x7e\x00"

class SSD1306(object):
    def __init__(self, bus=1, address=0x3c):
        self._address = address
        self._bus = smbus.SMBus(bus)

        self._command(0xae) # Display off.

        self._command(0xa8) # Multiplex ratio...
        self._command(0x3f) # ...63
        self._command(0xd3) # Display offset...
        self._command(0x00) # ...0
        self._command(0x40) # Display start line at 0.
        self._command(0xa1) # Segment Re-map with column 127 mapped to SEG0.
        self._command(0xc8) # Remapped mode, scan from COM[N-1] to COM0.
        self._command(0xda) # COM pins hardware configuration...
        self._command(0x32) # ...Alternative and Left/Right
        self._command(0xa4) # Entire display ON.
        self._command(0xa6) # Inverse display mode.
        self._command(0xd5) # Display clock...
        self._command(0x80) # ...No clock divide ratio and max frequency.
        self._command(0x8d) # Charge pump...
        self._command(0x14) # ...Enabled.
        self._command(0x20) # Memory addressing mode...
        self._command(0x20) # ...Horizontal.

        self._command(0xaf) # Display on.
    
    def _command(self, command_byte):
        self._bus.write_byte_data(self._address, 0x00, command_byte)

    def _data(self, data_byte):
        self._bus.write_byte_data(self._address, 0x40, data_byte)

    def reset_cursor(self):
        self._command(0x21) # Column address...
        self._command(0x00) # ...start at 0...
        self._command(0x7f) # ...end at 127.
        self._command(0x22) # Page address...
        self._command(0x00) # ...start at 0...
        self._command(0x07) # ...end at 7.

    def putc(self, char):
        if char in chardata:
            for column in range(0, 8):
                byte  = ((ord(chardata[char][0]) >> (7 - column)) & 1) << 1
                byte += ((ord(chardata[char][1]) >> (7 - column)) & 1) << 0
                byte += ((ord(chardata[char][2]) >> (7 - column)) & 1) << 3
                byte += ((ord(chardata[char][3]) >> (7 - column)) & 1) << 2
                byte += ((ord(chardata[char][4]) >> (7 - column)) & 1) << 5
                byte += ((ord(chardata[char][5]) >> (7 - column)) & 1) << 4
                byte += ((ord(chardata[char][6]) >> (7 - column)) & 1) << 7
                byte += ((ord(chardata[char][7]) >> (7 - column)) & 1) << 6
                self._data(byte)

    def puts(self, string):
        for char in string:
            self.putc(char)

class WiFiStatus(object):
    def __init__(self, interface):
        self._interface = interface

    def _get_status(self):
        iwconfig = subprocess.check_output("iwconfig %s" % (self._interface), shell=True)
        ifconfig = subprocess.check_output("ifconfig %s" % (self._interface), shell=True)

        match = re.search(r'inet ([^\ ]+?) ', ifconfig, flags=re.MULTILINE)
        if match:
            inet_address = match.group(1)
        else:
            inet_address = ""

        match = re.search(r'RX packets ([^\ ]+?) ', ifconfig, flags=re.MULTILINE)
        if match:
            rx_packets = match.group(1)
        else:
            rx_packets = ""

        match = re.search(r'TX packets ([^\ ]+?) ', ifconfig, flags=re.MULTILINE)
        if match:
            tx_packets = match.group(1)
        else:
            tx_packets = ""

        match = re.search(r'ESSID:"([^"]+?)"', iwconfig, flags=re.MULTILINE)
        if match:
            essid = match.group(1)
        else:
            essid = ""

        match = re.search(r'Link Quality=(\d+/\d+)', iwconfig, flags=re.MULTILINE)
        if match:
            link_quality = match.group(1)
        else:
            link_quality = ""

        match = re.search(r'Signal level=(-\d+ dBm)', iwconfig, flags=re.MULTILINE)
        if match:
            signal_level = match.group(1)
        else:
            signal_level = ""

        match = re.search(r'Bit Rate=([\.\d]+ Mb/s)', iwconfig, flags=re.MULTILINE)
        if match:
            bit_rate = match.group(1)
        else:
            bit_rate = ""

        match = re.search(r'Tx-Power=(\d+ dBm)', iwconfig, flags=re.MULTILINE)
        if match:
            tx_power = match.group(1)
        else:
            tx_power = ""

        return (inet_address, rx_packets, tx_packets, essid, link_quality, signal_level, bit_rate, tx_power)

    def loop(self):
        display = SSD1306()

        while True:
            (ia, rx, tx, si, lq, sl, br, tp) = self._get_status()
            display.reset_cursor()
            display.puts((si + "                ")[:16])
            display.puts((ia + "                ")[:16])
            display.puts(("Link: " + lq + "          ")[:16])
            display.puts(("Sig: " + sl + "           ")[:16])
            display.puts(("Rate: " + br + "          ")[:16])
            display.puts(("Pow: " + tp + "           ")[:16])
            display.puts(("Rx: " + rx + "            ")[:16])
            display.puts(("Tx: " + tx + "            ")[:16])
            time.sleep(3)

if __name__ == "__main__":
    import sys

    if len(sys.argv) < 2:
        print "Usage: %s <interface>" % (sys.argv[0])
        sys.exit(1)

    ws = WiFiStatus(sys.argv[1])
    ws.loop()
          


Topic: Scripts and Code, by Kjetil @ 05/10-2019, Article Link

RSS Feed

Moving to external web hosting has made it possible to finally create an RSS feed for this site. Note that the content itself is not part of the feed, only the headers and a corresponding link back to this site.

Link: RSS Feed

Topic: General, by Kjetil @ 01/09-2019, Article Link

New Web Hosting

After 12 years of hosting this site on a server in my own house I have decided to finally move it to an external web hosting site. Hopefully this will provide better uptime, as it does not rely on my own Internet connection.

Direct Link: http://kobolt.website/infocenter/

Topic: General, by Kjetil @ 22/08-2019, Article Link

OpenVPN Setup for Android

There are probably many ways to do this, but this is what worked for me in the end, after several trials and errors. I ended up making a "standalone" server solution based on running in GNU Screen to avoid messing too much with my existing server.

I started by downloading the EasyRSA scripts to help generating certificates and such. Then ran the following commands:

./easyrsa init-pki
./easyrsa build-ca
./easyrsa build-server-full server
./easyrsa build-client-full client
./easyrsa gen-dh
          

You will have to enter a CA key passphrase and PEM passphrase, keep those for later.

Once the files are created, copy them into a new location where everything will be stored, in my case the "openvpn" directory under my home directory:

mkdir ~/openvpn
cp pki/ca.crt ~/openvpn/
cp pki/dh.pem ~/openvpn/
cp pki/issued/client.crt ~/openvpn/
cp pki/issued/server.crt ~/openvpn/
cp pki/private/ca.key ~/openvpn/
cp pki/private/client.key ~/openvpn/
cp pki/private/server.key ~/openvpn/
          


The OpenVPN server configuration file must be created manually, at ~/openvpn/server.cfg with the following contents:

ca ca.crt
cert server.crt
key server.key
dh dh.pem
dev tun
ifconfig 10.8.0.1 10.8.0.2
tls-server
port 1194
proto udp
comp-lzo
push "redirect-gateway def1 bypass-dhcp"
push "dhcp-option DNS 8.8.8.8"
push "ifconfig 10.8.0.2 10.8.0.1"
mode server
verb 4
client-config-dir ccd
          


Create a new directory "ccd" under the directory structure and create the file ~/openvpn/ccd/client with the following single line:

iroute 10.8.0.0 255.255.255.0
          


To be able to start things easily and open the necessary parts of the firewall a script like this can be used, placed at ~/openvpn/start.sh:

#!/bin/sh
screen -S openvpn -d -m sudo openvpn server.cfg

sudo iptables -A INPUT -p udp --dport 1194 -i eth0 -j ACCEPT
sudo iptables -A INPUT -i tun0 -j ACCEPT
sudo iptables -A FORWARD -i tun0 -j ACCEPT
sudo iptables -A FORWARD -i eth0 -d 10.8.0.0/255.255.255.0 -j ACCEPT
          

This particular server already has iptables setup for NAT and such, so that is not present in this configuration.

Finally, the Android OpenVPN application requires a matching "ovpn" file with the client configuration. I had to make this one by manually looking something like this:

client
dev tun                             
proto udp
remote my.openvpn.server.com 1194
resolv-retry infinite
nobind
persist-key
persist-tun
comp-lzo
verb 3
<cert>
-----BEGIN CERTIFICATE-----
<contents of client.crt file>
-----END CERTIFICATE-----
</cert>
<key>
-----BEGIN ENCRYPTED PRIVATE KEY-----
<contents of client.key file>
-----END ENCRYPTED PRIVATE KEY-----
</key>
<ca>
-----BEGIN CERTIFICATE-----
<contents of ca.crt file>
-----END CERTIFICATE-----
</ca>
          


Topic: Configuration, by Kjetil @ 18/08-2019, Article Link

SSD1306 PBM Viewer

I recently bought a SSD1306 miniature OLED display. This communicates through I2C and can be connected to various boards, like the Raspberry Pi 3 which I have used.

As an initial experiment, I have made a Python script that will load a 2-color PBM image file and display it on the OLED. The image has to be in binary (P4) format and exactly 128x64 which is the same as the resolution. I have re-used the same initialization commands as mentioned here to get up and running quickly.

Enjoy:

#!/usr/bin/python
import smbus

class SSD1306(object):
    def __init__(self, bus=1, address=0x3c):
        self._address = address
        self._bus = smbus.SMBus(bus)

        self._command(0xae) # Display off.

        self._command(0xa8) # Multiplex ratio...
        self._command(0x3f) # ...63
        self._command(0xd3) # Display offset...
        self._command(0x00) # ...0
        self._command(0x40) # Display start line at 0.
        self._command(0xa1) # Segment Re-map with column 127 mapped to SEG0.
        self._command(0xc8) # Remapped mode, scan from COM[N-1] to COM0.
        self._command(0xda) # COM pins hardware configuration...
        self._command(0x32) # ...Alternative and Left/Right
        self._command(0xa4) # Entire display ON.
        self._command(0xa6) # Inverse display mode.
        self._command(0xd5) # Display clock...
        self._command(0x80) # ...No clock divide ratio and max frequency.
        self._command(0x8d) # Charge pump...
        self._command(0x14) # ...Enabled.
        self._command(0x20) # Memory addressing mode...
        self._command(0x20) # ...Horizontal.

        self._command(0xaf) # Display on.
    
    def _command(self, command_byte):
        self._bus.write_byte_data(self._address, 0x00, command_byte)

    def _data(self, data_byte):
        self._bus.write_byte_data(self._address, 0x40, data_byte)

    def reset_cursor(self):
        self._command(0x21) # Column address...
        self._command(0x00) # ...start at 0...
        self._command(0x7f) # ...end at 127.
        self._command(0x22) # Page address...
        self._command(0x00) # ...start at 0...
        self._command(0x07) # ...end at 7.

    def pbm(self, filename):
        fh = open(filename, "r")
        if not fh.readline().startswith("P4"):
            raise Exception("Not a binary PBM image!")
        header = fh.readline()
        while header.startswith("#"):
            header = fh.readline() # Ignore comments.
        if not header.startswith("128 64"):
            raise Exception("Dimensions must be 128x64!")
        data = fh.read()
        fh.close()

        if len(data) != 1024:
            raise Exception("Size of data is not 1024 bytes!")

        self.reset_cursor()
        for row_offset in [0, 128, 256, 384, 512, 640, 768, 896]:
            for column in range(0, 128):
                byte  = ((ord(data[row_offset + (column / 8)      ]) >> (7 - (column % 8))) & 1) << 1
                byte += ((ord(data[row_offset + (column / 8) + 16 ]) >> (7 - (column % 8))) & 1) << 0
                byte += ((ord(data[row_offset + (column / 8) + 32 ]) >> (7 - (column % 8))) & 1) << 3
                byte += ((ord(data[row_offset + (column / 8) + 48 ]) >> (7 - (column % 8))) & 1) << 2
                byte += ((ord(data[row_offset + (column / 8) + 64 ]) >> (7 - (column % 8))) & 1) << 5
                byte += ((ord(data[row_offset + (column / 8) + 80 ]) >> (7 - (column % 8))) & 1) << 4
                byte += ((ord(data[row_offset + (column / 8) + 96 ]) >> (7 - (column % 8))) & 1) << 7
                byte += ((ord(data[row_offset + (column / 8) + 112]) >> (7 - (column % 8))) & 1) << 6
                self._data(byte ^ 0xff)

if __name__ == "__main__":
    import sys

    if len(sys.argv) < 2:
        print "Usage: %s <128x64 binary PBM image>" % (sys.argv[0])
        sys.exit(1)

    display = SSD1306()
    display.pbm(sys.argv[1])
          


And here is how it looks with an image loaded:

SSD1306 in action.


Topic: Scripts and Code, by Kjetil @ 21/07-2019, Article Link

Commodore 64 Game Cheats

I recently tried out the same tricks from my older article about DOS games, but for a Commodore 64 game instead. This time using the VICE emulator for Blagger by Alligata, a game I could never finish as a kid.

I present some of the steps I used to create the "cheat" patch for infinite lives.
1) Start the game (should start with 5 lives) and go into the VICE monitor.
2) Dump the memory and state of the C64 with the "dump" command.
3) Continue the game, and just loose 1 life.
4) Re-enter the monitor and dump the memory and state again with the "dump" command.
5) Convert the dumps to hex and do a diff on them, to see what has changed. It may take a while to find what you are looking for, which may require additional dumps.
Eventually I found this suspicious memory area, where two values were decremented twice:

101c101
< 00000740  20 20 20 20 1e 57 57 1e  57 57 1e 7a 3a 3b 42 43  |    .WW.WW.z:;BC|
---
> 00000740  20 20 20 20 1e 57 57 1e  57 57 1e 7a 3a 3b 44 45  |    .WW.WW.z:;DE|
          

Although this is at address 0x74e and 0x74f in the dump file, the actual memory addresses are 0x6ca and 0x6cb due to the format of the dump.
6) Now, with an address to look at, set a watch point on this in the VICE monitor.
7) Continue the game again and loose another life.
8) The monitor should now stop execution automatically if done correctly. In my case it displayed:

(C:$1102) w $06ca
WATCH: 1  C:$06ca  (Stop on load store)
(C:$1102) x
#1 (Stop on  load 06ca)  076 050
.C:0de6  AE CA 06    LDX $06CA      - A:01 X:44 Y:00 SP:f6 ..-....C  184810550
.C:0de9  CA          DEX            - A:01 X:44 Y:00 SP:f6 ..-....C  184810550
(C:$0de9)
          

This assembly instruction (DEX) means the memory area is being decremented, exactly what we are looking for.
9) After investigation of the assembly code in that area I found two decrement instructions. These could be patched with NOP (No Operation) instructions (6502 machine code 0xEA) from the VICE monitor like so:

(C:$0e0c) > $0de9 ea
(C:$0e0c) > $0dea ea
          

10) Now, when continuing to play the game, any lost life is simply ignored.

To apply a patch like this permanently, do it on the file (in this case a PRG file) instead of directly in memory of course. The code location will be different, so it must be searched for manually.

Topic: Configuration, by Kjetil @ 02/07-2019, Article Link

Older articles