Python 2.7 Tkinter is not response when run program - sockets

I'm absolute beginner for python Tkinter. My program has serial port and TCP client socket connection (Running in thread). It's running well in console application but not work in Tkinter GUI.
count = 0
initialState = True
def initState(reader, ReaderName, readerType, serialport, baud, databit, readerPacket):
global count
global initialState
if initialState:
while not reader.SettingReader(ReaderName, readerType, serialport, baud, databit, readerPacket):
count += 1
count = 0
labelSearching.place(x=290, y=260)
labelReaderSetting.configure(image=readerSettingSuccess)
app.update_idletasks()
labelSearching.grid_forget()
labelReaderConnect.place(x=290, y=260)
app.update_idletasks()
labelReaderConnect.configure(image=readerConnected)
labelServerConnect.place(x=290, y=320)
app.update_idletasks()
while not reader.StartServer():
count += 1
count = 0
labelServerConnect.configure(image=serverConnected)
app.update_idletasks()
labelContainer.grid_forget()
labelReaderSetting.configure(image=readerSettingSuccessSmall)
labelReaderSetting.place(x=80, y=200)
labelReaderSetting.lift()
labelReaderConnect.configure(image=readerConnectedSmall)
labelReaderConnect.place(x=80, y=260)
labelReaderConnect.lift()
labelServerConnect.configure(image=serverConnectedSmall)
labelServerConnect.place(x=80, y=320)
labelServerConnect.lift()
labelWaitingTap.place(x=460, y=260)
labelLeft.grid(row=1, column=0)
labelRight.grid(row=1, column=1)
app.update_idletasks()
reader.SaveSettingToFile()
initialState = False
else:
runnMainProgram(reader)
app.update()
app.after(1000, functools.partial(initState, reader, ReaderName, readerType, serialport, baud, databit, readerPacket))
def runnMainProgram(reader):
try:
check = reader.StartReader(reader._CARDANDPASSWORD)
app.update_idletasks()
if check == True:
print "Open the door"
check = ""
print "Ready..."
app.update_idletasks()
elif check == False:
print "Doesn't Open The Door"
check = ""
print "Ready..."
app.update_idletasks()
elif check == 2:
print "Reader disconnect"
print "Reconnecting to Reader"
reader.ClosePort()
while not reader.OpenPort():
count += 1
count = 0
check = ""
print "Ready..."
app.update_idletasks()
except KeyboardInterrupt:
exit()
app.after(10, functools.partial(runnMainProgram, reader))
app = Tk()
app.title("Access Control")
app.geometry('800x610+200+50')
app.protocol('WM_DELETE_WINDOW', closewindow)
updateGUIThread = threading.Thread(target=updateGUI)
app.minsize('800', '610')
app.maxsize('800', '610')
"I'm create Tkinter widget here."
reader = Readers()
settingList = list()
readerType = ""
readerPacket = ""
try:
for line in fileinput.FileInput("Setting.txt", mode='r'):
settingList.append(line)
if str(line).find("DF760MSB", 0, len(str(line))) >= 0:
readerType = reader._DF760MSB
elif str(line).find("DF760LSB", 0, len(str(line))) >= 0:
readerType = reader._DF760LSB
else:
readerType = reader._DF760MSB
if str(line).find("SINGLEPACKET", 0, len(str(line))) >= 0:
readerPacket = reader.SINGLEPACKET
elif str(line).find("MULTIPACKET", 0, len(str(line))) >= 0:
readerPacket = reader.MULTIPACKETS
else:
readerPacket = reader.SINGLEPACKET
ReaderName = str(settingList[0]).rstrip()
baud = int(settingList[1])
databit = int(settingList[2])
HOST = str(settingList[3]).rstrip()
PORT = int(settingList[4])
TIMEOUT = int(settingList[5])
except:
ReaderName = "R001"
baud = 19200
databit = 8
HOST = "10.50.41.81"
PORT = 43
TIMEOUT = 10
serialport = 'COM3'
reader.SettingServer(HOST, PORT, TIMEOUT)
app.after(100, functools.partial(initState, reader, ReaderName, readerType, serialport, baud, databit, readerPacket))
app.mainloop()
when I'm run this code GUI will freezing but serial port and TCP client socket still running.
I've try to fix this problem (looking in every where) but I'm got nothing. Any idea? Thank so much.

The way to solve this would be to call app.after(100, <methodName>) from the receiving thread. This stops the main thread from being blocked by waiting for a signal, but also means that tkinter can update instantly too as the method pushed to .after will be executed in the main thread. By specifying 100 as the time frame, it will appear to change nigh on instantly as the argument passed is the number of milliseconds.

Related

Traceback after looping through all available news article

I am making a python CLI utility that will answer questions like "15 + 15" or "How many letters are in the alphabet".
I then decided to add the ability to search up the latest news using the newspaper module.
All of it works except when the for loop finishes, after printing a string literal, it gives me a error that I do not know what the heck it means.
Can someone decipher the error for me and if possible, help me fix the error? Thanks.
import requests
import wolframalpha
import wikipedia
import time
import sys
from threading import Thread
from newspaper import Article
import bs4
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen
version = 2.1
build = '19w12a6'
ready = 0
loadingAnimationStop = 0
appId = 'CENSORED STUFF BECAUSE I DON\'T WANT ANYONE TO TOUCH MY KEY'
client = wolframalpha.Client(appId)
exitNow = 0
def loadingAnimation():
while exitNow == 0:
print("Loading: |", end='\r')
time.sleep(0.2)
while ready == 1:
time.sleep(0)
print("Loading: /", end='\r')
time.sleep(0.2)
while ready == 1:
time.sleep(0)
print("Loading: -", end='\r')
time.sleep(0.2)
while ready == 1:
time.sleep(0)
sys.stdout.write("Loading: \ \r")
time.sleep(0.2)
while ready == 1:
time.sleep(0)
hui = Thread(target = loadingAnimation, args=())
hui.start()
def search_wiki(keyword=''):
searchResults = wikipedia.search(keyword)
if not searchResults:
print("No result from Wikipedia")
return
try:
page = wikipedia.page(searchResults[0])
except wikipedia.DisambiguationError:
page = wikipedia.page(err.options[0])
wikiTitle = str(page.title.encode('utf-8'))
wikiSummary = str(page.summary.encode('utf-8'))
print(' ', end='\r')
print(wikiTitle)
print(wikiSummary)
def search(text=''):
res = client.query(text)
if res['#success'] == 'false':
ready = 1
time.sleep(1)
print('Query cannot be resolved')
else:
result = ''
pod0 = res['pod'][0]
pod1 = res['pod'][1]
if (('definition' in pod1['#title'].lower()) or ('result' in pod1['#title'].lower()) or (pod1.get('#primary','false') == 'True')):
result = resolveListOrDict(pod1['subpod'])
ready = 1
time.sleep(0.75)
print(' ', end='\r')
print(result)
question = resolveListOrDict(pod0['subpod'])
question = removeBrackets(question)
#primaryImage(question)
else:
question = resolveListOrDict(pod0['subpod'])
question = removeBrackets(question)
search_wiki(question)
def removeBrackets(variable):
return variable.split('(')[0]
def resolveListOrDict(variable):
if isinstance(variable, list):
return variable[0]['plaintext']
else:
return variable['plaintext']
#def primaryImage(title=''):
# url = 'http://en.wikipedia.org/w/api.php'
# data = {'action':'query', 'prop':'pageimages','format':'json','piprop':'original','titles':title}
# try:
# res = requests.get(url, params=data)
# key = res.json()['query']['pages'].keys()[0]
# imageUrl = res.json()['query']['pages'][key]['original']['source']
# print(imageUrl)
# except Exception:
# print('Exception while finding image:= '+str(err))
page = requests.get('https://www.wolframalpha.com/')
s = page.status_code
if (s != 200):
ready = 1
time.sleep(1)
print('It looks like https://www.wolframalpha.com/ is not online.')
print('Please check your connection to the internet and https://www.wolframalpha.com/')
print('Stopping Python Information Engine')
while True:
time.sleep(1)
page = requests.get('https://www.wikipedia.org/')
s = page.status_code
if (s != 200):
ready = 1
time.sleep(1)
print('It looks like https://www.wikipedia.org/ is not online.')
print('Please check your connection to the internet and https://www.wikipedia.org/')
print('Stopping Python Information Engine')
while True:
time.sleep(1)
ready = 1
while exitNow == 0:
print('================================================================================================')
print('Python Information Engine CLI Version', end=' ')
print(version)
print('Create by Unsigned_Py')
print('================================================================================================')
ready = 1
time.sleep(1)
print(' ', end='\r')
print(' ', end='\r')
q = input('Search: ')
print('================================================================================================')
if (q == 'Credits()'):
print('Credits')
print('================================================================================================')
print('PIE is made by Unsigned_Py')
print('Unsigned_Py on the Python fourms: https://python-forum.io/User-Unsigned-Py')
print('Contact Unsigned_Py: Ckyiu#outlook.com')
if (q == 'Latest News'):
print('DISCLAIMER: The Python Information Engine News port is still in DEVELOPMENT!')
print('Getting latest news links from Google News...')
ready = 0
news_url = "https://news.google.com/news/rss"
Client = urlopen(news_url)
xml_page = Client.read()
Client.close()
soup_page = soup(xml_page,"xml")
news_list = soup_page.findAll("item")
ready = 1
print('================================================================================================')
article_number = 1
for news in news_list:
print(article_number, end=': ')
print(news.title.text)
print(news.pubDate.text)
if (input('Read (Y or N)? ') == 'y'):
ready = 0
url = news.link.text
article = Article(url)
article.download()
article.parse()
article.nlp()
ready = 1
print('================================================================================================')
print(article.summary)
print('================================================================================================')
article_number = article_number + 1
print("That's all for today!")
if (q == 'Version()'):
print('Python Information Engine CLI Version', end=' ')
print(version)
print('Running Build', end=' ')
print(build)
print('Upon finding a bug, please report to Unsigned_Py and I will try to fix it!')
print('Looking for Python Information Engine CLI Version 1.0 - 1.9?')
print("It's called Wolfram|Alpha and Wikipedia Engine Search!")
if (q != 'Exit()'):
if (q != 'Credits()'):
if (q != 'News'):
if (q != 'Version()'):
ready = 0
search(q)
else:
exitNow = 1
print('Thank you for using Python Information Engine')
print('================================================================================================')
time.sleep(2)
ready = 0
Here's the error:
Traceback (most recent call last):
File "C:\Users\ckyiu\OneDrive\Desktop\Python Information Engine 2.1.py", line 210, in <module>
search(q)
File "C:\Users\ckyiu\OneDrive\Desktop\Python Information Engine 2.1.py", line 62, in search
res = client.query(text)
File "C:\Users\ckyiu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wolframalpha\__init__.py", line 56, in query
return Result(resp)
File "C:\Users\ckyiu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wolframalpha\__init__.py", line 178, in __init__
super(Result, self).__init__(doc)
File "C:\Users\ckyiu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wolframalpha\__init__.py", line 62, in __init__
self._handle_error()
File "C:\Users\ckyiu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wolframalpha\__init__.py", line 69, in _handle_error
raise Exception(template.format(**self))
Exception: Error 0: Unknown error
Well I got it to work now, for some reason I put: if (q != 'News'): I wanted if (q != 'Latest News'):.
Then python threw me a error for that. I got it to work at least now.

get AT command call response

I'm trying a code to make a voice call using usb modem and it succeeded to make a call... now i want to get that call response to know if number is ringing,busy or unavailable
This is my used code:
string number = textBox1.Text;
po.PortName = "COM3";
po.BaudRate = int.Parse("9600");
po.DataBits = Convert.ToInt32("8");
po.Parity = Parity.None;
po.StopBits = StopBits.One;
po.ReadTimeout = int.Parse("300");
po.WriteTimeout = int.Parse("300");
po.Encoding = Encoding.GetEncoding("iso-8859-1");
po.Open();
po.DtrEnable = true;
po.RtsEnable = true;
po.Write("ATDT "+number+";\r");
System.Threading.Thread.Sleep(7000);
po.WriteLine("ATH+CHUP;\r");
po.DiscardInBuffer();
po.DiscardOutBuffer();
po.Close();
After ATD, you need reading the port for kind of information called URC.
For voice call, there are the following possible response,
If no dialtone
NO DIALTONE
If busy,
BUSY
If connection cannot be set up:
NO CARRIER
NO ANSWER
And, before ATD, you'd better set the error format using at+cmee, for exam, at+cmee=2 will enable the string format.
EDIT:(Here is an example with python)
#! /usr/bin/env python
# -*- coding: utf8 -*-
from __future__ import print_function
import sys
import serial
NUM = "111111111"
ser = serial.Serial("com1", 115200)
ser.write('at+cmee=2\r')
ser.timeout = 10.0
res = "invalid"
while len(res) > 0:
res = ser.read(1)
print(res, end='')
ser.write('atd' + NUM + ';\r')
ser.timeout = 60.0
res = "invalid"
while len(res) > 0:
res = ser.read(1)
print(res, end='')
ser.write("AT+CHUP\r")
ser.timeout = 10.0
res = "invalid"
while len(res) > 0:
res = ser.read(1)
print(res, end='')
Its output is (I reject the call from the phone "111111111"),
at+cmee=2
OK
atd111111111;
OK
NO CARRIER
AT+CHUP
+CME ERROR: operation not allowed
And, after the output of 'no carrier', there is no more need to hang up.

server doesn't send data to clients

I have this piece of code for server to handle clients. it properly receive data but when i want to send received data to clients nothing happens.
server
import socket
from _thread import *
class GameServer:
def __init__(self):
# Game parameters
board = [None] * 9
turn = 1
# TCP parameters specifying
self.tcp_ip = socket.gethostname()
self.tcp_port = 9999
self.buffer_size = 2048
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.s.bind((self.tcp_ip, self.tcp_port))
except:
print("socket error, Please try again! ")
self.s.listen(5)
print('Waiting for a connection...')
def messaging(self, conn):
while True:
data = conn.recv(self.buffer_size)
if not data:
break
print("This data from client:", data)
conn.send(data)
def thread_run(self):
while True:
conn, addr = self.s.accept()
print('connected to: ' + addr[0] + " : " + str(addr[1]))
start_new_thread(self.messaging, (conn,))
def main():
gameserver = GameServer()
gameserver.thread_run()
if __name__ == '__main__':
main()
'
I want to if data received completely send to clients by retrieve the address of sender and send it to other clients by means of conn.send() but seems there is no way to do this with 'send()' method.
The piece of client side code
'
def receive_parser(self):
global turn
rcv_data = self.s.recv(4096)
rcv_data.decode()
if rcv_data[:2] == 'c2':
message = rcv_data[2:]
if message[:3] == 'trn':
temp = message[3]
if temp == 2:
turn = -1
elif temp ==1:
turn = 1
elif message[:3] == 'num':
self.set_text(message[3])
elif message[:3] == 'txt':
self.plainTextEdit_4.appendPlainText('client1: ' + message[3:])
else:
print(rcv_data)
'
the receiver method does not receive any data.
I modified your code a little(as I have python 2.7) and conn.send() seems to work fine. You can also try conn.sendall(). Here is the code I ran:
Server code:
import socket
from thread import *
class GameServer:
def __init__(self):
# Game parameters
board = [None] * 9
turn = 1
# TCP parameters specifying
self.tcp_ip = "127.0.0.1"#socket.gethostname()
self.tcp_port = 9999
self.buffer_size = 2048
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.s.bind((self.tcp_ip, self.tcp_port))
except:
print("socket error, Please try again! ")
self.s.listen(5)
print('Waiting for a connection...')
def messaging(self, conn):
while True:
data = conn.recv(self.buffer_size)
if not data:
break
print("This data from client:", data)
conn.send(data)
def thread_run(self):
while True:
conn, addr = self.s.accept()
print('connected to: ' + addr[0] + " : " + str(addr[1]))
start_new_thread(self.messaging, (conn,))
def main():
gameserver = GameServer()
gameserver.thread_run()
main()
Client code:
import socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 9999))
def receive_parser():
#global turn
s.sendall("hello world")
rcv_data = s.recv(4096)
# rcv_data.decode()
# if rcv_data[:2] == 'c2':
# message = rcv_data[2:]
# if message[:3] == 'trn':
# temp = message[3]
# if temp == 2:
# turn = -1
# elif temp ==1:
# turn = 1
# elif message[:3] == 'num':
# self.set_text(message[3])
# elif message[:3] == 'txt':
# self.plainTextEdit_4.appendPlainText('client1: ' + message[3:])
# else:
print(rcv_data)
receive_parser()

PYSNMP stop and restart a trap reciever

