Yet Another WebIOPi+
 All Classes Namespaces Files Functions Variables Macros Pages
serial.py
Go to the documentation of this file.
1 # Copyright 2012-2013 Eric Ptak - trouch.com
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 
15 import os
16 import fcntl
17 import struct
18 import termios
19 
20 from webiopi.devices.bus import Bus
21 from webiopi.decorators.rest import request, response
22 
23 TIOCINQ = hasattr(termios, 'FIONREAD') and termios.FIONREAD or 0x541B
24 TIOCM_zero_str = struct.pack('I', 0)
25 
26 class Serial(Bus):
27  def __init__(self, device="/dev/ttyAMA0", baudrate=9600):
28  if not device.startswith("/dev/"):
29  device = "/dev/%s" % device
30 
31  if isinstance(baudrate, str):
32  baudrate = int(baudrate)
33 
34  aname = "B%d" % baudrate
35  if not hasattr(termios, aname):
36  raise Exception("Unsupported baudrate")
37  self.baudrate = baudrate
38 
39  Bus.__init__(self, "UART", device, os.O_RDWR | os.O_NOCTTY)
40  fcntl.fcntl(self.fd, fcntl.F_SETFL, os.O_NDELAY)
41 
42  #backup = termios.tcgetattr(self.fd)
43  options = termios.tcgetattr(self.fd)
44  # iflag
45  options[0] = 0
46 
47  # oflag
48  options[1] = 0
49 
50  # cflag
51  options[2] |= (termios.CLOCAL | termios.CREAD)
52  options[2] &= ~termios.PARENB
53  options[2] &= ~termios.CSTOPB
54  options[2] &= ~termios.CSIZE
55  options[2] |= termios.CS8
56 
57  # lflag
58  options[3] = 0
59 
60  speed = getattr(termios, aname)
61  # input speed
62  options[4] = speed
63  # output speed
64  options[5] = speed
65 
66  termios.tcsetattr(self.fd, termios.TCSADRAIN, options)
67 
68  def __str__(self):
69  return "Serial(%s, %dbps)" % (self.device, self.baudrate)
70 
71  def __family__(self):
72  return "Serial"
73 
74  def available(self):
75  s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str)
76  return struct.unpack('I',s)[0]
77 
78  @request("GET", "")
79  @response("%s")
80  def readString(self):
81  if self.available() > 0:
82  return self.read(self.available()).decode()
83  return ""
84 
85  @request("POST", "", "data")
86  def writeString(self, data):
87  if isinstance(data, str):
88  self.write(data.encode())
89  else:
90  self.write(data)
tuple response
Definition: coap-client.py:9