Raspberry Pi 3 Web Polling - python-3.x

import RPi.GPIO as GPIO
import urllib.request
import urllib.response
import urllib.error
GPIO.setmode (GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(40,GPIO.OUT)
true = 1
while(true):
try:
response = urllib.request.urlopen('xxxxxxxxxx')
status = response.read()
except urllib.error.HTTPError as e:
print (e.code)
except urllib.error.HTTPError as e:
print (e.args)
print (status)
if status=='ON':
print ("setting GPIO 40 ")
GPIO.output(40,True)
elif status=='OFF':
GPIO.output(40,False)
Error im getting is status is not defined. If i define status as a empty string, the output is not displaying. I am trying to control my Rpi GPIO using a website. I used this link as guidance https://medium.com/#softxide/remote-control-raspberrypi-leds-from-web-browser-ui-84205993b98f.
Thank u in advanced.

Related

Rotary encoder value looking sticky after using tkinter function " root.after"

I am quite new to python and tkinter ,I am working on a project where i give demand to slave device through rotary encoder value and reading feedback value from slave devices through communication.
I face issue when i use root.after () function .
Any suggestion regarding proper use of root.after () function so that my interrupt routine not affected welcome heartly.
Thank you.
Here is my code.
import pigpio
import tkinter as tk
from PIL import ImageTk,Image
import time
from RPi import GPIO
import serial
i="*00T%"
j="*01T%"
s=serial.Serial(port='/dev/ttyS0',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1)
class decoder: # class for decoding rotary encoder
def __init__(self, pi, gpioA, gpioB, callback):
----------
---------------
----------------
if __name__ == "__main__":
import RPi.GPIO as GPIO
import time
import pigpio
import tkinter as tk
import board
import busio
rpm=0
tor=0
pow=0
pi = pigpio.pi()
st=1
pos=0
def callback(way): # interrupt event sense on pin no 17,18
global pos
global st
if st ==1:
pos += way
if pos >= 9999:
pos=9999
if pos <= 0:
pos=0
var.set(pos)
print("pos={}".format(pos))
def rpm_update():
global rpm
s.write(str.encode(i))
print(i)
time.sleep(0.2)
if s.inWaiting():
rpm=s.readline(s.inWaiting())
rpm=rpm.decode('utf-8',errors='ignore')
rpm=rpm[5:-1]
print(rpm)
var2.set(rpm)
def tor_update():
global tor
s.write(str.encode(j))
print(j)
time.sleep(0.2)
if s.inWaiting():
tor=s.readline(s.inWaiting())
tor=tor.decode('utf-8',errors='ignore')
tor=tor[4:-1]
print(tor)
var3.set(tor)
def pow_update():
global rpm,tor,pow
try:
rpm=float(rpm)
tor=float(tor)
except ValueError:
pass
pow=int(rpm*tor/5252)
var4.set(pow)
def update():
rpm_update()
time.sleep(0.5)
tor_update()
time.sleep(0.5)
pow_update()
root.after(1000,update)
path="/home/pi/logo.png"
root=tk.Tk()
img=ImageTk.PhotoImage(Image.open(path))
panel=tk.Label(root,image=img)
panel.pack()
panel.place(x=195,y=10,height=50,width=80)
root.title("Dynalec")
root.geometry("500x600")
{
body of tkinter screen
}
decoder=decoder(pi, 17, 18, callback)
root.after(1000,update)
root.mainloop()
everything is working fine before root.after() function " root.after(1000,update)
but i need it because i have to read slave values in every sec and update in gui screen.
Adding as a answer because long for comments, will remove soon.
Try this out:
def update():
root.after(500,rpm_update)
root.after(500,tor_update)
root.after(500,pow_update)
root.after(1000,update)
Do let me know.

Why is my code not reaching the While Loop to register my Voice Assistant Wakeword?

I'm creating a Voice Assistant using Python. I'm using pyttsx3 for Text-to-Speech and I have a wakeword set up to activate the Voice Assistant. I'm using the Voice Assistant to do things such as read my calendar and such in a While Loop. But suddenly, the wakeword stops working. What is stopping my code from reaching the While Loop and the rest of the code?
Here is some of the code for my project:
from __future__ import print_function
import subprocess
import pytz
import speech_recognition as sr
import pyttsx3
import time
import os
import datetime
import pickle
import os.path
def speak(text):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
said = ""
try:
said = r.recognize_google(audio)
print(said)
except Exception as e:
print("Exception: " + str(e))
return said.lower()
WAKE = "Jarvis"
print("Jarvis is ready")
while True:
print("Jarvis is listening...")
text = get_audio()
if text.count(WAKE) > 0:
speak("Hello Sir, what would you like?")
text = get_audio()
DONE = ["never mind", "goodbye", "I'm done now"]
for phrase in DONE:
if phrase in text:
speak("Alright sir. Goodbye!")
quit()
NOTE_STRS = ["make a note", "write this down", "remember this"]
for phrase in NOTE_STRS:
if phrase in text:
speak("Sure. What would you like me to write down?")
note_text = get_audio()
note(note_text)
speak("Done Sir. I've made a note of that.")
TIME = ["time"]
for phrase in TIME:
if phrase in text:
import datetime
now = datetime.datetime.now()
speak("The current time is %d hours %d minutes" % (now.hour, now.minute))
Please tell me if any code is missing and I can send it to help solve the problem!
HyperionBlaze - What is happening with authenticate_google(). Is there any exception on that call?

python module keep crashing

I am trying to create a doorbell with a raspberry pi zero. When I press the button it will send a picture to telegram. The module works but, after a few pressed the button the module crash.
and see an error in terminal:
* Error in `python3': double free or corruption (out): 0x01f306e8 *
or I get this error:
python3: malloc.c:2406: sysmalloc: Assertion `(old_top == initial_top
(av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE &&
prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) ==
0)' failed.
I hope somebody know how to fix the problem
thanks alot!
python
import time
import random
import datetime
import telepot
from telepot.loop import MessageLoop
from picamera import PiCamera
import pygame
from settings import getstring
import RPi.GPIO as GPIO
camera = PiCamera()
bot = telepot.Bot('TOKEN')
ring = 'tones/doorbell.mp3'
pin = 22
pressed = 0
pygame.mixer.init()
pygame.mixer.music.load(ring)
def sendpic(chat_id):
camera.resolution = (1024, 768)
camera.capture('snapshots/test.jpg')
photo = open('snapshots/test.jpg', 'rb')
bot.sendPhoto(chat_id, photo)
def handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
print('Got command: %s' % command)
if command == '/roll':
bot.sendMessage(chat_id, random.randint(1,6))
elif command == '/time':
bot.sendMessage(chat_id, str(datetime.datetime.now()))
pygame.mixer.music.play()
sendpic(chat_id)
MessageLoop(bot, handle).run_as_thread()
print('I am listening ...')
# Define GPIO -pins as standard
GPIO.setmode(GPIO.BCM)
# Define pin X as input and enable internal resistors
GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# function for button press
while True:
input_state = GPIO.input(pin)
if input_state == False:
pressed = 1
else:
if pressed == 1:
print('Someone at the door.')
pygame.mixer.music.play()
pressed = 0
while 1:
time.sleep(10)

can't open device: Too many open files Error

Hi I Have Terrible codes in Raspberry Pi 3. I am trying to read 4 RC522 Module and i can do it. But after few minutes I got "can't open device: Too many open files" Error, and my while loop terminated.
I didnt share all the functions. I guess important part is while loop. I create instance in every loop. I guess this is big mistake. I cant add delay. I tried assign null to my object but i got still same error. My Codes are Below
Note: I have 4 SPI address, and i create instance with them.
#!/usr/bin/env python
# -*- coding: utf8 -*-
import time
import sys
import os
import RPi.GPIO as GPIO
import MFRC522
import signal
from time import gmtime, strftime
from time import sleep
import requests
#import xml.etree.ElementTree as ET
#import xmltodict, json
from lxml import objectify
from bs4 import BeautifulSoup
continue_reading = True
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT)
GPIO.setup(37, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
# Capture SIGINT for cleanup when the script is aborted
def end_read(signal,frame):
global continue_reading
print "Ctrl+C captured, ending read."
continue_reading = False
GPIO.cleanup()
kullanici = "xxxx"
sifre = "xxxx"
birim = "xxxx"
ogrKEY = " "
def end_read(signal,frame):
global continue_reading
print "Ctrl+C captured, ending read."
continue_reading = False
GPIO.cleanup()
# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)
# Create an object of the class MFRC522
#
adresler = ["/dev/spidev0.0", "/dev/spidev0.1", "/dev/spidev1.0","/dev/spidev1.1"]
# Welcome message
print "Welcome to the MFRC522 data read example"
print "Press Ctrl-C to stop."
j = 0
# This loop keeps checking for chips. If one is near it will get the UID and authenticate
while continue_reading:
MIFAREReader = None
pin = 0
if j == 100:
j = 0
i = j % 4
if i == 0:
MIFAREReader = MFRC522.MFRC522(adresler[0], 16)
pin = 15
elif i == 1:
MIFAREReader = MFRC522.MFRC522(adresler[1], 18)
pin = 13
elif i == 2:
MIFAREReader = MFRC522.MFRC522(adresler[2], 33)
pin = 7
else:
MIFAREReader = MFRC522.MFRC522(adresler[3], 31)
pin = 37
# Scan for cards
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
# If a card is found
if status == MIFAREReader.MI_OK:
print "Card detected"
# Get the UID of the card
(status,uid) = MIFAREReader.MFRC522_Anticoll()
# If we have the UID, continue
if status == MIFAREReader.MI_OK:
# print "su okuyucudan okundu" % i
# Print UID
print "Card read UID: "+str(uid[0])+","+str(uid[1])+","+str(uid[2])+","+str(uid[3])
# This is the default key for authentication
key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
# Select the scanned tag
MIFAREReader.MFRC522_SelectTag(uid)
# Authenticate
status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 10, key, uid)
# Check if authenticated
if status == MIFAREReader.MI_OK:
MIFAREReader.MFRC522_Read(10)
ogrKEY = MIFAREReader.returnOGR()
sonuc = parser(ogrKEY)
if sonuc == True:
openTurnsTile(pin)
else:
sonuc = personelKontrol(ogrKey)
if sonuc == True:
openTurnsTile(pin)
MIFAREReader.MFRC522_StopCrypto1()
else:
print "Authentication error"
j = j + 1
When you create the MFRC522 object it actually calls spi.openSPI() but never closes it. This python library is good for single instance but now that you are dealing with multiple instance where FDs are opened, needs to be closed as well using spi.closeSPI(), else you will get the error "Too many open FDs".
To check how many open FDs are there for your PID.

Pyserial, Getting extra info from OBD Device

I am new at programming and am trying to communicate with my vehicle with an OBD II device. Serial to USB. I've done what I want it to do but I get the command I entered to print out. How do I just get the information from the device?
Heres my code. I am using Python 3.2.3
import serial
import time
import string
import io
import os
import sys
ser = serial.Serial("/dev/ttyUSB1")
ser.baudrate = 38400
s = input('Enter AT command --> ')
print ('AT command = ' + s)
ser.write(bytes(s + '\r\n', encoding = 'utf-8'))
ser.timeout = 1
response = ser.read(999).decode('utf-8')
print(response)
ser.close()
And here is what prints out when I enter the command 'atrv'.
>>>
Enter AT command --> atrv
AT command = atrv
atrv
0.1V
>>>
How do I prevent the 'atrv' above the 0.1V from printing out?
Send ATE0 to the ELM-device.
This disables the echo, so atrv won't be send back to you!
Have a look into this: http://elmelectronics.com/DSheets/ELM327DS.pdf , collection of lots of AT commands, could be helpful!
on a raspberry PI i had to modify the code to:
import serial
import time
import string
import io
import os
import sys
ser = serial.Serial("/dev/rfcomm0")
ser.baudrate = 115200
s = input('Enter AT command --> ')
print ('AT command = ' + s)
ser.flushInput();
ser.write(bytes(s + '\r\n', encoding = 'utf-8'))
ser.flush();
ser.timeout = 1
response = ser.read(999).decode('utf-8')
print(response)
ser.close()

Resources