Merge pull request #601 from just-stuff-tm/dev
Fix Linux USB open crash and the glibc 2.39 release bundle
This commit is contained in:
74 files changed
+16313
-4
No files matched your search
@@ -82,6 +82,32 @@ if(TARGET flserial)
|
||||
target_compile_definitions(flserial PRIVATE __STDC_NO_THREADS__)
|
||||
endif()
|
||||
|
||||
# Issue zjs81/meshcore-open#600: the release zip must contain
|
||||
# libonnxruntime.so.1 and must not depend on the build machine's absolute
|
||||
# path. The plugin is linked against that library by absolute path, so CMake
|
||||
# records the download directory as the plugin RUNPATH, and install(FILES)
|
||||
# ships that build-tree file unchanged. The loader uses the plugin RUNPATH,
|
||||
# not the executable RPATH, when resolving the plugin's libonnxruntime.so.1
|
||||
# dependency. Keep the download directory so ld can resolve the SONAME while
|
||||
# linking meshcore_open, and add $ORIGIN so the copy installed next to the
|
||||
# plugin is found on a machine that does not have this build tree. Do not set
|
||||
# SKIP_BUILD_RPATH: without the download directory the link fails with
|
||||
# "libonnxruntime.so.1, needed by libflutter_onnxruntime_plugin.so, not found".
|
||||
if(TARGET flutter_onnxruntime_plugin)
|
||||
file(GLOB _onnx_link_libs
|
||||
"${CMAKE_BINARY_DIR}/plugins/flutter_onnxruntime/onnxruntime/onnxruntime-linux-*/lib/libonnxruntime.so"
|
||||
"${PROJECT_BINARY_DIR}/plugins/flutter_onnxruntime/onnxruntime/onnxruntime-linux-*/lib/libonnxruntime.so")
|
||||
if(_onnx_link_libs)
|
||||
list(GET _onnx_link_libs 0 _onnx_link_lib)
|
||||
get_filename_component(_onnx_lib_dir "${_onnx_link_lib}" DIRECTORY)
|
||||
set_target_properties(flutter_onnxruntime_plugin PROPERTIES
|
||||
BUILD_RPATH "\$ORIGIN;${_onnx_lib_dir}")
|
||||
endif()
|
||||
endif()
|
||||
set_target_properties(${BINARY_NAME} PROPERTIES
|
||||
INSTALL_RPATH "$ORIGIN/lib")
|
||||
target_link_options(${BINARY_NAME} PRIVATE "-Wl,--disable-new-dtags")
|
||||
|
||||
|
||||
# === Installation ===
|
||||
# By default, "installing" just makes a relocatable bundle in the build
|
||||
@@ -114,6 +140,27 @@ foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES})
|
||||
COMPONENT Runtime)
|
||||
endforeach(bundled_library)
|
||||
|
||||
# Copy ONNX Runtime under the names the dynamic linker asks for. The plugin
|
||||
# bundles libonnxruntime.so, which is a symlink; the NEEDED entry is
|
||||
# libonnxruntime.so.1.
|
||||
install(CODE "
|
||||
set(_onnx_roots
|
||||
\"${CMAKE_BINARY_DIR}/plugins/flutter_onnxruntime/onnxruntime\"
|
||||
\"${PROJECT_BINARY_DIR}/plugins/flutter_onnxruntime/onnxruntime\")
|
||||
foreach(_root \${_onnx_roots})
|
||||
file(GLOB _onnx_libs
|
||||
\"\${_root}/onnxruntime-linux-*/lib/libonnxruntime.so*\"
|
||||
\"\${_root}/onnxruntime-linux-*/lib/libonnxruntime_providers_shared.so\")
|
||||
foreach(_lib \${_onnx_libs})
|
||||
get_filename_component(_name \"\${_lib}\" NAME)
|
||||
execute_process(COMMAND readlink -f \"\${_lib}\"
|
||||
OUTPUT_VARIABLE _real OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
execute_process(COMMAND \"${CMAKE_COMMAND}\" -E copy
|
||||
\"\${_real}\" \"${INSTALL_BUNDLE_LIB_DIR}/\${_name}\")
|
||||
endforeach()
|
||||
endforeach()
|
||||
" COMPONENT Runtime)
|
||||
|
||||
# Copy the native assets provided by the build.dart from all packages.
|
||||
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/")
|
||||
install(DIRECTORY "${NATIVE_ASSETS_DIR}"
|
||||
|
||||
+4
-4
@@ -38,11 +38,11 @@ dependencies:
|
||||
# Use with the CupertinoIcons class for iOS style icons.
|
||||
cupertino_icons: ^1.0.8
|
||||
flutter_blue_plus: ^2.3.14
|
||||
# TODO: Switch to official flserial repo once changes are upstreamed
|
||||
# Vendored from MeshEnvy/flserial e1864de. Linux SerialThread waits
|
||||
# until fl_set_callback is installed so a port that transmits on open
|
||||
# does not call a null callback. Switch back upstream once that lands.
|
||||
flserial:
|
||||
git:
|
||||
url: https://github.com/MeshEnvy/flserial.git
|
||||
ref: e1864de9b65cda9656dba804329bdd2890dd5a92
|
||||
path: third_party/flserial
|
||||
ffi: ^2.1.3 # calloc.free for flserial's native I/O buffers
|
||||
provider: ^6.1.5+1
|
||||
shared_preferences: ^2.2.2
|
||||
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
# Disable clang-format for this vendored submodule so that local patches
|
||||
# are not stomped by editor auto-formatting.
|
||||
DisableFormat: true
|
||||
@@ -0,0 +1,53 @@
|
||||
# This workflow uses actions that are not certified by GitHub.
|
||||
# They are provided by a third-party and are governed by
|
||||
# separate terms of service, privacy policy, and support
|
||||
# documentation.
|
||||
|
||||
name: Flutter
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: subosito/flutter-action@v2
|
||||
- uses: seanmiddleditch/gha-setup-ninja@master
|
||||
|
||||
|
||||
- name: Sudo apt update
|
||||
run: sudo apt update
|
||||
|
||||
- name: Install gtk3
|
||||
run: sudo apt-get install libgtk-3-dev
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
|
||||
- name: Analyze project source
|
||||
run: flutter analyze
|
||||
|
||||
- name: Build release
|
||||
working-directory: ./example
|
||||
run: flutter build linux --release
|
||||
|
||||
- name: Print Folder Tree
|
||||
uses: jaywcjlove/github-action-folder-tree@main
|
||||
id: tree
|
||||
with:
|
||||
exclude: "node_modules|dist|.git|.husky"
|
||||
path: ./
|
||||
depth: 10
|
||||
|
||||
#- name: List files in the repository
|
||||
# run: ls -lR ${{ github.workspace }}/build/linux
|
||||
# - name: Run tests
|
||||
# run: cp ./example/build/linux/x64/release/bundle/lib/libflserial.so ./test/lib/libflserial.so
|
||||
#- name: Run tests
|
||||
# run: flutter test
|
||||
@@ -0,0 +1,29 @@
|
||||
# Miscellaneous
|
||||
*.class
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
.atom/
|
||||
.buildlog/
|
||||
.history
|
||||
.svn/
|
||||
migrate_working_dir/
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
|
||||
# The .vscode folder contains launch configuration and tasks you configure in
|
||||
# VS Code which you may wish to be included in version control, so this line
|
||||
# is commented out by default.
|
||||
#.vscode/
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
|
||||
/pubspec.lock
|
||||
**/doc/api/
|
||||
.dart_tool/
|
||||
build/
|
||||
Vendored
+42
@@ -0,0 +1,42 @@
|
||||
# This file tracks properties of this Flutter project.
|
||||
# Used by Flutter tool to assess capabilities and perform upgrades etc.
|
||||
#
|
||||
# This file should be version controlled and should not be manually edited.
|
||||
|
||||
version:
|
||||
revision: "dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668"
|
||||
channel: "stable"
|
||||
|
||||
project_type: plugin_ffi
|
||||
|
||||
# Tracks metadata for the flutter migrate command
|
||||
migration:
|
||||
platforms:
|
||||
- platform: root
|
||||
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
- platform: android
|
||||
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
- platform: ios
|
||||
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
- platform: linux
|
||||
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
- platform: macos
|
||||
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
- platform: windows
|
||||
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
|
||||
# User provided section
|
||||
|
||||
# List of Local paths (relative to this file) that should be
|
||||
# ignored by the migrate tool.
|
||||
#
|
||||
# Files that are not part of the templates will be ignored by default.
|
||||
unmanaged_files:
|
||||
- 'lib/main.dart'
|
||||
- 'ios/Runner.xcodeproj/project.pbxproj'
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
{
|
||||
// Użyj funkcji IntelliSense, aby uzyskać informacje o możliwych atrybutach.
|
||||
// Najedź kursorem, aby wyświetlić opisy istniejących atrybutów.
|
||||
// Aby uzyskać więcej informacji, odwiedź stronę: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "flserial",
|
||||
"request": "launch",
|
||||
"type": "dart"
|
||||
},
|
||||
{
|
||||
"name": "flserial (profile mode)",
|
||||
"request": "launch",
|
||||
"type": "dart",
|
||||
"flutterMode": "profile"
|
||||
},
|
||||
{
|
||||
"name": "flserial (release mode)",
|
||||
"request": "launch",
|
||||
"type": "dart",
|
||||
"flutterMode": "release"
|
||||
},
|
||||
{
|
||||
"name": "example",
|
||||
"cwd": "example",
|
||||
"request": "launch",
|
||||
"type": "dart"
|
||||
},
|
||||
{
|
||||
"name": "example (profile mode)",
|
||||
"cwd": "example",
|
||||
"request": "launch",
|
||||
"type": "dart",
|
||||
"flutterMode": "profile"
|
||||
},
|
||||
{
|
||||
"name": "example (release mode)",
|
||||
"cwd": "example",
|
||||
"request": "launch",
|
||||
"type": "dart",
|
||||
"flutterMode": "release"
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+49
@@ -0,0 +1,49 @@
|
||||
## 0.3.5
|
||||
* Add support 16KB Page Size
|
||||
|
||||
## 0.3.4
|
||||
* Changelog fix
|
||||
|
||||
## 0.3.3
|
||||
* Replace fifo library
|
||||
|
||||
## 0.3.2
|
||||
* MacOS support
|
||||
* Memory allocation fix
|
||||
|
||||
## 0.3.1
|
||||
* Update libs
|
||||
|
||||
## 0.3.0
|
||||
* Import project to new plugin ffi template
|
||||
* Few Api changes
|
||||
|
||||
## 0.2.0
|
||||
* New event model
|
||||
* Cleaning up unnecessary libs
|
||||
* Performance improvements
|
||||
* Api changes, main functions:
|
||||
|
||||
Stream based events, before:
|
||||
```
|
||||
serial.onSerialData.subscribe(
|
||||
```
|
||||
to:
|
||||
```
|
||||
serial.onSerialData.stream.listen(
|
||||
```
|
||||
|
||||
Write serial port, before:
|
||||
```
|
||||
serial.write(data.length, data);
|
||||
```
|
||||
to:
|
||||
```
|
||||
serial.write(data);
|
||||
```
|
||||
|
||||
## 0.1.2
|
||||
* Android compilation
|
||||
|
||||
## 0.1.1
|
||||
* Initial beta version
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Grzegorz Leśniak
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
+63
@@ -0,0 +1,63 @@
|
||||
# flserial
|
||||
Flutter Serial Port Plugin FFI based on great C library. Useful to communicate with RS232 devices.
|
||||
|
||||
Based on great serial library: https://github.com/wjwwood/serial
|
||||
|
||||
Supported platforms:
|
||||
- Linux
|
||||
- Windows
|
||||
- Android
|
||||
- MacOS
|
||||
|
||||
Example of usage:
|
||||
|
||||
```
|
||||
FlSerial serial = FlSerial();
|
||||
serial.init();
|
||||
serial.openPort("COM3", 9600);
|
||||
serial.onSerialData.stream.listen(
|
||||
(args) {
|
||||
if (args.len > 0) {
|
||||
print(args.serial.readList());
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
serial.setByteSize8();
|
||||
serial.setBitParityNone();
|
||||
serial.setStopBits1();
|
||||
serial.setFlowControlNone();
|
||||
|
||||
String msg = "Hello World!";
|
||||
var list = msg.codeUnits;
|
||||
serial.write(Uint8List.fromList(list));
|
||||
|
||||
serial.closePort();
|
||||
serial.free();
|
||||
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Grzegorz Leśniak
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
include: package:flutter_lints/flutter.yaml
|
||||
|
||||
# Additional information about this file can be found at
|
||||
# https://dart.dev/guides/language/analysis-options
|
||||
@@ -0,0 +1,9 @@
|
||||
*.iml
|
||||
.gradle
|
||||
/local.properties
|
||||
/.idea/workspace.xml
|
||||
/.idea/libraries
|
||||
.DS_Store
|
||||
/build
|
||||
/captures
|
||||
.cxx
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
// The Android Gradle Plugin builds the native code with the Android NDK.
|
||||
|
||||
group = "pl.glpro.flserial"
|
||||
version = "1.0"
|
||||
|
||||
buildscript {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// The Android Gradle Plugin knows how to build native code with the NDK.
|
||||
classpath("com.android.tools.build:gradle:8.13.0")
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.allprojects {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
apply plugin: "com.android.library"
|
||||
|
||||
android {
|
||||
if (project.android.hasProperty("namespace")) {
|
||||
namespace = "pl.glpro.flserial"
|
||||
}
|
||||
|
||||
// Bumping the plugin compileSdk version requires all clients of this plugin
|
||||
// to bump the version in their app.
|
||||
compileSdk = 36
|
||||
|
||||
// Use the NDK version
|
||||
// declared in /android/app/build.gradle file of the Flutter project.
|
||||
// Replace it with a version number if this plugin requires a specific NDK version.
|
||||
// (e.g. ndkVersion "23.1.7779620")
|
||||
// ndkVersion = android.ndkVersion
|
||||
ndkVersion = "29.0.14206865"
|
||||
|
||||
// Invoke the shared CMake build with the Android Gradle Plugin.
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
path = "../src/CMakeLists.txt"
|
||||
|
||||
// The default CMake version for the Android Gradle Plugin is 3.10.2.
|
||||
// https://developer.android.com/studio/projects/install-ndk#vanilla_cmake
|
||||
//
|
||||
// The Flutter tooling requires that developers have CMake 3.10 or later
|
||||
// installed. You should not increase this version, as doing so will cause
|
||||
// the plugin to fail to compile for some customers of the plugin.
|
||||
// version "3.10.2"
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 21
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
rootProject.name = 'flserial'
|
||||
@@ -0,0 +1,3 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="pl.glpro.flserial">
|
||||
</manifest>
|
||||
Vendored
+19
@@ -0,0 +1,19 @@
|
||||
# Run with `dart run ffigen --config ffigen.yaml`.
|
||||
name: FlserialBindings
|
||||
description: |
|
||||
Bindings for `src/flserial.h`.
|
||||
|
||||
Regenerate bindings with `dart run ffigen --config ffigen.yaml`.
|
||||
output: 'lib/flserial_bindings_generated.dart'
|
||||
headers:
|
||||
entry-points:
|
||||
- 'src/flserial.h'
|
||||
include-directives:
|
||||
- 'src/flserial.h'
|
||||
preamble: |
|
||||
// ignore_for_file: always_specify_types
|
||||
// ignore_for_file: camel_case_types
|
||||
// ignore_for_file: non_constant_identifier_names
|
||||
comments:
|
||||
style: any
|
||||
length: full
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
// Relative import to be able to reuse the C sources.
|
||||
// See the comment in ../flserial.podspec for more information.
|
||||
#include "../../src/flserial.cp"
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#
|
||||
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
|
||||
# Run `pod lib lint flserial.podspec` to validate before publishing.
|
||||
#
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'flserial'
|
||||
s.version = '0.0.1'
|
||||
s.summary = 'A new Flutter FFI plugin project.'
|
||||
s.description = <<-DESC
|
||||
A new Flutter FFI plugin project.
|
||||
DESC
|
||||
s.homepage = 'http://example.com'
|
||||
s.license = { :file => '../LICENSE' }
|
||||
s.author = { 'Your Company' => 'email@example.com' }
|
||||
|
||||
# This will ensure the source files in Classes/ are included in the native
|
||||
# builds of apps using this FFI plugin. Podspec does not support relative
|
||||
# paths, so Classes contains a forwarder C file that relatively imports
|
||||
# `../src/*` so that the C sources can be shared among all target platforms.
|
||||
s.source = { :path => '.' }
|
||||
s.source_files = 'Classes/**/*'
|
||||
s.dependency 'Flutter'
|
||||
s.platform = :ios, '12.0'
|
||||
|
||||
# Flutter.framework does not contain a i386 slice.
|
||||
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }
|
||||
s.swift_version = '5.0'
|
||||
end
|
||||
+452
@@ -0,0 +1,452 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:ffi';
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:ffi/ffi.dart';
|
||||
import 'package:flserial/flserial_exception.dart';
|
||||
|
||||
import 'flserial_bindings_generated.dart';
|
||||
|
||||
const String _libName = 'flserial';
|
||||
const int _serialIOBuffLen = 1024 * 8;
|
||||
|
||||
/// The dynamic library in which the symbols for [FlserialBindings] can be found.
|
||||
final DynamicLibrary dylib = () {
|
||||
if (Platform.isMacOS || Platform.isIOS) {
|
||||
return DynamicLibrary.open('$_libName.framework/$_libName');
|
||||
}
|
||||
if (Platform.isAndroid || Platform.isLinux) {
|
||||
return DynamicLibrary.open('lib$_libName.so');
|
||||
}
|
||||
if (Platform.isWindows) {
|
||||
return DynamicLibrary.open('$_libName.dll');
|
||||
}
|
||||
throw UnsupportedError('Unknown platform: ${Platform.operatingSystem}');
|
||||
}();
|
||||
|
||||
/// The bindings to the native functions in [_dylib].
|
||||
final FlserialBindings bindings = FlserialBindings(dylib);
|
||||
|
||||
/// Native pointer to string conversion
|
||||
String nativeInt8ToString(Pointer<Int8> pointer, {bool allowMalformed = true}) {
|
||||
var ptrName = pointer.cast<Utf8>();
|
||||
final ptrNameCodeUnits = pointer.cast<Uint8>();
|
||||
var list = ptrNameCodeUnits.asTypedList(ptrName.length);
|
||||
return utf8.decode(list, allowMalformed: allowMalformed);
|
||||
}
|
||||
|
||||
/// String conversion to native pointer, memory should be free outside function
|
||||
Pointer<Char> stringToNativeInt8(String str, {Allocator allocator = calloc}) {
|
||||
final units = utf8.encode(str);
|
||||
final result = allocator<Uint8>(units.length + 1);
|
||||
final nativeString = result.asTypedList(units.length + 1);
|
||||
nativeString.setAll(0, units);
|
||||
nativeString[units.length] = 0;
|
||||
|
||||
return result.cast<Char>();
|
||||
}
|
||||
|
||||
/// List conversion to native pointer, memory should be free outside function
|
||||
Pointer<Char> int8ListToPointerInt8(
|
||||
Uint8List units,
|
||||
Pointer<Uint8> pointer, {
|
||||
Allocator allocator = calloc,
|
||||
}) {
|
||||
final nativeString = pointer.asTypedList(units.length + 1); //blobBytes
|
||||
nativeString.setAll(0, units);
|
||||
nativeString[units.length] = 0;
|
||||
return pointer.cast<Char>();
|
||||
}
|
||||
|
||||
Pointer<Double> listToPointerDouble(List<double> sample) {
|
||||
final Pointer<Double> pointer = calloc.allocate<Double>(
|
||||
sample.length,
|
||||
alignment: 8,
|
||||
);
|
||||
final nativeSamples = pointer.asTypedList(sample.length);
|
||||
nativeSamples.setAll(0, sample);
|
||||
return pointer.cast<Double>();
|
||||
}
|
||||
|
||||
/// Native pointer conversion to list
|
||||
Int8List nativeInt8ToInt8List(Pointer<Int8> pointer) {
|
||||
var ptrName = pointer.cast<Utf8>();
|
||||
final ptrNameCodeUnits = pointer.cast<Int8>();
|
||||
var list = ptrNameCodeUnits.asTypedList(ptrName.length);
|
||||
return list;
|
||||
}
|
||||
|
||||
/// Open serial port status
|
||||
enum FlOpenStatus { open, closed, error }
|
||||
|
||||
/// Class for incoming data handling
|
||||
class FlSerialEventArgs {
|
||||
FlSerialEventArgs(this.serial, this.len, this.cts, this.dsr);
|
||||
final FlSerial serial;
|
||||
final int len;
|
||||
final bool cts, dsr;
|
||||
}
|
||||
|
||||
/// Main serial wrapper class over ffi
|
||||
class FlSerial {
|
||||
int flh = -1;
|
||||
bool prevCTS = false;
|
||||
bool prevDSR = false;
|
||||
var onSerialData = StreamController<FlSerialEventArgs>();
|
||||
Pointer<Char> serialReadBuff = Pointer.fromAddress(0);
|
||||
Pointer<Uint8> serialWriteBuff = Pointer.fromAddress(0);
|
||||
|
||||
/// Init should be called at program start, after FlSerial creation
|
||||
/// Function is used to make array of internal port structs for 16 parallel processing ports
|
||||
int init() {
|
||||
return bindings.fl_init(16);
|
||||
}
|
||||
|
||||
/// Setting callback to native code. Used for incoming data signal
|
||||
void setCallback(int flh, {required DartflcallbackFunction callback}) {
|
||||
final nativeCallable = NativeCallable<flcallbackFunction>.listener(
|
||||
callback,
|
||||
);
|
||||
bindings.fl_set_callback(flh, nativeCallable.nativeFunction);
|
||||
}
|
||||
|
||||
/// Listing serial ports. Platform depend
|
||||
static List<String> listPorts() {
|
||||
List<String> list = List<String>.empty(growable: true);
|
||||
|
||||
Allocator allocator = calloc;
|
||||
var result = allocator<Char>(1024);
|
||||
|
||||
for (int i = 0; i < 255; i++) {
|
||||
int len = bindings.fl_ports(i, 1024, result);
|
||||
if (len > 0) {
|
||||
String resultStr = result.cast<Utf8>().toDartString(length: len);
|
||||
list.add(resultStr);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
allocator.free(result);
|
||||
return list;
|
||||
}
|
||||
|
||||
/// Internal function for serial port handler checking
|
||||
int _checkFLH(int handler) {
|
||||
if (handler >= 0 && handler < MAX_PORT_COUNT) {
|
||||
return FlError.FL_ERROR_OK;
|
||||
}
|
||||
throw FlSerialException(FlError.FL_ERROR_HANDLER, msg: "$handler");
|
||||
}
|
||||
|
||||
/// Function for openning serial port
|
||||
FlOpenStatus openPort(String portname, int baudrate) {
|
||||
prevCTS = false;
|
||||
prevDSR = false;
|
||||
Pointer<Char> ptr = stringToNativeInt8(portname);
|
||||
flh = bindings.fl_open(flh, ptr, baudrate);
|
||||
calloc.free(ptr);
|
||||
int error = bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_LAST_ERROR, -1);
|
||||
int flerror = FlError.FL_ERROR_UNKNOW;
|
||||
if (error > 0) {
|
||||
/// error mapping
|
||||
String msg = "Port open error: $portname";
|
||||
switch (error) {
|
||||
case 1:
|
||||
case 3:
|
||||
flerror = FlError.FL_ERROR_PORT_NOT_EXIST;
|
||||
msg += " port not exist";
|
||||
break;
|
||||
case 2:
|
||||
flerror = FlError.FL_ERROR_PORT_ALLREADY_OPEN;
|
||||
msg += " port allready open";
|
||||
break;
|
||||
}
|
||||
|
||||
bindings.fl_close(flh);
|
||||
flh = -1;
|
||||
throw FlSerialException(flerror, msg: msg);
|
||||
}
|
||||
|
||||
onSerialData = StreamController<FlSerialEventArgs>();
|
||||
|
||||
Allocator allocator = calloc;
|
||||
serialReadBuff = allocator<Char>(_serialIOBuffLen);
|
||||
serialWriteBuff = allocator<Uint8>(_serialIOBuffLen);
|
||||
|
||||
setCallback(
|
||||
flh,
|
||||
callback: (cflh, len) async {
|
||||
if (len > 0) {
|
||||
onSerialData.add(FlSerialEventArgs(this, len, prevCTS, prevDSR));
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
return isOpen();
|
||||
}
|
||||
|
||||
/// Function check is serial port opened
|
||||
FlOpenStatus isOpen() {
|
||||
if (flh < 0) {
|
||||
return FlOpenStatus.closed;
|
||||
}
|
||||
|
||||
int error = bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_LAST_ERROR, -1);
|
||||
if (error > 0) {
|
||||
return FlOpenStatus.error;
|
||||
}
|
||||
int nres = bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_IS_PORT_OPEN, -1);
|
||||
if (nres == 0) {
|
||||
return FlOpenStatus.closed;
|
||||
}
|
||||
return FlOpenStatus.open;
|
||||
}
|
||||
|
||||
/// Get last error message. Return empty string if no error
|
||||
String getLastError() {
|
||||
_checkFLH(flh);
|
||||
|
||||
int res = bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_LAST_ERROR, -1);
|
||||
String strres = "";
|
||||
|
||||
switch (res) {
|
||||
case FlError.FL_ERROR_OK:
|
||||
strres = "0: None";
|
||||
break;
|
||||
case FlError.FL_ERROR_PORT_ALLREADY_OPEN:
|
||||
strres = "$res: Port allready open";
|
||||
break;
|
||||
case FlError.FL_ERROR_PORT_NOT_EXIST:
|
||||
strres = "$res: Port not exist";
|
||||
break;
|
||||
default:
|
||||
strres = "-1: Unknow error";
|
||||
break;
|
||||
}
|
||||
return strres;
|
||||
}
|
||||
|
||||
/*
|
||||
Future<int> _readLineStatus() async {
|
||||
|
||||
_checkFLH(flh);
|
||||
|
||||
bool currCTS = getCTS();
|
||||
bool currDSR = getDSR();
|
||||
if(currCTS != prevCTS || prevDSR != currDSR)
|
||||
{
|
||||
prevCTS = currCTS;
|
||||
prevDSR = currDSR;
|
||||
|
||||
onSerialData.broadcast(FlSerialEventArgs(
|
||||
readBuff.length, Uint8List(0), currCTS, currDSR));
|
||||
}
|
||||
return 0;
|
||||
}*/
|
||||
|
||||
/// Internal function to read serial data from lower layer with desired len. If no data is present, empty list is returned
|
||||
Uint8List _readList(int len) {
|
||||
_checkFLH(flh);
|
||||
|
||||
if (len > _serialIOBuffLen) {
|
||||
len = _serialIOBuffLen;
|
||||
}
|
||||
|
||||
int intres = bindings.fl_read(flh, len, serialReadBuff);
|
||||
|
||||
if (intres <= 0) {
|
||||
return Uint8List(0);
|
||||
}
|
||||
|
||||
final ptrNameCodeUnits = serialReadBuff.cast<Uint8>();
|
||||
var list = ptrNameCodeUnits.asTypedList(intres);
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/// Read full read bufer from serial port
|
||||
Uint8List readList() {
|
||||
_checkFLH(flh);
|
||||
|
||||
return readListLen(1024 * 8);
|
||||
}
|
||||
|
||||
/// Read desired len from serial port buffer
|
||||
Uint8List readListLen(int len) {
|
||||
_checkFLH(flh);
|
||||
|
||||
return _readList(len);
|
||||
}
|
||||
|
||||
/// Read single byte
|
||||
int read() {
|
||||
_checkFLH(flh);
|
||||
|
||||
Uint8List data = _readList(1);
|
||||
|
||||
if (data.isNotEmpty) {
|
||||
return data.first;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// Write list data to serial port
|
||||
int write(Uint8List data) {
|
||||
_checkFLH(flh);
|
||||
|
||||
Pointer<Char> ptr = int8ListToPointerInt8(data, serialWriteBuff);
|
||||
int res = bindings.fl_write(flh, data.length, ptr);
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
/// Close serial port and free resources
|
||||
int closePort() {
|
||||
_checkFLH(flh);
|
||||
bindings.fl_close(flh);
|
||||
onSerialData.close();
|
||||
Allocator allocator = calloc;
|
||||
if (serialReadBuff.value != 0) {
|
||||
allocator.free(serialReadBuff);
|
||||
}
|
||||
if (serialWriteBuff.value != 0) {
|
||||
allocator.free(serialWriteBuff);
|
||||
}
|
||||
flh = -1;
|
||||
return flh;
|
||||
}
|
||||
|
||||
/// Uniwersal function to control serial port
|
||||
int ctrl(int cmd, int value) {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, cmd, value);
|
||||
}
|
||||
|
||||
/// Function set RTS line in serial port
|
||||
int setRTS(bool value) {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_RTS, value ? 1 : 0);
|
||||
}
|
||||
|
||||
/// Function set CTS line in serial port
|
||||
bool getCTS() {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_GET_CTS, 0) > 0 ? true : false;
|
||||
}
|
||||
|
||||
/// Get status of DTR line
|
||||
int setDTR(bool value) {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_DTR, value ? 1 : 0);
|
||||
}
|
||||
|
||||
/// Get status of DSR line
|
||||
bool getDSR() {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_GET_DSR, 0) > 0 ? true : false;
|
||||
}
|
||||
|
||||
/// Set byte size to 5 bits
|
||||
int setByteSize5() {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_BYTESIZE_5, 0);
|
||||
}
|
||||
|
||||
/// Set byte size to 6 bits
|
||||
int setByteSize6() {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_BYTESIZE_6, 0);
|
||||
}
|
||||
|
||||
/// Set byte size to 7 bits
|
||||
int setByteSize7() {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_BYTESIZE_7, 0);
|
||||
}
|
||||
|
||||
/// Set byte size to 8 bits
|
||||
int setByteSize8() {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_BYTESIZE_8, 0);
|
||||
}
|
||||
|
||||
/// Set bit parity to none
|
||||
int setBitParityNone() {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_PARITY_NONE, 0);
|
||||
}
|
||||
|
||||
/// Set bit parity to odd
|
||||
int setBitParityOdd() {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_PARITY_ODD, 0);
|
||||
}
|
||||
|
||||
// Set bit parity to even
|
||||
int setBitParityEven() {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_PARITY_EVEN, 0);
|
||||
}
|
||||
|
||||
// Set bit parity to mark
|
||||
int setBitParityMark() {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_PARITY_MARK, 0);
|
||||
}
|
||||
|
||||
// Set bit parity to space
|
||||
int setBitParitySpace() {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_PARITY_SPACE, 0);
|
||||
}
|
||||
|
||||
/// Set stop bits to one
|
||||
int setStopBits1() {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_STOPBITS_ONE, 0);
|
||||
}
|
||||
|
||||
/// Set stop bits to one and half
|
||||
int setStopBits1_5() {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_STOPBITS_ONE_POINT_FIVE, 0);
|
||||
}
|
||||
|
||||
/// Set stop bits to two
|
||||
int setStopBits2() {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_STOPBITS_TWO, 0);
|
||||
}
|
||||
|
||||
/// Disable flow control
|
||||
int setFlowControlNone() {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_FLOWCONTROL_NONE, 0);
|
||||
}
|
||||
|
||||
/// Set hardware flow control
|
||||
int setFlowControlHardware() {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_FLOWCONTROL_HARDWARE, 0);
|
||||
}
|
||||
|
||||
/// Set xon/xoff flow control (software)
|
||||
int setFlowControlSoftware() {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_FLOWCONTROL_SOFTWARE, 0);
|
||||
}
|
||||
|
||||
/// Waiting for status line change
|
||||
int setWaitStatusChange() {
|
||||
_checkFLH(flh);
|
||||
return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_GET_STATUS_CHANGE, 0);
|
||||
}
|
||||
|
||||
/// Free resources. Serial port should not be used after calling this function
|
||||
int free() {
|
||||
return bindings.fl_free();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
// ignore_for_file: always_specify_types
|
||||
// ignore_for_file: camel_case_types
|
||||
// ignore_for_file: non_constant_identifier_names
|
||||
|
||||
// AUTO GENERATED FILE, DO NOT EDIT.
|
||||
//
|
||||
// Generated by `package:ffigen`.
|
||||
// ignore_for_file: type=lint
|
||||
import 'dart:ffi' as ffi;
|
||||
|
||||
/// Bindings for `src/flserial.h`.
|
||||
///
|
||||
/// Regenerate bindings with `dart run ffigen --config ffigen.yaml`.
|
||||
///
|
||||
class FlserialBindings {
|
||||
/// Holds the symbol lookup function.
|
||||
final ffi.Pointer<T> Function<T extends ffi.NativeType>(String symbolName)
|
||||
_lookup;
|
||||
|
||||
/// The symbols are looked up in [dynamicLibrary].
|
||||
FlserialBindings(ffi.DynamicLibrary dynamicLibrary)
|
||||
: _lookup = dynamicLibrary.lookup;
|
||||
|
||||
/// The symbols are looked up with [lookup].
|
||||
FlserialBindings.fromLookup(
|
||||
ffi.Pointer<T> Function<T extends ffi.NativeType>(String symbolName)
|
||||
lookup)
|
||||
: _lookup = lookup;
|
||||
|
||||
int fl_init(
|
||||
int portCount,
|
||||
) {
|
||||
return _fl_init(
|
||||
portCount,
|
||||
);
|
||||
}
|
||||
|
||||
late final _fl_initPtr =
|
||||
_lookup<ffi.NativeFunction<ffi.Int Function(ffi.Int)>>('fl_init');
|
||||
late final _fl_init = _fl_initPtr.asFunction<int Function(int)>();
|
||||
|
||||
int fl_set_callback(
|
||||
int flh,
|
||||
flcallback cb,
|
||||
) {
|
||||
return _fl_set_callback(
|
||||
flh,
|
||||
cb,
|
||||
);
|
||||
}
|
||||
|
||||
late final _fl_set_callbackPtr =
|
||||
_lookup<ffi.NativeFunction<ffi.Int Function(ffi.Int, flcallback)>>(
|
||||
'fl_set_callback');
|
||||
late final _fl_set_callback =
|
||||
_fl_set_callbackPtr.asFunction<int Function(int, flcallback)>();
|
||||
|
||||
int fl_ports(
|
||||
int index,
|
||||
int buffsize,
|
||||
ffi.Pointer<ffi.Char> buff,
|
||||
) {
|
||||
return _fl_ports(
|
||||
index,
|
||||
buffsize,
|
||||
buff,
|
||||
);
|
||||
}
|
||||
|
||||
late final _fl_portsPtr = _lookup<
|
||||
ffi.NativeFunction<
|
||||
ffi.Int Function(
|
||||
ffi.Int, ffi.Int, ffi.Pointer<ffi.Char>)>>('fl_ports');
|
||||
late final _fl_ports =
|
||||
_fl_portsPtr.asFunction<int Function(int, int, ffi.Pointer<ffi.Char>)>();
|
||||
|
||||
int fl_open(
|
||||
int flh,
|
||||
ffi.Pointer<ffi.Char> portname,
|
||||
int baudrate,
|
||||
) {
|
||||
return _fl_open(
|
||||
flh,
|
||||
portname,
|
||||
baudrate,
|
||||
);
|
||||
}
|
||||
|
||||
late final _fl_openPtr = _lookup<
|
||||
ffi.NativeFunction<
|
||||
ffi.Int Function(
|
||||
ffi.Int, ffi.Pointer<ffi.Char>, ffi.Int)>>('fl_open');
|
||||
late final _fl_open =
|
||||
_fl_openPtr.asFunction<int Function(int, ffi.Pointer<ffi.Char>, int)>();
|
||||
|
||||
int fl_read(
|
||||
int flh,
|
||||
int len,
|
||||
ffi.Pointer<ffi.Char> buff,
|
||||
) {
|
||||
return _fl_read(
|
||||
flh,
|
||||
len,
|
||||
buff,
|
||||
);
|
||||
}
|
||||
|
||||
late final _fl_readPtr = _lookup<
|
||||
ffi.NativeFunction<
|
||||
ffi.Int Function(
|
||||
ffi.Int, ffi.Int, ffi.Pointer<ffi.Char>)>>('fl_read');
|
||||
late final _fl_read =
|
||||
_fl_readPtr.asFunction<int Function(int, int, ffi.Pointer<ffi.Char>)>();
|
||||
|
||||
int fl_write(
|
||||
int flh,
|
||||
int len,
|
||||
ffi.Pointer<ffi.Char> data,
|
||||
) {
|
||||
return _fl_write(
|
||||
flh,
|
||||
len,
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
late final _fl_writePtr = _lookup<
|
||||
ffi.NativeFunction<
|
||||
ffi.Int Function(
|
||||
ffi.Int, ffi.Int, ffi.Pointer<ffi.Char>)>>('fl_write');
|
||||
late final _fl_write =
|
||||
_fl_writePtr.asFunction<int Function(int, int, ffi.Pointer<ffi.Char>)>();
|
||||
|
||||
int fl_close(
|
||||
int flh,
|
||||
) {
|
||||
return _fl_close(
|
||||
flh,
|
||||
);
|
||||
}
|
||||
|
||||
late final _fl_closePtr =
|
||||
_lookup<ffi.NativeFunction<ffi.Int Function(ffi.Int)>>('fl_close');
|
||||
late final _fl_close = _fl_closePtr.asFunction<int Function(int)>();
|
||||
|
||||
int fl_ctrl(
|
||||
int flh,
|
||||
int param,
|
||||
int value,
|
||||
) {
|
||||
return _fl_ctrl(
|
||||
flh,
|
||||
param,
|
||||
value,
|
||||
);
|
||||
}
|
||||
|
||||
late final _fl_ctrlPtr = _lookup<
|
||||
ffi.NativeFunction<ffi.Int Function(ffi.Int, ffi.Int32, ffi.Int)>>(
|
||||
'fl_ctrl');
|
||||
late final _fl_ctrl = _fl_ctrlPtr.asFunction<int Function(int, int, int)>();
|
||||
|
||||
int fl_free() {
|
||||
return _fl_free();
|
||||
}
|
||||
|
||||
late final _fl_freePtr =
|
||||
_lookup<ffi.NativeFunction<ffi.Int Function()>>('fl_free');
|
||||
late final _fl_free = _fl_freePtr.asFunction<int Function()>();
|
||||
}
|
||||
|
||||
abstract class FlCtrl {
|
||||
static const int FL_CTRL_LAST_ERROR = 0;
|
||||
static const int FL_CTRL_IS_PORT_OPEN = 1;
|
||||
static const int FL_CTRL_BREAK = 2;
|
||||
static const int FL_CTRL_SET_RTS = 3;
|
||||
static const int FL_CTRL_GET_CTS = 4;
|
||||
static const int FL_CTRL_SET_DTR = 5;
|
||||
static const int FL_CTRL_GET_DSR = 6;
|
||||
static const int FL_CTRL_SET_BYTESIZE_5 = 7;
|
||||
static const int FL_CTRL_SET_BYTESIZE_6 = 8;
|
||||
static const int FL_CTRL_SET_BYTESIZE_7 = 9;
|
||||
static const int FL_CTRL_SET_BYTESIZE_8 = 10;
|
||||
static const int FL_CTRL_SET_PARITY_NONE = 11;
|
||||
static const int FL_CTRL_SET_PARITY_ODD = 12;
|
||||
static const int FL_CTRL_SET_PARITY_EVEN = 13;
|
||||
static const int FL_CTRL_SET_PARITY_MARK = 14;
|
||||
static const int FL_CTRL_SET_PARITY_SPACE = 15;
|
||||
static const int FL_CTRL_SET_STOPBITS_ONE = 16;
|
||||
static const int FL_CTRL_SET_STOPBITS_TWO = 17;
|
||||
static const int FL_CTRL_SET_STOPBITS_ONE_POINT_FIVE = 18;
|
||||
static const int FL_CTRL_SET_FLOWCONTROL_NONE = 19;
|
||||
static const int FL_CTRL_SET_FLOWCONTROL_HARDWARE = 20;
|
||||
static const int FL_CTRL_SET_FLOWCONTROL_SOFTWARE = 21;
|
||||
static const int FL_CTRL_GET_STATUS_CHANGE = 22;
|
||||
static const int FL_CTRL_LAST = 23;
|
||||
}
|
||||
|
||||
abstract class FlError {
|
||||
static const int FL_ERROR_OK = 0;
|
||||
static const int FL_ERROR_UNKNOW = 1;
|
||||
static const int FL_ERROR_PORT_ALLREADY_OPEN = 2;
|
||||
static const int FL_ERROR_PORT_NOT_EXIST = 3;
|
||||
static const int FL_ERROR_IO = 4;
|
||||
static const int FL_ERROR_HANDLER = 5;
|
||||
static const int FL_ERROR_LAST = 6;
|
||||
}
|
||||
|
||||
typedef flcallback = ffi.Pointer<ffi.NativeFunction<flcallbackFunction>>;
|
||||
typedef flcallbackFunction = ffi.Void Function(
|
||||
ffi.UnsignedInt, ffi.UnsignedInt);
|
||||
typedef DartflcallbackFunction = void Function(int, int);
|
||||
|
||||
const int MAX_PORT_NAME_LEN = 512;
|
||||
|
||||
const int MAX_PORT_COUNT = 128;
|
||||
@@ -0,0 +1,6 @@
|
||||
/// Exception class for serial port
|
||||
class FlSerialException implements Exception {
|
||||
FlSerialException(this.error, {required this.msg});
|
||||
final int error;
|
||||
final String msg;
|
||||
}
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
export 'flserial_exception.dart';
|
||||
export 'flserial.dart';
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
# The Flutter tooling requires that developers have CMake 3.10 or later
|
||||
# installed. You should not increase this version, as doing so will cause
|
||||
# the plugin to fail to compile for some customers of the plugin.
|
||||
cmake_minimum_required(VERSION 3.10)
|
||||
|
||||
# Project-level configuration.
|
||||
set(PROJECT_NAME "flserial")
|
||||
project(${PROJECT_NAME} LANGUAGES CXX)
|
||||
|
||||
# Invoke the build for native code shared with the other target platforms.
|
||||
# This can be changed to accommodate different builds.
|
||||
add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/../src" "${CMAKE_CURRENT_BINARY_DIR}/shared")
|
||||
|
||||
# List of absolute paths to libraries that should be bundled with the plugin.
|
||||
# This list could contain prebuilt libraries, or libraries created by an
|
||||
# external build triggered from this build file.
|
||||
set(flserial_bundled_libraries
|
||||
# Defined in ../src/CMakeLists.txt.
|
||||
# This can be changed to accommodate different builds.
|
||||
$<TARGET_FILE:flserial>
|
||||
PARENT_SCOPE
|
||||
)
|
||||
+377
@@ -0,0 +1,377 @@
|
||||
#include "flserial.h"
|
||||
#include "native_libs/include/serial/serial.h"
|
||||
#include "native_libs/include/tinycthread.h"
|
||||
#include "native_libs/include/ringbuffer.h"
|
||||
#include <iostream>
|
||||
|
||||
#define FL_SERIAL_BUFF_LEN (8 * 1024)
|
||||
|
||||
typedef struct _flserial_
|
||||
{
|
||||
char portname[MAX_PORT_NAME_LEN + 1];
|
||||
int baudrate;
|
||||
serial::Serial *serialport;
|
||||
enum FlError lasterror;
|
||||
char lasterrormsg[512];
|
||||
thrd_t cthread;
|
||||
int breakThread;
|
||||
ring_buffer_t cinfifo;
|
||||
ring_buffer_t coutfifo;
|
||||
char inbuff[FL_SERIAL_BUFF_LEN];
|
||||
char outbuff[FL_SERIAL_BUFF_LEN];
|
||||
mtx_t inFifo_mutex;
|
||||
mtx_t outFifo_mutex;
|
||||
flcallback callback;
|
||||
} FlSerial;
|
||||
|
||||
int SerialThread(void *aArg)
|
||||
{
|
||||
FlSerial *serial = (FlSerial *)aArg;
|
||||
ring_buffer_size_t res = 0;
|
||||
uint8_t buff[FL_SERIAL_BUFF_LEN];
|
||||
ring_buffer_size_t len = sizeof(buff);
|
||||
ring_buffer_size_t total = 0;
|
||||
int isEmpty = 0;
|
||||
|
||||
while (!serial->breakThread)
|
||||
{
|
||||
try
|
||||
{
|
||||
res = (int)serial->serialport->read((uint8_t *)buff, (size_t)len);
|
||||
if (res > 0)
|
||||
{
|
||||
mtx_lock(&serial->inFifo_mutex);
|
||||
ring_buffer_queue_arr(&serial->cinfifo, (const char *)buff, res);
|
||||
mtx_unlock(&serial->inFifo_mutex);
|
||||
total += res;
|
||||
if(!serial->serialport->available()){
|
||||
serial->callback(0, total);
|
||||
total = 0;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
mtx_lock(&serial->outFifo_mutex);
|
||||
res = (ring_buffer_size_t)ring_buffer_dequeue_arr(&serial->coutfifo, (char *)buff, (int)len);
|
||||
mtx_unlock(&serial->outFifo_mutex);
|
||||
if (res > 0) {
|
||||
res = (int)serial->serialport->write((uint8_t*)buff, (size_t)res);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
catch (const serial::IOException &ioe)
|
||||
{
|
||||
serial->lasterror = FL_ERROR_IO;
|
||||
strncpy(serial->lasterrormsg , ioe.what(), sizeof(serial->lasterrormsg) - 1);
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
FlSerial *flserial_tab[MAX_PORT_COUNT];
|
||||
int flserial_count;
|
||||
int current_port;
|
||||
|
||||
/// Internal helper: close a single slot and null it out.
|
||||
/// Safe to call with a NULL entry — returns immediately.
|
||||
/// Sets breakThread=1 then calls thrd_join() so the SerialThread is
|
||||
/// guaranteed to have exited before this function returns. This is the
|
||||
/// critical ordering that prevents the Dart NativeCallable from being
|
||||
/// invoked after the isolate has freed it ("Callback invoked after it has
|
||||
/// been deleted").
|
||||
static void _fl_close_slot(int slot)
|
||||
{
|
||||
FlSerial *port = flserial_tab[slot];
|
||||
if (port == NULL)
|
||||
return;
|
||||
|
||||
port->breakThread = 1;
|
||||
|
||||
try
|
||||
{
|
||||
if (port->cthread != 0)
|
||||
thrd_join(port->cthread, NULL);
|
||||
|
||||
port->serialport->close();
|
||||
|
||||
mtx_destroy(&port->inFifo_mutex);
|
||||
mtx_destroy(&port->outFifo_mutex);
|
||||
}
|
||||
catch (const std::exception &)
|
||||
{
|
||||
}
|
||||
|
||||
delete port->serialport;
|
||||
port->serialport = NULL;
|
||||
delete port;
|
||||
flserial_tab[slot] = NULL;
|
||||
}
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_set_callback(int flh, flcallback cb)
|
||||
{
|
||||
FlSerial *port = flserial_tab[flh];
|
||||
port->callback = cb;
|
||||
return 0;
|
||||
}
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_init(int portCount)
|
||||
{
|
||||
if (portCount > MAX_PORT_COUNT)
|
||||
return 1;
|
||||
|
||||
flserial_count = portCount;
|
||||
current_port = -1;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_open(int flh, char *portname, int baudrate)
|
||||
{
|
||||
int porth = flh;
|
||||
|
||||
if (porth < 0)
|
||||
porth = ++current_port;
|
||||
|
||||
// If a previous FlSerial (and its SerialThread) is alive in this slot,
|
||||
// join and free it before overwriting. On Dart hot restart the isolate
|
||||
// dies without calling fl_close(), leaving the old thread running with a
|
||||
// dangling NativeCallable pointer. Joining here prevents the crash.
|
||||
_fl_close_slot(porth);
|
||||
|
||||
FlSerial *port = new FlSerial();
|
||||
port->breakThread = 0;
|
||||
|
||||
flserial_tab[porth] = port;
|
||||
|
||||
strncpy(port->portname, portname, MAX_PORT_NAME_LEN);
|
||||
|
||||
port->baudrate = baudrate;
|
||||
port->lasterror = FL_ERROR_OK;
|
||||
|
||||
port->serialport = new serial::Serial();
|
||||
#if !defined(__linux__) && !defined(__APPLE__)
|
||||
port->serialport->setTimeout(serial::Timeout(0, 2, 0, 0, 0));
|
||||
#endif // #if defined(__linux__)
|
||||
port->serialport->setPort(portname);
|
||||
port->serialport->setBaudrate(baudrate);
|
||||
|
||||
try
|
||||
{
|
||||
port->serialport->open();
|
||||
|
||||
ring_buffer_init(&port->cinfifo, port->inbuff, FL_SERIAL_BUFF_LEN );
|
||||
ring_buffer_init(&port->coutfifo, port->outbuff, FL_SERIAL_BUFF_LEN );
|
||||
|
||||
port->serialport->setBytesize(serial::bytesize_t::eightbits);
|
||||
port->serialport->setParity(serial::parity_t::parity_none);
|
||||
port->serialport->setStopbits(serial::stopbits_one);
|
||||
thrd_create(&port->cthread, SerialThread, (void *)port);
|
||||
mtx_init(&port->inFifo_mutex, mtx_plain);
|
||||
mtx_init(&port->outFifo_mutex, mtx_plain);
|
||||
}
|
||||
catch (const serial::IOException &ioe)
|
||||
{
|
||||
strncpy(port->lasterrormsg, ioe.what(), sizeof(port->lasterrormsg) - 1);
|
||||
|
||||
switch (ioe.getErrorNumber())
|
||||
{
|
||||
case 1:
|
||||
port->lasterror = FlError::FL_ERROR_PORT_NOT_EXIST;
|
||||
break;
|
||||
case 2:
|
||||
port->lasterror = FlError::FL_ERROR_PORT_ALLREADY_OPEN;
|
||||
break;
|
||||
default:
|
||||
port->lasterror = FlError::FL_ERROR_UNKNOW;
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (const std::exception)
|
||||
{
|
||||
port->lasterror = FlError::FL_ERROR_UNKNOW;
|
||||
}
|
||||
|
||||
return porth;
|
||||
}
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_ports(int index, int buffsize, char *buff)
|
||||
{
|
||||
auto list = serial::list_ports();
|
||||
if (serial::list_ports().size() <= index)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
serial::PortInfo info = list[index];
|
||||
return snprintf(buff, buffsize, "%s - %s - %s", info.port.c_str(), info.description.c_str(), info.hardware_id.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_read(int flh, int len, char *buff)
|
||||
{
|
||||
FlSerial *port = flserial_tab[flh];
|
||||
ring_buffer_size_t res = 0;
|
||||
|
||||
char *buf = NULL;
|
||||
ring_buffer_size_t size = 0;
|
||||
ring_buffer_size_t read = 0;
|
||||
|
||||
mtx_lock(&port->inFifo_mutex);
|
||||
read = ring_buffer_dequeue_arr(&port->cinfifo, buff, (ring_buffer_size_t) len);
|
||||
mtx_unlock(&port->inFifo_mutex);
|
||||
|
||||
return (int)read;
|
||||
}
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_write(int flh, int len, char *data)
|
||||
{
|
||||
FlSerial *port = flserial_tab[flh];
|
||||
int res = 0;
|
||||
try
|
||||
{
|
||||
mtx_lock(&port->outFifo_mutex);
|
||||
ring_buffer_queue_arr(&port->coutfifo, data, len);
|
||||
mtx_unlock(&port->outFifo_mutex);
|
||||
}
|
||||
catch (const std::exception &)
|
||||
{
|
||||
port->lasterror = FlError::FL_ERROR_PORT_ALLREADY_OPEN;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_close(int flh)
|
||||
{
|
||||
_fl_close_slot(flh);
|
||||
return 0;
|
||||
}
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_ctrl(int flh, FlCtrl param, int value)
|
||||
{
|
||||
|
||||
int result = -1;
|
||||
FlSerial *port = flserial_tab[flh];
|
||||
|
||||
try
|
||||
{
|
||||
switch (param)
|
||||
{
|
||||
case FL_CTRL_IS_PORT_OPEN:
|
||||
result = port->serialport->isOpen() ? 1 : 0;
|
||||
break;
|
||||
case FL_CTRL_LAST_ERROR:
|
||||
result = port->lasterror;
|
||||
break;
|
||||
case FL_CTRL_BREAK:
|
||||
port->serialport->setBreak();
|
||||
result = FL_ERROR_OK;
|
||||
break;
|
||||
case FL_CTRL_SET_RTS:
|
||||
port->serialport->setRTS(value > 0 ? true : false);
|
||||
result = FL_ERROR_OK;
|
||||
break;
|
||||
case FL_CTRL_GET_CTS:
|
||||
result = port->serialport->getCTS() ? 1 : 0;
|
||||
break;
|
||||
case FL_CTRL_SET_DTR:
|
||||
port->serialport->setDTR(value > 0 ? true : false);
|
||||
result = FL_ERROR_OK;
|
||||
break;
|
||||
case FL_CTRL_GET_DSR:
|
||||
result = port->serialport->getDSR() ? 1 : 0;
|
||||
break;
|
||||
|
||||
case FL_CTRL_SET_BYTESIZE_5:
|
||||
port->serialport->setBytesize(serial::bytesize_t::fivebits);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_BYTESIZE_6:
|
||||
port->serialport->setBytesize(serial::bytesize_t::sixbits);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_BYTESIZE_7:
|
||||
port->serialport->setBytesize(serial::bytesize_t::sevenbits);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_BYTESIZE_8:
|
||||
port->serialport->setBytesize(serial::bytesize_t::eightbits);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_PARITY_NONE:
|
||||
port->serialport->setParity(serial::parity_t::parity_none);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_PARITY_ODD:
|
||||
port->serialport->setParity(serial::parity_t::parity_odd);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_PARITY_EVEN:
|
||||
port->serialport->setParity(serial::parity_t::parity_even);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_PARITY_MARK:
|
||||
port->serialport->setParity(serial::parity_t::parity_mark);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_PARITY_SPACE:
|
||||
port->serialport->setParity(serial::parity_t::parity_space);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_STOPBITS_ONE:
|
||||
port->serialport->setStopbits(serial::stopbits_t::stopbits_one);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_STOPBITS_TWO:
|
||||
port->serialport->setStopbits(serial::stopbits_t::stopbits_two);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_STOPBITS_ONE_POINT_FIVE:
|
||||
port->serialport->setStopbits(serial::stopbits_t::stopbits_one_point_five);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_FLOWCONTROL_NONE:
|
||||
port->serialport->setFlowcontrol(serial::flowcontrol_t::flowcontrol_none);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_FLOWCONTROL_HARDWARE:
|
||||
port->serialport->setFlowcontrol(serial::flowcontrol_t::flowcontrol_hardware);
|
||||
result = 1;
|
||||
break;
|
||||
port->serialport->setFlowcontrol(serial::flowcontrol_t::flowcontrol_software);
|
||||
result = 1;
|
||||
case FL_CTRL_SET_FLOWCONTROL_SOFTWARE:
|
||||
break;
|
||||
case FL_CTRL_GET_STATUS_CHANGE:
|
||||
port->serialport->waitForChange();
|
||||
result = 1;
|
||||
break;
|
||||
|
||||
default:
|
||||
result = -1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (const std::exception &)
|
||||
{
|
||||
port->lasterror = FlError::FL_ERROR_PORT_ALLREADY_OPEN;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_free(void)
|
||||
{
|
||||
// Join every live SerialThread before the Dart isolate tears down on hot
|
||||
// restart. Without this, threads holding freed NativeCallable pointers
|
||||
// crash with "Callback invoked after it has been deleted".
|
||||
for (int i = 0; i < MAX_PORT_COUNT; i++)
|
||||
_fl_close_slot(i);
|
||||
|
||||
flserial_count = 0;
|
||||
current_port = -1;
|
||||
return 0;
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#if _WIN32
|
||||
#include <windows.h>
|
||||
#else
|
||||
#include <pthread.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#if _WIN32
|
||||
#define FFI_PLUGIN_EXPORT __declspec(dllexport)
|
||||
#else
|
||||
#define FFI_PLUGIN_EXPORT
|
||||
#endif
|
||||
|
||||
|
||||
#define MAX_PORT_FIFO_LEN 128*1024
|
||||
#define MAX_PORT_NAME_LEN 512
|
||||
#define MAX_PORT_COUNT 16
|
||||
|
||||
typedef enum FlCtrl {
|
||||
FL_CTRL_LAST_ERROR,
|
||||
FL_CTRL_IS_PORT_OPEN,
|
||||
FL_CTRL_BREAK,
|
||||
FL_CTRL_SET_RTS,
|
||||
FL_CTRL_GET_CTS,
|
||||
FL_CTRL_SET_DTR,
|
||||
FL_CTRL_GET_DSR,
|
||||
FL_CTRL_SET_BYTESIZE_5,
|
||||
FL_CTRL_SET_BYTESIZE_6,
|
||||
FL_CTRL_SET_BYTESIZE_7,
|
||||
FL_CTRL_SET_BYTESIZE_8,
|
||||
FL_CTRL_SET_PARITY_NONE,
|
||||
FL_CTRL_SET_PARITY_ODD,
|
||||
FL_CTRL_SET_PARITY_EVEN,
|
||||
FL_CTRL_SET_PARITY_MARK,
|
||||
FL_CTRL_SET_PARITY_SPACE,
|
||||
FL_CTRL_SET_STOPBITS_ONE,
|
||||
FL_CTRL_SET_STOPBITS_TWO,
|
||||
FL_CTRL_SET_STOPBITS_ONE_POINT_FIVE,
|
||||
FL_CTRL_SET_FLOWCONTROL_NONE,
|
||||
FL_CTRL_SET_FLOWCONTROL_HARDWARE,
|
||||
FL_CTRL_SET_FLOWCONTROL_SOFTWARE,
|
||||
FL_CTRL_GET_STATUS_CHANGE,
|
||||
FL_CTRL_LAST,
|
||||
} FlCtrl;
|
||||
|
||||
typedef enum FlError {
|
||||
FL_ERROR_OK,
|
||||
FL_ERROR_UNKNOW,
|
||||
FL_ERROR_PORT_ALLREADY_OPEN,
|
||||
FL_ERROR_PORT_NOT_EXIST,
|
||||
FL_ERROR_IO,
|
||||
FL_ERROR_HANDLER,
|
||||
FL_ERROR_LAST,
|
||||
} FlError;
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef void (*flcallback)(unsigned int, unsigned int);
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_init (int portCount);
|
||||
FFI_PLUGIN_EXPORT int fl_set_callback(int flh, flcallback cb);
|
||||
FFI_PLUGIN_EXPORT int fl_ports (int index, int buffsize, char *buff);
|
||||
FFI_PLUGIN_EXPORT int fl_open (int flh, char *portname, int baudrate);
|
||||
FFI_PLUGIN_EXPORT int fl_read (int flh, int len, char *buff);
|
||||
FFI_PLUGIN_EXPORT int fl_write (int flh, int len, char *data);
|
||||
FFI_PLUGIN_EXPORT int fl_close (int flh);
|
||||
FFI_PLUGIN_EXPORT int fl_ctrl (int flh, FlCtrl param, int value);
|
||||
FFI_PLUGIN_EXPORT int fl_free (void);
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
* Copyright (c) 1989, 1993
|
||||
* The Regents of the University of California. All rights reserved.
|
||||
*
|
||||
* This code is derived from software contributed to Berkeley by
|
||||
* Guido van Rossum.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of the University nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
|
||||
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
||||
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
||||
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
* SUCH DAMAGE.
|
||||
*
|
||||
* @(#)glob.h 8.1 (Berkeley) 6/2/93
|
||||
* $FreeBSD$
|
||||
*/
|
||||
|
||||
#ifndef _GLOB_H_
|
||||
#define _GLOB_H_
|
||||
|
||||
#include <sys/cdefs.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#ifndef _SIZE_T_DECLARED
|
||||
typedef size_t __size_t;
|
||||
#define _SIZE_T_DECLARED
|
||||
#endif
|
||||
|
||||
struct stat;
|
||||
typedef struct {
|
||||
size_t gl_pathc; /* Count of total paths so far. */
|
||||
size_t gl_matchc; /* Count of paths matching pattern. */
|
||||
size_t gl_offs; /* Reserved at beginning of gl_pathv. */
|
||||
int gl_flags; /* Copy of flags parameter to glob. */
|
||||
char **gl_pathv; /* List of paths matching pattern. */
|
||||
/* Copy of errfunc parameter to glob. */
|
||||
int (*gl_errfunc)(const char *, int);
|
||||
|
||||
/*
|
||||
* Alternate filesystem access methods for glob; replacement
|
||||
* versions of closedir(3), readdir(3), opendir(3), stat(2)
|
||||
* and lstat(2).
|
||||
*/
|
||||
void (*gl_closedir)(void *);
|
||||
struct dirent *(*gl_readdir)(void *);
|
||||
void *(*gl_opendir)(const char *);
|
||||
int (*gl_lstat)(const char *, struct stat *);
|
||||
int (*gl_stat)(const char *, struct stat *);
|
||||
} cglob_t;
|
||||
|
||||
|
||||
/* Believed to have been introduced in 1003.2-1992 */
|
||||
#define GLOB_APPEND 0x0001 /* Append to output from previous call. */
|
||||
#define GLOB_DOOFFS 0x0002 /* Use gl_offs. */
|
||||
#define GLOB_ERR 0x0004 /* Return on error. */
|
||||
#define GLOB_MARK 0x0008 /* Append / to matching directories. */
|
||||
#define GLOB_NOCHECK 0x0010 /* Return pattern itself if nothing matches. */
|
||||
#define GLOB_NOSORT 0x0020 /* Don't sort. */
|
||||
#define GLOB_NOESCAPE 0x2000 /* Disable backslash escaping. */
|
||||
|
||||
/* Error values returned by glob(3) */
|
||||
#define GLOB_NOSPACE (-1) /* Malloc call failed. */
|
||||
#define GLOB_ABORTED (-2) /* Unignored error. */
|
||||
#define GLOB_NOMATCH (-3) /* No match and GLOB_NOCHECK was not set. */
|
||||
#define GLOB_NOSYS (-4) /* Obsolete: source comptability only. */
|
||||
|
||||
|
||||
|
||||
#define GLOB_ALTDIRFUNC 0x0040 /* Use alternately specified directory funcs. */
|
||||
#define GLOB_BRACE 0x0080 /* Expand braces ala csh. */
|
||||
#define GLOB_MAGCHAR 0x0100 /* Pattern had globbing characters. */
|
||||
#define GLOB_NOMAGIC 0x0200 /* GLOB_NOCHECK without magic chars (csh). */
|
||||
#define GLOB_QUOTE 0x0400 /* Quote special chars with \. */
|
||||
#define GLOB_TILDE 0x0800 /* Expand tilde names from the passwd file. */
|
||||
#define GLOB_LIMIT 0x1000 /* limit number of returned paths */
|
||||
|
||||
/* source compatibility, these are the old names */
|
||||
#define GLOB_MAXPATH GLOB_LIMIT
|
||||
#define GLOB_ABEND GLOB_ABORTED
|
||||
|
||||
__BEGIN_DECLS
|
||||
int cglob(const char *, int, int (*)(const char *, int), cglob_t *);
|
||||
void cglobfree(cglob_t *);
|
||||
__END_DECLS
|
||||
|
||||
#endif /* !_GLOB_H_ */
|
||||
@@ -0,0 +1,144 @@
|
||||
#include <inttypes.h>
|
||||
#include <stddef.h>
|
||||
#include <assert.h>
|
||||
/**
|
||||
* @file
|
||||
* Prototypes and structures for the ring buffer module.
|
||||
*/
|
||||
|
||||
#ifndef RINGBUFFER_H
|
||||
#define RINGBUFFER_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
#define RING_BUFFER_ASSERT(x) assert(x)
|
||||
|
||||
/**
|
||||
* Checks if the buffer_size is a power of two.
|
||||
* Due to the design only <tt> RING_BUFFER_SIZE-1 </tt> items
|
||||
* can be contained in the buffer.
|
||||
* buffer_size must be a power of two.
|
||||
*/
|
||||
#define RING_BUFFER_IS_POWER_OF_TWO(buffer_size) ((buffer_size & (buffer_size - 1)) == 0)
|
||||
|
||||
/**
|
||||
* The type which is used to hold the size
|
||||
* and the indicies of the buffer.
|
||||
*/
|
||||
typedef size_t ring_buffer_size_t;
|
||||
|
||||
/**
|
||||
* Used as a modulo operator
|
||||
* as <tt> a % b = (a & (b − 1)) </tt>
|
||||
* where \c a is a positive index in the buffer and
|
||||
* \c b is the (power of two) size of the buffer.
|
||||
*/
|
||||
#define RING_BUFFER_MASK(rb) (rb->buffer_mask)
|
||||
|
||||
/**
|
||||
* Simplifies the use of <tt>struct ring_buffer_t</tt>.
|
||||
*/
|
||||
typedef struct ring_buffer_t ring_buffer_t;
|
||||
|
||||
/**
|
||||
* Structure which holds a ring buffer.
|
||||
* The buffer contains a buffer array
|
||||
* as well as metadata for the ring buffer.
|
||||
*/
|
||||
struct ring_buffer_t {
|
||||
/** Buffer memory. */
|
||||
char *buffer;
|
||||
/** Buffer mask. */
|
||||
ring_buffer_size_t buffer_mask;
|
||||
/** Index of tail. */
|
||||
ring_buffer_size_t tail_index;
|
||||
/** Index of head. */
|
||||
ring_buffer_size_t head_index;
|
||||
};
|
||||
|
||||
/**
|
||||
* Initializes the ring buffer pointed to by <em>buffer</em>.
|
||||
* This function can also be used to empty/reset the buffer.
|
||||
* The resulting buffer can contain <em>buf_size-1</em> bytes.
|
||||
* @param buffer The ring buffer to initialize.
|
||||
* @param buf The buffer allocated for the ringbuffer.
|
||||
* @param buf_size The size of the allocated ringbuffer.
|
||||
*/
|
||||
void ring_buffer_init(ring_buffer_t *buffer, char *buf, size_t buf_size);
|
||||
|
||||
/**
|
||||
* Adds a byte to a ring buffer.
|
||||
* @param buffer The buffer in which the data should be placed.
|
||||
* @param data The byte to place.
|
||||
*/
|
||||
void ring_buffer_queue(ring_buffer_t *buffer, char data);
|
||||
|
||||
/**
|
||||
* Adds an array of bytes to a ring buffer.
|
||||
* @param buffer The buffer in which the data should be placed.
|
||||
* @param data A pointer to the array of bytes to place in the queue.
|
||||
* @param size The size of the array.
|
||||
*/
|
||||
void ring_buffer_queue_arr(ring_buffer_t *buffer, const char *data, ring_buffer_size_t size);
|
||||
|
||||
/**
|
||||
* Returns the oldest byte in a ring buffer.
|
||||
* @param buffer The buffer from which the data should be returned.
|
||||
* @param data A pointer to the location at which the data should be placed.
|
||||
* @return 1 if data was returned; 0 otherwise.
|
||||
*/
|
||||
uint8_t ring_buffer_dequeue(ring_buffer_t *buffer, char *data);
|
||||
|
||||
/**
|
||||
* Returns the <em>len</em> oldest bytes in a ring buffer.
|
||||
* @param buffer The buffer from which the data should be returned.
|
||||
* @param data A pointer to the array at which the data should be placed.
|
||||
* @param len The maximum number of bytes to return.
|
||||
* @return The number of bytes returned.
|
||||
*/
|
||||
ring_buffer_size_t ring_buffer_dequeue_arr(ring_buffer_t *buffer, char *data, ring_buffer_size_t len);
|
||||
/**
|
||||
* Peeks a ring buffer, i.e. returns an element without removing it.
|
||||
* @param buffer The buffer from which the data should be returned.
|
||||
* @param data A pointer to the location at which the data should be placed.
|
||||
* @param index The index to peek.
|
||||
* @return 1 if data was returned; 0 otherwise.
|
||||
*/
|
||||
uint8_t ring_buffer_peek(ring_buffer_t *buffer, char *data, ring_buffer_size_t index);
|
||||
|
||||
|
||||
/**
|
||||
* Returns whether a ring buffer is empty.
|
||||
* @param buffer The buffer for which it should be returned whether it is empty.
|
||||
* @return 1 if empty; 0 otherwise.
|
||||
*/
|
||||
inline uint8_t ring_buffer_is_empty(ring_buffer_t *buffer) {
|
||||
return (buffer->head_index == buffer->tail_index);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether a ring buffer is full.
|
||||
* @param buffer The buffer for which it should be returned whether it is full.
|
||||
* @return 1 if full; 0 otherwise.
|
||||
*/
|
||||
inline uint8_t ring_buffer_is_full(ring_buffer_t *buffer) {
|
||||
return ((buffer->head_index - buffer->tail_index) & RING_BUFFER_MASK(buffer)) == RING_BUFFER_MASK(buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of items in a ring buffer.
|
||||
* @param buffer The buffer for which the number of items should be returned.
|
||||
* @return The number of items in the ring buffer.
|
||||
*/
|
||||
inline ring_buffer_size_t ring_buffer_num_items(ring_buffer_t *buffer) {
|
||||
return ((buffer->head_index - buffer->tail_index) & RING_BUFFER_MASK(buffer));
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* RINGBUFFER_H */
|
||||
@@ -0,0 +1,221 @@
|
||||
/*!
|
||||
* \file serial/impl/unix.h
|
||||
* \author William Woodall <wjwwood@gmail.com>
|
||||
* \author John Harrison <ash@greaterthaninfinity.com>
|
||||
* \version 0.1
|
||||
*
|
||||
* \section LICENSE
|
||||
*
|
||||
* The MIT License
|
||||
*
|
||||
* Copyright (c) 2012 William Woodall, John Harrison
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
* DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* \section DESCRIPTION
|
||||
*
|
||||
* This provides a unix based pimpl for the Serial class. This implementation is
|
||||
* based off termios.h and uses select for multiplexing the IO ports.
|
||||
*
|
||||
*/
|
||||
|
||||
#if !defined(_WIN32)
|
||||
|
||||
#ifndef SERIAL_IMPL_UNIX_H
|
||||
#define SERIAL_IMPL_UNIX_H
|
||||
|
||||
#include "../../../include/serial/serial.h"
|
||||
|
||||
#include <pthread.h>
|
||||
|
||||
namespace serial {
|
||||
|
||||
using std::size_t;
|
||||
using std::string;
|
||||
using std::invalid_argument;
|
||||
|
||||
using serial::SerialException;
|
||||
using serial::IOException;
|
||||
|
||||
class MillisecondTimer {
|
||||
public:
|
||||
MillisecondTimer(const uint32_t millis);
|
||||
int64_t remaining();
|
||||
|
||||
private:
|
||||
static timespec timespec_now();
|
||||
timespec expiry;
|
||||
};
|
||||
|
||||
class serial::Serial::SerialImpl {
|
||||
public:
|
||||
SerialImpl (const string &port,
|
||||
unsigned long baudrate,
|
||||
bytesize_t bytesize,
|
||||
parity_t parity,
|
||||
stopbits_t stopbits,
|
||||
flowcontrol_t flowcontrol);
|
||||
|
||||
virtual ~SerialImpl ();
|
||||
|
||||
void
|
||||
open ();
|
||||
|
||||
void
|
||||
close ();
|
||||
|
||||
bool
|
||||
isOpen () const;
|
||||
|
||||
size_t
|
||||
available ();
|
||||
|
||||
bool
|
||||
waitReadable (uint32_t timeout);
|
||||
|
||||
void
|
||||
waitByteTimes (size_t count);
|
||||
|
||||
size_t
|
||||
read (uint8_t *buf, size_t size = 1);
|
||||
|
||||
size_t
|
||||
write (const uint8_t *data, size_t length);
|
||||
|
||||
void
|
||||
flush ();
|
||||
|
||||
void
|
||||
flushInput ();
|
||||
|
||||
void
|
||||
flushOutput ();
|
||||
|
||||
void
|
||||
sendBreak (int duration);
|
||||
|
||||
void
|
||||
setBreak (bool level);
|
||||
|
||||
void
|
||||
setRTS (bool level);
|
||||
|
||||
void
|
||||
setDTR (bool level);
|
||||
|
||||
bool
|
||||
waitForChange ();
|
||||
|
||||
bool
|
||||
getCTS ();
|
||||
|
||||
bool
|
||||
getDSR ();
|
||||
|
||||
bool
|
||||
getRI ();
|
||||
|
||||
bool
|
||||
getCD ();
|
||||
|
||||
void
|
||||
setPort (const string &port);
|
||||
|
||||
string
|
||||
getPort () const;
|
||||
|
||||
void
|
||||
setTimeout (Timeout &timeout);
|
||||
|
||||
Timeout
|
||||
getTimeout () const;
|
||||
|
||||
void
|
||||
setBaudrate (unsigned long baudrate);
|
||||
|
||||
unsigned long
|
||||
getBaudrate () const;
|
||||
|
||||
void
|
||||
setBytesize (bytesize_t bytesize);
|
||||
|
||||
bytesize_t
|
||||
getBytesize () const;
|
||||
|
||||
void
|
||||
setParity (parity_t parity);
|
||||
|
||||
parity_t
|
||||
getParity () const;
|
||||
|
||||
void
|
||||
setStopbits (stopbits_t stopbits);
|
||||
|
||||
stopbits_t
|
||||
getStopbits () const;
|
||||
|
||||
void
|
||||
setFlowcontrol (flowcontrol_t flowcontrol);
|
||||
|
||||
flowcontrol_t
|
||||
getFlowcontrol () const;
|
||||
|
||||
void
|
||||
readLock ();
|
||||
|
||||
void
|
||||
readUnlock ();
|
||||
|
||||
void
|
||||
writeLock ();
|
||||
|
||||
void
|
||||
writeUnlock ();
|
||||
|
||||
protected:
|
||||
void reconfigurePort ();
|
||||
|
||||
private:
|
||||
string port_; // Path to the file descriptor
|
||||
int fd_; // The current file descriptor
|
||||
|
||||
bool is_open_;
|
||||
bool xonxoff_;
|
||||
bool rtscts_;
|
||||
|
||||
Timeout timeout_; // Timeout for read operations
|
||||
unsigned long baudrate_; // Baudrate
|
||||
uint32_t byte_time_ns_; // Nanoseconds to transmit/receive a single byte
|
||||
|
||||
parity_t parity_; // Parity
|
||||
bytesize_t bytesize_; // Size of the bytes
|
||||
stopbits_t stopbits_; // Stop Bits
|
||||
flowcontrol_t flowcontrol_; // Flow Control
|
||||
|
||||
// Mutex used to lock the read functions
|
||||
pthread_mutex_t read_mutex;
|
||||
// Mutex used to lock the write functions
|
||||
pthread_mutex_t write_mutex;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // SERIAL_IMPL_UNIX_H
|
||||
|
||||
#endif // !defined(_WIN32)
|
||||
@@ -0,0 +1,207 @@
|
||||
/*!
|
||||
* \file serial/impl/windows.h
|
||||
* \author William Woodall <wjwwood@gmail.com>
|
||||
* \author John Harrison <ash@greaterthaninfinity.com>
|
||||
* \version 0.1
|
||||
*
|
||||
* \section LICENSE
|
||||
*
|
||||
* The MIT License
|
||||
*
|
||||
* Copyright (c) 2012 William Woodall, John Harrison
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
* DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* \section DESCRIPTION
|
||||
*
|
||||
* This provides a windows implementation of the Serial class interface.
|
||||
*
|
||||
*/
|
||||
|
||||
#if defined(_WIN32)
|
||||
|
||||
#ifndef SERIAL_IMPL_WINDOWS_H
|
||||
#define SERIAL_IMPL_WINDOWS_H
|
||||
|
||||
#include "serial/serial.h"
|
||||
|
||||
#include "windows.h"
|
||||
|
||||
namespace serial {
|
||||
|
||||
using std::string;
|
||||
using std::wstring;
|
||||
using std::invalid_argument;
|
||||
|
||||
using serial::SerialException;
|
||||
using serial::IOException;
|
||||
|
||||
class serial::Serial::SerialImpl {
|
||||
public:
|
||||
SerialImpl (const string &port,
|
||||
unsigned long baudrate,
|
||||
bytesize_t bytesize,
|
||||
parity_t parity,
|
||||
stopbits_t stopbits,
|
||||
flowcontrol_t flowcontrol);
|
||||
|
||||
virtual ~SerialImpl ();
|
||||
|
||||
void
|
||||
open ();
|
||||
|
||||
void
|
||||
close ();
|
||||
|
||||
bool
|
||||
isOpen () const;
|
||||
|
||||
size_t
|
||||
available ();
|
||||
|
||||
bool
|
||||
waitReadable (uint32_t timeout);
|
||||
|
||||
void
|
||||
waitByteTimes (size_t count);
|
||||
|
||||
size_t
|
||||
read (uint8_t *buf, size_t size = 1);
|
||||
|
||||
size_t
|
||||
write (const uint8_t *data, size_t length);
|
||||
|
||||
void
|
||||
flush ();
|
||||
|
||||
void
|
||||
flushInput ();
|
||||
|
||||
void
|
||||
flushOutput ();
|
||||
|
||||
void
|
||||
sendBreak (int duration);
|
||||
|
||||
void
|
||||
setBreak (bool level);
|
||||
|
||||
void
|
||||
setRTS (bool level);
|
||||
|
||||
void
|
||||
setDTR (bool level);
|
||||
|
||||
bool
|
||||
waitForChange ();
|
||||
|
||||
bool
|
||||
getCTS ();
|
||||
|
||||
bool
|
||||
getDSR ();
|
||||
|
||||
bool
|
||||
getRI ();
|
||||
|
||||
bool
|
||||
getCD ();
|
||||
|
||||
void
|
||||
setPort (const string &port);
|
||||
|
||||
string
|
||||
getPort () const;
|
||||
|
||||
void
|
||||
setTimeout (Timeout &timeout);
|
||||
|
||||
Timeout
|
||||
getTimeout () const;
|
||||
|
||||
void
|
||||
setBaudrate (unsigned long baudrate);
|
||||
|
||||
unsigned long
|
||||
getBaudrate () const;
|
||||
|
||||
void
|
||||
setBytesize (bytesize_t bytesize);
|
||||
|
||||
bytesize_t
|
||||
getBytesize () const;
|
||||
|
||||
void
|
||||
setParity (parity_t parity);
|
||||
|
||||
parity_t
|
||||
getParity () const;
|
||||
|
||||
void
|
||||
setStopbits (stopbits_t stopbits);
|
||||
|
||||
stopbits_t
|
||||
getStopbits () const;
|
||||
|
||||
void
|
||||
setFlowcontrol (flowcontrol_t flowcontrol);
|
||||
|
||||
flowcontrol_t
|
||||
getFlowcontrol () const;
|
||||
|
||||
void
|
||||
readLock ();
|
||||
|
||||
void
|
||||
readUnlock ();
|
||||
|
||||
void
|
||||
writeLock ();
|
||||
|
||||
void
|
||||
writeUnlock ();
|
||||
|
||||
protected:
|
||||
void reconfigurePort ();
|
||||
|
||||
private:
|
||||
wstring port_; // Path to the file descriptor
|
||||
HANDLE fd_;
|
||||
|
||||
bool is_open_;
|
||||
|
||||
Timeout timeout_; // Timeout for read operations
|
||||
unsigned long baudrate_; // Baudrate
|
||||
|
||||
parity_t parity_; // Parity
|
||||
bytesize_t bytesize_; // Size of the bytes
|
||||
stopbits_t stopbits_; // Stop Bits
|
||||
flowcontrol_t flowcontrol_; // Flow Control
|
||||
|
||||
// Mutex used to lock the read functions
|
||||
HANDLE read_mutex;
|
||||
// Mutex used to lock the write functions
|
||||
HANDLE write_mutex;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // SERIAL_IMPL_WINDOWS_H
|
||||
|
||||
#endif // if defined(_WIN32)
|
||||
@@ -0,0 +1,780 @@
|
||||
/*!
|
||||
* \file serial/serial.h
|
||||
* \author William Woodall <wjwwood@gmail.com>
|
||||
* \author John Harrison <ash.gti@gmail.com>
|
||||
* \version 0.1
|
||||
*
|
||||
* \section LICENSE
|
||||
*
|
||||
* The MIT License
|
||||
*
|
||||
* Copyright (c) 2012 William Woodall
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
* DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* \section DESCRIPTION
|
||||
*
|
||||
* This provides a cross platform interface for interacting with Serial Ports.
|
||||
*/
|
||||
|
||||
#ifndef SERIAL_H
|
||||
#define SERIAL_H
|
||||
|
||||
#include <limits>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <cstring>
|
||||
#include <sstream>
|
||||
#include <exception>
|
||||
#include <stdexcept>
|
||||
#include "v8stdint.h"
|
||||
|
||||
|
||||
|
||||
#define THROWEX(exceptionClass, message, errorno) throw exceptionClass(__FILE__, \
|
||||
__LINE__, (message), (errorno) )
|
||||
|
||||
#define THROW(exceptionClass, message) throw exceptionClass(__FILE__, \
|
||||
__LINE__, (message) )
|
||||
|
||||
namespace serial {
|
||||
|
||||
/*!
|
||||
* Enumeration defines the possible bytesizes for the serial port.
|
||||
*/
|
||||
typedef enum {
|
||||
fivebits = 5,
|
||||
sixbits = 6,
|
||||
sevenbits = 7,
|
||||
eightbits = 8
|
||||
} bytesize_t;
|
||||
|
||||
/*!
|
||||
* Enumeration defines the possible parity types for the serial port.
|
||||
*/
|
||||
typedef enum {
|
||||
parity_none = 0,
|
||||
parity_odd = 1,
|
||||
parity_even = 2,
|
||||
parity_mark = 3,
|
||||
parity_space = 4
|
||||
} parity_t;
|
||||
|
||||
/*!
|
||||
* Enumeration defines the possible stopbit types for the serial port.
|
||||
*/
|
||||
typedef enum {
|
||||
stopbits_one = 1,
|
||||
stopbits_two = 2,
|
||||
stopbits_one_point_five
|
||||
} stopbits_t;
|
||||
|
||||
/*!
|
||||
* Enumeration defines the possible flowcontrol types for the serial port.
|
||||
*/
|
||||
typedef enum {
|
||||
flowcontrol_none = 0,
|
||||
flowcontrol_software,
|
||||
flowcontrol_hardware
|
||||
} flowcontrol_t;
|
||||
|
||||
/*!
|
||||
* Structure for setting the timeout of the serial port, times are
|
||||
* in milliseconds.
|
||||
*
|
||||
* In order to disable the interbyte timeout, set it to Timeout::max().
|
||||
*/
|
||||
struct Timeout {
|
||||
#ifdef max
|
||||
# undef max
|
||||
#endif
|
||||
static uint32_t max() {return std::numeric_limits<uint32_t>::max();}
|
||||
/*!
|
||||
* Convenience function to generate Timeout structs using a
|
||||
* single absolute timeout.
|
||||
*
|
||||
* \param timeout A long that defines the time in milliseconds until a
|
||||
* timeout occurs after a call to read or write is made.
|
||||
*
|
||||
* \return Timeout struct that represents this simple timeout provided.
|
||||
*/
|
||||
static Timeout simpleTimeout(uint32_t timeout) {
|
||||
return Timeout(10, timeout, 0, timeout, 0);
|
||||
}
|
||||
|
||||
/*! Number of milliseconds between bytes received to timeout on. */
|
||||
uint32_t inter_byte_timeout;
|
||||
/*! A constant number of milliseconds to wait after calling read. */
|
||||
uint32_t read_timeout_constant;
|
||||
/*! A multiplier against the number of requested bytes to wait after
|
||||
* calling read.
|
||||
*/
|
||||
uint32_t read_timeout_multiplier;
|
||||
/*! A constant number of milliseconds to wait after calling write. */
|
||||
uint32_t write_timeout_constant;
|
||||
/*! A multiplier against the number of requested bytes to wait after
|
||||
* calling write.
|
||||
*/
|
||||
uint32_t write_timeout_multiplier;
|
||||
|
||||
explicit Timeout (uint32_t inter_byte_timeout_=0,
|
||||
uint32_t read_timeout_constant_=0,
|
||||
uint32_t read_timeout_multiplier_=0,
|
||||
uint32_t write_timeout_constant_=0,
|
||||
uint32_t write_timeout_multiplier_=0)
|
||||
: inter_byte_timeout(inter_byte_timeout_),
|
||||
read_timeout_constant(read_timeout_constant_),
|
||||
read_timeout_multiplier(read_timeout_multiplier_),
|
||||
write_timeout_constant(write_timeout_constant_),
|
||||
write_timeout_multiplier(write_timeout_multiplier_)
|
||||
{}
|
||||
};
|
||||
|
||||
/*!
|
||||
* Class that provides a portable serial port interface.
|
||||
*/
|
||||
class Serial {
|
||||
public:
|
||||
/*!
|
||||
* Creates a Serial object and opens the port if a port is specified,
|
||||
* otherwise it remains closed until serial::Serial::open is called.
|
||||
*
|
||||
* \param port A std::string containing the address of the serial port,
|
||||
* which would be something like 'COM1' on Windows and '/dev/ttyS0'
|
||||
* on Linux.
|
||||
*
|
||||
* \param baudrate An unsigned 32-bit integer that represents the baudrate
|
||||
*
|
||||
* \param timeout A serial::Timeout struct that defines the timeout
|
||||
* conditions for the serial port. \see serial::Timeout
|
||||
*
|
||||
* \param bytesize Size of each byte in the serial transmission of data,
|
||||
* default is eightbits, possible values are: fivebits, sixbits, sevenbits,
|
||||
* eightbits
|
||||
*
|
||||
* \param parity Method of parity, default is parity_none, possible values
|
||||
* are: parity_none, parity_odd, parity_even
|
||||
*
|
||||
* \param stopbits Number of stop bits used, default is stopbits_one,
|
||||
* possible values are: stopbits_one, stopbits_one_point_five, stopbits_two
|
||||
*
|
||||
* \param flowcontrol Type of flowcontrol used, default is
|
||||
* flowcontrol_none, possible values are: flowcontrol_none,
|
||||
* flowcontrol_software, flowcontrol_hardware
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::IOException
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
Serial (const std::string &port = "",
|
||||
uint32_t baudrate = 9600,
|
||||
Timeout timeout = Timeout(),
|
||||
bytesize_t bytesize = eightbits,
|
||||
parity_t parity = parity_none,
|
||||
stopbits_t stopbits = stopbits_one,
|
||||
flowcontrol_t flowcontrol = flowcontrol_none);
|
||||
|
||||
/*! Destructor */
|
||||
virtual ~Serial ();
|
||||
|
||||
/*!
|
||||
* Opens the serial port as long as the port is set and the port isn't
|
||||
* already open.
|
||||
*
|
||||
* If the port is provided to the constructor then an explicit call to open
|
||||
* is not needed.
|
||||
*
|
||||
* \see Serial::Serial
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
* \throw serial::SerialException
|
||||
* \throw serial::IOException
|
||||
*/
|
||||
void
|
||||
open ();
|
||||
|
||||
/*! Gets the open status of the serial port.
|
||||
*
|
||||
* \return Returns true if the port is open, false otherwise.
|
||||
*/
|
||||
bool
|
||||
isOpen () const;
|
||||
|
||||
/*! Closes the serial port. */
|
||||
void
|
||||
close ();
|
||||
|
||||
/*! Return the number of characters in the buffer. */
|
||||
size_t
|
||||
available ();
|
||||
|
||||
/*! Block until there is serial data to read or read_timeout_constant
|
||||
* number of milliseconds have elapsed. The return value is true when
|
||||
* the function exits with the port in a readable state, false otherwise
|
||||
* (due to timeout or select interruption). */
|
||||
bool
|
||||
waitReadable ();
|
||||
|
||||
/*! Block for a period of time corresponding to the transmission time of
|
||||
* count characters at present serial settings. This may be used in con-
|
||||
* junction with waitReadable to read larger blocks of data from the
|
||||
* port. */
|
||||
void
|
||||
waitByteTimes (size_t count);
|
||||
|
||||
/*! Read a given amount of bytes from the serial port into a given buffer.
|
||||
*
|
||||
* The read function will return in one of three cases:
|
||||
* * The number of requested bytes was read.
|
||||
* * In this case the number of bytes requested will match the size_t
|
||||
* returned by read.
|
||||
* * A timeout occurred, in this case the number of bytes read will not
|
||||
* match the amount requested, but no exception will be thrown. One of
|
||||
* two possible timeouts occurred:
|
||||
* * The inter byte timeout expired, this means that number of
|
||||
* milliseconds elapsed between receiving bytes from the serial port
|
||||
* exceeded the inter byte timeout.
|
||||
* * The total timeout expired, which is calculated by multiplying the
|
||||
* read timeout multiplier by the number of requested bytes and then
|
||||
* added to the read timeout constant. If that total number of
|
||||
* milliseconds elapses after the initial call to read a timeout will
|
||||
* occur.
|
||||
* * An exception occurred, in this case an actual exception will be thrown.
|
||||
*
|
||||
* \param buffer An uint8_t array of at least the requested size.
|
||||
* \param size A size_t defining how many bytes to be read.
|
||||
*
|
||||
* \return A size_t representing the number of bytes read as a result of the
|
||||
* call to read.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
*/
|
||||
size_t
|
||||
read (uint8_t *buffer, size_t size);
|
||||
|
||||
/*! Read a given amount of bytes from the serial port into a give buffer.
|
||||
*
|
||||
* \param buffer A reference to a std::vector of uint8_t.
|
||||
* \param size A size_t defining how many bytes to be read.
|
||||
*
|
||||
* \return A size_t representing the number of bytes read as a result of the
|
||||
* call to read.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
*/
|
||||
size_t
|
||||
read (std::vector<uint8_t> &buffer, size_t size = 1);
|
||||
|
||||
/*! Read a given amount of bytes from the serial port into a give buffer.
|
||||
*
|
||||
* \param buffer A reference to a std::string.
|
||||
* \param size A size_t defining how many bytes to be read.
|
||||
*
|
||||
* \return A size_t representing the number of bytes read as a result of the
|
||||
* call to read.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
*/
|
||||
size_t
|
||||
read (std::string &buffer, size_t size = 1);
|
||||
|
||||
/*! Read a given amount of bytes from the serial port and return a string
|
||||
* containing the data.
|
||||
*
|
||||
* \param size A size_t defining how many bytes to be read.
|
||||
*
|
||||
* \return A std::string containing the data read from the port.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
*/
|
||||
std::string
|
||||
read (size_t size = 1);
|
||||
|
||||
/*! Reads in a line or until a given delimiter has been processed.
|
||||
*
|
||||
* Reads from the serial port until a single line has been read.
|
||||
*
|
||||
* \param buffer A std::string reference used to store the data.
|
||||
* \param size A maximum length of a line, defaults to 65536 (2^16)
|
||||
* \param eol A string to match against for the EOL.
|
||||
*
|
||||
* \return A size_t representing the number of bytes read.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
*/
|
||||
size_t
|
||||
readline (std::string &buffer, size_t size = 65536, std::string eol = "\n");
|
||||
|
||||
/*! Reads in a line or until a given delimiter has been processed.
|
||||
*
|
||||
* Reads from the serial port until a single line has been read.
|
||||
*
|
||||
* \param size A maximum length of a line, defaults to 65536 (2^16)
|
||||
* \param eol A string to match against for the EOL.
|
||||
*
|
||||
* \return A std::string containing the line.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
*/
|
||||
std::string
|
||||
readline (size_t size = 65536, std::string eol = "\n");
|
||||
|
||||
/*! Reads in multiple lines until the serial port times out.
|
||||
*
|
||||
* This requires a timeout > 0 before it can be run. It will read until a
|
||||
* timeout occurs and return a list of strings.
|
||||
*
|
||||
* \param size A maximum length of combined lines, defaults to 65536 (2^16)
|
||||
*
|
||||
* \param eol A string to match against for the EOL.
|
||||
*
|
||||
* \return A vector<string> containing the lines.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
*/
|
||||
std::vector<std::string>
|
||||
readlines (size_t size = 65536, std::string eol = "\n");
|
||||
|
||||
/*! Write a string to the serial port.
|
||||
*
|
||||
* \param data A const reference containing the data to be written
|
||||
* to the serial port.
|
||||
*
|
||||
* \param size A size_t that indicates how many bytes should be written from
|
||||
* the given data buffer.
|
||||
*
|
||||
* \return A size_t representing the number of bytes actually written to
|
||||
* the serial port.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
* \throw serial::IOException
|
||||
*/
|
||||
size_t
|
||||
write (const uint8_t *data, size_t size);
|
||||
|
||||
/*! Write a string to the serial port.
|
||||
*
|
||||
* \param data A const reference containing the data to be written
|
||||
* to the serial port.
|
||||
*
|
||||
* \return A size_t representing the number of bytes actually written to
|
||||
* the serial port.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
* \throw serial::IOException
|
||||
*/
|
||||
size_t
|
||||
write (const std::vector<uint8_t> &data);
|
||||
|
||||
/*! Write a string to the serial port.
|
||||
*
|
||||
* \param data A const reference containing the data to be written
|
||||
* to the serial port.
|
||||
*
|
||||
* \return A size_t representing the number of bytes actually written to
|
||||
* the serial port.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
* \throw serial::IOException
|
||||
*/
|
||||
size_t
|
||||
write (const std::string &data);
|
||||
|
||||
/*! Sets the serial port identifier.
|
||||
*
|
||||
* \param port A const std::string reference containing the address of the
|
||||
* serial port, which would be something like 'COM1' on Windows and
|
||||
* '/dev/ttyS0' on Linux.
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
void
|
||||
setPort (const std::string &port);
|
||||
|
||||
/*! Gets the serial port identifier.
|
||||
*
|
||||
* \see Serial::setPort
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
std::string
|
||||
getPort () const;
|
||||
|
||||
/*! Sets the timeout for reads and writes using the Timeout struct.
|
||||
*
|
||||
* There are two timeout conditions described here:
|
||||
* * The inter byte timeout:
|
||||
* * The inter_byte_timeout component of serial::Timeout defines the
|
||||
* maximum amount of time, in milliseconds, between receiving bytes on
|
||||
* the serial port that can pass before a timeout occurs. Setting this
|
||||
* to zero will prevent inter byte timeouts from occurring.
|
||||
* * Total time timeout:
|
||||
* * The constant and multiplier component of this timeout condition,
|
||||
* for both read and write, are defined in serial::Timeout. This
|
||||
* timeout occurs if the total time since the read or write call was
|
||||
* made exceeds the specified time in milliseconds.
|
||||
* * The limit is defined by multiplying the multiplier component by the
|
||||
* number of requested bytes and adding that product to the constant
|
||||
* component. In this way if you want a read call, for example, to
|
||||
* timeout after exactly one second regardless of the number of bytes
|
||||
* you asked for then set the read_timeout_constant component of
|
||||
* serial::Timeout to 1000 and the read_timeout_multiplier to zero.
|
||||
* This timeout condition can be used in conjunction with the inter
|
||||
* byte timeout condition with out any problems, timeout will simply
|
||||
* occur when one of the two timeout conditions is met. This allows
|
||||
* users to have maximum control over the trade-off between
|
||||
* responsiveness and efficiency.
|
||||
*
|
||||
* Read and write functions will return in one of three cases. When the
|
||||
* reading or writing is complete, when a timeout occurs, or when an
|
||||
* exception occurs.
|
||||
*
|
||||
* A timeout of 0 enables non-blocking mode.
|
||||
*
|
||||
* \param timeout A serial::Timeout struct containing the inter byte
|
||||
* timeout, and the read and write timeout constants and multipliers.
|
||||
*
|
||||
* \see serial::Timeout
|
||||
*/
|
||||
void
|
||||
setTimeout (Timeout &timeout);
|
||||
|
||||
/*! Sets the timeout for reads and writes. */
|
||||
void
|
||||
setTimeout (uint32_t inter_byte_timeout, uint32_t read_timeout_constant,
|
||||
uint32_t read_timeout_multiplier, uint32_t write_timeout_constant,
|
||||
uint32_t write_timeout_multiplier)
|
||||
{
|
||||
Timeout timeout(inter_byte_timeout, read_timeout_constant,
|
||||
read_timeout_multiplier, write_timeout_constant,
|
||||
write_timeout_multiplier);
|
||||
return setTimeout(timeout);
|
||||
}
|
||||
|
||||
/*! Gets the timeout for reads in seconds.
|
||||
*
|
||||
* \return A Timeout struct containing the inter_byte_timeout, and read
|
||||
* and write timeout constants and multipliers.
|
||||
*
|
||||
* \see Serial::setTimeout
|
||||
*/
|
||||
Timeout
|
||||
getTimeout () const;
|
||||
|
||||
/*! Sets the baudrate for the serial port.
|
||||
*
|
||||
* Possible baudrates depends on the system but some safe baudrates include:
|
||||
* 110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 56000,
|
||||
* 57600, 115200
|
||||
* Some other baudrates that are supported by some comports:
|
||||
* 128000, 153600, 230400, 256000, 460800, 500000, 921600
|
||||
*
|
||||
* \param baudrate An integer that sets the baud rate for the serial port.
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
void
|
||||
setBaudrate (uint32_t baudrate);
|
||||
|
||||
/*! Gets the baudrate for the serial port.
|
||||
*
|
||||
* \return An integer that sets the baud rate for the serial port.
|
||||
*
|
||||
* \see Serial::setBaudrate
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
uint32_t
|
||||
getBaudrate () const;
|
||||
|
||||
/*! Sets the bytesize for the serial port.
|
||||
*
|
||||
* \param bytesize Size of each byte in the serial transmission of data,
|
||||
* default is eightbits, possible values are: fivebits, sixbits, sevenbits,
|
||||
* eightbits
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
void
|
||||
setBytesize (bytesize_t bytesize);
|
||||
|
||||
/*! Gets the bytesize for the serial port.
|
||||
*
|
||||
* \see Serial::setBytesize
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
bytesize_t
|
||||
getBytesize () const;
|
||||
|
||||
/*! Sets the parity for the serial port.
|
||||
*
|
||||
* \param parity Method of parity, default is parity_none, possible values
|
||||
* are: parity_none, parity_odd, parity_even
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
void
|
||||
setParity (parity_t parity);
|
||||
|
||||
/*! Gets the parity for the serial port.
|
||||
*
|
||||
* \see Serial::setParity
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
parity_t
|
||||
getParity () const;
|
||||
|
||||
/*! Sets the stopbits for the serial port.
|
||||
*
|
||||
* \param stopbits Number of stop bits used, default is stopbits_one,
|
||||
* possible values are: stopbits_one, stopbits_one_point_five, stopbits_two
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
void
|
||||
setStopbits (stopbits_t stopbits);
|
||||
|
||||
/*! Gets the stopbits for the serial port.
|
||||
*
|
||||
* \see Serial::setStopbits
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
stopbits_t
|
||||
getStopbits () const;
|
||||
|
||||
/*! Sets the flow control for the serial port.
|
||||
*
|
||||
* \param flowcontrol Type of flowcontrol used, default is flowcontrol_none,
|
||||
* possible values are: flowcontrol_none, flowcontrol_software,
|
||||
* flowcontrol_hardware
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
void
|
||||
setFlowcontrol (flowcontrol_t flowcontrol);
|
||||
|
||||
/*! Gets the flow control for the serial port.
|
||||
*
|
||||
* \see Serial::setFlowcontrol
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
flowcontrol_t
|
||||
getFlowcontrol () const;
|
||||
|
||||
/*! Flush the input and output buffers */
|
||||
void
|
||||
flush ();
|
||||
|
||||
/*! Flush only the input buffer */
|
||||
void
|
||||
flushInput ();
|
||||
|
||||
/*! Flush only the output buffer */
|
||||
void
|
||||
flushOutput ();
|
||||
|
||||
/*! Sends the RS-232 break signal. See tcsendbreak(3). */
|
||||
void
|
||||
sendBreak (int duration);
|
||||
|
||||
/*! Set the break condition to a given level. Defaults to true. */
|
||||
void
|
||||
setBreak (bool level = true);
|
||||
|
||||
/*! Set the RTS handshaking line to the given level. Defaults to true. */
|
||||
void
|
||||
setRTS (bool level = true);
|
||||
|
||||
/*! Set the DTR handshaking line to the given level. Defaults to true. */
|
||||
void
|
||||
setDTR (bool level = true);
|
||||
|
||||
/*!
|
||||
* Blocks until CTS, DSR, RI, CD changes or something interrupts it.
|
||||
*
|
||||
* Can throw an exception if an error occurs while waiting.
|
||||
* You can check the status of CTS, DSR, RI, and CD once this returns.
|
||||
* Uses TIOCMIWAIT via ioctl if available (mostly only on Linux) with a
|
||||
* resolution of less than +-1ms and as good as +-0.2ms. Otherwise a
|
||||
* polling method is used which can give +-2ms.
|
||||
*
|
||||
* \return Returns true if one of the lines changed, false if something else
|
||||
* occurred.
|
||||
*
|
||||
* \throw SerialException
|
||||
*/
|
||||
bool
|
||||
waitForChange ();
|
||||
|
||||
/*! Returns the current status of the CTS line. */
|
||||
bool
|
||||
getCTS ();
|
||||
|
||||
/*! Returns the current status of the DSR line. */
|
||||
bool
|
||||
getDSR ();
|
||||
|
||||
/*! Returns the current status of the RI line. */
|
||||
bool
|
||||
getRI ();
|
||||
|
||||
/*! Returns the current status of the CD line. */
|
||||
bool
|
||||
getCD ();
|
||||
|
||||
private:
|
||||
// Disable copy constructors
|
||||
Serial(const Serial&);
|
||||
Serial& operator=(const Serial&);
|
||||
|
||||
// Pimpl idiom, d_pointer
|
||||
class SerialImpl;
|
||||
SerialImpl *pimpl_;
|
||||
|
||||
// Scoped Lock Classes
|
||||
class ScopedReadLock;
|
||||
class ScopedWriteLock;
|
||||
|
||||
// Read common function
|
||||
size_t
|
||||
read_ (uint8_t *buffer, size_t size);
|
||||
// Write common function
|
||||
size_t
|
||||
write_ (const uint8_t *data, size_t length);
|
||||
|
||||
};
|
||||
|
||||
class SerialException : public std::exception
|
||||
{
|
||||
// Disable copy constructors
|
||||
SerialException& operator=(const SerialException&);
|
||||
std::string e_what_;
|
||||
public:
|
||||
SerialException (const char *description) {
|
||||
std::stringstream ss;
|
||||
ss << "SerialException " << description << " failed.";
|
||||
e_what_ = ss.str();
|
||||
}
|
||||
SerialException (const SerialException& other) : e_what_(other.e_what_) {}
|
||||
virtual ~SerialException() throw() {}
|
||||
virtual const char* what () const throw () {
|
||||
return e_what_.c_str();
|
||||
}
|
||||
};
|
||||
|
||||
class IOException : public std::exception
|
||||
{
|
||||
// Disable copy constructors
|
||||
IOException& operator=(const IOException&);
|
||||
std::string file_;
|
||||
int line_;
|
||||
std::string e_what_;
|
||||
int errno_;
|
||||
public:
|
||||
explicit IOException (std::string file, int line, int errnum = 0)
|
||||
: file_(file), line_(line), errno_(errnum) {
|
||||
std::stringstream ss;
|
||||
#if defined(_WIN32) && !defined(__MINGW32__)
|
||||
char error_str [1024];
|
||||
strerror_s(error_str, 1024, errnum);
|
||||
#else
|
||||
char * error_str = strerror(errnum);
|
||||
#endif
|
||||
ss << "IO Exception (" << errno_ << "): " << error_str;
|
||||
ss << ", file " << file_ << ", line " << line_ << ".";
|
||||
e_what_ = ss.str();
|
||||
}
|
||||
explicit IOException (std::string file, int line, const char * description, int errnum = 0)
|
||||
: file_(file), line_(line), errno_(errnum) {
|
||||
std::stringstream ss;
|
||||
ss << "IO Exception: " << description;
|
||||
ss << ", file " << file_ << ", line " << line_ << ".";
|
||||
e_what_ = ss.str();
|
||||
}
|
||||
virtual ~IOException() throw() {}
|
||||
IOException (const IOException& other) : line_(other.line_), e_what_(other.e_what_), errno_(other.errno_) {}
|
||||
|
||||
int getErrorNumber () const { return errno_; }
|
||||
|
||||
virtual const char* what () const throw () {
|
||||
return e_what_.c_str();
|
||||
}
|
||||
};
|
||||
|
||||
class PortNotOpenedException : public std::exception
|
||||
{
|
||||
// Disable copy constructors
|
||||
const PortNotOpenedException& operator=(PortNotOpenedException);
|
||||
std::string e_what_;
|
||||
public:
|
||||
PortNotOpenedException (const char * description) {
|
||||
std::stringstream ss;
|
||||
ss << "PortNotOpenedException " << description << " failed.";
|
||||
e_what_ = ss.str();
|
||||
}
|
||||
PortNotOpenedException (const PortNotOpenedException& other) : e_what_(other.e_what_) {}
|
||||
virtual ~PortNotOpenedException() throw() {}
|
||||
virtual const char* what () const throw () {
|
||||
return e_what_.c_str();
|
||||
}
|
||||
};
|
||||
|
||||
/*!
|
||||
* Structure that describes a serial device.
|
||||
*/
|
||||
struct PortInfo {
|
||||
|
||||
/*! Address of the serial port (this can be passed to the constructor of Serial). */
|
||||
std::string port;
|
||||
|
||||
/*! Human readable description of serial device if available. */
|
||||
std::string description;
|
||||
|
||||
/*! Hardware ID (e.g. VID:PID of USB serial devices) or "n/a" if not available. */
|
||||
std::string hardware_id;
|
||||
|
||||
};
|
||||
|
||||
/* Lists the serial ports available on the system
|
||||
*
|
||||
* Returns a vector of available serial ports, each represented
|
||||
* by a serial::PortInfo data structure:
|
||||
*
|
||||
* \return vector of serial::PortInfo.
|
||||
*/
|
||||
std::vector<PortInfo>
|
||||
list_ports();
|
||||
|
||||
} // namespace serial
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,57 @@
|
||||
// This header is from the v8 google project:
|
||||
// http://code.google.com/p/v8/source/browse/trunk/include/v8stdint.h
|
||||
|
||||
// Copyright 2012 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// Load definitions of standard types.
|
||||
|
||||
#ifndef V8STDINT_H_
|
||||
#define V8STDINT_H_
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#if defined(_WIN32) && !defined(__MINGW32__)
|
||||
|
||||
typedef signed char int8_t;
|
||||
typedef unsigned char uint8_t;
|
||||
typedef short int16_t; // NOLINT
|
||||
typedef unsigned short uint16_t; // NOLINT
|
||||
typedef int int32_t;
|
||||
typedef unsigned int uint32_t;
|
||||
typedef __int64 int64_t;
|
||||
typedef unsigned __int64 uint64_t;
|
||||
// intptr_t and friends are defined in crtdefs.h through stdio.h.
|
||||
|
||||
#else
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#endif
|
||||
|
||||
#endif // V8STDINT_H_
|
||||
@@ -0,0 +1,479 @@
|
||||
/* -*- mode: c; tab-width: 2; indent-tabs-mode: nil; -*-
|
||||
Copyright (c) 2012 Marcus Geelnard
|
||||
Copyright (c) 2013-2016 Evan Nemerson
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
*/
|
||||
|
||||
#ifndef _TINYCTHREAD_H_
|
||||
#define _TINYCTHREAD_H_
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @file
|
||||
* @mainpage TinyCThread API Reference
|
||||
*
|
||||
* @section intro_sec Introduction
|
||||
* TinyCThread is a minimal, portable implementation of basic threading
|
||||
* classes for C.
|
||||
*
|
||||
* They closely mimic the functionality and naming of the C11 standard, and
|
||||
* should be easily replaceable with the corresponding standard variants.
|
||||
*
|
||||
* @section port_sec Portability
|
||||
* The Win32 variant uses the native Win32 API for implementing the thread
|
||||
* classes, while for other systems, the POSIX threads API (pthread) is used.
|
||||
*
|
||||
* @section misc_sec Miscellaneous
|
||||
* The following special keywords are available: #_Thread_local.
|
||||
*
|
||||
* For more detailed information, browse the different sections of this
|
||||
* documentation. A good place to start is:
|
||||
* tinycthread.h.
|
||||
*/
|
||||
|
||||
/* Which platform are we on? */
|
||||
#if !defined(_TTHREAD_PLATFORM_DEFINED_)
|
||||
#if defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__)
|
||||
#define _TTHREAD_WIN32_
|
||||
#else
|
||||
#define _TTHREAD_POSIX_
|
||||
#endif
|
||||
#define _TTHREAD_PLATFORM_DEFINED_
|
||||
#endif
|
||||
|
||||
/* Activate some POSIX functionality (e.g. clock_gettime and recursive mutexes) */
|
||||
#if defined(_TTHREAD_POSIX_)
|
||||
#undef _FEATURES_H
|
||||
#if !defined(_GNU_SOURCE)
|
||||
#define _GNU_SOURCE
|
||||
#endif
|
||||
#if !defined(_POSIX_C_SOURCE) || ((_POSIX_C_SOURCE - 0) < 199309L)
|
||||
#undef _POSIX_C_SOURCE
|
||||
#define _POSIX_C_SOURCE 199309L
|
||||
#endif
|
||||
#if !defined(_XOPEN_SOURCE) || ((_XOPEN_SOURCE - 0) < 500)
|
||||
#undef _XOPEN_SOURCE
|
||||
#define _XOPEN_SOURCE 500
|
||||
#endif
|
||||
#define _XPG6
|
||||
#endif
|
||||
|
||||
/* Generic includes */
|
||||
#include <time.h>
|
||||
|
||||
/* Platform specific includes */
|
||||
#if defined(_TTHREAD_POSIX_)
|
||||
#include <pthread.h>
|
||||
#elif defined(_TTHREAD_WIN32_)
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#define __UNDEF_LEAN_AND_MEAN
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#ifdef __UNDEF_LEAN_AND_MEAN
|
||||
#undef WIN32_LEAN_AND_MEAN
|
||||
#undef __UNDEF_LEAN_AND_MEAN
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/* Compiler-specific information */
|
||||
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
|
||||
#define TTHREAD_NORETURN _Noreturn
|
||||
#elif defined(__GNUC__)
|
||||
#define TTHREAD_NORETURN __attribute__((__noreturn__))
|
||||
#else
|
||||
#define TTHREAD_NORETURN
|
||||
#endif
|
||||
|
||||
/* If TIME_UTC is missing, provide it and provide a wrapper for
|
||||
timespec_get. */
|
||||
#ifndef TIME_UTC
|
||||
#define TIME_UTC 1
|
||||
#define _TTHREAD_EMULATE_TIMESPEC_GET_
|
||||
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
struct _tthread_timespec {
|
||||
time_t tv_sec;
|
||||
long tv_nsec;
|
||||
};
|
||||
#define timespec _tthread_timespec
|
||||
#endif
|
||||
|
||||
int _tthread_timespec_get(struct timespec *ts, int base);
|
||||
#define timespec_get _tthread_timespec_get
|
||||
#endif
|
||||
|
||||
/** TinyCThread version (major number). */
|
||||
#define TINYCTHREAD_VERSION_MAJOR 1
|
||||
/** TinyCThread version (minor number). */
|
||||
#define TINYCTHREAD_VERSION_MINOR 2
|
||||
/** TinyCThread version (full version). */
|
||||
#define TINYCTHREAD_VERSION (TINYCTHREAD_VERSION_MAJOR * 100 + TINYCTHREAD_VERSION_MINOR)
|
||||
|
||||
/**
|
||||
* @def _Thread_local
|
||||
* Thread local storage keyword.
|
||||
* A variable that is declared with the @c _Thread_local keyword makes the
|
||||
* value of the variable local to each thread (known as thread-local storage,
|
||||
* or TLS). Example usage:
|
||||
* @code
|
||||
* // This variable is local to each thread.
|
||||
* _Thread_local int variable;
|
||||
* @endcode
|
||||
* @note The @c _Thread_local keyword is a macro that maps to the corresponding
|
||||
* compiler directive (e.g. @c __declspec(thread)).
|
||||
* @note This directive is currently not supported on Mac OS X (it will give
|
||||
* a compiler error), since compile-time TLS is not supported in the Mac OS X
|
||||
* executable format. Also, some older versions of MinGW (before GCC 4.x) do
|
||||
* not support this directive, nor does the Tiny C Compiler.
|
||||
* @hideinitializer
|
||||
*/
|
||||
|
||||
#if !(defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201102L)) && !defined(_Thread_local)
|
||||
#if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__SUNPRO_CC) || defined(__IBMCPP__)
|
||||
#define _Thread_local __thread
|
||||
#else
|
||||
#define _Thread_local __declspec(thread)
|
||||
#endif
|
||||
#elif defined(__GNUC__) && defined(__GNUC_MINOR__) && (((__GNUC__ << 8) | __GNUC_MINOR__) < ((4 << 8) | 9))
|
||||
#define _Thread_local __thread
|
||||
#endif
|
||||
|
||||
/* Macros */
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
#define TSS_DTOR_ITERATIONS (4)
|
||||
#else
|
||||
#define TSS_DTOR_ITERATIONS PTHREAD_DESTRUCTOR_ITERATIONS
|
||||
#endif
|
||||
|
||||
/* Function return values */
|
||||
#define thrd_error 0 /**< The requested operation failed */
|
||||
#define thrd_success 1 /**< The requested operation succeeded */
|
||||
#define thrd_timedout 2 /**< The time specified in the call was reached without acquiring the requested resource */
|
||||
#define thrd_busy 3 /**< The requested operation failed because a tesource requested by a test and return function is already in use */
|
||||
#define thrd_nomem 4 /**< The requested operation failed because it was unable to allocate memory */
|
||||
|
||||
/* Mutex types */
|
||||
#define mtx_plain 0
|
||||
#define mtx_timed 1
|
||||
#define mtx_recursive 2
|
||||
|
||||
/* Mutex */
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
typedef struct {
|
||||
union {
|
||||
CRITICAL_SECTION cs; /* Critical section handle (used for non-timed mutexes) */
|
||||
HANDLE mut; /* Mutex handle (used for timed mutex) */
|
||||
} mHandle; /* Mutex handle */
|
||||
int mAlreadyLocked; /* TRUE if the mutex is already locked */
|
||||
int mRecursive; /* TRUE if the mutex is recursive */
|
||||
int mTimed; /* TRUE if the mutex is timed */
|
||||
} mtx_t;
|
||||
#else
|
||||
typedef pthread_mutex_t mtx_t;
|
||||
#endif
|
||||
|
||||
/** Create a mutex object.
|
||||
* @param mtx A mutex object.
|
||||
* @param type Bit-mask that must have one of the following six values:
|
||||
* @li @c mtx_plain for a simple non-recursive mutex
|
||||
* @li @c mtx_timed for a non-recursive mutex that supports timeout
|
||||
* @li @c mtx_plain | @c mtx_recursive (same as @c mtx_plain, but recursive)
|
||||
* @li @c mtx_timed | @c mtx_recursive (same as @c mtx_timed, but recursive)
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
*/
|
||||
int mtx_init(mtx_t *mtx, int type);
|
||||
|
||||
/** Release any resources used by the given mutex.
|
||||
* @param mtx A mutex object.
|
||||
*/
|
||||
void mtx_destroy(mtx_t *mtx);
|
||||
|
||||
/** Lock the given mutex.
|
||||
* Blocks until the given mutex can be locked. If the mutex is non-recursive, and
|
||||
* the calling thread already has a lock on the mutex, this call will block
|
||||
* forever.
|
||||
* @param mtx A mutex object.
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
*/
|
||||
int mtx_lock(mtx_t *mtx);
|
||||
|
||||
/** Lock the given mutex, or block until a specific point in time.
|
||||
* Blocks until either the given mutex can be locked, or the specified TIME_UTC
|
||||
* based time.
|
||||
* @param mtx A mutex object.
|
||||
* @param ts A UTC based calendar time
|
||||
* @return @ref The mtx_timedlock function returns thrd_success on success, or
|
||||
* thrd_timedout if the time specified was reached without acquiring the
|
||||
* requested resource, or thrd_error if the request could not be honored.
|
||||
*/
|
||||
int mtx_timedlock(mtx_t *mtx, const struct timespec *ts);
|
||||
|
||||
/** Try to lock the given mutex.
|
||||
* The specified mutex shall support either test and return or timeout. If the
|
||||
* mutex is already locked, the function returns without blocking.
|
||||
* @param mtx A mutex object.
|
||||
* @return @ref thrd_success on success, or @ref thrd_busy if the resource
|
||||
* requested is already in use, or @ref thrd_error if the request could not be
|
||||
* honored.
|
||||
*/
|
||||
int mtx_trylock(mtx_t *mtx);
|
||||
|
||||
/** Unlock the given mutex.
|
||||
* @param mtx A mutex object.
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
*/
|
||||
int mtx_unlock(mtx_t *mtx);
|
||||
|
||||
/* Condition variable */
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
typedef struct {
|
||||
HANDLE mEvents[2]; /* Signal and broadcast event HANDLEs. */
|
||||
unsigned int mWaitersCount; /* Count of the number of waiters. */
|
||||
CRITICAL_SECTION mWaitersCountLock; /* Serialize access to mWaitersCount. */
|
||||
} cnd_t;
|
||||
#else
|
||||
typedef pthread_cond_t cnd_t;
|
||||
#endif
|
||||
|
||||
/** Create a condition variable object.
|
||||
* @param cond A condition variable object.
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
*/
|
||||
int cnd_init(cnd_t *cond);
|
||||
|
||||
/** Release any resources used by the given condition variable.
|
||||
* @param cond A condition variable object.
|
||||
*/
|
||||
void cnd_destroy(cnd_t *cond);
|
||||
|
||||
/** Signal a condition variable.
|
||||
* Unblocks one of the threads that are blocked on the given condition variable
|
||||
* at the time of the call. If no threads are blocked on the condition variable
|
||||
* at the time of the call, the function does nothing and return success.
|
||||
* @param cond A condition variable object.
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
*/
|
||||
int cnd_signal(cnd_t *cond);
|
||||
|
||||
/** Broadcast a condition variable.
|
||||
* Unblocks all of the threads that are blocked on the given condition variable
|
||||
* at the time of the call. If no threads are blocked on the condition variable
|
||||
* at the time of the call, the function does nothing and return success.
|
||||
* @param cond A condition variable object.
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
*/
|
||||
int cnd_broadcast(cnd_t *cond);
|
||||
|
||||
/** Wait for a condition variable to become signaled.
|
||||
* The function atomically unlocks the given mutex and endeavors to block until
|
||||
* the given condition variable is signaled by a call to cnd_signal or to
|
||||
* cnd_broadcast. When the calling thread becomes unblocked it locks the mutex
|
||||
* before it returns.
|
||||
* @param cond A condition variable object.
|
||||
* @param mtx A mutex object.
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
*/
|
||||
int cnd_wait(cnd_t *cond, mtx_t *mtx);
|
||||
|
||||
/** Wait for a condition variable to become signaled.
|
||||
* The function atomically unlocks the given mutex and endeavors to block until
|
||||
* the given condition variable is signaled by a call to cnd_signal or to
|
||||
* cnd_broadcast, or until after the specified time. When the calling thread
|
||||
* becomes unblocked it locks the mutex before it returns.
|
||||
* @param cond A condition variable object.
|
||||
* @param mtx A mutex object.
|
||||
* @param xt A point in time at which the request will time out (absolute time).
|
||||
* @return @ref thrd_success upon success, or @ref thrd_timeout if the time
|
||||
* specified in the call was reached without acquiring the requested resource, or
|
||||
* @ref thrd_error if the request could not be honored.
|
||||
*/
|
||||
int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts);
|
||||
|
||||
/* Thread */
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
typedef HANDLE thrd_t;
|
||||
#else
|
||||
typedef pthread_t thrd_t;
|
||||
#endif
|
||||
|
||||
/** Thread start function.
|
||||
* Any thread that is started with the @ref thrd_create() function must be
|
||||
* started through a function of this type.
|
||||
* @param arg The thread argument (the @c arg argument of the corresponding
|
||||
* @ref thrd_create() call).
|
||||
* @return The thread return value, which can be obtained by another thread
|
||||
* by using the @ref thrd_join() function.
|
||||
*/
|
||||
typedef int (*thrd_start_t)(void *arg);
|
||||
|
||||
/** Create a new thread.
|
||||
* @param thr Identifier of the newly created thread.
|
||||
* @param func A function pointer to the function that will be executed in
|
||||
* the new thread.
|
||||
* @param arg An argument to the thread function.
|
||||
* @return @ref thrd_success on success, or @ref thrd_nomem if no memory could
|
||||
* be allocated for the thread requested, or @ref thrd_error if the request
|
||||
* could not be honored.
|
||||
* @note A thread’s identifier may be reused for a different thread once the
|
||||
* original thread has exited and either been detached or joined to another
|
||||
* thread.
|
||||
*/
|
||||
int thrd_create(thrd_t *thr, thrd_start_t func, void *arg);
|
||||
|
||||
/** Identify the calling thread.
|
||||
* @return The identifier of the calling thread.
|
||||
*/
|
||||
thrd_t thrd_current(void);
|
||||
|
||||
/** Dispose of any resources allocated to the thread when that thread exits.
|
||||
* @return thrd_success, or thrd_error on error
|
||||
*/
|
||||
int thrd_detach(thrd_t thr);
|
||||
|
||||
/** Compare two thread identifiers.
|
||||
* The function determines if two thread identifiers refer to the same thread.
|
||||
* @return Zero if the two thread identifiers refer to different threads.
|
||||
* Otherwise a nonzero value is returned.
|
||||
*/
|
||||
int thrd_equal(thrd_t thr0, thrd_t thr1);
|
||||
|
||||
/** Terminate execution of the calling thread.
|
||||
* @param res Result code of the calling thread.
|
||||
*/
|
||||
TTHREAD_NORETURN void thrd_exit(int res);
|
||||
|
||||
/** Wait for a thread to terminate.
|
||||
* The function joins the given thread with the current thread by blocking
|
||||
* until the other thread has terminated.
|
||||
* @param thr The thread to join with.
|
||||
* @param res If this pointer is not NULL, the function will store the result
|
||||
* code of the given thread in the integer pointed to by @c res.
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
*/
|
||||
int thrd_join(thrd_t thr, int *res);
|
||||
|
||||
/** Put the calling thread to sleep.
|
||||
* Suspend execution of the calling thread.
|
||||
* @param duration Interval to sleep for
|
||||
* @param remaining If non-NULL, this parameter will hold the remaining
|
||||
* time until time_point upon return. This will
|
||||
* typically be zero, but if the thread was woken up
|
||||
* by a signal that is not ignored before duration was
|
||||
* reached @c remaining will hold a positive time.
|
||||
* @return 0 (zero) on successful sleep, -1 if an interrupt occurred,
|
||||
* or a negative value if the operation fails.
|
||||
*/
|
||||
int thrd_sleep(const struct timespec *duration, struct timespec *remaining);
|
||||
|
||||
/** Yield execution to another thread.
|
||||
* Permit other threads to run, even if the current thread would ordinarily
|
||||
* continue to run.
|
||||
*/
|
||||
void thrd_yield(void);
|
||||
|
||||
/* Thread local storage */
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
typedef DWORD tss_t;
|
||||
#else
|
||||
typedef pthread_key_t tss_t;
|
||||
#endif
|
||||
|
||||
/** Destructor function for a thread-specific storage.
|
||||
* @param val The value of the destructed thread-specific storage.
|
||||
*/
|
||||
typedef void (*tss_dtor_t)(void *val);
|
||||
|
||||
/** Create a thread-specific storage.
|
||||
* @param key The unique key identifier that will be set if the function is
|
||||
* successful.
|
||||
* @param dtor Destructor function. This can be NULL.
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
* @note On Windows, the @c dtor will definitely be called when
|
||||
* appropriate for threads created with @ref thrd_create. It will be
|
||||
* called for other threads in most cases, the possible exception being
|
||||
* for DLLs loaded with LoadLibraryEx. In order to be certain, you
|
||||
* should use @ref thrd_create whenever possible.
|
||||
*/
|
||||
int tss_create(tss_t *key, tss_dtor_t dtor);
|
||||
|
||||
/** Delete a thread-specific storage.
|
||||
* The function releases any resources used by the given thread-specific
|
||||
* storage.
|
||||
* @param key The key that shall be deleted.
|
||||
*/
|
||||
void tss_delete(tss_t key);
|
||||
|
||||
/** Get the value for a thread-specific storage.
|
||||
* @param key The thread-specific storage identifier.
|
||||
* @return The value for the current thread held in the given thread-specific
|
||||
* storage.
|
||||
*/
|
||||
void *tss_get(tss_t key);
|
||||
|
||||
/** Set the value for a thread-specific storage.
|
||||
* @param key The thread-specific storage identifier.
|
||||
* @param val The value of the thread-specific storage to set for the current
|
||||
* thread.
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
*/
|
||||
int tss_set(tss_t key, void *val);
|
||||
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
typedef struct {
|
||||
LONG volatile status;
|
||||
CRITICAL_SECTION lock;
|
||||
} once_flag;
|
||||
#define ONCE_FLAG_INIT {0,}
|
||||
#else
|
||||
#define once_flag pthread_once_t
|
||||
#define ONCE_FLAG_INIT PTHREAD_ONCE_INIT
|
||||
#endif
|
||||
|
||||
/** Invoke a callback exactly once
|
||||
* @param flag Flag used to ensure the callback is invoked exactly
|
||||
* once.
|
||||
* @param func Callback to invoke.
|
||||
*/
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
void call_once(once_flag *flag, void (*func)(void));
|
||||
#else
|
||||
#define call_once(flag,func) pthread_once(flag,func)
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* _TINYTHREAD_H_ */
|
||||
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Natanael Arndt, 2011: removed collate.h dependencies
|
||||
* (my changes are trivial)
|
||||
*
|
||||
* Copyright (c) 1989, 1993
|
||||
* The Regents of the University of California. All rights reserved.
|
||||
*
|
||||
* This code is derived from software contributed to Berkeley by
|
||||
* Guido van Rossum.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 4. Neither the name of the University nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
|
||||
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
||||
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
||||
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
* SUCH DAMAGE.
|
||||
*/
|
||||
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 Anders Kalør
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,7 @@
|
||||
Copyright (c) 2012 William Woodall, John Harrison
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,25 @@
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
Copyright (c) 2012 Marcus Geelnard
|
||||
2013-2016 Evan Nemerson
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
@@ -0,0 +1,908 @@
|
||||
/*
|
||||
* Natanael Arndt, 2011: removed collate.h dependencies
|
||||
* (my changes are trivial)
|
||||
*
|
||||
* Copyright (c) 1989, 1993
|
||||
* The Regents of the University of California. All rights reserved.
|
||||
*
|
||||
* This code is derived from software contributed to Berkeley by
|
||||
* Guido van Rossum.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 4. Neither the name of the University nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
|
||||
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
||||
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
||||
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
* SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#if defined(LIBC_SCCS) && !defined(lint)
|
||||
static char sccsid[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93";
|
||||
#endif /* LIBC_SCCS and not lint */
|
||||
#include <sys/cdefs.h>
|
||||
__FBSDID("$FreeBSD$");
|
||||
|
||||
/*
|
||||
* glob(3) -- a superset of the one defined in POSIX 1003.2.
|
||||
*
|
||||
* The [!...] convention to negate a range is supported (SysV, Posix, ksh).
|
||||
*
|
||||
* Optional extra services, controlled by flags not defined by POSIX:
|
||||
*
|
||||
* GLOB_QUOTE:
|
||||
* Escaping convention: \ inhibits any special meaning the following
|
||||
* character might have (except \ at end of string is retained).
|
||||
* GLOB_MAGCHAR:
|
||||
* Set in gl_flags if pattern contained a globbing character.
|
||||
* GLOB_NOMAGIC:
|
||||
* Same as GLOB_NOCHECK, but it will only append pattern if it did
|
||||
* not contain any magic characters. [Used in csh style globbing]
|
||||
* GLOB_ALTDIRFUNC:
|
||||
* Use alternately specified directory access functions.
|
||||
* GLOB_TILDE:
|
||||
* expand ~user/foo to the /home/dir/of/user/foo
|
||||
* GLOB_BRACE:
|
||||
* expand {1,2}{a,b} to 1a 1b 2a 2b
|
||||
* gl_matchc:
|
||||
* Number of matches in the current invocation of glob.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Some notes on multibyte character support:
|
||||
* 1. Patterns with illegal byte sequences match nothing - even if
|
||||
* GLOB_NOCHECK is specified.
|
||||
* 2. Illegal byte sequences in filenames are handled by treating them as
|
||||
* single-byte characters with a value of the first byte of the sequence
|
||||
* cast to wchar_t.
|
||||
* 3. State-dependent encodings are not currently supported.
|
||||
*/
|
||||
|
||||
#include <sys/param.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <ctype.h>
|
||||
#include <dirent.h>
|
||||
#include <errno.h>
|
||||
#include "cglob.h"
|
||||
#include <limits.h>
|
||||
#include <pwd.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <wchar.h>
|
||||
|
||||
#define DOLLAR '$'
|
||||
#define DOT '.'
|
||||
#define EOS '\0'
|
||||
#define LBRACKET '['
|
||||
#define NOT '!'
|
||||
#define QUESTION '?'
|
||||
#define QUOTE '\\'
|
||||
#define RANGE '-'
|
||||
#define RBRACKET ']'
|
||||
#define SEP '/'
|
||||
#define STAR '*'
|
||||
#define TILDE '~'
|
||||
#define UNDERSCORE '_'
|
||||
#define LBRACE '{'
|
||||
#define RBRACE '}'
|
||||
#define SLASH '/'
|
||||
#define COMMA ','
|
||||
|
||||
#ifndef DEBUG
|
||||
|
||||
#define M_QUOTE 0x8000000000ULL
|
||||
#define M_PROTECT 0x4000000000ULL
|
||||
#define M_MASK 0xffffffffffULL
|
||||
#define M_CHAR 0x00ffffffffULL
|
||||
|
||||
typedef uint_fast64_t Char;
|
||||
|
||||
#else
|
||||
|
||||
#define M_QUOTE 0x80
|
||||
#define M_PROTECT 0x40
|
||||
#define M_MASK 0xff
|
||||
#define M_CHAR 0x7f
|
||||
|
||||
typedef char Char;
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
#define CHAR(c) ((Char)((c)&M_CHAR))
|
||||
#define META(c) ((Char)((c)|M_QUOTE))
|
||||
#define M_ALL META('*')
|
||||
#define M_END META(']')
|
||||
#define M_NOT META('!')
|
||||
#define M_ONE META('?')
|
||||
#define M_RNG META('-')
|
||||
#define M_SET META('[')
|
||||
#define ismeta(c) (((c)&M_QUOTE) != 0)
|
||||
|
||||
|
||||
static int compare(const void *, const void *);
|
||||
static int g_Ctoc(const Char *, char *, size_t);
|
||||
static int g_lstat(Char *, struct stat *, cglob_t *);
|
||||
static DIR *g_opendir(Char *, cglob_t *);
|
||||
static const Char *g_strchr(const Char *, wchar_t);
|
||||
#ifdef notdef
|
||||
static Char *g_strcat(Char *, const Char *);
|
||||
#endif
|
||||
static int g_stat(Char *, struct stat *, cglob_t *);
|
||||
static int glob0(const Char *, cglob_t *, size_t *);
|
||||
static int glob1(Char *, cglob_t *, size_t *);
|
||||
static int glob2(Char *, Char *, Char *, Char *, cglob_t *, size_t *);
|
||||
static int glob3(Char *, Char *, Char *, Char *, Char *, cglob_t *, size_t *);
|
||||
static int globextend(const Char *, cglob_t *, size_t *);
|
||||
static const Char *
|
||||
globtilde(const Char *, Char *, size_t, cglob_t *);
|
||||
static int globexp1(const Char *, cglob_t *, size_t *);
|
||||
static int globexp2(const Char *, const Char *, cglob_t *, int *, size_t *);
|
||||
static int match(Char *, Char *, Char *);
|
||||
#ifdef DEBUG
|
||||
static void qprintf(const char *, Char *);
|
||||
#endif
|
||||
|
||||
int
|
||||
cglob(const char *pattern, int flags, int (*errfunc)(const char *, int), cglob_t *pglob)
|
||||
{
|
||||
const char *patnext;
|
||||
size_t limit;
|
||||
Char *bufnext, *bufend, patbuf[MAXPATHLEN], prot;
|
||||
mbstate_t mbs;
|
||||
wchar_t wc;
|
||||
size_t clen;
|
||||
|
||||
patnext = pattern;
|
||||
if (!(flags & GLOB_APPEND)) {
|
||||
pglob->gl_pathc = 0;
|
||||
pglob->gl_pathv = NULL;
|
||||
if (!(flags & GLOB_DOOFFS))
|
||||
pglob->gl_offs = 0;
|
||||
}
|
||||
|
||||
if (flags & GLOB_LIMIT) {
|
||||
limit = pglob->gl_matchc;
|
||||
if (limit == 0)
|
||||
limit = ARG_MAX;
|
||||
} else
|
||||
limit = 0;
|
||||
|
||||
pglob->gl_flags = flags & ~GLOB_MAGCHAR;
|
||||
pglob->gl_errfunc = errfunc;
|
||||
pglob->gl_matchc = 0;
|
||||
|
||||
bufnext = patbuf;
|
||||
bufend = bufnext + MAXPATHLEN - 1;
|
||||
if (flags & GLOB_NOESCAPE) {
|
||||
memset(&mbs, 0, sizeof(mbs));
|
||||
while (bufend - bufnext >= MB_CUR_MAX) {
|
||||
clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
|
||||
if (clen == (size_t)-1 || clen == (size_t)-2)
|
||||
return (GLOB_NOMATCH);
|
||||
else if (clen == 0)
|
||||
break;
|
||||
*bufnext++ = wc;
|
||||
patnext += clen;
|
||||
}
|
||||
} else {
|
||||
/* Protect the quoted characters. */
|
||||
memset(&mbs, 0, sizeof(mbs));
|
||||
while (bufend - bufnext >= MB_CUR_MAX) {
|
||||
if (*patnext == QUOTE) {
|
||||
if (*++patnext == EOS) {
|
||||
*bufnext++ = QUOTE | M_PROTECT;
|
||||
continue;
|
||||
}
|
||||
prot = M_PROTECT;
|
||||
} else
|
||||
prot = 0;
|
||||
clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
|
||||
if (clen == (size_t)-1 || clen == (size_t)-2)
|
||||
return (GLOB_NOMATCH);
|
||||
else if (clen == 0)
|
||||
break;
|
||||
*bufnext++ = wc | prot;
|
||||
patnext += clen;
|
||||
}
|
||||
}
|
||||
*bufnext = EOS;
|
||||
|
||||
if (flags & GLOB_BRACE)
|
||||
return globexp1(patbuf, pglob, &limit);
|
||||
else
|
||||
return glob0(patbuf, pglob, &limit);
|
||||
}
|
||||
|
||||
/*
|
||||
* Expand recursively a glob {} pattern. When there is no more expansion
|
||||
* invoke the standard globbing routine to glob the rest of the magic
|
||||
* characters
|
||||
*/
|
||||
static int
|
||||
globexp1(const Char *pattern, cglob_t *pglob, size_t *limit)
|
||||
{
|
||||
const Char* ptr = pattern;
|
||||
int rv;
|
||||
|
||||
/* Protect a single {}, for find(1), like csh */
|
||||
if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
|
||||
return glob0(pattern, pglob, limit);
|
||||
|
||||
while ((ptr = g_strchr(ptr, LBRACE)) != NULL)
|
||||
if (!globexp2(ptr, pattern, pglob, &rv, limit))
|
||||
return rv;
|
||||
|
||||
return glob0(pattern, pglob, limit);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Recursive brace globbing helper. Tries to expand a single brace.
|
||||
* If it succeeds then it invokes globexp1 with the new pattern.
|
||||
* If it fails then it tries to glob the rest of the pattern and returns.
|
||||
*/
|
||||
static int
|
||||
globexp2(const Char *ptr, const Char *pattern, cglob_t *pglob, int *rv, size_t *limit)
|
||||
{
|
||||
int i;
|
||||
Char *lm, *ls;
|
||||
const Char *pe, *pm, *pm1, *pl;
|
||||
Char patbuf[MAXPATHLEN];
|
||||
|
||||
/* copy part up to the brace */
|
||||
for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
|
||||
continue;
|
||||
*lm = EOS;
|
||||
ls = lm;
|
||||
|
||||
/* Find the balanced brace */
|
||||
for (i = 0, pe = ++ptr; *pe; pe++)
|
||||
if (*pe == LBRACKET) {
|
||||
/* Ignore everything between [] */
|
||||
for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
|
||||
continue;
|
||||
if (*pe == EOS) {
|
||||
/*
|
||||
* We could not find a matching RBRACKET.
|
||||
* Ignore and just look for RBRACE
|
||||
*/
|
||||
pe = pm;
|
||||
}
|
||||
}
|
||||
else if (*pe == LBRACE)
|
||||
i++;
|
||||
else if (*pe == RBRACE) {
|
||||
if (i == 0)
|
||||
break;
|
||||
i--;
|
||||
}
|
||||
|
||||
/* Non matching braces; just glob the pattern */
|
||||
if (i != 0 || *pe == EOS) {
|
||||
*rv = glob0(patbuf, pglob, limit);
|
||||
return 0;
|
||||
}
|
||||
|
||||
for (i = 0, pl = pm = ptr; pm <= pe; pm++)
|
||||
switch (*pm) {
|
||||
case LBRACKET:
|
||||
/* Ignore everything between [] */
|
||||
for (pm1 = pm++; *pm != RBRACKET && *pm != EOS; pm++)
|
||||
continue;
|
||||
if (*pm == EOS) {
|
||||
/*
|
||||
* We could not find a matching RBRACKET.
|
||||
* Ignore and just look for RBRACE
|
||||
*/
|
||||
pm = pm1;
|
||||
}
|
||||
break;
|
||||
|
||||
case LBRACE:
|
||||
i++;
|
||||
break;
|
||||
|
||||
case RBRACE:
|
||||
if (i) {
|
||||
i--;
|
||||
break;
|
||||
}
|
||||
/* FALLTHROUGH */
|
||||
case COMMA:
|
||||
if (i && *pm == COMMA)
|
||||
break;
|
||||
else {
|
||||
/* Append the current string */
|
||||
for (lm = ls; (pl < pm); *lm++ = *pl++)
|
||||
continue;
|
||||
/*
|
||||
* Append the rest of the pattern after the
|
||||
* closing brace
|
||||
*/
|
||||
for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
|
||||
continue;
|
||||
|
||||
/* Expand the current pattern */
|
||||
#ifdef DEBUG
|
||||
qprintf("globexp2:", patbuf);
|
||||
#endif
|
||||
*rv = globexp1(patbuf, pglob, limit);
|
||||
|
||||
/* move after the comma, to the next string */
|
||||
pl = pm + 1;
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
*rv = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* expand tilde from the passwd file.
|
||||
*/
|
||||
static const Char *
|
||||
globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, cglob_t *pglob)
|
||||
{
|
||||
struct passwd *pwd;
|
||||
char *h;
|
||||
const Char *p;
|
||||
Char *b, *eb;
|
||||
|
||||
if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
|
||||
return pattern;
|
||||
|
||||
/*
|
||||
* Copy up to the end of the string or /
|
||||
*/
|
||||
eb = &patbuf[patbuf_len - 1];
|
||||
for (p = pattern + 1, h = (char *) patbuf;
|
||||
h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
|
||||
continue;
|
||||
|
||||
*h = EOS;
|
||||
|
||||
if (((char *) patbuf)[0] == EOS) {
|
||||
/*
|
||||
* handle a plain ~ or ~/ by expanding $HOME first (iff
|
||||
* we're not running setuid or setgid) and then trying
|
||||
* the password file
|
||||
*/
|
||||
/*if (issetugid() != 0 ||
|
||||
(h = getenv("HOME")) == NULL) {
|
||||
if (((h = getlogin()) != NULL &&
|
||||
(pwd = getpwnam(h)) != NULL) ||
|
||||
(pwd = getpwuid(getuid())) != NULL)
|
||||
h = pwd->pw_dir;
|
||||
else
|
||||
return pattern;
|
||||
}*/
|
||||
}
|
||||
else {
|
||||
/*
|
||||
* Expand a ~user
|
||||
*/
|
||||
if ((pwd = getpwnam((char*) patbuf)) == NULL)
|
||||
return pattern;
|
||||
else
|
||||
h = pwd->pw_dir;
|
||||
}
|
||||
|
||||
/* Copy the home directory */
|
||||
for (b = patbuf; b < eb && *h; *b++ = *h++)
|
||||
continue;
|
||||
|
||||
/* Append the rest of the pattern */
|
||||
while (b < eb && (*b++ = *p++) != EOS)
|
||||
continue;
|
||||
*b = EOS;
|
||||
|
||||
return patbuf;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* The main glob() routine: compiles the pattern (optionally processing
|
||||
* quotes), calls glob1() to do the real pattern matching, and finally
|
||||
* sorts the list (unless unsorted operation is requested). Returns 0
|
||||
* if things went well, nonzero if errors occurred.
|
||||
*/
|
||||
static int
|
||||
glob0(const Char *pattern, cglob_t *pglob, size_t *limit)
|
||||
{
|
||||
const Char *qpatnext;
|
||||
int err;
|
||||
size_t oldpathc;
|
||||
Char *bufnext, c, patbuf[MAXPATHLEN];
|
||||
|
||||
qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
|
||||
oldpathc = pglob->gl_pathc;
|
||||
bufnext = patbuf;
|
||||
|
||||
/* We don't need to check for buffer overflow any more. */
|
||||
while ((c = *qpatnext++) != EOS) {
|
||||
switch (c) {
|
||||
case LBRACKET:
|
||||
c = *qpatnext;
|
||||
if (c == NOT)
|
||||
++qpatnext;
|
||||
if (*qpatnext == EOS ||
|
||||
g_strchr(qpatnext+1, RBRACKET) == NULL) {
|
||||
*bufnext++ = LBRACKET;
|
||||
if (c == NOT)
|
||||
--qpatnext;
|
||||
break;
|
||||
}
|
||||
*bufnext++ = M_SET;
|
||||
if (c == NOT)
|
||||
*bufnext++ = M_NOT;
|
||||
c = *qpatnext++;
|
||||
do {
|
||||
*bufnext++ = CHAR(c);
|
||||
if (*qpatnext == RANGE &&
|
||||
(c = qpatnext[1]) != RBRACKET) {
|
||||
*bufnext++ = M_RNG;
|
||||
*bufnext++ = CHAR(c);
|
||||
qpatnext += 2;
|
||||
}
|
||||
} while ((c = *qpatnext++) != RBRACKET);
|
||||
pglob->gl_flags |= GLOB_MAGCHAR;
|
||||
*bufnext++ = M_END;
|
||||
break;
|
||||
case QUESTION:
|
||||
pglob->gl_flags |= GLOB_MAGCHAR;
|
||||
*bufnext++ = M_ONE;
|
||||
break;
|
||||
case STAR:
|
||||
pglob->gl_flags |= GLOB_MAGCHAR;
|
||||
/* collapse adjacent stars to one,
|
||||
* to avoid exponential behavior
|
||||
*/
|
||||
if (bufnext == patbuf || bufnext[-1] != M_ALL)
|
||||
*bufnext++ = M_ALL;
|
||||
break;
|
||||
default:
|
||||
*bufnext++ = CHAR(c);
|
||||
break;
|
||||
}
|
||||
}
|
||||
*bufnext = EOS;
|
||||
#ifdef DEBUG
|
||||
qprintf("glob0:", patbuf);
|
||||
#endif
|
||||
|
||||
if ((err = glob1(patbuf, pglob, limit)) != 0)
|
||||
return(err);
|
||||
|
||||
/*
|
||||
* If there was no match we are going to append the pattern
|
||||
* if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
|
||||
* and the pattern did not contain any magic characters
|
||||
* GLOB_NOMAGIC is there just for compatibility with csh.
|
||||
*/
|
||||
if (pglob->gl_pathc == oldpathc) {
|
||||
if (((pglob->gl_flags & GLOB_NOCHECK) ||
|
||||
((pglob->gl_flags & GLOB_NOMAGIC) &&
|
||||
!(pglob->gl_flags & GLOB_MAGCHAR))))
|
||||
return(globextend(pattern, pglob, limit));
|
||||
else
|
||||
return(GLOB_NOMATCH);
|
||||
}
|
||||
if (!(pglob->gl_flags & GLOB_NOSORT))
|
||||
qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
|
||||
pglob->gl_pathc - oldpathc, sizeof(char *), compare);
|
||||
return(0);
|
||||
}
|
||||
|
||||
static int
|
||||
compare(const void *p, const void *q)
|
||||
{
|
||||
return(strcmp(*(char **)p, *(char **)q));
|
||||
}
|
||||
|
||||
static int
|
||||
glob1(Char *pattern, cglob_t *pglob, size_t *limit)
|
||||
{
|
||||
Char pathbuf[MAXPATHLEN];
|
||||
|
||||
/* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
|
||||
if (*pattern == EOS)
|
||||
return(0);
|
||||
return(glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1,
|
||||
pattern, pglob, limit));
|
||||
}
|
||||
|
||||
/*
|
||||
* The functions glob2 and glob3 are mutually recursive; there is one level
|
||||
* of recursion for each segment in the pattern that contains one or more
|
||||
* meta characters.
|
||||
*/
|
||||
static int
|
||||
glob2(Char *pathbuf, Char *pathend, Char *pathend_last, Char *pattern,
|
||||
cglob_t *pglob, size_t *limit)
|
||||
{
|
||||
struct stat sb;
|
||||
Char *p, *q;
|
||||
int anymeta;
|
||||
|
||||
/*
|
||||
* Loop over pattern segments until end of pattern or until
|
||||
* segment with meta character found.
|
||||
*/
|
||||
for (anymeta = 0;;) {
|
||||
if (*pattern == EOS) { /* End of pattern? */
|
||||
*pathend = EOS;
|
||||
if (g_lstat(pathbuf, &sb, pglob))
|
||||
return(0);
|
||||
|
||||
if (((pglob->gl_flags & GLOB_MARK) &&
|
||||
pathend[-1] != SEP) && (S_ISDIR(sb.st_mode)
|
||||
|| (S_ISLNK(sb.st_mode) &&
|
||||
(g_stat(pathbuf, &sb, pglob) == 0) &&
|
||||
S_ISDIR(sb.st_mode)))) {
|
||||
if (pathend + 1 > pathend_last)
|
||||
return (GLOB_ABORTED);
|
||||
*pathend++ = SEP;
|
||||
*pathend = EOS;
|
||||
}
|
||||
++pglob->gl_matchc;
|
||||
return(globextend(pathbuf, pglob, limit));
|
||||
}
|
||||
|
||||
/* Find end of next segment, copy tentatively to pathend. */
|
||||
q = pathend;
|
||||
p = pattern;
|
||||
while (*p != EOS && *p != SEP) {
|
||||
if (ismeta(*p))
|
||||
anymeta = 1;
|
||||
if (q + 1 > pathend_last)
|
||||
return (GLOB_ABORTED);
|
||||
*q++ = *p++;
|
||||
}
|
||||
|
||||
if (!anymeta) { /* No expansion, do next segment. */
|
||||
pathend = q;
|
||||
pattern = p;
|
||||
while (*pattern == SEP) {
|
||||
if (pathend + 1 > pathend_last)
|
||||
return (GLOB_ABORTED);
|
||||
*pathend++ = *pattern++;
|
||||
}
|
||||
} else /* Need expansion, recurse. */
|
||||
return(glob3(pathbuf, pathend, pathend_last, pattern, p,
|
||||
pglob, limit));
|
||||
}
|
||||
/* NOTREACHED */
|
||||
}
|
||||
|
||||
static int
|
||||
glob3(Char *pathbuf, Char *pathend, Char *pathend_last,
|
||||
Char *pattern, Char *restpattern,
|
||||
cglob_t *pglob, size_t *limit)
|
||||
{
|
||||
struct dirent *dp;
|
||||
DIR *dirp;
|
||||
int err;
|
||||
char buf[MAXPATHLEN];
|
||||
|
||||
/*
|
||||
* The readdirfunc declaration can't be prototyped, because it is
|
||||
* assigned, below, to two functions which are prototyped in glob.h
|
||||
* and dirent.h as taking pointers to differently typed opaque
|
||||
* structures.
|
||||
*/
|
||||
struct dirent *(*readdirfunc)();
|
||||
|
||||
if (pathend > pathend_last)
|
||||
return (GLOB_ABORTED);
|
||||
*pathend = EOS;
|
||||
errno = 0;
|
||||
|
||||
if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
|
||||
/* TODO: don't call for ENOENT or ENOTDIR? */
|
||||
if (pglob->gl_errfunc) {
|
||||
if (g_Ctoc(pathbuf, buf, sizeof(buf)))
|
||||
return (GLOB_ABORTED);
|
||||
if (pglob->gl_errfunc(buf, errno) ||
|
||||
pglob->gl_flags & GLOB_ERR)
|
||||
return (GLOB_ABORTED);
|
||||
}
|
||||
return(0);
|
||||
}
|
||||
|
||||
err = 0;
|
||||
|
||||
/* Search directory for matching names. */
|
||||
if (pglob->gl_flags & GLOB_ALTDIRFUNC)
|
||||
readdirfunc = pglob->gl_readdir;
|
||||
else
|
||||
readdirfunc = readdir;
|
||||
while ((dp = (*readdirfunc)(dirp))) {
|
||||
char *sc;
|
||||
Char *dc;
|
||||
wchar_t wc;
|
||||
size_t clen;
|
||||
mbstate_t mbs;
|
||||
|
||||
/* Initial DOT must be matched literally. */
|
||||
if (dp->d_name[0] == DOT && *pattern != DOT)
|
||||
continue;
|
||||
memset(&mbs, 0, sizeof(mbs));
|
||||
dc = pathend;
|
||||
sc = dp->d_name;
|
||||
while (dc < pathend_last) {
|
||||
clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs);
|
||||
if (clen == (size_t)-1 || clen == (size_t)-2) {
|
||||
wc = *sc;
|
||||
clen = 1;
|
||||
memset(&mbs, 0, sizeof(mbs));
|
||||
}
|
||||
if ((*dc++ = wc) == EOS)
|
||||
break;
|
||||
sc += clen;
|
||||
}
|
||||
if (!match(pathend, pattern, restpattern)) {
|
||||
*pathend = EOS;
|
||||
continue;
|
||||
}
|
||||
err = glob2(pathbuf, --dc, pathend_last, restpattern,
|
||||
pglob, limit);
|
||||
if (err)
|
||||
break;
|
||||
}
|
||||
|
||||
if (pglob->gl_flags & GLOB_ALTDIRFUNC)
|
||||
(*pglob->gl_closedir)(dirp);
|
||||
else
|
||||
closedir(dirp);
|
||||
return(err);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Extend the gl_pathv member of a glob_t structure to accomodate a new item,
|
||||
* add the new item, and update gl_pathc.
|
||||
*
|
||||
* This assumes the BSD realloc, which only copies the block when its size
|
||||
* crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
|
||||
* behavior.
|
||||
*
|
||||
* Return 0 if new item added, error code if memory couldn't be allocated.
|
||||
*
|
||||
* Invariant of the glob_t structure:
|
||||
* Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
|
||||
* gl_pathv points to (gl_offs + gl_pathc + 1) items.
|
||||
*/
|
||||
static int
|
||||
globextend(const Char *path, cglob_t *pglob, size_t *limit)
|
||||
{
|
||||
char **pathv;
|
||||
size_t i, newsize, len;
|
||||
char *copy;
|
||||
const Char *p;
|
||||
|
||||
if (*limit && pglob->gl_pathc > *limit) {
|
||||
errno = 0;
|
||||
return (GLOB_NOSPACE);
|
||||
}
|
||||
|
||||
newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
|
||||
pathv = pglob->gl_pathv ?
|
||||
realloc((char *)pglob->gl_pathv, newsize) :
|
||||
malloc(newsize);
|
||||
if (pathv == NULL) {
|
||||
if (pglob->gl_pathv) {
|
||||
free(pglob->gl_pathv);
|
||||
pglob->gl_pathv = NULL;
|
||||
}
|
||||
return(GLOB_NOSPACE);
|
||||
}
|
||||
|
||||
if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
|
||||
/* first time around -- clear initial gl_offs items */
|
||||
pathv += pglob->gl_offs;
|
||||
for (i = pglob->gl_offs + 1; --i > 0; )
|
||||
*--pathv = NULL;
|
||||
}
|
||||
pglob->gl_pathv = pathv;
|
||||
|
||||
for (p = path; *p++;)
|
||||
continue;
|
||||
len = MB_CUR_MAX * (size_t)(p - path); /* XXX overallocation */
|
||||
if ((copy = malloc(len)) != NULL) {
|
||||
if (g_Ctoc(path, copy, len)) {
|
||||
free(copy);
|
||||
return (GLOB_NOSPACE);
|
||||
}
|
||||
pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
|
||||
}
|
||||
pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
|
||||
return(copy == NULL ? GLOB_NOSPACE : 0);
|
||||
}
|
||||
|
||||
/*
|
||||
* pattern matching function for filenames. Each occurrence of the *
|
||||
* pattern causes a recursion level.
|
||||
*/
|
||||
static int
|
||||
match(Char *name, Char *pat, Char *patend)
|
||||
{
|
||||
int ok, negate_range;
|
||||
Char c, k;
|
||||
|
||||
while (pat < patend) {
|
||||
c = *pat++;
|
||||
switch (c & M_MASK) {
|
||||
case M_ALL:
|
||||
if (pat == patend)
|
||||
return(1);
|
||||
do
|
||||
if (match(name, pat, patend))
|
||||
return(1);
|
||||
while (*name++ != EOS);
|
||||
return(0);
|
||||
case M_ONE:
|
||||
if (*name++ == EOS)
|
||||
return(0);
|
||||
break;
|
||||
case M_SET:
|
||||
ok = 0;
|
||||
if ((k = *name++) == EOS)
|
||||
return(0);
|
||||
if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
|
||||
++pat;
|
||||
while (((c = *pat++) & M_MASK) != M_END)
|
||||
if ((*pat & M_MASK) == M_RNG) {
|
||||
if (CHAR(c) <= CHAR(k) && CHAR(k) <= CHAR(pat[1])) ok = 1;
|
||||
pat += 2;
|
||||
} else if (c == k)
|
||||
ok = 1;
|
||||
if (ok == negate_range)
|
||||
return(0);
|
||||
break;
|
||||
default:
|
||||
if (*name++ != c)
|
||||
return(0);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return(*name == EOS);
|
||||
}
|
||||
|
||||
/* Free allocated data belonging to a glob_t structure. */
|
||||
void
|
||||
cglobfree(cglob_t *pglob)
|
||||
{
|
||||
size_t i;
|
||||
char **pp;
|
||||
|
||||
if (pglob->gl_pathv != NULL) {
|
||||
pp = pglob->gl_pathv + pglob->gl_offs;
|
||||
for (i = pglob->gl_pathc; i--; ++pp)
|
||||
if (*pp)
|
||||
free(*pp);
|
||||
free(pglob->gl_pathv);
|
||||
pglob->gl_pathv = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
static DIR *
|
||||
g_opendir(Char *str, cglob_t *pglob)
|
||||
{
|
||||
char buf[MAXPATHLEN];
|
||||
|
||||
if (!*str)
|
||||
strcpy(buf, ".");
|
||||
else {
|
||||
if (g_Ctoc(str, buf, sizeof(buf)))
|
||||
return (NULL);
|
||||
}
|
||||
|
||||
if (pglob->gl_flags & GLOB_ALTDIRFUNC)
|
||||
return((*pglob->gl_opendir)(buf));
|
||||
|
||||
return(opendir(buf));
|
||||
}
|
||||
|
||||
static int
|
||||
g_lstat(Char *fn, struct stat *sb, cglob_t *pglob)
|
||||
{
|
||||
char buf[MAXPATHLEN];
|
||||
|
||||
if (g_Ctoc(fn, buf, sizeof(buf))) {
|
||||
errno = ENAMETOOLONG;
|
||||
return (-1);
|
||||
}
|
||||
if (pglob->gl_flags & GLOB_ALTDIRFUNC)
|
||||
return((*pglob->gl_lstat)(buf, sb));
|
||||
return(lstat(buf, sb));
|
||||
}
|
||||
|
||||
static int
|
||||
g_stat(Char *fn, struct stat *sb, cglob_t *pglob)
|
||||
{
|
||||
char buf[MAXPATHLEN];
|
||||
|
||||
if (g_Ctoc(fn, buf, sizeof(buf))) {
|
||||
errno = ENAMETOOLONG;
|
||||
return (-1);
|
||||
}
|
||||
if (pglob->gl_flags & GLOB_ALTDIRFUNC)
|
||||
return((*pglob->gl_stat)(buf, sb));
|
||||
return(stat(buf, sb));
|
||||
}
|
||||
|
||||
static const Char *
|
||||
g_strchr(const Char *str, wchar_t ch)
|
||||
{
|
||||
|
||||
do {
|
||||
if (*str == ch)
|
||||
return (str);
|
||||
} while (*str++);
|
||||
return (NULL);
|
||||
}
|
||||
|
||||
static int
|
||||
g_Ctoc(const Char *str, char *buf, size_t len)
|
||||
{
|
||||
mbstate_t mbs;
|
||||
size_t clen;
|
||||
|
||||
memset(&mbs, 0, sizeof(mbs));
|
||||
while (len >= MB_CUR_MAX) {
|
||||
clen = wcrtomb(buf, *str, &mbs);
|
||||
if (clen == (size_t)-1)
|
||||
return (1);
|
||||
if (*str == L'\0')
|
||||
return (0);
|
||||
str++;
|
||||
buf += clen;
|
||||
len -= clen;
|
||||
}
|
||||
return (1);
|
||||
}
|
||||
|
||||
#ifdef DEBUG
|
||||
static void
|
||||
qprintf(const char *str, Char *s)
|
||||
{
|
||||
Char *p;
|
||||
|
||||
(void)printf("%s:\n", str);
|
||||
for (p = s; *p; p++)
|
||||
(void)printf("%c", CHAR(*p));
|
||||
(void)printf("\n");
|
||||
for (p = s; *p; p++)
|
||||
(void)printf("%c", *p & M_PROTECT ? '"' : ' ');
|
||||
(void)printf("\n");
|
||||
for (p = s; *p; p++)
|
||||
(void)printf("%c", ismeta(*p) ? '_' : ' ');
|
||||
(void)printf("\n");
|
||||
}
|
||||
#endif
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
#if defined(__linux__)
|
||||
|
||||
/*
|
||||
* Copyright (c) 2014 Craig Lilley <cralilley@gmail.com>
|
||||
* This software is made available under the terms of the MIT licence.
|
||||
* A copy of the licence can be obtained from:
|
||||
* http://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <cstdio>
|
||||
#include <cstdarg>
|
||||
#include <cstdlib>
|
||||
#ifdef ANDROID
|
||||
#include "cglob.h"
|
||||
#else
|
||||
#include <glob.h>
|
||||
#define cglob glob
|
||||
#define cglobfree globfree
|
||||
#define cglob_t glob_t
|
||||
#endif
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "serial/serial.h"
|
||||
|
||||
using serial::PortInfo;
|
||||
using std::istringstream;
|
||||
using std::ifstream;
|
||||
using std::getline;
|
||||
using std::vector;
|
||||
using std::string;
|
||||
using std::cout;
|
||||
using std::endl;
|
||||
|
||||
static vector<string> glob(const vector<string>& patterns);
|
||||
static string basename(const string& path);
|
||||
static string dirname(const string& path);
|
||||
static bool path_exists(const string& path);
|
||||
static string realpath(const string& path);
|
||||
static string usb_sysfs_friendly_name(const string& sys_usb_path);
|
||||
static vector<string> get_sysfs_info(const string& device_path);
|
||||
static string read_line(const string& file);
|
||||
static string usb_sysfs_hw_string(const string& sysfs_path);
|
||||
static string format(const char* format, ...);
|
||||
|
||||
vector<string>
|
||||
glob(const vector<string>& patterns)
|
||||
{
|
||||
vector<string> paths_found;
|
||||
|
||||
if(patterns.size() == 0)
|
||||
return paths_found;
|
||||
|
||||
cglob_t glob_results;
|
||||
|
||||
int glob_retval = cglob(patterns[0].c_str(), 0, NULL, &glob_results);
|
||||
|
||||
vector<string>::const_iterator iter = patterns.begin();
|
||||
|
||||
while(++iter != patterns.end())
|
||||
{
|
||||
glob_retval = cglob(iter->c_str(), GLOB_APPEND, NULL, &glob_results);
|
||||
}
|
||||
|
||||
for(int path_index = 0; path_index < glob_results.gl_pathc; path_index++)
|
||||
{
|
||||
paths_found.push_back(glob_results.gl_pathv[path_index]);
|
||||
}
|
||||
|
||||
cglobfree(&glob_results);
|
||||
|
||||
return paths_found;
|
||||
}
|
||||
|
||||
string
|
||||
basename(const string& path)
|
||||
{
|
||||
size_t pos = path.rfind("/");
|
||||
|
||||
if(pos == std::string::npos)
|
||||
return path;
|
||||
|
||||
return string(path, pos+1, string::npos);
|
||||
}
|
||||
|
||||
string
|
||||
dirname(const string& path)
|
||||
{
|
||||
size_t pos = path.rfind("/");
|
||||
|
||||
if(pos == std::string::npos)
|
||||
return path;
|
||||
else if(pos == 0)
|
||||
return "/";
|
||||
|
||||
return string(path, 0, pos);
|
||||
}
|
||||
|
||||
bool
|
||||
path_exists(const string& path)
|
||||
{
|
||||
struct stat sb;
|
||||
|
||||
if( stat(path.c_str(), &sb ) == 0 )
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
string
|
||||
realpath(const string& path)
|
||||
{
|
||||
char* real_path = realpath(path.c_str(), NULL);
|
||||
|
||||
string result;
|
||||
|
||||
if(real_path != NULL)
|
||||
{
|
||||
result = real_path;
|
||||
|
||||
free(real_path);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
string
|
||||
usb_sysfs_friendly_name(const string& sys_usb_path)
|
||||
{
|
||||
unsigned int device_number = 0;
|
||||
|
||||
istringstream( read_line(sys_usb_path + "/devnum") ) >> device_number;
|
||||
|
||||
string manufacturer = read_line( sys_usb_path + "/manufacturer" );
|
||||
|
||||
string product = read_line( sys_usb_path + "/product" );
|
||||
|
||||
string serial = read_line( sys_usb_path + "/serial" );
|
||||
|
||||
if( manufacturer.empty() && product.empty() && serial.empty() )
|
||||
return "";
|
||||
|
||||
return format("%s %s %s", manufacturer.c_str(), product.c_str(), serial.c_str() );
|
||||
}
|
||||
|
||||
vector<string>
|
||||
get_sysfs_info(const string& device_path)
|
||||
{
|
||||
string device_name = basename( device_path );
|
||||
|
||||
string friendly_name;
|
||||
|
||||
string hardware_id;
|
||||
|
||||
string sys_device_path = format( "/sys/class/tty/%s/device", device_name.c_str() );
|
||||
|
||||
if( device_name.compare(0,6,"ttyUSB") == 0 )
|
||||
{
|
||||
sys_device_path = dirname( dirname( realpath( sys_device_path ) ) );
|
||||
|
||||
if( path_exists( sys_device_path ) )
|
||||
{
|
||||
friendly_name = usb_sysfs_friendly_name( sys_device_path );
|
||||
|
||||
hardware_id = usb_sysfs_hw_string( sys_device_path );
|
||||
}
|
||||
}
|
||||
else if( device_name.compare(0,6,"ttyACM") == 0 )
|
||||
{
|
||||
sys_device_path = dirname( realpath( sys_device_path ) );
|
||||
|
||||
if( path_exists( sys_device_path ) )
|
||||
{
|
||||
friendly_name = usb_sysfs_friendly_name( sys_device_path );
|
||||
|
||||
hardware_id = usb_sysfs_hw_string( sys_device_path );
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Try to read ID string of PCI device
|
||||
|
||||
string sys_id_path = sys_device_path + "/id";
|
||||
|
||||
if( path_exists( sys_id_path ) )
|
||||
hardware_id = read_line( sys_id_path );
|
||||
}
|
||||
|
||||
if( friendly_name.empty() )
|
||||
friendly_name = device_name;
|
||||
|
||||
if( hardware_id.empty() )
|
||||
hardware_id = "n/a";
|
||||
|
||||
vector<string> result;
|
||||
result.push_back(friendly_name);
|
||||
result.push_back(hardware_id);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
string
|
||||
read_line(const string& file)
|
||||
{
|
||||
ifstream ifs(file.c_str(), ifstream::in);
|
||||
|
||||
string line;
|
||||
|
||||
if(ifs)
|
||||
{
|
||||
getline(ifs, line);
|
||||
}
|
||||
|
||||
return line;
|
||||
}
|
||||
|
||||
string
|
||||
format(const char* format, ...)
|
||||
{
|
||||
va_list ap;
|
||||
|
||||
size_t buffer_size_bytes = 256;
|
||||
|
||||
string result;
|
||||
|
||||
char* buffer = (char*)malloc(buffer_size_bytes);
|
||||
|
||||
if( buffer == NULL )
|
||||
return result;
|
||||
|
||||
bool done = false;
|
||||
|
||||
unsigned int loop_count = 0;
|
||||
|
||||
while(!done)
|
||||
{
|
||||
va_start(ap, format);
|
||||
|
||||
int return_value = vsnprintf(buffer, buffer_size_bytes, format, ap);
|
||||
|
||||
if( return_value < 0 )
|
||||
{
|
||||
done = true;
|
||||
}
|
||||
else if( return_value >= buffer_size_bytes )
|
||||
{
|
||||
// Realloc and try again.
|
||||
|
||||
buffer_size_bytes = return_value + 1;
|
||||
|
||||
char* new_buffer_ptr = (char*)realloc(buffer, buffer_size_bytes);
|
||||
|
||||
if( new_buffer_ptr == NULL )
|
||||
{
|
||||
done = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
buffer = new_buffer_ptr;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
result = buffer;
|
||||
done = true;
|
||||
}
|
||||
|
||||
va_end(ap);
|
||||
|
||||
if( ++loop_count > 5 )
|
||||
done = true;
|
||||
}
|
||||
|
||||
free(buffer);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
string
|
||||
usb_sysfs_hw_string(const string& sysfs_path)
|
||||
{
|
||||
string serial_number = read_line( sysfs_path + "/serial" );
|
||||
|
||||
if( serial_number.length() > 0 )
|
||||
{
|
||||
serial_number = format( "SNR=%s", serial_number.c_str() );
|
||||
}
|
||||
|
||||
string vid = read_line( sysfs_path + "/idVendor" );
|
||||
|
||||
string pid = read_line( sysfs_path + "/idProduct" );
|
||||
|
||||
return format("USB VID:PID=%s:%s %s", vid.c_str(), pid.c_str(), serial_number.c_str() );
|
||||
}
|
||||
|
||||
vector<PortInfo>
|
||||
serial::list_ports()
|
||||
{
|
||||
vector<PortInfo> results;
|
||||
|
||||
vector<string> search_globs;
|
||||
search_globs.push_back("/dev/ttyACM*");
|
||||
search_globs.push_back("/dev/ttyS*");
|
||||
search_globs.push_back("/dev/ttyUSB*");
|
||||
search_globs.push_back("/dev/tty.*");
|
||||
search_globs.push_back("/dev/cu.*");
|
||||
search_globs.push_back("/dev/rfcomm*");
|
||||
|
||||
vector<string> devices_found = glob( search_globs );
|
||||
|
||||
vector<string>::iterator iter = devices_found.begin();
|
||||
|
||||
while( iter != devices_found.end() )
|
||||
{
|
||||
string device = *iter++;
|
||||
|
||||
vector<string> sysfs_info = get_sysfs_info( device );
|
||||
|
||||
string friendly_name = sysfs_info[0];
|
||||
|
||||
string hardware_id = sysfs_info[1];
|
||||
|
||||
PortInfo device_entry;
|
||||
device_entry.port = device;
|
||||
device_entry.description = friendly_name;
|
||||
device_entry.hardware_id = hardware_id;
|
||||
|
||||
results.push_back( device_entry );
|
||||
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
#endif // defined(__linux__)
|
||||
+286
@@ -0,0 +1,286 @@
|
||||
#if defined(__APPLE__)
|
||||
|
||||
#include <sys/param.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include <CoreFoundation/CoreFoundation.h>
|
||||
#include <IOKit/IOKitLib.h>
|
||||
#include <IOKit/serial/IOSerialKeys.h>
|
||||
#include <IOKit/IOBSD.h>
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../../../include/serial/serial.h"
|
||||
|
||||
using serial::PortInfo;
|
||||
using std::string;
|
||||
using std::vector;
|
||||
|
||||
#define HARDWARE_ID_STRING_LENGTH 128
|
||||
|
||||
string cfstring_to_string( CFStringRef cfstring );
|
||||
string get_device_path( io_object_t& serial_port );
|
||||
string get_class_name( io_object_t& obj );
|
||||
io_registry_entry_t get_parent_iousb_device( io_object_t& serial_port );
|
||||
string get_string_property( io_object_t& device, const char* property );
|
||||
uint16_t get_int_property( io_object_t& device, const char* property );
|
||||
string rtrim(const string& str);
|
||||
|
||||
string
|
||||
cfstring_to_string( CFStringRef cfstring )
|
||||
{
|
||||
char cstring[MAXPATHLEN];
|
||||
string result;
|
||||
|
||||
if( cfstring )
|
||||
{
|
||||
Boolean success = CFStringGetCString( cfstring,
|
||||
cstring,
|
||||
sizeof(cstring),
|
||||
kCFStringEncodingASCII );
|
||||
|
||||
if( success )
|
||||
result = cstring;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
string
|
||||
get_device_path( io_object_t& serial_port )
|
||||
{
|
||||
CFTypeRef callout_path;
|
||||
string device_path;
|
||||
|
||||
callout_path = IORegistryEntryCreateCFProperty( serial_port,
|
||||
CFSTR(kIOCalloutDeviceKey),
|
||||
kCFAllocatorDefault,
|
||||
0 );
|
||||
|
||||
if (callout_path)
|
||||
{
|
||||
if( CFGetTypeID(callout_path) == CFStringGetTypeID() )
|
||||
device_path = cfstring_to_string( static_cast<CFStringRef>(callout_path) );
|
||||
|
||||
CFRelease(callout_path);
|
||||
}
|
||||
|
||||
return device_path;
|
||||
}
|
||||
|
||||
string
|
||||
get_class_name( io_object_t& obj )
|
||||
{
|
||||
string result;
|
||||
io_name_t class_name;
|
||||
kern_return_t kern_result;
|
||||
|
||||
kern_result = IOObjectGetClass( obj, class_name );
|
||||
|
||||
if( kern_result == KERN_SUCCESS )
|
||||
result = class_name;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
io_registry_entry_t
|
||||
get_parent_iousb_device( io_object_t& serial_port )
|
||||
{
|
||||
io_object_t device = serial_port;
|
||||
io_registry_entry_t parent = 0;
|
||||
io_registry_entry_t result = 0;
|
||||
kern_return_t kern_result = KERN_FAILURE;
|
||||
string name = get_class_name(device);
|
||||
|
||||
// Walk the IO Registry tree looking for this devices parent IOUSBDevice.
|
||||
while( name != "IOUSBDevice" )
|
||||
{
|
||||
kern_result = IORegistryEntryGetParentEntry( device,
|
||||
kIOServicePlane,
|
||||
&parent );
|
||||
|
||||
if(kern_result != KERN_SUCCESS)
|
||||
{
|
||||
result = 0;
|
||||
break;
|
||||
}
|
||||
|
||||
device = parent;
|
||||
|
||||
name = get_class_name(device);
|
||||
}
|
||||
|
||||
if(kern_result == KERN_SUCCESS)
|
||||
result = device;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
string
|
||||
get_string_property( io_object_t& device, const char* property )
|
||||
{
|
||||
string property_name;
|
||||
|
||||
if( device )
|
||||
{
|
||||
CFStringRef property_as_cfstring = CFStringCreateWithCString (
|
||||
kCFAllocatorDefault,
|
||||
property,
|
||||
kCFStringEncodingASCII );
|
||||
|
||||
CFTypeRef name_as_cfstring = IORegistryEntryCreateCFProperty(
|
||||
device,
|
||||
property_as_cfstring,
|
||||
kCFAllocatorDefault,
|
||||
0 );
|
||||
|
||||
if( name_as_cfstring )
|
||||
{
|
||||
if( CFGetTypeID(name_as_cfstring) == CFStringGetTypeID() )
|
||||
property_name = cfstring_to_string( static_cast<CFStringRef>(name_as_cfstring) );
|
||||
|
||||
CFRelease(name_as_cfstring);
|
||||
}
|
||||
|
||||
if(property_as_cfstring)
|
||||
CFRelease(property_as_cfstring);
|
||||
}
|
||||
|
||||
return property_name;
|
||||
}
|
||||
|
||||
uint16_t
|
||||
get_int_property( io_object_t& device, const char* property )
|
||||
{
|
||||
uint16_t result = 0;
|
||||
|
||||
if( device )
|
||||
{
|
||||
CFStringRef property_as_cfstring = CFStringCreateWithCString (
|
||||
kCFAllocatorDefault,
|
||||
property,
|
||||
kCFStringEncodingASCII );
|
||||
|
||||
CFTypeRef number = IORegistryEntryCreateCFProperty( device,
|
||||
property_as_cfstring,
|
||||
kCFAllocatorDefault,
|
||||
0 );
|
||||
|
||||
if(property_as_cfstring)
|
||||
CFRelease(property_as_cfstring);
|
||||
|
||||
if( number )
|
||||
{
|
||||
if( CFGetTypeID(number) == CFNumberGetTypeID() )
|
||||
{
|
||||
bool success = CFNumberGetValue( static_cast<CFNumberRef>(number),
|
||||
kCFNumberSInt16Type,
|
||||
&result );
|
||||
|
||||
if( !success )
|
||||
result = 0;
|
||||
}
|
||||
|
||||
CFRelease(number);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
string rtrim(const string& str)
|
||||
{
|
||||
string result = str;
|
||||
|
||||
string whitespace = " \t\f\v\n\r";
|
||||
|
||||
std::size_t found = result.find_last_not_of(whitespace);
|
||||
|
||||
if (found != std::string::npos)
|
||||
result.erase(found+1);
|
||||
else
|
||||
result.clear();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
vector<PortInfo>
|
||||
serial::list_ports(void)
|
||||
{
|
||||
vector<PortInfo> devices_found;
|
||||
CFMutableDictionaryRef classes_to_match;
|
||||
io_iterator_t serial_port_iterator;
|
||||
io_object_t serial_port;
|
||||
mach_port_t master_port;
|
||||
kern_return_t kern_result;
|
||||
|
||||
kern_result = IOMasterPort(MACH_PORT_NULL, &master_port);
|
||||
|
||||
if(kern_result != KERN_SUCCESS)
|
||||
return devices_found;
|
||||
|
||||
classes_to_match = IOServiceMatching(kIOSerialBSDServiceValue);
|
||||
|
||||
if (classes_to_match == NULL)
|
||||
return devices_found;
|
||||
|
||||
CFDictionarySetValue( classes_to_match,
|
||||
CFSTR(kIOSerialBSDTypeKey),
|
||||
CFSTR(kIOSerialBSDAllTypes) );
|
||||
|
||||
kern_result = IOServiceGetMatchingServices(master_port, classes_to_match, &serial_port_iterator);
|
||||
|
||||
if (KERN_SUCCESS != kern_result)
|
||||
return devices_found;
|
||||
|
||||
while ( (serial_port = IOIteratorNext(serial_port_iterator)) )
|
||||
{
|
||||
string device_path = get_device_path( serial_port );
|
||||
io_registry_entry_t parent = get_parent_iousb_device( serial_port );
|
||||
IOObjectRelease(serial_port);
|
||||
|
||||
if( device_path.empty() )
|
||||
continue;
|
||||
|
||||
PortInfo port_info;
|
||||
port_info.port = device_path;
|
||||
port_info.description = "n/a";
|
||||
port_info.hardware_id = "n/a";
|
||||
|
||||
string device_name = rtrim( get_string_property( parent, "USB Product Name" ) );
|
||||
string vendor_name = rtrim( get_string_property( parent, "USB Vendor Name") );
|
||||
string description = rtrim( vendor_name + " " + device_name );
|
||||
if( !description.empty() )
|
||||
port_info.description = description;
|
||||
|
||||
string serial_number = rtrim(get_string_property( parent, "USB Serial Number" ) );
|
||||
uint16_t vendor_id = get_int_property( parent, "idVendor" );
|
||||
uint16_t product_id = get_int_property( parent, "idProduct" );
|
||||
|
||||
if( vendor_id && product_id )
|
||||
{
|
||||
char cstring[HARDWARE_ID_STRING_LENGTH];
|
||||
|
||||
if(serial_number.empty())
|
||||
serial_number = "None";
|
||||
|
||||
int ret = snprintf( cstring, HARDWARE_ID_STRING_LENGTH, "USB VID:PID=%04x:%04x SNR=%s",
|
||||
vendor_id,
|
||||
product_id,
|
||||
serial_number.c_str() );
|
||||
|
||||
if( (ret >= 0) && (ret < HARDWARE_ID_STRING_LENGTH) )
|
||||
port_info.hardware_id = cstring;
|
||||
}
|
||||
|
||||
devices_found.push_back(port_info);
|
||||
}
|
||||
|
||||
IOObjectRelease(serial_port_iterator);
|
||||
return devices_found;
|
||||
}
|
||||
|
||||
#endif // defined(__APPLE__)
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
#if defined(_WIN32)
|
||||
|
||||
/*
|
||||
* Copyright (c) 2014 Craig Lilley <cralilley@gmail.com>
|
||||
* This software is made available under the terms of the MIT licence.
|
||||
* A copy of the licence can be obtained from:
|
||||
* http://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "serial/serial.h"
|
||||
#include <tchar.h>
|
||||
#include <windows.h>
|
||||
#include <setupapi.h>
|
||||
#include <initguid.h>
|
||||
#include <devguid.h>
|
||||
#include <cstring>
|
||||
|
||||
using serial::PortInfo;
|
||||
using std::vector;
|
||||
using std::string;
|
||||
|
||||
static const DWORD port_name_max_length = 256;
|
||||
static const DWORD friendly_name_max_length = 256;
|
||||
static const DWORD hardware_id_max_length = 256;
|
||||
|
||||
// Convert a wide Unicode string to an UTF8 string
|
||||
std::string utf8_encode(const std::wstring &wstr)
|
||||
{
|
||||
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
|
||||
std::string strTo( size_needed, 0 );
|
||||
WideCharToMultiByte (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
|
||||
return strTo;
|
||||
}
|
||||
|
||||
vector<PortInfo>
|
||||
serial::list_ports()
|
||||
{
|
||||
vector<PortInfo> devices_found;
|
||||
|
||||
HDEVINFO device_info_set = SetupDiGetClassDevs(
|
||||
(const GUID *) &GUID_DEVCLASS_PORTS,
|
||||
NULL,
|
||||
NULL,
|
||||
DIGCF_PRESENT);
|
||||
|
||||
unsigned int device_info_set_index = 0;
|
||||
SP_DEVINFO_DATA device_info_data;
|
||||
|
||||
device_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
|
||||
|
||||
while(SetupDiEnumDeviceInfo(device_info_set, device_info_set_index, &device_info_data))
|
||||
{
|
||||
device_info_set_index++;
|
||||
|
||||
// Get port name
|
||||
|
||||
HKEY hkey = SetupDiOpenDevRegKey(
|
||||
device_info_set,
|
||||
&device_info_data,
|
||||
DICS_FLAG_GLOBAL,
|
||||
0,
|
||||
DIREG_DEV,
|
||||
KEY_READ);
|
||||
|
||||
TCHAR port_name[port_name_max_length];
|
||||
DWORD port_name_length = port_name_max_length;
|
||||
|
||||
LONG return_code = RegQueryValueEx(
|
||||
hkey,
|
||||
_T("PortName"),
|
||||
NULL,
|
||||
NULL,
|
||||
(LPBYTE)port_name,
|
||||
&port_name_length);
|
||||
|
||||
RegCloseKey(hkey);
|
||||
|
||||
if(return_code != EXIT_SUCCESS)
|
||||
continue;
|
||||
|
||||
if(port_name_length > 0 && port_name_length <= port_name_max_length)
|
||||
port_name[port_name_length-1] = '\0';
|
||||
else
|
||||
port_name[0] = '\0';
|
||||
|
||||
// Ignore parallel ports
|
||||
|
||||
if(_tcsstr(port_name, _T("LPT")) != NULL)
|
||||
continue;
|
||||
|
||||
// Get port friendly name
|
||||
|
||||
TCHAR friendly_name[friendly_name_max_length];
|
||||
DWORD friendly_name_actual_length = 0;
|
||||
|
||||
BOOL got_friendly_name = SetupDiGetDeviceRegistryProperty(
|
||||
device_info_set,
|
||||
&device_info_data,
|
||||
SPDRP_FRIENDLYNAME,
|
||||
NULL,
|
||||
(PBYTE)friendly_name,
|
||||
friendly_name_max_length,
|
||||
&friendly_name_actual_length);
|
||||
|
||||
if(got_friendly_name == TRUE && friendly_name_actual_length > 0)
|
||||
friendly_name[friendly_name_actual_length-1] = '\0';
|
||||
else
|
||||
friendly_name[0] = '\0';
|
||||
|
||||
// Get hardware ID
|
||||
|
||||
TCHAR hardware_id[hardware_id_max_length];
|
||||
DWORD hardware_id_actual_length = 0;
|
||||
|
||||
BOOL got_hardware_id = SetupDiGetDeviceRegistryProperty(
|
||||
device_info_set,
|
||||
&device_info_data,
|
||||
SPDRP_HARDWAREID,
|
||||
NULL,
|
||||
(PBYTE)hardware_id,
|
||||
hardware_id_max_length,
|
||||
&hardware_id_actual_length);
|
||||
|
||||
if(got_hardware_id == TRUE && hardware_id_actual_length > 0)
|
||||
hardware_id[hardware_id_actual_length-1] = '\0';
|
||||
else
|
||||
hardware_id[0] = '\0';
|
||||
|
||||
#ifdef UNICODE
|
||||
std::string portName = utf8_encode(port_name);
|
||||
std::string friendlyName = utf8_encode(friendly_name);
|
||||
std::string hardwareId = utf8_encode(hardware_id);
|
||||
#else
|
||||
std::string portName = port_name;
|
||||
std::string friendlyName = friendly_name;
|
||||
std::string hardwareId = hardware_id;
|
||||
#endif
|
||||
|
||||
PortInfo port_entry;
|
||||
port_entry.port = portName;
|
||||
port_entry.description = friendlyName;
|
||||
port_entry.hardware_id = hardwareId;
|
||||
|
||||
devices_found.push_back(port_entry);
|
||||
}
|
||||
|
||||
SetupDiDestroyDeviceInfoList(device_info_set);
|
||||
|
||||
return devices_found;
|
||||
}
|
||||
|
||||
#endif // #if defined(_WIN32)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,651 @@
|
||||
#if defined(_WIN32)
|
||||
|
||||
/* Copyright 2012 William Woodall and John Harrison */
|
||||
|
||||
#include <sstream>
|
||||
|
||||
#include "serial/impl/win.h"
|
||||
|
||||
using std::string;
|
||||
using std::wstring;
|
||||
using std::stringstream;
|
||||
using std::invalid_argument;
|
||||
using serial::Serial;
|
||||
using serial::Timeout;
|
||||
using serial::bytesize_t;
|
||||
using serial::parity_t;
|
||||
using serial::stopbits_t;
|
||||
using serial::flowcontrol_t;
|
||||
using serial::SerialException;
|
||||
using serial::PortNotOpenedException;
|
||||
using serial::IOException;
|
||||
|
||||
inline wstring
|
||||
_prefix_port_if_needed(const wstring &input)
|
||||
{
|
||||
static wstring windows_com_port_prefix = L"\\\\.\\";
|
||||
if (input.compare(0, windows_com_port_prefix.size(), windows_com_port_prefix) != 0)
|
||||
{
|
||||
return windows_com_port_prefix + input;
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
Serial::SerialImpl::SerialImpl (const string &port, unsigned long baudrate,
|
||||
bytesize_t bytesize,
|
||||
parity_t parity, stopbits_t stopbits,
|
||||
flowcontrol_t flowcontrol)
|
||||
: port_ (port.begin(), port.end()), fd_ (INVALID_HANDLE_VALUE), is_open_ (false),
|
||||
baudrate_ (baudrate), parity_ (parity),
|
||||
bytesize_ (bytesize), stopbits_ (stopbits), flowcontrol_ (flowcontrol)
|
||||
{
|
||||
if (port_.empty () == false)
|
||||
open ();
|
||||
read_mutex = CreateMutex(NULL, false, NULL);
|
||||
write_mutex = CreateMutex(NULL, false, NULL);
|
||||
}
|
||||
|
||||
Serial::SerialImpl::~SerialImpl ()
|
||||
{
|
||||
this->close();
|
||||
CloseHandle(read_mutex);
|
||||
CloseHandle(write_mutex);
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::open ()
|
||||
{
|
||||
if (port_.empty ()) {
|
||||
throw invalid_argument ("Empty port is invalid.");
|
||||
}
|
||||
if (is_open_ == true) {
|
||||
throw SerialException ("Serial port already open.");
|
||||
}
|
||||
|
||||
// See: https://github.com/wjwwood/serial/issues/84
|
||||
wstring port_with_prefix = _prefix_port_if_needed(port_);
|
||||
LPCWSTR lp_port = port_with_prefix.c_str();
|
||||
fd_ = CreateFileW(lp_port,
|
||||
GENERIC_READ | GENERIC_WRITE,
|
||||
0,
|
||||
0,
|
||||
OPEN_EXISTING,
|
||||
FILE_ATTRIBUTE_NORMAL,
|
||||
0);
|
||||
|
||||
if (fd_ == INVALID_HANDLE_VALUE) {
|
||||
DWORD create_file_err = GetLastError();
|
||||
stringstream ss;
|
||||
switch (create_file_err) {
|
||||
case ERROR_FILE_NOT_FOUND:
|
||||
// Use this->getPort to convert to a std::string
|
||||
ss << "Specified port, " << this->getPort() << ", does not exist.";
|
||||
THROWEX (IOException, ss.str().c_str(), 1);
|
||||
case ERROR_ACCESS_DENIED:
|
||||
ss << "Specified port, " << this->getPort() << ", allready open.";
|
||||
THROWEX (IOException, ss.str().c_str(), 2);
|
||||
default:
|
||||
ss << "Unknown error opening the serial port: " << create_file_err;
|
||||
THROW (IOException, ss.str().c_str());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
reconfigurePort();
|
||||
is_open_ = true;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::reconfigurePort ()
|
||||
{
|
||||
if (fd_ == INVALID_HANDLE_VALUE) {
|
||||
// Can only operate on a valid file descriptor
|
||||
THROW (IOException, "Invalid file descriptor, is the serial port open?");
|
||||
}
|
||||
|
||||
DCB dcbSerialParams = {0};
|
||||
|
||||
dcbSerialParams.DCBlength=sizeof(dcbSerialParams);
|
||||
|
||||
if (!GetCommState(fd_, &dcbSerialParams)) {
|
||||
//error getting state
|
||||
THROW (IOException, "Error getting the serial port state.");
|
||||
}
|
||||
|
||||
// setup baud rate
|
||||
switch (baudrate_) {
|
||||
#ifdef CBR_0
|
||||
case 0: dcbSerialParams.BaudRate = CBR_0; break;
|
||||
#endif
|
||||
#ifdef CBR_50
|
||||
case 50: dcbSerialParams.BaudRate = CBR_50; break;
|
||||
#endif
|
||||
#ifdef CBR_75
|
||||
case 75: dcbSerialParams.BaudRate = CBR_75; break;
|
||||
#endif
|
||||
#ifdef CBR_110
|
||||
case 110: dcbSerialParams.BaudRate = CBR_110; break;
|
||||
#endif
|
||||
#ifdef CBR_134
|
||||
case 134: dcbSerialParams.BaudRate = CBR_134; break;
|
||||
#endif
|
||||
#ifdef CBR_150
|
||||
case 150: dcbSerialParams.BaudRate = CBR_150; break;
|
||||
#endif
|
||||
#ifdef CBR_200
|
||||
case 200: dcbSerialParams.BaudRate = CBR_200; break;
|
||||
#endif
|
||||
#ifdef CBR_300
|
||||
case 300: dcbSerialParams.BaudRate = CBR_300; break;
|
||||
#endif
|
||||
#ifdef CBR_600
|
||||
case 600: dcbSerialParams.BaudRate = CBR_600; break;
|
||||
#endif
|
||||
#ifdef CBR_1200
|
||||
case 1200: dcbSerialParams.BaudRate = CBR_1200; break;
|
||||
#endif
|
||||
#ifdef CBR_1800
|
||||
case 1800: dcbSerialParams.BaudRate = CBR_1800; break;
|
||||
#endif
|
||||
#ifdef CBR_2400
|
||||
case 2400: dcbSerialParams.BaudRate = CBR_2400; break;
|
||||
#endif
|
||||
#ifdef CBR_4800
|
||||
case 4800: dcbSerialParams.BaudRate = CBR_4800; break;
|
||||
#endif
|
||||
#ifdef CBR_7200
|
||||
case 7200: dcbSerialParams.BaudRate = CBR_7200; break;
|
||||
#endif
|
||||
#ifdef CBR_9600
|
||||
case 9600: dcbSerialParams.BaudRate = CBR_9600; break;
|
||||
#endif
|
||||
#ifdef CBR_14400
|
||||
case 14400: dcbSerialParams.BaudRate = CBR_14400; break;
|
||||
#endif
|
||||
#ifdef CBR_19200
|
||||
case 19200: dcbSerialParams.BaudRate = CBR_19200; break;
|
||||
#endif
|
||||
#ifdef CBR_28800
|
||||
case 28800: dcbSerialParams.BaudRate = CBR_28800; break;
|
||||
#endif
|
||||
#ifdef CBR_57600
|
||||
case 57600: dcbSerialParams.BaudRate = CBR_57600; break;
|
||||
#endif
|
||||
#ifdef CBR_76800
|
||||
case 76800: dcbSerialParams.BaudRate = CBR_76800; break;
|
||||
#endif
|
||||
#ifdef CBR_38400
|
||||
case 38400: dcbSerialParams.BaudRate = CBR_38400; break;
|
||||
#endif
|
||||
#ifdef CBR_115200
|
||||
case 115200: dcbSerialParams.BaudRate = CBR_115200; break;
|
||||
#endif
|
||||
#ifdef CBR_128000
|
||||
case 128000: dcbSerialParams.BaudRate = CBR_128000; break;
|
||||
#endif
|
||||
#ifdef CBR_153600
|
||||
case 153600: dcbSerialParams.BaudRate = CBR_153600; break;
|
||||
#endif
|
||||
#ifdef CBR_230400
|
||||
case 230400: dcbSerialParams.BaudRate = CBR_230400; break;
|
||||
#endif
|
||||
#ifdef CBR_256000
|
||||
case 256000: dcbSerialParams.BaudRate = CBR_256000; break;
|
||||
#endif
|
||||
#ifdef CBR_460800
|
||||
case 460800: dcbSerialParams.BaudRate = CBR_460800; break;
|
||||
#endif
|
||||
#ifdef CBR_921600
|
||||
case 921600: dcbSerialParams.BaudRate = CBR_921600; break;
|
||||
#endif
|
||||
default:
|
||||
// Try to blindly assign it
|
||||
dcbSerialParams.BaudRate = baudrate_;
|
||||
}
|
||||
|
||||
// setup char len
|
||||
if (bytesize_ == eightbits)
|
||||
dcbSerialParams.ByteSize = 8;
|
||||
else if (bytesize_ == sevenbits)
|
||||
dcbSerialParams.ByteSize = 7;
|
||||
else if (bytesize_ == sixbits)
|
||||
dcbSerialParams.ByteSize = 6;
|
||||
else if (bytesize_ == fivebits)
|
||||
dcbSerialParams.ByteSize = 5;
|
||||
else
|
||||
throw invalid_argument ("invalid char len");
|
||||
|
||||
// setup stopbits
|
||||
if (stopbits_ == stopbits_one)
|
||||
dcbSerialParams.StopBits = ONESTOPBIT;
|
||||
else if (stopbits_ == stopbits_one_point_five)
|
||||
dcbSerialParams.StopBits = ONE5STOPBITS;
|
||||
else if (stopbits_ == stopbits_two)
|
||||
dcbSerialParams.StopBits = TWOSTOPBITS;
|
||||
else
|
||||
throw invalid_argument ("invalid stop bit");
|
||||
|
||||
// setup parity
|
||||
if (parity_ == parity_none) {
|
||||
dcbSerialParams.Parity = NOPARITY;
|
||||
} else if (parity_ == parity_even) {
|
||||
dcbSerialParams.Parity = EVENPARITY;
|
||||
} else if (parity_ == parity_odd) {
|
||||
dcbSerialParams.Parity = ODDPARITY;
|
||||
} else if (parity_ == parity_mark) {
|
||||
dcbSerialParams.Parity = MARKPARITY;
|
||||
} else if (parity_ == parity_space) {
|
||||
dcbSerialParams.Parity = SPACEPARITY;
|
||||
} else {
|
||||
throw invalid_argument ("invalid parity");
|
||||
}
|
||||
|
||||
// setup flowcontrol
|
||||
if (flowcontrol_ == flowcontrol_none) {
|
||||
dcbSerialParams.fOutxCtsFlow = false;
|
||||
dcbSerialParams.fRtsControl = RTS_CONTROL_DISABLE;
|
||||
dcbSerialParams.fOutX = false;
|
||||
dcbSerialParams.fInX = false;
|
||||
}
|
||||
if (flowcontrol_ == flowcontrol_software) {
|
||||
dcbSerialParams.fOutxCtsFlow = false;
|
||||
dcbSerialParams.fRtsControl = RTS_CONTROL_DISABLE;
|
||||
dcbSerialParams.fOutX = true;
|
||||
dcbSerialParams.fInX = true;
|
||||
}
|
||||
if (flowcontrol_ == flowcontrol_hardware) {
|
||||
dcbSerialParams.fOutxCtsFlow = true;
|
||||
dcbSerialParams.fRtsControl = RTS_CONTROL_HANDSHAKE;
|
||||
dcbSerialParams.fOutX = false;
|
||||
dcbSerialParams.fInX = false;
|
||||
}
|
||||
|
||||
// activate settings
|
||||
if (!SetCommState(fd_, &dcbSerialParams)){
|
||||
CloseHandle(fd_);
|
||||
THROW (IOException, "Error setting serial port settings.");
|
||||
}
|
||||
|
||||
// Setup timeouts
|
||||
COMMTIMEOUTS timeouts = {0};
|
||||
timeouts.ReadIntervalTimeout = timeout_.inter_byte_timeout;
|
||||
timeouts.ReadTotalTimeoutConstant = timeout_.read_timeout_constant;
|
||||
timeouts.ReadTotalTimeoutMultiplier = timeout_.read_timeout_multiplier;
|
||||
timeouts.WriteTotalTimeoutConstant = timeout_.write_timeout_constant;
|
||||
timeouts.WriteTotalTimeoutMultiplier = timeout_.write_timeout_multiplier;
|
||||
if (!SetCommTimeouts(fd_, &timeouts)) {
|
||||
THROW (IOException, "Error setting timeouts.");
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::close ()
|
||||
{
|
||||
if (is_open_ == true) {
|
||||
if (fd_ != INVALID_HANDLE_VALUE) {
|
||||
int ret;
|
||||
ret = CloseHandle(fd_);
|
||||
if (ret == 0) {
|
||||
stringstream ss;
|
||||
ss << "Error while closing serial port: " << GetLastError();
|
||||
THROW (IOException, ss.str().c_str());
|
||||
} else {
|
||||
fd_ = INVALID_HANDLE_VALUE;
|
||||
}
|
||||
}
|
||||
is_open_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
bool
|
||||
Serial::SerialImpl::isOpen () const
|
||||
{
|
||||
return is_open_;
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::SerialImpl::available ()
|
||||
{
|
||||
if (!is_open_) {
|
||||
return 0;
|
||||
}
|
||||
COMSTAT cs;
|
||||
if (!ClearCommError(fd_, NULL, &cs)) {
|
||||
stringstream ss;
|
||||
ss << "Error while checking status of the serial port: " << GetLastError();
|
||||
THROW (IOException, ss.str().c_str());
|
||||
}
|
||||
return static_cast<size_t>(cs.cbInQue);
|
||||
}
|
||||
|
||||
bool
|
||||
Serial::SerialImpl::waitReadable (uint32_t /*timeout*/)
|
||||
{
|
||||
THROW (IOException, "waitReadable is not implemented on Windows.");
|
||||
return false;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::waitByteTimes (size_t /*count*/)
|
||||
{
|
||||
THROW (IOException, "waitByteTimes is not implemented on Windows.");
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::SerialImpl::read (uint8_t *buf, size_t size)
|
||||
{
|
||||
if (!is_open_) {
|
||||
throw PortNotOpenedException ("Serial::read");
|
||||
}
|
||||
DWORD bytes_read;
|
||||
if (!ReadFile(fd_, buf, static_cast<DWORD>(size), &bytes_read, NULL)) {
|
||||
stringstream ss;
|
||||
ss << "Error while reading from the serial port: " << GetLastError();
|
||||
THROW (IOException, ss.str().c_str());
|
||||
}
|
||||
return (size_t) (bytes_read);
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::SerialImpl::write (const uint8_t *data, size_t length)
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::write");
|
||||
}
|
||||
DWORD bytes_written;
|
||||
if (!WriteFile(fd_, data, static_cast<DWORD>(length), &bytes_written, NULL)) {
|
||||
stringstream ss;
|
||||
ss << "Error while writing to the serial port: " << GetLastError();
|
||||
THROW (IOException, ss.str().c_str());
|
||||
}
|
||||
return (size_t) (bytes_written);
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setPort (const string &port)
|
||||
{
|
||||
port_ = wstring(port.begin(), port.end());
|
||||
}
|
||||
|
||||
string
|
||||
Serial::SerialImpl::getPort () const
|
||||
{
|
||||
return string(port_.begin(), port_.end());
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setTimeout (serial::Timeout &timeout)
|
||||
{
|
||||
timeout_ = timeout;
|
||||
if (is_open_) {
|
||||
reconfigurePort ();
|
||||
}
|
||||
}
|
||||
|
||||
serial::Timeout
|
||||
Serial::SerialImpl::getTimeout () const
|
||||
{
|
||||
return timeout_;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setBaudrate (unsigned long baudrate)
|
||||
{
|
||||
baudrate_ = baudrate;
|
||||
if (is_open_) {
|
||||
reconfigurePort ();
|
||||
}
|
||||
}
|
||||
|
||||
unsigned long
|
||||
Serial::SerialImpl::getBaudrate () const
|
||||
{
|
||||
return baudrate_;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setBytesize (serial::bytesize_t bytesize)
|
||||
{
|
||||
bytesize_ = bytesize;
|
||||
if (is_open_) {
|
||||
reconfigurePort ();
|
||||
}
|
||||
}
|
||||
|
||||
serial::bytesize_t
|
||||
Serial::SerialImpl::getBytesize () const
|
||||
{
|
||||
return bytesize_;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setParity (serial::parity_t parity)
|
||||
{
|
||||
parity_ = parity;
|
||||
if (is_open_) {
|
||||
reconfigurePort ();
|
||||
}
|
||||
}
|
||||
|
||||
serial::parity_t
|
||||
Serial::SerialImpl::getParity () const
|
||||
{
|
||||
return parity_;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setStopbits (serial::stopbits_t stopbits)
|
||||
{
|
||||
stopbits_ = stopbits;
|
||||
if (is_open_) {
|
||||
reconfigurePort ();
|
||||
}
|
||||
}
|
||||
|
||||
serial::stopbits_t
|
||||
Serial::SerialImpl::getStopbits () const
|
||||
{
|
||||
return stopbits_;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setFlowcontrol (serial::flowcontrol_t flowcontrol)
|
||||
{
|
||||
flowcontrol_ = flowcontrol;
|
||||
if (is_open_) {
|
||||
reconfigurePort ();
|
||||
}
|
||||
}
|
||||
|
||||
serial::flowcontrol_t
|
||||
Serial::SerialImpl::getFlowcontrol () const
|
||||
{
|
||||
return flowcontrol_;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::flush ()
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::flush");
|
||||
}
|
||||
FlushFileBuffers (fd_);
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::flushInput ()
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException("Serial::flushInput");
|
||||
}
|
||||
PurgeComm(fd_, PURGE_RXCLEAR);
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::flushOutput ()
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException("Serial::flushOutput");
|
||||
}
|
||||
PurgeComm(fd_, PURGE_TXCLEAR);
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::sendBreak (int /*duration*/)
|
||||
{
|
||||
THROW (IOException, "sendBreak is not supported on Windows.");
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setBreak (bool level)
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::setBreak");
|
||||
}
|
||||
if (level) {
|
||||
EscapeCommFunction (fd_, SETBREAK);
|
||||
} else {
|
||||
EscapeCommFunction (fd_, CLRBREAK);
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setRTS (bool level)
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::setRTS");
|
||||
}
|
||||
if (level) {
|
||||
EscapeCommFunction (fd_, SETRTS);
|
||||
} else {
|
||||
EscapeCommFunction (fd_, CLRRTS);
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setDTR (bool level)
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::setDTR");
|
||||
}
|
||||
if (level) {
|
||||
EscapeCommFunction (fd_, SETDTR);
|
||||
} else {
|
||||
EscapeCommFunction (fd_, CLRDTR);
|
||||
}
|
||||
}
|
||||
|
||||
bool
|
||||
Serial::SerialImpl::waitForChange ()
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::waitForChange");
|
||||
}
|
||||
DWORD dwCommEvent;
|
||||
|
||||
if (!SetCommMask(fd_, EV_CTS | EV_DSR | EV_RING | EV_RLSD)) {
|
||||
// Error setting communications mask
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!WaitCommEvent(fd_, &dwCommEvent, NULL)) {
|
||||
// An error occurred waiting for the event.
|
||||
return false;
|
||||
} else {
|
||||
// Event has occurred.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool
|
||||
Serial::SerialImpl::getCTS ()
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::getCTS");
|
||||
}
|
||||
DWORD dwModemStatus;
|
||||
if (!GetCommModemStatus(fd_, &dwModemStatus)) {
|
||||
THROW (IOException, "Error getting the status of the CTS line.");
|
||||
}
|
||||
|
||||
return (MS_CTS_ON & dwModemStatus) != 0;
|
||||
}
|
||||
|
||||
bool
|
||||
Serial::SerialImpl::getDSR ()
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::getDSR");
|
||||
}
|
||||
DWORD dwModemStatus;
|
||||
if (!GetCommModemStatus(fd_, &dwModemStatus)) {
|
||||
THROW (IOException, "Error getting the status of the DSR line.");
|
||||
}
|
||||
|
||||
return (MS_DSR_ON & dwModemStatus) != 0;
|
||||
}
|
||||
|
||||
bool
|
||||
Serial::SerialImpl::getRI()
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::getRI");
|
||||
}
|
||||
DWORD dwModemStatus;
|
||||
if (!GetCommModemStatus(fd_, &dwModemStatus)) {
|
||||
THROW (IOException, "Error getting the status of the RI line.");
|
||||
}
|
||||
|
||||
return (MS_RING_ON & dwModemStatus) != 0;
|
||||
}
|
||||
|
||||
bool
|
||||
Serial::SerialImpl::getCD()
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::getCD");
|
||||
}
|
||||
DWORD dwModemStatus;
|
||||
if (!GetCommModemStatus(fd_, &dwModemStatus)) {
|
||||
// Error in GetCommModemStatus;
|
||||
THROW (IOException, "Error getting the status of the CD line.");
|
||||
}
|
||||
|
||||
return (MS_RLSD_ON & dwModemStatus) != 0;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::readLock()
|
||||
{
|
||||
if (WaitForSingleObject(read_mutex, INFINITE) != WAIT_OBJECT_0) {
|
||||
THROW (IOException, "Error claiming read mutex.");
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::readUnlock()
|
||||
{
|
||||
if (!ReleaseMutex(read_mutex)) {
|
||||
THROW (IOException, "Error releasing read mutex.");
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::writeLock()
|
||||
{
|
||||
if (WaitForSingleObject(write_mutex, INFINITE) != WAIT_OBJECT_0) {
|
||||
THROW (IOException, "Error claiming write mutex.");
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::writeUnlock()
|
||||
{
|
||||
if (!ReleaseMutex(write_mutex)) {
|
||||
THROW (IOException, "Error releasing write mutex.");
|
||||
}
|
||||
}
|
||||
|
||||
#endif // #if defined(_WIN32)
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
#include "ringbuffer.h"
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Implementation of ring buffer functions.
|
||||
*/
|
||||
|
||||
void ring_buffer_init(ring_buffer_t *buffer, char *buf, size_t buf_size) {
|
||||
RING_BUFFER_ASSERT(RING_BUFFER_IS_POWER_OF_TWO(buf_size) == 1);
|
||||
buffer->buffer = buf;
|
||||
buffer->buffer_mask = buf_size - 1;
|
||||
buffer->tail_index = 0;
|
||||
buffer->head_index = 0;
|
||||
}
|
||||
|
||||
void ring_buffer_queue(ring_buffer_t *buffer, char data) {
|
||||
/* Is buffer full? */
|
||||
if(ring_buffer_is_full(buffer)) {
|
||||
/* Is going to overwrite the oldest byte */
|
||||
/* Increase tail index */
|
||||
buffer->tail_index = ((buffer->tail_index + 1) & RING_BUFFER_MASK(buffer));
|
||||
}
|
||||
|
||||
/* Place data in buffer */
|
||||
buffer->buffer[buffer->head_index] = data;
|
||||
buffer->head_index = ((buffer->head_index + 1) & RING_BUFFER_MASK(buffer));
|
||||
}
|
||||
|
||||
void ring_buffer_queue_arr(ring_buffer_t *buffer, const char *data, ring_buffer_size_t size) {
|
||||
/* Add bytes; one by one */
|
||||
ring_buffer_size_t i;
|
||||
for(i = 0; i < size; i++) {
|
||||
ring_buffer_queue(buffer, data[i]);
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t ring_buffer_dequeue(ring_buffer_t *buffer, char *data) {
|
||||
if(ring_buffer_is_empty(buffer)) {
|
||||
/* No items */
|
||||
return 0;
|
||||
}
|
||||
|
||||
*data = buffer->buffer[buffer->tail_index];
|
||||
buffer->tail_index = ((buffer->tail_index + 1) & RING_BUFFER_MASK(buffer));
|
||||
return 1;
|
||||
}
|
||||
|
||||
ring_buffer_size_t ring_buffer_dequeue_arr(ring_buffer_t *buffer, char *data, ring_buffer_size_t len) {
|
||||
if(ring_buffer_is_empty(buffer)) {
|
||||
/* No items */
|
||||
return 0;
|
||||
}
|
||||
|
||||
char *data_ptr = data;
|
||||
ring_buffer_size_t cnt = 0;
|
||||
while((cnt < len) && ring_buffer_dequeue(buffer, data_ptr)) {
|
||||
cnt++;
|
||||
data_ptr++;
|
||||
}
|
||||
return cnt;
|
||||
}
|
||||
|
||||
uint8_t ring_buffer_peek(ring_buffer_t *buffer, char *data, ring_buffer_size_t index) {
|
||||
if(index >= ring_buffer_num_items(buffer)) {
|
||||
/* No items at index */
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Add index to pointer */
|
||||
ring_buffer_size_t data_index = ((buffer->tail_index + index) & RING_BUFFER_MASK(buffer));
|
||||
*data = buffer->buffer[data_index];
|
||||
return 1;
|
||||
}
|
||||
|
||||
extern inline uint8_t ring_buffer_is_empty(ring_buffer_t *buffer);
|
||||
extern inline uint8_t ring_buffer_is_full(ring_buffer_t *buffer);
|
||||
extern inline ring_buffer_size_t ring_buffer_num_items(ring_buffer_t *buffer);
|
||||
|
||||
@@ -0,0 +1,432 @@
|
||||
/* Copyright 2012 William Woodall and John Harrison */
|
||||
#include <algorithm>
|
||||
|
||||
#if !defined(_WIN32) && !defined(__OpenBSD__) && !defined(__FreeBSD__)
|
||||
# include <alloca.h>
|
||||
#endif
|
||||
|
||||
#if defined (__MINGW32__)
|
||||
# define alloca __builtin_alloca
|
||||
#endif
|
||||
|
||||
#include "../include/serial/serial.h"
|
||||
|
||||
#ifdef _WIN32
|
||||
#include "serial/impl/win.h"
|
||||
#else
|
||||
#include "../include/serial/impl/unix.h"
|
||||
#endif
|
||||
|
||||
using std::invalid_argument;
|
||||
using std::min;
|
||||
using std::numeric_limits;
|
||||
using std::vector;
|
||||
using std::size_t;
|
||||
using std::string;
|
||||
|
||||
using serial::Serial;
|
||||
using serial::SerialException;
|
||||
using serial::IOException;
|
||||
using serial::bytesize_t;
|
||||
using serial::parity_t;
|
||||
using serial::stopbits_t;
|
||||
using serial::flowcontrol_t;
|
||||
|
||||
class Serial::ScopedReadLock {
|
||||
public:
|
||||
ScopedReadLock(SerialImpl *pimpl) : pimpl_(pimpl) {
|
||||
this->pimpl_->readLock();
|
||||
}
|
||||
~ScopedReadLock() {
|
||||
this->pimpl_->readUnlock();
|
||||
}
|
||||
private:
|
||||
// Disable copy constructors
|
||||
ScopedReadLock(const ScopedReadLock&);
|
||||
const ScopedReadLock& operator=(ScopedReadLock);
|
||||
|
||||
SerialImpl *pimpl_;
|
||||
};
|
||||
|
||||
class Serial::ScopedWriteLock {
|
||||
public:
|
||||
ScopedWriteLock(SerialImpl *pimpl) : pimpl_(pimpl) {
|
||||
this->pimpl_->writeLock();
|
||||
}
|
||||
~ScopedWriteLock() {
|
||||
this->pimpl_->writeUnlock();
|
||||
}
|
||||
private:
|
||||
// Disable copy constructors
|
||||
ScopedWriteLock(const ScopedWriteLock&);
|
||||
const ScopedWriteLock& operator=(ScopedWriteLock);
|
||||
SerialImpl *pimpl_;
|
||||
};
|
||||
|
||||
Serial::Serial (const string &port, uint32_t baudrate, serial::Timeout timeout,
|
||||
bytesize_t bytesize, parity_t parity, stopbits_t stopbits,
|
||||
flowcontrol_t flowcontrol)
|
||||
: pimpl_(new SerialImpl (port, baudrate, bytesize, parity,
|
||||
stopbits, flowcontrol))
|
||||
{
|
||||
pimpl_->setTimeout(timeout);
|
||||
}
|
||||
|
||||
Serial::~Serial ()
|
||||
{
|
||||
delete pimpl_;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::open ()
|
||||
{
|
||||
pimpl_->open ();
|
||||
}
|
||||
|
||||
void
|
||||
Serial::close ()
|
||||
{
|
||||
pimpl_->close ();
|
||||
}
|
||||
|
||||
bool
|
||||
Serial::isOpen () const
|
||||
{
|
||||
return pimpl_->isOpen ();
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::available ()
|
||||
{
|
||||
return pimpl_->available ();
|
||||
}
|
||||
|
||||
bool
|
||||
Serial::waitReadable ()
|
||||
{
|
||||
serial::Timeout timeout(pimpl_->getTimeout ());
|
||||
return pimpl_->waitReadable(timeout.read_timeout_constant);
|
||||
}
|
||||
|
||||
void
|
||||
Serial::waitByteTimes (size_t count)
|
||||
{
|
||||
pimpl_->waitByteTimes(count);
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::read_ (uint8_t *buffer, size_t size)
|
||||
{
|
||||
return this->pimpl_->read (buffer, size);
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::read (uint8_t *buffer, size_t size)
|
||||
{
|
||||
ScopedReadLock lock(this->pimpl_);
|
||||
return this->pimpl_->read (buffer, size);
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::read (std::vector<uint8_t> &buffer, size_t size)
|
||||
{
|
||||
ScopedReadLock lock(this->pimpl_);
|
||||
uint8_t *buffer_ = new uint8_t[size];
|
||||
size_t bytes_read = 0;
|
||||
|
||||
try {
|
||||
bytes_read = this->pimpl_->read (buffer_, size);
|
||||
}
|
||||
catch (const std::exception) {
|
||||
delete[] buffer_;
|
||||
throw;
|
||||
}
|
||||
|
||||
buffer.insert (buffer.end (), buffer_, buffer_+bytes_read);
|
||||
delete[] buffer_;
|
||||
return bytes_read;
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::read (std::string &buffer, size_t size)
|
||||
{
|
||||
ScopedReadLock lock(this->pimpl_);
|
||||
uint8_t *buffer_ = new uint8_t[size];
|
||||
size_t bytes_read = 0;
|
||||
try {
|
||||
bytes_read = this->pimpl_->read (buffer_, size);
|
||||
}
|
||||
catch (const std::exception) {
|
||||
delete[] buffer_;
|
||||
throw;
|
||||
}
|
||||
buffer.append (reinterpret_cast<const char*>(buffer_), bytes_read);
|
||||
delete[] buffer_;
|
||||
return bytes_read;
|
||||
}
|
||||
|
||||
string
|
||||
Serial::read (size_t size)
|
||||
{
|
||||
std::string buffer;
|
||||
this->read (buffer, size);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::readline (string &buffer, size_t size, string eol)
|
||||
{
|
||||
ScopedReadLock lock(this->pimpl_);
|
||||
size_t eol_len = eol.length ();
|
||||
uint8_t *buffer_ = static_cast<uint8_t*>
|
||||
(alloca (size * sizeof (uint8_t)));
|
||||
size_t read_so_far = 0;
|
||||
while (true)
|
||||
{
|
||||
size_t bytes_read = this->read_ (buffer_ + read_so_far, 1);
|
||||
read_so_far += bytes_read;
|
||||
if (bytes_read == 0) {
|
||||
break; // Timeout occured on reading 1 byte
|
||||
}
|
||||
if(read_so_far < eol_len) continue;
|
||||
if (string (reinterpret_cast<const char*>
|
||||
(buffer_ + read_so_far - eol_len), eol_len) == eol) {
|
||||
break; // EOL found
|
||||
}
|
||||
if (read_so_far == size) {
|
||||
break; // Reached the maximum read length
|
||||
}
|
||||
}
|
||||
buffer.append(reinterpret_cast<const char*> (buffer_), read_so_far);
|
||||
return read_so_far;
|
||||
}
|
||||
|
||||
string
|
||||
Serial::readline (size_t size, string eol)
|
||||
{
|
||||
std::string buffer;
|
||||
this->readline (buffer, size, eol);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
vector<string>
|
||||
Serial::readlines (size_t size, string eol)
|
||||
{
|
||||
ScopedReadLock lock(this->pimpl_);
|
||||
std::vector<std::string> lines;
|
||||
size_t eol_len = eol.length ();
|
||||
uint8_t *buffer_ = static_cast<uint8_t*>
|
||||
(alloca (size * sizeof (uint8_t)));
|
||||
size_t read_so_far = 0;
|
||||
size_t start_of_line = 0;
|
||||
while (read_so_far < size) {
|
||||
size_t bytes_read = this->read_ (buffer_+read_so_far, 1);
|
||||
read_so_far += bytes_read;
|
||||
if (bytes_read == 0) {
|
||||
if (start_of_line != read_so_far) {
|
||||
lines.push_back (
|
||||
string (reinterpret_cast<const char*> (buffer_ + start_of_line),
|
||||
read_so_far - start_of_line));
|
||||
}
|
||||
break; // Timeout occured on reading 1 byte
|
||||
}
|
||||
if(read_so_far < eol_len) continue;
|
||||
if (string (reinterpret_cast<const char*>
|
||||
(buffer_ + read_so_far - eol_len), eol_len) == eol) {
|
||||
// EOL found
|
||||
lines.push_back(
|
||||
string(reinterpret_cast<const char*> (buffer_ + start_of_line),
|
||||
read_so_far - start_of_line));
|
||||
start_of_line = read_so_far;
|
||||
}
|
||||
if (read_so_far == size) {
|
||||
if (start_of_line != read_so_far) {
|
||||
lines.push_back(
|
||||
string(reinterpret_cast<const char*> (buffer_ + start_of_line),
|
||||
read_so_far - start_of_line));
|
||||
}
|
||||
break; // Reached the maximum read length
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::write (const string &data)
|
||||
{
|
||||
ScopedWriteLock lock(this->pimpl_);
|
||||
return this->write_ (reinterpret_cast<const uint8_t*>(data.c_str()),
|
||||
data.length());
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::write (const std::vector<uint8_t> &data)
|
||||
{
|
||||
ScopedWriteLock lock(this->pimpl_);
|
||||
return this->write_ (&data[0], data.size());
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::write (const uint8_t *data, size_t size)
|
||||
{
|
||||
ScopedWriteLock lock(this->pimpl_);
|
||||
return this->write_(data, size);
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::write_ (const uint8_t *data, size_t length)
|
||||
{
|
||||
return pimpl_->write (data, length);
|
||||
}
|
||||
|
||||
void
|
||||
Serial::setPort (const string &port)
|
||||
{
|
||||
ScopedReadLock rlock(this->pimpl_);
|
||||
ScopedWriteLock wlock(this->pimpl_);
|
||||
bool was_open = pimpl_->isOpen ();
|
||||
if (was_open) close();
|
||||
pimpl_->setPort (port);
|
||||
if (was_open) open ();
|
||||
}
|
||||
|
||||
string
|
||||
Serial::getPort () const
|
||||
{
|
||||
return pimpl_->getPort ();
|
||||
}
|
||||
|
||||
void
|
||||
Serial::setTimeout (serial::Timeout &timeout)
|
||||
{
|
||||
pimpl_->setTimeout (timeout);
|
||||
}
|
||||
|
||||
serial::Timeout
|
||||
Serial::getTimeout () const {
|
||||
return pimpl_->getTimeout ();
|
||||
}
|
||||
|
||||
void
|
||||
Serial::setBaudrate (uint32_t baudrate)
|
||||
{
|
||||
pimpl_->setBaudrate (baudrate);
|
||||
}
|
||||
|
||||
uint32_t
|
||||
Serial::getBaudrate () const
|
||||
{
|
||||
return uint32_t(pimpl_->getBaudrate ());
|
||||
}
|
||||
|
||||
void
|
||||
Serial::setBytesize (bytesize_t bytesize)
|
||||
{
|
||||
pimpl_->setBytesize (bytesize);
|
||||
}
|
||||
|
||||
bytesize_t
|
||||
Serial::getBytesize () const
|
||||
{
|
||||
return pimpl_->getBytesize ();
|
||||
}
|
||||
|
||||
void
|
||||
Serial::setParity (parity_t parity)
|
||||
{
|
||||
pimpl_->setParity (parity);
|
||||
}
|
||||
|
||||
parity_t
|
||||
Serial::getParity () const
|
||||
{
|
||||
return pimpl_->getParity ();
|
||||
}
|
||||
|
||||
void
|
||||
Serial::setStopbits (stopbits_t stopbits)
|
||||
{
|
||||
pimpl_->setStopbits (stopbits);
|
||||
}
|
||||
|
||||
stopbits_t
|
||||
Serial::getStopbits () const
|
||||
{
|
||||
return pimpl_->getStopbits ();
|
||||
}
|
||||
|
||||
void
|
||||
Serial::setFlowcontrol (flowcontrol_t flowcontrol)
|
||||
{
|
||||
pimpl_->setFlowcontrol (flowcontrol);
|
||||
}
|
||||
|
||||
flowcontrol_t
|
||||
Serial::getFlowcontrol () const
|
||||
{
|
||||
return pimpl_->getFlowcontrol ();
|
||||
}
|
||||
|
||||
void Serial::flush ()
|
||||
{
|
||||
ScopedReadLock rlock(this->pimpl_);
|
||||
ScopedWriteLock wlock(this->pimpl_);
|
||||
pimpl_->flush ();
|
||||
}
|
||||
|
||||
void Serial::flushInput ()
|
||||
{
|
||||
ScopedReadLock lock(this->pimpl_);
|
||||
pimpl_->flushInput ();
|
||||
}
|
||||
|
||||
void Serial::flushOutput ()
|
||||
{
|
||||
ScopedWriteLock lock(this->pimpl_);
|
||||
pimpl_->flushOutput ();
|
||||
}
|
||||
|
||||
void Serial::sendBreak (int duration)
|
||||
{
|
||||
pimpl_->sendBreak (duration);
|
||||
}
|
||||
|
||||
void Serial::setBreak (bool level)
|
||||
{
|
||||
pimpl_->setBreak (level);
|
||||
}
|
||||
|
||||
void Serial::setRTS (bool level)
|
||||
{
|
||||
pimpl_->setRTS (level);
|
||||
}
|
||||
|
||||
void Serial::setDTR (bool level)
|
||||
{
|
||||
pimpl_->setDTR (level);
|
||||
}
|
||||
|
||||
bool Serial::waitForChange()
|
||||
{
|
||||
return pimpl_->waitForChange();
|
||||
}
|
||||
|
||||
bool Serial::getCTS ()
|
||||
{
|
||||
return pimpl_->getCTS ();
|
||||
}
|
||||
|
||||
bool Serial::getDSR ()
|
||||
{
|
||||
return pimpl_->getDSR ();
|
||||
}
|
||||
|
||||
bool Serial::getRI ()
|
||||
{
|
||||
return pimpl_->getRI ();
|
||||
}
|
||||
|
||||
bool Serial::getCD ()
|
||||
{
|
||||
return pimpl_->getCD ();
|
||||
}
|
||||
@@ -0,0 +1,931 @@
|
||||
/* -*- mode: c; tab-width: 2; indent-tabs-mode: nil; -*-
|
||||
Copyright (c) 2012 Marcus Geelnard
|
||||
Copyright (c) 2013-2016 Evan Nemerson
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
*/
|
||||
|
||||
#include "../include/tinycthread.h"
|
||||
#include <stdlib.h>
|
||||
|
||||
/* Platform specific includes */
|
||||
#if defined(_TTHREAD_POSIX_)
|
||||
#include <signal.h>
|
||||
#include <sched.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/time.h>
|
||||
#include <errno.h>
|
||||
#elif defined(_TTHREAD_WIN32_)
|
||||
#include <process.h>
|
||||
#include <sys/timeb.h>
|
||||
#endif
|
||||
|
||||
/* Standard, good-to-have defines */
|
||||
#ifndef NULL
|
||||
#define NULL (void*)0
|
||||
#endif
|
||||
#ifndef TRUE
|
||||
#define TRUE 1
|
||||
#endif
|
||||
#ifndef FALSE
|
||||
#define FALSE 0
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
|
||||
int mtx_init(mtx_t *mtx, int type)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
mtx->mAlreadyLocked = FALSE;
|
||||
mtx->mRecursive = type & mtx_recursive;
|
||||
mtx->mTimed = type & mtx_timed;
|
||||
if (!mtx->mTimed)
|
||||
{
|
||||
InitializeCriticalSection(&(mtx->mHandle.cs));
|
||||
}
|
||||
else
|
||||
{
|
||||
mtx->mHandle.mut = CreateMutex(NULL, FALSE, NULL);
|
||||
if (mtx->mHandle.mut == NULL)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
}
|
||||
return thrd_success;
|
||||
#else
|
||||
int ret;
|
||||
pthread_mutexattr_t attr;
|
||||
pthread_mutexattr_init(&attr);
|
||||
if (type & mtx_recursive)
|
||||
{
|
||||
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
|
||||
}
|
||||
ret = pthread_mutex_init(mtx, &attr);
|
||||
pthread_mutexattr_destroy(&attr);
|
||||
return ret == 0 ? thrd_success : thrd_error;
|
||||
#endif
|
||||
}
|
||||
|
||||
void mtx_destroy(mtx_t *mtx)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
if (!mtx->mTimed)
|
||||
{
|
||||
DeleteCriticalSection(&(mtx->mHandle.cs));
|
||||
}
|
||||
else
|
||||
{
|
||||
CloseHandle(mtx->mHandle.mut);
|
||||
}
|
||||
#else
|
||||
pthread_mutex_destroy(mtx);
|
||||
#endif
|
||||
}
|
||||
|
||||
int mtx_lock(mtx_t *mtx)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
if (!mtx->mTimed)
|
||||
{
|
||||
EnterCriticalSection(&(mtx->mHandle.cs));
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (WaitForSingleObject(mtx->mHandle.mut, INFINITE))
|
||||
{
|
||||
case WAIT_OBJECT_0:
|
||||
break;
|
||||
case WAIT_ABANDONED:
|
||||
default:
|
||||
return thrd_error;
|
||||
}
|
||||
}
|
||||
|
||||
if (!mtx->mRecursive)
|
||||
{
|
||||
while(mtx->mAlreadyLocked) Sleep(1); /* Simulate deadlock... */
|
||||
mtx->mAlreadyLocked = TRUE;
|
||||
}
|
||||
return thrd_success;
|
||||
#else
|
||||
return pthread_mutex_lock(mtx) == 0 ? thrd_success : thrd_error;
|
||||
#endif
|
||||
}
|
||||
|
||||
int mtx_timedlock(mtx_t *mtx, const struct timespec *ts)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
struct timespec current_ts;
|
||||
DWORD timeoutMs;
|
||||
|
||||
if (!mtx->mTimed)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
|
||||
timespec_get(¤t_ts, TIME_UTC);
|
||||
|
||||
if ((current_ts.tv_sec > ts->tv_sec) || ((current_ts.tv_sec == ts->tv_sec) && (current_ts.tv_nsec >= ts->tv_nsec)))
|
||||
{
|
||||
timeoutMs = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
timeoutMs = (DWORD)(ts->tv_sec - current_ts.tv_sec) * 1000;
|
||||
timeoutMs += (ts->tv_nsec - current_ts.tv_nsec) / 1000000;
|
||||
timeoutMs += 1;
|
||||
}
|
||||
|
||||
/* TODO: the timeout for WaitForSingleObject doesn't include time
|
||||
while the computer is asleep. */
|
||||
switch (WaitForSingleObject(mtx->mHandle.mut, timeoutMs))
|
||||
{
|
||||
case WAIT_OBJECT_0:
|
||||
break;
|
||||
case WAIT_TIMEOUT:
|
||||
return thrd_timedout;
|
||||
case WAIT_ABANDONED:
|
||||
default:
|
||||
return thrd_error;
|
||||
}
|
||||
|
||||
if (!mtx->mRecursive)
|
||||
{
|
||||
while(mtx->mAlreadyLocked) Sleep(1); /* Simulate deadlock... */
|
||||
mtx->mAlreadyLocked = TRUE;
|
||||
}
|
||||
|
||||
return thrd_success;
|
||||
#elif defined(_POSIX_TIMEOUTS) && (_POSIX_TIMEOUTS >= 200112L) && defined(_POSIX_THREADS) && (_POSIX_THREADS >= 200112L)
|
||||
switch (pthread_mutex_timedlock(mtx, ts)) {
|
||||
case 0:
|
||||
return thrd_success;
|
||||
case ETIMEDOUT:
|
||||
return thrd_timedout;
|
||||
default:
|
||||
return thrd_error;
|
||||
}
|
||||
#else
|
||||
int rc;
|
||||
struct timespec cur, dur;
|
||||
|
||||
/* Try to acquire the lock and, if we fail, sleep for 5ms. */
|
||||
while ((rc = pthread_mutex_trylock (mtx)) == EBUSY) {
|
||||
timespec_get(&cur, TIME_UTC);
|
||||
|
||||
if ((cur.tv_sec > ts->tv_sec) || ((cur.tv_sec == ts->tv_sec) && (cur.tv_nsec >= ts->tv_nsec)))
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
dur.tv_sec = ts->tv_sec - cur.tv_sec;
|
||||
dur.tv_nsec = ts->tv_nsec - cur.tv_nsec;
|
||||
if (dur.tv_nsec < 0)
|
||||
{
|
||||
dur.tv_sec--;
|
||||
dur.tv_nsec += 1000000000;
|
||||
}
|
||||
|
||||
if ((dur.tv_sec != 0) || (dur.tv_nsec > 5000000))
|
||||
{
|
||||
dur.tv_sec = 0;
|
||||
dur.tv_nsec = 5000000;
|
||||
}
|
||||
|
||||
nanosleep(&dur, NULL);
|
||||
}
|
||||
|
||||
switch (rc) {
|
||||
case 0:
|
||||
return thrd_success;
|
||||
case ETIMEDOUT:
|
||||
case EBUSY:
|
||||
return thrd_timedout;
|
||||
default:
|
||||
return thrd_error;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
int mtx_trylock(mtx_t *mtx)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
int ret;
|
||||
|
||||
if (!mtx->mTimed)
|
||||
{
|
||||
ret = TryEnterCriticalSection(&(mtx->mHandle.cs)) ? thrd_success : thrd_busy;
|
||||
}
|
||||
else
|
||||
{
|
||||
ret = (WaitForSingleObject(mtx->mHandle.mut, 0) == WAIT_OBJECT_0) ? thrd_success : thrd_busy;
|
||||
}
|
||||
|
||||
if ((!mtx->mRecursive) && (ret == thrd_success))
|
||||
{
|
||||
if (mtx->mAlreadyLocked)
|
||||
{
|
||||
LeaveCriticalSection(&(mtx->mHandle.cs));
|
||||
ret = thrd_busy;
|
||||
}
|
||||
else
|
||||
{
|
||||
mtx->mAlreadyLocked = TRUE;
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
#else
|
||||
return (pthread_mutex_trylock(mtx) == 0) ? thrd_success : thrd_busy;
|
||||
#endif
|
||||
}
|
||||
|
||||
int mtx_unlock(mtx_t *mtx)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
mtx->mAlreadyLocked = FALSE;
|
||||
if (!mtx->mTimed)
|
||||
{
|
||||
LeaveCriticalSection(&(mtx->mHandle.cs));
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!ReleaseMutex(mtx->mHandle.mut))
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
}
|
||||
return thrd_success;
|
||||
#else
|
||||
return pthread_mutex_unlock(mtx) == 0 ? thrd_success : thrd_error;;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
#define _CONDITION_EVENT_ONE 0
|
||||
#define _CONDITION_EVENT_ALL 1
|
||||
#endif
|
||||
|
||||
int cnd_init(cnd_t *cond)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
cond->mWaitersCount = 0;
|
||||
|
||||
/* Init critical section */
|
||||
InitializeCriticalSection(&cond->mWaitersCountLock);
|
||||
|
||||
/* Init events */
|
||||
cond->mEvents[_CONDITION_EVENT_ONE] = CreateEvent(NULL, FALSE, FALSE, NULL);
|
||||
if (cond->mEvents[_CONDITION_EVENT_ONE] == NULL)
|
||||
{
|
||||
cond->mEvents[_CONDITION_EVENT_ALL] = NULL;
|
||||
return thrd_error;
|
||||
}
|
||||
cond->mEvents[_CONDITION_EVENT_ALL] = CreateEvent(NULL, TRUE, FALSE, NULL);
|
||||
if (cond->mEvents[_CONDITION_EVENT_ALL] == NULL)
|
||||
{
|
||||
CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]);
|
||||
cond->mEvents[_CONDITION_EVENT_ONE] = NULL;
|
||||
return thrd_error;
|
||||
}
|
||||
|
||||
return thrd_success;
|
||||
#else
|
||||
return pthread_cond_init(cond, NULL) == 0 ? thrd_success : thrd_error;
|
||||
#endif
|
||||
}
|
||||
|
||||
void cnd_destroy(cnd_t *cond)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
if (cond->mEvents[_CONDITION_EVENT_ONE] != NULL)
|
||||
{
|
||||
CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]);
|
||||
}
|
||||
if (cond->mEvents[_CONDITION_EVENT_ALL] != NULL)
|
||||
{
|
||||
CloseHandle(cond->mEvents[_CONDITION_EVENT_ALL]);
|
||||
}
|
||||
DeleteCriticalSection(&cond->mWaitersCountLock);
|
||||
#else
|
||||
pthread_cond_destroy(cond);
|
||||
#endif
|
||||
}
|
||||
|
||||
int cnd_signal(cnd_t *cond)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
int haveWaiters;
|
||||
|
||||
/* Are there any waiters? */
|
||||
EnterCriticalSection(&cond->mWaitersCountLock);
|
||||
haveWaiters = (cond->mWaitersCount > 0);
|
||||
LeaveCriticalSection(&cond->mWaitersCountLock);
|
||||
|
||||
/* If we have any waiting threads, send them a signal */
|
||||
if(haveWaiters)
|
||||
{
|
||||
if (SetEvent(cond->mEvents[_CONDITION_EVENT_ONE]) == 0)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
}
|
||||
|
||||
return thrd_success;
|
||||
#else
|
||||
return pthread_cond_signal(cond) == 0 ? thrd_success : thrd_error;
|
||||
#endif
|
||||
}
|
||||
|
||||
int cnd_broadcast(cnd_t *cond)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
int haveWaiters;
|
||||
|
||||
/* Are there any waiters? */
|
||||
EnterCriticalSection(&cond->mWaitersCountLock);
|
||||
haveWaiters = (cond->mWaitersCount > 0);
|
||||
LeaveCriticalSection(&cond->mWaitersCountLock);
|
||||
|
||||
/* If we have any waiting threads, send them a signal */
|
||||
if(haveWaiters)
|
||||
{
|
||||
if (SetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
}
|
||||
|
||||
return thrd_success;
|
||||
#else
|
||||
return pthread_cond_broadcast(cond) == 0 ? thrd_success : thrd_error;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
static int _cnd_timedwait_win32(cnd_t *cond, mtx_t *mtx, DWORD timeout)
|
||||
{
|
||||
DWORD result;
|
||||
int lastWaiter;
|
||||
|
||||
/* Increment number of waiters */
|
||||
EnterCriticalSection(&cond->mWaitersCountLock);
|
||||
++ cond->mWaitersCount;
|
||||
LeaveCriticalSection(&cond->mWaitersCountLock);
|
||||
|
||||
/* Release the mutex while waiting for the condition (will decrease
|
||||
the number of waiters when done)... */
|
||||
mtx_unlock(mtx);
|
||||
|
||||
/* Wait for either event to become signaled due to cnd_signal() or
|
||||
cnd_broadcast() being called */
|
||||
result = WaitForMultipleObjects(2, cond->mEvents, FALSE, timeout);
|
||||
if (result == WAIT_TIMEOUT)
|
||||
{
|
||||
/* The mutex is locked again before the function returns, even if an error occurred */
|
||||
mtx_lock(mtx);
|
||||
return thrd_timedout;
|
||||
}
|
||||
else if (result == WAIT_FAILED)
|
||||
{
|
||||
/* The mutex is locked again before the function returns, even if an error occurred */
|
||||
mtx_lock(mtx);
|
||||
return thrd_error;
|
||||
}
|
||||
|
||||
/* Check if we are the last waiter */
|
||||
EnterCriticalSection(&cond->mWaitersCountLock);
|
||||
-- cond->mWaitersCount;
|
||||
lastWaiter = (result == (WAIT_OBJECT_0 + _CONDITION_EVENT_ALL)) &&
|
||||
(cond->mWaitersCount == 0);
|
||||
LeaveCriticalSection(&cond->mWaitersCountLock);
|
||||
|
||||
/* If we are the last waiter to be notified to stop waiting, reset the event */
|
||||
if (lastWaiter)
|
||||
{
|
||||
if (ResetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0)
|
||||
{
|
||||
/* The mutex is locked again before the function returns, even if an error occurred */
|
||||
mtx_lock(mtx);
|
||||
return thrd_error;
|
||||
}
|
||||
}
|
||||
|
||||
/* Re-acquire the mutex */
|
||||
mtx_lock(mtx);
|
||||
|
||||
return thrd_success;
|
||||
}
|
||||
#endif
|
||||
|
||||
int cnd_wait(cnd_t *cond, mtx_t *mtx)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
return _cnd_timedwait_win32(cond, mtx, INFINITE);
|
||||
#else
|
||||
return pthread_cond_wait(cond, mtx) == 0 ? thrd_success : thrd_error;
|
||||
#endif
|
||||
}
|
||||
|
||||
int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
struct timespec now;
|
||||
if (timespec_get(&now, TIME_UTC) == TIME_UTC)
|
||||
{
|
||||
unsigned long long nowInMilliseconds = now.tv_sec * 1000 + now.tv_nsec / 1000000;
|
||||
unsigned long long tsInMilliseconds = ts->tv_sec * 1000 + ts->tv_nsec / 1000000;
|
||||
DWORD delta = (tsInMilliseconds > nowInMilliseconds) ?
|
||||
(DWORD)(tsInMilliseconds - nowInMilliseconds) : 0;
|
||||
return _cnd_timedwait_win32(cond, mtx, delta);
|
||||
}
|
||||
else
|
||||
return thrd_error;
|
||||
#else
|
||||
int ret;
|
||||
ret = pthread_cond_timedwait(cond, mtx, ts);
|
||||
if (ret == ETIMEDOUT)
|
||||
{
|
||||
return thrd_timedout;
|
||||
}
|
||||
return ret == 0 ? thrd_success : thrd_error;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
struct TinyCThreadTSSData {
|
||||
void* value;
|
||||
tss_t key;
|
||||
struct TinyCThreadTSSData* next;
|
||||
};
|
||||
|
||||
static tss_dtor_t _tinycthread_tss_dtors[1088] = { NULL, };
|
||||
|
||||
static _Thread_local struct TinyCThreadTSSData* _tinycthread_tss_head = NULL;
|
||||
static _Thread_local struct TinyCThreadTSSData* _tinycthread_tss_tail = NULL;
|
||||
|
||||
static void _tinycthread_tss_cleanup (void);
|
||||
|
||||
static void _tinycthread_tss_cleanup (void) {
|
||||
struct TinyCThreadTSSData* data;
|
||||
int iteration;
|
||||
unsigned int again = 1;
|
||||
void* value;
|
||||
|
||||
for (iteration = 0 ; iteration < TSS_DTOR_ITERATIONS && again > 0 ; iteration++)
|
||||
{
|
||||
again = 0;
|
||||
for (data = _tinycthread_tss_head ; data != NULL ; data = data->next)
|
||||
{
|
||||
if (data->value != NULL)
|
||||
{
|
||||
value = data->value;
|
||||
data->value = NULL;
|
||||
|
||||
if (_tinycthread_tss_dtors[data->key] != NULL)
|
||||
{
|
||||
again = 1;
|
||||
_tinycthread_tss_dtors[data->key](value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
while (_tinycthread_tss_head != NULL) {
|
||||
data = _tinycthread_tss_head->next;
|
||||
free (_tinycthread_tss_head);
|
||||
_tinycthread_tss_head = data;
|
||||
}
|
||||
_tinycthread_tss_head = NULL;
|
||||
_tinycthread_tss_tail = NULL;
|
||||
}
|
||||
|
||||
static void NTAPI _tinycthread_tss_callback(PVOID h, DWORD dwReason, PVOID pv)
|
||||
{
|
||||
(void)h;
|
||||
(void)pv;
|
||||
|
||||
if (_tinycthread_tss_head != NULL && (dwReason == DLL_THREAD_DETACH || dwReason == DLL_PROCESS_DETACH))
|
||||
{
|
||||
_tinycthread_tss_cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
#ifdef _M_X64
|
||||
#pragma const_seg(".CRT$XLB")
|
||||
#else
|
||||
#pragma data_seg(".CRT$XLB")
|
||||
#endif
|
||||
PIMAGE_TLS_CALLBACK p_thread_callback = _tinycthread_tss_callback;
|
||||
#ifdef _M_X64
|
||||
#pragma data_seg()
|
||||
#else
|
||||
#pragma const_seg()
|
||||
#endif
|
||||
#else
|
||||
PIMAGE_TLS_CALLBACK p_thread_callback __attribute__((section(".CRT$XLB"))) = _tinycthread_tss_callback;
|
||||
#endif
|
||||
|
||||
#endif /* defined(_TTHREAD_WIN32_) */
|
||||
|
||||
/** Information to pass to the new thread (what to run). */
|
||||
typedef struct {
|
||||
thrd_start_t mFunction; /**< Pointer to the function to be executed. */
|
||||
void * mArg; /**< Function argument for the thread function. */
|
||||
} _thread_start_info;
|
||||
|
||||
/* Thread wrapper function. */
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
static DWORD WINAPI _thrd_wrapper_function(LPVOID aArg)
|
||||
#elif defined(_TTHREAD_POSIX_)
|
||||
static void * _thrd_wrapper_function(void * aArg)
|
||||
#endif
|
||||
{
|
||||
thrd_start_t fun;
|
||||
void *arg;
|
||||
int res;
|
||||
|
||||
/* Get thread startup information */
|
||||
_thread_start_info *ti = (_thread_start_info *) aArg;
|
||||
fun = ti->mFunction;
|
||||
arg = ti->mArg;
|
||||
|
||||
/* The thread is responsible for freeing the startup information */
|
||||
free((void *)ti);
|
||||
|
||||
/* Call the actual client thread function */
|
||||
res = fun(arg);
|
||||
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
if (_tinycthread_tss_head != NULL)
|
||||
{
|
||||
_tinycthread_tss_cleanup();
|
||||
}
|
||||
|
||||
return (DWORD)res;
|
||||
#else
|
||||
return (void*)(intptr_t)res;
|
||||
#endif
|
||||
}
|
||||
|
||||
int thrd_create(thrd_t *thr, thrd_start_t func, void *arg)
|
||||
{
|
||||
/* Fill out the thread startup information (passed to the thread wrapper,
|
||||
which will eventually free it) */
|
||||
_thread_start_info* ti = (_thread_start_info*)malloc(sizeof(_thread_start_info));
|
||||
if (ti == NULL)
|
||||
{
|
||||
return thrd_nomem;
|
||||
}
|
||||
ti->mFunction = func;
|
||||
ti->mArg = arg;
|
||||
|
||||
/* Create the thread */
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
*thr = CreateThread(NULL, 0, _thrd_wrapper_function, (LPVOID) ti, 0, NULL);
|
||||
#elif defined(_TTHREAD_POSIX_)
|
||||
if(pthread_create(thr, NULL, _thrd_wrapper_function, (void *)ti) != 0)
|
||||
{
|
||||
*thr = 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Did we fail to create the thread? */
|
||||
if(!*thr)
|
||||
{
|
||||
free(ti);
|
||||
return thrd_error;
|
||||
}
|
||||
|
||||
return thrd_success;
|
||||
}
|
||||
|
||||
thrd_t thrd_current(void)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
return GetCurrentThread();
|
||||
#else
|
||||
return pthread_self();
|
||||
#endif
|
||||
}
|
||||
|
||||
int thrd_detach(thrd_t thr)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
/* https://stackoverflow.com/questions/12744324/how-to-detach-a-thread-on-windows-c#answer-12746081 */
|
||||
return CloseHandle(thr) != 0 ? thrd_success : thrd_error;
|
||||
#else
|
||||
return pthread_detach(thr) == 0 ? thrd_success : thrd_error;
|
||||
#endif
|
||||
}
|
||||
|
||||
int thrd_equal(thrd_t thr0, thrd_t thr1)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
return GetThreadId(thr0) == GetThreadId(thr1);
|
||||
#else
|
||||
return pthread_equal(thr0, thr1);
|
||||
#endif
|
||||
}
|
||||
|
||||
void thrd_exit(int res)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
if (_tinycthread_tss_head != NULL)
|
||||
{
|
||||
_tinycthread_tss_cleanup();
|
||||
}
|
||||
|
||||
ExitThread((DWORD)res);
|
||||
#else
|
||||
pthread_exit((void*)(intptr_t)res);
|
||||
#endif
|
||||
}
|
||||
|
||||
int thrd_join(thrd_t thr, int *res)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
DWORD dwRes;
|
||||
|
||||
if (WaitForSingleObject(thr, INFINITE) == WAIT_FAILED)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
if (res != NULL)
|
||||
{
|
||||
if (GetExitCodeThread(thr, &dwRes) != 0)
|
||||
{
|
||||
*res = (int) dwRes;
|
||||
}
|
||||
else
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
}
|
||||
CloseHandle(thr);
|
||||
#elif defined(_TTHREAD_POSIX_)
|
||||
void *pres;
|
||||
if (pthread_join(thr, &pres) != 0)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
if (res != NULL)
|
||||
{
|
||||
*res = (int)(intptr_t)pres;
|
||||
}
|
||||
#endif
|
||||
return thrd_success;
|
||||
}
|
||||
|
||||
int thrd_sleep(const struct timespec *duration, struct timespec *remaining)
|
||||
{
|
||||
#if !defined(_TTHREAD_WIN32_)
|
||||
int res = nanosleep(duration, remaining);
|
||||
if (res == 0) {
|
||||
return 0;
|
||||
} else if (errno == EINTR) {
|
||||
return -1;
|
||||
} else {
|
||||
return -2;
|
||||
}
|
||||
#else
|
||||
struct timespec start;
|
||||
DWORD t;
|
||||
|
||||
timespec_get(&start, TIME_UTC);
|
||||
|
||||
t = SleepEx((DWORD)(duration->tv_sec * 1000 +
|
||||
duration->tv_nsec / 1000000 +
|
||||
(((duration->tv_nsec % 1000000) == 0) ? 0 : 1)),
|
||||
TRUE);
|
||||
|
||||
if (t == 0) {
|
||||
return 0;
|
||||
} else {
|
||||
if (remaining != NULL) {
|
||||
timespec_get(remaining, TIME_UTC);
|
||||
remaining->tv_sec -= start.tv_sec;
|
||||
remaining->tv_nsec -= start.tv_nsec;
|
||||
if (remaining->tv_nsec < 0)
|
||||
{
|
||||
remaining->tv_nsec += 1000000000;
|
||||
remaining->tv_sec -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
return (t == WAIT_IO_COMPLETION) ? -1 : -2;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void thrd_yield(void)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
Sleep(0);
|
||||
#else
|
||||
sched_yield();
|
||||
#endif
|
||||
}
|
||||
|
||||
int tss_create(tss_t *key, tss_dtor_t dtor)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
*key = TlsAlloc();
|
||||
if (*key == TLS_OUT_OF_INDEXES)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
_tinycthread_tss_dtors[*key] = dtor;
|
||||
#else
|
||||
if (pthread_key_create(key, dtor) != 0)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
#endif
|
||||
return thrd_success;
|
||||
}
|
||||
|
||||
void tss_delete(tss_t key)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*) TlsGetValue (key);
|
||||
struct TinyCThreadTSSData* prev = NULL;
|
||||
if (data != NULL)
|
||||
{
|
||||
if (data == _tinycthread_tss_head)
|
||||
{
|
||||
_tinycthread_tss_head = data->next;
|
||||
}
|
||||
else
|
||||
{
|
||||
prev = _tinycthread_tss_head;
|
||||
if (prev != NULL)
|
||||
{
|
||||
while (prev->next != data)
|
||||
{
|
||||
prev = prev->next;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (data == _tinycthread_tss_tail)
|
||||
{
|
||||
_tinycthread_tss_tail = prev;
|
||||
}
|
||||
|
||||
free (data);
|
||||
}
|
||||
_tinycthread_tss_dtors[key] = NULL;
|
||||
TlsFree(key);
|
||||
#else
|
||||
pthread_key_delete(key);
|
||||
#endif
|
||||
}
|
||||
|
||||
void *tss_get(tss_t key)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*)TlsGetValue(key);
|
||||
if (data == NULL)
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
return data->value;
|
||||
#else
|
||||
return pthread_getspecific(key);
|
||||
#endif
|
||||
}
|
||||
|
||||
int tss_set(tss_t key, void *val)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*)TlsGetValue(key);
|
||||
if (data == NULL)
|
||||
{
|
||||
data = (struct TinyCThreadTSSData*)malloc(sizeof(struct TinyCThreadTSSData));
|
||||
if (data == NULL)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
|
||||
data->value = NULL;
|
||||
data->key = key;
|
||||
data->next = NULL;
|
||||
|
||||
if (_tinycthread_tss_tail != NULL)
|
||||
{
|
||||
_tinycthread_tss_tail->next = data;
|
||||
}
|
||||
else
|
||||
{
|
||||
_tinycthread_tss_tail = data;
|
||||
}
|
||||
|
||||
if (_tinycthread_tss_head == NULL)
|
||||
{
|
||||
_tinycthread_tss_head = data;
|
||||
}
|
||||
|
||||
if (!TlsSetValue(key, data))
|
||||
{
|
||||
free (data);
|
||||
return thrd_error;
|
||||
}
|
||||
}
|
||||
data->value = val;
|
||||
#else
|
||||
if (pthread_setspecific(key, val) != 0)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
#endif
|
||||
return thrd_success;
|
||||
}
|
||||
|
||||
#if defined(_TTHREAD_EMULATE_TIMESPEC_GET_)
|
||||
int _tthread_timespec_get(struct timespec *ts, int base)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
struct _timeb tb;
|
||||
#elif !defined(CLOCK_REALTIME)
|
||||
struct timeval tv;
|
||||
#endif
|
||||
|
||||
if (base != TIME_UTC)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
_ftime_s(&tb);
|
||||
ts->tv_sec = (time_t)tb.time;
|
||||
ts->tv_nsec = 1000000L * (long)tb.millitm;
|
||||
#elif defined(CLOCK_REALTIME)
|
||||
base = (clock_gettime(CLOCK_REALTIME, ts) == 0) ? base : 0;
|
||||
#else
|
||||
gettimeofday(&tv, NULL);
|
||||
ts->tv_sec = (time_t)tv.tv_sec;
|
||||
ts->tv_nsec = 1000L * (long)tv.tv_usec;
|
||||
#endif
|
||||
|
||||
return base;
|
||||
}
|
||||
#endif /* _TTHREAD_EMULATE_TIMESPEC_GET_ */
|
||||
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
void call_once(once_flag *flag, void (*func)(void))
|
||||
{
|
||||
/* The idea here is that we use a spin lock (via the
|
||||
InterlockedCompareExchange function) to restrict access to the
|
||||
critical section until we have initialized it, then we use the
|
||||
critical section to block until the callback has completed
|
||||
execution. */
|
||||
while (flag->status < 3)
|
||||
{
|
||||
switch (flag->status)
|
||||
{
|
||||
case 0:
|
||||
if (InterlockedCompareExchange (&(flag->status), 1, 0) == 0) {
|
||||
InitializeCriticalSection(&(flag->lock));
|
||||
EnterCriticalSection(&(flag->lock));
|
||||
flag->status = 2;
|
||||
func();
|
||||
flag->status = 3;
|
||||
LeaveCriticalSection(&(flag->lock));
|
||||
return;
|
||||
}
|
||||
break;
|
||||
case 1:
|
||||
break;
|
||||
case 2:
|
||||
EnterCriticalSection(&(flag->lock));
|
||||
LeaveCriticalSection(&(flag->lock));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif /* defined(_TTHREAD_WIN32_) */
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
#
|
||||
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
|
||||
# Run `pod lib lint flserial.podspec` to validate before publishing.
|
||||
#
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'flserial'
|
||||
s.version = '0.0.1'
|
||||
s.summary = 'A new Flutter FFI plugin project.'
|
||||
s.description = <<-DESC
|
||||
A new Flutter FFI plugin project.
|
||||
DESC
|
||||
s.homepage = 'http://example.com'
|
||||
s.license = { :file => '../LICENSE' }
|
||||
s.author = { 'Your Company' => 'email@example.com' }
|
||||
|
||||
# This will ensure the source files in Classes/ are included in the native
|
||||
# builds of apps using this FFI plugin. Podspec does not support relative
|
||||
# paths, so Classes contains a forwarder C file that relatively imports
|
||||
# `../src/*` so that the C sources can be shared among all target platforms.
|
||||
s.source = { :path => '.' }
|
||||
s.source_files = 'Classes/**/*'
|
||||
s.dependency 'FlutterMacOS'
|
||||
|
||||
s.platform = :osx, '10.11'
|
||||
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
|
||||
s.swift_version = '5.0'
|
||||
end
|
||||
Vendored
+80
@@ -0,0 +1,80 @@
|
||||
name: flserial
|
||||
description: "Flutter Serial Port Plugin FFI based on great C library. Useful to communicate with RS232 devices."
|
||||
version: 0.3.5
|
||||
homepage: https://github.com/grzesl/flserial
|
||||
|
||||
environment:
|
||||
sdk: ^3.4.0
|
||||
flutter: '>=3.3.0'
|
||||
|
||||
dependencies:
|
||||
flutter:
|
||||
sdk: flutter
|
||||
plugin_platform_interface: ^2.0.2
|
||||
ffi: ^2.1.3
|
||||
test: ^1.25.7
|
||||
|
||||
dev_dependencies:
|
||||
ffigen: ^19.1.0
|
||||
flutter_test:
|
||||
sdk: flutter
|
||||
flutter_lints: ^5.0.0
|
||||
|
||||
# For information on the generic Dart part of this file, see the
|
||||
# following page: https://dart.dev/tools/pub/pubspec
|
||||
|
||||
# The following section is specific to Flutter packages.
|
||||
flutter:
|
||||
# This section identifies this Flutter project as a plugin project.
|
||||
# The 'pluginClass' specifies the class (in Java, Kotlin, Swift, Objective-C, etc.)
|
||||
# which should be registered in the plugin registry. This is required for
|
||||
# using method channels.
|
||||
# The Android 'package' specifies package in which the registered class is.
|
||||
# This is required for using method channels on Android.
|
||||
# The 'ffiPlugin' specifies that native code should be built and bundled.
|
||||
# This is required for using `dart:ffi`.
|
||||
# All these are used by the tooling to maintain consistency when
|
||||
# adding or updating assets for this project.
|
||||
#
|
||||
# Please refer to README.md for a detailed explanation.
|
||||
plugin:
|
||||
platforms:
|
||||
macos:
|
||||
ffiPlugin: true
|
||||
android:
|
||||
ffiPlugin: true
|
||||
linux:
|
||||
ffiPlugin: true
|
||||
windows:
|
||||
ffiPlugin: true
|
||||
|
||||
# To add assets to your plugin package, add an assets section, like this:
|
||||
# assets:
|
||||
# - images/a_dot_burr.jpeg
|
||||
# - images/a_dot_ham.jpeg
|
||||
#
|
||||
# For details regarding assets in packages, see
|
||||
# https://flutter.dev/to/asset-from-package
|
||||
#
|
||||
# An image asset can refer to one or more resolution-specific "variants", see
|
||||
# https://flutter.dev/to/resolution-aware-images
|
||||
|
||||
# To add custom fonts to your plugin package, add a fonts section here,
|
||||
# in this "flutter" section. Each entry in this list should have a
|
||||
# "family" key with the font family name, and a "fonts" key with a
|
||||
# list giving the asset and other descriptors for the font. For
|
||||
# example:
|
||||
# fonts:
|
||||
# - family: Schyler
|
||||
# fonts:
|
||||
# - asset: fonts/Schyler-Regular.ttf
|
||||
# - asset: fonts/Schyler-Italic.ttf
|
||||
# style: italic
|
||||
# - family: Trajan Pro
|
||||
# fonts:
|
||||
# - asset: fonts/TrajanPro.ttf
|
||||
# - asset: fonts/TrajanPro_Bold.ttf
|
||||
# weight: 700
|
||||
#
|
||||
# For details regarding fonts in packages, see
|
||||
# https://flutter.dev/to/font-from-package
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
# The Flutter tooling requires that developers have CMake 3.10 or later
|
||||
# installed. You should not increase this version, as doing so will cause
|
||||
# the plugin to fail to compile for some customers of the plugin.
|
||||
cmake_minimum_required(VERSION 3.10)
|
||||
|
||||
project(flserial_library VERSION 0.3.5 LANGUAGES C CXX)
|
||||
|
||||
if(MSVC)
|
||||
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
|
||||
endif()
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
set(SRC_FILES
|
||||
"native_libs/src/serial.cpp"
|
||||
"native_libs/src/tinycthread.c"
|
||||
"native_libs/src/ringbuffer.c"
|
||||
"flserial.cpp"
|
||||
"flserial.def"
|
||||
)
|
||||
|
||||
if(APPLE)
|
||||
list(APPEND SRC_FILES native_libs/src/impl/unix.cpp)
|
||||
list(APPEND SRC_FILES native_libs/src/impl/list_ports/list_ports_osx.cpp)
|
||||
elseif(ANDROID)
|
||||
list(APPEND SRC_FILES native_libs/src/cglob.c)
|
||||
list(APPEND SRC_FILES native_libs/src/impl/unix.cpp)
|
||||
list(APPEND SRC_FILES native_libs/src/impl/list_ports/list_ports_linux.cpp)
|
||||
elseif(UNIX)
|
||||
list(APPEND SRC_FILES native_libs/src/impl/unix.cpp)
|
||||
list(APPEND SRC_FILES native_libs/src/impl/list_ports/list_ports_linux.cpp)
|
||||
else()
|
||||
list(APPEND SRC_FILES native_libs/src/impl/win.cpp)
|
||||
list(APPEND SRC_FILES native_libs/src/impl/list_ports/list_ports_win.cpp)
|
||||
endif()
|
||||
|
||||
add_library(flserial SHARED ${SRC_FILES})
|
||||
|
||||
if(APPLE)
|
||||
elseif(ANDROID)
|
||||
target_link_options(flserial PRIVATE "-Wl,-z,max-page-size=16384")
|
||||
elseif(UNIX)
|
||||
target_link_libraries(flserial rt pthread)
|
||||
else()
|
||||
target_link_libraries(flserial setupapi)
|
||||
endif()
|
||||
|
||||
|
||||
|
||||
|
||||
include_directories(native_libs/include native_libs/include/serial)
|
||||
|
||||
set_target_properties(flserial PROPERTIES
|
||||
PUBLIC_HEADER flserial.h
|
||||
OUTPUT_NAME "flserial"
|
||||
)
|
||||
|
||||
target_compile_definitions(flserial PUBLIC DART_SHARED_LIB)
|
||||
+391
@@ -0,0 +1,391 @@
|
||||
#include "flserial.h"
|
||||
#include "native_libs/include/serial/serial.h"
|
||||
#include "native_libs/include/tinycthread.h"
|
||||
#include "native_libs/include/ringbuffer.h"
|
||||
#include <iostream>
|
||||
|
||||
#define FL_SERIAL_BUFF_LEN (8 * 1024)
|
||||
|
||||
typedef struct _flserial_
|
||||
{
|
||||
char portname[MAX_PORT_NAME_LEN + 1];
|
||||
int baudrate;
|
||||
serial::Serial *serialport;
|
||||
enum FlError lasterror;
|
||||
char lasterrormsg[512];
|
||||
thrd_t cthread;
|
||||
int breakThread;
|
||||
ring_buffer_t cinfifo;
|
||||
ring_buffer_t coutfifo;
|
||||
char inbuff[FL_SERIAL_BUFF_LEN];
|
||||
char outbuff[FL_SERIAL_BUFF_LEN];
|
||||
mtx_t inFifo_mutex;
|
||||
mtx_t outFifo_mutex;
|
||||
flcallback callback;
|
||||
} FlSerial;
|
||||
|
||||
int SerialThread(void *aArg)
|
||||
{
|
||||
FlSerial *serial = (FlSerial *)aArg;
|
||||
ring_buffer_size_t res = 0;
|
||||
uint8_t buff[FL_SERIAL_BUFF_LEN];
|
||||
ring_buffer_size_t len = sizeof(buff);
|
||||
ring_buffer_size_t total = 0;
|
||||
int isEmpty = 0;
|
||||
|
||||
while (!serial->breakThread)
|
||||
{
|
||||
try
|
||||
{
|
||||
res = (int)serial->serialport->read((uint8_t *)buff, (size_t)len);
|
||||
if (res > 0)
|
||||
{
|
||||
mtx_lock(&serial->inFifo_mutex);
|
||||
ring_buffer_queue_arr(&serial->cinfifo, (const char *)buff, res);
|
||||
mtx_unlock(&serial->inFifo_mutex);
|
||||
total += res;
|
||||
if(!serial->serialport->available()){
|
||||
// fl_open starts this thread before Dart reaches
|
||||
// fl_set_callback. A companion that transmits as soon as
|
||||
// the port opens otherwise calls a null function pointer.
|
||||
while (serial->callback == nullptr && !serial->breakThread)
|
||||
{
|
||||
const struct timespec wait = {0, 1000000L};
|
||||
thrd_sleep(&wait, NULL);
|
||||
}
|
||||
if (serial->breakThread)
|
||||
break;
|
||||
serial->callback(0, total);
|
||||
total = 0;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
mtx_lock(&serial->outFifo_mutex);
|
||||
res = (ring_buffer_size_t)ring_buffer_dequeue_arr(&serial->coutfifo, (char *)buff, (int)len);
|
||||
mtx_unlock(&serial->outFifo_mutex);
|
||||
if (res > 0) {
|
||||
res = (int)serial->serialport->write((uint8_t*)buff, (size_t)res);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
catch (const serial::IOException &ioe)
|
||||
{
|
||||
serial->lasterror = FL_ERROR_IO;
|
||||
strncpy(serial->lasterrormsg , ioe.what(), sizeof(serial->lasterrormsg) - 1);
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
FlSerial *flserial_tab[MAX_PORT_COUNT];
|
||||
int flserial_count;
|
||||
int current_port;
|
||||
|
||||
/// Internal helper: close a single slot and null it out.
|
||||
/// Safe to call with a NULL entry — returns immediately.
|
||||
/// Sets breakThread=1 then calls thrd_join() so the SerialThread is
|
||||
/// guaranteed to have exited before this function returns. This is the
|
||||
/// critical ordering that prevents the Dart NativeCallable from being
|
||||
/// invoked after the isolate has freed it ("Callback invoked after it has
|
||||
/// been deleted").
|
||||
static void _fl_close_slot(int slot)
|
||||
{
|
||||
FlSerial *port = flserial_tab[slot];
|
||||
if (port == NULL)
|
||||
return;
|
||||
|
||||
port->breakThread = 1;
|
||||
|
||||
try
|
||||
{
|
||||
if (port->cthread != 0)
|
||||
thrd_join(port->cthread, NULL);
|
||||
|
||||
port->serialport->close();
|
||||
|
||||
mtx_destroy(&port->inFifo_mutex);
|
||||
mtx_destroy(&port->outFifo_mutex);
|
||||
}
|
||||
catch (const std::exception &)
|
||||
{
|
||||
}
|
||||
|
||||
delete port->serialport;
|
||||
port->serialport = NULL;
|
||||
delete port;
|
||||
flserial_tab[slot] = NULL;
|
||||
}
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_set_callback(int flh, flcallback cb)
|
||||
{
|
||||
FlSerial *port = flserial_tab[flh];
|
||||
port->callback = cb;
|
||||
return 0;
|
||||
}
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_init(int portCount)
|
||||
{
|
||||
if (portCount > MAX_PORT_COUNT)
|
||||
return 1;
|
||||
|
||||
flserial_count = portCount;
|
||||
current_port = -1;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_open(int flh, char *portname, int baudrate)
|
||||
{
|
||||
int porth = flh;
|
||||
|
||||
if (porth < 0)
|
||||
porth = ++current_port;
|
||||
|
||||
// If a previous FlSerial (and its SerialThread) is alive in this slot,
|
||||
// join and free it before overwriting. On Dart hot restart the isolate
|
||||
// dies without calling fl_close(), leaving the old thread running with a
|
||||
// dangling NativeCallable pointer. Joining here prevents the crash.
|
||||
_fl_close_slot(porth);
|
||||
|
||||
FlSerial *port = new FlSerial();
|
||||
port->breakThread = 0;
|
||||
port->callback = nullptr;
|
||||
port->cthread = 0;
|
||||
port->serialport = nullptr;
|
||||
|
||||
flserial_tab[porth] = port;
|
||||
|
||||
strncpy(port->portname, portname, MAX_PORT_NAME_LEN);
|
||||
|
||||
port->baudrate = baudrate;
|
||||
port->lasterror = FL_ERROR_OK;
|
||||
|
||||
port->serialport = new serial::Serial();
|
||||
#if !defined(__linux__) && !defined(__APPLE__)
|
||||
port->serialport->setTimeout(serial::Timeout(0, 2, 0, 0, 0));
|
||||
#endif // #if defined(__linux__)
|
||||
port->serialport->setPort(portname);
|
||||
port->serialport->setBaudrate(baudrate);
|
||||
|
||||
try
|
||||
{
|
||||
port->serialport->open();
|
||||
|
||||
ring_buffer_init(&port->cinfifo, port->inbuff, FL_SERIAL_BUFF_LEN );
|
||||
ring_buffer_init(&port->coutfifo, port->outbuff, FL_SERIAL_BUFF_LEN );
|
||||
|
||||
port->serialport->setBytesize(serial::bytesize_t::eightbits);
|
||||
port->serialport->setParity(serial::parity_t::parity_none);
|
||||
port->serialport->setStopbits(serial::stopbits_one);
|
||||
mtx_init(&port->inFifo_mutex, mtx_plain);
|
||||
mtx_init(&port->outFifo_mutex, mtx_plain);
|
||||
port->callback = nullptr;
|
||||
thrd_create(&port->cthread, SerialThread, (void *)port);
|
||||
}
|
||||
catch (const serial::IOException &ioe)
|
||||
{
|
||||
strncpy(port->lasterrormsg, ioe.what(), sizeof(port->lasterrormsg) - 1);
|
||||
|
||||
switch (ioe.getErrorNumber())
|
||||
{
|
||||
case 1:
|
||||
port->lasterror = FlError::FL_ERROR_PORT_NOT_EXIST;
|
||||
break;
|
||||
case 2:
|
||||
port->lasterror = FlError::FL_ERROR_PORT_ALLREADY_OPEN;
|
||||
break;
|
||||
default:
|
||||
port->lasterror = FlError::FL_ERROR_UNKNOW;
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (const std::exception)
|
||||
{
|
||||
port->lasterror = FlError::FL_ERROR_UNKNOW;
|
||||
}
|
||||
|
||||
return porth;
|
||||
}
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_ports(int index, int buffsize, char *buff)
|
||||
{
|
||||
auto list = serial::list_ports();
|
||||
if (serial::list_ports().size() <= index)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
serial::PortInfo info = list[index];
|
||||
return snprintf(buff, buffsize, "%s - %s - %s", info.port.c_str(), info.description.c_str(), info.hardware_id.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_read(int flh, int len, char *buff)
|
||||
{
|
||||
FlSerial *port = flserial_tab[flh];
|
||||
ring_buffer_size_t res = 0;
|
||||
|
||||
char *buf = NULL;
|
||||
ring_buffer_size_t size = 0;
|
||||
ring_buffer_size_t read = 0;
|
||||
|
||||
mtx_lock(&port->inFifo_mutex);
|
||||
read = ring_buffer_dequeue_arr(&port->cinfifo, buff, (ring_buffer_size_t) len);
|
||||
mtx_unlock(&port->inFifo_mutex);
|
||||
|
||||
return (int)read;
|
||||
}
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_write(int flh, int len, char *data)
|
||||
{
|
||||
FlSerial *port = flserial_tab[flh];
|
||||
int res = 0;
|
||||
try
|
||||
{
|
||||
mtx_lock(&port->outFifo_mutex);
|
||||
ring_buffer_queue_arr(&port->coutfifo, data, len);
|
||||
mtx_unlock(&port->outFifo_mutex);
|
||||
}
|
||||
catch (const std::exception &)
|
||||
{
|
||||
port->lasterror = FlError::FL_ERROR_PORT_ALLREADY_OPEN;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_close(int flh)
|
||||
{
|
||||
_fl_close_slot(flh);
|
||||
return 0;
|
||||
}
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_ctrl(int flh, FlCtrl param, int value)
|
||||
{
|
||||
|
||||
int result = -1;
|
||||
FlSerial *port = flserial_tab[flh];
|
||||
|
||||
try
|
||||
{
|
||||
switch (param)
|
||||
{
|
||||
case FL_CTRL_IS_PORT_OPEN:
|
||||
result = port->serialport->isOpen() ? 1 : 0;
|
||||
break;
|
||||
case FL_CTRL_LAST_ERROR:
|
||||
result = port->lasterror;
|
||||
break;
|
||||
case FL_CTRL_BREAK:
|
||||
port->serialport->setBreak();
|
||||
result = FL_ERROR_OK;
|
||||
break;
|
||||
case FL_CTRL_SET_RTS:
|
||||
port->serialport->setRTS(value > 0 ? true : false);
|
||||
result = FL_ERROR_OK;
|
||||
break;
|
||||
case FL_CTRL_GET_CTS:
|
||||
result = port->serialport->getCTS() ? 1 : 0;
|
||||
break;
|
||||
case FL_CTRL_SET_DTR:
|
||||
port->serialport->setDTR(value > 0 ? true : false);
|
||||
result = FL_ERROR_OK;
|
||||
break;
|
||||
case FL_CTRL_GET_DSR:
|
||||
result = port->serialport->getDSR() ? 1 : 0;
|
||||
break;
|
||||
|
||||
case FL_CTRL_SET_BYTESIZE_5:
|
||||
port->serialport->setBytesize(serial::bytesize_t::fivebits);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_BYTESIZE_6:
|
||||
port->serialport->setBytesize(serial::bytesize_t::sixbits);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_BYTESIZE_7:
|
||||
port->serialport->setBytesize(serial::bytesize_t::sevenbits);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_BYTESIZE_8:
|
||||
port->serialport->setBytesize(serial::bytesize_t::eightbits);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_PARITY_NONE:
|
||||
port->serialport->setParity(serial::parity_t::parity_none);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_PARITY_ODD:
|
||||
port->serialport->setParity(serial::parity_t::parity_odd);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_PARITY_EVEN:
|
||||
port->serialport->setParity(serial::parity_t::parity_even);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_PARITY_MARK:
|
||||
port->serialport->setParity(serial::parity_t::parity_mark);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_PARITY_SPACE:
|
||||
port->serialport->setParity(serial::parity_t::parity_space);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_STOPBITS_ONE:
|
||||
port->serialport->setStopbits(serial::stopbits_t::stopbits_one);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_STOPBITS_TWO:
|
||||
port->serialport->setStopbits(serial::stopbits_t::stopbits_two);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_STOPBITS_ONE_POINT_FIVE:
|
||||
port->serialport->setStopbits(serial::stopbits_t::stopbits_one_point_five);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_FLOWCONTROL_NONE:
|
||||
port->serialport->setFlowcontrol(serial::flowcontrol_t::flowcontrol_none);
|
||||
result = 1;
|
||||
break;
|
||||
case FL_CTRL_SET_FLOWCONTROL_HARDWARE:
|
||||
port->serialport->setFlowcontrol(serial::flowcontrol_t::flowcontrol_hardware);
|
||||
result = 1;
|
||||
break;
|
||||
port->serialport->setFlowcontrol(serial::flowcontrol_t::flowcontrol_software);
|
||||
result = 1;
|
||||
case FL_CTRL_SET_FLOWCONTROL_SOFTWARE:
|
||||
break;
|
||||
case FL_CTRL_GET_STATUS_CHANGE:
|
||||
port->serialport->waitForChange();
|
||||
result = 1;
|
||||
break;
|
||||
|
||||
default:
|
||||
result = -1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (const std::exception &)
|
||||
{
|
||||
port->lasterror = FlError::FL_ERROR_PORT_ALLREADY_OPEN;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_free(void)
|
||||
{
|
||||
// Join every live SerialThread before the Dart isolate tears down on hot
|
||||
// restart. Without this, threads holding freed NativeCallable pointers
|
||||
// crash with "Callback invoked after it has been deleted".
|
||||
for (int i = 0; i < MAX_PORT_COUNT; i++)
|
||||
_fl_close_slot(i);
|
||||
|
||||
flserial_count = 0;
|
||||
current_port = -1;
|
||||
return 0;
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
LIBRARY flserial
|
||||
EXPORTS
|
||||
fl_init
|
||||
fl_open
|
||||
fl_read
|
||||
fl_write
|
||||
fl_close
|
||||
fl_ctrl
|
||||
fl_free
|
||||
fl_ports
|
||||
fl_set_callback
|
||||
Vendored
+79
@@ -0,0 +1,79 @@
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#if _WIN32
|
||||
#include <windows.h>
|
||||
#else
|
||||
#include <pthread.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#if _WIN32
|
||||
#define FFI_PLUGIN_EXPORT __declspec(dllexport)
|
||||
#else
|
||||
#define FFI_PLUGIN_EXPORT
|
||||
#endif
|
||||
|
||||
|
||||
#define MAX_PORT_FIFO_LEN 256*1024
|
||||
#define MAX_PORT_NAME_LEN 512
|
||||
#define MAX_PORT_COUNT 16
|
||||
|
||||
typedef enum FlCtrl {
|
||||
FL_CTRL_LAST_ERROR,
|
||||
FL_CTRL_IS_PORT_OPEN,
|
||||
FL_CTRL_BREAK,
|
||||
FL_CTRL_SET_RTS,
|
||||
FL_CTRL_GET_CTS,
|
||||
FL_CTRL_SET_DTR,
|
||||
FL_CTRL_GET_DSR,
|
||||
FL_CTRL_SET_BYTESIZE_5,
|
||||
FL_CTRL_SET_BYTESIZE_6,
|
||||
FL_CTRL_SET_BYTESIZE_7,
|
||||
FL_CTRL_SET_BYTESIZE_8,
|
||||
FL_CTRL_SET_PARITY_NONE,
|
||||
FL_CTRL_SET_PARITY_ODD,
|
||||
FL_CTRL_SET_PARITY_EVEN,
|
||||
FL_CTRL_SET_PARITY_MARK,
|
||||
FL_CTRL_SET_PARITY_SPACE,
|
||||
FL_CTRL_SET_STOPBITS_ONE,
|
||||
FL_CTRL_SET_STOPBITS_TWO,
|
||||
FL_CTRL_SET_STOPBITS_ONE_POINT_FIVE,
|
||||
FL_CTRL_SET_FLOWCONTROL_NONE,
|
||||
FL_CTRL_SET_FLOWCONTROL_HARDWARE,
|
||||
FL_CTRL_SET_FLOWCONTROL_SOFTWARE,
|
||||
FL_CTRL_GET_STATUS_CHANGE,
|
||||
FL_CTRL_LAST,
|
||||
} FlCtrl;
|
||||
|
||||
typedef enum FlError {
|
||||
FL_ERROR_OK,
|
||||
FL_ERROR_UNKNOW,
|
||||
FL_ERROR_PORT_ALLREADY_OPEN,
|
||||
FL_ERROR_PORT_NOT_EXIST,
|
||||
FL_ERROR_IO,
|
||||
FL_ERROR_HANDLER,
|
||||
FL_ERROR_LAST,
|
||||
} FlError;
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef void (*flcallback)(unsigned int, unsigned int);
|
||||
|
||||
FFI_PLUGIN_EXPORT int fl_init (int portCount);
|
||||
FFI_PLUGIN_EXPORT int fl_set_callback(int flh, flcallback cb);
|
||||
FFI_PLUGIN_EXPORT int fl_ports (int index, int buffsize, char *buff);
|
||||
FFI_PLUGIN_EXPORT int fl_open (int flh, char *portname, int baudrate);
|
||||
FFI_PLUGIN_EXPORT int fl_read (int flh, int len, char *buff);
|
||||
FFI_PLUGIN_EXPORT int fl_write (int flh, int len, char *data);
|
||||
FFI_PLUGIN_EXPORT int fl_close (int flh);
|
||||
FFI_PLUGIN_EXPORT int fl_ctrl (int flh, FlCtrl param, int value);
|
||||
FFI_PLUGIN_EXPORT int fl_free (void);
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
* Copyright (c) 1989, 1993
|
||||
* The Regents of the University of California. All rights reserved.
|
||||
*
|
||||
* This code is derived from software contributed to Berkeley by
|
||||
* Guido van Rossum.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of the University nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
|
||||
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
||||
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
||||
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
* SUCH DAMAGE.
|
||||
*
|
||||
* @(#)glob.h 8.1 (Berkeley) 6/2/93
|
||||
* $FreeBSD$
|
||||
*/
|
||||
|
||||
#ifndef _GLOB_H_
|
||||
#define _GLOB_H_
|
||||
|
||||
#include <sys/cdefs.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#ifndef _SIZE_T_DECLARED
|
||||
typedef size_t __size_t;
|
||||
#define _SIZE_T_DECLARED
|
||||
#endif
|
||||
|
||||
struct stat;
|
||||
typedef struct {
|
||||
size_t gl_pathc; /* Count of total paths so far. */
|
||||
size_t gl_matchc; /* Count of paths matching pattern. */
|
||||
size_t gl_offs; /* Reserved at beginning of gl_pathv. */
|
||||
int gl_flags; /* Copy of flags parameter to glob. */
|
||||
char **gl_pathv; /* List of paths matching pattern. */
|
||||
/* Copy of errfunc parameter to glob. */
|
||||
int (*gl_errfunc)(const char *, int);
|
||||
|
||||
/*
|
||||
* Alternate filesystem access methods for glob; replacement
|
||||
* versions of closedir(3), readdir(3), opendir(3), stat(2)
|
||||
* and lstat(2).
|
||||
*/
|
||||
void (*gl_closedir)(void *);
|
||||
struct dirent *(*gl_readdir)(void *);
|
||||
void *(*gl_opendir)(const char *);
|
||||
int (*gl_lstat)(const char *, struct stat *);
|
||||
int (*gl_stat)(const char *, struct stat *);
|
||||
} cglob_t;
|
||||
|
||||
|
||||
/* Believed to have been introduced in 1003.2-1992 */
|
||||
#define GLOB_APPEND 0x0001 /* Append to output from previous call. */
|
||||
#define GLOB_DOOFFS 0x0002 /* Use gl_offs. */
|
||||
#define GLOB_ERR 0x0004 /* Return on error. */
|
||||
#define GLOB_MARK 0x0008 /* Append / to matching directories. */
|
||||
#define GLOB_NOCHECK 0x0010 /* Return pattern itself if nothing matches. */
|
||||
#define GLOB_NOSORT 0x0020 /* Don't sort. */
|
||||
#define GLOB_NOESCAPE 0x2000 /* Disable backslash escaping. */
|
||||
|
||||
/* Error values returned by glob(3) */
|
||||
#define GLOB_NOSPACE (-1) /* Malloc call failed. */
|
||||
#define GLOB_ABORTED (-2) /* Unignored error. */
|
||||
#define GLOB_NOMATCH (-3) /* No match and GLOB_NOCHECK was not set. */
|
||||
#define GLOB_NOSYS (-4) /* Obsolete: source comptability only. */
|
||||
|
||||
|
||||
|
||||
#define GLOB_ALTDIRFUNC 0x0040 /* Use alternately specified directory funcs. */
|
||||
#define GLOB_BRACE 0x0080 /* Expand braces ala csh. */
|
||||
#define GLOB_MAGCHAR 0x0100 /* Pattern had globbing characters. */
|
||||
#define GLOB_NOMAGIC 0x0200 /* GLOB_NOCHECK without magic chars (csh). */
|
||||
#define GLOB_QUOTE 0x0400 /* Quote special chars with \. */
|
||||
#define GLOB_TILDE 0x0800 /* Expand tilde names from the passwd file. */
|
||||
#define GLOB_LIMIT 0x1000 /* limit number of returned paths */
|
||||
|
||||
/* source compatibility, these are the old names */
|
||||
#define GLOB_MAXPATH GLOB_LIMIT
|
||||
#define GLOB_ABEND GLOB_ABORTED
|
||||
|
||||
__BEGIN_DECLS
|
||||
int cglob(const char *, int, int (*)(const char *, int), cglob_t *);
|
||||
void cglobfree(cglob_t *);
|
||||
__END_DECLS
|
||||
|
||||
#endif /* !_GLOB_H_ */
|
||||
@@ -0,0 +1,144 @@
|
||||
#include <inttypes.h>
|
||||
#include <stddef.h>
|
||||
#include <assert.h>
|
||||
/**
|
||||
* @file
|
||||
* Prototypes and structures for the ring buffer module.
|
||||
*/
|
||||
|
||||
#ifndef RINGBUFFER_H
|
||||
#define RINGBUFFER_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
#define RING_BUFFER_ASSERT(x) assert(x)
|
||||
|
||||
/**
|
||||
* Checks if the buffer_size is a power of two.
|
||||
* Due to the design only <tt> RING_BUFFER_SIZE-1 </tt> items
|
||||
* can be contained in the buffer.
|
||||
* buffer_size must be a power of two.
|
||||
*/
|
||||
#define RING_BUFFER_IS_POWER_OF_TWO(buffer_size) ((buffer_size & (buffer_size - 1)) == 0)
|
||||
|
||||
/**
|
||||
* The type which is used to hold the size
|
||||
* and the indicies of the buffer.
|
||||
*/
|
||||
typedef size_t ring_buffer_size_t;
|
||||
|
||||
/**
|
||||
* Used as a modulo operator
|
||||
* as <tt> a % b = (a & (b − 1)) </tt>
|
||||
* where \c a is a positive index in the buffer and
|
||||
* \c b is the (power of two) size of the buffer.
|
||||
*/
|
||||
#define RING_BUFFER_MASK(rb) (rb->buffer_mask)
|
||||
|
||||
/**
|
||||
* Simplifies the use of <tt>struct ring_buffer_t</tt>.
|
||||
*/
|
||||
typedef struct ring_buffer_t ring_buffer_t;
|
||||
|
||||
/**
|
||||
* Structure which holds a ring buffer.
|
||||
* The buffer contains a buffer array
|
||||
* as well as metadata for the ring buffer.
|
||||
*/
|
||||
struct ring_buffer_t {
|
||||
/** Buffer memory. */
|
||||
char *buffer;
|
||||
/** Buffer mask. */
|
||||
ring_buffer_size_t buffer_mask;
|
||||
/** Index of tail. */
|
||||
ring_buffer_size_t tail_index;
|
||||
/** Index of head. */
|
||||
ring_buffer_size_t head_index;
|
||||
};
|
||||
|
||||
/**
|
||||
* Initializes the ring buffer pointed to by <em>buffer</em>.
|
||||
* This function can also be used to empty/reset the buffer.
|
||||
* The resulting buffer can contain <em>buf_size-1</em> bytes.
|
||||
* @param buffer The ring buffer to initialize.
|
||||
* @param buf The buffer allocated for the ringbuffer.
|
||||
* @param buf_size The size of the allocated ringbuffer.
|
||||
*/
|
||||
void ring_buffer_init(ring_buffer_t *buffer, char *buf, size_t buf_size);
|
||||
|
||||
/**
|
||||
* Adds a byte to a ring buffer.
|
||||
* @param buffer The buffer in which the data should be placed.
|
||||
* @param data The byte to place.
|
||||
*/
|
||||
void ring_buffer_queue(ring_buffer_t *buffer, char data);
|
||||
|
||||
/**
|
||||
* Adds an array of bytes to a ring buffer.
|
||||
* @param buffer The buffer in which the data should be placed.
|
||||
* @param data A pointer to the array of bytes to place in the queue.
|
||||
* @param size The size of the array.
|
||||
*/
|
||||
void ring_buffer_queue_arr(ring_buffer_t *buffer, const char *data, ring_buffer_size_t size);
|
||||
|
||||
/**
|
||||
* Returns the oldest byte in a ring buffer.
|
||||
* @param buffer The buffer from which the data should be returned.
|
||||
* @param data A pointer to the location at which the data should be placed.
|
||||
* @return 1 if data was returned; 0 otherwise.
|
||||
*/
|
||||
uint8_t ring_buffer_dequeue(ring_buffer_t *buffer, char *data);
|
||||
|
||||
/**
|
||||
* Returns the <em>len</em> oldest bytes in a ring buffer.
|
||||
* @param buffer The buffer from which the data should be returned.
|
||||
* @param data A pointer to the array at which the data should be placed.
|
||||
* @param len The maximum number of bytes to return.
|
||||
* @return The number of bytes returned.
|
||||
*/
|
||||
ring_buffer_size_t ring_buffer_dequeue_arr(ring_buffer_t *buffer, char *data, ring_buffer_size_t len);
|
||||
/**
|
||||
* Peeks a ring buffer, i.e. returns an element without removing it.
|
||||
* @param buffer The buffer from which the data should be returned.
|
||||
* @param data A pointer to the location at which the data should be placed.
|
||||
* @param index The index to peek.
|
||||
* @return 1 if data was returned; 0 otherwise.
|
||||
*/
|
||||
uint8_t ring_buffer_peek(ring_buffer_t *buffer, char *data, ring_buffer_size_t index);
|
||||
|
||||
|
||||
/**
|
||||
* Returns whether a ring buffer is empty.
|
||||
* @param buffer The buffer for which it should be returned whether it is empty.
|
||||
* @return 1 if empty; 0 otherwise.
|
||||
*/
|
||||
inline uint8_t ring_buffer_is_empty(ring_buffer_t *buffer) {
|
||||
return (buffer->head_index == buffer->tail_index);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether a ring buffer is full.
|
||||
* @param buffer The buffer for which it should be returned whether it is full.
|
||||
* @return 1 if full; 0 otherwise.
|
||||
*/
|
||||
inline uint8_t ring_buffer_is_full(ring_buffer_t *buffer) {
|
||||
return ((buffer->head_index - buffer->tail_index) & RING_BUFFER_MASK(buffer)) == RING_BUFFER_MASK(buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of items in a ring buffer.
|
||||
* @param buffer The buffer for which the number of items should be returned.
|
||||
* @return The number of items in the ring buffer.
|
||||
*/
|
||||
inline ring_buffer_size_t ring_buffer_num_items(ring_buffer_t *buffer) {
|
||||
return ((buffer->head_index - buffer->tail_index) & RING_BUFFER_MASK(buffer));
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* RINGBUFFER_H */
|
||||
@@ -0,0 +1,221 @@
|
||||
/*!
|
||||
* \file serial/impl/unix.h
|
||||
* \author William Woodall <wjwwood@gmail.com>
|
||||
* \author John Harrison <ash@greaterthaninfinity.com>
|
||||
* \version 0.1
|
||||
*
|
||||
* \section LICENSE
|
||||
*
|
||||
* The MIT License
|
||||
*
|
||||
* Copyright (c) 2012 William Woodall, John Harrison
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
* DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* \section DESCRIPTION
|
||||
*
|
||||
* This provides a unix based pimpl for the Serial class. This implementation is
|
||||
* based off termios.h and uses select for multiplexing the IO ports.
|
||||
*
|
||||
*/
|
||||
|
||||
#if !defined(_WIN32)
|
||||
|
||||
#ifndef SERIAL_IMPL_UNIX_H
|
||||
#define SERIAL_IMPL_UNIX_H
|
||||
|
||||
#include "../../../include/serial/serial.h"
|
||||
|
||||
#include <pthread.h>
|
||||
|
||||
namespace serial {
|
||||
|
||||
using std::size_t;
|
||||
using std::string;
|
||||
using std::invalid_argument;
|
||||
|
||||
using serial::SerialException;
|
||||
using serial::IOException;
|
||||
|
||||
class MillisecondTimer {
|
||||
public:
|
||||
MillisecondTimer(const uint32_t millis);
|
||||
int64_t remaining();
|
||||
|
||||
private:
|
||||
static timespec timespec_now();
|
||||
timespec expiry;
|
||||
};
|
||||
|
||||
class serial::Serial::SerialImpl {
|
||||
public:
|
||||
SerialImpl (const string &port,
|
||||
unsigned long baudrate,
|
||||
bytesize_t bytesize,
|
||||
parity_t parity,
|
||||
stopbits_t stopbits,
|
||||
flowcontrol_t flowcontrol);
|
||||
|
||||
virtual ~SerialImpl ();
|
||||
|
||||
void
|
||||
open ();
|
||||
|
||||
void
|
||||
close ();
|
||||
|
||||
bool
|
||||
isOpen () const;
|
||||
|
||||
size_t
|
||||
available ();
|
||||
|
||||
bool
|
||||
waitReadable (uint32_t timeout);
|
||||
|
||||
void
|
||||
waitByteTimes (size_t count);
|
||||
|
||||
size_t
|
||||
read (uint8_t *buf, size_t size = 1);
|
||||
|
||||
size_t
|
||||
write (const uint8_t *data, size_t length);
|
||||
|
||||
void
|
||||
flush ();
|
||||
|
||||
void
|
||||
flushInput ();
|
||||
|
||||
void
|
||||
flushOutput ();
|
||||
|
||||
void
|
||||
sendBreak (int duration);
|
||||
|
||||
void
|
||||
setBreak (bool level);
|
||||
|
||||
void
|
||||
setRTS (bool level);
|
||||
|
||||
void
|
||||
setDTR (bool level);
|
||||
|
||||
bool
|
||||
waitForChange ();
|
||||
|
||||
bool
|
||||
getCTS ();
|
||||
|
||||
bool
|
||||
getDSR ();
|
||||
|
||||
bool
|
||||
getRI ();
|
||||
|
||||
bool
|
||||
getCD ();
|
||||
|
||||
void
|
||||
setPort (const string &port);
|
||||
|
||||
string
|
||||
getPort () const;
|
||||
|
||||
void
|
||||
setTimeout (Timeout &timeout);
|
||||
|
||||
Timeout
|
||||
getTimeout () const;
|
||||
|
||||
void
|
||||
setBaudrate (unsigned long baudrate);
|
||||
|
||||
unsigned long
|
||||
getBaudrate () const;
|
||||
|
||||
void
|
||||
setBytesize (bytesize_t bytesize);
|
||||
|
||||
bytesize_t
|
||||
getBytesize () const;
|
||||
|
||||
void
|
||||
setParity (parity_t parity);
|
||||
|
||||
parity_t
|
||||
getParity () const;
|
||||
|
||||
void
|
||||
setStopbits (stopbits_t stopbits);
|
||||
|
||||
stopbits_t
|
||||
getStopbits () const;
|
||||
|
||||
void
|
||||
setFlowcontrol (flowcontrol_t flowcontrol);
|
||||
|
||||
flowcontrol_t
|
||||
getFlowcontrol () const;
|
||||
|
||||
void
|
||||
readLock ();
|
||||
|
||||
void
|
||||
readUnlock ();
|
||||
|
||||
void
|
||||
writeLock ();
|
||||
|
||||
void
|
||||
writeUnlock ();
|
||||
|
||||
protected:
|
||||
void reconfigurePort ();
|
||||
|
||||
private:
|
||||
string port_; // Path to the file descriptor
|
||||
int fd_; // The current file descriptor
|
||||
|
||||
bool is_open_;
|
||||
bool xonxoff_;
|
||||
bool rtscts_;
|
||||
|
||||
Timeout timeout_; // Timeout for read operations
|
||||
unsigned long baudrate_; // Baudrate
|
||||
uint32_t byte_time_ns_; // Nanoseconds to transmit/receive a single byte
|
||||
|
||||
parity_t parity_; // Parity
|
||||
bytesize_t bytesize_; // Size of the bytes
|
||||
stopbits_t stopbits_; // Stop Bits
|
||||
flowcontrol_t flowcontrol_; // Flow Control
|
||||
|
||||
// Mutex used to lock the read functions
|
||||
pthread_mutex_t read_mutex;
|
||||
// Mutex used to lock the write functions
|
||||
pthread_mutex_t write_mutex;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // SERIAL_IMPL_UNIX_H
|
||||
|
||||
#endif // !defined(_WIN32)
|
||||
@@ -0,0 +1,207 @@
|
||||
/*!
|
||||
* \file serial/impl/windows.h
|
||||
* \author William Woodall <wjwwood@gmail.com>
|
||||
* \author John Harrison <ash@greaterthaninfinity.com>
|
||||
* \version 0.1
|
||||
*
|
||||
* \section LICENSE
|
||||
*
|
||||
* The MIT License
|
||||
*
|
||||
* Copyright (c) 2012 William Woodall, John Harrison
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
* DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* \section DESCRIPTION
|
||||
*
|
||||
* This provides a windows implementation of the Serial class interface.
|
||||
*
|
||||
*/
|
||||
|
||||
#if defined(_WIN32)
|
||||
|
||||
#ifndef SERIAL_IMPL_WINDOWS_H
|
||||
#define SERIAL_IMPL_WINDOWS_H
|
||||
|
||||
#include "serial/serial.h"
|
||||
|
||||
#include "windows.h"
|
||||
|
||||
namespace serial {
|
||||
|
||||
using std::string;
|
||||
using std::wstring;
|
||||
using std::invalid_argument;
|
||||
|
||||
using serial::SerialException;
|
||||
using serial::IOException;
|
||||
|
||||
class serial::Serial::SerialImpl {
|
||||
public:
|
||||
SerialImpl (const string &port,
|
||||
unsigned long baudrate,
|
||||
bytesize_t bytesize,
|
||||
parity_t parity,
|
||||
stopbits_t stopbits,
|
||||
flowcontrol_t flowcontrol);
|
||||
|
||||
virtual ~SerialImpl ();
|
||||
|
||||
void
|
||||
open ();
|
||||
|
||||
void
|
||||
close ();
|
||||
|
||||
bool
|
||||
isOpen () const;
|
||||
|
||||
size_t
|
||||
available ();
|
||||
|
||||
bool
|
||||
waitReadable (uint32_t timeout);
|
||||
|
||||
void
|
||||
waitByteTimes (size_t count);
|
||||
|
||||
size_t
|
||||
read (uint8_t *buf, size_t size = 1);
|
||||
|
||||
size_t
|
||||
write (const uint8_t *data, size_t length);
|
||||
|
||||
void
|
||||
flush ();
|
||||
|
||||
void
|
||||
flushInput ();
|
||||
|
||||
void
|
||||
flushOutput ();
|
||||
|
||||
void
|
||||
sendBreak (int duration);
|
||||
|
||||
void
|
||||
setBreak (bool level);
|
||||
|
||||
void
|
||||
setRTS (bool level);
|
||||
|
||||
void
|
||||
setDTR (bool level);
|
||||
|
||||
bool
|
||||
waitForChange ();
|
||||
|
||||
bool
|
||||
getCTS ();
|
||||
|
||||
bool
|
||||
getDSR ();
|
||||
|
||||
bool
|
||||
getRI ();
|
||||
|
||||
bool
|
||||
getCD ();
|
||||
|
||||
void
|
||||
setPort (const string &port);
|
||||
|
||||
string
|
||||
getPort () const;
|
||||
|
||||
void
|
||||
setTimeout (Timeout &timeout);
|
||||
|
||||
Timeout
|
||||
getTimeout () const;
|
||||
|
||||
void
|
||||
setBaudrate (unsigned long baudrate);
|
||||
|
||||
unsigned long
|
||||
getBaudrate () const;
|
||||
|
||||
void
|
||||
setBytesize (bytesize_t bytesize);
|
||||
|
||||
bytesize_t
|
||||
getBytesize () const;
|
||||
|
||||
void
|
||||
setParity (parity_t parity);
|
||||
|
||||
parity_t
|
||||
getParity () const;
|
||||
|
||||
void
|
||||
setStopbits (stopbits_t stopbits);
|
||||
|
||||
stopbits_t
|
||||
getStopbits () const;
|
||||
|
||||
void
|
||||
setFlowcontrol (flowcontrol_t flowcontrol);
|
||||
|
||||
flowcontrol_t
|
||||
getFlowcontrol () const;
|
||||
|
||||
void
|
||||
readLock ();
|
||||
|
||||
void
|
||||
readUnlock ();
|
||||
|
||||
void
|
||||
writeLock ();
|
||||
|
||||
void
|
||||
writeUnlock ();
|
||||
|
||||
protected:
|
||||
void reconfigurePort ();
|
||||
|
||||
private:
|
||||
wstring port_; // Path to the file descriptor
|
||||
HANDLE fd_;
|
||||
|
||||
bool is_open_;
|
||||
|
||||
Timeout timeout_; // Timeout for read operations
|
||||
unsigned long baudrate_; // Baudrate
|
||||
|
||||
parity_t parity_; // Parity
|
||||
bytesize_t bytesize_; // Size of the bytes
|
||||
stopbits_t stopbits_; // Stop Bits
|
||||
flowcontrol_t flowcontrol_; // Flow Control
|
||||
|
||||
// Mutex used to lock the read functions
|
||||
HANDLE read_mutex;
|
||||
// Mutex used to lock the write functions
|
||||
HANDLE write_mutex;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // SERIAL_IMPL_WINDOWS_H
|
||||
|
||||
#endif // if defined(_WIN32)
|
||||
@@ -0,0 +1,780 @@
|
||||
/*!
|
||||
* \file serial/serial.h
|
||||
* \author William Woodall <wjwwood@gmail.com>
|
||||
* \author John Harrison <ash.gti@gmail.com>
|
||||
* \version 0.1
|
||||
*
|
||||
* \section LICENSE
|
||||
*
|
||||
* The MIT License
|
||||
*
|
||||
* Copyright (c) 2012 William Woodall
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
* DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* \section DESCRIPTION
|
||||
*
|
||||
* This provides a cross platform interface for interacting with Serial Ports.
|
||||
*/
|
||||
|
||||
#ifndef SERIAL_H
|
||||
#define SERIAL_H
|
||||
|
||||
#include <limits>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <cstring>
|
||||
#include <sstream>
|
||||
#include <exception>
|
||||
#include <stdexcept>
|
||||
#include "v8stdint.h"
|
||||
|
||||
|
||||
|
||||
#define THROWEX(exceptionClass, message, errorno) throw exceptionClass(__FILE__, \
|
||||
__LINE__, (message), (errorno) )
|
||||
|
||||
#define THROW(exceptionClass, message) throw exceptionClass(__FILE__, \
|
||||
__LINE__, (message) )
|
||||
|
||||
namespace serial {
|
||||
|
||||
/*!
|
||||
* Enumeration defines the possible bytesizes for the serial port.
|
||||
*/
|
||||
typedef enum {
|
||||
fivebits = 5,
|
||||
sixbits = 6,
|
||||
sevenbits = 7,
|
||||
eightbits = 8
|
||||
} bytesize_t;
|
||||
|
||||
/*!
|
||||
* Enumeration defines the possible parity types for the serial port.
|
||||
*/
|
||||
typedef enum {
|
||||
parity_none = 0,
|
||||
parity_odd = 1,
|
||||
parity_even = 2,
|
||||
parity_mark = 3,
|
||||
parity_space = 4
|
||||
} parity_t;
|
||||
|
||||
/*!
|
||||
* Enumeration defines the possible stopbit types for the serial port.
|
||||
*/
|
||||
typedef enum {
|
||||
stopbits_one = 1,
|
||||
stopbits_two = 2,
|
||||
stopbits_one_point_five
|
||||
} stopbits_t;
|
||||
|
||||
/*!
|
||||
* Enumeration defines the possible flowcontrol types for the serial port.
|
||||
*/
|
||||
typedef enum {
|
||||
flowcontrol_none = 0,
|
||||
flowcontrol_software,
|
||||
flowcontrol_hardware
|
||||
} flowcontrol_t;
|
||||
|
||||
/*!
|
||||
* Structure for setting the timeout of the serial port, times are
|
||||
* in milliseconds.
|
||||
*
|
||||
* In order to disable the interbyte timeout, set it to Timeout::max().
|
||||
*/
|
||||
struct Timeout {
|
||||
#ifdef max
|
||||
# undef max
|
||||
#endif
|
||||
static uint32_t max() {return std::numeric_limits<uint32_t>::max();}
|
||||
/*!
|
||||
* Convenience function to generate Timeout structs using a
|
||||
* single absolute timeout.
|
||||
*
|
||||
* \param timeout A long that defines the time in milliseconds until a
|
||||
* timeout occurs after a call to read or write is made.
|
||||
*
|
||||
* \return Timeout struct that represents this simple timeout provided.
|
||||
*/
|
||||
static Timeout simpleTimeout(uint32_t timeout) {
|
||||
return Timeout(10, timeout, 0, timeout, 0);
|
||||
}
|
||||
|
||||
/*! Number of milliseconds between bytes received to timeout on. */
|
||||
uint32_t inter_byte_timeout;
|
||||
/*! A constant number of milliseconds to wait after calling read. */
|
||||
uint32_t read_timeout_constant;
|
||||
/*! A multiplier against the number of requested bytes to wait after
|
||||
* calling read.
|
||||
*/
|
||||
uint32_t read_timeout_multiplier;
|
||||
/*! A constant number of milliseconds to wait after calling write. */
|
||||
uint32_t write_timeout_constant;
|
||||
/*! A multiplier against the number of requested bytes to wait after
|
||||
* calling write.
|
||||
*/
|
||||
uint32_t write_timeout_multiplier;
|
||||
|
||||
explicit Timeout (uint32_t inter_byte_timeout_=0,
|
||||
uint32_t read_timeout_constant_=0,
|
||||
uint32_t read_timeout_multiplier_=0,
|
||||
uint32_t write_timeout_constant_=0,
|
||||
uint32_t write_timeout_multiplier_=0)
|
||||
: inter_byte_timeout(inter_byte_timeout_),
|
||||
read_timeout_constant(read_timeout_constant_),
|
||||
read_timeout_multiplier(read_timeout_multiplier_),
|
||||
write_timeout_constant(write_timeout_constant_),
|
||||
write_timeout_multiplier(write_timeout_multiplier_)
|
||||
{}
|
||||
};
|
||||
|
||||
/*!
|
||||
* Class that provides a portable serial port interface.
|
||||
*/
|
||||
class Serial {
|
||||
public:
|
||||
/*!
|
||||
* Creates a Serial object and opens the port if a port is specified,
|
||||
* otherwise it remains closed until serial::Serial::open is called.
|
||||
*
|
||||
* \param port A std::string containing the address of the serial port,
|
||||
* which would be something like 'COM1' on Windows and '/dev/ttyS0'
|
||||
* on Linux.
|
||||
*
|
||||
* \param baudrate An unsigned 32-bit integer that represents the baudrate
|
||||
*
|
||||
* \param timeout A serial::Timeout struct that defines the timeout
|
||||
* conditions for the serial port. \see serial::Timeout
|
||||
*
|
||||
* \param bytesize Size of each byte in the serial transmission of data,
|
||||
* default is eightbits, possible values are: fivebits, sixbits, sevenbits,
|
||||
* eightbits
|
||||
*
|
||||
* \param parity Method of parity, default is parity_none, possible values
|
||||
* are: parity_none, parity_odd, parity_even
|
||||
*
|
||||
* \param stopbits Number of stop bits used, default is stopbits_one,
|
||||
* possible values are: stopbits_one, stopbits_one_point_five, stopbits_two
|
||||
*
|
||||
* \param flowcontrol Type of flowcontrol used, default is
|
||||
* flowcontrol_none, possible values are: flowcontrol_none,
|
||||
* flowcontrol_software, flowcontrol_hardware
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::IOException
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
Serial (const std::string &port = "",
|
||||
uint32_t baudrate = 9600,
|
||||
Timeout timeout = Timeout(),
|
||||
bytesize_t bytesize = eightbits,
|
||||
parity_t parity = parity_none,
|
||||
stopbits_t stopbits = stopbits_one,
|
||||
flowcontrol_t flowcontrol = flowcontrol_none);
|
||||
|
||||
/*! Destructor */
|
||||
virtual ~Serial ();
|
||||
|
||||
/*!
|
||||
* Opens the serial port as long as the port is set and the port isn't
|
||||
* already open.
|
||||
*
|
||||
* If the port is provided to the constructor then an explicit call to open
|
||||
* is not needed.
|
||||
*
|
||||
* \see Serial::Serial
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
* \throw serial::SerialException
|
||||
* \throw serial::IOException
|
||||
*/
|
||||
void
|
||||
open ();
|
||||
|
||||
/*! Gets the open status of the serial port.
|
||||
*
|
||||
* \return Returns true if the port is open, false otherwise.
|
||||
*/
|
||||
bool
|
||||
isOpen () const;
|
||||
|
||||
/*! Closes the serial port. */
|
||||
void
|
||||
close ();
|
||||
|
||||
/*! Return the number of characters in the buffer. */
|
||||
size_t
|
||||
available ();
|
||||
|
||||
/*! Block until there is serial data to read or read_timeout_constant
|
||||
* number of milliseconds have elapsed. The return value is true when
|
||||
* the function exits with the port in a readable state, false otherwise
|
||||
* (due to timeout or select interruption). */
|
||||
bool
|
||||
waitReadable ();
|
||||
|
||||
/*! Block for a period of time corresponding to the transmission time of
|
||||
* count characters at present serial settings. This may be used in con-
|
||||
* junction with waitReadable to read larger blocks of data from the
|
||||
* port. */
|
||||
void
|
||||
waitByteTimes (size_t count);
|
||||
|
||||
/*! Read a given amount of bytes from the serial port into a given buffer.
|
||||
*
|
||||
* The read function will return in one of three cases:
|
||||
* * The number of requested bytes was read.
|
||||
* * In this case the number of bytes requested will match the size_t
|
||||
* returned by read.
|
||||
* * A timeout occurred, in this case the number of bytes read will not
|
||||
* match the amount requested, but no exception will be thrown. One of
|
||||
* two possible timeouts occurred:
|
||||
* * The inter byte timeout expired, this means that number of
|
||||
* milliseconds elapsed between receiving bytes from the serial port
|
||||
* exceeded the inter byte timeout.
|
||||
* * The total timeout expired, which is calculated by multiplying the
|
||||
* read timeout multiplier by the number of requested bytes and then
|
||||
* added to the read timeout constant. If that total number of
|
||||
* milliseconds elapses after the initial call to read a timeout will
|
||||
* occur.
|
||||
* * An exception occurred, in this case an actual exception will be thrown.
|
||||
*
|
||||
* \param buffer An uint8_t array of at least the requested size.
|
||||
* \param size A size_t defining how many bytes to be read.
|
||||
*
|
||||
* \return A size_t representing the number of bytes read as a result of the
|
||||
* call to read.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
*/
|
||||
size_t
|
||||
read (uint8_t *buffer, size_t size);
|
||||
|
||||
/*! Read a given amount of bytes from the serial port into a give buffer.
|
||||
*
|
||||
* \param buffer A reference to a std::vector of uint8_t.
|
||||
* \param size A size_t defining how many bytes to be read.
|
||||
*
|
||||
* \return A size_t representing the number of bytes read as a result of the
|
||||
* call to read.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
*/
|
||||
size_t
|
||||
read (std::vector<uint8_t> &buffer, size_t size = 1);
|
||||
|
||||
/*! Read a given amount of bytes from the serial port into a give buffer.
|
||||
*
|
||||
* \param buffer A reference to a std::string.
|
||||
* \param size A size_t defining how many bytes to be read.
|
||||
*
|
||||
* \return A size_t representing the number of bytes read as a result of the
|
||||
* call to read.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
*/
|
||||
size_t
|
||||
read (std::string &buffer, size_t size = 1);
|
||||
|
||||
/*! Read a given amount of bytes from the serial port and return a string
|
||||
* containing the data.
|
||||
*
|
||||
* \param size A size_t defining how many bytes to be read.
|
||||
*
|
||||
* \return A std::string containing the data read from the port.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
*/
|
||||
std::string
|
||||
read (size_t size = 1);
|
||||
|
||||
/*! Reads in a line or until a given delimiter has been processed.
|
||||
*
|
||||
* Reads from the serial port until a single line has been read.
|
||||
*
|
||||
* \param buffer A std::string reference used to store the data.
|
||||
* \param size A maximum length of a line, defaults to 65536 (2^16)
|
||||
* \param eol A string to match against for the EOL.
|
||||
*
|
||||
* \return A size_t representing the number of bytes read.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
*/
|
||||
size_t
|
||||
readline (std::string &buffer, size_t size = 65536, std::string eol = "\n");
|
||||
|
||||
/*! Reads in a line or until a given delimiter has been processed.
|
||||
*
|
||||
* Reads from the serial port until a single line has been read.
|
||||
*
|
||||
* \param size A maximum length of a line, defaults to 65536 (2^16)
|
||||
* \param eol A string to match against for the EOL.
|
||||
*
|
||||
* \return A std::string containing the line.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
*/
|
||||
std::string
|
||||
readline (size_t size = 65536, std::string eol = "\n");
|
||||
|
||||
/*! Reads in multiple lines until the serial port times out.
|
||||
*
|
||||
* This requires a timeout > 0 before it can be run. It will read until a
|
||||
* timeout occurs and return a list of strings.
|
||||
*
|
||||
* \param size A maximum length of combined lines, defaults to 65536 (2^16)
|
||||
*
|
||||
* \param eol A string to match against for the EOL.
|
||||
*
|
||||
* \return A vector<string> containing the lines.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
*/
|
||||
std::vector<std::string>
|
||||
readlines (size_t size = 65536, std::string eol = "\n");
|
||||
|
||||
/*! Write a string to the serial port.
|
||||
*
|
||||
* \param data A const reference containing the data to be written
|
||||
* to the serial port.
|
||||
*
|
||||
* \param size A size_t that indicates how many bytes should be written from
|
||||
* the given data buffer.
|
||||
*
|
||||
* \return A size_t representing the number of bytes actually written to
|
||||
* the serial port.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
* \throw serial::IOException
|
||||
*/
|
||||
size_t
|
||||
write (const uint8_t *data, size_t size);
|
||||
|
||||
/*! Write a string to the serial port.
|
||||
*
|
||||
* \param data A const reference containing the data to be written
|
||||
* to the serial port.
|
||||
*
|
||||
* \return A size_t representing the number of bytes actually written to
|
||||
* the serial port.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
* \throw serial::IOException
|
||||
*/
|
||||
size_t
|
||||
write (const std::vector<uint8_t> &data);
|
||||
|
||||
/*! Write a string to the serial port.
|
||||
*
|
||||
* \param data A const reference containing the data to be written
|
||||
* to the serial port.
|
||||
*
|
||||
* \return A size_t representing the number of bytes actually written to
|
||||
* the serial port.
|
||||
*
|
||||
* \throw serial::PortNotOpenedException
|
||||
* \throw serial::SerialException
|
||||
* \throw serial::IOException
|
||||
*/
|
||||
size_t
|
||||
write (const std::string &data);
|
||||
|
||||
/*! Sets the serial port identifier.
|
||||
*
|
||||
* \param port A const std::string reference containing the address of the
|
||||
* serial port, which would be something like 'COM1' on Windows and
|
||||
* '/dev/ttyS0' on Linux.
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
void
|
||||
setPort (const std::string &port);
|
||||
|
||||
/*! Gets the serial port identifier.
|
||||
*
|
||||
* \see Serial::setPort
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
std::string
|
||||
getPort () const;
|
||||
|
||||
/*! Sets the timeout for reads and writes using the Timeout struct.
|
||||
*
|
||||
* There are two timeout conditions described here:
|
||||
* * The inter byte timeout:
|
||||
* * The inter_byte_timeout component of serial::Timeout defines the
|
||||
* maximum amount of time, in milliseconds, between receiving bytes on
|
||||
* the serial port that can pass before a timeout occurs. Setting this
|
||||
* to zero will prevent inter byte timeouts from occurring.
|
||||
* * Total time timeout:
|
||||
* * The constant and multiplier component of this timeout condition,
|
||||
* for both read and write, are defined in serial::Timeout. This
|
||||
* timeout occurs if the total time since the read or write call was
|
||||
* made exceeds the specified time in milliseconds.
|
||||
* * The limit is defined by multiplying the multiplier component by the
|
||||
* number of requested bytes and adding that product to the constant
|
||||
* component. In this way if you want a read call, for example, to
|
||||
* timeout after exactly one second regardless of the number of bytes
|
||||
* you asked for then set the read_timeout_constant component of
|
||||
* serial::Timeout to 1000 and the read_timeout_multiplier to zero.
|
||||
* This timeout condition can be used in conjunction with the inter
|
||||
* byte timeout condition with out any problems, timeout will simply
|
||||
* occur when one of the two timeout conditions is met. This allows
|
||||
* users to have maximum control over the trade-off between
|
||||
* responsiveness and efficiency.
|
||||
*
|
||||
* Read and write functions will return in one of three cases. When the
|
||||
* reading or writing is complete, when a timeout occurs, or when an
|
||||
* exception occurs.
|
||||
*
|
||||
* A timeout of 0 enables non-blocking mode.
|
||||
*
|
||||
* \param timeout A serial::Timeout struct containing the inter byte
|
||||
* timeout, and the read and write timeout constants and multipliers.
|
||||
*
|
||||
* \see serial::Timeout
|
||||
*/
|
||||
void
|
||||
setTimeout (Timeout &timeout);
|
||||
|
||||
/*! Sets the timeout for reads and writes. */
|
||||
void
|
||||
setTimeout (uint32_t inter_byte_timeout, uint32_t read_timeout_constant,
|
||||
uint32_t read_timeout_multiplier, uint32_t write_timeout_constant,
|
||||
uint32_t write_timeout_multiplier)
|
||||
{
|
||||
Timeout timeout(inter_byte_timeout, read_timeout_constant,
|
||||
read_timeout_multiplier, write_timeout_constant,
|
||||
write_timeout_multiplier);
|
||||
return setTimeout(timeout);
|
||||
}
|
||||
|
||||
/*! Gets the timeout for reads in seconds.
|
||||
*
|
||||
* \return A Timeout struct containing the inter_byte_timeout, and read
|
||||
* and write timeout constants and multipliers.
|
||||
*
|
||||
* \see Serial::setTimeout
|
||||
*/
|
||||
Timeout
|
||||
getTimeout () const;
|
||||
|
||||
/*! Sets the baudrate for the serial port.
|
||||
*
|
||||
* Possible baudrates depends on the system but some safe baudrates include:
|
||||
* 110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 56000,
|
||||
* 57600, 115200
|
||||
* Some other baudrates that are supported by some comports:
|
||||
* 128000, 153600, 230400, 256000, 460800, 500000, 921600
|
||||
*
|
||||
* \param baudrate An integer that sets the baud rate for the serial port.
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
void
|
||||
setBaudrate (uint32_t baudrate);
|
||||
|
||||
/*! Gets the baudrate for the serial port.
|
||||
*
|
||||
* \return An integer that sets the baud rate for the serial port.
|
||||
*
|
||||
* \see Serial::setBaudrate
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
uint32_t
|
||||
getBaudrate () const;
|
||||
|
||||
/*! Sets the bytesize for the serial port.
|
||||
*
|
||||
* \param bytesize Size of each byte in the serial transmission of data,
|
||||
* default is eightbits, possible values are: fivebits, sixbits, sevenbits,
|
||||
* eightbits
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
void
|
||||
setBytesize (bytesize_t bytesize);
|
||||
|
||||
/*! Gets the bytesize for the serial port.
|
||||
*
|
||||
* \see Serial::setBytesize
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
bytesize_t
|
||||
getBytesize () const;
|
||||
|
||||
/*! Sets the parity for the serial port.
|
||||
*
|
||||
* \param parity Method of parity, default is parity_none, possible values
|
||||
* are: parity_none, parity_odd, parity_even
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
void
|
||||
setParity (parity_t parity);
|
||||
|
||||
/*! Gets the parity for the serial port.
|
||||
*
|
||||
* \see Serial::setParity
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
parity_t
|
||||
getParity () const;
|
||||
|
||||
/*! Sets the stopbits for the serial port.
|
||||
*
|
||||
* \param stopbits Number of stop bits used, default is stopbits_one,
|
||||
* possible values are: stopbits_one, stopbits_one_point_five, stopbits_two
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
void
|
||||
setStopbits (stopbits_t stopbits);
|
||||
|
||||
/*! Gets the stopbits for the serial port.
|
||||
*
|
||||
* \see Serial::setStopbits
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
stopbits_t
|
||||
getStopbits () const;
|
||||
|
||||
/*! Sets the flow control for the serial port.
|
||||
*
|
||||
* \param flowcontrol Type of flowcontrol used, default is flowcontrol_none,
|
||||
* possible values are: flowcontrol_none, flowcontrol_software,
|
||||
* flowcontrol_hardware
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
void
|
||||
setFlowcontrol (flowcontrol_t flowcontrol);
|
||||
|
||||
/*! Gets the flow control for the serial port.
|
||||
*
|
||||
* \see Serial::setFlowcontrol
|
||||
*
|
||||
* \throw std::invalid_argument
|
||||
*/
|
||||
flowcontrol_t
|
||||
getFlowcontrol () const;
|
||||
|
||||
/*! Flush the input and output buffers */
|
||||
void
|
||||
flush ();
|
||||
|
||||
/*! Flush only the input buffer */
|
||||
void
|
||||
flushInput ();
|
||||
|
||||
/*! Flush only the output buffer */
|
||||
void
|
||||
flushOutput ();
|
||||
|
||||
/*! Sends the RS-232 break signal. See tcsendbreak(3). */
|
||||
void
|
||||
sendBreak (int duration);
|
||||
|
||||
/*! Set the break condition to a given level. Defaults to true. */
|
||||
void
|
||||
setBreak (bool level = true);
|
||||
|
||||
/*! Set the RTS handshaking line to the given level. Defaults to true. */
|
||||
void
|
||||
setRTS (bool level = true);
|
||||
|
||||
/*! Set the DTR handshaking line to the given level. Defaults to true. */
|
||||
void
|
||||
setDTR (bool level = true);
|
||||
|
||||
/*!
|
||||
* Blocks until CTS, DSR, RI, CD changes or something interrupts it.
|
||||
*
|
||||
* Can throw an exception if an error occurs while waiting.
|
||||
* You can check the status of CTS, DSR, RI, and CD once this returns.
|
||||
* Uses TIOCMIWAIT via ioctl if available (mostly only on Linux) with a
|
||||
* resolution of less than +-1ms and as good as +-0.2ms. Otherwise a
|
||||
* polling method is used which can give +-2ms.
|
||||
*
|
||||
* \return Returns true if one of the lines changed, false if something else
|
||||
* occurred.
|
||||
*
|
||||
* \throw SerialException
|
||||
*/
|
||||
bool
|
||||
waitForChange ();
|
||||
|
||||
/*! Returns the current status of the CTS line. */
|
||||
bool
|
||||
getCTS ();
|
||||
|
||||
/*! Returns the current status of the DSR line. */
|
||||
bool
|
||||
getDSR ();
|
||||
|
||||
/*! Returns the current status of the RI line. */
|
||||
bool
|
||||
getRI ();
|
||||
|
||||
/*! Returns the current status of the CD line. */
|
||||
bool
|
||||
getCD ();
|
||||
|
||||
private:
|
||||
// Disable copy constructors
|
||||
Serial(const Serial&);
|
||||
Serial& operator=(const Serial&);
|
||||
|
||||
// Pimpl idiom, d_pointer
|
||||
class SerialImpl;
|
||||
SerialImpl *pimpl_;
|
||||
|
||||
// Scoped Lock Classes
|
||||
class ScopedReadLock;
|
||||
class ScopedWriteLock;
|
||||
|
||||
// Read common function
|
||||
size_t
|
||||
read_ (uint8_t *buffer, size_t size);
|
||||
// Write common function
|
||||
size_t
|
||||
write_ (const uint8_t *data, size_t length);
|
||||
|
||||
};
|
||||
|
||||
class SerialException : public std::exception
|
||||
{
|
||||
// Disable copy constructors
|
||||
SerialException& operator=(const SerialException&);
|
||||
std::string e_what_;
|
||||
public:
|
||||
SerialException (const char *description) {
|
||||
std::stringstream ss;
|
||||
ss << "SerialException " << description << " failed.";
|
||||
e_what_ = ss.str();
|
||||
}
|
||||
SerialException (const SerialException& other) : e_what_(other.e_what_) {}
|
||||
virtual ~SerialException() throw() {}
|
||||
virtual const char* what () const throw () {
|
||||
return e_what_.c_str();
|
||||
}
|
||||
};
|
||||
|
||||
class IOException : public std::exception
|
||||
{
|
||||
// Disable copy constructors
|
||||
IOException& operator=(const IOException&);
|
||||
std::string file_;
|
||||
int line_;
|
||||
std::string e_what_;
|
||||
int errno_;
|
||||
public:
|
||||
explicit IOException (std::string file, int line, int errnum = 0)
|
||||
: file_(file), line_(line), errno_(errnum) {
|
||||
std::stringstream ss;
|
||||
#if defined(_WIN32) && !defined(__MINGW32__)
|
||||
char error_str [1024];
|
||||
strerror_s(error_str, 1024, errnum);
|
||||
#else
|
||||
char * error_str = strerror(errnum);
|
||||
#endif
|
||||
ss << "IO Exception (" << errno_ << "): " << error_str;
|
||||
ss << ", file " << file_ << ", line " << line_ << ".";
|
||||
e_what_ = ss.str();
|
||||
}
|
||||
explicit IOException (std::string file, int line, const char * description, int errnum = 0)
|
||||
: file_(file), line_(line), errno_(errnum) {
|
||||
std::stringstream ss;
|
||||
ss << "IO Exception: " << description;
|
||||
ss << ", file " << file_ << ", line " << line_ << ".";
|
||||
e_what_ = ss.str();
|
||||
}
|
||||
virtual ~IOException() throw() {}
|
||||
IOException (const IOException& other) : line_(other.line_), e_what_(other.e_what_), errno_(other.errno_) {}
|
||||
|
||||
int getErrorNumber () const { return errno_; }
|
||||
|
||||
virtual const char* what () const throw () {
|
||||
return e_what_.c_str();
|
||||
}
|
||||
};
|
||||
|
||||
class PortNotOpenedException : public std::exception
|
||||
{
|
||||
// Disable copy constructors
|
||||
const PortNotOpenedException& operator=(PortNotOpenedException);
|
||||
std::string e_what_;
|
||||
public:
|
||||
PortNotOpenedException (const char * description) {
|
||||
std::stringstream ss;
|
||||
ss << "PortNotOpenedException " << description << " failed.";
|
||||
e_what_ = ss.str();
|
||||
}
|
||||
PortNotOpenedException (const PortNotOpenedException& other) : e_what_(other.e_what_) {}
|
||||
virtual ~PortNotOpenedException() throw() {}
|
||||
virtual const char* what () const throw () {
|
||||
return e_what_.c_str();
|
||||
}
|
||||
};
|
||||
|
||||
/*!
|
||||
* Structure that describes a serial device.
|
||||
*/
|
||||
struct PortInfo {
|
||||
|
||||
/*! Address of the serial port (this can be passed to the constructor of Serial). */
|
||||
std::string port;
|
||||
|
||||
/*! Human readable description of serial device if available. */
|
||||
std::string description;
|
||||
|
||||
/*! Hardware ID (e.g. VID:PID of USB serial devices) or "n/a" if not available. */
|
||||
std::string hardware_id;
|
||||
|
||||
};
|
||||
|
||||
/* Lists the serial ports available on the system
|
||||
*
|
||||
* Returns a vector of available serial ports, each represented
|
||||
* by a serial::PortInfo data structure:
|
||||
*
|
||||
* \return vector of serial::PortInfo.
|
||||
*/
|
||||
std::vector<PortInfo>
|
||||
list_ports();
|
||||
|
||||
} // namespace serial
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,57 @@
|
||||
// This header is from the v8 google project:
|
||||
// http://code.google.com/p/v8/source/browse/trunk/include/v8stdint.h
|
||||
|
||||
// Copyright 2012 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// Load definitions of standard types.
|
||||
|
||||
#ifndef V8STDINT_H_
|
||||
#define V8STDINT_H_
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#if defined(_WIN32) && !defined(__MINGW32__)
|
||||
|
||||
typedef signed char int8_t;
|
||||
typedef unsigned char uint8_t;
|
||||
typedef short int16_t; // NOLINT
|
||||
typedef unsigned short uint16_t; // NOLINT
|
||||
typedef int int32_t;
|
||||
typedef unsigned int uint32_t;
|
||||
typedef __int64 int64_t;
|
||||
typedef unsigned __int64 uint64_t;
|
||||
// intptr_t and friends are defined in crtdefs.h through stdio.h.
|
||||
|
||||
#else
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#endif
|
||||
|
||||
#endif // V8STDINT_H_
|
||||
@@ -0,0 +1,485 @@
|
||||
/* -*- mode: c; tab-width: 2; indent-tabs-mode: nil; -*-
|
||||
Copyright (c) 2012 Marcus Geelnard
|
||||
Copyright (c) 2013-2016 Evan Nemerson
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
*/
|
||||
|
||||
#ifndef _TINYCTHREAD_H_
|
||||
#define _TINYCTHREAD_H_
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @file
|
||||
* @mainpage TinyCThread API Reference
|
||||
*
|
||||
* @section intro_sec Introduction
|
||||
* TinyCThread is a minimal, portable implementation of basic threading
|
||||
* classes for C.
|
||||
*
|
||||
* They closely mimic the functionality and naming of the C11 standard, and
|
||||
* should be easily replaceable with the corresponding standard variants.
|
||||
*
|
||||
* @section port_sec Portability
|
||||
* The Win32 variant uses the native Win32 API for implementing the thread
|
||||
* classes, while for other systems, the POSIX threads API (pthread) is used.
|
||||
*
|
||||
* @section misc_sec Miscellaneous
|
||||
* The following special keywords are available: #_Thread_local.
|
||||
*
|
||||
* For more detailed information, browse the different sections of this
|
||||
* documentation. A good place to start is:
|
||||
* tinycthread.h.
|
||||
*/
|
||||
|
||||
/* Which platform are we on? */
|
||||
#if !defined(_TTHREAD_PLATFORM_DEFINED_)
|
||||
#if defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__)
|
||||
#define _TTHREAD_WIN32_
|
||||
#else
|
||||
#define _TTHREAD_POSIX_
|
||||
#endif
|
||||
#define _TTHREAD_PLATFORM_DEFINED_
|
||||
#endif
|
||||
|
||||
/* Activate some POSIX functionality (e.g. clock_gettime and recursive mutexes) */
|
||||
#if defined(_TTHREAD_POSIX_)
|
||||
#undef _FEATURES_H
|
||||
#if !defined(_GNU_SOURCE)
|
||||
#define _GNU_SOURCE
|
||||
#endif
|
||||
#if !defined(_POSIX_C_SOURCE) || ((_POSIX_C_SOURCE - 0) < 199309L)
|
||||
#undef _POSIX_C_SOURCE
|
||||
#define _POSIX_C_SOURCE 199309L
|
||||
#endif
|
||||
#if !defined(_XOPEN_SOURCE) || ((_XOPEN_SOURCE - 0) < 500)
|
||||
#undef _XOPEN_SOURCE
|
||||
#define _XOPEN_SOURCE 500
|
||||
#endif
|
||||
#define _XPG6
|
||||
#endif
|
||||
|
||||
/* Generic includes */
|
||||
#include <time.h>
|
||||
|
||||
/* Platform specific includes */
|
||||
#if defined(_TTHREAD_POSIX_)
|
||||
#include <pthread.h>
|
||||
#elif defined(_TTHREAD_WIN32_)
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#define __UNDEF_LEAN_AND_MEAN
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#ifdef __UNDEF_LEAN_AND_MEAN
|
||||
#undef WIN32_LEAN_AND_MEAN
|
||||
#undef __UNDEF_LEAN_AND_MEAN
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/* Compiler-specific information */
|
||||
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
|
||||
#define TTHREAD_NORETURN _Noreturn
|
||||
#elif defined(__GNUC__)
|
||||
#define TTHREAD_NORETURN __attribute__((__noreturn__))
|
||||
#else
|
||||
#define TTHREAD_NORETURN
|
||||
#endif
|
||||
|
||||
/* If TIME_UTC is missing, provide it and provide a wrapper for
|
||||
timespec_get. */
|
||||
#ifndef TIME_UTC
|
||||
#define TIME_UTC 1
|
||||
#define _TTHREAD_EMULATE_TIMESPEC_GET_
|
||||
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
struct _tthread_timespec {
|
||||
time_t tv_sec;
|
||||
long tv_nsec;
|
||||
};
|
||||
#define timespec _tthread_timespec
|
||||
#endif
|
||||
|
||||
int _tthread_timespec_get(struct timespec *ts, int base);
|
||||
#define timespec_get _tthread_timespec_get
|
||||
#endif
|
||||
|
||||
/** TinyCThread version (major number). */
|
||||
#define TINYCTHREAD_VERSION_MAJOR 1
|
||||
/** TinyCThread version (minor number). */
|
||||
#define TINYCTHREAD_VERSION_MINOR 2
|
||||
/** TinyCThread version (full version). */
|
||||
#define TINYCTHREAD_VERSION (TINYCTHREAD_VERSION_MAJOR * 100 + TINYCTHREAD_VERSION_MINOR)
|
||||
|
||||
/**
|
||||
* @def _Thread_local
|
||||
* Thread local storage keyword.
|
||||
* A variable that is declared with the @c _Thread_local keyword makes the
|
||||
* value of the variable local to each thread (known as thread-local storage,
|
||||
* or TLS). Example usage:
|
||||
* @code
|
||||
* // This variable is local to each thread.
|
||||
* _Thread_local int variable;
|
||||
* @endcode
|
||||
* @note The @c _Thread_local keyword is a macro that maps to the corresponding
|
||||
* compiler directive (e.g. @c __declspec(thread)).
|
||||
* @note This directive is currently not supported on Mac OS X (it will give
|
||||
* a compiler error), since compile-time TLS is not supported in the Mac OS X
|
||||
* executable format. Also, some older versions of MinGW (before GCC 4.x) do
|
||||
* not support this directive, nor does the Tiny C Compiler.
|
||||
* @hideinitializer
|
||||
*/
|
||||
|
||||
#if !(defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201102L)) && !defined(_Thread_local)
|
||||
#if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__SUNPRO_CC) || defined(__IBMCPP__)
|
||||
#define _Thread_local __thread
|
||||
#else
|
||||
#define _Thread_local __declspec(thread)
|
||||
#endif
|
||||
#elif defined(__GNUC__) && defined(__GNUC_MINOR__) && (((__GNUC__ << 8) | __GNUC_MINOR__) < ((4 << 8) | 9))
|
||||
#define _Thread_local __thread
|
||||
#endif
|
||||
|
||||
/* Macros */
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
#define TSS_DTOR_ITERATIONS (4)
|
||||
#else
|
||||
#define TSS_DTOR_ITERATIONS PTHREAD_DESTRUCTOR_ITERATIONS
|
||||
#endif
|
||||
|
||||
/* Function return values */
|
||||
#define thrd_error 0 /**< The requested operation failed */
|
||||
#define thrd_success 1 /**< The requested operation succeeded */
|
||||
#define thrd_timedout 2 /**< The time specified in the call was reached without acquiring the requested resource */
|
||||
#define thrd_busy 3 /**< The requested operation failed because a tesource requested by a test and return function is already in use */
|
||||
#define thrd_nomem 4 /**< The requested operation failed because it was unable to allocate memory */
|
||||
|
||||
/* Mutex types */
|
||||
#define mtx_plain 0
|
||||
#define mtx_timed 1
|
||||
#define mtx_recursive 2
|
||||
|
||||
/* Mutex */
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
typedef struct {
|
||||
union {
|
||||
CRITICAL_SECTION cs; /* Critical section handle (used for non-timed mutexes) */
|
||||
HANDLE mut; /* Mutex handle (used for timed mutex) */
|
||||
} mHandle; /* Mutex handle */
|
||||
int mAlreadyLocked; /* TRUE if the mutex is already locked */
|
||||
int mRecursive; /* TRUE if the mutex is recursive */
|
||||
int mTimed; /* TRUE if the mutex is timed */
|
||||
} mtx_t;
|
||||
#else
|
||||
typedef pthread_mutex_t mtx_t;
|
||||
#endif
|
||||
|
||||
/** Create a mutex object.
|
||||
* @param mtx A mutex object.
|
||||
* @param type Bit-mask that must have one of the following six values:
|
||||
* @li @c mtx_plain for a simple non-recursive mutex
|
||||
* @li @c mtx_timed for a non-recursive mutex that supports timeout
|
||||
* @li @c mtx_plain | @c mtx_recursive (same as @c mtx_plain, but recursive)
|
||||
* @li @c mtx_timed | @c mtx_recursive (same as @c mtx_timed, but recursive)
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
*/
|
||||
int mtx_init(mtx_t *mtx, int type);
|
||||
|
||||
/** Release any resources used by the given mutex.
|
||||
* @param mtx A mutex object.
|
||||
*/
|
||||
void mtx_destroy(mtx_t *mtx);
|
||||
|
||||
/** Lock the given mutex.
|
||||
* Blocks until the given mutex can be locked. If the mutex is non-recursive, and
|
||||
* the calling thread already has a lock on the mutex, this call will block
|
||||
* forever.
|
||||
* @param mtx A mutex object.
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
*/
|
||||
int mtx_lock(mtx_t *mtx);
|
||||
|
||||
/** Lock the given mutex, or block until a specific point in time.
|
||||
* Blocks until either the given mutex can be locked, or the specified TIME_UTC
|
||||
* based time.
|
||||
* @param mtx A mutex object.
|
||||
* @param ts A UTC based calendar time
|
||||
* @return @ref The mtx_timedlock function returns thrd_success on success, or
|
||||
* thrd_timedout if the time specified was reached without acquiring the
|
||||
* requested resource, or thrd_error if the request could not be honored.
|
||||
*/
|
||||
int mtx_timedlock(mtx_t *mtx, const struct timespec *ts);
|
||||
|
||||
/** Try to lock the given mutex.
|
||||
* The specified mutex shall support either test and return or timeout. If the
|
||||
* mutex is already locked, the function returns without blocking.
|
||||
* @param mtx A mutex object.
|
||||
* @return @ref thrd_success on success, or @ref thrd_busy if the resource
|
||||
* requested is already in use, or @ref thrd_error if the request could not be
|
||||
* honored.
|
||||
*/
|
||||
int mtx_trylock(mtx_t *mtx);
|
||||
|
||||
/** Unlock the given mutex.
|
||||
* @param mtx A mutex object.
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
*/
|
||||
int mtx_unlock(mtx_t *mtx);
|
||||
|
||||
/* Condition variable */
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
typedef struct {
|
||||
HANDLE mEvents[2]; /* Signal and broadcast event HANDLEs. */
|
||||
unsigned int mWaitersCount; /* Count of the number of waiters. */
|
||||
CRITICAL_SECTION mWaitersCountLock; /* Serialize access to mWaitersCount. */
|
||||
} cnd_t;
|
||||
#else
|
||||
typedef pthread_cond_t cnd_t;
|
||||
#endif
|
||||
|
||||
/** Create a condition variable object.
|
||||
* @param cond A condition variable object.
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
*/
|
||||
int cnd_init(cnd_t *cond);
|
||||
|
||||
/** Release any resources used by the given condition variable.
|
||||
* @param cond A condition variable object.
|
||||
*/
|
||||
void cnd_destroy(cnd_t *cond);
|
||||
|
||||
/** Signal a condition variable.
|
||||
* Unblocks one of the threads that are blocked on the given condition variable
|
||||
* at the time of the call. If no threads are blocked on the condition variable
|
||||
* at the time of the call, the function does nothing and return success.
|
||||
* @param cond A condition variable object.
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
*/
|
||||
int cnd_signal(cnd_t *cond);
|
||||
|
||||
/** Broadcast a condition variable.
|
||||
* Unblocks all of the threads that are blocked on the given condition variable
|
||||
* at the time of the call. If no threads are blocked on the condition variable
|
||||
* at the time of the call, the function does nothing and return success.
|
||||
* @param cond A condition variable object.
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
*/
|
||||
int cnd_broadcast(cnd_t *cond);
|
||||
|
||||
/** Wait for a condition variable to become signaled.
|
||||
* The function atomically unlocks the given mutex and endeavors to block until
|
||||
* the given condition variable is signaled by a call to cnd_signal or to
|
||||
* cnd_broadcast. When the calling thread becomes unblocked it locks the mutex
|
||||
* before it returns.
|
||||
* @param cond A condition variable object.
|
||||
* @param mtx A mutex object.
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
*/
|
||||
int cnd_wait(cnd_t *cond, mtx_t *mtx);
|
||||
|
||||
/** Wait for a condition variable to become signaled.
|
||||
* The function atomically unlocks the given mutex and endeavors to block until
|
||||
* the given condition variable is signaled by a call to cnd_signal or to
|
||||
* cnd_broadcast, or until after the specified time. When the calling thread
|
||||
* becomes unblocked it locks the mutex before it returns.
|
||||
* @param cond A condition variable object.
|
||||
* @param mtx A mutex object.
|
||||
* @param xt A point in time at which the request will time out (absolute time).
|
||||
* @return @ref thrd_success upon success, or @ref thrd_timeout if the time
|
||||
* specified in the call was reached without acquiring the requested resource, or
|
||||
* @ref thrd_error if the request could not be honored.
|
||||
*/
|
||||
int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts);
|
||||
|
||||
/* Thread */
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
typedef HANDLE thrd_t;
|
||||
#else
|
||||
typedef pthread_t thrd_t;
|
||||
#endif
|
||||
|
||||
/** Thread start function.
|
||||
* Any thread that is started with the @ref thrd_create() function must be
|
||||
* started through a function of this type.
|
||||
* @param arg The thread argument (the @c arg argument of the corresponding
|
||||
* @ref thrd_create() call).
|
||||
* @return The thread return value, which can be obtained by another thread
|
||||
* by using the @ref thrd_join() function.
|
||||
*/
|
||||
typedef int (*thrd_start_t)(void *arg);
|
||||
|
||||
/** Create a new thread.
|
||||
* @param thr Identifier of the newly created thread.
|
||||
* @param func A function pointer to the function that will be executed in
|
||||
* the new thread.
|
||||
* @param arg An argument to the thread function.
|
||||
* @return @ref thrd_success on success, or @ref thrd_nomem if no memory could
|
||||
* be allocated for the thread requested, or @ref thrd_error if the request
|
||||
* could not be honored.
|
||||
* @note A thread’s identifier may be reused for a different thread once the
|
||||
* original thread has exited and either been detached or joined to another
|
||||
* thread.
|
||||
*/
|
||||
int thrd_create(thrd_t *thr, thrd_start_t func, void *arg);
|
||||
|
||||
/** Identify the calling thread.
|
||||
* @return The identifier of the calling thread.
|
||||
*/
|
||||
thrd_t thrd_current(void);
|
||||
|
||||
/** Dispose of any resources allocated to the thread when that thread exits.
|
||||
* @return thrd_success, or thrd_error on error
|
||||
*/
|
||||
int thrd_detach(thrd_t thr);
|
||||
|
||||
/** Compare two thread identifiers.
|
||||
* The function determines if two thread identifiers refer to the same thread.
|
||||
* @return Zero if the two thread identifiers refer to different threads.
|
||||
* Otherwise a nonzero value is returned.
|
||||
*/
|
||||
int thrd_equal(thrd_t thr0, thrd_t thr1);
|
||||
|
||||
/** Terminate execution of the calling thread.
|
||||
* @param res Result code of the calling thread.
|
||||
*/
|
||||
TTHREAD_NORETURN void thrd_exit(int res);
|
||||
|
||||
/** Wait for a thread to terminate.
|
||||
* The function joins the given thread with the current thread by blocking
|
||||
* until the other thread has terminated.
|
||||
* @param thr The thread to join with.
|
||||
* @param res If this pointer is not NULL, the function will store the result
|
||||
* code of the given thread in the integer pointed to by @c res.
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
*/
|
||||
int thrd_join(thrd_t thr, int *res);
|
||||
|
||||
/** Put the calling thread to sleep.
|
||||
* Suspend execution of the calling thread.
|
||||
* @param duration Interval to sleep for
|
||||
* @param remaining If non-NULL, this parameter will hold the remaining
|
||||
* time until time_point upon return. This will
|
||||
* typically be zero, but if the thread was woken up
|
||||
* by a signal that is not ignored before duration was
|
||||
* reached @c remaining will hold a positive time.
|
||||
* @return 0 (zero) on successful sleep, -1 if an interrupt occurred,
|
||||
* or a negative value if the operation fails.
|
||||
*/
|
||||
int thrd_sleep(const struct timespec *duration, struct timespec *remaining);
|
||||
|
||||
/** Yield execution to another thread.
|
||||
* Permit other threads to run, even if the current thread would ordinarily
|
||||
* continue to run.
|
||||
*/
|
||||
void thrd_yield(void);
|
||||
|
||||
/* Thread local storage */
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
typedef DWORD tss_t;
|
||||
#else
|
||||
typedef pthread_key_t tss_t;
|
||||
#endif
|
||||
|
||||
/** Destructor function for a thread-specific storage.
|
||||
* @param val The value of the destructed thread-specific storage.
|
||||
*/
|
||||
typedef void (*tss_dtor_t)(void *val);
|
||||
|
||||
/** Create a thread-specific storage.
|
||||
* @param key The unique key identifier that will be set if the function is
|
||||
* successful.
|
||||
* @param dtor Destructor function. This can be NULL.
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
* @note On Windows, the @c dtor will definitely be called when
|
||||
* appropriate for threads created with @ref thrd_create. It will be
|
||||
* called for other threads in most cases, the possible exception being
|
||||
* for DLLs loaded with LoadLibraryEx. In order to be certain, you
|
||||
* should use @ref thrd_create whenever possible.
|
||||
*/
|
||||
int tss_create(tss_t *key, tss_dtor_t dtor);
|
||||
|
||||
/** Delete a thread-specific storage.
|
||||
* The function releases any resources used by the given thread-specific
|
||||
* storage.
|
||||
* @param key The key that shall be deleted.
|
||||
*/
|
||||
void tss_delete(tss_t key);
|
||||
|
||||
/** Get the value for a thread-specific storage.
|
||||
* @param key The thread-specific storage identifier.
|
||||
* @return The value for the current thread held in the given thread-specific
|
||||
* storage.
|
||||
*/
|
||||
void *tss_get(tss_t key);
|
||||
|
||||
/** Set the value for a thread-specific storage.
|
||||
* @param key The thread-specific storage identifier.
|
||||
* @param val The value of the thread-specific storage to set for the current
|
||||
* thread.
|
||||
* @return @ref thrd_success on success, or @ref thrd_error if the request could
|
||||
* not be honored.
|
||||
*/
|
||||
int tss_set(tss_t key, void *val);
|
||||
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
typedef struct {
|
||||
LONG volatile status;
|
||||
CRITICAL_SECTION lock;
|
||||
} once_flag;
|
||||
#define ONCE_FLAG_INIT {0,}
|
||||
#else
|
||||
#ifndef once_flag
|
||||
#define once_flag pthread_once_t
|
||||
#endif
|
||||
#ifndef ONCE_FLAG_INIT
|
||||
#define ONCE_FLAG_INIT PTHREAD_ONCE_INIT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/** Invoke a callback exactly once
|
||||
* @param flag Flag used to ensure the callback is invoked exactly
|
||||
* once.
|
||||
* @param func Callback to invoke.
|
||||
*/
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
void call_once(once_flag *flag, void (*func)(void));
|
||||
#else
|
||||
#ifndef call_once
|
||||
#define call_once(flag,func) pthread_once(flag,func)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* _TINYTHREAD_H_ */
|
||||
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Natanael Arndt, 2011: removed collate.h dependencies
|
||||
* (my changes are trivial)
|
||||
*
|
||||
* Copyright (c) 1989, 1993
|
||||
* The Regents of the University of California. All rights reserved.
|
||||
*
|
||||
* This code is derived from software contributed to Berkeley by
|
||||
* Guido van Rossum.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 4. Neither the name of the University nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
|
||||
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
||||
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
||||
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
* SUCH DAMAGE.
|
||||
*/
|
||||
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 Anders Kalør
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,7 @@
|
||||
Copyright (c) 2012 William Woodall, John Harrison
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,25 @@
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
Copyright (c) 2012 Marcus Geelnard
|
||||
2013-2016 Evan Nemerson
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
+908
@@ -0,0 +1,908 @@
|
||||
/*
|
||||
* Natanael Arndt, 2011: removed collate.h dependencies
|
||||
* (my changes are trivial)
|
||||
*
|
||||
* Copyright (c) 1989, 1993
|
||||
* The Regents of the University of California. All rights reserved.
|
||||
*
|
||||
* This code is derived from software contributed to Berkeley by
|
||||
* Guido van Rossum.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 4. Neither the name of the University nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
|
||||
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
||||
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
||||
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
* SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#if defined(LIBC_SCCS) && !defined(lint)
|
||||
static char sccsid[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93";
|
||||
#endif /* LIBC_SCCS and not lint */
|
||||
#include <sys/cdefs.h>
|
||||
__FBSDID("$FreeBSD$");
|
||||
|
||||
/*
|
||||
* glob(3) -- a superset of the one defined in POSIX 1003.2.
|
||||
*
|
||||
* The [!...] convention to negate a range is supported (SysV, Posix, ksh).
|
||||
*
|
||||
* Optional extra services, controlled by flags not defined by POSIX:
|
||||
*
|
||||
* GLOB_QUOTE:
|
||||
* Escaping convention: \ inhibits any special meaning the following
|
||||
* character might have (except \ at end of string is retained).
|
||||
* GLOB_MAGCHAR:
|
||||
* Set in gl_flags if pattern contained a globbing character.
|
||||
* GLOB_NOMAGIC:
|
||||
* Same as GLOB_NOCHECK, but it will only append pattern if it did
|
||||
* not contain any magic characters. [Used in csh style globbing]
|
||||
* GLOB_ALTDIRFUNC:
|
||||
* Use alternately specified directory access functions.
|
||||
* GLOB_TILDE:
|
||||
* expand ~user/foo to the /home/dir/of/user/foo
|
||||
* GLOB_BRACE:
|
||||
* expand {1,2}{a,b} to 1a 1b 2a 2b
|
||||
* gl_matchc:
|
||||
* Number of matches in the current invocation of glob.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Some notes on multibyte character support:
|
||||
* 1. Patterns with illegal byte sequences match nothing - even if
|
||||
* GLOB_NOCHECK is specified.
|
||||
* 2. Illegal byte sequences in filenames are handled by treating them as
|
||||
* single-byte characters with a value of the first byte of the sequence
|
||||
* cast to wchar_t.
|
||||
* 3. State-dependent encodings are not currently supported.
|
||||
*/
|
||||
|
||||
#include <sys/param.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <ctype.h>
|
||||
#include <dirent.h>
|
||||
#include <errno.h>
|
||||
#include "cglob.h"
|
||||
#include <limits.h>
|
||||
#include <pwd.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <wchar.h>
|
||||
|
||||
#define DOLLAR '$'
|
||||
#define DOT '.'
|
||||
#define EOS '\0'
|
||||
#define LBRACKET '['
|
||||
#define NOT '!'
|
||||
#define QUESTION '?'
|
||||
#define QUOTE '\\'
|
||||
#define RANGE '-'
|
||||
#define RBRACKET ']'
|
||||
#define SEP '/'
|
||||
#define STAR '*'
|
||||
#define TILDE '~'
|
||||
#define UNDERSCORE '_'
|
||||
#define LBRACE '{'
|
||||
#define RBRACE '}'
|
||||
#define SLASH '/'
|
||||
#define COMMA ','
|
||||
|
||||
#ifndef DEBUG
|
||||
|
||||
#define M_QUOTE 0x8000000000ULL
|
||||
#define M_PROTECT 0x4000000000ULL
|
||||
#define M_MASK 0xffffffffffULL
|
||||
#define M_CHAR 0x00ffffffffULL
|
||||
|
||||
typedef uint_fast64_t Char;
|
||||
|
||||
#else
|
||||
|
||||
#define M_QUOTE 0x80
|
||||
#define M_PROTECT 0x40
|
||||
#define M_MASK 0xff
|
||||
#define M_CHAR 0x7f
|
||||
|
||||
typedef char Char;
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
#define CHAR(c) ((Char)((c)&M_CHAR))
|
||||
#define META(c) ((Char)((c)|M_QUOTE))
|
||||
#define M_ALL META('*')
|
||||
#define M_END META(']')
|
||||
#define M_NOT META('!')
|
||||
#define M_ONE META('?')
|
||||
#define M_RNG META('-')
|
||||
#define M_SET META('[')
|
||||
#define ismeta(c) (((c)&M_QUOTE) != 0)
|
||||
|
||||
|
||||
static int compare(const void *, const void *);
|
||||
static int g_Ctoc(const Char *, char *, size_t);
|
||||
static int g_lstat(Char *, struct stat *, cglob_t *);
|
||||
static DIR *g_opendir(Char *, cglob_t *);
|
||||
static const Char *g_strchr(const Char *, wchar_t);
|
||||
#ifdef notdef
|
||||
static Char *g_strcat(Char *, const Char *);
|
||||
#endif
|
||||
static int g_stat(Char *, struct stat *, cglob_t *);
|
||||
static int glob0(const Char *, cglob_t *, size_t *);
|
||||
static int glob1(Char *, cglob_t *, size_t *);
|
||||
static int glob2(Char *, Char *, Char *, Char *, cglob_t *, size_t *);
|
||||
static int glob3(Char *, Char *, Char *, Char *, Char *, cglob_t *, size_t *);
|
||||
static int globextend(const Char *, cglob_t *, size_t *);
|
||||
static const Char *
|
||||
globtilde(const Char *, Char *, size_t, cglob_t *);
|
||||
static int globexp1(const Char *, cglob_t *, size_t *);
|
||||
static int globexp2(const Char *, const Char *, cglob_t *, int *, size_t *);
|
||||
static int match(Char *, Char *, Char *);
|
||||
#ifdef DEBUG
|
||||
static void qprintf(const char *, Char *);
|
||||
#endif
|
||||
|
||||
int
|
||||
cglob(const char *pattern, int flags, int (*errfunc)(const char *, int), cglob_t *pglob)
|
||||
{
|
||||
const char *patnext;
|
||||
size_t limit;
|
||||
Char *bufnext, *bufend, patbuf[MAXPATHLEN], prot;
|
||||
mbstate_t mbs;
|
||||
wchar_t wc;
|
||||
size_t clen;
|
||||
|
||||
patnext = pattern;
|
||||
if (!(flags & GLOB_APPEND)) {
|
||||
pglob->gl_pathc = 0;
|
||||
pglob->gl_pathv = NULL;
|
||||
if (!(flags & GLOB_DOOFFS))
|
||||
pglob->gl_offs = 0;
|
||||
}
|
||||
|
||||
if (flags & GLOB_LIMIT) {
|
||||
limit = pglob->gl_matchc;
|
||||
if (limit == 0)
|
||||
limit = ARG_MAX;
|
||||
} else
|
||||
limit = 0;
|
||||
|
||||
pglob->gl_flags = flags & ~GLOB_MAGCHAR;
|
||||
pglob->gl_errfunc = errfunc;
|
||||
pglob->gl_matchc = 0;
|
||||
|
||||
bufnext = patbuf;
|
||||
bufend = bufnext + MAXPATHLEN - 1;
|
||||
if (flags & GLOB_NOESCAPE) {
|
||||
memset(&mbs, 0, sizeof(mbs));
|
||||
while (bufend - bufnext >= MB_CUR_MAX) {
|
||||
clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
|
||||
if (clen == (size_t)-1 || clen == (size_t)-2)
|
||||
return (GLOB_NOMATCH);
|
||||
else if (clen == 0)
|
||||
break;
|
||||
*bufnext++ = wc;
|
||||
patnext += clen;
|
||||
}
|
||||
} else {
|
||||
/* Protect the quoted characters. */
|
||||
memset(&mbs, 0, sizeof(mbs));
|
||||
while (bufend - bufnext >= MB_CUR_MAX) {
|
||||
if (*patnext == QUOTE) {
|
||||
if (*++patnext == EOS) {
|
||||
*bufnext++ = QUOTE | M_PROTECT;
|
||||
continue;
|
||||
}
|
||||
prot = M_PROTECT;
|
||||
} else
|
||||
prot = 0;
|
||||
clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
|
||||
if (clen == (size_t)-1 || clen == (size_t)-2)
|
||||
return (GLOB_NOMATCH);
|
||||
else if (clen == 0)
|
||||
break;
|
||||
*bufnext++ = wc | prot;
|
||||
patnext += clen;
|
||||
}
|
||||
}
|
||||
*bufnext = EOS;
|
||||
|
||||
if (flags & GLOB_BRACE)
|
||||
return globexp1(patbuf, pglob, &limit);
|
||||
else
|
||||
return glob0(patbuf, pglob, &limit);
|
||||
}
|
||||
|
||||
/*
|
||||
* Expand recursively a glob {} pattern. When there is no more expansion
|
||||
* invoke the standard globbing routine to glob the rest of the magic
|
||||
* characters
|
||||
*/
|
||||
static int
|
||||
globexp1(const Char *pattern, cglob_t *pglob, size_t *limit)
|
||||
{
|
||||
const Char* ptr = pattern;
|
||||
int rv;
|
||||
|
||||
/* Protect a single {}, for find(1), like csh */
|
||||
if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
|
||||
return glob0(pattern, pglob, limit);
|
||||
|
||||
while ((ptr = g_strchr(ptr, LBRACE)) != NULL)
|
||||
if (!globexp2(ptr, pattern, pglob, &rv, limit))
|
||||
return rv;
|
||||
|
||||
return glob0(pattern, pglob, limit);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Recursive brace globbing helper. Tries to expand a single brace.
|
||||
* If it succeeds then it invokes globexp1 with the new pattern.
|
||||
* If it fails then it tries to glob the rest of the pattern and returns.
|
||||
*/
|
||||
static int
|
||||
globexp2(const Char *ptr, const Char *pattern, cglob_t *pglob, int *rv, size_t *limit)
|
||||
{
|
||||
int i;
|
||||
Char *lm, *ls;
|
||||
const Char *pe, *pm, *pm1, *pl;
|
||||
Char patbuf[MAXPATHLEN];
|
||||
|
||||
/* copy part up to the brace */
|
||||
for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
|
||||
continue;
|
||||
*lm = EOS;
|
||||
ls = lm;
|
||||
|
||||
/* Find the balanced brace */
|
||||
for (i = 0, pe = ++ptr; *pe; pe++)
|
||||
if (*pe == LBRACKET) {
|
||||
/* Ignore everything between [] */
|
||||
for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
|
||||
continue;
|
||||
if (*pe == EOS) {
|
||||
/*
|
||||
* We could not find a matching RBRACKET.
|
||||
* Ignore and just look for RBRACE
|
||||
*/
|
||||
pe = pm;
|
||||
}
|
||||
}
|
||||
else if (*pe == LBRACE)
|
||||
i++;
|
||||
else if (*pe == RBRACE) {
|
||||
if (i == 0)
|
||||
break;
|
||||
i--;
|
||||
}
|
||||
|
||||
/* Non matching braces; just glob the pattern */
|
||||
if (i != 0 || *pe == EOS) {
|
||||
*rv = glob0(patbuf, pglob, limit);
|
||||
return 0;
|
||||
}
|
||||
|
||||
for (i = 0, pl = pm = ptr; pm <= pe; pm++)
|
||||
switch (*pm) {
|
||||
case LBRACKET:
|
||||
/* Ignore everything between [] */
|
||||
for (pm1 = pm++; *pm != RBRACKET && *pm != EOS; pm++)
|
||||
continue;
|
||||
if (*pm == EOS) {
|
||||
/*
|
||||
* We could not find a matching RBRACKET.
|
||||
* Ignore and just look for RBRACE
|
||||
*/
|
||||
pm = pm1;
|
||||
}
|
||||
break;
|
||||
|
||||
case LBRACE:
|
||||
i++;
|
||||
break;
|
||||
|
||||
case RBRACE:
|
||||
if (i) {
|
||||
i--;
|
||||
break;
|
||||
}
|
||||
/* FALLTHROUGH */
|
||||
case COMMA:
|
||||
if (i && *pm == COMMA)
|
||||
break;
|
||||
else {
|
||||
/* Append the current string */
|
||||
for (lm = ls; (pl < pm); *lm++ = *pl++)
|
||||
continue;
|
||||
/*
|
||||
* Append the rest of the pattern after the
|
||||
* closing brace
|
||||
*/
|
||||
for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
|
||||
continue;
|
||||
|
||||
/* Expand the current pattern */
|
||||
#ifdef DEBUG
|
||||
qprintf("globexp2:", patbuf);
|
||||
#endif
|
||||
*rv = globexp1(patbuf, pglob, limit);
|
||||
|
||||
/* move after the comma, to the next string */
|
||||
pl = pm + 1;
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
*rv = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* expand tilde from the passwd file.
|
||||
*/
|
||||
static const Char *
|
||||
globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, cglob_t *pglob)
|
||||
{
|
||||
struct passwd *pwd;
|
||||
char *h;
|
||||
const Char *p;
|
||||
Char *b, *eb;
|
||||
|
||||
if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
|
||||
return pattern;
|
||||
|
||||
/*
|
||||
* Copy up to the end of the string or /
|
||||
*/
|
||||
eb = &patbuf[patbuf_len - 1];
|
||||
for (p = pattern + 1, h = (char *) patbuf;
|
||||
h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
|
||||
continue;
|
||||
|
||||
*h = EOS;
|
||||
|
||||
if (((char *) patbuf)[0] == EOS) {
|
||||
/*
|
||||
* handle a plain ~ or ~/ by expanding $HOME first (iff
|
||||
* we're not running setuid or setgid) and then trying
|
||||
* the password file
|
||||
*/
|
||||
/*if (issetugid() != 0 ||
|
||||
(h = getenv("HOME")) == NULL) {
|
||||
if (((h = getlogin()) != NULL &&
|
||||
(pwd = getpwnam(h)) != NULL) ||
|
||||
(pwd = getpwuid(getuid())) != NULL)
|
||||
h = pwd->pw_dir;
|
||||
else
|
||||
return pattern;
|
||||
}*/
|
||||
}
|
||||
else {
|
||||
/*
|
||||
* Expand a ~user
|
||||
*/
|
||||
if ((pwd = getpwnam((char*) patbuf)) == NULL)
|
||||
return pattern;
|
||||
else
|
||||
h = pwd->pw_dir;
|
||||
}
|
||||
|
||||
/* Copy the home directory */
|
||||
for (b = patbuf; b < eb && *h; *b++ = *h++)
|
||||
continue;
|
||||
|
||||
/* Append the rest of the pattern */
|
||||
while (b < eb && (*b++ = *p++) != EOS)
|
||||
continue;
|
||||
*b = EOS;
|
||||
|
||||
return patbuf;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* The main glob() routine: compiles the pattern (optionally processing
|
||||
* quotes), calls glob1() to do the real pattern matching, and finally
|
||||
* sorts the list (unless unsorted operation is requested). Returns 0
|
||||
* if things went well, nonzero if errors occurred.
|
||||
*/
|
||||
static int
|
||||
glob0(const Char *pattern, cglob_t *pglob, size_t *limit)
|
||||
{
|
||||
const Char *qpatnext;
|
||||
int err;
|
||||
size_t oldpathc;
|
||||
Char *bufnext, c, patbuf[MAXPATHLEN];
|
||||
|
||||
qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
|
||||
oldpathc = pglob->gl_pathc;
|
||||
bufnext = patbuf;
|
||||
|
||||
/* We don't need to check for buffer overflow any more. */
|
||||
while ((c = *qpatnext++) != EOS) {
|
||||
switch (c) {
|
||||
case LBRACKET:
|
||||
c = *qpatnext;
|
||||
if (c == NOT)
|
||||
++qpatnext;
|
||||
if (*qpatnext == EOS ||
|
||||
g_strchr(qpatnext+1, RBRACKET) == NULL) {
|
||||
*bufnext++ = LBRACKET;
|
||||
if (c == NOT)
|
||||
--qpatnext;
|
||||
break;
|
||||
}
|
||||
*bufnext++ = M_SET;
|
||||
if (c == NOT)
|
||||
*bufnext++ = M_NOT;
|
||||
c = *qpatnext++;
|
||||
do {
|
||||
*bufnext++ = CHAR(c);
|
||||
if (*qpatnext == RANGE &&
|
||||
(c = qpatnext[1]) != RBRACKET) {
|
||||
*bufnext++ = M_RNG;
|
||||
*bufnext++ = CHAR(c);
|
||||
qpatnext += 2;
|
||||
}
|
||||
} while ((c = *qpatnext++) != RBRACKET);
|
||||
pglob->gl_flags |= GLOB_MAGCHAR;
|
||||
*bufnext++ = M_END;
|
||||
break;
|
||||
case QUESTION:
|
||||
pglob->gl_flags |= GLOB_MAGCHAR;
|
||||
*bufnext++ = M_ONE;
|
||||
break;
|
||||
case STAR:
|
||||
pglob->gl_flags |= GLOB_MAGCHAR;
|
||||
/* collapse adjacent stars to one,
|
||||
* to avoid exponential behavior
|
||||
*/
|
||||
if (bufnext == patbuf || bufnext[-1] != M_ALL)
|
||||
*bufnext++ = M_ALL;
|
||||
break;
|
||||
default:
|
||||
*bufnext++ = CHAR(c);
|
||||
break;
|
||||
}
|
||||
}
|
||||
*bufnext = EOS;
|
||||
#ifdef DEBUG
|
||||
qprintf("glob0:", patbuf);
|
||||
#endif
|
||||
|
||||
if ((err = glob1(patbuf, pglob, limit)) != 0)
|
||||
return(err);
|
||||
|
||||
/*
|
||||
* If there was no match we are going to append the pattern
|
||||
* if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
|
||||
* and the pattern did not contain any magic characters
|
||||
* GLOB_NOMAGIC is there just for compatibility with csh.
|
||||
*/
|
||||
if (pglob->gl_pathc == oldpathc) {
|
||||
if (((pglob->gl_flags & GLOB_NOCHECK) ||
|
||||
((pglob->gl_flags & GLOB_NOMAGIC) &&
|
||||
!(pglob->gl_flags & GLOB_MAGCHAR))))
|
||||
return(globextend(pattern, pglob, limit));
|
||||
else
|
||||
return(GLOB_NOMATCH);
|
||||
}
|
||||
if (!(pglob->gl_flags & GLOB_NOSORT))
|
||||
qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
|
||||
pglob->gl_pathc - oldpathc, sizeof(char *), compare);
|
||||
return(0);
|
||||
}
|
||||
|
||||
static int
|
||||
compare(const void *p, const void *q)
|
||||
{
|
||||
return(strcmp(*(char **)p, *(char **)q));
|
||||
}
|
||||
|
||||
static int
|
||||
glob1(Char *pattern, cglob_t *pglob, size_t *limit)
|
||||
{
|
||||
Char pathbuf[MAXPATHLEN];
|
||||
|
||||
/* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
|
||||
if (*pattern == EOS)
|
||||
return(0);
|
||||
return(glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1,
|
||||
pattern, pglob, limit));
|
||||
}
|
||||
|
||||
/*
|
||||
* The functions glob2 and glob3 are mutually recursive; there is one level
|
||||
* of recursion for each segment in the pattern that contains one or more
|
||||
* meta characters.
|
||||
*/
|
||||
static int
|
||||
glob2(Char *pathbuf, Char *pathend, Char *pathend_last, Char *pattern,
|
||||
cglob_t *pglob, size_t *limit)
|
||||
{
|
||||
struct stat sb;
|
||||
Char *p, *q;
|
||||
int anymeta;
|
||||
|
||||
/*
|
||||
* Loop over pattern segments until end of pattern or until
|
||||
* segment with meta character found.
|
||||
*/
|
||||
for (anymeta = 0;;) {
|
||||
if (*pattern == EOS) { /* End of pattern? */
|
||||
*pathend = EOS;
|
||||
if (g_lstat(pathbuf, &sb, pglob))
|
||||
return(0);
|
||||
|
||||
if (((pglob->gl_flags & GLOB_MARK) &&
|
||||
pathend[-1] != SEP) && (S_ISDIR(sb.st_mode)
|
||||
|| (S_ISLNK(sb.st_mode) &&
|
||||
(g_stat(pathbuf, &sb, pglob) == 0) &&
|
||||
S_ISDIR(sb.st_mode)))) {
|
||||
if (pathend + 1 > pathend_last)
|
||||
return (GLOB_ABORTED);
|
||||
*pathend++ = SEP;
|
||||
*pathend = EOS;
|
||||
}
|
||||
++pglob->gl_matchc;
|
||||
return(globextend(pathbuf, pglob, limit));
|
||||
}
|
||||
|
||||
/* Find end of next segment, copy tentatively to pathend. */
|
||||
q = pathend;
|
||||
p = pattern;
|
||||
while (*p != EOS && *p != SEP) {
|
||||
if (ismeta(*p))
|
||||
anymeta = 1;
|
||||
if (q + 1 > pathend_last)
|
||||
return (GLOB_ABORTED);
|
||||
*q++ = *p++;
|
||||
}
|
||||
|
||||
if (!anymeta) { /* No expansion, do next segment. */
|
||||
pathend = q;
|
||||
pattern = p;
|
||||
while (*pattern == SEP) {
|
||||
if (pathend + 1 > pathend_last)
|
||||
return (GLOB_ABORTED);
|
||||
*pathend++ = *pattern++;
|
||||
}
|
||||
} else /* Need expansion, recurse. */
|
||||
return(glob3(pathbuf, pathend, pathend_last, pattern, p,
|
||||
pglob, limit));
|
||||
}
|
||||
/* NOTREACHED */
|
||||
}
|
||||
|
||||
static int
|
||||
glob3(Char *pathbuf, Char *pathend, Char *pathend_last,
|
||||
Char *pattern, Char *restpattern,
|
||||
cglob_t *pglob, size_t *limit)
|
||||
{
|
||||
struct dirent *dp;
|
||||
DIR *dirp;
|
||||
int err;
|
||||
char buf[MAXPATHLEN];
|
||||
|
||||
/*
|
||||
* The readdirfunc declaration can't be prototyped, because it is
|
||||
* assigned, below, to two functions which are prototyped in glob.h
|
||||
* and dirent.h as taking pointers to differently typed opaque
|
||||
* structures.
|
||||
*/
|
||||
struct dirent *(*readdirfunc)();
|
||||
|
||||
if (pathend > pathend_last)
|
||||
return (GLOB_ABORTED);
|
||||
*pathend = EOS;
|
||||
errno = 0;
|
||||
|
||||
if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
|
||||
/* TODO: don't call for ENOENT or ENOTDIR? */
|
||||
if (pglob->gl_errfunc) {
|
||||
if (g_Ctoc(pathbuf, buf, sizeof(buf)))
|
||||
return (GLOB_ABORTED);
|
||||
if (pglob->gl_errfunc(buf, errno) ||
|
||||
pglob->gl_flags & GLOB_ERR)
|
||||
return (GLOB_ABORTED);
|
||||
}
|
||||
return(0);
|
||||
}
|
||||
|
||||
err = 0;
|
||||
|
||||
/* Search directory for matching names. */
|
||||
if (pglob->gl_flags & GLOB_ALTDIRFUNC)
|
||||
readdirfunc = pglob->gl_readdir;
|
||||
else
|
||||
readdirfunc = readdir;
|
||||
while ((dp = (*readdirfunc)(dirp))) {
|
||||
char *sc;
|
||||
Char *dc;
|
||||
wchar_t wc;
|
||||
size_t clen;
|
||||
mbstate_t mbs;
|
||||
|
||||
/* Initial DOT must be matched literally. */
|
||||
if (dp->d_name[0] == DOT && *pattern != DOT)
|
||||
continue;
|
||||
memset(&mbs, 0, sizeof(mbs));
|
||||
dc = pathend;
|
||||
sc = dp->d_name;
|
||||
while (dc < pathend_last) {
|
||||
clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs);
|
||||
if (clen == (size_t)-1 || clen == (size_t)-2) {
|
||||
wc = *sc;
|
||||
clen = 1;
|
||||
memset(&mbs, 0, sizeof(mbs));
|
||||
}
|
||||
if ((*dc++ = wc) == EOS)
|
||||
break;
|
||||
sc += clen;
|
||||
}
|
||||
if (!match(pathend, pattern, restpattern)) {
|
||||
*pathend = EOS;
|
||||
continue;
|
||||
}
|
||||
err = glob2(pathbuf, --dc, pathend_last, restpattern,
|
||||
pglob, limit);
|
||||
if (err)
|
||||
break;
|
||||
}
|
||||
|
||||
if (pglob->gl_flags & GLOB_ALTDIRFUNC)
|
||||
(*pglob->gl_closedir)(dirp);
|
||||
else
|
||||
closedir(dirp);
|
||||
return(err);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Extend the gl_pathv member of a glob_t structure to accomodate a new item,
|
||||
* add the new item, and update gl_pathc.
|
||||
*
|
||||
* This assumes the BSD realloc, which only copies the block when its size
|
||||
* crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
|
||||
* behavior.
|
||||
*
|
||||
* Return 0 if new item added, error code if memory couldn't be allocated.
|
||||
*
|
||||
* Invariant of the glob_t structure:
|
||||
* Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
|
||||
* gl_pathv points to (gl_offs + gl_pathc + 1) items.
|
||||
*/
|
||||
static int
|
||||
globextend(const Char *path, cglob_t *pglob, size_t *limit)
|
||||
{
|
||||
char **pathv;
|
||||
size_t i, newsize, len;
|
||||
char *copy;
|
||||
const Char *p;
|
||||
|
||||
if (*limit && pglob->gl_pathc > *limit) {
|
||||
errno = 0;
|
||||
return (GLOB_NOSPACE);
|
||||
}
|
||||
|
||||
newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
|
||||
pathv = pglob->gl_pathv ?
|
||||
realloc((char *)pglob->gl_pathv, newsize) :
|
||||
malloc(newsize);
|
||||
if (pathv == NULL) {
|
||||
if (pglob->gl_pathv) {
|
||||
free(pglob->gl_pathv);
|
||||
pglob->gl_pathv = NULL;
|
||||
}
|
||||
return(GLOB_NOSPACE);
|
||||
}
|
||||
|
||||
if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
|
||||
/* first time around -- clear initial gl_offs items */
|
||||
pathv += pglob->gl_offs;
|
||||
for (i = pglob->gl_offs + 1; --i > 0; )
|
||||
*--pathv = NULL;
|
||||
}
|
||||
pglob->gl_pathv = pathv;
|
||||
|
||||
for (p = path; *p++;)
|
||||
continue;
|
||||
len = MB_CUR_MAX * (size_t)(p - path); /* XXX overallocation */
|
||||
if ((copy = malloc(len)) != NULL) {
|
||||
if (g_Ctoc(path, copy, len)) {
|
||||
free(copy);
|
||||
return (GLOB_NOSPACE);
|
||||
}
|
||||
pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
|
||||
}
|
||||
pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
|
||||
return(copy == NULL ? GLOB_NOSPACE : 0);
|
||||
}
|
||||
|
||||
/*
|
||||
* pattern matching function for filenames. Each occurrence of the *
|
||||
* pattern causes a recursion level.
|
||||
*/
|
||||
static int
|
||||
match(Char *name, Char *pat, Char *patend)
|
||||
{
|
||||
int ok, negate_range;
|
||||
Char c, k;
|
||||
|
||||
while (pat < patend) {
|
||||
c = *pat++;
|
||||
switch (c & M_MASK) {
|
||||
case M_ALL:
|
||||
if (pat == patend)
|
||||
return(1);
|
||||
do
|
||||
if (match(name, pat, patend))
|
||||
return(1);
|
||||
while (*name++ != EOS);
|
||||
return(0);
|
||||
case M_ONE:
|
||||
if (*name++ == EOS)
|
||||
return(0);
|
||||
break;
|
||||
case M_SET:
|
||||
ok = 0;
|
||||
if ((k = *name++) == EOS)
|
||||
return(0);
|
||||
if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
|
||||
++pat;
|
||||
while (((c = *pat++) & M_MASK) != M_END)
|
||||
if ((*pat & M_MASK) == M_RNG) {
|
||||
if (CHAR(c) <= CHAR(k) && CHAR(k) <= CHAR(pat[1])) ok = 1;
|
||||
pat += 2;
|
||||
} else if (c == k)
|
||||
ok = 1;
|
||||
if (ok == negate_range)
|
||||
return(0);
|
||||
break;
|
||||
default:
|
||||
if (*name++ != c)
|
||||
return(0);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return(*name == EOS);
|
||||
}
|
||||
|
||||
/* Free allocated data belonging to a glob_t structure. */
|
||||
void
|
||||
cglobfree(cglob_t *pglob)
|
||||
{
|
||||
size_t i;
|
||||
char **pp;
|
||||
|
||||
if (pglob->gl_pathv != NULL) {
|
||||
pp = pglob->gl_pathv + pglob->gl_offs;
|
||||
for (i = pglob->gl_pathc; i--; ++pp)
|
||||
if (*pp)
|
||||
free(*pp);
|
||||
free(pglob->gl_pathv);
|
||||
pglob->gl_pathv = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
static DIR *
|
||||
g_opendir(Char *str, cglob_t *pglob)
|
||||
{
|
||||
char buf[MAXPATHLEN];
|
||||
|
||||
if (!*str)
|
||||
strcpy(buf, ".");
|
||||
else {
|
||||
if (g_Ctoc(str, buf, sizeof(buf)))
|
||||
return (NULL);
|
||||
}
|
||||
|
||||
if (pglob->gl_flags & GLOB_ALTDIRFUNC)
|
||||
return((*pglob->gl_opendir)(buf));
|
||||
|
||||
return(opendir(buf));
|
||||
}
|
||||
|
||||
static int
|
||||
g_lstat(Char *fn, struct stat *sb, cglob_t *pglob)
|
||||
{
|
||||
char buf[MAXPATHLEN];
|
||||
|
||||
if (g_Ctoc(fn, buf, sizeof(buf))) {
|
||||
errno = ENAMETOOLONG;
|
||||
return (-1);
|
||||
}
|
||||
if (pglob->gl_flags & GLOB_ALTDIRFUNC)
|
||||
return((*pglob->gl_lstat)(buf, sb));
|
||||
return(lstat(buf, sb));
|
||||
}
|
||||
|
||||
static int
|
||||
g_stat(Char *fn, struct stat *sb, cglob_t *pglob)
|
||||
{
|
||||
char buf[MAXPATHLEN];
|
||||
|
||||
if (g_Ctoc(fn, buf, sizeof(buf))) {
|
||||
errno = ENAMETOOLONG;
|
||||
return (-1);
|
||||
}
|
||||
if (pglob->gl_flags & GLOB_ALTDIRFUNC)
|
||||
return((*pglob->gl_stat)(buf, sb));
|
||||
return(stat(buf, sb));
|
||||
}
|
||||
|
||||
static const Char *
|
||||
g_strchr(const Char *str, wchar_t ch)
|
||||
{
|
||||
|
||||
do {
|
||||
if (*str == ch)
|
||||
return (str);
|
||||
} while (*str++);
|
||||
return (NULL);
|
||||
}
|
||||
|
||||
static int
|
||||
g_Ctoc(const Char *str, char *buf, size_t len)
|
||||
{
|
||||
mbstate_t mbs;
|
||||
size_t clen;
|
||||
|
||||
memset(&mbs, 0, sizeof(mbs));
|
||||
while (len >= MB_CUR_MAX) {
|
||||
clen = wcrtomb(buf, *str, &mbs);
|
||||
if (clen == (size_t)-1)
|
||||
return (1);
|
||||
if (*str == L'\0')
|
||||
return (0);
|
||||
str++;
|
||||
buf += clen;
|
||||
len -= clen;
|
||||
}
|
||||
return (1);
|
||||
}
|
||||
|
||||
#ifdef DEBUG
|
||||
static void
|
||||
qprintf(const char *str, Char *s)
|
||||
{
|
||||
Char *p;
|
||||
|
||||
(void)printf("%s:\n", str);
|
||||
for (p = s; *p; p++)
|
||||
(void)printf("%c", CHAR(*p));
|
||||
(void)printf("\n");
|
||||
for (p = s; *p; p++)
|
||||
(void)printf("%c", *p & M_PROTECT ? '"' : ' ');
|
||||
(void)printf("\n");
|
||||
for (p = s; *p; p++)
|
||||
(void)printf("%c", ismeta(*p) ? '_' : ' ');
|
||||
(void)printf("\n");
|
||||
}
|
||||
#endif
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
#if defined(__linux__)
|
||||
|
||||
/*
|
||||
* Copyright (c) 2014 Craig Lilley <cralilley@gmail.com>
|
||||
* This software is made available under the terms of the MIT licence.
|
||||
* A copy of the licence can be obtained from:
|
||||
* http://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <cstdio>
|
||||
#include <cstdarg>
|
||||
#include <cstdlib>
|
||||
#ifdef ANDROID
|
||||
#include "cglob.h"
|
||||
#else
|
||||
#include <glob.h>
|
||||
#define cglob glob
|
||||
#define cglobfree globfree
|
||||
#define cglob_t glob_t
|
||||
#endif
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "serial/serial.h"
|
||||
|
||||
using serial::PortInfo;
|
||||
using std::istringstream;
|
||||
using std::ifstream;
|
||||
using std::getline;
|
||||
using std::vector;
|
||||
using std::string;
|
||||
using std::cout;
|
||||
using std::endl;
|
||||
|
||||
static vector<string> glob(const vector<string>& patterns);
|
||||
static string basename(const string& path);
|
||||
static string dirname(const string& path);
|
||||
static bool path_exists(const string& path);
|
||||
static string realpath(const string& path);
|
||||
static string usb_sysfs_friendly_name(const string& sys_usb_path);
|
||||
static vector<string> get_sysfs_info(const string& device_path);
|
||||
static string read_line(const string& file);
|
||||
static string usb_sysfs_hw_string(const string& sysfs_path);
|
||||
static string format(const char* format, ...);
|
||||
|
||||
vector<string>
|
||||
glob(const vector<string>& patterns)
|
||||
{
|
||||
vector<string> paths_found;
|
||||
|
||||
if(patterns.size() == 0)
|
||||
return paths_found;
|
||||
|
||||
cglob_t glob_results;
|
||||
|
||||
int glob_retval = cglob(patterns[0].c_str(), 0, NULL, &glob_results);
|
||||
|
||||
vector<string>::const_iterator iter = patterns.begin();
|
||||
|
||||
while(++iter != patterns.end())
|
||||
{
|
||||
glob_retval = cglob(iter->c_str(), GLOB_APPEND, NULL, &glob_results);
|
||||
}
|
||||
|
||||
for(int path_index = 0; path_index < glob_results.gl_pathc; path_index++)
|
||||
{
|
||||
paths_found.push_back(glob_results.gl_pathv[path_index]);
|
||||
}
|
||||
|
||||
cglobfree(&glob_results);
|
||||
|
||||
return paths_found;
|
||||
}
|
||||
|
||||
string
|
||||
basename(const string& path)
|
||||
{
|
||||
size_t pos = path.rfind("/");
|
||||
|
||||
if(pos == std::string::npos)
|
||||
return path;
|
||||
|
||||
return string(path, pos+1, string::npos);
|
||||
}
|
||||
|
||||
string
|
||||
dirname(const string& path)
|
||||
{
|
||||
size_t pos = path.rfind("/");
|
||||
|
||||
if(pos == std::string::npos)
|
||||
return path;
|
||||
else if(pos == 0)
|
||||
return "/";
|
||||
|
||||
return string(path, 0, pos);
|
||||
}
|
||||
|
||||
bool
|
||||
path_exists(const string& path)
|
||||
{
|
||||
struct stat sb;
|
||||
|
||||
if( stat(path.c_str(), &sb ) == 0 )
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
string
|
||||
realpath(const string& path)
|
||||
{
|
||||
char* real_path = realpath(path.c_str(), NULL);
|
||||
|
||||
string result;
|
||||
|
||||
if(real_path != NULL)
|
||||
{
|
||||
result = real_path;
|
||||
|
||||
free(real_path);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
string
|
||||
usb_sysfs_friendly_name(const string& sys_usb_path)
|
||||
{
|
||||
unsigned int device_number = 0;
|
||||
|
||||
istringstream( read_line(sys_usb_path + "/devnum") ) >> device_number;
|
||||
|
||||
string manufacturer = read_line( sys_usb_path + "/manufacturer" );
|
||||
|
||||
string product = read_line( sys_usb_path + "/product" );
|
||||
|
||||
string serial = read_line( sys_usb_path + "/serial" );
|
||||
|
||||
if( manufacturer.empty() && product.empty() && serial.empty() )
|
||||
return "";
|
||||
|
||||
return format("%s %s %s", manufacturer.c_str(), product.c_str(), serial.c_str() );
|
||||
}
|
||||
|
||||
vector<string>
|
||||
get_sysfs_info(const string& device_path)
|
||||
{
|
||||
string device_name = basename( device_path );
|
||||
|
||||
string friendly_name;
|
||||
|
||||
string hardware_id;
|
||||
|
||||
string sys_device_path = format( "/sys/class/tty/%s/device", device_name.c_str() );
|
||||
|
||||
if( device_name.compare(0,6,"ttyUSB") == 0 )
|
||||
{
|
||||
sys_device_path = dirname( dirname( realpath( sys_device_path ) ) );
|
||||
|
||||
if( path_exists( sys_device_path ) )
|
||||
{
|
||||
friendly_name = usb_sysfs_friendly_name( sys_device_path );
|
||||
|
||||
hardware_id = usb_sysfs_hw_string( sys_device_path );
|
||||
}
|
||||
}
|
||||
else if( device_name.compare(0,6,"ttyACM") == 0 )
|
||||
{
|
||||
sys_device_path = dirname( realpath( sys_device_path ) );
|
||||
|
||||
if( path_exists( sys_device_path ) )
|
||||
{
|
||||
friendly_name = usb_sysfs_friendly_name( sys_device_path );
|
||||
|
||||
hardware_id = usb_sysfs_hw_string( sys_device_path );
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Try to read ID string of PCI device
|
||||
|
||||
string sys_id_path = sys_device_path + "/id";
|
||||
|
||||
if( path_exists( sys_id_path ) )
|
||||
hardware_id = read_line( sys_id_path );
|
||||
}
|
||||
|
||||
if( friendly_name.empty() )
|
||||
friendly_name = device_name;
|
||||
|
||||
if( hardware_id.empty() )
|
||||
hardware_id = "n/a";
|
||||
|
||||
vector<string> result;
|
||||
result.push_back(friendly_name);
|
||||
result.push_back(hardware_id);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
string
|
||||
read_line(const string& file)
|
||||
{
|
||||
ifstream ifs(file.c_str(), ifstream::in);
|
||||
|
||||
string line;
|
||||
|
||||
if(ifs)
|
||||
{
|
||||
getline(ifs, line);
|
||||
}
|
||||
|
||||
return line;
|
||||
}
|
||||
|
||||
string
|
||||
format(const char* format, ...)
|
||||
{
|
||||
va_list ap;
|
||||
|
||||
size_t buffer_size_bytes = 256;
|
||||
|
||||
string result;
|
||||
|
||||
char* buffer = (char*)malloc(buffer_size_bytes);
|
||||
|
||||
if( buffer == NULL )
|
||||
return result;
|
||||
|
||||
bool done = false;
|
||||
|
||||
unsigned int loop_count = 0;
|
||||
|
||||
while(!done)
|
||||
{
|
||||
va_start(ap, format);
|
||||
|
||||
int return_value = vsnprintf(buffer, buffer_size_bytes, format, ap);
|
||||
|
||||
if( return_value < 0 )
|
||||
{
|
||||
done = true;
|
||||
}
|
||||
else if( return_value >= buffer_size_bytes )
|
||||
{
|
||||
// Realloc and try again.
|
||||
|
||||
buffer_size_bytes = return_value + 1;
|
||||
|
||||
char* new_buffer_ptr = (char*)realloc(buffer, buffer_size_bytes);
|
||||
|
||||
if( new_buffer_ptr == NULL )
|
||||
{
|
||||
done = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
buffer = new_buffer_ptr;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
result = buffer;
|
||||
done = true;
|
||||
}
|
||||
|
||||
va_end(ap);
|
||||
|
||||
if( ++loop_count > 5 )
|
||||
done = true;
|
||||
}
|
||||
|
||||
free(buffer);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
string
|
||||
usb_sysfs_hw_string(const string& sysfs_path)
|
||||
{
|
||||
string serial_number = read_line( sysfs_path + "/serial" );
|
||||
|
||||
if( serial_number.length() > 0 )
|
||||
{
|
||||
serial_number = format( "SNR=%s", serial_number.c_str() );
|
||||
}
|
||||
|
||||
string vid = read_line( sysfs_path + "/idVendor" );
|
||||
|
||||
string pid = read_line( sysfs_path + "/idProduct" );
|
||||
|
||||
return format("USB VID:PID=%s:%s %s", vid.c_str(), pid.c_str(), serial_number.c_str() );
|
||||
}
|
||||
|
||||
vector<PortInfo>
|
||||
serial::list_ports()
|
||||
{
|
||||
vector<PortInfo> results;
|
||||
|
||||
vector<string> search_globs;
|
||||
search_globs.push_back("/dev/ttyACM*");
|
||||
search_globs.push_back("/dev/ttyS*");
|
||||
search_globs.push_back("/dev/ttyUSB*");
|
||||
search_globs.push_back("/dev/tty.*");
|
||||
search_globs.push_back("/dev/cu.*");
|
||||
search_globs.push_back("/dev/rfcomm*");
|
||||
|
||||
vector<string> devices_found = glob( search_globs );
|
||||
|
||||
vector<string>::iterator iter = devices_found.begin();
|
||||
|
||||
while( iter != devices_found.end() )
|
||||
{
|
||||
string device = *iter++;
|
||||
|
||||
vector<string> sysfs_info = get_sysfs_info( device );
|
||||
|
||||
string friendly_name = sysfs_info[0];
|
||||
|
||||
string hardware_id = sysfs_info[1];
|
||||
|
||||
PortInfo device_entry;
|
||||
device_entry.port = device;
|
||||
device_entry.description = friendly_name;
|
||||
device_entry.hardware_id = hardware_id;
|
||||
|
||||
results.push_back( device_entry );
|
||||
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
#endif // defined(__linux__)
|
||||
@@ -0,0 +1,286 @@
|
||||
#if defined(__APPLE__)
|
||||
|
||||
#include <sys/param.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include <CoreFoundation/CoreFoundation.h>
|
||||
#include <IOKit/IOKitLib.h>
|
||||
#include <IOKit/serial/IOSerialKeys.h>
|
||||
#include <IOKit/IOBSD.h>
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../../../include/serial/serial.h"
|
||||
|
||||
using serial::PortInfo;
|
||||
using std::string;
|
||||
using std::vector;
|
||||
|
||||
#define HARDWARE_ID_STRING_LENGTH 128
|
||||
|
||||
string cfstring_to_string( CFStringRef cfstring );
|
||||
string get_device_path( io_object_t& serial_port );
|
||||
string get_class_name( io_object_t& obj );
|
||||
io_registry_entry_t get_parent_iousb_device( io_object_t& serial_port );
|
||||
string get_string_property( io_object_t& device, const char* property );
|
||||
uint16_t get_int_property( io_object_t& device, const char* property );
|
||||
string rtrim(const string& str);
|
||||
|
||||
string
|
||||
cfstring_to_string( CFStringRef cfstring )
|
||||
{
|
||||
char cstring[MAXPATHLEN];
|
||||
string result;
|
||||
|
||||
if( cfstring )
|
||||
{
|
||||
Boolean success = CFStringGetCString( cfstring,
|
||||
cstring,
|
||||
sizeof(cstring),
|
||||
kCFStringEncodingASCII );
|
||||
|
||||
if( success )
|
||||
result = cstring;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
string
|
||||
get_device_path( io_object_t& serial_port )
|
||||
{
|
||||
CFTypeRef callout_path;
|
||||
string device_path;
|
||||
|
||||
callout_path = IORegistryEntryCreateCFProperty( serial_port,
|
||||
CFSTR(kIOCalloutDeviceKey),
|
||||
kCFAllocatorDefault,
|
||||
0 );
|
||||
|
||||
if (callout_path)
|
||||
{
|
||||
if( CFGetTypeID(callout_path) == CFStringGetTypeID() )
|
||||
device_path = cfstring_to_string( static_cast<CFStringRef>(callout_path) );
|
||||
|
||||
CFRelease(callout_path);
|
||||
}
|
||||
|
||||
return device_path;
|
||||
}
|
||||
|
||||
string
|
||||
get_class_name( io_object_t& obj )
|
||||
{
|
||||
string result;
|
||||
io_name_t class_name;
|
||||
kern_return_t kern_result;
|
||||
|
||||
kern_result = IOObjectGetClass( obj, class_name );
|
||||
|
||||
if( kern_result == KERN_SUCCESS )
|
||||
result = class_name;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
io_registry_entry_t
|
||||
get_parent_iousb_device( io_object_t& serial_port )
|
||||
{
|
||||
io_object_t device = serial_port;
|
||||
io_registry_entry_t parent = 0;
|
||||
io_registry_entry_t result = 0;
|
||||
kern_return_t kern_result = KERN_FAILURE;
|
||||
string name = get_class_name(device);
|
||||
|
||||
// Walk the IO Registry tree looking for this devices parent IOUSBDevice.
|
||||
while( name != "IOUSBDevice" )
|
||||
{
|
||||
kern_result = IORegistryEntryGetParentEntry( device,
|
||||
kIOServicePlane,
|
||||
&parent );
|
||||
|
||||
if(kern_result != KERN_SUCCESS)
|
||||
{
|
||||
result = 0;
|
||||
break;
|
||||
}
|
||||
|
||||
device = parent;
|
||||
|
||||
name = get_class_name(device);
|
||||
}
|
||||
|
||||
if(kern_result == KERN_SUCCESS)
|
||||
result = device;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
string
|
||||
get_string_property( io_object_t& device, const char* property )
|
||||
{
|
||||
string property_name;
|
||||
|
||||
if( device )
|
||||
{
|
||||
CFStringRef property_as_cfstring = CFStringCreateWithCString (
|
||||
kCFAllocatorDefault,
|
||||
property,
|
||||
kCFStringEncodingASCII );
|
||||
|
||||
CFTypeRef name_as_cfstring = IORegistryEntryCreateCFProperty(
|
||||
device,
|
||||
property_as_cfstring,
|
||||
kCFAllocatorDefault,
|
||||
0 );
|
||||
|
||||
if( name_as_cfstring )
|
||||
{
|
||||
if( CFGetTypeID(name_as_cfstring) == CFStringGetTypeID() )
|
||||
property_name = cfstring_to_string( static_cast<CFStringRef>(name_as_cfstring) );
|
||||
|
||||
CFRelease(name_as_cfstring);
|
||||
}
|
||||
|
||||
if(property_as_cfstring)
|
||||
CFRelease(property_as_cfstring);
|
||||
}
|
||||
|
||||
return property_name;
|
||||
}
|
||||
|
||||
uint16_t
|
||||
get_int_property( io_object_t& device, const char* property )
|
||||
{
|
||||
uint16_t result = 0;
|
||||
|
||||
if( device )
|
||||
{
|
||||
CFStringRef property_as_cfstring = CFStringCreateWithCString (
|
||||
kCFAllocatorDefault,
|
||||
property,
|
||||
kCFStringEncodingASCII );
|
||||
|
||||
CFTypeRef number = IORegistryEntryCreateCFProperty( device,
|
||||
property_as_cfstring,
|
||||
kCFAllocatorDefault,
|
||||
0 );
|
||||
|
||||
if(property_as_cfstring)
|
||||
CFRelease(property_as_cfstring);
|
||||
|
||||
if( number )
|
||||
{
|
||||
if( CFGetTypeID(number) == CFNumberGetTypeID() )
|
||||
{
|
||||
bool success = CFNumberGetValue( static_cast<CFNumberRef>(number),
|
||||
kCFNumberSInt16Type,
|
||||
&result );
|
||||
|
||||
if( !success )
|
||||
result = 0;
|
||||
}
|
||||
|
||||
CFRelease(number);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
string rtrim(const string& str)
|
||||
{
|
||||
string result = str;
|
||||
|
||||
string whitespace = " \t\f\v\n\r";
|
||||
|
||||
std::size_t found = result.find_last_not_of(whitespace);
|
||||
|
||||
if (found != std::string::npos)
|
||||
result.erase(found+1);
|
||||
else
|
||||
result.clear();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
vector<PortInfo>
|
||||
serial::list_ports(void)
|
||||
{
|
||||
vector<PortInfo> devices_found;
|
||||
CFMutableDictionaryRef classes_to_match;
|
||||
io_iterator_t serial_port_iterator;
|
||||
io_object_t serial_port;
|
||||
mach_port_t master_port;
|
||||
kern_return_t kern_result;
|
||||
|
||||
kern_result = IOMasterPort(MACH_PORT_NULL, &master_port);
|
||||
|
||||
if(kern_result != KERN_SUCCESS)
|
||||
return devices_found;
|
||||
|
||||
classes_to_match = IOServiceMatching(kIOSerialBSDServiceValue);
|
||||
|
||||
if (classes_to_match == NULL)
|
||||
return devices_found;
|
||||
|
||||
CFDictionarySetValue( classes_to_match,
|
||||
CFSTR(kIOSerialBSDTypeKey),
|
||||
CFSTR(kIOSerialBSDAllTypes) );
|
||||
|
||||
kern_result = IOServiceGetMatchingServices(master_port, classes_to_match, &serial_port_iterator);
|
||||
|
||||
if (KERN_SUCCESS != kern_result)
|
||||
return devices_found;
|
||||
|
||||
while ( (serial_port = IOIteratorNext(serial_port_iterator)) )
|
||||
{
|
||||
string device_path = get_device_path( serial_port );
|
||||
io_registry_entry_t parent = get_parent_iousb_device( serial_port );
|
||||
IOObjectRelease(serial_port);
|
||||
|
||||
if( device_path.empty() )
|
||||
continue;
|
||||
|
||||
PortInfo port_info;
|
||||
port_info.port = device_path;
|
||||
port_info.description = "n/a";
|
||||
port_info.hardware_id = "n/a";
|
||||
|
||||
string device_name = rtrim( get_string_property( parent, "USB Product Name" ) );
|
||||
string vendor_name = rtrim( get_string_property( parent, "USB Vendor Name") );
|
||||
string description = rtrim( vendor_name + " " + device_name );
|
||||
if( !description.empty() )
|
||||
port_info.description = description;
|
||||
|
||||
string serial_number = rtrim(get_string_property( parent, "USB Serial Number" ) );
|
||||
uint16_t vendor_id = get_int_property( parent, "idVendor" );
|
||||
uint16_t product_id = get_int_property( parent, "idProduct" );
|
||||
|
||||
if( vendor_id && product_id )
|
||||
{
|
||||
char cstring[HARDWARE_ID_STRING_LENGTH];
|
||||
|
||||
if(serial_number.empty())
|
||||
serial_number = "None";
|
||||
|
||||
int ret = snprintf( cstring, HARDWARE_ID_STRING_LENGTH, "USB VID:PID=%04x:%04x SNR=%s",
|
||||
vendor_id,
|
||||
product_id,
|
||||
serial_number.c_str() );
|
||||
|
||||
if( (ret >= 0) && (ret < HARDWARE_ID_STRING_LENGTH) )
|
||||
port_info.hardware_id = cstring;
|
||||
}
|
||||
|
||||
devices_found.push_back(port_info);
|
||||
}
|
||||
|
||||
IOObjectRelease(serial_port_iterator);
|
||||
return devices_found;
|
||||
}
|
||||
|
||||
#endif // defined(__APPLE__)
|
||||
@@ -0,0 +1,152 @@
|
||||
#if defined(_WIN32)
|
||||
|
||||
/*
|
||||
* Copyright (c) 2014 Craig Lilley <cralilley@gmail.com>
|
||||
* This software is made available under the terms of the MIT licence.
|
||||
* A copy of the licence can be obtained from:
|
||||
* http://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "serial/serial.h"
|
||||
#include <tchar.h>
|
||||
#include <windows.h>
|
||||
#include <setupapi.h>
|
||||
#include <initguid.h>
|
||||
#include <devguid.h>
|
||||
#include <cstring>
|
||||
|
||||
using serial::PortInfo;
|
||||
using std::vector;
|
||||
using std::string;
|
||||
|
||||
static const DWORD port_name_max_length = 256;
|
||||
static const DWORD friendly_name_max_length = 256;
|
||||
static const DWORD hardware_id_max_length = 256;
|
||||
|
||||
// Convert a wide Unicode string to an UTF8 string
|
||||
std::string utf8_encode(const std::wstring &wstr)
|
||||
{
|
||||
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
|
||||
std::string strTo( size_needed, 0 );
|
||||
WideCharToMultiByte (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
|
||||
return strTo;
|
||||
}
|
||||
|
||||
vector<PortInfo>
|
||||
serial::list_ports()
|
||||
{
|
||||
vector<PortInfo> devices_found;
|
||||
|
||||
HDEVINFO device_info_set = SetupDiGetClassDevs(
|
||||
(const GUID *) &GUID_DEVCLASS_PORTS,
|
||||
NULL,
|
||||
NULL,
|
||||
DIGCF_PRESENT);
|
||||
|
||||
unsigned int device_info_set_index = 0;
|
||||
SP_DEVINFO_DATA device_info_data;
|
||||
|
||||
device_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
|
||||
|
||||
while(SetupDiEnumDeviceInfo(device_info_set, device_info_set_index, &device_info_data))
|
||||
{
|
||||
device_info_set_index++;
|
||||
|
||||
// Get port name
|
||||
|
||||
HKEY hkey = SetupDiOpenDevRegKey(
|
||||
device_info_set,
|
||||
&device_info_data,
|
||||
DICS_FLAG_GLOBAL,
|
||||
0,
|
||||
DIREG_DEV,
|
||||
KEY_READ);
|
||||
|
||||
TCHAR port_name[port_name_max_length];
|
||||
DWORD port_name_length = port_name_max_length;
|
||||
|
||||
LONG return_code = RegQueryValueEx(
|
||||
hkey,
|
||||
_T("PortName"),
|
||||
NULL,
|
||||
NULL,
|
||||
(LPBYTE)port_name,
|
||||
&port_name_length);
|
||||
|
||||
RegCloseKey(hkey);
|
||||
|
||||
if(return_code != EXIT_SUCCESS)
|
||||
continue;
|
||||
|
||||
if(port_name_length > 0 && port_name_length <= port_name_max_length)
|
||||
port_name[port_name_length-1] = '\0';
|
||||
else
|
||||
port_name[0] = '\0';
|
||||
|
||||
// Ignore parallel ports
|
||||
|
||||
if(_tcsstr(port_name, _T("LPT")) != NULL)
|
||||
continue;
|
||||
|
||||
// Get port friendly name
|
||||
|
||||
TCHAR friendly_name[friendly_name_max_length];
|
||||
DWORD friendly_name_actual_length = 0;
|
||||
|
||||
BOOL got_friendly_name = SetupDiGetDeviceRegistryProperty(
|
||||
device_info_set,
|
||||
&device_info_data,
|
||||
SPDRP_FRIENDLYNAME,
|
||||
NULL,
|
||||
(PBYTE)friendly_name,
|
||||
friendly_name_max_length,
|
||||
&friendly_name_actual_length);
|
||||
|
||||
if(got_friendly_name == TRUE && friendly_name_actual_length > 0)
|
||||
friendly_name[friendly_name_actual_length-1] = '\0';
|
||||
else
|
||||
friendly_name[0] = '\0';
|
||||
|
||||
// Get hardware ID
|
||||
|
||||
TCHAR hardware_id[hardware_id_max_length];
|
||||
DWORD hardware_id_actual_length = 0;
|
||||
|
||||
BOOL got_hardware_id = SetupDiGetDeviceRegistryProperty(
|
||||
device_info_set,
|
||||
&device_info_data,
|
||||
SPDRP_HARDWAREID,
|
||||
NULL,
|
||||
(PBYTE)hardware_id,
|
||||
hardware_id_max_length,
|
||||
&hardware_id_actual_length);
|
||||
|
||||
if(got_hardware_id == TRUE && hardware_id_actual_length > 0)
|
||||
hardware_id[hardware_id_actual_length-1] = '\0';
|
||||
else
|
||||
hardware_id[0] = '\0';
|
||||
|
||||
#ifdef UNICODE
|
||||
std::string portName = utf8_encode(port_name);
|
||||
std::string friendlyName = utf8_encode(friendly_name);
|
||||
std::string hardwareId = utf8_encode(hardware_id);
|
||||
#else
|
||||
std::string portName = port_name;
|
||||
std::string friendlyName = friendly_name;
|
||||
std::string hardwareId = hardware_id;
|
||||
#endif
|
||||
|
||||
PortInfo port_entry;
|
||||
port_entry.port = portName;
|
||||
port_entry.description = friendlyName;
|
||||
port_entry.hardware_id = hardwareId;
|
||||
|
||||
devices_found.push_back(port_entry);
|
||||
}
|
||||
|
||||
SetupDiDestroyDeviceInfoList(device_info_set);
|
||||
|
||||
return devices_found;
|
||||
}
|
||||
|
||||
#endif // #if defined(_WIN32)
|
||||
+1138
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,651 @@
|
||||
#if defined(_WIN32)
|
||||
|
||||
/* Copyright 2012 William Woodall and John Harrison */
|
||||
|
||||
#include <sstream>
|
||||
|
||||
#include "serial/impl/win.h"
|
||||
|
||||
using std::string;
|
||||
using std::wstring;
|
||||
using std::stringstream;
|
||||
using std::invalid_argument;
|
||||
using serial::Serial;
|
||||
using serial::Timeout;
|
||||
using serial::bytesize_t;
|
||||
using serial::parity_t;
|
||||
using serial::stopbits_t;
|
||||
using serial::flowcontrol_t;
|
||||
using serial::SerialException;
|
||||
using serial::PortNotOpenedException;
|
||||
using serial::IOException;
|
||||
|
||||
inline wstring
|
||||
_prefix_port_if_needed(const wstring &input)
|
||||
{
|
||||
static wstring windows_com_port_prefix = L"\\\\.\\";
|
||||
if (input.compare(0, windows_com_port_prefix.size(), windows_com_port_prefix) != 0)
|
||||
{
|
||||
return windows_com_port_prefix + input;
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
Serial::SerialImpl::SerialImpl (const string &port, unsigned long baudrate,
|
||||
bytesize_t bytesize,
|
||||
parity_t parity, stopbits_t stopbits,
|
||||
flowcontrol_t flowcontrol)
|
||||
: port_ (port.begin(), port.end()), fd_ (INVALID_HANDLE_VALUE), is_open_ (false),
|
||||
baudrate_ (baudrate), parity_ (parity),
|
||||
bytesize_ (bytesize), stopbits_ (stopbits), flowcontrol_ (flowcontrol)
|
||||
{
|
||||
if (port_.empty () == false)
|
||||
open ();
|
||||
read_mutex = CreateMutex(NULL, false, NULL);
|
||||
write_mutex = CreateMutex(NULL, false, NULL);
|
||||
}
|
||||
|
||||
Serial::SerialImpl::~SerialImpl ()
|
||||
{
|
||||
this->close();
|
||||
CloseHandle(read_mutex);
|
||||
CloseHandle(write_mutex);
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::open ()
|
||||
{
|
||||
if (port_.empty ()) {
|
||||
throw invalid_argument ("Empty port is invalid.");
|
||||
}
|
||||
if (is_open_ == true) {
|
||||
throw SerialException ("Serial port already open.");
|
||||
}
|
||||
|
||||
// See: https://github.com/wjwwood/serial/issues/84
|
||||
wstring port_with_prefix = _prefix_port_if_needed(port_);
|
||||
LPCWSTR lp_port = port_with_prefix.c_str();
|
||||
fd_ = CreateFileW(lp_port,
|
||||
GENERIC_READ | GENERIC_WRITE,
|
||||
0,
|
||||
0,
|
||||
OPEN_EXISTING,
|
||||
FILE_ATTRIBUTE_NORMAL,
|
||||
0);
|
||||
|
||||
if (fd_ == INVALID_HANDLE_VALUE) {
|
||||
DWORD create_file_err = GetLastError();
|
||||
stringstream ss;
|
||||
switch (create_file_err) {
|
||||
case ERROR_FILE_NOT_FOUND:
|
||||
// Use this->getPort to convert to a std::string
|
||||
ss << "Specified port, " << this->getPort() << ", does not exist.";
|
||||
THROWEX (IOException, ss.str().c_str(), 1);
|
||||
case ERROR_ACCESS_DENIED:
|
||||
ss << "Specified port, " << this->getPort() << ", allready open.";
|
||||
THROWEX (IOException, ss.str().c_str(), 2);
|
||||
default:
|
||||
ss << "Unknown error opening the serial port: " << create_file_err;
|
||||
THROW (IOException, ss.str().c_str());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
reconfigurePort();
|
||||
is_open_ = true;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::reconfigurePort ()
|
||||
{
|
||||
if (fd_ == INVALID_HANDLE_VALUE) {
|
||||
// Can only operate on a valid file descriptor
|
||||
THROW (IOException, "Invalid file descriptor, is the serial port open?");
|
||||
}
|
||||
|
||||
DCB dcbSerialParams = {0};
|
||||
|
||||
dcbSerialParams.DCBlength=sizeof(dcbSerialParams);
|
||||
|
||||
if (!GetCommState(fd_, &dcbSerialParams)) {
|
||||
//error getting state
|
||||
THROW (IOException, "Error getting the serial port state.");
|
||||
}
|
||||
|
||||
// setup baud rate
|
||||
switch (baudrate_) {
|
||||
#ifdef CBR_0
|
||||
case 0: dcbSerialParams.BaudRate = CBR_0; break;
|
||||
#endif
|
||||
#ifdef CBR_50
|
||||
case 50: dcbSerialParams.BaudRate = CBR_50; break;
|
||||
#endif
|
||||
#ifdef CBR_75
|
||||
case 75: dcbSerialParams.BaudRate = CBR_75; break;
|
||||
#endif
|
||||
#ifdef CBR_110
|
||||
case 110: dcbSerialParams.BaudRate = CBR_110; break;
|
||||
#endif
|
||||
#ifdef CBR_134
|
||||
case 134: dcbSerialParams.BaudRate = CBR_134; break;
|
||||
#endif
|
||||
#ifdef CBR_150
|
||||
case 150: dcbSerialParams.BaudRate = CBR_150; break;
|
||||
#endif
|
||||
#ifdef CBR_200
|
||||
case 200: dcbSerialParams.BaudRate = CBR_200; break;
|
||||
#endif
|
||||
#ifdef CBR_300
|
||||
case 300: dcbSerialParams.BaudRate = CBR_300; break;
|
||||
#endif
|
||||
#ifdef CBR_600
|
||||
case 600: dcbSerialParams.BaudRate = CBR_600; break;
|
||||
#endif
|
||||
#ifdef CBR_1200
|
||||
case 1200: dcbSerialParams.BaudRate = CBR_1200; break;
|
||||
#endif
|
||||
#ifdef CBR_1800
|
||||
case 1800: dcbSerialParams.BaudRate = CBR_1800; break;
|
||||
#endif
|
||||
#ifdef CBR_2400
|
||||
case 2400: dcbSerialParams.BaudRate = CBR_2400; break;
|
||||
#endif
|
||||
#ifdef CBR_4800
|
||||
case 4800: dcbSerialParams.BaudRate = CBR_4800; break;
|
||||
#endif
|
||||
#ifdef CBR_7200
|
||||
case 7200: dcbSerialParams.BaudRate = CBR_7200; break;
|
||||
#endif
|
||||
#ifdef CBR_9600
|
||||
case 9600: dcbSerialParams.BaudRate = CBR_9600; break;
|
||||
#endif
|
||||
#ifdef CBR_14400
|
||||
case 14400: dcbSerialParams.BaudRate = CBR_14400; break;
|
||||
#endif
|
||||
#ifdef CBR_19200
|
||||
case 19200: dcbSerialParams.BaudRate = CBR_19200; break;
|
||||
#endif
|
||||
#ifdef CBR_28800
|
||||
case 28800: dcbSerialParams.BaudRate = CBR_28800; break;
|
||||
#endif
|
||||
#ifdef CBR_57600
|
||||
case 57600: dcbSerialParams.BaudRate = CBR_57600; break;
|
||||
#endif
|
||||
#ifdef CBR_76800
|
||||
case 76800: dcbSerialParams.BaudRate = CBR_76800; break;
|
||||
#endif
|
||||
#ifdef CBR_38400
|
||||
case 38400: dcbSerialParams.BaudRate = CBR_38400; break;
|
||||
#endif
|
||||
#ifdef CBR_115200
|
||||
case 115200: dcbSerialParams.BaudRate = CBR_115200; break;
|
||||
#endif
|
||||
#ifdef CBR_128000
|
||||
case 128000: dcbSerialParams.BaudRate = CBR_128000; break;
|
||||
#endif
|
||||
#ifdef CBR_153600
|
||||
case 153600: dcbSerialParams.BaudRate = CBR_153600; break;
|
||||
#endif
|
||||
#ifdef CBR_230400
|
||||
case 230400: dcbSerialParams.BaudRate = CBR_230400; break;
|
||||
#endif
|
||||
#ifdef CBR_256000
|
||||
case 256000: dcbSerialParams.BaudRate = CBR_256000; break;
|
||||
#endif
|
||||
#ifdef CBR_460800
|
||||
case 460800: dcbSerialParams.BaudRate = CBR_460800; break;
|
||||
#endif
|
||||
#ifdef CBR_921600
|
||||
case 921600: dcbSerialParams.BaudRate = CBR_921600; break;
|
||||
#endif
|
||||
default:
|
||||
// Try to blindly assign it
|
||||
dcbSerialParams.BaudRate = baudrate_;
|
||||
}
|
||||
|
||||
// setup char len
|
||||
if (bytesize_ == eightbits)
|
||||
dcbSerialParams.ByteSize = 8;
|
||||
else if (bytesize_ == sevenbits)
|
||||
dcbSerialParams.ByteSize = 7;
|
||||
else if (bytesize_ == sixbits)
|
||||
dcbSerialParams.ByteSize = 6;
|
||||
else if (bytesize_ == fivebits)
|
||||
dcbSerialParams.ByteSize = 5;
|
||||
else
|
||||
throw invalid_argument ("invalid char len");
|
||||
|
||||
// setup stopbits
|
||||
if (stopbits_ == stopbits_one)
|
||||
dcbSerialParams.StopBits = ONESTOPBIT;
|
||||
else if (stopbits_ == stopbits_one_point_five)
|
||||
dcbSerialParams.StopBits = ONE5STOPBITS;
|
||||
else if (stopbits_ == stopbits_two)
|
||||
dcbSerialParams.StopBits = TWOSTOPBITS;
|
||||
else
|
||||
throw invalid_argument ("invalid stop bit");
|
||||
|
||||
// setup parity
|
||||
if (parity_ == parity_none) {
|
||||
dcbSerialParams.Parity = NOPARITY;
|
||||
} else if (parity_ == parity_even) {
|
||||
dcbSerialParams.Parity = EVENPARITY;
|
||||
} else if (parity_ == parity_odd) {
|
||||
dcbSerialParams.Parity = ODDPARITY;
|
||||
} else if (parity_ == parity_mark) {
|
||||
dcbSerialParams.Parity = MARKPARITY;
|
||||
} else if (parity_ == parity_space) {
|
||||
dcbSerialParams.Parity = SPACEPARITY;
|
||||
} else {
|
||||
throw invalid_argument ("invalid parity");
|
||||
}
|
||||
|
||||
// setup flowcontrol
|
||||
if (flowcontrol_ == flowcontrol_none) {
|
||||
dcbSerialParams.fOutxCtsFlow = false;
|
||||
dcbSerialParams.fRtsControl = RTS_CONTROL_DISABLE;
|
||||
dcbSerialParams.fOutX = false;
|
||||
dcbSerialParams.fInX = false;
|
||||
}
|
||||
if (flowcontrol_ == flowcontrol_software) {
|
||||
dcbSerialParams.fOutxCtsFlow = false;
|
||||
dcbSerialParams.fRtsControl = RTS_CONTROL_DISABLE;
|
||||
dcbSerialParams.fOutX = true;
|
||||
dcbSerialParams.fInX = true;
|
||||
}
|
||||
if (flowcontrol_ == flowcontrol_hardware) {
|
||||
dcbSerialParams.fOutxCtsFlow = true;
|
||||
dcbSerialParams.fRtsControl = RTS_CONTROL_HANDSHAKE;
|
||||
dcbSerialParams.fOutX = false;
|
||||
dcbSerialParams.fInX = false;
|
||||
}
|
||||
|
||||
// activate settings
|
||||
if (!SetCommState(fd_, &dcbSerialParams)){
|
||||
CloseHandle(fd_);
|
||||
THROW (IOException, "Error setting serial port settings.");
|
||||
}
|
||||
|
||||
// Setup timeouts
|
||||
COMMTIMEOUTS timeouts = {0};
|
||||
timeouts.ReadIntervalTimeout = timeout_.inter_byte_timeout;
|
||||
timeouts.ReadTotalTimeoutConstant = timeout_.read_timeout_constant;
|
||||
timeouts.ReadTotalTimeoutMultiplier = timeout_.read_timeout_multiplier;
|
||||
timeouts.WriteTotalTimeoutConstant = timeout_.write_timeout_constant;
|
||||
timeouts.WriteTotalTimeoutMultiplier = timeout_.write_timeout_multiplier;
|
||||
if (!SetCommTimeouts(fd_, &timeouts)) {
|
||||
THROW (IOException, "Error setting timeouts.");
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::close ()
|
||||
{
|
||||
if (is_open_ == true) {
|
||||
if (fd_ != INVALID_HANDLE_VALUE) {
|
||||
int ret;
|
||||
ret = CloseHandle(fd_);
|
||||
if (ret == 0) {
|
||||
stringstream ss;
|
||||
ss << "Error while closing serial port: " << GetLastError();
|
||||
THROW (IOException, ss.str().c_str());
|
||||
} else {
|
||||
fd_ = INVALID_HANDLE_VALUE;
|
||||
}
|
||||
}
|
||||
is_open_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
bool
|
||||
Serial::SerialImpl::isOpen () const
|
||||
{
|
||||
return is_open_;
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::SerialImpl::available ()
|
||||
{
|
||||
if (!is_open_) {
|
||||
return 0;
|
||||
}
|
||||
COMSTAT cs;
|
||||
if (!ClearCommError(fd_, NULL, &cs)) {
|
||||
stringstream ss;
|
||||
ss << "Error while checking status of the serial port: " << GetLastError();
|
||||
THROW (IOException, ss.str().c_str());
|
||||
}
|
||||
return static_cast<size_t>(cs.cbInQue);
|
||||
}
|
||||
|
||||
bool
|
||||
Serial::SerialImpl::waitReadable (uint32_t /*timeout*/)
|
||||
{
|
||||
THROW (IOException, "waitReadable is not implemented on Windows.");
|
||||
return false;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::waitByteTimes (size_t /*count*/)
|
||||
{
|
||||
THROW (IOException, "waitByteTimes is not implemented on Windows.");
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::SerialImpl::read (uint8_t *buf, size_t size)
|
||||
{
|
||||
if (!is_open_) {
|
||||
throw PortNotOpenedException ("Serial::read");
|
||||
}
|
||||
DWORD bytes_read;
|
||||
if (!ReadFile(fd_, buf, static_cast<DWORD>(size), &bytes_read, NULL)) {
|
||||
stringstream ss;
|
||||
ss << "Error while reading from the serial port: " << GetLastError();
|
||||
THROW (IOException, ss.str().c_str());
|
||||
}
|
||||
return (size_t) (bytes_read);
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::SerialImpl::write (const uint8_t *data, size_t length)
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::write");
|
||||
}
|
||||
DWORD bytes_written;
|
||||
if (!WriteFile(fd_, data, static_cast<DWORD>(length), &bytes_written, NULL)) {
|
||||
stringstream ss;
|
||||
ss << "Error while writing to the serial port: " << GetLastError();
|
||||
THROW (IOException, ss.str().c_str());
|
||||
}
|
||||
return (size_t) (bytes_written);
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setPort (const string &port)
|
||||
{
|
||||
port_ = wstring(port.begin(), port.end());
|
||||
}
|
||||
|
||||
string
|
||||
Serial::SerialImpl::getPort () const
|
||||
{
|
||||
return string(port_.begin(), port_.end());
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setTimeout (serial::Timeout &timeout)
|
||||
{
|
||||
timeout_ = timeout;
|
||||
if (is_open_) {
|
||||
reconfigurePort ();
|
||||
}
|
||||
}
|
||||
|
||||
serial::Timeout
|
||||
Serial::SerialImpl::getTimeout () const
|
||||
{
|
||||
return timeout_;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setBaudrate (unsigned long baudrate)
|
||||
{
|
||||
baudrate_ = baudrate;
|
||||
if (is_open_) {
|
||||
reconfigurePort ();
|
||||
}
|
||||
}
|
||||
|
||||
unsigned long
|
||||
Serial::SerialImpl::getBaudrate () const
|
||||
{
|
||||
return baudrate_;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setBytesize (serial::bytesize_t bytesize)
|
||||
{
|
||||
bytesize_ = bytesize;
|
||||
if (is_open_) {
|
||||
reconfigurePort ();
|
||||
}
|
||||
}
|
||||
|
||||
serial::bytesize_t
|
||||
Serial::SerialImpl::getBytesize () const
|
||||
{
|
||||
return bytesize_;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setParity (serial::parity_t parity)
|
||||
{
|
||||
parity_ = parity;
|
||||
if (is_open_) {
|
||||
reconfigurePort ();
|
||||
}
|
||||
}
|
||||
|
||||
serial::parity_t
|
||||
Serial::SerialImpl::getParity () const
|
||||
{
|
||||
return parity_;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setStopbits (serial::stopbits_t stopbits)
|
||||
{
|
||||
stopbits_ = stopbits;
|
||||
if (is_open_) {
|
||||
reconfigurePort ();
|
||||
}
|
||||
}
|
||||
|
||||
serial::stopbits_t
|
||||
Serial::SerialImpl::getStopbits () const
|
||||
{
|
||||
return stopbits_;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setFlowcontrol (serial::flowcontrol_t flowcontrol)
|
||||
{
|
||||
flowcontrol_ = flowcontrol;
|
||||
if (is_open_) {
|
||||
reconfigurePort ();
|
||||
}
|
||||
}
|
||||
|
||||
serial::flowcontrol_t
|
||||
Serial::SerialImpl::getFlowcontrol () const
|
||||
{
|
||||
return flowcontrol_;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::flush ()
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::flush");
|
||||
}
|
||||
FlushFileBuffers (fd_);
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::flushInput ()
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException("Serial::flushInput");
|
||||
}
|
||||
PurgeComm(fd_, PURGE_RXCLEAR);
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::flushOutput ()
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException("Serial::flushOutput");
|
||||
}
|
||||
PurgeComm(fd_, PURGE_TXCLEAR);
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::sendBreak (int /*duration*/)
|
||||
{
|
||||
THROW (IOException, "sendBreak is not supported on Windows.");
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setBreak (bool level)
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::setBreak");
|
||||
}
|
||||
if (level) {
|
||||
EscapeCommFunction (fd_, SETBREAK);
|
||||
} else {
|
||||
EscapeCommFunction (fd_, CLRBREAK);
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setRTS (bool level)
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::setRTS");
|
||||
}
|
||||
if (level) {
|
||||
EscapeCommFunction (fd_, SETRTS);
|
||||
} else {
|
||||
EscapeCommFunction (fd_, CLRRTS);
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::setDTR (bool level)
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::setDTR");
|
||||
}
|
||||
if (level) {
|
||||
EscapeCommFunction (fd_, SETDTR);
|
||||
} else {
|
||||
EscapeCommFunction (fd_, CLRDTR);
|
||||
}
|
||||
}
|
||||
|
||||
bool
|
||||
Serial::SerialImpl::waitForChange ()
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::waitForChange");
|
||||
}
|
||||
DWORD dwCommEvent;
|
||||
|
||||
if (!SetCommMask(fd_, EV_CTS | EV_DSR | EV_RING | EV_RLSD)) {
|
||||
// Error setting communications mask
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!WaitCommEvent(fd_, &dwCommEvent, NULL)) {
|
||||
// An error occurred waiting for the event.
|
||||
return false;
|
||||
} else {
|
||||
// Event has occurred.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool
|
||||
Serial::SerialImpl::getCTS ()
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::getCTS");
|
||||
}
|
||||
DWORD dwModemStatus;
|
||||
if (!GetCommModemStatus(fd_, &dwModemStatus)) {
|
||||
THROW (IOException, "Error getting the status of the CTS line.");
|
||||
}
|
||||
|
||||
return (MS_CTS_ON & dwModemStatus) != 0;
|
||||
}
|
||||
|
||||
bool
|
||||
Serial::SerialImpl::getDSR ()
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::getDSR");
|
||||
}
|
||||
DWORD dwModemStatus;
|
||||
if (!GetCommModemStatus(fd_, &dwModemStatus)) {
|
||||
THROW (IOException, "Error getting the status of the DSR line.");
|
||||
}
|
||||
|
||||
return (MS_DSR_ON & dwModemStatus) != 0;
|
||||
}
|
||||
|
||||
bool
|
||||
Serial::SerialImpl::getRI()
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::getRI");
|
||||
}
|
||||
DWORD dwModemStatus;
|
||||
if (!GetCommModemStatus(fd_, &dwModemStatus)) {
|
||||
THROW (IOException, "Error getting the status of the RI line.");
|
||||
}
|
||||
|
||||
return (MS_RING_ON & dwModemStatus) != 0;
|
||||
}
|
||||
|
||||
bool
|
||||
Serial::SerialImpl::getCD()
|
||||
{
|
||||
if (is_open_ == false) {
|
||||
throw PortNotOpenedException ("Serial::getCD");
|
||||
}
|
||||
DWORD dwModemStatus;
|
||||
if (!GetCommModemStatus(fd_, &dwModemStatus)) {
|
||||
// Error in GetCommModemStatus;
|
||||
THROW (IOException, "Error getting the status of the CD line.");
|
||||
}
|
||||
|
||||
return (MS_RLSD_ON & dwModemStatus) != 0;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::readLock()
|
||||
{
|
||||
if (WaitForSingleObject(read_mutex, INFINITE) != WAIT_OBJECT_0) {
|
||||
THROW (IOException, "Error claiming read mutex.");
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::readUnlock()
|
||||
{
|
||||
if (!ReleaseMutex(read_mutex)) {
|
||||
THROW (IOException, "Error releasing read mutex.");
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::writeLock()
|
||||
{
|
||||
if (WaitForSingleObject(write_mutex, INFINITE) != WAIT_OBJECT_0) {
|
||||
THROW (IOException, "Error claiming write mutex.");
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Serial::SerialImpl::writeUnlock()
|
||||
{
|
||||
if (!ReleaseMutex(write_mutex)) {
|
||||
THROW (IOException, "Error releasing write mutex.");
|
||||
}
|
||||
}
|
||||
|
||||
#endif // #if defined(_WIN32)
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
#include "ringbuffer.h"
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Implementation of ring buffer functions.
|
||||
*/
|
||||
|
||||
void ring_buffer_init(ring_buffer_t *buffer, char *buf, size_t buf_size) {
|
||||
RING_BUFFER_ASSERT(RING_BUFFER_IS_POWER_OF_TWO(buf_size) == 1);
|
||||
buffer->buffer = buf;
|
||||
buffer->buffer_mask = buf_size - 1;
|
||||
buffer->tail_index = 0;
|
||||
buffer->head_index = 0;
|
||||
}
|
||||
|
||||
void ring_buffer_queue(ring_buffer_t *buffer, char data) {
|
||||
/* Is buffer full? */
|
||||
if(ring_buffer_is_full(buffer)) {
|
||||
/* Is going to overwrite the oldest byte */
|
||||
/* Increase tail index */
|
||||
buffer->tail_index = ((buffer->tail_index + 1) & RING_BUFFER_MASK(buffer));
|
||||
}
|
||||
|
||||
/* Place data in buffer */
|
||||
buffer->buffer[buffer->head_index] = data;
|
||||
buffer->head_index = ((buffer->head_index + 1) & RING_BUFFER_MASK(buffer));
|
||||
}
|
||||
|
||||
void ring_buffer_queue_arr(ring_buffer_t *buffer, const char *data, ring_buffer_size_t size) {
|
||||
/* Add bytes; one by one */
|
||||
ring_buffer_size_t i;
|
||||
for(i = 0; i < size; i++) {
|
||||
ring_buffer_queue(buffer, data[i]);
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t ring_buffer_dequeue(ring_buffer_t *buffer, char *data) {
|
||||
if(ring_buffer_is_empty(buffer)) {
|
||||
/* No items */
|
||||
return 0;
|
||||
}
|
||||
|
||||
*data = buffer->buffer[buffer->tail_index];
|
||||
buffer->tail_index = ((buffer->tail_index + 1) & RING_BUFFER_MASK(buffer));
|
||||
return 1;
|
||||
}
|
||||
|
||||
ring_buffer_size_t ring_buffer_dequeue_arr(ring_buffer_t *buffer, char *data, ring_buffer_size_t len) {
|
||||
if(ring_buffer_is_empty(buffer)) {
|
||||
/* No items */
|
||||
return 0;
|
||||
}
|
||||
|
||||
char *data_ptr = data;
|
||||
ring_buffer_size_t cnt = 0;
|
||||
while((cnt < len) && ring_buffer_dequeue(buffer, data_ptr)) {
|
||||
cnt++;
|
||||
data_ptr++;
|
||||
}
|
||||
return cnt;
|
||||
}
|
||||
|
||||
uint8_t ring_buffer_peek(ring_buffer_t *buffer, char *data, ring_buffer_size_t index) {
|
||||
if(index >= ring_buffer_num_items(buffer)) {
|
||||
/* No items at index */
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Add index to pointer */
|
||||
ring_buffer_size_t data_index = ((buffer->tail_index + index) & RING_BUFFER_MASK(buffer));
|
||||
*data = buffer->buffer[data_index];
|
||||
return 1;
|
||||
}
|
||||
|
||||
extern inline uint8_t ring_buffer_is_empty(ring_buffer_t *buffer);
|
||||
extern inline uint8_t ring_buffer_is_full(ring_buffer_t *buffer);
|
||||
extern inline ring_buffer_size_t ring_buffer_num_items(ring_buffer_t *buffer);
|
||||
|
||||
+432
@@ -0,0 +1,432 @@
|
||||
/* Copyright 2012 William Woodall and John Harrison */
|
||||
#include <algorithm>
|
||||
|
||||
#if !defined(_WIN32) && !defined(__OpenBSD__) && !defined(__FreeBSD__)
|
||||
# include <alloca.h>
|
||||
#endif
|
||||
|
||||
#if defined (__MINGW32__)
|
||||
# define alloca __builtin_alloca
|
||||
#endif
|
||||
|
||||
#include "../include/serial/serial.h"
|
||||
|
||||
#ifdef _WIN32
|
||||
#include "serial/impl/win.h"
|
||||
#else
|
||||
#include "../include/serial/impl/unix.h"
|
||||
#endif
|
||||
|
||||
using std::invalid_argument;
|
||||
using std::min;
|
||||
using std::numeric_limits;
|
||||
using std::vector;
|
||||
using std::size_t;
|
||||
using std::string;
|
||||
|
||||
using serial::Serial;
|
||||
using serial::SerialException;
|
||||
using serial::IOException;
|
||||
using serial::bytesize_t;
|
||||
using serial::parity_t;
|
||||
using serial::stopbits_t;
|
||||
using serial::flowcontrol_t;
|
||||
|
||||
class Serial::ScopedReadLock {
|
||||
public:
|
||||
ScopedReadLock(SerialImpl *pimpl) : pimpl_(pimpl) {
|
||||
this->pimpl_->readLock();
|
||||
}
|
||||
~ScopedReadLock() {
|
||||
this->pimpl_->readUnlock();
|
||||
}
|
||||
private:
|
||||
// Disable copy constructors
|
||||
ScopedReadLock(const ScopedReadLock&);
|
||||
const ScopedReadLock& operator=(ScopedReadLock);
|
||||
|
||||
SerialImpl *pimpl_;
|
||||
};
|
||||
|
||||
class Serial::ScopedWriteLock {
|
||||
public:
|
||||
ScopedWriteLock(SerialImpl *pimpl) : pimpl_(pimpl) {
|
||||
this->pimpl_->writeLock();
|
||||
}
|
||||
~ScopedWriteLock() {
|
||||
this->pimpl_->writeUnlock();
|
||||
}
|
||||
private:
|
||||
// Disable copy constructors
|
||||
ScopedWriteLock(const ScopedWriteLock&);
|
||||
const ScopedWriteLock& operator=(ScopedWriteLock);
|
||||
SerialImpl *pimpl_;
|
||||
};
|
||||
|
||||
Serial::Serial (const string &port, uint32_t baudrate, serial::Timeout timeout,
|
||||
bytesize_t bytesize, parity_t parity, stopbits_t stopbits,
|
||||
flowcontrol_t flowcontrol)
|
||||
: pimpl_(new SerialImpl (port, baudrate, bytesize, parity,
|
||||
stopbits, flowcontrol))
|
||||
{
|
||||
pimpl_->setTimeout(timeout);
|
||||
}
|
||||
|
||||
Serial::~Serial ()
|
||||
{
|
||||
delete pimpl_;
|
||||
}
|
||||
|
||||
void
|
||||
Serial::open ()
|
||||
{
|
||||
pimpl_->open ();
|
||||
}
|
||||
|
||||
void
|
||||
Serial::close ()
|
||||
{
|
||||
pimpl_->close ();
|
||||
}
|
||||
|
||||
bool
|
||||
Serial::isOpen () const
|
||||
{
|
||||
return pimpl_->isOpen ();
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::available ()
|
||||
{
|
||||
return pimpl_->available ();
|
||||
}
|
||||
|
||||
bool
|
||||
Serial::waitReadable ()
|
||||
{
|
||||
serial::Timeout timeout(pimpl_->getTimeout ());
|
||||
return pimpl_->waitReadable(timeout.read_timeout_constant);
|
||||
}
|
||||
|
||||
void
|
||||
Serial::waitByteTimes (size_t count)
|
||||
{
|
||||
pimpl_->waitByteTimes(count);
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::read_ (uint8_t *buffer, size_t size)
|
||||
{
|
||||
return this->pimpl_->read (buffer, size);
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::read (uint8_t *buffer, size_t size)
|
||||
{
|
||||
ScopedReadLock lock(this->pimpl_);
|
||||
return this->pimpl_->read (buffer, size);
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::read (std::vector<uint8_t> &buffer, size_t size)
|
||||
{
|
||||
ScopedReadLock lock(this->pimpl_);
|
||||
uint8_t *buffer_ = new uint8_t[size];
|
||||
size_t bytes_read = 0;
|
||||
|
||||
try {
|
||||
bytes_read = this->pimpl_->read (buffer_, size);
|
||||
}
|
||||
catch (const std::exception) {
|
||||
delete[] buffer_;
|
||||
throw;
|
||||
}
|
||||
|
||||
buffer.insert (buffer.end (), buffer_, buffer_+bytes_read);
|
||||
delete[] buffer_;
|
||||
return bytes_read;
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::read (std::string &buffer, size_t size)
|
||||
{
|
||||
ScopedReadLock lock(this->pimpl_);
|
||||
uint8_t *buffer_ = new uint8_t[size];
|
||||
size_t bytes_read = 0;
|
||||
try {
|
||||
bytes_read = this->pimpl_->read (buffer_, size);
|
||||
}
|
||||
catch (const std::exception) {
|
||||
delete[] buffer_;
|
||||
throw;
|
||||
}
|
||||
buffer.append (reinterpret_cast<const char*>(buffer_), bytes_read);
|
||||
delete[] buffer_;
|
||||
return bytes_read;
|
||||
}
|
||||
|
||||
string
|
||||
Serial::read (size_t size)
|
||||
{
|
||||
std::string buffer;
|
||||
this->read (buffer, size);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::readline (string &buffer, size_t size, string eol)
|
||||
{
|
||||
ScopedReadLock lock(this->pimpl_);
|
||||
size_t eol_len = eol.length ();
|
||||
uint8_t *buffer_ = static_cast<uint8_t*>
|
||||
(alloca (size * sizeof (uint8_t)));
|
||||
size_t read_so_far = 0;
|
||||
while (true)
|
||||
{
|
||||
size_t bytes_read = this->read_ (buffer_ + read_so_far, 1);
|
||||
read_so_far += bytes_read;
|
||||
if (bytes_read == 0) {
|
||||
break; // Timeout occured on reading 1 byte
|
||||
}
|
||||
if(read_so_far < eol_len) continue;
|
||||
if (string (reinterpret_cast<const char*>
|
||||
(buffer_ + read_so_far - eol_len), eol_len) == eol) {
|
||||
break; // EOL found
|
||||
}
|
||||
if (read_so_far == size) {
|
||||
break; // Reached the maximum read length
|
||||
}
|
||||
}
|
||||
buffer.append(reinterpret_cast<const char*> (buffer_), read_so_far);
|
||||
return read_so_far;
|
||||
}
|
||||
|
||||
string
|
||||
Serial::readline (size_t size, string eol)
|
||||
{
|
||||
std::string buffer;
|
||||
this->readline (buffer, size, eol);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
vector<string>
|
||||
Serial::readlines (size_t size, string eol)
|
||||
{
|
||||
ScopedReadLock lock(this->pimpl_);
|
||||
std::vector<std::string> lines;
|
||||
size_t eol_len = eol.length ();
|
||||
uint8_t *buffer_ = static_cast<uint8_t*>
|
||||
(alloca (size * sizeof (uint8_t)));
|
||||
size_t read_so_far = 0;
|
||||
size_t start_of_line = 0;
|
||||
while (read_so_far < size) {
|
||||
size_t bytes_read = this->read_ (buffer_+read_so_far, 1);
|
||||
read_so_far += bytes_read;
|
||||
if (bytes_read == 0) {
|
||||
if (start_of_line != read_so_far) {
|
||||
lines.push_back (
|
||||
string (reinterpret_cast<const char*> (buffer_ + start_of_line),
|
||||
read_so_far - start_of_line));
|
||||
}
|
||||
break; // Timeout occured on reading 1 byte
|
||||
}
|
||||
if(read_so_far < eol_len) continue;
|
||||
if (string (reinterpret_cast<const char*>
|
||||
(buffer_ + read_so_far - eol_len), eol_len) == eol) {
|
||||
// EOL found
|
||||
lines.push_back(
|
||||
string(reinterpret_cast<const char*> (buffer_ + start_of_line),
|
||||
read_so_far - start_of_line));
|
||||
start_of_line = read_so_far;
|
||||
}
|
||||
if (read_so_far == size) {
|
||||
if (start_of_line != read_so_far) {
|
||||
lines.push_back(
|
||||
string(reinterpret_cast<const char*> (buffer_ + start_of_line),
|
||||
read_so_far - start_of_line));
|
||||
}
|
||||
break; // Reached the maximum read length
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::write (const string &data)
|
||||
{
|
||||
ScopedWriteLock lock(this->pimpl_);
|
||||
return this->write_ (reinterpret_cast<const uint8_t*>(data.c_str()),
|
||||
data.length());
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::write (const std::vector<uint8_t> &data)
|
||||
{
|
||||
ScopedWriteLock lock(this->pimpl_);
|
||||
return this->write_ (&data[0], data.size());
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::write (const uint8_t *data, size_t size)
|
||||
{
|
||||
ScopedWriteLock lock(this->pimpl_);
|
||||
return this->write_(data, size);
|
||||
}
|
||||
|
||||
size_t
|
||||
Serial::write_ (const uint8_t *data, size_t length)
|
||||
{
|
||||
return pimpl_->write (data, length);
|
||||
}
|
||||
|
||||
void
|
||||
Serial::setPort (const string &port)
|
||||
{
|
||||
ScopedReadLock rlock(this->pimpl_);
|
||||
ScopedWriteLock wlock(this->pimpl_);
|
||||
bool was_open = pimpl_->isOpen ();
|
||||
if (was_open) close();
|
||||
pimpl_->setPort (port);
|
||||
if (was_open) open ();
|
||||
}
|
||||
|
||||
string
|
||||
Serial::getPort () const
|
||||
{
|
||||
return pimpl_->getPort ();
|
||||
}
|
||||
|
||||
void
|
||||
Serial::setTimeout (serial::Timeout &timeout)
|
||||
{
|
||||
pimpl_->setTimeout (timeout);
|
||||
}
|
||||
|
||||
serial::Timeout
|
||||
Serial::getTimeout () const {
|
||||
return pimpl_->getTimeout ();
|
||||
}
|
||||
|
||||
void
|
||||
Serial::setBaudrate (uint32_t baudrate)
|
||||
{
|
||||
pimpl_->setBaudrate (baudrate);
|
||||
}
|
||||
|
||||
uint32_t
|
||||
Serial::getBaudrate () const
|
||||
{
|
||||
return uint32_t(pimpl_->getBaudrate ());
|
||||
}
|
||||
|
||||
void
|
||||
Serial::setBytesize (bytesize_t bytesize)
|
||||
{
|
||||
pimpl_->setBytesize (bytesize);
|
||||
}
|
||||
|
||||
bytesize_t
|
||||
Serial::getBytesize () const
|
||||
{
|
||||
return pimpl_->getBytesize ();
|
||||
}
|
||||
|
||||
void
|
||||
Serial::setParity (parity_t parity)
|
||||
{
|
||||
pimpl_->setParity (parity);
|
||||
}
|
||||
|
||||
parity_t
|
||||
Serial::getParity () const
|
||||
{
|
||||
return pimpl_->getParity ();
|
||||
}
|
||||
|
||||
void
|
||||
Serial::setStopbits (stopbits_t stopbits)
|
||||
{
|
||||
pimpl_->setStopbits (stopbits);
|
||||
}
|
||||
|
||||
stopbits_t
|
||||
Serial::getStopbits () const
|
||||
{
|
||||
return pimpl_->getStopbits ();
|
||||
}
|
||||
|
||||
void
|
||||
Serial::setFlowcontrol (flowcontrol_t flowcontrol)
|
||||
{
|
||||
pimpl_->setFlowcontrol (flowcontrol);
|
||||
}
|
||||
|
||||
flowcontrol_t
|
||||
Serial::getFlowcontrol () const
|
||||
{
|
||||
return pimpl_->getFlowcontrol ();
|
||||
}
|
||||
|
||||
void Serial::flush ()
|
||||
{
|
||||
ScopedReadLock rlock(this->pimpl_);
|
||||
ScopedWriteLock wlock(this->pimpl_);
|
||||
pimpl_->flush ();
|
||||
}
|
||||
|
||||
void Serial::flushInput ()
|
||||
{
|
||||
ScopedReadLock lock(this->pimpl_);
|
||||
pimpl_->flushInput ();
|
||||
}
|
||||
|
||||
void Serial::flushOutput ()
|
||||
{
|
||||
ScopedWriteLock lock(this->pimpl_);
|
||||
pimpl_->flushOutput ();
|
||||
}
|
||||
|
||||
void Serial::sendBreak (int duration)
|
||||
{
|
||||
pimpl_->sendBreak (duration);
|
||||
}
|
||||
|
||||
void Serial::setBreak (bool level)
|
||||
{
|
||||
pimpl_->setBreak (level);
|
||||
}
|
||||
|
||||
void Serial::setRTS (bool level)
|
||||
{
|
||||
pimpl_->setRTS (level);
|
||||
}
|
||||
|
||||
void Serial::setDTR (bool level)
|
||||
{
|
||||
pimpl_->setDTR (level);
|
||||
}
|
||||
|
||||
bool Serial::waitForChange()
|
||||
{
|
||||
return pimpl_->waitForChange();
|
||||
}
|
||||
|
||||
bool Serial::getCTS ()
|
||||
{
|
||||
return pimpl_->getCTS ();
|
||||
}
|
||||
|
||||
bool Serial::getDSR ()
|
||||
{
|
||||
return pimpl_->getDSR ();
|
||||
}
|
||||
|
||||
bool Serial::getRI ()
|
||||
{
|
||||
return pimpl_->getRI ();
|
||||
}
|
||||
|
||||
bool Serial::getCD ()
|
||||
{
|
||||
return pimpl_->getCD ();
|
||||
}
|
||||
@@ -0,0 +1,931 @@
|
||||
/* -*- mode: c; tab-width: 2; indent-tabs-mode: nil; -*-
|
||||
Copyright (c) 2012 Marcus Geelnard
|
||||
Copyright (c) 2013-2016 Evan Nemerson
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
*/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include "../include/tinycthread.h"
|
||||
|
||||
/* Platform specific includes */
|
||||
#if defined(_TTHREAD_POSIX_)
|
||||
#include <signal.h>
|
||||
#include <sched.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/time.h>
|
||||
#include <errno.h>
|
||||
#elif defined(_TTHREAD_WIN32_)
|
||||
#include <process.h>
|
||||
#include <sys/timeb.h>
|
||||
#endif
|
||||
|
||||
/* Standard, good-to-have defines */
|
||||
#ifndef NULL
|
||||
#define NULL (void*)0
|
||||
#endif
|
||||
#ifndef TRUE
|
||||
#define TRUE 1
|
||||
#endif
|
||||
#ifndef FALSE
|
||||
#define FALSE 0
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
|
||||
int mtx_init(mtx_t *mtx, int type)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
mtx->mAlreadyLocked = FALSE;
|
||||
mtx->mRecursive = type & mtx_recursive;
|
||||
mtx->mTimed = type & mtx_timed;
|
||||
if (!mtx->mTimed)
|
||||
{
|
||||
InitializeCriticalSection(&(mtx->mHandle.cs));
|
||||
}
|
||||
else
|
||||
{
|
||||
mtx->mHandle.mut = CreateMutex(NULL, FALSE, NULL);
|
||||
if (mtx->mHandle.mut == NULL)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
}
|
||||
return thrd_success;
|
||||
#else
|
||||
int ret;
|
||||
pthread_mutexattr_t attr;
|
||||
pthread_mutexattr_init(&attr);
|
||||
if (type & mtx_recursive)
|
||||
{
|
||||
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
|
||||
}
|
||||
ret = pthread_mutex_init(mtx, &attr);
|
||||
pthread_mutexattr_destroy(&attr);
|
||||
return ret == 0 ? thrd_success : thrd_error;
|
||||
#endif
|
||||
}
|
||||
|
||||
void mtx_destroy(mtx_t *mtx)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
if (!mtx->mTimed)
|
||||
{
|
||||
DeleteCriticalSection(&(mtx->mHandle.cs));
|
||||
}
|
||||
else
|
||||
{
|
||||
CloseHandle(mtx->mHandle.mut);
|
||||
}
|
||||
#else
|
||||
pthread_mutex_destroy(mtx);
|
||||
#endif
|
||||
}
|
||||
|
||||
int mtx_lock(mtx_t *mtx)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
if (!mtx->mTimed)
|
||||
{
|
||||
EnterCriticalSection(&(mtx->mHandle.cs));
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (WaitForSingleObject(mtx->mHandle.mut, INFINITE))
|
||||
{
|
||||
case WAIT_OBJECT_0:
|
||||
break;
|
||||
case WAIT_ABANDONED:
|
||||
default:
|
||||
return thrd_error;
|
||||
}
|
||||
}
|
||||
|
||||
if (!mtx->mRecursive)
|
||||
{
|
||||
while(mtx->mAlreadyLocked) Sleep(1); /* Simulate deadlock... */
|
||||
mtx->mAlreadyLocked = TRUE;
|
||||
}
|
||||
return thrd_success;
|
||||
#else
|
||||
return pthread_mutex_lock(mtx) == 0 ? thrd_success : thrd_error;
|
||||
#endif
|
||||
}
|
||||
|
||||
int mtx_timedlock(mtx_t *mtx, const struct timespec *ts)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
struct timespec current_ts;
|
||||
DWORD timeoutMs;
|
||||
|
||||
if (!mtx->mTimed)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
|
||||
timespec_get(¤t_ts, TIME_UTC);
|
||||
|
||||
if ((current_ts.tv_sec > ts->tv_sec) || ((current_ts.tv_sec == ts->tv_sec) && (current_ts.tv_nsec >= ts->tv_nsec)))
|
||||
{
|
||||
timeoutMs = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
timeoutMs = (DWORD)(ts->tv_sec - current_ts.tv_sec) * 1000;
|
||||
timeoutMs += (ts->tv_nsec - current_ts.tv_nsec) / 1000000;
|
||||
timeoutMs += 1;
|
||||
}
|
||||
|
||||
/* TODO: the timeout for WaitForSingleObject doesn't include time
|
||||
while the computer is asleep. */
|
||||
switch (WaitForSingleObject(mtx->mHandle.mut, timeoutMs))
|
||||
{
|
||||
case WAIT_OBJECT_0:
|
||||
break;
|
||||
case WAIT_TIMEOUT:
|
||||
return thrd_timedout;
|
||||
case WAIT_ABANDONED:
|
||||
default:
|
||||
return thrd_error;
|
||||
}
|
||||
|
||||
if (!mtx->mRecursive)
|
||||
{
|
||||
while(mtx->mAlreadyLocked) Sleep(1); /* Simulate deadlock... */
|
||||
mtx->mAlreadyLocked = TRUE;
|
||||
}
|
||||
|
||||
return thrd_success;
|
||||
#elif defined(_POSIX_TIMEOUTS) && (_POSIX_TIMEOUTS >= 200112L) && defined(_POSIX_THREADS) && (_POSIX_THREADS >= 200112L)
|
||||
switch (pthread_mutex_timedlock(mtx, ts)) {
|
||||
case 0:
|
||||
return thrd_success;
|
||||
case ETIMEDOUT:
|
||||
return thrd_timedout;
|
||||
default:
|
||||
return thrd_error;
|
||||
}
|
||||
#else
|
||||
int rc;
|
||||
struct timespec cur, dur;
|
||||
|
||||
/* Try to acquire the lock and, if we fail, sleep for 5ms. */
|
||||
while ((rc = pthread_mutex_trylock (mtx)) == EBUSY) {
|
||||
timespec_get(&cur, TIME_UTC);
|
||||
|
||||
if ((cur.tv_sec > ts->tv_sec) || ((cur.tv_sec == ts->tv_sec) && (cur.tv_nsec >= ts->tv_nsec)))
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
dur.tv_sec = ts->tv_sec - cur.tv_sec;
|
||||
dur.tv_nsec = ts->tv_nsec - cur.tv_nsec;
|
||||
if (dur.tv_nsec < 0)
|
||||
{
|
||||
dur.tv_sec--;
|
||||
dur.tv_nsec += 1000000000;
|
||||
}
|
||||
|
||||
if ((dur.tv_sec != 0) || (dur.tv_nsec > 5000000))
|
||||
{
|
||||
dur.tv_sec = 0;
|
||||
dur.tv_nsec = 5000000;
|
||||
}
|
||||
|
||||
nanosleep(&dur, NULL);
|
||||
}
|
||||
|
||||
switch (rc) {
|
||||
case 0:
|
||||
return thrd_success;
|
||||
case ETIMEDOUT:
|
||||
case EBUSY:
|
||||
return thrd_timedout;
|
||||
default:
|
||||
return thrd_error;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
int mtx_trylock(mtx_t *mtx)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
int ret;
|
||||
|
||||
if (!mtx->mTimed)
|
||||
{
|
||||
ret = TryEnterCriticalSection(&(mtx->mHandle.cs)) ? thrd_success : thrd_busy;
|
||||
}
|
||||
else
|
||||
{
|
||||
ret = (WaitForSingleObject(mtx->mHandle.mut, 0) == WAIT_OBJECT_0) ? thrd_success : thrd_busy;
|
||||
}
|
||||
|
||||
if ((!mtx->mRecursive) && (ret == thrd_success))
|
||||
{
|
||||
if (mtx->mAlreadyLocked)
|
||||
{
|
||||
LeaveCriticalSection(&(mtx->mHandle.cs));
|
||||
ret = thrd_busy;
|
||||
}
|
||||
else
|
||||
{
|
||||
mtx->mAlreadyLocked = TRUE;
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
#else
|
||||
return (pthread_mutex_trylock(mtx) == 0) ? thrd_success : thrd_busy;
|
||||
#endif
|
||||
}
|
||||
|
||||
int mtx_unlock(mtx_t *mtx)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
mtx->mAlreadyLocked = FALSE;
|
||||
if (!mtx->mTimed)
|
||||
{
|
||||
LeaveCriticalSection(&(mtx->mHandle.cs));
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!ReleaseMutex(mtx->mHandle.mut))
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
}
|
||||
return thrd_success;
|
||||
#else
|
||||
return pthread_mutex_unlock(mtx) == 0 ? thrd_success : thrd_error;;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
#define _CONDITION_EVENT_ONE 0
|
||||
#define _CONDITION_EVENT_ALL 1
|
||||
#endif
|
||||
|
||||
int cnd_init(cnd_t *cond)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
cond->mWaitersCount = 0;
|
||||
|
||||
/* Init critical section */
|
||||
InitializeCriticalSection(&cond->mWaitersCountLock);
|
||||
|
||||
/* Init events */
|
||||
cond->mEvents[_CONDITION_EVENT_ONE] = CreateEvent(NULL, FALSE, FALSE, NULL);
|
||||
if (cond->mEvents[_CONDITION_EVENT_ONE] == NULL)
|
||||
{
|
||||
cond->mEvents[_CONDITION_EVENT_ALL] = NULL;
|
||||
return thrd_error;
|
||||
}
|
||||
cond->mEvents[_CONDITION_EVENT_ALL] = CreateEvent(NULL, TRUE, FALSE, NULL);
|
||||
if (cond->mEvents[_CONDITION_EVENT_ALL] == NULL)
|
||||
{
|
||||
CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]);
|
||||
cond->mEvents[_CONDITION_EVENT_ONE] = NULL;
|
||||
return thrd_error;
|
||||
}
|
||||
|
||||
return thrd_success;
|
||||
#else
|
||||
return pthread_cond_init(cond, NULL) == 0 ? thrd_success : thrd_error;
|
||||
#endif
|
||||
}
|
||||
|
||||
void cnd_destroy(cnd_t *cond)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
if (cond->mEvents[_CONDITION_EVENT_ONE] != NULL)
|
||||
{
|
||||
CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]);
|
||||
}
|
||||
if (cond->mEvents[_CONDITION_EVENT_ALL] != NULL)
|
||||
{
|
||||
CloseHandle(cond->mEvents[_CONDITION_EVENT_ALL]);
|
||||
}
|
||||
DeleteCriticalSection(&cond->mWaitersCountLock);
|
||||
#else
|
||||
pthread_cond_destroy(cond);
|
||||
#endif
|
||||
}
|
||||
|
||||
int cnd_signal(cnd_t *cond)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
int haveWaiters;
|
||||
|
||||
/* Are there any waiters? */
|
||||
EnterCriticalSection(&cond->mWaitersCountLock);
|
||||
haveWaiters = (cond->mWaitersCount > 0);
|
||||
LeaveCriticalSection(&cond->mWaitersCountLock);
|
||||
|
||||
/* If we have any waiting threads, send them a signal */
|
||||
if(haveWaiters)
|
||||
{
|
||||
if (SetEvent(cond->mEvents[_CONDITION_EVENT_ONE]) == 0)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
}
|
||||
|
||||
return thrd_success;
|
||||
#else
|
||||
return pthread_cond_signal(cond) == 0 ? thrd_success : thrd_error;
|
||||
#endif
|
||||
}
|
||||
|
||||
int cnd_broadcast(cnd_t *cond)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
int haveWaiters;
|
||||
|
||||
/* Are there any waiters? */
|
||||
EnterCriticalSection(&cond->mWaitersCountLock);
|
||||
haveWaiters = (cond->mWaitersCount > 0);
|
||||
LeaveCriticalSection(&cond->mWaitersCountLock);
|
||||
|
||||
/* If we have any waiting threads, send them a signal */
|
||||
if(haveWaiters)
|
||||
{
|
||||
if (SetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
}
|
||||
|
||||
return thrd_success;
|
||||
#else
|
||||
return pthread_cond_broadcast(cond) == 0 ? thrd_success : thrd_error;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
static int _cnd_timedwait_win32(cnd_t *cond, mtx_t *mtx, DWORD timeout)
|
||||
{
|
||||
DWORD result;
|
||||
int lastWaiter;
|
||||
|
||||
/* Increment number of waiters */
|
||||
EnterCriticalSection(&cond->mWaitersCountLock);
|
||||
++ cond->mWaitersCount;
|
||||
LeaveCriticalSection(&cond->mWaitersCountLock);
|
||||
|
||||
/* Release the mutex while waiting for the condition (will decrease
|
||||
the number of waiters when done)... */
|
||||
mtx_unlock(mtx);
|
||||
|
||||
/* Wait for either event to become signaled due to cnd_signal() or
|
||||
cnd_broadcast() being called */
|
||||
result = WaitForMultipleObjects(2, cond->mEvents, FALSE, timeout);
|
||||
if (result == WAIT_TIMEOUT)
|
||||
{
|
||||
/* The mutex is locked again before the function returns, even if an error occurred */
|
||||
mtx_lock(mtx);
|
||||
return thrd_timedout;
|
||||
}
|
||||
else if (result == WAIT_FAILED)
|
||||
{
|
||||
/* The mutex is locked again before the function returns, even if an error occurred */
|
||||
mtx_lock(mtx);
|
||||
return thrd_error;
|
||||
}
|
||||
|
||||
/* Check if we are the last waiter */
|
||||
EnterCriticalSection(&cond->mWaitersCountLock);
|
||||
-- cond->mWaitersCount;
|
||||
lastWaiter = (result == (WAIT_OBJECT_0 + _CONDITION_EVENT_ALL)) &&
|
||||
(cond->mWaitersCount == 0);
|
||||
LeaveCriticalSection(&cond->mWaitersCountLock);
|
||||
|
||||
/* If we are the last waiter to be notified to stop waiting, reset the event */
|
||||
if (lastWaiter)
|
||||
{
|
||||
if (ResetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0)
|
||||
{
|
||||
/* The mutex is locked again before the function returns, even if an error occurred */
|
||||
mtx_lock(mtx);
|
||||
return thrd_error;
|
||||
}
|
||||
}
|
||||
|
||||
/* Re-acquire the mutex */
|
||||
mtx_lock(mtx);
|
||||
|
||||
return thrd_success;
|
||||
}
|
||||
#endif
|
||||
|
||||
int cnd_wait(cnd_t *cond, mtx_t *mtx)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
return _cnd_timedwait_win32(cond, mtx, INFINITE);
|
||||
#else
|
||||
return pthread_cond_wait(cond, mtx) == 0 ? thrd_success : thrd_error;
|
||||
#endif
|
||||
}
|
||||
|
||||
int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
struct timespec now;
|
||||
if (timespec_get(&now, TIME_UTC) == TIME_UTC)
|
||||
{
|
||||
unsigned long long nowInMilliseconds = now.tv_sec * 1000 + now.tv_nsec / 1000000;
|
||||
unsigned long long tsInMilliseconds = ts->tv_sec * 1000 + ts->tv_nsec / 1000000;
|
||||
DWORD delta = (tsInMilliseconds > nowInMilliseconds) ?
|
||||
(DWORD)(tsInMilliseconds - nowInMilliseconds) : 0;
|
||||
return _cnd_timedwait_win32(cond, mtx, delta);
|
||||
}
|
||||
else
|
||||
return thrd_error;
|
||||
#else
|
||||
int ret;
|
||||
ret = pthread_cond_timedwait(cond, mtx, ts);
|
||||
if (ret == ETIMEDOUT)
|
||||
{
|
||||
return thrd_timedout;
|
||||
}
|
||||
return ret == 0 ? thrd_success : thrd_error;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
struct TinyCThreadTSSData {
|
||||
void* value;
|
||||
tss_t key;
|
||||
struct TinyCThreadTSSData* next;
|
||||
};
|
||||
|
||||
static tss_dtor_t _tinycthread_tss_dtors[1088] = { NULL, };
|
||||
|
||||
static _Thread_local struct TinyCThreadTSSData* _tinycthread_tss_head = NULL;
|
||||
static _Thread_local struct TinyCThreadTSSData* _tinycthread_tss_tail = NULL;
|
||||
|
||||
static void _tinycthread_tss_cleanup (void);
|
||||
|
||||
static void _tinycthread_tss_cleanup (void) {
|
||||
struct TinyCThreadTSSData* data;
|
||||
int iteration;
|
||||
unsigned int again = 1;
|
||||
void* value;
|
||||
|
||||
for (iteration = 0 ; iteration < TSS_DTOR_ITERATIONS && again > 0 ; iteration++)
|
||||
{
|
||||
again = 0;
|
||||
for (data = _tinycthread_tss_head ; data != NULL ; data = data->next)
|
||||
{
|
||||
if (data->value != NULL)
|
||||
{
|
||||
value = data->value;
|
||||
data->value = NULL;
|
||||
|
||||
if (_tinycthread_tss_dtors[data->key] != NULL)
|
||||
{
|
||||
again = 1;
|
||||
_tinycthread_tss_dtors[data->key](value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
while (_tinycthread_tss_head != NULL) {
|
||||
data = _tinycthread_tss_head->next;
|
||||
free (_tinycthread_tss_head);
|
||||
_tinycthread_tss_head = data;
|
||||
}
|
||||
_tinycthread_tss_head = NULL;
|
||||
_tinycthread_tss_tail = NULL;
|
||||
}
|
||||
|
||||
static void NTAPI _tinycthread_tss_callback(PVOID h, DWORD dwReason, PVOID pv)
|
||||
{
|
||||
(void)h;
|
||||
(void)pv;
|
||||
|
||||
if (_tinycthread_tss_head != NULL && (dwReason == DLL_THREAD_DETACH || dwReason == DLL_PROCESS_DETACH))
|
||||
{
|
||||
_tinycthread_tss_cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
#ifdef _M_X64
|
||||
#pragma const_seg(".CRT$XLB")
|
||||
#else
|
||||
#pragma data_seg(".CRT$XLB")
|
||||
#endif
|
||||
PIMAGE_TLS_CALLBACK p_thread_callback = _tinycthread_tss_callback;
|
||||
#ifdef _M_X64
|
||||
#pragma data_seg()
|
||||
#else
|
||||
#pragma const_seg()
|
||||
#endif
|
||||
#else
|
||||
PIMAGE_TLS_CALLBACK p_thread_callback __attribute__((section(".CRT$XLB"))) = _tinycthread_tss_callback;
|
||||
#endif
|
||||
|
||||
#endif /* defined(_TTHREAD_WIN32_) */
|
||||
|
||||
/** Information to pass to the new thread (what to run). */
|
||||
typedef struct {
|
||||
thrd_start_t mFunction; /**< Pointer to the function to be executed. */
|
||||
void * mArg; /**< Function argument for the thread function. */
|
||||
} _thread_start_info;
|
||||
|
||||
/* Thread wrapper function. */
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
static DWORD WINAPI _thrd_wrapper_function(LPVOID aArg)
|
||||
#elif defined(_TTHREAD_POSIX_)
|
||||
static void * _thrd_wrapper_function(void * aArg)
|
||||
#endif
|
||||
{
|
||||
thrd_start_t fun;
|
||||
void *arg;
|
||||
int res;
|
||||
|
||||
/* Get thread startup information */
|
||||
_thread_start_info *ti = (_thread_start_info *) aArg;
|
||||
fun = ti->mFunction;
|
||||
arg = ti->mArg;
|
||||
|
||||
/* The thread is responsible for freeing the startup information */
|
||||
free((void *)ti);
|
||||
|
||||
/* Call the actual client thread function */
|
||||
res = fun(arg);
|
||||
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
if (_tinycthread_tss_head != NULL)
|
||||
{
|
||||
_tinycthread_tss_cleanup();
|
||||
}
|
||||
|
||||
return (DWORD)res;
|
||||
#else
|
||||
return (void*)(intptr_t)res;
|
||||
#endif
|
||||
}
|
||||
|
||||
int thrd_create(thrd_t *thr, thrd_start_t func, void *arg)
|
||||
{
|
||||
/* Fill out the thread startup information (passed to the thread wrapper,
|
||||
which will eventually free it) */
|
||||
_thread_start_info* ti = (_thread_start_info*)malloc(sizeof(_thread_start_info));
|
||||
if (ti == NULL)
|
||||
{
|
||||
return thrd_nomem;
|
||||
}
|
||||
ti->mFunction = func;
|
||||
ti->mArg = arg;
|
||||
|
||||
/* Create the thread */
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
*thr = CreateThread(NULL, 0, _thrd_wrapper_function, (LPVOID) ti, 0, NULL);
|
||||
#elif defined(_TTHREAD_POSIX_)
|
||||
if(pthread_create(thr, NULL, _thrd_wrapper_function, (void *)ti) != 0)
|
||||
{
|
||||
*thr = 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Did we fail to create the thread? */
|
||||
if(!*thr)
|
||||
{
|
||||
free(ti);
|
||||
return thrd_error;
|
||||
}
|
||||
|
||||
return thrd_success;
|
||||
}
|
||||
|
||||
thrd_t thrd_current(void)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
return GetCurrentThread();
|
||||
#else
|
||||
return pthread_self();
|
||||
#endif
|
||||
}
|
||||
|
||||
int thrd_detach(thrd_t thr)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
/* https://stackoverflow.com/questions/12744324/how-to-detach-a-thread-on-windows-c#answer-12746081 */
|
||||
return CloseHandle(thr) != 0 ? thrd_success : thrd_error;
|
||||
#else
|
||||
return pthread_detach(thr) == 0 ? thrd_success : thrd_error;
|
||||
#endif
|
||||
}
|
||||
|
||||
int thrd_equal(thrd_t thr0, thrd_t thr1)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
return GetThreadId(thr0) == GetThreadId(thr1);
|
||||
#else
|
||||
return pthread_equal(thr0, thr1);
|
||||
#endif
|
||||
}
|
||||
|
||||
void thrd_exit(int res)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
if (_tinycthread_tss_head != NULL)
|
||||
{
|
||||
_tinycthread_tss_cleanup();
|
||||
}
|
||||
|
||||
ExitThread((DWORD)res);
|
||||
#else
|
||||
pthread_exit((void*)(intptr_t)res);
|
||||
#endif
|
||||
}
|
||||
|
||||
int thrd_join(thrd_t thr, int *res)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
DWORD dwRes;
|
||||
|
||||
if (WaitForSingleObject(thr, INFINITE) == WAIT_FAILED)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
if (res != NULL)
|
||||
{
|
||||
if (GetExitCodeThread(thr, &dwRes) != 0)
|
||||
{
|
||||
*res = (int) dwRes;
|
||||
}
|
||||
else
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
}
|
||||
CloseHandle(thr);
|
||||
#elif defined(_TTHREAD_POSIX_)
|
||||
void *pres;
|
||||
if (pthread_join(thr, &pres) != 0)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
if (res != NULL)
|
||||
{
|
||||
*res = (int)(intptr_t)pres;
|
||||
}
|
||||
#endif
|
||||
return thrd_success;
|
||||
}
|
||||
|
||||
int thrd_sleep(const struct timespec *duration, struct timespec *remaining)
|
||||
{
|
||||
#if !defined(_TTHREAD_WIN32_)
|
||||
int res = nanosleep(duration, remaining);
|
||||
if (res == 0) {
|
||||
return 0;
|
||||
} else if (errno == EINTR) {
|
||||
return -1;
|
||||
} else {
|
||||
return -2;
|
||||
}
|
||||
#else
|
||||
struct timespec start;
|
||||
DWORD t;
|
||||
|
||||
timespec_get(&start, TIME_UTC);
|
||||
|
||||
t = SleepEx((DWORD)(duration->tv_sec * 1000 +
|
||||
duration->tv_nsec / 1000000 +
|
||||
(((duration->tv_nsec % 1000000) == 0) ? 0 : 1)),
|
||||
TRUE);
|
||||
|
||||
if (t == 0) {
|
||||
return 0;
|
||||
} else {
|
||||
if (remaining != NULL) {
|
||||
timespec_get(remaining, TIME_UTC);
|
||||
remaining->tv_sec -= start.tv_sec;
|
||||
remaining->tv_nsec -= start.tv_nsec;
|
||||
if (remaining->tv_nsec < 0)
|
||||
{
|
||||
remaining->tv_nsec += 1000000000;
|
||||
remaining->tv_sec -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
return (t == WAIT_IO_COMPLETION) ? -1 : -2;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void thrd_yield(void)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
Sleep(0);
|
||||
#else
|
||||
sched_yield();
|
||||
#endif
|
||||
}
|
||||
|
||||
int tss_create(tss_t *key, tss_dtor_t dtor)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
*key = TlsAlloc();
|
||||
if (*key == TLS_OUT_OF_INDEXES)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
_tinycthread_tss_dtors[*key] = dtor;
|
||||
#else
|
||||
if (pthread_key_create(key, dtor) != 0)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
#endif
|
||||
return thrd_success;
|
||||
}
|
||||
|
||||
void tss_delete(tss_t key)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*) TlsGetValue (key);
|
||||
struct TinyCThreadTSSData* prev = NULL;
|
||||
if (data != NULL)
|
||||
{
|
||||
if (data == _tinycthread_tss_head)
|
||||
{
|
||||
_tinycthread_tss_head = data->next;
|
||||
}
|
||||
else
|
||||
{
|
||||
prev = _tinycthread_tss_head;
|
||||
if (prev != NULL)
|
||||
{
|
||||
while (prev->next != data)
|
||||
{
|
||||
prev = prev->next;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (data == _tinycthread_tss_tail)
|
||||
{
|
||||
_tinycthread_tss_tail = prev;
|
||||
}
|
||||
|
||||
free (data);
|
||||
}
|
||||
_tinycthread_tss_dtors[key] = NULL;
|
||||
TlsFree(key);
|
||||
#else
|
||||
pthread_key_delete(key);
|
||||
#endif
|
||||
}
|
||||
|
||||
void *tss_get(tss_t key)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*)TlsGetValue(key);
|
||||
if (data == NULL)
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
return data->value;
|
||||
#else
|
||||
return pthread_getspecific(key);
|
||||
#endif
|
||||
}
|
||||
|
||||
int tss_set(tss_t key, void *val)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*)TlsGetValue(key);
|
||||
if (data == NULL)
|
||||
{
|
||||
data = (struct TinyCThreadTSSData*)malloc(sizeof(struct TinyCThreadTSSData));
|
||||
if (data == NULL)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
|
||||
data->value = NULL;
|
||||
data->key = key;
|
||||
data->next = NULL;
|
||||
|
||||
if (_tinycthread_tss_tail != NULL)
|
||||
{
|
||||
_tinycthread_tss_tail->next = data;
|
||||
}
|
||||
else
|
||||
{
|
||||
_tinycthread_tss_tail = data;
|
||||
}
|
||||
|
||||
if (_tinycthread_tss_head == NULL)
|
||||
{
|
||||
_tinycthread_tss_head = data;
|
||||
}
|
||||
|
||||
if (!TlsSetValue(key, data))
|
||||
{
|
||||
free (data);
|
||||
return thrd_error;
|
||||
}
|
||||
}
|
||||
data->value = val;
|
||||
#else
|
||||
if (pthread_setspecific(key, val) != 0)
|
||||
{
|
||||
return thrd_error;
|
||||
}
|
||||
#endif
|
||||
return thrd_success;
|
||||
}
|
||||
|
||||
#if defined(_TTHREAD_EMULATE_TIMESPEC_GET_)
|
||||
int _tthread_timespec_get(struct timespec *ts, int base)
|
||||
{
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
struct _timeb tb;
|
||||
#elif !defined(CLOCK_REALTIME)
|
||||
struct timeval tv;
|
||||
#endif
|
||||
|
||||
if (base != TIME_UTC)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
_ftime_s(&tb);
|
||||
ts->tv_sec = (time_t)tb.time;
|
||||
ts->tv_nsec = 1000000L * (long)tb.millitm;
|
||||
#elif defined(CLOCK_REALTIME)
|
||||
base = (clock_gettime(CLOCK_REALTIME, ts) == 0) ? base : 0;
|
||||
#else
|
||||
gettimeofday(&tv, NULL);
|
||||
ts->tv_sec = (time_t)tv.tv_sec;
|
||||
ts->tv_nsec = 1000L * (long)tv.tv_usec;
|
||||
#endif
|
||||
|
||||
return base;
|
||||
}
|
||||
#endif /* _TTHREAD_EMULATE_TIMESPEC_GET_ */
|
||||
|
||||
#if defined(_TTHREAD_WIN32_)
|
||||
void call_once(once_flag *flag, void (*func)(void))
|
||||
{
|
||||
/* The idea here is that we use a spin lock (via the
|
||||
InterlockedCompareExchange function) to restrict access to the
|
||||
critical section until we have initialized it, then we use the
|
||||
critical section to block until the callback has completed
|
||||
execution. */
|
||||
while (flag->status < 3)
|
||||
{
|
||||
switch (flag->status)
|
||||
{
|
||||
case 0:
|
||||
if (InterlockedCompareExchange (&(flag->status), 1, 0) == 0) {
|
||||
InitializeCriticalSection(&(flag->lock));
|
||||
EnterCriticalSection(&(flag->lock));
|
||||
flag->status = 2;
|
||||
func();
|
||||
flag->status = 3;
|
||||
LeaveCriticalSection(&(flag->lock));
|
||||
return;
|
||||
}
|
||||
break;
|
||||
case 1:
|
||||
break;
|
||||
case 2:
|
||||
EnterCriticalSection(&(flag->lock));
|
||||
LeaveCriticalSection(&(flag->lock));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif /* defined(_TTHREAD_WIN32_) */
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,35 @@
|
||||
import 'dart:ffi';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flserial/flserial_bindings_generated.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
const String libName = 'flserial';
|
||||
|
||||
/// The dynamic library in which the symbols for [FlserialBindings] can be found.
|
||||
final DynamicLibrary dylib = () {
|
||||
if (Platform.isMacOS || Platform.isIOS) {
|
||||
return DynamicLibrary.open('$libName.framework/$libName');
|
||||
}
|
||||
if (Platform.isAndroid || Platform.isLinux) {
|
||||
return DynamicLibrary.open('lib$libName.so');
|
||||
}
|
||||
if (Platform.isWindows) {
|
||||
return DynamicLibrary.open(
|
||||
'./build/windows/x64/runner/Release/$libName.dll',
|
||||
);
|
||||
}
|
||||
throw UnsupportedError('Unknown platform: ${Platform.operatingSystem}');
|
||||
}();
|
||||
|
||||
/// The bindings to the native functions in [_dylib].
|
||||
final FlserialBindings bindings = FlserialBindings(dylib);
|
||||
//'/home/runner/work/flserial/flserial/build/linux/x64/release/shared/libflserial.so');
|
||||
|
||||
test('FLSerial status should be closed', () {
|
||||
bindings.fl_init(10);
|
||||
|
||||
bindings.fl_free();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
flutter/
|
||||
|
||||
# Visual Studio user-specific files.
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# Visual Studio build-related files.
|
||||
x64/
|
||||
x86/
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!*.[Cc]ache/
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
# The Flutter tooling requires that developers have a version of Visual Studio
|
||||
# installed that includes CMake 3.14 or later. You should not increase this
|
||||
# version, as doing so will cause the plugin to fail to compile for some
|
||||
# customers of the plugin.
|
||||
cmake_minimum_required(VERSION 3.14)
|
||||
|
||||
# Project-level configuration.
|
||||
set(PROJECT_NAME "flserial")
|
||||
project(${PROJECT_NAME} LANGUAGES CXX)
|
||||
|
||||
# Invoke the build for native code shared with the other target platforms.
|
||||
# This can be changed to accommodate different builds.
|
||||
add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/../src" "${CMAKE_CURRENT_BINARY_DIR}/shared")
|
||||
|
||||
# List of absolute paths to libraries that should be bundled with the plugin.
|
||||
# This list could contain prebuilt libraries, or libraries created by an
|
||||
# external build triggered from this build file.
|
||||
set(flserial_bundled_libraries
|
||||
# Defined in ../src/CMakeLists.txt.
|
||||
# This can be changed to accommodate different builds.
|
||||
$<TARGET_FILE:flserial>
|
||||
PARENT_SCOPE
|
||||
)
|
||||
Reference in new issue
Block a user