Created
March 5, 2020 07:18
-
-
Save aonurdemir/115d6ef662304a6a43ac2cf5b031a28c to your computer and use it in GitHub Desktop.
Simple TCP Server for microcontrollers which should not use HTTP/json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##########TCP SERVER ####################### | |
#If you are already familiar with django, and your microcontroller supports sending HTTP (REST) requests and can parse Json , you can just add a regular django based view that returns json: | |
# views.py | |
from django.http import JsonResponse | |
def my_view(request): | |
# handle input here, probably using request.GET / request.POST | |
return JsonResponse({'status': 'OK'}) | |
#However, if your microcontroller is very simple and cannot do HTTP/json, you can use a simple SocketServer from python's standard library instead: | |
import SocketServer | |
class MyTCPHandler(SocketServer.BaseRequestHandler): | |
def handle(self): | |
self.data = self.request.recv(1024).strip() | |
print "{} wrote:".format(self.client_address[0]) | |
print self.data | |
# just send back the same data, but upper-cased | |
self.request.sendall(self.data.upper()) | |
if __name__ == "__main__": | |
HOST, PORT = "localhost", 9999 | |
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler) | |
server.serve_forever() | |
#Keep in mind you can still import django's libraries and use django's ORM (DB) inside a SocketServer. | |
#Another popular option is to use Tornado's tcpserver: | |
from tornado.ioloop import IOLoop | |
from tornado.tcpserver import TCPServer | |
class MyTCPServer(TCPServer): | |
def handle_stream(self, stream, address): | |
def got_data(data): | |
print "Input: {}".format(repr(data)) | |
stream.write("OK", stream.close) | |
stream.read_until("\n", got_data) | |
if __name__ == '__main__': | |
server = MyTCPServer() | |
server.listen(9876) | |
IOLoop.instance().start() | |
######################################################################################## |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment