Go Programming Language | Installation | Gobot Framework

The Go Programming Language is an open source, compiled, concurrent, garbage-collected, statically typed language developed at Google. Google created it to solve its own problems in relation to multicore processors, networked systems and large codebases. While languages such as C and C++ are fast, they are hard to master and development takes longer. While Python is easier to work with, it compromises on runtime efficiency. Go was designed to be efficient, scalable and productive.

This programming language designed by Google engineers Robert Griesemer, Rob Pike, and Ken Thompson.

Try it now https://play.golang.org/

Why was Go invented?

Go was invented (in 2007) at a time when multicore CPU architectures were common, largely because Moore’s Law was failing to deliver. With multiple cores, code can run in parallel on all available cores; but there was no programming language that simplified the development of multithreaded applications. The responsibility of managing different threads safely and efficiently fell on developers. Thread-locking, race conditions and deadlocks are usual challenges. Go was designed with concurrent programming in mind.

Adoption of Go language

GO adopted by Docker, Kubernetes, Weave, Shipyard, etcd, Fleet, Deis, Flynn. Since Go is suited to distributed server apps, all of these apps are cloud related. Lime is an example of a desktop app for text editing. InfluxDB, a distributed time series database, is written in Go. Gogs (Go Git Service) helps you to run a Git service, like GitHub. Go is a suitable fit for Docker due to static compilation and ability to build for different architecture with less effort. In 2016, Go was rated the most popular language in the TIOBE index. Multiple developer surveys in 2018 show interest and adoption of Go.

Features of Go language

  • Concurrency
  • Scalability
  • Fast performance
  • Garbage collection and cross platform
  • Compiled language
  • Use as object-oriented language

What are some criticisms of Go Programming Language?

  • Go doesn’t support generics
  • Packages are not versioned in a centralized place.
  • We can’t define immutable data types
  • Compile-time checks are lacking.
  • It’s slow compared to C, C++ and Rust.
  • Interfaces are implicit.

Why IoT Should Pay Attention To Go

In IoT framework requires a good and dependable programming language. If you look at many of the tools today, you really only have  C/C++ or a NodeJS integration, which lacks modular support cause they are generally designed to work with only one particular device. Let me introduce you to using Go as part of your IoT solution.

As a relatively new language that was inspired by C roots without all of its dangers, built in concurrency sweetens the deal further by allowing you to define goroutines that plug straight into your embedded devices. The concurrency model here is much easier and safer to implement. Remember the last time you had to deal with pthreads along with the mutexes, condition variables and semaphores?

It’s probably Go’s intention to not be part of the embedded toolchain. It was not designed to replace embedded C, but more towards handling the communication layer to and from these devices. The garbage collection in Go makes it less ideal for it to implemented at the embedded device level, but great for people seeking greater control of resources without paying too much overhead for such features.

Sample code of Go Programming Language:

// This program solves the (English) peg
// solitaire board game.
// http://en.wikipedia.org/wiki/Peg_solitaire

package main

import "fmt"

const N = 11 + 1 // length of a row (+1 for \n)

// The board must be surrounded by 2 illegal
// fields in each direction so that move()
// doesn't need to check the board boundaries.
// Periods represent illegal fields,
// ● are pegs, and ○ are holes.

var board = []rune(
    `...........
...........
....●●●....
....●●●....
..●●●●●●●..
..●●●○●●●..
..●●●●●●●..
....●●●....
....●●●....
...........
...........
`)

// center is the position of the center hole if
// there is a single one; otherwise it is -1.
var center int

func init() {
    n := 0
    for pos, field := range board {
        if field == '○' {
            center = pos
            n++
        }
    }
    if n != 1 {
        center = -1 // no single hole
    }
}

var moves int // number of times move is called

// move tests if there is a peg at position pos that
// can jump over another peg in direction dir. If the
// move is valid, it is executed and move returns true.
// Otherwise, move returns false.
func move(pos, dir int) bool {
    moves++
    if board[pos] == '●' && board[pos+dir] == '●' && board[pos+2*dir] == '○' {
        board[pos] = '○'
        board[pos+dir] = '○'
        board[pos+2*dir] = '●'
        return true
    }
    return false
}

// unmove reverts a previously executed valid move.
func unmove(pos, dir int) {
    board[pos] = '●'
    board[pos+dir] = '●'
    board[pos+2*dir] = '○'
}

// solve tries to find a sequence of moves such that
// there is only one peg left at the end; if center is
// >= 0, that last peg must be in the center position.
// If a solution is found, solve prints the board after
// each move in a backward fashion (i.e., the last
// board position is printed first, all the way back to
// the starting board position).
func solve() bool {
    var last, n int
    for pos, field := range board {
        // try each board position
        if field == '●' {
            // found a peg
            for _, dir := range [...]int{-1, -N, +1, +N} {
                // try each direction
                if move(pos, dir) {
                    // a valid move was found and executed,
                    // see if this new board has a solution
                    if solve() {
                        unmove(pos, dir)
                        fmt.Println(string(board))
                        return true
                    }
                    unmove(pos, dir)
                }
            }
            last = pos
            n++
        }
    }
    // tried each possible move
    if n == 1 && (center < 0 || last == center) {
        // there's only one peg left
        fmt.Println(string(board))
        return true
    }
    // no solution found for this board
    return false
}

