Giter Site home page Giter Site logo

serialport's Introduction

SerialPort

Build Status Build status codecov Dub Downloads License

Docs generated by adrdox.

Library provides versatile work with serial port for Linux, Windows and MacOS.

Simple usage

auto com = new SerialPortBlk("/dev/ttyUSB0", 19200);

// setting parameters example
com.config = SPConfig(9600, DataBits.data8, Parity.none, StopBits.one)
com.set(19200).set(DataBits.data8);
com.stopBits = StopBits.two;
// set 9600 baudrate, 8 data bits, no parity and one stop bit
com.set("9600:8N1");

auto cnt = com.write(someDataArray);
// cnt must be equal someDataArray.length

// res1 is slice of bufferForReading with readed data
auto res1 = com.read(bufferForReading);

See also example: monitor.

Class hierarchy

         abstract
      SerialPortBase
        ^        ^
        |        |
        |   SerialPortNonBlk
        |
    abstract
   SerialPort
     ^     ^
     |     |
     |  SerialPortFR
     |
SerialPortBlk

Class SerialPortBase provides work with settings (baudrate, stop bits etc).

Class SerialPortNonBlk provides non-blocking void[] read(void[] buf) (immediatlly return data in system serial port buffer) and size_t write(const(void[])) (return writed bytes count at the first onset).

Class SerialPort provides void[] read(void[] buf, CanRead cr=CanRead.allOrNothing), void write(const(void[])) and timeouts properties.

Class SerialPortBlk provides blocking read and write.

If you want use library in fibers it provides SerialPortFR (Fiber Ready), where read and write is loops: call non-blocking read and write and sleep between tries. Loops algorithms use Fiber.yield if available, or Thread.sleep as failback. If you want redefine this behavior, you can set void delegate(Duration) @nogc sleepFunc field directly or through last parameter of ctor.

write method of SerialPort can throw TimeoutException if it can't finish write all data to serial port during timeout = writeTimeout + writeTimeoutMult * data.length.

read method of SerialPort also can throw TimeoutException, but here the behavior can be different depending on the CanRead flag.

Receive data time schema:

---|-------|--------------|-------|--> t
 call      |              |       |
 read      |              |       |
   |       |<----data receive---->|
   |       |=====   ====  | ======|
   |       |              |
   |       |<-readedData->|
   |                      |
   |<---readTimeoutSum--->|
   |                   return
   |<---read work time--->|

where readTimeoutSum = readTimeout + readTimeoutMult * dataBuffer.length;

if CanRead cr flag is:

  • CanRead.allOrNothing

    if (readedData.length < dataBuffer.length)
        throw TimeoutException(port);
    else return readedData;
  • CanRead.anyNonZero

    if (readedData.length == 0)
        throw TimeoutException(port);
    else return readedData;
  • CanRead.zero

    return readedData;

SerialPortFR.readContinues method

void[] readContinues(void[] arr, Duration startTimeout=1.seconds, Duration frameGap=50.msecs, bool expectAnything=true)

It reads in loop from serial port while silent time is less what frameGap and throws TimeoutException only if timeout is expires when no data was readed and expectAnything flag is setted.

------|--------|-----|------------|-----|------------> t
    call       |     |            |     |
readContinues  |     |            |     |
      |        |     |            |     |
      |        |<---------data receive---------->|
      |        |=== =====   ======|     |   |== =| data stream
      |        |     |  |   |     |     |
      |<--timeout--->|  |   |     |     |
      |        |<-1->|  |<2>|     |<-3->|
      |        |                  |     |
      |        |<---readedData--->|     |
      |                               return
      |<-------readAll work time------->|

(1) if readedData.length > 0 then continue reading
    else if expectAnything throw TimeoutException
    else return readedData (empty)
(2) silent time, if silent < frameGap then continue reading
(3) else if silent > frameGap then stop reading
    and return readedData

It's useful if you don't know how much data can come:

  • allocate buffer for reading (4kB for example)
  • call readContinues and get data frame

Warning

unix systems allow only standard speeds:

[0, 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400]

Tests

Real hardware

Two paired USB->UART (FTDI FT232RL) uses for tests on linux and windows.

CI

For linux and OSX tested (socat as tty pipe creator)

  • dmd (from 2.79.1 to actual and nightly)
  • ldc (from 1.8.0 to actual and beta)

For windows tested (build only, see note) fox x86 and x64

  • dmd stable and nightly
  • ldc stable and beta

See .travis.yml .appveyor.yml

NOTE

  1. Windows not full tested by CI (no real test with virtual com ports) because I did not configure to adjust the work com0com program https://help.appveyor.com/discussions/questions/427-how-can-i-use-com0com

serialport's People

Contributors

chocopi avatar deviator avatar wilzbach avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

serialport's Issues

error in test

I use your modbus lib in my project, but when I test it:

> dub test -q                                                                                          master ⬆ ◼
../../../.dub/packages/serialport-2.2.3/serialport/source/serialport/util.d(59,6): Error: typesafe variadic function parameter `list` of type `Pair!(int, int)[]` cannot be marked `return`
/usr/bin/dmd failed with exit code 1.
> dmd --version                                                                                    ✘ 2 master ⬆ ◼
DMD64 D Compiler v2.100.0

but if I test your source:

> cd ~/d/serialport/                                                                                   master ⬆ ◼
> git describe                                                                                             master
v2.2.3
> dub test -q                                                                                              master
=== start real test ===
...
> cd ~/d/serialport/                                                                                   master ⬆ ◼
[I] [10:13:50] o3o@forty /home/o3o/d/serialport
> git describe                                                                                             master
v2.2.3
[I] [10:13:57] o3o@forty /home/o3o/d/serialport
> dub test -q                                                                                              master
=== start real test ===
...
<<< success fiber sleep func test
=== finish real test ===
4 modules passed unittests

odd...

fix a compile error on the windows platform

port.d

static string[] listAvailable() @property
{
    ...
    
    version (Windows)
    {
        import std.windows.registry;
        auto vals = Registry
                .localMachine()
                .getKey("HARDWARE")
                .getKey("DEVICEMAP")
                .getKey("SERIALCOMM")
                .values;

        string [] arr;
        foreach(v;vals)
            arr ~= v.value_SZ;
        return arr;
    }
}

Build error with ldc-1.18.0

First, thanks for this great library.

Now, I can't compile it with ldc-1.18.0. The output is following:

/home/bobalus/dlang/ldc-1.18.0/bin/../import/std/traits.d(8387,5): Error: template instance isAggregateType!(exception) does not match template declaration isAggregateType(T)
../../.dub/packages/serialport-2.2.0/serialport/source/serialport/exception.d(148,26):        while looking for match for getSymbolsByUDA!(exception, preallocated)
/home/bobalus/dlang/ldc-1.18.0/bin/ldc2 failed with exit code 1.

Build is successful with ldc-1.17.0, 1.15.0.

UPD: little investigation reveals that it is troubles with phobos library.

dlang/phobos@86733d5

Then issue was opened
https://issues.dlang.org/show_bug.cgi?id=20054

There was another pull request to revert changes, but still is not approved.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.