Created
November 26, 2015 01:15
-
-
Save joffilyfe/cfe3f0a2a19b36a9b3bc to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# -*- coding: utf-8 -*- | |
import SocketServer | |
import serial | |
import time | |
class SerialHandler(object): | |
''' | |
Classe responsável pela comunicação serial | |
''' | |
port = '/dev/tty.usbmodem1421' | |
speed = 9600 | |
def connect(self): | |
''' | |
Faz a conexão com a porta do Arduino | |
''' | |
try: | |
self.connection = serial.Serial(self.port, | |
self.speed, timeout=2000, | |
stopbits=serial.STOPBITS_TWO) | |
except: | |
print('Cant connect') | |
return | |
def sendMessage(self, msg): | |
''' | |
Envia uma mensagem na porta serial | |
''' | |
self.connection.write(msg) | |
print(msg) | |
print(msg) | |
print(msg) | |
def closeConnection(self): | |
''' | |
Encerra a conexão na porta serial | |
''' | |
self.connection.close() | |
class MyTCPHandler(SocketServer.BaseRequestHandler, SerialHandler): | |
def handle(self): | |
# self.request is the TCP socket connected to the client | |
self.data = self.request.recv(1024).strip() | |
print "{} wrote:".format(self.client_address[0]) | |
print self.data | |
try: | |
self.connect() | |
''' | |
Foi preciso esse hack para conseguir passar as mensagens ao arduino | |
em tempo hábil | |
''' | |
time.sleep(1.5) | |
self.sendMessage(self.data) | |
self.closeConnection() | |
except: | |
pass | |
self.request.sendall(self.data.upper()) | |
if __name__ == "__main__": | |
HOST, PORT = "localhost", 9999 | |
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler) | |
server.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment