Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added read/write functional with timeout var (instead of deadline) #7

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions serial.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,8 @@ type Port struct {
c *C.struct_sp_port_config
readDeadline time.Time
writeDeadline time.Time
readTimeout time.Duration
writeTimeout time.Duration
}

// Implementation of net.Addr
Expand Down Expand Up @@ -290,6 +292,20 @@ func deadline2millis(deadline time.Time) int64 {
return millis
}

//
func timeout2millis(timeout time.Duration) int64 {
duration := timeout + time.Millisecond - time.Nanosecond
duration /= time.Millisecond

millis := int64(duration)

if Debug {
log.Printf("timeout: %d ms", millis)
}

return millis
}

// Print libserialport debug messages to stderr.
func SetDebug(enable bool) {
if enable {
Expand Down Expand Up @@ -995,7 +1011,12 @@ func (p *Port) Read(b []byte) (int, error) {

buf, size := unsafe.Pointer(&b[0]), C.size_t(len(b))

if p.readDeadline.IsZero() {
if millis := timeout2millis(p.readTimeout); millis > 0 {

// call blocking read
c = C.sp_blocking_read(p.p, buf, size, C.uint(millis))

} else if p.readDeadline.IsZero() {

// no deadline
c = C.sp_blocking_read(p.p, buf, size, 0)
Expand Down Expand Up @@ -1042,7 +1063,12 @@ func (p *Port) Write(b []byte) (int, error) {

buf, size := unsafe.Pointer(&b[0]), C.size_t(len(b))

if p.writeDeadline.IsZero() {
if millis := timeout2millis(p.writeTimeout); millis > 0 {

// call blocking write
c = C.sp_blocking_write(p.p, buf, size, C.uint(millis))

} else if p.writeDeadline.IsZero() {

// no deadline
c = C.sp_blocking_write(p.p, buf, size, 0)
Expand Down Expand Up @@ -1098,6 +1124,13 @@ func (p *Port) SetDeadline(t time.Time) error {
return nil
}

// Set timeout
func (p *Port) SetTimeout(t time.Duration) error {
p.readTimeout = t
p.writeTimeout = t
return nil
}

// Implementation of net.Conn.SetReadDeadline
func (p *Port) SetReadDeadline(t time.Time) error {
p.readDeadline = t
Expand Down