Information wants to be free...

Space Ship Simulator in OpenGL

I finally finished a project I had suspended many years ago when I was looking into OpenGL. At that time my solution had problems that I now later have discovered was related to the dreaded Gimbal lock caused by the use of Euler angles. The new solution uses rotation matrices directly. It uses the GLUT library which is kind of deprecated, but still very widely available and convenient for simpler OpenGL programs and demos like this one.

This space ship simulator is quite simple, but allows movement in all directions. When the program is started, the "universe" is populated with some randomly generated (really small) planets which can be navigated around. Use W/S to pitch, A/S to yaw, Z/C to roll and R/F to increase/decrease thrusters.

Here is the code, compile it like so: gcc -o space space.c -lGL -lGLU -lglut -lm -Wall

#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

#define WORLD_SIZE 25 /* Distance to fake walls from origin. */

#define GRID_SPACING 5
#define GRID_START ((0 - WORLD_SIZE) + GRID_SPACING)
#define GRID_END (WORLD_SIZE - GRID_SPACING)
#define GRID_SIZE ((GRID_END - GRID_START) / GRID_SPACING)

#define PLANETS_MAX 10
#define PLANETS_CHANCE (GRID_SIZE * GRID_SIZE * GRID_SIZE) / PLANETS_MAX



typedef struct vector_s {
  float x;
  float y;
  float z;
} vector_t;

typedef struct planet_s {
  vector_t pos;
  float size;
  float color_r;
  float color_g;
  float color_b;
} planet_t;

typedef struct planet_distance_s {
  int planet_index;
  float distance;
} planet_distance_t;



static int camera_mode = 0;
static float ship_speed = 0.0;
static int old_mouse_x;
static int old_mouse_y;

static planet_t planets[PLANETS_MAX];
static int planets_count = 0;

static vector_t ship_forward_vector = {1,0,0};
static vector_t ship_up_vector      = {0,1,0};
static vector_t ship_right_vector   = {0,0,1};
static vector_t ship_position       = {0,0,0};



static vector_t vector_normalize(vector_t v)
{
  float magnitude;
  vector_t normalized;

  magnitude = sqrt((v.x * v.x) + (v.y * v.y) + (v.z * v.z));
  normalized.x = v.x / magnitude;
  normalized.y = v.y / magnitude;
  normalized.z = v.z / magnitude;

  return normalized;
}

static vector_t vector_cross_product(vector_t a, vector_t b)
{
  vector_t cross;

  cross.x = (a.y * b.z) - (a.z * b.y);
  cross.y = (a.z * b.x) - (a.x * b.z);
  cross.z = (a.x * b.y) - (a.y * b.x);

  return cross;
}

static vector_t vector_multiply(vector_t v, float f)
{
  vector_t product;

  product.x = v.x * f;
  product.y = v.y * f;
  product.z = v.z * f;

  return product;
}

static vector_t vector_sum(vector_t a, vector_t b)
{
  vector_t sum;

  sum.x = a.x + b.x;
  sum.y = a.y + b.y;
  sum.z = a.z + b.z;

  return sum;
}

static vector_t vector_difference(vector_t a, vector_t b)
{
  vector_t difference;

  difference.x = a.x - b.x;
  difference.y = a.y - b.y;
  difference.z = a.z - b.z;

  return difference;
}

static float vector_distance(vector_t a, vector_t b)
{
  return sqrt(((a.x - b.x) * (a.x - b.x)) +
              ((a.y - b.y) * (a.y - b.y)) +
              ((a.z - b.z) * (a.z - b.z)));
}



static void ship_pitch(float angle)
{
  ship_forward_vector = vector_normalize(
    vector_sum(
      vector_multiply(ship_forward_vector, cos(angle * (M_PI / 180))),
      vector_multiply(ship_up_vector, sin(angle * (M_PI / 180)))));

  ship_up_vector = vector_cross_product(
    ship_forward_vector, ship_right_vector);

  ship_up_vector = vector_multiply(ship_up_vector, -1.0);
}

static void ship_yaw(float angle)
{
  ship_forward_vector = vector_normalize(
    vector_difference(
      vector_multiply(ship_forward_vector, cos(angle * (M_PI / 180))),
      vector_multiply(ship_right_vector, sin(angle * (M_PI / 180)))));

  ship_right_vector = vector_cross_product(
    ship_forward_vector, ship_up_vector);
}

static void ship_roll(float angle)
{
  ship_right_vector = vector_normalize(
    vector_sum(
      vector_multiply(ship_right_vector, cos(angle * (M_PI / 180))),
      vector_multiply(ship_up_vector, sin(angle * (M_PI / 180)))));

  ship_up_vector = vector_cross_product(
    ship_forward_vector, ship_right_vector);

  ship_up_vector = vector_multiply(ship_up_vector, -1.0);
}

static void ship_advance(float distance)
{
  ship_position = vector_sum(ship_position, 
    vector_multiply(ship_forward_vector, distance));
}

#ifdef DEBUG_MODE
static void ship_ascend(float distance)
{
  ship_position = vector_sum(ship_position, 
    vector_multiply(ship_up_vector, distance));
}

static void ship_strafe(float distance)
{
  ship_position = vector_sum(ship_position, 
    vector_multiply(ship_right_vector, distance));
}
#endif /* DEBUG_MODE */



static void idle()
{
  if (ship_speed != 0) {
    ship_advance(ship_speed);
  }

  glutPostRedisplay();

#ifdef DEBUG_MODE
  fprintf(stderr, "Speed: %.2f, X: %.2f, Y: %.2f, Z: %.2f\n",
    ship_speed, ship_position.x, ship_position.y, ship_position.z);
#endif /* DEBUG_MODE */
}

static void draw_ship(void)
{
  float rotation[16];

  glTranslatef(ship_position.x, ship_position.y, ship_position.z);

  rotation[0]  = ship_right_vector.x;
  rotation[1]  = ship_right_vector.y;
  rotation[2]  = ship_right_vector.z;
  rotation[3]  = 0;
  rotation[4]  = ship_up_vector.x;
  rotation[5]  = ship_up_vector.y;
  rotation[6]  = ship_up_vector.z;
  rotation[7]  = 0;
  rotation[8]  = ship_forward_vector.x;
  rotation[9]  = ship_forward_vector.y;
  rotation[10] = ship_forward_vector.z;
  rotation[11] = 0;
  rotation[12] = 0;
  rotation[13] = 0;
  rotation[14] = 0;
  rotation[15] = 1;
  glMultMatrixf(rotation);

  glScalef(0.5, 0.5, 0.5);
  glColor3f(0.9, 0.9, 0.9);

  glBegin(GL_LINE_LOOP);
    glVertex3f(-1.0, -1.0, 0.0);
    glVertex3f(1.0, -1.0, 0.0);
    glVertex3f(1.0, 1.0, 0.0);
    glVertex3f(-1.0, 1.0, 0.0);
  glEnd();
  glBegin(GL_LINE_LOOP);
    glVertex3f(-1.0, -1.0, 0.0);
    glVertex3f(1.0, -1.0, 0.0);
    glVertex3f(0.0, 0.0, 4.0);
  glEnd();
  glBegin(GL_LINE_LOOP);
    glVertex3f(1.0, -1.0, 0.0);
    glVertex3f(1.0, 1.0, 0.0);
    glVertex3f(0.0, 0.0, 4.0);
  glEnd();
  glBegin(GL_LINE_LOOP);
    glVertex3f(1.0, 1.0, 0.0);
    glVertex3f(-1.0, 1.0, 0.0);
    glVertex3f(0.0, 0.0, 4.0);
  glEnd();
  glBegin(GL_LINE_LOOP);
    glVertex3f(-1.0, 1.0, 0.0);
    glVertex3f(-1.0, -1.0, 0.0);
    glVertex3f(0.0, 0.0, 4.0);
  glEnd();
}

#ifdef DEBUG_MODE
static void draw_axis_indicator(void)
{
  /* Draw it at origin. */
  GLfloat old_line_width;
  glGetFloatv(GL_LINE_WIDTH, &old_line_width);
  glLineWidth(3.0);

  glBegin(GL_LINES);
    /* Red X-Axis */
    glColor3f(1, 0, 0);
    glVertex3f(0, 0, 0);
    glVertex3f(1, 0, 0); 
    /* Green Y-Axis */
    glColor3f(0, 1, 0);
    glVertex3f(0, 0, 0);
    glVertex3f(0, 1, 0);
    /* Blue Z-Axis */
    glColor3f(0, 0, 1);
    glVertex3f(0, 0, 0);
    glVertex3f(0, 0, 1); 
  glEnd();

  glLineWidth(old_line_width);
}
#endif /* DEBUG_MODE */

static int planet_distance_compare(const void *p1, const void *p2)
{
  return ((planet_distance_t *)p1)->distance <
         ((planet_distance_t *)p2)->distance;
}

