Raspberry pi and IFTTT and Google Home - raspberry-pi

i am trying to use my raspberry pi with google home through IFTTT but it seems that there is an error in my code.
So the situation is like this when i say "Hey google, turn on the servo", Google Mini will reply "Alright" and turn the servo.
However, i do get the reply "Alright" but my servo did not turn. Why is that so?
FYI: i am using raspberry pi 3 b+. The servo turns well without flask in the python code. Furthermore, when i access the url: XXX.XXX.XXX.XXX/5300, the servo did turned. What is the problem here?
This is my code
import RPi.GPIO as GPIO
from time import sleep
from flask import (Flask,render_template,request, jsonify)
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(13,GPIO.OUT)
app = Flask(__name__)
#app.route('/')
def index():
p = GPIO.PWM(13,50)
p.start(0)
p.ChangeDutyCycle(3)
sleep(1)
p.ChangeDutyCycle(12)
sleep(1)
p.stop
return 'Hello world'
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5300)
In my IFTTT,
For
(1) What do you want to say: Turn the $
(2) What do you want the Assistant to say in response?: Alright
(3) URL: http://XXX.XXX.XXX.XXX:5300/
(4) Method: GET

Try to replace:
return 'Hello world'
with:
print ('Request Received')
Check if 'Request Received' will appear in the console when you ask google to turn servo - means IFTTT was able to reach your raspberry pi.
If not, check if your port 5300 where Flask server is running is open, it might be that IFTTT can't reach RPi and you may need to forward it on the router.
Check another example on my blog IFTTT, Python and Flask
Might be good to specify the HTTP method for your route decorator:
#app.route("/api/v1/users/", methods=['GET'])

Related

Change url of a webpage on a local network

I built a webpage on an ESP32 chip, charged to create an access point allowing my computer to connect in order to access this page.
For the moment I can only access it using the IP of my ESP by typing it in a browser but it can be very bothersome.
I'd like to know if it was possible to change the url of the page using words instead of the ESP's IP.
Maybe I'm missing some technical terms but I didn't find any solution on the internet.
PS: I'm using micropython with sockets to serve html files from the board:
def handleClient(client_socket):
headers, data = loadRequest(client_socket.recv(1024).decode('utf-8'))
# print('[*] Received:\n%s\n%s\n' % (headers, data))
if headers['method'] == 'GET' and '/connect' == headers['route']:#'/connect' in headers['route']:
ssid, password, status, code = connect(headers)
client_socket.sendall(RESPONSE_TEMPLATE % (code, status, {'ssid': ssid, 'password': password}, code))
return ssid, password
elif headers['method'] == 'GET' and headers['route'] == '/':
renderWebPage(client_socket)
client_socket.close()
return None, None
there are two parts needed to solve your Q:
publish a name (using mdns)
resolve that name from a client
MicroPython has built-in support for mdns since v1.12.
The essential code is to assign a hostname using the below:
wlan.config(dhcp_hostname="prettyname")
Note that your client also needs to have mdns support in order to be able to resolve that address. That may/will depend on your client.
a complete sample would be:
import network
wlan = network.WLAN(network.STA_IF)
if not wlan.isconnected():
wlan.active(True)
mac = wlan.config('mac')
host = "prettyname"
wlan.config(dhcp_hostname = host)
wlan.connect('myssid', 'mypassword')
while not wlan.isconnected():
pass
host = wlan.config('dhcp_hostname')
print('Wifi connected as {}/{}, net={}, gw={}, dns={}'.format(
host, *wlan.ifconfig()))
Source: MicroPython Forum
Certainly. The easiest option is enabling mDNS. This allows hosts in the same local network to resolve the device's name (e.g. espressif.local) into its IP. Only works in local network and requires an mDNS client on the computer (Mac, Linux and Windows all tend to have it built in these days).
No idea how to do it in Micropython, though. Give Google a try.

GitLab health endpoint before integrating code

I’m new to deploying ML models and I want to deploy a model that contains several modules, each of which consist of “folders” containing some data files, .py scripts and a Python notebook.
I created a project in GitLab and I’m trying to follow tutorials on FastAPI since this is what I’m gonna be using. But I’ve been told that before I start integrating the code, I need to set up a health endpoint.
I know about the request curl "https://gitlab.example.com/-/health", but do I need to set up anything? Is there anything else I need to do for the project setup before doing the requirements.txt, building the skeleton of the application etc.?
It depend totaly of your needs, there is no health endpoint implemented natively in fastapi.
But I’ve been told that before I start integrating the code, I need to set up a health endpoint.
not necessarly a bad practice, you could start by listing all your futur health checks and build your route from there.
update from comment:
But I don’t know how to implement this. I need a config file? I’m very new to this.
From what i understand you are very new to python api so you should start by following the official fastapi user guide. You can also follow fastapi first steps from this.
Very basic one file project that run as is:
# main.py
from fastapi import FastAPI
app = FastAPI()
#app.get("/health")
async def root():
return {"message": "Alive!"}
Remember that the above is not suitable for production, only for testing/learning purposes, to make a production api you should follow the official advanced user guide and implement something like the following.
more advanced router:
You have this health lib for fastapi that is nice.
You can make basic checks like this:
# app.routers.health.py
from fastapi import APIRouter, status, Depends
from fastapi_health import health
from app.internal.health import healthy_condition, sick_condition
router = APIRouter(
tags=["healthcheck"],
responses={404: {"description": "not found"}},
)
#router.get('/health', status_code=status.HTTP_200_OK)
def perform_api_healthcheck(health_endpoint=Depends(health([healthy_condition, sick_condition]))):
return health_endpoint
# app.internal.health.py
def healthy_condition(): # just for testing puposes
return {"database": "online"}
def sick_condition(): # just for testing puposes
return True

GETS request not works after deploy

Works with the digital ocean server, mongo atlas and nodejs , front react
This is the problem I get in all the get requests on the site.
When I check like this I do get the information from mongo atlas
And that's what I get from cmd
[
Seems like you have a few things going on
The first screen shot says data.error is not defined.. So there is no .error as part of the data object, you may want to place that in a try catch OR if the call is promis based
then .catch( (e) =>{
console.log(e)
})
The later part of you post shows the error shows both apps are running on port 3000. PM2 in cluster mode will take care of multiple apps / port issues but if you are using PM2 to manage multiple applications they will need to be on different ports and then via nginx proxy 80 to that location.

openshift 3.12 websocket ERR_CONNECTION_ABORTED

I would like to start websocket connections (ws://whaterver)
in OpenShift but somehow they always ends with ERR_CONNECTION_ABORTED
immediately (new WebSocket('ws://whatever').
First I thought that the problem is in our application
but I created a minimal example and I got the same result.
First I created a pod and started this minimal Python websocket server.
import asyncio
import websockets
async def hello(websocket, path):
name = await websocket.recv()
print(f"< {name}")
greeting = f"Hello {name}!"
await websocket.send(greeting)
print(f"> {greeting}")
start_server = websockets.serve(hello, "0.0.0.0", 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Then I created a service (TCP 8000) and created a routing too and I got the same result.
I also tried to use different port or different targets (e.g.: /ws), without success.
This minimal script was able to respond to a simple http request, but for the websocket connection it can't.
Do you have any idea what could be the problem?
(by the documentation these connections should work as they are)
Should I try to play with some routing environment variables or are there any limitations which are not mentioned in the documentation?
Posting Károly Frendrich answer as community wiki:
Finally we realized that the TLS termination is required to be set.
It can be done using Secured Routes

Cloud9 bottle Web Server, accessed externally

I create a Web Server in python using bottle library. Its works fine and run in https://c9.io. I want access this web service externally.
I´m using host=os.environ['IP'] and port=os.environ['PORT'] to capture the port and ip environment variable.
How can I do it?
Another thing you can do is to replace your host as 0.0.0.0 instead of localhost. This will redirect you to your cloud9's localhost. For example, I'm running my app as:
bottle.run(host='0.0.0.0', port=8082)
You can access the server from a new tab after running your server.
Currently I am facing with the same problem and my solution was to start the app like this:
python myapp.py $IP $PORT
And inside the main module used entrypont2 to map those arguments to variable and use it for run bottle:
from bottle import run
from entrypoint2 import entrypoint
#...
#entrypoint
def main(ip, port):
run(server='gevent', host=ip, port=port, debug=True)
Then I can reach it from web browser using url like this:
http://<workspace>.<user>.c9.io/