HTTPS Get request with Micropython on a ESP8266 failing - esp8266

apologies upfront for being a complete SSL noob.
I´m starting to work with Micropython and ran into a problem that with HHTPS requests. With the below code on an ESP8266MOD 12F I try to get some information from a test API, but all I get is an error.
import urequests as requests
import network
WIFI_SSID = "***********"
WIFI_PW = "************"
def connect_wifi(wlan, ssid, password):
if not wlan.isconnected():
print("\nConnecting...")
wlan.connect(ssid, password)
while not wlan.isconnected():
pass
print("Wifi connected")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
connect_wifi(wlan, WIFI_SSID, WIFI_PW)
if not wlan.isconnected():
connect_wifi(wlan, WIFI_SSID, WIFI_PW)
else:
url = "http://api.coindesk.com/v1/bpi/currentprice.json"
r = requests.get(url)
print(r.text)
The error I get is:
Traceback (most recent call last):
File "<stdin>", line 25, in <module>
File "urequests.py", line 116, in get
File "urequests.py", line 62, in request
OSError: [Errno 107] ENOTCONN
My original attempt was to get to the Telelgram Bot API so I can send Telegram messages from my IoT devices. If I use an URL for the Telelgram API in the form of
url = "https://api.telegram.org/bot*****:***********/sendMessage?text=Klingel&chat_id=*****"
I get a different error which is
Traceback (most recent call last):
File "<stdin>", line 25, in <module>
File "urequests.py", line 116, in get
File "urequests.py", line 60, in request
OSError: [Errno 103] ECONNABORTED
When changing the Coindesk URL to HTTP, everything works fine. Unfortunately the Telegram API does not accept HTTP requests.
I tried several different urequests libraries as the on e isntalles via pip seemed to be a bit dated. The one I´m currently trying I got from github here. My ESP is running the current firmware esp8266-20220618-v1.19.1 from micropython.org.
I searched the internet for 4 days now and did not find anything that helped me. Nevertheless there seem to be quite some people to managed to use SSL in this configuration. As I am a true beginner in this whole topic, any help would be appreciated.
Thanks
Marcus

After some deeper digging I found out that the problem was caused by my Adguard DNS server which blocked the Telegram API. I did not see it on my laptop because it used a different DNS server. Now that I fixed the DNS issue, I´m getting OSError -40 which seems to be a common problem with the axTLS library used in the ESP8266. At least that makes sense to me now.
Thanks Andy for the quick reply.,

Related

Getting permission Error while calling API method using valid oauth2 access token

I am trying to authenticate using bearer token.
When I am trying to call the api with valid oauth2.0 access token
https://**************/api/method/frappe.auth.get_logged_user
I am getting this error response.
{
"exc": "[\"Traceback (most recent call last):\\n File \\\"/home/frappe/frappe-bench/apps/frappe/frappe/app.py\\\", line 66, in application\\n response = frappe.api.handle()\\n File \\\"/home/frappe/frappe-bench/apps/frappe/frappe/api.py\\\", line 56, in handle\\n return frappe.handler.handle()\\n File \\\"/home/frappe/frappe-bench/apps/frappe/frappe/handler.py\\\", line 21, in handle\\n data = execute_cmd(cmd)\\n File \\\"/home/frappe/frappe-bench/apps/frappe/frappe/handler.py\\\", line 54, in execute_cmd\\n is_whitelisted(method)\\n File \\\"/home/frappe/frappe-bench/apps/frappe/frappe/handler.py\\\", line 64, in is_whitelisted\\n raise frappe.PermissionError('Not Allowed, {0}'.format(method))\\nPermissionError: Not Allowed, <function get_logged_user at 0x7f9c027a9c08>\\n\"]",
"_server_messages": "[\"{\\\"message\\\": \\\"Not permitted\\\"}\"]"
}
Hard to tell without the code base. But it looks like the
execute_cmd(..)
is raising a Permissions error. I think the problem is with the script itself running on that machine. i.e. Not necessarily the access token. But without code this is a guess. You could verify by manually running that script when logged into the machine with the same user/permissions as when running as a web server.

JIRA application link token generation failure

