ZorrataS
Posts: 1
Joined: Mon Sep 23, 2019 4:24 pm

Permission Denied: Can't run my .py program (Gatttool)

Mon Sep 23, 2019 4:52 pm

I can't run my .py program in terminal. It keeps saying "permission denied",
11.PNG
11.PNG (79.16 KiB) Viewed 115 times
. I even used sudo, now I don't know what to do anymore. I am using backend called gatttool for my miflora. This is the program source code:
P.S. Please help, I really need this for my final year project.

Code: Select all

#!/usr/bin/env python3
from tkinter import *
import argparse
import re
import logging
import sys
import RPi.GPIO as GPIO
import time
import sqlite3
import datetime
import tkinter as tk
import tkinter.font

from btlewrap import available_backends, BluepyBackend, GatttoolBackend, PygattBackend

from miflora.miflora_poller import MiFloraPoller, \
    MI_CONDUCTIVITY, MI_MOISTURE, MI_LIGHT, MI_TEMPERATURE, MI_BATTERY
from miflora import miflora_scanner

##DATABASE
conn = sqlite3.connect('plants.db')
c = conn.cursor()

def create_table():
    c.execute('CREATE TABLE IF NOT EXISTS tblrecord(RID INTEGER PRIMARY KEY AUTOINCREMENT,TEMP TEXT, MOISTURE TEXT, LIGHT TEXT, CONDUCT TEXT, BATT TEXT, xdate TIME)')

def valid_miflora_mac(mac, pat=re.compile(r"C4:7C:8D:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}")):
    """Check for valid mac adresses."""
    if not pat.match(mac.upper()):
        raise argparse.ArgumentTypeError('The MAC address "{}" seems to be in the wrong format'.format(mac))
    return mac

def poll(args):

    """Poll data from the sensor."""        
    while True:
     backend = _get_backend(args)
     poller = MiFloraPoller(args.mac, backend)
     print()
     print("GETTING DATA FROM MI FLORA")
     print("FW: {}".format(poller.firmware_version()))
     print("Name: {}".format(poller.name()))
     print("Temperature: {}".format(poller.parameter_value(MI_TEMPERATURE)))
     print("Moisture: {}".format(poller.parameter_value(MI_MOISTURE)))
     print("Light: {}".format(poller.parameter_value(MI_LIGHT)))
     print("Conductivity: {}".format(poller.parameter_value(MI_CONDUCTIVITY)))
     print("Battery: {}".format(poller.parameter_value(MI_BATTERY)))
     dtx = time.time()
     print()
     print()
     time.sleep(2)
     print("                 RECORD HISTORY                   ")
     print("--------------------------------------------------")
     data_insert(poller.parameter_value(MI_TEMPERATURE), poller.parameter_value(MI_MOISTURE), poller.parameter_value(MI_LIGHT), poller.parameter_value(MI_CONDUCTIVITY), poller.parameter_value(MI_BATTERY), str(datetime.datetime.fromtimestamp(dtx).strftime('%Y-%m-%d %H:%M:%S')))
     loadData()
     print("--------------------------------------------------")
     time.sleep(2)
     

def data_insert(temp, moist, light, conduct, batt, dt):
    c.execute("INSERT INTO tblrecord(temp, moisture, light, conduct, batt, xdate)VALUES(?, ?, ?, ?, ?, ?)", (temp, moist, light, conduct, batt, dt))
    conn.commit()

def loadData():
    c.execute('SELECT * FROM tblrecord')
    for row in c.fetchall():
      print(row)

def scan(args):
    """Scan for sensors."""
    backend = _get_backend(args)
    print('Scanning for 10 seconds...')
    devices = miflora_scanner.scan(backend, 10)
    print('Found {} devices:'.format(len(devices)))
    for device in devices:
        print('  {}'.format(device))


def _get_backend(args):
    """Extract the backend class from the command line arguments."""
    if args.backend == 'gatttool':
        backend = GatttoolBackend
    elif args.backend == 'bluepy':
        backend = BluepyBackend
    elif args.backend == 'pygatt':
        backend = PygattBackend
    else:
        raise Exception('unknown backend: {}'.format(args.backend))
    return backend


def list_backends(_):
    """List all available backends."""
    backends = [b.__name__ for b in available_backends()]
    print('\n'.join(backends))


def main():
    """Main function.

    Mostly parsing the command line arguments.
    """
    create_table()
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(22, GPIO.OUT)
    GPIO.setup(17, GPIO.OUT)
    GPIO.setup(27, GPIO.OUT)
    GPIO.setup(23, GPIO.OUT)
    GPIO.setup(24, GPIO.OUT)
    GPIO.output(17, True) #OFF RELAY
    GPIO.output(27, True)
    GPIO.output(23, True)
    GPIO.output(24, True)
    time.sleep(1)
    parser = argparse.ArgumentParser()
    parser.add_argument('--backend', choices=['gatttool', 'bluepy', 'pygatt'], default='gatttool')
    parser.add_argument('-v', '--verbose', action='store_const', const=True)
    subparsers = parser.add_subparsers(help='sub-command help', )

    parser_poll = subparsers.add_parser('poll', help='poll data from a sensor')
    parser_poll.add_argument('mac', type=valid_miflora_mac)
    parser_poll.set_defaults(func=poll)

    parser_scan = subparsers.add_parser('scan', help='scan for devices')
    parser_scan.set_defaults(func=scan)

    parser_scan = subparsers.add_parser('backends', help='list the available backends')
    parser_scan.set_defaults(func=list_backends)

    args = parser.parse_args()
    
    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)

    if not hasattr(args, "func"):
        parser.print_help()
        sys.exit(0)

    args.func(args)


def closeprogram():
    window.destroy()

window = tk.Tk()
window.title("Plant Environment Form")
window.configure(background='white')
window.wm_attributes("-fullscreen", True)

labelT = Label(window, text = "Greenhouse Plant Environment Monitoring", fg='green', bg='yellow', relief = "solid", width=50, font = ("arial",19,"bold"))
labelT.place(x=355, y=25)

btnQuit = Button(window, text="Quit", width=12, bg='brown', fg='white')
btnQuit.place(x=1140, y=660)

frameMntrng = LabelFrame(window, text="Monitoring", padx=15, pady=15, font = ("arial",15,"bold"), bg='white')
frameMntrng.place(x=80, y=130)

frameMi = LabelFrame(frameMntrng, text="Mi Flora", padx=15, pady=15, bg='white')
frameMi.grid(row=1, column=1)

frameDht = LabelFrame(frameMntrng, text="DHT22", padx=15, pady=15, bg='white')
frameDht.grid(row=2, column=1)

frameSetup = LabelFrame(window, text="Setup", padx=15, pady=15, font = ("arial",15,"bold"), bg='white')
frameSetup.place(x=500, y=130)


#put items in label frame Mi Flora
# lab = Label, Mi = Miflora, Dht = DHT22

labMiMois = Label(frameMi, text = "Soil Moisture: ", width = 20, font = ("arial",10,"bold"), padx=10, pady=10, bg='white')
labMiMois.grid(row=1, column=1)

labMiTemp = Label(frameMi, text = "Soil Temperature: ", width = 20, font = ("arial",10,"bold"), padx=10, pady=10, bg='white')
labMiTemp.grid(row=2, column=1)

labMiCon = Label(frameMi, text = "Soil Conductivity: ", width = 20, font = ("arial",10,"bold"), padx=10, pady=10, bg='white')
labMiCon.grid(row=3, column=1)

labMiLight = Label(frameMi, text = "Light: ", width = 20, font = ("arial",10,"bold"), padx=10, pady=10, bg='white')
labMiLight.grid(row=4, column=1)

MiMois = Label(frameMi, text = "--", width = 20, font = ("arial",10,"bold"), padx=10, pady=10, bg='white')
MiMois.grid(row=1, column=2)

MiTemp = Label(frameMi, text = "--", width = 20, font = ("arial",10,"bold"), padx=10, pady=10, bg='white')
MiTemp.grid(row=2, column=2)

MiCon = Label(frameMi, text = "--", width = 20, font = ("arial",10,"bold"), padx=10, pady=10, bg='white')
MiCon.grid(row=3, column=2)

