Telnet Demo

Enabling Telnet in Windows 10

telnet YOU WILL GET THE SERVER IN CLASS
EHLO totally.legit.server.com
MAIL FROM:<NAME@AURLIWILLGIVEYOU.com>
RCPT TO: <ONEOFOUREMAILS@gmail.com>
DATA
From: Da Boss <NAME@AURLIWILLGIVEYOU.com>
To: The Dude <ONEOFOUREMAILS@gmail.com>
Subject: Totally legit offer for The Dude
Hello Mr The Dude,
I would like to give you lots of free money. Please click this not
at all suspicious link to claim it:
Best,
Da Boss
Totally Legitimate Company, Inc.
.
QUIT

Platformer Python Code


import turtle, random,time
map = input('Select a map from 1-8 or press 9 for random map')
max = 8
map = int(map)
if map == max:
  map = random.randint(1,max-1)
if map == 1:
  mapName = "v"
if map == 2:
  mapName = "d"
if map == 3:
  mapName = "m"
if map == 4:
  mapName = "a"
if map == 5:
  mapName = "j"
if map == 6:
  mapName = "e (1)"
if map == 7:
  mapName = "t"
if map == 8:
  mapName = "l"

charlist = ['rainbowbob','Kataniguana','yurp','REEE','Zhane','america','lightning','Goku','Symmetra','Dva','Junkrat2','Mercy','soldier']
print(charlist)
char1 = int(input('Player 1 Choose a character from the list.'))
char2 = int(input('Player 2 Choose a character from the list.'))
char1 = charlist[char1-1]
char2 = charlist[char2-1]

you = turtle.Turtle()
you.penup()
them = turtle.Turtle()
them.penup()
ball = turtle.Turtle()
screen = turtle.Screen()
screen.setup(400, 400)
direction = "up"
screen.bgpic(mapName+".png")
screen.addshape(char1+".png")
you.shape(char1+".png")
screen.addshape(char2+".png")
them.shape(char2+".png")
move_speed = 10


##MOVEMENT CODE FOR SPRITE 1 (YOU)
def up():
  xold = you.xcor()
  yold = you.ycor()
  you.sety(you.ycor()+move_speed)
  if you.ycor()> 200:
    you.sety(-200)
  print(str(you.xcor())+','+str(you.ycor()))
  findbox(xold,yold)
def down():
  xold = you.xcor()
  yold = you.ycor()
  you.sety(you.ycor()-move_speed)
  if you.ycor()< -200:
    you.sety(200)
  print(str(you.xcor())+','+str(you.ycor()))
  findbox(xold,yold)
def left():
  xold = you.xcor()
  yold = you.ycor()
  you.setx(you.xcor()-move_speed)
  if you.xcor()< -200:
    you.setx(200)
  print(str(you.xcor())+','+str(you.ycor()))
  findbox(xold,yold)
def right():
  xold = you.xcor()
  yold = you.ycor()
  you.setx(you.xcor()+move_speed)
  if you.xcor()> 200:
    you.setx(-200)
  print(str(you.xcor())+','+str(you.ycor()))
  findbox(xold,yold)
def jump():
  up()
  up()
  up()
  time.sleep(0.1)
  down()
  down()
  down()
  

##MOVEMENT CODE FOR SPRITE 2 (THEM)
def up2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  them.sety(them.ycor()+move_speed)
  if them.ycor()> 200:
    them.sety(-200)
  print(str(them.xcor())+','+str(them.ycor()))
  findbox(xold2,yold2)
def down2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  them.sety(them.ycor()-move_speed)
  if them.ycor()< -200:
    them.sety(200)
  print(str(them.xcor())+','+str(them.ycor()))
  findbox(xold2,yold2)
def left2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  them.setx(them.xcor()-move_speed)
  if them.xcor()< -200:
    them.setx(200)
  print(str(them.xcor())+','+str(them.ycor()))
  findbox(xold2,yold2)
def right2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  them.setx(them.xcor()+move_speed)
  if them.xcor()> 200:
    them.setx(-200)
  print(str(them.xcor())+','+str(them.ycor()))
  findbox(xold2,yold2)
def jump2():
  up2()
  up2()
  up2()
  time.sleep(0.1)
  down2()
  down2()
  down2()
  
  
  
def findbox(xold, yold):
  if map == 1:
    coords = [
    [30,90,90,180],
    [10,120,30,70],
    [160,200,-10,70],
    [-160,-20,20,70],
    [-200,-180,20,80],
    [-80,-10,100,180],
    [-170,-120,100,200],
    [-190,-100,-80,-30],
    [-40,10,-90,-40]]
  if map == 7:
     coords = [
    [10,180,-110,-70],
    [10,180,-160,-120],
    [10,180,-180,-160],
    [-80,0,-180,-60],
    [-190,-90,-170,-60],
    [120,200,70,200],
    [20,70,80,190],
    [-160,-20,120,190],
    [-170,-120,70,100],
    [-120,-80,70,100],
    [-70,-30,70,100]]


  sprites = [you, them]
  for i in sprites:
    for j in coords:
      if i.xcor() > j[0] and i.xcor() < j[1]: 
        if i.ycor() > j[2] and i.ycor() < j[3]:
          print('you are in the box')
          i.setx(xold)
          i.sety(yold)
   
def fly(ball):
  global direction
  ball.hideturtle()
  ball.setx(you.xcor())
  ball.sety(you.ycor())
  ball.pendown()
  if direction == "up":
    ball.sety(200)
  if direction == "down":
    ball.sety(-200)
  if direction == "left":
    ball.setx(-200)
  if direction == "right":
    ball.setx(200)
  ball.penup()
  ball.showturtle()

you.penup()
you.speed(0)
you.home()
you.left(90)

them.penup()
them.speed(0)
them.home()
them.left(90)

screen.onkey(up, "Up")
screen.onkey(down, "Down")
screen.onkey(left, "Left")
screen.onkey(right, "Right")
screen.onkey(jump,"Space")

screen.onkey(up2, "w")
screen.onkey(down2, "s")
screen.onkey(left2, "a")
screen.onkey(right2, "d")
screen.onkey(jump2,"x")
screen.listen()

GPS Code for USB Receiver

import serial
gpsPort = "/dev/ttyACM0"
gpsSerial = serial.Serial(gpsPort, baudrate = 9600, timeout = 0.5)

def parseGPS(data):
    gps = data

    try:        
        if gps[2:8] == "$GNGGA":
            gps = gps.split(",")

            timeHour = (int(gps[1][0:2]) - 4) % 24
            timeMin = int(gps[1][2:4])
            timeSec = int(gps[1][4:6])
            print("Time: " + str(timeHour) + ":" + str(timeMin) + ":" + str(timeSec))

            latDeg = int(gps[2][0:2])
            latMin = int(gps[2][2:4])
            latSec = float(gps[2][5:9]) * (3/500)
            latNS = gps[3]
            print("Latitude:  " + str(latDeg) + "°" + str(latMin) + "'" + str(latSec) + '" ' + latNS)

            longDeg = int(gps[4][0:3])
            longMin = int(gps[4][3:5])
            longSec = float(gps[4][6:10]) * (3/500)
            longEW = gps[5]
            print("Longitude:  " + str(longDeg) + "°" + str(longMin) + "'" + str(longSec) + '" ' + longEW)

            alt = float(gps[9])
            print("Altitude: " + str(alt) + " m")

            sat = int(gps[7])
            print("Satellites: " + str(sat))
        if gps[2:8] == "$GNRMC":
            gps = gps.split(",")

            speed = float(gps[7]) * 1.852
            print("Speed: " + str(speed) + " km/h")
            
            head = float(gps[8])
            print("Heading: " + str(head))
        else:
            gps = ""
    except Exception as error:
        print(error)

    return gps
while True:
    print(parseGPS(gpsSerial.readline()))

Current Combined Code


import os
import picamera
import sense_hat
import time
import yagmail

camera = picamera.PiCamera()
camera.resolution = (1280, 720)
framerate = 5
camera.framerate = framerate
camera.annotate_text_size = 18

senseHat = sense_hat.SenseHat()

gps = "GPS Data"

def annotate():
    timeNow = "Time: " + str(time.strftime("%a %d %b %Y %H:%M:%S", time.localtime()))
    temperatureNow = "Temperature: " + str(round(senseHat.get_temperature())) + " C"
    humidityNow = "Humidity: " + str(round(senseHat.get_humidity())) + "%"
    locationNow = "Location: " +gps
    
    annotation = timeNow + "\n" + temperatureNow + "\n" + humidityNow + "\n" + locationNow
    return annotation

def getPicture(annotation):
    filename = "/home/pi/Pictures/" + str(time.strftime("%Y-%m-%d@%H:%M:%S", time.localtime())) + ".jpg"

    try:
        camera.start_preview()
        time.sleep(5)
        camera.annotate_text = annotation
        camera.capture(filename)
        camera.stop_preview()
    except Exception as error:
        print(error)

    return filename

def getVideo(length):
    filename = "/home/pi/Videos/" + str(time.strftime("%Y-%m-%d@%H:%M:%S", time.localtime())) + ".mp4"
    
    try:
        camera.start_recording("/home/pi/testVideo.h264")

        for index in range(length):
            camera.annotate_text = (annotate())
            time.sleep(1)
        
        camera.stop_recording()
    except Exception as error:
        print(error)

    os.system("ffmpeg -r " + str(framerate) + " -i /home/pi/testVideo.h264 -vcodec copy " + filename)

    return filename

def sendMail(filename):
    receiver = ["yoimgeorge25@gmail.com", "otheremail@gmail.com"]
    body = "Sent at " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "."

    try:
        gmail = yagmail.SMTP("email@gmail.com", "password")

        gmail.send(
            to = receiver,
            subject = "Paul's Balloon",
            contents = body, 
            attachments = filename
        )
    except Exception as error:
        print(error)

    print("Message sent.")

sendMail(getPicture(annotate()))

Sending Emails in Python

Sending an email in Python with no attachments.

import smtplib, ssl

smtp_server = "smtp.gmail.com"
port = 587  # For starttls
sender_email = "my@gmail.com"
password = input("Type your password and press enter: ")

# Create a secure SSL context
context = ssl.create_default_context()

# Try to log in to server and send email
try:
    server = smtplib.SMTP(smtp_server,port)
    server.ehlo() # Can be omitted
    server.starttls(context=context) # Secure the connection
    server.ehlo() # Can be omitted
    server.login(sender_email, password)
    # TODO: Send email here
except Exception as e:
    # Print any error messages to stdout
    print(e)
finally:
    server.quit() 

Snapping a still image in Python

from picamera import PiCamera
camera = PiCamera()
camera.capture('/home/pi/Desktop/snapshot.jpg')

Raspberry Pi Camera Source

SENDING AN EMAIL WITH AN ATTACHMENT

import email, smtplib, ssl

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

subject = "An email with attachment from Python"
body = "This is an email with attachment sent from Python"
sender_email = "my@gmail.com"
receiver_email = "your@gmail.com"
password = input("Type your password and press enter:")

# Create a multipart message and set headers
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email  # Recommended for mass emails

# Add body to email
message.attach(MIMEText(body, "plain"))

filename = "document.pdf"  # In same directory as script

# Open PDF file in binary mode
with open(filename, "rb") as attachment:
    # Add file as application/octet-stream
    # Email client can usually download this automatically as attachment
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())

# Encode file in ASCII characters to send by email    
encoders.encode_base64(part)

# Add header as key/value pair to attachment part
part.add_header(
    "Content-Disposition",
    f"attachment; filename= {filename}",
)

# Add attachment to message and convert message to string
message.attach(part)
text = message.as_string()

# Log in to server using secure context and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, text)

USING YAGMAIL

import yagmail

receiver = "your@gmail.com"
body = "Hello there from Yagmail"
filename = "document.pdf"

yag = yagmail.SMTP('mygmailusername', 'mygmailpassword')
yag.send(
    to=receiver,
    subject="Yagmail test with attachment",
    contents=body, 
    attachments=filename,
)

pip3 install yagmail 🙂
Source

.h264 to .mp4 Video with MP4Box

MP4 Video Format

The Pi captures video as a raw H264 video stream. Many media players will refuse to play it, or play it at an incorrect speed, unless it is “wrapped” in a suitable container format like MP4. The easiest way to obtain an MP4 file from the raspivid command is using MP4Box.

Install MP4Box with this command:

sudo apt-get install -y gpac

Capture your raw video with raspivid and wrap it in an MP4 container like this:

# Capture 30 seconds of raw video at 640x480 and 150kB/s bit rate into a pivideo.h264 file:
raspivid -t 30000 -w 640 -h 480 -fps 25 -b 1200000 -p 0,0,640,480 -o pivideo.h264 
# Wrap the raw video with an MP4 container: 
MP4Box -add pivideo.h264 pivideo.mp4
# Remove the source raw file, leaving the remaining pivideo.mp4 file to play
rm pivideo.h264

Alternatively, wrap MP4 around your existing raspivid output, like this:

MP4Box -add video.h264 video.mp4

Source

Scheduling Scripts in CRON

Setting up the Pi to run Python scripts

All right, your Pi is up and running, now you just need to configure it to run Python scripts.
The good news is: there’s not much to do if you are using Raspbian, as it has Python installed out of the box
Screen Shot 2018-09-05 at 18.18.11.pngOne thing you can do is download the latest version, probably because Raspbian does not have the latest release. Head over to python.org, and upgrade if necessary.But other than this you are good to go. You can copy your existing .py files and start using them with the built in IDE or Terminal straight away. Speaking of which: if you are copying over files you used on Windows or OS X, remember that on Linux you’ll need a different shebang line. You probably know where to look this up, but here it is for reference:

  • On Windows, the shebang line is #! python3.
  • On OS X, the shebang line is #! /usr/bin/env python3.
  • On Linux, the shebang line is #! /usr/bin/python3.
    (shebang lines are the first lines in python script files that tells the system where to locate the interpreter)

Also, if you want to start scripts from the terminal there are a few extra steps to do:

  • Place them .py files in your home folder
  • Make them executable with the following command: chmod +x script.py
    Now you can start a script by typing in ./script.py to the terminal
    (If you place them somewhere else than your home folder you will have to describe the whole path to start them)

Automating scripts on the Pi with CRON

Now to the interesting part. So far we set up our Pi and started to run python scripts on it. But logging in through RealVNC or SSH every time we want a script to run is not really convenient (with the exception if we want to trigger scripts via SSH coming from another device or service automatically, but this will be detailed in another post).
If we have a web-scraping script that looks for some info on the web every day and returns some information (like the food notifier explained in my previous post), then what we want is total automation. The script should start all by it self, do it’s job, and return the information.
Luckily we can do that with a built in tool in Linux called CRON.

How to setup CRON

  • Log into your Pi with realVNC, and start Terminal.
    RPi Terminal.png
  • In the Terminal, enter crontab -e. If you want a command to run with system permissions, use the sudo crontab -e command to open the root account’s crontab file.
  • You might be asked to select an editor. If this happens choose Nano (for me this was the default)
  • You will be presented with the following screen:
    RPi Terminal crontab.png
    Every line that starts with a # is just a comment and will be not executed.
  • Use the arrows or Page Down to scroll down to the bottom of the page
  • Each line you add here will be executed.

The format for the parameters is the following:
Minutes Hours Day of month Month Weekday Command
If you want to skip a parameter, just add * as input.

From the Raspberry Pi Official API:

Scheduling tasks with Cron

Cron is a tool for configuring scheduled tasks on Unix systems. It is used to schedule commands or scripts to run periodically and at fixed intervals. Tasks range from backing up the user’s home folders every day at midnight, to logging CPU information every hour.

The command crontab (cron table) is used to edit the list of scheduled tasks in operation, and is done on a per-user basis; each user (including root) has their own crontab.

Cron GUI

A graphical application for Cron is available by installing the gnome-schedulepackage:

sudo apt-get install gnome-schedule

You can then launch the program Scheduled Tasks from the main menu.

Editing crontab

Run crontab with the -e flag to edit the cron table:

crontab -e

Select an editor

The first time you run crontab you’ll be prompted to select an editor; if you are not sure which one to use, choose nano by pressing Enter.

Add a scheduled task

The layout for a cron entry is made up of six components: minute, hour, day of month, month of year, day of week, and the command to be executed.

# m h  dom mon dow   command
# * * * * *  command to execute
# ┬ ┬ ┬ ┬ ┬
# │ │ │ │ │
# │ │ │ │ │
# │ │ │ │ └───── day of week (0 - 7) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
# │ │ │ └────────── month (1 - 12)
# │ │ └─────────────── day of month (1 - 31)
# │ └──────────────────── hour (0 - 23)
# └───────────────────────── min (0 - 59)

For example:

0 0 * * *  /home/pi/backup.sh

This cron entry would run the backup.sh script every day at midnight.

View scheduled tasks

View your currently saved scheduled tasks with:

crontab -l

Run a task on reboot

To run a command every time the Raspberry Pi starts up, write @reboot instead of the time and date. For example:

@reboot python /home/pi/myscript.py

This will run your Python script every time the Raspberry Pi reboots. If you want your command to be run in the background while the Raspberry Pi continues starting up, add a space and & at the end of the line, like this:

@reboot python /home/pi/myscript.py &

Raspbian API

Source