Socket timeout not working Python lora - python

I'm noob with python and lora, I want to open a socket wait for a message, if there is no message then do something else, my code so far is:
from network import LoRa
import socket
import machine
import time
import binascii
import network
n = 0
try:
the_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
except socket.error:
exit('Error creating socket.')
the_sock.settimeout(5)
while True:
try:
n=n+1
print("Hola"+str(n))
time.sleep(1)
the_sock.setblocking(True)
ack = the_sock.recv(HEADER_SIZE)
except socket.timeout, e:
err = e.args[0]
print(err)
break`
The problem is that the timeout it's not working, I've checked some answers but the code looks good to me, can you help me please?
Kind Regards

You do not need "socket.error" in you except statement, you should just say except. Just a tip, for your "n=n+1" statement you can just do "n+=1." Just helps speed up things I guess. For your "break" statement at the end, there is a mark after it, which could cause an error. Anyway, I hoped I helped in some way! Note: I do not code LORA. I code INET and SOCK_DGRAM, SOCK_STREAM. Hope I helped!

Related

Set esp32 access point web server using Micropython

I am trying to run a mini web server on my ESP32 feather huzzah32, but I hit an error every time I try to open the console. I tried several times, updated everything, erased the flash also few time to start over and the same.
The line 37 seems to have a problem I cannot figure out.
When I am done with compiling and upload the code, I see this error:
(IOError #[0047:0013:0000:0048:0000:0000:0000:0000]
oops, something wrong while linkin:
(IOError at line 37 of main raised at line 97 of wireless.wifi.link
Here is my code.
import streams
import socket
from wireless import wifi
from espressif.esp32net import esp32wifi as wifi_driver
streams.serial()
wifi_driver.auto_init()
wifi.link("my-ssid",wifi.WIFI_WPA2,"my-password")
except Exception as e:
print("ooops, something wrong while linking :(", e)
while True:
sleep(1000)
print("Linked!")
info = wifi.link_info()
print("My IP is:",info[0])
sock = socket.socket()
sock.bind(80)
sock.listen()
while True:
try:
client = streams.SocketStream(clientsock)
line = client.readline()
while line!="\n" and line!="\r\n":
line = client.readline()
print("HTTP request received!")
print("HTTP/1.1 200 OK\r",stream=client)
print("Content-Type: text/html\r",stream=client)
print("Connection: close\r\n\r",stream=client)
print("<html><body>Hello Zerynth!",random(0,100),"</body></html>",stream=client)
client.close()
except Exception as e:
print("ooops, something wrong:",e)
I am using Zerynth.
Any ideas?
I found the issue. It was a bit silly but often errors are indeed silly. Istead of using routers SSID, I tried with the name of the WIFI network and it worked just fine. There is the code, line 37.
wifi.link("NAME_OF_THE_NETWORK",wifi.WIFI_WPA2,"NETWORK_PASSWORD")

Treat try and except the same

I'm writing something that checks if a port is open, but modifying it to my use.
I set timeout for the check and if timeout reaches it raises socket.timeout exception, but I want a code block inside the try to also be invoked on socket.timeout:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
result = sock.connect_ex((check_server_ip, check_port))
if result == 0:
# act on open port
else:
# act on closed port
sock.close()
except socket.timeout:
# act on closed port
The code block I have on # act on closed port is long. I can create a function that has the code and call it on the else statement and socket.timeout exception, but I bet python has something more clever.
What can achieve this?
I don't think you need something clever or magical here. I looked at your code, then entered python -c "import this" in my terminal and saw this among the lines:
Flat is better than nested.
So, you don't need to create, set timeout and close a socket in the try ... except timeout - nothing throws timeout there:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
try:
result = sock.connect_ex((check_server_ip, check_port))
socket_connected = result == 0
except socket.timeout:
socket_connected = False
if socket_connected:
do_connected_stuff()
else:
do_disconnected_stuff()
sock.close()
However, the correctness of this code really depends on if do_connected_stuff() can throw socket.timeout and if do_disconnected_stuff() is a meaningful action in this case. If yes to all questions, then you've already got a pretty much optimal structure - at least without the full view of your system.

Closing connectionSocket throwing 'Invalid syntax with except IOError'

I tried executing this code, but am getting an error message saying "Invalid syntax".
Please help me out, since am new to this.
#import socket module
from socket import *
connectonSocket.close()
except IOError:
connectionSocket.send('\nHTTP/1.1 404 Not Found\n\n')
#Close client socket
connectionSocket.close()
serverSocket.close()
Please see this informative TutorialsPoint page for a great explanation of try/except/else/finally Python code!
Your code should be:
#import socket module
from socket import *
try:
connectonSocket.open()
except IOError:
connectionSocket.send('\nHTTP/1.1 404 Not Found\n\n')
#Close client socket
finally:
connectionSocket.close()
serverSocket.close()
And if you are copying and pasting your code into cmd/terminal you cannot have blank lines (If you do you'll get an indentation error).
try/except/finally
TRY:
Means to 'try' to do something, ie. call a function, method, etc.
EXCEPT (you can have multiple excepts):
Means if your 'try' code did NOT work, do 'this' in response.
FINALLY:
Means do 'this' stuff whether or not you 'tried' and succeeded, or 'excepted'.

PYTHON - URLLIB2 Catch socket.error

Right now I am using urllib to pull some data off a server. However, the server is a bit dodgy and tends to go down every now and then for a minute or so. To deal with, when my code encounters an error, it just waits two seconds and tries again:
def fin(group):
try:
data = urllib2.urlopen("cool website" + group)
return data.read()
except urllib2.HTTPError, err:
time.sleep(2)
fin(group) #calls itself again
except urllib2.URLError, err:
time.sleep(2)
fin(group)
That works fine if the website goes down or I lose my internet connection. However, last night I left the code running and got this error:
socket.error: [Errno 10053] An established connection was aborted by the software in your host machine
I am not quite sure how to catch that. After some searching I am thinking I may need to do this:
except httplib.HTTPException, err:
time.sleep(2)
fin(group)
But I am not certain. Would anyone be able to help me out?

How do you maintain continous client / server communication?

I am trying to have a client connect to my server, and have a stream of communication between them. The only reason the connection should break is due to network errors, or unless the client wants to stop talking.
The issue I am running into is keeping the handler in a tight loop, and parsing the JSON.
My server code is :
#!/usr/bin/env python
import SocketServer
import socket
import json
import time
class MyTCPServer(SocketServer.ThreadingTCPServer):
allow_reuse_address = True
class MyTCPServerHandler(SocketServer.BaseRequestHandler):
def handle(self):
while 1:
try:
networkData = (self.request.recv(1024).strip())
try:
jsonInputData = json.loads(networkData)
print jsonInputData
try:
if jsonInputData['type'] == 'SAY_HI':
print "HI"
except Exception, e:
print "no hi"
pass
try:
if jsonInputData['type'] == 'GO_AWAY':
print "Going away!"
except Exception, e:
print "no go away"
pass
except Exception, e:
pass
#time.sleep(0.001)
#print "JSON Error", e
except Exception, e:
#time.sleep(0.001)
pass
#print "No message", e
server = MyTCPServer(('192.168.1.115', 13373), MyTCPServerHandler)
server.serve_forever()
My client code is simple :
#!/usr/bin/env python
import socket
import json
import time
import sys
hostname = '192.168.1.103'
port = 13373
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((hostname,port))
except Exception, e:
print "Error, could not open socket: ", e
data = {'type':'SAY_HI'}
sock.send(json.dumps(data))
data = {'type':'SAY_BYE'}
sock.send(json.dumps(data))
Sometimes I'll see the messages being sent, "SAY_HI" and "SAY_BYE", but most of the times, no data is being displayed on the server side.
This question is really not clear, but calling self.request.recv(1024) is very likely not what you want to do. You're eliminating all of the nice application-level handling that TCP will happily do for you. If you change that to self.request.recv(8) or a similarly very small number (such that recv() returns whenever it receives data, and doesn't try to fill your buffer), you may get better results.
Ultimately this is super-simplistic change, even if it works, that will not work in a larger context. You will need to be handling exceptions from your json parser on the server side and waiting for more data until an entire well-formed message is received.
This is a hopelessly more complex subject than will be handled generally in any SO answer. If you're going to be doing any amount of raw sockets programming, you absolutely must own a copy of Unix Network Programming, Volume 1.

Categories