We are trying to use the JIRA application link for creating the token. But we are getting the error as 400 response
Traceback (most recent call last):
File "generate_access_token.py", line 30, in
request_token = oauth.fetch_request_token(REQUEST_TOKEN_URL)
File "/usr/lib/python2.7/site-packages/requests_oauthlib/oauth1_session.py", line 284, in fetch_request_token
token = self._fetch_token(url, **request_kwargs)
File "/usr/lib/python2.7/site-packages/requests_oauthlib/oauth1_session.py", line 368, in _fetch_token
raise TokenRequestDenied(error % (r.status_code, r.text), r)
requests_oauthlib.oauth1_session.TokenRequestDenied: Token request failed with code 400, response was 'oauth_parameters_absent=oauth_consumer_key&oauth_problem=parameter_absent'.
Can someone please help?
The error seems to explain that a value for oauth_consumer_key is not being passed.
The parameter_absent error means that you are not sending the required OAuth parameters to the actual endpoint.
Can you check if this is being passed correctly or if it is not being passed totally? Adding your code snippet should help others help you identify the issue quickly!
Hope this answers your question!

Libcloud ECS access

trying to test out the ECS driver of libcloud for a project.
i wrote a simple test:
with open("conf.json") as f:
data = json.loads(f.read())
driver = get_driver(getattr(Provider,'ECS'))
with open('.cloud_credentials/'+data['provider']+'/access_id', 'r') as myfile:
ACCESS_KEY_ID = myfile.read().replace('\n', '')
print ACCESS_KEY_ID
with open('.cloud_credentials/'+data['provider']+'/secret_key', 'r') as myfile:
SECRET_KEY = myfile.read().replace('\n', '')
print SECRET_KEY
timer.start()
conn = driver(access_id = ACCESS_KEY_ID,
secret = SECRET_KEY,
region = 'us-east-1')
timer.stop()
cluster = conn.create_cluster('pippo','us-east-1')
However running it produce this error:
Traceback (most recent call last):
File "launch.py", line 32, in <module>
cluster = conn.create_cluster('pippo',data['region'])
File "/home/sergio/anaconda2/lib/python2.7/site-packages/libcloud/container/drivers/ecs.py", line 151, in create_cluster
headers=self._get_headers('CreateCluster')
File "/home/sergio/anaconda2/lib/python2.7/site-packages/libcloud/common/base.py", line 604, in request
headers=headers, stream=stream)
File "/home/sergio/anaconda2/lib/python2.7/site-packages/libcloud/http.py", line 212, in request
verify=self.verification
File "/home/sergio/anaconda2/lib/python2.7/site-packages/requests/sessions.py", line 468, in request
resp = self.send(prep, **send_kwargs)
File "/home/sergio/anaconda2/lib/python2.7/site-packages/requests/sessions.py", line 576, in send
r = adapter.send(request, **kwargs)
File "/home/sergio/anaconda2/lib/python2.7/site-packages/requests/adapters.py", line 437, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='ecs.%s.amazonaws.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f5f16dca950>: Failed to establish a new connection: [Errno -2] Name or service not known',))
I Think that the problem lies with the host string, containing that %s. Digging in the library looks like that string is a dummy one initialized in the file:
/libcloud/container/drivers/ecs.py
I suppose that there should be somewhere in those files a function supposed to overwrite the base-string, that probably doesn't get called for some reasons but, being a novice with the libcloud library, makes it kind of difficult to find the culprit.
Curiously, inspecting the headers that are being sent, looks like they contain the correct(?) address there:
headers: {'Host': u'ecs.us-east-1.amazonaws.com', 'User-Agent': 'libcloud/2.2.1 (Amazon Elastic Container Service) ', 'Content-Type': 'application/x-amz-json-1.1', 'Accept-Encoding': 'gzip,deflate', 'x-amz-target': 'AmazonEC2ContainerServiceV20141113.CreateCluster'}
Anyone with more experience could point me in the right direction? It would be much appreciated.
This looks like a bug, it's not something you've done.

How to send a request to twitter using a proxy?

I'm trying to extract data from twitter. When I use the code in my home network, it works very well, but in my university we use a proxy server. So I need to configure the request. I'm not specialised on computer science, so I don't know how to modify the request.
I read the documentation in https://dev.twitter.com/ but I couldn't find a solution!
This is an exemple of code :
import tweepy
from tweepy import OAuthHandler
consumer_key = 'XXXXXXXXXX'
consumer_secret = 'XXXXXXXXXXXX'
access_token = 'XXXXXXXXXXXXXXXXXXXX'
access_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)
for status in tweepy.Cursor(api.home_timeline).items(100):
# Process a single status
print(status.text)
This is the error I got:
Traceback (most recent call last):
File "D:\formation\python\github tools\fbp.py", line 14, in <module>
for status in tweepy.Cursor(api.home_timeline).items(100):
File "C:\Anaconda\lib\site-packages\tweepy\cursor.py", line 197, in next
self.current_page = self.page_iterator.next()
File "C:\Anaconda\lib\site-packages\tweepy\cursor.py", line 108, in next
data = self.method(max_id=self.max_id, parser=RawParser(), *self.args, **self.kargs)
File "C:\Anaconda\lib\site-packages\tweepy\binder.py", line 245, in _call
return method.execute()
File "C:\Anaconda\lib\site-packages\tweepy\binder.py", line 189, in execute
raise TweepError('Failed to send request: %s' % e)
TweepError: Failed to send request: HTTPSConnectionPool(host='api.twitter.com', port=443): Max retries exceeded with url: /1.1/statuses/home_timeline.json (Caused by ProxyError('Cannot connect to proxy.', error('Tunnel connection failed: 407 Authentification proxy requise',)))
You can add a proxy using the follow code:
api =tweepy.API(auth,proxy="127.0.0.1:1080")
It works on my computer. You can try to modify you code like this.

Graphstory and Neo4jphp

I have succesfully used neo4jphp library with graphenedb with this simple steps as per documentation (considering that graphenedb does not require https)
require('vendor/autoload.php'); // or your custom autoloader
// Connecting to a different port or host
$client = new Everyman\Neo4j\Client(url, port);
// Connecting using HTTP and Basic Auth
$client->getTransport()
->setAuth('username', 'password');
// Test connection to server
print_r($client->getServerInfo());
However, when trying to connect to a graphstory instance (of course they both work fine if I call the rest api from browser, the neo4j console works fine etc.) which requires https as follows
require('vendor/autoload.php'); // or your custom autoloader
// Connecting to a different port or host
$client = new Everyman\Neo4j\Client(url, port);
// Connecting using HTTPS and Basic Auth
$client->getTransport()
->useHttps()
->setAuth('username', 'password');
// Test connection to server
print_r($client->getServerInfo());
I get the following error. They should be identical, I can't get why.
Fatal error: Uncaught exception 'Everyman\Neo4j\Exception' with message 'Can't open connection to https://neo-54f500bf2cc7e-364459c455.do-stories.graphstory.com:7473/db/data/' in /Applications/XAMPP/xamppfiles/htdocs/graphene/vendor/everyman/neo4jphp/lib/Everyman/Neo4j/Transport/Curl.php:91
Stack trace:
#0 /Applications/XAMPP/xamppfiles/htdocs/graphene/vendor/everyman/neo4jphp/lib/Everyman/Neo4j/Transport.php(95): Everyman\Neo4j\Transport\Curl->makeRequest('GET', '/', NULL)
#1 /Applications/XAMPP/xamppfiles/htdocs/graphene/vendor/everyman/neo4jphp/lib/Everyman/Neo4j/Command.php(64): Everyman\Neo4j\Transport->get('/', NULL)
#2 /Applications/XAMPP/xamppfiles/htdocs/graphene/vendor/everyman/neo4jphp/lib/Everyman/Neo4j/Client.php(828): Everyman\Neo4j\Command->execute()
#3 /Applications/XAMPP/xamppfiles/htdocs/graphene/vendor/everyman/neo4jphp/lib/Everyman/Neo4j/Client.php(464): Everyman\Neo4j\Client->runCommand(Object(Everyman\Neo4j\Command\GetServerInfo))
#4 /Applications/XAMPP/xamppfiles/htdocs/graphene/story.php(20): Every in /Applications/XAMPP/xamppfiles/htdocs/graphene/vendor/everyman/neo4jphp/lib/Everyman/Neo4j/Transport/Curl.php on line 91
It seems to me that neo4jphp is not configuring the TLS part in the cURL request.
I fixed it by downloading the certificate bundle from http://curl.haxx.se/docs/caextract.html (ca_bundle.crt) and adding the following line to Everyman\Neo4j\Transport\Curl.php, function makeRequest:
$options[CURLOPT_CAINFO] = "your/path/to/ca-bundle.crt";
I've created an issue on GitHub for this: https://github.com/jadell/neo4jphp/issues/171
I'm the CTO/Lead Dev at Graph Story. Sorry to hear you're having troubles. I've actually just taken a look at your instance and things seem OK from the server side.
Without additional info it's hard to say if there's an issue with your sample connection code. Considering that you've used that same library to connect to GrapheneDB in the past, I think the chances an error in the sample code is low.
Based on the current state of your instance and on the exception thrown by Neo4jPHP, my guess is that port 7473 may be blocked on your network. You can confirm that with local tech support or by switching to a network where you know port 7473 is open and trying to connect again.

Resources