top of page

Bootstrap

Ok, so you're ready for some robot code. Here is a bootstrap, the minimum you need to talk to the controller app. Don't worry if it looks a little daunting. You just need to copy this to a file on your robot and run it. Of course it won't make it do anything, it will just print out the data it gets to the console.  It is written in CPython.

#!/usr/bin/env python3

import socket

import random

import os

 

hostName = socket.gethostname()

hostIPA = socket.gethostbyname(hostName)

print("hostIP",hostIPA)

port = random.randint(50000,50999)

os.system('setfont Lat15-TerminusBold32x16')

print("host",hostIPA)

print("port",port)

 

online = True

 

backlog = 1

size = 1024

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind((hostIPA,port))

s.listen(backlog)

try:

    client, address = s.accept()

    while online:

        data = client.recv(size)

        decoded = data.decode('utf-8')

        if decoded:

            print("data",decoded)

except AssertionError as error:    

    print("Closing app socket",error)    

    client.close()

    s.close()

    exit()

Bootstrap II

Here is another bootstrap. It is the same thing, but written in MicroPython this time. It looks a little different cause I needed different code to get the IP address and I added a special method to display the port number using images since it is not possible to change the tiny text size with MicroPython. The images I used are display in a line next to the code.

#!/usr/bin/env pybricks-micropython

from pybricks import ev3brick as brick

from time import sleep

 

import time

import random

import socket

import os

​

hostname = os.popen('hostname -I').read().strip().split(" ")

print("hostname address",hostname[0])

hostIPA = hostname[0]

millis = int(round(time.time()))

print(millis)

random.seed(millis)

port = random.randint(50000,50999)

 

brick.display.clear()

brick.sound.beep(2)

 

def bigText(No):

    xCord = 25

    portText = str(port)

    for figure in range(len(portText)):

        no = portText[figure:figure+1]

        no2display = "/home/robot/robot/No" + no + ".png"

        brick.display.image(no2display,(xCord,0),clear=False)

        xCord = xCord + 25

 

online = True

bigText(port)

sleep(12)

 

brick.sound.beep(4)

 

ai = socket.getaddrinfo(hostIPA,port)

addr = ai[0][-1]

 

backlog = 5

size = 1024

s = socket.socket()

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

s.bind(addr)

s.listen(backlog)

 

try:

    res = s.accept()

    while online:

        client_s = res[0]

        #client_addr = res[1]

        data = client_s.recv(1024)

        decoded = data.decode('utf-8')

        if decoded:

            print("data",decoded)

except AssertionError as error:

    print("Closing socket",error)

    client_s.close()

    s.close()

No0.png
No1.png
No2.png
No3.png
No4.png
No5.png
No6.png
No7.png
No8.png
No9.png
bottom of page