Exemple #1
0
// Init attempts to initialises the port represented by the port name passed in.
func Init(s *Conf, name string) (int32, error) {
	var result int32 = SP_OK
	C.sp_new_config(&s.oldConfig)
	C.sp_new_config(&s.newConfig)
	cp := C.CString(name)
	defer C.free(unsafe.Pointer(cp))
	result = C.sp_get_port_by_name(cp, &s.Port)
	checkResult(result)
	// Open before setting params
	result = C.sp_open(s.Port, SP_MODE_READ|SP_MODE_WRITE)
	return result, checkResult(result)
}
func (p *Port) getConf() error {
	if p.c == nil {
		if err := errmsg(C.sp_new_config(&p.c)); err != nil {
			return err
		}
	}
	return errmsg(C.sp_get_config(p.p, p.c))
}
// Apply port options.
func (p *Port) Apply(o *Options) (err error) {
	// get port config
	var conf *C.struct_sp_port_config
	if err = errmsg(C.sp_new_config(&conf)); err != nil {
		return
	}
	defer C.sp_free_config(conf)

	// set bit rate
	if o.BitRate != 0 {
		err = errmsg(C.sp_set_config_baudrate(conf, C.int(o.BitRate)))
		if err != nil {
			return
		}
	}

	// set data bits
	if o.DataBits != 0 {
		err = errmsg(C.sp_set_config_bits(conf, C.int(o.DataBits)))
		if err != nil {
			return
		}
	}

	// set stop bits
	if o.StopBits != 0 {
		err = errmsg(C.sp_set_config_stopbits(conf, C.int(o.StopBits)))
		if err != nil {
			return
		}
	}

	// set parity
	if o.Parity != 0 {
		cparity := parity2c(o.Parity)
		if err = errmsg(C.sp_set_config_parity(conf, cparity)); err != nil {
			return
		}
	}

	// set flow control
	if o.FlowControl != 0 {
		cfc, err := flow2c(o.FlowControl)
		if err != nil {
			return err
		}
		if err = errmsg(C.sp_set_config_flowcontrol(conf, cfc)); err != nil {
			return err
		}
	}

	// set RTS
	if o.RTS != 0 {
		crts := rts2c(o.RTS)
		if err = errmsg(C.sp_set_config_rts(conf, crts)); err != nil {
			return
		}
	}

	// set CTS
	if o.CTS != 0 {
		ccts := cts2c(o.CTS)
		if err = errmsg(C.sp_set_config_cts(conf, ccts)); err != nil {
			return
		}
	}

	// set DTR
	if o.DTR != 0 {
		cdtr := dtr2c(o.DTR)
		if err = errmsg(C.sp_set_config_dtr(conf, cdtr)); err != nil {
			return
		}
	}

	// set DSR
	if o.DSR != 0 {
		cdsr := dsr2c(o.DSR)
		if err = errmsg(C.sp_set_config_dsr(conf, cdsr)); err != nil {
			return
		}
	}

	// apply config
	if err = errmsg(C.sp_set_config(p.p, conf)); err != nil {
		return
	}

	// update local config
	return p.getConf()
}