lexfp / fpvradar

Raspberry pi & SDR dongle combined to notify you if aircraft are close by
11 stars 5 forks source link

Python3 support #1

Closed blurcak closed 2 years ago

blurcak commented 2 years ago

Hi, very nice project, i was waiting for Bruce to release his product (still waiting :) ) I have problem running your script im using Bullsyey + Python3 and im getting some errors thx

● fpvradar.service - FPV Radar Service Loaded: loaded (/lib/systemd/system/fpvradar.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Tue 2022-06-14 20:27:02 CEST; 5min ago Process: 515 ExecStart=/usr/bin/python /home/pi/fpvradar/fpvradar.py (code=exited, status=1/FAILURE) Main PID: 515 (code=exited, status=1/FAILURE) CPU: 595ms

Jun 14 20:27:00 PiAware systemd[1]: Started FPV Radar Service. Jun 14 20:27:02 PiAware python[515]: File "/home/pi/fpvradar/fpvradar.py", line 64 Jun 14 20:27:02 PiAware python[515]: return (lastKnownLat, lastKnownLon) Jun 14 20:27:02 PiAware python[515]: TabError: inconsistent use of tabs and spaces in indentation Jun 14 20:27:02 PiAware systemd[1]: fpvradar.service: Main process exited, code=exited, status=1/FAILURE Jun 14 20:27:02 PiAware systemd[1]: fpvradar.service: Failed with result 'exit-code'.

lexfp commented 2 years ago

looks like you may have modified the file and added/removed some spaces. If you wish to make modifications, you should learn how spacing works in python so you can modify it correctly.

blurcak commented 2 years ago

hmm tried 2to3 still same error only thing i was able to fix is

File "/home/pi/fpvradar/fpvradar.py", line 59 print "NON TPV gps class encountered: "+nx['class'] ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print("NON TPV gps class encountered: "+nx['class'])?

coding is not my cup of coffe and im too old for this. Thx

lexfp commented 2 years ago

Make sure you have python 2.7.16 installed (python -V)

blurcak commented 2 years ago

After some digging i was able to manualy install P2.7.16 (tarball) with all needed modules with PIP. But its PiA :) On RaspiOs is 2.7 EoL and especialy PIP.

oh and for Skyaware7.2 there is change in DUMP1090_URL = 'http://127.0.0.1/skyaware/data/aircraft.json'

Thx the script is working now.

lexfp commented 2 years ago

Unfortunately, things do keep changing. Glad you got it working though!

TTN- commented 1 year ago

Use the 4.0 release: https://piaware.flightcdn.com/piaware-sd-card-4.0.img.zip

When doing apt-get update you'll need to do: sudo apt-get update --allow-releaseinfo-change

Following the rest of the guide everything goes well right up until I needed to check the service status with:

It had an issue with the colorzero python2.7 module being missing which is a pain in the bum. It was easier to change how the buzzer was controlled than to fiddle with dependancies. Changed fpvradar.py import and buzz() function. instead of listing edits, have a copy of the file as it is now:

import requests
import geopy.distance
import time
import sys
from gps import *
from time import sleep
#from gpiozero import Buzzer
import RPi.GPIO as GPIO
from datetime import datetime

#This code is released under the terms of the unlicense: https://unlicense.org/
#Author github.com/lexfp

# Disclaimer: This code is not pretty. It is written like a script since that is what it is.
DUMP1090_URL = 'http://127.0.0.1/dump1090-fa/data/aircraft.json'
UNKNOWN = 'Unknown'
LATITUDE = 'lat'
LONGTITUDE = 'lon'
BUZZER_PIN = 17
# seconds between each check
INTERVAL_SECONDS = 3
# set this to false if you don't want a long beep on initial gps lock
initialGPSLockBeep=True
# I keep this value large so I know the app is running since it will always beep once.
# you can set the value lower to have a quieter system and a 3rd perimeter
OUTER_PERIMETER_ALARM_MILES = 100
# middle perimeter trigger sets of 2 beeps
MIDDLE_PERIMETER_ALARM_MILES = 5
# inner perimeter trigger sets of 3 beeps
INNER_PERIMETER_ALARM_MILES = 2
# upper limit of altitude at which you want to monitor aircraft
ALTITUDE_ALARM_FEET = 1000
running = True
gpsd = gps(mode=WATCH_ENABLE | WATCH_NEWSTYLE)

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(BUZZER_PIN, GPIO.OUT, initial=GPIO.LOW)

lastKnownLat=UNKNOWN
lastKnownLon=UNKNOWN
# the number of iterations we should try to reuse the last known position
# set this to -1 if you plan on relocating the unit to a location with poor GPS
# reception once initial position is established and you don't plan on moving around
# then it will never need the GPS coordinates again if they are not available
LAST_KNOWN_POSITION_REUSE_TIMES = 3
lastKnownPosReuse=0
failedGPSTries=0

def getPositionData(gps):
    nx = gpsd.next()
    # For a list of all supported classes and fields refer to:
    # https://gpsd.gitlab.io/gpsd/gpsd_json.html
    global lastKnownLat
    global lastKnownLon
    global lastKnownPosReuse
    if nx['class'] == 'TPV':
        lastKnownLat = getattr(nx, LATITUDE, UNKNOWN)
        lastKnownLon = getattr(nx, LONGTITUDE, UNKNOWN)
        lastKnownPosReuse=0 #reset counter since we refreshed coords
        #print "Your position: lon = " + str(longitude) + ", lat = " + str(latitude)
        return (lastKnownLat, lastKnownLon)
    else:
        print "NON TPV gps class encountered: "+nx['class']
        if LAST_KNOWN_POSITION_REUSE_TIMES < 0:
            return (lastKnownLat, lastKnownLon)
        elif lastKnownPosReuse < LAST_KNOWN_POSITION_REUSE_TIMES:
            lastKnownPosReuse += 1
            return (lastKnownLat, lastKnownLon)
        else:
            return(UNKNOWN,UNKNOWN)

def buzz(wait=0.1):
    GPIO.setup(BUZZER_PIN, GPIO.OUT, initial=GPIO.HIGH)
    sleep(wait)
    GPIO.setup(BUZZER_PIN, GPIO.OUT, initial=GPIO.LOW)
    sleep(0.2)

def checkRadar():
    global failedGPSTries
    global gpsd
    homecoords = getPositionData(gpsd)
    print homecoords
    if (homecoords[0] == UNKNOWN) or (homecoords[1] == UNKNOWN):
        #print "Cannot determine GPS position yet...try #"+str(failedGPSTries)
        #sleep(1)
        failedGPSTries += 1
        if failedGPSTries > 10:
            print "Too many failed GPS tries, initializing new GPS object..."
            failedGPSTries = 0
            gpsd = gps(mode=WATCH_ENABLE | WATCH_NEWSTYLE)
        return
    global initialGPSLockBeep
    if initialGPSLockBeep == True:
        initialGPSLockBeep=False
        buzz(1)
        sleep(5)
    r = requests.get(DUMP1090_URL)
    try:
        airplanes = r.json()
    except:
        #print 'Error while getting airplane data'
        return
    outerAlarmTriggered = False
    middleAlarmTriggered = False
    innerAlarmTriggered = False
    for airplane in airplanes['aircraft']:
        try:
            altitude = airplane["alt_baro"]
            planecoords = (airplane[LATITUDE], airplane[LONGTITUDE])
            distanceToPlane = geopy.distance.vincenty(homecoords, planecoords).miles
            if altitude < ALTITUDE_ALARM_FEET:
                if distanceToPlane < INNER_PERIMETER_ALARM_MILES:
                    innerAlarmTriggered = True
                    print 'Inner alarm triggered by '+airplane['flight']+' at '+str(datetime.now())+' with distance '+str(distanceToPlane)
                elif distanceToPlane < MIDDLE_PERIMETER_ALARM_MILES:
                    middleAlarmTriggered = True
                    print 'Middle alarm triggered by '+airplane['flight']+' at ' +str(datetime.now())+' with distance '+str(distanceToPlane)
                elif distanceToPlane < OUTER_PERIMETER_ALARM_MILES:
                    outerAlarmTriggered = True
                    print 'Outer alarm triggered by '+airplane['flight']+' at ' +str(datetime.now())+' with distance '+str(distanceToPlane)
        except KeyError:
            pass
    if innerAlarmTriggered:
        buzz()
        buzz()
        buzz()
    elif middleAlarmTriggered:
        buzz()
        buzz()
    elif outerAlarmTriggered:
        buzz()

try:
    print "Application started!"
    while running:
        checkRadar()
        sys.stdout.flush()
        time.sleep(INTERVAL_SECONDS)

except (ValueError):
        #sometimes we get errors parsing json
    pass

except (KeyboardInterrupt):
    running = False
    print "Applications closed!"

except:
    print "Caught generic exception - continuing"
    sys.stdout.flush()
    pass