func main() {
    if !solve() {
        fmt.Println("no solution found")
    }
    fmt.Println(moves, "moves tried")
}

How to Install Go on Ubuntu


Install Go

  • Use curl or wget to download the current binary for Go from the official download page. As of this writing, the current version is 1.11 Check the download page for updates, and replace 1.11 with the most recent stable version if necessary.
curl -O https://storage.googleapis.com/golang/go1.11.linux-amd64.tar.gz
  • Extract the tar file:
tar -xvf go1.11.linux-amd64.tar.gz
  • Adjust the permissions and move the go directory to /usr/local:
sudo chown -R root:root ./go
sudo mv go /usr/local

Adjust the Path Variable

Using a text editor, open the ~/.profile file and add the following two lines to the bottom of the file:

export GOPATH=$HOME/go
export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin

Save the file, and load the commands into the current shell instance:

source ~/.profile

Test the Installation

According to the official documentation, the following steps are the recommended way to test the success of the installation:

In your home directory create a folder named go, this will be your workspace:

mkdir go

Within that directory create /src/hello and within that directory copy and paste the contents of the file below:

mkdir -p go/src/hello && cd go/src/hello
touch hello.go
package main

import "fmt"

func main() {
fmt.Printf("hello, world\n")
}

Build the hello.go file:

go build

Run the script:

./hello

hello, world


Gobot – A Framework for robots, drones, and IoT


What is Gobot?

Gobot is a framework for robotics, physical computing, and the Internet of Things (IoT), written in the Go programming language. It provides drivers and adapters for controlling a wide variety of physical devices from low-level Arduino and Raspberry Pi, as well as drones, toys, and other complete devices that themselves have APIs.

The “Robot” is the main software abstraction that makes it easy to build interesting high-level functionality for supported devices. Robots (Go programs) written with Gobot can run on a host machine communicating to connected devices, or directly on a single-board Linux computer, or anywhere in between. It can also provide an external facing API to allow other programs to control from individual devices to entire groups of Robots on a shared network, implemented using JSON-over-HTTP API. Gobot’s approach to standardization and abstraction makes it easy to write a program that works on multiple hardware platforms with little modification.

Set Up Your Environment

Installing Go

Go is an open-source programming language that makes it easy to develop simple, reliable, and efficient software.

Follow the official installation instructions to get started.

Installing Gobot

With Go installed, the go get tool will help you install Gobot and its required dependencies:

$ go get -d -u gobot.io/x/gobot/...

Platform Support

It has a extensible system for connecting to hardware devices. Currently 35 platforms supported. Many GPIO, SPI, I2c drivers available with go lang packages.

API

It includes a RESTful API to query the status of any connection, device or robot running in your swarm. It additionally has the ability to issue commands directly to your devices and robots. Check out http://cppp.io for more information.

It also comes with the robeaux React.JS interface baked right into its API server for quick and easy configuration. You can check out more information on the Gobot API in the docs here.

CLI

Gobot is designed to be using in conjunction with Gort, a Command Line Toolkit (CLI) for RobotOps. Gort provides tools to scan for connected devices, upload firmware, and it works perfectly with Gobot. Also included with Gobot is a CLI for generating new robots and adaptors. It also has it own CLI which you can learn more about here.

Getting Started with a Simple Tutorial

The “Hello, World” Of Things -This program connects to an Arduino, and toggles an LED, every one second.

package main

import (
  "time"

  "gobot.io/x/gobot"
  "gobot.io/x/gobot/drivers/gpio"
  "gobot.io/x/gobot/platforms/firmata"
)

func main() {
  firmataAdaptor := firmata.NewAdaptor("/dev/ttyACM0")
  led := gpio.NewLedDriver(firmataAdaptor, "13")

  work := func() {
    gobot.Every(1*time.Second, func() {
      led.Toggle()
    })
  }

  robot := gobot.NewRobot("bot",
    []gobot.Connection{firmataAdaptor},
    []gobot.Device{led},
    work,
  )

  robot.Start()
}

To run your Robot, you can just pass the source file to go run:

$ go run blink.go

You should see the LED turn on and off every second. Explore More examples for IoT project.

Useful links


I hope you like this post. Do you have any questions? Leave a comment down below!

Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing my blog.

You may like also:

Harshvardhan Mishra

Hi, I'm Harshvardhan Mishra. I am a tech blogger and an IoT Enthusiast. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. Thank you for reading my blog! Happy learning! Follow and send tweets me on @harshvardhanrvm. If you want to help support me on my journey, consider sharing my articles, or Buy me a Coffee!

Leave a Reply

%d bloggers like this: