OSError: -2 (when using urequests module in mycropython) - python

I'm pretty new to this and am trying to use my raspberry pi pico to connect to my wifi network and then get the date and time from a website and display it on a 16x2 display. basically, it worked perfectly the first couple of time I ran the script and then suddenly refused to work giving me the following error:
Traceback (most recent call last):
File "<stdin>", line 38, in <module>
File "urequests.py", line 180, in get
File "urequests.py", line 76, in request
OSError: -2
the code I used to do this:
import time
import network
import urequests
from machine import I2C, Pin
from I2C_LCD import I2CLcd
ssidRouter = 'xxxx' #my router name
passwordRouter = 'xxxx' #my router password
i2c = I2C(1, sda=Pin(14), scl=Pin(15), freq=400000)
devices = i2c.scan()
led = Pin("LED", Pin.OUT)
poop = I2CLcd(i2c, devices[0], 2, 16)
def STA_Setup(ssidRouter,passwordRouter):
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
poop.putstr("Connecting")
sta_if.active(True)
sta_if.connect(ssidRouter,passwordRouter)
while not sta_if.isconnected():
led.value(1)
time.sleep(0.5)
led.value(0)
time.sleep(0.5)
poop.clear()
STA_Setup(ssidRouter,passwordRouter)
while True:
r = urequests.get("http://date.jsontest.com")
ti = r.json()["time"]
da = r.json()["date"]
poop.move_to(0, 0)
poop.putstr("Time:" + ti)
poop.move_to(0, 1)
poop.putstr(("Date: " + da))
time.sleep(1)
r.close()

That error appears to be coming from this line in the urequests module:
ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM)
If getaddrinfo is failing, that suggests that either your device has lost its network connection, or that there is a more general problem with DNS lookups in your environment.
Some diagnostics you can perform:
Is the device connected to Wifi?
>>> import network
>>> sta_if = network.WLAN(network.STA_IF)
>>> sta_if.isconnected()
True
Does it have a sane network configuration?
>>> sta_if.ifconfig()
('192.168.1.45', '255.255.255.0', '192.168.1.1', '192.168.1.1')
Can you perform hostname lookups?
>>> import socket
>>> socket.getaddrinfo('www.google.com', 80, 0, socket.SOCK_STREAM)
[(2, 1, 0, '', ('142.250.80.68', 80))]
(You may need import usocket instead of import socket; I'm working with an esp8266 instead of a Pico.)

Related

pydbus reconnection after target is rebooted

I'm facing the following problem.
I'm using pydbus python package to test API by connecting to a target linux machine which is in the same network by using the environment variable DBUS_SYSTEM_BUS_ADDRESS
Under normal circumstances this works well, I'm able to call any valid API over the proxy object created.
Eg:
import os
import pydbus
os.environ['DBUS_SYSTEM_BUS_ADDRESS'] = \
"tcp:host=192.168.1.100,port=55556,family=ipv4"
bus = pydbus.SystemBus()
proxy = bus.get("busname", "object_path")
return_value = proxy.method-name(args)
As part of my testing, my target linux machine gets rebooted in between and when I re-use the proxy object, I get the following error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/harman/.local/lib/python2.7/site-packages/pydbus/proxy.py", line 47, in get
0, timeout_to_glib(timeout), None)
GLib.Error: g-io-error-quark: The connection is closed (18)
I realize that the previous connection no longer exists, so I tried re-initialising the connection with the following
bus = pydbus.SystemBus()
proxy = bus.get("busname", "object_path")
I get the same error on the bus.get() statement.
Is there a solution/possible workaround to this problem?

BlueZ AutoReconnect as device to PC

I'm working on a HID bluetooth device with the code on the device in Python; at the moment it can connect to a PC by running:
os.system("hciconfig hcio class 0x002560")
os.system("hciconfig hcio name DataPaqWalk")
Then we can use pybluez to connect the sockets and wait for a connection:
print("Waiting for connections")
self.scontrol=BluetoothSocket(L2CAP)
self.sinterrupt=BluetoothSocket(L2CAP)
self.scontrol.listen(1) # Limit of 1 connection
self.sinterrupt.listen(1)
self.ccontrol,cinfo = self.scontrol.accept()
self.cinterrupt, cinfo = self.sinterrupt.accept()
This works and we have a thread polling with hcitool con to detect the Windows PC (adapter) disconnecting where we dump the sockets and listen again. The hci is setup with no security so the PC connecting to it automatically pairs - this all works.
However the issue comes when the device is powered off; the PC correctly detects that the device is gone and it remains in the paired state. What I want to do is to get the device to automatically connect to the PC it is paired with. I've obviously got the Mac address of the PC and I am trying to connect using:
(P_CTRL is 17 and P_INTR is 19)
self.ccontrol,cinfo = self.scontrol.connect(('C8:FF:28:79:05:D4', self.P_CTRL))
self.controlClientMac = cinfo[0]
self.controlClientPsm = cinfo[1]
print ('control is ' + self.controlClientMac + " " + str(self.controlClientPsm))
self.cinterrupt,cinfo = self.scontrol.connect(('C8:FF:28:79:05:D4', self.P_INTR))
self.interruptClientMac = cinfo[0]
self.interruptClientPsm = cinfo[1]
print ('interrupt is ' + self.interruptClientMac + " " + str(self.interruptClientPsm))
This basically tries to connect and gives me back:
Traceback (most recent call last):
File "server/btk_server.py", line 267, in <module>
myservice = BTKbService();
File "server/btk_server.py", line 226, in __init__
self.device.listen();
File "server/btk_server.py", line 174, in listen
self.ccontrol,cinfo = self.scontrol.connect(('C8:FF:28:79:05:D4', self.P_CTRL))
File "<string>", line 5, in connect
bluetooth.btcommon.BluetoothError: (111, 'Connection refused')
In the bluetooth windows dialog you can see that it flicks to connected but straight back to paired. The question is; how do I get the device to connect to the paired windows adapter? Note that I'm getting a similar response in bluetoothctl.
Wouldnt you be able to run a script on the rpi upon startup automatically that starts looking for a bluetooth socket? https://www.dexterindustries.com/howto/run-a-program-on-your-raspberry-pi-at-startup/

can't login with Paramiko ssh client

local-host --->Aterm server (security server ) -----> target-machine(
I am trying to write a code in Python using Paramiko to first SSH from local-host to the target-machine. From the target-machine, I want to capture some outputs and store them locally either as a variable or as a file (havent got to that point yet). I found an example from stackoverflow where they talk about using nested SSH with paramiko, and I follow it but I get stuck here:
i need just reaching the target-machine
My code:
import paramiko
import sys
import subprocess
hostname = '10.10.10.1'
port = 22
username = 'mohamed.hosseny'
password ='Pass#1'
client = paramiko.Transport((hostname, port))
client.connect(username=username, password=password)
client.close()
but i found the below error message :
Traceback (most recent call last):
File "C:/Users/mohamed.hosseny/Desktop/Paramiko.py", line 13, in <module>
client = paramiko.Transport((hostname, port))
File "C:\Python27\lib\site-packages\paramiko\transport.py", line 332, in
__init__
'Unable to connect to {}: {}'.format(hostname, reason))
SSHException: Unable to connect to 10.10.10.1: [Errno 10060] A connection
attempt failed because the connected party did not properly respond after
a period of time, or established connection failed because connected host
has failed to respond
paramiko.Transport is a lower level API. Don't use it unless you have a good reason. Instead, you can use paramiko.SSHClient.

Python/P2P - Unable to connect to rendezvous server