MiLight = Label(frameMi, text = "--", width = 20, font = ("arial",10,"bold"), padx=10, pady=10, bg='white')
MiLight.grid(row=4, column=2)


#put items in label frame DHT22
# lab = Label, Mi = Miflora, Dht = DHT22

labDhtHum = Label(frameDht, text = "Humidity: ", width = 20, font = ("arial",10,"bold"), padx=10, pady=10, bg='white')
labDhtHum.grid(row=1, column=1)

labDhtTemp = Label(frameDht, text = "Temperature: ", width = 20, font = ("arial",10,"bold"), padx=10, pady=10, bg='white')
labDhtTemp.grid(row=2, column=1)

DhtHum = Label(frameDht, text = "--", width = 20, font = ("arial",10,"bold"), padx=10, pady=10, bg='white')
DhtHum.grid(row=1, column=2)

DhtTemp = Label(frameDht, text = "--", width = 20, font = ("arial",10,"bold"), padx=10, pady=10, bg='white')
DhtTemp.grid(row=2, column=2)


#put items in frameSetup

#Table Title

labSParam = Label(frameSetup, text = "Parameters", width = 20, font = ("arial",10,"bold"), relief='solid', padx=10, pady=10, bg='white')
labSParam.grid(row=1, column=1)

labSChnge = Label(frameSetup, text = "Change", width = 20, font = ("arial",10,"bold"), relief='solid', padx=10, pady=10, bg='white')
labSChnge.grid(row=1, column=2)

labSCrrnt = Label(frameSetup, text = "Current", width = 20, font = ("arial",10,"bold"), relief='solid', padx=10, pady=10, bg='white')
labSCrrnt.grid(row=1, column=3)

#Labels Parameters

labSMiMois = Label(frameSetup, text = "Soil Moisture: ", width = 20, font = ("arial",10,"bold"), padx=10, pady=10, bg='white')
labSMiMois.grid(row=2, column=1)

labSMiCon = Label(frameSetup, text = "Soil Conductivity: ", width = 20, font = ("arial",10,"bold"), padx=10, pady=10, bg='white')
labSMiCon.grid(row=3, column=1)

labSDhtHum = Label(frameSetup, text = "Humidity: ", width = 20, font = ("arial",10,"bold"), padx=10, pady=10, bg='white')
labSDhtHum.grid(row=4, column=1)

#Labels Current (Displays current desired value of soil moisture, soil conductivity, and humidity)

labSCMiMois = Label(frameSetup, text = "--", width = 20, font = ("arial",10,"bold"), padx=10, pady=10, bg='white')
labSCMiMois.grid(row=2, column=3)

labSCMiCon = Label(frameSetup, text = "--", width = 20, font = ("arial",10,"bold"), padx=10, pady=10, bg='white')
labSCMiCon.grid(row=3, column=3)

labSCDhtHum = Label(frameSetup, text = "--", width = 20, font = ("arial",10,"bold"), padx=10, pady=10, bg='white')
labSCDhtHum.grid(row=4, column=3)

#Entry (The user can input the value they want to replace the current desired value of...
# ... soil moisture, soil conductivity, and humidity)

enSMiMois = Entry(frameSetup, width = 20, font = ("arial",10,"bold"), bg='white')
enSMiMois.grid(row=2, column=2)

enSMiCon = Entry(frameSetup, width = 20, font = ("arial",10,"bold"), bg='white')
enSMiCon.grid(row=3, column=2)

enSDhtHum = Entry(frameSetup, width = 20, font = ("arial",10,"bold"), bg='white')
enSDhtHum.grid(row=4, column=2)

#Buttons

btnChange = Button(frameSetup, text="Enter", width=12, bg='grey', fg='white')
btnChange.grid(row=5, column=2)

main()
window.mainloop()





Kendek
Posts: 145
Joined: Thu Jul 25, 2019 4:39 pm
Location: Kaposvár, Hungary

Re: Permission Denied: Can't run my .py program (Gatttool)

Mon Sep 23, 2019 5:04 pm

Code: Select all

chmod +x prjMiFlora.py
./prjMiFlora.py
or

Code: Select all

python3 prjMiFlora.py

Return to “Troubleshooting”