Skip to content

Instantly share code, notes, and snippets.

@Maarrk
Created May 17, 2023 13:45
Show Gist options
  • Save Maarrk/905984bdbc5cf34f16ae9174e4d83b2a to your computer and use it in GitHub Desktop.
Save Maarrk/905984bdbc5cf34f16ae9174e4d83b2a to your computer and use it in GitHub Desktop.
Help Haptics
from http.server import BaseHTTPRequestHandler, HTTPServer
import socket
import time
hostName = "0.0.0.0" # Accept any address
# serve on port 8080 (try in this pc like http://localhost:8080)
serverPort = 8080
arduinoSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
arduinoAddress = '192.168.222.33'
arduinoPort = 1234
class MyServer(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(
"<html><head><title>Basic server</title></head><body>".encode("utf-8"))
if self.path == '/start':
self.wfile.write("<p>Starting vibration</p>".encode('utf8'))
arduinoSocket.sendto('start'.encode('ascii'),
(arduinoAddress, arduinoPort))
elif self.path == '/stop':
self.wfile.write("<p>Stopping vibration</p>".encode('utf8'))
arduinoSocket.sendto('stop'.encode('ascii'),
(arduinoAddress, arduinoPort))
elif self.path != '/':
self.wfile.write(
"<p>Unrecognised command: {}</p>".format(self.path).encode('utf8'))
self.wfile.write(
"<p>This is a server to control the arduino on address {}, port {}</p>".format(arduinoAddress, arduinoPort).encode("utf-8"))
self.wfile.write("</body></html>".encode("utf-8"))
if __name__ == "__main__":
webServer = HTTPServer((hostName, serverPort), MyServer)
print("Server started http://{}:{}".format(hostName, serverPort))
try:
webServer.serve_forever()
except KeyboardInterrupt:
pass
webServer.server_close()
print("Server stopped.")
import socket
UDP_IP = "0.0.0.0"
UDP_PORT = 1234
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
sock.settimeout(1.0)
while True:
try:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print("Received:", data)
except socket.timeout:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment