1#!/usr/bin/env python 2 3# Copyright JS Foundation and other contributors, http://js.foundation 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16 17import select 18import serial 19 20class Serial(object): 21 """ Create a new socket using the given address family, socket type and protocol number. """ 22 def __init__(self, serial_config): 23 config = serial_config.split(',') 24 config_size = len(config) 25 26 port = config[0] if config_size > 0 else "/dev/ttyUSB0" 27 baudrate = config[1] if config_size > 1 else 115200 28 bytesize = int(config[2]) if config_size > 2 else 8 29 parity = config[3] if config_size > 3 else 'N' 30 stopbits = int(config[4]) if config_size > 4 else 1 31 32 self.ser = serial.Serial(port=port, baudrate=baudrate, parity=parity, 33 stopbits=stopbits, bytesize=bytesize, timeout=1) 34 35 def connect(self): 36 """ Connect to the server, write a 'c' to the serial port """ 37 self.send_data('c') 38 39 def close(self): 40 """" close the serial port. """ 41 self.ser.close() 42 43 def receive_data(self, max_size=1024): 44 """ The maximum amount of data to be received at once is specified by max_size. """ 45 return self.ser.read(max_size) 46 47 def send_data(self, data): 48 """ Write data to the serial port. """ 49 return self.ser.write(data) 50 51 def ready(self): 52 """ Monitor the file descriptor. """ 53 result = select.select([self.ser.fileno()], [], [], 0)[0] 54 55 return self.ser.fileno() in result 56