123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172 |
- package door
- import (
- "bytes"
- "log"
- "sync"
- "syscall"
- )
- type OSWriter struct {
- Mutex sync.Mutex
- Closed bool
- Handle int
- TranslateNL bool
- TranslateToUnicode bool
- nlBuffer *bytes.Buffer
- uniBuffer *bytes.Buffer
- }
- func (ow *OSWriter) Init(d *Door) {
- ow.Closed = false
- ow.Handle = d.Config.Comm_handle
- ow.TranslateNL = true
- ow.nlBuffer = &bytes.Buffer{}
- }
- func (ow *OSWriter) CP437toUnicode(output []byte) []byte {
- if ow.uniBuffer == nil {
- ow.uniBuffer = &bytes.Buffer{}
- }
- return ow.uniBuffer.Bytes()
- }
- func (ow *OSWriter) NewLines(output []byte) []byte {
- var pos, nextpos int
- ow.nlBuffer.Reset()
- for pos != -1 {
- nextpos = bytes.Index(output[pos:], []byte{'\n'})
- if nextpos != -1 {
- nextpos += pos
-
- ow.nlBuffer.Write(output[pos:nextpos])
- nextpos++
- pos = nextpos
- ow.nlBuffer.Write([]byte("\r\n"))
- } else {
- ow.nlBuffer.Write(output[pos:])
- pos = nextpos
- }
- }
-
- return ow.nlBuffer.Bytes()
- }
- func (ow *OSWriter) OSWrite(buffer []byte) (int, error) {
- var buff []byte = buffer
- if DEBUG_DOOR {
- if ow.Mutex.TryLock() {
- log.Panic("OSWrite: mutex was NOT locked.")
- }
- }
-
- if ow.TranslateNL {
- buff = ow.NewLines(buff)
- }
- n, err := syscall.Write(ow.Handle, buff)
- if (err != nil) || (n != len(buff)) {
- if !ow.Closed {
- ow.Closed = true
-
-
- }
- }
- return n, err
- }
- func (ow *OSWriter) Write(buffer []byte) (int, error) {
- ow.Mutex.Lock()
- defer ow.Mutex.Unlock()
- if ow.Closed {
- return 0, ErrDisconnected
- }
-
-
-
-
-
- return ow.OSWrite(buffer)
- }
- func (ow *OSWriter) Stop() {
- ow.Mutex.Lock()
- defer ow.Mutex.Unlock()
- ow.Closed = true
- }
- func (ow *OSWriter) IsClosed() bool {
- ow.Mutex.Lock()
- defer ow.Mutex.Unlock()
- return ow.Closed
- }
|