I am trying to create a P2P node using python (pyp2p) but I am getting this error:
Eamons-MacBook-Pro:blockchain eamonwhite$ python3 serveralice.py
HTTP Error 404: Not Found
HTTP Error 404: Not Found
HTTP Error 404: Not Found
HTTP Error 404: Not Found
Traceback (most recent call last):
File "/Users/eamonwhite/.pyenv/versions/3.6.3/lib/python3.6/site-packages/pyp2p/net.py", line 732, in start
rendezvous_con = self.rendezvous.server_connect()
File "/Users/eamonwhite/.pyenv/versions/3.6.3/lib/python3.6/site-packages/pyp2p/rendezvous_client.py", line 92, in server_connect
con.connect(server["addr"], server["port"])
File "/Users/eamonwhite/.pyenv/versions/3.6.3/lib/python3.6/site-packages/pyp2p/sock.py", line 189, in connect
self.s.bind((src_ip, 0))
TypeError: str, bytes or bytearray expected, not NoneType
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "serveralice.py", line 10, in <module>
alice.start()
File "/Users/eamonwhite/.pyenv/versions/3.6.3/lib/python3.6/site-packages/pyp2p/net.py", line 735, in start
raise Exception("Unable to connect to rendezvous server.")
Exception: Unable to connect to rendezvous server.
My relevant code looks like this:
from uuid import uuid4
from blockchain import Blockchain
from flask import Flask, jsonify, request
from pyp2p.net import *
import time
#Setup Alice's p2p node.
alice = Net(passive_bind="192.168.1.131", passive_port=44444, interface="en0", node_type="passive", debug=1)
alice.start()
alice.bootstrap()
alice.advertise()
while 1:
for con in alice:
for reply in con:
print(reply)
time.sleep(1)
...
It is getting stuck on the Net function right at the beginning - something to do with the rendezvous package. The IP is my IP on the my network, and I port forwarded 44444 although I'm not sure if I need to do that or not. Thanks.
I am new to this, apparently with the way the server code was configured, it needed a rendezvous server to work (a node that handles all the other nodes). It is in net.py of the pyp2p package:
# Bootstrapping + TCP hole punching server.
rendezvous_servers = [
{
"addr": "162.243.213.95",
"port": 8000
}
]
The address was the problem, obviously it is just a placeholder IP. So then I realized I needed my own rendezvous server, and I used this code - https://raw.githubusercontent.com/StorjOld/pyp2p/master/pyp2p/rendezvous_server.py.
However I had to debug this file a little, it ended up needing to have import sys, import time and import re statements at the top before it would work. Now I am going to host it on my raspberry pi so that it is always up to handle nodes :)

Thrift : TypeError: getaddrinfo() argument 1 must be string or None

Hi I am trying to write a simple thrift server in python (named PythonServer.py) with a single method that returns a string for learning purposes. The server code is below. I am having the following errors in the Thrift's python libraries when I run the server. Has anyone experienced this problem and suggest a workaround?
The execution output:
Starting server
Traceback (most recent call last):
File "/home/dae/workspace/BasicTestEnvironmentV1.0/src/PythonServer.py", line 38, in <module>
server.serve()
File "usr/lib/python2.6/site-packages/thrift/server/TServer.py", line 101, in serve
File "usr/lib/python2.6/site-packages/thrift/transport/TSocket.py", line 136, in listen
File "usr/lib/python2.6/site-packages/thrift/transport/TSocket.py", line 31, in _resolveAddr
TypeError: getaddrinfo() argument 1 must be string or None
PythonServer.java
port = 9090
import MyService as myserv
#from ttypes import *
# Thrift files
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
# Server implementation
class MyHandler:
# return server message
def sendMessage(self, text):
print text
return 'In the garage!!!'
# set handler to our implementation
handler = MyHandler()
processor = myserv.Processor(handler)
transport = TSocket.TServerSocket(port)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
# set server
server = TServer.TThreadedServer(processor, transport, tfactory, pfactory)
print 'Starting server'
server.serve() ##### LINE 38 GOES HERE ##########
Your problem is the line:
transport = TSocket.TServerSocket(port)
When calling TSocket.TServerSocket which a single argument, the value is treated as a host identifier, hence the error with getaddrinfo().
To fix that, change the line to:
transport = TSocket.TServerSocket(port=port)
I had this problem while running PythonServer.py ...
I changed this line
transport = TSocket.TServerSocket(9090)
to
transport = TSocket.TServerSocket('9090')
and my server started running.
I had a similar problem. My fix is
TSocket.TServerSocket('your server ip',port)

Categories

Resources