I am trying to create a pysnmp daemon. I want to have the ability to start, stop, and restart the thread that the daemon is running on. I am having trouble cleaning the socket, notification receiver, and transport dispatcher.
I am using a pysnmp v1/2c trap receiver
class trapReceiverThread(threading.Thread):
def __init__(self):
try:
trapworking = snmpEngine.transportDispatcher.jobsArePending()
except:
trapworking = -1
if trapworking == 0:
snmpEngine.transportDispatcher.jobStarted(1)
elif trapworking == -1:
print "starting"
# UDP over IPv4, first listening interface/port
config.addV1System(snmpEngine, 'my-area', 'public')
# SecurityName <-> CommunityName mapping
print "d0"
config.addSocketTransport(
snmpEngine,
udp.domainName + (1,),
udp.UdpTransport().openServerMode(( 'localhost', 162 ))
)
ntfrcv.NotificationReceiver(snmpEngine, cbFun)
snmpEngine.transportDispatcher.jobStarted(1)
else:
print "Trap receiver already started."
def run(self):
try:
snmpEngine.transportDispatcher.runDispatcher()
except:
print "fail"
snmpEngine.transportDispatcher.closeDispatcher()
raise
def cbFun(snmpEngine,
stateReference,
contextEngineId, contextName,
varBinds,
cbCtx):
transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo(stateReference)
print('Notification from %s, ContextEngineId "%s", ContextName "%s"' % (
transportAddress, contextEngineId.prettyPrint(),
contextName.prettyPrint()
)
)
for obj in varBinds:
print obj
trapStatus = threading.Thread(target = trapReceiverThread().run)
trapStatus.deamon = True
def start():
global trapStatus
if trapStatus.isAlive() == False:
try:
trapStatus.start();
except:
trapStatus = threading.Thread(target = trapReceiverThread().run)
trapStatus.start();
def stop():
if snmpEngine.transportDispatcher.jobsArePending():
print "stopping"
"""
CODE to stop SocketTransport, transportDispatcher, and NotificationReceiver
"""
snmpEngine.transportDispatcher.jobFinished(1)
trapStatus.join()
def restart():
stop()
start()
Since the trap is defined the the local variable transportDispater, the process can be stopped by finishing job #1 and releasing the port.
transportDispatcher.jobFinished(1)
transportDispatcher.unregisterRecvCbFun(recvId=None)
transportDispatcher.unregisterTransport(udp.domainName)

Apple Push APNS Sometimes not arriving

I have an app which is already on the app store,
I also have a server that sends push notification to the iphone.
My problem is that sometimes, the notification does not arrive to the iphone,
and this only happened after there was no apns communication to the apple push server after 2 or 3 hours, but after timeout, it would start working again. it was really random.
At first i though the problem was a timeout, then i tried to print out the return value of my ssl_wrap.send() functions, and it did return the length of the strings that was supposed to be sent, meaning, Apple APNS received all my json strings. it is just not broadcasting them to the client phone.
I need to keep firing the apns server until it timeouts before making the push notification work again, this is not right.
Any ideas?
class PushSender:
def __init__(self):
_sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
_sock.settimeout(2)
self.ssl_sock = ssl.wrap_socket( _sock, certfile = theCertfile )
self.ssl_sock.settimeout(1)
self.ssl_sock.connect( theHost )
self.counter = 0
self.lastPush = time()
def reset(self):
Log("Reset APNS");
self.ssl_sock.close()
_sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
_sock.settimeout(2)
self.ssl_sock = ssl.wrap_socket( _sock, certfile = theCertfile )
self.ssl_sock.settimeout(1)
self.ssl_sock.connect( theHost )
self.counter = self.counter + 1;
self.lastPush = time()
def send(self,token, message, badge, sound):
#Log("INIT APNS")
payload = {}
aps = {}
aps["alert"] = str(message)
aps["badge"] = badge
aps["sound"] = str(sound)
payload["aps"] = aps
if time() - self.lastPush> 60*30 : # 30 minutes idle reconnect
self.reset()
try:
#Log("Making Message APNS")
tokenh = binascii.unhexlify(token)
payloadstr = json.dumps(payload, separators=(',',':'))
payloadLen = len(payloadstr)
fmt = "!cH32sH%ds" % payloadLen
command = '\x00'
msg = struct.pack(fmt, command, 32, tokenh, payloadLen, payloadstr)
except:
Log("APNS Data Error " +token+" " +message);
return;
try:
#Log(msg)
sent = 0;
while sent < len(msg):
msg2 = msg[sent:];
justSent = self.ssl_sock.write( msg2 )
#Log(str(len(msg)) + " " + str(justSent))
sent += justSent
if justSent==0 :
raise socket.error(0,"Send failed")
except socket.error, err:
Log( "APNS Error: "+str(self.counter)+" "+ str(err) )
self.reset()
if self.counter<=2 : self.send(token,message,badge,sound)
Log( "APNS DONE"+ str(self.counter))
self.counter = 0;
self.lastPush = time()