static void display(void)
{
  glClear(GL_COLOR_BUFFER_BIT);
  glLoadIdentity();

  if (camera_mode == 0) {
    /* Inside ship. */
    vector_t view_point;
    view_point = vector_sum(ship_position, ship_forward_vector);

    gluLookAt(ship_position.x, ship_position.y, ship_position.z,
              view_point.x, view_point.y, view_point.z,
              ship_up_vector.x, ship_up_vector.y, ship_up_vector.z);
  } else {
    /* Outside ship, a static look towards origin. */
    glRotatef(45.0, 1.0, 0.0, 0.0);
    glRotatef(120.0, 0.0, 1.0, 0.0);
    glTranslatef(WORLD_SIZE / 2, 0 - (WORLD_SIZE / 2), WORLD_SIZE / 2);
  }

  /* Draw floor/roof/walls, which are actually big cubes! */
  glColor3f(0.0, 0.0, 0.0);

  glPushMatrix();
    glTranslatef(0.0, -WORLD_SIZE, 0.0);
    glScalef(WORLD_SIZE * 2, 0.1, WORLD_SIZE * 2);
#ifdef DEBUG_MODE
    glColor3f(0.0, 0.5, 0.0);
#endif /* DEBUG_MODE */
    glutSolidCube(1.0);
  glPopMatrix();

  glPushMatrix();
    glTranslatef(0.0, WORLD_SIZE, 0.0);
    glScalef(WORLD_SIZE * 2, 0.1, WORLD_SIZE * 2);
#ifdef DEBUG_MODE
    glColor3f(0.0, 0.0, 0.5);
#endif /* DEBUG_MODE */
    glutSolidCube(1.0);
  glPopMatrix();

  glPushMatrix();
    glTranslatef(WORLD_SIZE, 0.0, 0.0);
    glScalef(0.1, WORLD_SIZE * 2, WORLD_SIZE * 2);
#ifdef DEBUG_MODE
    glColor3f(0.5, 0.0, 0.0);
#endif /* DEBUG_MODE */
    glutSolidCube(1.0);
  glPopMatrix();

  glPushMatrix();
    glTranslatef(-WORLD_SIZE, 0.0, 0.0);
    glScalef(0.1, WORLD_SIZE * 2, WORLD_SIZE * 2);
#ifdef DEBUG_MODE
    glColor3f(0.5, 0.5, 0.0);
#endif /* DEBUG_MODE */
    glutSolidCube(1.0);
  glPopMatrix();

  glPushMatrix();
    glTranslatef(0.0, 0.0, WORLD_SIZE);
    glScalef(WORLD_SIZE * 2, WORLD_SIZE * 2, 0.1);
#ifdef DEBUG_MODE
    glColor3f(0.5, 0.0, 0.5);
#endif /* DEBUG_MODE */
    glutSolidCube(1.0);
  glPopMatrix();

  glPushMatrix();
    glTranslatef(0.0, 0.0, -WORLD_SIZE);
    glScalef(WORLD_SIZE * 2, WORLD_SIZE * 2, 0.1);
#ifdef DEBUG_MODE
    glColor3f(0.0, 0.5, 0.5);
#endif /* DEBUG_MODE */
    glutSolidCube(1.0);
  glPopMatrix();

  /* Calculate distance from ship to planets, because they need to be
     drawn/rendered from the furthest away first. */
  planet_distance_t distance[PLANETS_MAX];
  for (int i = 0; i < planets_count; i++) {
    distance[i].planet_index = i;
    distance[i].distance = vector_distance(ship_position, planets[i].pos);
  }
  qsort(distance, planets_count, sizeof(planet_distance_t),
    planet_distance_compare);

  /* Draw planets. */
  for (int i = 0; i < planets_count; i++) {
    int n = distance[i].planet_index;
    glPushMatrix();
      GLUquadric *quadric = gluNewQuadric();
      if (quadric != 0) {
        glTranslatef(planets[n].pos.x, planets[n].pos.y, planets[n].pos.z);
        glColor3f(planets[n].color_r, planets[n].color_g, planets[n].color_b);
        gluSphere(quadric, planets[n].size, 20, 20);
        gluDeleteQuadric(quadric);
      }
    glPopMatrix();
  }
    
  if (camera_mode != 0) {
    glPushMatrix();
      draw_ship();
    glPopMatrix();
  }

#ifdef DEBUG_MODE
  glPushMatrix();
    draw_axis_indicator();
  glPopMatrix();
#endif /* DEBUG_MODE */

  glFlush();
  glutSwapBuffers();
}

static void reshape(int w, int h)
{
  glViewport(0, 0, (GLsizei)w, (GLsizei)h);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 150.0);
  glMatrixMode(GL_MODELVIEW);
}

static void keyboard(unsigned char key, int x, int y)
{
  switch (key) {
  case 's':
    ship_pitch(-1.0);
    break;
  case 'w':
    ship_pitch(1.0);
    break;
  case 'd':
    ship_yaw(-1.0);
    break;
  case 'a':
    ship_yaw(1.0);
    break;
  case 'z':
    ship_roll(-1.0);
    break;
  case 'c':
    ship_roll(1.0);
    break;
  case 'r':
    ship_speed += 0.01;
    break;
  case 'f':
    ship_speed -= 0.01;
    break;
#ifdef DEBUG_MODE
  case 't':
    ship_advance(0.1);
    break;
  case 'g':
    ship_advance(-0.1);
    break;
  case 'y':
    ship_ascend(0.1);
    break;
  case 'h':
    ship_ascend(-0.1);
    break;
  case 'u':
    ship_strafe(0.1);
    break;
  case 'j':
    ship_strafe(-0.1);
    break;
  case 'x':
    camera_mode = (camera_mode) ? 0 : 1;
    break;
#endif /* DEBUG_MODE */
  case 'q':
    exit(0);
    break;
  }
}

static void motion(int x, int y)
{
  if (x > old_mouse_x) {
    ship_yaw(1.0);
  } else if (x < old_mouse_x) {
    ship_yaw(-1.0);
  }

  if (y > old_mouse_y) {
    ship_pitch(-1.0);
  } else if (y < old_mouse_y) {
    ship_pitch(1.0);
  }

  old_mouse_x = x;
  old_mouse_y = y;
}

void generate_planets(void)
{
  for (int x = GRID_START; x < GRID_END; x += GRID_SPACING) {
    for (int y = GRID_START; y < GRID_END; y += GRID_SPACING) {
      for (int z = GRID_START; z < GRID_END; z += GRID_SPACING) {
        if (x == 0 && y == 0 && z == 0) {
          /* Ignore origin. */
          continue;
        }

        if ((rand() % PLANETS_CHANCE) == 0) {
          planets[planets_count].pos.x = (x - 2) + (rand() % 4);
          planets[planets_count].pos.y = (y - 2) + (rand() % 4);
          planets[planets_count].pos.z = (z - 2) + (rand() % 4);
          planets[planets_count].size = 
            ((rand() % ((GRID_SPACING * 10) - 1)) / 20.0) + 0.1;
          planets[planets_count].color_r = (rand() % 11) / 10.0;
          planets[planets_count].color_g = (rand() % 11) / 10.0;
          planets[planets_count].color_b = (rand() % 11) / 10.0;

#ifdef DEBUG_MODE
          printf("X=%.1f, Y=%.1f, Z=%.1f, Size=%.1f, Col=%.1f;%.1f;%.1f\n", 
            planets[planets_count].pos.x,
            planets[planets_count].pos.y,
            planets[planets_count].pos.z,
            planets[planets_count].size,
            planets[planets_count].color_r,
            planets[planets_count].color_g,
            planets[planets_count].color_b);
#endif /* DEBUG_MODE */

          if ((planets_count + 1) >= PLANETS_MAX) {
            return;
          } else {
            planets_count++;
          }
        }
      }
    }
  }
}

int main(int argc, char *argv[])
{
  srand(time(NULL));
  generate_planets();
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
  glutInitWindowSize(800, 800);
  glutInitWindowPosition(100, 100);
  glutCreateWindow(argv[0]);
  glClearColor(0.0, 0.0, 0.0, 0.0);
  glShadeModel(GL_FLAT);
  glutDisplayFunc(display);
  glutReshapeFunc(reshape);
  glutIdleFunc(idle);
  glutKeyboardFunc(keyboard);
  glutMotionFunc(motion);
  glutMainLoop();
  return 0;
}
          


Here is a screenshot of what it looks like, just some "planets" that looks like spheres:

Space Ship Simulator Screenshot


Topic: Scripts and Code, by Kjetil @ 05/03-2021, Article Link

Turning Frog VL6180 Upgrade

Many years ago I got a soldering kit, the "ELENCO 21-882" which is a "frog robot" with two motors that reacts to sound. I had been thinking about ways to upgrade it, and I finally got around to doing that by controlling it with a Arduino Pro Mini and a VL6180 sensor to measure distance.

The original sound based control works by clocking a "4017 Decade Counter" IC with the input from a electret microphone. The easiest way to hijack the control is to remove this IC from the socket and wire the Arduino into it.

I used the following connections:
Arduino RAW <-> Socket pin 16 (VDD, 9V supply from battery.)
Arduino GND <-> Socket pin 8 (VSS)
Arduino D10 <-> Socket pin 1 (Output, diode for left motor.)
Arduino D11 <-> Socket pin 7 (Output, diode for right motor.)
Arduino D12 <-> Socket pin 2 (Output, diodes for both motors.)

Cobbled together it looks like this:

Frog Upgrade

The FTDI is only used for uploading the program and can be removed of course.

The Arduino Sketch code is very simple:

#include "Adafruit_VL6180X.h"

static Adafruit_VL6180X vl = Adafruit_VL6180X();
static int keep_going = 0;

void setup() {
  pinMode(10, OUTPUT); // Left motor
  pinMode(11, OUTPUT); // Right motor
  pinMode(12, OUTPUT); // Both motors
  pinMode(13, OUTPUT); // On-board Arduino LED
  vl.begin();
}

void loop() {
  uint8_t range = vl.readRange();
  uint8_t status = vl.readRangeStatus();

  if ((status == VL6180X_ERROR_NONE) && (range < 200)) {
    // Go left
    digitalWrite(12, LOW);
    digitalWrite(10, HIGH);
    keep_going = 10; // Keep going to finish the turn...
  } else {
    if (keep_going > 0) {
      keep_going--;
    } else {
      // Go forward
      digitalWrite(10, LOW);
      digitalWrite(12, HIGH);
    }
  }
  
  delay(50);
}
          


Topic: Scripts and Code, by Kjetil @ 13/02-2021, Article Link

USB IR REMOCON Firmware Replacement

I bought this Bit Trade One USB Infrared Remote Control Kit at an electronics store in Japan, which lets you use a standard TV remote to control a PC. While the device works on Linux, since it presents itself as a standard USB HID device, it can only be configured in Windows. But a bigger problem is that the original firmware contained some kind of bug where part of the TV remote mappings would get corrupted after power cycling.

To get around these limitations and problems I have created a new firmware replacement for the onboard PIC18F14K50 microcontroller. For maximum flexibility I decided to make something that emulates the protocol used by the Dangerous Prototypes USB IR Toy. This means the device can be used together with LIRC on Linux, which offers a lot of advanced functionality. This also moves the configuration aspect to software on Linux instead of needing to re-flash the PIC microcontroller EEPROM. Note that this device also has an IR sender, but I only implemented support for the IR receive part.

You can get the firmware here or the MPLAB project source code here. I have used Microchip's own USB stack for this project, which is licensed under the Apache license. The parts I wrote myself I consider to be released unlicensed directly into the public domain. I'm including the main part of the code here for an easy reference:

#include "system.h"

#include <stdint.h>
#include <string.h>
#include <stddef.h>

#include "usb.h"

#include "app_irtoy_emu.h"
#include "usb_config.h"

static uint8_t readBuffer[CDC_DATA_OUT_EP_SIZE];
static uint8_t writeBuffer[CDC_DATA_IN_EP_SIZE];

static bool inSamplingMode = false;
static uint16_t pulseHighLen = 0;
static uint16_t pulseLowLen = 0;
static uint16_t pendingPulse = 0;
static bool endOfTransmission = true;
static bool waitForEOT = false;

void samplingModeSetup(void)
{
    /* Set variables to known state. */
    pulseHighLen = 0;
    pulseLowLen = 0;
    pendingPulse = 0;
    endOfTransmission = true;
    waitForEOT = false;

    T0CON = 0b11000000; /* Enable Timer0 as 8-Bit with no scaling. */

    RCONbits.IPEN = 1; /* Enable priority levels on interrupts. */
    INTCON2bits.TMR0IP = 1; /* Make Timer0 a high priority interrupt. */
    INTCONbits.TMR0IF = 0; /* Clear Timer0 interrupt flag. */
    INTCONbits.TMR0IE = 1; /* Enable Timer0 interrupts. */
    INTCONbits.GIEH = 1; /* Make sure high priority interrupts are enabled. */
    INTCONbits.GIEL = 1; /* Make sure low priority interrupts are enabled. */
}

void samplingModeService(void)
{
    uint8_t numBytesRead;

    numBytesRead = getsUSBUSART(readBuffer, 1);
    if (numBytesRead == 1 && readBuffer[0] == 0x00) /* Reset */
    {
        /* Disable Timer0 interrupts. */
        INTCONbits.TMR0IE = 0;
        inSamplingMode = false;
        return;
    }

    INTCONbits.TMR0IE = 0;
    if (pendingPulse > 5)
    {
        writeBuffer[0] = (uint8_t)(pendingPulse / 256);
        writeBuffer[1] = (uint8_t)(pendingPulse % 256);
        putUSBUSART(writeBuffer, 2);
        pendingPulse = 0;
        endOfTransmission = false;
        waitForEOT = true;
    }

    if ((waitForEOT == true) && (endOfTransmission == true))
    {
        writeBuffer[0] = 0xFF;
        writeBuffer[1] = 0xFF;
        putUSBUSART(writeBuffer, 2);
        waitForEOT = false;
    }
    INTCONbits.TMR0IE = 1;
}

void APP_IRToyEmulationInterrupt(void)
{
    if (INTCONbits.TMR0IF == 1)
    {
        /* Check if IR sensor (inverted input) is active. */
        if (PORTCbits.RC7 == 0)
        {
            if (pulseLowLen > 5)
            {
                pendingPulse = pulseLowLen;
            }
            pulseLowLen = 0;

            pulseHighLen += 2;
        }
        else
        {
            if (pulseHighLen > 5)
            {
                pendingPulse = pulseHighLen;
                endOfTransmission = false;
            }
            pulseHighLen = 0;

            if (endOfTransmission == false)
            {
                pulseLowLen += 2;
                if (pulseLowLen >= 0xFFFE)
                {
                    pulseLowLen = 0;
                    endOfTransmission = true;
                }
            }
        }
        INTCONbits.TMR0IF = 0;
    }
}

void APP_IRToyEmulationInitialize()
{   
    line_coding.bCharFormat = 0;
    line_coding.bDataBits = 8;
    line_coding.bParityType = 0;
    line_coding.dwDTERate = 115200;

    /* I/O settings as used in orignal Bit Trade One firmware. */
    TRISB  = 0x00;
    TRISC  = 0x80;
    LATC   = 0xFF;
    ANSEL  = 0x00;
    ANSELH = 0x00;

    /* But turn off IR sender diode output, no support implemented. */
    PORTCbits.RC5 = 0;
}

void APP_IRToyEmulationTasks()
{
    /* If the USB device isn't configured yet, we can't really do anything
     * else since we don't have a host to talk to.  So jump back to the
     * top of the while loop. */
    if (USBGetDeviceState() < CONFIGURED_STATE)
    {
        return;
    }

    /* If we are currently suspended, then we need to see if we need to
     * issue a remote wakeup.  In either case, we shouldn't process any
     * keyboard commands since we aren't currently communicating to the host
     * thus just continue back to the start of the while loop. */
    if (USBIsDeviceSuspended() == true)
    {
        return;
    }

    if (inSamplingMode == true)
    {
        samplingModeService();
    }
    else
    {
        if (USBUSARTIsTxTrfReady() == true)
        {
            uint8_t numBytesRead;
            numBytesRead = getsUSBUSART(readBuffer, 1);

            if (numBytesRead == 1)
            {
                switch (readBuffer[0])
                {
                case 'S': /* IRIO Sampling Mode */
                case 's':
                    writeBuffer[0] = 'S'; /* Answer OK */
                    writeBuffer[1] = '0';
                    writeBuffer[2] = '1';
                    putUSBUSART(writeBuffer, 3);
                    samplingModeSetup();
                    inSamplingMode = true;
                    break;

                case 'V': /* Acquire Version */
                case 'v':
                    writeBuffer[0] = 'V'; /* Answer OK */
                    writeBuffer[1] = '9'; /* Hardware Version */
                    writeBuffer[2] = '9'; /* Firmware Version High */
                    writeBuffer[3] = '9'; /* Firmware Version Low */
                    putUSBUSART(writeBuffer, 4);
                    break;

                default: /* All the rest is unsupported! */
                    writeBuffer[0] = '?';
                    putUSBUSART(writeBuffer, 1);
                    break;
                }
            }
        }
    }

#if defined(USB_POLLING)
    USBDeviceTasks();
#endif
    CDCTxService();
}
          


To use it in LIRC, setup lirc_options.conf similar to the IR Toy using:

driver = irtoy
device = /dev/ttyACM0
          


Topic: Scripts and Code, by Kjetil @ 23/01-2021, Article Link

USB Relay Control Simplified

I got a USB controlled relay board a while ago, which is identified with the USB ID 16c0:05df. There are various controller programs for these on GitHub, but all of them are rather complicated, so I decided to write my own simplified version using the same principles. Like others, it has a dependency against the hidapi library.

The result is this C program:

#include <hidapi/hidapi.h>
#include <wchar.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define TARGET_DEVICE L"USBRelay2"

#define RELAY_OFF 0xfd
#define RELAY_ON  0xff

int main(int argc, char *argv[])
{
  struct hid_device_info *hidinfo;
  hid_device *hiddev;
  unsigned char buf[8];
  int result, relay_number, relay_operation;

  hidinfo = hid_enumerate(0, 0);
  while (hidinfo != NULL) {
    if (0 == wcscmp(hidinfo->product_string, TARGET_DEVICE)) {
      break;
    }
    hidinfo = hidinfo->next;
  }

  if (hidinfo == NULL) {
    fprintf(stderr, "Did not find '%ls' in USB devices!\n", TARGET_DEVICE);
    return 1;
  }

  hiddev = hid_open_path(hidinfo->path);
  if (hiddev == NULL) {
    fprintf(stderr, "hid_open_path() failed on: %s\n", hidinfo->path);
    return 1;
  }

  if (argc > 2) {
    relay_number = atoi(argv[1]) & 0b11; /* Limit to 2 relays. */
    relay_operation = 0;
    if (0 == strcasecmp(argv[2], "on")) {
      relay_operation = RELAY_ON;
    } else if (0 == strcasecmp(argv[2], "off")) {
      relay_operation = RELAY_OFF;
    } else {
      fprintf(stderr, "Invalid relay operation\n");
      hid_close(hiddev);
      return 1;
    }

    memset(buf, 0x00, sizeof(buf));
    buf[0] = 0x00;
    buf[1] = relay_operation;
    buf[2] = relay_number;
    result = hid_write(hiddev, buf, sizeof(buf));
    if (result == -1) {
      fprintf(stderr, "hid_write() failed!\n");
      hid_close(hiddev);
      return 1;
    }
  }

  buf[0] = 0x01;
  result = hid_get_feature_report(hiddev, buf, sizeof(buf));
  if (result == -1) {
    fprintf(stderr, "hid_get_feature_report() failed!\n");
    hid_close(hiddev);
    return 1;
  }

  printf("Relay #1: %d\n",  buf[7] & 0b01);
  printf("Relay #2: %d\n", (buf[7] & 0b10) >> 1);
  printf("Usage: %s <relay number> <on|off>\n", argv[0]);

  hid_close(hiddev);
  return 0;
}
          


Compile it like so: gcc -o usbrelay2 usbrelay2.c -lhidapi-hidraw

Topic: Scripts and Code, by Kjetil @ 02/01-2021, Article Link

Booting DOS from PS/2 BASIC

I have a old standalone motherboard from an IBM PS/2 Model 80. The PS/2 systems have a different kind of floppy connector and floppy drive, so one cannot simply connect a regular PC floppy drive without doing some hardware modifications. But fortunately, most of the PS/2 systems have IBM Cassette BASIC in ROM chips on the motherboard and will boot that in case everything else fails.

Someone else has already managed to boot some software from BASIC, so I took it a step further and was able to boot DOS as well. My work is based on the previous Serial Port Floppy Drive Emulation tricks to emulate the floppy drive over the COM1 port. The assembly program presented here will attempt boot a floppy image. Unfortunately I have not been able to boot the reference disk yet...

Once booted into BASIC, it is technically possible to input the complete program by hand (by keyboard):

1 data 233,157,0,184,192,7,142,192,49,219,184,1,2,185,1,0,49,210
2 data 205,19,234,0,124,0,0,251,128,250,0,117,90,128,252,2,116,5
3 data 128,252,3,117,74,83,81,82,80,80,80,232,76,0,136,224,232,71
4 data 0,136,200,232,66,0,136,232,232,61,0,136,208,232,56,0,136,240
5 data 232,51,0,90,48,246,184,0,2,247,226,137,193,88,128,252,3,116
6 data 11,232,49,0,38,136,7,67,226,247,235,9,38,138,7,232,18,0
7 data 67,226,247,88,90,89,91,48,228,248,202,2,0,234,121,0,121,0
8 data 82,186,248,3,238,186,253,3,236,36,32,132,192,116,249,90,195,82
9 data 186,250,3,236,36,14,60,4,117,246,186,248,3,236,90,195,186,251
10 data 3,236,12,128,238,186,248,3,176,12,238,186,249,3,176,0,238,186
11 data 251,3,236,36,127,238,186,250,3,176,6,238,186,251,3,176,3,238
12 data 186,249,3,236,12,1,238,49,192,142,216,250,232,0,0,88,91,45
13 data 210,0,137,198,184,48,0,142,192,191,0,0,185,157,0,46,138,4
14 data 38,136,5,70,71,226,246,62,161,76,0,38,163,119,0,62,161,78
15 data 0,38,163,121,0,62,199,6,76,0,22,0,62,140,6,78,0,49
16 data 192,62,163,0,4,251,180,9,176,33,183,0,179,4,185,3,0,205
17 data 16,180,0,205,22,234,0,0,48,0
99 def seg=1984:a=0:for i=0 to 297:read j:poke a+i,j:next:call a
          

However, it is very easy to make a mistake and this work is very tedious.
Instead it's a lot better to chain-load the program using the same method from the GitHub link.

The steps are as follows, assuming you are on a Linux box:
1) Make sure that the serial port on your system is set correctly:

stty -F /dev/ttyS0 9600 raw
          


2) Enter and run the chain-loader in BASIC on the PS/2 system:

1 data 14,7,184,227,0,153,137,215,205,20,185,19,1,180,2,205,20,158,120,249,252,170,226,245,81,195
2 def seg=256:a=65432:for i=0 to 25:read j:poke a+i,j:next:call a
          


3) Send the assembled program directly through the serial port:

cat sfdboot.bin > /dev/ttyS0
          


4) Start the serial port floppy drive emulator with a bootable image:

./serialfd -d /dev/ttyS0 -a floppy.img
          


5) If everything went well, there should be three red exclamation marks on the PS/2 system, press any key to commence the booting from the emulated image.

In the case of booting MS-DOS it should look something like this:

Starting MS-DOS...


Here is the assembly code, assembled with NASM as follows: nasm sfdboot.asm -fbin -o sfdboot.bin

org 0x0 ; Position independent.
bits 16
cpu 8086

COM1_BASE equ 0x3f8
COM1_THR  equ COM1_BASE + 0 ; Transmitter Holding Buffer
COM1_RBR  equ COM1_BASE + 0 ; Receiver Buffer
COM1_IER  equ COM1_BASE + 1 ; Interrupt Enable Register
COM1_FCR  equ COM1_BASE + 2 ; FIFO Control Register
COM1_IIR  equ COM1_BASE + 2 ; Interrupt Identification Register
COM1_LCR  equ COM1_BASE + 3 ; Line Control Register
COM1_LSR  equ COM1_BASE + 5 ; Line Status Register
COM1_DLL  equ COM1_BASE + 0 ; Divisor Latch Low Byte
COM1_DLH  equ COM1_BASE + 1 ; Divisor Latch High Byte

RESIDENT_SEGMENT equ 0x0030 ; Bootstrap stack area.

section .text
start:
  jmp main

resident_code_start:
  ; Setup ES:BX to point at bootloader address 07C0:0
  mov ax, 0x07C0
  mov es, ax
  xor bx, bx

  ; Read VBR into bootloader memory area:
  mov ax, 0x0201
  mov cx, 0x0001
  xor dx, dx
  int 0x13

  ; Jump to bootloader:
  jmp 0x0:0x7C00

int13_interrupt:
  ; Allow other interrupts:
  sti

  ; Check if accessing drive 0 (A:)
  ; If not, then jump to original interrupt instead.
  cmp dl, 0
  jne original_int13

  ; Only operation 0x02 (Read) and 0x03 (Write) are forwarded.
  ; The rest are bypassed directly and returns OK.
  cmp ah, 2
  je _int13_interrupt_ah_ok
  cmp ah, 3
  jne _int13_interrupt_end
_int13_interrupt_ah_ok:

  ; Save registers:
  push bx
  push cx
  push dx

  ; Save sectors and operation information on stack for use later:
  push ax
  push ax
  push ax

  ; Register AL already set.
  call com_port_send
  mov al, ah
  call com_port_send
  mov al, cl
  call com_port_send
  mov al, ch
  call com_port_send
  mov al, dl
  call com_port_send
  mov al, dh
  call com_port_send

  ; Retrieve sector information (stack AL) into DL register:
  pop dx
  xor dh, dh

  mov ax, 512
  mul dx ; DX:AX = AX * DX
  mov cx, ax

  ; Determine receive (Read) or send (Write) from operation (stack AH):
  pop ax
  cmp ah, 3
  je _int13_interrupt_send_loop

_int13_interrupt_recv_loop:
  call com_port_recv
  mov [es:bx], al
  inc bx
  loop _int13_interrupt_recv_loop
  jmp _int13_loop_done

_int13_interrupt_send_loop:
  mov al, [es:bx]
  call com_port_send
  inc bx
  loop _int13_interrupt_send_loop

_int13_loop_done:

  ; Retrieve sector information (stack AL) as sectors handled:
  pop ax

  ; Restore registers:
  pop dx
  pop cx
  pop bx

_int13_interrupt_end:
  ; AL register will have same value as upon entering routine.
  xor ah, ah ; Code 0 (No Error)
  clc ; Clear error bit.
  retf 2

original_int13:
  jmp original_int13:original_int13 ; Will be overwritten runtime!

; Send contents from AL on COM1 port:
com_port_send:
  push dx
  mov dx, COM1_THR
  out dx, al
  mov dx, COM1_LSR
_com_port_send_wait:
  in al, dx
  and al, 0b00100000 ; Empty Transmit Holding Register
  test al, al
  jz _com_port_send_wait
  pop dx
  ret

; Return contents in AL on COM1 port:
com_port_recv:
  push dx
_com_port_recv_wait:
  mov dx, COM1_IIR
  in al, dx
  and al, 0b00001110 ; Identification
  cmp al, 0b00000100 ; Enable Received Data Available Interrupt
  jne _com_port_recv_wait
  mov dx, COM1_RBR
  in al, dx
  pop dx
  ret

resident_code_end:

main:
  ; Set Baudrate on COM1 to 9600, divisor = 12:
  mov dx, COM1_LCR
  in al, dx
  or al, 0b10000000 ; Set Divisor Latch Access Bit (DLAB).
  out dx, al

  mov dx, COM1_DLL
  mov al, 0xc
  out dx, al
  
  mov dx, COM1_DLH
  mov al, 0
  out dx, al

  mov dx, COM1_LCR
  in al, dx
  and al, 0b01111111 ; Reset Divisor Latch Access Bit (DLAB).
  out dx, al

  ; Disable and clear FIFO on COM1, to put it in 8250 compatibility mode:
  mov dx, COM1_FCR
  mov al, 0b00000110 ; Clear both FIFOs.
  out dx, al
  ; NOTE: Not tested what happens if this is run on an actual 8250 chip...

  ; Set mode on COM1 to 8 data bits, no parity and 1 stop bit:
  mov dx, COM1_LCR
  mov al, 0b00000011 ; 8-N-1
  out dx, al

  ; Enable interrupt bit on COM1:
  mov dx, COM1_IER
  in al, dx
  or al, 0b00000001 ; Enable Received Data Available Interrupt
  out dx, al

  ; Interact directly with IVT:
  xor ax, ax
  mov ds, ax ; Data Segment now 0000
  cli ; Disable Interrupts

  call get_ip
get_ip:
  pop ax ; IP
  pop bx ; CS
  sub ax, (get_ip - resident_code_start)
  mov si, ax ; "resident_code_start" now in SI.

  ; Copy the code to a new resident area using CS:SI -> ES:DI
  mov ax, RESIDENT_SEGMENT
  mov es, ax
  mov di, 0
  mov cx, (resident_code_end - resident_code_start)
_copy_to_resident_area:
  mov byte al, [cs:si]
  mov byte [es:di], al
  inc si
  inc di
  loop _copy_to_resident_area

  ; Save old interrupt handler:
  ; ES = RESIDENT_SEGMENT
  mov ax, [ds:0x4c]
  mov word [es:original_int13 - resident_code_start + 1], ax
  mov ax, [ds:0x4e]
  mov word [es:original_int13 - resident_code_start + 3], ax

  ; Overwrite with new interrupt handler:
  ; ES = RESIDENT_SEGMENT
  mov word [ds:0x4c], (int13_interrupt - resident_code_start)
  mov word [ds:0x4e], es

  ; Zero out COM1 port address in BDA to avoid DOS interference:
  ; DOS can set baudrate to 2400 at startup, which will cause issues.
  xor ax, ax
  mov word [ds:0x400], ax

  sti ; Enable Interrupts

  ; Indicate on screen "Ready for Loading" after key press:
  mov ah, 0x9  ; Write character and attribute at cursor position.
  mov al, 0x21 ; Character = '!'
  mov bh, 0    ; Page Number = 0
  mov bl, 0x4  ; Color = Red
  mov cx, 0x3  ; Number of Times = 3
  int 0x10

  ; Read any key press:
  mov ah, 0x0  ; Read keystroke.
  int 0x16

  ; Jump to new resident area:
  jmp RESIDENT_SEGMENT:0
          


The code is also uploaded to the serialfd GitHub repository in case of future changes and improvements.

Topic: Scripts and Code, by Kjetil @ 02/08-2020, Article Link

Serial Port Floppy Drive Emulation

While working on another project I needed to figure out a way to emulate a floppy drive. After doing some research I learned more about how the Interrupt Vector Table on PCs work and how TSR programs operate under DOS. So the result is a DOS TSR program that intercepts BIOS INT 13H calls and forwards these over the serial port to a remote Linux box that operates on a floppy disk image.

I have borrowed some code from my previous Kermit project that also uses x86 assembly with serial ports. This program also shares some of the same limitations; hard coded with baudrate 9600 on the COM1 port. The TSR has been tested on the Bochs emulator and on a real 25MHz 80486SX PC.

Here is the TSR part of the program, assembled with NASM as follows: nasm serialfd.asm -fbin -o serialfd.com

org 0x100
bits 16
cpu 8086

COM1_BASE equ 0x3f8
COM1_THR  equ COM1_BASE + 0 ; Transmitter Holding Buffer
COM1_RBR  equ COM1_BASE + 0 ; Receiver Buffer
COM1_IER  equ COM1_BASE + 1 ; Interrupt Enable Register
COM1_FCR  equ COM1_BASE + 2 ; FIFO Control Register
COM1_IIR  equ COM1_BASE + 2 ; Interrupt Identification Register
COM1_LCR  equ COM1_BASE + 3 ; Line Control Register
COM1_LSR  equ COM1_BASE + 5 ; Line Status Register
COM1_DLL  equ COM1_BASE + 0 ; Divisor Latch Low Byte
COM1_DLH  equ COM1_BASE + 1 ; Divisor Latch High Byte

section .text
start:
  jmp main

int13_interrupt:
  ; Allow other interrupts:
  sti

  ; Check if accessing drive 0 (A:) or drive 1 (B:)
  ; If not, then jump to original interrupt instead.
  cmp dl, 0
  je _int13_interrupt_dl_ok
  cmp dl, 1
  jne original_int13
_int13_interrupt_dl_ok:

  ; Only operation 0x02 (Read) and 0x03 (Write) are forwarded.
  ; The rest are bypassed directly and returns OK.
  cmp ah, 2
  je _int13_interrupt_ah_ok
  cmp ah, 3
  jne _int13_interrupt_end
_int13_interrupt_ah_ok:

  ; Save registers:
  push bx
  push cx
  push dx

  ; Save sectors and operation information on stack for use later:
  push ax
  push ax
  push ax

  ; Register AL already set.
  call com_port_send
  mov al, ah
  call com_port_send
  mov al, cl
  call com_port_send
  mov al, ch
  call com_port_send
  mov al, dl
  call com_port_send
  mov al, dh
  call com_port_send

  ; Retrieve sector information (stack AL) into DL register:
  pop dx
  xor dh, dh

  mov ax, 512
  mul dx ; DX:AX = AX * DX
  mov cx, ax

  ; Determine receive (Read) or send (Write) from operation (stack AH):
  pop ax
  cmp ah, 3
  je _int13_interrupt_send_loop

_int13_interrupt_recv_loop:
  call com_port_recv
  mov [es:bx], al
  inc bx
  loop _int13_interrupt_recv_loop
  jmp _int13_loop_done

_int13_interrupt_send_loop:
  mov al, [es:bx]
  call com_port_send
  inc bx
  loop _int13_interrupt_send_loop

_int13_loop_done:

  ; Retrieve sector information (stack AL) as sectors handled:
  pop ax

  ; Restore registers:
  pop dx
  pop cx
  pop bx

_int13_interrupt_end:
  ; AL register will have same value as upon entering routine.
  xor ah, ah ; Code 0 (No Error)
  clc ; Clear error bit.
  retf 2

original_int13:
  jmp original_int13:original_int13 ; Will be overwritten runtime!

; Send contents from AL on COM1 port:
com_port_send:
  push dx
  mov dx, COM1_THR
  out dx, al
  mov dx, COM1_LSR
_com_port_send_wait:
  in al, dx
  and al, 0b00100000 ; Empty Transmit Holding Register
  test al, al
  jz _com_port_send_wait
  pop dx
  ret

; Return contents in AL on COM1 port:
com_port_recv:
  push dx
_com_port_recv_wait:
  mov dx, COM1_IIR
  in al, dx
  and al, 0b00001110 ; Identification
  cmp al, 0b00000100 ; Enable Received Data Available Interrupt
  jne _com_port_recv_wait
  mov dx, COM1_RBR
  in al, dx
  pop dx
  ret

; TSR end marker:
tsr_end:

main:
  ; NOTE: No protection to prevent TSR from being loaded twice or more!

  ; Set Baudrate on COM1 to 9600, divisor = 12:
  mov dx, COM1_LCR
  in al, dx
  or al, 0b10000000 ; Set Divisor Latch Access Bit (DLAB).
  out dx, al

  mov dx, COM1_DLL
  mov al, 0xc
  out dx, al
  
  mov dx, COM1_DLH
  mov al, 0
  out dx, al

  mov dx, COM1_LCR
  in al, dx
  and al, 0b01111111 ; Reset Divisor Latch Access Bit (DLAB).
  out dx, al

  ; Disable and clear FIFO on COM1, to put it in 8250 compatibility mode:
  mov dx, COM1_FCR
  mov al, 0b00000110 ; Clear both FIFOs.
  out dx, al
  ; NOTE: Not tested what happens if this is run on an actual 8250 chip...

  ; Set mode on COM1 to 8 data bits, no parity and 1 stop bit:
  mov dx, COM1_LCR
  mov al, 0b00000011 ; 8-N-1
  out dx, al

  ; Enable interrupt bit on COM1:
  mov dx, COM1_IER
  in al, dx
  or al, 0b00000001 ; Enable Received Data Available Interrupt
  out dx, al

  ; Call DOS to get original interrupt handler:
  mov al, 0x13
  mov ah, 0x35
  int 0x21
  mov word [original_int13 + 3], es
  mov word [original_int13 + 1], bx

  ; Call DOS to set interrupt handler:
  mov al, 0x13
  mov ah, 0x25
  ; DS is already same as CS, no need to change.
  mov dx, int13_interrupt
  int 0x21

  ; Terminate and Stay Resident:
  mov dx, tsr_end
  shr dx, 1
  shr dx, 1
  shr dx, 1
  shr dx, 1
  add dx, 0x11 ; Add 0x1 for remainder and 0x10 for PSP.
  mov ax, 0x3100
  int 0x21
          


And here the Linux counterpart in C, just compile with GCC:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <string.h>

#define REGISTER_AL 0
#define REGISTER_AH 1
#define REGISTER_CL 2
#define REGISTER_CH 3
#define REGISTER_DL 4
#define REGISTER_DH 5

#define SECTOR_SIZE 512
#define HEADS_PER_CYLINDER_DEFAULT 2

#define OPERATION_READ_DISK_SECTORS 0x02
#define OPERATION_WRITE_DISK_SECTORS 0x03

static uint16_t get_sectors_per_track(FILE *fh)
{
  uint16_t spt;

  fseek(fh, 24, SEEK_SET); /* Offset in Volume Boot Record. */

  if (fread(&spt, sizeof(uint16_t), 1, fh) != 1) {
    return 0; /* Error */
  }

  /* Currently handling 720K and 1.44M floppies. */
  if (spt == 9 || spt == 18) {
    return spt; /* Valid */
  }

  return 0; /* Invalid */
}

static void display_help(char *progname)
{ 
  fprintf(stderr, "Usage: %s <options>\n", progname);
  fprintf(stderr, "Options:\n"
     "  -h          Display this help and exit.\n"
     "  -d DEVICE   Use TTY DEVICE.\n"
     "  -a IMAGE    Floppy IMAGE for A:\n"
     "  -b IMAGE    Floppy IMAGE for B:\n"
     "  -H HPC      Force HPC heads per cylinder.\n"
     "  -S SPT      Force SPT sectors per track.\n"
     "  -v          Verbose debugging output.\n"
     "\n");
}

int main(int argc, char *argv[])
{
  int result = EXIT_SUCCESS;
  int i, c, arg;
  int cylinder, sector, lba;
  struct termios attr;
  unsigned char registers[6];
  int debug_output = 0;
  char *tty_device = NULL;
  int tty_fd = -1;
  FILE *fh;
  char *floppy_a_image = NULL;
  char *floppy_b_image = NULL;
  FILE *floppy_a_fh = NULL;
  FILE *floppy_b_fh = NULL;
  uint16_t floppy_a_spt = 0;
  uint16_t floppy_b_spt = 0;
  int spt = 0;
  int hpc = HEADS_PER_CYLINDER_DEFAULT;
  char *operation;

  while ((c = getopt(argc, argv, "hd:a:b:H:S:v")) != -1) {
    switch (c) {
    case 'h':
      display_help(argv[0]);
      return EXIT_SUCCESS;

    case 'd':
      tty_device = optarg;
      break;

    case 'a':
      floppy_a_image = optarg;
      break;

    case 'b':
      floppy_b_image = optarg;
      break;

    case 'H':
      hpc = atoi(optarg);
      break;

    case 'S':
      spt = atoi(optarg);
      break;

    case 'v':
      debug_output = 1;
      break;

    case '?':
    default:
      display_help(argv[0]);
      return EXIT_FAILURE;
    }
  }

  if (tty_device == NULL) {
    fprintf(stderr, "Please specify a TTY!\n");
    display_help(argv[0]);
    return EXIT_FAILURE;
  }

  if (floppy_a_image == NULL && floppy_b_image == NULL) {
    fprintf(stderr, "Please specify at least one floppy image!\n");
    display_help(argv[0]);
    return EXIT_FAILURE;
  }

  if (hpc == 0) {
    fprintf(stderr, "Invalid heads per cylinder!\n");
    return EXIT_FAILURE;
  }

  /* Open serial TTY device. */
  tty_fd = open(tty_device, O_RDWR | O_NOCTTY);
  if (tty_fd == -1) {
    fprintf(stderr, "open() on TTY device failed with errno: %d\n", errno);
    return EXIT_FAILURE;
  }

  /* Set TTY into a very raw mode. */
  memset(&attr, 0, sizeof(struct termios));
  attr.c_cflag = B9600 | CS8 | CLOCAL | CREAD;
  attr.c_cc[VMIN] = 1;

  if (tcsetattr(tty_fd, TCSANOW, &attr) == -1) {
    fprintf(stderr, "tcgetattr() on TTY device failed with errno: %d\n", errno);
    close(tty_fd);
    return EXIT_FAILURE;
  }

  /* Make sure TTY "Clear To Send" signal is set. */
  arg = TIOCM_CTS;
  if (ioctl(tty_fd, TIOCMBIS, &arg) == -1) {
    fprintf(stderr, "ioctl() on TTY device failed with errno: %d\n", errno);
    close(tty_fd);
    return EXIT_FAILURE;
  }

  /* Get information about floppy A: */
  if (floppy_a_image != NULL) {
    floppy_a_fh = fopen(floppy_a_image, "r+b");
    if (floppy_a_fh == NULL) {
      fprintf(stderr, "fopen() for floppy A: failed with errno: %d\n", errno);
      result = EXIT_FAILURE;
      goto main_end;
    }

    if (spt == 0) {
      floppy_a_spt = get_sectors_per_track(floppy_a_fh);
    } else {
      floppy_a_spt = spt;
    }
    if (floppy_a_spt == 0) {
      fprintf(stderr, "Invalid sectors per track for floppy A:\n");
      result = EXIT_FAILURE;
      goto main_end;
    }
  }

  /* Get information about floppy B: */
  if (floppy_b_image != NULL) {
    floppy_b_fh = fopen(floppy_b_image, "r+b");
    if (floppy_b_fh == NULL) {
      fprintf(stderr, "fopen() for floppy B: failed with errno: %d\n", errno);
      result = EXIT_FAILURE;
      goto main_end;
    }

    if (spt == 0) {
      floppy_b_spt = get_sectors_per_track(floppy_b_fh);
    } else {
      floppy_b_spt = spt;
    }
    if (floppy_b_spt == 0) {
      fprintf(stderr, "Invalid sectors per track for floppy B:\n");
      result = EXIT_FAILURE;
      goto main_end;
    }
  }

  /* Process input and output. */
  while (1) {
    for (i = 0; i < 6; i++) {
      if (read(tty_fd, &registers[i], sizeof(unsigned char)) != 1) {
        fprintf(stderr, "read() failed with errno: %d\n", errno);
        result = EXIT_FAILURE;
        goto main_end;
      }
    }

    if (debug_output) {
      fprintf(stderr, "AL: 0x%02x\n", registers[REGISTER_AL]);
      fprintf(stderr, "AH: 0x%02x\n", registers[REGISTER_AH]);
      fprintf(stderr, "CL: 0x%02x\n", registers[REGISTER_CL]);
      fprintf(stderr, "CH: 0x%02x\n", registers[REGISTER_CH]);
      fprintf(stderr, "DL: 0x%02x\n", registers[REGISTER_DL]);
      fprintf(stderr, "DH: 0x%02x\n", registers[REGISTER_DH]);
    }

    if (registers[REGISTER_DL] == 0x00) {
      spt = floppy_a_spt;
      fh = floppy_a_fh;
    } else if (registers[REGISTER_DL] == 0x01) {
      spt = floppy_b_spt;
      fh = floppy_b_fh;
    } else {
      fprintf(stderr, "Error: Invalid drive number: %02x\n",
        registers[REGISTER_DL]);
      result = EXIT_FAILURE;
      goto main_end;
    }

    /* CX =       ---CH--- ---CL---
     * cylinder : 76543210 98
     * sector   :            543210
     * LBA = ( ( cylinder * HPC + head ) * SPT ) + sector - 1
    */

    cylinder = ((registers[REGISTER_CL] & 0xc0) << 2)
      + registers[REGISTER_CH];
    sector = registers[REGISTER_CL] & 0x3f;
    lba = ((cylinder * hpc + registers[REGISTER_DH]) * spt) + sector - 1;

    if (debug_output) {
      fprintf(stderr, "Cylinder: %d\n", cylinder);
      fprintf(stderr, "Sector  : %d\n", sector);
      fprintf(stderr, "SPT     : %d\n", spt);
      fprintf(stderr, "HPC     : %d\n", hpc);
      fprintf(stderr, "LBA     : %d\n", lba);
      fprintf(stderr, "Offset  : 0x%x\n", lba * SECTOR_SIZE);
    } else {
      switch (registers[REGISTER_AH]) {
      case OPERATION_READ_DISK_SECTORS:
        operation = "Read";
        break;
      case OPERATION_WRITE_DISK_SECTORS:
        operation = "Write";
        break;
      default:
        operation = "Unknown";
        break;
      }
      fprintf(stderr, "%s %c: sector=%d, cylinder=%d count=%d\n",
        operation, (registers[REGISTER_DL] == 0x00) ? 'A' : 'B',
        sector, cylinder, registers[REGISTER_AL]);
    }

    if (fh != NULL) {
      if (fseek(fh, lba * SECTOR_SIZE, SEEK_SET) == -1) {
        fprintf(stderr, "fseek() failed with errno: %d\n", errno);
        result = EXIT_FAILURE;
        goto main_end;
      }
    }

    switch (registers[REGISTER_AH]) {
    case OPERATION_READ_DISK_SECTORS:
      if (debug_output) {
        fprintf(stderr, "READ SECTOR DATA:\n");
      }
      for (i = 0; i < (SECTOR_SIZE * registers[REGISTER_AL]); i++) {
        if (fh != NULL) {
          c = fgetc(fh);
        } else {
          c = 0xFF; /* Dummy data if image is not loaded. */
        }
        if (debug_output) {
          fprintf(stderr, "%02x ", c);
          if (i % 16 == 15) {
            fprintf(stderr, "\n");
          }
        }
        write(tty_fd, &c, sizeof(unsigned char));
      }
      break;

    case OPERATION_WRITE_DISK_SECTORS:
      if (debug_output) {
        fprintf(stderr, "WRITE SECTOR DATA:\n");
      }
      for (i = 0; i < (SECTOR_SIZE * registers[REGISTER_AL]); i++) {
        read(tty_fd, &c, sizeof(unsigned char));
        if (fh != NULL) {
          fputc(c, fh);
        }
        if (debug_output) {
          fprintf(stderr, "%02x ", c);
          if (i % 16 == 15) {
            fprintf(stderr, "\n");
          }
        }
      }
      if (fh != NULL) {
        fflush(fh);
      }
      break;

    default:
      fprintf(stderr, "Error: Unhandled operation: %02x\n",
        registers[REGISTER_AH]);
      result = EXIT_FAILURE;
      goto main_end;
    }
  }

main_end:
  if (tty_fd != -1) close(tty_fd);
  if (floppy_a_fh != NULL) fclose(floppy_a_fh);
  if (floppy_b_fh != NULL) fclose(floppy_b_fh);

  return result;
}
          


I have also uploaded the code to GitHub in case case of further improvements in the future.

Topic: Scripts and Code, by Kjetil @ 03/07-2020, Article Link

Kermit in x86 Assembly

This is kind of a follow up to my other project on file transfers in DOS. I have made a huge improvement by implementing the Kermit Protocol in 16-bit x86 assembly language. Instead of relying on the horrible BIOS service routines, this program interfaces directly to the 8250/16550 UART chip on the PC.

The purpose of this program is bootstrapping, so it has several limitations. It is based loosely on the "Baby Kermit" BASIC program that can be found in the official Kermit manuals. It's hard coded to run at 9600 baud with 8-N-1 parameters on the COM1 port. Both sending and receiving is performed by hogging the CPU and busy-waiting. I recommend to use this program as a means to transfer the real full-feature MS-DOS Kermit.

Apart from testing the program in both the DOSBox and Bochs emulators, I have also tried it on two real machines. On a 8MHz 8088 XT-class machine, it gets some transmission errors, but those are corrected. On a 25MHz 80486SX it runs fine without any errors.

I have uploaded the code to GitHub in case of further improvements, by me or anyone else. But here is the first version, assembled with NASM as follows: nasm kermit.asm -fbin -o kermit.com

org 0x100
bits 16
cpu 8086

COM1_BASE equ 0x3f8
COM1_THR  equ COM1_BASE + 0 ; Transmitter Holding Buffer
COM1_RBR  equ COM1_BASE + 0 ; Receiver Buffer
COM1_IER  equ COM1_BASE + 1 ; Interrupt Enable Register
COM1_FCR  equ COM1_BASE + 2 ; FIFO Control Register
COM1_IIR  equ COM1_BASE + 2 ; Interrupt Identification Register
COM1_LCR  equ COM1_BASE + 3 ; Line Control Register
COM1_LSR  equ COM1_BASE + 5 ; Line Status Register
COM1_DLL  equ COM1_BASE + 0 ; Divisor Latch Low Byte
COM1_DLH  equ COM1_BASE + 1 ; Divisor Latch High Byte

RECV_BUFFER_SIZE equ 100 ; As per Kermit documentation.
SEND_BUFFER_SIZE equ 16 ; No packets sent from this program exceed this.
PACKET_DATA_SIZE equ 94 ; Receive buffer size - 6 fields/terminator.

section .text
start:
  ; Set Baudrate on COM1 to 9600, divisor = 12:
  mov dx, COM1_LCR
  in al, dx
  or al, 0b10000000 ; Set Divisor Latch Access Bit (DLAB)
  out dx, al

  mov dx, COM1_DLL
  mov al, 0xc
  out dx, al
  
  mov dx, COM1_DLH
  mov al, 0
  out dx, al

  mov dx, COM1_LCR
  in al, dx
  and al, 0b01111111 ; Reset Divisor Latch Access Bit (DLAB)
  out dx, al

  ; Disable and clear FIFO on COM1, to put it in 8250 compatibility mode:
  mov dx, COM1_FCR
  mov al, 0b00000110 ; Clear both FIFOs.
  out dx, al

  ; Set mode on COM1 to 8 data bits, no parity and 1 stop bit:
  mov dx, COM1_LCR
  mov al, 0b00000011 ; 8-N-1
  out dx, al

  ; Enable interrupt bit on COM1:
  mov dx, COM1_IER
  in al, dx
  or al, 0b00000001 ; Enable Received Data Available Interrupt
  out dx, al

  ; Initialize sequence number:
  mov byte [send_seq_no], 0

  ; Initialize retransmit message in send buffer:
  mov byte [send_buffer],     0x01 ; 'MARK' Start marker (Ctrl-A)
  mov byte [send_buffer + 1], 35   ; 'LEN' Packet length of 3 (+ 32)
  mov byte [send_buffer + 2], 32   ; 'SEQ' Sequence number 0 (+ 32)
  mov byte [send_buffer + 3], 'N'  ; 'TYPE' Packet type 'N' meaning NAK
  mov byte [send_buffer + 4], 0x33 ; 'CHECK' Checksum 0x13 (+ 32)
  mov byte [send_buffer + 5], 0x13 ; Terminator (Carriage Return)
  mov word [send_buffer_index], 6

  ; Get Send Initialization packet, exchange parameters...

  mov dx, message_waiting
  call print_string
  call get_valid_packet

  mov byte al, [packet_type]
  cmp al, 'S' ; 'S' = Send Initiation
  je _handle_s_packet

  ; Simplified version of error message: "<?> Packet in S State"
  mov byte [packet_data], al
  mov byte [packet_data + 1], 'S'
  mov byte [packet_type], 'E' ; 'E' = Error
  mov word [packet_data_len], 2
  call send_packet
  jmp _main_end

_handle_s_packet:
  ; Override local EOL marker from sender if available:
  mov byte al, [packet_data_len]
  cmp al, 4
  jb _acknowledge_s_packet
  mov byte bl, [packet_data + 4] ; 'EOL'
  sub bl, 32
  mov [eol_marker], bl

  ; Override local CTL marker from sender if available:
  cmp al, 5
  jb _acknowledge_s_packet
  mov byte bl, [packet_data + 5] ; 'QCTL'
  mov [ctl_marker], bl

_acknowledge_s_packet:
  mov byte [packet_type], 'Y' ; 'Y' = Acknowledgement (ACK)
  mov byte [packet_data],     72  ; 'MAXL'
  mov byte [packet_data + 1], 42  ; 'TIME'
  mov byte [packet_data + 2], 32  ; 'NPAD'
  mov byte [packet_data + 3], 64  ; 'PADC'
  mov byte [packet_data + 4], 45  ; 'EOL' = 0x0d (+ 32)
  mov byte [packet_data + 5], 35  ; 'QCTL' = '#'
  mov byte [packet_data + 6], 'N' ; 'QBIN' = 'N' = Will not do 8-bit quoting.
  mov byte [packet_data + 7], '1' ; 'CHKT' = '1' = Single character checksum.
  mov word [packet_data_len], 8
  call send_packet

_wait_for_file_header_packet:
  ; Get a File Header packet. If a B packet comes, we're all done:
  call get_valid_packet

  mov byte al, [packet_type]
  cmp al, 'B' ; 'B' = Break transmission
  je _handle_b_packet
  cmp al, 'F' ; 'F' = File Header
  je _handle_f_packet

  ; Simplified version of error message: "<?> Packet in F State"
  mov byte [packet_data], al
  mov byte [packet_data + 1], 'F'
  mov byte [packet_type], 'E' ; 'E' = Error
  mov word [packet_data_len], 2
  call send_packet
  jmp _main_end

_handle_b_packet:
  call send_acknowledgement_packet
  jmp _main_end

_handle_f_packet:
  mov dx, message_receiving
  call print_string

  ; Dollar terminate the received filename:
  mov word di, [packet_data_len]
  mov byte [packet_data + di], '$'
  mov dx, packet_data
  call print_string

  ; Zero terminate the received filename:
  mov byte [packet_data + di], 0

  ; Call DOS to create new file and handle.
  mov ah, 0x3c
  mov cx, 0 ; Standard attributes.
  ; DX already containing pointer to packet data.
  int 0x21
  jc _handle_f_packet_error
  mov [file_handle], ax

  call send_acknowledgement_packet

_wait_for_data_packet:
  ; Get Data packets. If a Z packet comes, the file is complete:
  call get_valid_packet

  mov byte al, [packet_type]
  cmp al, 'Z' ; 'Z' = End of file
  je _handle_z_packet
  cmp al, 'D' ; 'D' = Data Packet
  je _handle_d_packet

  ; Simplified version of error message: "<?> Packet in D State"
  mov byte [packet_data], al
  mov byte [packet_data + 1], 'D'
  mov byte [packet_type], 'E' ; 'E' = Error
  mov word [packet_data_len], 2
  call send_packet
  jmp _main_end

_handle_z_packet:
  ; Call DOS to close file handle.
  mov ah, 0x3e
  mov bx, [file_handle]
  int 0x21

  call send_acknowledgement_packet

  mov dx, message_ok
  call print_string

  jmp _wait_for_file_header_packet

_handle_d_packet:
  ; Call DOS to write to file.
  mov ah, 0x40
  mov word bx, [file_handle]
  mov word cx, [packet_data_len]
  mov dx, packet_data
  int 0x21
  jc _handle_d_packet_error

  call send_acknowledgement_packet

  jmp _wait_for_data_packet

_handle_f_packet_error:
  ; Send error code 'C', since new file could not be created.
  mov byte [packet_data], 'C'
  mov byte [packet_type], 'E' ; 'E' = Error
  mov word [packet_data_len], 1
  call send_packet
  jmp _main_end

_handle_d_packet_error:
  ; Send error code 'W', since new file could not be written to.
  mov byte [packet_data], 'W'
  mov byte [packet_type], 'E' ; 'E' = Error
  mov word [packet_data_len], 1
  call send_packet
  jmp _main_end

_main_end:
  mov dx, message_done
  call print_string

  ; Disable interrupt bit on COM1:
  mov dx, COM1_IER
  in al, dx
  and al, 0b11111110 ; Disable Received Data Available Interrupt
  out dx, al

  ; Exit to DOS.
  mov ah, 0x4c
  int 0x21

; PROCEDURE: get_valid_packet
;
; INPUT:
;   N/A
;
; OUTPUT:
;   ds:[packet_type]
;   ds:[packet_data]
;   ds:[packet_data_len]
;
get_valid_packet:
  push ax
  push bx
  push cx

  ; Try to get a valid packet with the desired sequence number.

  mov cx, 5 ; Retry maximum 5 times.
_get_valid_packet_loop:
  call recv_packet

  mov byte al, [recv_seq_no]
  mov byte bl, [send_seq_no]
  cmp al, bl
  jne _get_valid_packet_resend
  mov byte al, [packet_type]
  cmp al, 'Q' ; 'Q' = Block check error
  je _get_valid_packet_resend
  jmp _get_valid_packet_return ; Got a valid packet.

_get_valid_packet_resend:
  call com_port_send ; Contains a retransmit message in send buffer already.

  push dx
  mov dl, '%' ; Indicate retry.
  call print_character
  pop dx

  loop _get_valid_packet_loop ; Until CX = 0

  mov byte [packet_type], 'T' ; 'T' = Timeout

_get_valid_packet_return:
  pop cx
  pop bx
  pop ax
  ret

; PROCEDURE: send_acknowledgement_packet
;
; INPUT:
;   N/A
;
; OUTPUT:
;   N/A
;
send_acknowledgement_packet:
  mov byte [packet_type], 'Y' ; 'Y' = Acknowledgement (ACK)
  mov word [packet_data_len], 0
  call send_packet
  ret

; PROCEDURE: send_packet
;
; INPUT:
;   ds:[packet_type]
;   ds:[packet_data]
;   ds:[packet_data_len]
;   
; OUTPUT:
;   N/A
;
send_packet:
  push ax
  push bx
  push cx
  push di
  push si

  mov di, send_buffer
  mov byte [di], 0x01
  inc di

  mov word ax, [packet_data_len]
  add al, 35 ; 32 + 3 bytes for 'SEQ', 'TYPE' & 'CHECK'
  mov bl, al ; Checksum = LEN
  mov byte [di], al
  inc di

  mov byte al, [send_seq_no]
  add al, 32
  add bl, al ; Checksum += SEQ
  mov byte [di], al
  inc di

  mov byte al, [packet_type]
  add bl, al ; Checksum += TYPE
  mov byte [di], al
  inc di

  mov si, packet_data
  mov word cx, [packet_data_len]
  test cx, cx
  jz _send_packet_empty
_send_packet_loop:
  mov al, [si]
  mov [di], al
  add bl, al ; Checksum += DATA
  inc di
  inc si

  loop _send_packet_loop ; Until CX = 0
_send_packet_empty:

  ; Calculate checksum:
  mov cl, bl
  and cl, 192
  shr cl, 1 ; 8086 is limited to one shift at a time.
  shr cl, 1
  shr cl, 1
  shr cl, 1
  shr cl, 1
  shr cl, 1
  add cl, bl
  and cl, 63
  add cl, 32
  mov byte [di], cl
  inc di

  mov byte al, [eol_marker]
  mov byte [di], al

  mov word ax, [packet_data_len]
  add ax, 6 ; Add 'MARK', 'LEN', 'SEQ', 'TYPE' 'CHECK' and terminator.
  mov word [send_buffer_index], ax

  call com_port_send

  ; Increment packet sequence number:
  inc byte [send_seq_no]
  and byte [send_seq_no], 63 ; Always reduce to 6 bits.

  push dx
  mov dl, '.'; Indicate ACK sent.
  call print_character
  pop dx

  pop si
  pop di
  pop cx
  pop bx
  pop ax
  ret

; PROCEDURE: com_port_send
;
; INPUT:
;   ds:[send_buffer]
;   ds:[send_buffer_index]
;   
; OUTPUT:
;   N/A
;
com_port_send:
  push ax
  push cx
  push dx
  push si

  mov si, 0
  mov word cx, [send_buffer_index]
_com_port_send_byte:

  mov dx, COM1_THR
  mov byte al, [send_buffer + si]
  out dx, al

  mov dx, COM1_LSR
_com_port_send_wait:
  in al, dx
  and al, 0b00100000 ; Empty Transmit Holding Register
  test al, al
  jz _com_port_send_wait ; Busy wait...

  inc si
  loop _com_port_send_byte ; Until CX = 0

  pop si
  pop dx
  pop cx
  pop ax
  ret

; PROCEDURE: recv_packet
;
; INPUT:
;   N/A
;   
; OUTPUT:
;   ds:[packet_type]
;   ds:[packet_data]
;   ds:[packet_data_len]
;   ds:[recv_seq_no]
;
recv_packet:
  push ax
  push bx
  push cx
  push dx
  push di
  push si

  call com_port_recv

  ; Look for 'MARK' start marker 0x01 (Ctrl-A) in buffer:
  mov si, -1
_recv_packet_look_for_marker:
  inc si
  mov ax, [recv_buffer_index]
  cmp si, ax
  jge _recv_packet_fail ; Reached end of buffer.
  mov byte al, [recv_buffer + si]
  cmp al, 0x01 ; (Ctrl-A)
  jne _recv_packet_look_for_marker
  ; Start position now in SI register.

  ; Copy initial packet fields:
  ; * Using AL for data.
  ; * Using BL for checksum.
  ; * Using CX for packet length.
  inc si
  xor cx, cx
  mov byte cl, [recv_buffer + si] ; Packet 'LEN' field.
  mov bl, cl ; Checksum = LEN
  sub cx, 35 ; 32 + 3 bytes for 'SEQ', 'TYPE' & 'CHECK'
  inc si
  mov byte al, [recv_buffer + si] ; Packet 'SEQ' field.
  add bl, al ; Checksum += SEQ
  sub al, 32
  mov byte [recv_seq_no], al
  inc si
  mov byte al, [recv_buffer + si] ; Packet 'TYPE' field.
  add bl, al ; Checksum += TYPE
  mov byte [packet_type], al
  inc si
  ; Packet length now in CX register.
  ; Checksum now in BL register.
  ; Start of data position now in SI register.

  mov word [packet_data_len], cx
  test cx, cx
  jz _recv_packet_checksum ; Zero size packet, skip decoding/copying.

  ; Copy packet data:
  ; * Using AL for data.
  ; * Using BL for checksum.
  ; * Using CX for packet length.
  ; * Using DL for comparisons and temporary storage.
  ; * Using DH for decode flag.
  xor dh, dh
  mov di, packet_data
_recv_packet_copy:
  mov byte al, [recv_buffer + si] ; Packet 'DATA' field.
  add bl, al ; Checksum += DATA
  mov byte dl, [packet_type]
  cmp dl, 'S' ; 'S' = Send Initiation
  jne _recv_packet_decode ; Type 'S' packets shall not be decoded!
  mov [di], al ; Copy un-decoded.
  jmp _recv_packet_increment

_recv_packet_decode:
  cmp dh, 0
  jne _recv_packet_decode_flag_not_set_1
  mov byte dl, [ctl_marker]
  cmp dl, al
  jne _recv_packet_decode_flag_not_set_1
  mov dh, 1
  dec byte [packet_data_len] ; Decoding reduces resulting packet size.
  jmp _recv_packet_increment_source_only

_recv_packet_decode_flag_not_set_1:
  cmp dh, 1
  jne _recv_packet_decode_flag_not_set_2
  xor dh, dh

  mov dl, al
  and dl, 127
  cmp dl, 62
  jng _recv_packet_decode_flag_not_set_2
  cmp dl, 96
  jg _recv_packet_decode_flag_not_set_2
  xor al, 64

_recv_packet_decode_flag_not_set_2:
  mov [di], al
_recv_packet_increment:
  inc di
_recv_packet_increment_source_only:
  inc si
  loop _recv_packet_copy ; Until CX = 0

_recv_packet_checksum:
  ; Calculate and check checksum:
  mov dl, bl
  and dl, 192
  shr dl, 1 ; 8086 is limited to one shift at a time.
  shr dl, 1
  shr dl, 1
  shr dl, 1
  shr dl, 1
  shr dl, 1
  add dl, bl
  and dl, 63
  mov byte al, [recv_buffer + si] ; Packet 'CHECK' field.
  sub al, 32
  cmp al, dl
  jne _recv_packet_fail

  ; All OK!
  jmp _recv_packet_ok

_recv_packet_fail:
  mov byte [packet_type], 'Q' ; 'Q' = Block check error
_recv_packet_ok:
  pop si
  pop di
  pop dx
  pop cx
  pop bx
  pop ax
  ret

; PROCEDURE: com_port_recv
;
; INPUT:
;   N/A
;   
; OUTPUT:
;   ds:[recv_buffer]
;   ds:[recv_buffer_index]
;
com_port_recv:
  push ax
  push dx
  push di

  mov di, 0
_com_port_recv_byte:

  mov dx, COM1_IIR
_com_port_recv_wait:
  in al, dx
  and al, 0b00001110 ; Identification
  cmp al, 0b00000100 ; Enable Received Data Available Interrupt
  jne _com_port_recv_wait ; Busy wait...

  mov dx, COM1_RBR
  in al, dx

  cmp di, RECV_BUFFER_SIZE
  jb _com_port_recv_copy
  mov di, 0 ; Reset and wrap to prevent overflow.
_com_port_recv_copy:
  mov byte [recv_buffer + di], al
  inc di

  ; Keep reading until a terminator 0x0d (Carriage Return) arrives:
  cmp al, 0x0d
  jne _com_port_recv_byte

  mov word [recv_buffer_index], di

  pop di
  pop dx
  pop ax
  ret

; PROCEDURE: print_character
;
; INPUT:
;   dl
;   
; OUTPUT:
;   N/A
;
print_character:
  push ax
  push dx
  ; Call DOS to display character:
  mov ah, 0x2
  ; DL set by caller...
  int 0x21
  pop dx
  pop ax
  ret

; PROCEDURE: print_string
;
; INPUT:
;   dx
;   
; OUTPUT:
;   N/A
;
print_string:
  push ax
  ; Call DOS to display string:
  mov ah, 0x9
  ; DS is already same as CS, no need to change.
  ; DX set by caller...
  int 0x21
  pop ax
  ret

section .data:
recv_buffer_index:
  dw 0 ; 16-bit word due to SI/DI registers.
recv_buffer:
  times RECV_BUFFER_SIZE db 0

send_buffer_index:
  dw 0 ; 16-bit word due to SI/DI registers.
send_buffer:
  times SEND_BUFFER_SIZE db 0

send_seq_no:
  db 0
recv_seq_no:
  db 0

packet_type:
  db 0
packet_data_len:
  dw 0 ; 16-bit word due to SI/DI registers.
packet_data:
  times PACKET_DATA_SIZE db 0

ctl_marker:
  db '#'  ; Default
eol_marker:
  db 0x0d ; Default

file_handle:
  dw 0

message_waiting:
  db "Waiting...", 0x0d, 0x0a, "$"
message_receiving:
  db "Receiving: $"
message_ok:
  db "(OK)", 0x0d, 0x0a, "$"
message_done:
  db "(DONE)", 0x0d, 0x0a, "$"
          


For convenience, here is an example of commands to send a file with C-Kermit on Linux:

set modem type none
set line /dev/ttyUSB0
set carrier-watch off
set speed 9600
set flow none
set parity none
set stop-bits 1
send <filename>
          


Topic: Scripts and Code, by Kjetil @ 06/06-2020, Article Link

Reverse SSH Tunnel Listener

The Reverse SSH Tunnel Launcher script I posted a while ago has some limitations. The worst part is that the tunnel is only open for 5 minutes, leaving too little time to get any work done. This is kind of by design, to prevent having these connections open and "live" when not in use.

The solution to this limitation is another small script, this time just hacked together as a Bourne shell script. Take a look:

#!/bin/sh

while /bin/true; do
  if /bin/netstat -tln | fgrep 127.0.0.1:1337 > /dev/null; then
    ssh localhost -p 1337 screen -d -m ssh -v -R 1338:localhost:22 -N -p 22 192.168.0.1
    echo "New tunnel established!"
    exit
  fi
  sleep 10
done
          


This script will loop forever and wait for a socket to appear on the port (1337) opened by the original launcher. Once this happens, a new tunnel is created (on port 1338) in parallel which will persist forever through a screen session.

Topic: Scripts and Code, by Kjetil @ 02/02-2020, 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

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

Older articles