Monday, October 9, 2017

Socks Proxy Setup

RIP WPA2

I can never remember how to set up a Socks proxy to my Digital Ocean Droplet, so here is a simple little how-to guide.

Using a secure proxy server to somewhere else in the wild wild world, to get through a local insecurity suddenly got added urgency, since the WiFi WPA2 protocol is now officially broken.

Using a secure proxy in this way, will prevent local script kiddies from looking over your shoulder on a WiFi connection.

Note that the cheapest Digital Ocean Linux or BSD virtual server costs only $5 per month and that is all you need.  You don't even need to change or install anything on it, since it comes with sshd running by default.  So, just sign up for one, start using socks over ssh and relax.

On the laptop:
Add nameserver 8.8.8.8 to the top of /etc/resolv.conf

Start the socks proxy:
# killall ssh
# ssh -fND 2222 -p 22 root@w.x.y.z

Firefox:
Open Menu
Preferences, Advanced, Network, Settings:
Socks host: localhost, port 2222
Socks 5
Use Remote DNS

Skype:
Open Skype.
Enter your Skype credentials and Sign in.
In the Menu Bar click Tools and then Options…
Advanced, Connection.
Automatic proxy detection: SOCKS 5.
Host: localhost
Port: 2222.
Uncheck Enable proxy authentication.
Save.
OK.
Restart Skype and Sign in again.


This script sort of works:
#! /bin/bash
sed -i -e 's/nameserver/nameserver 8.8.8.8\nnameserver/' /etc/resolv.conf
killall ssh
ssh -fND 2222 -p 22 root@w.x.y.z


Mac

On a Macintosh, as soon as you enable the Socks proxy server in the System Settings, *everything* will go through it - Email, Safari, Firefox, Skype...  This is both convenient and annoying, since from then on, you always have to run the proxy.


La voila!

Herman

Friday, September 22, 2017

Scattering - RCS calculation with NEC2

Would you like to know the scattering Radar Cross Section (RCS) of your RC or UAV quadcopter toy?  If you are a Real, Card Carrying Geek, then of course you would...

Calculation of the RCS of an aircraft is difficult, due to the lack of good tools.  Even the commercial tools struggle with this problem, so before you waste money on a super expensive commercial tool, do try the Free ones first.

Here is some background information on the Numerical Electromagnetic Code (NEC), which is a method of moments type of successive approximation program needed to do the modelling:
http://www.aeronetworks.ca/2017/07/olde-skool-antenna-design-with-nec2-on.html

To calculate scattering of a plane wave, you need to make an electrical model of the aircraft.  Part3 of the NEC2 manual contains an example for calculation of the RCS of a stick model of an aircraft.  This looks absurdly simple, but there is method in the madness, since in many cases a stick model is good enough.  An aircraft with a cylindrical, conductive body (alluminium or carbon fibre composite) can be well enough approximated by simple thick wires.

However, if you want a better estimate, then you need to take a CAD model of the aircraft and convert that into a 1D mesh of short wire segments.  This can be done with the gmsh program, and then you need to convert the result into a format that your method of moments antenna modelling tool  can read.

Sticks and Stones

Here is a NEC2 stick model of a small aircraft for RCS calculation with xnec2c:

CM An approximation of a small aircraft Radar Cross Section
CM
CM AV dimensions:
CM The AV fuselage is about 3086 mm long and 680 mm high at the centre.
CM First approximation is a wire of 3086 mm, 340 mm radius.
CM Second approximation is a tapered wire 3086 long x 340 mm radius at hub,
CM tapering to 50 mm radius at the ends.
CM
CM The Gain is the scattering cross section in square wavelengths (sigma/lambda^2.
CM
CM Long range surveillance radar:
CM Fequency = 300 MHz:
CM Wave length = 1 m
CM 1/10th wave length = 100 mm
CM
CM Patch/Wire segment sizes:
CM Length: 3086 mm / 100 mm = 31 sections
CM Height: 680 mm / 100 mm = 7 sections
CM Tail: 2048 mm /100 mm = 21 sections
CM Nose: 1038 mm / 100 mm = 10 sections
CM Radius at hub = 340 mm
CM Taper radius at nose/tail: 50 mm
CM
CM Single wire:
CM GW 1,31,0,0,0,3.086,0,0,.340
CM
CM Two tapered wire segments:
CM GW 1,21,0,0,0,2.048,0,0,0
CM GC 0,0,1,.050,.340
CM GW 2,10,2.048,0,0,3.086,0,0,0
CM GC 0,0,1,.340,.050
CM
CM Excite:
CM EX 1,1,1,0,0
CM EX 1,1,1,0,90,30,-90
CM
CM Radiation Pattern examples for xnec2c:
CM RP 0,72,72,0,0,0,5,5,0,0,0
CM RP 0,90,90,0,0,0,4,4,0,0,0
CM
CE
GW 1,21,0,0,0,2.048,0,0,0
GC 0,0,1,.050,.340
GW 2,10,2.048,0,0,3.086,0,0,0
GC 0,0,1,.340,.050
GE
FR 0,1,0,0,300
EX 1,1,1,0,0
RP 0,90,90,0,0,0,4,4,0,0,0
EN


This model uses fat wire segments for the body, tapered towards the nose and tail, to make it a little more realistic.  The tail planes, wings and landing gear can be handled similarly, but there is diminishing returns - when you add the smaller features, the RCS doesn't change by much, since they are so much smaller than the main fuselage and wings.

CAD Solid Model to 1D Mesh

A CAD model STP file can be converted into a surface mesh with gmsh, but the default settings result in an enormous number (millions) of triangles and lines.  To be able to process the data on a general purpose computer, you need to reduce that to a few thousand elements.

Otherwise, you need to head over to a place like Amazon or Digital Ocean and rent a large virtual machine with many cores and oodles of RAM for a month, to do your calculation.

The gmsh program can read most CAD file types.  The output should be in a form that is easy to parse.  The following line will create an INRIA mesh file:

$ gmsh model.stp -1 clmin 20 -clmax 100 -format auto -o model-1d.mesh

The maximum edge length is set to 100 mm, which is one tenth of a typical long range 300 MHz radar with 1 m wave length.  The result for me was a file with about 30,000 edges.

Mesh to NEC2

Converting the mesh to something that NEC2 can handle required some scripting.  The following Bash script which I creatively named m2n, loops through the mesh file one line at a time to read each wire segment and then search the vertex file from the top down to find the start and end points x,y,z co-ordinates to generate a GW card for each wire.

Note that there may also be a z-axis problem - more on that down below.

#! /bin/bash
echo Convert a 1d INRIA mesh file to a NEC2 wire segment file
#
# Configuration:
# You have to set the file names down below
#
# Mesh generate example:
# ./Applications/gmsh model.stp -1 clmin 20 -clmax 100 -format auto -o model.mesh
#
# INRIA mesh format:
# MeshVersionFormatted 2
# Dimension
# 3
# Vertices
# 4
#     -303.41676307005          -79.958172002481           239.91717070429      1
#     -296.94332277259          -79.958171898826           240.50417216528      2
#     -251.72110263339          -87.385817660601           208.53092734841      3
#     -251.90752255856          -89.319412217105            210.5867628726      4
# Edges
# 4
# 1 2 1
# 2 3 1
# 3 4 2
# 4 1 2
#
# Vertex Format: x, y, z, vertex#
# Edge format: v1, v2, line#
#
# Therefore each edge line segment is defined by a record pointing to two x,y,z vertices
# The STP file is assumed to be in mm and is scaled to m with a GS card
#
# NEC Text File Format:
# The original Fortran NEC used punch cards with strict columnar data
# It is now done with lines in a text file
# A text line can use either spaces or commas as field delimeters
# Empty fields are padded with a zero
# The end of the line need not be padded with zeros
# Floating point numbers need to be in exponential format with decimal points
# Bash doesn't do exponential arithmetic (use bc), but the printf function can output it
# The locale settings in the printf statements ensure use of decimal points
#
#
# File Names:
#export mesh="short.mesh"
export vert="model.vert"
export nec="model.nec"
export mesh="model.mesh"
# Mesh file parse state:
# header, edges, edge, vertex1, vertex2, end
export state="header"
export edgestart="0"
export edgeend="0"
export edgenum="0"
export errmax=50000
export vertexnum=0
# NEC file data:
export wire="1"
export segments="1"
# Copy the vertices
$( cp "$mesh" "$vert" )
# Create the header of the NEC file
echo "CM NEC2 Card Stack Produced by m2n">"$nec"
echo "CE">>"$nec"
# Read lines from the mesh file
end_of_mesh_file=0
while [[ $end_of_mesh_file == 0 ]]
do
  read -r meshline
  # the last exit status is the
  # flag of the end of file
  end_of_mesh_file=$?
  #echo "meshline: $meshline"
  if [ "$meshline" == "End" ]
  then
    state="end"
    echo "state: $state"
    break
  fi
  if [ "$state" == "header" ]
  then
    #echo "state: $state"
    if [ "$meshline" == "Edges" ]
    then
      state="edges"
    fi
  elif [ "$state" == "edges" ]
  then
    #echo "state: $state"
    total="$meshline"
    state="edge"
  elif [ "$state" == "edge" ]
  then
    #echo "state: $state"
    edgeverts=($(echo $meshline | tr ' ' "\n"))
    # echo "edgestart: ${edgeverts[0]}"
    edgestart="${edgeverts[0]}"
    # echo "edgeend: ${edgeverts[1]}"
    edgeend="${edgeverts[1]}"
    # echo "edgenum: ${edgeverts[2]}"
    edgenum="${edgeverts[2]}"
    state="vertex1"
  fi
  if [ "$state" == "vertex1" ]
  then
    #echo "state: $state"
    # Read lines from the vertices file
    vertexnum=-5
    end_of_vertices_file=0
    while [[ $end_of_vertices_file == 0 ]]
    do
      read -r vertexline
      # the last exit status is the
      # flag of the end of file
      end_of_vertices_file=$?
      if [ "$vertexline" == "Edges" ]
      then
         echo "Error1: Vertex not found"
         exit 1
      fi
      if [ "$vertexnum" -ge "$errmax" ]
      then
         echo "Error11: Vertex not found"
         exit 1
      fi
      # Count the records manually
      (( vertexnum++ ))
      if [ "$vertexnum" == "$edgestart" ]
      then
        #echo "vertexline: $vertexline"
        vert1=($(echo $vertexline | tr ' ' "\n"))
        # echo "vertx1: ${vert1[0]}"
        vertx1="${vert1[0]}"
        # echo "verty1: ${vert1[1]}"
        verty1="${vert1[1]}"
         # echo "vertz1: ${vert1[2]}"
        vertz1="${vert1[2]}"
        (( wire++ ))
        break
      fi
    done < "$vert"
    state="vertex2"
    fi
    if [ "$state" == "vertex2" ]
    then
      #echo "state: $state"
      # Read lines from the vertices file
      vertexnum=-5
      end_of_vertices_file=0
      while [[ $end_of_vertices_file == 0 ]]
      do
        read -r vertexline
        # the last exit status is the
        # flag of the end of file
        end_of_vertices_file=$?
        if [ "$vertexline" == "Edges" ]
        then
           echo "Error2: Vertex not found"
           exit 1
        fi
        if [ "$vertexnum" -ge "$errmax" ]
        then
           echo "Error21: Vertex not found"
           exit 1
        fi
        # count the records manually
        (( vertexnum++ ))
        if [ "$vertexnum" == "$edgeend" ]
        then
          #echo "vertexline: $vertexline"
          vert2=($(echo $vertexline | tr ' ' "\n"))
          # echo "vertx2: ${vert2[0]}"
          vertx2="${vert2[0]}"
          # echo "verty2: ${vert2[1]}"
          verty2="${vert2[1]}"
          # echo "vertz2: ${vert2[2]}"
          vertz2="${vert2[2]}"
          LC_NUMERIC="en_US.UTF-8" printf "GW $wire $segments %.8E %.8E %.8E %.8E %.8E %.8E 1\n" \
            $vertx1 $verty1 $vertz1 $vertx2 $verty2 $vertz2
          LC_NUMERIC="en_US.UTF-8" printf "GW $wire $segments %.8E %.8E %.8E %.8E %.8E %.8E 1\n" \
            $vertx1 $verty1 $vertz1 $vertx2 $verty2 $vertz2 >>"$nec"
          break
        fi
      done < "$vert"
      state="edge"
    fi
  done < "$mesh"
# Create footer of NEC file
# Scale everything from mm to m
echo "GS 0 0 .001">>"$nec"
echo "GE">>"$nec"
echo "FR 0 1 0 0 300">>"$nec"
echo "EX 1 1 1 0 0">>"$nec"
echo "RP 0 90 90 0 0 0 4 4 0 0 0">>"$nec"
echo "EN">>"$nec"
exit 0


This script is sloooow...

Meshing a CAD file of a large model with gmsh may take 15 minutes, but converting the result to a NEC card file with this m2n script can take a whole day.  You have to test it with a much shortened file and you should make some errors in the file to see what the script does with them - having it exit due to an error after 24 hours of running on your personal two core 1 GHz super computer, would be disappointing.

Just commenting out most echo debug statements speeded the script up by about ten times, but the important thing is correctness, not speed, so I left one printf to the screen to see what it is doing.  However if someone would rewrite the program in C, please send me a copy!

Computing Troubles

All the meshing programs that I tried, have multiple bugs.  The INRIA mesh file created by gmsh has sequence number problems, but other meshers caused little bits and pieces of aircraft hanging in space around the main model, so gmsh is the least of all evils.

The vertex sequence number overflows and goes from 12076 back to 1 and then get stuck on 3 for a while and so on.   I therefore had to modify the above script to count the vertex record numbers by itself, since it cannot trust the values in the mesh file.  In the script I simply started the line counter at minus 5, to account for the 5 lines of overhead.

The edge record numbers are also doubled up: 1, 1, 2, 2, 3, 3..., but those are not used for anything here.

So with all meshing programs, you need to look at the data files with a text editor and see whether they make sense.  Avoid the binary file formats, since then you will never be able to figure out what went wrong.  Also note that if the resulting pattern plot looks like a hedgehog on a LSD trip, then your wire segments may simply be too long.  The wire segments should be about 1/10 the length of the incident wave.

Another problem is the speed of the calculations.  Much time is wasted accessing the disk drive and that can be alleviated with the use of a small RAM disk.  A RAM disk would be about 10 times faster than a SSD, which is also a good ten times faster than spinning rust.  On Linux systems, the tmpfs used for the /tmp directory is a RAM disk, so it is as simple as copying your files over there.

On a Mac, you need to manually make a RAM disk.  Here is a handy script that will make one and mount it inside your home directory.  Just remember that when you reboot, it goes to the great bit bucket in the sky:

#!/bin/bash 
echo Create a small RAM Disk in the user home directory
ramfs_size_mb=20 
mount_point=~/ramdisk 
ramfs_size_sectors=$((${ramfs_size_mb}*1024*1024/512)) 
ramdisk_dev=`hdid -nomount ram://${ramfs_size_sectors}` 
newfs_hfs -v 'Volatile' ${ramdisk_dev} 
mkdir -p ${mount_point} 
mount -o noatime -t hfs ${ramdisk_dev} ${mount_point} 


To process 30,000 edges, would require a very good super computer.  The complexity of the calculation increases exponentially with increased wire segment count.  On a small computer, you should be able to calculate scattering of a model with 3000 to 5000 elements.  It also looks like xnec2c currently has a maximum limit of 10,000 elements.  So if you only have a small computer, then you need to break your aircraft model up into multiple segments, to simplify your mesh models, but you will have to choose the segments wisely to get useful results.

Depending on the CAD model origin, one may also need to do some shifting on the z-axis, to ensure that the whole model is above the ground plane.  It is best to do this with a separate program to scan the whole file, find the minimum z and then shift everything up in a second pass.  This is hard to do since Bash doesn't handle floating point numbers, so one has to pipe the numbers into the calculator bc.  Here is my wonderfully named NEC Shift Up (nsu) script for this purpose:

#! /bin/bash
echo This script takes a NEC model file and shift it up in the z-axis,
echo to ensure that the whole model is 1 mm above zero.
#
# NEC Text File Format:
# The original Fortran NEC used punch cards with strict columnar data
# It is now done with lines in a text file
# A text line can use either spaces or commas as field delimeters
# Empty fields are padded with a zero
# The end of the line need not be padded with zeros
# Floating point numbers need to be in exponential format with decimal points
# Bash doesn't do exponential arithmetic (use bc), but the printf function can output it
# The locale settings in the printf statements ensure use of decimal points
#
# File Names:
export nec="model.nec"
export shift="shift.nec"
#
# Variables
export zmin="0"
export necline=""
export shiftline=""
#
# States: header, gw, head, shift, end
export state="header"
#
# Read lines from the NEC file to find the minimum z
end_of_nec_file=0
while [[ $end_of_nec_file == 0 ]]
do
  read -r necline
  # The last exit status is the flag of the end of file
  end_of_nec_file=$?
  #echo "necline: $necline"
  if [ "$necline" == "End" ]
  then
    echo "Error1: Premature EOF"
    exit 1
  fi
  if [ "$state" == "header" ]
  then
    echo "state: $state"
    if [ "$necline" == "CE" ]
    then
      state="gw"
      echo "state: $state"
    fi
  elif [ "$state" == "gw" ]
  then
    #echo "state: $state"
    if [ "$necline" == "GE" ]
    then
      state="head"
      break
    fi
    # Parse the GW x,y,z values into an array of 10 variables
    gw=($(echo $necline | tr ' ' "\n"))
    val="${gw[5]}"
    z=$( printf "%f" $val )
    #echo "zmin: $zmin, z: $z"
    if (( $(echo "$zmin > $z" |bc -l) ))
    then
      zmin="$z"
      echo "zmin: $zmin"
    fi
    val="${gw[8]}"
    z=$( printf "%.8f" $val )
    #echo "zmin: $zmin, z: $z"
    if (( $(echo "$zmin > $z" |bc -l) ))
    then
      zmin="$z"
      echo "zmin: $zmin"
    fi
  fi
done < "$nec"
echo "state: $state"
echo "zmin: $zmin"
# Read lines from the NEC file, write to a new file and scale up by minimum z
$( rm -f "shift" )
$( touch "shift" )
end_of_nec_file=0
while [[ $end_of_nec_file == 0 ]]
do
  read -r necline
  # The last exit status is the flag of the end of file
  end_of_nec_file=$?
  #echo "necline: $necline"
  if [ "$necline" == "End" ]
  then
    echo "Error1: Premature EOF"
    exit 1
  fi
  if [ "$state" == "head" ]
  then
    echo "state: $state"
    if [ "$necline" == "CE" ]
    then
      state="shift"
      echo "state: $state"
    fi
    echo "$necline">>$shift
  elif [ "$state" == "shift" ]
  then
    #echo "state: $state"
    # Parse the GW x,y,z values into an array of 10 variables
    gw=($(echo $necline | tr ' ' "\n"))
    gs="${gw[0]}"
    scale="${gw[3]}"
    if [ "$gs" == "GS" ]
    then
      echo "GS 0 0 $scale\n"
      echo "GS 0 0 $scale" >>$shift
      state="end"
      echo "state: $state"
    else
      wire="${gw[1]}"
      segments="${gw[2]}"
      x1="${gw[3]}"
      y1="${gw[4]}"
      val="${gw[5]}"
      z=$( printf "%f" $val )
      z1=$(echo "$z - $zmin + 1" |bc -l)
      x2="${gw[6]}"
      y2="${gw[7]}"
      val="${gw[8]}"
      z=$( printf "%.8f" $val )
      z2=$(echo "$z - $zmin + 1" |bc -l)
      printf "GW $wire $segments $x1 $y1 %.8E $x2 $y2 %.8E 1\n" $z1 $z2
      printf "GW $wire $segments $x1 $y1 %.8E $x2 $y2 %.8E 1\n" $z1 $z2 >>$shift
    fi
  elif [ "$state" == "end" ]
  then
    #echo "state: $state"
    echo "$necline"
    echo "$necline">>$shift
    if [ "$necline" == "EN" ]
    then
      state="done"
      break
    fi
  fi
done < "$nec"
echo "state: $state"
exit 0

The next problem is finding a computer with enough memory that can process all this without crashing. A Macbook Pro would certainly be a better candidate than a netbook.

Why do I do this with Bash?  I must be a masochist, but all workstations have Bash (even Windoze now has Bash) and a script allows one to debug text processing more rapidly than with C.

Thanks

Thank you to Neoklis Kyriazis http://www.qsl.net/5b4az/ for translating NEC2 to C.



Have fun!

Herman


Thursday, August 31, 2017

HF Mini Radio - BitX40

I am an ex Army Signals officer and also built military HF radio equipment for a period of about ten years - man pack, ground and airborne, so when I saw the new BitX40 radio kit, I just had to get a couple to play with.

These kits are made in India, are good quality surface mount, built up tested and aligned.  For the princely sum of $59, one can get two or three and have fun:
http://www.hfsigs.com/

Bread and Circuses

Here is my breadboard setup.  Yup, it is a real olde skool bread cutting board.  Wood is a good insulator and some blue ticky-tacky keeps things down:

BitX40 7 MHz SSB HF Radio

The BitX40 is an analogue radio, with a digital synthesizer tuner - so it is a throwback to some time before the dinosaurs, circa 1985 - nice and simple.

The default setup is for the 40 meter band, but one can tune it for any HF band, by using switches and coils.  They are so cheap, one could get multiple radios and configure each for a different band of interest.  However, given the current sun spot cycle, the 40 meter band is probably the best one.

Instead of an antenna, I hooked up a 50 Ohm wire wound resistor.  Being a coil, it is actually not a good dummy load, but I always use one for radios and it works well enough. Another advantage of using resistors is that they leak enough that one can communicate over the air in a lab between two radios.

Once I'm sure the radio works properly, I'll build it into an instrument case, but knowing me, it will likely stay exactly like that for the next 6 months.

Instrument Case

I dug up a little instrument case that I bought years ago, thinking that it will come in handy some day and it was a perfect fit.  I just need to get a few more momentary switches and sockets from Electronic Surplus or similar junk shop. 

To keep the wiring up and away from the mother board, I'll add a little cable rack in the middle.  It is important to make the box easy to open and close, since the BitX is designed to be experimented with. 

Insides

The packaged radio now is about the same size as the Grinel TR178 HF Mini that I worked on many moons ago.

 Completed BitX40 HF Mini Transceiver

The toggle switches are on-off-momentary type.  These are for PTT, Up, Down and Enter.  The last three can be added to the Arduino software to navigate a menu of new features.  Maybe I'll make it frequency hop one day - about 5 Hz hop rate would be fun and with a simple resynch on each PTT, it won't need temperature controlled, super stable clocks.

I cut the rectangle for the display with a Nibbling Tool.  The trick for a pro finish is to slit open some 3 mm black heat shrink tubing and put it around the display cut-out edge at final assembly.  All other holes are round and most were made with a Stepped Reamer.  Two tools that are indispensable for a hobbyist!

Tune-Up

A problem with a HF radio is of course the long antennas.  The 40 meter band is called that for a reason and a quarter wave antenna needs to be 10 meters long.  I am a firm believer in antenna tuners though.  With a decent tuner, one can make any piece of metal resonate and these tuners need not be very complex - Grinel made a HF frequency hopping antenna that made a whole helicopter resonate.

In general, a series coil makes an antenna electrically longer and a series capacitor makes it shorter.  Reactive components do not absorb energy - they don't get hot - and once a circuit is tuned and resonating merrily, it will radiate on the attached antenna wire.

Therefore, my next project will have to be a tuner, otherwise this little radio will never be usable.  A L-match circuit can make a too short random wire/gutter/downspout/flagpole antenna resonate merrily:

Maximum Smoke L-Tuner

The above is as simple as it gets.  Instead of struggling to tune with complicated forward and reverse SWR power meter circuits on the radio side, simply tune for maximum smoke on the antenna side. Once in tune, real power is what you get, the imaginary components are gone and then a simple indicator works!

A 2 inch coil of 60 turns will have an inductance of about 120 uH and together with a 170 pF capacitor, it will resonate at about 1 MHz, so this tuner will work over the whole HF band.

For the coils, you can use a 2 inch air core coil former (also known as a chewing gum bottle), or a piece of ferrite - sticky tape and super glue (or the original contents of the bottle...) will also be handy.  Once you have a few turns glued down, it becomes easier.  Give super glue plenty time to dry or you will have wire wound finger tips instead of a coil.  It is rather easier winding around ferrite and you'll use much less magnet wire.

 Air Core Coil and Ferrite Toroid LED Transformer

If you like binary, then make the main coil with taps at 4, 8, 16, 32, 64 turns.  If you like decimal then make it 10, 20, 30, 40, 50, 60, whatever floats your boat.  For the LED, make some taps as well, so you can tweak the maximum brightness since it is dependent on the LED. If you manage to pop the LED, then your tuner really works.

The variable capacitor is available from various places that sell crystal radio kits (Mike's Electronic Parts) and then you'll get a ferrite bar also.

A ferrite bar makes a much more compact coil

Toroids look fancy, but are painful to wind.  Winding a coil or transformer around a bar is much easier and works just as well - if you look inside an old radio, you won't see any toroids.  Sure, bars leak more RFI than toroids, but radiating is the whole purpose of an antenna, so in this case it really doesn't matter.  Don't sweat about the design of a low power tuner - if it works, it works.

For a high power tuner, you need to pay attention to the high voltages and currents and use thicker, insulated wire and bigger ferrites, so then you need to do a few calculations to make sure it won't melt or arc.

 HF Low Power Antenna Tuner

To tune up, first set the cap to the middle, then adjust the coil for maximum noise on receive.  Finally, press PTT, whistle into the mic (or use CW) and sweep the capacitor back and forth to find the range where the LED lights up and set it to the middle. That's all there is to it.

Note that the tuner needs to be at the base of the antenna, which is fine if your antenna is right next to, or on the roof of your radio shack.  If your antenna is some distance away in the yard at the end of a long coax, then you need a remote controlled tuner.  For that, you would need a more complex design with discrete coils, capacitors, a handful of relays and a little embedded processor.

The important point is that a tuner is always specific to a radio and an antenna.  You will end up building one for each antenna project, so keep it simple.  There is no point in making a complicated 'general purpose' tuner, since that is not how a tuner is used.


. -.-. .-. .- ... . --.. / .-.. .----. .. -. ..-. .- -- .

Nastravje,

Herman

Wednesday, August 23, 2017

Digital Slow Scan TV with gstreamer

I had a look at radio amateur Slow Scan TV and noticed that it is analogue, so I wondered whether I can create a digital version using gstreamer.

Here is an example script that will play one video frame every ten seconds.  This could very well form the basis for a digital SSTV system.

The first part of the script are commented tests that show how I worked my way up to the super slow method that uses the videorate plugin to drop most of the frames.

Note that due to the long time between SSTV frames, everything will always be different, so motion jpeg will likely work better than h.264 compression.


#! /bin/bash
echo Slow Scan TV example with a laptop PC camera and gstreamer

# Install all the plugins including v4l2src:
# dnf install gst*plugin*

# Play the laptop PC camera the simplest possible way using the system defaults:
# gst-launch-0.10 v4l2src device=/dev/video0 ! autovideosink

# Play the camera and scale it smaller at 30 frames per second
# gst-launch-0.10 v4l2src device=/dev/video0 ! video/x-raw-yuv,framerate=30/1,width=640,height=480 ! autovideosink

# Play the camera and scale it smaller at 1 frame per 10 seconds:
gst-launch-0.10 v4l2src device=/dev/video0 ! video/x-raw-yuv,framerate=30/1,width=640,height=480 ! videorate ! video/x-raw-yuv,framerate=1/10,width=640,height=480 ! autovideosink

# Eventually, one can use a motion jpeg encoder and replace autovideosink with udpsink to stream it:
# ! udpsink host=127.0.0.1 port=5000 sync=false



What it means is that whereas amateur radio SSTV sends low definition 320p video at 1 frame per 2 minutes using 1960s analogue techniques, one could possibly send 720p HD video at 1 frame per 2 minutes using present day digital techniques, over the same shortwave SSB radio.  It is worth exploring further.

I think all one needs to add to the above is a simple phase continuous dual tone FSK modem with some FEC.  Maybe I'll resurrect some ancient code I did for a modem some time late last century - if the disk drive lying in my junk box is still readable!




Bunnel's Horse With No Name sort of applies to where I am living now:
You see I've been through the desert on a horse with no name
It felt good to be out of the rain
...

La, la ... voila!


Herman

Friday, July 28, 2017

Olde Skool Antenna Design with NEC2 on OpenBSD

The Numerical Electromagnetics Code (NEC) is a powerful and efficient program for the analysis of the electromagnetic properties of antennas and other objects. It is a Method of Moments type of successive approximation program and dates back to the time of the dinosaurs.  NEC was developed on a CDC 7700 in the mid 1970s to early 80s at Lawrence Livermore by Burke and Poggio for the US Navy and it was paid for by the friendly US tax payers - free for use by anyone now.


Dipole Antenna Example

CDC - Control Data Corporation, became Computing Devices Canada, which became General Dynamics Canada - I worked there through all the name changes - but you don't need to go hunt in a museum for a CDC 7700 to run NEC - an Intel PC will do.   The NEC documentation amusingly still refers to stacks of punch cards, but these have been replaced with simple text files.  I learned programming with punch cards on a Sperry-Univac, so the batch processing way that NEC works is not strange to me, but it does bring back some scary memories of the good old, bad old days of iron age, hollow state computing...

NEC was considered a large program, requiring a powerful mainframe to execute.  However, what used to require a big room full of computing equipment, can now be done on a laptop computer.  Just to prove the point, I installed NEC on my Lenovo S10e netbook running OpenBSD.

The original FORTRAN code is still available, but it has been rewritten a few times into C and C++, to improve the efficiency and ability to handle very large numbers of wire elements. The new versions can handle tens of thousands of elements and can be used to model a whole aircraft for example, but then you would need something with a wee bit more RAM than my netbook.

Here is another similar method of moments approach for the calculation of scattering (RCS) of very large objects (Ships).  However, this program is not maintained at the moment and needs to be installed on a specific version of Ubuntu Linux: http://www.aeronetworks.ca/2015/04/rcs-calculations-puma-em-on-ubuntu-linux.html

As usual with high tech things, there is absolutely no correlation between price and quality.  You can spend $100,000 on an antenna design program from ANSYS or others, or you can use NEC2 or Puma EM - for Free! - or buy a LLNL NEC4 license for $300 to $1500 https://ipo.llnl.gov/technologies/nec.

The difference is that the $100,000 package comes with training and support, whereas with NEC, you have to figure it out yourself - but figuring it out yourself over a few days, is rather less than $100,000 me thinks and even with the commercial support and training session, you still need to sit for a few days to figure it out anyway.  If you have big money burning your pocket, then spending it on RF test equipment may be a better idea.

Getting Started With NEC2 Antenna Modelling

The place to start is here: http://www.nec2.org/

Download the manuals, and read them:

The first manual describes how NEC works and the third manual describes how to use NEC to model an antenna.  There are many examples, from dipoles to Yagis and helixes - it is all there.  To get started, you could find a suitable example and tweak it to suit your purpose.

Download the NEC example files from the American Radio Relay League:

Download an antenna handbook or two and clue up on antennas, so that you can tell when your simulations are going wrong:

If you are broke, get this one - the author passed away before he could complete it and his legacy is a free antenna book: 

NEC on OpenBSD

If you are a very recent convert and don't have an OpenBSD laptop computer yet: http://www.aeronetworks.ca/2017/02/openbsd-on-netbook.html

Assuming that you have a machine which is minimally working, first set up the OpenBSD ports system.  Look for a file named ports.tar.gz on the mirrors.

$ cd /tmp
$ ftp https://ftp.openbsd.org/pub/OpenBSD/$(uname -r)/{ports.tar.gz,SHA256.sig}
$ signify -Cp /etc/signify/openbsd-$(uname -r | cut -c 1,3)-base.pub -x SHA256.sig ports.tar.gz

Untar this file in the /usr directory, to create /usr/ports and all the directories under it.

# su -
password
# cd /usr
# tar xzf /tmp/ports.tar.gz

Look for nec2 based antenna design software:
# cd /usr/ports
# make search key="nec2"
  Port:   xnecview-1.36p0
  Port:   necpp-1.2.3p3

Build necpp:
# cd cad/necpp
# make install
... looong wait ...
# make clean

Build xnecview:
# cd cad/xnecview/
# make install
... looong wait ...
# make clean

OK, so which programs do we have now?
$ ls /usr/local/bin/*nec*
  nec2++              nec2diff            xnecview

Apparently we have nec2++ for antenna design and xnecview to plot the results.  A text editor and some RTFMing is all that is needed to create the input files.  Mousepad or even vi will do.

Helical Antenna Model

Let's look at a helical antenna model.  There is one in the other.zip file from ARRL.  The NEC manual has two parts, part 1 describes the program and part 3 describes how to use it, with exhaustive examples.  A volunteer is needed to write part 2!   A helical antenna card stack is described on page 20 of part 3 of the manual.

Helix - CocoaNEC

A helical antenna definition is extremely simple, since it is only one wire.  Nevertheless, you need to refer to page 20 of the third manual to know what exactly the Geometry Helix (GH) line means:

$ cat HELIX.NEC
CE  HELIX TEST
GH 1,60, .05,.5,.1,.1,.1,.1,.00001
GE
EN

RTFM:
$ man nec2++
$ man xnecview

Let's put the card stack in the hopper and run it to see what happens.  Watch out for the continuous paper spewing out of the high speed line printer...

$ nec2++ -iHELIX.NEC -ohelix.out

Let's view it:
$ xnecview HELIX.NEC helix.out

To make the original example useful, one has to add definitions for the EX signal source and RP antenna pattern cards.

With EX 0 1 1 0 1 and RP 0 1 360 360 1000 0 0 1 1,  I eventually got something to plot, but it didn't look pretty and an attempt to calculate an admittance matrix caused the netbook to run out of RAM and the program was terminated.

Eventually, I got the NEC syntax sorted and the plots made sense once I used a very large number of elements (500 or more).  As the elements are straight sections, if you specify too few, then the simulation of the spiral becomes complete nonsense.

CM Helix, 900 MHz, 15 loops, 1.15 meter
CM Herman Oosthuysen, July 2017
CM Wave length = 2.998x10^8 / 900MHz = 0.333 m
CM Use Kraus formula:
CM Radius = 116.2 / 2 = 58.1 mm
CM Loops = 15
CM Spacing = .23 = 76.6 mm
CM Length = 1150 mm
CM GH 1,200,.0766,1.150,.0581,.0581,.0581,.0581,.0066
CM EX element 1 has voltage source of 1V
CM EX 0,1,1,0,1,0,0,0,0,0,0
CM FR Freq response 800 to 1000 MHz, 5 points
CM FR 0,5,0,0,800,50
CM RP 72 points x 5 = 360 degrees
CM RP XNDA = 0 (max pwr gain) works best
CM RP 0,1,72,72,0,0,0,5,5,0,0
CM The simulation needs a very large number of elements, 500 or more
CE
GH 1,500,.0766,1.150,.0581,.0581,.0581,.0581,.0066
GE
EX 0,1,1,0,1,0,0,0,0,0,0
FR 0,5,0,0,800,50,,,,,
RP 0,1,72,72,0,0,0,5,5,0,0
EN


Helix 900 MHz

The little netbook can calculate up to about 5 frequencies in a sweep.  For more accurate rendering, a better computer is required!

Equations from Kraus:
G= 10.8 + 10*log10(  (C/lambda)2*N*(S/lambda) )    (Note1)
Z= 150/sqrt(C/lambda) Ohm
D= lambda /PI
S= C/4
HPBW= 52/( (C/lambda)*sqrt(N*(S/lambda)) ),  Half power beamwidth.
BWFN= 115/( (C/lambda)*sqrt(N*(S/lambda)) ),  Beamwidth first nulls.
Ae= D*lambda2/(4*PI)

Where C is circumference, which is about one wavelength for axial mode.

What exactly the gain of this antenna will be, is not clear - somewhere between 7 and 15 dBi - but the simulation at least shows that it radiates in axial mode.

Log Periodic Antenna Model

Just for fun, I tried a few more example files and a log periodic design plotted beautifully.

Logperiodic Example Plots

Therefore the design software is shown to be working fine and now the real work can start, to make a new antenna from scratch.  This becomes complicated when you add all the parasitic things: Stubs, ground plane, loading...

Vertical Dipole Model

Here is something simple that I created with xnec2c on Fedora Linux.  The picture is at the top of the page.

CM VERTICAL HALF WAVELENGTH ANTENNA,
CM 900 MHz, WL = 0.333 m, 1/4 WL = 0.083 m
CM Limitations of xnec2c visualization program RP card:
CM Cannot plot a 360 degree sweep with ground plane (need to remove GN cards)
CM The XNDA field must be 0
CE
GW     1     9  0.00000E+00  0.00000E+00  0.00000E+00  0.00000E+00  0.00000E+00  8.30000E-02  1.00000E-03
GE
FR     0     0     11     0  8.00000E+02  2.00000E+01  0.00000E+00  0.00000E+00  0.00000E+00  0.00000E+00
EX     0     0     5      0  1.00000E+00  0.00000E+00  0.00000E+00  0.00000E+00  0.00000E+00  0.00000E+00
RP     0    72    72      0  0.00000E+00  0.00000E+00  5.00000E+00  5.00000E+00  0.00000E+00  0.00000E+00
EN

 

Why?

A helical antenna is the general case of a wire antenna.  If you squash it up, it becomes a loop and if your stretch it out, it becomes a long wire.

Helical antennas can radiate in two modes (and everything in between...) Normal, or Axial.  Normal mode occurs when the helix circumference is smaller than 1/2 wavelength (0.2 nominal) and Axial mode occurs when it is larger than 0.8 wavelength (1 nominal). (See John D. Kraus, The Helical Antenna, Proceedings of the IRE, 1949).

As you can see in this graph from Kraus, there is almost no right or wrong way to make a helical antenna, provided that you stay close to the two D lambda curves.  To increase the gain, use more wire and reduce the spacing.  To make it more wide band, make the loops bigger.  To match the impedance to your radio, you can either add a tuner, or bend the first loop a little bit!

Axial mode is good for a ground antenna pointing at a small aircraft just like a Yagi-Uda, but the circular polarization will ensure minimal changes in signal strength when the aircraft banks in turns.

Normal mode is good when a retired radio amateur tries to fit a 160 meter HF dipole antenna into the attic of a small cottage.  If one uses two curly cords then a dipole becomes much smaller - any size you want it to be really, so it is a guaranteed fit, whether in your roof or outside in the yard.  Wrap the dipole wire around a plastic drain pipe, stretch it out as much as you can and stick a tuner on it to match it to your radio for whatever frequency you want to work at - as easy as borscht.

Axial mode concerns me at the moment and the normal mode will eventually!

While playing with example designs from the web in order to get going with the modelling programs, I noticed that many published designs and 'antenna calculators' are quite dreadful.  I even found some Yagis that radiate more backwards than forwards, so you really should model an antenna before you build it.

Heretics

Heretic geeks can buy EZNec for Windows and Linux cowboys can do dnf install nec2c xnec2c, or apt install nec2c xnec2c.  For Mac users, there is CocoaNEC.  All these programs work the same, since the underlying engine is the same, but they do have different bugs.

For example, xnec2c has trouble with the radiation pattern plot when there is a ground plane (remove the GN card) and the RP XNDA field must be 0.  Despite this, xnec2c seems to make better plots than xnecview as it handles edge cases better (where things go to zero).  CocoaNEC creates the best graphics by far, but it also struggles with a helical antenna (it won't display the helix structure, but it can display the radiation pattern) and CocoaNEC always inserts its own RP card - which ensures that it always works.

Note that when NEC crashes due to a divide by zero, then moving a ground plane or other element by a fraction of a millimeter can make the problem go away!

Different RP Card Handling:
  • xnec2++:     RP 0,1,72,72,1000,0,0,5,5,0,0
  • xnec2c:        RP 0,72,72,0,0,0,5,5,0,0,0
  • CocoaNEC: RP 0,91,120,1000,0,0,2,3,5000
So, you just have to pick one and play with it a bit till you figured it out - they all work - eventually.

However, the fancy GUIs only implement a small subset of what NEC can do.  Therefore, to do anything special, you need to stick your nose into the manual and edit the source card stack file with a text editor, the old fashioned way.  This is not easy and fancy GUIs cannot make it so.

La voila!

Herman



Monday, July 3, 2017

Cube Satellites

For a few years, it has been possible to launch tiny educational satellites - for free - to fill up some of the unused payload space on big rockets.  http://www.asc-csa.gc.ca/eng/satellites/cubesat/default.asp


This opportunity has been used by many universities and radio amateur groups: http://www.asc-csa.gc.ca/eng/sciences/canadian-cubesat-project.asp

A few months ago, the American University in Sharjah also launched a cubesat called NAYIF-1: http://www.arrl.org/news/nayif-1-cubesat-to-have-funcube-transponder.

It has been passing overhead many times and I was a bit miffed that I did not know about it before the launch, had no idea how to connect to it and to my knowledge, the radio amateur law in the UAE did not allow foreigners to operate.

The final straw was when I learned that Russia and Slovakia launched three cubesats in the same week:  


It turns out that in preparation for all this, the UAE radio amateur law was changed last year https://www.tra.gov.ae/assets/Le2rh2VP.pdf.aspx, a radio amateur society (EARS) was founded in Sharjah and expats are welcome: http://ears.ae/en/

NAYIF-1 Cubesat

The NAYIF-1 has a Funcube transponder, which has a beacon and a bent pipe.  Anyone can listen to the beacon, but to send something through the transponder would require a ham license: http://wp.rac.ca/uae-satellite-will-have-amateur-radio-transponder/

Cubesat Ground Station

The Funcube project is based in the UK: https://funcube.org.uk/

Educational material is posted here: https://funcube.org.uk/education-outreach/

To connect to the NAYIF-1 (or other) satellite, you need to know when it is passing: http://data.amsat-uk.org/nayif1/index 

To see all the cubesats currently flying, try this: https://in-the-sky.org/satmap_worldmap.php?day=4&month=7&year=2017&hour=10&min=50&show=sl&show=st  There are hundreds.  Which ones are actually working is another matter though.

To send data through a cubesat transponder, you would need a V/UHF radio, which could be an off the shelf SSB ham radio, or a Software Defined Radio specially built for this purpose: http://www.funcubedongle.com/

In practice, you need to know exactly when the satellite will pass overhead and then you have one or two minutes (depending on the height of the orbit) to bounce a message through the transponder before it disappears over the other horizon and then you may not see it again for several hours.

Ham Equipment

A new Yaesu/Kenwood/Icom/Xiegu/Alinco transceiver will cost around $800 to $8000, but you could buy a radio kit for $200 and assemble it yourself and end up with a similar high quality transceiver.

For example:
http://qrznow.com/kenwood-tm-v71a-full-dual-bander-144430mhz/

or:
http://www.kenwood.com/usa/com/amateur/ts-2000_b2000_2000x/ 

If you design the whole toy from scratch like I usually do, then it may take years to complete, it will likely end up costing $500 or more and the quality will be much inferior, but it will be a whole lot more fun to do and you could then say: This is a total piece of junk, it barely works, but I built it myself!

You could follow a somewhat easier path and build a ham radio kit, some of which are amazing quality and will look exactly the same as a factory built unit, but you could buy a second hand rig on Ebay for much less.

Absolutely amazing high quality factory built or DIY radio kits:

The best value kit which was refreshed recently in 2016, is BITX40, a 25 Watt, SSB, digitally controlled transceiver, built and tested PCB for only $60:
Due to the present low sun spot cycle, the 40 meter (7 MHz) HF band is best for long distance work and the BITX40 is ideal for that.  With the BITX40, you can chat to someone on the other side of the globe on SSB if you have a proper antenna (With a 15 meter flag pole and a tuner you can look very patriotic too!).

Very simple fun kits (which perform much worse and could cost more than the above!):

There are also crazy kits for ancient vacuum tube sets (for old fogeys like me), or little transceivers using only 7 parts that barely work, or radios built entirely from 2N2222 NPN bipolar transistors just because...:

Of course, someone then went and did the same with a radio built entirely from small signal PNP transistors!

A simple little radio can be much fun to chat to people around your city, but they are usually unstable and the transmit frequency will drift.  A good radio will lock on and follow a bad radio, so you can have fun provided that whoever you try to talk to has a good quality rig.  It will also help a lot if you run your fun radio off a battery and let it warm up and settle down for 15 minutes before you transmit.

A 7 Ah motorcycle battery is stable and has no noise and will make your toy work much, much better than a noisy unregulated wall wart and then you may be able to rag with someone hundreds of kilometers away on less power than a child's night light.

Ham Software

The best ham resources are probably the DXzone and ARRL web sites.

Here is a laundry list of Linux ham software and what they are good for:
http://www.dxzone.com/catalog/Software/Linux/

and this is for Macintosh:
http://www.dxzone.com/catalog/Software/Macintosh/

All the radioham utilities are available on Fedora, Ubuntu, Slackware, OpenBSD, Mac...  but you can also try Knoppix or Shackbox if you want to run off a USB stick without actually installing Linux on a machine.


Morse Code???

Everybody associates ham radio with Continuous Wave Morse code and if you listen to the HF bands, then you will hear a lot of it.  CW with Morse was the first digital telegraph modem about 200 years ago.  However, nobody learns to send Morse any more.  I was in the Corps of Signals in 1982 and didn't learn Morse - it was already long obsolete.

However, if you want two data link radios to connect to each other, then they have to use the same modem waveform on both sides of the link and Morse is the 'lowest common denominator', which can even work with a friendly doddering OM (old man) or XYL (ex young lady) clutching a pencil on the other side...

There are a multitude of modem programs that run on common garden variety computers that send data via the sound adaptors.  The most common ham modem modes are RTTY, PSK31 and CW Morse - there are many, many others, but it doesn't help if you are the only one trying to use it, since it will make you feel very lonely.

The best modem program at the moment, which works on Windows, Linux, BSD and Mac, is FLDigi: https://sourceforge.net/projects/fldigi/

However, as with most software things, you need at least a half decent computer and any half decent computer works better with Linux or BSD than with Windows. The Windows scheduler is not good for real-time operation and therefore cannot do encoding and decoding very reliably since it stutters too much.  This is why you will see many disparate reviews of the same amateur radio software, with one bloke saying it works great and the next bloke saying it doesn't.  If you don't want any hassle, use a Macintosh (which runs a kind of BSD).

FLDigi and Satscape are the most fun you can have with your geek hat on...

Best of all, you don't even need a radio to try it.  You can install FLDigi and play through your sound system to hear first hand what it does, or even let two computers side by side, talk to each other over the air, never mind the ether!


--. .-. --- ..- -. -.. / -.-. --- -. - .-. --- .-.. / - --- / -- .- .--- --- .-. / - --- -- / -.-. --- -- -- . -. -.-. .. -. --. / -.-. --- ..- -. - -.. --- .-- -. --..-- / . -. --. .. -. . ... / --- -.

Have fun with the Funcubes!

Herman