-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnection.py
More file actions
executable file
·93 lines (80 loc) · 2.75 KB
/
Copy pathconnection.py
File metadata and controls
executable file
·93 lines (80 loc) · 2.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env python
import socket
import ConfigParser
from time import sleep
class Connection:
def __init__(self, device="microcontroller", cfg="temp_settings.cfg", verbose=True):
'''
Initializes a Connection object using a TCP/IP socket.
PARAMETERS: Custom values for ip address, port, and timeout.
A config file is used where parameters are not given.
'''
self.verbose = verbose
config = ConfigParser.ConfigParser()
config.read(cfg)
self.ip = config.get(device,"ip")
self.port = config.getint(device,"port")
self.timeout = config.getint(device,"timeout")
self.connected = False
self.sock2micro = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect(self):
'''
Establishes the connection to the configured IP.
'''
try:
self.close()
self.log("Connecting to microcontroller at %s:%s." % \
(self.ip, self.port))
self.sock2micro = socket.socket(socket.AF_INET, \
socket.SOCK_STREAM)
self.sock2micro.settimeout(self.timeout)
self.sock2micro.connect((self.ip, self.port))
self.log("Connected successfully.")
self.connected = True
except socket.error, e:
self.log("%s error" % e)
self.connected = False
def close(self):
'''
Closes the connection.
'''
self.sock2micro.close()
self.connected = False
self.log("Connection closed.")
def send(self, data):
'''
Writes specified data to the socket.
PARAMETERS: data - Byte array to send
'''
if self.connected:
try:
self.sock2micro.send(data)
except socket.error, e:
self.log('%s error sending "%s"' % (e, data))
self.connected = False
def recv(self, length = 1024):
'''
Reads a specified number of bytes from the socket.
PARAMETERS: length - Number of bytes to read
RETURNS: received - bytes read, None if none are read
'''
if self.connected:
try:
received = self.sock2micro.recv(length)
return received
except socket.error, e:
self.log('%s error receiving %d bytes' % (e, length))
self.connected = False
return None
def log(self, msg):
if self.verbose:
print msg
if __name__ == "__main__":
conn = Connection()
while not conn.connected:
conn.connect()
sleep(0.01);
#conn.send("2")
#data = conn.recv(4)
#print data
conn.close()