OSError micropython - micropython

I get OSError on esp8266. First request is successful but second and more are failed with OSError, I dont know why. Can you help me?
Edit: I solved it. I wrote the solution at the end of the codes.
import network
name, password="wifiname", "passwordd"
wlan = network.WLAN(network.STA_IF)
wlan.active(True) # activate the interface
wlan.scan() # scan for access points
wlan.isconnected() # check if the station is connected to an AP
wlan.connect(name, password) # connect to an AP
wlan.config('mac') # get the interface's MAC address
wlan.ifconfig() # get the interface's IP/netmask/gw/DNS addresses
ap = network.WLAN(network.AP_IF) # create access-point interface
ap.active(True) # activate the interface
ap.config(essid='ESP-AP') # set the ESSID of the access point
print('Wifi connected! My IP:', wlan.ifconfig()[0])
import urequests
import time
while 1:
try:
t1=time.time()
r=urequests.get('https://saitamatechnoo.web.app/')
t2=time.time()
print(r.status_code, 'Time:', t2-t1)
except OSError:
print('error')
Guys, I solved it. It works with socket and we should close every socket after using it.
For example:
r=urequests.get('https://saitamatechnoo.web.app/')
print(r.status_code)
r.close()

Related

PYCOM FiPy does not attach to the Cellular Network - LTE Italy

I have tried to connect to the internet using LTE but the network won't attach.
I want to determine the proper carrier on my Fipy, I did not get any response, the list was empty.
The comand AT+CEREG?' response OK.
The firmware version that I have is LR5.1.1.0-47510
Does someone have any idea on how I could manage to attach to the network? Any previous experiences Thank you in advance.
`>>> from network import LTE
>>> lte=LTE()
>>> lte.send_at_cmd("AT+SQNCTM=?")
''
>>>
I have been running all variations of the default test program with any success
from network import LTE
import time
import socket
lte = LTE()
lte.attach()
print("attaching..",end='')
while not lte.isattached():
time.sleep(0.25)
print('.',end='')
print(lte.send_at_cmd('AT!="fsm"')) # get the System FSM
print("attached!")
lte.connect()
print("connecting [##",end='')
while not lte.isconnected():
time.sleep(0.25)
print('#',end='')
#print(lte.send_at_cmd('AT!="showphy"'))
print(lte.send_at_cmd('AT!="fsm"'))
print("] connected!")

ESP32 MicroPython SSL WebSocket server fail

I'm trying to set up a secure socket server on esp32 with micropython. I used/tried the latest bulid (esp32-idf3-20200117-v1.12-68-g3032ae115.bin) with a self-signed certificate.
I saw a lot of memory leak related problem with ssl.wrap_socket() on esp32/esp8266 but what I got is different:
mbedtls_ssl_handshake error: -4310
Traceback (most recent call last):
File "boot.py", line 100, in <module>
OSError: [Errno 5] EIO
and the connection fails of course. I try to connect from my laptop. The exact same code of client side works if I start a secure socket server on the laptop itself (127.0.0.1) so I suppose that the client side is OK and the problem is on the server side.
I could not find any solution for this problem yet. I tried certificate and key both in 'der' and 'pem' format the result is the same.
The toy server code I tried:
import esp
esp.osdebug(None)
import gc
gc.collect()
import usocket as socket
import ssl
import machine
import network
KEY_PATH = 'server_key.der'
CERT_PATH = 'server_cert.der'
ssid= "AP_local"
pw="passwd"
ap = network.WLAN(network.AP_IF) # create access-point interface
ap.config(essid=ssid, password=pw, authmode=4) # set the ESSID of the access point
ap.ifconfig(('192.168.3.1', '255.25.255.0', '192.168.3.1', '8.8.8.8'))
ap.active(True)
with open(KEY_PATH, 'rb') as f:
key = f.read()
print(key)
print(" ")
with open(CERT_PATH, 'rb') as f:
cert = f.read()
#s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ad = ap.ifconfig()
addr = socket.getaddrinfo(ad[0], 8443)[0][-1]
s.bind(addr)
s.listen(5)
import gc
gc.collect()
while True:
print("ssl connection started")
cl, addr = s.accept()
scl = ssl.wrap_socket(cl, server_side=True, cert=cert, key=key)
print(gc.mem_free())
l = 0
while True:
req = scl.read(1024)
print(req)
if not req or b'\r\n' in req:
break
response = '\r\n'.join(['HTTP/1.1 200 OK',
'Content-Type: text/plain',
'OK',
'Connection: close', '\r\n'])
scl.write(response.encode("utf-8"))
scl.close()
I hope someone could help me with this, thanks!
OK, after spending a few days on searching and reading and testing I got a solution and a possible reason for this issue. I hope it will help others a little.
I want to put forward that I didn't dig into the source code of mbedtls so the reasoning is somewhat phenomenological.
First, I tried to connect from a python program with default settings which failed as shown above. Then I tried with the openssl cli, which also failed.
I tried with the example given at https://github.com/micropython/micropython/blob/master/examples/network/http_server_ssl.py and failed again but with different error codes.
Finally I found a very useful page:
https://tls.mbed.org/api/ssl_8h.html#a55ed67b6e414f9b381ff536d9ea6b9c0
which helped to understand where the problem occures.
Now depending on requirements different errors occured from -7900,-7780, -7380, -7d00.
It turned out that although in the documentation the cipher suit being used is automatically agreed during handshake but there is some bug in it or the implementation of some of them in micropython is different.
I didn't tested all the available ciphers on my laptop but e.g.: AES_256_GCM_SHA384
cipher works.
For me it is enough now.

IP_ADD_MEMBERSHIP fails when set both on interface and its subinterface; is that expected?

I'm debugging a 3rd-party network application and trying to figure out why it reports errors when calling setsockopt with IP_ADD_MEMBERSHIP to set up a multicast group. The application is in C++, but I've written an MWE in python that replicates the same syscalls:
import socket
import struct
ETH0_IP = "192.168.88.85"
ETH0_1_IP = "192.168.88.254"
MULTICAST_IP = "224.0.0.7"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
ip = socket.inet_aton(ETH0_IP)
s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, ip)
group = struct.pack("4s4s", socket.inet_aton(MULTICAST_IP), ip)
s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, group)
# s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
s2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
ip2 = socket.inet_aton(ETH0_1_IP)
s2.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, ip2)
group2 = struct.pack("4s4s", socket.inet_aton(MULTICAST_IP), ip2)
# the second group is added to the first socket so that we can only bind to one socket and read data from it
s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, group2)
At the second IP_ADD_MEMBERSHIP call I get error OSError: [Errno 98] Address already in use.
I found out this only happens when ETH0_1_IP is a subinterface of ETH_0_IP. And I'm not sure if this is expected. If it is, is there a way to actually detect this situation and discard subinterfaces of already bound interfaces? Further, would my multicast socket receive data sent to the subinterface if registration for it fails with the above error?
For the sake of completeness:
$ cat /etc/network/interfaces
auto lo
iface lo inet loopback
iface lo inet6 loopback
auto eth0:1
iface eth0:1 inet static
address 192.168.88.254
netmask 255.255.240.0
Linux is tracking your alias interface as the same interface and so rejecting the attempt to re-use the interface.
In a bit more detail, I have run your code successfully on CentOS 7 using two separate physical interfaces with no changes. If I then change the code to use an alias on the same physical address, it fails with the same error that you see.
Digging a little further, I see that if I dump the interface indeces (using SIOCGIFINDEX) for the physical adaptor and the alias, they do indeed have the same index.
If you want to use Python to check this for yourself, have a quick look at https://gist.github.com/firaxis/0e538c8e5f81eaa55748acc5e679a36e for some code (missing imports of ctypes and socket) and then try something like this:
print(Interface(name="eth0").index)
print(Interface(name="eth0:1").index)

Can't read data from OBD2 serial port connection on Raspberry Pi

I'm currently working on a raspberry pi project for school where I read data from an OBD2 to usb censor in my car.
When I'm using Screen to connect to the serial port everything works fine, but when I try to do it in python the serial.readline() returns an empty string.
Does anybody know how I can retrieve data from the serial port in python?
I've tried about every option available.
import serial
ser = 0
#Function to Initialize the Serial Port
def init_serial():
global ser
ser = serial.Serial()
ser.baudrate = 38400
ser.port = '/dev/ttyUSB0'
ser.timeout = 1
ser.open() #Opens SerialPort
# print port open or closed
if ser.isOpen():
print 'Open: ' + ser.portstr
#Function Ends Here
init_serial()
temp = raw_input('Type what you want to send, hit enter:\r\n')
ser.write(temp) #Writes to the SerialPort
while 1:
bytes = ser.readline() #Read from Serial Port
print bytes #Print What is Read from Port
You may not be sending valid data to get a response. I believe the ODB2 interface uses the AT command set. Sending AT\n may be a good starting point.
I'm using a Bluetooth ODB2 interface and found that the serial baudrate was fixed. Using any other baudrate failed to correctly get data.
I recommend testing from putty or other terminal that supports serial ports, until you get the device to respond correctly. Then use valid settings to troubleshoot your code.
You're not sending a \r\n with your command, ELM327 requires a new line character at the end of a command.

Trouble authenticating Tor with python

Probably doing something very silly here, but I'm having some trouble authenticating automatically through Tor.
I'm using 32 bit ubuntu 12.04 with obfuscated bridges.
This should be all the relevant code, but let me know if there's something else that would be useful in debugging this issue:
import socket
import socks
import httplib
def connectTor():
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050, True)
#9050 is the Tor proxy port
socket.socket = socks.socksocket
def newIdentity():
socks.setdefaultproxy() #Disconnect from Tor network
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 46594))
s.send("AUTHENTICATE\r\n")
response = s.recv(128)
#128 bytes of data for now, just to see how Tor responds
print response
if response.startswith("250"): #250 is the code for a positive response from Tor
s.send("SIGNAL NEWNYM\r\n") #Use a new identity
s.close()
connectTor() #Just to make sure we're still connected to Tor
Whenever I run this I get the following error:
515 Authentication failed: Password did not match HashedControlPassword value from configuration. Maybe you tried a plain text password
I tried using the --hash-password option and pasting that in the place of the AUTHENTICATE string, but that just caused the script to hang. Thoughts?
That error means that you set the HashedControlPassword option in your torrc. I would suggest option for CookieAuthentication 1 instead then using a controller library rather than doing this from scratch.
What you're trying to do here (issue a NEWNYM) is a very, very common request (1, 2) so I just added a FAQ entry for it. Here's an example using stem...
from stem import Signal
from stem.control import Controller
with Controller.from_port(port = 9051) as controller:
controller.authenticate()
controller.signal(Signal.NEWNYM)