User avatar
rpdom
Posts: 15589
Joined: Sun May 06, 2012 5:17 am
Location: Chelmsford, Essex, UK

Re: Program not running

Fri Mar 16, 2018 9:18 pm

No "except:" for your "try:" block?

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: Program not running

Fri Mar 16, 2018 9:28 pm

:facepalm: whoops. Thanks. Felt like I was forgetting something and couldn't figure out what, but i got it figured now.

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: Program not running

Fri Mar 16, 2018 10:02 pm

Code: Select all

#Imports
import RPi.GPIO as GPIO
import time

#RPi Board Setup
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)

#Control Pin List
pinList = [33, 37]

#Loop through pins, set mode/state to HIGH
for i in pinList:
    GPIO.setup(i, GPIO.OUT)
    GPIO.output(i, GPIO.HIGH)

#Set time between ML functions
DownTime = 2

#Main Loop
try:
    GPIO.output(33, GPIO.LOW)
    print("Alpha")
    time.sleep(DownTime);
    GPIO.output(37, GPIO.LOW)
    print("Bravo")
    time.sleep(DownTime);
    GPIO.cleanup()
    print("Good-Bye!")
Now if i removed the time setting, and main loop to be replaced by

Code: Select all

#Loop through pins, set mode/state to HIGH
for i in pinList:
    GPIO.setup(i, GPIO.OUT)
    GPIO.output(i, True)
the relay would remain on until the keystroke or power down right?

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: Program not running

Fri Mar 16, 2018 10:31 pm

Code: Select all

#Imports
import RPi.GPIO as GPIO
import time

#RPi Board Setup
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)

#Control Pin List
pin = 33
GPIO.setup(pin, GPIO.OUT)

try:
     GPIO.output(pin, GPIO.LOW)
     print("Done")
except KeyboardInterrupt:
     print("You quitter!")
     
     GPIO.cleanup() 
This code indefinitely turns on the relay until powering down the Pi. Now I am going to integrate coding this into the user functions within my security coding. Is it best to do 'import', or code directly into the security script?

How would I go about using 'import' correctly if it is the better way do this via multiple scripts?

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: Program not running

Sat Mar 17, 2018 1:29 am

Ok, so i have defined the functions for the users. But I have hit a snag.
The current script for my User selection Password verify needs some tweaking.

Based on this:

Code: Select all

result = check_keypad(1)
while(result != "1") and (result != "2"):
        result = check_keypad(1)
user = "User" + result

#Users
if user== "User1":
    print("       ----------------------------")
    print("       |       Welcome User!!     |")
    print("       ----------------------------")
    password = "A1234"
    length = len(password)

if user == "User2":
    print("       ----------------------------")
    print("       |       Welcome User!!     |")
    print("       ----------------------------")
    password = "B5678"
    length = len(password)

#Password From KeyPad
print("    ----------------------------------")
print("    |   Please Enter User Password:  |")
print("    ----------------------------------")
result = check_keypad(length)

#print('Password Entered: "{entry}"'.format(entry = result))
usernames = {'User1': "Maker",
             'User2': "Guest"}

#Password Check
if result == password:
    print("    ----------------------------------")
    print("    |         Welcome {name}!!        |" .format(name=usernames[user]))
    print("    ----------------------------------")

else:
    print("    ----------------------------------")
it only verifies the user, but idk how specify which user has which functions when the correct password is entered.

and here is the defined relay function code:

Code: Select all

def bravoRelay():
    GPIO.setmode(GPIO.BOARD)
    GPIO.setwarnings(False)

    #Identufy Relay Signal Pin
    pin = **your wired pin goes here**
    GPIO.setup(pin, GPIO.OUT)

    #Function
    try:
        GPIO.output(pin, GPIO.LOW)
        print("    ----------------------------------")
        print("    |        Relay Is Active!!!      |")
        print("    ----------------------------------")
    except KeyboardInterrupt:
        print("Quitting Is For Losers!!!")

        GPIO.cleanup()

User avatar
Paeryn
Posts: 2745
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: Program not running

Sat Mar 17, 2018 1:36 am

StangPi wrote:
Fri Mar 16, 2018 10:31 pm
How would I go about using 'import' correctly if it is the better way do this via multiple scripts?
You can sort of think of import as running the imported file at that point in your code but with a few things slightly changed (there may be more but off the top of my head),
  1. Imported modules are only run the first time they appear in your program no matter whether you import them or another module imports them.
  2. Things declared globally in the module are created as members of the module (you still use them as globals within the module itself, it's how others see them that changes).
From point 1, if you define and initialise a global object in your module and import the module twice, the object only gets initialised the first time. Any other time it is imported the object will keep whatever value it has.
From point 2, it changes how you refer to those objects in your code that imports a module (usually, you can have objects created that reference the module's objects but be careful doing that, the created objects are just references, if you change these object's values you don't change the ones in the module).

E.g.
testing.py

Code: Select all

## Module testing.py
counter = 1

def increment():
  global counter
  counter = counter + 1

def display():
  global counter
  print('Counter = {value}'.format(value=counter))

print('Module testing imported')
example.py

Code: Select all

# example.py
import testing

testing.display()
testing.increment()
testing.display()

import testing
testing.display()
Running example.py gives the following output

Code: Select all

[email protected]:~/Programming/pyth/stang $ python3 example.py
Module testing imported
Counter = 1
Counter = 2
Counter = 2
You can see that the module is only run once as it only prints Module testing imported the first time and also the counter still shows the value it had before the second import.
Also it shows that to call the functions in testing.py you have to give the module name before it (just like you do with time, etc.). You can change the name you use for the module object in your code by using import ... as ... like you do with import RPi.GPIO as GPIO, e.g.

Code: Select all

import testing as my_test
my_test.display()  # We now refer to testing as my_test
If you want to use the object names from the module directly in your main code (without having to use the module name) then you use

Code: Select all

from testing import display
display()  # We don't have to use the module name
This only makes available the objects you specify (though you can use * to import (just about) everything). Generally you don't want to do this though, it might look like less to type is better but having separate namespaces is a big advantage especially as your projects get bigger. Think of it as for special cases only, and then only when you understand the implications.
She who travels light — forgot something.

User avatar
Paeryn
Posts: 2745
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: Program not running

Sat Mar 17, 2018 2:06 am

StangPi wrote:
Sat Mar 17, 2018 1:29 am
Ok, so i have defined the functions for the users. But I have hit a snag.
The current script for my User selection Password verify needs some tweaking.

<snipped code>

it only verifies the user, but idk how specify which user has which functions when the correct password is entered.
It depends on how you want to do things, from the point where you have verified the user's password is correct you currently have user holding the string Userx where x is the number of the user. You could just use that and have separate functions to handle each user's options (showing them their own menus, only accepting choices they can do, etc.), e.g.

Code: Select all

if user == 'User1':
  process_user1_options()
elif user == 'User2':
  process_user2_options()
## continue for more users if needed
You can use user to decide if they are allowed to run things when they try, e.g.

Code: Select all

bravoRelayAllowedUsers = ['User1', 'User3']  # Only allow User1 and User3 to run bravoRelay()

if user in bravoRelayAllowedUsers:
  bravoRelay()
else:
  print('Sorry, you are not authorised to switch the relay on')
She who travels light — forgot something.

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: Program not running

Sat Mar 17, 2018 2:13 am

Got it working:

Code: Select all

#print('Password Entered: "{entry}"'.format(entry = result))
usernames = {'User1': "Maker",
             'User2': "Guest"}

#Password Check
if result == password:
    print("    ----------------------------------")
    print("    |         Welcome {name}!!        |" .format(name=usernames[user]))
    print("    ----------------------------------")

else:
    print("    ----------------------------------")
In this bit of code, specifically in the #Password Check I added this:

Code: Select all

#Password Check
if result == password:
    print("    ----------------------------------")
    print("    |         Welcome {name}!!        |" .format(name=usernames[user]))
    print("    ----------------------------------")
    
    if user == "User1":
       alphaRelay.alphaRelay()

else:
    print("    ----------------------------------")
it works, relay clicks and my test light does come on. think i may combine relay modules into one module for easier import.

amino2111
Posts: 1
Joined: Sat Mar 17, 2018 12:53 pm

Re: Program not running

Sat Mar 17, 2018 12:56 pm

i use this software all the time try it : wxpython :D ;) ;)

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: Program not running

Sun Mar 18, 2018 6:02 pm

The next issue I am working on, is creating new users.

Code: Select all

print("Please Make User Selection!")
result = check_keypad(1)
	while(result != "1") and (result != "2"):
	result =  check_keypad(1)
user = "User" + result
with this snippit, the user is designated and once their password is entered correctly they will have their own functions either automatic or manually controlled.

Instead of using:

Code: Select all

 while(result != "1") and (result != "2"): 
, what other way could it be done. i did try

Code: Select all

 while(result != "1"||"2")
and also by separating the numbers with commas and neither worked. Odds are I may have to stick with the original way. also if i wanted to have double digits user selectors (21, 22, etc etc), would I import float?

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: Program not running

Thu Sep 27, 2018 1:03 am

Hello everyone, it has been quite awhile since i posted in this thread. Hope everyone is well, and doing good things :)

So far I have made significant progress on my project. It now talks back to me telling me what choice i have made, nd various greetings to each user. All via flite

Currently my newest update to this project is to have my security script as a seperate module, which in turn would have its own modules.

Starting script opens and there are 4 choices: A, B, C, d. Upon selecting A, it takes me to the security module. In the security module, when i make a user selection i should be prompted to enter the password for that user but instead i get this error:

Code: Select all

Traceback (most recent call last):
  File "ProgramName.py", line 64, in <module>
    projectPi.projectPi()
  File "/home/pi/Desktop/Testing Ground/projectPi.py", line 64, in projectPi
    result = check_keypad(1)
  File "/home/pi/Desktop/Testing Ground/projectPi.py", line 51, in projectPi
    GPIO.out(COL[j], 1)
AttributeError: 'module' object has no 'ouput'
Both the starting script, and security module have this keypad checking code:

Code: Select all

# GPIO setup
GPIO.setmode (GPIO.BOARD)
GPIO.setwarnings(False)
COL = [7,11,13,15]
ROW = [12,22,29,31]
 
for j in range(4):
    GPIO.setup(COL[j], GPIO.OUT)
    GPIO.output (COL[j], 1)
    GPIO.setup(ROW[j], GPIO.IN, pull_up_down = GPIO.PUD_UP)
    
# function for checking keypad input    
def check_keypad(length):

    COL = [7,11,13,15]
    ROW = [12,22,29,31]

    MATRIX = [["1","2","3","A"],
              ["4","5","6","B"],
              ["7","8","9","C"],
              ["0","F","E","D"]] 
    result = "" 
    while(True):
        for j in range(4):
            GPIO.output(COL[j],0)

            for i in range(4):
                if GPIO.input(ROW[i]) == 0:
                    time.sleep(0.02)
                    result = result + MATRIX [i][j]
                    while(GPIO.input(ROW[i]) == 0):
                        time.sleep(0.02)
                     
            GPIO.output(COL[j],1)
            if len(result) >= length:
                return result
I can only guess that somewhere in the starting script, it is somehow hindering the security module to fully utilize the keypad checking code.

Any help would be appreciated.

User avatar
Paeryn
Posts: 2745
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: Program not running

Thu Sep 27, 2018 1:49 am

StangPi wrote:
Thu Sep 27, 2018 1:03 am
Starting script opens and there are 4 choices: A, B, C, d. Upon selecting A, it takes me to the security module. In the security module, when i make a user selection i should be prompted to enter the password for that user but instead i get this error:

Code: Select all

Traceback (most recent call last):
  File "ProgramName.py", line 64, in <module>
    projectPi.projectPi()
  File "/home/pi/Desktop/Testing Ground/projectPi.py", line 64, in projectPi
    result = check_keypad(1)
  File "/home/pi/Desktop/Testing Ground/projectPi.py", line 51, in projectPi
    GPIO.out(COL[j], 1)
AttributeError: 'module' object has no 'ouput'
The last line of the error looks wrong given the line it says it is on, it should say

Code: Select all

AttributeError: 'module' object has no attribute 'out'
as the line it is complaining about says

Code: Select all

GPIO.out(COL[j], 1)
If the line of code it printed is what is really what is in the file and you wrote the error line wrongly when pasting it on here (likely as you also missed out the word attribute in the error message) then that makes sense, the function is GPIO.output() but you have GPIO.out().
Python3 gives a better error in that it correctly names RPi.GPIO as not having the attribute rather than the vague module.
She who travels light — forgot something.

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: Program not running

Thu Sep 27, 2018 1:55 am

-.- thanks lol i retyped that whole error message and didnt realize i copied the mistakes lol

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: Program not running

Sun Apr 14, 2019 8:58 pm

Now i am working on encrypting my passwords.

Here:https://blog.tecladocode.com/learn-pyth ... d-passlib/
is where i found something i think work.

It shows to install passlib which uses CryptContext. Once CryptContext is installed i can encrypt or decrypt my passwords.

Code: Select all

def encrypt_password(password):
    return pwd_context.encrypt(password)


def check_encrypted_password(password, hashed):
    return pwd_context.verify(password, hashed)
Still reading how to use CryptContext, but any visual examples would help me understand. Thank you for any help.

Return to “Python”