DApp Learnings  –  Storing & Iterating a Collection

I’ve been working on a rock, paper, scissors Ethereum DApp using Solidity, Web3 and the Truffle framework. I hit a few difficulties trying to replicate functionality that would normally be trivial in a non blockchain world so I thought I’d share what I learned.

My first thoughts for the DApp was to display a list of existing games that people had created. Normally if I were doing something like this in Django I’d create a game model and save any new games in the database. To display a list of existing games on the front end I’d query the db and iterate over the returned collection. (I realise storage is expensive when using the Ethereum blockchain but I thought trying to replicate this functionality would make sense and would be a good place to start.)

Solidity

Structures

While investigating the various data types that could be used I found the Typing and Your Contracts Storage page from Ethereum useful. I settled on using a struct, a grouping of variables, stored under one reference.

struct Game {
   string name;
   uint move;
   bool isFinished;
   address ownerAddress;
   uint stake;
   uint index;
}

That handles one game but I want to store all games. I attempted to do this in a number of different ways but settled on mapping using the games index as the key. Every time a new game is added the index is incremented so I also use gameCount to keep count of the total games.

mapping (uint => Game) games;
uint gameCount;

struct Game {
        string name;
        uint move;
        bool isFinished;
        address ownerAddress;
        uint stake;
        uint index;
    }

To add a new game I used this function:

function StartGame(uint moveId, string gameName) payable {
      require(moveId >= 0 && moveId <= 2);
      games[gameCount].name = gameName;
      games[gameCount].move = moveId;
      games[gameCount].isFinished = false;
      games[gameCount].ownerAddress = msg.sender;
      games[gameCount].stake = msg.value;
      games[gameCount].index = gameCount;
      gameCount++;
}

I also added a function that returns the total number of games:

function GetGamesLength() public returns (uint){
   return gameCount;
}

Returning A Structure

Next I want to be able to get information about a game using it’s index. In Solidity a structure can only be returned by a function from an internal call so for the front end to get the data I had to find another way. I went with the suggestion here — return the fields of the struct as separate return variables.

function GetGame(uint Index) public returns (string, bool, address, uint, uint) {
    return (games[Index].name, games[Index].isFinished, games[Index].ownerAddress, games[Index].stake, games[Index].index);
}

Front End

On the front end I use Web3 to iterate over each game and display it. To begin I call the GetGamesLength() function. As we saw previously this gives the total number of games. Then I can iterate the index from 0->NoGames to get the data for each game using the GetGame(uint Index) function.

When my page first loads it calls:

getGames: function() {
    var rpsInstance;
    App.contracts.RpsFirst.deployed().then(function(instance) {
      rpsInstance = instance;
      return rpsInstance.GetGamesLength.call();
    }).then(function(gameCount) {
      App.getAllGames(web3.toDecimal(gameCount), rpsInstance);
    }).catch(function(err) {
      console.log(err.message);
    });
  },

Web3 – Promises, Promises & more Promises…

The getAllGames function calls GetGame(uint Index) for each game. To do this I created a sequence of promises using the method described here:

getAllGames: function(NoGames, Instance){
   
   var sequence = Promise.resolve()

   for (var i=0; i < NoGames; i++){(function(){  
         var capturedindex = i
         sequence = sequence.then(function(){
            return Instance.GetGame.call(capturedindex);
         }).then(function(Game){
            console.log(Game + ' fetched!'
            // Do something with game data. 
            console.log(Game[0]); // Name
            console.log(Game[1]); // isFinished
         }).catch(function(err){
            console.log('Error loading ' + err)
         })
      }())
   }
}

Conclusion

Looking back at this now it’s all pretty easy looking but it took me a while to get there! I’m still not even sure if it’s the best way to do it. Any advice would be awesome and if it helps someone even better.

Python & Redis PUB/SUB

I recently had an issue where I have three Python scripts that need to be started on my RaspberryPI when it boots. Script 1 is identifying what serial devices are attached to the PI, saving the information to a database. Scripts 2 and 3 need to use this information, so have to wait until script 1 has completed.

I wasn’t sure of the best way to do this but I thought of a method that lets me experiment with Redis PUB/SUB which I’ve wanted an excuse to use for a while!

My Scripts

The redis-py Python Client is well documented and really easy to use. I created a function, RedisCheck(), that Scripts 2 & 3 call when they start. The function subscribes to a Redis channel called ‘startScripts’. It then goes into a loop until it receives a ‘START’ message on that channel. Once this is received the main scripts can continue with their primary jobs.

Script1 is very simple, the ‘START’ message is PUBLISHED via the ‘startScripts’ channel once the main work is done.

The following code should demonstrate how easy the code was to write and it works really well.

RedisCheck() SUB for Scripts 2 & 3

Script 1 PUB START

Publishing Via The Command Line

Another nice thing I found was how easy it was to PUBLISH the ‘START’ message using the redis-cli. All I do is run:

# redis-cli

> PUBLISH startScripts START

This is really useful if I’m debugging and so easy to do. Overall I really like Redis.

Python Map Plotting Using Cartopy

Cartopy Plot of Scotland

Recently I’ve been using Python and Cartopy to plot some Latitude/Longitude data on a map. Initially it took some time to figure out how to get it to work so I thought I’d share my code incase it was useful.

According to the Cartopy intro it is

“a Python package designed to make drawing maps for data analysis and visualisation as easy as possible.”

I’m not sure how active the project is and I found the documentation a bit lacking but once I was up and running it was pretty easy to use and I think the results look pretty good.

Plotting My Data

I have a csv file with various data timestamped and saved on each line. For this case I was interested in the lat/lng location, signal strength (for an antenna) and also a satellite number. An example of one line of data is:

2017–07–10 22:31:59:203,Processing UpdatePacket: [‘:’, ‘1’, ‘0’, ‘0’, ‘1’, ‘0’, ‘0’, ‘1.63’, ‘17.15’, ‘246.57’, ‘114.11’, ‘57.008263’, ‘-5.827861’, ‘310.00’, ‘1’, ‘NAN’, ‘0’, ‘2’, ‘0’, ‘c\n’]

and from that the information I require is:

lat/lng position: 57.008263,-5.827861
signal strength: 1.63
satellite number: 310.00

Initially for each lat/lng position I wanted to plot the point on a map and colour the marker at that point to show which satellite number it was. Also if the signal strength was -100 the marker colour should be shown as red. An example taken from some of the data is shown below.

 

Lat/Lng Plots with different zoom level

The following Gist shows the Python script I used:

Script Details

Most of the script is actually concerned with reading the file and parsing the relevant data. The main plotting functionality is in the section:

ax = plt.axes(projection=ccrs.Mercator()) # Map projection
ax.coastlines(resolution=’10m’)           # Adds coastline to map at highest resolution

plt.scatter(lngArr, latArr, s=area, c=satLngArr, alpha=0.5, transform=ccrs.Geodetic())                # Plot
plt.show()

The projection sets the coordinate system and is selected from the Cartopy projection list (there’s a lot to pick from and I chose the one I thought looked the best).

Next a coastline is added to the projection. As I was focusing on a small section of Scottish coastline I went with the 10m resolution which is the highest but lower resolutions can be selected as detailed in the documentation.

Finally a scatter plot is created. The data has been parsed into equal sized lists of longitude and latitude points.

The ‘s’ parameter defines the size of the marker at each point, in this case all set to 1pt radii.

The ‘c’ parameter defines the colour of the marker, in this case blue for satellite 310, green for 60, yellow for 302, black for any other satellite and red if signal strength is -100.

Finally the transform=ccrs.Geodetic() sets the lat/lng coordinate system as defined here.

Scaling Marker Size

It’s also possible to adjust the radius of the marker at each point. To scale it relative to the signal strength (I removed the -100 strengths):

area = np.pi * (strengthNpArray)**2

Which gives:

 

Marker scaled to strength at point

DApp – My First Solidity Contract

As explained in my previous post my first smart contract is based on the “Withdrawal from Contracts” example from the Solidity Common Patterns documentation. In this post I review some of the Solidity code I learned.

Smart Contract Intro

The example in the documentation was inspired by the King of the Ether game and the rules of the contract are:

  • To play a user submits a value of X Ether paid from his address
  • If X > historicHighest:
  • user is king
  • old king can collect previous payments
  • historicHighest = X

The contract itself is:

pragma solidity ^0.4.2;

contract WithdrawalContract {
    address public richest;
    uint public mostSent;
    mapping (address => uint) pendingWithdrawals;

    function WithdrawalContract() payable {
        richest = msg.sender;
        mostSent = msg.value;
    }

    event BecameRichestEvent(address sender, uint amount);
    event FailedRichestEvent(address sender, uint amount);
    event Collected(uint amount);

    function BecomeRichest() payable returns (bool) {

        if (msg.value > mostSent) {
            pendingWithdrawals[richest] += msg.value;
            richest = msg.sender;
            mostSent = msg.value;
            BecameRichestEvent(msg.sender, msg.value);
            return true;
        } else {
            FailedRichestEvent(msg.sender, msg.value);
            return false;
        }
 }

function withdraw() {
    uint amount = pendingWithdrawals[msg.sender];
    // Remember to zero the pending refund before
    // sending to prevent re-entrancy attacks
    pendingWithdrawals[msg.sender] = 0;
    msg.sender.transfer(amount);
    Collected(amount);
 }
}

Solidity Specifics

I found this Introduction to Smart Contracts documentation a good source of information.

Addresses – address public richest;

Type address — holds a 20byte Ethereum address. Here it’s used to save the address of the user who is currently the richest.

public allows other contracts to access the variable.

An address has various member functions as detailed here. One of these is address.transfer(uint256 amount) which sends the given amount of Wei to the address. In this case transfer is used in the Withdraw function to safely send Ether to a valid users address.

Mappings - mapping (address => uint) pendingWithdrawals;

The next line, mapping (address => uint) public balances; also creates a public state variable, but it is a more complex datatype.

Mappings can be seen as hash tables. pendinWithdrawals maps addresses to unsigned integers. For example:

pendingWithdrawals[0xc7975434577b0d57248e1de03fcc6f27cd6cc742] = 7;

Maps the value 7 to address 0xc7975434577b0d57248e1de03fcc6f27cd6cc742 and can be called using:

x = pendingWithdrawals[0xc7975434577b0d57248e1de03fcc6f27cd6cc742]; 

x = 7

Transactions & Constructors – function WithdrawalContract() payable

This is a constructor – a function that is run when the contract is first created.

The payable modifier means the function is a transaction. A transaction is the transfer of data between two accounts (good explanation here). A transaction contains some standard data e.g. sender address or the amount of wei being transferred. We can access the transaction data using the global msg variable.

In this case msg is used to set the initial richest address to msg.sender which is the address of the person deploying the contract. It also saves the mostSent as the msg.value which is the number of wei sent during the deployment.

Events – event BecameRichestEvent(address sender, uint amount);

The front end of the application, in my case Web3.js, listens for Solidity events being fired so it can update the interface. For example the BecameRichest event fires when a new account becomes the richest.

The event is fired by the line:

BecameRichestEvent(msg.sender, msg.value);

The listener will have access to the sender and value data passed to the call.

In the next post I plan to detail some of the front end functionality, including how to listen for events.

Ethereum Work – Beginners Sending & Receiving Eth

Intro

I’ve been following the Status project for some time and recently they announced their virtual hackathon. I’d been planning on diving into the Ethereum/Decentralised App development world and thought this would be an ideal time to start and I pretty quickly saw how powerful and relatively simple this can be.

As a complete beginner to working with the blockchain I found it better to begin by forgetting about the Status part and even the Dapp part and just see how to interact with a blockchain. Basically you can send some Eth between accounts using one function – that’s impressive.

Setup

I figured you need to get set-up with three things to get going:

1. A blockchain

Normally this would be the Ethereum blockchain but whenever you run a smart contract on Ethereum you must pay for the computation using gas. Testnets simulate the Ethereum network on you local machine and allow you to experiment for free. I installed testrpc.

2. web3.js

web3.js is a Javascript library which runs in a browser, connects to a local blockchain node and allows you to make calls on the blockchain. It does this using remote procedure calls (RPC) which basically means passing messages in JSON format.

3. Truffle

Truffle is a development environment for Ethereum that makes development a lot easier. For this exercise I’m just using the Truffle console to interact with web3.js manually. It’s way more powerful than that, which I hope show during some more posts in the future.

The Action

Start the testnet

To begin the testrpc testnet needs to be started by entering the following command:

testrpc -p 8546
This just means a simulated Eth client is listening on my laptops IP address on port 8546.
When it starts gives a list of test wallets that are loaded with 100Eth (unfortunately not real Eth, just Eth for the simulated environment). These are handy for experimenting with. My output showed:
Available Accounts
 ==================
 (0) 0xc7975434577b0d57248e1de03fcc6f27cd6cc742
 (1) 0x74dcfef837aff77d7c43d44d1d69b1eef5d708a6
 (2) 0xac63a31fd24d692997e577c02524f81eb223cd1d
 (3) 0x86fd495d744d13d43d00aa700dc9517a92eb9eae
 (4) .......

Run web3 commands

Truffle has a console tool that can be used to run web3 commands. To start it just type (keep testrpc running in separate window):

truffle console

Then try:

web3.eth.accounts

you should see a list of the same accounts you saw when you started testrpc.

Send send send

So now the really cool part. To transfer Eth between accounts all you need to enter is:

var sender = web3.eth.accounts[0];
Which shows the first address in your list, in my case: ‘0x72ddd46949fddd6add06d99a3f64357a18506470′
var receiver = web3.eth.accounts[1]
Which shows the second address in your list, in my case:
‘0x05fc7ea9e73061234d45381e8cc2e1995d4d02da’
To show the current balances in both accounts:
web3.eth.getBalance(sender)

web3.eth.getBalance(receiver)

These should both return,

{ [String: '100000000000000000000'] s: 1, e: 20, c: [ 1000000 ] }
which shows 100Eth in both accounts.
We’ll transfer 0.01Eth:
var amount = web3.toWei(0.01, 'ether')
 And the actual transfer (this could have been run by itself right from the start but the above steps make the process a bit clearer):
web3.eth.sendTransaction({from:sender, to:receiver, value: amount})
 This returns a transaction address like: ‘0x9e9963f4782b4248b2cd42d8af17e85d64d049e052da335e3517f4a8a69aa064’
To confirm the transfer we can check the balances again:
web3.eth.getBalance(sender) this time shows:
{ [String: ‘99989999999999979000’] s: 1, e: 19, c: [ 999899, 99999999979000 ] }
web3.eth.getBalance(receiver) this time shows:

{ [String: ‘100010000000000000000’] s: 1, e: 20, c: [ 1000100 ] }

So 0.01Eth has been transferred!
If you look in your testrpc window you should see the transaction information on the blockchain, something like:
0x9e9963f4782b4248b2cd42d8af17e85d64d049e052da335e3517f4a8a69aa064
 Gas usage: 0x5208
 Block Number: 0x01
 Block Time: Tue Jun 06 2017 19:34:54 GMT+0100 (BST)

So with as little as one command you can transfer value electronically, cryptographically proven and with minimal fee. From a pure tech geek point of view that’s awesome, no wonder people get excited about this stuff!

Antenna Arrays And Python – The Array (finally!)

As mentioned in my intro post an array antenna is a set of individual antennas connected to work as a single antenna. So far we’ve covered the individual antennas, i.e. the square patches, now it’s time to look at how they can be connected to work together.

Array Factor Fun

You can’t get far digging into arrays before you come across the Array Factor. It looks complicated but to me the easiest way to think of it is that it combines every elements position, radiating amplitude and radiating phase to give the overall array performance.

The Array Factor demonstrates that by altering an element, such as its position or phase, we can alter the arrays properties. For example the arrays beam could be steered to a desired position by altering the phase of each element.

The Array Factor is given by:

Where:

θ, φ = Direction from origin

N = number of elements

An= Amp of element

βn = Phase of element in rads

k0 = 2π/λ rads/m

And:

is the relative phase of incident wave at element n located at xn, yn, zn.

Array Factor in Python

The script below shows how easy it is to calculate the Array Factor in Python:

Array Radiation Pattern, Directivity & Gain

The above Array Factor equation is independent of each elements individual radiating pattern. The overall radiation pattern of an array is determined by the array factor combined with the radiation pattern of each element, Fn(θn, φn), giving:

The overall radiation pattern results in a certain directivity and thus gain linked through the efficiency as discussed previously.

Some Examples

To demonstrate the effects the individual element patterns have on the overall array performance we can investigate some examples using Python.

Isotropic antenna elements

In this case each element radiates equally in all directions so Fn(θn, φn) is the same for each θn, φn. The antenna radiation pattern is now just the Array Factor as described in the code above.

15×15 Array of Isotropic Elements

Patch antenna elements

Using elements described by the PatchFunction discussed previously:

PatchFunction(θ, φ, Freq, 10.7e-3, 10.47e-3, 3e-3, 2.5)
15×15 Array of patches

Python script for patch array:

Horn antenna elements

And finally using horn antenna elements represented by cos²⁸(θ) function.

15×15 Array of cos²⁸(θ) Horns

Python script for horn array:

Next time we can see how to calculate an elements phase to steer the beam.

Antenna Arrays And Python – Patch Efficiency & Gain

Last post I dealt with antenna directivity, this post discusses antenna gain which is closely related.

Gain combines an antennas directivity and efficiency to describe how good it is at sending/receiving power in a direction. This is useful for things like link budget analysis which basically calculates if two antennas can communicate.

Antenna Gain, G, can be calculate from the directivity, D, and antenna efficiency, εr by:

The efficiency of an antenna describes how well the input power is radiated by the antenna (and due to reciprocity receive efficiency is the same as transmit efficiency):

A high efficiency antenna will radiate most of the input power while a low efficiency antenna will lose a lot of the input power before it is radiated due to things like dielectric loss, impedance mismatch, etc.

Patch Efficiency

The Python script at the bottom of the post is based on the ArrayCalc calc_patchr_eff.m file and defines a function, CalculatePatchEff, that calculate the efficiency of a rectangular patch based on the patch dimensions and materials. The comments provide some example material properties and the main function has some examples that demonstrate the effects of the material selection on the efficiency:

FR4 Patch, 14GHz, Efficiency = 47.27%

RO4350 Patch, 14GHz, Efficiency = 62.32%

Python Script

Antenna Arrays And Python – Plotting with Pyplot

One of the most useful things to see when investigating an antenna design is the radiation pattern – a plot showing where the antenna transmits or receives power. In the previous post a Python function was developed for a square patch that calculated the total E-field pattern as a function of theta and phi. Now I want to plot this E-field which will show the radiation pattern.

matplotlib

I don’t have a great deal of experience with visualisation or plotting in Python but I have used matplotlib before and found it relatively ok. matplotlib is a plotting library for the Python programming language and Pyplot is a matplotlib module that provides a collection of command style functions to make matplotlib work like MATLAB.

This Pyplot tutorial covers the basics and I find the gallery useful to find example code.

E-plane & H-plane plots

First plots I wanted to see were for E-field vs 0°<theta<90 °for phi cuts at 0° and 90°. Referring to the patch geometry we described earlier this will give us the E-plane (phi = 0°) and the H-plane (phi = 90°).

Patch geometry

An example plot of a patch with W=7mm, L=5.58mm, Er=3.66, h=10.1mm is shown below. The complete Python script can be found at the end of the post with the relevant function being: PatchEHPlanePlot(freq, W, L, h, Er).

Example E&H-Plane plot

3d surface plot

The next plot I wanted was a 3D plot of the E-field across all phi and theta values. This will allow the visualisation of things like the main beam direction, side lobes, etc. While it is nice to see this for the patch it will be very helpful when it comes to investigating a full array.

An example of the surface plot for the same rectangular microstrip element is shown below and was plotted using the SurfacePlot(Fields) function in the code.

Patch Surface Plot

Patch Script

The completed patch script can be seen below. It consists of the following functions:

main: Some examples of various patch designs.

DesignPatch(Er, h, Freq): Theory taken from ArrayCalc. It returns the patch L & W for specified Er, h and freq.

SurfacePlot(Fields, Freq, W, L, h, Er): Plots a 3D surface of the field.

PatchEHPlanePlot(Freq, W, L, h, Er, isLog=True): Plots the 2D E&H-planes.

GetPatchFields(PhiStart, PhiStop, ThetaStart, ThetaStop, Freq, W, L, h, Er): Returns an array with fields for patch over phi and theta range.

PatchFunction(thetaInDeg, phiInDeg, Freq, W, L, h, Er): Calculates total E-field pattern for patch as a function of theta and phi as detailed in previous post.

Antenna Arrays And Python – Square Patch Element

As mentioned in my intro post, the individual antennas in an array are often known as “elements”. To compute the arrays performance each individual elements field contribution needs to be summed. For my initial investigation I focus on using a rectangular microstrip patch element and this post will cover the model that is used.

A microstrip or patch antenna is a low ­profile antenna that has a number of advantages over other antennas – it is lightweight, inexpensive, and easy to integrate with accompanying electronics because they can be printed directly onto a circuit board which makes them easy to fabricate.

A patch antenna usually consists of a conductive patch with width W, and length L, sitting on top of a substrate (i.e. a dielectric circuit board) with thickness h and relative permittivity Er. The substrate then sits on top of a conductive ground plane.

 

Patch Antenna (taken from ArrayCalc)
The element model is taken from C.A. Balanis 2nd Edition Page 745, and represents the far-field element radiation patterns as closed form mathematical equations. The model used is the cavity/transmission-line model and is referenced by most antenna texts covering microstrip antennas. The patch is modelled as 2 radiating slots, separated by a nominally half wavelength section of low impedance transmission line. The calculations are fully detailed in the ArrayCalc Design_patchr.m file and also the theory is detailed in the Theory Of Operation document. I also find the antenna-theory website a useful resource for further reading.

With the model used there is no account taken of mutual coupling between the elements. This can have a significant effect on array performance when array elements themselves are large, elements are closely spaced or large scan angles are used. It is also assumed the ground plane is infinite so the model is only valid over 0°<theta<90°, 0°<phi < 360°. The benefits of this model are the calculation is potentially very fast and despite the limitations the model still provides enough accuracy to give a useful insight into the potential performance of an array, before committing to more detailed modelling or prototyping.

The E theta and E phi components of the far-field radiation pattern are given by the equations below:

Using these equations allows us to create the following Python function to calculate the total E-field pattern for the patch as a function of theta and phi:

Before moving on to the array calculation itself next time I’ll detail the Python scripts I use to visualise the fields as it’s always nice to see what’s going on.

Deploying a Django app to Heroku

Note to self — before deploying a local Django app to Heroku I should do the following:

Install the wsgi HTTP server, gunicorn:

pip install gunicorn

Install package to help work with environment variables:

pip install python-dotenv

Install Python-PostgreSQL Database Adapter:

pip install psycopg2

Create requirements file:

pip freeze > requirements.txt

Configure settings.py to load environment variables and the database:

import dotenv
import dj_database_url

# this line is already in your settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# load environment variables from .env
dotenv_file = os.path.join(BASE_DIR, ".env")
if os.path.isfile(dotenv_file):
    dotenv.load_dotenv(dotenv_file)

# load database from the DATABASE_URL environment variable
DATABASES = {}
DATABASES['default'] = dj_database_url.config(conn_max_age=600)

Also delete the default database config:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

Add a .env file to project base directory and add the database URL:

DATABASE_URL=sqlite:///db.sqlite3

Make sure .env is added to .gitignore so it doesn’t get pushed to repo. My last .gitignore looked like:

*.pyc
*~
__pycache__
myvenv
venv
db.sqlite3
.DS_Store
.env

Assuming there is already a heroku account run:

heroku login

locally to associate machine with heroku account.

On the heroku dashboard create a new app. Under the “Settings” tab and under “Buildpacks” add a new buildpack called “heroku/python”.

Under “Config Variables” add “DISABLE_COLLECTSTATIC” with a value of “1”.

To set-up the database go back to command line and enter:

heroku addons:create heroku-postgresql:hobby-dev -a YOUR_APP_NAME

This provisions a new postgres database and should add the url to the Config Variables. Run command:

heroku config -a YOUR_APP_NAME

DATABASE_URL should be added to Config Variables.

Now create a new file called Procfile in the base directory of project and add:

web: gunicorn YOURSITE.wsgi --log-level=info --log-file -

Where YOURSITE is specific to the project.

Add another file in base directory called runtime.txt and add the version of python you want to use:

python-3.5.2

To serve static assets I use the WhiteNoise project. To install:

pip install whitenoise
...
pip freeze > requirements.txt

Add it to the app by changing wsgi.py to include:

from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise

application = get_wsgi_application()
application = DjangoWhiteNoise(application)

Now that should be it! Commit the changes locally then run:

git push heroku master

It should display the progress of installation and eventually be up and running.

References

This was trying to put a bunch of stuff I read in the articles below into an order I’ve found works for me.

https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django